Merge pull request #13056 from xwu/much-of-a-muchness

[stdlib/Sema/AST] Adopt a commonly used implementation for combining hashes
diff --git a/README.md b/README.md
index 7ef4f79..4f82124 100644
--- a/README.md
+++ b/README.md
@@ -54,7 +54,7 @@
 
 #### macOS
 
-To build for macOS, you need [Xcode 9.2 beta 2](https://developer.apple.com/xcode/downloads/).
+To build for macOS, you need [Xcode 9.2](https://developer.apple.com/xcode/downloads/).
 The required version of Xcode changes frequently, and is often a beta release.
 Check this document or the host information on <https://ci.swift.org> for the
 current required version.
@@ -114,7 +114,7 @@
 Manager, building for various platforms, running tests after builds, and more.
 
 There are two primary build systems to use: Xcode and Ninja. The Xcode build
-system allows you to work in Xcode.app, but Ninja is a bit faster and supports
+system allows you to work in Xcode, but Ninja is a bit faster and supports
 more environments.
 
 To build using Ninja, run:
@@ -143,7 +143,7 @@
 #### Xcode
 
 To build using Xcode, specify the `--xcode` argument on any of the above commands.
-Xcode.app can be used to edit the Swift source code, but it is not currently
+Xcode can be used to edit the Swift source code, but it is not currently
 fully supported as a build environment for SDKs other than macOS. The generated
 Xcode project does not integrate with the test runner, but the tests can be run
 with the 'check-swift' target.
@@ -159,7 +159,7 @@
 
 #### Ninja
 
-Once the first build has completed, ninja can perform fast incremental builds of
+Once the first build has completed, Ninja can perform fast incremental builds of
 various products. These incremental builds are a big timesaver when developing
 and debugging.
 
diff --git a/benchmark/CMakeLists.txt b/benchmark/CMakeLists.txt
index 405cbc1..f6e3558 100644
--- a/benchmark/CMakeLists.txt
+++ b/benchmark/CMakeLists.txt
@@ -217,6 +217,20 @@
   "Produce optimization view for benchmarks"
   FALSE)
 
+set(SWIFT_BENCHMARK_OPT_VIEWER "" CACHE FILEPATH
+  "Path to opt-viewer")
+
+if(SWIFT_BENCHMARK_OPT_VIEWER)
+  # If the path to the opt-viewer was specified manually and we have no access
+  # to the LLVM tree, assume we have the modules for the opt-viewer installed.
+  if(SWIFT_BENCHMARK_BUILT_STANDALONE)
+    set(LLVM_HAVE_OPT_VIEWER_MODULES 1)
+  endif()
+else()
+  set (SWIFT_BENCHMARK_OPT_VIEWER
+    "${LLVM_BUILD_MAIN_SRC_DIR}/tools/opt-viewer/opt-viewer.py")
+endif()
+
 # Options for other configurations
 set(BENCHOPTS_MULTITHREADED
     "-whole-module-optimization" "-num-threads" "4")
diff --git a/benchmark/cmake/modules/AddSwiftBenchmarkSuite.cmake b/benchmark/cmake/modules/AddSwiftBenchmarkSuite.cmake
index 9592abd..18db7f8 100644
--- a/benchmark/cmake/modules/AddSwiftBenchmarkSuite.cmake
+++ b/benchmark/cmake/modules/AddSwiftBenchmarkSuite.cmake
@@ -96,6 +96,16 @@
   set(${objfile_out} ${objfiles} PARENT_SCOPE)
 endfunction()
 
+function(add_opt_view opt_view_main_dir, module_name, opt_view_dir_out)
+  set(opt_view_dir "${opt_view_main_dir}/${module_name}")
+  set(opt_record "${objdir}/${module_name}.opt.yaml")
+  add_custom_command(
+    OUTPUT ${opt_view_dir}
+    DEPENDS "${objfile}"
+    COMMAND ${SWIFT_BENCHMARK_OPT_VIEWER} ${opt_record} "-o" ${opt_view_dir})
+  set(${opt_view_dir_out} ${opt_view_dir} PARENT_SCOPE)
+endfunction()
+
 # Regular whole-module-compilation: only a single object file is
 # generated.
 function (add_swift_multisource_wmo_benchmark_library objfile_out)
@@ -201,14 +211,11 @@
       "-no-link-objc-runtime"
       "-I" "${srcdir}/utils/ObjectiveCTests")
 
-  set(optview_main_dir)
+  set(opt_view_main_dir)
   if(SWIFT_BENCHMARK_GENERATE_OPT_VIEW AND LLVM_HAVE_OPT_VIEWER_MODULES)
-    precondition(SWIFT_BENCHMARK_BUILT_STANDALONE NEGATE
-      "Opt-viewer is not supported when running the benchmarks outside the Swift tree")
-
     if(NOT ${optflag} STREQUAL "Onone" AND "${bench_flags}" MATCHES "-whole-module.*")
       list(APPEND common_options "-save-optimization-record")
-      set(optview_main_dir "${objdir}/opt-view")
+      set(opt_view_main_dir "${objdir}/opt-view")
     endif()
   endif()
 
@@ -337,14 +344,10 @@
             "${source}")
       endif()
 
-      if(optview_main_dir)
-        set(opt_record "${objdir}/${module_name}.opt.yaml")
-        set(opt_viewer "${LLVM_BUILD_MAIN_SRC_DIR}/tools/opt-viewer/opt-viewer.py")
-        set(opt_view_dir "${optview_main_dir}/${module_name}")
-        add_custom_command(
-            OUTPUT ${opt_view_dir}
-            DEPENDS "${objfile}"
-            COMMAND ${opt_viewer} ${opt_record} "-o" ${opt_view_dir})
+      if(opt_view_main_dir)
+        set(opt_view_dir)
+        add_opt_view(${opt_view_main_dir}, ${module_name}, opt_view_dir)
+        precondition(opt_view_dir)
         list(APPEND opt_view_dirs ${opt_view_dir})
       endif()
     endif()
@@ -365,6 +368,13 @@
         DEPENDS ${bench_library_objects} ${stdlib_dependencies})
       precondition(objfile_out)
       list(APPEND SWIFT_BENCH_OBJFILES "${objfile_out}")
+
+      if(opt_view_main_dir)
+        set(opt_view_dir)
+        add_opt_view(${opt_view_main_dir}, ${module_name}, opt_view_dir)
+        precondition(opt_view_dir)
+        list(APPEND opt_view_dirs ${opt_view_dir})
+      endif()
     else()
       set(objfiles_out)
       add_swift_multisource_nonwmo_benchmark_library(objfiles_out
@@ -394,6 +404,13 @@
         DEPENDS ${bench_library_objects} ${stdlib_dependencies})
       precondition(objfile_out)
       list(APPEND SWIFT_BENCH_OBJFILES "${objfile_out}")
+
+      if(opt_view_main_dir)
+        set(opt_view_dir)
+        add_opt_view(${opt_view_main_dir}, ${module_name}, opt_view_dir)
+        precondition(opt_view_dir)
+        list(APPEND opt_view_dirs ${opt_view_dir})
+      endif()
     else()
       set(objfiles_out)
       add_swift_multisource_nonwmo_benchmark_library(objfiles_out
diff --git a/benchmark/single-source/ArraySetElement.swift b/benchmark/single-source/ArraySetElement.swift
index 08973f2..292b6a3 100644
--- a/benchmark/single-source/ArraySetElement.swift
+++ b/benchmark/single-source/ArraySetElement.swift
@@ -18,7 +18,7 @@
 public var ArraySetElement = BenchmarkInfo(
   name: "ArraySetElement",
   runFunction: run_ArraySetElement,
-  tags: [.runtime, .cpubench]
+  tags: [.runtime, .cpubench, .unstable]
 )
 
 // This is an effort to defeat isUniquelyReferenced optimization. Ideally
diff --git a/benchmark/single-source/Exclusivity.swift b/benchmark/single-source/Exclusivity.swift
index c3a93fc..9785899 100644
--- a/benchmark/single-source/Exclusivity.swift
+++ b/benchmark/single-source/Exclusivity.swift
@@ -35,7 +35,7 @@
   BenchmarkInfo(
     name: "ExclusivityInMatSet",
     runFunction: run_accessInMatSet,
-    tags: [.runtime, .cpubench]
+    tags: [.runtime, .cpubench, .unstable]
   ),
   // At -Onone
   // 25% swift_release
diff --git a/benchmark/single-source/StringComparison.swift b/benchmark/single-source/StringComparison.swift
index 0422bfd..1397f00 100644
--- a/benchmark/single-source/StringComparison.swift
+++ b/benchmark/single-source/StringComparison.swift
@@ -63,19 +63,21 @@
     name: "StringComparison_zalgo",
     runFunction: run_StringComparison_zalgo,
     tags: [.validation, .api, .String]),    
+  BenchmarkInfo(
+    name: "StringComparison_longSharedPrefix",
+    runFunction: run_StringComparison_longSharedPrefix,
+    tags: [.validation, .api, .String]),    
 ]
     
   @inline(never)
   public func run_StringComparison_ascii(_ N: Int) {
-    var count = 0
     let workload = Workload.ascii
     let tripCount = workload.tripCount
     let payload = workload.payload
     for _ in 1...tripCount*N {
       for s1 in payload {
         for s2 in payload {
-          let cmp = s1 < s2
-          count += cmp ? 1 : 0
+          blackHole(s1 < s2)
         }
       }
     }
@@ -83,15 +85,13 @@
     
   @inline(never)
   public func run_StringComparison_latin1(_ N: Int) {
-    var count = 0
     let workload = Workload.latin1
     let tripCount = workload.tripCount
     let payload = workload.payload
     for _ in 1...tripCount*N {
       for s1 in payload {
         for s2 in payload {
-          let cmp = s1 < s2
-          count += cmp ? 1 : 0
+          blackHole(s1 < s2)
         }
       }
     }
@@ -99,15 +99,13 @@
     
   @inline(never)
   public func run_StringComparison_fastPrenormal(_ N: Int) {
-    var count = 0
     let workload = Workload.fastPrenormal
     let tripCount = workload.tripCount
     let payload = workload.payload
     for _ in 1...tripCount*N {
       for s1 in payload {
         for s2 in payload {
-          let cmp = s1 < s2
-          count += cmp ? 1 : 0
+          blackHole(s1 < s2)
         }
       }
     }
@@ -115,15 +113,13 @@
     
   @inline(never)
   public func run_StringComparison_slowerPrenormal(_ N: Int) {
-    var count = 0
     let workload = Workload.slowerPrenormal
     let tripCount = workload.tripCount
     let payload = workload.payload
     for _ in 1...tripCount*N {
       for s1 in payload {
         for s2 in payload {
-          let cmp = s1 < s2
-          count += cmp ? 1 : 0
+          blackHole(s1 < s2)
         }
       }
     }
@@ -131,15 +127,13 @@
     
   @inline(never)
   public func run_StringComparison_nonBMPSlowestPrenormal(_ N: Int) {
-    var count = 0
     let workload = Workload.nonBMPSlowestPrenormal
     let tripCount = workload.tripCount
     let payload = workload.payload
     for _ in 1...tripCount*N {
       for s1 in payload {
         for s2 in payload {
-          let cmp = s1 < s2
-          count += cmp ? 1 : 0
+          blackHole(s1 < s2)
         }
       }
     }
@@ -147,15 +141,13 @@
     
   @inline(never)
   public func run_StringComparison_emoji(_ N: Int) {
-    var count = 0
     let workload = Workload.emoji
     let tripCount = workload.tripCount
     let payload = workload.payload
     for _ in 1...tripCount*N {
       for s1 in payload {
         for s2 in payload {
-          let cmp = s1 < s2
-          count += cmp ? 1 : 0
+          blackHole(s1 < s2)
         }
       }
     }
@@ -163,15 +155,13 @@
     
   @inline(never)
   public func run_StringComparison_abnormal(_ N: Int) {
-    var count = 0
     let workload = Workload.abnormal
     let tripCount = workload.tripCount
     let payload = workload.payload
     for _ in 1...tripCount*N {
       for s1 in payload {
         for s2 in payload {
-          let cmp = s1 < s2
-          count += cmp ? 1 : 0
+          blackHole(s1 < s2)
         }
       }
     }
@@ -179,15 +169,27 @@
     
   @inline(never)
   public func run_StringComparison_zalgo(_ N: Int) {
-    var count = 0
     let workload = Workload.zalgo
     let tripCount = workload.tripCount
     let payload = workload.payload
     for _ in 1...tripCount*N {
       for s1 in payload {
         for s2 in payload {
-          let cmp = s1 < s2
-          count += cmp ? 1 : 0
+          blackHole(s1 < s2)
+        }
+      }
+    }
+  }
+    
+  @inline(never)
+  public func run_StringComparison_longSharedPrefix(_ N: Int) {
+    let workload = Workload.longSharedPrefix
+    let tripCount = workload.tripCount
+    let payload = workload.payload
+    for _ in 1...tripCount*N {
+      for s1 in payload {
+        for s2 in payload {
+          blackHole(s1 < s2)
         }
       }
     }
@@ -389,4 +391,19 @@
     scaleMultiplier: 0.25
   )
   
+  static let longSharedPrefix = Workload(
+    name: "LongSharedPrefix",
+    payload: """
+    http://www.dogbook.com/dog/239495828/friends/mutual/2939493815
+    http://www.dogbook.com/dog/239495828/friends/mutual/3910583739
+    http://www.dogbook.com/dog/239495828/friends/mutual/3910583739/shared
+    http://www.dogbook.com/dog/239495828/friends/mutual/3910583739/shared
+    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.🤔
+    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+    🤔Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.🤔
+    """.lines()
+  )
+  
 }
\ No newline at end of file
diff --git a/benchmark/single-source/StringComparison.swift.gyb b/benchmark/single-source/StringComparison.swift.gyb
index 27112f3..25c5a40 100644
--- a/benchmark/single-source/StringComparison.swift.gyb
+++ b/benchmark/single-source/StringComparison.swift.gyb
@@ -30,7 +30,7 @@
   }
 }
 
-% Names = ["ascii", "latin1", "fastPrenormal", "slowerPrenormal", "nonBMPSlowestPrenormal", "emoji", "abnormal", "zalgo"]
+% Names = ["ascii", "latin1", "fastPrenormal", "slowerPrenormal", "nonBMPSlowestPrenormal", "emoji", "abnormal", "zalgo", "longSharedPrefix"]
 
 public let StringComparison = [
 % for Name in Names:
@@ -44,15 +44,13 @@
 % for Name in Names:
   @inline(never)
   public func run_StringComparison_${Name}(_ N: Int) {
-    var count = 0
     let workload = Workload.${Name}
     let tripCount = workload.tripCount
     let payload = workload.payload
     for _ in 1...tripCount*N {
       for s1 in payload {
         for s2 in payload {
-          let cmp = s1 < s2
-          count += cmp ? 1 : 0
+          blackHole(s1 < s2)
         }
       }
     }
@@ -255,4 +253,19 @@
     scaleMultiplier: 0.25
   )
   
+  static let longSharedPrefix = Workload(
+    name: "LongSharedPrefix",
+    payload: """
+    http://www.dogbook.com/dog/239495828/friends/mutual/2939493815
+    http://www.dogbook.com/dog/239495828/friends/mutual/3910583739
+    http://www.dogbook.com/dog/239495828/friends/mutual/3910583739/shared
+    http://www.dogbook.com/dog/239495828/friends/mutual/3910583739/shared
+    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.🤔
+    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+    🤔Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.🤔
+    """.lines()
+  )
+  
 }
\ No newline at end of file
diff --git a/benchmark/single-source/Suffix.swift b/benchmark/single-source/Suffix.swift
index d734c2a..8eac396 100644
--- a/benchmark/single-source/Suffix.swift
+++ b/benchmark/single-source/Suffix.swift
@@ -50,7 +50,7 @@
   BenchmarkInfo(
     name: "SuffixArray",
     runFunction: run_SuffixArray,
-    tags: [.validation, .api, .Array]),
+    tags: [.validation, .api, .Array, .unstable]),
   BenchmarkInfo(
     name: "SuffixCountableRangeLazy",
     runFunction: run_SuffixCountableRangeLazy,
@@ -78,7 +78,7 @@
   BenchmarkInfo(
     name: "SuffixArrayLazy",
     runFunction: run_SuffixArrayLazy,
-    tags: [.validation, .api]),
+    tags: [.validation, .api, .Array, .unstable]),
 ]
 
 @inline(never)
diff --git a/benchmark/single-source/Suffix.swift.gyb b/benchmark/single-source/Suffix.swift.gyb
index fa59451..521d520 100644
--- a/benchmark/single-source/Suffix.swift.gyb
+++ b/benchmark/single-source/Suffix.swift.gyb
@@ -46,7 +46,7 @@
   BenchmarkInfo(
     name: "Suffix${Name}",
     runFunction: run_Suffix${Name},
-    tags: [.validation, .api${', .Array' if Name == 'Array' else ''}]),
+    tags: [.validation, .api${', .Array, .unstable' if Name == 'Array' or Name == 'ArrayLazy' else ''}]),
 % end
 ]
 
diff --git a/cmake/modules/AddSwift.cmake b/cmake/modules/AddSwift.cmake
index ce84b9b..b5133a0 100644
--- a/cmake/modules/AddSwift.cmake
+++ b/cmake/modules/AddSwift.cmake
@@ -856,6 +856,9 @@
   if("${SWIFTLIB_SINGLE_SDK}" STREQUAL "WINDOWS")
     swift_windows_include_for_arch(${SWIFTLIB_SINGLE_ARCHITECTURE} SWIFTLIB_INCLUDE)
     target_include_directories("${target}" SYSTEM PRIVATE ${SWIFTLIB_INCLUDE})
+    set_target_properties(${target}
+                          PROPERTIES
+                            CXX_STANDARD 14)
   endif()
 
   if("${SWIFTLIB_SINGLE_SDK}" STREQUAL "WINDOWS" AND NOT "${CMAKE_SYSTEM_NAME}" STREQUAL "Windows")
diff --git a/docs/ABI/Mangling.rst b/docs/ABI/Mangling.rst
index 78c574e..fefc6bb 100644
--- a/docs/ABI/Mangling.rst
+++ b/docs/ABI/Mangling.rst
@@ -175,9 +175,13 @@
   static ::= 'Z'
   curry-thunk ::= 'Tc'
 
+  label-list ::= empty-list            // represents complete absence of parameter labels
+  label-list ::= ('_' | identifier)*   // '_' is inserted as placeholder for empty label,
+                                       // since the number of labels should match the number of parameters
+
   // The leading type is the function type
-  entity-spec ::= type file-discriminator? 'fC'      // allocating constructor
-  entity-spec ::= type file-discriminator? 'fc'      // non-allocating constructor
+  entity-spec ::= label-list type file-discriminator? 'fC'      // allocating constructor
+  entity-spec ::= label-list type file-discriminator? 'fc'      // non-allocating constructor
   entity-spec ::= type 'fU' INDEX            // explicit anonymous closure expression
   entity-spec ::= type 'fu' INDEX            // implicit anonymous closure
   entity-spec ::= 'fA' INDEX                 // default argument N+1 generator
@@ -189,11 +193,11 @@
   entity-spec ::= 'Tv' NATURAL               // outlined global variable (from context function)
   entity-spec ::= 'Te' bridge-spec           // outlined objective c method call
 
-  entity-spec ::= decl-name function-signature generic-signature? 'F'    // function
-  entity-spec ::= type file-discriminator? 'i' ACCESSOR                  // subscript
-  entity-spec ::= decl-name type 'v' ACCESSOR                            // variable
-  entity-spec ::= decl-name type 'fp'                // generic type parameter
-  entity-spec ::= decl-name type 'fo'                // enum element (currently not used)
+  entity-spec ::= decl-name label-list function-signature generic-signature? 'F'    // function
+  entity-spec ::= label-list type file-discriminator? 'i' ACCESSOR                  // subscript
+  entity-spec ::= decl-name label-list? type 'v' ACCESSOR                           // variable
+  entity-spec ::= decl-name type 'fp'                                               // generic type parameter
+  entity-spec ::= decl-name type 'fo'                                               // enum element (currently not used)
 
   ACCESSOR ::= 'm'                           // materializeForSet
   ACCESSOR ::= 's'                           // setter
@@ -351,7 +355,8 @@
   function-signature ::= params-type params-type throws? // results and parameters
 
   params-type := type 'z'? 'h'?              // tuple in case of multiple parameters or a single parameter with a single tuple type
-                                             // with optional inout convention, shared convention
+                                             // with optional inout convention, shared convention. parameters don't have labels,
+                                             // they are mangled separately as part of the entity.
   params-type := empty-list                  // shortcut for no parameters
 
   throws ::= 'K'                             // 'throws' annotation on function types
diff --git a/docs/ErrorHandlingRationale.rst b/docs/ErrorHandlingRationale.rst
index 4457ac6..71dd3e4 100644
--- a/docs/ErrorHandlingRationale.rst
+++ b/docs/ErrorHandlingRationale.rst
@@ -577,9 +577,9 @@
 generally want to reserve flexibility about the exact kind of error
 they produce, and so many errors just end up falling into broad
 buckets.  Different libraries end up with their own library-specific
-general error classes, and exceptions list end up just restating the
+general error classes, and exception lists end up just restating the
 library's own dependencies or wrapping the underlying errors in ways
-that loses critical information.
+that lose critical information.
 
 
 Tradeoffs of typed propagation
@@ -799,7 +799,7 @@
 clean-ups before propagating the error further.  It may even
 completely eliminate the need for a landing pad.
 
-The ObjC/C++ exceptions system on iOS/ARM32 is kindof like that
+The ObjC/C++ exceptions system on iOS/ARM32 is kind of like that
 hybrid.  Propagation and clean-up code is explicit in the function,
 but the registered context includes the "personality" information from
 the unwinding tables, which makes the decision whether to land at the
@@ -1096,7 +1096,7 @@
 
 Objective-C exceptions are *mostly* only used for unrecoverable
 conditions, akin to what I called "failures" above.  There are a few
-major exceptions to this rule, where APIs that do use exceptions to
+major exceptions to this rule, where APIs do use exceptions to
 report errors.
 
 Instead, Objective-C mostly relies on manual propagation,
@@ -1134,7 +1134,7 @@
 statically-enforced model where truly catastrophic problems can still
 be handled when necessary.  Unfortunately, these motivations don't
 seem to have been communicated very well to developers, and the result
-is kindof a mess.
+is kind of a mess.
 
 Java allows methods to be very specific about the kinds of exception
 they throw.  In my experience, exceptions tend to fall into two
@@ -1420,9 +1420,9 @@
 whether an argument function throws; it is easy to imagine algorithms
 that can be implemented more efficiently if they do not need to worry
 about exceptions.  (We do not, however, particularly want to encourage
-a pattern of duplicating This is straightforward if the primary
+a pattern of duplicating. This is straightforward if the primary
 type-checking pass is able to reliably decide whether a function value
-can throw.
+can throw.)
 
 Typed propagation checking can generally be performed in a secondary
 pass over a type-checked function body: if a function is not permitted
@@ -1509,7 +1509,7 @@
 aggressively forbid them, and thus forbid conformances by types whose
 operations naturally throw.
 
-There are several different ways we could approach this problem, but
+There are several different ways we could approach this problem, and
 after some investigation I feel confident that they're workable.
 Unfortunately, they are clearly out-of-scope for the first release.
 For now, the standard library should provide protocols that cannot
diff --git a/docs/Runtime.md b/docs/Runtime.md
index a7a8899..10347ba 100644
--- a/docs/Runtime.md
+++ b/docs/Runtime.md
@@ -314,8 +314,9 @@
 000000000001e620 T _swift_allocateGenericValueMetadata
 0000000000022be0 T _swift_initClassMetadata_UniversalStrategy
 000000000001c100 T _swift_initEnumMetadataMultiPayload
-000000000001bd60 T _swift_initEnumValueWitnessTableSinglePayload
-0000000000022a20 T _swift_initStructMetadata_UniversalStrategy
+000000000001bd60 T _swift_initEnumMetadataSingleCase
+000000000001bd60 T _swift_initEnumMetadataSinglePayload
+0000000000022a20 T _swift_initStructMetadata
 0000000000024230 T _swift_initializeSuperclass
 0000000000028b60 T _swift_instantiateObjCClass
 ```
diff --git a/include/swift/ABI/MetadataValues.h b/include/swift/ABI/MetadataValues.h
index fdd3a02..affac91 100644
--- a/include/swift/ABI/MetadataValues.h
+++ b/include/swift/ABI/MetadataValues.h
@@ -747,6 +747,62 @@
   return uintptr_t(flags) & uintptr_t(ExclusivityFlags::WarningOnly);
 }
 
+/// Flags for struct layout.
+enum class StructLayoutFlags : uintptr_t {
+  /// Reserve space for 256 layout algorithms.
+  AlgorithmMask     = 0xff,
+
+  /// The ABI baseline algorithm, i.e. the algorithm implemented in Swift 5.
+  Swift5Algorithm   = 0x00,
+
+  /// Is the value-witness table mutable in place, or does layout need to
+  /// clone it?
+  IsVWTMutable      = 0x100,
+};
+static inline StructLayoutFlags operator|(StructLayoutFlags lhs,
+                                          StructLayoutFlags rhs) {
+  return StructLayoutFlags(uintptr_t(lhs) | uintptr_t(rhs));
+}
+static inline StructLayoutFlags &operator|=(StructLayoutFlags &lhs,
+                                            StructLayoutFlags rhs) {
+  return (lhs = (lhs | rhs));
+}
+static inline StructLayoutFlags getLayoutAlgorithm(StructLayoutFlags flags) {
+  return StructLayoutFlags(uintptr_t(flags)
+                             & uintptr_t(StructLayoutFlags::AlgorithmMask));
+}
+static inline bool isValueWitnessTableMutable(StructLayoutFlags flags) {
+  return uintptr_t(flags) & uintptr_t(StructLayoutFlags::IsVWTMutable);
+}
+
+/// Flags for enum layout.
+enum class EnumLayoutFlags : uintptr_t {
+  /// Reserve space for 256 layout algorithms.
+  AlgorithmMask     = 0xff,
+
+  /// The ABI baseline algorithm, i.e. the algorithm implemented in Swift 5.
+  Swift5Algorithm   = 0x00,
+
+  /// Is the value-witness table mutable in place, or does layout need to
+  /// clone it?
+  IsVWTMutable      = 0x100,
+};
+static inline EnumLayoutFlags operator|(EnumLayoutFlags lhs,
+                                        EnumLayoutFlags rhs) {
+  return EnumLayoutFlags(uintptr_t(lhs) | uintptr_t(rhs));
+}
+static inline EnumLayoutFlags &operator|=(EnumLayoutFlags &lhs,
+                                          EnumLayoutFlags rhs) {
+  return (lhs = (lhs | rhs));
+}
+static inline EnumLayoutFlags getLayoutAlgorithm(EnumLayoutFlags flags) {
+  return EnumLayoutFlags(uintptr_t(flags)
+                           & uintptr_t(EnumLayoutFlags::AlgorithmMask));
+}
+static inline bool isValueWitnessTableMutable(EnumLayoutFlags flags) {
+  return uintptr_t(flags) & uintptr_t(EnumLayoutFlags::IsVWTMutable);
+}
+
 } // end namespace swift
 
 #endif /* SWIFT_ABI_METADATAVALUES_H */
diff --git a/include/swift/ABI/TrailingObjects.h b/include/swift/ABI/TrailingObjects.h
new file mode 100644
index 0000000..550308d
--- /dev/null
+++ b/include/swift/ABI/TrailingObjects.h
@@ -0,0 +1,411 @@
+//===--- TrailingObjects.h - Variable-length, Swift-ABI classes -*- C++ -*-===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// This header is a fork of the LLVM TrailingObjects template. It has the
+/// additional constraint over llvm::TrailingObjects of having to maintain ABI
+/// stability across versions. The following documentation is copied from
+/// the original TrailingObjects implementation:
+///
+/// This header defines support for implementing classes that have
+/// some trailing object (or arrays of objects) appended to them. The
+/// main purpose is to make it obvious where this idiom is being used,
+/// and to make the usage more idiomatic and more difficult to get
+/// wrong.
+///
+/// The TrailingObject template abstracts away the reinterpret_cast,
+/// pointer arithmetic, and size calculations used for the allocation
+/// and access of appended arrays of objects, and takes care that they
+/// are all allocated at their required alignment. Additionally, it
+/// ensures that the base type is final -- deriving from a class that
+/// expects data appended immediately after it is typically not safe.
+///
+/// Users are expected to derive from this template, and provide
+/// numTrailingObjects implementations for each trailing type except
+/// the last, e.g. like this sample:
+///
+/// \code
+/// class VarLengthObj : private TrailingObjects<VarLengthObj, int, double> {
+///   friend TrailingObjects;
+///
+///   unsigned NumInts, NumDoubles;
+///   size_t numTrailingObjects(OverloadToken<int>) const { return NumInts; }
+///  };
+/// \endcode
+///
+/// You can access the appended arrays via 'getTrailingObjects', and
+/// determine the size needed for allocation via
+/// 'additionalSizeToAlloc' and 'totalSizeToAlloc'.
+///
+/// All the methods implemented by this class are are intended for use
+/// by the implementation of the class, not as part of its interface
+/// (thus, private inheritance is suggested).
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef SWIFT_ABI_TRAILINGOBJECTS_H
+#define SWIFT_ABI_TRAILINGOBJECTS_H
+
+#include "llvm/Support/AlignOf.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/type_traits.h"
+#include <new>
+#include <type_traits>
+
+namespace swift {
+namespace ABI {
+
+namespace trailing_objects_internal {
+/// Helper template to calculate the max alignment requirement for a set of
+/// objects.
+template <typename First, typename... Rest> class AlignmentCalcHelper {
+private:
+  enum {
+    FirstAlignment = alignof(First),
+    RestAlignment = AlignmentCalcHelper<Rest...>::Alignment,
+  };
+
+public:
+  enum {
+    Alignment = FirstAlignment > RestAlignment ? FirstAlignment : RestAlignment
+  };
+};
+
+template <typename First> class AlignmentCalcHelper<First> {
+public:
+  enum { Alignment = alignof(First) };
+};
+
+/// The base class for TrailingObjects* classes.
+class TrailingObjectsBase {
+protected:
+  /// OverloadToken's purpose is to allow specifying function overloads
+  /// for different types, without actually taking the types as
+  /// parameters. (Necessary because member function templates cannot
+  /// be specialized, so overloads must be used instead of
+  /// specialization.)
+  template <typename T> struct OverloadToken {};
+};
+
+/// This helper template works-around MSVC 2013's lack of useful
+/// alignas() support. The argument to LLVM_ALIGNAS(), in MSVC, is
+/// required to be a literal integer. But, you *can* use template
+/// specialization to select between a bunch of different LLVM_ALIGNAS
+/// expressions...
+template <int Align>
+class TrailingObjectsAligner : public TrailingObjectsBase {};
+template <>
+class LLVM_ALIGNAS(1) TrailingObjectsAligner<1> : public TrailingObjectsBase {};
+template <>
+class LLVM_ALIGNAS(2) TrailingObjectsAligner<2> : public TrailingObjectsBase {};
+template <>
+class LLVM_ALIGNAS(4) TrailingObjectsAligner<4> : public TrailingObjectsBase {};
+template <>
+class LLVM_ALIGNAS(8) TrailingObjectsAligner<8> : public TrailingObjectsBase {};
+template <>
+class LLVM_ALIGNAS(16) TrailingObjectsAligner<16> : public TrailingObjectsBase {
+};
+template <>
+class LLVM_ALIGNAS(32) TrailingObjectsAligner<32> : public TrailingObjectsBase {
+};
+
+// Just a little helper for transforming a type pack into the same
+// number of a different type. e.g.:
+//   ExtractSecondType<Foo..., int>::type
+template <typename Ty1, typename Ty2> struct ExtractSecondType {
+  typedef Ty2 type;
+};
+
+// TrailingObjectsImpl is somewhat complicated, because it is a
+// recursively inheriting template, in order to handle the template
+// varargs. Each level of inheritance picks off a single trailing type
+// then recurses on the rest. The "Align", "BaseTy", and
+// "TopTrailingObj" arguments are passed through unchanged through the
+// recursion. "PrevTy" is, at each level, the type handled by the
+// level right above it.
+
+template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy,
+          typename... MoreTys>
+class TrailingObjectsImpl {
+  // The main template definition is never used -- the two
+  // specializations cover all possibilities.
+};
+
+template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy,
+          typename NextTy, typename... MoreTys>
+class TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, PrevTy, NextTy,
+                          MoreTys...>
+    : public TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, NextTy,
+                                 MoreTys...> {
+
+  typedef TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, NextTy, MoreTys...>
+      ParentType;
+
+  struct RequiresRealignment {
+    static const bool value = alignof(PrevTy) < alignof(NextTy);
+  };
+
+  static constexpr bool requiresRealignment() {
+    return RequiresRealignment::value;
+  }
+
+protected:
+  // Ensure the inherited getTrailingObjectsImpl is not hidden.
+  using ParentType::getTrailingObjectsImpl;
+
+  // These two functions are helper functions for
+  // TrailingObjects::getTrailingObjects. They recurse to the left --
+  // the result for each type in the list of trailing types depends on
+  // the result of calling the function on the type to the
+  // left. However, the function for the type to the left is
+  // implemented by a *subclass* of this class, so we invoke it via
+  // the TopTrailingObj, which is, via the
+  // curiously-recurring-template-pattern, the most-derived type in
+  // this recursion, and thus, contains all the overloads.
+  static const NextTy *
+  getTrailingObjectsImpl(const BaseTy *Obj,
+                         TrailingObjectsBase::OverloadToken<NextTy>) {
+    auto *Ptr = TopTrailingObj::getTrailingObjectsImpl(
+                    Obj, TrailingObjectsBase::OverloadToken<PrevTy>()) +
+                TopTrailingObj::callNumTrailingObjects(
+                    Obj, TrailingObjectsBase::OverloadToken<PrevTy>());
+
+    if (requiresRealignment())
+      return reinterpret_cast<const NextTy *>(
+          llvm::alignAddr(Ptr, alignof(NextTy)));
+    else
+      return reinterpret_cast<const NextTy *>(Ptr);
+  }
+
+  static NextTy *
+  getTrailingObjectsImpl(BaseTy *Obj,
+                         TrailingObjectsBase::OverloadToken<NextTy>) {
+    auto *Ptr = TopTrailingObj::getTrailingObjectsImpl(
+                    Obj, TrailingObjectsBase::OverloadToken<PrevTy>()) +
+                TopTrailingObj::callNumTrailingObjects(
+                    Obj, TrailingObjectsBase::OverloadToken<PrevTy>());
+
+    if (requiresRealignment())
+      return reinterpret_cast<NextTy *>(llvm::alignAddr(Ptr, alignof(NextTy)));
+    else
+      return reinterpret_cast<NextTy *>(Ptr);
+  }
+
+  // Helper function for TrailingObjects::additionalSizeToAlloc: this
+  // function recurses to superclasses, each of which requires one
+  // fewer size_t argument, and adds its own size.
+  static constexpr size_t additionalSizeToAllocImpl(
+      size_t SizeSoFar, size_t Count1,
+      typename ExtractSecondType<MoreTys, size_t>::type... MoreCounts) {
+    return ParentType::additionalSizeToAllocImpl(
+        (requiresRealignment() ? llvm::alignTo<alignof(NextTy)>(SizeSoFar)
+                               : SizeSoFar) +
+            sizeof(NextTy) * Count1,
+        MoreCounts...);
+  }
+};
+
+// The base case of the TrailingObjectsImpl inheritance recursion,
+// when there's no more trailing types.
+template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy>
+class TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, PrevTy>
+    : public TrailingObjectsAligner<Align> {
+protected:
+  // This is a dummy method, only here so the "using" doesn't fail --
+  // it will never be called, because this function recurses backwards
+  // up the inheritance chain to subclasses.
+  static void getTrailingObjectsImpl();
+
+  static constexpr size_t additionalSizeToAllocImpl(size_t SizeSoFar) {
+    return SizeSoFar;
+  }
+
+  template <bool CheckAlignment> static void verifyTrailingObjectsAlignment() {}
+};
+
+} // end namespace trailing_objects_internal
+
+// Finally, the main type defined in this file, the one intended for users...
+
+/// See the file comment for details on the usage of the
+/// TrailingObjects type.
+template <typename BaseTy, typename... TrailingTys>
+class TrailingObjects : private trailing_objects_internal::TrailingObjectsImpl<
+                            trailing_objects_internal::AlignmentCalcHelper<
+                                TrailingTys...>::Alignment,
+                            BaseTy, TrailingObjects<BaseTy, TrailingTys...>,
+                            BaseTy, TrailingTys...> {
+
+  template <int A, typename B, typename T, typename P, typename... M>
+  friend class trailing_objects_internal::TrailingObjectsImpl;
+
+  template <typename... Tys> class Foo {};
+
+  typedef trailing_objects_internal::TrailingObjectsImpl<
+      trailing_objects_internal::AlignmentCalcHelper<TrailingTys...>::Alignment,
+      BaseTy, TrailingObjects<BaseTy, TrailingTys...>, BaseTy, TrailingTys...>
+      ParentType;
+  using TrailingObjectsBase = trailing_objects_internal::TrailingObjectsBase;
+
+  using ParentType::getTrailingObjectsImpl;
+
+  // This function contains only a static_assert BaseTy is final. The
+  // static_assert must be in a function, and not at class-level
+  // because BaseTy isn't complete at class instantiation time, but
+  // will be by the time this function is instantiated.
+  static void verifyTrailingObjectsAssertions() {
+#ifdef LLVM_IS_FINAL
+    static_assert(LLVM_IS_FINAL(BaseTy), "BaseTy must be final.");
+#endif
+  }
+
+  // These two methods are the base of the recursion for this method.
+  static const BaseTy *
+  getTrailingObjectsImpl(const BaseTy *Obj,
+                         TrailingObjectsBase::OverloadToken<BaseTy>) {
+    return Obj;
+  }
+
+  static BaseTy *
+  getTrailingObjectsImpl(BaseTy *Obj,
+                         TrailingObjectsBase::OverloadToken<BaseTy>) {
+    return Obj;
+  }
+
+  // callNumTrailingObjects simply calls numTrailingObjects on the
+  // provided Obj -- except when the type being queried is BaseTy
+  // itself. There is always only one of the base object, so that case
+  // is handled here. (An additional benefit of indirecting through
+  // this function is that consumers only say "friend
+  // TrailingObjects", and thus, only this class itself can call the
+  // numTrailingObjects function.)
+  static size_t
+  callNumTrailingObjects(const BaseTy *Obj,
+                         TrailingObjectsBase::OverloadToken<BaseTy>) {
+    return 1;
+  }
+
+  template <typename T>
+  static size_t callNumTrailingObjects(const BaseTy *Obj,
+                                       TrailingObjectsBase::OverloadToken<T>) {
+    return Obj->numTrailingObjects(TrailingObjectsBase::OverloadToken<T>());
+  }
+
+public:
+  // Make this (privately inherited) member public.
+#ifndef _MSC_VER
+  using ParentType::OverloadToken;
+#else
+  // MSVC bug prevents the above from working, at least up through CL
+  // 19.10.24629.
+  template <typename T>
+  using OverloadToken = typename ParentType::template OverloadToken<T>;
+#endif
+
+  /// Returns a pointer to the trailing object array of the given type
+  /// (which must be one of those specified in the class template). The
+  /// array may have zero or more elements in it.
+  template <typename T> const T *getTrailingObjects() const {
+    verifyTrailingObjectsAssertions();
+    // Forwards to an impl function with overloads, since member
+    // function templates can't be specialized.
+    return this->getTrailingObjectsImpl(
+        static_cast<const BaseTy *>(this),
+        TrailingObjectsBase::OverloadToken<T>());
+  }
+
+  /// Returns a pointer to the trailing object array of the given type
+  /// (which must be one of those specified in the class template). The
+  /// array may have zero or more elements in it.
+  template <typename T> T *getTrailingObjects() {
+    verifyTrailingObjectsAssertions();
+    // Forwards to an impl function with overloads, since member
+    // function templates can't be specialized.
+    return this->getTrailingObjectsImpl(
+        static_cast<BaseTy *>(this), TrailingObjectsBase::OverloadToken<T>());
+  }
+
+  /// Returns the size of the trailing data, if an object were
+  /// allocated with the given counts (The counts are in the same order
+  /// as the template arguments). This does not include the size of the
+  /// base object.  The template arguments must be the same as those
+  /// used in the class; they are supplied here redundantly only so
+  /// that it's clear what the counts are counting in callers.
+  template <typename... Tys>
+  static constexpr typename std::enable_if<
+      std::is_same<Foo<TrailingTys...>, Foo<Tys...>>::value, size_t>::type
+  additionalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType<
+                        TrailingTys, size_t>::type... Counts) {
+    return ParentType::additionalSizeToAllocImpl(0, Counts...);
+  }
+
+  /// Returns the total size of an object if it were allocated with the
+  /// given trailing object counts. This is the same as
+  /// additionalSizeToAlloc, except it *does* include the size of the base
+  /// object.
+  template <typename... Tys>
+  static constexpr typename std::enable_if<
+      std::is_same<Foo<TrailingTys...>, Foo<Tys...>>::value, size_t>::type
+  totalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType<
+                   TrailingTys, size_t>::type... Counts) {
+    return sizeof(BaseTy) + ParentType::additionalSizeToAllocImpl(0, Counts...);
+  }
+
+  /// A type where its ::with_counts template member has a ::type member
+  /// suitable for use as uninitialized storage for an object with the given
+  /// trailing object counts. The template arguments are similar to those
+  /// of additionalSizeToAlloc.
+  ///
+  /// Use with FixedSizeStorageOwner, e.g.:
+  ///
+  /// \code{.cpp}
+  ///
+  /// MyObj::FixedSizeStorage<void *>::with_counts<1u>::type myStackObjStorage;
+  /// MyObj::FixedSizeStorageOwner
+  ///     myStackObjOwner(new ((void *)&myStackObjStorage) MyObj);
+  /// MyObj *const myStackObjPtr = myStackObjOwner.get();
+  ///
+  /// \endcode
+  template <typename... Tys> struct FixedSizeStorage {
+    template <size_t... Counts> struct with_counts {
+      enum { Size = totalSizeToAlloc<Tys...>(Counts...) };
+      typedef llvm::AlignedCharArray<alignof(BaseTy), Size> type;
+    };
+  };
+
+  /// A type that acts as the owner for an object placed into fixed storage.
+  class FixedSizeStorageOwner {
+  public:
+    FixedSizeStorageOwner(BaseTy *p) : p(p) {}
+    ~FixedSizeStorageOwner() {
+      assert(p && "FixedSizeStorageOwner owns null?");
+      p->~BaseTy();
+    }
+
+    BaseTy *get() { return p; }
+    const BaseTy *get() const { return p; }
+
+  private:
+    FixedSizeStorageOwner(const FixedSizeStorageOwner &) = delete;
+    FixedSizeStorageOwner(FixedSizeStorageOwner &&) = delete;
+    FixedSizeStorageOwner &operator=(const FixedSizeStorageOwner &) = delete;
+    FixedSizeStorageOwner &operator=(FixedSizeStorageOwner &&) = delete;
+
+    BaseTy *const p;
+  };
+};
+
+} // end namespace ABI
+} // end namespace swift
+
+#endif
diff --git a/include/swift/AST/ASTMangler.h b/include/swift/AST/ASTMangler.h
index 8a99f64..5f89b68 100644
--- a/include/swift/AST/ASTMangler.h
+++ b/include/swift/AST/ASTMangler.h
@@ -187,6 +187,7 @@
 
   void appendAnyGenericType(const GenericTypeDecl *decl);
 
+  void appendFunction(AnyFunctionType *fn, bool isFunctionMangling = false);
   void appendFunctionType(AnyFunctionType *fn);
 
   void appendFunctionSignature(AnyFunctionType *fn);
diff --git a/include/swift/AST/Builtins.h b/include/swift/AST/Builtins.h
index 5380db2..f12dc48 100644
--- a/include/swift/AST/Builtins.h
+++ b/include/swift/AST/Builtins.h
@@ -99,7 +99,8 @@
 StringRef getBuiltinName(BuiltinValueKind ID);
   
 /// \brief The information identifying the builtin - its kind and types.
-struct BuiltinInfo {
+class BuiltinInfo {
+public:
   BuiltinValueKind ID;
   SmallVector<Type, 4> Types;
   bool isReadNone() const;
diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h
index 680c57b..ff1fdd5 100644
--- a/include/swift/AST/Decl.h
+++ b/include/swift/AST/Decl.h
@@ -30,6 +30,7 @@
 #include "swift/AST/TypeWalker.h"
 #include "swift/AST/Witness.h"
 #include "swift/Basic/Compiler.h"
+#include "swift/Basic/InlineBitfield.h"
 #include "swift/Basic/OptionalEnum.h"
 #include "swift/Basic/Range.h"
 #include "llvm/ADT/DenseMap.h"
@@ -82,10 +83,14 @@
 
 enum class DeclKind : uint8_t {
 #define DECL(Id, Parent) Id,
+#define LAST_DECL(Id) Last_Decl = Id,
 #define DECL_RANGE(Id, FirstId, LastId) \
   First_##Id##Decl = FirstId, Last_##Id##Decl = LastId,
 #include "swift/AST/DeclNodes.def"
 };
+enum : unsigned { NumDeclKindBits =
+  countBitsUsed(static_cast<unsigned>(DeclKind::Last_Decl)) };
+
 
 /// Fine-grained declaration kind that provides a description of the
 /// kind of entity a declaration represents, as it would be used in
@@ -228,184 +233,185 @@
 /// Determine whether two overload signatures conflict.
 bool conflicting(const OverloadSignature& sig1, const OverloadSignature& sig2);
 
-#define BITFIELD_START(D, PD, C) \
-  enum { Num##D##Bits = Num##PD##Bits + C }; \
-  static_assert(Num##D##Bits <= 64, "fits in a uint64_t"); \
-  class D##Bitfields { \
-    friend class D; \
-    uint64_t : Num##PD##Bits
-
-#define BITFIELD_END }
 
 /// Decl - Base class for all declarations in Swift.
 class alignas(1 << DeclAlignInBits) Decl {
-  enum { Num_DeclBits = 0 };
-  BITFIELD_START(Decl, _Decl, 13);
-    unsigned Kind : 6;
+  SWIFT_INLINE_BITFIELD_BASE(Decl, bitmax(NumDeclKindBits,8)+1+1+1+1+1+1+1,
+    Kind : bitmax(NumDeclKindBits,8),
 
     /// \brief Whether this declaration is invalid.
-    unsigned Invalid : 1;
+    Invalid : 1,
 
     /// \brief Whether this declaration was implicitly created, e.g.,
     /// an implicit constructor in a struct.
-    unsigned Implicit : 1;
+    Implicit : 1,
 
     /// \brief Whether this declaration was mapped directly from a Clang AST.
     ///
     /// Use getClangNode() to retrieve the corresponding Clang AST.
-    unsigned FromClang : 1;
+    FromClang : 1,
 
     /// \brief Whether we've already performed early attribute validation.
     /// FIXME: This is ugly.
-    unsigned EarlyAttrValidation : 1;
+    EarlyAttrValidation : 1,
 
     /// \brief Whether this declaration is currently being validated.
-    unsigned BeingValidated : 1;
+    BeingValidated : 1,
 
     /// \brief Whether we have started validating the declaration; this *isn't*
     /// reset after finishing it.
-    unsigned ValidationStarted : 1;
+    ValidationStarted : 1,
 
     /// \brief Whether this declaration was added to the surrounding
     /// DeclContext of an active #if config clause.
-    unsigned EscapedFromIfConfig : 1;
-  BITFIELD_END;
+    EscapedFromIfConfig : 1
+  );
 
-  BITFIELD_START(PatternBindingDecl, Decl, 19);
+  SWIFT_INLINE_BITFIELD_FULL(PatternBindingDecl, Decl, 1+2+16,
     /// \brief Whether this pattern binding declares static variables.
-    unsigned IsStatic : 1;
+    IsStatic : 1,
 
     /// \brief Whether 'static' or 'class' was used.
-    unsigned StaticSpelling : 2;
+    StaticSpelling : 2,
+
+    : NumPadBits,
 
     /// \brief The number of pattern binding declarations.
-    unsigned NumPatternEntries : 16;
-  BITFIELD_END;
+    NumPatternEntries : 16
+  );
   
-  BITFIELD_START(ValueDecl, Decl, 3);
-    friend class MemberLookupTable;
+  SWIFT_INLINE_BITFIELD_FULL(EnumCaseDecl, Decl, 32,
+    : NumPadBits,
 
-    unsigned AlreadyInLookupTable : 1;
+    /// The number of tail-allocated element pointers.
+    NumElements : 32
+  );
+
+  SWIFT_INLINE_BITFIELD(ValueDecl, Decl, 1+1+1,
+    AlreadyInLookupTable : 1,
 
     /// Whether we have already checked whether this declaration is a 
     /// redeclaration.
-    unsigned CheckedRedeclaration : 1;
+    CheckedRedeclaration : 1,
 
     /// Whether the decl can be accessed by swift users; for instance,
     /// a.storage for lazy var a is a decl that cannot be accessed.
-    unsigned IsUserAccessible : 1;
-  BITFIELD_END;
+    IsUserAccessible : 1
+  );
 
-  BITFIELD_START(AbstractStorageDecl, ValueDecl, 7);
+  SWIFT_INLINE_BITFIELD(AbstractStorageDecl, ValueDecl, 1+1+1+4,
     /// Whether we are overridden later
-    unsigned Overridden : 1;
+    Overridden : 1,
 
     /// Whether the getter is mutating.
-    unsigned IsGetterMutating : 1;
+    IsGetterMutating : 1,
 
     /// Whether the setter is mutating.
-    unsigned IsSetterMutating : 1;
+    IsSetterMutating : 1,
 
     /// The storage kind.
-    unsigned StorageKind : 4;
-  BITFIELD_END;
+    StorageKind : 4
+  );
 
-  BITFIELD_START(VarDecl, AbstractStorageDecl, 6);
+  SWIFT_INLINE_BITFIELD(VarDecl, AbstractStorageDecl, 1+2+1+1+1,
     /// \brief Whether this property is a type property (currently unfortunately
     /// called 'static').
-    unsigned IsStatic : 1;
+    IsStatic : 1,
 
     /// \brief The specifier associated with this variable or parameter.  This
     /// determines the storage semantics of the value e.g. mutability.
-    unsigned Specifier : 2;
+    Specifier : 2,
 
     /// \brief Whether this declaration was an element of a capture list.
-    unsigned IsCaptureList : 1;
+    IsCaptureList : 1,
 
     /// \brief Whether this vardecl has an initial value bound to it in a way
     /// that isn't represented in the AST with an initializer in the pattern
     /// binding.  This happens in cases like "for i in ...", switch cases, etc.
-    unsigned HasNonPatternBindingInit : 1;
+    HasNonPatternBindingInit : 1,
 
     /// \brief Whether this is a property used in expressions in the debugger.
     /// It is up to the debugger to instruct SIL how to access this variable.
-    unsigned IsDebuggerVar : 1;
-  BITFIELD_END;
+    IsDebuggerVar : 1
+  );
 
-  BITFIELD_START(ParamDecl, VarDecl, 1 + NumDefaultArgumentKindBits);
+  SWIFT_INLINE_BITFIELD(ParamDecl, VarDecl, 1 + NumDefaultArgumentKindBits,
     /// True if the type is implicitly specified in the source, but this has an
     /// apparently valid typeRepr.  This is used in accessors, which look like:
     ///    set (value) {
     /// but need to get the typeRepr from the property as a whole so Sema can
     /// resolve the type.
-    unsigned IsTypeLocImplicit : 1;
+    IsTypeLocImplicit : 1,
 
     /// Information about a symbolic default argument, like #file.
-    unsigned defaultArgumentKind : NumDefaultArgumentKindBits;
-  BITFIELD_END;
+    defaultArgumentKind : NumDefaultArgumentKindBits
+  );
 
-  BITFIELD_START(EnumElementDecl, ValueDecl, 3);
+  SWIFT_INLINE_BITFIELD(EnumElementDecl, ValueDecl, 3,
+    /// \brief Whether or not this element has an associated value.
+    HasArgumentType : 1,
+
     /// \brief Whether or not this element directly or indirectly references
     /// the enum type.
-    unsigned Recursiveness : 2;
-
-    /// \brief Whether or not this element has an associated value.
-    unsigned HasArgumentType : 1;
-  BITFIELD_END;
+    Recursiveness : 2
+  );
   
-  BITFIELD_START(AbstractFunctionDecl, ValueDecl, 13);
+  SWIFT_INLINE_BITFIELD(AbstractFunctionDecl, ValueDecl, 3+8+5+1+1+1+1+1,
     /// \see AbstractFunctionDecl::BodyKind
-    unsigned BodyKind : 3;
+    BodyKind : 3,
+
+    /// Import as member status.
+    IAMStatus : 8,
 
     /// Number of curried parameter lists.
-    unsigned NumParameterLists : 5;
+    NumParameterLists : 5,
 
     /// Whether we are overridden later.
-    unsigned Overridden : 1;
+    Overridden : 1,
 
     /// Whether the function body throws.
-    unsigned Throws : 1;
+    Throws : 1,
 
     /// Whether this function requires a new vtable entry.
-    unsigned NeedsNewVTableEntry : 1;
+    NeedsNewVTableEntry : 1,
 
     /// Whether NeedsNewVTableEntry is valid.
-    unsigned HasComputedNeedsNewVTableEntry : 1;
+    HasComputedNeedsNewVTableEntry : 1,
 
     /// The ResilienceExpansion to use for default arguments.
-    unsigned DefaultArgumentResilienceExpansion : 1;
-  BITFIELD_END;
+    DefaultArgumentResilienceExpansion : 1
+  );
 
-  BITFIELD_START(FuncDecl, AbstractFunctionDecl, 7);
+  SWIFT_INLINE_BITFIELD(FuncDecl, AbstractFunctionDecl, 1+2+1+1+2,
     /// Whether this function is a 'static' method.
-    unsigned IsStatic : 1;
+    IsStatic : 1,
 
     /// \brief Whether 'static' or 'class' was used.
-    unsigned StaticSpelling : 2;
+    StaticSpelling : 2,
 
     /// Whether we are statically dispatched even if overridable
-    unsigned ForcedStaticDispatch : 1;
+    ForcedStaticDispatch : 1,
 
     /// Whether this function has a dynamic Self return type.
-    unsigned HasDynamicSelf : 1;
+    HasDynamicSelf : 1,
 
     /// Backing bits for 'self' access kind.
-    unsigned SelfAccess : 2;
-  BITFIELD_END;
+    SelfAccess : 2
+  );
 
-  BITFIELD_START(ConstructorDecl, AbstractFunctionDecl, 8);
+  SWIFT_INLINE_BITFIELD(ConstructorDecl, AbstractFunctionDecl, 3+2+2+1,
     /// The body initialization kind (+1), or zero if not yet computed.
     ///
     /// This value is cached but is not serialized, because it is a property
     /// of the definition of the constructor that is useful only to semantic
     /// analysis and SIL generation.
-    unsigned ComputedBodyInitKind : 3;
+    ComputedBodyInitKind : 3,
 
     /// The kind of initializer we have.
-    unsigned InitKind : 2;
+    InitKind : 2,
 
     /// The failability of this initializer, which is an OptionalTypeKind.
-    unsigned Failability : 2;
+    Failability : 2,
 
     /// Whether this initializer is a stub placed into a subclass to
     /// catch invalid delegations to a designated initializer not
@@ -414,177 +420,202 @@
     /// Initializer stubs can be invoked from Objective-C or through
     /// the Objective-C runtime; there is no way to directly express
     /// an object construction that will invoke a stub.
-    unsigned HasStubImplementation : 1;
-  BITFIELD_END;
+    HasStubImplementation : 1
+  );
 
-  BITFIELD_START(TypeDecl, ValueDecl, 1);
+  SWIFT_INLINE_BITFIELD(TypeDecl, ValueDecl, 1,
     /// Whether we have already checked the inheritance clause.
     ///
     /// FIXME: Is this too fine-grained?
-    unsigned CheckedInheritanceClause : 1;
-  BITFIELD_END;
+    CheckedInheritanceClause : 1
+  );
 
-  BITFIELD_START(GenericTypeDecl, TypeDecl, 0);
-  BITFIELD_END;
+  SWIFT_INLINE_BITFIELD_EMPTY(AbstractTypeParamDecl, TypeDecl);
 
-  BITFIELD_START(TypeAliasDecl, GenericTypeDecl, 1);
+  SWIFT_INLINE_BITFIELD_FULL(GenericTypeParamDecl, AbstractTypeParamDecl, 16+16,
+    : NumPadBits,
+
+    Depth : 16,
+    Index : 16
+  );
+
+  SWIFT_INLINE_BITFIELD_EMPTY(GenericTypeDecl, TypeDecl);
+
+  SWIFT_INLINE_BITFIELD(TypeAliasDecl, GenericTypeDecl, 1,
     /// Whether the typealias forwards perfectly to its underlying type.
-    unsigned IsCompatibilityAlias : 1;
-  BITFIELD_END;
+    IsCompatibilityAlias : 1
+  );
 
-  BITFIELD_START(NominalTypeDecl, GenericTypeDecl, 4);
-    /// Whether or not the nominal type decl has delayed protocol or member
-    /// declarations.
-    unsigned HasDelayedMembers : 1;
-
+  SWIFT_INLINE_BITFIELD(NominalTypeDecl, GenericTypeDecl, 1+1+1,
     /// Whether we have already added implicitly-defined initializers
     /// to this declaration.
-    unsigned AddedImplicitInitializers : 1;
+    AddedImplicitInitializers : 1,
 
     /// Whether there is are lazily-loaded conformances for this nominal type.
-    unsigned HasLazyConformances : 1;
+    HasLazyConformances : 1,
 
     /// Whether we have already validated all members of the type that
     /// affect layout.
-    unsigned HasValidatedLayout : 1;
-  BITFIELD_END;
+    HasValidatedLayout : 1
+  );
 
-  BITFIELD_START(ProtocolDecl, NominalTypeDecl, 8);
+  SWIFT_INLINE_BITFIELD_FULL(ProtocolDecl, NominalTypeDecl, 1+1+1+1+1+1+1+2+8+16,
     /// Whether the \c RequiresClass bit is valid.
-    unsigned RequiresClassValid : 1;
+    RequiresClassValid : 1,
 
     /// Whether this is a class-bounded protocol.
-    unsigned RequiresClass : 1;
+    RequiresClass : 1,
 
     /// Whether the \c ExistentialConformsToSelf bit is valid.
-    unsigned ExistentialConformsToSelfValid : 1;
+    ExistentialConformsToSelfValid : 1,
 
     /// Whether the existential of this protocol conforms to itself.
-    unsigned ExistentialConformsToSelf : 1;
+    ExistentialConformsToSelf : 1,
 
     /// Whether the \c ExistentialTypeSupported bit is valid.
-    unsigned ExistentialTypeSupportedValid : 1;
+    ExistentialTypeSupportedValid : 1,
 
     /// Whether the existential of this protocol can be represented.
-    unsigned ExistentialTypeSupported : 1;
+    ExistentialTypeSupported : 1,
+
+    /// True if the protocol has requirements that cannot be satisfied (e.g.
+    /// because they could not be imported from Objective-C).
+    HasMissingRequirements : 1,
 
     /// The stage of the circularity check for this protocol.
-    unsigned Circularity : 2;
-  BITFIELD_END;
+    Circularity : 2,
 
-  BITFIELD_START(ClassDecl, NominalTypeDecl, 8);
-    /// The stage of the inheritance circularity check for this class.
-    unsigned Circularity : 2;
+    : NumPadBits,
 
+    /// If this is a compiler-known protocol, this will be a KnownProtocolKind
+    /// value, plus one. Otherwise, it will be 0.
+    KnownProtocol : 8, // '8' for speed. This only needs 6.
+
+    /// The number of requirements in the requirement signature.
+    NumRequirementsInSignature : 16
+  );
+
+  SWIFT_INLINE_BITFIELD(ClassDecl, NominalTypeDecl, 1+2+2+2+1+3+1+1,
     /// Whether this class requires all of its instance variables to
     /// have in-class initializers.
-    unsigned RequiresStoredPropertyInits : 1;
+    RequiresStoredPropertyInits : 1,
+
+    /// The stage of the inheritance circularity check for this class.
+    Circularity : 2,
 
     /// Whether this class inherits its superclass's convenience
     /// initializers.
     ///
     /// This is a value of \c StoredInheritsSuperclassInits.
-    unsigned InheritsSuperclassInits : 2;
+    InheritsSuperclassInits : 2,
 
     /// \see ClassDecl::ForeignKind
-    unsigned RawForeignKind : 2;
+    RawForeignKind : 2,
     
     /// Whether this class contains a destructor decl.
     ///
     /// A fully type-checked class always contains a destructor member, even if
     /// it is implicit. This bit is used during parsing and type-checking to
     /// control inserting the implicit destructor.
-    unsigned HasDestructorDecl : 1;
-  BITFIELD_END;
+    HasDestructorDecl : 1,
 
-  BITFIELD_START(StructDecl, NominalTypeDecl, 1);
+    /// Whether the class has @objc ancestry.
+    ObjCKind : 3,
+
+    HasMissingDesignatedInitializers : 1,
+    HasMissingVTableEntries : 1
+  );
+
+  SWIFT_INLINE_BITFIELD(StructDecl, NominalTypeDecl, 1,
     /// True if this struct has storage for fields that aren't accessible in
     /// Swift.
-    unsigned HasUnreferenceableStorage : 1;
-  BITFIELD_END;
+    HasUnreferenceableStorage : 1
+  );
   
-  BITFIELD_START(EnumDecl, NominalTypeDecl, 4);
+  SWIFT_INLINE_BITFIELD(EnumDecl, NominalTypeDecl, 2+2,
     /// The stage of the raw type circularity check for this class.
-    unsigned Circularity : 2;
+    Circularity : 2,
 
     /// True if the enum has cases and at least one case has associated values.
-    mutable unsigned HasAssociatedValues : 2;
-  BITFIELD_END;
+    HasAssociatedValues : 2
+  );
 
-  BITFIELD_START(PrecedenceGroupDecl, Decl, 11);
-    /// The group's associativity.  A value of the Associativity enum.
-    unsigned Associativity : 2;
-
+  SWIFT_INLINE_BITFIELD(PrecedenceGroupDecl, Decl, 1+2,
     /// Is this an assignment operator?
-    unsigned IsAssignment : 1;
-  BITFIELD_END;
+    IsAssignment : 1,
 
-  BITFIELD_START(AssociatedTypeDecl, TypeDecl, 2);
-    unsigned ComputedOverridden : 1;
-    unsigned HasOverridden : 1;
-  BITFIELD_END;
+    /// The group's associativity.  A value of the Associativity enum.
+    Associativity : 2
+  );
 
-  BITFIELD_START(ImportDecl, Decl, 3);
-    unsigned ImportKind : 3;
-  BITFIELD_END;
+  SWIFT_INLINE_BITFIELD(AssociatedTypeDecl, TypeDecl, 1+1,
+    ComputedOverridden : 1,
+    HasOverridden : 1
+  );
 
-  BITFIELD_START(ExtensionDecl, Decl, 5);
-    /// Whether we have already checked the inheritance clause.
-    ///
-    /// FIXME: Is this too fine-grained?
-    unsigned CheckedInheritanceClause : 1;
+  SWIFT_INLINE_BITFIELD(ImportDecl, Decl, 3+8,
+    ImportKind : 3,
 
+    /// The number of elements in this path.
+    NumPathElements : 8
+  );
+
+  SWIFT_INLINE_BITFIELD(ExtensionDecl, Decl, 3+1+1,
     /// An encoding of the default and maximum access level for this extension.
     ///
     /// This is encoded as (1 << (maxAccess-1)) | (1 << (defaultAccess-1)),
     /// which works because the maximum is always greater than or equal to the
     /// default, and 'private' is never used. 0 represents an uncomputed value.
-    unsigned DefaultAndMaxAccessLevel : 3;
+    DefaultAndMaxAccessLevel : 3,
+
+    /// Whether we have already checked the inheritance clause.
+    ///
+    /// FIXME: Is this too fine-grained?
+    CheckedInheritanceClause : 1,
 
     /// Whether there is are lazily-loaded conformances for this extension.
-    unsigned HasLazyConformances : 1;
-  BITFIELD_END;
+    HasLazyConformances : 1
+  );
 
-  BITFIELD_START(IfConfigDecl, Decl, 1);
+  SWIFT_INLINE_BITFIELD(IfConfigDecl, Decl, 1,
     /// Whether this decl is missing its closing '#endif'.
-    unsigned HadMissingEnd : 1;
-  BITFIELD_END;
+    HadMissingEnd : 1
+  );
 
-  BITFIELD_START(MissingMemberDecl, Decl, 3);
-    unsigned NumberOfVTableEntries : 2;
-    unsigned NumberOfFieldOffsetVectorEntries : 1;
-  BITFIELD_END;
+  SWIFT_INLINE_BITFIELD(MissingMemberDecl, Decl, 1+2,
+    NumberOfFieldOffsetVectorEntries : 1,
+    NumberOfVTableEntries : 2
+  );
 
-#undef BITFIELD_START
-#undef BITFIELD_END
 protected:
   union {
-    DeclBitfields DeclBits;
-    PatternBindingDeclBitfields PatternBindingDeclBits;
-    ValueDeclBitfields ValueDeclBits;
-    AbstractStorageDeclBitfields AbstractStorageDeclBits;
-    AbstractFunctionDeclBitfields AbstractFunctionDeclBits;
-    VarDeclBitfields VarDeclBits;
-    ParamDeclBitfields ParamDeclBits;
-    EnumElementDeclBitfields EnumElementDeclBits;
-    FuncDeclBitfields FuncDeclBits;
-    ConstructorDeclBitfields ConstructorDeclBits;
-    TypeDeclBitfields TypeDeclBits;
-    GenericTypeDeclBitfields GenericTypeDeclBits;
-    TypeAliasDeclBitfields TypeAliasDeclBits;
-    NominalTypeDeclBitfields NominalTypeDeclBits;
-    ProtocolDeclBitfields ProtocolDeclBits;
-    ClassDeclBitfields ClassDeclBits;
-    StructDeclBitfields StructDeclBits;
-    EnumDeclBitfields EnumDeclBits;
-    AssociatedTypeDeclBitfields AssociatedTypeDeclBits;
-    PrecedenceGroupDeclBitfields PrecedenceGroupDeclBits;
-    ImportDeclBitfields ImportDeclBits;
-    ExtensionDeclBitfields ExtensionDeclBits;
-    IfConfigDeclBitfields IfConfigDeclBits;
-    MissingMemberDeclBitfields MissingMemberDeclBits;
     uint64_t OpaqueBits;
-  };
+    SWIFT_INLINE_BITS(Decl);
+    SWIFT_INLINE_BITS(PatternBindingDecl);
+    SWIFT_INLINE_BITS(EnumCaseDecl);
+    SWIFT_INLINE_BITS(ValueDecl);
+    SWIFT_INLINE_BITS(AbstractStorageDecl);
+    SWIFT_INLINE_BITS(AbstractFunctionDecl);
+    SWIFT_INLINE_BITS(VarDecl);
+    SWIFT_INLINE_BITS(ParamDecl);
+    SWIFT_INLINE_BITS(EnumElementDecl);
+    SWIFT_INLINE_BITS(FuncDecl);
+    SWIFT_INLINE_BITS(ConstructorDecl);
+    SWIFT_INLINE_BITS(TypeDecl);
+    SWIFT_INLINE_BITS(GenericTypeParamDecl);
+    SWIFT_INLINE_BITS(TypeAliasDecl);
+    SWIFT_INLINE_BITS(NominalTypeDecl);
+    SWIFT_INLINE_BITS(ProtocolDecl);
+    SWIFT_INLINE_BITS(ClassDecl);
+    SWIFT_INLINE_BITS(StructDecl);
+    SWIFT_INLINE_BITS(EnumDecl);
+    SWIFT_INLINE_BITS(AssociatedTypeDecl);
+    SWIFT_INLINE_BITS(PrecedenceGroupDecl);
+    SWIFT_INLINE_BITS(ImportDecl);
+    SWIFT_INLINE_BITS(ExtensionDecl);
+    SWIFT_INLINE_BITS(IfConfigDecl);
+    SWIFT_INLINE_BITS(MissingMemberDecl);
+  } Bits;
 
   // Storage for the declaration attributes.
   DeclAttributes Attrs;
@@ -606,26 +637,27 @@
 protected:
 
   Decl(DeclKind kind, llvm::PointerUnion<DeclContext *, ASTContext *> context)
-    : OpaqueBits(0), Context(context) {
-    DeclBits.Kind = unsigned(kind);
-    DeclBits.Invalid = false;
-    DeclBits.Implicit = false;
-    DeclBits.FromClang = false;
-    DeclBits.EarlyAttrValidation = false;
-    DeclBits.BeingValidated = false;
-    DeclBits.ValidationStarted = false;
-    DeclBits.EscapedFromIfConfig = false;
+    : Context(context) {
+    Bits.OpaqueBits = 0;
+    Bits.Decl.Kind = unsigned(kind);
+    Bits.Decl.Invalid = false;
+    Bits.Decl.Implicit = false;
+    Bits.Decl.FromClang = false;
+    Bits.Decl.EarlyAttrValidation = false;
+    Bits.Decl.BeingValidated = false;
+    Bits.Decl.ValidationStarted = false;
+    Bits.Decl.EscapedFromIfConfig = false;
   }
 
   ClangNode getClangNodeImpl() const {
-    assert(DeclBits.FromClang);
+    assert(Bits.Decl.FromClang);
     return ClangNode::getFromOpaqueValue(
         *(reinterpret_cast<void * const*>(this) - 1));
   }
 
   /// \brief Set the Clang node associated with this declaration.
   void setClangNode(ClangNode Node) {
-    DeclBits.FromClang = true;
+    Bits.Decl.FromClang = true;
     // Extra memory is allocated for this.
     *(reinterpret_cast<void **>(this) - 1) = Node.getOpaqueValue();
   }
@@ -639,7 +671,7 @@
   DeclContext *getDeclContextForModule() const;
 
 public:
-  DeclKind getKind() const { return DeclKind(DeclBits.Kind); }
+  DeclKind getKind() const { return DeclKind(Bits.Decl.Kind); }
 
   /// \brief Retrieve the name of the given declaration kind.
   ///
@@ -746,55 +778,55 @@
   bool walk(ASTWalker &walker);
 
   /// \brief Return whether this declaration has been determined invalid.
-  bool isInvalid() const { return DeclBits.Invalid; }
+  bool isInvalid() const { return Bits.Decl.Invalid; }
   
   /// \brief Mark this declaration invalid.
-  void setInvalid(bool isInvalid = true) { DeclBits.Invalid = isInvalid; }
+  void setInvalid(bool isInvalid = true) { Bits.Decl.Invalid = isInvalid; }
 
   /// \brief Determine whether this declaration was implicitly generated by the
   /// compiler (rather than explicitly written in source code).
-  bool isImplicit() const { return DeclBits.Implicit; }
+  bool isImplicit() const { return Bits.Decl.Implicit; }
 
   /// \brief Mark this declaration as implicit.
-  void setImplicit(bool implicit = true) { DeclBits.Implicit = implicit; }
+  void setImplicit(bool implicit = true) { Bits.Decl.Implicit = implicit; }
 
   /// Whether we have already done early attribute validation.
-  bool didEarlyAttrValidation() const { return DeclBits.EarlyAttrValidation; }
+  bool didEarlyAttrValidation() const { return Bits.Decl.EarlyAttrValidation; }
 
   /// Set whether we've performed early attribute validation.
   void setEarlyAttrValidation(bool validated = true) {
-    DeclBits.EarlyAttrValidation = validated;
+    Bits.Decl.EarlyAttrValidation = validated;
   }
   
   /// Whether the declaration has a valid interface type and
   /// generic signature.
   bool isBeingValidated() const {
-    return DeclBits.BeingValidated;
+    return Bits.Decl.BeingValidated;
   }
 
   /// Toggle whether or not the declaration is being validated.
   void setIsBeingValidated(bool ibv = true) {
-    assert(DeclBits.BeingValidated != ibv);
-    DeclBits.BeingValidated = ibv;
+    assert(Bits.Decl.BeingValidated != ibv);
+    Bits.Decl.BeingValidated = ibv;
     if (ibv) {
-      DeclBits.ValidationStarted = true;
+      Bits.Decl.ValidationStarted = true;
     }
   }
 
-  bool hasValidationStarted() const { return DeclBits.ValidationStarted; }
+  bool hasValidationStarted() const { return Bits.Decl.ValidationStarted; }
 
   /// Manually indicate that validation has started for the declaration.
   ///
   /// This is implied by setIsBeingValidated(true) (i.e. starting validation)
   /// and so rarely needs to be called directly.
-  void setValidationStarted() { DeclBits.ValidationStarted = true; }
+  void setValidationStarted() { Bits.Decl.ValidationStarted = true; }
 
   bool escapedFromIfConfig() const {
-    return DeclBits.EscapedFromIfConfig;
+    return Bits.Decl.EscapedFromIfConfig;
   }
 
   void setEscapedFromIfConfig(bool Escaped) {
-    DeclBits.EscapedFromIfConfig = Escaped;
+    Bits.Decl.EscapedFromIfConfig = Escaped;
   }
 
   /// \returns the unparsed comment attached to this declaration.
@@ -812,13 +844,13 @@
   /// \brief Returns true if there is a Clang AST node associated
   /// with self.
   bool hasClangNode() const {
-    return DeclBits.FromClang;
+    return Bits.Decl.FromClang;
   }
 
   /// \brief Retrieve the Clang AST node from which this declaration was
   /// synthesized, if any.
   ClangNode getClangNode() const {
-    if (!DeclBits.FromClang)
+    if (!Bits.Decl.FromClang)
       return ClangNode();
 
     return getClangNodeImpl();
@@ -827,7 +859,7 @@
   /// \brief Retrieve the Clang declaration from which this declaration was
   /// synthesized, if any.
   const clang::Decl *getClangDecl() const {
-    if (!DeclBits.FromClang)
+    if (!Bits.Decl.FromClang)
       return nullptr;
 
     return getClangNodeImpl().getAsDecl();
@@ -836,7 +868,7 @@
   /// \brief Retrieve the Clang macro from which this declaration was
   /// synthesized, if any.
   const clang::MacroInfo *getClangMacro() {
-    if (!DeclBits.FromClang)
+    if (!Bits.Decl.FromClang)
       return nullptr;
 
     return getClangNodeImpl().getAsMacro();
@@ -1450,9 +1482,6 @@
   SourceLoc ImportLoc;
   SourceLoc KindLoc;
 
-  /// The number of elements in this path.
-  unsigned NumPathElements;
-
   /// The resolved module.
   ModuleDecl *Mod = nullptr;
   /// The resolved decls if this is a decl import.
@@ -1481,7 +1510,8 @@
   static Optional<ImportKind> findBestImportKind(ArrayRef<ValueDecl *> Decls);
 
   ArrayRef<AccessPathElement> getFullAccessPath() const {
-    return {getTrailingObjects<AccessPathElement>(), NumPathElements};
+    return {getTrailingObjects<AccessPathElement>(),
+            Bits.ImportDecl.NumPathElements};
   }
 
   ArrayRef<AccessPathElement> getModulePath() const {
@@ -1498,7 +1528,7 @@
   }
 
   ImportKind getImportKind() const {
-    return static_cast<ImportKind>(ImportDeclBits.ImportKind);
+    return static_cast<ImportKind>(Bits.ImportDecl.ImportKind);
   }
 
   bool isExported() const {
@@ -1565,7 +1595,7 @@
   /// same operation. The caller is responsible for loading the
   /// conformances.
   std::pair<LazyMemberLoader *, uint64_t> takeConformanceLoader() {
-    if (!ExtensionDeclBits.HasLazyConformances)
+    if (!Bits.ExtensionDecl.HasLazyConformances)
       return { nullptr, 0 };
 
     return takeConformanceLoaderSlow();
@@ -1617,24 +1647,24 @@
 
   /// Whether we already type-checked the inheritance clause.
   bool checkedInheritanceClause() const {
-    return ExtensionDeclBits.CheckedInheritanceClause;
+    return Bits.ExtensionDecl.CheckedInheritanceClause;
   }
 
   /// Note that we have already type-checked the inheritance clause.
   void setCheckedInheritanceClause(bool checked = true) {
-    ExtensionDeclBits.CheckedInheritanceClause = checked;
+    Bits.ExtensionDecl.CheckedInheritanceClause = checked;
   }
 
   bool hasDefaultAccessLevel() const {
-    return ExtensionDeclBits.DefaultAndMaxAccessLevel != 0;
+    return Bits.ExtensionDecl.DefaultAndMaxAccessLevel != 0;
   }
 
   AccessLevel getDefaultAccessLevel() const {
     assert(hasDefaultAccessLevel() && "not computed yet");
-    if (ExtensionDeclBits.DefaultAndMaxAccessLevel &
+    if (Bits.ExtensionDecl.DefaultAndMaxAccessLevel &
         (1 << (static_cast<unsigned>(AccessLevel::FilePrivate) - 1)))
       return AccessLevel::FilePrivate;
-    if (ExtensionDeclBits.DefaultAndMaxAccessLevel &
+    if (Bits.ExtensionDecl.DefaultAndMaxAccessLevel &
         (1 << (static_cast<unsigned>(AccessLevel::Internal) - 1)))
       return AccessLevel::Internal;
     return AccessLevel::Public;
@@ -1642,10 +1672,10 @@
 
   AccessLevel getMaxAccessLevel() const {
     assert(hasDefaultAccessLevel() && "not computed yet");
-    if (ExtensionDeclBits.DefaultAndMaxAccessLevel &
+    if (Bits.ExtensionDecl.DefaultAndMaxAccessLevel &
         (1 << (static_cast<unsigned>(AccessLevel::Public) - 1)))
       return AccessLevel::Public;
-    if (ExtensionDeclBits.DefaultAndMaxAccessLevel &
+    if (Bits.ExtensionDecl.DefaultAndMaxAccessLevel &
         (1 << (static_cast<unsigned>(AccessLevel::Internal) - 1)))
       return AccessLevel::Internal;
     return AccessLevel::FilePrivate;
@@ -1657,7 +1687,7 @@
     assert(maxAccess >= defaultAccess);
     assert(maxAccess != AccessLevel::Private && "private not valid");
     assert(defaultAccess != AccessLevel::Private && "private not valid");
-    ExtensionDeclBits.DefaultAndMaxAccessLevel =
+    Bits.ExtensionDecl.DefaultAndMaxAccessLevel =
         (1 << (static_cast<unsigned>(defaultAccess) - 1)) |
         (1 << (static_cast<unsigned>(maxAccess) - 1));
     assert(getDefaultAccessLevel() == defaultAccess && "not enough bits");
@@ -1845,7 +1875,7 @@
   SourceRange getSourceRange() const;
 
   unsigned getNumPatternEntries() const {
-    return PatternBindingDeclBits.NumPatternEntries;
+    return Bits.PatternBindingDecl.NumPatternEntries;
   }
   
   ArrayRef<PatternBindingEntry> getPatternList() const {
@@ -1917,13 +1947,13 @@
   /// destructuring, retrieve that variable.
   VarDecl *getSingleVar() const;
 
-  bool isStatic() const { return PatternBindingDeclBits.IsStatic; }
-  void setStatic(bool s) { PatternBindingDeclBits.IsStatic = s; }
+  bool isStatic() const { return Bits.PatternBindingDecl.IsStatic; }
+  void setStatic(bool s) { Bits.PatternBindingDecl.IsStatic = s; }
   SourceLoc getStaticLoc() const { return StaticLoc; }
   /// \returns the way 'static'/'class' was spelled in the source.
   StaticSpellingKind getStaticSpelling() const {
     return static_cast<StaticSpellingKind>(
-        PatternBindingDeclBits.StaticSpelling);
+        Bits.PatternBindingDecl.StaticSpelling);
   }
   /// \returns the way 'static'/'class' should be spelled for this declaration.
   StaticSpellingKind getCorrectStaticSpelling() const;
@@ -2002,7 +2032,7 @@
                SourceLoc EndLoc, bool HadMissingEnd)
     : Decl(DeclKind::IfConfig, Parent), Clauses(Clauses), EndLoc(EndLoc)
   {
-    IfConfigDeclBits.HadMissingEnd = HadMissingEnd;
+    Bits.IfConfigDecl.HadMissingEnd = HadMissingEnd;
   }
 
   ArrayRef<IfConfigClause> getClauses() const { return Clauses; }
@@ -2023,7 +2053,7 @@
   SourceLoc getEndLoc() const { return EndLoc; }
   SourceLoc getLoc() const { return Clauses[0].Loc; }
 
-  bool hadMissingEnd() const { return IfConfigDeclBits.HadMissingEnd; }
+  bool hadMissingEnd() const { return Bits.IfConfigDecl.HadMissingEnd; }
   
   SourceRange getSourceRange() const;
   
@@ -2044,9 +2074,18 @@
             llvm::PointerUnion<DeclContext *, ASTContext *> context,
             DeclName name, SourceLoc NameLoc)
     : Decl(K, context), Name(name), NameLoc(NameLoc) {
-    ValueDeclBits.AlreadyInLookupTable = false;
-    ValueDeclBits.CheckedRedeclaration = false;
-    ValueDeclBits.IsUserAccessible = true;
+    Bits.ValueDecl.AlreadyInLookupTable = false;
+    Bits.ValueDecl.CheckedRedeclaration = false;
+    Bits.ValueDecl.IsUserAccessible = true;
+  }
+
+  // MemberLookupTable borrows a bit from this type
+  friend class MemberLookupTable;
+  bool isAlreadyInLookupTable() {
+    return Bits.ValueDecl.AlreadyInLookupTable;
+  }
+  void setAlreadyInLookupTable(bool value = true) {
+    Bits.ValueDecl.AlreadyInLookupTable = value;
   }
 
 public:
@@ -2063,21 +2102,21 @@
   /// Determine whether we have already checked whether this
   /// declaration is a redeclaration.
   bool alreadyCheckedRedeclaration() const { 
-    return ValueDeclBits.CheckedRedeclaration; 
+    return Bits.ValueDecl.CheckedRedeclaration; 
   }
 
   /// Set whether we have already checked this declaration as a
   /// redeclaration.
   void setCheckedRedeclaration(bool checked) {
-    ValueDeclBits.CheckedRedeclaration = checked;
+    Bits.ValueDecl.CheckedRedeclaration = checked;
   }
 
   void setUserAccessible(bool Accessible) {
-    ValueDeclBits.IsUserAccessible = Accessible;
+    Bits.ValueDecl.IsUserAccessible = Accessible;
   }
 
   bool isUserAccessible() const {
-    return ValueDeclBits.IsUserAccessible;
+    return Bits.ValueDecl.IsUserAccessible;
   }
 
   bool hasName() const { return bool(Name); }
@@ -2313,7 +2352,7 @@
            MutableArrayRef<TypeLoc> inherited) :
     ValueDecl(K, context, name, NameLoc), Inherited(inherited)
   {
-    TypeDeclBits.CheckedInheritanceClause = false;
+    Bits.TypeDecl.CheckedInheritanceClause = false;
   }
 
 public:
@@ -2337,12 +2376,12 @@
 
   /// Whether we already type-checked the inheritance clause.
   bool checkedInheritanceClause() const {
-    return TypeDeclBits.CheckedInheritanceClause;
+    return Bits.TypeDecl.CheckedInheritanceClause;
   }
 
   /// Note that we have already type-checked the inheritance clause.
   void setCheckedInheritanceClause(bool checked = true) {
-    TypeDeclBits.CheckedInheritanceClause = checked;
+    Bits.TypeDecl.CheckedInheritanceClause = checked;
   }
 
   void setInherited(MutableArrayRef<TypeLoc> i) { Inherited = i; }
@@ -2425,11 +2464,11 @@
   UnboundGenericType *getUnboundGenericType() const;
 
   bool isCompatibilityAlias() const {
-    return TypeAliasDeclBits.IsCompatibilityAlias;
+    return Bits.TypeAliasDecl.IsCompatibilityAlias;
   }
 
   void markAsCompatibilityAlias(bool newValue = true) {
-    TypeAliasDeclBits.IsCompatibilityAlias = newValue;
+    Bits.TypeAliasDecl.IsCompatibilityAlias = newValue;
   }
 
   static bool classof(const Decl *D) {
@@ -2481,9 +2520,6 @@
 /// func min<T : Comparable>(x : T, y : T) -> T { ... }
 /// \endcode
 class GenericTypeParamDecl : public AbstractTypeParamDecl {
-  unsigned Depth : 16;
-  unsigned Index : 16;
-
 public:
   static const unsigned InvalidDepth = 0xFFFF;
 
@@ -2508,12 +2544,15 @@
   /// \endcode
   ///
   /// Here 'T' has depth 0 and 'U' has depth 1. Both have index 0.
-  unsigned getDepth() const { return Depth; }
+  unsigned getDepth() const { return Bits.GenericTypeParamDecl.Depth; }
 
   /// Set the depth of this generic type parameter.
   ///
   /// \sa getDepth
-  void setDepth(unsigned depth) { Depth = depth; }
+  void setDepth(unsigned depth) {
+    Bits.GenericTypeParamDecl.Depth = depth;
+    assert(Bits.GenericTypeParamDecl.Depth == depth && "Truncation");
+  }
 
   /// The index of this generic type parameter within its generic parameter
   /// list.
@@ -2525,7 +2564,7 @@
   /// \endcode
   ///
   /// Here 'T' and 'U' have indexes 0 and 1, respectively. 'V' has index 0.
-  unsigned getIndex() const { return Index; }
+  unsigned getIndex() const { return Bits.GenericTypeParamDecl.Index; }
 
   SourceLoc getStartLoc() const { return getNameLoc(); }
   SourceRange getSourceRange() const;
@@ -2622,7 +2661,7 @@
 
   /// Whether the overridden declarations have already been computed.
   bool overriddenDeclsComputed() const {
-    return AssociatedTypeDeclBits.ComputedOverridden;
+    return Bits.AssociatedTypeDecl.ComputedOverridden;
   }
 
   /// Record the set of overridden declarations.
@@ -2699,7 +2738,7 @@
   /// same operation. The caller is responsible for loading the
   /// conformances.
   std::pair<LazyMemberLoader *, uint64_t> takeConformanceLoader() {
-    if (!NominalTypeDeclBits.HasLazyConformances)
+    if (!Bits.NominalTypeDecl.HasLazyConformances)
       return { nullptr, 0 };
 
     return takeConformanceLoaderSlow();
@@ -2758,11 +2797,10 @@
     IterableDeclContext(IterableDeclContextKind::NominalTypeDecl)
   {
     setGenericParams(GenericParams);
-    NominalTypeDeclBits.HasDelayedMembers = false;
-    NominalTypeDeclBits.AddedImplicitInitializers = false;
+    Bits.NominalTypeDecl.AddedImplicitInitializers = false;
     ExtensionGeneration = 0;
-    NominalTypeDeclBits.HasLazyConformances = false;
-    NominalTypeDeclBits.HasValidatedLayout = false;
+    Bits.NominalTypeDecl.HasLazyConformances = false;
+    Bits.NominalTypeDecl.HasValidatedLayout = false;
   }
 
   friend class ProtocolType;
@@ -2788,38 +2826,27 @@
   /// module?
   bool hasFixedLayout(ModuleDecl *M, ResilienceExpansion expansion) const;
 
-  /// \brief Returns true if this decl contains delayed value or protocol
-  /// declarations.
-  bool hasDelayedMembers() const {
-    return NominalTypeDeclBits.HasDelayedMembers;
-  }
-  
-  /// \brief Mark this declaration as having delayed members or not.
-  void setHasDelayedMembers(bool hasDelayedMembers = true) {
-    NominalTypeDeclBits.HasDelayedMembers = hasDelayedMembers;
-  }
-
   /// Determine whether we have already attempted to add any
   /// implicitly-defined initializers to this declaration.
   bool addedImplicitInitializers() const {
-    return NominalTypeDeclBits.AddedImplicitInitializers;
+    return Bits.NominalTypeDecl.AddedImplicitInitializers;
   }
 
   /// Note that we have attempted to add implicit initializers.
   void setAddedImplicitInitializers() {
-    NominalTypeDeclBits.AddedImplicitInitializers = true;
+    Bits.NominalTypeDecl.AddedImplicitInitializers = true;
   }
 
   /// Determine whether we have already validated any members
   /// which affect layout.
   bool hasValidatedLayout() const {
-    return NominalTypeDeclBits.HasValidatedLayout;
+    return Bits.NominalTypeDecl.HasValidatedLayout;
   }
 
   /// Note that we have attempted to validate any members
   /// which affect layout.
   void setHasValidatedLayout() {
-    NominalTypeDeclBits.HasValidatedLayout = true;
+    Bits.NominalTypeDecl.HasValidatedLayout = true;
   }
 
   /// Compute the type of this nominal type.
@@ -3077,12 +3104,12 @@
   
   /// Retrieve the status of circularity checking for class inheritance.
   CircularityCheck getCircularityCheck() const {
-    return static_cast<CircularityCheck>(EnumDeclBits.Circularity);
+    return static_cast<CircularityCheck>(Bits.EnumDecl.Circularity);
   }
   
   /// Record the current stage of circularity checking.
   void setCircularityCheck(CircularityCheck circularity) {
-    EnumDeclBits.Circularity = static_cast<unsigned>(circularity);
+    Bits.EnumDecl.Circularity = static_cast<unsigned>(circularity);
   }
   
   // Implement isa/cast/dyncast/etc.
@@ -3176,11 +3203,11 @@
   /// Does this struct contain unreferenceable storage, such as C fields that
   /// cannot be represented in Swift?
   bool hasUnreferenceableStorage() const {
-    return StructDeclBits.HasUnreferenceableStorage;
+    return Bits.StructDecl.HasUnreferenceableStorage;
   }
 
   void setHasUnreferenceableStorage(bool v) {
-    StructDeclBits.HasUnreferenceableStorage = v;
+    Bits.StructDecl.HasUnreferenceableStorage = v;
   }
 };
 
@@ -3226,12 +3253,6 @@
     llvm::PointerIntPair<Type, 1, bool> Superclass;
   } LazySemanticInfo;
 
-  /// Whether the class has @objc ancestry.
-  unsigned ObjCKind : 3;
-
-  unsigned HasMissingDesignatedInitializers : 1;
-  unsigned HasMissingVTableEntries : 1;
-
   friend class IterativeTypeChecker;
 
 public:
@@ -3259,24 +3280,24 @@
 
   /// Retrieve the status of circularity checking for class inheritance.
   CircularityCheck getCircularityCheck() const {
-    return static_cast<CircularityCheck>(ClassDeclBits.Circularity);
+    return static_cast<CircularityCheck>(Bits.ClassDecl.Circularity);
   }
 
   /// Record the current stage of circularity checking.
   void setCircularityCheck(CircularityCheck circularity) {
-    ClassDeclBits.Circularity = static_cast<unsigned>(circularity);
+    Bits.ClassDecl.Circularity = static_cast<unsigned>(circularity);
   }
 
   //// Whether this class requires all of its stored properties to
   //// have initializers in the class definition.
   bool requiresStoredPropertyInits() const { 
-    return ClassDeclBits.RequiresStoredPropertyInits;
+    return Bits.ClassDecl.RequiresStoredPropertyInits;
   }
 
   /// Set whether this class requires all of its stored properties to
   /// have initializers in the class definition.
   void setRequiresStoredPropertyInits(bool requiresInits) {
-    ClassDeclBits.RequiresStoredPropertyInits = requiresInits;
+    Bits.ClassDecl.RequiresStoredPropertyInits = requiresInits;
   }
 
   /// \see getForeignClassKind
@@ -3303,10 +3324,10 @@
   /// We may find ourselves wanting to break this bit into more
   /// precise chunks later.
   ForeignKind getForeignClassKind() const {
-    return static_cast<ForeignKind>(ClassDeclBits.RawForeignKind);
+    return static_cast<ForeignKind>(Bits.ClassDecl.RawForeignKind);
   }
   void setForeignClassKind(ForeignKind kind) {
-    ClassDeclBits.RawForeignKind = static_cast<unsigned>(kind);
+    Bits.ClassDecl.RawForeignKind = static_cast<unsigned>(kind);
   }
 
   /// Returns true if this class is any kind of "foreign class".
@@ -3324,7 +3345,7 @@
   bool hasMissingDesignatedInitializers() const;
 
   void setHasMissingDesignatedInitializers(bool newValue = true) {
-    HasMissingDesignatedInitializers = newValue;
+    Bits.ClassDecl.HasMissingDesignatedInitializers = newValue;
   }
 
   /// Returns true if the class has missing members that require vtable entries.
@@ -3334,7 +3355,7 @@
   bool hasMissingVTableEntries() const;
 
   void setHasMissingVTableEntries(bool newValue = true) {
-    HasMissingVTableEntries = newValue;
+    Bits.ClassDecl.HasMissingVTableEntries = newValue;
   }
 
   /// Find a method of a class that overrides a given method.
@@ -3353,10 +3374,10 @@
   /// Fully type-checked classes always contain destructors, but during parsing
   /// or type-checking, the implicit destructor may not have been synthesized
   /// yet if one was not explicitly declared.
-  bool hasDestructor() const { return ClassDeclBits.HasDestructorDecl; }
+  bool hasDestructor() const { return Bits.ClassDecl.HasDestructorDecl; }
 
   /// Set the 'has destructor' flag.
-  void setHasDestructor() { ClassDeclBits.HasDestructorDecl = 1; }
+  void setHasDestructor() { Bits.ClassDecl.HasDestructorDecl = 1; }
   
   /// Retrieve the destructor for this class.
   DestructorDecl *getDestructor();
@@ -3523,17 +3544,6 @@
   /// by this protocol.
   const Requirement *RequirementSignature = nullptr;
 
-  /// True if the protocol has requirements that cannot be satisfied (e.g.
-  /// because they could not be imported from Objective-C).
-  unsigned HasMissingRequirements : 1;
-
-  /// If this is a compiler-known protocol, this will be a KnownProtocolKind
-  /// value, plus one. Otherwise, it will be 0.
-  unsigned KnownProtocol : 6;
-
-  /// The number of requirements in the requirement signature.
-  unsigned NumRequirementsInSignature : 16;
-
   bool requiresClassSlow();
 
   bool existentialConformsToSelfSlow();
@@ -3584,8 +3594,8 @@
 
   /// True if this protocol can only be conformed to by class types.
   bool requiresClass() const {
-    if (ProtocolDeclBits.RequiresClassValid)
-      return ProtocolDeclBits.RequiresClass;
+    if (Bits.ProtocolDecl.RequiresClassValid)
+      return Bits.ProtocolDecl.RequiresClass;
 
     return const_cast<ProtocolDecl *>(this)->requiresClassSlow();
   }
@@ -3593,8 +3603,8 @@
   /// Specify that this protocol is class-bounded, e.g., because it was
   /// annotated with the 'class' keyword.
   void setRequiresClass(bool requiresClass = true) {
-    ProtocolDeclBits.RequiresClassValid = true;
-    ProtocolDeclBits.RequiresClass = requiresClass;
+    Bits.ProtocolDecl.RequiresClassValid = true;
+    Bits.ProtocolDecl.RequiresClass = requiresClass;
   }
 
   /// Determine whether an existential conforming to this protocol can be
@@ -3603,8 +3613,8 @@
   /// can do with the metatype, which means the protocol must not have
   /// any static methods and must be declared @objc.
   bool existentialConformsToSelf() const {
-    if (ProtocolDeclBits.ExistentialConformsToSelfValid)
-      return ProtocolDeclBits.ExistentialConformsToSelf;
+    if (Bits.ProtocolDecl.ExistentialConformsToSelfValid)
+      return Bits.ProtocolDecl.ExistentialConformsToSelf;
 
     return const_cast<ProtocolDecl *>(this)
              ->existentialConformsToSelfSlow();
@@ -3633,8 +3643,8 @@
   /// all the members do not contain any associated types, and do not
   /// contain 'Self' in 'parameter' or 'other' position.
   bool existentialTypeSupported(LazyResolver *resolver) const {
-    if (ProtocolDeclBits.ExistentialTypeSupportedValid)
-      return ProtocolDeclBits.ExistentialTypeSupported;
+    if (Bits.ProtocolDecl.ExistentialTypeSupportedValid)
+      return Bits.ProtocolDecl.ExistentialTypeSupported;
 
     return const_cast<ProtocolDecl *>(this)
              ->existentialTypeSupportedSlow(resolver);
@@ -3644,8 +3654,8 @@
   /// it from members. Only called from deserialization, where the flag
   /// was stored in the serialized record.
   void setExistentialTypeSupported(bool supported) {
-    ProtocolDeclBits.ExistentialTypeSupported = supported;
-    ProtocolDeclBits.ExistentialTypeSupportedValid = true;
+    Bits.ProtocolDecl.ExistentialTypeSupported = supported;
+    Bits.ProtocolDecl.ExistentialTypeSupportedValid = true;
   }
 
   /// If this is known to be a compiler-known protocol, returns the kind.
@@ -3653,9 +3663,9 @@
   ///
   /// Note that this is only valid after type-checking.
   Optional<KnownProtocolKind> getKnownProtocolKind() const {
-    if (KnownProtocol == 0)
+    if (Bits.ProtocolDecl.KnownProtocol == 0)
       return None;
-    return static_cast<KnownProtocolKind>(KnownProtocol - 1);
+    return static_cast<KnownProtocolKind>(Bits.ProtocolDecl.KnownProtocol - 1);
   }
 
   /// Check whether this protocol is of a specific, known protocol kind.
@@ -3670,19 +3680,19 @@
   void setKnownProtocolKind(KnownProtocolKind kind) {
     assert((!getKnownProtocolKind() || *getKnownProtocolKind() == kind) &&
            "can't reset known protocol kind");
-    KnownProtocol = static_cast<unsigned>(kind) + 1;
+    Bits.ProtocolDecl.KnownProtocol = static_cast<unsigned>(kind) + 1;
     assert(getKnownProtocolKind() && *getKnownProtocolKind() == kind &&
            "not enough bits");
   }
 
   /// Retrieve the status of circularity checking for protocol inheritance.
   CircularityCheck getCircularityCheck() const {
-    return static_cast<CircularityCheck>(ProtocolDeclBits.Circularity);
+    return static_cast<CircularityCheck>(Bits.ProtocolDecl.Circularity);
   }
 
   /// Record the current stage of circularity checking.
   void setCircularityCheck(CircularityCheck circularity) {
-    ProtocolDeclBits.Circularity = static_cast<unsigned>(circularity);
+    Bits.ProtocolDecl.Circularity = static_cast<unsigned>(circularity);
   }
 
   /// Returns true if the protocol has requirements that are not listed in its
@@ -3692,11 +3702,11 @@
   /// with requirements that cannot be represented in Swift.
   bool hasMissingRequirements() const {
     (void)getMembers();
-    return HasMissingRequirements;
+    return Bits.ProtocolDecl.HasMissingRequirements;
   }
 
   void setHasMissingRequirements(bool newValue) {
-    HasMissingRequirements = newValue;
+    Bits.ProtocolDecl.HasMissingRequirements = newValue;
   }
 
   /// Returns the default witness for a requirement, or nullptr if there is
@@ -3733,7 +3743,8 @@
   ArrayRef<Requirement> getRequirementSignature() const {
     assert(isRequirementSignatureComputed() &&
            "getting requirement signature before computing it");
-    return llvm::makeArrayRef(RequirementSignature, NumRequirementsInSignature);
+    return llvm::makeArrayRef(RequirementSignature,
+                              Bits.ProtocolDecl.NumRequirementsInSignature);
   }
 
   /// Has the requirement signature been computed yet?
@@ -3999,17 +4010,17 @@
   }
 
   void setStorageKind(StorageKindTy K) {
-    AbstractStorageDeclBits.StorageKind = unsigned(K);
+    Bits.AbstractStorageDecl.StorageKind = unsigned(K);
   }
 
 protected:
   AbstractStorageDecl(DeclKind Kind, DeclContext *DC, DeclName Name,
                       SourceLoc NameLoc)
     : ValueDecl(Kind, DC, Name, NameLoc), OverriddenDecl(nullptr) {
-    AbstractStorageDeclBits.StorageKind = Stored;
-    AbstractStorageDeclBits.IsGetterMutating = false;
-    AbstractStorageDeclBits.IsSetterMutating = true;
-    AbstractStorageDeclBits.Overridden = false;
+    Bits.AbstractStorageDecl.StorageKind = Stored;
+    Bits.AbstractStorageDecl.IsGetterMutating = false;
+    Bits.AbstractStorageDecl.IsSetterMutating = true;
+    Bits.AbstractStorageDecl.Overridden = false;
   }
 public:
 
@@ -4025,7 +4036,7 @@
   /// has no storage but does have a user-defined getter or setter.
   ///
   StorageKindTy getStorageKind() const {
-    return (StorageKindTy) AbstractStorageDeclBits.StorageKind;
+    return (StorageKindTy) Bits.AbstractStorageDecl.StorageKind;
   }
 
   /// \brief Return true if this is a VarDecl that has storage associated with
@@ -4114,19 +4125,19 @@
   /// \brief Return true if reading this storage requires the ability to
   /// modify the base value.
   bool isGetterMutating() const {
-    return AbstractStorageDeclBits.IsGetterMutating;
+    return Bits.AbstractStorageDecl.IsGetterMutating;
   }
   void setIsGetterMutating(bool isMutating) {
-    AbstractStorageDeclBits.IsGetterMutating = isMutating;
+    Bits.AbstractStorageDecl.IsGetterMutating = isMutating;
   }
   
   /// \brief Return true if modifying this storage requires the ability to
   /// modify the base value.
   bool isSetterMutating() const {
-    return AbstractStorageDeclBits.IsSetterMutating;
+    return Bits.AbstractStorageDecl.IsSetterMutating;
   }
   void setIsSetterMutating(bool isMutating) {
-    AbstractStorageDeclBits.IsSetterMutating = isMutating;
+    Bits.AbstractStorageDecl.IsSetterMutating = isMutating;
   }
 
   FuncDecl *getAccessorFunction(AccessorKind accessor) const;
@@ -4293,14 +4304,14 @@
   ///
   /// Resolved during type checking
   void setIsOverridden() {
-    AbstractStorageDeclBits.Overridden = true;
+    Bits.AbstractStorageDecl.Overridden = true;
   }
 
   /// Whether the declaration is later overridden in the module
   ///
   /// Overrides are resolved during type checking; only query this field after
   /// the whole module has been checked
-  bool isOverridden() const { return AbstractStorageDeclBits.Overridden; }
+  bool isOverridden() const { return Bits.AbstractStorageDecl.Overridden; }
 
   /// Returns the location of 'override' keyword, if any.
   SourceLoc getOverrideLoc() const;
@@ -4379,11 +4390,11 @@
           SourceLoc NameLoc, Identifier Name, Type Ty, DeclContext *DC)
     : AbstractStorageDecl(Kind, DC, Name, NameLoc)
   {
-    VarDeclBits.IsStatic = IsStatic;
-    VarDeclBits.Specifier = static_cast<unsigned>(Sp);
-    VarDeclBits.IsCaptureList = IsCaptureList;
-    VarDeclBits.IsDebuggerVar = false;
-    VarDeclBits.HasNonPatternBindingInit = false;
+    Bits.VarDecl.IsStatic = IsStatic;
+    Bits.VarDecl.Specifier = static_cast<unsigned>(Sp);
+    Bits.VarDecl.IsCaptureList = IsCaptureList;
+    Bits.VarDecl.IsDebuggerVar = false;
+    Bits.VarDecl.HasNonPatternBindingInit = false;
     setType(Ty);
   }
 
@@ -4494,10 +4505,10 @@
 
   /// Return the raw specifier value for this property or parameter.
   Specifier getSpecifier() const {
-    return static_cast<Specifier>(VarDeclBits.Specifier);
+    return static_cast<Specifier>(Bits.VarDecl.Specifier);
   }
   void setSpecifier(Specifier Spec) {
-    VarDeclBits.Specifier = static_cast<unsigned>(Spec);
+    Bits.VarDecl.Specifier = static_cast<unsigned>(Spec);
   }
   
   /// Is the type of this parameter 'inout'?
@@ -4512,8 +4523,8 @@
   
   
   /// Is this a type ('static') variable?
-  bool isStatic() const { return VarDeclBits.IsStatic; }
-  void setStatic(bool IsStatic) { VarDeclBits.IsStatic = IsStatic; }
+  bool isStatic() const { return Bits.VarDecl.IsStatic; }
+  void setStatic(bool IsStatic) { Bits.VarDecl.IsStatic = IsStatic; }
 
   /// \returns the way 'static'/'class' should be spelled for this declaration.
   StaticSpellingKind getCorrectStaticSpelling() const;
@@ -4524,22 +4535,22 @@
   bool isShared() const { return getSpecifier() == Specifier::Shared; }
   
   /// Is this an element in a capture list?
-  bool isCaptureList() const { return VarDeclBits.IsCaptureList; }
+  bool isCaptureList() const { return Bits.VarDecl.IsCaptureList; }
 
   /// Return true if this vardecl has an initial value bound to it in a way
   /// that isn't represented in the AST with an initializer in the pattern
   /// binding.  This happens in cases like "for i in ...", switch cases, etc.
   bool hasNonPatternBindingInit() const {
-    return VarDeclBits.HasNonPatternBindingInit;
+    return Bits.VarDecl.HasNonPatternBindingInit;
   }
   void setHasNonPatternBindingInit(bool V = true) {
-    VarDeclBits.HasNonPatternBindingInit = V;
+    Bits.VarDecl.HasNonPatternBindingInit = V;
   }
   
   /// Is this a special debugger variable?
-  bool isDebuggerVar() const { return VarDeclBits.IsDebuggerVar; }
+  bool isDebuggerVar() const { return Bits.VarDecl.IsDebuggerVar; }
   void setDebuggerVar(bool IsDebuggerVar) {
-    VarDeclBits.IsDebuggerVar = IsDebuggerVar;
+    Bits.VarDecl.IsDebuggerVar = IsDebuggerVar;
   }
 
   /// Return the Objective-C runtime name for this property.
@@ -4609,17 +4620,17 @@
   
   SourceLoc getSpecifierLoc() const { return SpecifierLoc; }
     
-  bool isTypeLocImplicit() const { return ParamDeclBits.IsTypeLocImplicit; }
-  void setIsTypeLocImplicit(bool val) { ParamDeclBits.IsTypeLocImplicit = val; }
+  bool isTypeLocImplicit() const { return Bits.ParamDecl.IsTypeLocImplicit; }
+  void setIsTypeLocImplicit(bool val) { Bits.ParamDecl.IsTypeLocImplicit = val; }
   
   DefaultArgumentKind getDefaultArgumentKind() const {
-    return static_cast<DefaultArgumentKind>(ParamDeclBits.defaultArgumentKind);
+    return static_cast<DefaultArgumentKind>(Bits.ParamDecl.defaultArgumentKind);
   }
   bool isDefaultArgument() const {
     return getDefaultArgumentKind() != DefaultArgumentKind::None;
   }
   void setDefaultArgumentKind(DefaultArgumentKind K) {
-    ParamDeclBits.defaultArgumentKind = static_cast<unsigned>(K);
+    Bits.ParamDecl.defaultArgumentKind = static_cast<unsigned>(K);
   }
   
   Expr *getDefaultValue() const {
@@ -4784,10 +4795,17 @@
 
 /// Encodes imported-as-member status for C functions that get imported
 /// as methods.
-struct ImportAsMemberStatus {
+class ImportAsMemberStatus {
+  friend class AbstractFunctionDecl;
+
   // non-0 denotes import-as-member. 1 denotes no self index. n+2 denotes self
   // index of n
-  uint8_t rawValue = 0;
+  uint8_t rawValue;
+
+public:
+  ImportAsMemberStatus(uint8_t rawValue = 0) : rawValue(rawValue) {}
+
+  uint8_t getRawValue() const { return rawValue; }
 
   bool isImportAsMember() const { return rawValue != 0; }
   bool isInstance() const { return rawValue >= 2; }
@@ -4836,7 +4854,7 @@
   };
 
   BodyKind getBodyKind() const {
-    return BodyKind(AbstractFunctionDeclBits.BodyKind);
+    return BodyKind(Bits.AbstractFunctionDecl.BodyKind);
   }
 
   using BodySynthesizer = void (*)(AbstractFunctionDecl *);
@@ -4864,8 +4882,6 @@
   /// Location of the 'throws' token.
   SourceLoc ThrowsLoc;
 
-  ImportAsMemberStatus IAMStatus;
-
   AbstractFunctionDecl(DeclKind Kind, DeclContext *Parent, DeclName Name,
                        SourceLoc NameLoc, bool Throws, SourceLoc ThrowsLoc,
                        unsigned NumParameterLists,
@@ -4875,20 +4891,20 @@
         Body(nullptr), ThrowsLoc(ThrowsLoc) {
     setBodyKind(BodyKind::None);
     setGenericParams(GenericParams);
-    AbstractFunctionDeclBits.NumParameterLists = NumParameterLists;
-    AbstractFunctionDeclBits.Overridden = false;
-    AbstractFunctionDeclBits.Throws = Throws;
-    AbstractFunctionDeclBits.NeedsNewVTableEntry = false;
-    AbstractFunctionDeclBits.HasComputedNeedsNewVTableEntry = false;
-    AbstractFunctionDeclBits.DefaultArgumentResilienceExpansion =
+    Bits.AbstractFunctionDecl.NumParameterLists = NumParameterLists;
+    Bits.AbstractFunctionDecl.Overridden = false;
+    Bits.AbstractFunctionDecl.Throws = Throws;
+    Bits.AbstractFunctionDecl.NeedsNewVTableEntry = false;
+    Bits.AbstractFunctionDecl.HasComputedNeedsNewVTableEntry = false;
+    Bits.AbstractFunctionDecl.DefaultArgumentResilienceExpansion =
         unsigned(ResilienceExpansion::Maximal);
 
     // Verify no bitfield truncation.
-    assert(AbstractFunctionDeclBits.NumParameterLists == NumParameterLists);
+    assert(Bits.AbstractFunctionDecl.NumParameterLists == NumParameterLists);
   }
 
   void setBodyKind(BodyKind K) {
-    AbstractFunctionDeclBits.BodyKind = unsigned(K);
+    Bits.AbstractFunctionDecl.BodyKind = unsigned(K);
   }
 
 public:
@@ -4903,21 +4919,39 @@
   bool isTransparent() const;
 
   // Expose our import as member status
-  bool isImportAsMember() const { return IAMStatus.isImportAsMember(); }
-  bool isImportAsInstanceMember() const { return IAMStatus.isInstance(); }
-  bool isImportAsStaticMember() const { return IAMStatus.isStatic(); }
-  uint8_t getSelfIndex() const { return IAMStatus.getSelfIndex(); }
-  ImportAsMemberStatus getImportAsMemberStatus() const { return IAMStatus; }
+  ImportAsMemberStatus getImportAsMemberStatus() const {
+    return ImportAsMemberStatus(Bits.AbstractFunctionDecl.IAMStatus);
+  }
+  bool isImportAsMember() const {
+    return getImportAsMemberStatus().isImportAsMember();
+  }
+  bool isImportAsInstanceMember() const {
+    return getImportAsMemberStatus().isInstance();
+  }
+  bool isImportAsStaticMember() const {
+    return getImportAsMemberStatus().isStatic();
+  }
+  uint8_t getSelfIndex() const {
+    return getImportAsMemberStatus().getSelfIndex();
+  }
 
-  void setImportAsStaticMember() { IAMStatus.setStatic(); }
-  void setSelfIndex(uint8_t idx) { return IAMStatus.setSelfIndex(idx); }
+  void setImportAsStaticMember() {
+    auto newValue = getImportAsMemberStatus();
+    newValue.setStatic();
+    Bits.AbstractFunctionDecl.IAMStatus = newValue.getRawValue();
+  }
+  void setSelfIndex(uint8_t idx) {
+    auto newValue = getImportAsMemberStatus();
+    newValue.setSelfIndex(idx);
+    Bits.AbstractFunctionDecl.IAMStatus = newValue.getRawValue();
+  }
 
 public:
   /// Retrieve the location of the 'throws' keyword, if present.
   SourceLoc getThrowsLoc() const { return ThrowsLoc; }
 
   /// Returns true if the function body throws.
-  bool hasThrows() const { return AbstractFunctionDeclBits.Throws; }
+  bool hasThrows() const { return Bits.AbstractFunctionDecl.Throws; }
 
   // FIXME: Hack that provides names with keyword arguments for accessors.
   DeclName getEffectiveFullName() const;
@@ -5002,14 +5036,14 @@
   }
 
   void setNeedsNewVTableEntry(bool value) {
-    AbstractFunctionDeclBits.HasComputedNeedsNewVTableEntry = true;
-    AbstractFunctionDeclBits.NeedsNewVTableEntry = value;
+    Bits.AbstractFunctionDecl.HasComputedNeedsNewVTableEntry = true;
+    Bits.AbstractFunctionDecl.NeedsNewVTableEntry = value;
   }
 
   bool needsNewVTableEntry() const {
-    if (!AbstractFunctionDeclBits.HasComputedNeedsNewVTableEntry)
+    if (!Bits.AbstractFunctionDecl.HasComputedNeedsNewVTableEntry)
       const_cast<AbstractFunctionDecl *>(this)->computeNeedsNewVTableEntry();
-    return AbstractFunctionDeclBits.NeedsNewVTableEntry;
+    return Bits.AbstractFunctionDecl.NeedsNewVTableEntry;
   }
 
 private:
@@ -5051,7 +5085,7 @@
   /// function.  This value is one for free-standing functions, and two for
   /// methods.
   unsigned getNumParameterLists() const {
-    return AbstractFunctionDeclBits.NumParameterLists;
+    return Bits.AbstractFunctionDecl.NumParameterLists;
   }
 
   /// \brief Returns the parameter pattern(s) for the function definition that
@@ -5092,12 +5126,12 @@
   ///
   /// Overrides are resolved during type checking; only query this field after
   /// the whole module has been checked
-  bool isOverridden() const { return AbstractFunctionDeclBits.Overridden; }
+  bool isOverridden() const { return Bits.AbstractFunctionDecl.Overridden; }
 
   /// The declaration has been overridden in the module
   ///
   /// Resolved during type checking
-  void setIsOverridden() { AbstractFunctionDeclBits.Overridden = true; }
+  void setIsOverridden() { Bits.AbstractFunctionDecl.Overridden = true; }
 
   /// The ResilienceExpansion for default arguments.
   ///
@@ -5105,12 +5139,12 @@
   /// obey the restrictions imposed upon inlineable function bodies.
   ResilienceExpansion getDefaultArgumentResilienceExpansion() const {
     return ResilienceExpansion(
-        AbstractFunctionDeclBits.DefaultArgumentResilienceExpansion);
+        Bits.AbstractFunctionDecl.DefaultArgumentResilienceExpansion);
   }
 
   /// Set the ResilienceExpansion for default arguments.
   void setDefaultArgumentResilienceExpansion(ResilienceExpansion expansion) {
-    AbstractFunctionDeclBits.DefaultArgumentResilienceExpansion =
+    Bits.AbstractFunctionDecl.DefaultArgumentResilienceExpansion =
         unsigned(expansion);
   }
 
@@ -5192,14 +5226,14 @@
       AccessorKeywordLoc(AccessorKeywordLoc),
       OverriddenOrBehaviorParamDecl(),
       OperatorAndAddressorKind(nullptr, AddressorKind::NotAddressor) {
-    FuncDeclBits.IsStatic =
+    Bits.FuncDecl.IsStatic =
       StaticLoc.isValid() || StaticSpelling != StaticSpellingKind::None;
-    FuncDeclBits.StaticSpelling = static_cast<unsigned>(StaticSpelling);
+    Bits.FuncDecl.StaticSpelling = static_cast<unsigned>(StaticSpelling);
     assert(NumParameterLists > 0 && "Must have at least an empty tuple arg");
 
-    FuncDeclBits.HasDynamicSelf = false;
-    FuncDeclBits.ForcedStaticDispatch = false;
-    FuncDeclBits.SelfAccess = static_cast<unsigned>(SelfAccessKind::NonMutating);
+    Bits.FuncDecl.HasDynamicSelf = false;
+    Bits.FuncDecl.ForcedStaticDispatch = false;
+    Bits.FuncDecl.SelfAccess = static_cast<unsigned>(SelfAccessKind::NonMutating);
   }
 
   static FuncDecl *createImpl(ASTContext &Context, SourceLoc StaticLoc,
@@ -5239,16 +5273,16 @@
   Identifier getName() const { return getFullName().getBaseIdentifier(); }
 
   bool isStatic() const {
-    return FuncDeclBits.IsStatic;
+    return Bits.FuncDecl.IsStatic;
   }
   /// \returns the way 'static'/'class' was spelled in the source.
   StaticSpellingKind getStaticSpelling() const {
-    return static_cast<StaticSpellingKind>(FuncDeclBits.StaticSpelling);
+    return static_cast<StaticSpellingKind>(Bits.FuncDecl.StaticSpelling);
   }
   /// \returns the way 'static'/'class' should be spelled for this declaration.
   StaticSpellingKind getCorrectStaticSpelling() const;
   void setStatic(bool IsStatic = true) {
-    FuncDeclBits.IsStatic = IsStatic;
+    Bits.FuncDecl.IsStatic = IsStatic;
   }
       
   bool isMutating() const {
@@ -5266,10 +5300,10 @@
   }
   
   SelfAccessKind getSelfAccessKind() const {
-    return static_cast<SelfAccessKind>(FuncDeclBits.SelfAccess);
+    return static_cast<SelfAccessKind>(Bits.FuncDecl.SelfAccess);
   }
   void setSelfAccessKind(SelfAccessKind mod) {
-    FuncDeclBits.SelfAccess = static_cast<unsigned>(mod);
+    Bits.FuncDecl.SelfAccess = static_cast<unsigned>(mod);
   }
       
   /// \brief Returns the parameter lists(s) for the function definition.
@@ -5377,11 +5411,11 @@
 
   /// Determine whether this function has a dynamic \c Self return
   /// type.
-  bool hasDynamicSelf() const { return FuncDeclBits.HasDynamicSelf; }
+  bool hasDynamicSelf() const { return Bits.FuncDecl.HasDynamicSelf; }
 
   /// Set whether this function has a dynamic \c Self return or not.
   void setDynamicSelf(bool hasDynamicSelf) { 
-    FuncDeclBits.HasDynamicSelf = hasDynamicSelf;
+    Bits.FuncDecl.HasDynamicSelf = hasDynamicSelf;
   }
 
   void getLocalCaptures(SmallVectorImpl<CapturedValue> &Result) const {
@@ -5430,10 +5464,10 @@
   
   /// Returns true if the function is forced to be statically dispatched.
   bool hasForcedStaticDispatch() const {
-    return FuncDeclBits.ForcedStaticDispatch;
+    return Bits.FuncDecl.ForcedStaticDispatch;
   }
   void setForcedStaticDispatch(bool flag) {
-    FuncDeclBits.ForcedStaticDispatch = flag;
+    Bits.FuncDecl.ForcedStaticDispatch = flag;
   }
 
   static bool classof(const Decl *D) { return D->getKind() == DeclKind::Func; }
@@ -5461,15 +5495,13 @@
   friend TrailingObjects;
   SourceLoc CaseLoc;
   
-  /// The number of tail-allocated element pointers.
-  unsigned NumElements;
-  
   EnumCaseDecl(SourceLoc CaseLoc,
                ArrayRef<EnumElementDecl *> Elements,
                DeclContext *DC)
     : Decl(DeclKind::EnumCase, DC),
-      CaseLoc(CaseLoc), NumElements(Elements.size())
+      CaseLoc(CaseLoc)
   {
+    Bits.EnumCaseDecl.NumElements = Elements.size();
     std::uninitialized_copy(Elements.begin(), Elements.end(),
                             getTrailingObjects<EnumElementDecl *>());
   }
@@ -5481,7 +5513,8 @@
   
   /// Get the list of elements declared in this case.
   ArrayRef<EnumElementDecl *> getElements() const {
-    return {getTrailingObjects<EnumElementDecl *>(), NumElements};
+    return {getTrailingObjects<EnumElementDecl *>(),
+            Bits.EnumCaseDecl.NumElements};
   }
   
   SourceLoc getLoc() const {
@@ -5536,9 +5569,9 @@
     EqualsLoc(EqualsLoc),
     RawValueExpr(RawValueExpr)
   {
-    EnumElementDeclBits.Recursiveness =
+    Bits.EnumElementDecl.Recursiveness =
         static_cast<unsigned>(ElementRecursiveness::NotRecursive);
-    EnumElementDeclBits.HasArgumentType = HasArgumentType;
+    Bits.EnumElementDecl.HasArgumentType = HasArgumentType;
   }
 
   Identifier getName() const { return getFullName().getBaseIdentifier(); }
@@ -5584,15 +5617,15 @@
   
   ElementRecursiveness getRecursiveness() const {
     return
-      static_cast<ElementRecursiveness>(EnumElementDeclBits.Recursiveness);
+      static_cast<ElementRecursiveness>(Bits.EnumElementDecl.Recursiveness);
   }
   
   void setRecursiveness(ElementRecursiveness recursiveness) {
-    EnumElementDeclBits.Recursiveness = static_cast<unsigned>(recursiveness);
+    Bits.EnumElementDecl.Recursiveness = static_cast<unsigned>(recursiveness);
   }
 
   bool hasAssociatedValues() const {
-    return EnumElementDeclBits.HasArgumentType;
+    return Bits.EnumElementDecl.HasArgumentType;
   }
 
   static bool classof(const Decl *D) {
@@ -5766,12 +5799,12 @@
 
   /// Determine the kind of initializer this is.
   CtorInitializerKind getInitKind() const {
-    return static_cast<CtorInitializerKind>(ConstructorDeclBits.InitKind);
+    return static_cast<CtorInitializerKind>(Bits.ConstructorDecl.InitKind);
   }
 
   /// Set whether this is a convenience initializer.
   void setInitKind(CtorInitializerKind kind) {
-    ConstructorDeclBits.InitKind = static_cast<unsigned>(kind);
+    Bits.ConstructorDecl.InitKind = static_cast<unsigned>(kind);
   }
 
   /// Whether this is a designated initializer.
@@ -5815,7 +5848,7 @@
 
   /// Determine the failability of the initializer.
   OptionalTypeKind getFailability() const {
-    return static_cast<OptionalTypeKind>(ConstructorDeclBits.Failability);
+    return static_cast<OptionalTypeKind>(Bits.ConstructorDecl.Failability);
   }
 
   /// Retrieve the location of the '!' or '?' in a failable initializer.
@@ -5823,13 +5856,13 @@
 
   /// Whether the implementation of this method is a stub that traps at runtime.
   bool hasStubImplementation() const {
-    return ConstructorDeclBits.HasStubImplementation;
+    return Bits.ConstructorDecl.HasStubImplementation;
   }
 
   /// Set whether the implementation of this method is a stub that
   /// traps at runtime.
   void setStubImplementation(bool stub) {
-    ConstructorDeclBits.HasStubImplementation = stub;
+    Bits.ConstructorDecl.HasStubImplementation = stub;
   }
 
   ConstructorDecl *getOverriddenDecl() const { return OverriddenDecl; }
@@ -6020,7 +6053,7 @@
   }
 
   Associativity getAssociativity() const {
-    return Associativity(PrecedenceGroupDeclBits.Associativity);
+    return Associativity(Bits.PrecedenceGroupDecl.Associativity);
   }
   bool isLeftAssociative() const {
     return getAssociativity() == Associativity::Left;
@@ -6049,7 +6082,7 @@
   }
 
   bool isAssignment() const {
-    return PrecedenceGroupDeclBits.IsAssignment;
+    return Bits.PrecedenceGroupDecl.IsAssignment;
   }
 
   bool isHigherThanImplicit() const {
@@ -6233,9 +6266,9 @@
                     unsigned vtableEntries,
                     unsigned fieldOffsetVectorEntries)
       : Decl(DeclKind::MissingMember, DC), Name(name) {
-    MissingMemberDeclBits.NumberOfVTableEntries = vtableEntries;
+    Bits.MissingMemberDecl.NumberOfVTableEntries = vtableEntries;
     assert(getNumberOfVTableEntries() == vtableEntries && "not enough bits");
-    MissingMemberDeclBits.NumberOfFieldOffsetVectorEntries =
+    Bits.MissingMemberDecl.NumberOfFieldOffsetVectorEntries =
       fieldOffsetVectorEntries;
     assert(getNumberOfFieldOffsetVectorEntries() == fieldOffsetVectorEntries
            && "not enough bits");
@@ -6267,11 +6300,11 @@
   }
 
   unsigned getNumberOfVTableEntries() const {
-    return MissingMemberDeclBits.NumberOfVTableEntries;
+    return Bits.MissingMemberDecl.NumberOfVTableEntries;
   }
 
   unsigned getNumberOfFieldOffsetVectorEntries() const {
-    return MissingMemberDeclBits.NumberOfFieldOffsetVectorEntries;
+    return Bits.MissingMemberDecl.NumberOfFieldOffsetVectorEntries;
   }
 
   SourceLoc getLoc() const {
diff --git a/include/swift/AST/DeclContext.h b/include/swift/AST/DeclContext.h
index 3740f2f..bec8aae 100644
--- a/include/swift/AST/DeclContext.h
+++ b/include/swift/AST/DeclContext.h
@@ -591,7 +591,7 @@
 
 /// The kind of an \c IterableDeclContext.
 enum class IterableDeclContextKind : uint8_t {  
-  NominalTypeDecl,
+  NominalTypeDecl = 0,
   ExtensionDecl,
 };
 
@@ -601,24 +601,28 @@
 /// Note that an iterable declaration context must inherit from both
 /// \c IterableDeclContext and \c DeclContext.
 class IterableDeclContext {
+  enum LazyMembers : unsigned {
+    Present = 1 << 0,
+
+    /// Lazy member loading has a variety of feedback loops that need to
+    /// switch to pseudo-empty-member behaviour to avoid infinite recursion;
+    /// we use this flag to control them.
+    InProgress = 1 << 1,
+  };
+
   /// The first declaration in this context along with a bit indicating whether
   /// the members of this context will be lazily produced.
-  mutable llvm::PointerIntPair<Decl *, 1, bool> FirstDeclAndLazyMembers;
+  mutable llvm::PointerIntPair<Decl *, 2, LazyMembers> FirstDeclAndLazyMembers;
 
   /// The last declaration in this context, used for efficient insertion,
   /// along with the kind of iterable declaration context.
-  mutable llvm::PointerIntPair<Decl *, 2, IterableDeclContextKind> 
+  mutable llvm::PointerIntPair<Decl *, 1, IterableDeclContextKind>
     LastDeclAndKind;
 
   /// The DeclID this IDC was deserialized from, if any. Used for named lazy
   /// member loading, as a key when doing lookup in this IDC.
   serialization::DeclID SerialID;
 
-  /// Lazy member loading has a variety of feedback loops that need to
-  /// switch to pseudo-empty-member behaviour to avoid infinite recursion;
-  /// we use this flag to control them.
-  bool lazyMemberLoadingInProgress = false;
-
   template<class A, class B, class C>
   friend struct ::llvm::cast_convert_val;
 
@@ -650,15 +654,20 @@
 
   /// Check whether there are lazily-loaded members.
   bool hasLazyMembers() const {
-    return FirstDeclAndLazyMembers.getInt();
+    return FirstDeclAndLazyMembers.getInt() & LazyMembers::Present;
   }
 
   bool isLoadingLazyMembers() {
-    return lazyMemberLoadingInProgress;
+    return FirstDeclAndLazyMembers.getInt() & LazyMembers::InProgress;
   }
 
   void setLoadingLazyMembers(bool inProgress) {
-    lazyMemberLoadingInProgress = inProgress;
+    LazyMembers status = FirstDeclAndLazyMembers.getInt();
+    if (inProgress)
+      status = LazyMembers(status | LazyMembers::InProgress);
+    else
+      status = LazyMembers(status & ~LazyMembers::InProgress);
+    FirstDeclAndLazyMembers.setInt(status);
   }
 
   /// Setup the loader for lazily-loaded members.
diff --git a/include/swift/AST/DeclNodes.def b/include/swift/AST/DeclNodes.def
index b5fa511..0d1db7d 100644
--- a/include/swift/AST/DeclNodes.def
+++ b/include/swift/AST/DeclNodes.def
@@ -86,6 +86,10 @@
 #define DECL_RANGE(Id, First, Last)
 #endif
 
+#ifndef LAST_DECL
+#define LAST_DECL(Id)
+#endif
+
 DECL(Import, Decl)
 EXTENSION_DECL(Extension, Decl)
 DECL(PatternBinding, Decl)
@@ -130,6 +134,7 @@
     DECL_RANGE(AbstractFunction, Constructor, Func)
   VALUE_DECL(EnumElement, ValueDecl)
   DECL_RANGE(Value, GenericTypeParam, EnumElement)
+LAST_DECL(EnumElement)
 
 #undef NOMINAL_TYPE_DECL
 #undef VALUE_DECL
@@ -140,3 +145,4 @@
 #undef CONTEXT_VALUE_DECL
 #undef EXTENSION_DECL
 #undef DECL
+#undef LAST_DECL
diff --git a/include/swift/AST/DiagnosticsFrontend.def b/include/swift/AST/DiagnosticsFrontend.def
index 0f65198..796a19b 100644
--- a/include/swift/AST/DiagnosticsFrontend.def
+++ b/include/swift/AST/DiagnosticsFrontend.def
@@ -157,6 +157,12 @@
 ERROR(error_cannot_have_input_files_with_file_list,none,
 "cannot have input files with file list", ())
 
+ERROR(error_cannot_have_primary_files_with_primary_file_list,none,
+"cannot have primary input files with primary file list", ())
+
+ERROR(error_duplicate_input_file,none,
+"duplicate input file '%0'", (StringRef))
+
 ERROR(repl_must_be_initialized,none,
       "variables currently must have an initial value when entered at the "
       "top level of the REPL", ())
diff --git a/include/swift/AST/DiagnosticsSIL.def b/include/swift/AST/DiagnosticsSIL.def
index 5e3e513..01c1274 100644
--- a/include/swift/AST/DiagnosticsSIL.def
+++ b/include/swift/AST/DiagnosticsSIL.def
@@ -244,7 +244,7 @@
         "code after '%select{return|break|continue|throw}0' will never "
         "be executed", (unsigned))
 WARNING(unreachable_case,none,
-        "%select{case|default}0 will never be executed", (bool))
+        "case will never be executed", ())
 WARNING(switch_on_a_constant,none,
         "switch condition evaluates to a constant", ())
 NOTE(unreachable_code_note,none, "will never be executed", ())
diff --git a/include/swift/AST/DiagnosticsSema.def b/include/swift/AST/DiagnosticsSema.def
index a67744d..0f6b040 100644
--- a/include/swift/AST/DiagnosticsSema.def
+++ b/include/swift/AST/DiagnosticsSema.def
@@ -1087,6 +1087,9 @@
       "only methods can be declared %0", (DeclAttribute))
 ERROR(access_control_in_protocol,none,
       "%0 modifier cannot be used in protocols", (DeclAttribute))
+NOTE(access_control_in_protocol_detail,none,
+     "protocol requirements implicitly have the same access as the "
+     "protocol itself", ())
 ERROR(access_control_setter,none,
       "'%select{private|fileprivate|internal|public|open}0(set)' modifier can only "
       "be applied to variables and subscripts",
@@ -1368,9 +1371,6 @@
 ERROR(use_of_equal_instead_of_equality,none,
       "use of '=' in a boolean context, did you mean '=='?", ())
 
-ERROR(experimental_conditional_conformances,none,
-      "conditional conformance of %0 to %1 depends on an experimental feature "
-      "(SE-0143)", (Type, Type))
 
 ERROR(protocol_does_not_conform_objc,none,
       "using %0 as a concrete type conforming to protocol %1 is not supported",
@@ -1795,10 +1795,13 @@
      "potential overridden %0 %1 here",
       (DescriptiveDeclKind, DeclName))
 ERROR(override_decl_extension,none,
-      "overriding declarations %select{in extensions|from extensions}0 "
-      "is not supported", (bool))
+      "overriding %select{|non-@objc }0declarations "
+      "%select{in extensions|from extensions}0 is not supported", (bool, bool))
 NOTE(overridden_here,none,
      "overridden declaration is here", ())
+NOTE(overridden_here_can_be_objc,none,
+     "add '@objc' to make this declaration overridable", ())
+
 ERROR(override_objc_type_mismatch_method,none,
       "overriding method with selector %0 has incompatible type %1",
       (ObjCSelector, Type))
@@ -2507,7 +2510,8 @@
       "missing protocol %0", (Identifier))
 ERROR(nil_literal_broken_proto,none,
       "protocol 'ExpressibleByNilLiteral' is broken", ())
-
+ERROR(array_protocol_broken,none,
+      "ExpressibleByArrayLiteral protocol definition is broken", ())
 ERROR(builtin_integer_literal_broken_proto,none,
       "protocol '_ExpressibleByBuiltinIntegerLiteral' is broken", ())
 ERROR(integer_literal_broken_proto,none,
@@ -2541,10 +2545,9 @@
       "protocol 'ExpressibleByStringLiteral' is broken", ())
 
 // Array literals
-ERROR(array_protocol_broken,none,
-      "ExpressibleByArrayLiteral protocol definition is broken", ())
-ERROR(type_is_not_array,none,
-      "contextual type %0 cannot be used with array literal", (Type))
+ERROR(should_use_dictionary_literal,none,
+      "dictionary of type %0 cannot be %select{used|initialized}1 "
+      "with array literal", (Type, bool))
 NOTE(meant_dictionary_lit,none,
      "did you mean to use a dictionary literal instead?", ())
 ERROR(should_use_empty_dictionary_literal,none,
@@ -3857,6 +3860,11 @@
 NOTE(redundant_particular_literal_case_here,none,
      "first occurrence of identical literal pattern is here", ())
 
+ERROR(cannot_prove_exhaustive_switch,none,
+      "analysis of uncovered switch statement is too complex to perform in a "
+      "reasonable amount of time; "
+      "insert a 'default' clause to cover this switch statement", ())
+
 // HACK: Downgrades the above to warnings if any of the cases is marked
 // @_downgrade_exhaustivity_check.
 WARNING(non_exhaustive_switch_warn_swift3,none, "switch must be exhaustive", ())
diff --git a/include/swift/AST/Expr.h b/include/swift/AST/Expr.h
index f750f5b..fcef79d 100644
--- a/include/swift/AST/Expr.h
+++ b/include/swift/AST/Expr.h
@@ -26,6 +26,7 @@
 #include "swift/AST/TypeLoc.h"
 #include "swift/AST/TypeRepr.h"
 #include "swift/AST/Availability.h"
+#include "swift/Basic/InlineBitfield.h"
 #include "llvm/Support/TrailingObjects.h"
 #include <utility>
 
@@ -59,10 +60,13 @@
 
 enum class ExprKind : uint8_t {
 #define EXPR(Id, Parent) Id,
+#define LAST_EXPR(Id) Last_Expr = Id,
 #define EXPR_RANGE(Id, FirstId, LastId) \
   First_##Id##Expr = FirstId, Last_##Id##Expr = LastId,
 #include "swift/AST/ExprNodes.def"
 };
+enum : unsigned { NumExprKindBits =
+  countBitsUsed(static_cast<unsigned>(ExprKind::Last_Expr)) };
   
 /// Discriminates certain kinds of checked cast that have specialized diagnostic
 /// and/or code generation peephole behavior.
@@ -126,354 +130,294 @@
   Expr(const Expr&) = delete;
   void operator=(const Expr&) = delete;
 
-  class ExprBitfields {
-    friend class Expr;
+  SWIFT_INLINE_BITFIELD_BASE(Expr, bitmax(NumExprKindBits,8)+2+1,
     /// The subclass of Expr that this is.
-    unsigned Kind : 8;
+    Kind : bitmax(NumExprKindBits,8),
     /// How this l-value is used, if it's an l-value.
-    unsigned LValueAccessKind : 2;
+    LValueAccessKind : 2,
     /// Whether the Expr represents something directly written in source or
     /// it was implicitly generated by the type-checker.
-    unsigned Implicit : 1;
-  };
-  enum { NumExprBits = 11 };
-  static_assert(NumExprBits <= 32, "fits in an unsigned");
+    Implicit : 1
+  );
 
-  class LiteralExprBitfields {
-    friend class LiteralExpr;
-    unsigned : NumExprBits;
-  };
-  enum { NumLiteralExprBits = NumExprBits + 0 };
-  static_assert(NumLiteralExprBits <= 32, "fits in an unsigned");
+  SWIFT_INLINE_BITFIELD_FULL(CollectionExpr, Expr, 64-NumExprBits,
+    /// True if the type of this collection expr was inferred by the collection
+    /// fallback type, like [Any].
+    IsTypeDefaulted : 1,
+    /// Number of comma source locations.
+    NumCommas : 32 - 1 - NumExprBits,
+    /// Number of entries in the collection. If this is a DictionaryLiteral,
+    /// each entry is a Tuple with the key and value pair.
+    NumSubExprs : 32
+  );
 
-  class NumberLiteralExprBitfields {
-    friend class NumberLiteralExpr;
-    unsigned : NumLiteralExprBits;
+  SWIFT_INLINE_BITFIELD_EMPTY(LiteralExpr, Expr);
+  SWIFT_INLINE_BITFIELD_EMPTY(IdentityExpr, Expr);
 
-    unsigned IsNegative : 1;
-  };
-  enum { NumNumberLiteralExprBits = NumLiteralExprBits + 1 };
-  static_assert(NumNumberLiteralExprBits <= 32, "fits in an unsigned");
+  SWIFT_INLINE_BITFIELD(ParenExpr, IdentityExpr, 1,
+    /// \brief Whether we're wrapping a trailing closure expression.
+    HasTrailingClosure : 1
+  );
 
-  class StringLiteralExprBitfields {
-    friend class StringLiteralExpr;
-    unsigned : NumLiteralExprBits;
+  SWIFT_INLINE_BITFIELD(NumberLiteralExpr, LiteralExpr, 1,
+    IsNegative : 1
+  );
 
-    unsigned Encoding : 3;
-    unsigned IsSingleUnicodeScalar : 1;
-    unsigned IsSingleExtendedGraphemeCluster : 1;
-  };
-  enum { NumStringLiteralExprBits = NumLiteralExprBits + 4 };
-  static_assert(NumStringLiteralExprBits <= 32, "fits in an unsigned");
+  SWIFT_INLINE_BITFIELD(StringLiteralExpr, LiteralExpr, 3+1+1,
+    Encoding : 3,
+    IsSingleUnicodeScalar : 1,
+    IsSingleExtendedGraphemeCluster : 1
+  );
 
-  class DeclRefExprBitfields {
-    friend class DeclRefExpr;
-    unsigned : NumExprBits;
-    unsigned Semantics : 2; // an AccessSemantics
-    unsigned FunctionRefKind : 2;
-  };
-  enum { NumDeclRefExprBits = NumExprBits + 4 };
-  static_assert(NumDeclRefExprBits <= 32, "fits in an unsigned");
+  SWIFT_INLINE_BITFIELD(DeclRefExpr, Expr, 2+2,
+    Semantics : 2, // an AccessSemantics
+    FunctionRefKind : 2
+  );
 
-  class UnresolvedDeclRefExprBitfields {
-    friend class UnresolvedDeclRefExpr;
-    unsigned : NumExprBits;
-    unsigned DeclRefKind : 2;
-    unsigned FunctionRefKind : 2;
-  };
-  enum { NumUnresolvedDeclRefExprBits = NumExprBits + 4 };
-  static_assert(NumUnresolvedDeclRefExprBits <= 32, "fits in an unsigned");
+  SWIFT_INLINE_BITFIELD(UnresolvedDeclRefExpr, Expr, 2+2,
+    DeclRefKind : 2,
+    FunctionRefKind : 2
+  );
 
-  class MemberRefExprBitfields {
-    friend class MemberRefExpr;
-    unsigned : NumExprBits;
-    unsigned Semantics : 2; // an AccessSemantics
-    unsigned IsSuper : 1;
-  };
-  enum { NumMemberRefExprBits = NumExprBits + 3 };
-  static_assert(NumMemberRefExprBits <= 32, "fits in an unsigned");
+  SWIFT_INLINE_BITFIELD(MemberRefExpr, Expr, 2+1,
+    Semantics : 2, // an AccessSemantics
+    IsSuper : 1
+  );
 
-  class TupleExprBitfields {
-    friend class TupleExpr;
-    unsigned : NumExprBits;
+  SWIFT_INLINE_BITFIELD_FULL(TupleElementExpr, Expr, 32,
+    : NumPadBits,
+    FieldNo : 32
+  );
 
+  SWIFT_INLINE_BITFIELD_FULL(TupleExpr, Expr, 1+1+1+32,
     /// Whether this tuple has a trailing closure.
-    unsigned HasTrailingClosure : 1;
+    HasTrailingClosure : 1,
 
     /// Whether this tuple has any labels.
-    unsigned HasElementNames : 1;
+    HasElementNames : 1,
 
     /// Whether this tuple has label locations.
-    unsigned HasElementNameLocations : 1;
-  };
-  enum { NumTupleExprBits = NumExprBits + 3 };
-  static_assert(NumTupleExprBits <= 32, "fits in an unsigned");
+    HasElementNameLocations : 1,
 
-  class UnresolvedDotExprBitfields {
-    friend class UnresolvedDotExpr;
-    unsigned : NumExprBits;
-    unsigned FunctionRefKind : 2;
-  };
-  enum { NumUnresolvedDotExprExprBits = NumExprBits + 2 };
-  static_assert(NumUnresolvedDotExprExprBits <= 32, "fits in an unsigned");
+    : NumPadBits,
+    NumElements : 32
+  );
 
-  class SubscriptExprBitfields {
-    friend class SubscriptExpr;
-    unsigned : NumExprBits;
-    unsigned Semantics : 2; // an AccessSemantics
-    unsigned IsSuper : 1;
-    /// # of argument labels stored after the SubscriptExpr.
-    unsigned NumArgLabels : 16;
+  SWIFT_INLINE_BITFIELD(UnresolvedDotExpr, Expr, 2,
+    FunctionRefKind : 2
+  );
+
+  SWIFT_INLINE_BITFIELD_FULL(SubscriptExpr, Expr, 2+1+16+1+1,
+    Semantics : 2, // an AccessSemantics
+    IsSuper : 1,
     /// Whether the SubscriptExpr also has source locations for the argument
     /// label.
-    unsigned HasArgLabelLocs : 1;
+    HasArgLabelLocs : 1,
     /// Whether the last argument is a trailing closure.
-    unsigned HasTrailingClosure : 1;
-  };
-  enum { NumSubscriptExprBits = NumExprBits + 21 };
-  static_assert(NumSubscriptExprBits <= 32, "fits in an unsigned");
+    HasTrailingClosure : 1,
+    : NumPadBits,
+    /// # of argument labels stored after the SubscriptExpr.
+    NumArgLabels : 16
+  );
 
-  class DynamicSubscriptExprBitfields {
-    friend class DynamicSubscriptExpr;
-    unsigned : NumExprBits;
-    /// # of argument labels stored after the DynamicSubscriptExpr.
-    unsigned NumArgLabels : 16;
+  SWIFT_INLINE_BITFIELD_FULL(DynamicSubscriptExpr, Expr, 1+1+16,
     /// Whether the DynamicSubscriptExpr also has source locations for the
     /// argument label.
-    unsigned HasArgLabelLocs : 1;
+    HasArgLabelLocs : 1,
     /// Whether the last argument is a trailing closure.
-    unsigned HasTrailingClosure : 1;
-  };
-  enum { NumDynamicSubscriptExprBits = NumExprBits + 18 };
-  static_assert(NumDynamicSubscriptExprBits <= 32, "fits in an unsigned");
+    HasTrailingClosure : 1,
+    : NumPadBits,
+    /// # of argument labels stored after the DynamicSubscriptExpr.
+    NumArgLabels : 16
+  );
 
-  class UnresolvedMemberExprBitfields {
-    friend class UnresolvedMemberExpr;
-    unsigned : NumExprBits;
+  SWIFT_INLINE_BITFIELD_FULL(UnresolvedMemberExpr, Expr, 1+1+1+16,
     /// Whether the UnresolvedMemberExpr has arguments.
-    unsigned HasArguments : 1;
-    /// # of argument labels stored after the UnresolvedMemberExpr.
-    unsigned NumArgLabels : 16;
+    HasArguments : 1,
     /// Whether the UnresolvedMemberExpr also has source locations for the
     /// argument label.
-    unsigned HasArgLabelLocs : 1;
+    HasArgLabelLocs : 1,
     /// Whether the last argument is a trailing closure.
-    unsigned HasTrailingClosure : 1;
-  };
-  enum { NumUnresolvedMemberExprBits = NumExprBits + 19 };
-  static_assert(NumUnresolvedMemberExprBits <= 32, "fits in an unsigned");
+    HasTrailingClosure : 1,
+    : NumPadBits,
+    /// # of argument labels stored after the UnresolvedMemberExpr.
+    NumArgLabels : 16
+  );
 
-  class OverloadSetRefExprBitfields {
-    friend class OverloadSetRefExpr;
-    unsigned : NumExprBits;
-    unsigned FunctionRefKind : 2;
-  };
-  enum { NumOverloadSetRefExprBits = NumExprBits + 2};
-  static_assert(NumOverloadSetRefExprBits <= 32, "fits in an unsigned");
+  SWIFT_INLINE_BITFIELD(OverloadSetRefExpr, Expr, 2,
+    FunctionRefKind : 2
+  );
 
-  class BooleanLiteralExprBitfields {
-    friend class BooleanLiteralExpr;
-    unsigned : NumLiteralExprBits;
+  SWIFT_INLINE_BITFIELD(BooleanLiteralExpr, LiteralExpr, 1,
+    Value : 1
+  );
 
-    unsigned Value : 1;
-  };
-  enum { NumBooleanLiteralExprBits = NumLiteralExprBits + 1 };
-  static_assert(NumBooleanLiteralExprBits <= 32, "fits in an unsigned");
+  SWIFT_INLINE_BITFIELD(MagicIdentifierLiteralExpr, LiteralExpr, 3+1,
+    Kind : 3,
+    StringEncoding : 1
+  );
 
-  class MagicIdentifierLiteralExprBitfields {
-    friend class MagicIdentifierLiteralExpr;
-    unsigned : NumLiteralExprBits;
-
-    unsigned Kind : 3;
-    unsigned StringEncoding : 1;
-  };
-  enum { NumMagicIdentifierLiteralExprBits = NumLiteralExprBits + 4 };
-  static_assert(NumMagicIdentifierLiteralExprBits <= 32, "fits in an unsigned");
-
-  class ObjectLiteralExprBitfields {
-    friend class ObjectLiteralExpr;
-    unsigned : NumLiteralExprBits;
-
-    unsigned LitKind : 3;
-    /// # of argument labels stored after the ObjectLiteralExpr.
-    unsigned NumArgLabels : 16;
+  SWIFT_INLINE_BITFIELD_FULL(ObjectLiteralExpr, LiteralExpr, 3+1+1+16,
+    LitKind : 3,
     /// Whether the ObjectLiteralExpr also has source locations for the argument
     /// label.
-    unsigned HasArgLabelLocs : 1;
+    HasArgLabelLocs : 1,
     /// Whether the last argument is a trailing closure.
-    unsigned HasTrailingClosure : 1;
-  };
-  enum { NumObjectLiteralExprBits = NumLiteralExprBits + 21 };
-  static_assert(NumObjectLiteralExprBits <= 32, "fits in an unsigned");
+    HasTrailingClosure : 1,
+    : NumPadBits,
+    /// # of argument labels stored after the ObjectLiteralExpr.
+    NumArgLabels : 16
+  );
 
-  class AbstractClosureExprBitfields {
-    friend class AbstractClosureExpr;
-    unsigned : NumExprBits;
-    unsigned Discriminator : 16;
+  SWIFT_INLINE_BITFIELD(AbstractClosureExpr, Expr, (16-NumExprBits)+16,
+    : 16 - NumExprBits, // Align and leave room for subclasses
+    Discriminator : 16
+  );
 
-    enum : unsigned {
-      InvalidDiscriminator = 0xFFFF
-    };
-  };
-  enum { NumAbstractClosureExprBits = NumExprBits + 16 };
-  static_assert(NumAbstractClosureExprBits <= 32, "fits in an unsigned");
-
-  class ClosureExprBitfields {
-    friend class ClosureExpr;
-    unsigned : NumAbstractClosureExprBits;
-
+  SWIFT_INLINE_BITFIELD(ClosureExpr, AbstractClosureExpr, 1,
     /// True if closure parameters were synthesized from anonymous closure
     /// variables.
-    unsigned HasAnonymousClosureVars : 1;
-  };
-  enum { NumClosureExprBits = NumAbstractClosureExprBits + 1 };
-  static_assert(NumClosureExprBits <= 32, "fits in an unsigned");
+    HasAnonymousClosureVars : 1
+  );
 
-  class BindOptionalExprBitfields {
-    friend class BindOptionalExpr;
-    unsigned : NumExprBits;
-    unsigned Depth : 16;
-  };
-  enum { NumBindOptionalExprBits = NumExprBits + 16 };
-  static_assert(NumBindOptionalExprBits <= 32, "fits in an unsigned");
+  SWIFT_INLINE_BITFIELD_FULL(BindOptionalExpr, Expr, 16,
+    : NumPadBits,
+    Depth : 16
+  );
 
-  enum { NumImplicitConversionExprBits = NumExprBits };
+  SWIFT_INLINE_BITFIELD_EMPTY(ImplicitConversionExpr, Expr);
 
-  class TupleShuffleExprBitfields {
-    friend class TupleShuffleExpr;
-    unsigned : NumImplicitConversionExprBits;
-    unsigned TypeImpact : 2;
-  };
-  enum { NumTupleShuffleExprBits = NumImplicitConversionExprBits + 2 };
-  static_assert(NumTupleShuffleExprBits <= 32, "fits in an unsigned");
+  SWIFT_INLINE_BITFIELD_FULL(TupleShuffleExpr, ImplicitConversionExpr, 2+16+16+16,
+    TypeImpact : 2,
+    : NumPadBits,
+    NumCallerDefaultArgs : 16,
+    /// This contains an entry for each element in the Expr type.  Each element
+    /// specifies which index from the SubExpr that the destination element gets.
+    /// If the element value is DefaultInitialize, then the destination value
+    /// gets the default initializer for that tuple element value.
+    NumElementMappings : 16,
+    /// The arguments that are packed into the variadic element.
+    NumVariadicArgs : 16
+  );
 
-  class InOutToPointerExprBitfields {
-    friend class InOutToPointerExpr;
-    unsigned : NumImplicitConversionExprBits;
-    unsigned IsNonAccessing : 1;
-  };
-  enum { NumInOutToPointerExprBits = NumImplicitConversionExprBits + 1 };
-  static_assert(NumInOutToPointerExprBits <= 32, "fits in an unsigned");
+  SWIFT_INLINE_BITFIELD(InOutToPointerExpr, ImplicitConversionExpr, 1,
+    IsNonAccessing : 1
+  );
 
-  class ArrayToPointerExprBitfields {
-    friend class ArrayToPointerExpr;
-    unsigned : NumImplicitConversionExprBits;
-    unsigned IsNonAccessing : 1;
-  };
-  enum { NumArrayToPointerExprBits = NumImplicitConversionExprBits + 1 };
-  static_assert(NumArrayToPointerExprBits <= 32, "fits in an unsigned");
+  SWIFT_INLINE_BITFIELD(ArrayToPointerExpr, ImplicitConversionExpr, 1,
+    IsNonAccessing : 1
+  );
 
-  class ApplyExprBitfields {
-    friend class ApplyExpr;
-    unsigned : NumExprBits;
-    unsigned ThrowsIsSet : 1;
-    unsigned Throws : 1;
-  };
-  enum { NumApplyExprBits = NumExprBits + 2 };
-  static_assert(NumApplyExprBits <= 32, "fits in an unsigned");
+  SWIFT_INLINE_BITFIELD_FULL(ErasureExpr, ImplicitConversionExpr, 32,
+    : NumPadBits,
+    NumConformances : 32
+  );
 
-  class CallExprBitfields {
-    friend class CallExpr;
-    unsigned : NumApplyExprBits;
-    /// # of argument labels stored after the CallExpr.
-    unsigned NumArgLabels : 16;
+  SWIFT_INLINE_BITFIELD_FULL(UnresolvedSpecializeExpr, Expr, 32,
+    : NumPadBits,
+    NumUnresolvedParams : 32
+  );
+
+  SWIFT_INLINE_BITFIELD_FULL(CaptureListExpr, Expr, 32,
+    : NumPadBits,
+    NumCaptures : 32
+  );
+
+  SWIFT_INLINE_BITFIELD(ApplyExpr, Expr, 1+1,
+    ThrowsIsSet : 1,
+    Throws : 1
+  );
+
+  SWIFT_INLINE_BITFIELD_FULL(CallExpr, ApplyExpr, 1+1+16,
     /// Whether the CallExpr also has source locations for the argument label.
-    unsigned HasArgLabelLocs : 1;
+    HasArgLabelLocs : 1,
     /// Whether the last argument is a trailing closure.
-    unsigned HasTrailingClosure : 1;
-  };
-  enum { NumCallExprBits = NumApplyExprBits + 18 };
-  static_assert(NumCallExprBits <= 32, "fits in an unsigned");
+    HasTrailingClosure : 1,
+    : NumPadBits,
+    /// # of argument labels stored after the CallExpr.
+    NumArgLabels : 16
+  );
 
   enum { NumCheckedCastKindBits = 4 };
-  class CheckedCastExprBitfields {
-    friend class CheckedCastExpr;
-    unsigned : NumExprBits;
-    unsigned CastKind : NumCheckedCastKindBits;
-  };
-  enum { NumCheckedCastExprBits = NumExprBits + NumCheckedCastKindBits };
-  static_assert(NumCheckedCastExprBits <= 32, "fits in an unsigned");
+  SWIFT_INLINE_BITFIELD(CheckedCastExpr, Expr, NumCheckedCastKindBits,
+    CastKind : NumCheckedCastKindBits
+  );
   static_assert(unsigned(CheckedCastKind::Last_CheckedCastKind)
                   < (1 << NumCheckedCastKindBits),
                 "unable to fit a CheckedCastKind in the given number of bits");
 
-  class CollectionUpcastConversionExprBitfields {
-    friend class CollectionUpcastConversionExpr;
-    unsigned : NumExprBits;
-  };
-  enum { NumCollectionUpcastConversionExprBits = NumExprBits + 0 };
-  static_assert(NumCollectionUpcastConversionExprBits <= 32, "fits in an unsigned");
+  SWIFT_INLINE_BITFIELD_EMPTY(CollectionUpcastConversionExpr, Expr);
 
-  class ObjCSelectorExprBitfields {
-    friend class ObjCSelectorExpr;
-    unsigned : NumExprBits;
-
+  SWIFT_INLINE_BITFIELD(ObjCSelectorExpr, Expr, 2,
     /// The selector kind.
-    unsigned SelectorKind : 2;
-  };
-  enum { NumObjCSelectorExprBits = NumExprBits + 2 };
-  static_assert(NumObjCSelectorExprBits <= 32, "fits in an unsigned");
+    SelectorKind : 2
+  );
 
-  class KeyPathExprBitfields {
-    friend class KeyPathExpr;
-    unsigned : NumExprBits;
-
+  SWIFT_INLINE_BITFIELD(KeyPathExpr, Expr, 1,
     /// Whether this is an ObjC stringified keypath.
-    unsigned IsObjC : 1;
-  };
-  enum { NumKeyPathExprBits = NumExprBits + 2 };
-  static_assert(NumKeyPathExprBits <= 32, "fits in an unsigned");
+    IsObjC : 1
+  );
+
+  SWIFT_INLINE_BITFIELD_FULL(SequenceExpr, Expr, 32,
+    : NumPadBits,
+    NumElements : 32
+  );
 
 protected:
   union {
-    ExprBitfields ExprBits;
-    LiteralExprBitfields LiteralExprBits;
-    NumberLiteralExprBitfields NumberLiteralExprBits;
-    StringLiteralExprBitfields StringLiteralExprBits;
-    DeclRefExprBitfields DeclRefExprBits;
-    UnresolvedDeclRefExprBitfields UnresolvedDeclRefExprBits;
-    TupleExprBitfields TupleExprBits;
-    MemberRefExprBitfields MemberRefExprBits;
-    UnresolvedDotExprBitfields UnresolvedDotExprBits;
-    SubscriptExprBitfields SubscriptExprBits;
-    DynamicSubscriptExprBitfields DynamicSubscriptExprBits;
-    UnresolvedMemberExprBitfields UnresolvedMemberExprBits;
-    OverloadSetRefExprBitfields OverloadSetRefExprBits;
-    BooleanLiteralExprBitfields BooleanLiteralExprBits;
-    MagicIdentifierLiteralExprBitfields MagicIdentifierLiteralExprBits;
-    ObjectLiteralExprBitfields ObjectLiteralExprBits;
-    AbstractClosureExprBitfields AbstractClosureExprBits;
-    ClosureExprBitfields ClosureExprBits;
-    BindOptionalExprBitfields BindOptionalExprBits;
-    ApplyExprBitfields ApplyExprBits;
-    CallExprBitfields CallExprBits;
-    CheckedCastExprBitfields CheckedCastExprBits;
-    CollectionUpcastConversionExprBitfields CollectionUpcastConversionExprBits;
-    TupleShuffleExprBitfields TupleShuffleExprBits;
-    InOutToPointerExprBitfields InOutToPointerExprBits;
-    ArrayToPointerExprBitfields ArrayToPointerExprBits;
-    ObjCSelectorExprBitfields ObjCSelectorExprBits;
-    KeyPathExprBitfields KeyPathExprBits;
-  };
+    SWIFT_INLINE_BITS(Expr);
+    SWIFT_INLINE_BITS(NumberLiteralExpr);
+    SWIFT_INLINE_BITS(StringLiteralExpr);
+    SWIFT_INLINE_BITS(DeclRefExpr);
+    SWIFT_INLINE_BITS(UnresolvedDeclRefExpr);
+    SWIFT_INLINE_BITS(TupleExpr);
+    SWIFT_INLINE_BITS(TupleElementExpr);
+    SWIFT_INLINE_BITS(MemberRefExpr);
+    SWIFT_INLINE_BITS(UnresolvedDotExpr);
+    SWIFT_INLINE_BITS(SubscriptExpr);
+    SWIFT_INLINE_BITS(DynamicSubscriptExpr);
+    SWIFT_INLINE_BITS(UnresolvedMemberExpr);
+    SWIFT_INLINE_BITS(OverloadSetRefExpr);
+    SWIFT_INLINE_BITS(BooleanLiteralExpr);
+    SWIFT_INLINE_BITS(MagicIdentifierLiteralExpr);
+    SWIFT_INLINE_BITS(ObjectLiteralExpr);
+    SWIFT_INLINE_BITS(AbstractClosureExpr);
+    SWIFT_INLINE_BITS(ClosureExpr);
+    SWIFT_INLINE_BITS(BindOptionalExpr);
+    SWIFT_INLINE_BITS(ApplyExpr);
+    SWIFT_INLINE_BITS(CallExpr);
+    SWIFT_INLINE_BITS(CheckedCastExpr);
+    SWIFT_INLINE_BITS(TupleShuffleExpr);
+    SWIFT_INLINE_BITS(InOutToPointerExpr);
+    SWIFT_INLINE_BITS(ArrayToPointerExpr);
+    SWIFT_INLINE_BITS(ObjCSelectorExpr);
+    SWIFT_INLINE_BITS(KeyPathExpr);
+    SWIFT_INLINE_BITS(ParenExpr);
+    SWIFT_INLINE_BITS(SequenceExpr);
+    SWIFT_INLINE_BITS(CollectionExpr);
+    SWIFT_INLINE_BITS(ErasureExpr);
+    SWIFT_INLINE_BITS(UnresolvedSpecializeExpr);
+    SWIFT_INLINE_BITS(CaptureListExpr);
+  } Bits;
 
 private:
   /// Ty - This is the type of the expression.
   Type Ty;
 
   void setLValueAccessKind(AccessKind accessKind) {
-    ExprBits.LValueAccessKind = unsigned(accessKind) + 1;
+    Bits.Expr.LValueAccessKind = unsigned(accessKind) + 1;
   }
  
 protected:
   Expr(ExprKind Kind, bool Implicit, Type Ty = Type()) : Ty(Ty) {
-    ExprBits.Kind = unsigned(Kind);
-    ExprBits.Implicit = Implicit;
-    ExprBits.LValueAccessKind = 0;
+    Bits.Expr.Kind = unsigned(Kind);
+    Bits.Expr.Implicit = Implicit;
+    Bits.Expr.LValueAccessKind = 0;
   }
 
 public:
   /// Return the kind of this expression.
-  ExprKind getKind() const { return ExprKind(ExprBits.Kind); }
+  ExprKind getKind() const { return ExprKind(Bits.Expr.Kind); }
 
   /// \brief Retrieve the name of the given expression kind.
   ///
@@ -570,22 +514,22 @@
   /// isImplicit - Determines whether this expression was implicitly-generated,
   /// rather than explicitly written in the AST.
   bool isImplicit() const {
-    return ExprBits.Implicit;
+    return Bits.Expr.Implicit;
   }
   void setImplicit(bool Implicit = true) {
-    ExprBits.Implicit = Implicit;
+    Bits.Expr.Implicit = Implicit;
   }
 
   /// getLValueAccessKind - Determines how this l-value expression is used.
   AccessKind getLValueAccessKind() const {
     assert(hasLValueAccessKind());
-    return AccessKind(ExprBits.LValueAccessKind - 1);
+    return AccessKind(Bits.Expr.LValueAccessKind - 1);
   }
   bool hasLValueAccessKind() const {
-    return ExprBits.LValueAccessKind != 0;
+    return Bits.Expr.LValueAccessKind != 0;
   }
   void clearLValueAccessKind() {
-    ExprBits.LValueAccessKind = 0;
+    Bits.Expr.LValueAccessKind = 0;
   }
 
   /// Set that this l-value expression is used in the given way.
@@ -848,13 +792,13 @@
                      StringRef Val, SourceLoc DigitsLoc, bool Implicit)
        : LiteralExpr(Kind, Implicit), Val(Val), DigitsLoc(DigitsLoc)
    {
-     NumberLiteralExprBits.IsNegative = false;
+     Bits.NumberLiteralExpr.IsNegative = false;
    }
   
-  bool isNegative() const { return NumberLiteralExprBits.IsNegative; }
+  bool isNegative() const { return Bits.NumberLiteralExpr.IsNegative; }
   void setNegative(SourceLoc Loc) {
     MinusLoc = Loc;
-    NumberLiteralExprBits.IsNegative = true;
+    Bits.NumberLiteralExpr.IsNegative = true;
   }
 
   StringRef getDigitsText() const { return Val; }
@@ -926,11 +870,11 @@
 public:
   BooleanLiteralExpr(bool Value, SourceLoc Loc, bool Implicit = false)
     : LiteralExpr(ExprKind::BooleanLiteral, Implicit), Loc(Loc) {
-    BooleanLiteralExprBits.Value = Value;
+    Bits.BooleanLiteralExpr.Value = Value;
   }
 
   /// Retrieve the Boolean value of this literal.
-  bool getValue() const { return BooleanLiteralExprBits.Value; }
+  bool getValue() const { return Bits.BooleanLiteralExpr.Value; }
 
   SourceRange getSourceRange() const {
     return Loc;
@@ -974,20 +918,20 @@
 
   /// Determine the encoding that should be used for this string literal.
   Encoding getEncoding() const {
-    return static_cast<Encoding>(StringLiteralExprBits.Encoding);
+    return static_cast<Encoding>(Bits.StringLiteralExpr.Encoding);
   }
 
   /// Set the encoding that should be used for this string literal.
   void setEncoding(Encoding encoding) {
-    StringLiteralExprBits.Encoding = static_cast<unsigned>(encoding);
+    Bits.StringLiteralExpr.Encoding = static_cast<unsigned>(encoding);
   }
 
   bool isSingleUnicodeScalar() const {
-    return StringLiteralExprBits.IsSingleUnicodeScalar;
+    return Bits.StringLiteralExpr.IsSingleUnicodeScalar;
   }
 
   bool isSingleExtendedGraphemeCluster() const {
-    return StringLiteralExprBits.IsSingleExtendedGraphemeCluster;
+    return Bits.StringLiteralExpr.IsSingleExtendedGraphemeCluster;
   }
 
   /// Retrieve the builtin initializer that will be used to construct the string
@@ -1077,13 +1021,13 @@
 public:
   MagicIdentifierLiteralExpr(Kind kind, SourceLoc loc, bool implicit = false)
     : LiteralExpr(ExprKind::MagicIdentifierLiteral, implicit), Loc(loc) {
-    MagicIdentifierLiteralExprBits.Kind = static_cast<unsigned>(kind);
-    MagicIdentifierLiteralExprBits.StringEncoding
+    Bits.MagicIdentifierLiteralExpr.Kind = static_cast<unsigned>(kind);
+    Bits.MagicIdentifierLiteralExpr.StringEncoding
       = static_cast<unsigned>(StringLiteralExpr::UTF8);
   }
   
   Kind getKind() const {
-    return static_cast<Kind>(MagicIdentifierLiteralExprBits.Kind);
+    return static_cast<Kind>(Bits.MagicIdentifierLiteralExpr.Kind);
   }
 
   bool isFile() const { return getKind() == File; }
@@ -1111,14 +1055,14 @@
   StringLiteralExpr::Encoding getStringEncoding() const {
     assert(isString() && "Magic identifier literal has non-string encoding");
     return static_cast<StringLiteralExpr::Encoding>(
-             MagicIdentifierLiteralExprBits.StringEncoding);
+             Bits.MagicIdentifierLiteralExpr.StringEncoding);
   }
 
   // For a magic identifier that produces a string literal, set the encoding
   // for the string literal.
   void setStringEncoding(StringLiteralExpr::Encoding encoding) {
     assert(isString() && "Magic identifier literal has non-string encoding");
-    MagicIdentifierLiteralExprBits.StringEncoding
+    Bits.MagicIdentifierLiteralExpr.StringEncoding
       = static_cast<unsigned>(encoding);
   }
 
@@ -1208,22 +1152,22 @@
                                    bool implicit);
 
   LiteralKind getLiteralKind() const {
-    return static_cast<LiteralKind>(ObjectLiteralExprBits.LitKind);
+    return static_cast<LiteralKind>(Bits.ObjectLiteralExpr.LitKind);
   }
 
   Expr *getArg() const { return Arg; }
   void setArg(Expr *arg) { Arg = arg; }
 
   unsigned getNumArguments() const {
-    return ObjectLiteralExprBits.NumArgLabels;
+    return Bits.ObjectLiteralExpr.NumArgLabels;
   }
   bool hasArgumentLabelLocs() const {
-    return ObjectLiteralExprBits.HasArgLabelLocs;
+    return Bits.ObjectLiteralExpr.HasArgLabelLocs;
   }
 
   /// Whether this call with written with a trailing closure.
   bool hasTrailingClosure() const {
-    return ObjectLiteralExprBits.HasTrailingClosure;
+    return Bits.ObjectLiteralExpr.HasTrailingClosure;
   }
 
   Expr *getSemanticExpr() const { return SemanticExpr; }
@@ -1272,8 +1216,8 @@
               AccessSemantics semantics = AccessSemantics::Ordinary,
               Type Ty = Type())
     : Expr(ExprKind::DeclRef, Implicit, Ty), D(D), Loc(Loc) {
-    DeclRefExprBits.Semantics = (unsigned) semantics;
-    DeclRefExprBits.FunctionRefKind =
+    Bits.DeclRefExpr.Semantics = (unsigned) semantics;
+    Bits.DeclRefExpr.FunctionRefKind =
       static_cast<unsigned>(Loc.isCompound() ? FunctionRefKind::Compound
                                              : FunctionRefKind::Unapplied);
   }
@@ -1286,7 +1230,7 @@
   /// Return true if this access is direct, meaning that it does not call the
   /// getter or setter.
   AccessSemantics getAccessSemantics() const {
-    return (AccessSemantics) DeclRefExprBits.Semantics;
+    return (AccessSemantics) Bits.DeclRefExpr.Semantics;
   }
 
   /// Retrieve the concrete declaration reference.
@@ -1300,12 +1244,12 @@
 
   /// Retrieve the kind of function reference.
   FunctionRefKind getFunctionRefKind() const {
-    return static_cast<FunctionRefKind>(DeclRefExprBits.FunctionRefKind);
+    return static_cast<FunctionRefKind>(Bits.DeclRefExpr.FunctionRefKind);
   }
 
   /// Set the kind of function reference.
   void setFunctionRefKind(FunctionRefKind refKind) {
-    DeclRefExprBits.FunctionRefKind = static_cast<unsigned>(refKind);
+    Bits.DeclRefExpr.FunctionRefKind = static_cast<unsigned>(refKind);
   }
 
   static bool classof(const Expr *E) {
@@ -1446,7 +1390,7 @@
   OverloadSetRefExpr(ExprKind Kind, ArrayRef<ValueDecl*> decls,
                      FunctionRefKind functionRefKind, bool Implicit, Type Ty)
       : Expr(Kind, Implicit, Ty), Decls(decls) {
-    OverloadSetRefExprBits.FunctionRefKind =
+    Bits.OverloadSetRefExpr.FunctionRefKind =
       static_cast<unsigned>(functionRefKind);
   }
 
@@ -1469,12 +1413,12 @@
   /// Retrieve the kind of function reference.
   FunctionRefKind getFunctionRefKind() const {
     return static_cast<FunctionRefKind>(
-             OverloadSetRefExprBits.FunctionRefKind);
+             Bits.OverloadSetRefExpr.FunctionRefKind);
   }
 
   /// Set the kind of function reference.
   void setFunctionRefKind(FunctionRefKind refKind) {
-    OverloadSetRefExprBits.FunctionRefKind = static_cast<unsigned>(refKind);
+    Bits.OverloadSetRefExpr.FunctionRefKind = static_cast<unsigned>(refKind);
   }
 
   static bool classof(const Expr *E) {
@@ -1519,8 +1463,8 @@
   UnresolvedDeclRefExpr(DeclName name, DeclRefKind refKind, DeclNameLoc loc)
       : Expr(ExprKind::UnresolvedDeclRef, /*Implicit=*/loc.isInvalid()),
         Name(name), Loc(loc) {
-    UnresolvedDeclRefExprBits.DeclRefKind = static_cast<unsigned>(refKind);
-    UnresolvedDeclRefExprBits.FunctionRefKind =
+    Bits.UnresolvedDeclRefExpr.DeclRefKind = static_cast<unsigned>(refKind);
+    Bits.UnresolvedDeclRefExpr.FunctionRefKind =
       static_cast<unsigned>(Loc.isCompound() ? FunctionRefKind::Compound
                                              : FunctionRefKind::Unapplied);
   }
@@ -1529,18 +1473,18 @@
   DeclName getName() const { return Name; }
 
   DeclRefKind getRefKind() const {
-    return static_cast<DeclRefKind>(UnresolvedDeclRefExprBits.DeclRefKind);
+    return static_cast<DeclRefKind>(Bits.UnresolvedDeclRefExpr.DeclRefKind);
   }
 
   /// Retrieve the kind of function reference.
   FunctionRefKind getFunctionRefKind() const {
     return static_cast<FunctionRefKind>(
-             UnresolvedDeclRefExprBits.FunctionRefKind);
+             Bits.UnresolvedDeclRefExpr.FunctionRefKind);
   }
 
   /// Set the kind of function reference.
   void setFunctionRefKind(FunctionRefKind refKind) {
-    UnresolvedDeclRefExprBits.FunctionRefKind = static_cast<unsigned>(refKind);
+    Bits.UnresolvedDeclRefExpr.FunctionRefKind = static_cast<unsigned>(refKind);
   }
 
   DeclNameLoc getNameLoc() const { return Loc; }
@@ -1578,16 +1522,16 @@
   /// Return true if this member access is direct, meaning that it
   /// does not call the getter or setter.
   AccessSemantics getAccessSemantics() const {
-    return (AccessSemantics) MemberRefExprBits.Semantics;
+    return (AccessSemantics) Bits.MemberRefExpr.Semantics;
   }
 
   /// Determine whether this member reference refers to the
   /// superclass's property.
-  bool isSuper() const { return MemberRefExprBits.IsSuper; }
+  bool isSuper() const { return Bits.MemberRefExpr.IsSuper; }
 
   /// Set whether this member reference refers to the superclass's
   /// property.
-  void setIsSuper(bool isSuper) { MemberRefExprBits.IsSuper = isSuper; }
+  void setIsSuper(bool isSuper) { Bits.MemberRefExpr.IsSuper = isSuper; }
 
   SourceLoc getLoc() const { return NameLoc.getBaseNameLoc(); }
   SourceLoc getStartLoc() const {
@@ -1750,16 +1694,16 @@
   void setIndex(Expr *E) { Index = E; }
 
   unsigned getNumArguments() const {
-    return DynamicSubscriptExprBits.NumArgLabels;
+    return Bits.DynamicSubscriptExpr.NumArgLabels;
   }
 
   bool hasArgumentLabelLocs() const {
-    return DynamicSubscriptExprBits.HasArgLabelLocs;
+    return Bits.DynamicSubscriptExpr.HasArgLabelLocs;
   }
 
   /// Whether this call with written with a trailing closure.
   bool hasTrailingClosure() const {
-    return DynamicSubscriptExprBits.HasTrailingClosure;
+    return Bits.DynamicSubscriptExpr.HasTrailingClosure;
   }
 
   SourceLoc getLoc() const { return Index->getStartLoc(); }
@@ -1815,20 +1759,20 @@
 
   /// Whether this reference has arguments.
   bool hasArguments() const {
-    return UnresolvedMemberExprBits.HasArguments;
+    return Bits.UnresolvedMemberExpr.HasArguments;
   }
 
   unsigned getNumArguments() const {
-    return UnresolvedMemberExprBits.NumArgLabels;
+    return Bits.UnresolvedMemberExpr.NumArgLabels;
   }
 
   bool hasArgumentLabelLocs() const {
-    return UnresolvedMemberExprBits.HasArgLabelLocs;
+    return Bits.UnresolvedMemberExpr.HasArgLabelLocs;
   }
 
   /// Whether this call with written with a trailing closure.
   bool hasTrailingClosure() const {
-    return UnresolvedMemberExprBits.HasTrailingClosure;
+    return Bits.UnresolvedMemberExpr.HasTrailingClosure;
   }
 
   SourceLoc getLoc() const { return NameLoc.getBaseNameLoc(); }
@@ -1980,17 +1924,13 @@
 class ParenExpr : public IdentityExpr {
   SourceLoc LParenLoc, RParenLoc;
   
-  /// \brief Whether we're wrapping a trailing closure expression.
-  /// FIXME: Pack bit into superclass.
-  bool HasTrailingClosure;
-
 public:
   ParenExpr(SourceLoc lploc, Expr *subExpr, SourceLoc rploc,
             bool hasTrailingClosure,
             Type ty = Type())
     : IdentityExpr(ExprKind::Paren, subExpr, ty),
-      LParenLoc(lploc), RParenLoc(rploc),
-      HasTrailingClosure(hasTrailingClosure) {
+      LParenLoc(lploc), RParenLoc(rploc) {
+    Bits.ParenExpr.HasTrailingClosure = hasTrailingClosure;
     assert(lploc.isValid() == rploc.isValid() &&
            "Mismatched source location information");
   }
@@ -2008,13 +1948,13 @@
   SourceLoc getEndLoc() const {
     // If we have a trailing closure, our end point is the end of the
     // trailing closure.
-    if (RParenLoc.isInvalid() || HasTrailingClosure)
+    if (RParenLoc.isInvalid() || Bits.ParenExpr.HasTrailingClosure)
       return getSubExpr()->getEndLoc();
     return RParenLoc;
   }
 
   /// \brief Whether this expression has a trailing closure as its argument.
-  bool hasTrailingClosure() const { return HasTrailingClosure; }
+  bool hasTrailingClosure() const { return Bits.ParenExpr.HasTrailingClosure; }
 
   static bool classof(const Expr *E) { return E->getKind() == ExprKind::Paren; }
 };
@@ -2028,7 +1968,6 @@
 
   SourceLoc LParenLoc;
   SourceLoc RParenLoc;
-  unsigned NumElements;
 
   size_t numTrailingObjects(OverloadToken<Expr *>) const {
     return getNumElements();
@@ -2086,7 +2025,7 @@
   SourceRange getSourceRange() const;
 
   /// \brief Whether this expression has a trailing closure as its argument.
-  bool hasTrailingClosure() const { return TupleExprBits.HasTrailingClosure; }
+  bool hasTrailingClosure() const { return Bits.TupleExpr.HasTrailingClosure; }
 
   /// Retrieve the elements of this tuple.
   MutableArrayRef<Expr*> getElements() {
@@ -2098,7 +2037,7 @@
     return { getTrailingObjects<Expr *>(), getNumElements() };
   }
   
-  unsigned getNumElements() const { return NumElements; }
+  unsigned getNumElements() const { return Bits.TupleExpr.NumElements; }
   
   Expr *getElement(unsigned i) const {
     return getElements()[i];
@@ -2109,7 +2048,7 @@
 
   /// Whether this tuple has element names.
   bool hasElementNames() const { 
-    return TupleExprBits.HasElementNames;
+    return Bits.TupleExpr.HasElementNames;
   }
 
   /// Retrieve the element names for a tuple.
@@ -2124,7 +2063,7 @@
   
   /// Whether this tuple has element name locations.
   bool hasElementNameLocs() const { 
-    return TupleExprBits.HasElementNameLocations;
+    return Bits.TupleExpr.HasElementNameLocations;
   }
 
   /// Retrieve the locations of the element names for a tuple.
@@ -2152,36 +2091,66 @@
   SourceLoc LBracketLoc;
   SourceLoc RBracketLoc;
 
-  /// ASTContext allocated element lists.  Each entry is one entry of the
-  /// collection.  If this is a DictionaryLiteral, each entry is a Tuple with
-  /// the key and value pair.
-  MutableArrayRef<Expr*> Elements;
-
   Expr *SemanticExpr = nullptr;
 
-  /// True if the type of this collection expr was inferred by the collection
-  /// fallback type, like [Any].
-  bool IsTypeDefaulted = false;
+  /// Retrieve the intrusive pointer storage from the subtype
+  Expr *const *getTrailingObjectsPointer() const;
+  Expr **getTrailingObjectsPointer() {
+    const CollectionExpr *temp = this;
+    return const_cast<Expr**>(temp->getTrailingObjectsPointer());
+  }
+
+  /// Retrieve the intrusive pointer storage from the subtype
+  const SourceLoc *getTrailingSourceLocs() const;
+  SourceLoc *getTrailingSourceLocs() {
+    const CollectionExpr *temp = this;
+    return const_cast<SourceLoc*>(temp->getTrailingSourceLocs());
+  }
 
 protected:
   CollectionExpr(ExprKind Kind, SourceLoc LBracketLoc,
-                 MutableArrayRef<Expr*> Elements,
+                 ArrayRef<Expr*> Elements, ArrayRef<SourceLoc> CommaLocs,
                  SourceLoc RBracketLoc, Type Ty)
     : Expr(Kind, /*Implicit=*/false, Ty),
-      LBracketLoc(LBracketLoc), RBracketLoc(RBracketLoc),
-      Elements(Elements) { }
+      LBracketLoc(LBracketLoc), RBracketLoc(RBracketLoc) {
+    Bits.CollectionExpr.IsTypeDefaulted = false;
+    Bits.CollectionExpr.NumSubExprs = Elements.size();
+    Bits.CollectionExpr.NumCommas = CommaLocs.size();
+    assert(Bits.CollectionExpr.NumCommas == CommaLocs.size() && "Truncation");
+    std::uninitialized_copy(Elements.begin(), Elements.end(),
+                            getTrailingObjectsPointer());
+    std::uninitialized_copy(CommaLocs.begin(), CommaLocs.end(),
+                            getTrailingSourceLocs());
+  }
 
 public:
 
   /// Retrieve the elements stored in the collection.
-  ArrayRef<Expr *> getElements() const { return Elements; }
-  MutableArrayRef<Expr *> getElements() { return Elements; }
-  Expr *getElement(unsigned i) const { return Elements[i]; }
-  void setElement(unsigned i, Expr *E) { Elements[i] = E; }
-  unsigned getNumElements() const { return Elements.size(); }
+  ArrayRef<Expr *> getElements() const {
+    return {getTrailingObjectsPointer(), Bits.CollectionExpr.NumSubExprs};
+  }
+  MutableArrayRef<Expr *> getElements() {
+    return {getTrailingObjectsPointer(), Bits.CollectionExpr.NumSubExprs};
+  }
+  Expr *getElement(unsigned i) const { return getElements()[i]; }
+  void setElement(unsigned i, Expr *E) { getElements()[i] = E; }
+  unsigned getNumElements() const { return Bits.CollectionExpr.NumSubExprs; }
 
-  bool isTypeDefaulted() const { return IsTypeDefaulted; }
-  void setIsTypeDefaulted(bool value = true) { IsTypeDefaulted = value; }
+  /// Retrieve the comma source locations stored in the collection. Please note
+  /// that trailing commas are currently allowed, and that invalid code may have
+  /// stray or missing commas.
+  MutableArrayRef<SourceLoc> getCommaLocs() {
+    return {getTrailingSourceLocs(), Bits.CollectionExpr.NumCommas};
+  }
+  ArrayRef<SourceLoc> getCommaLocs() const {
+    return {getTrailingSourceLocs(), Bits.CollectionExpr.NumCommas};
+  }
+  unsigned getNumCommas() const { return Bits.CollectionExpr.NumCommas; }
+
+  bool isTypeDefaulted() const { return Bits.CollectionExpr.IsTypeDefaulted; }
+  void setIsTypeDefaulted(bool value = true) {
+    Bits.CollectionExpr.IsTypeDefaulted = value;
+  }
 
   SourceLoc getLBracketLoc() const { return LBracketLoc; }
   SourceLoc getRBracketLoc() const { return RBracketLoc; }
@@ -2200,16 +2169,23 @@
 };
  
 /// \brief An array literal expression [a, b, c].
-class ArrayExpr : public CollectionExpr {
-  /// ASTContext allocated list of comma locations, there is one less entry here
-  /// than the number of elements.
-  MutableArrayRef<SourceLoc> CommaLocs;
+class ArrayExpr final : public CollectionExpr,
+    private llvm::TrailingObjects<ArrayExpr, Expr*, SourceLoc> {
+  friend TrailingObjects;
+  friend CollectionExpr;
 
-  ArrayExpr(SourceLoc LBracketLoc, MutableArrayRef<Expr*> Elements,
-            MutableArrayRef<SourceLoc> CommaLocs,
+  size_t numTrailingObjects(OverloadToken<Expr *>) const {
+    return getNumElements();
+  }
+  size_t numTrailingObjects(OverloadToken<SourceLoc>) const {
+    return getNumCommas();
+  }
+
+  ArrayExpr(SourceLoc LBracketLoc, ArrayRef<Expr*> Elements,
+            ArrayRef<SourceLoc> CommaLocs,
             SourceLoc RBracketLoc, Type Ty)
-  : CollectionExpr(ExprKind::Array, LBracketLoc, Elements, RBracketLoc, Ty),
-    CommaLocs(CommaLocs) {}
+  : CollectionExpr(ExprKind::Array, LBracketLoc, Elements, CommaLocs,
+                   RBracketLoc, Ty) { }
 public:
   static ArrayExpr *create(ASTContext &C, SourceLoc LBracketLoc,
                            ArrayRef<Expr*> Elements,
@@ -2217,29 +2193,37 @@
                            SourceLoc RBracketLoc,
                            Type Ty = Type());
 
-  /// ASTContext allocated list of comma locations, there is one less entry here
-  /// than the number of elements.
-  MutableArrayRef<SourceLoc> getCommaLocs() { return CommaLocs; }
-  ArrayRef<SourceLoc> getCommaLocs() const { return CommaLocs; }
-
   static bool classof(const Expr *e) {
     return e->getKind() == ExprKind::Array;
   }
 };
 
 /// \brief A dictionary literal expression [a : x, b : y, c : z].
-class DictionaryExpr : public CollectionExpr {
-  DictionaryExpr(SourceLoc LBracketLoc, MutableArrayRef<Expr*> Elements,
+class DictionaryExpr final : public CollectionExpr,
+    private llvm::TrailingObjects<DictionaryExpr, Expr*, SourceLoc> {
+  friend TrailingObjects;
+  friend CollectionExpr;
+
+  size_t numTrailingObjects(OverloadToken<Expr *>) const {
+    return getNumElements();
+  }
+  size_t numTrailingObjects(OverloadToken<SourceLoc>) const {
+    return getNumCommas();
+  }
+
+  DictionaryExpr(SourceLoc LBracketLoc, ArrayRef<Expr*> Elements,
+                 ArrayRef<SourceLoc> CommaLocs,
                  SourceLoc RBracketLoc, Type Ty)
-    : CollectionExpr(ExprKind::Dictionary, LBracketLoc, Elements, RBracketLoc,
-                     Ty) { }
+    : CollectionExpr(ExprKind::Dictionary, LBracketLoc, Elements, CommaLocs,
+                     RBracketLoc, Ty) { }
 public:
 
   static DictionaryExpr *create(ASTContext &C, SourceLoc LBracketLoc,
-                                ArrayRef<Expr*> Elements, SourceLoc RBracketLoc,
+                                ArrayRef<Expr*> Elements,
+                                ArrayRef<SourceLoc> CommaLocs,
+                                SourceLoc RBracketLoc,
                                 Type Ty = Type());
 
-
   static bool classof(const Expr *e) {
     return e->getKind() == ExprKind::Dictionary;
   }
@@ -2300,31 +2284,31 @@
   void setIndex(Expr *E) { Index = E; }
 
   unsigned getNumArguments() const {
-    return SubscriptExprBits.NumArgLabels;
+    return Bits.SubscriptExpr.NumArgLabels;
   }
 
   bool hasArgumentLabelLocs() const {
-    return SubscriptExprBits.HasArgLabelLocs;
+    return Bits.SubscriptExpr.HasArgLabelLocs;
   }
 
   /// Whether this call with written with a trailing closure.
   bool hasTrailingClosure() const {
-    return SubscriptExprBits.HasTrailingClosure;
+    return Bits.SubscriptExpr.HasTrailingClosure;
   }
 
   /// Determine whether this subscript reference should bypass the
   /// ordinary accessors.
   AccessSemantics getAccessSemantics() const {
-    return (AccessSemantics) SubscriptExprBits.Semantics;
+    return (AccessSemantics) Bits.SubscriptExpr.Semantics;
   }
   
   /// Determine whether this member reference refers to the
   /// superclass's property.
-  bool isSuper() const { return SubscriptExprBits.IsSuper; }
+  bool isSuper() const { return Bits.SubscriptExpr.IsSuper; }
 
   /// Set whether this member reference refers to the superclass's
   /// property.
-  void setIsSuper(bool isSuper) { SubscriptExprBits.IsSuper = isSuper; }
+  void setIsSuper(bool isSuper) { Bits.SubscriptExpr.IsSuper = isSuper; }
 
   /// Determine whether subscript operation has a known underlying
   /// subscript declaration or not.
@@ -2387,7 +2371,7 @@
                     DeclNameLoc nameloc, bool Implicit)
     : Expr(ExprKind::UnresolvedDot, Implicit), SubExpr(subexpr), DotLoc(dotloc),
       NameLoc(nameloc), Name(name) {
-    UnresolvedDotExprBits.FunctionRefKind =
+    Bits.UnresolvedDotExpr.FunctionRefKind =
       static_cast<unsigned>(NameLoc.isCompound() ? FunctionRefKind::Compound
                                                  : FunctionRefKind::Unapplied);
   }
@@ -2411,12 +2395,12 @@
 
   /// Retrieve the kind of function reference.
   FunctionRefKind getFunctionRefKind() const {
-    return static_cast<FunctionRefKind>(UnresolvedDotExprBits.FunctionRefKind);
+    return static_cast<FunctionRefKind>(Bits.UnresolvedDotExpr.FunctionRefKind);
   }
 
   /// Set the kind of function reference.
   void setFunctionRefKind(FunctionRefKind refKind) {
-    UnresolvedDotExprBits.FunctionRefKind = static_cast<unsigned>(refKind);
+    Bits.UnresolvedDotExpr.FunctionRefKind = static_cast<unsigned>(refKind);
   }
 
   static bool classof(const Expr *E) {
@@ -2429,20 +2413,21 @@
 class TupleElementExpr : public Expr {
   Expr *SubExpr;
   SourceLoc NameLoc;
-  unsigned FieldNo;
   SourceLoc DotLoc;
 
 public:
   TupleElementExpr(Expr *SubExpr, SourceLoc DotLoc, unsigned FieldNo,
                    SourceLoc NameLoc, Type Ty)
     : Expr(ExprKind::TupleElement, /*Implicit=*/false, Ty), SubExpr(SubExpr),
-      NameLoc(NameLoc), FieldNo(FieldNo), DotLoc(DotLoc) {}
+      NameLoc(NameLoc), DotLoc(DotLoc) {
+    Bits.TupleElementExpr.FieldNo = FieldNo;
+  }
 
   SourceLoc getLoc() const { return NameLoc; }
   Expr *getBase() const { return SubExpr; }
   void setBase(Expr *e) { SubExpr = e; }
 
-  unsigned getFieldNumber() const { return FieldNo; }
+  unsigned getFieldNumber() const { return Bits.TupleElementExpr.FieldNo; }
   SourceLoc getNameLoc() const { return NameLoc; }  
   SourceLoc getDotLoc() const { return DotLoc; }
   
@@ -2477,8 +2462,8 @@
                    unsigned depth, Type ty = Type())
     : Expr(ExprKind::BindOptional, /*Implicit=*/ questionLoc.isInvalid(), ty),
       SubExpr(subExpr), QuestionLoc(questionLoc) {
-    BindOptionalExprBits.Depth = depth;
-    assert(BindOptionalExprBits.Depth == depth && "bitfield truncation");
+    Bits.BindOptionalExpr.Depth = depth;
+    assert(Bits.BindOptionalExpr.Depth == depth && "bitfield truncation");
   }
 
   SourceRange getSourceRange() const {
@@ -2500,9 +2485,9 @@
   }
   SourceLoc getQuestionLoc() const { return QuestionLoc; }
 
-  unsigned getDepth() const { return BindOptionalExprBits.Depth; }
+  unsigned getDepth() const { return Bits.BindOptionalExpr.Depth; }
   void setDepth(unsigned depth) {
-    BindOptionalExprBits.Depth = depth;
+    Bits.BindOptionalExpr.Depth = depth;
   }
 
   Expr *getSubExpr() const { return SubExpr; }
@@ -2777,16 +2762,16 @@
 public:
   InOutToPointerExpr(Expr *subExpr, Type ty)
       : ImplicitConversionExpr(ExprKind::InOutToPointer, subExpr, ty) {
-    InOutToPointerExprBits.IsNonAccessing = false;
+    Bits.InOutToPointerExpr.IsNonAccessing = false;
   }
 
   /// Is this conversion "non-accessing"?  That is, is it only using the
   /// pointer for its identity, as opposed to actually accessing the memory?
   bool isNonAccessing() const {
-    return InOutToPointerExprBits.IsNonAccessing;
+    return Bits.InOutToPointerExpr.IsNonAccessing;
   }
   void setNonAccessing(bool nonAccessing = true) {
-    InOutToPointerExprBits.IsNonAccessing = nonAccessing;
+    Bits.InOutToPointerExpr.IsNonAccessing = nonAccessing;
   }
 
   static bool classof(const Expr *E) {
@@ -2799,16 +2784,16 @@
 public:
   ArrayToPointerExpr(Expr *subExpr, Type ty)
       : ImplicitConversionExpr(ExprKind::ArrayToPointer, subExpr, ty) {
-    ArrayToPointerExprBits.IsNonAccessing = false;
+    Bits.ArrayToPointerExpr.IsNonAccessing = false;
   }
   
   /// Is this conversion "non-accessing"?  That is, is it only using the
   /// pointer for its identity, as opposed to actually accessing the memory?
   bool isNonAccessing() const {
-    return ArrayToPointerExprBits.IsNonAccessing;
+    return Bits.ArrayToPointerExpr.IsNonAccessing;
   }
   void setNonAccessing(bool nonAccessing = true) {
-    ArrayToPointerExprBits.IsNonAccessing = nonAccessing;
+    Bits.ArrayToPointerExpr.IsNonAccessing = nonAccessing;
   }
 
   static bool classof(const Expr *E) {
@@ -2866,7 +2851,20 @@
 /// If hasScalarSource() is true, the subexpression should be treated
 /// as if it were implicitly injected into a single-element tuple
 /// type.  Otherwise, the subexpression is known to have a tuple type.
-class TupleShuffleExpr : public ImplicitConversionExpr {
+class TupleShuffleExpr final : public ImplicitConversionExpr,
+    private llvm::TrailingObjects<TupleShuffleExpr, Expr *, int, unsigned> {
+  friend TrailingObjects;
+
+  size_t numTrailingObjects(OverloadToken<Expr *>) const {
+    return Bits.TupleShuffleExpr.NumCallerDefaultArgs;
+  }
+  size_t numTrailingObjects(OverloadToken<int>) const {
+    return Bits.TupleShuffleExpr.NumElementMappings;
+  }
+  size_t numTrailingObjects(OverloadToken<unsigned>) const {
+    return Bits.TupleShuffleExpr.NumVariadicArgs;
+  }
+
 public:
   enum : int {
     /// The element mapping value indicating that a field of the destination
@@ -2901,12 +2899,6 @@
   };
 
 private:
-  /// This contains an entry for each element in the Expr type.  Each element
-  /// specifies which index from the SubExpr that the destination element gets.
-  /// If the element value is DefaultInitialize, then the destination value
-  /// gets the default initializer for that tuple element value.
-  ArrayRef<int> ElementMapping;
-
   /// If we're doing a varargs shuffle, this is the array type to build.
   Type VarargsArrayTy;
 
@@ -2914,32 +2906,45 @@
   /// declaration.
   ConcreteDeclRef DefaultArgsOwner;
 
-  /// The arguments that are packed into the variadic element.
-  ArrayRef<unsigned> VariadicArgs;
-
-  MutableArrayRef<Expr *> CallerDefaultArgs;
-
-public:
-  TupleShuffleExpr(Expr *subExpr, ArrayRef<int> elementMapping, 
+  TupleShuffleExpr(Expr *subExpr, ArrayRef<int> elementMapping,
                    TypeImpact typeImpact,
                    ConcreteDeclRef defaultArgsOwner,
                    ArrayRef<unsigned> VariadicArgs,
                    Type VarargsArrayTy,
-                   MutableArrayRef<Expr *> CallerDefaultArgs,
+                   ArrayRef<Expr *> CallerDefaultArgs,
                    Type ty)
     : ImplicitConversionExpr(ExprKind::TupleShuffle, subExpr, ty),
-      ElementMapping(elementMapping), VarargsArrayTy(VarargsArrayTy),
-      DefaultArgsOwner(defaultArgsOwner), VariadicArgs(VariadicArgs),
-      CallerDefaultArgs(CallerDefaultArgs)
-  {
-    TupleShuffleExprBits.TypeImpact = typeImpact;
+      VarargsArrayTy(VarargsArrayTy), DefaultArgsOwner(defaultArgsOwner) {
+    Bits.TupleShuffleExpr.TypeImpact = typeImpact;
+    Bits.TupleShuffleExpr.NumCallerDefaultArgs = CallerDefaultArgs.size();
+    Bits.TupleShuffleExpr.NumElementMappings = elementMapping.size();
+    Bits.TupleShuffleExpr.NumVariadicArgs = VariadicArgs.size();
+    std::uninitialized_copy(CallerDefaultArgs.begin(), CallerDefaultArgs.end(),
+                            getTrailingObjects<Expr*>());
+    std::uninitialized_copy(elementMapping.begin(), elementMapping.end(),
+                            getTrailingObjects<int>());
+    std::uninitialized_copy(VariadicArgs.begin(), VariadicArgs.end(),
+                            getTrailingObjects<unsigned>());
   }
 
-  ArrayRef<int> getElementMapping() const { return ElementMapping; }
+public:
+  static TupleShuffleExpr *create(ASTContext &ctx, Expr *subExpr,
+                                  ArrayRef<int> elementMapping,
+                                  TypeImpact typeImpact,
+                                  ConcreteDeclRef defaultArgsOwner,
+                                  ArrayRef<unsigned> VariadicArgs,
+                                  Type VarargsArrayTy,
+                                  ArrayRef<Expr *> CallerDefaultArgs,
+                                  Type ty);
+
+  ArrayRef<int> getElementMapping() const {
+    return {getTrailingObjects<int>(),
+            Bits.TupleShuffleExpr.NumElementMappings};
+  }
 
   /// What is the type impact of this shuffle?
   TypeImpact getTypeImpact() const {
-    return TypeImpact(TupleShuffleExprBits.TypeImpact);
+    return TypeImpact(Bits.TupleShuffleExpr.TypeImpact);
   }
 
   bool isSourceScalar() const {
@@ -2959,16 +2964,25 @@
   }
 
   /// Retrieve the argument indices for the variadic arguments.
-  ArrayRef<unsigned> getVariadicArgs() const { return VariadicArgs; }
+  ArrayRef<unsigned> getVariadicArgs() const {
+    return {getTrailingObjects<unsigned>(),
+            Bits.TupleShuffleExpr.NumVariadicArgs};
+  }
 
   /// Retrieve the owner of the default arguments.
   ConcreteDeclRef getDefaultArgsOwner() const { return DefaultArgsOwner; }
 
   /// Retrieve the caller-defaulted arguments.
-  ArrayRef<Expr *> getCallerDefaultArgs() const { return CallerDefaultArgs; }
+  ArrayRef<Expr *> getCallerDefaultArgs() const {
+    return {getTrailingObjects<Expr*>(),
+            Bits.TupleShuffleExpr.NumCallerDefaultArgs};
+  }
 
   /// Retrieve the caller-defaulted arguments.
-  MutableArrayRef<Expr *> getCallerDefaultArgs() { return CallerDefaultArgs; }
+  MutableArrayRef<Expr *> getCallerDefaultArgs() {
+    return {getTrailingObjects<Expr*>(),
+            Bits.TupleShuffleExpr.NumCallerDefaultArgs};
+  }
 
   static bool classof(const Expr *E) {
     return E->getKind() == ExprKind::TupleShuffle;
@@ -3132,14 +3146,21 @@
 ///
 /// "Appropriate kind" means e.g. a concrete/existential metatype if the
 /// result is an existential metatype.
-class ErasureExpr : public ImplicitConversionExpr {
-  ArrayRef<ProtocolConformanceRef> Conformances;
+class ErasureExpr final : public ImplicitConversionExpr,
+    private llvm::TrailingObjects<ErasureExpr, ProtocolConformanceRef> {
+  friend TrailingObjects;
 
-public:
   ErasureExpr(Expr *subExpr, Type type,
               ArrayRef<ProtocolConformanceRef> conformances)
-    : ImplicitConversionExpr(ExprKind::Erasure, subExpr, type),
-      Conformances(conformances) {}
+    : ImplicitConversionExpr(ExprKind::Erasure, subExpr, type) {
+    Bits.ErasureExpr.NumConformances = conformances.size();
+    std::uninitialized_copy(conformances.begin(), conformances.end(),
+                            getTrailingObjects<ProtocolConformanceRef>());
+  }
+
+public:
+  static ErasureExpr *create(ASTContext &ctx, Expr *subExpr, Type type,
+                             ArrayRef<ProtocolConformanceRef> conformances);
 
   /// \brief Retrieve the mapping specifying how the type of the subexpression
   /// maps to the resulting existential type. If the resulting existential
@@ -3152,7 +3173,8 @@
   /// type is either an archetype or an existential type that conforms to
   /// that corresponding protocol).
   ArrayRef<ProtocolConformanceRef> getConformances() const {
-    return Conformances;
+    return {getTrailingObjects<ProtocolConformanceRef>(),
+            Bits.ErasureExpr.NumConformances };
   }
 
   static bool classof(const Expr *E) {
@@ -3231,28 +3253,43 @@
 
 /// UnresolvedSpecializeExpr - Represents an explicit specialization using
 /// a type parameter list (e.g. "Vector<Int>") that has not been resolved.
-class UnresolvedSpecializeExpr : public Expr {
+class UnresolvedSpecializeExpr final : public Expr,
+    private llvm::TrailingObjects<UnresolvedSpecializeExpr, TypeLoc> {
+  friend TrailingObjects;
+
   Expr *SubExpr;
   SourceLoc LAngleLoc;
   SourceLoc RAngleLoc;
-  MutableArrayRef<TypeLoc> UnresolvedParams;
-public:
+
   UnresolvedSpecializeExpr(Expr *SubExpr,
                            SourceLoc LAngleLoc,
-                           MutableArrayRef<TypeLoc> UnresolvedParams,
+                           ArrayRef<TypeLoc> UnresolvedParams,
                            SourceLoc RAngleLoc)
     : Expr(ExprKind::UnresolvedSpecialize, /*Implicit=*/false),
-      SubExpr(SubExpr),
-      LAngleLoc(LAngleLoc), RAngleLoc(RAngleLoc),
-      UnresolvedParams(UnresolvedParams) { }
+      SubExpr(SubExpr), LAngleLoc(LAngleLoc), RAngleLoc(RAngleLoc) {
+    Bits.UnresolvedSpecializeExpr.NumUnresolvedParams = UnresolvedParams.size();
+    std::uninitialized_copy(UnresolvedParams.begin(), UnresolvedParams.end(),
+                            getTrailingObjects<TypeLoc>());
+  }
+
+public:
+  static UnresolvedSpecializeExpr *
+  create(ASTContext &ctx, Expr *SubExpr, SourceLoc LAngleLoc,
+         ArrayRef<TypeLoc> UnresolvedParams, SourceLoc RAngleLoc);
   
   Expr *getSubExpr() const { return SubExpr; }
   void setSubExpr(Expr *e) { SubExpr = e; }
   
   /// \brief Retrieve the list of type parameters. These parameters have not yet
   /// been bound to archetypes of the entity to be specialized.
-  ArrayRef<TypeLoc> getUnresolvedParams() const { return UnresolvedParams; }
-  MutableArrayRef<TypeLoc> getUnresolvedParams() { return UnresolvedParams; }
+  ArrayRef<TypeLoc> getUnresolvedParams() const {
+    return {getTrailingObjects<TypeLoc>(),
+            Bits.UnresolvedSpecializeExpr.NumUnresolvedParams};
+  }
+  MutableArrayRef<TypeLoc> getUnresolvedParams() {
+    return {getTrailingObjects<TypeLoc>(),
+            Bits.UnresolvedSpecializeExpr.NumUnresolvedParams};
+  }
   
   SourceLoc getLoc() const { return LAngleLoc; }
   SourceLoc getLAngleLoc() const { return LAngleLoc; }
@@ -3320,12 +3357,10 @@
     private llvm::TrailingObjects<SequenceExpr, Expr *> {
   friend TrailingObjects;
 
-  unsigned NumElements;
-
   SequenceExpr(ArrayRef<Expr*> elements)
-    : Expr(ExprKind::Sequence, /*Implicit=*/false),
-      NumElements(elements.size()) {
-    assert(NumElements > 0 && "zero-length sequence!");
+    : Expr(ExprKind::Sequence, /*Implicit=*/false) {
+    Bits.SequenceExpr.NumElements = elements.size();
+    assert(Bits.SequenceExpr.NumElements > 0 && "zero-length sequence!");
     std::uninitialized_copy(elements.begin(), elements.end(),
                             getTrailingObjects<Expr*>());
   }
@@ -3340,14 +3375,14 @@
     return getElement(getNumElements() - 1)->getEndLoc();
   }
   
-  unsigned getNumElements() const { return NumElements; }
+  unsigned getNumElements() const { return Bits.SequenceExpr.NumElements; }
 
   MutableArrayRef<Expr*> getElements() {
-    return {getTrailingObjects<Expr*>(), NumElements};
+    return {getTrailingObjects<Expr*>(), Bits.SequenceExpr.NumElements};
   }
 
   ArrayRef<Expr*> getElements() const {
-    return {getTrailingObjects<Expr*>(), NumElements};
+    return {getTrailingObjects<Expr*>(), Bits.SequenceExpr.NumElements};
   }
 
   Expr *getElement(unsigned i) const {
@@ -3377,7 +3412,7 @@
       : Expr(Kind, Implicit, FnType),
         DeclContext(DeclContextKind::AbstractClosureExpr, Parent),
         parameterList(nullptr) {
-    AbstractClosureExprBits.Discriminator = Discriminator;
+    Bits.AbstractClosureExpr.Discriminator = Discriminator;
   }
 
   CaptureInfo &getCaptureInfo() { return Captures; }
@@ -3407,17 +3442,14 @@
   /// Having their symbol names be stable across minor code changes is
   /// therefore pretty useful for debugging.)
   unsigned getDiscriminator() const {
-    return AbstractClosureExprBits.Discriminator;
+    return Bits.AbstractClosureExpr.Discriminator;
   }
   void setDiscriminator(unsigned discriminator) {
     assert(getDiscriminator() == InvalidDiscriminator);
     assert(discriminator != InvalidDiscriminator);
-    AbstractClosureExprBits.Discriminator = discriminator;
+    Bits.AbstractClosureExpr.Discriminator = discriminator;
   }
-  enum : unsigned {
-    InvalidDiscriminator =
-      decltype(AbstractClosureExprBits)::InvalidDiscriminator
-  };
+  enum : unsigned { InvalidDiscriminator = 0xFFFF };
 
   ArrayRef<ParameterList *> getParameterLists() {
     return parameterList ? parameterList : ArrayRef<ParameterList *>();
@@ -3526,7 +3558,7 @@
       ExplicitResultType(explicitResultType),
       Body(nullptr) {
     setParameterList(params);
-    ClosureExprBits.HasAnonymousClosureVars = false;
+    Bits.ClosureExpr.HasAnonymousClosureVars = false;
   }
 
   SourceRange getSourceRange() const;
@@ -3543,13 +3575,13 @@
   /// \brief Determine whether the parameters of this closure are actually
   /// anonymous closure variables.
   bool hasAnonymousClosureVars() const {
-    return ClosureExprBits.HasAnonymousClosureVars;
+    return Bits.ClosureExpr.HasAnonymousClosureVars;
   }
 
   /// \brief Set the parameters of this closure along with a flag indicating
   /// whether these parameters are actually anonymous closure variables.
   void setHasAnonymousClosureVars() {
-    ClosureExprBits.HasAnonymousClosureVars = true;
+    Bits.ClosureExpr.HasAnonymousClosureVars = true;
   }
   
   /// \brief Determine whether this closure expression has an
@@ -3692,17 +3724,30 @@
 /// CaptureList wraps the ClosureExpr.  The dynamic semantics are that evaluates
 /// the variable bindings from the capture list, then evaluates the
 /// subexpression (the closure itself) and returns the result.
-class CaptureListExpr : public Expr {
-  ArrayRef<CaptureListEntry> captureList;
+class CaptureListExpr final : public Expr,
+    private llvm::TrailingObjects<CaptureListExpr, CaptureListEntry> {
+  friend TrailingObjects;
+
   ClosureExpr *closureBody;
-public:
+
   CaptureListExpr(ArrayRef<CaptureListEntry> captureList,
                   ClosureExpr *closureBody)
     : Expr(ExprKind::CaptureList, /*Implicit=*/false, Type()),
-      captureList(captureList), closureBody(closureBody) {
+      closureBody(closureBody) {
+    Bits.CaptureListExpr.NumCaptures = captureList.size();
+    std::uninitialized_copy(captureList.begin(), captureList.end(),
+                            getTrailingObjects<CaptureListEntry>());
   }
 
-  ArrayRef<CaptureListEntry> getCaptureList() { return captureList; }
+public:
+  static CaptureListExpr *create(ASTContext &ctx,
+                                 ArrayRef<CaptureListEntry> captureList,
+                                 ClosureExpr *closureBody);
+
+  ArrayRef<CaptureListEntry> getCaptureList() {
+    return {getTrailingObjects<CaptureListEntry>(),
+            Bits.CaptureListExpr.NumCaptures};
+  }
   ClosureExpr *getClosureBody() { return closureBody; }
   const ClosureExpr *getClosureBody() const { return closureBody; }
 
@@ -3789,7 +3834,7 @@
   ApplyExpr(ExprKind Kind, Expr *Fn, Expr *Arg, bool Implicit, Type Ty = Type())
     : Expr(Kind, Implicit, Ty), Fn(Fn), ArgAndIsSuper(Arg, false) {
     assert(classof((Expr*)this) && "ApplyExpr::classof out of date");
-    ApplyExprBits.ThrowsIsSet = false;
+    Bits.ApplyExpr.ThrowsIsSet = false;
   }
 
 public:
@@ -3812,7 +3857,7 @@
   /// Has the type-checker set the 'throws' bit yet?
   ///
   /// In general, this should only be used for debugging purposes.
-  bool isThrowsSet() const { return ApplyExprBits.ThrowsIsSet; }
+  bool isThrowsSet() const { return Bits.ApplyExpr.ThrowsIsSet; }
 
   /// Does this application throw?  This is only meaningful after
   /// complete type-checking.
@@ -3820,13 +3865,13 @@
   /// If true, the function expression must have a throwing function
   /// type.  The converse is not true because of 'rethrows' functions.
   bool throws() const {
-    assert(ApplyExprBits.ThrowsIsSet);
-    return ApplyExprBits.Throws;
+    assert(Bits.ApplyExpr.ThrowsIsSet);
+    return Bits.ApplyExpr.Throws;
   }
   void setThrows(bool throws) {
-    assert(!ApplyExprBits.ThrowsIsSet);
-    ApplyExprBits.ThrowsIsSet = true;
-    ApplyExprBits.Throws = throws;
+    assert(!Bits.ApplyExpr.ThrowsIsSet);
+    Bits.ApplyExpr.ThrowsIsSet = true;
+    Bits.ApplyExpr.Throws = throws;
   }
 
   ValueDecl *getCalledValue() const;
@@ -3917,11 +3962,11 @@
     return FnLoc.isValid() ? FnLoc : getArg()->getLoc();
   }
 
-  unsigned getNumArguments() const { return CallExprBits.NumArgLabels; }
-  bool hasArgumentLabelLocs() const { return CallExprBits.HasArgLabelLocs; }
+  unsigned getNumArguments() const { return Bits.CallExpr.NumArgLabels; }
+  bool hasArgumentLabelLocs() const { return Bits.CallExpr.HasArgLabelLocs; }
 
   /// Whether this call with written with a trailing closure.
-  bool hasTrailingClosure() const { return CallExprBits.HasTrailingClosure; }
+  bool hasTrailingClosure() const { return Bits.CallExpr.HasTrailingClosure; }
 
   using TrailingCallArguments::getArgumentLabels;
 
@@ -4161,15 +4206,15 @@
                   Expr *sub, SourceLoc asLoc, TypeLoc castTy, Type resultTy)
     : ExplicitCastExpr(kind, sub, asLoc, castTy, resultTy)
   {
-    CheckedCastExprBits.CastKind = unsigned(CheckedCastKind::Unresolved);
+    Bits.CheckedCastExpr.CastKind = unsigned(CheckedCastKind::Unresolved);
   }
   
   /// Return the semantic kind of cast performed.
   CheckedCastKind getCastKind() const {
-    return CheckedCastKind(CheckedCastExprBits.CastKind);
+    return CheckedCastKind(Bits.CheckedCastExpr.CastKind);
   }
   void setCastKind(CheckedCastKind kind) {
-    CheckedCastExprBits.CastKind = unsigned(kind);
+    Bits.CheckedCastExpr.CastKind = unsigned(kind);
   }
   
   /// True if the cast has been type-checked and its kind has been set.
@@ -4560,7 +4605,7 @@
     : Expr(ExprKind::ObjCSelector, /*Implicit=*/false),
       KeywordLoc(keywordLoc), LParenLoc(lParenLoc),
       ModifierLoc(modifierLoc), SubExpr(subExpr), RParenLoc(rParenLoc) {
-    ObjCSelectorExprBits.SelectorKind = static_cast<unsigned>(kind);
+    Bits.ObjCSelectorExpr.SelectorKind = static_cast<unsigned>(kind);
   }
 
   Expr *getSubExpr() const { return SubExpr; }
@@ -4612,7 +4657,7 @@
 
   /// Retrieve the kind of the selector (method, getter, setter)
   ObjCSelectorKind getSelectorKind() const {
-    return static_cast<ObjCSelectorKind>(ObjCSelectorExprBits.SelectorKind);
+    return static_cast<ObjCSelectorKind>(Bits.ObjCSelectorExpr.SelectorKind);
   }
 
   /// Override the selector kind.
@@ -4621,7 +4666,7 @@
   /// expressions.
   void overrideObjCSelectorKind(ObjCSelectorKind newKind,
                                 SourceLoc modifierLoc) {
-    ObjCSelectorExprBits.SelectorKind = static_cast<unsigned>(newKind);
+    Bits.ObjCSelectorExpr.SelectorKind = static_cast<unsigned>(newKind);
     ModifierLoc = modifierLoc;
   }
 
@@ -4950,7 +4995,7 @@
         ParsedRoot(parsedRoot), ParsedPath(parsedPath) {
     assert((parsedRoot || parsedPath) &&
            "keypath must have either root or path");
-    KeyPathExprBits.IsObjC = false;
+    Bits.KeyPathExpr.IsObjC = false;
   }
 
   SourceLoc getLoc() const { return StartLoc; }
@@ -5009,7 +5054,7 @@
   }
 
   /// True if this is an ObjC key path expression.
-  bool isObjC() const { return KeyPathExprBits.IsObjC; }
+  bool isObjC() const { return Bits.KeyPathExpr.IsObjC; }
 
   static bool classof(const Expr *E) {
     return E->getKind() == ExprKind::KeyPath;
@@ -5038,6 +5083,22 @@
          isa<AssignExpr>(this) || isa<ExplicitCastExpr>(this);
 }
 
+inline Expr *const *CollectionExpr::getTrailingObjectsPointer() const {
+  if (auto ty = dyn_cast<ArrayExpr>(this))
+    return ty->getTrailingObjects<Expr*>();
+  if (auto ty = dyn_cast<DictionaryExpr>(this))
+    return ty->getTrailingObjects<Expr*>();
+  llvm_unreachable("Unhandled CollectionExpr!");
+}
+
+inline const SourceLoc *CollectionExpr::getTrailingSourceLocs() const {
+  if (auto ty = dyn_cast<ArrayExpr>(this))
+    return ty->getTrailingObjects<SourceLoc>();
+  if (auto ty = dyn_cast<DictionaryExpr>(this))
+    return ty->getTrailingObjects<SourceLoc>();
+  llvm_unreachable("Unhandled CollectionExpr!");
+}
+
 #undef SWIFT_FORWARD_SOURCE_LOCS_TO
   
 } // end namespace swift
diff --git a/include/swift/AST/ExprNodes.def b/include/swift/AST/ExprNodes.def
index db83e2c..d628a9c 100644
--- a/include/swift/AST/ExprNodes.def
+++ b/include/swift/AST/ExprNodes.def
@@ -54,6 +54,10 @@
 #define EXPR_RANGE(Id, First, Last)
 #endif
 
+#ifndef LAST_EXPR
+#define LAST_EXPR(Id)
+#endif
+
 EXPR(Error, Expr)
 ABSTRACT_EXPR(Literal, Expr)
   LITERAL_EXPR(NilLiteral, LiteralExpr)
@@ -172,9 +176,11 @@
 EXPR(ObjCSelector, Expr)
 EXPR(KeyPath, Expr)
 UNCHECKED_EXPR(KeyPathDot, Expr)
+LAST_EXPR(KeyPathDot)
 
 #undef EXPR_RANGE
 #undef LITERAL_EXPR
 #undef UNCHECKED_EXPR
 #undef ABSTRACT_EXPR
 #undef EXPR
+#undef LAST_EXPR
diff --git a/include/swift/AST/GenericSignatureBuilder.h b/include/swift/AST/GenericSignatureBuilder.h
index 35f9411..f155ad8 100644
--- a/include/swift/AST/GenericSignatureBuilder.h
+++ b/include/swift/AST/GenericSignatureBuilder.h
@@ -936,9 +936,11 @@
   /// Whether there is a trailing written requirement location.
   const bool hasTrailingWrittenRequirementLoc;
 
+public:
   /// Whether a protocol requirement came from the requirement signature.
   const bool usesRequirementSignature;
 
+private:
   /// The actual storage, described by \c storageKind.
   union {
     /// The type to which a requirement applies.
diff --git a/include/swift/AST/LazyResolver.h b/include/swift/AST/LazyResolver.h
index 2f581a5..5a4a808 100644
--- a/include/swift/AST/LazyResolver.h
+++ b/include/swift/AST/LazyResolver.h
@@ -96,15 +96,6 @@
   /// Resolve an implicitly-generated member with the given name.
   virtual void resolveImplicitMember(NominalTypeDecl *nominal, DeclName member) = 0;
 
-  /// Resolve any implicitly-generated members and conformances for generated
-  /// external decls.
-  virtual void resolveExternalDeclImplicitMembers(NominalTypeDecl *nominal) = 0;
-
-  /// Determine whether the given (potentially constrained) protocol extension
-  /// is usable for the given type.
-  virtual bool isProtocolExtensionUsable(DeclContext *dc, Type type,
-                                         ExtensionDecl *protocolExtension) = 0;
-
   /// Mark the given conformance as "used" from the given declaration context.
   virtual void markConformanceUsed(ProtocolConformanceRef conformance,
                                    DeclContext *dc) = 0;
@@ -169,15 +160,6 @@
     Principal.resolveImplicitMember(nominal, member);
   }
 
-  void resolveExternalDeclImplicitMembers(NominalTypeDecl *nominal) override {
-    Principal.resolveExternalDeclImplicitMembers(nominal);
-  }
-
-  bool isProtocolExtensionUsable(DeclContext *dc, Type type,
-                                 ExtensionDecl *protocolExtension) override {
-    return Principal.isProtocolExtensionUsable(dc, type, protocolExtension);
-  }
-
   void markConformanceUsed(ProtocolConformanceRef conformance,
                            DeclContext *dc) override {
     return Principal.markConformanceUsed(conformance, dc);
@@ -231,7 +213,7 @@
   /// Returns None if an error occurred \em or named member-lookup
   /// was otherwise unsupported in this implementation or Decl.
   virtual Optional<TinyPtrVector<ValueDecl *>>
-  loadNamedMembers(const IterableDeclContext *IDC, DeclName N,
+  loadNamedMembers(const IterableDeclContext *IDC, DeclBaseName N,
                    uint64_t contextData) = 0;
 
   /// Populates the given vector with all conformances for \p D.
diff --git a/include/swift/AST/Pattern.h b/include/swift/AST/Pattern.h
index 96f2d3e..95019ba 100644
--- a/include/swift/AST/Pattern.h
+++ b/include/swift/AST/Pattern.h
@@ -25,6 +25,7 @@
 #include "swift/AST/Types.h"
 #include "swift/AST/TypeLoc.h"
 #include "swift/AST/TypeAlignments.h"
+#include "swift/Basic/InlineBitfield.h"
 #include "swift/Basic/OptionSet.h"
 #include "llvm/Support/TrailingObjects.h"
 
@@ -37,58 +38,57 @@
 /// value-matching pattern.
 enum class PatternKind : uint8_t {
 #define PATTERN(ID, PARENT) ID,
+#define LAST_PATTERN(ID) Last_Pattern = ID,
 #include "PatternNodes.def"
 };
+enum : unsigned { NumPatternKindBits =
+  countBitsUsed(static_cast<unsigned>(PatternKind::Last_Pattern)) };
 
 /// Diagnostic printing of PatternKinds.
 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, PatternKind kind);
   
 /// Pattern - Base class for all patterns in Swift.
 class alignas(8) Pattern {
-  class PatternBitfields {
-    friend class Pattern;
-    unsigned Kind : 8;
-    unsigned isImplicit : 1;
-    mutable unsigned hasInterfaceType : 1;
-  };
-  enum { NumPatternBits = 10 };
-  enum { NumBitsAllocated = 32 };
+  SWIFT_INLINE_BITFIELD_BASE(Pattern, bitmax(NumPatternKindBits,8)+1+1,
+    Kind : bitmax(NumPatternKindBits,8),
+    isImplicit : 1,
+    hasInterfaceType : 1
+  );
 
-  class TuplePatternBitfields {
-    friend class TuplePattern;
-    unsigned : NumPatternBits;
-    unsigned NumElements : NumBitsAllocated - NumPatternBits;
-  };
+  SWIFT_INLINE_BITFIELD_FULL(TuplePattern, Pattern, 32,
+    : NumPadBits,
+    NumElements : 32
+  );
 
-  class TypedPatternBitfields {
-    friend class TypedPattern;
-    unsigned : NumPatternBits;
-    unsigned IsPropagatedType : 1;
-  };
+  SWIFT_INLINE_BITFIELD(TypedPattern, Pattern, 1,
+    IsPropagatedType : 1
+  );
 
 protected:
   union {
-    PatternBitfields PatternBits;
-    TuplePatternBitfields TuplePatternBits;
-    TypedPatternBitfields TypedPatternBits;
-  };
+    uint64_t OpaqueBits;
+    SWIFT_INLINE_BITS(Pattern);
+    SWIFT_INLINE_BITS(TuplePattern);
+    SWIFT_INLINE_BITS(TypedPattern);
+  } Bits;
 
   Pattern(PatternKind kind) {
-    PatternBits.Kind = unsigned(kind);
-    PatternBits.isImplicit = false;
-    PatternBits.hasInterfaceType = false;
+    Bits.OpaqueBits = 0;
+    Bits.Pattern.Kind = unsigned(kind);
+    Bits.Pattern.isImplicit = false;
+    Bits.Pattern.hasInterfaceType = false;
   }
 
 private:
   /// The checked type of the pattern.
   ///
-  /// if \c PatternBits.hasInterfaceType, this stores the interface type of the
+  /// if \c Bits.Pattern.hasInterfaceType, this stores the interface type of the
   /// pattern, which will be lazily resolved to the contextual type using
   /// the environment in \c ASTContext::DelayedPatternContexts.
   mutable Type Ty;
 
 public:
-  PatternKind getKind() const { return PatternKind(PatternBits.Kind); }
+  PatternKind getKind() const { return PatternKind(Bits.Pattern.Kind); }
 
   /// \brief Retrieve the name of the given pattern kind.
   ///
@@ -99,8 +99,8 @@
 
   /// A pattern is implicit if it is compiler-generated and there
   /// exists no source code for it.
-  bool isImplicit() const { return PatternBits.isImplicit; }
-  void setImplicit() { PatternBits.isImplicit = true; }
+  bool isImplicit() const { return Bits.Pattern.isImplicit; }
+  void setImplicit() { Bits.Pattern.isImplicit = true; }
 
   /// Find the smallest subpattern which obeys the property that matching it is
   /// equivalent to matching this pattern.
@@ -126,7 +126,7 @@
   ///
   /// Note: this is used for delayed deserialization logic.
   Type getDelayedInterfaceType() const {
-    if (PatternBits.hasInterfaceType) return Ty;
+    if (Bits.Pattern.hasInterfaceType) return Ty;
     return nullptr;
   }
 
@@ -280,12 +280,12 @@
     private llvm::TrailingObjects<TuplePattern, TuplePatternElt> {
   friend TrailingObjects;
   SourceLoc LPLoc, RPLoc;
-  // TuplePatternBits.NumElements
+  // Bits.TuplePattern.NumElements
 
   TuplePattern(SourceLoc lp, unsigned numElements, SourceLoc rp,
                bool implicit)
       : Pattern(PatternKind::Tuple), LPLoc(lp), RPLoc(rp) {
-    TuplePatternBits.NumElements = numElements;
+    Bits.TuplePattern.NumElements = numElements;
     assert(lp.isValid() == rp.isValid());
     if (implicit)
       setImplicit();
@@ -303,7 +303,7 @@
                                Optional<bool> implicit = None);
 
   unsigned getNumElements() const {
-    return TuplePatternBits.NumElements;
+    return Bits.TuplePattern.NumElements;
   }
 
   MutableArrayRef<TuplePatternElt> getElements() {
@@ -381,7 +381,7 @@
     : Pattern(PatternKind::Typed), SubPattern(pattern), PatType(tl) {
     if (implicit.hasValue() ? *implicit : !tl.hasLocation())
       setImplicit();
-    TypedPatternBits.IsPropagatedType = false;
+    Bits.TypedPattern.IsPropagatedType = false;
   }
 
   /// True if the type in this \c TypedPattern was propagated from a different
@@ -393,10 +393,10 @@
   /// \endcode
   /// 'a' and 'c' will have this bit set to true.
   bool isPropagatedType() const {
-    return TypedPatternBits.IsPropagatedType;
+    return Bits.TypedPattern.IsPropagatedType;
   }
   void setPropagatedType() {
-    TypedPatternBits.IsPropagatedType = true;
+    Bits.TypedPattern.IsPropagatedType = true;
   }
 
   Pattern *getSubPattern() { return SubPattern; }
diff --git a/include/swift/AST/PatternNodes.def b/include/swift/AST/PatternNodes.def
index 94c14c3..ef7b4da 100644
--- a/include/swift/AST/PatternNodes.def
+++ b/include/swift/AST/PatternNodes.def
@@ -28,6 +28,10 @@
 # define REFUTABLE_PATTERN(Id, Parent) PATTERN(Id, Parent)
 #endif
 
+#ifndef LAST_PATTERN
+#define LAST_PATTERN(Id)
+#endif
+
 PATTERN(Paren, Pattern)
 PATTERN(Tuple, Pattern)
 PATTERN(Named, Pattern)
@@ -39,6 +43,8 @@
 REFUTABLE_PATTERN(OptionalSome, Pattern)
 REFUTABLE_PATTERN(Bool, Pattern)
 REFUTABLE_PATTERN(Expr, Pattern)
+LAST_PATTERN(Expr)
 
-#undef PATTERN
 #undef REFUTABLE_PATTERN
+#undef PATTERN
+#undef LAST_PATTERN
diff --git a/include/swift/AST/RequirementEnvironment.h b/include/swift/AST/RequirementEnvironment.h
new file mode 100644
index 0000000..ce5165c
--- /dev/null
+++ b/include/swift/AST/RequirementEnvironment.h
@@ -0,0 +1,124 @@
+//===--- RequirementEnvironment.h - Requirement Environments ----*- C++ -*-===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines the RequirementEnvironment class, which is used to
+// capture how a witness to a protocol requirement maps type parameters.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef SWIFT_AST_REQUIREMENT_ENVIRONMENT_H
+#define SWIFT_AST_REQUIREMENT_ENVIRONMENT_H
+
+#include "swift/AST/SubstitutionMap.h"
+
+namespace swift {
+
+/// Describes the environment of a requirement that will be used when
+/// matching witnesses against the requirement and to form the resulting
+/// \c Witness value.
+///
+/// The produced generic environment will have a fresh set of archetypes that
+/// describe the combined constraints of the requirement (because those
+/// are available to all potential witnesses) as well as the constraints from
+/// the context to which the protocol conformance is ascribed, which may
+/// include additional constraints beyond those of the extended type if the
+/// conformance is conditional. The type parameters for the generic
+/// environment are the type parameters of the conformance context
+/// (\c conformanceDC) with another (deeper) level of type parameters for
+/// generic requirements. See the \c Witness class for more information about
+/// this synthetic environment.
+class RequirementEnvironment {
+  /// A generic signature that combines the generic parameters of the
+  /// concrete conforming type with the generic parameters of the
+  /// requirement.
+  ///
+  ///
+  /// For example, if you have:
+  ///
+  /// protocol P { func f<T>(_: T) }
+  /// struct S<A, B> : P { func f<T>(_: T) }
+  ///
+  /// The requirement and witness signatures are, respectively:
+  ///
+  /// <Self : P, T>
+  /// <A, B, T>
+  ///
+  /// The synthetic signature in this case is just the witness signature.
+  ///
+  /// It may be that the witness is more generic than the requirement,
+  /// for example:
+  ///
+  /// protocol P { func f(_: Int) }
+  /// struct S<A, B> : P { func f<T>(_: T) { } }
+  ///
+  /// Here, the requirement signature and witness signatures are:
+  ///
+  /// <Self : P>
+  /// <A, B, T>
+  ///
+  /// The synthetic signature is just:
+  ///
+  /// <A, B>
+  ///
+  /// The witness thunk emitted by SILGen uses the synthetic signature.
+  /// Therefore one invariant we preserve is that the witness thunk is
+  /// ABI compatible with the requirement's function type.
+  GenericSignature *syntheticSignature = nullptr;
+  GenericEnvironment *syntheticEnvironment = nullptr;
+
+  /// The generic signature of the protocol requirement member.
+  GenericSignature *reqSig = nullptr;
+
+  /// A substitution map mapping the requirement signature to the
+  /// generic parameters of the synthetic signature.
+  SubstitutionMap reqToSyntheticEnvMap;
+
+public:
+  /// Create a new environment for matching the given requirement within a
+  /// particular conformance.
+  ///
+  /// \param conformanceDC The \c DeclContext to which the protocol
+  /// conformance is ascribed, which provides additional constraints.
+  ///
+  /// \param reqSig The generic signature of the requirement for which we
+  /// are creating a generic environment.
+  ///
+  /// \param proto The protocol containing the requirement.
+  ///
+  /// \param conformance The protocol conformance, or null if there is no
+  /// conformance (because we're finding default implementations).
+  RequirementEnvironment(DeclContext *conformanceDC,
+                         GenericSignature *reqSig,
+                         ProtocolDecl *proto,
+                         ClassDecl *covariantSelf,
+                         ProtocolConformance *conformance);
+
+  /// Retrieve the synthetic generic environment.
+  GenericEnvironment *getSyntheticEnvironment() const {
+    return syntheticEnvironment;
+  }
+
+  /// Retrieve the generic signature of the requirement.
+  const GenericSignature *getRequirementSignature() const {
+    return reqSig;
+  }
+
+  /// Retrieve the substitution map that maps the interface types of the
+  /// requirement to the interface types of the synthetic environment.
+  const SubstitutionMap &getRequirementToSyntheticMap() const {
+    return reqToSyntheticEnvMap;
+  }
+};
+
+}
+
+#endif // SWIFT_AST_REQUIREMENT_ENVIRONMENT_H
diff --git a/include/swift/AST/SILOptions.h b/include/swift/AST/SILOptions.h
index 7d46db8..d773bdb 100644
--- a/include/swift/AST/SILOptions.h
+++ b/include/swift/AST/SILOptions.h
@@ -161,6 +161,10 @@
   bool shouldOptimize() const {
     return OptMode > OptimizationMode::NoOptimization;
   }
+
+  bool hasMultipleIRGenThreads() const { return NumThreads > 1; }
+  bool shouldPerformIRGenerationInParallel() const { return NumThreads != 0; }
+  bool hasMultipleIGMs() const { return hasMultipleIRGenThreads(); }
 };
 
 } // end namespace swift
diff --git a/include/swift/AST/Stmt.h b/include/swift/AST/Stmt.h
index d86b77a..51aadd4 100644
--- a/include/swift/AST/Stmt.h
+++ b/include/swift/AST/Stmt.h
@@ -38,22 +38,59 @@
   
 enum class StmtKind {
 #define STMT(ID, PARENT) ID,
+#define LAST_STMT(ID) Last_Stmt = ID,
 #define STMT_RANGE(Id, FirstId, LastId) \
   First_##Id##Stmt = FirstId, Last_##Id##Stmt = LastId,
 #include "swift/AST/StmtNodes.def"
 };
+enum : unsigned { NumStmtKindBits =
+  countBitsUsed(static_cast<unsigned>(StmtKind::Last_Stmt)) };
 
 /// Stmt - Base class for all statements in swift.
 class alignas(8) Stmt {
   Stmt(const Stmt&) = delete;
   Stmt& operator=(const Stmt&) = delete;
 
-  /// Kind - The subclass of Stmt that this is.
-  unsigned Kind : 31;
-  /// Implicit - Whether this statement is implicit.
-  unsigned Implicit : 1;
+  SWIFT_INLINE_BITFIELD_BASE(Stmt, bitmax(NumStmtKindBits,8) + 1,
+    /// Kind - The subclass of Stmt that this is.
+    Kind : bitmax(NumStmtKindBits,8),
+
+    /// Implicit - Whether this statement is implicit.
+    Implicit : 1
+  );
+
+  SWIFT_INLINE_BITFIELD_FULL(BraceStmt, Stmt, 32,
+    : NumPadBits,
+    NumElements : 32
+  );
+
+  SWIFT_INLINE_BITFIELD_FULL(CaseStmt, Stmt, 32,
+    : NumPadBits,
+    NumPatterns : 32
+  );
+
+  SWIFT_INLINE_BITFIELD_EMPTY(LabeledStmt, Stmt);
+
+  SWIFT_INLINE_BITFIELD_FULL(DoCatchStmt, LabeledStmt, 32,
+    : NumPadBits,
+    NumCatches : 32
+  );
+
+  SWIFT_INLINE_BITFIELD_FULL(SwitchStmt, LabeledStmt, 32,
+    : NumPadBits,
+    CaseCount : 32
+  );
 
 protected:
+  union {
+    uint64_t OpaqueBits;
+    SWIFT_INLINE_BITS(Stmt);
+    SWIFT_INLINE_BITS(BraceStmt);
+    SWIFT_INLINE_BITS(DoCatchStmt);
+    SWIFT_INLINE_BITS(CaseStmt);
+    SWIFT_INLINE_BITS(SwitchStmt);
+  } Bits;
+
   /// Return the given value for the 'implicit' flag if present, or if None,
   /// return true if the location is invalid.
   static bool getDefaultImplicitFlag(Optional<bool> implicit, SourceLoc keyLoc){
@@ -61,10 +98,13 @@
   }
   
 public:
-  Stmt(StmtKind kind, bool implicit)
-    : Kind(unsigned(kind)), Implicit(unsigned(implicit)) {}
+  Stmt(StmtKind kind, bool implicit) {
+    Bits.OpaqueBits = 0;
+    Bits.Stmt.Kind = static_cast<unsigned>(kind);
+    Bits.Stmt.Implicit = implicit;
+  }
 
-  StmtKind getKind() const { return StmtKind(Kind); }
+  StmtKind getKind() const { return StmtKind(Bits.Stmt.Kind); }
 
   /// \brief Retrieve the name of the given statement kind.
   ///
@@ -84,7 +124,7 @@
   
   /// isImplicit - Determines whether this statement was implicitly-generated,
   /// rather than explicitly written in the AST.
-  bool isImplicit() const { return bool(Implicit); }
+  bool isImplicit() const { return Bits.Stmt.Implicit; }
 
   /// walk - This recursively walks the AST rooted at this statement.
   Stmt *walk(ASTWalker &walker);
@@ -112,8 +152,6 @@
     private llvm::TrailingObjects<BraceStmt, ASTNode> {
   friend TrailingObjects;
 
-  unsigned NumElements;
-  
   SourceLoc LBLoc;
   SourceLoc RBLoc;
 
@@ -131,19 +169,19 @@
   
   SourceRange getSourceRange() const { return SourceRange(LBLoc, RBLoc); }
 
-  unsigned getNumElements() const { return NumElements; }
+  unsigned getNumElements() const { return Bits.BraceStmt.NumElements; }
 
   ASTNode getElement(unsigned i) const { return getElements()[i]; }
   void setElement(unsigned i, ASTNode node) { getElements()[i] = node; }
 
   /// The elements contained within the BraceStmt.
   MutableArrayRef<ASTNode> getElements() {
-    return {getTrailingObjects<ASTNode>(), NumElements};
+    return {getTrailingObjects<ASTNode>(), Bits.BraceStmt.NumElements};
   }
 
   /// The elements contained within the BraceStmt (const version).
   ArrayRef<ASTNode> getElements() const {
-    return {getTrailingObjects<ASTNode>(), NumElements};
+    return {getTrailingObjects<ASTNode>(), Bits.BraceStmt.NumElements};
   }
   
   static bool classof(const Stmt *S) { return S->getKind() == StmtKind::Brace; }
@@ -506,14 +544,13 @@
 
   SourceLoc DoLoc;
   Stmt *Body;
-  unsigned NumCatches;
 
   DoCatchStmt(LabeledStmtInfo labelInfo, SourceLoc doLoc,
               Stmt *body, ArrayRef<CatchStmt*> catches,
               Optional<bool> implicit)
     : LabeledStmt(StmtKind::DoCatch, getDefaultImplicitFlag(implicit, doLoc),
-                  labelInfo),
-      DoLoc(doLoc), Body(body), NumCatches(catches.size()) {
+                  labelInfo), DoLoc(doLoc), Body(body) {
+    Bits.DoCatchStmt.NumCatches = catches.size();
     std::uninitialized_copy(catches.begin(), catches.end(),
                             getTrailingObjects<CatchStmt *>());
   }
@@ -533,10 +570,10 @@
   void setBody(Stmt *s) { Body = s; }
 
   ArrayRef<CatchStmt*> getCatches() const {
-    return {getTrailingObjects<CatchStmt*>(), NumCatches};
+    return {getTrailingObjects<CatchStmt*>(), Bits.DoCatchStmt.NumCatches};
   }
   MutableArrayRef<CatchStmt*> getMutableCatches() {
-    return {getTrailingObjects<CatchStmt*>(), NumCatches};
+    return {getTrailingObjects<CatchStmt*>(), Bits.DoCatchStmt.NumCatches};
   }
 
   /// Does this statement contain a syntactically exhaustive catch
@@ -837,7 +874,6 @@
   SourceLoc ColonLoc;
 
   llvm::PointerIntPair<Stmt *, 1, bool> BodyAndHasBoundDecls;
-  unsigned NumPatterns;
 
   CaseStmt(SourceLoc CaseLoc, ArrayRef<CaseLabelItem> CaseLabelItems,
            bool HasBoundDecls, SourceLoc ColonLoc, Stmt *Body,
@@ -850,10 +886,10 @@
                           Optional<bool> Implicit = None);
 
   ArrayRef<CaseLabelItem> getCaseLabelItems() const {
-    return {getTrailingObjects<CaseLabelItem>(), NumPatterns};
+    return {getTrailingObjects<CaseLabelItem>(), Bits.CaseStmt.NumPatterns};
   }
   MutableArrayRef<CaseLabelItem> getMutableCaseLabelItems() {
-    return {getTrailingObjects<CaseLabelItem>(), NumPatterns};
+    return {getTrailingObjects<CaseLabelItem>(), Bits.CaseStmt.NumPatterns};
   }
 
   Stmt *getBody() const { return BodyAndHasBoundDecls.getPointer(); }
@@ -883,7 +919,6 @@
 
   SourceLoc SwitchLoc, LBraceLoc, RBraceLoc;
   Expr *SubjectExpr;
-  unsigned CaseCount;
 
   SwitchStmt(LabeledStmtInfo LabelInfo, SourceLoc SwitchLoc, Expr *SubjectExpr,
              SourceLoc LBraceLoc, unsigned CaseCount, SourceLoc RBraceLoc,
@@ -891,8 +926,9 @@
     : LabeledStmt(StmtKind::Switch, getDefaultImplicitFlag(implicit, SwitchLoc),
                   LabelInfo),
       SwitchLoc(SwitchLoc), LBraceLoc(LBraceLoc), RBraceLoc(RBraceLoc),
-      SubjectExpr(SubjectExpr), CaseCount(CaseCount)
-  {}
+      SubjectExpr(SubjectExpr) {
+    Bits.SwitchStmt.CaseCount = CaseCount;
+  }
 
 public:
   /// Allocate a new SwitchStmt in the given ASTContext.
@@ -920,7 +956,7 @@
   void setSubjectExpr(Expr *e) { SubjectExpr = e; }
 
   ArrayRef<ASTNode> getRawCases() const {
-    return {getTrailingObjects<ASTNode>(), CaseCount};
+    return {getTrailingObjects<ASTNode>(), Bits.SwitchStmt.CaseCount};
   }
 
 private:
diff --git a/include/swift/AST/StmtNodes.def b/include/swift/AST/StmtNodes.def
index c92bfb8..47b10f3 100644
--- a/include/swift/AST/StmtNodes.def
+++ b/include/swift/AST/StmtNodes.def
@@ -40,6 +40,10 @@
 #define STMT_RANGE(Id, First, Last)
 #endif
 
+#ifndef LAST_STMT
+#define LAST_STMT(Id)
+#endif
+
 STMT(Brace, Stmt)
 STMT(Return, Stmt)
 STMT(Defer, Stmt)
@@ -62,8 +66,10 @@
 STMT(Fallthrough, Stmt)
 STMT(Fail, Stmt)
 STMT(Throw, Stmt)
+LAST_STMT(Throw)
 
 #undef STMT_RANGE
 #undef LABELED_STMT
 #undef ABSTRACT_STMT
 #undef STMT
+#undef LAST_STMT
diff --git a/include/swift/AST/TypeMatcher.h b/include/swift/AST/TypeMatcher.h
index 7f37714..34cedc0 100644
--- a/include/swift/AST/TypeMatcher.h
+++ b/include/swift/AST/TypeMatcher.h
@@ -279,9 +279,7 @@
             return false;
         }
 
-        return this->visit(firstFunc.getInput(), secondFunc->getInput(),
-                           sugaredFirstFunc->getInput()) &&
-               this->visit(firstFunc.getResult(), secondFunc->getResult(),
+        return this->visit(firstFunc.getResult(), secondFunc->getResult(),
                            sugaredFirstFunc->getResult());
       }
 
diff --git a/include/swift/AST/TypeNodes.def b/include/swift/AST/TypeNodes.def
index 2821074..ba05eee 100644
--- a/include/swift/AST/TypeNodes.def
+++ b/include/swift/AST/TypeNodes.def
@@ -83,6 +83,10 @@
 #define TYPE_RANGE(Id, First, Last)
 #endif
 
+#ifndef LAST_TYPE
+#define LAST_TYPE(Id)
+#endif
+
 TYPE(Error, Type)
 UNCHECKED_TYPE(Unresolved, Type)
 ABSTRACT_TYPE(Builtin, Type)
@@ -143,6 +147,7 @@
   TYPE(BoundGenericStruct, BoundGenericType)
   TYPE_RANGE(BoundGeneric, BoundGenericClass, BoundGenericStruct)
 UNCHECKED_TYPE(TypeVariable, Type)
+LAST_TYPE(TypeVariable)
 
 #undef TYPE_RANGE
 #undef ABSTRACT_SUGARED_TYPE
@@ -153,3 +158,4 @@
 #undef BUILTIN_TYPE
 #undef ALWAYS_CANONICAL_TYPE
 #undef TYPE
+#undef LAST_TYPE
diff --git a/include/swift/AST/TypeRepr.h b/include/swift/AST/TypeRepr.h
index 1a06f08..6fd4ff0 100644
--- a/include/swift/AST/TypeRepr.h
+++ b/include/swift/AST/TypeRepr.h
@@ -25,6 +25,7 @@
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/PointerUnion.h"
 #include "llvm/ADT/STLExtras.h"
+#include "swift/Basic/InlineBitfield.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/TrailingObjects.h"
 
@@ -37,50 +38,51 @@
 
 enum class TypeReprKind : uint8_t {
 #define TYPEREPR(ID, PARENT) ID,
+#define LAST_TYPEREPR(ID) Last_TypeRepr = ID,
 #include "TypeReprNodes.def"
 };
+enum : unsigned { NumTypeReprKindBits =
+  countBitsUsed(static_cast<unsigned>(TypeReprKind::Last_TypeRepr)) };
 
 /// \brief Representation of a type as written in source.
 class alignas(8) TypeRepr {
   TypeRepr(const TypeRepr&) = delete;
   void operator=(const TypeRepr&) = delete;
 
-  class TypeReprBitfields {
-    friend class TypeRepr;
+  SWIFT_INLINE_BITFIELD_BASE(TypeRepr, bitmax(NumTypeReprKindBits,8)+1+1,
     /// The subclass of TypeRepr that this is.
-    unsigned Kind : 6;
+    Kind : bitmax(NumTypeReprKindBits,8),
 
     /// Whether this type representation is known to contain an invalid
     /// type.
-    unsigned Invalid : 1;
+    Invalid : 1,
 
     /// Whether this type representation had a warning emitted related to it.
     /// This is a hack related to how we resolve type exprs multiple times in
     /// generic contexts.
-    unsigned Warned : 1;
-  };
-  enum { NumTypeReprBits = 8 };
-  class TupleTypeReprBitfields {
-    friend class TupleTypeRepr;
-    unsigned : NumTypeReprBits;
+    Warned : 1
+  );
 
-    /// The number of elements contained.
-    unsigned NumElements : 16;
-
+  SWIFT_INLINE_BITFIELD_FULL(TupleTypeRepr, TypeRepr, 1+16,
     /// Whether this tuple has '...' and its position.
-    unsigned HasEllipsis : 1;
-  };
+    HasEllipsis : 1,
+    : NumPadBits,
+    /// The number of elements contained.
+    NumElements : 16
+  );
 
 protected:
   union {
-    TypeReprBitfields TypeReprBits;
-    TupleTypeReprBitfields TupleTypeReprBits;
-  };
+    uint64_t OpaqueBits;
+    SWIFT_INLINE_BITS(TypeRepr);
+    SWIFT_INLINE_BITS(TupleTypeRepr);
+  } Bits;
 
   TypeRepr(TypeReprKind K) {
-    TypeReprBits.Kind = static_cast<unsigned>(K);
-    TypeReprBits.Invalid = false;
-    TypeReprBits.Warned = false;
+    Bits.OpaqueBits = 0;
+    Bits.TypeRepr.Kind = static_cast<unsigned>(K);
+    Bits.TypeRepr.Invalid = false;
+    Bits.TypeRepr.Warned = false;
   }
 
 private:
@@ -88,19 +90,19 @@
 
 public:
   TypeReprKind getKind() const {
-    return static_cast<TypeReprKind>(TypeReprBits.Kind);
+    return static_cast<TypeReprKind>(Bits.TypeRepr.Kind);
   }
 
   /// Is this type representation known to be invalid?
-  bool isInvalid() const { return TypeReprBits.Invalid; }
+  bool isInvalid() const { return Bits.TypeRepr.Invalid; }
 
   /// Note that this type representation describes an invalid type.
-  void setInvalid() { TypeReprBits.Invalid = true; }
+  void setInvalid() { Bits.TypeRepr.Invalid = true; }
 
   /// If a warning is produced about this type repr, keep track of that so we
   /// don't emit another one upon further reanalysis.
-  bool isWarnedAbout() const { return TypeReprBits.Warned; }
-  void setWarned() { TypeReprBits.Warned = true; }
+  bool isWarnedAbout() const { return Bits.TypeRepr.Warned; }
+  void setWarned() { Bits.TypeRepr.Warned = true; }
   
   /// Get the representative location for pointing at this type.
   SourceLoc getLoc() const;
@@ -594,7 +596,6 @@
   SourceLoc SecondNameLoc;
   SourceLoc UnderscoreLoc;
   SourceLoc ColonLoc;
-  SourceLoc InOutLoc;
   TypeRepr *Type;
   SourceLoc TrailingCommaLoc;
 
@@ -617,14 +618,14 @@
   SourceRange Parens;
   
   size_t numTrailingObjects(OverloadToken<TupleTypeReprElement>) const {
-    return TupleTypeReprBits.NumElements;
+    return Bits.TupleTypeRepr.NumElements;
   }
 
   TupleTypeRepr(ArrayRef<TupleTypeReprElement> Elements,
                 SourceRange Parens, SourceLoc Ellipsis, unsigned EllipsisIdx);
 
 public:
-  unsigned getNumElements() const { return TupleTypeReprBits.NumElements; }
+  unsigned getNumElements() const { return Bits.TupleTypeRepr.NumElements; }
   bool hasElementNames() const {
     for (auto &Element : getElements()) {
       if (Element.NameLoc.isValid()) {
@@ -636,7 +637,7 @@
 
   ArrayRef<TupleTypeReprElement> getElements() const {
     return { getTrailingObjects<TupleTypeReprElement>(),
-             TupleTypeReprBits.NumElements };
+             Bits.TupleTypeRepr.NumElements };
   }
 
   void getElementTypes(SmallVectorImpl<TypeRepr *> &Types) const {
@@ -678,7 +679,7 @@
   SourceRange getParens() const { return Parens; }
 
   bool hasEllipsis() const {
-    return TupleTypeReprBits.HasEllipsis;
+    return Bits.TupleTypeRepr.HasEllipsis;
   }
 
   SourceLoc getEllipsisLoc() const {
@@ -689,12 +690,12 @@
   unsigned getEllipsisIndex() const {
     return hasEllipsis() ?
       getTrailingObjects<SourceLocAndIdx>()[0].second :
-        TupleTypeReprBits.NumElements;
+        Bits.TupleTypeRepr.NumElements;
   }
 
   void removeEllipsis() {
     if (hasEllipsis()) {
-      TupleTypeReprBits.HasEllipsis = false;
+      Bits.TupleTypeRepr.HasEllipsis = false;
       getTrailingObjects<SourceLocAndIdx>()[0] = {
         SourceLoc(),
         getNumElements()
@@ -703,7 +704,7 @@
   }
 
   bool isParenType() const {
-    return TupleTypeReprBits.NumElements == 1 &&
+    return Bits.TupleTypeRepr.NumElements == 1 &&
            getElementNameLoc(0).isInvalid() &&
            !hasEllipsis();
   }
diff --git a/include/swift/AST/TypeReprNodes.def b/include/swift/AST/TypeReprNodes.def
index 0feaf9e..48d14c3 100644
--- a/include/swift/AST/TypeReprNodes.def
+++ b/include/swift/AST/TypeReprNodes.def
@@ -31,6 +31,10 @@
 #define ABSTRACT_TYPEREPR(Id, Parent)
 #endif
 
+#ifndef LAST_TYPEREPR
+#define LAST_TYPEREPR(Id)
+#endif
+
 TYPEREPR(Error, TypeRepr)
 TYPEREPR(Attributed, TypeRepr)
 
@@ -54,6 +58,8 @@
   TYPEREPR(Shared, SpecifierTypeRepr)
 TYPEREPR(Fixed, TypeRepr)
 TYPEREPR(SILBox, TypeRepr)
+LAST_TYPEREPR(SILBox)
 
 #undef ABSTRACT_TYPEREPR
 #undef TYPEREPR
+#undef LAST_TYPEREPR
diff --git a/include/swift/AST/Types.h b/include/swift/AST/Types.h
index 15b7ff1..d7167bc 100644
--- a/include/swift/AST/Types.h
+++ b/include/swift/AST/Types.h
@@ -28,6 +28,7 @@
 #include "swift/AST/Type.h"
 #include "swift/AST/TypeAlignments.h"
 #include "swift/Basic/ArrayRefView.h"
+#include "swift/Basic/InlineBitfield.h"
 #include "swift/Basic/UUID.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMapInfo.h"
@@ -74,10 +75,13 @@
 
   enum class TypeKind : uint8_t {
 #define TYPE(id, parent) id,
+#define LAST_TYPE(id) Last_Type = id,
 #define TYPE_RANGE(Id, FirstId, LastId) \
   First_##Id##Type = FirstId, Last_##Id##Type = LastId,
 #include "swift/AST/TypeNodes.def"
   };
+  enum : unsigned { NumTypeKindBits =
+    countBitsUsed(static_cast<unsigned>(TypeKind::Last_Type)) };
   
 /// Various properties of types that are primarily defined recursively
 /// on structural types.
@@ -243,10 +247,6 @@
 };
 using TypeMatchOptions = OptionSet<TypeMatchFlags>;
 
-#define NUMBITS(E, V) \
-  enum { Num##E##Bits = V }; \
-  static_assert(Num##E##Bits <= 64, "fits in a uint64_t")
-
 /// TypeBase - Base class for all types in Swift.
 class alignas(1 << TypeAlignInBits) TypeBase {
   
@@ -259,13 +259,13 @@
   /// form of a non-canonical type is requested.
   llvm::PointerUnion<TypeBase *, const ASTContext *> CanonicalType;
 
-  struct TypeBaseBitfields {
+  SWIFT_INLINE_BITFIELD_BASE(TypeBase, bitmax(NumTypeKindBits,8) +
+                             RecursiveTypeProperties::BitWidth,
     /// Kind - The discriminator that indicates what subclass of type this is.
-    const TypeKind Kind; // Naturally sized for speed (it only needs 6 bits).
+    Kind : bitmax(NumTypeKindBits,8),
 
-    unsigned Properties : RecursiveTypeProperties::BitWidth;
-  };
-  NUMBITS(TypeBase, RecursiveTypeProperties::BitWidth + sizeof(TypeKind) * 8 );
+    Properties : RecursiveTypeProperties::BitWidth
+  );
 
   /// Returns true if the given type is a sugared type.
   ///
@@ -277,96 +277,118 @@
   }
 
 protected:
-  struct ErrorTypeBitfields {
-    unsigned : NumTypeBaseBits;
-
+  SWIFT_INLINE_BITFIELD(ErrorType, TypeBase, 1,
     /// Whether there is an original type.
-    unsigned HasOriginalType : 1;
-  };
-  NUMBITS(ErrorType, NumTypeBaseBits + 1);
+    HasOriginalType : 1
+  );
 
-  struct AnyFunctionTypeBitfields {
-    unsigned : NumTypeBaseBits;
+  enum { NumFlagBits = 5 };
+  SWIFT_INLINE_BITFIELD(ParenType, TypeBase, NumFlagBits,
+    /// Whether there is an original type.
+    Flags : NumFlagBits
+  );
 
+  enum { NumAFTExtInfoBits = 7 };
+  SWIFT_INLINE_BITFIELD_FULL(AnyFunctionType, TypeBase, NumAFTExtInfoBits+16,
     /// Extra information which affects how the function is called, like
     /// regparm and the calling convention.
-    enum { NumExtInfoBits = 7 };
-    unsigned ExtInfo : NumExtInfoBits;
-  };
-  NUMBITS(AnyFunctionType, NumTypeBaseBits + 7);
+    ExtInfo : NumAFTExtInfoBits,
 
-  struct ArchetypeTypeBitfields {
-    unsigned : NumTypeBaseBits;
+    : NumPadBits,
+    NumParams : 16
+  );
 
-    unsigned ExpandedNestedTypes : 1;
-    unsigned HasSuperclass : 1;
-    unsigned HasLayoutConstraint : 1;
-    unsigned NumProtocols : 16;
-  };
-  NUMBITS(ArchetypeType, NumTypeBaseBits + 19);
+  SWIFT_INLINE_BITFIELD_FULL(ArchetypeType, TypeBase, 1+1+1+16,
+    ExpandedNestedTypes : 1,
+    HasSuperclass : 1,
+    HasLayoutConstraint : 1,
+    : NumPadBits,
+    NumProtocols : 16
+  );
 
-  struct TypeVariableTypeBitfields {
-    unsigned : NumTypeBaseBits;
-
+  SWIFT_INLINE_BITFIELD_FULL(TypeVariableType, TypeBase, 64-NumTypeBaseBits,
     /// \brief The unique number assigned to this type variable.
-    uint64_t ID : 64 - NumTypeBaseBits;
-  };
-  NUMBITS(TypeVariableType, 64);
+    ID : 32 - NumTypeBaseBits,
 
-  struct SILFunctionTypeBitfields {
-    unsigned : NumTypeBaseBits;
-    enum { NumExtInfoBits = 6 };
-    unsigned ExtInfo : NumExtInfoBits;
-    unsigned CalleeConvention : 3;
-    unsigned HasErrorResult : 1;
-    unsigned CoroutineKind : 2;
-  };
-  NUMBITS(SILFunctionType, NumTypeBaseBits + 12);
+    /// Type variable options.
+    Options : 3,
 
-  struct AnyMetatypeTypeBitfields {
-    unsigned : NumTypeBaseBits;
+    ///  Index into the list of type variables, as used by the
+    ///  constraint graph.
+    GraphIndex : 29
+  );
+
+  enum { NumSILExtInfoBits = 6 };
+  SWIFT_INLINE_BITFIELD(SILFunctionType, TypeBase, NumSILExtInfoBits+3+1+2,
+    ExtInfo : NumSILExtInfoBits,
+    CalleeConvention : 3,
+    HasErrorResult : 1,
+    CoroutineKind : 2
+  );
+
+  SWIFT_INLINE_BITFIELD_FULL(SILBoxType, TypeBase, 32,
+    : NumPadBits,
+    NumGenericArgs : 32
+  );
+
+  SWIFT_INLINE_BITFIELD(AnyMetatypeType, TypeBase, 2,
     /// The representation of the metatype.
     ///
     /// Zero indicates that no representation has been set; otherwise,
     /// the value is the representation + 1
-    unsigned Representation : 2;
-  };
-  NUMBITS(AnyMetatypeType, NumTypeBaseBits + 2);
+    Representation : 2
+  );
 
-  struct ProtocolCompositionTypeBitfields {
-    unsigned : NumTypeBaseBits;
+  SWIFT_INLINE_BITFIELD_FULL(ProtocolCompositionType, TypeBase, 1+32,
     /// Whether we have an explicitly-stated class constraint not
     /// implied by any of our members.
-    unsigned HasExplicitAnyObject : 1;
-  };
-  NUMBITS(ProtocolCompositionType, NumTypeBaseBits + 1);
+    HasExplicitAnyObject : 1,
 
-  struct TupleTypeBitfields {
-    unsigned : NumTypeBaseBits;
-    
+    : NumPadBits,
+
+    /// The number of protocols being composed.
+    Count : 32
+  );
+
+  SWIFT_INLINE_BITFIELD_FULL(TupleType, TypeBase, 1+32,
     /// Whether an element of the tuple is inout.
-    unsigned HasInOutElement : 1;
-  };
-  NUMBITS(TupleType, NumTypeBaseBits + 1);
+    HasInOutElement : 1,
 
-#undef NUMBITS
+    : NumPadBits,
+
+    /// The number of elements of the tuple.
+    Count : 32
+  );
+
+  SWIFT_INLINE_BITFIELD_FULL(BoundGenericType, TypeBase, 32,
+    : NumPadBits,
+
+    /// The number of generic arguments.
+    GenericArgCount : 32
+  );
+
   union {
-    TypeBaseBitfields TypeBaseBits;
-    ErrorTypeBitfields ErrorTypeBits;
-    AnyFunctionTypeBitfields AnyFunctionTypeBits;
-    TypeVariableTypeBitfields TypeVariableTypeBits;
-    ArchetypeTypeBitfields ArchetypeTypeBits;
-    SILFunctionTypeBitfields SILFunctionTypeBits;
-    AnyMetatypeTypeBitfields AnyMetatypeTypeBits;
-    ProtocolCompositionTypeBitfields ProtocolCompositionTypeBits;
-    TupleTypeBitfields TupleTypeBits;
-  };
+    uint64_t OpaqueBits;
+    SWIFT_INLINE_BITS(TypeBase);
+    SWIFT_INLINE_BITS(ErrorType);
+    SWIFT_INLINE_BITS(ParenType);
+    SWIFT_INLINE_BITS(AnyFunctionType);
+    SWIFT_INLINE_BITS(TypeVariableType);
+    SWIFT_INLINE_BITS(ArchetypeType);
+    SWIFT_INLINE_BITS(SILFunctionType);
+    SWIFT_INLINE_BITS(SILBoxType);
+    SWIFT_INLINE_BITS(AnyMetatypeType);
+    SWIFT_INLINE_BITS(ProtocolCompositionType);
+    SWIFT_INLINE_BITS(TupleType);
+    SWIFT_INLINE_BITS(BoundGenericType);
+  } Bits;
 
 protected:
   TypeBase(TypeKind kind, const ASTContext *CanTypeCtx,
            RecursiveTypeProperties properties)
     : CanonicalType((TypeBase*)nullptr) {
-    *const_cast<TypeKind *>(&TypeBaseBits.Kind) = kind;
+    Bits.OpaqueBits = 0;
+    Bits.TypeBase.Kind = static_cast<unsigned>(kind);
     // If this type is canonical, switch the CanonicalType union to ASTContext.
     if (CanTypeCtx)
       CanonicalType = CanTypeCtx;
@@ -374,13 +396,13 @@
   }
 
   void setRecursiveProperties(RecursiveTypeProperties properties) {
-    TypeBaseBits.Properties = properties.getBits();
-    assert(TypeBaseBits.Properties == properties.getBits() && "Bits dropped!");
+    Bits.TypeBase.Properties = properties.getBits();
+    assert(Bits.TypeBase.Properties == properties.getBits() && "Bits dropped!");
   }
 
 public:
   /// getKind - Return what kind of type this is.
-  TypeKind getKind() const { return TypeBaseBits.Kind; }
+  TypeKind getKind() const { return static_cast<TypeKind>(Bits.TypeBase.Kind); }
 
   /// isCanonical - Return true if this is a canonical type.
   bool isCanonical() const { return CanonicalType.is<const ASTContext *>(); }
@@ -388,10 +410,20 @@
   /// hasCanonicalTypeComputed - Return true if we've already computed a
   /// canonical version of this type.
   bool hasCanonicalTypeComputed() const { return !CanonicalType.isNull(); }
-  
+
+private:
+  void computeCanonicalType();
+
+public:
   /// getCanonicalType - Return the canonical version of this type, which has
   /// sugar from all levels stripped off.
-  CanType getCanonicalType();
+  CanType getCanonicalType() {
+    if (isCanonical())
+      return CanType(this);
+    if (!hasCanonicalTypeComputed())
+      computeCanonicalType();
+    return CanType(CanonicalType.get<TypeBase*>());
+  }
 
   /// getCanonicalType - Stronger canonicalization which folds away equivalent
   /// associated types, or type parameters that have been made concrete.
@@ -444,7 +476,7 @@
   /// getRecursiveProperties - Returns the properties defined on the
   /// structure of this type.
   RecursiveTypeProperties getRecursiveProperties() const {
-    return RecursiveTypeProperties(TypeBaseBits.Properties);
+    return RecursiveTypeProperties(Bits.TypeBase.Properties);
   }
 
   /// hasReferenceSemantics() - Do objects of this type have reference
@@ -1006,7 +1038,7 @@
 /// is produced when parsing types and when name binding type aliases, and is
 /// installed in declaration that use these erroneous types.  All uses of a
 /// declaration of invalid type should be ignored and not re-diagnosed.
-class ErrorType : public TypeBase {
+class ErrorType final : public TypeBase {
   friend class ASTContext;
   // The Error type is always canonical.
   ErrorType(ASTContext &C, Type originalType,
@@ -1014,10 +1046,10 @@
       : TypeBase(TypeKind::Error, &C, properties) {
     assert(properties.hasError());
     if (originalType) {
-      ErrorTypeBits.HasOriginalType = true;
+      Bits.ErrorType.HasOriginalType = true;
       *reinterpret_cast<Type *>(this + 1) = originalType;
     } else {
-      ErrorTypeBits.HasOriginalType = false;
+      Bits.ErrorType.HasOriginalType = false;
     }
   }
 
@@ -1031,7 +1063,7 @@
   /// Retrieve the original type that this error type replaces, or none if
   /// there is no such type.
   Type getOriginalType() const {
-    if (ErrorTypeBits.HasOriginalType)
+    if (Bits.ErrorType.HasOriginalType)
       return *reinterpret_cast<const Type *>(this + 1);
 
     return Type();
@@ -1415,6 +1447,9 @@
 
 public:
   ParameterTypeFlags() = default;
+  static ParameterTypeFlags fromRaw(uint8_t raw) {
+    return ParameterTypeFlags(OptionSet<ParameterFlags>(raw));
+  }
 
   ParameterTypeFlags(bool variadic, bool autoclosure, bool escaping, bool inOut, bool shared)
       : value((variadic ? Variadic : 0) |
@@ -1465,7 +1500,6 @@
 /// ParenType - A paren type is a type that's been written in parentheses.
 class ParenType : public TypeBase {
   Type UnderlyingType;
-  ParameterTypeFlags parameterFlags;
 
   friend class ASTContext;
   
@@ -1482,7 +1516,9 @@
   TypeBase *getSinglyDesugaredType();
 
   /// Get the parameter flags
-  ParameterTypeFlags getParameterFlags() const { return parameterFlags; }
+  ParameterTypeFlags getParameterFlags() const {
+    return ParameterTypeFlags::fromRaw(Bits.ParenType.Flags);
+  }
 
   // Implement isa/cast/dyncast/etc.
   static bool classof(const TypeBase *T) {
@@ -1556,8 +1592,9 @@
 /// TupleType - A tuple is a parenthesized list of types where each name has an
 /// optional name.
 ///
-class TupleType : public TypeBase, public llvm::FoldingSetNode {
-  const ArrayRef<TupleTypeElt> Elements;
+class TupleType final : public TypeBase, public llvm::FoldingSetNode,
+    private llvm::TrailingObjects<TupleType, TupleTypeElt> {
+  friend TrailingObjects;
   
 public:
   /// get - Return the uniqued tuple type with the specified elements.
@@ -1569,16 +1606,20 @@
   /// getEmpty - Return the empty tuple type '()'.
   static CanTypeWrapper<TupleType> getEmpty(const ASTContext &C);
 
-  /// getFields - Return the fields of this tuple.
-  ArrayRef<TupleTypeElt> getElements() const { return Elements; }
+  unsigned getNumElements() const { return Bits.TupleType.Count; }
 
-  unsigned getNumElements() const { return Elements.size(); }
+  /// getElements - Return the elements of this tuple.
+  ArrayRef<TupleTypeElt> getElements() const {
+    return {getTrailingObjects<TupleTypeElt>(), getNumElements()};
+  }
 
-  const TupleTypeElt &getElement(unsigned i) const { return Elements[i]; }
+  const TupleTypeElt &getElement(unsigned i) const {
+    return getTrailingObjects<TupleTypeElt>()[i];
+  }
 
   /// getElementType - Return the type of the specified element.
   Type getElementType(unsigned ElementNo) const {
-    return Elements[ElementNo].getType();
+    return getTrailingObjects<TupleTypeElt>()[ElementNo].getType();
   }
 
   TupleEltTypeArrayRef getElementTypes() const {
@@ -1601,7 +1642,7 @@
   
   /// Returns true if this tuple has inout elements.
   bool hasInOutElement() const {
-    return static_cast<bool>(TupleTypeBits.HasInOutElement);
+    return static_cast<bool>(Bits.TupleType.HasInOutElement);
   }
   
   // Implement isa/cast/dyncast/etc.
@@ -1610,7 +1651,7 @@
   }
 
   void Profile(llvm::FoldingSetNodeID &ID) {
-    Profile(ID, Elements);
+    Profile(ID, getElements());
   }
   static void Profile(llvm::FoldingSetNodeID &ID, 
                       ArrayRef<TupleTypeElt> Elements);
@@ -1619,8 +1660,11 @@
   TupleType(ArrayRef<TupleTypeElt> elements, const ASTContext *CanCtx,
             RecursiveTypeProperties properties,
             bool hasInOut)
-     : TypeBase(TypeKind::Tuple, CanCtx, properties), Elements(elements) {
-     TupleTypeBits.HasInOutElement = hasInOut;
+     : TypeBase(TypeKind::Tuple, CanCtx, properties) {
+     Bits.TupleType.HasInOutElement = hasInOut;
+     Bits.TupleType.Count = elements.size();
+     std::uninitialized_copy(elements.begin(), elements.end(),
+                             getTrailingObjects<TupleTypeElt>());
   }
 };
 BEGIN_CAN_TYPE_WRAPPER(TupleType, Type)
@@ -1691,8 +1735,12 @@
   /// \brief The type of the parent, in which this type is nested.
   Type Parent;
   
-  ArrayRef<Type> GenericArgs;
-  
+  /// Retrieve the intrusive pointer storage from the subtype
+  const Type *getTrailingObjectsPointer() const;
+  Type *getTrailingObjectsPointer() {
+    const BoundGenericType *temp = this;
+    return const_cast<Type *>(temp->getTrailingObjectsPointer());
+  }
 
 protected:
   BoundGenericType(TypeKind theKind, NominalTypeDecl *theDecl, Type parent,
@@ -1717,10 +1765,12 @@
   Type getParent() const { return Parent; }
 
   /// Retrieve the set of generic arguments provided at this level.
-  ArrayRef<Type> getGenericArgs() const { return GenericArgs; }
+  ArrayRef<Type> getGenericArgs() const {
+    return {getTrailingObjectsPointer(), Bits.BoundGenericType.GenericArgCount};
+  }
 
   void Profile(llvm::FoldingSetNodeID &ID) {
-    Profile(ID, TheDecl, Parent, GenericArgs);
+    Profile(ID, TheDecl, Parent, getGenericArgs());
   }
   static void Profile(llvm::FoldingSetNodeID &ID, NominalTypeDecl *TheDecl,
                       Type Parent, ArrayRef<Type> GenericArgs);
@@ -1741,7 +1791,10 @@
 
 /// BoundGenericClassType - A subclass of BoundGenericType for the case
 /// when the nominal type is a generic class type.
-class BoundGenericClassType : public BoundGenericType {
+class BoundGenericClassType final : public BoundGenericType,
+    private llvm::TrailingObjects<BoundGenericClassType, Type> {
+  friend TrailingObjects;
+
 private:
   BoundGenericClassType(ClassDecl *theDecl, Type parent,
                         ArrayRef<Type> genericArgs, const ASTContext *context,
@@ -1772,7 +1825,10 @@
 
 /// BoundGenericEnumType - A subclass of BoundGenericType for the case
 /// when the nominal type is a generic enum type.
-class BoundGenericEnumType : public BoundGenericType {
+class BoundGenericEnumType final : public BoundGenericType,
+    private llvm::TrailingObjects<BoundGenericEnumType, Type> {
+  friend TrailingObjects;
+
 private:
   BoundGenericEnumType(EnumDecl *theDecl, Type parent,
                        ArrayRef<Type> genericArgs, const ASTContext *context,
@@ -1803,7 +1859,10 @@
 
 /// BoundGenericStructType - A subclass of BoundGenericType for the case
 /// when the nominal type is a generic struct type.
-class BoundGenericStructType : public BoundGenericType {
+class BoundGenericStructType final : public BoundGenericType,
+    private llvm::TrailingObjects<BoundGenericStructType, Type> {
+  friend TrailingObjects;
+
 private:
   BoundGenericStructType(StructDecl *theDecl, Type parent,
                          ArrayRef<Type> genericArgs, const ASTContext *context,
@@ -2004,7 +2063,7 @@
   ///
   /// Only SIL metatype types have a representation.
   bool hasRepresentation() const {
-    return AnyMetatypeTypeBits.Representation > 0;
+    return Bits.AnyMetatypeType.Representation > 0;
   }
   
   /// Retrieve the metatype representation.
@@ -2013,10 +2072,10 @@
   /// metatypes can be lowered away to empty types in IR, unless a
   /// metatype value is required at an abstraction level.
   MetatypeRepresentation getRepresentation() const {
-    assert(AnyMetatypeTypeBits.Representation &&
+    assert(Bits.AnyMetatypeType.Representation &&
            "metatype has no representation");
     return static_cast<MetatypeRepresentation>(
-             AnyMetatypeTypeBits.Representation - 1);
+             Bits.AnyMetatypeType.Representation - 1);
   }
 
   // Implement isa/cast/dyncast/etc.
@@ -2324,7 +2383,6 @@
 class AnyFunctionType : public TypeBase {
   const Type Input;
   const Type Output;
-  const unsigned NumParams;
   
 public:
   using Representation = FunctionTypeRepresentation;
@@ -2536,13 +2594,13 @@
   AnyFunctionType(TypeKind Kind, const ASTContext *CanTypeContext,
                   Type Input, Type Output, RecursiveTypeProperties properties,
                   unsigned NumParams, const ExtInfo &Info)
-  : TypeBase(Kind, CanTypeContext, properties), Input(Input), Output(Output),
-    NumParams(NumParams) {
-    AnyFunctionTypeBits.ExtInfo = Info.Bits;
+  : TypeBase(Kind, CanTypeContext, properties), Input(Input), Output(Output) {
+    Bits.AnyFunctionType.ExtInfo = Info.Bits;
+    Bits.AnyFunctionType.NumParams = NumParams;
+    assert(Bits.AnyFunctionType.NumParams == NumParams && "Params dropped!");
     // The use of both assert() and static_assert() is intentional.
-    assert(AnyFunctionTypeBits.ExtInfo == Info.Bits && "Bits were dropped!");
-    static_assert(ExtInfo::NumMaskBits ==
-                  AnyFunctionTypeBitfields::NumExtInfoBits,
+    assert(Bits.AnyFunctionType.ExtInfo == Info.Bits && "Bits were dropped!");
+    static_assert(ExtInfo::NumMaskBits == NumAFTExtInfoBits,
                  "ExtInfo and AnyFunctionTypeBitfields must agree on bit size");
   }
 
@@ -2565,12 +2623,12 @@
   Type getInput() const { return Input; }
   Type getResult() const { return Output; }
   ArrayRef<AnyFunctionType::Param> getParams() const;
-  unsigned getNumParams() const { return NumParams; }
+  unsigned getNumParams() const { return Bits.AnyFunctionType.NumParams; }
 
   GenericSignature *getOptGenericSignature() const;
   
   ExtInfo getExtInfo() const {
-    return ExtInfo(AnyFunctionTypeBits.ExtInfo);
+    return ExtInfo(Bits.AnyFunctionType.ExtInfo);
   }
 
   /// \brief Get the representation of the function type.
@@ -2919,9 +2977,9 @@
   /// guarantees its validity for the entirety of the call.
   Direct_Guaranteed,
 };
-// Check that the enum values fit inside SILFunctionTypeBits.
+// Check that the enum values fit inside Bits.SILFunctionType.
 static_assert(unsigned(ParameterConvention::Direct_Guaranteed) < (1<<3),
-              "fits in SILFunctionTypeBits");
+              "fits in Bits.SILFunctionType and SILParameterInfo");
 
 // Does this parameter convention require indirect storage? This reflects a
 // SILFunctionType's formal (immutable) conventions, as opposed to the transient
@@ -2981,20 +3039,19 @@
 
 /// A parameter type and the rules for passing it.
 class SILParameterInfo {
-  CanType Ty;
-  ParameterConvention Convention;
+  llvm::PointerIntPair<CanType, 3, ParameterConvention> TypeAndConvention;
 public:
-  SILParameterInfo() : Ty(), Convention((ParameterConvention)0) {}
+  SILParameterInfo() = default;//: Ty(), Convention((ParameterConvention)0) {}
   SILParameterInfo(CanType type, ParameterConvention conv)
-    : Ty(type), Convention(conv) {
+    : TypeAndConvention(type, conv) {
     assert(type->isLegalSILType() && "SILParameterInfo has illegal SIL type");
   }
 
   CanType getType() const {
-    return Ty;
+    return TypeAndConvention.getPointer();
   }
   ParameterConvention getConvention() const {
-    return Convention;
+    return TypeAndConvention.getInt();
   }
   // Does this parameter convention require indirect storage? This reflects a
   // SILFunctionType's formal (immutable) conventions, as opposed to the
@@ -3055,8 +3112,8 @@
   }
 
   void profile(llvm::FoldingSetNodeID &id) {
-    id.AddPointer(Ty.getPointer());
-    id.AddInteger((unsigned)Convention);
+    id.AddPointer(getType().getPointer());
+    id.AddInteger((unsigned)getConvention());
   }
 
   void dump() const;
@@ -3070,7 +3127,7 @@
   }
 
   bool operator==(SILParameterInfo rhs) const {
-    return Ty == rhs.Ty && Convention == rhs.Convention;
+    return getType() == rhs.getType() && getConvention() == rhs.getConvention();
   }
   bool operator!=(SILParameterInfo rhs) const {
     return !(*this == rhs);
@@ -3476,6 +3533,14 @@
                                 const ASTContext &ctx,
               Optional<ProtocolConformanceRef> witnessMethodConformance = None);
 
+  /// Return a structurally-identical function type with a slightly tweaked
+  /// ExtInfo.
+  CanSILFunctionType getWithExtInfo(ExtInfo ext);
+
+  /// Return a structurally-identical function type with a slightly tweaked
+  /// representation.
+  CanSILFunctionType getWithRepresentation(Representation repr);
+
   /// Given that this function type uses a C-language convention, return its
   /// formal semantic result type.
   ///
@@ -3490,7 +3555,7 @@
   /// Return the convention under which the callee is passed, if this
   /// is a thick non-block callee.
   ParameterConvention getCalleeConvention() const {
-    return ParameterConvention(SILFunctionTypeBits.CalleeConvention);
+    return ParameterConvention(Bits.SILFunctionType.CalleeConvention);
   }
   bool isCalleeConsumed() const {
     return getCalleeConvention() == ParameterConvention::Direct_Owned;
@@ -3507,7 +3572,7 @@
     return getCoroutineKind() != SILCoroutineKind::None;
   }
   SILCoroutineKind getCoroutineKind() const {
-    return SILCoroutineKind(SILFunctionTypeBits.CoroutineKind);
+    return SILCoroutineKind(Bits.SILFunctionType.CoroutineKind);
   }
 
   /// Return the array of all the yields.
@@ -3609,7 +3674,7 @@
 
   /// Does this function have a blessed Swift-native error result?
   bool hasErrorResult() const {
-    return SILFunctionTypeBits.HasErrorResult;
+    return Bits.SILFunctionType.HasErrorResult;
   }
   SILResultInfo getErrorResult() const {
     return const_cast<SILFunctionType*>(this)->getMutableErrorResult();
@@ -3665,7 +3730,7 @@
     return WitnessMethodConformance;
   }
 
-  ExtInfo getExtInfo() const { return ExtInfo(SILFunctionTypeBits.ExtInfo); }
+  ExtInfo getExtInfo() const { return ExtInfo(Bits.SILFunctionType.ExtInfo); }
 
   /// \brief Returns the language-level calling convention of the function.
   Language getLanguage() const {
@@ -3773,7 +3838,6 @@
   friend TrailingObjects;
   
   SILLayout *Layout;
-  unsigned NumGenericArgs;
 
   static RecursiveTypeProperties
   getRecursivePropertiesFromSubstitutions(SubstitutionList Args);
@@ -3789,7 +3853,7 @@
   SILLayout *getLayout() const { return Layout; }
   SubstitutionList getGenericArgs() const {
     return llvm::makeArrayRef(getTrailingObjects<Substitution>(),
-                              NumGenericArgs);
+                              Bits.SILBoxType.NumGenericArgs);
   }
   
   // In SILType.h:
@@ -4058,8 +4122,10 @@
 /// inheritance) protocol list. If the sorted, minimized list is a single
 /// protocol, then the canonical type is that protocol type. Otherwise, it is
 /// a composition of the protocols in that list.
-class ProtocolCompositionType : public TypeBase, public llvm::FoldingSetNode {
-  ArrayRef<Type> Members;
+class ProtocolCompositionType final : public TypeBase,
+    public llvm::FoldingSetNode,
+    private llvm::TrailingObjects<ProtocolCompositionType, Type> {
+  friend TrailingObjects;
   
 public:
   /// \brief Retrieve an instance of a protocol composition type with the
@@ -4080,10 +4146,12 @@
   /// Note that the list of members is not sufficient to uniquely identify
   /// a protocol composition type; you also have to look at
   /// hasExplicitAnyObject().
-  ArrayRef<Type> getMembers() const { return Members; }
+  ArrayRef<Type> getMembers() const {
+    return {getTrailingObjects<Type>(), Bits.ProtocolCompositionType.Count};
+  }
 
   void Profile(llvm::FoldingSetNodeID &ID) {
-    Profile(ID, Members, hasExplicitAnyObject());
+    Profile(ID, getMembers(), hasExplicitAnyObject());
   }
   static void Profile(llvm::FoldingSetNodeID &ID,
                       ArrayRef<Type> Members,
@@ -4096,7 +4164,7 @@
 
   /// True if the class requirement is stated directly via '& AnyObject'.
   bool hasExplicitAnyObject() {
-    return ProtocolCompositionTypeBits.HasExplicitAnyObject;
+    return Bits.ProtocolCompositionType.HasExplicitAnyObject;
   }
 
   // Implement isa/cast/dyncast/etc.
@@ -4112,10 +4180,11 @@
   ProtocolCompositionType(const ASTContext *ctx, ArrayRef<Type> members,
                           bool hasExplicitAnyObject,
                           RecursiveTypeProperties properties)
-    : TypeBase(TypeKind::ProtocolComposition, /*Context=*/ctx,
-               properties),
-      Members(members) {
-    ProtocolCompositionTypeBits.HasExplicitAnyObject = hasExplicitAnyObject;
+    : TypeBase(TypeKind::ProtocolComposition, /*Context=*/ctx, properties) {
+    Bits.ProtocolCompositionType.HasExplicitAnyObject = hasExplicitAnyObject;
+    Bits.ProtocolCompositionType.Count = members.size();
+    std::uninitialized_copy(members.begin(), members.end(),
+                            getTrailingObjects<Type>());
   }
 };
 BEGIN_CAN_TYPE_WRAPPER(ProtocolCompositionType, Type)
@@ -4226,15 +4295,15 @@
   friend TrailingObjects;
 
   size_t numTrailingObjects(OverloadToken<ProtocolDecl *>) const {
-    return ArchetypeTypeBits.NumProtocols;
+    return Bits.ArchetypeType.NumProtocols;
   }
 
   size_t numTrailingObjects(OverloadToken<Type>) const {
-    return ArchetypeTypeBits.HasSuperclass ? 1 : 0;
+    return Bits.ArchetypeType.HasSuperclass ? 1 : 0;
   }
 
   size_t numTrailingObjects(OverloadToken<LayoutConstraint>) const {
-    return ArchetypeTypeBits.HasLayoutConstraint ? 1 : 0;
+    return Bits.ArchetypeType.HasLayoutConstraint ? 1 : 0;
   }
 
   size_t numTrailingObjects(OverloadToken<UUID>) const {
@@ -4326,7 +4395,7 @@
   /// type shall conform.
   ArrayRef<ProtocolDecl *> getConformsTo() const {
     return { getTrailingObjects<ProtocolDecl *>(),
-             ArchetypeTypeBits.NumProtocols };
+             Bits.ArchetypeType.NumProtocols };
   }
   
   /// requiresClass - True if the type can only be substituted with class types.
@@ -4336,14 +4405,14 @@
 
   /// \brief Retrieve the superclass of this type, if such a requirement exists.
   Type getSuperclass() const {
-    if (!ArchetypeTypeBits.HasSuperclass) return Type();
+    if (!Bits.ArchetypeType.HasSuperclass) return Type();
 
     return *getTrailingObjects<Type>();
   }
 
   /// \brief Retrieve the layout constraint of this type, if such a requirement exists.
   LayoutConstraint getLayoutConstraint() const {
-    if (!ArchetypeTypeBits.HasLayoutConstraint) return LayoutConstraint();
+    if (!Bits.ArchetypeType.HasLayoutConstraint) return LayoutConstraint();
 
     return *getTrailingObjects<LayoutConstraint>();
   }
@@ -4712,7 +4781,7 @@
   TypeVariableType(const ASTContext &C, unsigned ID)
     : TypeBase(TypeKind::TypeVariable, &C,
                RecursiveTypeProperties::HasTypeVariable) {
-    TypeVariableTypeBits.ID = ID;
+    Bits.TypeVariableType.ID = ID;
   }
 
   class Implementation;
@@ -4748,7 +4817,7 @@
     return reinterpret_cast<Implementation *>(this + 1);
   }
 
-  unsigned getID() const { return TypeVariableTypeBits.ID; }
+  unsigned getID() const { return Bits.TypeVariableType.ID; }
 
   // Implement isa/cast/dyncast/etc.
   static bool classof(const TypeBase *T) {
@@ -5026,6 +5095,27 @@
   bool inOut = paramTy->is<InOutType>();
   return {isVariadic, autoclosure, escaping, inOut, isShared};
 }
+
+inline const Type *BoundGenericType::getTrailingObjectsPointer() const {
+  if (auto ty = dyn_cast<BoundGenericStructType>(this))
+    return ty->getTrailingObjects<Type>();
+  if (auto ty = dyn_cast<BoundGenericEnumType>(this))
+    return ty->getTrailingObjects<Type>();
+  if (auto ty = dyn_cast<BoundGenericClassType>(this))
+    return ty->getTrailingObjects<Type>();
+  llvm_unreachable("Unhandled BoundGenericType!");
+}
+
+inline ArrayRef<AnyFunctionType::Param> AnyFunctionType::getParams() const {
+  switch (getKind()) {
+  case TypeKind::Function:
+    return cast<FunctionType>(this)->getParams();
+  case TypeKind::GenericFunction:
+    return cast<GenericFunctionType>(this)->getParams();
+  default:
+    llvm_unreachable("Undefined function type");
+  }
+}
   
 /// \brief If this is a method in a type or extension thereof, compute
 /// and return a parameter to be used for the 'self' argument.  The type of
diff --git a/include/swift/Basic/InlineBitfield.h b/include/swift/Basic/InlineBitfield.h
new file mode 100644
index 0000000..23acdfb
--- /dev/null
+++ b/include/swift/Basic/InlineBitfield.h
@@ -0,0 +1,160 @@
+//===--- InlineBitfield.h - Inline bitfield macros --------------*- C++ -*-===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2017 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+//
+//  This file provides macros to simplify inline/intrusive bitfield logic.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef SWIFT_INLINE_BITFIELD_H
+#define SWIFT_INLINE_BITFIELD_H
+
+#include "llvm/Support/Compiler.h"
+#include <cstdint>
+
+// Boilerplate namespace in case we add non-macros.
+namespace swift {
+
+/// NOTE: When passing the bit count to these macros, please do NOT precompute
+/// the total. Instead, sum the bit counts in field order. This makes visually
+/// verifying that all the fields are accounted for easier. For example:
+/// SWIFT_INLINE_BITFIELD(Foo, Bar, 1+3+7+2, w:1, x:3, y:7, z:2);
+
+/// Define a base bitfield for type 'T' with 'C' bits used.
+///
+/// Please note that the 'base' type does not need to be the root class in a
+/// hierarchy. If a superclass bitfield is full, then a subclass can start a new
+/// bitfield union for its subclasses to use.
+#define SWIFT_INLINE_BITFIELD_BASE(T, C, ...) \
+  LLVM_PACKED_START \
+  class T##Bitfield { \
+    friend class T; \
+    uint64_t __VA_ARGS__; \
+    uint64_t : 64 - (C); /* Pad and error if C > 64 */ \
+  }; \
+  LLVM_PACKED_END \
+  enum { Num##T##Bits = (C) }
+
+/// Define an bitfield for type 'T' with parent class 'U' and 'C' bits used.
+#define SWIFT_INLINE_BITFIELD(T, U, C, ...) \
+  LLVM_PACKED_START \
+  class T##Bitfield { \
+    friend class T; \
+    uint64_t : Num##U##Bits, __VA_ARGS__; \
+    uint64_t : 64 - (Num##U##Bits + (C)); /* Pad and error if C > 64 */ \
+  }; \
+  LLVM_PACKED_END \
+  enum { Num##T##Bits = Num##U##Bits + (C) }
+
+/// Define a full bitfield for type 'T' that uses all of the remaining bits in
+/// the inline bitfield.
+///
+/// For optimal code gen, place naturally sized fields at the end, with the
+/// largest naturally sized field at the very end. For example:
+///
+/// SWIFT_INLINE_BITFIELD_FULL(Foo, Bar, 1+8+16,
+///   flag : 1,
+///   : NumPadBits, // pad the center, not the end
+///   x : 8,
+///   y : 16
+/// );
+#define SWIFT_INLINE_BITFIELD_FULL(T, U, C, ...) \
+  LLVM_PACKED_START \
+  class T##Bitfield { \
+    friend class T; \
+    enum { NumPadBits = 64 - (Num##U##Bits + (C)) }; \
+    uint64_t : Num##U##Bits, __VA_ARGS__; \
+  }; \
+  LLVM_PACKED_END \
+  static_assert(sizeof(T##Bitfield) <= 8, "Bitfield overflow")
+
+/// Define an empty bitfield for type 'T'.
+#define SWIFT_INLINE_BITFIELD_EMPTY(T, U) \
+  enum { Num##T##Bits = Num##U##Bits }
+
+#define SWIFT_INLINE_BITS(T) T##Bitfield T
+
+// XXX/HACK: templated max() doesn't seem to work in a bitfield size context.
+constexpr unsigned bitmax(unsigned a, unsigned b) {
+  return a > b ? a : b;
+}
+
+constexpr unsigned countBitsUsed(uint64_t arg) {
+  // Is there a C++ "std::countLeadingZeros()"?
+  return (arg & 1ull << 63 ? 63 :
+          arg & 1ull << 62 ? 62 :
+          arg & 1ull << 61 ? 61 :
+          arg & 1ull << 60 ? 60 :
+          arg & 1ull << 59 ? 59 :
+          arg & 1ull << 58 ? 58 :
+          arg & 1ull << 57 ? 57 :
+          arg & 1ull << 56 ? 56 :
+          arg & 1ull << 55 ? 55 :
+          arg & 1ull << 54 ? 54 :
+          arg & 1ull << 53 ? 53 :
+          arg & 1ull << 52 ? 52 :
+          arg & 1ull << 51 ? 51 :
+          arg & 1ull << 50 ? 50 :
+          arg & 1ull << 49 ? 49 :
+          arg & 1ull << 48 ? 48 :
+          arg & 1ull << 47 ? 47 :
+          arg & 1ull << 46 ? 46 :
+          arg & 1ull << 45 ? 45 :
+          arg & 1ull << 44 ? 44 :
+          arg & 1ull << 43 ? 43 :
+          arg & 1ull << 42 ? 42 :
+          arg & 1ull << 41 ? 41 :
+          arg & 1ull << 40 ? 40 :
+          arg & 1ull << 39 ? 39 :
+          arg & 1ull << 38 ? 38 :
+          arg & 1ull << 37 ? 37 :
+          arg & 1ull << 36 ? 36 :
+          arg & 1ull << 35 ? 35 :
+          arg & 1ull << 34 ? 34 :
+          arg & 1ull << 33 ? 33 :
+          arg & 1ull << 32 ? 32 :
+          arg & 1ull << 31 ? 31 :
+          arg & 1ull << 30 ? 30 :
+          arg & 1ull << 29 ? 29 :
+          arg & 1ull << 28 ? 28 :
+          arg & 1ull << 27 ? 27 :
+          arg & 1ull << 26 ? 26 :
+          arg & 1ull << 25 ? 25 :
+          arg & 1ull << 24 ? 24 :
+          arg & 1ull << 23 ? 23 :
+          arg & 1ull << 22 ? 22 :
+          arg & 1ull << 21 ? 21 :
+          arg & 1ull << 20 ? 20 :
+          arg & 1ull << 19 ? 19 :
+          arg & 1ull << 18 ? 18 :
+          arg & 1ull << 17 ? 17 :
+          arg & 1ull << 16 ? 16 :
+          arg & 1ull << 15 ? 15 :
+          arg & 1ull << 14 ? 14 :
+          arg & 1ull << 13 ? 13 :
+          arg & 1ull << 12 ? 12 :
+          arg & 1ull << 11 ? 11 :
+          arg & 1ull << 10 ? 10 :
+          arg & 1ull << 9 ? 9 :
+          arg & 1ull << 8 ? 8 :
+          arg & 1ull << 7 ? 7 :
+          arg & 1ull << 6 ? 6 :
+          arg & 1ull << 5 ? 5 :
+          arg & 1ull << 4 ? 4 :
+          arg & 1ull << 3 ? 3 :
+          arg & 1ull << 2 ? 2 :
+          arg & 1ull << 1 ? 1 : 0
+      ) + 1;
+}
+
+} // end namespace swift
+
+#endif // SWIFT_INLINE_BITFIELD_H
diff --git a/include/swift/Basic/LangOptions.h b/include/swift/Basic/LangOptions.h
index 55a8d79..b3fb777 100644
--- a/include/swift/Basic/LangOptions.h
+++ b/include/swift/Basic/LangOptions.h
@@ -116,6 +116,10 @@
     /// expression.
     bool CodeCompleteInitsInPostfixExpr = false;
 
+    /// Whether to use heuristics to decide whether to show call-pattern
+    /// completions.
+    bool CodeCompleteCallPatternHeuristics = false;
+
     ///
     /// Flags for use by tests
     ///
@@ -134,9 +138,6 @@
     /// was not compiled with -enable-testing.
     bool EnableTestableAttrRequiresTestableModule = true;
 
-    /// Whether SE-0143: Conditional Conformances are enabled.
-    bool EnableConditionalConformances = false;
-
     ///
     /// Flags for developers
     ///
diff --git a/include/swift/Basic/OwnedString.h b/include/swift/Basic/OwnedString.h
index f059c9e..483fd67 100644
--- a/include/swift/Basic/OwnedString.h
+++ b/include/swift/Basic/OwnedString.h
@@ -52,7 +52,6 @@
   void initialize(const char* Data, size_t Length, StringOwnership Ownership) {
     this->Length = Length;
     this->Ownership = Ownership;
-    assert(Length >= 0 && "expected length to be non-negative");
     if (Ownership == StringOwnership::Copied && Data) {
       char *substring = static_cast<char *>(malloc(Length + 1));
       assert(substring && "expected successful malloc of copy");
diff --git a/include/swift/Demangling/DemangleNodes.def b/include/swift/Demangling/DemangleNodes.def
index d2aabf3..7269a4a 100644
--- a/include/swift/Demangling/DemangleNodes.def
+++ b/include/swift/Demangling/DemangleNodes.def
@@ -198,5 +198,6 @@
 NODE(OutlinedDestroy)
 NODE(OutlinedVariable)
 NODE(AssocTypePath)
+NODE(LabelList)
 #undef CONTEXT_NODE
 #undef NODE
diff --git a/include/swift/Demangling/Demangler.h b/include/swift/Demangling/Demangler.h
index ce28160..0fa8809 100644
--- a/include/swift/Demangling/Demangler.h
+++ b/include/swift/Demangling/Demangler.h
@@ -378,6 +378,9 @@
                                  NodePointer Child2);
   NodePointer createWithChildren(Node::Kind kind, NodePointer Child1,
                                  NodePointer Child2, NodePointer Child3);
+  NodePointer createWithChildren(Node::Kind kind, NodePointer Child1,
+                                 NodePointer Child2, NodePointer Child3,
+                                 NodePointer Child4);
   NodePointer createWithPoppedType(Node::Kind kind) {
     return createWithChild(kind, popNode(Node::Kind::Type));
   }
@@ -413,6 +416,7 @@
   NodePointer demanglePlainFunction();
   NodePointer popFunctionType(Node::Kind kind);
   NodePointer popFunctionParams(Node::Kind kind);
+  NodePointer popFunctionParamLabels(NodePointer FuncType);
   NodePointer popTuple();
   NodePointer popTypeList();
   NodePointer popProtocol();
@@ -460,6 +464,7 @@
   NodePointer demangleValueWitness();
 
   NodePointer demangleObjCTypeName();
+  NodePointer demangleTypeMangling();
 
   void dump();
 
diff --git a/include/swift/Frontend/Frontend.h b/include/swift/Frontend/Frontend.h
index 44e2a1d..6d29611 100644
--- a/include/swift/Frontend/Frontend.h
+++ b/include/swift/Frontend/Frontend.h
@@ -242,20 +242,6 @@
     return FrontendOpts.ModuleName;
   }
 
-  void addInputFilename(StringRef Filename) {
-    FrontendOpts.Inputs.addInputFilename(Filename);
-  }
-
-  /// Does not take ownership of \p Buf.
-  void addInputBuffer(llvm::MemoryBuffer *Buf) {
-    FrontendOpts.Inputs.addInputBuffer(Buf);
-  }
-
-  void setPrimaryInput(SelectedInput pi) {
-    FrontendOpts.Inputs.setPrimaryInput(pi);
-  }
-
-  void clearInputs() { FrontendOpts.Inputs.clearInputs(); }
 
   StringRef getOutputFilename() const {
     return FrontendOpts.getSingleOutputFilename();
@@ -307,7 +293,7 @@
   /// Return value includes the buffer so caller can keep it alive.
   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
   setUpInputForSILTool(StringRef inputFilename, StringRef moduleNameArg,
-                       bool alwaysSetModuleToMain,
+                       bool alwaysSetModuleToMain, bool bePrimary,
                        serialization::ExtendedValidationInfo &extendedInfo);
   bool hasSerializedAST() {
     return FrontendOpts.InputKind == InputFileKind::IFK_Swift_Library;
@@ -359,8 +345,6 @@
   void createSILModule();
   void setPrimarySourceFile(SourceFile *SF);
 
-  bool setUpForFileAt(unsigned i);
-
 public:
   SourceManager &getSourceMgr() { return SourceMgr; }
 
@@ -436,6 +420,46 @@
   /// \brief Returns true if there was an error during setup.
   bool setup(const CompilerInvocation &Invocation);
 
+private:
+  void setUpLLVMArguments();
+  void setUpDiagnosticOptions();
+  bool setUpModuleLoaders();
+  bool isInputSwift() {
+    return Invocation.getInputKind() == InputFileKind::IFK_Swift;
+  }
+  bool isInSILMode() {
+    return Invocation.getInputKind() == InputFileKind::IFK_SIL;
+  }
+
+  bool setUpInputs();
+  Optional<unsigned> setUpCodeCompletionBuffer();
+
+  /// Set up all state in the CompilerInstance to process the given input file.
+  /// Return true on error.
+  bool setUpForInput(const InputFile &input);
+
+  /// Find a buffer for a given input file and ensure it is recorded in
+  /// SourceMgr, PartialModules, or InputSourceCodeBufferIDs as appropriate.
+  /// Return the buffer ID if it is not already compiled, or None if so.
+  /// Set failed on failure.
+
+  Optional<unsigned> getRecordedBufferID(const InputFile &input, bool &failed);
+
+  /// Given an input file, return a buffer to use for its contents,
+  /// and a buffer for the corresponding module doc file if one exists.
+  /// On failure, return a null pointer for the first element of the returned
+  /// pair.
+  std::pair<std::unique_ptr<llvm::MemoryBuffer>,
+            std::unique_ptr<llvm::MemoryBuffer>>
+  getInputBufferAndModuleDocBufferIfPresent(const InputFile &input);
+
+  /// Try to open the module doc file corresponding to the input parameter.
+  /// Return None for error, nullptr if no such file exists, or the buffer if
+  /// one was found.
+  Optional<std::unique_ptr<llvm::MemoryBuffer>>
+  openModuleDoc(const InputFile &input);
+
+public:
   /// Parses and type-checks all input files.
   void performSema();
 
@@ -445,6 +469,13 @@
   ///
   void performParseOnly(bool EvaluateConditionals = false);
 
+private:
+  SourceFile *
+  createSourceFileForMainModule(SourceFileKind FileKind,
+                                SourceFile::ImplicitModuleImportKind ImportKind,
+                                Optional<unsigned> BufferID);
+
+public:
   /// Frees up the ASTContext and SILModule objects that this instance is
   /// holding on.
   void freeContextAndSIL();
@@ -469,7 +500,7 @@
   };
 
 private:
-  void createREPLFile(const ImplicitImports &implicitImports) const;
+  void createREPLFile(const ImplicitImports &implicitImports);
   std::unique_ptr<DelayedParsingCallbacks>
   computeDelayedParsingCallback(bool isPrimary);
 
diff --git a/include/swift/Frontend/FrontendOptions.h b/include/swift/Frontend/FrontendOptions.h
index 7681da8..876d57f 100644
--- a/include/swift/Frontend/FrontendOptions.h
+++ b/include/swift/Frontend/FrontendOptions.h
@@ -25,34 +25,6 @@
 
 namespace swift {
 
-class SelectedInput {
-public:
-  /// The index of the input, in either FrontendOptions::InputFilenames or
-  /// FrontendOptions::InputBuffers, depending on this SelectedInput's
-  /// InputKind.
-  unsigned Index;
-
-  enum class InputKind {
-    /// Denotes a file input, in FrontendOptions::InputFilenames
-    Filename,
-
-    /// Denotes a buffer input, in FrontendOptions::InputBuffers
-    Buffer,
-  };
-
-  /// The kind of input which this SelectedInput represents.
-  InputKind Kind;
-
-  SelectedInput(unsigned Index, InputKind Kind = InputKind::Filename)
-      : Index(Index), Kind(Kind) {}
-
-  /// \returns true if the SelectedInput's Kind is a filename
-  bool isFilename() const { return Kind == InputKind::Filename; }
-
-  /// \returns true if the SelectedInput's Kind is a buffer
-  bool isBuffer() const { return Kind == InputKind::Buffer; }
-};
-
 enum class InputFileKind {
   IFK_None,
   IFK_Swift,
@@ -62,64 +34,107 @@
   IFK_LLVM_IR
 };
 
+// Inputs may include buffers that override contents, and eventually should
+// always include a buffer.
+class InputFile {
+  std::string Filename;
+  bool IsPrimary;
+  /// Null if the contents are not overridden.
+  llvm::MemoryBuffer *Buffer;
+
+public:
+  /// Does not take ownership of \p buffer. Does take ownership of (copy) a
+  /// string.
+  InputFile(StringRef name, bool isPrimary,
+            llvm::MemoryBuffer *buffer = nullptr)
+      : Filename(name), IsPrimary(isPrimary), Buffer(buffer) {
+    assert(!name.empty());
+  }
+
+  bool isPrimary() const { return IsPrimary; }
+  llvm::MemoryBuffer *buffer() const { return Buffer; }
+  StringRef file() const {
+    assert(!Filename.empty());
+    return Filename;
+  }
+
+  /// Return Swift-standard file name from a buffer name set by
+  /// llvm::MemoryBuffer::getFileOrSTDIN, which uses "<stdin>" instead of "-".
+  static StringRef convertBufferNameFromLLVM_getFileOrSTDIN_toSwiftConventions(
+      StringRef filename) {
+    return filename.equals("<stdin>") ? "-" : filename;
+  }
+};
+
 /// Information about all the inputs to the frontend.
 class FrontendInputs {
   friend class ArgsToFrontendInputsConverter;
 
-private:
-  /// The names of input files to the frontend.
-  std::vector<std::string> InputFilenames;
-
-  /// Input buffers which may override the file contents of input files.
-  std::vector<llvm::MemoryBuffer *> InputBuffers;
-
-  /// The inputs for which output should be generated. If empty, output will
-  /// be generated for the whole module, in other words, whole-module mode.
-  /// Even if every input file is mentioned here, it is not the same as
-  /// whole-module mode.
-  std::vector<SelectedInput> PrimaryInputs;
+  std::vector<InputFile> AllFiles;
+  typedef llvm::StringMap<unsigned> InputFileMap;
+  InputFileMap PrimaryInputs;
 
 public:
+  FrontendInputs() = default;
+
+  FrontendInputs(const FrontendInputs &other) {
+    for (InputFile input : other.getAllFiles())
+      addInput(input);
+  }
+
+  FrontendInputs &operator=(const FrontendInputs &other) {
+    clearInputs();
+    for (InputFile input : other.getAllFiles())
+      addInput(input);
+    return *this;
+  }
+
   // Readers:
 
-  // Input filename readers
-  ArrayRef<std::string> getInputFilenames() const { return InputFilenames; }
-  bool hasInputFilenames() const { return !getInputFilenames().empty(); }
-  unsigned inputFilenameCount() const { return getInputFilenames().size(); }
+  ArrayRef<InputFile> getAllFiles() const { return AllFiles; }
 
-  bool hasUniqueInputFilename() const { return inputFilenameCount() == 1; }
-  const std::string &getFilenameOfFirstInput() const {
-    assert(hasInputFilenames());
-    return getInputFilenames()[0];
+  std::vector<std::string> getInputFilenames() const {
+    std::vector<std::string> filenames;
+    for (auto &input : getAllFiles()) {
+      assert(!input.file().empty());
+      filenames.push_back(input.file());
+    }
+    return filenames;
+  }
+
+  unsigned inputCount() const { return getAllFiles().size(); }
+
+  bool hasInputs() const { return !AllFiles.empty(); }
+
+  bool hasSingleInput() const { return inputCount() == 1; }
+
+  StringRef getFilenameOfFirstInput() const {
+    assert(hasInputs());
+    const InputFile &inp = getAllFiles()[0];
+    StringRef f = inp.file();
+    assert(!f.empty());
+    return f;
   }
 
   bool isReadingFromStdin() const {
-    return hasUniqueInputFilename() && getFilenameOfFirstInput() == "-";
+    return hasSingleInput() && getFilenameOfFirstInput() == "-";
   }
 
   // If we have exactly one input filename, and its extension is "bc" or "ll",
   // treat the input as LLVM_IR.
   bool shouldTreatAsLLVM() const;
 
-  // Input buffer readers
-
-  ArrayRef<llvm::MemoryBuffer *> getInputBuffers() const {
-    return InputBuffers;
-  }
-  unsigned inputBufferCount() const { return getInputBuffers().size(); }
-
   // Primary input readers
 
 private:
   void assertMustNotBeMoreThanOnePrimaryInput() const {
-    assert(PrimaryInputs.size() < 2 &&
+    assert(primaryInputCount() < 2 &&
            "have not implemented >1 primary input yet");
   }
+  bool areAllNonPrimariesSIB() const;
 
 public:
-  ArrayRef<SelectedInput> getPrimaryInputs() const { return PrimaryInputs; }
-
-  unsigned primaryInputCount() const { return getPrimaryInputs().size(); }
+  unsigned primaryInputCount() const { return PrimaryInputs.size(); }
 
   // Primary count readers:
 
@@ -131,113 +146,61 @@
 
   // Count-dependend readers:
 
-  Optional<SelectedInput> getOptionalPrimaryInput() const {
-    return hasPrimaryInputs() ? Optional<SelectedInput>(getPrimaryInputs()[0])
-                              : Optional<SelectedInput>();
-  }
-
-  SelectedInput getRequiredUniquePrimaryInput() const {
-    assert(hasUniquePrimaryInput());
-    return getPrimaryInputs()[0];
-  }
-
-  Optional<SelectedInput> getOptionalUniquePrimaryInput() const {
-    return hasUniquePrimaryInput()
-               ? Optional<SelectedInput>(getPrimaryInputs()[0])
-               : Optional<SelectedInput>();
-  }
-
-  bool hasAPrimaryInputFile() const {
-    return hasPrimaryInputs() && getOptionalPrimaryInput()->isFilename();
-  }
-
-  Optional<StringRef> getOptionalUniquePrimaryInputFilename() const {
-    Optional<SelectedInput> primaryInput = getOptionalUniquePrimaryInput();
-    return (primaryInput && primaryInput->isFilename())
-               ? Optional<StringRef>(getInputFilenames()[primaryInput->Index])
-               : Optional<StringRef>();
-  }
-
-  bool isInputPrimary(unsigned i) const {
+  /// Return the unique primary input, if one exists.
+  const InputFile *getUniquePrimaryInput() const {
     assertMustNotBeMoreThanOnePrimaryInput();
-    if (Optional<SelectedInput> primaryInput = getOptionalPrimaryInput())
-      return primaryInput->isFilename() && primaryInput->Index == i;
-    return false;
+    const auto b = PrimaryInputs.begin();
+    return b == PrimaryInputs.end() ? nullptr : &AllFiles[b->second];
   }
 
-  Optional<unsigned> primaryInputFileIndex() const {
-    return hasAPrimaryInputFile()
-               ? Optional<unsigned>(getOptionalPrimaryInput()->Index)
-               : None;
+  const InputFile &getRequiredUniquePrimaryInput() const {
+    if (const auto *input = getUniquePrimaryInput())
+      return *input;
+    llvm_unreachable("No primary when one is required");
   }
 
-  StringRef primaryInputFilenameIfAny() const {
-    if (auto Index = primaryInputFileIndex()) {
-      return getInputFilenames()[*Index];
-    }
-    return StringRef();
+  /// Return the name of the unique primary input, or an empty StrinRef if there
+  /// isn't one.
+  StringRef getNameOfUniquePrimaryInputFile() const {
+    const auto *input = getUniquePrimaryInput();
+    return input == nullptr ? StringRef() : input->file();
   }
 
-public:
+  bool isFilePrimary(StringRef file) {
+    auto iterator = PrimaryInputs.find(file);
+    return iterator != PrimaryInputs.end() &&
+           AllFiles[iterator->second].isPrimary();
+  }
+
+  unsigned numberOfPrimaryInputsEndingWith(const char *extension) const;
+
   // Multi-facet readers
+
   bool shouldTreatAsSIL() const;
 
   /// Return true for error
   bool verifyInputs(DiagnosticEngine &diags, bool treatAsSIL,
                     bool isREPLRequested, bool isNoneRequested) const;
 
-  // Input filename writers
+  // Writers
 
-  void addInputFilename(StringRef Filename) {
-    InputFilenames.push_back(Filename);
+  void addInputFile(StringRef file, llvm::MemoryBuffer *buffer = nullptr) {
+    addInput(InputFile(file, false, buffer));
   }
-  void transformInputFilenames(
-      const llvm::function_ref<std::string(std::string)> &fn);
-
-  // Input buffer writers
-
-  void addInputBuffer(llvm::MemoryBuffer *Buf) { InputBuffers.push_back(Buf); }
-
-  // Primary input writers
-
-private:
-  std::vector<SelectedInput> &getMutablePrimaryInputs() {
-    assertMustNotBeMoreThanOnePrimaryInput();
-    return PrimaryInputs;
+  void addPrimaryInputFile(StringRef file,
+                           llvm::MemoryBuffer *buffer = nullptr) {
+    addInput(InputFile(file, true, buffer));
   }
 
-public:
-  void clearPrimaryInputs() { getMutablePrimaryInputs().clear(); }
-
-  void setPrimaryInputToFirstFile() {
-    clearPrimaryInputs();
-    addPrimaryInput(SelectedInput(0, SelectedInput::InputKind::Filename));
+  void addInput(const InputFile &input) {
+    if (!input.file().empty() && input.isPrimary())
+      PrimaryInputs.insert(std::make_pair(input.file(), AllFiles.size()));
+    AllFiles.push_back(input);
   }
 
-  void addPrimaryInput(SelectedInput si) { PrimaryInputs.push_back(si); }
-
-  void setPrimaryInput(SelectedInput si) {
-    clearPrimaryInputs();
-    getMutablePrimaryInputs().push_back(si);
-  }
-
-  void addPrimaryInputFilename(unsigned index) {
-    addPrimaryInput(SelectedInput(index, SelectedInput::InputKind::Filename));
-  }
-
-  void setPrimaryInputForInputFilename(const std::string &inputFilename) {
-    setPrimaryInput(!inputFilename.empty() && inputFilename != "-"
-                        ? SelectedInput(inputFilenameCount(),
-                                        SelectedInput::InputKind::Filename)
-                        : SelectedInput(inputBufferCount(),
-                                        SelectedInput::InputKind::Buffer));
-  }
-
-  // Multi-faceted writers
-
   void clearInputs() {
-    InputFilenames.clear();
-    InputBuffers.clear();
+    AllFiles.clear();
+    PrimaryInputs.clear();
   }
 };
 
@@ -528,8 +491,7 @@
   StringRef determineFallbackModuleName() const;
 
   bool isCompilingExactlyOneSwiftFile() const {
-    return InputKind == InputFileKind::IFK_Swift &&
-           Inputs.hasUniqueInputFilename();
+    return InputKind == InputFileKind::IFK_Swift && Inputs.hasSingleInput();
   }
 
 private:
diff --git a/include/swift/IRGen/Linking.h b/include/swift/IRGen/Linking.h
index c230ca1..678ff89 100644
--- a/include/swift/IRGen/Linking.h
+++ b/include/swift/IRGen/Linking.h
@@ -37,12 +37,29 @@
 
 class UniversalLinkageInfo {
 public:
-  bool IsELFObject, UseDLLStorage, HasMultipleIGMs, IsWholeModule;
+  bool IsELFObject;
+  bool UseDLLStorage;
+
+  /// True iff are multiple llvm modules.
+  bool HasMultipleIGMs;
+
+  bool IsWholeModule;
 
   UniversalLinkageInfo(IRGenModule &IGM);
 
   UniversalLinkageInfo(const llvm::Triple &triple, bool hasMultipleIGMs,
                        bool isWholeModule);
+
+  /// In case of multiple llvm modules (in multi-threaded compilation) all
+  /// private decls must be visible from other files.
+  bool shouldAllPrivateDeclsBeVisibleFromOtherFiles() const {
+    return HasMultipleIGMs;
+  }
+  /// In case of multipe llvm modules, private lazy protocol
+  /// witness table accessors could be emitted by two different IGMs during
+  /// IRGen into different object files and the linker would complain about
+  /// duplicate symbols.
+  bool needLinkerToMergeDuplicateSymbols() const { return HasMultipleIGMs; }
 };
 
 /// Selector for type metadata symbol kinds.
diff --git a/include/swift/Option/FrontendOptions.td b/include/swift/Option/FrontendOptions.td
index 4aa8317..ac060ca 100644
--- a/include/swift/Option/FrontendOptions.td
+++ b/include/swift/Option/FrontendOptions.td
@@ -26,6 +26,8 @@
 
 def filelist : Separate<["-"], "filelist">,
   HelpText<"Specify source inputs in a file rather than on the command line">;
+def primary_filelist : Separate<["-"], "primary-filelist">,
+  HelpText<"Specify primary inputs in a file rather than on the command line">;
 def output_filelist : Separate<["-"], "output-filelist">,
   HelpText<"Specify outputs in a file rather than on the command line">;
 
@@ -187,9 +189,6 @@
 def disable_arc_opts : Flag<["-"], "disable-arc-opts">,
   HelpText<"Don't run SIL ARC optimization passes.">;
 
-def enable_guaranteed_closure_contexts : Flag<["-"], "enable-guaranteed-closure-contexts">,
-  HelpText<"Use @guaranteed convention for closure context">;
-
 def disable_sil_partial_apply : Flag<["-"], "disable-sil-partial-apply">,
   HelpText<"Disable use of partial_apply in SIL generation">;
 
@@ -200,6 +199,8 @@
 
 def code_complete_inits_in_postfix_expr : Flag<["-"], "code-complete-inits-in-postfix-expr">,
   HelpText<"Include initializers when completing a postfix expression">;
+def code_complete_call_pattern_heuristics : Flag<["-"], "code-complete-call-pattern-heuristics">,
+  HelpText<"Use heuristics to guess whether we want call pattern completions">;
 
 def disable_autolink_framework : Separate<["-"],"disable-autolink-framework">,
   HelpText<"Disable autolinking against the provided framework">;
diff --git a/include/swift/Option/Options.td b/include/swift/Option/Options.td
index 8eb5a73..71043ee 100644
--- a/include/swift/Option/Options.td
+++ b/include/swift/Option/Options.td
@@ -281,11 +281,6 @@
   Flags<[FrontendOption, HelpHidden]>,
   HelpText<"Disable using the swift bridge attribute">;
 
-def enable_experimental_conditional_conformances : Flag<["-"],
-  "enable-experimental-conditional-conformances">,
-  Flags<[FrontendOption]>,
-HelpText<"Enable experimental implementation of SE-0143: Conditional Conformances">;
-
 def enable_bridging_pch : Flag<["-"], "enable-bridging-pch">,
   Flags<[HelpHidden]>,
   HelpText<"Enable automatic generation of bridging PCH files">;
diff --git a/include/swift/Parse/CodeCompletionCallbacks.h b/include/swift/Parse/CodeCompletionCallbacks.h
index a266983..68e65d4 100644
--- a/include/swift/Parse/CodeCompletionCallbacks.h
+++ b/include/swift/Parse/CodeCompletionCallbacks.h
@@ -34,7 +34,7 @@
 protected:
   Parser &P;
   ASTContext &Context;
-  Parser::ParserPosition ExprBeginPosition;
+  ParserPosition ExprBeginPosition;
 
   /// The declaration parsed during delayed parsing that was caused by code
   /// completion. This declaration contained the code completion token.
@@ -65,7 +65,7 @@
     return CompleteExprSelectorContext != ObjCSelectorContext::None;
   }
 
-  void setExprBeginning(Parser::ParserPosition PP) {
+  void setExprBeginning(ParserPosition PP) {
     ExprBeginPosition = PP;
   }
 
diff --git a/include/swift/Parse/Lexer.h b/include/swift/Parse/Lexer.h
index aea6da8..1fb56df 100644
--- a/include/swift/Parse/Lexer.h
+++ b/include/swift/Parse/Lexer.h
@@ -20,6 +20,7 @@
 #include "swift/AST/DiagnosticEngine.h"
 #include "swift/Basic/SourceLoc.h"
 #include "swift/Basic/SourceManager.h"
+#include "swift/Parse/LexerState.h"
 #include "swift/Parse/Token.h"
 #include "swift/Syntax/References.h"
 #include "swift/Syntax/Trivia.h"
@@ -59,13 +60,15 @@
   /// separated by 4 "="s, and terminated by 4 "<"s.
   Perforce
 };
-  
+
 class Lexer {
   const LangOptions &LangOpts;
   const SourceManager &SourceMgr;
   DiagnosticEngine *Diags;
   const unsigned BufferID;
 
+  using State = LexerState;
+
   /// Pointer to the first character of the buffer, even in a lexer that
   /// scans a subrange of the buffer.
   const char *BufferStart;
@@ -83,6 +86,9 @@
   /// produce a code completion token.
   const char *CodeCompletionPtr = nullptr;
 
+  /// Points to BufferStart or past the end of UTF-8 BOM sequence if it exists.
+  const char *ContentStart;
+
   /// Pointer to the next not consumed character.
   const char *CurPtr;
 
@@ -128,28 +134,6 @@
   /// `TriviaRetentionMode::WithTrivia`.
   syntax::TriviaList TrailingTrivia;
   
-public:
-  /// \brief Lexer state can be saved/restored to/from objects of this class.
-  class State {
-  public:
-    State() {}
-
-    bool isValid() const {
-      return Loc.isValid();
-    }
-
-    State advance(unsigned Offset) const {
-      assert(isValid());
-      return State(Loc.getAdvancedLoc(Offset));
-    }
-
-  private:
-    explicit State(SourceLoc Loc) : Loc(Loc) {}
-    SourceLoc Loc;
-    friend class Lexer;
-  };
-
-private:
   Lexer(const Lexer&) = delete;
   void operator=(const Lexer&) = delete;
 
@@ -262,10 +246,6 @@
   /// there.
   State getStateForBeginningOfToken(const Token &Tok,
                                     const syntax::Trivia &LeadingTrivia = {}) const {
-    // If trivia parsing mode, start position of trivia is the position we want
-    // to restore.
-    if (TriviaRetention == TriviaRetentionMode::WithTrivia)
-      return State(Tok.getLoc().getAdvancedLoc(-LeadingTrivia.getTextLength()));
 
     // If the token has a comment attached to it, rewind to before the comment,
     // not just the start of the token.  This ensures that we will re-lex and
@@ -273,13 +253,20 @@
     SourceLoc TokStart = Tok.getCommentStart();
     if (TokStart.isInvalid())
       TokStart = Tok.getLoc();
-    return getStateForBeginningOfTokenLoc(TokStart);
+    auto S = getStateForBeginningOfTokenLoc(TokStart);
+    if (TriviaRetention == TriviaRetentionMode::WithTrivia)
+      S.LeadingTrivia = LeadingTrivia.Pieces;
+    return S;
   }
 
   State getStateForEndOfTokenLoc(SourceLoc Loc) const {
     return State(getLocForEndOfToken(SourceMgr, Loc));
   }
 
+  bool isStateForCurrentBuffer(LexerState State) const {
+    return SourceMgr.findBufferContainingLoc(State.Loc) == getBufferID();
+  }
+
   /// \brief Restore the lexer state to a given one, that can be located either
   /// before or after the current position.
   void restoreState(State S, bool enableDiagnostics = false) {
@@ -288,7 +275,13 @@
     // Don't reemit diagnostics while readvancing the lexer.
     llvm::SaveAndRestore<DiagnosticEngine*>
       D(Diags, enableDiagnostics ? Diags : nullptr);
+
     lexImpl();
+
+    // Restore Trivia.
+    if (TriviaRetention == TriviaRetentionMode::WithTrivia)
+      if (auto &LTrivia = S.LeadingTrivia)
+        LeadingTrivia = std::move(*LTrivia);
   }
 
   /// \brief Restore the lexer state to a given state that is located before
@@ -492,18 +485,16 @@
 
   void formToken(tok Kind, const char *TokStart, bool MultilineString = false);
 
-  /// Advance to the end of the line but leave the current buffer pointer
-  /// at that newline character.
-  void skipUpToEndOfLine();
-
-  /// Advance past the next newline character.
-  void skipToEndOfLine();
+  /// Advance to the end of the line.
+  /// If EatNewLine is true, CurPtr will be at end of newline character.
+  /// Otherwise, CurPtr will be at newline character.
+  void skipToEndOfLine(bool EatNewline);
 
   /// Skip to the end of the line of a // comment.
-  void skipSlashSlashComment();
+  void skipSlashSlashComment(bool EatNewline);
 
   /// Skip a #! hashbang line.
-  void skipHashbang();
+  void skipHashbang(bool EatNewline);
 
   void skipSlashStarComment();
   void lexHash();
@@ -526,7 +517,7 @@
 
   /// Try to lex conflict markers by checking for the presence of the start and
   /// end of the marker in diff3 or Perforce style respectively.
-  bool tryLexConflictMarker();
+  bool tryLexConflictMarker(bool EatNewline);
 };
   
 /// Given an ordered token \param Array , get the iterator pointing to the first
diff --git a/include/swift/Parse/LexerState.h b/include/swift/Parse/LexerState.h
new file mode 100644
index 0000000..ec0ed9c
--- /dev/null
+++ b/include/swift/Parse/LexerState.h
@@ -0,0 +1,48 @@
+//===--- LexerState.h - Lexer State -----------------------------*- C++ -*-===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+//
+//  This file defines the LexerState object.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef SWIFT_LEXERSTATE_H
+#define SWIFT_LEXERSTATE_H
+
+#include "llvm/ADT/Optional.h"
+#include "swift/Basic/SourceLoc.h"
+#include "swift/Syntax/Trivia.h"
+
+namespace swift {
+class Lexer;
+
+/// \brief Lexer state can be saved/restored to/from objects of this class.
+class LexerState {
+public:
+  LexerState() {}
+
+  bool isValid() const { return Loc.isValid(); }
+
+  LexerState advance(unsigned Offset) const {
+    assert(isValid());
+    return LexerState(Loc.getAdvancedLoc(Offset));
+  }
+
+private:
+  explicit LexerState(SourceLoc Loc) : Loc(Loc) {}
+  SourceLoc Loc;
+  llvm::Optional<syntax::TriviaList> LeadingTrivia;
+  friend class Lexer;
+};
+
+} // end namespace swift
+
+#endif
diff --git a/include/swift/Parse/Parser.h b/include/swift/Parse/Parser.h
index 7fc3589..717127b 100644
--- a/include/swift/Parse/Parser.h
+++ b/include/swift/Parse/Parser.h
@@ -30,6 +30,7 @@
 #include "swift/Parse/LocalContext.h"
 #include "swift/Parse/PersistentParserState.h"
 #include "swift/Parse/Token.h"
+#include "swift/Parse/ParserPosition.h"
 #include "swift/Parse/ParserResult.h"
 #include "swift/Parse/SyntaxParserResult.h"
 #include "swift/Syntax/SyntaxParsingContext.h"
@@ -358,24 +359,6 @@
   //===--------------------------------------------------------------------===//
   // Routines to save and restore parser state.
 
-  class ParserPosition {
-  public:
-    ParserPosition() = default;
-    ParserPosition &operator=(const ParserPosition &) = default;
-
-    bool isValid() const {
-      return LS.isValid();
-    }
-
-  private:
-    ParserPosition(Lexer::State LS, SourceLoc PreviousLoc):
-        LS(LS), PreviousLoc(PreviousLoc)
-    {}
-    Lexer::State LS;
-    SourceLoc PreviousLoc;
-    friend class Parser;
-  };
-
   ParserPosition getParserPosition() {
     return ParserPosition(L->getStateForBeginningOfToken(Tok, LeadingTrivia),
                           PreviousLoc);
@@ -867,6 +850,8 @@
                 SmallVectorImpl<Decl *> &decls);
   };
 
+  void parseAccessorAttributes(DeclAttributes &Attributes);
+
   bool parseGetSetImpl(ParseDeclOptions Flags,
                        GenericParamList *GenericParams,
                        ParameterList *Indices,
diff --git a/include/swift/Parse/ParserPosition.h b/include/swift/Parse/ParserPosition.h
new file mode 100644
index 0000000..a89b159
--- /dev/null
+++ b/include/swift/Parse/ParserPosition.h
@@ -0,0 +1,41 @@
+//===--- ParserPosition.h - Parser Position ---------------------*- C++ -*-===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+//
+// Parser position where Parser can jump to.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef SWIFT_PARSE_PARSERPOSITION_H
+#define SWIFT_PARSE_PARSERPOSITION_H
+
+#include "swift/Basic/SourceLoc.h"
+#include "swift/Parse/LexerState.h"
+
+namespace swift {
+
+class ParserPosition {
+  LexerState LS;
+  SourceLoc PreviousLoc;
+  friend class Parser;
+
+  ParserPosition(LexerState LS, SourceLoc PreviousLoc)
+      : LS(LS), PreviousLoc(PreviousLoc) {}
+public:
+  ParserPosition() = default;
+  ParserPosition &operator=(const ParserPosition &) = default;
+
+  bool isValid() const { return LS.isValid(); }
+};
+
+} // end namespace swift
+
+#endif
diff --git a/include/swift/Parse/PersistentParserState.h b/include/swift/Parse/PersistentParserState.h
index 55087cd..3038421 100644
--- a/include/swift/Parse/PersistentParserState.h
+++ b/include/swift/Parse/PersistentParserState.h
@@ -19,6 +19,7 @@
 
 #include "swift/Basic/SourceLoc.h"
 #include "swift/Parse/LocalContext.h"
+#include "swift/Parse/ParserPosition.h"
 #include "swift/Parse/Scope.h"
 #include "llvm/ADT/DenseMap.h"
 
@@ -114,7 +115,7 @@
   DelayedAccessorBodiesTy DelayedAccessorBodies;
 
   /// \brief Parser sets this if it stopped parsing before the buffer ended.
-  ParserPos MarkedPos;
+  ParserPosition MarkedPos;
 
   std::unique_ptr<DelayedDeclState> CodeCompletionDelayedDeclState;
 
@@ -166,16 +167,16 @@
     return TopLevelCode;
   }
 
-  void markParserPosition(SourceLoc Loc, SourceLoc PrevLoc,
+  void markParserPosition(ParserPosition Pos,
                           bool InPoundLineEnvironment) {
-    MarkedPos = {Loc, PrevLoc};
+    MarkedPos = Pos;
     this->InPoundLineEnvironment = InPoundLineEnvironment;
   }
 
   /// \brief Returns the marked parser position and resets it.
-  ParserPos takeParserPosition() {
-    ParserPos Pos = MarkedPos;
-    MarkedPos = ParserPos();
+  ParserPosition takeParserPosition() {
+    ParserPosition Pos = MarkedPos;
+    MarkedPos = ParserPosition();
     return Pos;
   }
 };
diff --git a/include/swift/Remote/MetadataReader.h b/include/swift/Remote/MetadataReader.h
index e77064b..1b4acee 100644
--- a/include/swift/Remote/MetadataReader.h
+++ b/include/swift/Remote/MetadataReader.h
@@ -894,9 +894,9 @@
     case MetadataKind::ForeignClass: {
       auto namePtrAddress =
         Meta.getAddress() + TargetForeignClassMetadata<Runtime>::OffsetToName;
-      StoredPointer namePtr;
-      if (!Reader->readInteger(RemoteAddress(namePtrAddress), &namePtr) ||
-          namePtr == 0)
+      
+      StoredPointer namePtr = resolveRelativeOffset<int32_t>(namePtrAddress);
+      if (namePtr == 0)
         return BuiltType();
       std::string name;
       if (!Reader->readString(RemoteAddress(namePtr), name))
diff --git a/include/swift/Runtime/Config.h b/include/swift/Runtime/Config.h
index 93071ad..ca8b293 100644
--- a/include/swift/Runtime/Config.h
+++ b/include/swift/Runtime/Config.h
@@ -33,18 +33,6 @@
 #endif
 #endif
 
-/// Does the current Swift platform use LLVM's intrinsic "swiftcall"
-/// calling convention for Swift functions?
-#ifndef SWIFT_USE_SWIFTCALL
-// Clang doesn't support mangling functions with the swiftcall attribute
-// on Windows and crashes during compilation: http://bugs.llvm.org/show_bug.cgi?id=32000
-#if (__has_attribute(swiftcall) || defined(__linux__)) && !defined(_WIN32)
-#define SWIFT_USE_SWIFTCALL 1
-#else
-#define SWIFT_USE_SWIFTCALL 0
-#endif
-#endif
-
 /// Does the current Swift platform allow information other than the
 /// class pointer to be stored in the isa field?  If so, when deriving
 /// the class pointer of an object, we must apply a
@@ -105,7 +93,11 @@
 #define SWIFT_CC_preserve_all  __attribute__((preserve_all))
 #define SWIFT_CC_c
 
-#if SWIFT_USE_SWIFTCALL
+// Define SWIFT_CC_swift in terms of the Swift CC for runtime functions.
+// Functions outside the stdlib or runtime that include this file may be built 
+// with a compiler that doesn't support swiftcall; don't define these macros
+// in that case so any incorrect usage is caught.
+#if __has_attribute(swiftcall)
 #define SWIFT_CC_swift __attribute__((swiftcall))
 #define SWIFT_CONTEXT __attribute__((swift_context))
 #define SWIFT_ERROR_RESULT __attribute__((swift_error_result))
@@ -117,6 +109,8 @@
 #define SWIFT_INDIRECT_RESULT
 #endif
 
+#define SWIFT_CC_SwiftCC SWIFT_CC_swift
+
 // Map a logical calling convention (e.g. RegisterPreservingCC) to LLVM calling
 // convention.
 #define SWIFT_LLVM_CC(CC) SWIFT_LLVM_CC_##CC
@@ -135,11 +129,7 @@
 
 #define SWIFT_LLVM_CC_RegisterPreservingCC llvm::CallingConv::PreserveMost
 
-#if SWIFT_USE_SWIFTCALL
 #define SWIFT_LLVM_CC_SwiftCC llvm::CallingConv::Swift
-#else
-#define SWIFT_LLVM_CC_SwiftCC llvm::CallingConv::C
-#endif
 
 // If defined, it indicates that runtime function wrappers
 // should be used on all platforms, even they do not support
diff --git a/include/swift/Runtime/Enum.h b/include/swift/Runtime/Enum.h
index 6102ff7..2b514ae 100644
--- a/include/swift/Runtime/Enum.h
+++ b/include/swift/Runtime/Enum.h
@@ -33,17 +33,29 @@
 using EnumMetadata = TargetEnumMetadata<InProcess>;
 struct TypeLayout;
 
-/// \brief Initialize the value witness table for a generic, single-payload
-///        enum instance.
+/// \brief Initialize the type metadata for a single-case enum type.
 ///
-/// \param vwtable - pointer to the instantiated but uninitialized value
-///                  witness table for the enum.
+/// \param enumType - pointer to the instantiated but uninitialized metadata
+///                   for the enum.
+/// \param flags - flags controlling the layout
+/// \param payload - type metadata for the payload of the enum.
+SWIFT_RUNTIME_EXPORT
+void swift_initEnumMetadataSingleCase(EnumMetadata *enumType,
+                                      EnumLayoutFlags flags,
+                                      const TypeLayout *payload);
+
+/// \brief Initialize the type metadata for a single-payload enum type.
+///
+/// \param enumType - pointer to the instantiated but uninitialized metadata
+///                   for the enum.
+/// \param flags - flags controlling the layout
 /// \param payload - type metadata for the payload case of the enum.
 /// \param emptyCases - the number of empty cases in the enum.
 SWIFT_RUNTIME_EXPORT
-void swift_initEnumValueWitnessTableSinglePayload(ValueWitnessTable *vwtable,
-                                                  const TypeLayout *payload,
-                                                  unsigned emptyCases);
+void swift_initEnumMetadataSinglePayload(EnumMetadata *enumType,
+                                         EnumLayoutFlags flags,
+                                         const TypeLayout *payload,
+                                         unsigned emptyCases);
 
 /// \brief Faster variant of the above which avoids digging into the enum type
 /// metadata when the caller already has the payload information handy.
@@ -81,11 +93,11 @@
                                      unsigned emptyCases)
   SWIFT_CC(RegisterPreservingCC);
 
-/// \brief Initialize the value witness table for a generic, multi-payload
+/// \brief Initialize the type metadata for a generic, multi-payload
 ///        enum instance.
 SWIFT_RUNTIME_EXPORT
-void swift_initEnumMetadataMultiPayload(ValueWitnessTable *vwtable,
-                                        EnumMetadata *enumType,
+void swift_initEnumMetadataMultiPayload(EnumMetadata *enumType,
+                                        EnumLayoutFlags flags,
                                         unsigned numPayloads,
                                         const TypeLayout * const *payloadTypes);
 
diff --git a/include/swift/Runtime/Metadata.h b/include/swift/Runtime/Metadata.h
index ef8f0dc..22dd495 100644
--- a/include/swift/Runtime/Metadata.h
+++ b/include/swift/Runtime/Metadata.h
@@ -29,6 +29,7 @@
 #include "swift/Runtime/Config.h"
 #include "swift/ABI/MetadataValues.h"
 #include "swift/ABI/System.h"
+#include "swift/ABI/TrailingObjects.h"
 #include "swift/Basic/Malloc.h"
 #include "swift/Basic/FlaggedPointer.h"
 #include "swift/Basic/RelativePointer.h"
@@ -1023,12 +1024,12 @@
   /// to NumGenericRequirements; it counts only the type parameters
   /// and not any required witness tables.
   uint32_t NumPrimaryParams;
+  
+  // TODO: add meaningful descriptions of the generic requirements.
 };
 
-/// Header for a generic parameter descriptor. This is a variable-sized
-/// structure that describes how to find and parse a generic parameter vector
-/// within the type metadata for an instance of a nominal type.
-struct GenericParameterDescriptor {
+/// Header for a generic parameter descriptor.
+struct GenericParameterDescriptorHeader {
   /// The offset to the first generic argument from the start of
   /// metadata record.
   ///
@@ -1063,13 +1064,6 @@
   bool isGeneric() const {
     return hasGenericRequirements();
   }
-
-  GenericContextDescriptor getContext(unsigned depth) const {
-    assert(depth < NestingDepth);
-    return ((const GenericContextDescriptor *)(this + 1))[depth];
-  }
-
-  // TODO: add meaningful descriptions of the generic requirements.
 };
 
 template <typename Runtime>
@@ -1086,27 +1080,43 @@
 /// Header for a class vtable descriptor. This is a variable-sized
 /// structure that describes how to find and parse a vtable
 /// within the type metadata for a class.
-template <typename Runtime>
-struct TargetVTableDescriptor {
+struct VTableDescriptorHeader {
   /// The offset of the vtable for this class in its metadata, if any.
   uint32_t VTableOffset;
-  /// The number of vtable entries, in words.
+  /// The number of vtable entries. This is the number of MethodDescriptor
+  /// records following the vtable header in the class's nominal type
+  /// descriptor, which is equal to the number of words this subclass's vtable
+  /// entries occupy in instantiated class metadata.
   uint32_t VTableSize;
-
-  using MethodDescriptor = TargetMethodDescriptor<Runtime>;
-
-  MethodDescriptor VTable[];
-
-  void *getMethod(unsigned index) const {
-    return VTable[index].Impl.get();
-  }
 };
 
+template<typename Runtime> struct TargetNominalTypeDescriptor;
+
+template<typename Runtime>
+using TargetNominalTypeDescriptorTrailingObjects
+  = swift::ABI::TrailingObjects<TargetNominalTypeDescriptor<Runtime>,
+        GenericContextDescriptor,
+        VTableDescriptorHeader,
+        TargetMethodDescriptor<Runtime>>;
+
 /// Common information about all nominal types. For generic types, this
-/// descriptor is shared for all instantiations of the generic type.
+/// descriptor is shared for all instantiations of the generic type. Unlike
+/// metadata records, the uniqueness of a nominal type descriptor should not
+/// be relied on.
 template <typename Runtime>
-struct TargetNominalTypeDescriptor {
+struct TargetNominalTypeDescriptor final
+    : private TargetNominalTypeDescriptorTrailingObjects<Runtime>
+{
+private:
+  using TrailingObjects = TargetNominalTypeDescriptorTrailingObjects<Runtime>;
+  friend TrailingObjects;
+  template<typename T>
+  using OverloadToken = typename TrailingObjects::template OverloadToken<T>;
+
+public:
   using StoredPointer = typename Runtime::StoredPointer;
+  using MethodDescriptor = TargetMethodDescriptor<Runtime>;
+  
   /// The mangled name of the nominal type.
   TargetRelativeDirectPointer<Runtime, const char> Name;
   
@@ -1231,29 +1241,56 @@
     return offsetof(TargetNominalTypeDescriptor<Runtime>, Name);
   }
 
-  using VTableDescriptor = TargetVTableDescriptor<Runtime>;
-
-  const VTableDescriptor *getVTableDescriptor() const {
-    if (getKind() != NominalTypeKind::Class ||
-        !GenericParams.Flags.hasVTable())
-      return nullptr;
-
-    auto asWords = reinterpret_cast<const uint32_t *>(this + 1);
-
-    // TODO: Once we emit reflective descriptions of generic requirements,
-    // skip the right number of words here.
-
-    return reinterpret_cast<const VTableDescriptor *>(asWords
-        + GenericParams.NestingDepth);
-  }
-
   /// The generic parameter descriptor header. This describes how to find and
   /// parse the generic parameter vector in metadata records for this nominal
   /// type.
-  GenericParameterDescriptor GenericParams;
+  GenericParameterDescriptorHeader GenericParams;
+
+  const GenericContextDescriptor *getGenericContexts() const {
+    return this->template getTrailingObjects<GenericContextDescriptor>();
+  }
   
-  // NOTE: GenericParams ends with a tail-allocated array, so it cannot be
-  // followed by additional fields.
+  const GenericContextDescriptor &getGenericContext(unsigned i) const {
+    assert(i < numTrailingObjects(OverloadToken<GenericContextDescriptor>{}));
+    return getGenericContexts()[i];
+  }
+
+  bool hasVTable() const {
+    return getKind() == NominalTypeKind::Class
+      && GenericParams.Flags.hasVTable();
+  }
+  
+  const VTableDescriptorHeader *getVTableDescriptor() const {
+    if (!hasVTable())
+      return nullptr;
+    return this->template getTrailingObjects<VTableDescriptorHeader>();
+  }
+  
+  const MethodDescriptor *getMethodDescriptors() const {
+    if (!hasVTable())
+      return nullptr;
+    return this->template getTrailingObjects<MethodDescriptor>();
+  }
+  
+  void *getMethod(unsigned i) const {
+    assert(hasVTable()
+           && i < numTrailingObjects(OverloadToken<MethodDescriptor>{}));
+    return getMethodDescriptors()[i].Impl.get();
+  }
+
+private:
+  size_t numTrailingObjects(OverloadToken<GenericContextDescriptor>) const {
+    return GenericParams.NestingDepth;
+  }
+  size_t numTrailingObjects(OverloadToken<VTableDescriptorHeader>) const {
+    return hasVTable() ? 1 : 0;
+  }
+  size_t numTrailingObjects(OverloadToken<MethodDescriptor>) const {
+    if (!hasVTable())
+      return 0;
+
+    return getVTableDescriptor()->VTableSize;
+  }
 };
 using NominalTypeDescriptor = TargetNominalTypeDescriptor<InProcess>;
 
@@ -1530,86 +1567,152 @@
   using StoredPointer = typename Runtime::StoredPointer;
   using StoredSize = typename Runtime::StoredSize;
   using InitializationFunction_t =
-    void (*)(TargetForeignTypeMetadata<Runtime> *selectedMetadata);
+    void (TargetForeignTypeMetadata<Runtime> *selectedMetadata);
   using RuntimeMetadataPointer =
       ConstTargetMetadataPointer<Runtime, swift::TargetForeignTypeMetadata>;
 
+  /// An invasive cache for the runtime-uniqued lookup structure that is stored
+  /// in the header prefix of foreign metadata records.
+  ///
+  /// Prior to initialization, as emitted by the compiler, this contains the
+  /// initialization flags.
+  /// After initialization, it holds a pointer to the actual, runtime-uniqued
+  /// metadata for this type.
+  struct CacheValue {
+    StoredSize Value;
+    
+    /// Work around a bug in libstdc++'s std::atomic that requires the type to
+    /// be default-constructible.
+    CacheValue() = default;
+    
+    explicit CacheValue(RuntimeMetadataPointer p)
+      : Value(reinterpret_cast<StoredSize>(p))
+    {}
+
+    /// Various flags. The largest flag bit should be less than 4096 so that
+    /// a flag set is distinguishable from a valid pointer.
+    enum : StoredSize {
+      /// This metadata has an initialization callback function.  If
+      /// this flag is not set, the metadata object needn't actually
+      /// have a InitializationFunction field, and that field will be
+      /// undefined.
+      HasInitializationFunction = 0x1,
+      
+      LargestFlagMask = 0xFFF,
+    };    
+
+    /// True if the metadata record associated with this cache has not been
+    /// initialized, so contains a flag set describing parameters to the
+    /// initialization operation. isFlags() == !isInitialized()
+    bool isFlags() const {
+      return Value <= LargestFlagMask;
+    }
+    /// True if the metadata record associated with this cache has an
+    /// initialization function which must be run if it is picked as the
+    /// canonical metadata record for its key.
+    ///
+    /// Undefined if !isFlags().
+    bool hasInitializationFunction() const {
+      assert(isFlags());
+      return Value & HasInitializationFunction;
+    }
+    
+    /// True if the metadata record associated with this cache has been
+    /// initialized, so the cache contains an absolute pointer to the
+    /// canonical metadata record for its key. isInitialized() == !isFlags()
+    bool isInitialized() const {
+      return !isFlags();
+    }
+    
+    /// Gets the cached pointer to the unique canonical metadata record for
+    /// this metadata record's key.
+    ///
+    /// Undefined if !isInitialized().
+    RuntimeMetadataPointer getCachedUniqueMetadata() const {
+      assert(isInitialized());
+      return RuntimeMetadataPointer(Value);
+    }
+  };
+
+
   /// Foreign type metadata may have extra header fields depending on
   /// the flags.
   struct HeaderPrefix {
     /// An optional callback performed when a particular metadata object
     /// is chosen as the unique structure.
+    ///
     /// If there is no initialization function, this metadata record can be
     /// assumed to be immutable (except for the \c Unique invasive cache
-    /// field).
-    InitializationFunction_t InitializationFunction;
+    /// field). The field is not present unless the HasInitializationFunction
+    /// flag is set.
+    RelativeDirectPointer<InitializationFunction_t> InitializationFunction;
     
-    /// The Swift-mangled name of the type. This is the uniquing key for the
-    /// type.
-    TargetPointer<Runtime, const char> Name;
+    /// The uniquing key for the metadata record. Metadata records with the
+    /// same Name string are considered equivalent by the runtime, and the
+    /// runtime will pick one to be canonical.
+    RelativeDirectPointer<const char> Name;
 
-    /// A pointer to the actual, runtime-uniqued metadata for this
-    /// type.  This is essentially an invasive cache for the lookup
-    /// structure.
-    mutable std::atomic<RuntimeMetadataPointer> Unique;
-
-    /// Various flags.
-    enum : StoredSize {
-      /// This metadata has an initialization callback function.  If
-      /// this flag is not set, the metadata object needn't actually
-      /// have a InitializationFunction field.
-      HasInitializationFunction = 0x1,
-    } Flags;
+    mutable std::atomic<CacheValue> Cache;
   };
 
   struct HeaderType : HeaderPrefix, TypeMetadataHeader {};
 
-  static constexpr int OffsetToName =
-    (int) offsetof(HeaderType, Name) - (int) sizeof(HeaderType);
+  static constexpr int32_t OffsetToName =
+    (int32_t) offsetof(HeaderType, Name) - (int32_t) sizeof(HeaderType);
 
   TargetPointer<Runtime, const char> getName() const {
     return reinterpret_cast<TargetPointer<Runtime, const char>>(
-      asFullMetadata(this)->Name);
+      asFullMetadata(this)->Name.get());
   }
 
-  RuntimeMetadataPointer getCachedUniqueMetadata() const {
-#if __alpha__
-    // TODO: This can be a relaxed-order load if there is no initialization
-    // function. On platforms we care about, consume is no more expensive than
-    // relaxed, so there's no reason to branch here (and LLVM isn't smart
-    // enough to eliminate it when it's not needed).
-    if (!hasInitializationFunction())
-      return asFullMetadata(this)->Unique.load(std::memory_order_relaxed);
-#endif
-    return asFullMetadata(this)->Unique.load(SWIFT_MEMORY_ORDER_CONSUME);
+  CacheValue getCacheValue() const {
+    /// NB: This can be a relaxed-order load if there is no initialization
+    /// function. On platforms Swift currently targets, consume is no more
+    /// expensive than relaxed, so there's no reason to branch here (and LLVM
+    /// isn't smart enough to eliminate it when it's not needed).
+    ///
+    /// A port to a platform where relaxed is significantly less expensive than
+    /// consume (historically, Alpha) would probably want to preserve the
+    /// 'hasInitializationFunction' bit in its own word to be able to avoid
+    /// the consuming load when not needed.
+    return asFullMetadata(this)->Cache
+      .load(SWIFT_MEMORY_ORDER_CONSUME);
   }
 
   void setCachedUniqueMetadata(RuntimeMetadataPointer unique) const {
-    assert((static_cast<RuntimeMetadataPointer>(asFullMetadata(this)->Unique) ==
-                nullptr ||
-            asFullMetadata(this)->Unique == unique) &&
-           "already set unique metadata");
+    auto cache = getCacheValue();
+
+    // If the cache was already set to a pointer, we're done. We ought to
+    // converge on a single unique pointer.
+    if (cache.isInitialized()) {
+      assert(cache.getCachedUniqueMetadata() == unique
+             && "already set unique metadata to something else");
+      return;
+    }
+    
+    auto newCache = CacheValue(unique);
 
     // If there is no initialization function, this can be a relaxed store.
-    if (!hasInitializationFunction())
-      asFullMetadata(this)->Unique.store(unique, std::memory_order_relaxed);
+    if (cache.hasInitializationFunction())
+      asFullMetadata(this)->Cache.store(newCache, std::memory_order_relaxed);
     
     // Otherwise, we need a release store to publish the result of
-    // initialization
+    // initialization.
     else
-      asFullMetadata(this)->Unique.store(unique, std::memory_order_release);
+      asFullMetadata(this)->Cache.store(newCache, std::memory_order_release);
   }
   
-  StoredSize getFlags() const {
-    return asFullMetadata(this)->Flags;
-  }
+  /// Return the initialization function for this metadata record.
+  ///
+  /// As a prerequisite, the metadata record must not have been initialized yet,
+  /// and must have an initialization function to begin with, otherwise the
+  /// result is undefined.
+  InitializationFunction_t *getInitializationFunction() const {
+#ifndef NDEBUG
+    auto cache = getCacheValue();
+    assert(cache.hasInitializationFunction());
+#endif
 
-  bool hasInitializationFunction() const {
-    return getFlags() & HeaderPrefix::HasInitializationFunction;
-  }
-
-  InitializationFunction_t getInitializationFunction() const {
-    assert(hasInitializationFunction());
     return asFullMetadata(this)->InitializationFunction;
   }
 };
@@ -2864,10 +2967,11 @@
 /// Initialize the value witness table and struct field offset vector for a
 /// struct, using the "Universal" layout strategy.
 SWIFT_RUNTIME_EXPORT
-void swift_initStructMetadata_UniversalStrategy(size_t numFields,
-                                         const TypeLayout * const *fieldTypes,
-                                         size_t *fieldOffsets,
-                                         ValueWitnessTable *vwtable);
+void swift_initStructMetadata(StructMetadata *self,
+                              StructLayoutFlags flags,
+                              size_t numFields,
+                              const TypeLayout * const *fieldTypes,
+                              size_t *fieldOffsets);
 
 /// Relocate the metadata for a class and copy fields from the given template.
 /// The final size of the metadata is calculated at runtime from the size of
diff --git a/include/swift/Runtime/RuntimeFunctions.def b/include/swift/Runtime/RuntimeFunctions.def
index 86b0ce9..5bee126 100644
--- a/include/swift/Runtime/RuntimeFunctions.def
+++ b/include/swift/Runtime/RuntimeFunctions.def
@@ -968,37 +968,47 @@
               SizeTy->getPointerTo()),
          ATTRS(NoUnwind))
 
-// void swift_initStructMetadata_UniversalStrategy(size_t numFields,
-//                                              TypeLayout * const *fieldTypes,
-//                                              size_t *fieldOffsets,
-//                                              value_witness_table_t *vwtable);
-FUNCTION(InitStructMetadataUniversal,
-         swift_initStructMetadata_UniversalStrategy, DefaultCC,
+// void swift_initStructMetadata(Metadata *structType,
+//                               StructLayoutFlags flags,
+//                               size_t numFields,
+//                               TypeLayout * const *fieldTypes,
+//                               size_t *fieldOffsets);
+FUNCTION(InitStructMetadata,
+         swift_initStructMetadata, DefaultCC,
          RETURNS(VoidTy),
-         ARGS(SizeTy, Int8PtrPtrTy->getPointerTo(),
-              SizeTy->getPointerTo(), WitnessTablePtrTy),
+         ARGS(TypeMetadataPtrTy, SizeTy, SizeTy, Int8PtrPtrTy->getPointerTo(0),
+              SizeTy->getPointerTo()),
          ATTRS(NoUnwind))
 
-// void swift_initEnumValueWitnessTableSinglePayload(value_witness_table_t *vwt,
-//                                                   TypeLayout *payload,
-//                                                   unsigned num_empty_cases);
-FUNCTION(InitEnumValueWitnessTableSinglePayload,
-         swift_initEnumValueWitnessTableSinglePayload,
+// void swift_initEnumMetadataSingleCase(Metadata *enumType,
+//                                       EnumLayoutFlags flags,
+//                                       TypeLayout *payload);
+FUNCTION(InitEnumMetadataSingleCase,
+         swift_initEnumMetadataSingleCase,
          DefaultCC,
          RETURNS(VoidTy),
-         ARGS(WitnessTablePtrTy, Int8PtrPtrTy, Int32Ty),
+         ARGS(TypeMetadataPtrTy, SizeTy, Int8PtrPtrTy),
          ATTRS(NoUnwind))
 
-// void swift_initEnumMetadataMultiPayload(value_witness_table_t *vwt,
-//                                         Metadata *enumType,
+// void swift_initEnumMetadataSinglePayload(Metadata *enumType,
+//                                          EnumLayoutFlags flags,
+//                                          TypeLayout *payload,
+//                                          unsigned num_empty_cases);
+FUNCTION(InitEnumMetadataSinglePayload,
+         swift_initEnumMetadataSinglePayload,
+         DefaultCC,
+         RETURNS(VoidTy),
+         ARGS(TypeMetadataPtrTy, SizeTy, Int8PtrPtrTy, Int32Ty),
+         ATTRS(NoUnwind))
+
+// void swift_initEnumMetadataMultiPayload(Metadata *enumType,
 //                                         size_t numPayloads,
 //                                         TypeLayout * const *payloadTypes);
 FUNCTION(InitEnumMetadataMultiPayload,
          swift_initEnumMetadataMultiPayload,
          DefaultCC,
          RETURNS(VoidTy),
-         ARGS(WitnessTablePtrTy, TypeMetadataPtrTy, SizeTy,
-              Int8PtrPtrTy->getPointerTo(0)),
+         ARGS(TypeMetadataPtrTy, SizeTy, SizeTy, Int8PtrPtrTy->getPointerTo(0)),
          ATTRS(NoUnwind))
 
 // int swift_getEnumCaseSinglePayload(opaque_t *obj, Metadata *payload,
@@ -1059,14 +1069,10 @@
          ATTRS(NoUnwind, ReadNone))
 
 // Metadata *swift_getObjectType(id object);
-//
-// Since this is intended to look through dynamic subclasses, it's
-// invariant across reasonable isa-rewriting schemes and therefore can
-// be readnone.
 FUNCTION(GetObjectType, swift_getObjectType, DefaultCC,
          RETURNS(TypeMetadataPtrTy),
          ARGS(ObjCPtrTy),
-         ATTRS(NoUnwind, ReadNone))
+         ATTRS(NoUnwind, ReadOnly))
 
 // Metadata *swift_getDynamicType(opaque_t *obj, Metadata *self);
 FUNCTION(GetDynamicType, swift_getDynamicType, DefaultCC,
diff --git a/include/swift/SIL/AbstractionPattern.h b/include/swift/SIL/AbstractionPattern.h
index 24e4a89..2113fd8 100644
--- a/include/swift/SIL/AbstractionPattern.h
+++ b/include/swift/SIL/AbstractionPattern.h
@@ -369,7 +369,7 @@
                              Kind kind,
                              ImportAsMemberStatus memberStatus) {
     initClangType(signature, origType, clangType, kind);
-    OtherData = memberStatus.rawValue;
+    OtherData = memberStatus.getRawValue();
   }
 
   AbstractionPattern() {}
@@ -482,9 +482,7 @@
   /// method with no `self` parameter.
   ImportAsMemberStatus getImportAsMemberStatus() const {
     assert(hasImportAsMemberStatus());
-    ImportAsMemberStatus status;
-    status.rawValue = OtherData;
-    return status;
+    return ImportAsMemberStatus(OtherData);
   }
   
   /// Return an abstraction pattern for a value that is discarded after being
diff --git a/include/swift/SIL/Dominance.h b/include/swift/SIL/Dominance.h
index 79e20d8..539c580 100644
--- a/include/swift/SIL/Dominance.h
+++ b/include/swift/SIL/Dominance.h
@@ -52,6 +52,11 @@
   /// Does instruction A properly dominate instruction B?
   bool properlyDominates(SILInstruction *a, SILInstruction *b);
 
+  /// Does instruction A dominate instruction B?
+  bool dominates(SILInstruction *a, SILInstruction *b) {
+    return a == b || properlyDominates(a, b);
+  }
+
   /// Does value A properly dominate instruction B?
   bool properlyDominates(SILValue a, SILInstruction *b);
 
@@ -74,6 +79,7 @@
   }
 
   using DominatorTreeBase::properlyDominates;
+  using DominatorTreeBase::dominates;
 
   bool isValid(SILFunction *F) const {
     return getNode(&F->front()) != nullptr;
diff --git a/include/swift/SIL/OptimizationRemark.h b/include/swift/SIL/OptimizationRemark.h
index 0f66af3..f60e0e5 100644
--- a/include/swift/SIL/OptimizationRemark.h
+++ b/include/swift/SIL/OptimizationRemark.h
@@ -50,6 +50,7 @@
   Argument(StringRef Key, unsigned long long N);
 
   Argument(StringRef Key, SILFunction *F);
+  Argument(StringRef Key, SILType *Ty);
 };
 
 /// Shorthand to insert named-value pairs.
diff --git a/include/swift/SIL/SILArgument.h b/include/swift/SIL/SILArgument.h
index 0440176..ce6a152 100644
--- a/include/swift/SIL/SILArgument.h
+++ b/include/swift/SIL/SILArgument.h
@@ -43,11 +43,14 @@
 
   SILBasicBlock *ParentBB;
   const ValueDecl *Decl;
-  ValueOwnershipKind OwnershipKind;
 
 public:
-  ValueOwnershipKind getOwnershipKind() const { return OwnershipKind; }
-  void setOwnershipKind(ValueOwnershipKind NewKind) { OwnershipKind = NewKind; }
+  ValueOwnershipKind getOwnershipKind() const {
+    return static_cast<ValueOwnershipKind>(Bits.SILArgument.VOKind);
+  }
+  void setOwnershipKind(ValueOwnershipKind NewKind) {
+    Bits.SILArgument.VOKind = static_cast<unsigned>(NewKind);
+  }
 
   SILBasicBlock *getParent() { return ParentBB; }
   const SILBasicBlock *getParent() const { return ParentBB; }
@@ -125,7 +128,9 @@
                        ValueOwnershipKind OwnershipKind,
                        const ValueDecl *D = nullptr)
       : ValueBase(SubClassKind, Ty, IsRepresentative::Yes), ParentBB(nullptr),
-        Decl(D), OwnershipKind(OwnershipKind) {}
+        Decl(D) {
+    Bits.SILArgument.VOKind = static_cast<unsigned>(OwnershipKind);
+  }
   void setParent(SILBasicBlock *P) { ParentBB = P; }
 
   friend SILBasicBlock;
diff --git a/include/swift/SIL/SILBasicBlock.h b/include/swift/SIL/SILBasicBlock.h
index 5de833b..8fd8e18 100644
--- a/include/swift/SIL/SILBasicBlock.h
+++ b/include/swift/SIL/SILBasicBlock.h
@@ -68,7 +68,7 @@
   /// Returns -1 if the block is not contained in a function.
   /// Warning: This function is slow. Therefore it should only be used for
   ///          debug output.
-  int getDebugID();
+  int getDebugID() const;
 
   SILFunction *getParent() { return Parent; }
   const SILFunction *getParent() const { return Parent; }
diff --git a/include/swift/SIL/SILDeclRef.h b/include/swift/SIL/SILDeclRef.h
index cdda0cf..185cbce 100644
--- a/include/swift/SIL/SILDeclRef.h
+++ b/include/swift/SIL/SILDeclRef.h
@@ -361,6 +361,11 @@
   /// declarations do not always have vtable entries.
   SILDeclRef getNextOverriddenVTableEntry() const;
 
+  /// Return the most derived override which requires a new vtable entry.
+  /// If the method does not override anything or no override is vtable
+  /// dispatched, will return the least derived method.
+  SILDeclRef getOverriddenVTableEntry() const;
+
   /// True if the referenced entity is some kind of thunk.
   bool isThunk() const;
 
diff --git a/include/swift/SIL/SILInstruction.h b/include/swift/SIL/SILInstruction.h
index 27f9c0c..3329c15 100644
--- a/include/swift/SIL/SILInstruction.h
+++ b/include/swift/SIL/SILInstruction.h
@@ -774,7 +774,7 @@
   }
 
   unsigned getIndex() const {
-    return unsigned((getSubclassData() >> IndexBitOffset) & IndexMask);
+    return Bits.MultipleValueInstructionResult.Index;
   }
 
   /// Get the ownership kind assigned to this result by its parent.
@@ -802,10 +802,6 @@
 
   /// Set the index of this result.
   void setIndex(unsigned NewIndex);
-
-  static constexpr unsigned NumIndexBits = 24;
-  static constexpr uint64_t IndexMask = (uint64_t(1) << 24) - 1;
-  static constexpr uint64_t IndexBitOffset = ValueOwnershipKind::NumBits;
 };
 
 template <class Result>
@@ -1078,6 +1074,10 @@
     : public InstructionBase<Kind, Base>,
       protected llvm::TrailingObjects<Derived, Operand, OtherTrailingTypes...> {
 
+  unsigned getNumOperandsStorage() const {
+    return SILInstruction::Bits.UIWTDOB.NumOperands;
+  }
+
 protected:
   friend llvm::TrailingObjects<Derived, Operand, OtherTrailingTypes...>;
 
@@ -1086,18 +1086,14 @@
 
   using TrailingObjects::totalSizeToAlloc;
 
-  // Total number of operands of this instruction.
-  // It is number of type dependent operands + 1.
-  unsigned NumOperands;
-
 public:
   template <typename... Args>
   UnaryInstructionWithTypeDependentOperandsBase(
       SILDebugLocation debugLoc, SILValue operand,
       ArrayRef<SILValue> typeDependentOperands,
       Args &&...args)
-        : InstructionBase<Kind, Base>(debugLoc, std::forward<Args>(args)...),
-          NumOperands(1 + typeDependentOperands.size()) {
+        : InstructionBase<Kind, Base>(debugLoc, std::forward<Args>(args)...) {
+    SILInstruction::Bits.UIWTDOB.NumOperands = 1 + typeDependentOperands.size();
     TrailingOperandsList::InitOperandsList(getAllOperands().begin(), this,
                                            operand, typeDependentOperands);
   }
@@ -1105,18 +1101,18 @@
   // Destruct tail allocated objects.
   ~UnaryInstructionWithTypeDependentOperandsBase() {
     Operand *Operands = &getAllOperands()[0];
-    for (unsigned i = 0, end = NumOperands; i < end; ++i) {
+    for (unsigned i = 0, end = getNumOperandsStorage(); i < end; ++i) {
       Operands[i].~Operand();
     }
   }
 
   size_t numTrailingObjects(
     typename TrailingObjects::template OverloadToken<Operand>) const {
-    return NumOperands;
+    return getNumOperandsStorage();
   }
 
   unsigned getNumTypeDependentOperands() const {
-    return NumOperands - 1;
+    return getNumOperandsStorage() - 1;
   }
 
   SILValue getOperand() const { return getAllOperands()[0].get(); }
@@ -1126,12 +1122,12 @@
 
   ArrayRef<Operand> getAllOperands() const {
     return {TrailingObjects::template getTrailingObjects<Operand>(),
-            static_cast<size_t>(NumOperands)};
+            static_cast<size_t>(getNumOperandsStorage())};
   }
 
   MutableArrayRef<Operand> getAllOperands() {
     return {TrailingObjects::template getTrailingObjects<Operand>(),
-            static_cast<size_t>(NumOperands)};
+            static_cast<size_t>(getNumOperandsStorage())};
   }
 
   ArrayRef<Operand> getTypeDependentOperands() const {
@@ -1160,23 +1156,30 @@
 /// A DebugVariable where storage for the strings has been
 /// tail-allocated following the parent SILInstruction.
 class TailAllocatedDebugVariable {
-  /// The source function argument position from left to right
-  /// starting with 1 or 0 if this is a local variable.
-  unsigned ArgNo : 16;
-  /// When this is nonzero there is a tail-allocated string storing
-  /// variable name present. This typically only happens for
-  /// instructions that were created from parsing SIL assembler.
-  unsigned NameLength : 15;
-  bool Constant : 1;
+  union {
+    uint32_t RawValue;
+    struct {
+      /// The source function argument position from left to right
+      /// starting with 1 or 0 if this is a local variable.
+      unsigned ArgNo : 16;
+      bool Constant : 1;
+      /// When this is nonzero there is a tail-allocated string storing
+      /// variable name present. This typically only happens for
+      /// instructions that were created from parsing SIL assembler.
+      unsigned NameLength : 15;
+    } Data;
+  };
 public:
   TailAllocatedDebugVariable(SILDebugVariable DbgVar, char *buf);
+  TailAllocatedDebugVariable(uint32_t RawValue) : RawValue(RawValue) {}
+  uint32_t getRawValue() const { return RawValue; }
 
-  unsigned getArgNo() const { return ArgNo; }
-  void setArgNo(unsigned N) { ArgNo = N; }
+  unsigned getArgNo() const { return Data.ArgNo; }
+  void setArgNo(unsigned N) { Data.ArgNo = N; }
   /// Returns the name of the source variable, if it is stored in the
   /// instruction.
   StringRef getName(const char *buf) const;
-  bool isLet() const  { return Constant; }
+  bool isLet() const  { return Data.Constant; }
 
   SILDebugVariable get(VarDecl *VD, const char *buf) const {
     if (VD)
@@ -1186,6 +1189,8 @@
       return {getName(buf), isLet(), getArgNo()};
   }
 };
+static_assert(sizeof(TailAllocatedDebugVariable) == 4,
+              "SILNode inline bitfield needs updating");
 
 //===----------------------------------------------------------------------===//
 // Allocation Instructions
@@ -1202,24 +1207,6 @@
   DEFINE_ABSTRACT_SINGLE_VALUE_INST_BOILERPLATE(AllocationInst)
 };
 
-/// Base class for allocation/deallocation instructions where the allocation
-/// can be promoted to the stack.
-/// Note that IRGen can still decide to _not_ promote the allocation on the
-/// stack.
-class StackPromotable {
-
-  /// If true, the allocation can be done on the stack (the final decision is
-  /// in IRGen).
-  bool OnStack = false;
-
-public:
-  StackPromotable(bool OnStack) : OnStack(OnStack) { }
-
-  bool canAllocOnStack() const { return OnStack; }
-
-  void setStackAllocatable() { OnStack = true; }
-};
-
 /// AllocStackInst - This represents the allocation of an unboxed (i.e., no
 /// reference count) stack memory.  The memory is provided uninitialized.
 class AllocStackInst final
@@ -1229,9 +1216,6 @@
   friend TrailingObjects;
   friend SILBuilder;
 
-  unsigned NumOperands;
-  TailAllocatedDebugVariable VarInfo;
-
   AllocStackInst(SILDebugLocation Loc, SILType elementType,
                  ArrayRef<SILValue> TypeDependentOperands,
                  SILFunction &F,
@@ -1243,13 +1227,14 @@
                                 SILDebugVariable Var);
 
   size_t numTrailingObjects(OverloadToken<Operand>) const {
-    return NumOperands;
+    return SILInstruction::Bits.AllocStackInst.NumOperands;
   }
 
 public:
   ~AllocStackInst() {
     Operand *Operands = getTrailingObjects<Operand>();
-    for (unsigned i = 0, end = NumOperands; i < end; ++i) {
+    size_t end = SILInstruction::Bits.AllocStackInst.NumOperands;
+    for (unsigned i = 0; i < end; ++i) {
       Operands[i].~Operand();
     }
   }
@@ -1260,9 +1245,16 @@
 
   /// Return the debug variable information attached to this instruction.
   SILDebugVariable getVarInfo() const {
-    return VarInfo.get(getDecl(), getTrailingObjects<char>());
+    auto RawValue = SILInstruction::Bits.AllocStackInst.VarInfo;
+    auto VI = TailAllocatedDebugVariable(RawValue);
+    return VI.get(getDecl(), getTrailingObjects<char>());
   };
-  void setArgNo(unsigned N) { VarInfo.setArgNo(N); }
+  void setArgNo(unsigned N) {
+    auto RawValue = SILInstruction::Bits.AllocStackInst.VarInfo;
+    auto VI = TailAllocatedDebugVariable(RawValue);
+    VI.setArgNo(N);
+    SILInstruction::Bits.AllocStackInst.VarInfo = VI.getRawValue();
+  }
 
   /// getElementType - Get the type of the allocated memory (as opposed to the
   /// type of the instruction itself, which will be an address type).
@@ -1271,11 +1263,13 @@
   }
 
   ArrayRef<Operand> getAllOperands() const {
-    return { getTrailingObjects<Operand>(), NumOperands };
+    return { getTrailingObjects<Operand>(),
+             SILInstruction::Bits.AllocStackInst.NumOperands };
   }
 
   MutableArrayRef<Operand> getAllOperands() {
-    return { getTrailingObjects<Operand>(), NumOperands };
+    return { getTrailingObjects<Operand>(),
+             SILInstruction::Bits.AllocStackInst.NumOperands };
   }
 
   ArrayRef<Operand> getTypeDependentOperands() const {
@@ -1288,9 +1282,7 @@
 };
 
 /// The base class for AllocRefInst and AllocRefDynamicInst.
-class AllocRefInstBase
-    : public AllocationInst,
-      public StackPromotable {
+class AllocRefInstBase : public AllocationInst {
 protected:
 
   AllocRefInstBase(SILInstructionKind Kind,
@@ -1300,11 +1292,6 @@
                    ArrayRef<SILType> ElementTypes,
                    ArrayRef<SILValue> AllOperands);
 
-  // Number of tail-allocated arrays.
-  unsigned short NumTailTypes;
-
-  bool ObjC;
-
   /// The first NumTailTypes operands are counts for the tail allocated
   /// elements, the remaining operands are opened archetype operands.
   TailAllocatedOperandList<0> Operands;
@@ -1317,21 +1304,33 @@
     return reinterpret_cast<const SILType*>(Operands.asArray().end());
   }
 
+  unsigned getNumTailTypes() const {
+    return SILInstruction::Bits.AllocRefInstBase.NumTailTypes;
+  }
+
 public:
+  bool canAllocOnStack() const {
+    return SILInstruction::Bits.AllocRefInstBase.OnStack;
+  }
+
+  void setStackAllocatable(bool OnStack = true) {
+    SILInstruction::Bits.AllocRefInstBase.OnStack = OnStack;
+  }
+
   ArrayRef<SILType> getTailAllocatedTypes() const {
-    return {getTypeStorage(), NumTailTypes};
+    return {getTypeStorage(), getNumTailTypes()};
   }
 
   MutableArrayRef<SILType> getTailAllocatedTypes() {
-    return {getTypeStorage(), NumTailTypes};
+    return {getTypeStorage(), getNumTailTypes()};
   }
   
   ArrayRef<Operand> getTailAllocatedCounts() const {
-    return getAllOperands().slice(0, NumTailTypes);
+    return getAllOperands().slice(0, getNumTailTypes());
   }
 
   MutableArrayRef<Operand> getTailAllocatedCounts() {
-    return getAllOperands().slice(0, NumTailTypes);
+    return getAllOperands().slice(0, getNumTailTypes());
   }
 
   ArrayRef<Operand> getAllOperands() const {
@@ -1343,7 +1342,9 @@
   }
   
   /// Whether to use Objective-C's allocation mechanism (+allocWithZone:).
-  bool isObjC() const { return ObjC; }
+  bool isObjC() const {
+    return SILInstruction::Bits.AllocRefInstBase.ObjC;
+  }
 };
 
 /// AllocRefInst - This represents the primitive allocation of an instance
@@ -1376,11 +1377,11 @@
 
 public:
   ArrayRef<Operand> getTypeDependentOperands() const {
-    return getAllOperands().slice(NumTailTypes);
+    return getAllOperands().slice(getNumTailTypes());
   }
 
   MutableArrayRef<Operand> getTypeDependentOperands() {
-    return getAllOperands().slice(NumTailTypes);
+    return getAllOperands().slice(getNumTailTypes());
   }
 };
 
@@ -1414,15 +1415,15 @@
 
 public:
   SILValue getMetatypeOperand() const {
-    return getAllOperands()[NumTailTypes].get();
+    return getAllOperands()[getNumTailTypes()].get();
   }
 
   ArrayRef<Operand> getTypeDependentOperands() const {
-    return getAllOperands().slice(NumTailTypes + 1);
+    return getAllOperands().slice(getNumTailTypes() + 1);
   }
 
   MutableArrayRef<Operand> getTypeDependentOperands() {
-    return getAllOperands().slice(NumTailTypes + 1);
+    return getAllOperands().slice(getNumTailTypes() + 1);
   }
 };
 
@@ -1443,7 +1444,6 @@
          SILFunction &F, SILOpenedArchetypesState &OpenedArchetypes);
 
 public:
-
   SILType getValueType() const { return getType().getObjectType(); }
 };
 
@@ -2774,8 +2774,6 @@
   friend TrailingObjects;
   friend SILBuilder;
 
-  unsigned numBits;
-
   IntegerLiteralInst(SILDebugLocation Loc, SILType Ty, const APInt &Value);
 
   static IntegerLiteralInst *create(IntegerLiteralExpr *E,
@@ -2802,8 +2800,6 @@
   friend TrailingObjects;
   friend SILBuilder;
 
-  unsigned numBits;
-
   FloatLiteralInst(SILDebugLocation Loc, SILType Ty, const APInt &Bits);
 
   static FloatLiteralInst *create(FloatLiteralExpr *E, SILDebugLocation Loc,
@@ -2924,6 +2920,7 @@
 enum class LoadOwnershipQualifier {
   Unqualified, Take, Copy, Trivial
 };
+static_assert(2 == SILNode::NumLoadOwnershipQualifierBits, "Size mismatch");
 
 /// LoadInst - Represents a load from a memory location.
 class LoadInst
@@ -2932,8 +2929,6 @@
 {
   friend SILBuilder;
 
-  LoadOwnershipQualifier OwnershipQualifier;
-
   /// Constructs a LoadInst.
   ///
   /// \param DebugLoc The location of the expression that caused the load.
@@ -2943,12 +2938,14 @@
   LoadInst(SILDebugLocation DebugLoc, SILValue LValue,
            LoadOwnershipQualifier Q = LoadOwnershipQualifier::Unqualified)
       : UnaryInstructionBase(DebugLoc, LValue,
-                             LValue->getType().getObjectType()),
-        OwnershipQualifier(Q) {}
+                             LValue->getType().getObjectType()) {
+    SILInstruction::Bits.LoadInst.OwnershipQualifier = unsigned(Q);
+  }
 
 public:
   LoadOwnershipQualifier getOwnershipQualifier() const {
-    return OwnershipQualifier;
+    return LoadOwnershipQualifier(
+      SILInstruction::Bits.LoadInst.OwnershipQualifier);
   }
 };
 
@@ -2957,6 +2954,7 @@
 enum class StoreOwnershipQualifier {
   Unqualified, Init, Assign, Trivial
 };
+static_assert(2 == SILNode::NumStoreOwnershipQualifierBits, "Size mismatch");
 
 /// StoreInst - Represents a store from a memory location.
 class StoreInst
@@ -2966,7 +2964,6 @@
 
 private:
   FixedOperandList<2> Operands;
-  StoreOwnershipQualifier OwnershipQualifier;
 
   StoreInst(SILDebugLocation DebugLoc, SILValue Src, SILValue Dest,
             StoreOwnershipQualifier Qualifier);
@@ -2986,7 +2983,8 @@
   MutableArrayRef<Operand> getAllOperands() { return Operands.asArray(); }
 
   StoreOwnershipQualifier getOwnershipQualifier() const {
-    return OwnershipQualifier;
+    return StoreOwnershipQualifier(
+      SILInstruction::Bits.StoreInst.OwnershipQualifier);
   }
 };
 
@@ -3139,33 +3137,39 @@
                                   SingleValueInstruction> {
   friend class SILBuilder;
 
-  SILAccessKind AccessKind;
-  SILAccessEnforcement Enforcement;
-
   BeginAccessInst(SILDebugLocation loc, SILValue lvalue,
                   SILAccessKind accessKind, SILAccessEnforcement enforcement)
-      : UnaryInstructionBase(loc, lvalue, lvalue->getType()),
-        AccessKind(accessKind), Enforcement(enforcement) {
+      : UnaryInstructionBase(loc, lvalue, lvalue->getType()) {
+    SILInstruction::Bits.BeginAccessInst.AccessKind = unsigned(accessKind);
+    SILInstruction::Bits.BeginAccessInst.Enforcement = unsigned(enforcement);
 
     static_assert(unsigned(SILAccessKind::Last) < (1 << 2),
                   "reserve sufficient bits for serialized SIL");
     static_assert(unsigned(SILAccessEnforcement::Last) < (1 << 2),
                   "reserve sufficient bits for serialized SIL");
+
+    static_assert(unsigned(SILAccessKind::Last) <
+                  (1 << SILNode::NumSILAccessKindBits),
+                  "SILNode needs updating");
+    static_assert(unsigned(SILAccessEnforcement::Last) <
+                  (1 << SILNode::NumSILAccessEnforcementBits),
+                  "SILNode needs updating");
   }
 
 public:
   SILAccessKind getAccessKind() const {
-    return AccessKind;
+    return SILAccessKind(SILInstruction::Bits.BeginAccessInst.AccessKind);
   }
   void setAccessKind(SILAccessKind kind) {
-    AccessKind = kind;
+    SILInstruction::Bits.BeginAccessInst.AccessKind = unsigned(kind);
   }
 
   SILAccessEnforcement getEnforcement() const {
-    return Enforcement;
+    return
+      SILAccessEnforcement(SILInstruction::Bits.BeginAccessInst.Enforcement);
   }
   void setEnforcement(SILAccessEnforcement enforcement) {
-    Enforcement = enforcement;
+    SILInstruction::Bits.BeginAccessInst.Enforcement = unsigned(enforcement);
   }
 
   SILValue getSource() const {
@@ -3190,12 +3194,10 @@
                                   NonValueInstruction> {
   friend class SILBuilder;
 
-  bool Aborting;
-
 private:
-  EndAccessInst(SILDebugLocation loc, SILValue access,
-                bool aborting = false)
-    : UnaryInstructionBase(loc, access), Aborting(aborting) {
+  EndAccessInst(SILDebugLocation loc, SILValue access, bool aborting = false)
+      : UnaryInstructionBase(loc, access) {
+    SILInstruction::Bits.EndAccessInst.Aborting = aborting;
   }
 
 public:
@@ -3206,10 +3208,10 @@
   /// Only AccessKind::Init and AccessKind::Deinit accesses can be
   /// aborted.
   bool isAborting() const {
-    return Aborting;
+    return SILInstruction::Bits.EndAccessInst.Aborting;
   }
-  void setAborting(bool aborting) {
-    Aborting = aborting;
+  void setAborting(bool aborting = true) {
+    SILInstruction::Bits.EndAccessInst.Aborting = aborting;
   }
 
   BeginAccessInst *getBeginAccess() const {
@@ -3611,17 +3613,17 @@
     return SILType::getPrimitiveObjectType(refType.getReferentType());
   }
 
-  unsigned IsTake : 1; // FIXME: pack this somewhere
-
 protected:
   LoadReferenceInstBase(SILDebugLocation loc, SILValue lvalue, IsTake_t isTake)
     : UnaryInstructionBase<K, SingleValueInstruction>(loc, lvalue,
-                                             getResultType(lvalue->getType())),
-      IsTake(unsigned(isTake)) {
+                                             getResultType(lvalue->getType())) {
+    SILInstruction::Bits.LoadReferenceInstBaseT.IsTake = unsigned(isTake);
   }
 
 public:
-  IsTake_t isTake() const { return IsTake_t(IsTake); }
+  IsTake_t isTake() const {
+    return IsTake_t(SILInstruction::Bits.LoadReferenceInstBaseT.IsTake);
+  }
 };
 
 /// An abstract class representing a store to some kind of reference storage.
@@ -3629,13 +3631,13 @@
 class StoreReferenceInstBase : public InstructionBase<K, NonValueInstruction> {
   enum { Src, Dest };
   FixedOperandList<2> Operands;
-  unsigned IsInitializationOfDest : 1; // FIXME: pack this somewhere
 protected:
   StoreReferenceInstBase(SILDebugLocation loc, SILValue src, SILValue dest,
                          IsInitialization_t isInit)
     : InstructionBase<K, NonValueInstruction>(loc),
-      Operands(this, src, dest),
-      IsInitializationOfDest(unsigned(isInit)) {
+      Operands(this, src, dest) {
+    SILInstruction::Bits.StoreReferenceInstBaseT.IsInitializationOfDest =
+      unsigned(isInit);
   }
 
 public:
@@ -3643,10 +3645,12 @@
   SILValue getDest() const { return Operands[Dest].get(); }
 
   IsInitialization_t isInitializationOfDest() const {
-    return IsInitialization_t(IsInitializationOfDest);
+    return IsInitialization_t(
+      SILInstruction::Bits.StoreReferenceInstBaseT.IsInitializationOfDest);
   }
   void setIsInitializationOfDest(IsInitialization_t I) {
-    IsInitializationOfDest = (bool)I;
+    SILInstruction::Bits.StoreReferenceInstBaseT.IsInitializationOfDest =
+      (bool)I;
   }
 
   ArrayRef<Operand> getAllOperands() const { return Operands.asArray(); }
@@ -3727,16 +3731,6 @@
   };
 
 private:
-  // FIXME: compress storage
-
-  /// IsTakeOfSrc - True if ownership will be taken from the value at the source
-  /// memory location.
-  unsigned IsTakeOfSrc : 1;
-
-  /// IsInitializationOfDest - True if this is the initialization of the
-  /// uninitialized destination memory location.
-  unsigned IsInitializationOfDest : 1;
-
   FixedOperandList<2> Operands;
 
   CopyAddrInst(SILDebugLocation DebugLoc, SILValue Src, SILValue Dest,
@@ -3749,16 +3743,19 @@
   void setSrc(SILValue V) { Operands[Src].set(V); }
   void setDest(SILValue V) { Operands[Dest].set(V); }
 
-  IsTake_t isTakeOfSrc() const { return IsTake_t(IsTakeOfSrc); }
+  IsTake_t isTakeOfSrc() const {
+    return IsTake_t(SILInstruction::Bits.CopyAddrInst.IsTakeOfSrc);
+  }
   IsInitialization_t isInitializationOfDest() const {
-    return IsInitialization_t(IsInitializationOfDest);
+    return IsInitialization_t(
+      SILInstruction::Bits.CopyAddrInst.IsInitializationOfDest);
   }
 
   void setIsTakeOfSrc(IsTake_t T) {
-    IsTakeOfSrc = (bool)T;
+    SILInstruction::Bits.CopyAddrInst.IsTakeOfSrc = (bool)T;
   }
   void setIsInitializationOfDest(IsInitialization_t I) {
-    IsInitializationOfDest = (bool)I;
+    SILInstruction::Bits.CopyAddrInst.IsInitializationOfDest = (bool)I;
   }
 
   ArrayRef<Operand> getAllOperands() const { return Operands.asArray(); }
@@ -3945,22 +3942,26 @@
 {
   friend SILBuilder;
 
-  bool IsStrict, IsInvariant;
-
   PointerToAddressInst(SILDebugLocation DebugLoc, SILValue Operand, SILType Ty,
                        bool IsStrict, bool IsInvariant)
-    : UnaryInstructionBase(DebugLoc, Operand, Ty),
-      IsStrict(IsStrict), IsInvariant(IsInvariant) {}
+    : UnaryInstructionBase(DebugLoc, Operand, Ty) {
+    SILInstruction::Bits.PointerToAddressInst.IsStrict = IsStrict;
+    SILInstruction::Bits.PointerToAddressInst.IsInvariant = IsInvariant;
+  }
 
 public:
   /// Whether the returned address adheres to strict aliasing.
   /// If true, then the type of each memory access dependent on
   /// this address must be consistent with the memory's bound type.
-  bool isStrict() const { return IsStrict; }
+  bool isStrict() const {
+    return SILInstruction::Bits.PointerToAddressInst.IsStrict;
+  }
   /// Whether the returned address is invariant.
   /// If true, then loading from an address derived from this pointer always
   /// produces the same value.
-  bool isInvariant() const { return IsInvariant; }
+  bool isInvariant() const {
+    return SILInstruction::Bits.PointerToAddressInst.IsInvariant;
+  }
 };
 
 /// Convert a heap object reference to a different type without any runtime
@@ -4486,18 +4487,26 @@
     NonAtomic,
   };
 protected:
-  Atomicity atomicity;
-protected:
   RefCountingInst(SILInstructionKind Kind, SILDebugLocation DebugLoc)
-      : NonValueInstruction(Kind, DebugLoc), atomicity(Atomicity::Atomic) {}
+      : NonValueInstruction(Kind, DebugLoc) {
+    SILInstruction::Bits.RefCountingInst.atomicity = bool(Atomicity::Atomic);
+  }
 
 public:
-  void setAtomicity(Atomicity flag) { atomicity = flag; }
-  void setNonAtomic() { atomicity = Atomicity::NonAtomic; }
-  void setAtomic() { atomicity = Atomicity::Atomic; }
-  Atomicity getAtomicity() const { return atomicity; }
-  bool isNonAtomic() const { return atomicity == Atomicity::NonAtomic; }
-  bool isAtomic() const { return atomicity == Atomicity::Atomic; }
+  void setAtomicity(Atomicity flag) {
+    SILInstruction::Bits.RefCountingInst.atomicity = bool(flag);
+  }
+  void setNonAtomic() {
+    SILInstruction::Bits.RefCountingInst.atomicity = bool(Atomicity::NonAtomic);
+  }
+  void setAtomic() {
+    SILInstruction::Bits.RefCountingInst.atomicity = bool(Atomicity::Atomic);
+  }
+  Atomicity getAtomicity() const {
+    return Atomicity(SILInstruction::Bits.RefCountingInst.atomicity);
+  }
+  bool isNonAtomic() const { return getAtomicity() == Atomicity::NonAtomic; }
+  bool isAtomic() const { return getAtomicity() == Atomicity::Atomic; }
 
   DEFINE_ABSTRACT_NON_VALUE_INST_BOILERPLATE(RefCountingInst)
 };
@@ -4645,18 +4654,25 @@
 
 private:
   friend SILBuilder;
-  Atomicity atomicity;
 
   StrongPinInst(SILDebugLocation DebugLoc, SILValue operand,
                 Atomicity atomicity);
 
 public:
-  void setAtomicity(Atomicity flag) { atomicity = flag; }
-  void setNonAtomic() { atomicity = Atomicity::NonAtomic; }
-  void setAtomic() { atomicity = Atomicity::Atomic; }
-  Atomicity getAtomicity() const { return atomicity; }
-  bool isNonAtomic() const { return atomicity == Atomicity::NonAtomic; }
-  bool isAtomic() const { return atomicity == Atomicity::Atomic; }
+  void setAtomicity(Atomicity flag) {
+    SILInstruction::Bits.StrongPinInst.atomicity = bool(flag);
+  }
+  void setNonAtomic() {
+    SILInstruction::Bits.StrongPinInst.atomicity = bool(Atomicity::NonAtomic);
+  }
+  void setAtomic() {
+    SILInstruction::Bits.StrongPinInst.atomicity = bool(Atomicity::Atomic);
+  }
+  Atomicity getAtomicity() const {
+    return Atomicity(SILInstruction::Bits.StrongPinInst.atomicity);
+  }
+  bool isNonAtomic() const { return getAtomicity() == Atomicity::NonAtomic; }
+  bool isAtomic() const { return getAtomicity() == Atomicity::Atomic; }
 };
 
 /// StrongUnpinInst - Given that the operand is the result of a
@@ -5140,7 +5156,9 @@
   friend TrailingObjects;
   friend SILBuilder;
 
-  unsigned NumOperands;
+  unsigned _getNumOperands() const {
+    return SILInstruction::Bits.MetatypeInst.NumOperands;
+  };
 
   /// Constructs a MetatypeInst
   MetatypeInst(SILDebugLocation DebugLoc, SILType Metatype,
@@ -5153,25 +5171,25 @@
 public:
   ~MetatypeInst() {
     Operand *Operands = getTrailingObjects<Operand>();
-    for (unsigned i = 0, end = NumOperands; i < end; ++i) {
+    for (unsigned i = 0, end = _getNumOperands(); i < end; ++i) {
       Operands[i].~Operand();
     }
   }
 
   ArrayRef<Operand> getAllOperands() const {
-    return { getTrailingObjects<Operand>(), NumOperands };
+    return { getTrailingObjects<Operand>(), _getNumOperands() };
   }
 
   MutableArrayRef<Operand> getAllOperands() {
-    return { getTrailingObjects<Operand>(), NumOperands };
+    return { getTrailingObjects<Operand>(), _getNumOperands() };
   }
 
   ArrayRef<Operand> getTypeDependentOperands() const {
-    return { getTrailingObjects<Operand>(), NumOperands };
+    return { getTrailingObjects<Operand>(), _getNumOperands() };
   }
 
   MutableArrayRef<Operand> getTypeDependentOperands() {
-    return { getTrailingObjects<Operand>(), NumOperands };
+    return { getTrailingObjects<Operand>(), _getNumOperands() };
   }
 };
 
@@ -5206,14 +5224,16 @@
 {
   friend SILBuilder;
 
-  unsigned FieldNo;
-
   TupleExtractInst(SILDebugLocation DebugLoc, SILValue Operand,
                    unsigned FieldNo, SILType ResultTy)
-      : UnaryInstructionBase(DebugLoc, Operand, ResultTy), FieldNo(FieldNo) {}
+      : UnaryInstructionBase(DebugLoc, Operand, ResultTy) {
+    SILInstruction::Bits.TupleExtractInst.FieldNo = FieldNo;
+  }
 
 public:
-  unsigned getFieldNo() const { return FieldNo; }
+  unsigned getFieldNo() const {
+    return SILInstruction::Bits.TupleExtractInst.FieldNo;
+  }
 
   TupleType *getTupleType() const {
     return getOperand()->getType().getSwiftRValueType()->castTo<TupleType>();
@@ -5236,14 +5256,16 @@
 {
   friend SILBuilder;
 
-  unsigned FieldNo;
-
   TupleElementAddrInst(SILDebugLocation DebugLoc, SILValue Operand,
                        unsigned FieldNo, SILType ResultTy)
-      : UnaryInstructionBase(DebugLoc, Operand, ResultTy), FieldNo(FieldNo) {}
+      : UnaryInstructionBase(DebugLoc, Operand, ResultTy) {
+    SILInstruction::Bits.TupleElementAddrInst.FieldNo = FieldNo;
+  }
 
 public:
-  unsigned getFieldNo() const { return FieldNo; }
+  unsigned getFieldNo() const {
+    return SILInstruction::Bits.TupleElementAddrInst.FieldNo;
+  }
 
 
   TupleType *getTupleType() const {
@@ -5474,14 +5496,18 @@
 
   CanType LookupType;
   ProtocolConformanceRef Conformance;
-  unsigned NumOperands;
+
+  unsigned getNumOperands() const {
+    return SILInstruction::Bits.WitnessMethodInst.NumOperands;
+  }
 
   WitnessMethodInst(SILDebugLocation DebugLoc, CanType LookupType,
                     ProtocolConformanceRef Conformance, SILDeclRef Member,
                     SILType Ty, ArrayRef<SILValue> TypeDependentOperands)
       : InstructionBase(DebugLoc, Ty, Member),
-        LookupType(LookupType), Conformance(Conformance),
-        NumOperands(TypeDependentOperands.size()) {
+        LookupType(LookupType), Conformance(Conformance) {
+    SILInstruction::Bits.WitnessMethodInst.NumOperands =
+      TypeDependentOperands.size();
     TrailingOperandsList::InitOperandsList(getAllOperands().begin(), this,
                                            TypeDependentOperands);
   }
@@ -5506,7 +5532,7 @@
 public:
   ~WitnessMethodInst() {
     Operand *Operands = getTrailingObjects<Operand>();
-    for (unsigned i = 0, end = NumOperands; i < end; ++i) {
+    for (unsigned i = 0, end = getNumOperands(); i < end; ++i) {
       Operands[i].~Operand();
     }
   }
@@ -5520,19 +5546,19 @@
   ProtocolConformanceRef getConformance() const { return Conformance; }
 
   ArrayRef<Operand> getAllOperands() const {
-    return { getTrailingObjects<Operand>(), NumOperands };
+    return { getTrailingObjects<Operand>(), getNumOperands() };
   }
 
   MutableArrayRef<Operand> getAllOperands() {
-    return { getTrailingObjects<Operand>(), NumOperands };
+    return { getTrailingObjects<Operand>(), getNumOperands() };
   }
 
   ArrayRef<Operand> getTypeDependentOperands() const {
-    return { getTrailingObjects<Operand>(), NumOperands };
+    return { getTrailingObjects<Operand>(), getNumOperands() };
   }
 
   MutableArrayRef<Operand> getTypeDependentOperands() {
-    return { getTrailingObjects<Operand>(), NumOperands };
+    return { getTrailingObjects<Operand>(), getNumOperands() };
   }
 };
 
@@ -5992,15 +6018,16 @@
                                   SingleValueInstruction> {
   friend SILBuilder;
 
-  ValueOwnershipKind Kind;
-
   UncheckedOwnershipConversionInst(SILDebugLocation DebugLoc, SILValue operand,
                                    ValueOwnershipKind Kind)
-      : UnaryInstructionBase(DebugLoc, operand, operand->getType()),
-        Kind(Kind) {}
+      : UnaryInstructionBase(DebugLoc, operand, operand->getType()) {
+    SILInstruction::Bits.UncheckedOwnershipConversionInst.Kind = Kind;
+  }
 
 public:
-  ValueOwnershipKind getConversionOwnershipKind() const { return Kind; }
+  ValueOwnershipKind getConversionOwnershipKind() const {
+    return SILInstruction::Bits.UncheckedOwnershipConversionInst.Kind;
+  }
 };
 
 /// MarkDependenceInst - Marks that one value depends on another for
@@ -6125,14 +6152,23 @@
 /// most derived type of the allocated instance.
 class DeallocRefInst :
   public UnaryInstructionBase<SILInstructionKind::DeallocRefInst,
-                              DeallocationInst>,
-  public StackPromotable {
+                              DeallocationInst> {
   friend SILBuilder;
 
 private:
   DeallocRefInst(SILDebugLocation DebugLoc, SILValue Operand,
                  bool canBeOnStack = false)
-      : UnaryInstructionBase(DebugLoc, Operand), StackPromotable(canBeOnStack) {
+      : UnaryInstructionBase(DebugLoc, Operand) {
+    SILInstruction::Bits.DeallocRefInst.OnStack = canBeOnStack;
+  }
+
+public:
+  bool canAllocOnStack() const {
+    return SILInstruction::Bits.DeallocRefInst.OnStack;
+  }
+
+  void setStackAllocatable(bool OnStack) {
+    SILInstruction::Bits.DeallocRefInst.OnStack = OnStack;
   }
 };
 
@@ -6795,8 +6831,6 @@
                              TermInst> {
   friend SILBuilder;
 
-  unsigned NumCases : 31;
-  unsigned HasDefault : 1;
   TailAllocatedOperandList<1> Operands;
 
   SwitchValueInst(SILDebugLocation DebugLoc, SILValue Operand,
@@ -6838,20 +6872,24 @@
 
   SuccessorListTy getSuccessors() {
     return MutableArrayRef<SILSuccessor>{getSuccessorBuf(),
-                           static_cast<size_t>(NumCases + HasDefault)};
+                           static_cast<size_t>(getNumCases() + hasDefault())};
   }
 
-  unsigned getNumCases() const { return NumCases; }
+  unsigned getNumCases() const {
+    return SILInstruction::Bits.SwitchValueInst.NumCases;
+  }
   std::pair<SILValue, SILBasicBlock*>
   getCase(unsigned i) const {
-    assert(i < NumCases && "case out of bounds");
+    assert(i < getNumCases() && "case out of bounds");
     return {getCaseBuf()[i], getSuccessorBuf()[i]};
   }
 
-  bool hasDefault() const { return HasDefault; }
+  bool hasDefault() const {
+    return SILInstruction::Bits.SwitchValueInst.HasDefault;
+  }
   SILBasicBlock *getDefaultBB() const {
-    assert(HasDefault && "doesn't have a default");
-    return getSuccessorBuf()[NumCases];
+    assert(hasDefault() && "doesn't have a default");
+    return getSuccessorBuf()[getNumCases()];
   }
 };
 
@@ -6859,8 +6897,6 @@
 /// switch_enum_addr instructions.
 class SwitchEnumInstBase : public TermInst {
   FixedOperandList<1> Operands;
-  unsigned NumCases : 31;
-  unsigned HasDefault : 1;
 
   // Tail-allocated after the SwitchEnumInst record are:
   // - an array of `NumCases` EnumElementDecl* pointers, referencing the case
@@ -6881,10 +6917,10 @@
   }
 
   SILSuccessor *getSuccessorBuf() {
-    return reinterpret_cast<SILSuccessor*>(getCaseBuf() + NumCases);
+    return reinterpret_cast<SILSuccessor*>(getCaseBuf() + getNumCases());
   }
   const SILSuccessor *getSuccessorBuf() const {
-    return reinterpret_cast<const SILSuccessor*>(getCaseBuf() + NumCases);
+    return reinterpret_cast<const SILSuccessor*>(getCaseBuf() + getNumCases());
   }
 
 protected:
@@ -6912,17 +6948,19 @@
 
   SuccessorListTy getSuccessors() {
     return MutableArrayRef<SILSuccessor>{getSuccessorBuf(),
-                           static_cast<size_t>(NumCases + HasDefault)};
+                           static_cast<size_t>(getNumCases() + hasDefault())};
   }
 
-  unsigned getNumCases() const { return NumCases; }
+  unsigned getNumCases() const {
+    return SILInstruction::Bits.SwitchEnumInstBase.NumCases;
+  }
   std::pair<EnumElementDecl*, SILBasicBlock*>
   getCase(unsigned i) const {
-    assert(i < NumCases && "case out of bounds");
+    assert(i < getNumCases() && "case out of bounds");
     return {getCaseBuf()[i], getSuccessorBuf()[i].getBB()};
   }
   ProfileCounter getCaseCount(unsigned i) const {
-    assert(i < NumCases && "case out of bounds");
+    assert(i < getNumCases() && "case out of bounds");
     return getSuccessorBuf()[i].getCount();
   }
 
@@ -6948,14 +6986,16 @@
   /// return it.
   NullablePtr<EnumElementDecl> getUniqueCaseForDestination(SILBasicBlock *BB);
 
-  bool hasDefault() const { return HasDefault; }
+  bool hasDefault() const {
+    return SILInstruction::Bits.SwitchEnumInstBase.HasDefault;
+  }
   SILBasicBlock *getDefaultBB() const {
-    assert(HasDefault && "doesn't have a default");
-    return getSuccessorBuf()[NumCases];
+    assert(hasDefault() && "doesn't have a default");
+    return getSuccessorBuf()[getNumCases()];
   }
   ProfileCounter getDefaultCount() const {
-    assert(HasDefault && "doesn't have a default");
-    return getSuccessorBuf()[NumCases].getCount();
+    assert(hasDefault() && "doesn't have a default");
+    return getSuccessorBuf()[getNumCases()].getCount();
   }
 
   static bool classof(const SILInstruction *I) {
diff --git a/include/swift/SIL/SILNode.h b/include/swift/SIL/SILNode.h
index 8b383c8..6120cc4 100644
--- a/include/swift/SIL/SILNode.h
+++ b/include/swift/SIL/SILNode.h
@@ -19,6 +19,7 @@
 
 #include "llvm/Support/Compiler.h"
 #include "llvm/ADT/DenseMapInfo.h"
+#include "swift/Basic/InlineBitfield.h"
 #include "swift/Basic/LLVM.h"
 #include <type_traits>
 
@@ -43,11 +44,10 @@
 #include "swift/SIL/SILNodes.def"
 };
 
-enum {
-  NumSILNodeKindBits = 8
-};
-static_assert(unsigned(SILNodeKind::Last_SILNode) < (1 << NumSILNodeKindBits),
-              "SILNodeKind fits in NumSILNodeKindBits bits");
+enum { NumSILNodeKindBits =
+  countBitsUsed(static_cast<unsigned>(SILNodeKind::Last_SILNode)) };
+
+enum class SILInstructionKind : std::underlying_type<SILNodeKind>::type;
 
 /// A SILNode is a node in the use-def graph of a SILFunction.  It is
 /// either an instruction or a defined value which can be used by an
@@ -93,51 +93,269 @@
 ///   Always use the LLVM casts (cast<>, dyn_cast<>, etc.) instead.
 class alignas(8) SILNode {
 public:
-  /// The assumed number of bits that a SILNode+padding will take up. Public for
-  /// static assertion purposes.
-  static constexpr unsigned NumTotalSILNodeBits = 64;
-
-private:
-  static constexpr unsigned NumKindBits = NumSILNodeKindBits;
-  static constexpr unsigned NumStorageLocBits = 1;
-  static constexpr unsigned NumIsRepresentativeBits = 1;
-
+  enum { NumVOKindBits = 3 };
+  enum { NumStoreOwnershipQualifierBits = 2 };
+  enum { NumLoadOwnershipQualifierBits = 2 };
+  enum { NumSILAccessKindBits = 2 };
+  enum { NumSILAccessEnforcementBits = 2 };
 protected:
-  static constexpr unsigned NumSubclassDataBits =
-      NumTotalSILNodeBits - NumKindBits - NumStorageLocBits -
-      NumIsRepresentativeBits;
+  SWIFT_INLINE_BITFIELD_BASE(SILNode, bitmax(NumSILNodeKindBits,8)+1+1,
+    Kind : bitmax(NumSILNodeKindBits,8),
+    StorageLoc : 1,
+    IsRepresentativeNode : 1
+  );
+
+  SWIFT_INLINE_BITFIELD_EMPTY(ValueBase, SILNode);
+
+  SWIFT_INLINE_BITFIELD(SILArgument, ValueBase, NumVOKindBits,
+    VOKind : NumVOKindBits
+  );
+
+  // No MultipleValueInstructionResult subclass needs inline bits right now,
+  // therefore let's naturally align and size the Index for speed.
+  SWIFT_INLINE_BITFIELD_FULL(MultipleValueInstructionResult, ValueBase,
+                             NumVOKindBits+32,
+      VOKind : NumVOKindBits,
+      : NumPadBits,
+      Index : 32
+  );
+
+  SWIFT_INLINE_BITFIELD_EMPTY(SILInstruction, SILNode);
+
+  // Special handling for UnaryInstructionWithTypeDependentOperandsBase
+  SWIFT_INLINE_BITFIELD(UIWTDOB, SILNode, 32,
+    // DO NOT allocate bits at the front!
+    // UIWTDOB is a template, and must allocate bits from back to front and
+    // update UIWTDOB_BITFIELD().
+
+    /*pad*/ : 32-NumSILNodeBits,
+
+    // Total number of operands of this instruction.
+    // It is number of type dependent operands + 1.
+    NumOperands : 32;
+    template<SILInstructionKind Kind, typename, typename, typename...>
+    friend class UnaryInstructionWithTypeDependentOperandsBase
+  );
+
+#define UIWTDOB_BITFIELD(T, U, C, ...) \
+  SWIFT_INLINE_BITFIELD_FULL(T, U, (C)+32, __VA_ARGS__)
+
+  SWIFT_INLINE_BITFIELD_EMPTY(SingleValueInstruction, SILInstruction);
+  SWIFT_INLINE_BITFIELD_EMPTY(DeallocationInst, SILInstruction);
+  SWIFT_INLINE_BITFIELD_EMPTY(LiteralInst, SingleValueInstruction);
+  SWIFT_INLINE_BITFIELD_EMPTY(AllocationInst, SingleValueInstruction);
+
+  SWIFT_INLINE_BITFIELD_FULL(IntegerLiteralInst, LiteralInst, 32,
+    : NumPadBits,
+    numBits : 32
+  );
+
+  SWIFT_INLINE_BITFIELD_FULL(FloatLiteralInst, LiteralInst, 32,
+    : NumPadBits,
+    numBits : 32
+  );
+
+  SWIFT_INLINE_BITFIELD(DeallocRefInst, DeallocationInst, 1,
+    OnStack : 1
+  );
+
+  SWIFT_INLINE_BITFIELD_FULL(AllocStackInst, AllocationInst,
+                             64-NumAllocationInstBits,
+    NumOperands : 32-NumAllocationInstBits,
+    VarInfo : 32
+  );
+  SWIFT_INLINE_BITFIELD_FULL(AllocRefInstBase, AllocationInst, 1+1+32,
+    ObjC : 1,
+    OnStack : 1,
+    : NumPadBits,
+    // Number of tail-allocated arrays.
+    NumTailTypes : 32
+  );
+  UIWTDOB_BITFIELD(AllocValueBufferInst, AllocationInst, 0, : NumPadBits);
+
+  // TODO: Sort the following in SILNodes.def order
+
+  SWIFT_INLINE_BITFIELD_EMPTY(NonValueInstruction, SILInstruction);
+  SWIFT_INLINE_BITFIELD(RefCountingInst, NonValueInstruction, 1,
+      atomicity : 1
+  );
+  SWIFT_INLINE_BITFIELD(StrongPinInst, SingleValueInstruction, 1,
+      atomicity : 1
+  );
+
+  SWIFT_INLINE_BITFIELD_FULL(MetatypeInst, SingleValueInstruction, 32,
+      : NumPadBits,
+      NumOperands : 32
+  );
+
+  SWIFT_INLINE_BITFIELD(CopyAddrInst, NonValueInstruction, 1+1,
+    /// IsTakeOfSrc - True if ownership will be taken from the value at the
+    /// source memory location.
+    IsTakeOfSrc : 1,
+
+    /// IsInitializationOfDest - True if this is the initialization of the
+    /// uninitialized destination memory location.
+    IsInitializationOfDest : 1
+  );
+
+  SWIFT_INLINE_BITFIELD(LoadReferenceInstBaseT, NonValueInstruction, 1,
+    IsTake : 1;
+    template<SILInstructionKind K>
+    friend class LoadReferenceInstBase
+  );
+
+  SWIFT_INLINE_BITFIELD(StoreReferenceInstBaseT, NonValueInstruction, 1,
+    IsInitializationOfDest : 1;
+    template<SILInstructionKind K>
+    friend class StoreReferenceInstBase
+  );
+
+  SWIFT_INLINE_BITFIELD(BeginAccessInst, SingleValueInstruction,
+                        NumSILAccessKindBits+NumSILAccessEnforcementBits,
+    AccessKind : NumSILAccessKindBits,
+    Enforcement : NumSILAccessEnforcementBits
+  );
+
+  SWIFT_INLINE_BITFIELD(EndAccessInst, NonValueInstruction, 1,
+    Aborting : 1
+  );
+
+  SWIFT_INLINE_BITFIELD(StoreInst, NonValueInstruction,
+                        NumStoreOwnershipQualifierBits,
+    OwnershipQualifier : NumStoreOwnershipQualifierBits
+  );
+  SWIFT_INLINE_BITFIELD(LoadInst, SingleValueInstruction,
+                        NumLoadOwnershipQualifierBits,
+    OwnershipQualifier : NumLoadOwnershipQualifierBits
+  );
+
+  SWIFT_INLINE_BITFIELD(UncheckedOwnershipConversionInst,SingleValueInstruction,
+                        NumVOKindBits,
+    Kind : NumVOKindBits
+  );
+
+  SWIFT_INLINE_BITFIELD_FULL(TupleExtractInst, SingleValueInstruction, 32,
+    : NumPadBits,
+    FieldNo : 32
+  );
+  SWIFT_INLINE_BITFIELD_FULL(TupleElementAddrInst, SingleValueInstruction, 32,
+    : NumPadBits,
+    FieldNo : 32
+  );
+
+  SWIFT_INLINE_BITFIELD_EMPTY(MethodInst, SingleValueInstruction);
+  SWIFT_INLINE_BITFIELD_FULL(WitnessMethodInst, MethodInst, 32,
+    : NumPadBits,
+    NumOperands : 32
+  );
+  UIWTDOB_BITFIELD(ObjCMethodInst, MethodInst, 0, : NumPadBits);
+
+  SWIFT_INLINE_BITFIELD_EMPTY(ConversionInst, SingleValueInstruction);
+  SWIFT_INLINE_BITFIELD(PointerToAddressInst, ConversionInst, 1+1,
+    IsStrict : 1,
+    IsInvariant : 1
+  );
+
+  UIWTDOB_BITFIELD(ConvertFunctionInst, ConversionInst, 0, : NumPadBits);
+  UIWTDOB_BITFIELD(PointerToThinFunctionInst, ConversionInst, 0, : NumPadBits);
+  UIWTDOB_BITFIELD(UnconditionalCheckedCastInst, ConversionInst, 0, : NumPadBits);
+  UIWTDOB_BITFIELD(UpcastInst, ConversionInst, 0, : NumPadBits);
+  UIWTDOB_BITFIELD(UncheckedRefCastInst, ConversionInst, 0, : NumPadBits);
+  UIWTDOB_BITFIELD(UncheckedAddrCastInst, ConversionInst, 0, : NumPadBits);
+  UIWTDOB_BITFIELD(UncheckedTrivialBitCastInst, ConversionInst, 0, : NumPadBits);
+  UIWTDOB_BITFIELD(UncheckedBitwiseCastInst, ConversionInst, 0, : NumPadBits);
+  UIWTDOB_BITFIELD(ThinToThickFunctionInst, ConversionInst, 0, : NumPadBits);
+  UIWTDOB_BITFIELD(UnconditionalCheckedCastValueInst, ConversionInst, 0, : NumPadBits);
+  UIWTDOB_BITFIELD(InitExistentialAddrInst, SingleValueInstruction, 0, : NumPadBits);
+  UIWTDOB_BITFIELD(InitExistentialValueInst, SingleValueInstruction, 0, : NumPadBits);
+  UIWTDOB_BITFIELD(InitExistentialRefInst, SingleValueInstruction, 0, : NumPadBits);
+  UIWTDOB_BITFIELD(InitExistentialMetatypeInst, SingleValueInstruction, 0, : NumPadBits);
+
+  SWIFT_INLINE_BITFIELD_EMPTY(TermInst, SILInstruction);
+  UIWTDOB_BITFIELD(CheckedCastBranchInst, SingleValueInstruction, 0, : NumPadBits);
+  UIWTDOB_BITFIELD(CheckedCastValueBranchInst, SingleValueInstruction, 0, : NumPadBits);
+
+  SWIFT_INLINE_BITFIELD_FULL(SwitchValueInst, TermInst, 1+32,
+    HasDefault : 1,
+    : NumPadBits,
+    NumCases : 32
+  );
+  SWIFT_INLINE_BITFIELD_FULL(SwitchEnumInstBase, TermInst, 1+32,
+    HasDefault : 1,
+    : NumPadBits,
+    NumCases : 32
+  );
 
   enum class SILNodeStorageLocation : uint8_t { Value, Instruction };
 
-  enum class IsRepresentative : uint8_t {
-    No = 0,
-    Yes = 1,
+  enum class IsRepresentative : bool {
+    No = false,
+    Yes = true,
   };
 
+  union {
+    uint64_t OpaqueBits;
+    SWIFT_INLINE_BITS(SILNode);
+    SWIFT_INLINE_BITS(SILArgument);
+    SWIFT_INLINE_BITS(MultipleValueInstructionResult);
+    SWIFT_INLINE_BITS(UIWTDOB);
+    SWIFT_INLINE_BITS(AllocStackInst);
+    SWIFT_INLINE_BITS(AllocRefInstBase);
+    SWIFT_INLINE_BITS(AllocValueBufferInst);
+    SWIFT_INLINE_BITS(ConvertFunctionInst);
+    SWIFT_INLINE_BITS(PointerToThinFunctionInst);
+    SWIFT_INLINE_BITS(UpcastInst);
+    SWIFT_INLINE_BITS(UncheckedRefCastInst);
+    SWIFT_INLINE_BITS(UncheckedAddrCastInst);
+    SWIFT_INLINE_BITS(UncheckedTrivialBitCastInst);
+    SWIFT_INLINE_BITS(UncheckedBitwiseCastInst);
+    SWIFT_INLINE_BITS(ThinToThickFunctionInst);
+    SWIFT_INLINE_BITS(UnconditionalCheckedCastInst);
+    SWIFT_INLINE_BITS(UnconditionalCheckedCastValueInst);
+    SWIFT_INLINE_BITS(ObjCMethodInst);
+    SWIFT_INLINE_BITS(InitExistentialAddrInst);
+    SWIFT_INLINE_BITS(InitExistentialValueInst);
+    SWIFT_INLINE_BITS(InitExistentialRefInst);
+    SWIFT_INLINE_BITS(InitExistentialMetatypeInst);
+    SWIFT_INLINE_BITS(CheckedCastBranchInst);
+    SWIFT_INLINE_BITS(CheckedCastValueBranchInst);
+    SWIFT_INLINE_BITS(UncheckedOwnershipConversionInst);
+    SWIFT_INLINE_BITS(RefCountingInst);
+    SWIFT_INLINE_BITS(StoreReferenceInstBaseT);
+    SWIFT_INLINE_BITS(LoadReferenceInstBaseT);
+    SWIFT_INLINE_BITS(StrongPinInst);
+    SWIFT_INLINE_BITS(CopyAddrInst);
+    SWIFT_INLINE_BITS(StoreInst);
+    SWIFT_INLINE_BITS(LoadInst);
+    SWIFT_INLINE_BITS(IntegerLiteralInst);
+    SWIFT_INLINE_BITS(FloatLiteralInst);
+    SWIFT_INLINE_BITS(DeallocRefInst);
+    SWIFT_INLINE_BITS(WitnessMethodInst);
+    SWIFT_INLINE_BITS(TupleExtractInst);
+    SWIFT_INLINE_BITS(TupleElementAddrInst);
+    SWIFT_INLINE_BITS(SwitchValueInst);
+    SWIFT_INLINE_BITS(SwitchEnumInstBase);
+    SWIFT_INLINE_BITS(PointerToAddressInst);
+    SWIFT_INLINE_BITS(BeginAccessInst);
+    SWIFT_INLINE_BITS(EndAccessInst);
+    SWIFT_INLINE_BITS(MetatypeInst);
+  } Bits;
+
 private:
-  const uint64_t Kind : NumKindBits;
-  const uint64_t StorageLoc : NumStorageLocBits;
-  const uint64_t IsRepresentativeNode : NumIsRepresentativeBits;
-  uint64_t SubclassData : NumSubclassDataBits;
 
   SILNodeStorageLocation getStorageLoc() const {
-    return SILNodeStorageLocation(StorageLoc);
+    return SILNodeStorageLocation(Bits.SILNode.StorageLoc);
   }
 
   const SILNode *getRepresentativeSILNodeSlowPath() const;
 
 protected:
   SILNode(SILNodeKind kind, SILNodeStorageLocation storageLoc,
-          IsRepresentative isRepresentative)
-      : Kind(unsigned(kind)), StorageLoc(unsigned(storageLoc)),
-        IsRepresentativeNode(unsigned(isRepresentative)), SubclassData(0) {}
-
-  uint64_t getSubclassData() const { return SubclassData; }
-
-  void setSubclassData(uint64_t NewData) {
-    assert(!(NewData & ~((uint64_t(1) << NumSubclassDataBits) - 1)) &&
-           "New subclass data is too large to fit in SubclassData");
-    SubclassData = NewData;
+          IsRepresentative isRepresentative) {
+    Bits.OpaqueBits = 0;
+    Bits.SILNode.Kind = unsigned(kind);
+    Bits.SILNode.StorageLoc = unsigned(storageLoc);
+    Bits.SILNode.IsRepresentativeNode = unsigned(isRepresentative);
   }
 
 public:
@@ -154,7 +372,9 @@
   }
 
   /// Is this SILNode the representative SILNode subobject in this object?
-  bool isRepresentativeSILNodeInObject() const { return IsRepresentativeNode; }
+  bool isRepresentativeSILNodeInObject() const {
+    return Bits.SILNode.IsRepresentativeNode;
+  }
 
   /// Return a pointer to the representative SILNode subobject in this object.
   SILNode *getRepresentativeSILNodeInObject() {
@@ -171,7 +391,7 @@
 
   LLVM_ATTRIBUTE_ALWAYS_INLINE
   SILNodeKind getKind() const {
-    return SILNodeKind(Kind);
+    return SILNodeKind(Bits.SILNode.Kind);
   }
 
   /// Return the SILNodeKind of this node's representative SILNode.
diff --git a/include/swift/SIL/SILVTableVisitor.h b/include/swift/SIL/SILVTableVisitor.h
index 54c07d9..abf4f24 100644
--- a/include/swift/SIL/SILVTableVisitor.h
+++ b/include/swift/SIL/SILVTableVisitor.h
@@ -18,10 +18,8 @@
 #ifndef SWIFT_SIL_SILVTABLEVISITOR_H
 #define SWIFT_SIL_SILVTABLEVISITOR_H
 
-#include "swift/AST/Attr.h"
 #include "swift/AST/Decl.h"
 #include "swift/AST/Types.h"
-#include "swift/SIL/TypeLowering.h"
 
 namespace swift {
 
@@ -35,9 +33,10 @@
 /// - addMethodOverride(SILDeclRef baseRef, SILDeclRef derivedRef):
 ///   update vtable entry for baseRef to call derivedRef
 ///
+/// - addPlaceholder(MissingMemberDecl *);
+///   introduce an entry for a method that could not be deserialized
+///
 template <class T> class SILVTableVisitor {
-  Lowering::TypeConverter &Types;
-
   T &asDerived() { return *static_cast<T*>(this); }
 
   void maybeAddMethod(FuncDecl *fd) {
@@ -71,15 +70,13 @@
     // Update any existing entries that it overrides.
     auto nextRef = declRef;
     while ((nextRef = nextRef.getNextOverriddenVTableEntry())) {
-      auto baseRef = Types.getOverriddenVTableEntry(nextRef);
+      auto baseRef = nextRef.getOverriddenVTableEntry();
       asDerived().addMethodOverride(baseRef, declRef);
       nextRef = baseRef;
     }
   }
 
 protected:
-  SILVTableVisitor(Lowering::TypeConverter &Types) : Types(Types) {}
-
   void addVTableEntries(ClassDecl *theClass) {
     // Imported classes do not have a vtable.
     if (!theClass->hasKnownSwiftImplementation())
diff --git a/include/swift/SIL/SILValue.h b/include/swift/SIL/SILValue.h
index e76db69..44039a9 100644
--- a/include/swift/SIL/SILValue.h
+++ b/include/swift/SIL/SILValue.h
@@ -114,7 +114,7 @@
   } Value;
 
   using UnderlyingType = std::underlying_type<innerty>::type;
-  static constexpr unsigned NumBits = 3;
+  static constexpr unsigned NumBits = SILNode::NumVOKindBits;
   static constexpr UnderlyingType MaxValue = (UnderlyingType(1) << NumBits);
   static constexpr uint64_t Mask = MaxValue - 1;
   static_assert(unsigned(ValueOwnershipKind::LastValueOwnershipKind) < MaxValue,
diff --git a/include/swift/SIL/SILWitnessVisitor.h b/include/swift/SIL/SILWitnessVisitor.h
index 5d82389..a2a9e70 100644
--- a/include/swift/SIL/SILWitnessVisitor.h
+++ b/include/swift/SIL/SILWitnessVisitor.h
@@ -24,9 +24,7 @@
 #include "swift/AST/ProtocolAssociations.h"
 #include "swift/AST/Types.h"
 #include "swift/SIL/TypeLowering.h"
-#include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/ErrorHandling.h"
-#include "llvm/Support/raw_ostream.h"
 
 namespace swift {
 
@@ -119,9 +117,6 @@
 
   /// Fallback for unexpected protocol requirements.
   void visitDecl(Decl *d) {
-#ifndef NDEBUG
-    d->print(llvm::errs());
-#endif
     llvm_unreachable("unhandled protocol requirement");
   }
 
diff --git a/include/swift/SIL/TypeLowering.h b/include/swift/SIL/TypeLowering.h
index 431f2d0..7bc9dcc 100644
--- a/include/swift/SIL/TypeLowering.h
+++ b/include/swift/SIL/TypeLowering.h
@@ -89,11 +89,6 @@
                                 : ParameterConvention::Direct_Unowned,
                             witnessMethodConformance);
 }
-inline CanSILFunctionType
-adjustFunctionType(CanSILFunctionType t, SILFunctionType::Representation rep) {
-  return adjustFunctionType(t, rep, t->getWitnessMethodConformanceOrNone());
-}
-  
 
 /// Flag used to place context-dependent TypeLowerings in their own arena which
 /// can be disposed when a generic context is exited.
@@ -704,11 +699,6 @@
   /// `constant` must refer to a method.
   SILParameterInfo getConstantSelfParameter(SILDeclRef constant);
 
-  /// Return the most derived override which requires a new vtable entry.
-  /// If the method does not override anything or no override is vtable
-  /// dispatched, will return the least derived method.
-  SILDeclRef getOverriddenVTableEntry(SILDeclRef method);
-
   /// Returns the SILFunctionType that must be used to perform a vtable dispatch
   /// to the given declaration.
   ///
@@ -729,7 +719,7 @@
     if (next.isNull())
       return getConstantInfo(constant);
 
-    auto base = getOverriddenVTableEntry(constant);
+    auto base = constant.getOverriddenVTableEntry();
     return getConstantOverrideInfo(constant, base);
   }
 
diff --git a/include/swift/SILOptimizer/Utils/Devirtualize.h b/include/swift/SILOptimizer/Utils/Devirtualize.h
index cde3124..1ccdaf0 100644
--- a/include/swift/SILOptimizer/Utils/Devirtualize.h
+++ b/include/swift/SILOptimizer/Utils/Devirtualize.h
@@ -31,6 +31,9 @@
 #include "llvm/ADT/ArrayRef.h"
 
 namespace swift {
+namespace OptRemark {
+class Emitter;
+}
 
 /// A pair representing results of devirtualization.
 ///  - The first element is the value representing the result of the
@@ -62,17 +65,22 @@
                       ClassHierarchyAnalysis::ClassList &Subs);
 
 DevirtualizationResult tryDevirtualizeApply(ApplySite AI,
-                                            ClassHierarchyAnalysis *CHA);
+                                            ClassHierarchyAnalysis *CHA,
+                                            OptRemark::Emitter *ORE = nullptr);
 bool canDevirtualizeApply(FullApplySite AI, ClassHierarchyAnalysis *CHA);
 bool isNominalTypeWithUnboundGenericParameters(SILType Ty, SILModule &M);
-bool canDevirtualizeClassMethod(FullApplySite AI, SILType ClassInstanceType);
+bool canDevirtualizeClassMethod(FullApplySite AI, SILType ClassInstanceType,
+                                OptRemark::Emitter *ORE = nullptr);
 SILFunction *getTargetClassMethod(SILModule &M, SILType ClassOrMetatypeType,
                                   MethodInst *MI);
 DevirtualizationResult devirtualizeClassMethod(FullApplySite AI,
-                                               SILValue ClassInstance);
+                                               SILValue ClassInstance,
+                                               OptRemark::Emitter *ORE);
 DevirtualizationResult tryDevirtualizeClassMethod(FullApplySite AI,
-                                                  SILValue ClassInstance);
-DevirtualizationResult tryDevirtualizeWitnessMethod(ApplySite AI);
+                                                  SILValue ClassInstance,
+                                                  OptRemark::Emitter *ORE);
+DevirtualizationResult
+tryDevirtualizeWitnessMethod(ApplySite AI, OptRemark::Emitter *ORE);
 }
 
 #endif
diff --git a/include/swift/Serialization/ModuleFile.h b/include/swift/Serialization/ModuleFile.h
index f701536..5c8e5cf 100644
--- a/include/swift/Serialization/ModuleFile.h
+++ b/include/swift/Serialization/ModuleFile.h
@@ -733,7 +733,7 @@
 
   virtual
   Optional<TinyPtrVector<ValueDecl *>>
-  loadNamedMembers(const IterableDeclContext *IDC, DeclName N,
+  loadNamedMembers(const IterableDeclContext *IDC, DeclBaseName N,
                    uint64_t contextData) override;
 
   virtual void
diff --git a/include/swift/Serialization/ModuleFormat.h b/include/swift/Serialization/ModuleFormat.h
index 46fe9e6..8b792ab 100644
--- a/include/swift/Serialization/ModuleFormat.h
+++ b/include/swift/Serialization/ModuleFormat.h
@@ -54,7 +54,7 @@
 /// in source control, you should also update the comment to briefly
 /// describe what change you made. The content of this comment isn't important;
 /// it just ensures a conflict if two people change the module format.
-const uint16_t VERSION_MINOR = 390; // Last change: remove 'volatile' bit from witness_method
+const uint16_t VERSION_MINOR = 391; // Last change: normal protocol conformance
 
 using DeclIDField = BCFixed<31>;
 
@@ -1215,11 +1215,11 @@
     NORMAL_PROTOCOL_CONFORMANCE,
     DeclIDField, // the protocol
     DeclContextIDField, // the decl that provided this conformance
-    BCVBR<5>, // value mapping count
     BCVBR<5>, // type mapping count
+    BCVBR<5>, // value mapping count
     BCVBR<5>, // requirement signature conformance count
     BCArray<DeclIDField>
-    // The array contains archetype-value pairs, then type declarations.
+    // The array contains type witnesses, then value witnesses.
     // Requirement signature conformances follow, then the substitution records
     // for the associated types.
   >;
diff --git a/include/swift/Subsystems.h b/include/swift/Subsystems.h
index c133755..5031fd8 100644
--- a/include/swift/Subsystems.h
+++ b/include/swift/Subsystems.h
@@ -184,10 +184,6 @@
                            unsigned WarnLongExpressionTypeChecking = 0,
                            unsigned ExpressionTimeoutThreshold = 0);
 
-  /// Once type checking is complete, this walks protocol requirements
-  /// to resolve default witnesses.
-  void finishTypeCheckingFile(SourceFile &SF);
-
   /// Now that we have type-checked an entire module, perform any type
   /// checking that requires the full module, e.g., Objective-C method
   /// override checking.
diff --git a/include/swift/Syntax/RawSyntax.h b/include/swift/Syntax/RawSyntax.h
index 3982724..5ab66be 100644
--- a/include/swift/Syntax/RawSyntax.h
+++ b/include/swift/Syntax/RawSyntax.h
@@ -100,6 +100,17 @@
 #define syntax_assert_token_is(Tok, Kind, Text) ({});
 #endif
 
+#ifndef NDEBUG
+#define syntax_assert_node_choice(Raw, CursorName, NodeName)                   \
+  ({                                                                           \
+    auto Child = Raw->getChild(Cursor::CursorName);                            \
+    auto Node = make<Syntax>(Child);                                           \
+    assert(check##CursorName##In##NodeName(Node));                             \
+  })
+#else
+#define syntax_assert_node_choice(Raw, CursorName, NodeName) ({});
+#endif
+
 namespace swift {
 namespace syntax {
 
diff --git a/include/swift/Syntax/Serialization/SyntaxSerialization.h b/include/swift/Syntax/Serialization/SyntaxSerialization.h
index 4de0417..9259095 100644
--- a/include/swift/Syntax/Serialization/SyntaxSerialization.h
+++ b/include/swift/Syntax/Serialization/SyntaxSerialization.h
@@ -68,6 +68,7 @@
       case syntax::TriviaKind::VerticalTab:
       case syntax::TriviaKind::Formfeed:
       case syntax::TriviaKind::Newline:
+      case syntax::TriviaKind::CarriageReturn:
       case syntax::TriviaKind::Backtick:
         out.mapRequired("value", value.Count);
         break;
@@ -93,6 +94,7 @@
     out.enumCase(value, "VerticalTab", syntax::TriviaKind::VerticalTab);
     out.enumCase(value, "Formfeed", syntax::TriviaKind::Formfeed);
     out.enumCase(value, "Newline", syntax::TriviaKind::Newline);
+    out.enumCase(value, "CarriageReturn", syntax::TriviaKind::CarriageReturn);
     out.enumCase(value, "LineComment", syntax::TriviaKind::LineComment);
     out.enumCase(value, "BlockComment", syntax::TriviaKind::BlockComment);
     out.enumCase(value, "DocLineComment", syntax::TriviaKind::DocLineComment);
diff --git a/include/swift/Syntax/SyntaxBuilders.h.gyb b/include/swift/Syntax/SyntaxBuilders.h.gyb
index 4614abf..7dd31e6 100644
--- a/include/swift/Syntax/SyntaxBuilders.h.gyb
+++ b/include/swift/Syntax/SyntaxBuilders.h.gyb
@@ -38,13 +38,12 @@
 
 public:
 %     for child in node.children:
+  ${node.name}Builder &use${child.name}(${child.type_name} ${child.name});
 %       child_node = NODE_MAP.get(child.syntax_kind)
 %       if child_node and child_node.is_syntax_collection():
 %         child_elt = child_node.collection_element_name
 %         child_elt_type = child_node.collection_element_type
   ${node.name}Builder &add${child_elt}(${child_elt_type} ${child_elt});
-%       else:
-  ${node.name}Builder &use${child.name}(${child.type_name} ${child.name});
 %       end
 %     end
 
diff --git a/include/swift/Syntax/SyntaxFactory.h.gyb b/include/swift/Syntax/SyntaxFactory.h.gyb
index 1911e04..a019934 100644
--- a/include/swift/Syntax/SyntaxFactory.h.gyb
+++ b/include/swift/Syntax/SyntaxFactory.h.gyb
@@ -59,8 +59,6 @@
   /// between these two numbers is the number of optional children.
   static std::pair<unsigned, unsigned> countChildren(SyntaxKind Kind);
 
-  static SyntaxKind getUnknownKind(SyntaxKind Kind);
-
   static Syntax
   makeBlankCollectionSyntax(SyntaxKind Kind);
 
diff --git a/include/swift/Syntax/SyntaxKind.h.gyb b/include/swift/Syntax/SyntaxKind.h.gyb
index dff3204..5462e85 100644
--- a/include/swift/Syntax/SyntaxKind.h.gyb
+++ b/include/swift/Syntax/SyntaxKind.h.gyb
@@ -63,6 +63,8 @@
 bool isTokenKind(SyntaxKind Kind);
 
 bool isUnknownKind(SyntaxKind Kind);
+
+SyntaxKind getUnknownKind(SyntaxKind Kind);
 } // end namespace syntax
 
 namespace json {
diff --git a/include/swift/Syntax/SyntaxNodes.h.gyb b/include/swift/Syntax/SyntaxNodes.h.gyb
index 78baadd..5b06ee2 100644
--- a/include/swift/Syntax/SyntaxNodes.h.gyb
+++ b/include/swift/Syntax/SyntaxNodes.h.gyb
@@ -100,6 +100,9 @@
 %   end
 % end
 
+bool checkAccessorListOrStmtListInAccessorBlock(const Syntax &S);
+bool checkInputInClosureSignature(const Syntax &S);
+bool checkContentInDictionaryExpr(const Syntax &S);
 }
 }
 
diff --git a/include/swift/Syntax/Trivia.h b/include/swift/Syntax/Trivia.h
index 8110678..16c0601 100644
--- a/include/swift/Syntax/Trivia.h
+++ b/include/swift/Syntax/Trivia.h
@@ -111,6 +111,9 @@
   /// A newline '\n' character.
   Newline,
 
+  /// A newline '\r' character.
+  CarriageReturn,
+
   /// A developer line comment, starting with '//'
   LineComment,
 
@@ -175,12 +178,18 @@
     return {TriviaKind::Formfeed, Count};
   }
 
-  /// Return a piece of trivia for some number of newline characters
+  /// Return a piece of trivia for some number of newline (LF) characters
   /// in a row.
   static TriviaPiece newlines(unsigned Count) {
     return {TriviaKind::Newline, Count};
   }
 
+  /// Return a piece of trivia for some number of carriage-return (CR)
+  /// characters in a row.
+  static TriviaPiece carriageReturns(unsigned Count) {
+    return {TriviaKind::CarriageReturn, Count};
+  }
+
   /// Return a piece of trivia for a single line of ('//') developer comment.
   static TriviaPiece lineComment(const OwnedString Text) {
     return {TriviaKind::LineComment, Text};
@@ -225,6 +234,7 @@
       case TriviaKind::GarbageText:
         return Text.size();
       case TriviaKind::Newline:
+      case TriviaKind::CarriageReturn:
       case TriviaKind::Space:
       case TriviaKind::Backtick:
       case TriviaKind::Tab:
@@ -385,7 +395,7 @@
   }
 
   /// Return a collection of trivia of some number of newline characters
-  // in a row.
+  /// in a row.
   static Trivia newlines(unsigned Count) {
     if (Count == 0) {
       return {};
@@ -393,8 +403,17 @@
     return {{TriviaPiece::newlines(Count)}};
   }
 
+  /// Return a collection of trivia of some number of carriage-return characters
+  /// in a row.
+  static Trivia carriageReturns(unsigned Count) {
+    if (Count == 0) {
+      return {};
+    }
+    return {{TriviaPiece::carriageReturns(Count)}};
+  }
+
   /// Return a collection of trivia with a single line of ('//')
-  // developer comment.
+  /// developer comment.
   static Trivia lineComment(const OwnedString Text) {
     assert(Text.str().startswith("//"));
     return {{TriviaPiece::lineComment(Text)}};
@@ -414,7 +433,7 @@
   }
 
   /// Return a collection of trivia with a documentation block
-  // comment ('/** ... */')
+  /// comment ('/** ... */')
   static Trivia docBlockComment(const OwnedString Text) {
     assert(Text.str().startswith("/**"));
     assert(Text.str().endswith("*/"));
diff --git a/include/swift/TBDGen/TBDGen.h b/include/swift/TBDGen/TBDGen.h
index 626b989..ba9121c 100644
--- a/include/swift/TBDGen/TBDGen.h
+++ b/include/swift/TBDGen/TBDGen.h
@@ -24,12 +24,11 @@
 class ModuleDecl;
 
 void enumeratePublicSymbols(FileUnit *module, llvm::StringSet<> &symbols,
-                            bool hasMultipleIRGenThreads);
+                            bool hasMultipleIGMs);
 void enumeratePublicSymbols(ModuleDecl *module, llvm::StringSet<> &symbols,
-                            bool hasMultipleIRGenThreads);
+                            bool hasMultipleIGMs);
 
-void writeTBDFile(ModuleDecl *M, llvm::raw_ostream &os,
-                  bool hasMultipleIRGenThreads,
+void writeTBDFile(ModuleDecl *M, llvm::raw_ostream &os, bool hasMultipleIGMs,
                   llvm::StringRef installName);
 
 } // end namespace swift
diff --git a/lib/AST/ASTContext.cpp b/lib/AST/ASTContext.cpp
index 88d630e..d53d188 100644
--- a/lib/AST/ASTContext.cpp
+++ b/lib/AST/ASTContext.cpp
@@ -1667,9 +1667,9 @@
 
 ArrayRef<AssociatedTypeDecl *> AssociatedTypeDecl::getOverriddenDecls() const {
   // If we already computed the set of overridden associated types, return it.
-  if (AssociatedTypeDeclBits.ComputedOverridden) {
+  if (Bits.AssociatedTypeDecl.ComputedOverridden) {
     // We didn't override any associated types, so return the empty set.
-    if (!AssociatedTypeDeclBits.HasOverridden)
+    if (!Bits.AssociatedTypeDecl.HasOverridden)
       return { };
 
     // Look up the overrides.
@@ -1680,8 +1680,8 @@
 
   // While we are computing overridden declarations, pretend there are none.
   auto mutableThis = const_cast<AssociatedTypeDecl *>(this);
-  mutableThis->AssociatedTypeDeclBits.ComputedOverridden = true;
-  mutableThis->AssociatedTypeDeclBits.HasOverridden = false;
+  mutableThis->Bits.AssociatedTypeDecl.ComputedOverridden = true;
+  mutableThis->Bits.AssociatedTypeDecl.HasOverridden = false;
 
   // Find associated types with the given name in all of the inherited
   // protocols.
@@ -1717,25 +1717,25 @@
                        inheritedAssociatedTypes.end(),
                        compareSimilarAssociatedTypes);
 
-  mutableThis->AssociatedTypeDeclBits.ComputedOverridden = false;
+  mutableThis->Bits.AssociatedTypeDecl.ComputedOverridden = false;
   return mutableThis->setOverriddenDecls(inheritedAssociatedTypes);
 }
 
 ArrayRef<AssociatedTypeDecl *> AssociatedTypeDecl::setOverriddenDecls(
                                   ArrayRef<AssociatedTypeDecl *> overridden) {
-  assert(!AssociatedTypeDeclBits.ComputedOverridden &&
+  assert(!Bits.AssociatedTypeDecl.ComputedOverridden &&
          "Overridden decls already computed");
-  AssociatedTypeDeclBits.ComputedOverridden = true;
+  Bits.AssociatedTypeDecl.ComputedOverridden = true;
 
   // If the set of overridden declarations is empty, note that.
   if (overridden.empty()) {
-    AssociatedTypeDeclBits.HasOverridden = false;
+    Bits.AssociatedTypeDecl.HasOverridden = false;
     return { };
   }
 
   // Record the overrides in the context.
   auto &ctx = getASTContext();
-  AssociatedTypeDeclBits.HasOverridden = true;
+  Bits.AssociatedTypeDecl.HasOverridden = true;
   auto overriddenCopy = ctx.AllocateCopy(overridden);
   auto inserted =
     ctx.Impl.AssociatedTypeOverrides.insert({this, overriddenCopy}).second;
@@ -3077,10 +3077,6 @@
         = C.Impl.getArena(arena).TupleTypes.FindNodeOrInsertPos(ID,InsertPos))
     return TT;
 
-  // Make a copy of the fields list into ASTContext owned memory.
-  TupleTypeElt *FieldsCopy =
-    C.AllocateCopy<TupleTypeElt>(Fields.begin(), Fields.end(), arena);
-
   bool IsCanonical = true;   // All canonical elts means this is canonical.
   for (const TupleTypeElt &Elt : Fields) {
     if (Elt.getType().isNull() || !Elt.getType()->isCanonical()) {
@@ -3089,11 +3085,12 @@
     }
   }
 
-  Fields = ArrayRef<TupleTypeElt>(FieldsCopy, Fields.size());
-
-  TupleType *New =
-      new (C, arena) TupleType(Fields, IsCanonical ? &C : nullptr,
-                               properties, hasInOut);
+  // TupleType will copy the fields list into ASTContext owned memory.
+  void *mem = C.Allocate(sizeof(TupleType) +
+                         sizeof(TupleTypeElt) * Fields.size(),
+                         alignof(TupleType), arena);
+  auto New = new (mem) TupleType(Fields, IsCanonical ? &C : nullptr, properties,
+                                 hasInOut);
   C.Impl.getArena(arena).TupleTypes.InsertNode(New, InsertPos);
   return New;
 }
@@ -3247,8 +3244,12 @@
                                    const ASTContext *context,
                                    RecursiveTypeProperties properties)
   : TypeBase(theKind, context, properties),
-    TheDecl(theDecl), Parent(parent), GenericArgs(genericArgs)
+    TheDecl(theDecl), Parent(parent)
 {
+  Bits.BoundGenericType.GenericArgCount = genericArgs.size();
+  // Subtypes are required to provide storage for the generic arguments
+  std::uninitialized_copy(genericArgs.begin(), genericArgs.end(),
+                          getTrailingObjectsPointer());
 }
 
 BoundGenericType *BoundGenericType::get(NominalTypeDecl *TheDecl,
@@ -3277,7 +3278,6 @@
                                                                      InsertPos))
     return BGT;
 
-  ArrayRef<Type> ArgsCopy = C.AllocateCopy(GenericArgs, arena);
   bool IsCanonical = !Parent || Parent->isCanonical();
   if (IsCanonical) {
     for (Type Arg : GenericArgs) {
@@ -3290,15 +3290,22 @@
 
   BoundGenericType *newType;
   if (auto theClass = dyn_cast<ClassDecl>(TheDecl)) {
-    newType = new (C, arena) BoundGenericClassType(
-        theClass, Parent, ArgsCopy, IsCanonical ? &C : nullptr, properties);
+    auto mem = C.Allocate(sizeof(BoundGenericClassType) + sizeof(Type) *
+                          GenericArgs.size(), alignof(Type), arena);
+    newType = new (mem) BoundGenericClassType(
+        theClass, Parent, GenericArgs, IsCanonical ? &C : nullptr, properties);
   } else if (auto theStruct = dyn_cast<StructDecl>(TheDecl)) {
-    newType = new (C, arena) BoundGenericStructType(
-        theStruct, Parent, ArgsCopy, IsCanonical ? &C : nullptr, properties);
+    auto mem = C.Allocate(sizeof(BoundGenericStructType) + sizeof(Type) *
+                          GenericArgs.size(), alignof(Type), arena);
+    newType = new (mem) BoundGenericStructType(
+        theStruct, Parent, GenericArgs, IsCanonical ? &C : nullptr, properties);
+  } else if (auto theEnum = dyn_cast<EnumDecl>(TheDecl)) {
+    auto mem = C.Allocate(sizeof(BoundGenericEnumType) + sizeof(Type) *
+                          GenericArgs.size(), alignof(Type), arena);
+    newType = new (mem) BoundGenericEnumType(
+        theEnum, Parent, GenericArgs, IsCanonical ? &C : nullptr, properties);
   } else {
-    auto theEnum = cast<EnumDecl>(TheDecl);
-    newType = new (C, arena) BoundGenericEnumType(
-        theEnum, Parent, ArgsCopy, IsCanonical ? &C : nullptr, properties);
+    llvm_unreachable("Unhandled NominalTypeDecl");
   }
   C.Impl.getArena(arena).BoundGenericTypes.InsertNode(newType, InsertPos);
 
@@ -3434,14 +3441,14 @@
           .FindNodeOrInsertPos(ID, InsertPos))
     return compTy;
 
-  auto compTy
-    = new (C, arena)
-        ProtocolCompositionType(isCanonical ? &C : nullptr,
-                                C.AllocateCopy(Members),
-                                HasExplicitAnyObject,
-                                properties);
-  C.Impl.getArena(arena).ProtocolCompositionTypes
-    .InsertNode(compTy, InsertPos);
+  // Use trailing objects for member type storage
+  auto mem = C.Allocate(sizeof(ProtocolCompositionType) + sizeof(Type) *
+                        Members.size(), alignof(Type), arena);
+  auto compTy = new (mem) ProtocolCompositionType(isCanonical ? &C : nullptr,
+                                                  Members,
+                                                  HasExplicitAnyObject,
+                                                  properties);
+  C.Impl.getArena(arena).ProtocolCompositionTypes.InsertNode(compTy, InsertPos);
   return compTy;
 }
 
@@ -3481,9 +3488,9 @@
                                  Optional<MetatypeRepresentation> repr)
     : TypeBase(kind, C, properties), InstanceType(instanceType) {
   if (repr) {
-    AnyMetatypeTypeBits.Representation = static_cast<char>(*repr) + 1;
+    Bits.AnyMetatypeType.Representation = static_cast<char>(*repr) + 1;
   } else {
-    AnyMetatypeTypeBits.Representation = 0;
+    Bits.AnyMetatypeType.Representation = 0;
   }
 }
 
@@ -3598,17 +3605,6 @@
   return properties;
 }
 
-ArrayRef<AnyFunctionType::Param> AnyFunctionType::getParams() const {
-  switch (getKind()) {
-  case TypeKind::Function:
-    return cast<FunctionType>(this)->getParams();
-  case TypeKind::GenericFunction:
-    return cast<GenericFunctionType>(this)->getParams();
-  default:
-    llvm_unreachable("Undefined function type");
-  }
-}
-
 AnyFunctionType *AnyFunctionType::withExtInfo(ExtInfo info) const {
   if (isa<FunctionType>(this))
     return FunctionType::get(getInput(), getResult(), info);
@@ -3867,14 +3863,13 @@
       GenericSig(genericSig),
       WitnessMethodConformance(witnessMethodConformance) {
 
-  SILFunctionTypeBits.HasErrorResult = errorResult.hasValue();
-  SILFunctionTypeBits.ExtInfo = ext.Bits;
+  Bits.SILFunctionType.HasErrorResult = errorResult.hasValue();
+  Bits.SILFunctionType.ExtInfo = ext.Bits;
   // The use of both assert() and static_assert() below is intentional.
-  assert(SILFunctionTypeBits.ExtInfo == ext.Bits && "Bits were dropped!");
-  static_assert(ExtInfo::NumMaskBits ==
-                SILFunctionTypeBitfields::NumExtInfoBits,
+  assert(Bits.SILFunctionType.ExtInfo == ext.Bits && "Bits were dropped!");
+  static_assert(ExtInfo::NumMaskBits == NumSILExtInfoBits,
                 "ExtInfo and SILFunctionTypeBitfields must agree on bit size");
-  SILFunctionTypeBits.CoroutineKind = unsigned(coroutineKind);
+  Bits.SILFunctionType.CoroutineKind = unsigned(coroutineKind);
   NumParameters = params.size();
   if (coroutineKind == SILCoroutineKind::None) {
     assert(yields.empty());
@@ -3895,7 +3890,7 @@
   }
 
   assert(!isIndirectFormalParameter(calleeConvention));
-  SILFunctionTypeBits.CalleeConvention = unsigned(calleeConvention);
+  Bits.SILFunctionType.CalleeConvention = unsigned(calleeConvention);
 
   memcpy(getMutableParameters().data(), params.data(),
          params.size() * sizeof(SILParameterInfo));
diff --git a/lib/AST/ASTDumper.cpp b/lib/AST/ASTDumper.cpp
index 75f2e93..3f3ecaf 100644
--- a/lib/AST/ASTDumper.cpp
+++ b/lib/AST/ASTDumper.cpp
@@ -1807,16 +1807,20 @@
     PrintWithColorRAII(OS, ParenthesisColor) << ')';
   }
   void visitOverloadedDeclRefExpr(OverloadedDeclRefExpr *E) {
-    printCommon(E, "overloaded_decl_ref_expr")
-      << " name=" << E->getDecls()[0]->getBaseName()
-      << " #decls=" << E->getDecls().size()
-      << " function_ref=" << getFunctionRefKindStr(E->getFunctionRefKind());
-
-    for (ValueDecl *D : E->getDecls()) {
-      OS << '\n';
-      OS.indent(Indent);
-      D->dumpRef(OS);
-    }
+    printCommon(E, "overloaded_decl_ref_expr");
+    PrintWithColorRAII(OS, IdentifierColor) << " name="
+      << E->getDecls()[0]->getBaseName();
+    PrintWithColorRAII(OS, ExprModifierColor)
+      << " number_of_decls=" << E->getDecls().size()
+      << " function_ref=" << getFunctionRefKindStr(E->getFunctionRefKind())
+      << " decls=[\n";
+    interleave(E->getDecls(),
+               [&](ValueDecl *D) {
+                 OS.indent(Indent + 2);
+                 D->dumpRef(PrintWithColorRAII(OS, DeclModifierColor).getOS());
+               },
+               [&] { PrintWithColorRAII(OS, DeclModifierColor) << ",\n"; });
+    PrintWithColorRAII(OS, ExprModifierColor) << "]";
     PrintWithColorRAII(OS, ParenthesisColor) << ')';
   }
   void visitUnresolvedDeclRefExpr(UnresolvedDeclRefExpr *E) {
diff --git a/lib/AST/ASTMangler.cpp b/lib/AST/ASTMangler.cpp
index b229394..ce2e2eb 100644
--- a/lib/AST/ASTMangler.cpp
+++ b/lib/AST/ASTMangler.cpp
@@ -388,7 +388,12 @@
     bindGenericParameters(DC);
   DeclCtx = DC;
 
-  appendType(Ty);
+  if (auto *fnType = Ty->getAs<AnyFunctionType>()) {
+    appendFunction(fnType, false);
+  } else {
+    appendType(Ty);
+  }
+
   appendOperator("D");
   return finalize();
 }
@@ -1446,6 +1451,32 @@
   addSubstitution(key.getPointer());
 }
 
+void ASTMangler::appendFunction(AnyFunctionType *fn, bool isFunctionMangling) {
+  // Append parameter labels right before the signature/type.
+  auto parameters = fn->getParams();
+  auto firstLabel = std::find_if(
+                  parameters.begin(), parameters.end(),
+                  [&](AnyFunctionType::Param param) { return param.hasLabel(); });
+
+  if (firstLabel != parameters.end()) {
+    for (auto param : parameters) {
+      auto label = param.getLabel();
+      if (!label.empty())
+        appendIdentifier(label.str());
+      else
+        appendOperator("_");
+    }
+  } else if (parameters.size() > 0) {
+    appendOperator("y");
+  }
+
+  if (isFunctionMangling) {
+    appendFunctionSignature(fn);
+  } else {
+    appendFunctionType(fn);
+  }
+}
+
 void ASTMangler::appendFunctionType(AnyFunctionType *fn) {
   assert((DWARFMangling || fn->isCanonical()) &&
          "expecting canonical types when not mangling for the debugger");
@@ -1500,7 +1531,7 @@
     // it as a single type dropping sugar.
     if (!param.hasLabel() && !param.isVariadic() &&
         !isa<TupleType>(type.getPointer())) {
-      appendTypeListElement(param.getLabel(), type, param.getParameterFlags());
+      appendTypeListElement(Identifier(), type, param.getParameterFlags());
       break;
     }
 
@@ -1512,7 +1543,7 @@
   default:
     bool isFirstParam = true;
     for (auto &param : params) {
-      appendTypeListElement(param.getLabel(), param.getType(),
+      appendTypeListElement(Identifier(), param.getType(),
                             param.getParameterFlags());
       appendListSeparator(isFirstParam);
     }
@@ -1849,11 +1880,7 @@
   auto type = getDeclTypeForMangling(decl, genericSig, parentGenericSig);
 
   if (AnyFunctionType *FuncTy = type->getAs<AnyFunctionType>()) {
-    if (isFunctionMangling) {
-      appendFunctionSignature(FuncTy);
-    } else {
-      appendFunctionType(FuncTy);
-    }
+    appendFunction(FuncTy, isFunctionMangling);
   } else {
     appendType(type);
   }
diff --git a/lib/AST/Builtins.cpp b/lib/AST/Builtins.cpp
index 2559621..fb7f872 100644
--- a/lib/AST/Builtins.cpp
+++ b/lib/AST/Builtins.cpp
@@ -1103,11 +1103,11 @@
 static ValueDecl *getOnceOperation(ASTContext &Context,
                                    Identifier Id,
                                    bool withContext) {
-  // (RawPointer, @convention(thin) ([Context]) -> ()[, Context]) -> ()
+  // (RawPointer, @convention(c) ([Context]) -> ()[, Context]) -> ()
   
   auto HandleTy = Context.TheRawPointerType;
   auto VoidTy = Context.TheEmptyTupleType;
-  auto Thin = FunctionType::ExtInfo(FunctionTypeRepresentation::Thin,
+  auto Thin = FunctionType::ExtInfo(FunctionTypeRepresentation::CFunctionPointer,
                                     /*throws*/ false);
   if (withContext) {
     auto ContextTy = Context.TheRawPointerType;
diff --git a/lib/AST/CMakeLists.txt b/lib/AST/CMakeLists.txt
index 64a29a1..b4da5ed 100644
--- a/lib/AST/CMakeLists.txt
+++ b/lib/AST/CMakeLists.txt
@@ -44,6 +44,7 @@
   PrettyStackTrace.cpp
   ProtocolConformance.cpp
   RawComment.cpp
+  RequirementEnvironment.cpp
   SyntaxASTMap.cpp
   SILLayout.cpp
   Stmt.cpp
diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp
index e7b7ec2..67cd773 100644
--- a/lib/AST/Decl.cpp
+++ b/lib/AST/Decl.cpp
@@ -757,9 +757,10 @@
 
 ImportDecl::ImportDecl(DeclContext *DC, SourceLoc ImportLoc, ImportKind K,
                        SourceLoc KindLoc, ArrayRef<AccessPathElement> Path)
-  : Decl(DeclKind::Import, DC), ImportLoc(ImportLoc), KindLoc(KindLoc),
-    NumPathElements(Path.size()) {
-  ImportDeclBits.ImportKind = static_cast<unsigned>(K);
+  : Decl(DeclKind::Import, DC), ImportLoc(ImportLoc), KindLoc(KindLoc) {
+  Bits.ImportDecl.NumPathElements = Path.size();
+  assert(Bits.ImportDecl.NumPathElements == Path.size() && "Truncation error");
+  Bits.ImportDecl.ImportKind = static_cast<unsigned>(K);
   assert(getImportKind() == K && "not enough bits for ImportKind");
   std::uninitialized_copy(Path.begin(), Path.end(),
                           getTrailingObjects<AccessPathElement>());
@@ -837,9 +838,9 @@
 
 void NominalTypeDecl::setConformanceLoader(LazyMemberLoader *lazyLoader,
                                            uint64_t contextData) {
-  assert(!NominalTypeDeclBits.HasLazyConformances &&
+  assert(!Bits.NominalTypeDecl.HasLazyConformances &&
          "Already have lazy conformances");
-  NominalTypeDeclBits.HasLazyConformances = true;
+  Bits.NominalTypeDecl.HasLazyConformances = true;
 
   ASTContext &ctx = getASTContext();
   auto contextInfo = ctx.getOrCreateLazyIterableContextData(this, lazyLoader);
@@ -848,8 +849,8 @@
 
 std::pair<LazyMemberLoader *, uint64_t>
 NominalTypeDecl::takeConformanceLoaderSlow() {
-  assert(NominalTypeDeclBits.HasLazyConformances && "not lazy conformances");
-  NominalTypeDeclBits.HasLazyConformances = false;
+  assert(Bits.NominalTypeDecl.HasLazyConformances && "not lazy conformances");
+  Bits.NominalTypeDecl.HasLazyConformances = false;
   auto contextInfo =
     getASTContext().getOrCreateLazyIterableContextData(this, nullptr);
   return { contextInfo->loader, contextInfo->allConformancesData };
@@ -867,9 +868,9 @@
     ExtendedType(extendedType),
     Inherited(inherited)
 {
-  ExtensionDeclBits.CheckedInheritanceClause = false;
-  ExtensionDeclBits.DefaultAndMaxAccessLevel = 0;
-  ExtensionDeclBits.HasLazyConformances = false;
+  Bits.ExtensionDecl.CheckedInheritanceClause = false;
+  Bits.ExtensionDecl.DefaultAndMaxAccessLevel = 0;
+  Bits.ExtensionDecl.HasLazyConformances = false;
   setTrailingWhereClause(trailingWhereClause);
 }
 
@@ -896,9 +897,9 @@
 
 void ExtensionDecl::setConformanceLoader(LazyMemberLoader *lazyLoader,
                                          uint64_t contextData) {
-  assert(!ExtensionDeclBits.HasLazyConformances && 
+  assert(!Bits.ExtensionDecl.HasLazyConformances && 
          "Already have lazy conformances");
-  ExtensionDeclBits.HasLazyConformances = true;
+  Bits.ExtensionDecl.HasLazyConformances = true;
 
   ASTContext &ctx = getASTContext();
   auto contextInfo = ctx.getOrCreateLazyIterableContextData(this, lazyLoader);
@@ -907,8 +908,8 @@
 
 std::pair<LazyMemberLoader *, uint64_t>
 ExtensionDecl::takeConformanceLoaderSlow() {
-  assert(ExtensionDeclBits.HasLazyConformances && "no conformance loader?");
-  ExtensionDeclBits.HasLazyConformances = false;
+  assert(Bits.ExtensionDecl.HasLazyConformances && "no conformance loader?");
+  Bits.ExtensionDecl.HasLazyConformances = false;
 
   auto contextInfo =
     getASTContext().getOrCreateLazyIterableContextData(this, nullptr);
@@ -937,10 +938,10 @@
                                        DeclContext *Parent)
   : Decl(DeclKind::PatternBinding, Parent),
     StaticLoc(StaticLoc), VarLoc(VarLoc) {
-  PatternBindingDeclBits.IsStatic = StaticLoc.isValid();
-  PatternBindingDeclBits.StaticSpelling =
+  Bits.PatternBindingDecl.IsStatic = StaticLoc.isValid();
+  Bits.PatternBindingDecl.StaticSpelling =
        static_cast<unsigned>(StaticSpelling);
-  PatternBindingDeclBits.NumPatternEntries = NumPatternEntries;
+  Bits.PatternBindingDecl.NumPatternEntries = NumPatternEntries;
 }
 
 PatternBindingDecl *
@@ -2488,7 +2489,7 @@
                              GenericParamList *GenericParams, DeclContext *DC)
   : GenericTypeDecl(DeclKind::TypeAlias, DC, Name, NameLoc, {}, GenericParams),
     TypeAliasLoc(TypeAliasLoc), EqualLoc(EqualLoc) {
-  TypeAliasDeclBits.IsCompatibilityAlias = false;
+  Bits.TypeAliasDecl.IsCompatibilityAlias = false;
 }
 
 SourceRange TypeAliasDecl::getSourceRange() const {
@@ -2562,9 +2563,11 @@
 GenericTypeParamDecl::GenericTypeParamDecl(DeclContext *dc, Identifier name,
                                            SourceLoc nameLoc,
                                            unsigned depth, unsigned index)
-  : AbstractTypeParamDecl(DeclKind::GenericTypeParam, dc, name, nameLoc),
-    Depth(depth), Index(index)
-{
+  : AbstractTypeParamDecl(DeclKind::GenericTypeParam, dc, name, nameLoc) {
+  Bits.GenericTypeParamDecl.Depth = depth;
+  assert(Bits.GenericTypeParamDecl.Depth == depth && "Truncation");
+  Bits.GenericTypeParamDecl.Index = index;
+  assert(Bits.GenericTypeParamDecl.Index == index && "Truncation");
   auto &ctx = dc->getASTContext();
   auto type = new (ctx, AllocationArena::Permanent) GenericTypeParamType(this);
   setInterfaceType(MetatypeType::get(type, ctx));
@@ -2587,8 +2590,8 @@
       KeywordLoc(keywordLoc), DefaultDefinition(defaultDefinition),
       TrailingWhere(trailingWhere) {
 
-  AssociatedTypeDeclBits.ComputedOverridden = false;
-  AssociatedTypeDeclBits.HasOverridden = false;
+  Bits.AssociatedTypeDecl.ComputedOverridden = false;
+  Bits.AssociatedTypeDecl.HasOverridden = false;
 }
 
 AssociatedTypeDecl::AssociatedTypeDecl(DeclContext *dc, SourceLoc keywordLoc,
@@ -2600,8 +2603,8 @@
       KeywordLoc(keywordLoc), TrailingWhere(trailingWhere),
       Resolver(definitionResolver), ResolverContextData(resolverData) {
   assert(Resolver && "missing resolver");
-  AssociatedTypeDeclBits.ComputedOverridden = false;
-  AssociatedTypeDeclBits.HasOverridden = false;
+  Bits.AssociatedTypeDecl.ComputedOverridden = false;
+  Bits.AssociatedTypeDecl.HasOverridden = false;
 }
 
 void AssociatedTypeDecl::computeType() {
@@ -2661,9 +2664,9 @@
                     GenericParams),
     EnumLoc(EnumLoc)
 {
-  EnumDeclBits.Circularity
+  Bits.EnumDecl.Circularity
     = static_cast<unsigned>(CircularityCheck::Unchecked);
-  EnumDeclBits.HasAssociatedValues
+  Bits.EnumDecl.HasAssociatedValues
     = static_cast<unsigned>(AssociatedValueCheck::Unchecked);
 }
 
@@ -2674,7 +2677,7 @@
                     GenericParams),
     StructLoc(StructLoc)
 {
-  StructDeclBits.HasUnreferenceableStorage = false;
+  Bits.StructDecl.HasUnreferenceableStorage = false;
 }
 
 ClassDecl::ClassDecl(SourceLoc ClassLoc, Identifier Name, SourceLoc NameLoc,
@@ -2683,16 +2686,16 @@
   : NominalTypeDecl(DeclKind::Class, Parent, Name, NameLoc, Inherited,
                     GenericParams),
     ClassLoc(ClassLoc) {
-  ClassDeclBits.Circularity
+  Bits.ClassDecl.Circularity
     = static_cast<unsigned>(CircularityCheck::Unchecked);
-  ClassDeclBits.RequiresStoredPropertyInits = 0;
-  ClassDeclBits.InheritsSuperclassInits
+  Bits.ClassDecl.RequiresStoredPropertyInits = 0;
+  Bits.ClassDecl.InheritsSuperclassInits
     = static_cast<unsigned>(StoredInheritsSuperclassInits::Unchecked);
-  ClassDeclBits.RawForeignKind = 0;
-  ClassDeclBits.HasDestructorDecl = 0;
-  ObjCKind = 0;
-  HasMissingDesignatedInitializers = 0;
-  HasMissingVTableEntries = 0;
+  Bits.ClassDecl.RawForeignKind = 0;
+  Bits.ClassDecl.HasDestructorDecl = 0;
+  Bits.ClassDecl.ObjCKind = 0;
+  Bits.ClassDecl.HasMissingDesignatedInitializers = 0;
+  Bits.ClassDecl.HasMissingVTableEntries = 0;
 }
 
 DestructorDecl *ClassDecl::getDestructor() {
@@ -2749,12 +2752,12 @@
   auto *mutableThis = const_cast<ClassDecl *>(this);
   (void)mutableThis->lookupDirect(getASTContext().Id_init,
                                   /*ignoreNewExtensions*/true);
-  return HasMissingDesignatedInitializers;
+  return Bits.ClassDecl.HasMissingDesignatedInitializers;
 }
 
 bool ClassDecl::hasMissingVTableEntries() const {
   (void)getMembers();
-  return HasMissingVTableEntries;
+  return Bits.ClassDecl.HasMissingVTableEntries;
 }
 
 bool ClassDecl::inheritsSuperclassInitializers(LazyResolver *resolver) {
@@ -2764,7 +2767,7 @@
 
   // Check whether we already have a cached answer.
   switch (static_cast<StoredInheritsSuperclassInits>(
-            ClassDeclBits.InheritsSuperclassInits)) {
+            Bits.ClassDecl.InheritsSuperclassInits)) {
   case StoredInheritsSuperclassInits::Unchecked:
     // Compute below.
     break;
@@ -2780,7 +2783,7 @@
   ClassDecl *superclassDecl;
   if (!getSuperclass() ||
       !(superclassDecl = getSuperclass()->getClassOrBoundGenericClass())) {
-    ClassDeclBits.InheritsSuperclassInits
+    Bits.ClassDecl.InheritsSuperclassInits
       = static_cast<unsigned>(StoredInheritsSuperclassInits::NotInherited);
     return false;
   }
@@ -2788,7 +2791,7 @@
   // If the superclass has known-missing designated initializers, inheriting
   // is unsafe.
   if (superclassDecl->hasMissingDesignatedInitializers()) {
-    ClassDeclBits.InheritsSuperclassInits
+    Bits.ClassDecl.InheritsSuperclassInits
       = static_cast<unsigned>(StoredInheritsSuperclassInits::NotInherited);
     return false;
   }
@@ -2840,7 +2843,7 @@
 
     // If this designated initializer wasn't overridden, we can't inherit.
     if (overriddenInits.count(ctor) == 0) {
-      ClassDeclBits.InheritsSuperclassInits
+      Bits.ClassDecl.InheritsSuperclassInits
         = static_cast<unsigned>(StoredInheritsSuperclassInits::NotInherited);
       return false;
     }
@@ -2848,15 +2851,15 @@
 
   // All of the direct superclass's designated initializers have been overridden
   // by the subclass. Initializers can be inherited.
-  ClassDeclBits.InheritsSuperclassInits
+  Bits.ClassDecl.InheritsSuperclassInits
     = static_cast<unsigned>(StoredInheritsSuperclassInits::Inherited);
   return true;
 }
 
 ObjCClassKind ClassDecl::checkObjCAncestry() const {
   // See if we've already computed this.
-  if (ObjCKind)
-    return ObjCClassKind(ObjCKind - 1);
+  if (Bits.ClassDecl.ObjCKind)
+    return ObjCClassKind(Bits.ClassDecl.ObjCKind - 1);
 
   llvm::SmallPtrSet<const ClassDecl *, 8> visited;
   bool genericAncestry = false, isObjC = false;
@@ -2893,7 +2896,7 @@
     kind = ObjCClassKind::ObjCWithSwiftRoot;
 
   // Save the result for later.
-  const_cast<ClassDecl *>(this)->ObjCKind
+  const_cast<ClassDecl *>(this)->Bits.ClassDecl.ObjCKind
     = unsigned(kind) + 1;
   return kind;
 }
@@ -3020,7 +3023,7 @@
 bool EnumDecl::hasOnlyCasesWithoutAssociatedValues() const {
   // Check whether we already have a cached answer.
   switch (static_cast<AssociatedValueCheck>(
-            EnumDeclBits.HasAssociatedValues)) {
+            Bits.EnumDecl.HasAssociatedValues)) {
     case AssociatedValueCheck::Unchecked:
       // Compute below.
       break;
@@ -3033,12 +3036,12 @@
   }
   for (auto elt : getAllElements()) {
     if (elt->hasAssociatedValues()) {
-      EnumDeclBits.HasAssociatedValues
+      const_cast<EnumDecl*>(this)->Bits.EnumDecl.HasAssociatedValues
         = static_cast<unsigned>(AssociatedValueCheck::HasAssociatedValues);
       return false;
     }
   }
-  EnumDeclBits.HasAssociatedValues
+  const_cast<EnumDecl*>(this)->Bits.EnumDecl.HasAssociatedValues
     = static_cast<unsigned>(AssociatedValueCheck::NoAssociatedValues);
   return true;
 }
@@ -3050,15 +3053,15 @@
     : NominalTypeDecl(DeclKind::Protocol, DC, Name, NameLoc, Inherited,
                       nullptr),
       ProtocolLoc(ProtocolLoc), TrailingWhere(TrailingWhere) {
-  ProtocolDeclBits.RequiresClassValid = false;
-  ProtocolDeclBits.RequiresClass = false;
-  ProtocolDeclBits.ExistentialConformsToSelfValid = false;
-  ProtocolDeclBits.ExistentialConformsToSelf = false;
-  ProtocolDeclBits.Circularity
+  Bits.ProtocolDecl.RequiresClassValid = false;
+  Bits.ProtocolDecl.RequiresClass = false;
+  Bits.ProtocolDecl.ExistentialConformsToSelfValid = false;
+  Bits.ProtocolDecl.ExistentialConformsToSelf = false;
+  Bits.ProtocolDecl.Circularity
     = static_cast<unsigned>(CircularityCheck::Unchecked);
-  HasMissingRequirements = false;
-  KnownProtocol = 0;
-  NumRequirementsInSignature = 0;
+  Bits.ProtocolDecl.NumRequirementsInSignature = 0;
+  Bits.ProtocolDecl.HasMissingRequirements = false;
+  Bits.ProtocolDecl.KnownProtocol = 0;
 }
 
 llvm::TinyPtrVector<ProtocolDecl *>
@@ -3158,11 +3161,11 @@
 
 bool ProtocolDecl::requiresClassSlow() {
   // Set this first to catch (invalid) circular inheritance.
-  ProtocolDeclBits.RequiresClassValid = true;
+  Bits.ProtocolDecl.RequiresClassValid = true;
 
   // Quick check: @objc protocols require a class.
   if (isObjC()) {
-    ProtocolDeclBits.RequiresClass = true;
+    Bits.ProtocolDecl.RequiresClass = true;
     return true;
   }
 
@@ -3170,30 +3173,30 @@
   // class-constrained existential.
   //
   // FIXME: Use the requirement signature if available.
-  ProtocolDeclBits.RequiresClass = false;
+  Bits.ProtocolDecl.RequiresClass = false;
   for (auto inherited : getInherited()) {
     auto type = inherited.getType();
     assert(type && "Should have type checked inheritance clause by now");
     if (type->isExistentialType()) {
       auto layout = type->getExistentialLayout();
       if (layout.requiresClass()) {
-        ProtocolDeclBits.RequiresClass = true;
+        Bits.ProtocolDecl.RequiresClass = true;
         return true;
       }
     }
   }
 
-  return ProtocolDeclBits.RequiresClass;
+  return Bits.ProtocolDecl.RequiresClass;
 }
 
 bool ProtocolDecl::existentialConformsToSelfSlow() {
   // Assume for now that the existential conforms to itself; this
   // prevents circularity issues.
-  ProtocolDeclBits.ExistentialConformsToSelfValid = true;
-  ProtocolDeclBits.ExistentialConformsToSelf = true;
+  Bits.ProtocolDecl.ExistentialConformsToSelfValid = true;
+  Bits.ProtocolDecl.ExistentialConformsToSelf = true;
 
   if (!isObjC()) {
-    ProtocolDeclBits.ExistentialConformsToSelf = false;
+    Bits.ProtocolDecl.ExistentialConformsToSelf = false;
     return false;
   }
 
@@ -3205,7 +3208,7 @@
     if (auto vd = dyn_cast<ValueDecl>(member)) {
       if (!vd->isInstanceMember()) {
         // A protocol cannot conform to itself if it has static members.
-        ProtocolDeclBits.ExistentialConformsToSelf = false;
+        Bits.ProtocolDecl.ExistentialConformsToSelf = false;
         return false;
       }
     }
@@ -3215,7 +3218,7 @@
   // themselves.
   for (auto proto : getInheritedProtocols()) {
     if (!proto->existentialConformsToSelf()) {
-      ProtocolDeclBits.ExistentialConformsToSelf = false;
+      Bits.ProtocolDecl.ExistentialConformsToSelf = false;
       return false;
     }
   }
@@ -3399,8 +3402,8 @@
 bool ProtocolDecl::existentialTypeSupportedSlow(LazyResolver *resolver) {
   // Assume for now that the existential type is supported; this
   // prevents circularity issues.
-  ProtocolDeclBits.ExistentialTypeSupportedValid = true;
-  ProtocolDeclBits.ExistentialTypeSupported = true;
+  Bits.ProtocolDecl.ExistentialTypeSupportedValid = true;
+  Bits.ProtocolDecl.ExistentialTypeSupported = true;
 
   // ObjC protocols can always be existential.
   if (isObjC())
@@ -3423,7 +3426,7 @@
     if (isa<AssociatedTypeDecl>(member)) {
       // An existential type cannot be used if the protocol has an
       // associated type.
-      ProtocolDeclBits.ExistentialTypeSupported = false;
+      Bits.ProtocolDecl.ExistentialTypeSupported = false;
       return false;
     }
 
@@ -3436,7 +3439,7 @@
       }
 
       if (!isAvailableInExistential(valueMember)) {
-        ProtocolDeclBits.ExistentialTypeSupported = false;
+        Bits.ProtocolDecl.ExistentialTypeSupported = false;
         return false;
       }
     }
@@ -3446,7 +3449,7 @@
   // types themselves.
   for (auto proto : getInheritedProtocols()) {
     if (!proto->existentialTypeSupported(resolver)) {
-      ProtocolDeclBits.ExistentialTypeSupported = false;
+      Bits.ProtocolDecl.ExistentialTypeSupported = false;
       return false;
     }
   }
@@ -3500,17 +3503,18 @@
     GenericSignatureBuilder::computeRequirementSignature(this);
   RequirementSignature = requirementSig->getRequirements().data();
   assert(RequirementSignature != nullptr);
-  NumRequirementsInSignature = requirementSig->getRequirements().size();
+  Bits.ProtocolDecl.NumRequirementsInSignature =
+    requirementSig->getRequirements().size();
 }
 
 void ProtocolDecl::setRequirementSignature(ArrayRef<Requirement> requirements) {
   assert(!RequirementSignature && "already computed requirement signature");
   if (requirements.empty()) {
     RequirementSignature = reinterpret_cast<Requirement *>(this + 1);
-    NumRequirementsInSignature = 0;
+    Bits.ProtocolDecl.NumRequirementsInSignature = 0;
   } else {
     RequirementSignature = getASTContext().AllocateCopy(requirements).data();
-    NumRequirementsInSignature = requirements.size();
+    Bits.ProtocolDecl.NumRequirementsInSignature = requirements.size();
   }
 }
 
@@ -4162,8 +4166,8 @@
   return false;
 }
 
-/// Return true if this stored property needs to be accessed with getters and
-/// setters for Objective-C.
+/// Return true if this stored property has a getter and
+/// setter that are accessible from Objective-C.
 bool AbstractStorageDecl::hasForeignGetterAndSetter() const {
   if (auto override = getOverriddenDecl())
     return override->hasForeignGetterAndSetter();
@@ -4184,9 +4188,11 @@
   // Imported accessors are foreign and only have objc entry points.
   if (hasClangNode())
     return true;
-  // Otherwise, we only dispatch by @objc if the declaration is dynamic or
-  // NSManaged.
-  return isDynamic() || getAttrs().hasAttribute<NSManagedAttr>();
+  // Otherwise, we only dispatch by @objc if the declaration is dynamic,
+  // NSManaged, or dispatched through an ObjC protocol.
+  return isDynamic()
+    || getAttrs().hasAttribute<NSManagedAttr>()
+    || (isa<ProtocolDecl>(getDeclContext()) && isProtocolRequirement());
 }
 
 
@@ -4296,8 +4302,8 @@
   SpecifierLoc(specifierLoc) {
     assert(specifier != Specifier::Var &&
            "'var' cannot appear on parameters; you meant 'inout'");
-  ParamDeclBits.IsTypeLocImplicit = false;
-  ParamDeclBits.defaultArgumentKind =
+  Bits.ParamDecl.IsTypeLocImplicit = false;
+  Bits.ParamDecl.defaultArgumentKind =
     static_cast<unsigned>(DefaultArgumentKind::None);
 }
 
@@ -4314,8 +4320,8 @@
     ArgumentNameLoc(PD->getArgumentNameLoc()),
     SpecifierLoc(PD->getSpecifierLoc()),
     DefaultValueAndIsVariadic(nullptr, PD->DefaultValueAndIsVariadic.getInt()) {
-  ParamDeclBits.IsTypeLocImplicit = PD->ParamDeclBits.IsTypeLocImplicit;
-  ParamDeclBits.defaultArgumentKind = PD->ParamDeclBits.defaultArgumentKind;
+  Bits.ParamDecl.IsTypeLocImplicit = PD->Bits.ParamDecl.IsTypeLocImplicit;
+  Bits.ParamDecl.defaultArgumentKind = PD->Bits.ParamDecl.defaultArgumentKind;
   typeLoc = PD->getTypeLoc().clone(PD->getASTContext());
   if (!withTypes && typeLoc.getTypeRepr())
     typeLoc.setType(Type());
@@ -4554,9 +4560,15 @@
 }
 
 SourceRange SubscriptDecl::getSourceRange() const {
-  if (getBracesRange().isValid())
+  if (getBracesRange().isValid()) {
     return { getSubscriptLoc(), getBracesRange().End };
-  return { getSubscriptLoc(), ElementTy.getSourceRange().End };
+  } else if (ElementTy.getSourceRange().End.isValid()) {
+    return { getSubscriptLoc(), ElementTy.getSourceRange().End };
+  } else if (ArrowLoc.isValid()) {
+    return { getSubscriptLoc(), ArrowLoc };
+  } else {
+    return getSubscriptLoc();
+  }
 }
 
 SourceRange SubscriptDecl::getSignatureSourceRange() const {
@@ -5085,10 +5097,10 @@
 {
   setParameterLists(SelfDecl, BodyParams);
   
-  ConstructorDeclBits.ComputedBodyInitKind = 0;
-  ConstructorDeclBits.HasStubImplementation = 0;
-  ConstructorDeclBits.InitKind = static_cast<unsigned>(CtorInitializerKind::Designated);
-  ConstructorDeclBits.Failability = static_cast<unsigned>(Failability);
+  Bits.ConstructorDecl.ComputedBodyInitKind = 0;
+  Bits.ConstructorDecl.HasStubImplementation = 0;
+  Bits.ConstructorDecl.InitKind = static_cast<unsigned>(CtorInitializerKind::Designated);
+  Bits.ConstructorDecl.Failability = static_cast<unsigned>(Failability);
 }
 
 void ConstructorDecl::setParameterLists(ParamDecl *selfDecl,
@@ -5207,7 +5219,7 @@
 }
 
 Type EnumElementDecl::getArgumentInterfaceType() const {
-  if (!EnumElementDeclBits.HasArgumentType)
+  if (!Bits.EnumElementDecl.HasArgumentType)
     return nullptr;
 
   auto interfaceType = getInterfaceType();
@@ -5280,9 +5292,9 @@
     *init = nullptr;
 
   // If we already computed the result, return it.
-  if (ConstructorDeclBits.ComputedBodyInitKind) {
+  if (Bits.ConstructorDecl.ComputedBodyInitKind) {
     return static_cast<BodyInitKind>(
-             ConstructorDeclBits.ComputedBodyInitKind - 1);
+             Bits.ConstructorDecl.ComputedBodyInitKind - 1);
   }
 
 
@@ -5433,7 +5445,7 @@
   // Cache the result if it is trustworthy.
   if (diags) {
     auto *mutableThis = const_cast<ConstructorDecl *>(this);
-    mutableThis->ConstructorDeclBits.ComputedBodyInitKind =
+    mutableThis->Bits.ConstructorDecl.ComputedBodyInitKind =
         static_cast<unsigned>(Kind) + 1;
     if (init)
       *init = finder.InitExpr;
@@ -5507,8 +5519,8 @@
     AssignmentValueLoc(assignmentValueLoc),
     HigherThanLoc(higherThanLoc), LowerThanLoc(lowerThanLoc), Name(name),
     NumHigherThan(higherThan.size()), NumLowerThan(lowerThan.size()) {
-  PrecedenceGroupDeclBits.Associativity = unsigned(associativity);
-  PrecedenceGroupDeclBits.IsAssignment = isAssignment;
+  Bits.PrecedenceGroupDecl.Associativity = unsigned(associativity);
+  Bits.PrecedenceGroupDecl.IsAssignment = isAssignment;
   memcpy(getHigherThanBuffer(), higherThan.data(),
          higherThan.size() * sizeof(Relation));
   memcpy(getLowerThanBuffer(), lowerThan.data(),
diff --git a/lib/AST/DeclContext.cpp b/lib/AST/DeclContext.cpp
index 6865794..b3bfe08 100644
--- a/lib/AST/DeclContext.cpp
+++ b/lib/AST/DeclContext.cpp
@@ -938,7 +938,8 @@
 
   ASTContext &ctx = getASTContext();
   auto contextInfo = ctx.getOrCreateLazyIterableContextData(this, loader);
-  FirstDeclAndLazyMembers.setInt(true);
+  auto lazyMembers = FirstDeclAndLazyMembers.getInt() | LazyMembers::Present;
+  FirstDeclAndLazyMembers.setInt(LazyMembers(lazyMembers));
   contextInfo->memberData = contextData;
 
   ++NumLazyIterableDeclContexts;
@@ -958,7 +959,8 @@
   ASTContext &ctx = getASTContext();
   auto contextInfo = ctx.getOrCreateLazyIterableContextData(this,
     /*lazyLoader=*/nullptr);
-  FirstDeclAndLazyMembers.setInt(false);
+  auto lazyMembers = FirstDeclAndLazyMembers.getInt() & ~LazyMembers::Present;
+  FirstDeclAndLazyMembers.setInt(LazyMembers(lazyMembers));
 
   const Decl *container = getDecl();
   contextInfo->loader->loadAllMembers(const_cast<Decl *>(container),
diff --git a/lib/AST/Expr.cpp b/lib/AST/Expr.cpp
index 03ba1bb..7dbaf8c 100644
--- a/lib/AST/Expr.cpp
+++ b/lib/AST/Expr.cpp
@@ -1052,10 +1052,10 @@
                                      bool Implicit)
     : LiteralExpr(ExprKind::StringLiteral, Implicit), Val(Val),
       Range(Range) {
-  StringLiteralExprBits.Encoding = static_cast<unsigned>(UTF8);
-  StringLiteralExprBits.IsSingleUnicodeScalar =
+  Bits.StringLiteralExpr.Encoding = static_cast<unsigned>(UTF8);
+  Bits.StringLiteralExpr.IsSingleUnicodeScalar =
       unicode::isSingleUnicodeScalar(Val);
-  StringLiteralExprBits.IsSingleExtendedGraphemeCluster =
+  Bits.StringLiteralExpr.IsSingleExtendedGraphemeCluster =
       unicode::isSingleExtendedGraphemeCluster(Val);
 }
 
@@ -1256,11 +1256,11 @@
                                      bool implicit)
     : LiteralExpr(ExprKind::ObjectLiteral, implicit), 
       Arg(Arg), SemanticExpr(nullptr), PoundLoc(PoundLoc) {
-  ObjectLiteralExprBits.LitKind = static_cast<unsigned>(LitKind);
+  Bits.ObjectLiteralExpr.LitKind = static_cast<unsigned>(LitKind);
   assert(getLiteralKind() == LitKind);
-  ObjectLiteralExprBits.NumArgLabels = argLabels.size();
-  ObjectLiteralExprBits.HasArgLabelLocs = !argLabelLocs.empty();
-  ObjectLiteralExprBits.HasTrailingClosure = hasTrailingClosure;
+  Bits.ObjectLiteralExpr.NumArgLabels = argLabels.size();
+  Bits.ObjectLiteralExpr.HasArgLabelLocs = !argLabelLocs.empty();
+  Bits.ObjectLiteralExpr.HasTrailingClosure = hasTrailingClosure;
   initializeCallArguments(argLabels, argLabelLocs, hasTrailingClosure);  
 }
 
@@ -1337,8 +1337,8 @@
   : Expr(ExprKind::MemberRef, Implicit), Base(base),
     Member(member), DotLoc(dotLoc), NameLoc(nameLoc) {
    
-  MemberRefExprBits.Semantics = (unsigned) semantics;
-  MemberRefExprBits.IsSuper = false;
+  Bits.MemberRefExpr.Semantics = (unsigned) semantics;
+  Bits.MemberRefExpr.IsSuper = false;
   assert(Member);
 }
 
@@ -1370,6 +1370,49 @@
   return ::new(Buffer) SequenceExpr(elements);
 }
 
+ErasureExpr *ErasureExpr::create(ASTContext &ctx, Expr *subExpr, Type type,
+                                 ArrayRef<ProtocolConformanceRef> conformances){
+  auto size = totalSizeToAlloc<ProtocolConformanceRef>(conformances.size());
+  auto mem = ctx.Allocate(size, alignof(ErasureExpr));
+  return ::new(mem) ErasureExpr(subExpr, type, conformances);
+}
+
+UnresolvedSpecializeExpr *UnresolvedSpecializeExpr::create(ASTContext &ctx,
+                                             Expr *SubExpr, SourceLoc LAngleLoc,
+                                             ArrayRef<TypeLoc> UnresolvedParams,
+                                             SourceLoc RAngleLoc) {
+  auto size = totalSizeToAlloc<TypeLoc>(UnresolvedParams.size());
+  auto mem = ctx.Allocate(size, alignof(UnresolvedSpecializeExpr));
+  return ::new(mem) UnresolvedSpecializeExpr(SubExpr, LAngleLoc,
+                                             UnresolvedParams, RAngleLoc);
+}
+
+CaptureListExpr *CaptureListExpr::create(ASTContext &ctx,
+                                         ArrayRef<CaptureListEntry> captureList,
+                                         ClosureExpr *closureBody) {
+  auto size = totalSizeToAlloc<CaptureListEntry>(captureList.size());
+  auto mem = ctx.Allocate(size, alignof(CaptureListExpr));
+  return ::new(mem) CaptureListExpr(captureList, closureBody);
+}
+
+TupleShuffleExpr *TupleShuffleExpr::create(ASTContext &ctx,
+                                           Expr *subExpr,
+                                           ArrayRef<int> elementMapping,
+                                           TypeImpact typeImpact,
+                                           ConcreteDeclRef defaultArgsOwner,
+                                           ArrayRef<unsigned> VariadicArgs,
+                                           Type VarargsArrayTy,
+                                           ArrayRef<Expr *> CallerDefaultArgs,
+                                           Type ty) {
+  auto size = totalSizeToAlloc<Expr*, int, unsigned>(CallerDefaultArgs.size(),
+                                                     elementMapping.size(),
+                                                     VariadicArgs.size());
+  auto mem = ctx.Allocate(size, alignof(TupleShuffleExpr));
+  return ::new(mem) TupleShuffleExpr(subExpr, elementMapping, typeImpact,
+                                     defaultArgsOwner, VariadicArgs,
+                                     VarargsArrayTy, CallerDefaultArgs, ty);
+}
+
 SourceRange TupleExpr::getSourceRange() const {
   SourceLoc start = SourceLoc();
   SourceLoc end = SourceLoc();
@@ -1416,12 +1459,11 @@
                      SourceLoc RParenLoc, bool HasTrailingClosure, 
                      bool Implicit, Type Ty)
   : Expr(ExprKind::Tuple, Implicit, Ty),
-    LParenLoc(LParenLoc), RParenLoc(RParenLoc),
-    NumElements(SubExprs.size())
-{
-  TupleExprBits.HasTrailingClosure = HasTrailingClosure;
-  TupleExprBits.HasElementNames = !ElementNames.empty();
-  TupleExprBits.HasElementNameLocations = !ElementNameLocs.empty();
+    LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
+  Bits.TupleExpr.HasTrailingClosure = HasTrailingClosure;
+  Bits.TupleExpr.HasElementNames = !ElementNames.empty();
+  Bits.TupleExpr.HasElementNameLocations = !ElementNameLocs.empty();
+  Bits.TupleExpr.NumElements = SubExprs.size();
   
   assert(LParenLoc.isValid() == RParenLoc.isValid() &&
          "Mismatched parenthesis location information validity");
@@ -1482,18 +1524,22 @@
                              ArrayRef<Expr*> Elements,
                              ArrayRef<SourceLoc> CommaLocs,
                              SourceLoc RBracketLoc, Type Ty) {
-  // Copy the element list into the ASTContext.
-  auto NewElements = C.AllocateCopy(Elements);
-  auto NewCommas = C.AllocateCopy(CommaLocs);
-  return new (C) ArrayExpr(LBracketLoc, NewElements, NewCommas, RBracketLoc,Ty);
+  auto Size = totalSizeToAlloc<Expr *, SourceLoc>(Elements.size(),
+                                                  CommaLocs.size());
+  auto Mem = C.Allocate(Size, alignof(ArrayExpr));
+  return new (Mem) ArrayExpr(LBracketLoc, Elements, CommaLocs, RBracketLoc, Ty);
 }
 
 DictionaryExpr *DictionaryExpr::create(ASTContext &C, SourceLoc LBracketLoc,
-                             ArrayRef<Expr*> Elements, SourceLoc RBracketLoc,
+                             ArrayRef<Expr*> Elements,
+                             ArrayRef<SourceLoc> CommaLocs,
+                             SourceLoc RBracketLoc,
                              Type Ty) {
-  // Copy the element list into the ASTContext.
-  auto NewElements = C.AllocateCopy(Elements);
-  return new (C) DictionaryExpr(LBracketLoc, NewElements, RBracketLoc, Ty);
+  auto Size = totalSizeToAlloc<Expr *, SourceLoc>(Elements.size(),
+                                                  CommaLocs.size());
+  auto Mem = C.Allocate(Size, alignof(DictionaryExpr));
+  return new (Mem) DictionaryExpr(LBracketLoc, Elements, CommaLocs, RBracketLoc,
+                                  Ty);
 }
 
 static ValueDecl *getCalledValue(Expr *E) {
@@ -1517,11 +1563,11 @@
                              bool implicit, AccessSemantics semantics)
     : Expr(ExprKind::Subscript, implicit, Type()),
       TheDecl(decl), Base(base), Index(index) {
-  SubscriptExprBits.Semantics = (unsigned) semantics;
-  SubscriptExprBits.IsSuper = false;
-  SubscriptExprBits.NumArgLabels = argLabels.size();
-  SubscriptExprBits.HasArgLabelLocs = !argLabelLocs.empty();
-  SubscriptExprBits.HasTrailingClosure = hasTrailingClosure;
+  Bits.SubscriptExpr.Semantics = (unsigned) semantics;
+  Bits.SubscriptExpr.IsSuper = false;
+  Bits.SubscriptExpr.NumArgLabels = argLabels.size();
+  Bits.SubscriptExpr.HasArgLabelLocs = !argLabelLocs.empty();
+  Bits.SubscriptExpr.HasTrailingClosure = hasTrailingClosure;
   initializeCallArguments(argLabels, argLabelLocs, hasTrailingClosure);
 }
 
@@ -1584,9 +1630,9 @@
                                            bool implicit)
     : DynamicLookupExpr(ExprKind::DynamicSubscript, member, base),
       Index(index) {
-  DynamicSubscriptExprBits.NumArgLabels = argLabels.size();
-  DynamicSubscriptExprBits.HasArgLabelLocs = !argLabelLocs.empty();
-  DynamicSubscriptExprBits.HasTrailingClosure = hasTrailingClosure;
+  Bits.DynamicSubscriptExpr.NumArgLabels = argLabels.size();
+  Bits.DynamicSubscriptExpr.HasArgLabelLocs = !argLabelLocs.empty();
+  Bits.DynamicSubscriptExpr.HasTrailingClosure = hasTrailingClosure;
   initializeCallArguments(argLabels, argLabelLocs, hasTrailingClosure);
   if (implicit) setImplicit(implicit);
 }
@@ -1648,10 +1694,10 @@
                                            bool implicit)
   : Expr(ExprKind::UnresolvedMember, implicit),
     DotLoc(dotLoc), NameLoc(nameLoc), Name(name), Argument(argument) {
-  UnresolvedMemberExprBits.HasArguments = (argument != nullptr);
-  UnresolvedMemberExprBits.NumArgLabels = argLabels.size();
-  UnresolvedMemberExprBits.HasArgLabelLocs = !argLabelLocs.empty();
-  UnresolvedMemberExprBits.HasTrailingClosure = hasTrailingClosure;
+  Bits.UnresolvedMemberExpr.HasArguments = (argument != nullptr);
+  Bits.UnresolvedMemberExpr.NumArgLabels = argLabels.size();
+  Bits.UnresolvedMemberExpr.HasArgLabelLocs = !argLabelLocs.empty();
+  Bits.UnresolvedMemberExpr.HasTrailingClosure = hasTrailingClosure;
   initializeCallArguments(argLabels, argLabelLocs, hasTrailingClosure);
 }
 
@@ -1735,9 +1781,9 @@
                    Type ty)
     : ApplyExpr(ExprKind::Call, fn, arg, Implicit, ty)
 {
-  CallExprBits.NumArgLabels = argLabels.size();
-  CallExprBits.HasArgLabelLocs = !argLabelLocs.empty();
-  CallExprBits.HasTrailingClosure = hasTrailingClosure;
+  Bits.CallExpr.NumArgLabels = argLabels.size();
+  Bits.CallExpr.HasArgLabelLocs = !argLabelLocs.empty();
+  Bits.CallExpr.HasTrailingClosure = hasTrailingClosure;
   initializeCallArguments(argLabels, argLabelLocs, hasTrailingClosure);
 }
 
@@ -2109,7 +2155,7 @@
   std::uninitialized_copy(components.begin(), components.end(),
                           Components.begin());
 
-  KeyPathExprBits.IsObjC = true;
+  Bits.KeyPathExpr.IsObjC = true;
 }
 
 void
diff --git a/lib/AST/GenericSignature.cpp b/lib/AST/GenericSignature.cpp
index 2c61f001..35674f8 100644
--- a/lib/AST/GenericSignature.cpp
+++ b/lib/AST/GenericSignature.cpp
@@ -900,12 +900,71 @@
   using GSBConstraint = GenericSignatureBuilder::Constraint<T>;
 } // end anonymous namespace
 
+/// Determine whether there is a conformance of the given
+/// subject type to the given protocol within the given set of explicit
+/// requirements.
+static bool hasConformanceInSignature(ArrayRef<Requirement> requirements,
+                                      Type subjectType,
+                                      ProtocolDecl *proto) {
+  // Make sure this requirement exists in the requirement signature.
+  for (const auto &req: requirements) {
+    if (req.getKind() == RequirementKind::Conformance &&
+        req.getFirstType()->isEqual(subjectType) &&
+        req.getSecondType()->castTo<ProtocolType>()->getDecl()
+          == proto) {
+      return true;
+    }
+  }
+
+  return false;
+}
+
+/// Check whether the given requirement source has any non-canonical protocol
+/// requirements in it.
+static bool hasNonCanonicalSelfProtocolRequirement(
+                                          const RequirementSource *source,
+                                          ProtocolDecl *conformingProto) {
+  for (; source; source = source->parent) {
+    // Only look at protocol requirements.
+    if (!source->isProtocolRequirement())
+      continue;
+
+    // If we don't already have a requirement signature for this protocol,
+    // build one now.
+    auto inProto = source->getProtocolDecl();
+    if (!inProto->isRequirementSignatureComputed()) {
+      inProto->computeRequirementSignature();
+      assert(inProto->isRequirementSignatureComputed() &&
+             "couldn't compute requirement signature?");
+    }
+
+    // Check whether the given requirement is in the requirement signature.
+    if (!source->usesRequirementSignature &&
+        !hasConformanceInSignature(inProto->getRequirementSignature(),
+                                   source->getStoredType(), conformingProto))
+      return true;
+
+    // Update the conforming protocol for the rest of the search.
+    conformingProto = inProto;
+  }
+
+  return false;
+}
+
 /// Retrieve the best requirement source from the list
 static const RequirementSource *
-getBestRequirementSource(ArrayRef<GSBConstraint<ProtocolDecl *>> constraints) {
+getBestCanonicalRequirementSource(
+                      ArrayRef<GSBConstraint<ProtocolDecl *>> constraints) {
   const RequirementSource *bestSource = nullptr;
   for (const auto &constraint : constraints) {
     auto source = constraint.source;
+
+    // If there is a non-canonical protocol requirement next to the root,
+    // skip this requirement source.
+    if (hasNonCanonicalSelfProtocolRequirement(source, constraint.value))
+      continue;
+
+    // Check whether this is better than our best source.
     if (!bestSource || source->compare(bestSource) < 0)
       bestSource = source;
   }
@@ -934,27 +993,6 @@
   typedef GenericSignatureBuilder::RequirementSource RequirementSource;
   ConformanceAccessPath path;
 
-#ifndef NDEBUG
-  // Local function to determine whether there is a conformance of the given
-  // subject type to the given protocol within the given set of explicit
-  // requirements.
-  auto hasConformanceInSignature = [&](ArrayRef<Requirement> requirements,
-                                       Type subjectType,
-                                       ProtocolDecl *proto) -> bool {
-    // Make sure this requirement exists in the requirement signature.
-    for (const auto& req: requirements) {
-      if (req.getKind() == RequirementKind::Conformance &&
-          req.getFirstType()->isEqual(subjectType) &&
-          req.getSecondType()->castTo<ProtocolType>()->getDecl()
-            == proto) {
-        return true;
-      }
-    }
-
-    return false;
-  };
-#endif
-
   // Local function to construct the conformance access path from the
   // requirement.
   std::function<void(ArrayRef<Requirement>, const RequirementSource *,
@@ -1003,13 +1041,6 @@
         return;
       }
 
-      // Canonicalize this step with respect to the requirement signature.
-      if (!inProtocol->isRequirementSignatureComputed()) {
-        inProtocol->computeRequirementSignature();
-        assert(inProtocol->isRequirementSignatureComputed() &&
-               "missing signature");
-      }
-
       // Get a generic signature for the protocol's signature.
       auto inProtoSig = inProtocol->getGenericSignature();
       auto &inProtoSigBuilder = *inProtoSig->getGenericSignatureBuilder();
@@ -1031,7 +1062,7 @@
       assert(conforms != equivClass->conformsTo.end());
 
       // Compute the root type, canonicalizing it w.r.t. the protocol context.
-      auto conformsSource = getBestRequirementSource(conforms->second);
+      auto conformsSource = getBestCanonicalRequirementSource(conforms->second);
       assert(conformsSource != source || !requirementSignatureProto);
       Type localRootType = conformsSource->getRootType();
       localRootType = inProtoSig->getCanonicalTypeInContext(localRootType);
@@ -1079,7 +1110,7 @@
   };
 
   // Canonicalize the root type.
-  auto source = getBestRequirementSource(conforms->second);
+  auto source = getBestCanonicalRequirementSource(conforms->second);
   Type rootType = source->getRootType()->getCanonicalType(this);
 
   // Build the path.
diff --git a/lib/AST/LookupVisibleDecls.cpp b/lib/AST/LookupVisibleDecls.cpp
index 0e05608..04a4463 100644
--- a/lib/AST/LookupVisibleDecls.cpp
+++ b/lib/AST/LookupVisibleDecls.cpp
@@ -195,15 +195,8 @@
     if (!isExtensionApplied(*const_cast<DeclContext*>(CurrDC), BaseType,
                             extension))
       continue;
-    bool validatedExtension = false;
-    if (TypeResolver && extension->getAsProtocolExtensionContext()) {
-      if (!TypeResolver->isProtocolExtensionUsable(
-              const_cast<DeclContext *>(CurrDC), BaseType, extension)) {
-        continue;
-      }
-      validatedExtension = true;
-    }
 
+    bool validatedExtension = false;
     for (auto Member : extension->getMembers()) {
       if (auto VD = dyn_cast<ValueDecl>(Member))
         if (isDeclVisibleInLookupMode(VD, LS, CurrDC, TypeResolver)) {
diff --git a/lib/AST/NameLookup.cpp b/lib/AST/NameLookup.cpp
index 9e8fba4..066a0ca 100644
--- a/lib/AST/NameLookup.cpp
+++ b/lib/AST/NameLookup.cpp
@@ -1033,7 +1033,7 @@
     assert(LastExtensionIncluded == nullptr);
     for (auto const &i : Lookup) {
       for (auto d : i.getSecond()) {
-        d->ValueDeclBits.AlreadyInLookupTable = false;
+        d->setAlreadyInLookupTable(false);
       }
     }
     Lookup.clear();
@@ -1102,10 +1102,10 @@
 
   // If this declaration is already in the lookup table, don't add it
   // again.
-  if (vd->ValueDeclBits.AlreadyInLookupTable) {
+  if (vd->isAlreadyInLookupTable()) {
     return;
   }
-  vd->ValueDeclBits.AlreadyInLookupTable = true;
+  vd->setAlreadyInLookupTable();
 
   // Add this declaration to the lookup set under its compound name and simple
   // name.
@@ -1249,7 +1249,8 @@
   IDC->setLoadingLazyMembers(true);
   auto ci = ctx.getOrCreateLazyIterableContextData(IDC,
                                                    /*lazyLoader=*/nullptr);
-  if (auto res = ci->loader->loadNamedMembers(IDC, name, ci->memberData)) {
+  if (auto res = ci->loader->loadNamedMembers(IDC, name.getBaseName(),
+                                              ci->memberData)) {
     IDC->setLoadingLazyMembers(false);
     if (auto s = ctx.Stats) {
       ++s->getFrontendCounters().NamedLazyMemberLoadSuccessCount;
diff --git a/lib/AST/Pattern.cpp b/lib/AST/Pattern.cpp
index 1ed64df..606e421 100644
--- a/lib/AST/Pattern.cpp
+++ b/lib/AST/Pattern.cpp
@@ -101,14 +101,14 @@
   Ty = interfaceTy;
   ASTContext &ctx = interfaceTy->getASTContext();
   ctx.DelayedPatternContexts[this] = dc;
-  PatternBits.hasInterfaceType = true;
+  Bits.Pattern.hasInterfaceType = true;
 }
 
 Type Pattern::getType() const {
   assert(hasType());
 
   // If this pattern has an interface type, map it into the context type.
-  if (PatternBits.hasInterfaceType) {
+  if (Bits.Pattern.hasInterfaceType) {
     ASTContext &ctx = Ty->getASTContext();
 
     // Retrieve the generic environment to use for the mapping.
@@ -119,7 +119,7 @@
     if (auto genericEnv = dc->getGenericEnvironmentOfContext()) {
       ctx.DelayedPatternContexts.erase(this);
       Ty = genericEnv->mapTypeIntoContext(Ty);
-      PatternBits.hasInterfaceType = false;
+      const_cast<Pattern*>(this)->Bits.Pattern.hasInterfaceType = false;
     }
   }
 
diff --git a/lib/AST/ProtocolConformance.cpp b/lib/AST/ProtocolConformance.cpp
index 0349d52..0c15ad8 100644
--- a/lib/AST/ProtocolConformance.cpp
+++ b/lib/AST/ProtocolConformance.cpp
@@ -387,6 +387,11 @@
 
 void NormalProtocolConformance::setSignatureConformances(
                                ArrayRef<ProtocolConformanceRef> conformances) {
+  if (conformances.empty()) {
+    SignatureConformances = { };
+    return;
+  }
+
   auto &ctx = getProtocol()->getASTContext();
   SignatureConformances = ctx.AllocateCopy(conformances);
 
@@ -460,11 +465,6 @@
       other.owning = false;
     }
 
-    ~Writer() {
-      assert((!owning || self->isInvalid() || requirementSignature.empty()) &&
-             "signature conformances were not fully populated");
-    }
-
     void operator()(ProtocolConformanceRef conformance){
       // Make sure we have the right conformance.
       assert(!requirementSignature.empty() && "Too many conformances?");
diff --git a/lib/AST/RequirementEnvironment.cpp b/lib/AST/RequirementEnvironment.cpp
new file mode 100644
index 0000000..105bbe6
--- /dev/null
+++ b/lib/AST/RequirementEnvironment.cpp
@@ -0,0 +1,231 @@
+//===--- RequirementEnvironment.cpp - Requirement Environments ------------===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the RequirementEnvironment class, which is used to
+// capture how a witness to a protocol requirement maps type parameters.
+//
+//===----------------------------------------------------------------------===//
+
+#include "swift/AST/RequirementEnvironment.h"
+#include "swift/AST/ASTContext.h"
+#include "swift/AST/Decl.h"
+#include "swift/AST/DeclContext.h"
+#include "swift/AST/GenericSignature.h"
+#include "swift/AST/GenericSignatureBuilder.h"
+#include "swift/AST/ProtocolConformance.h"
+#include "swift/AST/Types.h"
+#include "llvm/ADT/Statistic.h"
+
+#define DEBUG_TYPE "Protocol conformance checking"
+
+using namespace swift;
+
+STATISTIC(NumRequirementEnvironments, "# of requirement environments");
+
+RequirementEnvironment::RequirementEnvironment(
+                                           DeclContext *conformanceDC,
+                                           GenericSignature *reqSig,
+                                           ProtocolDecl *proto,
+                                           ClassDecl *covariantSelf,
+                                           ProtocolConformance *conformance)
+    : reqSig(reqSig) {
+  ASTContext &ctx = conformanceDC->getASTContext();
+
+  auto concreteType = conformanceDC->getSelfInterfaceType();
+  auto *conformanceSig = conformanceDC->getGenericSignatureOfContext();
+
+  // Build a substitution map from the generic parameters of the conforming
+  // type to the synthetic environment.
+  //
+  // For structs, enums and protocols, this is a 1:1 mapping; for classes,
+  // we increase the depth of each generic parameter by 1 so that we can
+  // introduce a class-bound 'Self' parameter.
+  auto substConcreteType = concreteType;
+  SubstitutionMap conformanceToSyntheticEnvMap;
+  if (conformanceSig) {
+    conformanceToSyntheticEnvMap = conformanceSig->getSubstitutionMap(
+      [&](SubstitutableType *type) {
+        auto *genericParam = cast<GenericTypeParamType>(type);
+        if (covariantSelf) {
+          return GenericTypeParamType::get(
+              genericParam->getDepth() + 1,
+              genericParam->getIndex(),
+              ctx);
+        }
+
+        return GenericTypeParamType::get(
+            genericParam->getDepth(),
+            genericParam->getIndex(),
+            ctx);
+      },
+      MakeAbstractConformanceForGenericType());
+
+    substConcreteType = concreteType.subst(conformanceToSyntheticEnvMap);
+  }
+
+  // Calculate the depth at which the requirement's generic parameters
+  // appear in the synthetic signature.
+  unsigned depth = 0;
+  if (covariantSelf) {
+    depth++;
+  }
+  if (conformanceSig) {
+    depth += conformanceSig->getGenericParams().back()->getDepth() + 1;
+  }
+
+  // Build a substitution map to replace the protocol's \c Self and the type
+  // parameters of the requirement into a combined context that provides the
+  // type parameters of the conformance context and the parameters of the
+  // requirement.
+  auto selfType = cast<GenericTypeParamType>(
+      proto->getSelfInterfaceType()->getCanonicalType());
+
+  reqToSyntheticEnvMap = reqSig->getSubstitutionMap(
+    [selfType, substConcreteType, depth, covariantSelf, &ctx]
+    (SubstitutableType *type) -> Type {
+      // If the conforming type is a class, the protocol 'Self' maps to
+      // the class-constrained 'Self'. Otherwise, it maps to the concrete
+      // type.
+      if (type->isEqual(selfType)) {
+        if (covariantSelf)
+          return GenericTypeParamType::get(/*depth=*/0, /*index=*/0, ctx);
+        return substConcreteType;
+      }
+      // Other requirement generic parameters map 1:1 with their depth
+      // increased appropriately.
+      auto *genericParam = cast<GenericTypeParamType>(type);
+      // In a protocol requirement, the only generic parameter at depth 0
+      // should be 'Self', and all others at depth 1. Anything else is
+      // invalid code.
+      if (genericParam->getDepth() != 1)
+        return Type();
+      auto substGenericParam =
+        GenericTypeParamType::get(depth, genericParam->getIndex(), ctx);
+      return substGenericParam;
+    },
+    [selfType, substConcreteType, conformance, conformanceDC, &ctx](
+        CanType type, Type replacement, ProtocolType *protoType)
+          -> Optional<ProtocolConformanceRef> {
+      auto proto = protoType->getDecl();
+
+      // The protocol 'Self' conforms concretely to the conforming type.
+      if (type->isEqual(selfType)) {
+        ProtocolConformance *specialized = conformance;
+        if (conformance && conformance->getGenericSignature()) {
+          auto concreteSubs =
+            substConcreteType->getContextSubstitutionMap(
+              conformanceDC->getParentModule(), conformanceDC);
+          specialized =
+            ctx.getSpecializedConformance(substConcreteType, conformance,
+                                          concreteSubs);
+        }
+
+        if (specialized)
+          return ProtocolConformanceRef(specialized);
+      }
+
+      // All other generic parameters come from the requirement itself
+      // and conform abstractly.
+      return ProtocolConformanceRef(proto);
+    });
+
+  // If the requirement itself is non-generic, the synthetic signature
+  // is that of the conformance context.
+  if (!covariantSelf &&
+      reqSig->getGenericParams().size() == 1 &&
+      reqSig->getRequirements().size() == 1) {
+    syntheticSignature = conformanceDC->getGenericSignatureOfContext();
+    if (syntheticSignature) {
+      syntheticSignature = syntheticSignature->getCanonicalSignature();
+      syntheticEnvironment =
+        syntheticSignature->createGenericEnvironment();
+    }
+
+    return;
+  }
+
+  // Construct a generic signature builder by collecting the constraints
+  // from the requirement and the context of the conformance together,
+  // because both define the capabilities of the requirement.
+  GenericSignatureBuilder builder(ctx);
+
+  auto source =
+    GenericSignatureBuilder::FloatingRequirementSource::forAbstract();
+
+  // If the conforming type is a class, add a class-constrained 'Self'
+  // parameter.
+  if (covariantSelf) {
+    auto paramTy = GenericTypeParamType::get(/*depth=*/0, /*index=*/0, ctx);
+    builder.addGenericParameter(paramTy);
+  }
+
+  // Now, add all generic parameters from the conforming type.
+  if (conformanceSig) {
+    for (auto param : conformanceSig->getGenericParams()) {
+      builder.addGenericParameter(
+          Type(param).subst(conformanceToSyntheticEnvMap)
+              ->castTo<GenericTypeParamType>());
+    }
+  }
+
+  // Next, add requirements.
+  if (covariantSelf) {
+    auto paramTy = GenericTypeParamType::get(/*depth=*/0, /*index=*/0, ctx);
+    Requirement reqt(RequirementKind::Superclass, paramTy, substConcreteType);
+    builder.addRequirement(reqt, source, nullptr);
+  }
+
+  if (conformanceSig) {
+    for (auto &rawReq : conformanceSig->getRequirements()) {
+      if (auto req = rawReq.subst(conformanceToSyntheticEnvMap))
+        builder.addRequirement(*req, source, nullptr);
+    }
+  }
+
+  // Finally, add the generic parameters from the requirement.
+  for (auto genericParam : reqSig->getGenericParams().slice(1)) {
+    // The only depth that makes sense is depth == 1, the generic parameters
+    // of the requirement itself. Anything else is from invalid code.
+    if (genericParam->getDepth() != 1) {
+      return;
+    }
+
+    // Create an equivalent generic parameter at the next depth.
+    auto substGenericParam =
+      GenericTypeParamType::get(depth, genericParam->getIndex(), ctx);
+
+    builder.addGenericParameter(substGenericParam);
+  }
+
+  ++NumRequirementEnvironments;
+
+  // Next, add each of the requirements (mapped from the requirement's
+  // interface types into the abstract type parameters).
+  for (auto &rawReq : reqSig->getRequirements()) {
+    // FIXME: This should not be necessary, since the constraint is redundant,
+    // but we need it to work around some crashes for now.
+    if (rawReq.getKind() == RequirementKind::Conformance &&
+        rawReq.getFirstType()->isEqual(selfType) &&
+        rawReq.getSecondType()->isEqual(proto->getDeclaredType()))
+      continue;
+
+    if (auto req = rawReq.subst(reqToSyntheticEnvMap))
+      builder.addRequirement(*req, source, conformanceDC->getParentModule());
+  }
+
+  // Produce the generic signature and environment.
+  // FIXME: Pass in a source location for the conformance, perhaps? It seems
+  // like this could fail.
+  syntheticSignature =
+    std::move(builder).computeGenericSignature(SourceLoc());
+  syntheticEnvironment = syntheticSignature->createGenericEnvironment();
+}
diff --git a/lib/AST/Stmt.cpp b/lib/AST/Stmt.cpp
index c324680..a760b95 100644
--- a/lib/AST/Stmt.cpp
+++ b/lib/AST/Stmt.cpp
@@ -130,8 +130,9 @@
 BraceStmt::BraceStmt(SourceLoc lbloc, ArrayRef<ASTNode> elts,
                      SourceLoc rbloc, Optional<bool> implicit)
   : Stmt(StmtKind::Brace, getDefaultImplicitFlag(implicit, lbloc)),
-    NumElements(elts.size()), LBLoc(lbloc), RBLoc(rbloc)
+    LBLoc(lbloc), RBLoc(rbloc)
 {
+  Bits.BraceStmt.NumElements = elts.size();
   std::uninitialized_copy(elts.begin(), elts.end(),
                           getTrailingObjects<ASTNode>());
 }
@@ -371,13 +372,14 @@
                    Optional<bool> Implicit)
     : Stmt(StmtKind::Case, getDefaultImplicitFlag(Implicit, CaseLoc)),
       CaseLoc(CaseLoc), ColonLoc(ColonLoc),
-      BodyAndHasBoundDecls(Body, HasBoundDecls),
-      NumPatterns(CaseLabelItems.size()) {
-  assert(NumPatterns > 0 && "case block must have at least one pattern");
+      BodyAndHasBoundDecls(Body, HasBoundDecls) {
+  Bits.CaseStmt.NumPatterns = CaseLabelItems.size();
+  assert(Bits.CaseStmt.NumPatterns > 0 &&
+         "case block must have at least one pattern");
   MutableArrayRef<CaseLabelItem> Items{ getTrailingObjects<CaseLabelItem>(),
-                                        NumPatterns };
+                                        Bits.CaseStmt.NumPatterns };
 
-  for (unsigned i = 0; i < NumPatterns; ++i) {
+  for (unsigned i = 0; i < Bits.CaseStmt.NumPatterns; ++i) {
     new (&Items[i]) CaseLabelItem(CaseLabelItems[i]);
     Items[i].getPattern()->markOwnedByStatement(this);
   }
diff --git a/lib/AST/Type.cpp b/lib/AST/Type.cpp
index f48268c..ebdabd9 100644
--- a/lib/AST/Type.cpp
+++ b/lib/AST/Type.cpp
@@ -1045,17 +1045,9 @@
   return inputType;
 }
 
-/// getCanonicalType - Return the canonical version of this type, which has
-/// sugar from all levels stripped off.
-CanType TypeBase::getCanonicalType() {
-  // If the type is itself canonical, return it.
-  if (isCanonical())
-    return CanType(this);
-  // If the canonical type was already computed, just return what we have.
-  if (TypeBase *CT = CanonicalType.get<TypeBase*>())
-    return CanType(CT);
+void TypeBase::computeCanonicalType() {
+  assert(!hasCanonicalTypeComputed() && "called unnecessarily");
 
-  // Otherwise, compute and cache it.
   TypeBase *Result = nullptr;
   switch (getKind()) {
 #define ALWAYS_CANONICAL_TYPE(id, parent) case TypeKind::id:
@@ -1227,12 +1219,10 @@
     break;
   }
   }
-    
-  
+
   // Cache the canonical type for future queries.
   assert(Result && "Case not implemented!");
   CanonicalType = Result;
-  return CanType(Result);
 }
 
 CanType TypeBase::getCanonicalType(GenericSignature *sig) {
@@ -1314,8 +1304,8 @@
   : TypeBase(TypeKind::Paren, nullptr, properties),
     UnderlyingType(flags.isInOut()
                      ? InOutType::get(baseType)
-                     : baseType),
-    parameterFlags(flags) {
+                     : baseType) {
+  Bits.ParenType.Flags = flags.toRaw();
   if (flags.isInOut())
     assert(!baseType->is<InOutType>() && "caller did not pass a base type");
   if (baseType->is<InOutType>())
@@ -2006,6 +1996,10 @@
              nullptr };
   }
 
+  // Give special dispensation to builtin types for testing purposes.
+  if (type->is<BuiltinType>())
+    return { ForeignRepresentableKind::Trivial, nullptr };
+
   auto nominal = type->getAnyNominal();
   if (!nominal) return failure();
 
@@ -2384,8 +2378,8 @@
 /// getNamedElementId - If this tuple has a field with the specified name,
 /// return the field index, otherwise return -1.
 int TupleType::getNamedElementId(Identifier I) const {
-  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
-    if (Elements[i].getName() == I)
+  for (unsigned i = 0, e = Bits.TupleType.Count; i != e; ++i) {
+    if (getTrailingObjects<TupleTypeElt>()[i].getName() == I)
       return i;
   }
 
@@ -2397,15 +2391,15 @@
 /// scalar, return the field number that the scalar is assigned to.  If not,
 /// return -1.
 int TupleType::getElementForScalarInit() const {
-  if (Elements.empty()) return -1;
+  if (Bits.TupleType.Count == 0) return -1;
   
   int FieldWithoutDefault = -1;
-  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
+  for (unsigned i = 0, e = Bits.TupleType.Count; i != e; ++i) {
     // If we already saw a non-vararg field missing a default value, then we
     // cannot assign a scalar to this tuple.
     if (FieldWithoutDefault != -1) {
       // Vararg fields are okay; they'll just end up being empty.
-      if (Elements[i].isVararg())
+      if (getTrailingObjects<TupleTypeElt>()[i].isVararg())
         continue;
     
       return -1;
@@ -2424,9 +2418,9 @@
 /// varargs element (i.e., if it is "Int...", this returns Int, not [Int]).
 /// Otherwise, this returns Type().
 Type TupleType::getVarArgsBaseType() const {
-  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
-    if (Elements[i].isVararg())
-      return Elements[i].getVarargBaseTy();
+  for (unsigned i = 0, e = Bits.TupleType.Count; i != e; ++i) {
+    if (getTrailingObjects<TupleTypeElt>()[i].isVararg())
+      return getTrailingObjects<TupleTypeElt>()[i].getVarargBaseTy();
   }
   
   return Type();
@@ -2451,10 +2445,10 @@
   }
 
   // Set up the bits we need for trailing objects to work.
-  ArchetypeTypeBits.ExpandedNestedTypes = false;
-  ArchetypeTypeBits.HasSuperclass = static_cast<bool>(Superclass);
-  ArchetypeTypeBits.HasLayoutConstraint = static_cast<bool>(Layout);
-  ArchetypeTypeBits.NumProtocols = ConformsTo.size();
+  Bits.ArchetypeType.ExpandedNestedTypes = false;
+  Bits.ArchetypeType.HasSuperclass = static_cast<bool>(Superclass);
+  Bits.ArchetypeType.HasLayoutConstraint = static_cast<bool>(Layout);
+  Bits.ArchetypeType.NumProtocols = ConformsTo.size();
 
   // Record the superclass.
   if (Superclass)
@@ -2479,10 +2473,10 @@
                         RecursiveTypeProperties::HasOpenedExistential)),
     ParentOrOpenedOrEnvironment(Existential.getPointer()) {
   // Set up the bits we need for trailing objects to work.
-  ArchetypeTypeBits.ExpandedNestedTypes = false;
-  ArchetypeTypeBits.HasSuperclass = static_cast<bool>(Superclass);
-  ArchetypeTypeBits.HasLayoutConstraint = static_cast<bool>(Layout);
-  ArchetypeTypeBits.NumProtocols = ConformsTo.size();
+  Bits.ArchetypeType.ExpandedNestedTypes = false;
+  Bits.ArchetypeType.HasSuperclass = static_cast<bool>(Superclass);
+  Bits.ArchetypeType.HasLayoutConstraint = static_cast<bool>(Layout);
+  Bits.ArchetypeType.NumProtocols = ConformsTo.size();
 
   // Record the superclass.
   if (Superclass)
@@ -2546,7 +2540,7 @@
 }
 
 bool ArchetypeType::requiresClass() const {
-  if (ArchetypeTypeBits.HasSuperclass)
+  if (Bits.ArchetypeType.HasSuperclass)
     return true;
   if (auto layout = getLayoutConstraint())
     if (layout->isClass())
@@ -2582,7 +2576,7 @@
 } // end anonymous namespace
 
 void ArchetypeType::populateNestedTypes() const {
-  if (ArchetypeTypeBits.ExpandedNestedTypes) return;
+  if (Bits.ArchetypeType.ExpandedNestedTypes) return;
 
   // Collect the set of nested types of this archetype.
   SmallVector<std::pair<Identifier, Type>, 4> nestedTypes;
@@ -2657,10 +2651,10 @@
 void ArchetypeType::setNestedTypes(
                                  ASTContext &Ctx,
                                  ArrayRef<std::pair<Identifier, Type>> Nested) {
-  assert(!ArchetypeTypeBits.ExpandedNestedTypes && "Already expanded");
+  assert(!Bits.ArchetypeType.ExpandedNestedTypes && "Already expanded");
   NestedTypes = Ctx.AllocateCopy(Nested);
   std::sort(NestedTypes.begin(), NestedTypes.end(), OrderArchetypeByName());
-  ArchetypeTypeBits.ExpandedNestedTypes = true;
+  Bits.ArchetypeType.ExpandedNestedTypes = true;
 }
 
 void ArchetypeType::registerNestedType(Identifier name, Type nested) {
@@ -4103,10 +4097,8 @@
 SILBoxType::SILBoxType(ASTContext &C,
                        SILLayout *Layout, SubstitutionList Args)
 : TypeBase(TypeKind::SILBox, &C,
-           getRecursivePropertiesFromSubstitutions(Args)),
-  Layout(Layout),
-  NumGenericArgs(Args.size())
-{
+           getRecursivePropertiesFromSubstitutions(Args)), Layout(Layout) {
+  Bits.SILBoxType.NumGenericArgs = Args.size();
 #ifndef NDEBUG
   // Check that the generic args are reasonable for the box's signature.
   if (Layout->getGenericSignature())
@@ -4115,9 +4107,8 @@
     assert(arg.getReplacement()->isCanonical() &&
            "box arguments must be canonical types!");
 #endif
-  auto paramsBuf = getTrailingObjects<Substitution>();
-  for (unsigned i = 0; i < NumGenericArgs; ++i)
-    ::new (paramsBuf + i) Substitution(Args[i]);
+  std::uninitialized_copy(Args.begin(), Args.end(),
+                          getTrailingObjects<Substitution>());
 }
 
 RecursiveTypeProperties SILBoxType::
diff --git a/lib/AST/TypeRepr.cpp b/lib/AST/TypeRepr.cpp
index e9a685b..d62fe10 100644
--- a/lib/AST/TypeRepr.cpp
+++ b/lib/AST/TypeRepr.cpp
@@ -414,8 +414,8 @@
   // Copy elements.
   std::uninitialized_copy(Elements.begin(), Elements.end(),
                           getTrailingObjects<TupleTypeReprElement>());
-  TupleTypeReprBits.HasEllipsis = Ellipsis.isValid();
-  TupleTypeReprBits.NumElements = Elements.size();
+  Bits.TupleTypeRepr.HasEllipsis = Ellipsis.isValid();
+  Bits.TupleTypeRepr.NumElements = Elements.size();
 
   // Set ellipsis location and index.
   if (Ellipsis.isValid()) {
@@ -477,7 +477,7 @@
 
   Printer << "(";
 
-  for (unsigned i = 0, e = TupleTypeReprBits.NumElements; i != e; ++i) {
+  for (unsigned i = 0, e = Bits.TupleTypeRepr.NumElements; i != e; ++i) {
     if (i) Printer << ", ";
     Printer.callPrintStructurePre(PrintStructureKind::TupleElement);
     auto name = getElementName(i);
diff --git a/lib/ClangImporter/ClangImporter.cpp b/lib/ClangImporter/ClangImporter.cpp
index 5ddf1f3..ae16ed8 100644
--- a/lib/ClangImporter/ClangImporter.cpp
+++ b/lib/ClangImporter/ClangImporter.cpp
@@ -3292,7 +3292,7 @@
 
 Optional<TinyPtrVector<ValueDecl *>>
 ClangImporter::Implementation::loadNamedMembers(
-    const IterableDeclContext *IDC, DeclName N, uint64_t contextData) {
+    const IterableDeclContext *IDC, DeclBaseName N, uint64_t contextData) {
 
   auto *D = IDC->getDecl();
   auto *DC = cast<DeclContext>(D);
@@ -3351,7 +3351,7 @@
   assert(isa<clang::ObjCContainerDecl>(CD));
 
   TinyPtrVector<ValueDecl *> Members;
-  for (auto entry : table->lookup(SerializedSwiftName(N.getBaseName()),
+  for (auto entry : table->lookup(SerializedSwiftName(N),
                                   effectiveClangContext)) {
     if (!entry.is<clang::NamedDecl *>()) continue;
     auto member = entry.get<clang::NamedDecl *>();
@@ -3365,7 +3365,7 @@
     for (auto *TD : tmp) {
       if (auto *V = dyn_cast<ValueDecl>(TD)) {
         // Skip ValueDecls if they import under different names.
-        if (V->getFullName().matchesRef(N)) {
+        if (V->getBaseName() == N) {
           Members.push_back(V);
         }
       }
diff --git a/lib/ClangImporter/ImportDecl.cpp b/lib/ClangImporter/ImportDecl.cpp
index f1e4c18..ffd450b 100644
--- a/lib/ClangImporter/ImportDecl.cpp
+++ b/lib/ClangImporter/ImportDecl.cpp
@@ -1384,8 +1384,6 @@
   var->addTrivialAccessors(varGetter, nullptr, nullptr);
   assert(var->hasStorage());
 
-  structDecl->setHasDelayedMembers();
-
   // Create constructors to initialize that value from a value of the
   // underlying type.
   if (options.contains(MakeStructRawValuedFlags::MakeUnlabeledValueInit))
@@ -1537,7 +1535,6 @@
         Impl, structDecl, computedVar, storedVar,
         /*wantLabel*/ false, wantBody);
 
-  structDecl->setHasDelayedMembers();
   if (unlabeledCtor)
     structDecl->addMember(unlabeledCtor);
   structDecl->addMember(init);
@@ -6348,8 +6345,6 @@
              ->getAsNominalTypeOrNominalTypeExtensionContext() ==
          setter->getDeclContext()
              ->getAsNominalTypeOrNominalTypeExtensionContext());
-    // TODO: Possible that getter and setter are different instantiations
-    // of the same objc generic type?
 
     // Whether we can update the types involved in the subscript
     // operation.
@@ -6404,8 +6399,16 @@
     }
   }
 
-  // The context into which the subscript should go.
-  bool associateWithSetter = setter && !getterAndSetterInSameType;
+  // The context into which the subscript should go. We prefer wherever the
+  // getter is declared unless the two accessors are in different types and the
+  // one we started with is the setter. This happens when:
+  // - A read-only subscript is made read/write is a subclass.
+  // - A setter is redeclared in a subclass, but not the getter.
+  // And not when:
+  // - A getter is redeclared in a subclass, but not the setter.
+  // - The getter and setter are part of the same type.
+  // - There is no setter.
+  bool associateWithSetter = !getterAndSetterInSameType && setter == decl;
   DeclContext *dc =
       associateWithSetter ? setter->getDeclContext() : getter->getDeclContext();
 
@@ -7472,25 +7475,15 @@
 }
 
 void ClangImporter::Implementation::finishPendingActions() {
-  while (true) {
-    // The odd shape of this loop comes from previously having more than one
-    // possible kind of pending action. It's left this way to make it easy to
-    // add another one back in an `else if` clause.
-    if (!RegisteredExternalDecls.empty()) {
-      if (hasFinishedTypeChecking()) {
-        RegisteredExternalDecls.clear();
-      } else {
-        Decl *D = RegisteredExternalDecls.pop_back_val();
-        SwiftContext.addExternalDecl(D);
-        if (auto typeResolver = getTypeResolver())
-          if (auto *nominal = dyn_cast<NominalTypeDecl>(D))
-            if (!nominal->hasDelayedMembers())
-              typeResolver->resolveExternalDeclImplicitMembers(nominal);
-      }
-    } else {
-      break;
-    }
+  if (RegisteredExternalDecls.empty())
+    return;
+
+  if (!hasFinishedTypeChecking()) {
+    for (auto *D : RegisteredExternalDecls)
+      SwiftContext.addExternalDecl(D);
   }
+
+  RegisteredExternalDecls.clear();
 }
 
 /// Look up associated type requirements in the conforming type.
diff --git a/lib/ClangImporter/ImporterImpl.h b/lib/ClangImporter/ImporterImpl.h
index b57e881..1303c08 100644
--- a/lib/ClangImporter/ImporterImpl.h
+++ b/lib/ClangImporter/ImporterImpl.h
@@ -1149,7 +1149,7 @@
   loadAllMembers(Decl *D, uint64_t unused) override;
 
   virtual Optional<TinyPtrVector<ValueDecl *>>
-  loadNamedMembers(const IterableDeclContext *IDC, DeclName N,
+  loadNamedMembers(const IterableDeclContext *IDC, DeclBaseName N,
                    uint64_t contextData) override;
 
 private:
diff --git a/lib/Demangling/Demangler.cpp b/lib/Demangling/Demangler.cpp
index 7624cfa..cdbff5f 100644
--- a/lib/Demangling/Demangler.cpp
+++ b/lib/Demangling/Demangler.cpp
@@ -355,6 +355,20 @@
   return Nd;
 }
 
+NodePointer Demangler::createWithChildren(Node::Kind kind, NodePointer Child1,
+                                          NodePointer Child2,
+                                          NodePointer Child3,
+                                          NodePointer Child4) {
+  if (!Child1 || !Child2 || !Child3 || !Child4)
+    return nullptr;
+  NodePointer Nd = createNode(kind);
+  Nd->addChild(Child1, *this);
+  Nd->addChild(Child2, *this);
+  Nd->addChild(Child3, *this);
+  Nd->addChild(Child4, *this);
+  return Nd;
+}
+
 NodePointer Demangler::changeKind(NodePointer Node, Node::Kind NewKind) {
   if (!Node)
     return nullptr;
@@ -372,13 +386,22 @@
   return NewNode;
 }
 
+NodePointer Demangler::demangleTypeMangling() {
+  auto Type = popNode(Node::Kind::Type);
+  auto LabelList = popFunctionParamLabels(Type);
+  auto TypeMangling = createNode(Node::Kind::TypeMangling);
+
+  addChild(TypeMangling, LabelList);
+  addChild(TypeMangling, Type);
+  return TypeMangling;
+}
+
 NodePointer Demangler::demangleOperator() {
   switch (char c = nextChar()) {
     case 'A': return demangleMultiSubstitutions();
     case 'B': return demangleBuiltinType();
     case 'C': return demangleAnyGenericType(Node::Kind::Class);
-    case 'D': return createWithChild(Node::Kind::TypeMangling,
-                                     popNode(Node::Kind::Type));
+    case 'D': return demangleTypeMangling();
     case 'E': return demangleExtensionContext();
     case 'F': return demanglePlainFunction();
     case 'G': return demangleBoundGenericType();
@@ -812,12 +835,19 @@
 NodePointer Demangler::demanglePlainFunction() {
   NodePointer GenSig = popNode(Node::Kind::DependentGenericSignature);
   NodePointer Type = popFunctionType(Node::Kind::FunctionType);
+  NodePointer LabelList = popFunctionParamLabels(Type);
+
   if (GenSig) {
     Type = createType(createWithChildren(Node::Kind::DependentGenericType,
                                          GenSig, Type));
   }
-  NodePointer Name = popNode(isDeclName);
-  NodePointer Ctx = popContext();
+
+  auto Name = popNode(isDeclName);
+  auto Ctx = popContext();
+
+  if (LabelList)
+    return createWithChildren(Node::Kind::Function, Ctx, Name, LabelList, Type);
+
   return createWithChildren(Node::Kind::Function, Ctx, Name, Type);
 }
 
@@ -837,7 +867,53 @@
   } else {
     ParamsType = popNode(Node::Kind::Type);
   }
-  return createWithChild(kind, ParamsType);
+
+  NodePointer Node = nullptr;
+  // Store the number of parameters in the argument tuple
+  // node to make it easier to reach it, see `popFunctionParamLabels`.
+  if (ParamsType && kind == Node::Kind::ArgumentTuple) {
+    auto Params = ParamsType->getFirstChild();
+    Node::IndexType NumParams =
+        Params->getKind() == Node::Kind::Tuple ? Params->getNumChildren() : 1;
+    Node = createNode(kind, NumParams);
+  } else {
+    Node = createNode(kind);
+  }
+
+  return addChild(Node, ParamsType);
+}
+
+NodePointer Demangler::popFunctionParamLabels(NodePointer Type) {
+  if (popNode(Node::Kind::EmptyList))
+    return createNode(Node::Kind::LabelList);
+
+  assert(Type->getKind() == Node::Kind::Type);
+
+  auto FuncType = Type->getFirstChild();
+  if (FuncType->getKind() == Node::Kind::DependentGenericType)
+    FuncType = FuncType->getChild(1)->getFirstChild();
+
+  if (FuncType->getKind() != Node::Kind::FunctionType)
+    return nullptr;
+
+  auto ParameterType = FuncType->getFirstChild();
+  if (ParameterType->getKind() == Node::Kind::ThrowsAnnotation)
+    ParameterType = FuncType->getChild(1);
+
+  assert(ParameterType->getKind() == Node::Kind::ArgumentTuple);
+  if (ParameterType->getIndex() == 0)
+    return nullptr;
+
+  auto LabelList = createNode(Node::Kind::LabelList);
+  for (unsigned i = 0, n = ParameterType->getIndex(); i != n; ++i) {
+    auto Label = popNode();
+    assert(Label && (Label->getKind() == Node::Kind::Identifier ||
+                     Label->getKind() == Node::Kind::FirstElementMarker));
+    LabelList->addChild(Label, *this);
+  }
+
+  LabelList->reverseChildren();
+  return LabelList;
 }
 
 NodePointer Demangler::popTuple() {
@@ -1900,20 +1976,21 @@
     default: return nullptr;
   }
 
-  NodePointer Child1 = nullptr, Child2 = nullptr;
+  NodePointer NameOrIndex = nullptr, ParamType = nullptr, LabelList = nullptr;
   switch (Args) {
     case None:
       break;
     case TypeAndMaybePrivateName:
-      Child1 = popNode(Node::Kind::PrivateDeclName);
-      Child2 = popNode(Node::Kind::Type);
+      NameOrIndex = popNode(Node::Kind::PrivateDeclName);
+      ParamType = popNode(Node::Kind::Type);
+      LabelList = popFunctionParamLabels(ParamType);
       break;
     case TypeAndIndex:
-      Child1 = demangleIndexAsNode();
-      Child2 = popNode(Node::Kind::Type);
+      NameOrIndex = demangleIndexAsNode();
+      ParamType = popNode(Node::Kind::Type);
       break;
     case Index:
-      Child1 = demangleIndexAsNode();
+      NameOrIndex = demangleIndexAsNode();
       break;
   }
   NodePointer Entity = createWithChild(Kind, popContext());
@@ -1921,16 +1998,16 @@
     case None:
       break;
     case Index:
-      Entity = addChild(Entity, Child1);
+      addChild(Entity, NameOrIndex);
       break;
     case TypeAndMaybePrivateName:
-      if (Child1)
-        Entity = addChild(Entity, Child1);
-      Entity = addChild(Entity, Child2);
+      addChild(Entity, LabelList);
+      addChild(Entity, ParamType);
+      addChild(Entity, NameOrIndex);
       break;
     case TypeAndIndex:
-      Entity = addChild(Entity, Child1);
-      Entity = addChild(Entity, Child2);
+      addChild(Entity, NameOrIndex);
+      addChild(Entity, ParamType);
       break;
   }
   return Entity;
@@ -1938,9 +2015,11 @@
 
 NodePointer Demangler::demangleEntity(Node::Kind Kind) {
   NodePointer Type = popNode(Node::Kind::Type);
+  NodePointer LabelList = popFunctionParamLabels(Type);
   NodePointer Name = popNode(isDeclName);
   NodePointer Context = popContext();
-  return createWithChildren(Kind, Context, Name, Type);
+  return LabelList ? createWithChildren(Kind, Context, Name, LabelList, Type)
+                   : createWithChildren(Kind, Context, Name, Type);
 }
 
 NodePointer Demangler::demangleVariable() {
@@ -1951,13 +2030,14 @@
 NodePointer Demangler::demangleSubscript() {
   NodePointer PrivateName = popNode(Node::Kind::PrivateDeclName);
   NodePointer Type = popNode(Node::Kind::Type);
+  NodePointer LabelList = popFunctionParamLabels(Type);
   NodePointer Context = popContext();
 
   NodePointer Subscript = createNode(Node::Kind::Subscript);
-  Subscript->addChild(Context, *this);
-  Subscript->addChild(Type, *this);
-  if (PrivateName)
-    Subscript->addChild(PrivateName, *this);
+  addChild(Subscript, Context);
+  addChild(Subscript, LabelList);
+  addChild(Subscript, Type);
+  addChild(Subscript, PrivateName);
 
   return demangleAccessor(Subscript);
 }
diff --git a/lib/Demangling/NodePrinter.cpp b/lib/Demangling/NodePrinter.cpp
index fb82c18..63338be 100644
--- a/lib/Demangling/NodePrinter.cpp
+++ b/lib/Demangling/NodePrinter.cpp
@@ -14,6 +14,7 @@
 //
 //===----------------------------------------------------------------------===//
 
+#include "swift/Basic/STLExtras.h"
 #include "swift/Demangling/Demangle.h"
 #include "swift/Strings.h"
 #include <cstdio>
@@ -277,6 +278,7 @@
     case Node::Kind::Type:
     case Node::Kind::TypeAlias:
     case Node::Kind::TypeList:
+    case Node::Kind::LabelList:
       return true;
 
     case Node::Kind::ProtocolList:
@@ -541,46 +543,87 @@
     }
   }
 
-  void printFunctionType(NodePointer node) {
+  NodePointer getChildIf(NodePointer Node, Node::Kind Kind) {
+    auto result =
+        std::find_if(Node->begin(), Node->end(), [&](NodePointer child) {
+          return child->getKind() == Kind;
+        });
+    return result != Node->end() ? *result : nullptr;
+  }
+
+  void printFunctionParameters(NodePointer LabelList, NodePointer ParameterType,
+                               bool showTypes) {
+    assert(ParameterType->getKind() == Node::Kind::ArgumentTuple);
+
+    NodePointer Parameters = ParameterType->getFirstChild();
+    assert(Parameters->getKind() == Node::Kind::Type);
+    Parameters = Parameters->getFirstChild();
+    if (Parameters->getKind() != Node::Kind::Tuple) {
+      // only a single not-named parameter
+      if (showTypes) {
+        Printer << '(';
+        print(Parameters);
+        Printer << ')';
+      } else {
+        Printer << "(_:)";
+      }
+      return;
+    }
+
+    auto getLabelFor = [&](NodePointer Param, unsigned Index) -> std::string {
+      auto Label = LabelList->getChild(Index);
+      assert(Label && (Label->getKind() == Node::Kind::Identifier ||
+                       Label->getKind() == Node::Kind::FirstElementMarker));
+      return Label->getKind() == Node::Kind::Identifier ? Label->getText()
+                                                        : "_";
+    };
+
+    unsigned ParamIndex = 0;
+    bool hasLabels = LabelList && LabelList->getNumChildren() > 0;
+
+    Printer << '(';
+    interleave(Parameters->begin(), Parameters->end(),
+               [&](NodePointer Param) {
+                 assert(Param->getKind() == Node::Kind::TupleElement);
+
+                 if (hasLabels) {
+                   Printer << getLabelFor(Param, ParamIndex) << ':';
+                 } else if (!showTypes) {
+                   if (auto Label = getChildIf(Param,
+                                               Node::Kind::TupleElementName))
+                     Printer << Label->getText() << ":";
+                   else
+                     Printer << "_:";
+                 }
+
+                 if (hasLabels && showTypes)
+                   Printer << ' ';
+
+                 ++ParamIndex;
+
+                 if (showTypes)
+                   print(Param);
+               },
+               [&]() { Printer << (showTypes ? ", " : ""); });
+    Printer << ')';
+  }
+
+  void printFunctionType(NodePointer LabelList, NodePointer node) {
     assert(node->getNumChildren() == 2 || node->getNumChildren() == 3);
     unsigned startIndex = 0;
-    bool throws = false;
-    if (node->getNumChildren() == 3) {
-      assert(node->getChild(0)->getKind() == Node::Kind::ThrowsAnnotation);
-      startIndex++;
-      throws = true;
-    }
-    if (Options.ShowFunctionArgumentTypes) {
-      print(node->getChild(startIndex));
-      if (throws) Printer << " throws";
-      print(node->getChild(startIndex+1));
+    if (node->getChild(0)->getKind() == Node::Kind::ThrowsAnnotation)
+      startIndex = 1;
+
+    printFunctionParameters(LabelList, node->getChild(startIndex),
+                            Options.ShowFunctionArgumentTypes);
+
+    if (!Options.ShowFunctionArgumentTypes)
       return;
-    }
-    // Print simplified arguments
-    NodePointer Args = node->getChild(startIndex);
-    assert(Args->getKind() == Node::Kind::ArgumentTuple);
-    Args = Args->getFirstChild();
-    assert(Args->getKind() == Node::Kind::Type);
-    Args = Args->getFirstChild();
-    if (Args->getKind() != Node::Kind::Tuple) {
-      // only a single not-named argument
-      Printer << "(_:)";
-      return;
-    }
-    Printer << '(';
-    for (NodePointer Arg : *Args) {
-      assert(Arg->getKind() == Node::Kind::TupleElement);
-      unsigned NameIdx = 0;
-      if (Arg->getFirstChild()->getKind() == Node::Kind::VariadicMarker)
-        NameIdx = 1;
-      if (Arg->getChild(NameIdx)->getKind() == Node::Kind::TupleElementName) {
-        Printer << Arg->getChild(NameIdx)->getText();
-      } else {
-        Printer << '_';
-      }
-      Printer << ':';
-    }
-    Printer << ')';
+
+    if (startIndex == 1)
+      Printer << " throws";
+
+    print(node->getChild(startIndex + 1));
   }
 
   void printImplFunctionType(NodePointer fn) {
@@ -910,7 +953,11 @@
     print(Node->getChild(0));
     return nullptr;
   case Node::Kind::TypeMangling:
-    print(Node->getChild(0));
+    if (Node->getChild(0)->getKind() == Node::Kind::LabelList) {
+      printFunctionType(Node->getChild(0), Node->getChild(1)->getFirstChild());
+    } else {
+      print(Node->getChild(0));
+    }
     return nullptr;
   case Node::Kind::Class:
   case Node::Kind::Structure:
@@ -950,39 +997,19 @@
     return nullptr;
   case Node::Kind::AutoClosureType:
     Printer << "@autoclosure ";
-    printFunctionType(Node);
+    printFunctionType(nullptr, Node);
     return nullptr;
   case Node::Kind::ThinFunctionType:
     Printer << "@convention(thin) ";
-    printFunctionType(Node);
+    printFunctionType(nullptr, Node);
     return nullptr;
   case Node::Kind::FunctionType:
   case Node::Kind::UncurriedFunctionType:
-    printFunctionType(Node);
+    printFunctionType(nullptr, Node);
     return nullptr;
-  case Node::Kind::ArgumentTuple: {
-    bool need_parens = false;
-    if (Node->getNumChildren() > 1)
-      need_parens = true;
-    else {
-      if (!Node->hasChildren())
-        need_parens = true;
-      else {
-        Node::Kind child0_kind = Node->getChild(0)->getKind();
-        if (child0_kind == Node::Kind::Type)
-          child0_kind = Node->getChild(0)->getChild(0)->getKind();
-
-        if (child0_kind != Node::Kind::Tuple)
-          need_parens = true;
-      }
-    }
-    if (need_parens)
-      Printer << "(";
-    printChildren(Node);
-    if (need_parens)
-      Printer << ")";
+  case Node::Kind::ArgumentTuple:
+    printFunctionParameters(nullptr, Node, Options.ShowFunctionArgumentTypes);
     return nullptr;
-  }
   case Node::Kind::Tuple: {
     Printer << "(";
     printChildren(Node, ", ");
@@ -990,27 +1017,16 @@
     return nullptr;
   }
   case Node::Kind::TupleElement: {
-    unsigned Idx = 0;
-    bool isVariadic = false;
-    if (Node->getNumChildren() >= 1 &&
-        Node->getFirstChild()->getKind() == Node::Kind::VariadicMarker) {
-      isVariadic = true;
-      Idx++;
-    }
-    NodePointer type = nullptr;
-    if (Node->getNumChildren() == Idx + 1) {
-      type = Node->getChild(Idx);
-    } else if (Node->getNumChildren() == Idx + 2) {
-      NodePointer id = Node->getChild(Idx);
-      type = Node->getChild(Idx + 1);
-      print(id);
-    }
-    if (isVariadic) {
-      print(type);
+    if (auto Label = getChildIf(Node, Node::Kind::TupleElementName))
+      Printer << Label->getText() << ": ";
+
+    auto Type = getChildIf(Node, Node::Kind::Type);
+    assert(Type && "malformed Node::Kind::TupleElement");
+
+    print(Type);
+
+    if (auto isVariadic = getChildIf(Node, Node::Kind::VariadicMarker))
       Printer << "...";
-    } else {
-      print(type);
-    }
     return nullptr;
   }
   case Node::Kind::TupleElementName:
@@ -1401,12 +1417,12 @@
     return nullptr;
   case Node::Kind::CFunctionPointer: {
     Printer << "@convention(c) ";
-    printFunctionType(Node);
+    printFunctionType(nullptr, Node);
     return nullptr;
   }
   case Node::Kind::ObjCBlock: {
     Printer << "@convention(block) ";
-    printFunctionType(Node);
+    printFunctionType(nullptr, Node);
     return nullptr;
   }
   case Node::Kind::SILBoxType: {
@@ -1603,6 +1619,8 @@
   case Node::Kind::TypeList:
     printChildren(Node);
     return nullptr;
+  case Node::Kind::LabelList:
+    return nullptr;
   case Node::Kind::ImplEscaping:
     Printer << "@escaping";
     return nullptr;
@@ -1889,7 +1907,12 @@
     if (!OverwriteName.empty()) {
       Printer << OverwriteName;
     } else {
-      print(Entity->getChild(1));
+      auto Name = Entity->getChild(1);
+      if (Name->getKind() != Node::Kind::PrivateDeclName)
+        print(Name);
+
+      if (auto PrivateName = getChildIf(Entity, Node::Kind::PrivateDeclName))
+        print(PrivateName);
     }
     if (Printer.getStringRef().size() != CurrentPos && !ExtraName.empty())
       Printer << '.';
@@ -1900,10 +1923,8 @@
       Printer << ExtraIndex;
   }
   if (TypePr != TypePrinting::NoType) {
-    NodePointer type = Entity->getChild(1);
-    if (type->getKind() != Node::Kind::Type)
-      type = Entity->getChild(2);
-    assert(type->getKind() == Node::Kind::Type);
+    NodePointer type = getChildIf(Entity, Node::Kind::Type);
+    assert(type && "malformed entity");
     type = type->getChild(0);
     if (TypePr == TypePrinting::FunctionStyle) {
       // We expect to see a function type here, but if we don't, use the colon.
@@ -1917,17 +1938,33 @@
         TypePr = TypePrinting::WithColon;
       }
     }
+
+    auto printEntityType = [&](NodePointer type) {
+      if (auto labelList = getChildIf(Entity, Node::Kind::LabelList)) {
+        if (type->getKind() == Node::Kind::DependentGenericType) {
+          print(type->getChild(0)); // generic signature
+
+          auto dependentType = type->getChild(1);
+          if (needSpaceBeforeType(dependentType))
+            Printer << ' ';
+          type = dependentType->getFirstChild();
+        }
+        printFunctionType(labelList, type);
+      } else {
+        print(type);
+      }
+    };
+
     if (TypePr == TypePrinting::WithColon) {
       if (Options.DisplayEntityTypes) {
         Printer << " : ";
-        print(type);
+        printEntityType(type);
       }
     } else {
       assert(TypePr == TypePrinting::FunctionStyle);
       if (MultiWordName || needSpaceBeforeType(type))
         Printer << ' ';
-
-      print(type);
+      printEntityType(type);
     }
   }
   if (!asPrefixContext && PostfixContext) {
diff --git a/lib/Demangling/OldRemangler.cpp b/lib/Demangling/OldRemangler.cpp
index 3cb1315..043956b 100644
--- a/lib/Demangling/OldRemangler.cpp
+++ b/lib/Demangling/OldRemangler.cpp
@@ -312,6 +312,73 @@
 }
 #include "swift/Demangling/DemangleNodes.def"
 
+/// Re-apply labels from the function to its parameter type
+/// to preserve old mangling style.
+///
+/// \param LabelList The list of labels to apply.
+/// \param OrigType  The function parameter type to apply labels to.
+/// \param Factory   The node factory to use to allocate new nodes.
+static NodePointer applyParamLabels(NodePointer LabelList, NodePointer OrigType,
+                                    NodeFactory &Factory) {
+  if (LabelList->getNumChildren() == 0)
+    return OrigType;
+
+  auto applyParamLabels = [&](NodePointer ArgTuple) -> NodePointer {
+    assert(ArgTuple->getKind() == Node::Kind::ArgumentTuple);
+
+    auto ParamsType = Factory.createNode(Node::Kind::ArgumentTuple);
+    auto Tuple = Factory.createNode(Node::Kind::Tuple);
+
+    auto OrigTuple = ArgTuple->getFirstChild()->getFirstChild();
+    assert(OrigTuple->getKind() == Node::Kind::Tuple);
+
+    for (unsigned i = 0, n = OrigTuple->getNumChildren(); i != n; ++i) {
+      const auto Label = LabelList->getChild(i);
+      if (Label->getKind() == Node::Kind::FirstElementMarker) {
+        Tuple->addChild(OrigTuple->getChild(i), Factory);
+        continue;
+      }
+
+      auto OrigElt = OrigTuple->getChild(i);
+      auto NewElt = Factory.createNode(Node::Kind::TupleElement);
+
+      NewElt->addChild(Factory.createNodeWithAllocatedText(
+                           Node::Kind::TupleElementName, Label->getText()),
+                       Factory);
+
+      for (auto &Child : *OrigElt)
+        NewElt->addChild(Child, Factory);
+
+      Tuple->addChild(NewElt, Factory);
+    }
+
+    auto Type = Factory.createNode(Node::Kind::Type);
+    Type->addChild(Tuple, Factory);
+    ParamsType->addChild(Type, Factory);
+    return ParamsType;
+  };
+
+  auto visitTypeChild = [&](NodePointer Child) -> NodePointer {
+    if (Child->getKind() != Node::Kind::FunctionType)
+      return Child;
+
+    auto FuncType = Factory.createNode(Node::Kind::FunctionType);
+    for (unsigned i = 0, n = Child->getNumChildren(); i != n; ++i) {
+      NodePointer FuncChild = Child->getChild(i);
+      if (FuncChild->getKind() == Node::Kind::ArgumentTuple)
+        FuncChild = applyParamLabels(FuncChild);
+      FuncType->addChild(FuncChild, Factory);
+    }
+    return FuncType;
+  };
+
+  auto Type = Factory.createNode(OrigType->getKind());
+  for (auto &Child : *OrigType)
+    Type->addChild(visitTypeChild(Child), Factory);
+
+  return Type;
+}
+
 /// Reset the currently-active set of substitutions.  This is useful
 /// when part of the mangling is done independently, e.g. when an
 /// optimization pass modifies a pass.
@@ -778,19 +845,36 @@
   Out << 'F';
   mangleEntityContext(storageNode->getChild(0), ctx);
   Out << accessorCode;
-  switch (storageNode->getKind()) {
-  case Demangle::Node::Kind::Variable:
-    mangleChildNode(storageNode, 1);
-    mangleEntityType(storageNode->getChild(2), ctx);
-    break;
-  case Demangle::Node::Kind::Subscript:
-    if (storageNode->getNumChildren() > 2 &&
-        storageNode->getChild(2)->getKind() == Node::Kind::PrivateDeclName) {
-      mangleChildNode(storageNode, 2);
+
+  auto mangleAccessorType = [&](unsigned TypeIndex) {
+    auto LabelList = storageNode->getChild(TypeIndex);
+    if (LabelList->getKind() == Node::Kind::LabelList) {
+      auto Type = storageNode->getChild(TypeIndex + 1);
+      mangleEntityType(applyParamLabels(LabelList, Type, Factory), ctx);
+    } else {
+      mangleEntityType(storageNode->getChild(TypeIndex), ctx);
     }
-    mangleIdentifier("subscript", OperatorKind::NotOperator);
-    mangleEntityType(storageNode->getChild(1), ctx);
+  };
+
+  switch (storageNode->getKind()) {
+  case Demangle::Node::Kind::Variable: {
+    mangleChildNode(storageNode, 1);
+    mangleAccessorType(2);
     break;
+  }
+
+  case Demangle::Node::Kind::Subscript: {
+    auto NumChildren = storageNode->getNumChildren();
+    assert(NumChildren <= 4);
+
+    auto PrivateName = storageNode->getChild(NumChildren - 1);
+    if (PrivateName->getKind() == Node::Kind::PrivateDeclName)
+      mangle(PrivateName);
+
+    mangleIdentifier("subscript", OperatorKind::NotOperator);
+    mangleAccessorType(1);
+    break;
+  }
   default:
       unreachable("Not a storage node");
   }
@@ -922,22 +1006,36 @@
 void Remangler::mangleTypedEntity(Node *node, char basicKind,
                                   StringRef entityKind,
                                   EntityContext &ctx) {
-  assert(node->getNumChildren() == 2);
+  assert(node->getNumChildren() == 2 || node->getNumChildren() == 3);
   Out << basicKind;
   mangleEntityContext(node->begin()[0], ctx);
   Out << entityKind;
-  mangleEntityType(node->begin()[1], ctx);
+
+  if (node->begin()[1]->getKind() == Node::Kind::LabelList) {
+    auto LabelList = node->begin()[1];
+    auto Type = node->begin()[2];
+    mangleEntityType(applyParamLabels(LabelList, Type, Factory), ctx);
+  } else {
+    mangleEntityType(node->begin()[1], ctx);
+  }
 }
 
 void Remangler::mangleNamedAndTypedEntity(Node *node, char basicKind,
                                           StringRef entityKind,
                                           EntityContext &ctx) {
-  assert(node->getNumChildren() == 3);
+  assert(node->getNumChildren() == 3 || node->getNumChildren() == 4);
   Out << basicKind;
   mangleEntityContext(node->begin()[0], ctx);
   Out << entityKind;
   mangleChildNode(node, 1); // decl name / index
-  mangleEntityType(node->begin()[2], ctx);
+
+  if (node->begin()[2]->getKind() == Node::Kind::LabelList) {
+    auto LabelList = node->begin()[2];
+    auto Type = node->begin()[3];
+    mangleEntityType(applyParamLabels(LabelList, Type, Factory), ctx);
+  } else {
+    mangleEntityType(node->begin()[2], ctx);
+  }
 }
 
 void Remangler::mangleEntityContext(Node *node, EntityContext &ctx) {
@@ -1649,6 +1747,13 @@
   Out << '_';
 }
 
+void Remangler::mangleLabelList(Node *node) {
+  if (node->getNumChildren() == 0)
+    Out << 'y';
+  else
+    mangleChildNodes(node);
+}
+
 void Remangler::mangleReflectionMetadataBuiltinDescriptor(Node *node) {
   Out << "MRb";
 }
diff --git a/lib/Demangling/Remangler.cpp b/lib/Demangling/Remangler.cpp
index 8a03e3a..2c6f152 100644
--- a/lib/Demangling/Remangler.cpp
+++ b/lib/Demangling/Remangler.cpp
@@ -618,12 +618,7 @@
 }
 
 void Remangler::mangleAnyConstructor(Node *node, char kindOp) {
-  mangleChildNode(node, 0);
-  if (node->getNumChildren() > 2) {
-    assert(node->getNumChildren() == 3);
-    mangleChildNode(node, 2);
-  }
-  mangleChildNode(node, 1);
+  mangleChildNodes(node);
   Buffer << "f" << kindOp;
 }
 
@@ -860,13 +855,20 @@
 void Remangler::mangleFunction(Node *node) {
   mangleChildNode(node, 0); // context
   mangleChildNode(node, 1); // name
-  Node *FuncType = getSingleChild(node->getChild(2));
+
+  bool hasLabels = node->getChild(2)->getKind() == Node::Kind::LabelList;
+  Node *FuncType = getSingleChild(node->getChild(hasLabels ? 3 : 2));
+
+  if (hasLabels)
+    mangleChildNode(node, 2); // parameter labels
+
   if (FuncType->getKind() == Node::Kind::DependentGenericType) {
     mangleFunctionSignature(getSingleChild(FuncType->getChild(1)));
     mangleChildNode(FuncType, 0); // generic signature
   } else {
     mangleFunctionSignature(FuncType);
   }
+
   Buffer << "F";
 }
 
@@ -1614,8 +1616,15 @@
   mangleEndOfList(FirstElem);
 }
 
+void Remangler::mangleLabelList(Node *node) {
+  if (node->getNumChildren() == 0)
+    Buffer << 'y';
+  else
+    mangleChildNodes(node);
+}
+
 void Remangler::mangleTypeMangling(Node *node) {
-  mangleSingleChildNode(node);
+  mangleChildNodes(node);
   Buffer << 'D';
 }
 
diff --git a/lib/Driver/ToolChains.cpp b/lib/Driver/ToolChains.cpp
index 60e41d5..8071960 100644
--- a/lib/Driver/ToolChains.cpp
+++ b/lib/Driver/ToolChains.cpp
@@ -140,9 +140,6 @@
                        options::OPT_warn_swift3_objc_inference_complete);
   inputArgs.AddLastArg(arguments, options::OPT_typo_correction_limit);
   inputArgs.AddLastArg(arguments, options::OPT_enable_app_extension);
-  inputArgs.AddLastArg(
-                     arguments,
-                     options::OPT_enable_experimental_conditional_conformances);
   inputArgs.AddLastArg(arguments, options::OPT_enable_testing);
   inputArgs.AddLastArg(arguments, options::OPT_g_Group);
   inputArgs.AddLastArg(arguments, options::OPT_import_underlying_module);
@@ -335,10 +332,12 @@
     break;
   }
   case OutputInfo::Mode::SingleCompile: {
+    StringRef PrimaryFileWrittenToCommandLine;
     if (context.Output.getPrimaryOutputType() == types::TY_IndexData) {
       if (Arg *A = context.Args.getLastArg(options::OPT_index_file_path)) {
         Arguments.push_back("-primary-file");
         Arguments.push_back(A->getValue());
+        PrimaryFileWrittenToCommandLine = A->getValue();
       }
     }
     if (context.Args.hasArg(options::OPT_driver_use_filelists) ||
@@ -347,7 +346,10 @@
       Arguments.push_back(context.getAllSourcesPath());
     } else {
       for (const Action *A : context.InputActions) {
-        cast<InputAction>(A)->getInputArg().render(context.Args, Arguments);
+        const Arg &InputArg = cast<InputAction>(A)->getInputArg();
+        // Frontend no longer tolerates redundant input files on command line.
+        if (InputArg.getValue() != PrimaryFileWrittenToCommandLine)
+          InputArg.render(context.Args, Arguments);
       }
     }
     break;
diff --git a/lib/Frontend/CompilerInvocation.cpp b/lib/Frontend/CompilerInvocation.cpp
index 3aef06d..5b7c020 100644
--- a/lib/Frontend/CompilerInvocation.cpp
+++ b/lib/Frontend/CompilerInvocation.cpp
@@ -118,116 +118,131 @@
   FrontendInputs &Inputs;
 
   Arg const *const FilelistPathArg;
+  Arg const *const PrimaryFilelistPathArg;
 
-  std::unique_ptr<llvm::MemoryBuffer> FilelistBuffer;
+  SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 4> BuffersToKeepAlive;
 
-  llvm::StringMap<unsigned> FileIndices;
-  std::vector<StringRef> PrimaryFiles;
-
-  StringRef filelistPath() { return FilelistPathArg->getValue(); }
-
-  void addPrimary(StringRef file) { PrimaryFiles.push_back(file); }
-
-  void addInput(StringRef file) {
-    FileIndices.insert({file, Inputs.inputFilenameCount()});
-    Inputs.addInputFilename(file);
-  }
-
-  bool arePrimariesOnCommandLineAlsoAppearingInFilelist() {
-    return FilelistPathArg != nullptr;
-  }
-
-  enum class Whence {
-    PrimaryFromCommandLine,
-    SecondaryFromCommandLine,
-    SecondaryFromFileList
-  };
-
-  void addFile(StringRef file, Whence whence) {
-    switch (whence) {
-    case Whence::PrimaryFromCommandLine:
-      addPrimary(file);
-      if (!arePrimariesOnCommandLineAlsoAppearingInFilelist())
-        addInput(file);
-      break;
-    case Whence::SecondaryFromCommandLine:
-    case Whence::SecondaryFromFileList:
-      addInput(file);
-      break;
-    }
-  }
+  llvm::SetVector<StringRef> Files;
 
 public:
   ArgsToFrontendInputsConverter(DiagnosticEngine &Diags, const ArgList &Args,
                                 FrontendInputs &Inputs)
       : Diags(Diags), Args(Args), Inputs(Inputs),
-        FilelistPathArg(Args.getLastArg(options::OPT_filelist)) {}
+        FilelistPathArg(Args.getLastArg(options::OPT_filelist)),
+        PrimaryFilelistPathArg(Args.getLastArg(options::OPT_primary_filelist)) {
+  }
 
   bool convert() {
     if (enforceFilelistExclusion())
       return true;
-    getFilesFromCommandLine();
-    if (getFilesFromFilelist())
+    if (FilelistPathArg ? readInputFilesFromFilelist()
+                        : readInputFilesFromCommandLine())
       return true;
-    return setPrimaryFiles();
+    Optional<std::set<StringRef>> primaryFiles = readPrimaryFiles();
+    if (!primaryFiles)
+      return true;
+    std::set<StringRef> unusedPrimaryFiles =
+        createInputFilesConsumingPrimaries(*primaryFiles);
+    return checkForMissingPrimaryFiles(unusedPrimaryFiles);
   }
 
 private:
   bool enforceFilelistExclusion() {
-    if (Args.hasArg(options::OPT_INPUT) && FilelistPathArg != nullptr) {
+    if (Args.hasArg(options::OPT_INPUT) && FilelistPathArg) {
       Diags.diagnose(SourceLoc(),
                      diag::error_cannot_have_input_files_with_file_list);
       return true;
     }
+    // The following is not strictly necessary, but the restriction makes
+    // it easier to understand a given command line:
+    if (Args.hasArg(options::OPT_primary_file) && PrimaryFilelistPathArg) {
+      Diags.diagnose(
+          SourceLoc(),
+          diag::error_cannot_have_primary_files_with_primary_file_list);
+      return true;
+    }
     return false;
   }
-  void getFilesFromCommandLine() {
+
+  bool readInputFilesFromCommandLine() {
+    bool hadDuplicates = false;
     for (const Arg *A :
          Args.filtered(options::OPT_INPUT, options::OPT_primary_file)) {
-      StringRef file = A->getValue();
-      if (A->getOption().matches(options::OPT_INPUT))
-        addFile(file, Whence::SecondaryFromCommandLine);
-      else if (A->getOption().matches(options::OPT_primary_file))
-        addFile(file, Whence::PrimaryFromCommandLine);
-      else
-        llvm_unreachable("Unknown input-related argument!");
+      hadDuplicates = addFile(A->getValue()) || hadDuplicates;
     }
+    return false; // FIXME: Don't bail out for duplicates, too many tests depend
+                  // on it.
   }
 
-  bool getFilesFromFilelist() {
-    if (FilelistPathArg == nullptr)
+  bool readInputFilesFromFilelist() {
+    bool hadDuplicates = false;
+    bool hadError =
+        forAllFilesInFilelist(FilelistPathArg, [&](StringRef file) -> void {
+          hadDuplicates = addFile(file) || hadDuplicates;
+        });
+    if (hadError)
+      return true;
+    return false; // FIXME: Don't bail out for duplicates, too many tests depend on it.
+  }
+
+  bool forAllFilesInFilelist(Arg const *const pathArg,
+                             llvm::function_ref<void(StringRef)> fn) {
+    if (!pathArg)
       return false;
+    StringRef path = pathArg->getValue();
     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> filelistBufferOrError =
-        llvm::MemoryBuffer::getFile(filelistPath());
+        llvm::MemoryBuffer::getFile(path);
     if (!filelistBufferOrError) {
-      Diags.diagnose(SourceLoc(), diag::cannot_open_file, filelistPath(),
+      Diags.diagnose(SourceLoc(), diag::cannot_open_file, path,
                      filelistBufferOrError.getError().message());
       return true;
     }
-    // Keep buffer alive because code passes around StringRefs.
-    FilelistBuffer = std::move(*filelistBufferOrError);
-    for (auto file : llvm::make_range(llvm::line_iterator(*FilelistBuffer),
-                                      llvm::line_iterator())) {
-      addFile(file, Whence::SecondaryFromFileList);
-    }
+    for (auto file :
+         llvm::make_range(llvm::line_iterator(*filelistBufferOrError->get()),
+                          llvm::line_iterator()))
+      fn(file);
+    BuffersToKeepAlive.push_back(std::move(*filelistBufferOrError));
     return false;
   }
 
-  bool setPrimaryFiles() {
-    for (StringRef primaryFile : PrimaryFiles) {
-      const auto iterator = FileIndices.find(primaryFile);
+  bool addFile(StringRef file) {
+    if (Files.insert(file))
+      return false;
+    Diags.diagnose(SourceLoc(), diag::error_duplicate_input_file, file);
+    return true;
+  }
+
+  Optional<std::set<StringRef>> readPrimaryFiles() {
+    std::set<StringRef> primaryFiles;
+    for (const Arg *A : Args.filtered(options::OPT_primary_file))
+      primaryFiles.insert(A->getValue());
+    if (forAllFilesInFilelist(
+            PrimaryFilelistPathArg,
+            [&](StringRef file) -> void { primaryFiles.insert(file); }))
+      return None;
+    return primaryFiles;
+  }
+
+  std::set<StringRef>
+  createInputFilesConsumingPrimaries(std::set<StringRef> primaryFiles) {
+    for (auto &file : Files) {
+      bool isPrimary = primaryFiles.count(file) > 0;
+      Inputs.addInput(InputFile(file, isPrimary));
+      if (isPrimary)
+        primaryFiles.erase(file);
+    }
+    return primaryFiles;
+  }
+
+  bool checkForMissingPrimaryFiles(std::set<StringRef> primaryFiles) {
+    for (auto &file : primaryFiles) {
       // Catch "swiftc -frontend -c -filelist foo -primary-file
       // some-file-not-in-foo".
-      if (iterator == FileIndices.end()) {
-        assert(FilelistPathArg != nullptr &&
-               "Missing primary with no filelist");
-        Diags.diagnose(SourceLoc(), diag::error_primary_file_not_found,
-                       primaryFile, filelistPath());
-        return true;
-      }
-      Inputs.addPrimaryInputFilename(iterator->second);
+      assert(FilelistPathArg && "Missing primary with no filelist");
+      Diags.diagnose(SourceLoc(), diag::error_primary_file_not_found, file,
+                     FilelistPathArg->getValue());
     }
-    return false;
+    return !primaryFiles.empty();
   }
 };
 class FrontendArgsToOptionsConverter {
@@ -278,6 +293,8 @@
 
   std::string determineBaseNameOfOutput() const;
 
+  void deriveOutputFilenameFromParts(StringRef dir, StringRef base);
+
   void determineSupplementaryOutputFilenames();
 
   /// Returns the output filenames on the command line or in the output
@@ -659,10 +676,10 @@
     Opts.ModuleName = "REPL";
     return false;
   }
-  if (!Opts.Inputs.hasInputFilenames()) {
+  // In order to pass some tests, must leave ModuleName empty.
+  if (!Opts.Inputs.hasInputs()) {
     Opts.ModuleName = StringRef();
     // FIXME: This is a bug that should not happen, but does in tests.
-    // The current behavior is needed to pass the tests.
     // The compiler should bail out earlier, where "no frontend action was
     // selected".
     return false;
@@ -675,7 +692,7 @@
       !llvm::sys::fs::is_directory(outputFilenames[0]);
   std::string nameToStem = isOutputAUniqueOrdinaryFile
                                ? outputFilenames[0]
-                               : Opts.Inputs.getFilenameOfFirstInput();
+                               : Opts.Inputs.getFilenameOfFirstInput().str();
   Opts.ModuleName = llvm::sys::path::stem(nameToStem);
   return false;
 }
@@ -728,11 +745,7 @@
     }
     return false;
   }
-  llvm::SmallString<128> path(baseName);
-  StringRef suffix = FrontendOptions::suffixForPrincipalOutputFileForAction(
-      Opts.RequestedAction);
-  llvm::sys::path::replace_extension(path, suffix);
-  Opts.OutputFilenames.push_back(path.str());
+  deriveOutputFilenameFromParts("", baseName);
   return false;
 }
 
@@ -745,25 +758,29 @@
                    outputDir);
     return true;
   }
-  llvm::SmallString<128> path(outputDir);
-  llvm::sys::path::append(path, baseName);
+  deriveOutputFilenameFromParts(outputDir, baseName);
+  return false;
+}
+
+void FrontendArgsToOptionsConverter::deriveOutputFilenameFromParts(
+    StringRef dir, StringRef base) {
+  assert(!base.empty());
+  llvm::SmallString<128> path(dir);
+  llvm::sys::path::append(path, base);
   StringRef suffix = FrontendOptions::suffixForPrincipalOutputFileForAction(
       Opts.RequestedAction);
   llvm::sys::path::replace_extension(path, suffix);
   Opts.OutputFilenames.push_back(path.str());
-  return false;
 }
 
 std::string FrontendArgsToOptionsConverter::determineBaseNameOfOutput() const {
   std::string nameToStem;
-  if (Opts.Inputs.hasAPrimaryInputFile()) {
-    assert(Opts.Inputs.hasUniquePrimaryInput() &&
-           "Cannot handle multiple primaries yet");
-    nameToStem = Opts.Inputs.primaryInputFilenameIfAny();
+  if (Opts.Inputs.hasPrimaryInputs()) {
+    nameToStem = Opts.Inputs.getRequiredUniquePrimaryInput().file();
   } else if (auto UserSpecifiedModuleName =
                  Args.getLastArg(options::OPT_module_name)) {
     nameToStem = UserSpecifiedModuleName->getValue();
-  } else if (Opts.Inputs.inputFilenameCount() == 1) {
+  } else if (Opts.Inputs.hasSingleInput()) {
     nameToStem = Opts.Inputs.getFilenameOfFirstInput();
   } else
     nameToStem = "";
@@ -1037,14 +1054,15 @@
   Opts.CodeCompleteInitsInPostfixExpr |=
       Args.hasArg(OPT_code_complete_inits_in_postfix_expr);
 
+  Opts.CodeCompleteCallPatternHeuristics |=
+      Args.hasArg(OPT_code_complete_call_pattern_heuristics);
+
   if (auto A = Args.getLastArg(OPT_enable_target_os_checking,
                                OPT_disable_target_os_checking)) {
     Opts.EnableTargetOSChecking
       = A->getOption().matches(OPT_enable_target_os_checking);
   }
-
-  Opts.EnableConditionalConformances |=
-  Args.hasArg(OPT_enable_experimental_conditional_conformances);
+  
   Opts.EnableASTScopeLookup |= Args.hasArg(OPT_enable_astscope_lookup);
   Opts.DebugConstraintSolver |= Args.hasArg(OPT_debug_constraints);
   Opts.EnableConstraintPropagation |= Args.hasArg(OPT_propagate_constraints);
@@ -1650,10 +1668,10 @@
   // in other classes.
   if (!SILOpts.SILOutputFileNameForDebugging.empty()) {
     Opts.MainInputFilename = SILOpts.SILOutputFileNameForDebugging;
-  } else if (const Optional<StringRef> filename =
-                 FrontendOpts.Inputs.getOptionalUniquePrimaryInputFilename()) {
-    Opts.MainInputFilename = filename.getValue();
-  } else if (FrontendOpts.Inputs.hasUniqueInputFilename()) {
+  } else if (const InputFile *input =
+                 FrontendOpts.Inputs.getUniquePrimaryInput()) {
+    Opts.MainInputFilename = input->file();
+  } else if (FrontendOpts.Inputs.hasSingleInput()) {
     Opts.MainInputFilename = FrontendOpts.Inputs.getFilenameOfFirstInput();
   }
   Opts.OutputFilenames = FrontendOpts.OutputFilenames;
@@ -1886,7 +1904,7 @@
 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
 CompilerInvocation::setUpInputForSILTool(
     StringRef inputFilename, StringRef moduleNameArg,
-    bool alwaysSetModuleToMain,
+    bool alwaysSetModuleToMain, bool bePrimary,
     serialization::ExtendedValidationInfo &extendedInfo) {
   // Load the input file.
   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> fileBufOrErr =
@@ -1897,7 +1915,8 @@
 
   // If it looks like we have an AST, set the source file kind to SIL and the
   // name of the module to the file's name.
-  addInputBuffer(fileBufOrErr.get().get());
+  getFrontendOptions().Inputs.addInput(
+      InputFile(inputFilename, bePrimary, fileBufOrErr.get().get()));
 
   auto result = serialization::validateSerializedAST(
       fileBufOrErr.get()->getBuffer(), &extendedInfo);
diff --git a/lib/Frontend/Frontend.cpp b/lib/Frontend/Frontend.cpp
index ff0228a..90652c5 100644
--- a/lib/Frontend/Frontend.cpp
+++ b/lib/Frontend/Frontend.cpp
@@ -74,26 +74,8 @@
 bool CompilerInstance::setup(const CompilerInvocation &Invok) {
   Invocation = Invok;
 
-  // Honor -Xllvm.
-  if (!Invok.getFrontendOptions().LLVMArgs.empty()) {
-    llvm::SmallVector<const char *, 4> Args;
-    Args.push_back("swift (LLVM option parsing)");
-    for (unsigned i = 0, e = Invok.getFrontendOptions().LLVMArgs.size(); i != e;
-         ++i)
-      Args.push_back(Invok.getFrontendOptions().LLVMArgs[i].c_str());
-    Args.push_back(nullptr);
-    llvm::cl::ParseCommandLineOptions(Args.size()-1, Args.data());
-  }
-
-  if (Invocation.getDiagnosticOptions().ShowDiagnosticsAfterFatalError) {
-    Diagnostics.setShowDiagnosticsAfterFatalError();
-  }
-  if (Invocation.getDiagnosticOptions().SuppressWarnings) {
-    Diagnostics.setSuppressWarnings(true);
-  }
-  if (Invocation.getDiagnosticOptions().WarningsAsErrors) {
-    Diagnostics.setWarningsAsErrors(true);
-  }
+  setUpLLVMArguments();
+  setUpDiagnosticOptions();
 
   // If we are asked to emit a module documentation file, configure lexing and
   // parsing to remember comments.
@@ -107,10 +89,47 @@
   }
 
   Context.reset(new ASTContext(Invocation.getLangOptions(),
-                               Invocation.getSearchPathOptions(),
-                               SourceMgr, Diagnostics));
+                               Invocation.getSearchPathOptions(), SourceMgr,
+                               Diagnostics));
 
-  if (Invocation.getFrontendOptions().EnableSourceImport) {
+  if (setUpModuleLoaders())
+    return true;
+
+  assert(Lexer::isIdentifier(Invocation.getModuleName()));
+
+  if (isInSILMode())
+    Invocation.getLangOptions().EnableAccessControl = false;
+
+  return setUpInputs();
+}
+
+void CompilerInstance::setUpLLVMArguments() {
+  // Honor -Xllvm.
+  if (!Invocation.getFrontendOptions().LLVMArgs.empty()) {
+    llvm::SmallVector<const char *, 4> Args;
+    Args.push_back("swift (LLVM option parsing)");
+    for (unsigned i = 0, e = Invocation.getFrontendOptions().LLVMArgs.size();
+         i != e; ++i)
+      Args.push_back(Invocation.getFrontendOptions().LLVMArgs[i].c_str());
+    Args.push_back(nullptr);
+    llvm::cl::ParseCommandLineOptions(Args.size()-1, Args.data());
+  }
+}
+
+void CompilerInstance::setUpDiagnosticOptions() {
+  if (Invocation.getDiagnosticOptions().ShowDiagnosticsAfterFatalError) {
+    Diagnostics.setShowDiagnosticsAfterFatalError();
+  }
+  if (Invocation.getDiagnosticOptions().SuppressWarnings) {
+    Diagnostics.setSuppressWarnings(true);
+  }
+  if (Invocation.getDiagnosticOptions().WarningsAsErrors) {
+    Diagnostics.setWarningsAsErrors(true);
+  }
+}
+
+bool CompilerInstance::setUpModuleLoaders() {
+  if (hasSourceImport()) {
     bool immediate = FrontendOptions::isActionImmediate(
         Invocation.getFrontendOptions().RequestedAction);
     bool enableResilience = Invocation.getFrontendOptions().EnableResilience;
@@ -138,74 +157,150 @@
 
     Context->addModuleLoader(std::move(clangImporter), /*isClang*/ true);
   }
+  return false;
+}
 
-  assert(Lexer::isIdentifier(Invocation.getModuleName()));
-
-  Optional<unsigned> CodeCompletionBufferID;
-  auto CodeCompletePoint = Invocation.getCodeCompletionPoint();
-  if (CodeCompletePoint.first) {
-    auto MemBuf = CodeCompletePoint.first;
+Optional<unsigned> CompilerInstance::setUpCodeCompletionBuffer() {
+  Optional<unsigned> codeCompletionBufferID;
+  auto codeCompletePoint = Invocation.getCodeCompletionPoint();
+  if (codeCompletePoint.first) {
+    auto memBuf = codeCompletePoint.first;
     // CompilerInvocation doesn't own the buffers, copy to a new buffer.
-    CodeCompletionBufferID = SourceMgr.addMemBufferCopy(MemBuf);
-    InputSourceCodeBufferIDs.push_back(*CodeCompletionBufferID);
-    SourceMgr.setCodeCompletionPoint(*CodeCompletionBufferID,
-                                     CodeCompletePoint.second);
+    codeCompletionBufferID = SourceMgr.addMemBufferCopy(memBuf);
+    InputSourceCodeBufferIDs.push_back(*codeCompletionBufferID);
+    SourceMgr.setCodeCompletionPoint(*codeCompletionBufferID,
+                                     codeCompletePoint.second);
   }
+  return codeCompletionBufferID;
+}
 
-  bool MainMode = (Invocation.getInputKind() == InputFileKind::IFK_Swift);
-  bool SILMode = (Invocation.getInputKind() == InputFileKind::IFK_SIL);
+bool CompilerInstance::setUpInputs() {
+  // Adds to InputSourceCodeBufferIDs, so may need to happen before the
+  // per-input setup.
+  const Optional<unsigned> codeCompletionBufferID = setUpCodeCompletionBuffer();
 
-  if (SILMode)
-    Invocation.getLangOptions().EnableAccessControl = false;
-
-  const Optional<SelectedInput> &PrimaryInput =
-      Invocation.getFrontendOptions().Inputs.getOptionalPrimaryInput();
-
-  // Add the memory buffers first, these will be associated with a filename
-  // and they can replace the contents of an input filename.
-  for (unsigned i = 0,
-                e = Invocation.getFrontendOptions().Inputs.inputBufferCount();
-       i != e; ++i) {
-    // CompilerInvocation doesn't own the buffers, copy to a new buffer.
-    auto *InputBuffer =
-        Invocation.getFrontendOptions().Inputs.getInputBuffers()[i];
-    auto Copy = std::unique_ptr<llvm::MemoryBuffer>(
-        llvm::MemoryBuffer::getMemBufferCopy(
-            InputBuffer->getBuffer(), InputBuffer->getBufferIdentifier()));
-    if (serialization::isSerializedAST(Copy->getBuffer())) {
-      PartialModules.push_back({ std::move(Copy), nullptr });
-    } else {
-      unsigned BufferID = SourceMgr.addNewSourceBuffer(std::move(Copy));
-      InputSourceCodeBufferIDs.push_back(BufferID);
-
-      if (SILMode)
-        MainBufferID = BufferID;
-
-      if (PrimaryInput && PrimaryInput->isBuffer() && PrimaryInput->Index == i)
-        PrimaryBufferID = BufferID;
-    }
-  }
-
-  for (unsigned i = 0,
-                e = Invocation.getFrontendOptions().Inputs.inputFilenameCount();
-       i != e; ++i) {
-    bool hasError = setUpForFileAt(i);
-    if (hasError) {
+  for (const InputFile &input :
+       Invocation.getFrontendOptions().Inputs.getAllFiles())
+    if (setUpForInput(input))
       return true;
-    }
-  }
 
   // Set the primary file to the code-completion point if one exists.
-  if (CodeCompletionBufferID.hasValue())
-    PrimaryBufferID = *CodeCompletionBufferID;
+  if (codeCompletionBufferID.hasValue() &&
+      *codeCompletionBufferID != PrimaryBufferID) {
+    assert(PrimaryBufferID == NO_SUCH_BUFFER && "re-setting PrimaryBufferID");
+    PrimaryBufferID = *codeCompletionBufferID;
+  }
 
-  if (MainMode && MainBufferID == NO_SUCH_BUFFER &&
+  if (isInputSwift() && MainBufferID == NO_SUCH_BUFFER &&
       InputSourceCodeBufferIDs.size() == 1)
     MainBufferID = InputSourceCodeBufferIDs.front();
 
   return false;
 }
 
+bool CompilerInstance::setUpForInput(const InputFile &input) {
+  bool failed = false;
+  Optional<unsigned> bufferID = getRecordedBufferID(input, failed);
+  if (failed)
+    return true;
+  if (!bufferID)
+    return false;
+
+  if (isInSILMode() ||
+      (input.buffer() == nullptr && isInputSwift() &&
+       llvm::sys::path::filename(input.file()) == "main.swift")) {
+    assert(MainBufferID == NO_SUCH_BUFFER && "re-setting MainBufferID");
+    MainBufferID = *bufferID;
+  }
+
+  if (input.isPrimary()) {
+    assert(PrimaryBufferID == NO_SUCH_BUFFER && "re-setting PrimaryBufferID");
+    PrimaryBufferID = *bufferID;
+  }
+  return false;
+}
+
+Optional<unsigned> CompilerInstance::getRecordedBufferID(const InputFile &input,
+                                                         bool &failed) {
+  if (!input.buffer()) {
+    if (Optional<unsigned> existingBufferID =
+            SourceMgr.getIDForBufferIdentifier(input.file())) {
+      return existingBufferID;
+    }
+  }
+  std::pair<std::unique_ptr<llvm::MemoryBuffer>,
+            std::unique_ptr<llvm::MemoryBuffer>>
+      buffers = getInputBufferAndModuleDocBufferIfPresent(input);
+
+  if (!buffers.first) {
+    failed = true;
+    return None;
+  }
+
+  // FIXME: The fact that this test happens twice, for some cases,
+  // suggests that setupInputs could use another round of refactoring.
+  if (serialization::isSerializedAST(buffers.first->getBuffer())) {
+    PartialModules.push_back(
+        {std::move(buffers.first), std::move(buffers.second)});
+    return None;
+  }
+  assert(buffers.second.get() == nullptr);
+  // Transfer ownership of the MemoryBuffer to the SourceMgr.
+  unsigned bufferID = SourceMgr.addNewSourceBuffer(std::move(buffers.first));
+
+  InputSourceCodeBufferIDs.push_back(bufferID);
+  return bufferID;
+}
+
+std::pair<std::unique_ptr<llvm::MemoryBuffer>,
+          std::unique_ptr<llvm::MemoryBuffer>>
+CompilerInstance::getInputBufferAndModuleDocBufferIfPresent(
+    const InputFile &input) {
+  if (auto b = input.buffer()) {
+    return std::make_pair(llvm::MemoryBuffer::getMemBufferCopy(
+                              b->getBuffer(), b->getBufferIdentifier()),
+                          nullptr);
+  }
+  // FIXME: Working with filenames is fragile, maybe use the real path
+  // or have some kind of FileManager.
+  using FileOrError = llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>;
+  FileOrError inputFileOrErr = llvm::MemoryBuffer::getFileOrSTDIN(input.file());
+  if (!inputFileOrErr) {
+    Diagnostics.diagnose(SourceLoc(), diag::error_open_input_file, input.file(),
+                         inputFileOrErr.getError().message());
+    return std::make_pair(nullptr, nullptr);
+  }
+  if (!serialization::isSerializedAST((*inputFileOrErr)->getBuffer()))
+    return std::make_pair(std::move(*inputFileOrErr), nullptr);
+
+  if (Optional<std::unique_ptr<llvm::MemoryBuffer>> moduleDocBuffer =
+          openModuleDoc(input)) {
+    return std::make_pair(std::move(*inputFileOrErr),
+                          std::move(*moduleDocBuffer));
+  }
+  return std::make_pair(nullptr, nullptr);
+}
+
+Optional<std::unique_ptr<llvm::MemoryBuffer>>
+CompilerInstance::openModuleDoc(const InputFile &input) {
+  llvm::SmallString<128> moduleDocFilePath(input.file());
+  llvm::sys::path::replace_extension(moduleDocFilePath,
+                                     SERIALIZED_MODULE_DOC_EXTENSION);
+  using FileOrError = llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>;
+  FileOrError moduleDocFileOrErr =
+      llvm::MemoryBuffer::getFileOrSTDIN(moduleDocFilePath);
+  if (moduleDocFileOrErr)
+    return std::move(*moduleDocFileOrErr);
+
+  if (moduleDocFileOrErr.getError() == std::errc::no_such_file_or_directory)
+    return std::unique_ptr<llvm::MemoryBuffer>();
+
+  Diagnostics.diagnose(SourceLoc(), diag::error_open_input_file,
+                       moduleDocFilePath,
+                       moduleDocFileOrErr.getError().message());
+  return None;
+}
+
 ModuleDecl *CompilerInstance::getMainModule() {
   if (!MainModule) {
     Identifier ID = Context->getIdentifier(Invocation.getModuleName());
@@ -390,13 +485,10 @@
   }
 }
 
-void CompilerInstance::createREPLFile(
-    const ImplicitImports &implicitImports) const {
-  auto *singleInputFile = new (*Context) SourceFile(
-      *MainModule, Invocation.getSourceFileKind(), None, implicitImports.kind,
-      Invocation.getLangOptions().KeepSyntaxInfoInSourceFile);
-  MainModule->addFile(*singleInputFile);
-  addAdditionalInitialImportsTo(singleInputFile, implicitImports);
+void CompilerInstance::createREPLFile(const ImplicitImports &implicitImports) {
+  auto *SingleInputFile = createSourceFileForMainModule(
+      Invocation.getSourceFileKind(), implicitImports.kind, None);
+  addAdditionalInitialImportsTo(SingleInputFile, implicitImports);
 }
 
 std::unique_ptr<DelayedParsingCallbacks>
@@ -417,14 +509,9 @@
   if (Kind == InputFileKind::IFK_Swift)
     SourceMgr.setHashbangBufferID(MainBufferID);
 
-  auto *MainFile = new (*Context) SourceFile(
-      *MainModule, Invocation.getSourceFileKind(), MainBufferID,
-      implicitImports.kind, Invocation.getLangOptions().KeepSyntaxInfoInSourceFile);
-  MainModule->addFile(*MainFile);
+  auto *MainFile = createSourceFileForMainModule(
+      Invocation.getSourceFileKind(), implicitImports.kind, MainBufferID);
   addAdditionalInitialImportsTo(MainFile, implicitImports);
-
-  if (MainBufferID == PrimaryBufferID)
-    setPrimarySourceFile(MainFile);
 }
 
 void CompilerInstance::parseAndCheckTypes(
@@ -495,15 +582,12 @@
     DelayedParsingCallbacks *SecondaryDelayedCB) {
   SharedTimer timer("performSema-parseLibraryFile");
 
-  auto *NextInput = new (*Context) SourceFile(
-      *MainModule, SourceFileKind::Library, BufferID, implicitImports.kind,
-      Invocation.getLangOptions().KeepSyntaxInfoInSourceFile);
-  MainModule->addFile(*NextInput);
+  auto *NextInput = createSourceFileForMainModule(
+      SourceFileKind::Library, implicitImports.kind, BufferID);
   addAdditionalInitialImportsTo(NextInput, implicitImports);
 
   auto *DelayedCB = SecondaryDelayedCB;
   if (BufferID == PrimaryBufferID) {
-    setPrimarySourceFile(NextInput);
     DelayedCB = PrimaryDelayedCB;
   }
   if (isWholeModuleCompilation())
@@ -629,8 +713,8 @@
 static void
 forEachSourceFileIn(ModuleDecl *module,
                     llvm::function_ref<void(SourceFile &)> fn) {
-  for (auto file : module->getFiles()) {
-    if (auto SF = dyn_cast<SourceFile>(file))
+  for (auto fileName : module->getFiles()) {
+    if (auto SF = dyn_cast<SourceFile>(fileName))
       fn(*SF);
   }
 }
@@ -651,35 +735,41 @@
       performWholeModuleTypeChecking(SF);
     });
   }
-  forEachFileToTypeCheck([&](SourceFile &SF) { finishTypeCheckingFile(SF); });
+}
+
+SourceFile *CompilerInstance::createSourceFileForMainModule(
+    SourceFileKind fileKind, SourceFile::ImplicitModuleImportKind importKind,
+    Optional<unsigned> bufferID) {
+  ModuleDecl *mainModule = getMainModule();
+  bool keepSyntaxInfo = Invocation.getLangOptions().KeepSyntaxInfoInSourceFile;
+  SourceFile *inputFile = new (*Context)
+      SourceFile(*mainModule, fileKind, bufferID, importKind, keepSyntaxInfo);
+  MainModule->addFile(*inputFile);
+
+  if (bufferID && *bufferID == PrimaryBufferID)
+    setPrimarySourceFile(inputFile);
+
+  return inputFile;
 }
 
 void CompilerInstance::performParseOnly(bool EvaluateConditionals) {
   const InputFileKind Kind = Invocation.getInputKind();
-  ModuleDecl *MainModule = getMainModule();
+  ModuleDecl *const MainModule = getMainModule();
   Context->LoadedModules[MainModule->getName()] = MainModule;
-  bool KeepSyntaxInfo = Invocation.getLangOptions().KeepSyntaxInfoInSourceFile;
 
   assert((Kind == InputFileKind::IFK_Swift ||
           Kind == InputFileKind::IFK_Swift_Library) &&
          "only supports parsing .swift files");
   (void)Kind;
 
-  auto implicitModuleImportKind = SourceFile::ImplicitModuleImportKind::None;
-
   // Make sure the main file is the first file in the module but parse it last,
   // to match the parsing logic used when performing Sema.
   if (MainBufferID != NO_SUCH_BUFFER) {
     assert(Kind == InputFileKind::IFK_Swift);
     SourceMgr.setHashbangBufferID(MainBufferID);
-
-    auto *MainFile = new (*Context)
-        SourceFile(*MainModule, Invocation.getSourceFileKind(), MainBufferID,
-                   implicitModuleImportKind, KeepSyntaxInfo);
-    MainModule->addFile(*MainFile);
-
-    if (MainBufferID == PrimaryBufferID)
-      setPrimarySourceFile(MainFile);
+    createSourceFileForMainModule(Invocation.getSourceFileKind(),
+                                  SourceFile::ImplicitModuleImportKind::None,
+                                  MainBufferID);
   }
 
   PersistentParserState PersistentState;
@@ -689,12 +779,9 @@
     if (BufferID == MainBufferID)
       continue;
 
-    auto *NextInput = new (*Context)
-        SourceFile(*MainModule, SourceFileKind::Library, BufferID,
-                   implicitModuleImportKind, KeepSyntaxInfo);
-    MainModule->addFile(*NextInput);
-    if (BufferID == PrimaryBufferID)
-      setPrimarySourceFile(NextInput);
+    SourceFile *NextInput = createSourceFileForMainModule(
+        SourceFileKind::Library, SourceFile::ImplicitModuleImportKind::None,
+        BufferID);
 
     bool Done;
     do {
@@ -729,64 +816,3 @@
   PrimarySourceFile = nullptr;
 }
 
-bool CompilerInstance::setUpForFileAt(unsigned i) {
-  bool MainMode = (Invocation.getInputKind() == InputFileKind::IFK_Swift);
-  bool SILMode = (Invocation.getInputKind() == InputFileKind::IFK_SIL);
-
-  auto &File = Invocation.getFrontendOptions().Inputs.getInputFilenames()[i];
-
-  // FIXME: Working with filenames is fragile, maybe use the real path
-  // or have some kind of FileManager.
-  using namespace llvm::sys::path;
-  if (Optional<unsigned> ExistingBufferID =
-          SourceMgr.getIDForBufferIdentifier(File)) {
-    if (SILMode || (MainMode && filename(File) == "main.swift"))
-      MainBufferID = ExistingBufferID.getValue();
-
-    if (Invocation.getFrontendOptions().Inputs.isInputPrimary(i))
-      PrimaryBufferID = ExistingBufferID.getValue();
-
-    return false; // replaced by a memory buffer.
-  }
-
-  // Open the input file.
-  using FileOrError = llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>;
-  FileOrError InputFileOrErr = llvm::MemoryBuffer::getFileOrSTDIN(File);
-  if (!InputFileOrErr) {
-    Diagnostics.diagnose(SourceLoc(), diag::error_open_input_file, File,
-                         InputFileOrErr.getError().message());
-    return true;
-  }
-
-  if (serialization::isSerializedAST(InputFileOrErr.get()->getBuffer())) {
-    llvm::SmallString<128> ModuleDocFilePath(File);
-    llvm::sys::path::replace_extension(ModuleDocFilePath,
-                                       SERIALIZED_MODULE_DOC_EXTENSION);
-    FileOrError ModuleDocOrErr =
-        llvm::MemoryBuffer::getFileOrSTDIN(ModuleDocFilePath.str());
-    if (!ModuleDocOrErr &&
-        ModuleDocOrErr.getError() != std::errc::no_such_file_or_directory) {
-      Diagnostics.diagnose(SourceLoc(), diag::error_open_input_file, File,
-                           ModuleDocOrErr.getError().message());
-      return true;
-    }
-    PartialModules.push_back(
-        {std::move(InputFileOrErr.get()),
-         ModuleDocOrErr ? std::move(ModuleDocOrErr.get()) : nullptr});
-    return false;
-  }
-
-  // Transfer ownership of the MemoryBuffer to the SourceMgr.
-  unsigned BufferID =
-      SourceMgr.addNewSourceBuffer(std::move(InputFileOrErr.get()));
-
-  InputSourceCodeBufferIDs.push_back(BufferID);
-
-  if (SILMode || (MainMode && filename(File) == "main.swift"))
-    MainBufferID = BufferID;
-
-  if (Invocation.getFrontendOptions().Inputs.isInputPrimary(i))
-    PrimaryBufferID = BufferID;
-
-  return false;
-}
diff --git a/lib/Frontend/FrontendOptions.cpp b/lib/Frontend/FrontendOptions.cpp
index 24ffd12..3c373ad 100644
--- a/lib/Frontend/FrontendOptions.cpp
+++ b/lib/Frontend/FrontendOptions.cpp
@@ -28,7 +28,7 @@
 using namespace llvm::opt;
 
 bool FrontendInputs::shouldTreatAsLLVM() const {
-  if (hasUniqueInputFilename()) {
+  if (hasSingleInput()) {
     StringRef Input(getFilenameOfFirstInput());
     return llvm::sys::path::extension(Input).endswith(LLVM_BC_EXTENSION) ||
            llvm::sys::path::extension(Input).endswith(LLVM_IR_EXTENSION);
@@ -37,7 +37,7 @@
 }
 
 bool FrontendInputs::shouldTreatAsSIL() const {
-  if (hasUniqueInputFilename()) {
+  if (hasSingleInput()) {
     // If we have exactly one input filename, and its extension is "sil",
     // treat the input as SIL.
     StringRef Input(getFilenameOfFirstInput());
@@ -45,55 +45,66 @@
   }
   // If we have one primary input and it's a filename with extension "sil",
   // treat the input as SIL.
-  if (const Optional<StringRef> filename =
-          getOptionalUniquePrimaryInputFilename()) {
-    return llvm::sys::path::extension(filename.getValue())
-        .endswith(SIL_EXTENSION);
+  unsigned silPrimaryCount = numberOfPrimaryInputsEndingWith(SIL_EXTENSION);
+  if (silPrimaryCount == 0)
+    return false;
+  if (silPrimaryCount == primaryInputCount()) {
+    // Not clear what to do someday with multiple primaries
+    assertMustNotBeMoreThanOnePrimaryInput();
+    return true;
   }
-  return false;
+  llvm_unreachable("Either all primaries or none must end with .sil");
+}
+
+unsigned
+FrontendInputs::numberOfPrimaryInputsEndingWith(const char *extension) const {
+  return count_if(
+      PrimaryInputs, [&](const llvm::StringMapEntry<unsigned> &elem) -> bool {
+        StringRef filename = AllFiles[elem.second].file();
+        return llvm::sys::path::extension(filename).endswith(extension);
+      });
 }
 
 bool FrontendInputs::verifyInputs(DiagnosticEngine &diags, bool treatAsSIL,
                                   bool isREPLRequested,
                                   bool isNoneRequested) const {
   if (isREPLRequested) {
-    if (hasInputFilenames()) {
+    if (hasInputs()) {
       diags.diagnose(SourceLoc(), diag::error_repl_requires_no_input_files);
       return true;
     }
-  } else if (treatAsSIL && hasPrimaryInputs()) {
-    // If we have the SIL as our primary input, we can waive the one file
-    // requirement as long as all the other inputs are SIBs.
-    for (unsigned i = 0, e = inputFilenameCount(); i != e; ++i) {
-      if (i == getOptionalUniquePrimaryInput()->Index)
-        continue;
-
-      StringRef file(getInputFilenames()[i]);
-      if (!llvm::sys::path::extension(file).endswith(SIB_EXTENSION)) {
+  } else if (treatAsSIL) {
+    if (isWholeModule()) {
+      if (inputCount() != 1) {
+        diags.diagnose(SourceLoc(), diag::error_mode_requires_one_input_file);
+        return true;
+      }
+    } else {
+      assertMustNotBeMoreThanOnePrimaryInput();
+      // If we have the SIL as our primary input, we can waive the one file
+      // requirement as long as all the other inputs are SIBs.
+      if (!areAllNonPrimariesSIB()) {
         diags.diagnose(SourceLoc(),
                        diag::error_mode_requires_one_sil_multi_sib);
         return true;
       }
     }
-  } else if (treatAsSIL) {
-    if (!hasUniqueInputFilename()) {
-      diags.diagnose(SourceLoc(), diag::error_mode_requires_one_input_file);
-      return true;
-    }
-  } else if (!isNoneRequested) {
-    if (!hasInputFilenames()) {
-      diags.diagnose(SourceLoc(), diag::error_mode_requires_an_input_file);
-      return true;
-    }
+  } else if (!isNoneRequested && !hasInputs()) {
+    diags.diagnose(SourceLoc(), diag::error_mode_requires_an_input_file);
+    return true;
   }
   return false;
 }
 
-void FrontendInputs::transformInputFilenames(
-    const llvm::function_ref<std::string(std::string)> &fn) {
-  for (auto &InputFile : InputFilenames) {
-    InputFile = fn(InputFile);
+bool FrontendInputs::areAllNonPrimariesSIB() const {
+  for (const InputFile &input : getAllFiles()) {
+    if (input.isPrimary())
+      continue;
+    if (!llvm::sys::path::extension(input.file()).endswith(SIB_EXTENSION)) {
+      return false;
+    }
   }
+  return true;
 }
 
 bool FrontendOptions::needsProperModuleName(ActionType action) {
@@ -188,11 +199,12 @@
     // Put the serialized diagnostics file next to the output file.
     return getSingleOutputFilename();
 
-  StringRef fn = Inputs.primaryInputFilenameIfAny();
   // If we have a primary input, so use that as the basis for the name of the
   // serialized diagnostics file, otherwise fall back on the
   // module name.
-  return !fn.empty() ? llvm::sys::path::filename(fn) : StringRef(ModuleName);
+  const auto input = Inputs.getUniquePrimaryInput();
+  return input ? llvm::sys::path::filename(input->file())
+               : StringRef(ModuleName);
 }
 
 bool FrontendOptions::isOutputFileDirectory() const {
diff --git a/lib/FrontendTool/FrontendTool.cpp b/lib/FrontendTool/FrontendTool.cpp
index aa034a2..5946bae 100644
--- a/lib/FrontendTool/FrontendTool.cpp
+++ b/lib/FrontendTool/FrontendTool.cpp
@@ -391,9 +391,13 @@
 // This is a separate function so that it shows up in stack traces.
 LLVM_ATTRIBUTE_NOINLINE
 static void debugFailWithAssertion() {
-  // This assertion should always fail, per the user's request, and should
-  // not be converted to llvm_unreachable.
-  assert(0 && "This is an assertion!");
+  // Per the user's request, this assertion should always fail in
+  // builds with assertions enabled.
+
+  // This should not be converted to llvm_unreachable, as those are
+  // treated as optimization hints in builds where they turn into
+  // __builtin_unreachable().
+  assert((0) && "This is an assertion!");
 }
 
 // This is a separate function so that it shows up in stack traces.
@@ -541,7 +545,7 @@
     auto &LLVMContext = getGlobalLLVMContext();
 
     // Load in bitcode file.
-    assert(Invocation.getFrontendOptions().Inputs.hasUniqueInputFilename() &&
+    assert(Invocation.getFrontendOptions().Inputs.hasSingleInput() &&
            "We expect a single input for bitcode input!");
     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
         llvm::MemoryBuffer::getFileOrSTDIN(
@@ -753,12 +757,11 @@
 
   const auto &SILOpts = Invocation.getSILOptions();
   if (!opts.TBDPath.empty()) {
-    auto hasMultipleIRGenThreads = SILOpts.NumThreads > 1;
     auto installName = opts.TBDInstallName.empty()
                            ? "lib" + Invocation.getModuleName().str() + ".dylib"
                            : opts.TBDInstallName;
 
-    if (writeTBD(Instance.getMainModule(), hasMultipleIRGenThreads,
+    if (writeTBD(Instance.getMainModule(), SILOpts.hasMultipleIGMs(),
                  opts.TBDPath, installName))
       return true;
   }
@@ -776,11 +779,20 @@
       auto SASTF = dyn_cast<SerializedASTFile>(File);
       return SASTF && SASTF->isSIB();
     };
-    if (opts.Inputs.hasAPrimaryInputFile()) {
+    if (opts.Inputs.hasPrimaryInputs()) {
       FileUnit *PrimaryFile = PrimarySourceFile;
       if (!PrimaryFile) {
-        auto Index = opts.Inputs.getRequiredUniquePrimaryInput().Index;
-        PrimaryFile = Instance.getMainModule()->getFiles()[Index];
+        for (FileUnit *fileUnit : Instance.getMainModule()->getFiles()) {
+          if (auto SASTF = dyn_cast<SerializedASTFile>(fileUnit)) {
+            if (Invocation.getFrontendOptions().Inputs.isFilePrimary(
+                    InputFile::
+                        convertBufferNameFromLLVM_getFileOrSTDIN_toSwiftConventions(
+                            SASTF->getFilename()))) {
+              assert(!PrimaryFile && "Can only handle one primary so far");
+              PrimaryFile = fileUnit;
+            }
+          }
+        }
       }
       astGuaranteedToCorrespondToSIL = !fileIsSIB(PrimaryFile);
       SM = performSILGeneration(*PrimaryFile, Invocation.getSILOptions(),
@@ -1069,14 +1081,13 @@
       break;
 
     const auto &SILOpts = Invocation.getSILOptions();
-    auto hasMultipleIRGenThreads = SILOpts.NumThreads > 1;
+    const auto hasMultipleIGMs = SILOpts.hasMultipleIGMs();
     bool error;
     if (PrimarySourceFile)
-      error = validateTBD(PrimarySourceFile, *IRModule, hasMultipleIRGenThreads,
+      error = validateTBD(PrimarySourceFile, *IRModule, hasMultipleIGMs,
                           allSymbols);
     else
-      error = validateTBD(Instance.getMainModule(), *IRModule,
-                          hasMultipleIRGenThreads,
+      error = validateTBD(Instance.getMainModule(), *IRModule, hasMultipleIGMs,
                           allSymbols);
     if (error)
       return true;
@@ -1372,7 +1383,7 @@
     auto &FEOpts = Invocation.getFrontendOptions();
     auto &LangOpts = Invocation.getLangOptions();
     auto &SILOpts = Invocation.getSILOptions();
-    StringRef InputName = FEOpts.Inputs.primaryInputFilenameIfAny();
+    StringRef InputName = FEOpts.Inputs.getNameOfUniquePrimaryInputFile();
     StringRef OptType = silOptModeArgStr(SILOpts.OptMode);
     StringRef OutFile = FEOpts.getSingleOutputFilename();
     StringRef OutputType = llvm::sys::path::extension(OutFile);
diff --git a/lib/FrontendTool/TBD.cpp b/lib/FrontendTool/TBD.cpp
index 3cb84d6..2c93389 100644
--- a/lib/FrontendTool/TBD.cpp
+++ b/lib/FrontendTool/TBD.cpp
@@ -38,9 +38,8 @@
   return sorted;
 }
 
-bool swift::writeTBD(ModuleDecl *M, bool hasMultipleIRGenThreads,
-                     StringRef OutputFilename,
-                     StringRef installName) {
+bool swift::writeTBD(ModuleDecl *M, bool hasMultipleIGMs,
+                     StringRef OutputFilename, StringRef installName) {
   std::error_code EC;
   llvm::raw_fd_ostream OS(OutputFilename, EC, llvm::sys::fs::F_None);
   if (EC) {
@@ -49,7 +48,7 @@
     return true;
   }
 
-  writeTBDFile(M, OS, hasMultipleIRGenThreads, installName);
+  writeTBDFile(M, OS, hasMultipleIGMs, installName);
 
   return false;
 }
@@ -118,20 +117,18 @@
 }
 
 bool swift::validateTBD(ModuleDecl *M, llvm::Module &IRModule,
-                        bool hasMultipleIRGenThreads,
-                        bool diagnoseExtraSymbolsInTBD) {
+                        bool hasMultipleIGMs, bool diagnoseExtraSymbolsInTBD) {
   llvm::StringSet<> symbols;
-  enumeratePublicSymbols(M, symbols, hasMultipleIRGenThreads);
+  enumeratePublicSymbols(M, symbols, hasMultipleIGMs);
 
   return validateSymbolSet(M->getASTContext().Diags, symbols, IRModule,
                            diagnoseExtraSymbolsInTBD);
 }
 
 bool swift::validateTBD(FileUnit *file, llvm::Module &IRModule,
-                        bool hasMultipleIRGenThreads,
-                        bool diagnoseExtraSymbolsInTBD) {
+                        bool hasMultipleIGMs, bool diagnoseExtraSymbolsInTBD) {
   llvm::StringSet<> symbols;
-  enumeratePublicSymbols(file, symbols, hasMultipleIRGenThreads);
+  enumeratePublicSymbols(file, symbols, hasMultipleIGMs);
 
   return validateSymbolSet(file->getParentModule()->getASTContext().Diags,
                            symbols, IRModule, diagnoseExtraSymbolsInTBD);
diff --git a/lib/FrontendTool/TBD.h b/lib/FrontendTool/TBD.h
index 5d73578..446618a 100644
--- a/lib/FrontendTool/TBD.h
+++ b/lib/FrontendTool/TBD.h
@@ -24,15 +24,12 @@
 class FileUnit;
 class FrontendOptions;
 
-bool writeTBD(ModuleDecl *M, bool hasMultipleIRGenThreads,
-              llvm::StringRef OutputFilename,
-              llvm::StringRef installName);
+bool writeTBD(ModuleDecl *M, bool hasMultipleIGMs,
+              llvm::StringRef OutputFilename, llvm::StringRef installName);
 bool inputFileKindCanHaveTBDValidated(InputFileKind kind);
-bool validateTBD(ModuleDecl *M, llvm::Module &IRModule,
-                 bool hasMultipleIRGenThreads,
+bool validateTBD(ModuleDecl *M, llvm::Module &IRModule, bool hasMultipleIGMs,
                  bool diagnoseExtraSymbolsInTBD);
-bool validateTBD(FileUnit *M, llvm::Module &IRModule,
-                 bool hasMultipleIRGenThreads,
+bool validateTBD(FileUnit *M, llvm::Module &IRModule, bool hasMultipleIGMs,
                  bool diagnoseExtraSymbolsInTBD);
 }
 
diff --git a/lib/IDE/CodeCompletion.cpp b/lib/IDE/CodeCompletion.cpp
index 09e813d..e20b9c0 100644
--- a/lib/IDE/CodeCompletion.cpp
+++ b/lib/IDE/CodeCompletion.cpp
@@ -399,8 +399,8 @@
   const_cast<AbstractFunctionDecl *>(AFD)->walk(Finder);
   return Finder.getFoundStmt();
 }
-
-/// Erase any ErrorType types on the given expression, allowing later
+/// Prepare the given expression for type-checking again, prinicipally by
+/// erasing any ErrorType types on the given expression, allowing later
 /// type-checking to make progress.
 ///
 /// FIXME: this is fundamentally a workaround for the fact that we may end up
@@ -408,12 +408,15 @@
 /// the context, and later for checking more-specific things like unresolved
 /// members.  We should restructure code-completion type-checking so that we
 /// never typecheck more than once (or find a more principled way to do it).
-static void eraseErrorTypes(Expr *E) {
+static void prepareForRetypechecking(Expr *E) {
   assert(E);
   struct Eraser : public ASTWalker {
     std::pair<bool, Expr *> walkToExprPre(Expr *expr) override {
       if (expr && expr->getType() && expr->getType()->hasError())
         expr->setType(Type());
+      if (auto *ACE = dyn_cast_or_null<AutoClosureExpr>(expr)) {
+        return { true, ACE->getSingleExpressionBody() };
+      }
       return { true, expr };
     }
     bool walkToTypeLocPre(TypeLoc &TL) override {
@@ -1294,7 +1297,6 @@
   int AttrParamIndex;
   bool IsInSil;
   bool HasSpace = false;
-  bool HasRParen = false;
   bool ShouldCompleteCallPatternAfterParen = true;
   bool PreferFunctionReferencesToCalls = false;
   Optional<DeclKind> AttTargetDK;
@@ -1389,7 +1391,7 @@
       return std::make_pair(ParsedExpr->getType(),
                             ParsedExpr->getReferencedDecl());
 
-    eraseErrorTypes(ParsedExpr);
+    prepareForRetypechecking(ParsedExpr);
 
     ConcreteDeclRef ReferencedDecl = nullptr;
     Expr *ModifiedExpr = ParsedExpr;
@@ -1592,7 +1594,6 @@
   unsigned NumBytesToEraseForOptionalUnwrap = 0;
 
   bool HaveLParen = false;
-  bool HaveRParen = false;
   bool IsSuperRefExpr = false;
   bool IsSelfRefExpr = false;
   bool IsKeyPathExpr = false;
@@ -1747,10 +1748,6 @@
     HaveLParen = Value;
   }
 
-  void setHaveRParen(bool Value) {
-    HaveRParen = Value;
-  }
-
   void setIsSuperRefExpr() {
     IsSuperRefExpr = true;
   }
@@ -2344,9 +2341,12 @@
 
     // Add the pattern, possibly including any default arguments.
     auto addPattern = [&](bool includeDefaultArgs = true) {
+      // FIXME: to get the corect semantic context we need to know how lookup
+      // would have found the declaration AFD. For now, just choose a reasonable
+      // default, it's most likely to be CurrentModule or CurrentNominal.
       CodeCompletionResultBuilder Builder(
           Sink, CodeCompletionResult::ResultKind::Pattern,
-          SemanticContextKind::ExpressionSpecific, ExpectedTypes);
+          SemanticContextKind::CurrentModule, ExpectedTypes);
       if (!HaveLParen)
         Builder.addLeftParen();
       else
@@ -2354,13 +2354,14 @@
 
       bool anyParam = addParamPatternFromFunction(Builder, AFT, AFD, includeDefaultArgs);
 
-      if (HaveLParen && HaveRParen && !anyParam) {
+      if (HaveLParen && !anyParam) {
         // Empty result, don't add it.
         Builder.cancel();
         return;
       }
 
-      if (!HaveRParen)
+      // The rparen matches the lparen here so that we insert both or neither.
+      if (!HaveLParen)
         Builder.addRightParen();
       else
         Builder.addAnnotatedRightParen();
@@ -2562,13 +2563,14 @@
       bool anyParam = addParamPatternFromFunction(Builder, ConstructorType, CD,
                                   includeDefaultArgs);
 
-      if (HaveLParen && HaveRParen && !anyParam) {
+      if (HaveLParen && !anyParam) {
         // Empty result, don't add it.
         Builder.cancel();
         return;
       }
 
-      if (!HaveRParen)
+      // The rparen matches the lparen here so that we insert both or neither.
+      if (!HaveLParen)
         Builder.addRightParen();
       else
         Builder.addAnnotatedRightParen();
@@ -3336,7 +3338,7 @@
       // Reset sequence.
       SE->setElement(SE->getNumElements() - 1, nullptr);
       SE->setElement(SE->getNumElements() - 2, nullptr);
-      eraseErrorTypes(SE);
+      prepareForRetypechecking(SE);
 
       // Reset any references to operators in types, so they are properly
       // handled as operators by sequence folding.
@@ -3395,7 +3397,7 @@
   void typeCheckLeadingSequence(SmallVectorImpl<Expr *> &sequence) {
     Expr *expr =
         SequenceExpr::create(CurrDeclContext->getASTContext(), sequence);
-    eraseErrorTypes(expr);
+    prepareForRetypechecking(expr);
     // Take advantage of the fact the type-checker leaves the types on the AST.
     if (!typeCheckExpression(const_cast<DeclContext *>(CurrDeclContext),
                              expr)) {
@@ -3433,7 +3435,7 @@
     sequence.push_back(nullptr); // operator
     sequence.push_back(nullptr); // RHS
     auto *SE = SequenceExpr::create(CurrDeclContext->getASTContext(), sequence);
-    eraseErrorTypes(SE);
+    prepareForRetypechecking(SE);
 
     for (auto op : operators) {
       switch (op->getKind()) {
@@ -4491,18 +4493,16 @@
   CurDeclContext = P.CurDeclContext;
   CodeCompleteTokenExpr = static_cast<CodeCompletionExpr*>(CodeCompletionE);
 
-  // Lookahead one token to decide what kind of call completions to provide.
-  // When it appears that there is already code for the call present, just
-  // complete values and/or argument labels.  Otherwise give the entire call
-  // pattern.
-  Token next = P.peekToken();
-  if (next.isAtStartOfLine() || next.is(tok::eof)) {
-    ShouldCompleteCallPatternAfterParen = true;
-  } else if (next.is(tok::r_paren)) {
-    HasRParen = true;
-    ShouldCompleteCallPatternAfterParen = true;
-  } else {
-    ShouldCompleteCallPatternAfterParen = false;
+  ShouldCompleteCallPatternAfterParen = true;
+  if (Context.LangOpts.CodeCompleteCallPatternHeuristics) {
+    // Lookahead one token to decide what kind of call completions to provide.
+    // When it appears that there is already code for the call present, just
+    // complete values and/or argument labels.  Otherwise give the entire call
+    // pattern.
+    Token next = P.peekToken();
+    if (!next.isAtStartOfLine() && !next.is(tok::eof) && !next.is(tok::r_paren)) {
+      ShouldCompleteCallPatternAfterParen = false;
+    }
   }
 }
 
@@ -5223,7 +5223,6 @@
 
     if (ExprType) {
       if (ShouldCompleteCallPatternAfterParen) {
-        Lookup.setHaveRParen(HasRParen);
         Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl());
       } else {
         // Add argument labels, then fallthrough to get values.
@@ -5341,7 +5340,7 @@
     CurDeclContext->walkContext(Walker);
     bool Success = false;
     if (auto PE = Walker.ParentFarthest.get<Expr *>()) {
-      eraseErrorTypes(PE);
+      prepareForRetypechecking(PE);
       Success = typeCheckUnresolvedExpr(*CurDeclContext, UnresolvedExpr, PE,
                                         PossibleTypes);
       Lookup.getUnresolvedMemberCompletions(PossibleTypes);
diff --git a/lib/IDE/Refactoring.cpp b/lib/IDE/Refactoring.cpp
index 0c31ecc..bc794c7 100644
--- a/lib/IDE/Refactoring.cpp
+++ b/lib/IDE/Refactoring.cpp
@@ -1051,9 +1051,9 @@
   auto InputBuffer = llvm::MemoryBuffer::getMemBufferCopy(SourceText,"<extract>");
 
   CompilerInvocation Invocation{};
-  Invocation.addInputBuffer(InputBuffer.get());
-  Invocation.getFrontendOptions().Inputs.setPrimaryInput(
-      {0, SelectedInput::InputKind::Buffer});
+
+  Invocation.getFrontendOptions().Inputs.addInput(
+      InputFile("<extract>", true, InputBuffer.get()));
   Invocation.getFrontendOptions().ModuleName = "extract";
 
   auto Instance = llvm::make_unique<swift::CompilerInstance>();
diff --git a/lib/IDE/SwiftSourceDocInfo.cpp b/lib/IDE/SwiftSourceDocInfo.cpp
index 1ba8af9..fdce021 100644
--- a/lib/IDE/SwiftSourceDocInfo.cpp
+++ b/lib/IDE/SwiftSourceDocInfo.cpp
@@ -319,6 +319,11 @@
     }
   }
 
+  // FIXME: Even implicit Decls should have proper ranges if they include any
+  // non-implicit children (fix implicit Decls created for lazy vars).
+  if (D->isImplicit())
+    return !isDone();
+
   if (shouldSkip(D->getSourceRange()))
     return false;
   
diff --git a/lib/IDE/TypeReconstruction.cpp b/lib/IDE/TypeReconstruction.cpp
index d8eb873..e789b6b 100644
--- a/lib/IDE/TypeReconstruction.cpp
+++ b/lib/IDE/TypeReconstruction.cpp
@@ -50,6 +50,13 @@
   return std::string(formatted.get());
 }
 
+static bool
+CompareFunctionTypes(const AnyFunctionType *f, const AnyFunctionType *g,
+                     Optional<std::vector<StringRef>> fLabels = None,
+                     Optional<std::vector<StringRef>> gLabels = None,
+                     bool *input_matches = nullptr,
+                     bool *output_matches = nullptr);
+
 class DeclsLookupSource {
 public:
   typedef SmallVectorImpl<ValueDecl *> ValueDecls;
@@ -799,6 +806,7 @@
     Demangle::NodePointer cur_node, VisitNodeResult &result) {
   VisitNodeResult kind_type_result;
   VisitNodeResult type_result;
+  std::vector<StringRef> labels;
 
   Demangle::Node::iterator end = cur_node->end();
   for (Demangle::Node::iterator pos = cur_node->begin(); pos != end; ++pos) {
@@ -809,6 +817,16 @@
     case Demangle::Node::Kind::Structure:
       VisitNode(ast, *pos, kind_type_result);
       break;
+    case Demangle::Node::Kind::LabelList: {
+      for (const auto &label : **pos) {
+        if (label->getKind() == Demangle::Node::Kind::FirstElementMarker)
+          labels.push_back(StringRef());
+        else {
+          labels.push_back(label->getText());
+        }
+      }
+      break;
+    }
     case Demangle::Node::Kind::Type:
       VisitNode(ast, *pos, type_result);
       break;
@@ -850,10 +868,8 @@
 
             const AnyFunctionType *type_func =
                 type_result._types.front()->getAs<AnyFunctionType>();
-            if (identifier_func->getResult()->isEqual(
-                    type_func->getResult()) &&
-                identifier_func->getInput()->isEqual(
-                    type_func->getInput())) {
+
+            if (CompareFunctionTypes(type_func, identifier_func, labels)) {
               result._module = kind_type_result._module;
               result._decls.push_back(kind_type_result._decls[i]);
               result._types.push_back(
@@ -1081,26 +1097,43 @@
 
 static bool CompareFunctionTypes(const AnyFunctionType *f,
                                  const AnyFunctionType *g,
-                                 bool *input_matches = nullptr,
-                                 bool *output_matches = nullptr) {
-  bool in_matches = false, out_matches = false;
+                                 Optional<std::vector<StringRef>> fLabels,
+                                 Optional<std::vector<StringRef>> gLabels,
+                                 bool *input_matches, bool *output_matches) {
   if (nullptr == f)
     return (nullptr == g);
   if (nullptr == g)
     return false;
 
-  auto f_input = f->getInput();
-  auto g_input = g->getInput();
+  auto getLabel = [&](Optional<std::vector<StringRef>> labels,
+                      AnyFunctionType::Param &param,
+                      unsigned index) -> StringRef {
+    return (labels && labels->size() > index) ? (*labels)[index]
+                                              : param.getLabel().str();
+  };
 
-  auto f_output = f->getResult();
-  auto g_output = g->getResult();
+  auto params1 = f->getParams();
+  auto params2 = g->getParams();
 
-  if (f_input->isEqual(g_input)) {
-    in_matches = true;
-    if (f_output->isEqual(g_output))
-      out_matches = true;
+  bool in_matches = params1.size() == params2.size(), out_matches = true;
+  auto numParams = std::min(params2.size(), params1.size());
+
+  for (unsigned i = 0; i != numParams; ++i) {
+    auto param1 = params1[i];
+    auto param2 = params2[i];
+
+    auto label1 = getLabel(fLabels, param1, i);
+    auto label2 = getLabel(gLabels, param2, i);
+
+    if (label1.equals(label2) && param1.getType()->isEqual(param2.getType()))
+      continue;
+
+    in_matches = false;
+    break;
   }
 
+  out_matches = f->getResult()->isEqual(g->getResult());
+
   if (input_matches)
     *input_matches = in_matches;
   if (output_matches)
@@ -1116,6 +1149,8 @@
   VisitNodeResult identifier_result;
   VisitNodeResult type_result;
   VisitNodeResult decl_scope_result;
+  std::vector<StringRef> labels;
+
   Demangle::Node::iterator end = cur_node->end();
   bool found_univocous = false;
   for (Demangle::Node::iterator pos = cur_node->begin(); pos != end; ++pos) {
@@ -1141,6 +1176,17 @@
       VisitNode(ast, *pos, decl_scope_result);
       break;
 
+    case Demangle::Node::Kind::LabelList: {
+      for (const auto &label : **pos) {
+        if (label->getKind() == Demangle::Node::Kind::FirstElementMarker)
+          labels.push_back(StringRef());
+        else {
+          labels.push_back(label->getText());
+        }
+      }
+      break;
+    }
+
     case Demangle::Node::Kind::LocalDeclName: {
       if (child->getNumChildren() != 2 || !child->getChild(1)->hasText()) {
         if (result._error.empty())
@@ -1235,7 +1281,7 @@
             identifier_type->getAs<AnyFunctionType>();
         const AnyFunctionType *type_func =
             type_result._types.front()->getAs<AnyFunctionType>();
-        if (CompareFunctionTypes(identifier_func, type_func)) {
+        if (CompareFunctionTypes(type_func, identifier_func, labels)) {
           result._module = identifier_result._module;
           result._decls.push_back(identifier_result._decls[i]);
           result._types.push_back(
diff --git a/lib/IRGen/Address.h b/lib/IRGen/Address.h
index 4877a8a..3f2f3a5 100644
--- a/lib/IRGen/Address.h
+++ b/lib/IRGen/Address.h
@@ -120,6 +120,11 @@
   StackAddress(Address address, llvm::Value *SP)
       : Addr(address), StackPtrResetLocation(SP) {}
 
+  /// Return a StackAddress with the address changed in some superficial way.
+  StackAddress withAddress(Address addr) const {
+    return StackAddress(addr, StackPtrResetLocation);
+  }
+
   llvm::Value *getAddressPointer() const { return Addr.getAddress(); }
   Alignment getAlignment() const { return Addr.getAlignment(); }
   Address getAddress() const { return Addr; }
diff --git a/lib/IRGen/CallEmission.h b/lib/IRGen/CallEmission.h
index 264f6a7..e226061 100644
--- a/lib/IRGen/CallEmission.h
+++ b/lib/IRGen/CallEmission.h
@@ -17,6 +17,7 @@
 #ifndef SWIFT_IRGEN_CALLEMISSION_H
 #define SWIFT_IRGEN_CALLEMISSION_H
 
+#include "Address.h"
 #include "Callee.h"
 
 namespace llvm {
@@ -26,7 +27,6 @@
 namespace swift {
 namespace irgen {
 
-class Address;
 class Explosion;
 class LoadableTypeInfo;
 struct WitnessMetadata;
@@ -36,10 +36,18 @@
 public:
   IRGenFunction &IGF;
 
+  struct TypedTemporary {
+    StackAddress Temp;
+    SILType Type;
+  };
+
 private:
   /// The builtin/special arguments to pass to the call.
   SmallVector<llvm::Value*, 8> Args;
 
+  /// Temporaries required by the call.
+  SmallVector<TypedTemporary, 4> Temporaries;
+
   /// The function we're going to call.
   Callee CurCallee;
 
diff --git a/lib/IRGen/ClassMetadataVisitor.h b/lib/IRGen/ClassMetadataVisitor.h
index c1602c9..1a1df37 100644
--- a/lib/IRGen/ClassMetadataVisitor.h
+++ b/lib/IRGen/ClassMetadataVisitor.h
@@ -45,7 +45,7 @@
   ClassDecl *const Target;
 
   ClassMetadataVisitor(IRGenModule &IGM, ClassDecl *target)
-    : super(IGM), SILVTableVisitor<Impl>(IGM.getSILTypes()), Target(target) {}
+    : super(IGM), Target(target) {}
 
 public:
   void layout() {
@@ -90,21 +90,31 @@
 private:
   /// Add fields associated with the given class and its bases.
   void addClassMembers(ClassDecl *theClass, Type type) {
-    // Add any fields associated with the superclass.
-    // NB: We don't apply superclass substitutions to members because we want
-    // consistent metadata layout between generic superclasses and concrete
-    // subclasses.
+    // Visit the superclass first.
     if (Type superclass = type->getSuperclass()) {
-      ClassDecl *superclassDecl = superclass->getClassOrBoundGenericClass();
-      // Skip superclass fields if superclass is resilient.
-      // FIXME: Needs runtime support to ensure the field offset vector is
-      // populated correctly.
-      if (!IGM.Context.LangOpts.EnableClassResilience ||
-          !IGM.isResilient(superclassDecl, ResilienceExpansion::Maximal)) {
+      auto *superclassDecl = superclass->getClassOrBoundGenericClass();
+      if (IGM.Context.LangOpts.EnableClassResilience &&
+          IGM.isResilient(superclassDecl, ResilienceExpansion::Maximal)) {
+        // Just note that we have a resilient superclass and move on.
+        //
+        // Runtime metadata instantiation needs to slide our entries down
+        // and copy in the superclass metadata.
+        //
+        // Metadata access needs to access our fields relative to a
+        // global variable.
+        asImpl().noteResilientSuperclass();
+      } else {
+        // NB: We don't apply superclass substitutions to members because we want
+        // consistent metadata layout between generic superclasses and concrete
+        // subclasses.
         addClassMembers(superclassDecl, superclass);
       }
     }
 
+    // Note that we have to emit a global variable storing the metadata
+    // start offset, or access remaining fields relative to one.
+    asImpl().noteStartOfImmediateMembers(theClass);
+
     // Add space for the generic parameters, if applicable.
     // Note that we only add references for the immediate parameters;
     // parameters for the parent context are handled by the parent.
diff --git a/lib/IRGen/FixedTypeInfo.h b/lib/IRGen/FixedTypeInfo.h
index 0391ae6..188dcea 100644
--- a/lib/IRGen/FixedTypeInfo.h
+++ b/lib/IRGen/FixedTypeInfo.h
@@ -76,7 +76,7 @@
     return (isFixedSize(expansion) && StorageSize.isZero());
   }
 
-  StackAddress allocateStack(IRGenFunction &IGF, SILType T, bool isEntryBlock,
+  StackAddress allocateStack(IRGenFunction &IGF, SILType T,
                              const llvm::Twine &name) const override;
   void deallocateStack(IRGenFunction &IGF, StackAddress addr, SILType T) const override;
   void destroyStack(IRGenFunction &IGF, StackAddress addr, SILType T,
@@ -226,7 +226,7 @@
   /// Fixed-size types never need dynamic value witness table instantiation.
   void initializeMetadata(IRGenFunction &IGF,
                           llvm::Value *metadata,
-                          llvm::Value *vwtable,
+                          bool isVWTMutable,
                           SILType T) const override {}
 
   void collectArchetypeMetadata(
diff --git a/lib/IRGen/GenBuiltin.cpp b/lib/IRGen/GenBuiltin.cpp
index d34a0a1..0e273ca 100644
--- a/lib/IRGen/GenBuiltin.cpp
+++ b/lib/IRGen/GenBuiltin.cpp
@@ -116,13 +116,10 @@
 }
 
 /// emitBuiltinCall - Emit a call to a builtin function.
-void irgen::emitBuiltinCall(IRGenFunction &IGF, Identifier FnId,
-                            SILType resultType,
+void irgen::emitBuiltinCall(IRGenFunction &IGF, const BuiltinInfo &Builtin,
+                            Identifier FnId, SILType resultType,
                             Explosion &args, Explosion &out,
                             SubstitutionList substitutions) {
-  // Decompose the function's name into a builtin name and type list.
-  const BuiltinInfo &Builtin = IGF.getSILModule().getBuiltinInfo(FnId);
-
   if (Builtin.ID == BuiltinValueKind::UnsafeGuaranteedEnd) {
     // Just consume the incoming argument.
     assert(args.size() == 1 && "Expecting one incoming argument");
diff --git a/lib/IRGen/GenBuiltin.h b/lib/IRGen/GenBuiltin.h
index a351bbe..dee62ed 100644
--- a/lib/IRGen/GenBuiltin.h
+++ b/lib/IRGen/GenBuiltin.h
@@ -22,6 +22,7 @@
 #include "swift/Basic/LLVM.h"
 
 namespace swift {
+  class BuiltinInfo;
   class Identifier;
   class SILType;
 
@@ -30,8 +31,8 @@
   class IRGenFunction;
 
   /// Emit a call to a builtin function.
-  void emitBuiltinCall(IRGenFunction &IGF, Identifier FnId,
-                       SILType resultType,
+  void emitBuiltinCall(IRGenFunction &IGF, const BuiltinInfo &builtin,
+                       Identifier fnId, SILType resultType,
                        Explosion &args, Explosion &result,
                        SubstitutionList substitutions);
 
diff --git a/lib/IRGen/GenCall.cpp b/lib/IRGen/GenCall.cpp
index b8038b1..c260771 100644
--- a/lib/IRGen/GenCall.cpp
+++ b/lib/IRGen/GenCall.cpp
@@ -108,7 +108,7 @@
 
 static llvm::CallingConv::ID getFreestandingConvention(IRGenModule &IGM) {
   // TODO: use a custom CC that returns three scalars efficiently
-  return SWIFT_LLVM_CC(SwiftCC);
+  return IGM.SwiftCC;
 }
 
 /// Expand the requirements of the given abstract calling convention
@@ -146,8 +146,6 @@
 
 void IRGenModule::addSwiftSelfAttributes(llvm::AttributeList &attrs,
                                          unsigned argIndex) {
-  if (!UseSwiftCC)
-    return;
   llvm::AttrBuilder b;
   b.addAttribute(llvm::Attribute::SwiftSelf);
   attrs = attrs.addAttributes(this->LLVMContext,
@@ -160,7 +158,7 @@
   // We create a shadow stack location of the swifterror parameter for the
   // debugger on such platforms and so we can't mark the parameter with a
   // swifterror attribute.
-  if (!UseSwiftCC || !this->IsSwiftErrorInRegister)
+  if (!this->IsSwiftErrorInRegister)
     return;
 
   llvm::AttrBuilder b;
@@ -1283,8 +1281,10 @@
   assert(LastArgWritten == 1 && "emitting unnaturally to indirect result");
 
   Args[0] = result.getAddress();
+  SILFunctionConventions FnConv(CurCallee.getSubstFunctionType(),
+                                IGF.getSILModule());
   addIndirectResultAttributes(IGF.IGM, CurCallee.getMutableAttributes(),
-                              0, true);
+                              0, FnConv.getNumIndirectSILResults() <= 1);
 #ifndef NDEBUG
   LastArgWritten = 0; // appease an assert
 #endif
@@ -1317,6 +1317,12 @@
 
   Args.clear();
 
+  // Deallocate all the temporaries.
+  for (auto &temporary : Temporaries) {
+    auto &ti = IGF.getTypeInfo(temporary.Type);
+    ti.deallocateStack(IGF, temporary.Temp, temporary.Type);
+  }
+
   // Return.
   return call;
 }
@@ -1388,7 +1394,7 @@
   // explode that temporary.
   if (LastArgWritten == 1) {
     StackAddress ctemp = substResultTI.allocateStack(IGF, substResultType,
-                                                     false, "call.aggresult");
+                                                     "call.aggresult");
     Address temp = ctemp.getAddress();
     emitToMemory(temp, substResultTI, isOutlined);
 
@@ -1625,8 +1631,9 @@
   }
 
   // Otherwise, materialize to a temporary.
-  Address temporary =
-    paramTI.allocateStack(IGF, paramTy, false, "coerce-and-expand.temp").getAddress();
+  auto temporaryAlloc =
+    paramTI.allocateStack(IGF, paramTy, "coerce-and-expand.temp");
+  Address temporary = temporaryAlloc.getAddress();
 
   auto coercionTyLayout = IGF.IGM.DataLayout.getStructLayout(coercionTy);
 
@@ -1685,7 +1692,7 @@
     paramTI.loadAsTake(IGF, temporary, out);
   }
 
-  paramTI.deallocateStack(IGF, StackAddress(temporary), paramTy);
+  paramTI.deallocateStack(IGF, temporaryAlloc, paramTy);
 }
 
 static void emitDirectExternalArgument(IRGenFunction &IGF, SILType argType,
@@ -1796,12 +1803,14 @@
   }
 
   // Otherwise, materialize to a temporary.
-  Address temp = swiftTI.allocateStack(IGF, swiftType, false,
-                                       "clang-expand-arg.temp").getAddress();
+  auto ctemp = swiftTI.allocateStack(IGF, swiftType, "clang-expand-arg.temp");
+  Address temp = ctemp.getAddress();
   swiftTI.initialize(IGF, in, temp, isOutlined);
 
   Address castTemp = IGF.Builder.CreateBitCast(temp, IGF.IGM.Int8PtrTy);
   ClangExpandLoadEmitter(IGF, out).visit(clangType, castTemp);
+
+  swiftTI.deallocateStack(IGF, ctemp, swiftType);
 }
 
 /// Given a Clang-expanded (according to ABIArgInfo::Expand) parameter
@@ -1818,17 +1827,21 @@
   }
 
   // Otherwise, materialize to a temporary.
-  Address temp = swiftTI.allocateStack(IGF, swiftType, false,
-                                       "clang-expand-param.temp").getAddress();
+  auto tempAlloc = swiftTI.allocateStack(IGF, swiftType,
+                                         "clang-expand-param.temp");
+  Address temp = tempAlloc.getAddress();
   Address castTemp = IGF.Builder.CreateBitCast(temp, IGF.IGM.Int8PtrTy);
   ClangExpandStoreEmitter(IGF, in).visit(clangType, castTemp);
 
   // Then load out.
   swiftTI.loadAsTake(IGF, temp, out);
+
+  swiftTI.deallocateStack(IGF, tempAlloc, swiftType);
 }
 
 static void externalizeArguments(IRGenFunction &IGF, const Callee &callee,
                                  Explosion &in, Explosion &out,
+                 SmallVectorImpl<CallEmission::TypedTemporary> &temporaries,
                                  bool isOutlined) {
   auto silConv = IGF.IGM.silConv;
   auto fnType = callee.getOrigFunctionType();
@@ -1896,8 +1909,11 @@
     }
     case clang::CodeGen::ABIArgInfo::Indirect: {
       auto &ti = cast<LoadableTypeInfo>(IGF.getTypeInfo(paramType));
-      Address addr = ti.allocateStack(IGF, paramType, false,
-                                      "indirect-temporary").getAddress();
+
+      auto temp = ti.allocateStack(IGF, paramType, "indirect-temporary");
+      temporaries.push_back({temp, paramType});
+
+      Address addr = temp.getAddress();
       // Set at least the alignment the ABI expects.
       if (AI.getIndirectByVal()) {
         auto ABIAlign = AI.getIndirectAlign();
@@ -2123,7 +2139,8 @@
   case SILFunctionTypeRepresentation::ObjCMethod:
     adjusted.add(getCallee().getObjCMethodReceiver());
     adjusted.add(getCallee().getObjCMethodSelector());
-    externalizeArguments(IGF, getCallee(), original, adjusted, isOutlined);
+    externalizeArguments(IGF, getCallee(), original, adjusted,
+                         Temporaries, isOutlined);
     break;
 
   case SILFunctionTypeRepresentation::Block:
@@ -2131,7 +2148,8 @@
     LLVM_FALLTHROUGH;
 
   case SILFunctionTypeRepresentation::CFunctionPointer:
-    externalizeArguments(IGF, getCallee(), original, adjusted, isOutlined);
+    externalizeArguments(IGF, getCallee(), original, adjusted,
+                         Temporaries, isOutlined);
     break;
 
   case SILFunctionTypeRepresentation::WitnessMethod:
@@ -2206,23 +2224,23 @@
 
     // Create the alloca.  We don't use allocateStack because we're
     // not allocating this in stack order.
-    auto addr = builder.CreateAlloca(errorTI.getStorageType(), nullptr,
-                                     "swifterror");
-    addr->setAlignment(errorTI.getFixedAlignment().getValue());
+    auto addr = createAlloca(errorTI.getStorageType(),
+                             errorTI.getFixedAlignment(),
+                             "swifterror");
 
     // Only add the swifterror attribute on ABIs that pass it in a register.
     // We create a shadow stack location of the swifterror parameter for the
     // debugger on platforms that pass swifterror by reference and so we can't
     // mark the parameter with a swifterror attribute for these.
     if (IGM.IsSwiftErrorInRegister)
-      addr->setSwiftError(true);
+      cast<llvm::AllocaInst>(addr.getAddress())->setSwiftError(true);
 
     // Initialize at the alloca point.
     auto nullError = llvm::ConstantPointerNull::get(
                             cast<llvm::PointerType>(errorTI.getStorageType()));
-    builder.CreateStore(nullError, addr, errorTI.getFixedAlignment());
+    builder.CreateStore(nullError, addr);
 
-    ErrorResultSlot = addr;
+    ErrorResultSlot = addr.getAddress();
   }
   return Address(ErrorResultSlot, IGM.getPointerAlignment());
 }
@@ -2258,8 +2276,9 @@
   Builder.SetInsertPoint(EntryBB);
 
   // Set up the alloca insertion point.
-  AllocaIP = Builder.CreateAlloca(IGM.Int1Ty, /*array size*/ nullptr,
-                                  "alloca point");
+  AllocaIP = Builder.IRBuilderBase::CreateAlloca(IGM.Int1Ty,
+                                                 /*array size*/ nullptr,
+                                                 "alloca point");
 }
 
 /// Emit a branch to the return block and set the insert point there.
@@ -2575,6 +2594,8 @@
       temporary, loadableTI.getStorageType()->getPointerTo());
   loadableTI.loadAsTake(IGF, storageAddr, nonNativeExplosion);
 
+  Builder.CreateLifetimeEnd(temporary, tempSize);
+
   return nonNativeExplosion;
 }
 
diff --git a/lib/IRGen/GenClass.cpp b/lib/IRGen/GenClass.cpp
index 493c944..83703b1 100644
--- a/lib/IRGen/GenClass.cpp
+++ b/lib/IRGen/GenClass.cpp
@@ -253,6 +253,9 @@
       if (theClass->isGenericContext())
         ClassMetadataRequiresDynamicInitialization = true;
 
+      if (IGM.isResilient(theClass, ResilienceExpansion::Maximal))
+        ClassMetadataRequiresDynamicInitialization = true;
+
       if (theClass->hasSuperclass()) {
         SILType superclassType = classType.getSuperclass();
         auto superclass = superclassType.getClassOrBoundGenericClass();
diff --git a/lib/IRGen/GenDecl.cpp b/lib/IRGen/GenDecl.cpp
index 7be0a1c..2fce470 100644
--- a/lib/IRGen/GenDecl.cpp
+++ b/lib/IRGen/GenDecl.cpp
@@ -1416,16 +1416,16 @@
   case SILLinkage::Hidden:
     return RESULT(External, Hidden, Default);
 
-  case SILLinkage::Private:
-    // In case of multiple llvm modules (in multi-threaded compilation) all
-    // private decls must be visible from other files.
-    // We use LinkOnceODR instead of External here because private lazy protocol
-    // witness table accessors could be emitted by two different IGMs during
-    // IRGen into different object files and the linker would complain about
-    // duplicate symbols.
-    if (info.HasMultipleIGMs)
-      return RESULT(LinkOnceODR, Hidden, Default);
-    return RESULT(Internal, Default, Default);
+  case SILLinkage::Private: {
+    auto linkage = info.needLinkerToMergeDuplicateSymbols()
+                       ? llvm::GlobalValue::LinkOnceODRLinkage
+                       : llvm::GlobalValue::InternalLinkage;
+    auto visibility = info.shouldAllPrivateDeclsBeVisibleFromOtherFiles()
+                          ? llvm::GlobalValue::HiddenVisibility
+                          : llvm::GlobalValue::DefaultVisibility;
+    return std::make_tuple(linkage, visibility,
+                           llvm::GlobalValue::DefaultStorageClass);
+  }
 
   case SILLinkage::PublicExternal: {
     if (isDefinition) {
diff --git a/lib/IRGen/GenEnum.cpp b/lib/IRGen/GenEnum.cpp
index 7776b2d..eb1bca6 100644
--- a/lib/IRGen/GenEnum.cpp
+++ b/lib/IRGen/GenEnum.cpp
@@ -130,6 +130,14 @@
 using namespace swift;
 using namespace irgen;
 
+static llvm::Constant *emitEnumLayoutFlags(IRGenModule &IGM, bool isVWTMutable){
+  // For now, we always use the Swift 5 algorithm.
+  auto flags = EnumLayoutFlags::Swift5Algorithm;
+  if (isVWTMutable) flags |= EnumLayoutFlags::IsVWTMutable;
+
+  return IGM.getSize(Size(uintptr_t(flags)));
+}
+
 SpareBitVector getBitVectorFromAPInt(const APInt &bits, unsigned startBit = 0) {
   if (startBit == 0) {
     return SpareBitVector::fromAPInt(bits);
@@ -587,78 +595,21 @@
 
     void initializeMetadata(IRGenFunction &IGF,
                             llvm::Value *metadata,
-                            llvm::Value *vwtable,
+                            bool isVWTMutable,
                             SILType T) const override {
       // Fixed-size enums don't need dynamic witness table initialization.
       if (TIK >= Fixed) return;
 
-      assert(!ElementsWithPayload.empty() &&
+      assert(ElementsWithPayload.size() == 1 &&
              "empty singleton enum should not be dynamic!");
 
-      // Get the value witness table for the element.
-      SILType eltTy = T.getEnumElementType(ElementsWithPayload[0].decl,
-                                           IGM.getSILModule());
-      llvm::Value *eltLayout = IGF.emitTypeLayoutRef(eltTy);
-
-      Address vwtAddr(vwtable, IGF.IGM.getPointerAlignment());
-      Address eltLayoutAddr(eltLayout, IGF.IGM.getPointerAlignment());
-
-      auto getWitnessDestAndSrc = [&](ValueWitness witness,
-                                      Address *dest,
-                                      Address *src) {
-        *dest = IGF.Builder.CreateConstArrayGEP(vwtAddr,
-                                   unsigned(witness), IGF.IGM.getPointerSize());
-        *src = IGF.Builder.CreateConstArrayGEP(eltLayoutAddr,
-          unsigned(witness) - unsigned(ValueWitness::First_TypeLayoutWitness),
-          IGF.IGM.getPointerSize());
-      };
-
-      auto copyWitnessFromElt = [&](ValueWitness witness) {
-        Address dest, src;
-        getWitnessDestAndSrc(witness, &dest, &src);
-        auto val = IGF.Builder.CreateLoad(src);
-        IGF.Builder.CreateStore(val, dest);
-      };
-
-      copyWitnessFromElt(ValueWitness::Size);
-      copyWitnessFromElt(ValueWitness::Stride);
-
-      // Copy flags over, adding HasEnumWitnesses flag
-      auto copyFlagsFromElt = [&](ValueWitness witness) -> llvm::Value* {
-        Address dest, src;
-        getWitnessDestAndSrc(witness, &dest, &src);
-        auto val = IGF.Builder.CreateLoad(src);
-        auto ewFlag = IGF.Builder.CreatePtrToInt(val, IGF.IGM.SizeTy);
-        auto ewMask
-          = IGF.IGM.getSize(Size(ValueWitnessFlags::HasEnumWitnesses));
-        ewFlag = IGF.Builder.CreateOr(ewFlag, ewMask);
-        auto flag = IGF.Builder.CreateIntToPtr(ewFlag,
-                                              dest.getType()->getElementType());
-        IGF.Builder.CreateStore(flag, dest);
-        return val;
-      };
-
-      auto flags = copyFlagsFromElt(ValueWitness::Flags);
-
-      // If the original type had extra inhabitants, carry over its
-      // extra inhabitant flags.
-      auto xiBB = llvm::BasicBlock::Create(IGF.IGM.getLLVMContext());
-      auto noXIBB = llvm::BasicBlock::Create(IGF.IGM.getLLVMContext());
-
-      auto xiFlag = IGF.Builder.CreatePtrToInt(flags, IGF.IGM.SizeTy);
-      auto xiMask
-        = IGF.IGM.getSize(Size(ValueWitnessFlags::Enum_HasExtraInhabitants));
-      xiFlag = IGF.Builder.CreateAnd(xiFlag, xiMask);
-      auto xiBool = IGF.Builder.CreateICmpNE(xiFlag,
-                                             IGF.IGM.getSize(Size(0)));
-      IGF.Builder.CreateCondBr(xiBool, xiBB, noXIBB);
-
-      IGF.Builder.emitBlock(xiBB);
-      ConditionalDominanceScope condition(IGF);
-      copyWitnessFromElt(ValueWitness::ExtraInhabitantFlags);
-      IGF.Builder.CreateBr(noXIBB);
-
-      IGF.Builder.emitBlock(noXIBB);
+      auto payloadTy = T.getEnumElementType(ElementsWithPayload[0].decl,
+                                            IGM.getSILModule());
+      auto payloadLayout = IGF.emitTypeLayoutRef(payloadTy);
+      auto flags = emitEnumLayoutFlags(IGF.IGM, isVWTMutable);
+      IGF.Builder.CreateCall(
+                    IGF.IGM.getInitEnumMetadataSingleCaseFn(),
+                    {metadata, flags, payloadLayout});
     }
 
     bool mayHaveExtraInhabitants(IRGenModule &IGM) const override {
@@ -904,7 +855,7 @@
 
     void initializeMetadata(IRGenFunction &IGF,
                             llvm::Value *metadata,
-                            llvm::Value *vwtable,
+                            bool isVWTMutable,
                             SILType T) const override {
       // No-payload enums are always fixed-size so never need dynamic value
       // witness table initialization.
@@ -2846,7 +2797,7 @@
 
     void initializeMetadata(IRGenFunction &IGF,
                             llvm::Value *metadata,
-                            llvm::Value *vwtable,
+                            bool isVWTMutable,
                             SILType T) const override {
       // Fixed-size enums don't need dynamic witness table initialization.
       if (TIK >= Fixed) return;
@@ -2858,10 +2809,10 @@
       auto payloadLayout = IGF.emitTypeLayoutRef(payloadTy);
       auto emptyCasesVal = llvm::ConstantInt::get(IGF.IGM.Int32Ty,
                                                   ElementsWithNoPayload.size());
-
+      auto flags = emitEnumLayoutFlags(IGF.IGM, isVWTMutable);
       IGF.Builder.CreateCall(
-                    IGF.IGM.getInitEnumValueWitnessTableSinglePayloadFn(),
-                    {vwtable, payloadLayout, emptyCasesVal});
+                    IGF.IGM.getInitEnumMetadataSinglePayloadFn(),
+                    {metadata, flags, payloadLayout, emptyCasesVal});
     }
 
     /// \group Extra inhabitants
@@ -4744,7 +4695,7 @@
 
     void initializeMetadata(IRGenFunction &IGF,
                             llvm::Value *metadata,
-                            llvm::Value *vwtable,
+                            bool isVWTMutable,
                             SILType T) const override {
       // Fixed-size enums don't need dynamic metadata initialization.
       if (TIK >= Fixed) return;
@@ -4754,8 +4705,9 @@
       auto numPayloadsVal = llvm::ConstantInt::get(IGF.IGM.SizeTy,
                                                    ElementsWithPayload.size());
 
+      auto flags = emitEnumLayoutFlags(IGF.IGM, isVWTMutable);
       IGF.Builder.CreateCall(IGF.IGM.getInitEnumMetadataMultiPayloadFn(),
-                             {vwtable, metadata, numPayloadsVal,
+                             {metadata, flags, numPayloadsVal,
                               payloadLayoutArray});
     }
 
@@ -5139,7 +5091,7 @@
 
     void initializeMetadata(IRGenFunction &IGF,
                             llvm::Value *metadata,
-                            llvm::Value *vwtable,
+                            bool isVWTMutable,
                             SILType T) const override {
       llvm_unreachable("resilient enums cannot be defined");
     }
@@ -5392,9 +5344,9 @@
     }
     void initializeMetadata(IRGenFunction &IGF,
                             llvm::Value *metadata,
-                            llvm::Value *vwtable,
+                            bool isVWTMutable,
                             SILType T) const override {
-      return Strategy.initializeMetadata(IGF, metadata, vwtable, T);
+      return Strategy.initializeMetadata(IGF, metadata, isVWTMutable, T);
     }
     bool mayHaveExtraInhabitants(IRGenModule &IGM) const override {
       return Strategy.mayHaveExtraInhabitants(IGM);
diff --git a/lib/IRGen/GenEnum.h b/lib/IRGen/GenEnum.h
index b82a370..262f88e 100644
--- a/lib/IRGen/GenEnum.h
+++ b/lib/IRGen/GenEnum.h
@@ -372,7 +372,7 @@
 
   virtual void initializeMetadata(IRGenFunction &IGF,
                                   llvm::Value *metadata,
-                                  llvm::Value *vwtable,
+                                  bool isVWTMutable,
                                   SILType T) const = 0;
 
   virtual bool mayHaveExtraInhabitants(IRGenModule &IGM) const = 0;
diff --git a/lib/IRGen/GenFunc.cpp b/lib/IRGen/GenFunc.cpp
index 2e44089..ee24d6b 100644
--- a/lib/IRGen/GenFunc.cpp
+++ b/lib/IRGen/GenFunc.cpp
@@ -813,7 +813,7 @@
     } else if (origNativeSchema.requiresIndirect()) {
       assert(!nativeResultSchema.requiresIndirect());
       auto stackAddr = outResultTI.allocateStack(
-          subIGF, outConv.getSILResultType(), false, "return.temp");
+          subIGF, outConv.getSILResultType(), "return.temp");
       resultValueAddr = stackAddr.getAddress();
       auto resultAddr = subIGF.Builder.CreateBitCast(
           resultValueAddr,
@@ -967,7 +967,15 @@
       auto paramInfo = substType->getParameters()[paramI];
       auto &ti = IGM.getTypeInfoForLowered(paramInfo.getType());
       Explosion param;
-      param.add(subIGF.Builder.CreateBitCast(rawData, ti.getStorageType()));
+      auto ref = rawData;
+      // We can get a '{ swift.refcounted* }' type for AnyObject on linux.
+      if (!ti.getStorageType()->isPointerTy() &&
+          ti.isSingleSwiftRetainablePointer(ResilienceExpansion::Maximal))
+        ref = subIGF.coerceValue(rawData, ti.getStorageType(),
+                                 subIGF.IGM.DataLayout);
+      else
+        ref = subIGF.Builder.CreateBitCast(rawData, ti.getStorageType());
+      param.add(ref);
       bindPolymorphicParameter(subIGF, origType, substType, param, paramI);
       (void)param.claimAll();
     }
@@ -1089,7 +1097,7 @@
         // The +1 argument is passed indirectly, so we need to copy into a
         // temporary.
         needsAllocas = true;
-        auto stackAddr = fieldTI.allocateStack(subIGF, fieldTy, false, "arg.temp");
+        auto stackAddr = fieldTI.allocateStack(subIGF, fieldTy, "arg.temp");
         auto addressPointer = stackAddr.getAddress().getAddress();
         fieldTI.initializeWithCopy(subIGF, stackAddr.getAddress(), fieldAddr,
                                    fieldTy, false);
diff --git a/lib/IRGen/GenInit.cpp b/lib/IRGen/GenInit.cpp
index 0350931..bc6ee10 100644
--- a/lib/IRGen/GenInit.cpp
+++ b/lib/IRGen/GenInit.cpp
@@ -57,7 +57,6 @@
 }
 
 StackAddress FixedTypeInfo::allocateStack(IRGenFunction &IGF, SILType T,
-                                          bool isEntryBlock,
                                           const Twine &name) const {
   // If the type is known to be empty, don't actually allocate anything.
   if (isKnownEmpty(ResilienceExpansion::Maximal)) {
diff --git a/lib/IRGen/GenKeyPath.cpp b/lib/IRGen/GenKeyPath.cpp
index e846e2e..4058426 100644
--- a/lib/IRGen/GenKeyPath.cpp
+++ b/lib/IRGen/GenKeyPath.cpp
@@ -904,7 +904,7 @@
           idKind = KeyPathComponentHeader::VTableOffset;
           auto dc = declRef.getDecl()->getDeclContext();
           if (isa<ClassDecl>(dc)) {
-            auto overridden = getSILTypes().getOverriddenVTableEntry(declRef);
+            auto overridden = declRef.getOverriddenVTableEntry();
             auto declaringClass =
               cast<ClassDecl>(overridden.getDecl()->getDeclContext());
             auto &metadataLayout = getMetadataLayout(declaringClass);
diff --git a/lib/IRGen/GenMeta.cpp b/lib/IRGen/GenMeta.cpp
index 62bf20f..c85e809 100644
--- a/lib/IRGen/GenMeta.cpp
+++ b/lib/IRGen/GenMeta.cpp
@@ -2424,9 +2424,7 @@
   public:
     ClassNominalTypeDescriptorBuilder(IRGenModule &IGM,
                                        ClassDecl *c)
-      : super(IGM),
-        SILVTableVisitor<ClassNominalTypeDescriptorBuilder>(IGM.getSILTypes()),
-        Target(c)
+      : super(IGM), Target(c)
     {
       auto &layout = IGM.getMetadataLayout(Target);
       FieldVectorOffset = layout.getStaticFieldOffsetVectorOffset();
@@ -2781,14 +2779,9 @@
     bool HasDependentMetadata = false;
     
     /// Set to true if the value witness table for the generic type is dependent
-    /// on its generic parameters. If true, the value witness will be
-    /// tail-emplaced inside the metadata pattern and initialized by the fill
-    /// function. Implies HasDependentMetadata.
+    /// on its generic parameters. Implies HasDependentMetadata.
     bool HasDependentVWT = false;
     
-    /// The offset of the tail-allocated dependent VWT, if any.
-    Size DependentVWTPoint = Size::invalid();
-
     template <class... T>
     GenericMetadataBuilderBase(IRGenModule &IGM, T &&...args)
       : super(IGM, std::forward<T>(args)...) {}
@@ -2854,31 +2847,13 @@
         value = IGF.Builder.CreateBitCast(value, IGM.Int8PtrTy);
         IGF.Builder.CreateStore(value, dest);
       }
-      
-      // Initialize the instantiated dependent value witness table, if we have
-      // one.
-      llvm::Value *vwtableValue = nullptr;
-      if (HasDependentVWT) {
-        assert(!AddressPoint.isInvalid() && "did not set valid address point!");
-        assert(!DependentVWTPoint.isInvalid() && "did not set dependent VWT point!");
-        
-        // Fill in the pointer from the metadata to the VWT. The VWT pointer
-        // always immediately precedes the address point.
-        auto vwtAddr = createPointerSizedGEP(IGF, metadataWords,
-                                             DependentVWTPoint - AddressPoint);
-        vwtableValue = IGF.Builder.CreateBitCast(vwtAddr.getAddress(),
-                                                 IGF.IGM.WitnessTablePtrTy);
 
-        auto vwtAddrVal = IGF.Builder.CreateBitCast(vwtableValue, IGM.Int8PtrTy);
-        auto vwtRefAddr = createPointerSizedGEP(IGF, metadataWords,
-                                                Size(0) - IGM.getPointerSize());
-        IGF.Builder.CreateStore(vwtAddrVal, vwtRefAddr);
-        
+      // A dependent VWT means that we have dependent metadata.
+      if (HasDependentVWT)
         HasDependentMetadata = true;
-      }
 
       if (HasDependentMetadata) {
-        asImpl().emitInitializeMetadata(IGF, metadataValue, vwtableValue);
+        asImpl().emitInitializeMetadata(IGF, metadataValue, false);
       }
       
       // The metadata is now complete.
@@ -2914,13 +2889,6 @@
       // Lay out the template data.
       super::layout();
       
-      // If we have a dependent value witness table, emit its template.
-      if (HasDependentVWT) {
-        // Note the dependent VWT offset.
-        DependentVWTPoint = getNextOffsetFromTemplateHeader();
-        asImpl().addDependentValueWitnessTablePattern();
-      }
-      
       // Fill in the header:
 
       //   Metadata *(*CreateFunction)(GenericMetadata *, const void*);
@@ -3011,7 +2979,7 @@
 void irgen::emitInitializeFieldOffsetVector(IRGenFunction &IGF,
                                             SILType T,
                                             llvm::Value *metadata,
-                                            llvm::Value *vwtable) {
+                                            bool isVWTMutable) {
   auto *target = T.getNominalOrBoundGenericNominal();
   llvm::Value *fieldVector
     = emitAddressOfFieldOffsetVector(IGF, metadata, target)
@@ -3047,15 +3015,18 @@
   auto numFields = IGF.IGM.getSize(Size(storedProperties.size()));
 
   if (isa<ClassDecl>(target)) {
-    assert(vwtable == nullptr);
     IGF.Builder.CreateCall(IGF.IGM.getInitClassMetadataUniversalFn(),
                            {metadata, numFields,
                             fields.getAddress(), fieldVector});
   } else {
     assert(isa<StructDecl>(target));
-    IGF.Builder.CreateCall(IGF.IGM.getInitStructMetadataUniversalFn(),
-                           {numFields, fields.getAddress(),
-                            fieldVector, vwtable});
+    StructLayoutFlags flags = StructLayoutFlags::Swift5Algorithm;
+    if (isVWTMutable)
+      flags |= StructLayoutFlags::IsVWTMutable;
+
+    IGF.Builder.CreateCall(IGF.IGM.getInitStructMetadataFn(),
+                           {metadata, IGF.IGM.getSize(Size(uintptr_t(flags))),
+                            numFields, fields.getAddress(), fieldVector});
   }
 
   IGF.Builder.CreateLifetimeEnd(fields,
@@ -3226,6 +3197,8 @@
     using super::Target;
     using super::asImpl;
 
+    bool HasResilientSuperclass = false;
+
     ConstantStructBuilder &B;
     const StructLayout &Layout;
     const ClassLayout &FieldLayout;
@@ -3241,6 +3214,45 @@
         Members(IGM, theClass, builder, layout, fieldLayout) {}
 
   public:
+    void noteResilientSuperclass() {
+      // FIXME: Perform sliding
+      HasResilientSuperclass = true;
+    }
+
+    void noteStartOfImmediateMembers(ClassDecl *theClass) {
+      // Only classes defined in resilient modules, or those that have
+      // a resilient superclass need this.
+      if (!HasResilientSuperclass &&
+          !IGM.isResilient(theClass, ResilienceExpansion::Minimal)) {
+        return;
+      }
+
+      if (theClass == Target) {
+        auto *offsetAddr =
+          IGM.getAddrOfClassMetadataBaseOffset(theClass,
+                                               ForDefinition);
+        auto *offsetVar = cast<llvm::GlobalVariable>(offsetAddr);
+
+        if (HasResilientSuperclass) {
+          // If the superclass is resilient to us, we have to compute and
+          // initialize the global when we initialize the metadata.
+          auto *init = llvm::ConstantInt::get(IGM.SizeTy, 0);
+
+          offsetVar->setInitializer(init);
+          offsetVar->setConstant(false);
+          return;
+        }
+
+        // Otherwise, we know the offset at compile time, even if our
+        // clients do not, so just emit a constant.
+        auto value = asImpl().getNextOffsetFromAddressPoint().getValue();
+        auto *init = llvm::ConstantInt::get(IGM.SizeTy, value);
+
+        offsetVar->setInitializer(init);
+        offsetVar->setConstant(true);
+      }
+    }
+
     /// The 'metadata flags' field in a class is actually a pointer to
     /// the metaclass object for the class.
     ///
@@ -3458,25 +3470,15 @@
 
     llvm::Value *emitFinishInitializationOfClassMetadata(IRGenFunction &IGF,
                                                          llvm::Value *metadata) {
-      // We assume that we've already filled in the class's generic arguments.
-      // We need to:
-      //   - fill out the subclass's field offset vector, if its layout
-      //     wasn't fixed;
-      //   - copy field offsets and generic arguments from higher in the
-      //     class hierarchy, if 
-      //   - copy the superclass data, if there are generic arguments
-      //     or field offset vectors there that weren't filled in;
-      //   - populate the field offset vector, if layout isn't fixed, and
-      //   - register the class with the ObjC runtime, if ObjC interop is
-      //     enabled.
-      //
-      // emitInitializeFieldOffsetVector will do everything in the full case.
       if (doesClassMetadataRequireDynamicInitialization(IGF.IGM, Target)) {
+        // We need to:
+        //   - fill out the subclass's field offset vector
+        //   - copy field offsets and generic arguments from higher in the
+        //     class hierarchy
         auto classTy = Target->getDeclaredTypeInContext()->getCanonicalType();
         auto loweredClassTy = IGF.IGM.getLoweredType(classTy);
         emitInitializeFieldOffsetVector(IGF, loweredClassTy,
-                                        metadata,
-                                        /*vwtable=*/nullptr);
+                                        metadata, /*VWT is mutable*/ false);
 
         // Realizing the class with the ObjC runtime will copy back to the
         // field offset globals for us; but if ObjC interop is disabled, we
@@ -3484,9 +3486,8 @@
         // correctly in the first place.
         if (!IGF.IGM.ObjCInterop)
           emitInitializeFieldOffsets(IGF, metadata);
-
-      // Otherwise, all we need to do is register with the ObjC runtime.
       } else {
+        // Otherwise, all we need to do is register with the ObjC runtime.
         metadata = emitFinishIdempotentInitialization(IGF, metadata);
       }
 
@@ -3497,6 +3498,43 @@
       return metadata;
     }
 
+    // Store the runtime-computed metadata size of our superclass into the
+    // target class's metadata base offset global variable.
+    //
+    // Note that this code will run for each generic instantiation of the
+    // class, if the class is generic. This should be OK because the
+    // metadata size does not change between generic instantiations, so
+    // all stores after the first should be idempotent.
+    void emitInitializeClassMetadataBaseOffset(IRGenFunction &IGF,
+                                               llvm::Value *superMetadata) {
+      if (!HasResilientSuperclass)
+        return;
+
+      auto &layout = IGM.getMetadataLayout(Target);
+
+      // Load the size of the superclass metadata.
+      Address metadataAsBytes(
+          IGF.Builder.CreateBitCast(superMetadata, IGF.IGM.Int8PtrTy),
+          IGM.getPointerAlignment());
+
+      Address slot = IGF.Builder.CreateConstByteArrayGEP(
+          metadataAsBytes,
+          layout.getMetadataSizeOffset());
+      slot = IGF.Builder.CreateBitCast(slot, IGM.Int32Ty->getPointerTo());
+      llvm::Value *size = IGF.Builder.CreateLoad(slot);
+      if (IGM.SizeTy != IGM.Int32Ty)
+        size = IGF.Builder.CreateZExt(size, IGM.SizeTy);
+
+      Address offsetAddr(
+          IGM.getAddrOfClassMetadataBaseOffset(Target,
+                                               NotForDefinition),
+          IGM.getPointerAlignment());
+
+      // FIXME: Do we need to worry about memory barriers here, and when we
+      // load from the global?
+      IGF.Builder.CreateStore(size, offsetAddr);
+    }
+
     // Update vtable entries for method overrides. The runtime copies in
     // the vtable from the superclass for us; we have to install method
     // overrides ourselves.
@@ -3602,6 +3640,7 @@
     using super::Target;
     using super::B;
     using super::addReferenceToHeapMetadata;
+    using super::emitInitializeClassMetadataBaseOffset;
     using super::emitFinishInitializationOfClassMetadata;
     using super::emitFinishIdempotentInitialization;
     using super::emitFieldOffsetGlobals;
@@ -3697,15 +3736,18 @@
       // Initialize the superclass if we didn't do so as a constant.
       if (HasUnfilledSuperclass) {
         auto superclass = type->getSuperclass()->getCanonicalType();
-        llvm::Value *superclassMetadata =
+        llvm::Value *superMetadata =
           emitClassHeapMetadataRef(IGF, superclass,
                                    MetadataValueType::TypeMetadata,
                                    /*allowUninit*/ false);
+
+        emitInitializeClassMetadataBaseOffset(IGF, superMetadata);
+
         Address superField =
           emitAddressOfSuperclassRefInClassMetadata(IGF, metadata);
         superField = IGF.Builder.CreateElementBitCast(superField,
                                                      IGM.TypeMetadataPtrTy);
-        IGF.Builder.CreateStore(superclassMetadata, superField);
+        IGF.Builder.CreateStore(superMetadata, superField);
       }
 
       // Relocate the metadata if it has a superclass that is resilient
@@ -3794,12 +3836,13 @@
         superMetadata =
           emitClassHeapMetadataRef(IGF, superclass->getCanonicalType(),
                                    MetadataValueType::ObjCClass);
+
+        emitInitializeClassMetadataBaseOffset(IGF, superMetadata);
       } else if (IGM.ObjCInterop) {
         superMetadata = emitObjCHeapMetadataRef(IGF,
                                IGM.getObjCRuntimeBaseForSwiftRootClass(Target));
       } else {
-        superMetadata
-          = llvm::ConstantPointerNull::get(IGM.ObjCClassPtrTy);
+        superMetadata = llvm::ConstantPointerNull::get(IGM.ObjCClassPtrTy);
       }
 
       auto numImmediateMembers =
@@ -3852,10 +3895,6 @@
       DependentMetaclassRODataPoint -= TemplateHeaderSize;
     }
                             
-    void addDependentValueWitnessTablePattern() {
-      llvm_unreachable("classes should never have dependent vwtables");
-    }
-
     void noteStartOfFieldOffsets(ClassDecl *whichClass) {}
     
     void noteEndOfFieldOffsets(ClassDecl *whichClass) {}
@@ -3889,7 +3928,7 @@
 
     void emitInitializeMetadata(IRGenFunction &IGF,
                                 llvm::Value *metadata,
-                                llvm::Value *vwtable) {
+                                bool isVWTMutable) {
       assert(!HasDependentVWT && "class should never have dependent VWT");
 
       // Fill in the metaclass pointer.
@@ -4342,7 +4381,7 @@
                                          object,
                                          object->getName() + ".Type");
   metadata->setDoesNotThrow();
-  metadata->setDoesNotAccessMemory();
+  metadata->setOnlyReadsMemory();
   return metadata;
 }
 
@@ -4411,7 +4450,7 @@
     = cast<AbstractFunctionDecl>(method.getDecl());
 
   // Find the vtable entry for this method.
-  SILDeclRef overridden = IGF.IGM.getSILTypes().getOverriddenVTableEntry(method);
+  SILDeclRef overridden = method.getOverriddenVTableEntry();
 
   // Find the metadata.
   llvm::Value *metadata;
@@ -4482,12 +4521,8 @@
   SILType loweredType = IGF.IGM.getLoweredType(AbstractionPattern(type), type);
   auto &ti = IGF.IGM.getTypeInfo(loweredType);
   if (!ti.isFixedSize()) {
-    // We assume that that value witness table will already have been written
-    // into the metadata; just load it.
-    llvm::Value *vwtable = IGF.emitValueWitnessTableRefForMetadata(metadata);
-
     // Initialize the metadata.
-    ti.initializeMetadata(IGF, metadata, vwtable, loweredType.getAddressType());
+    ti.initializeMetadata(IGF, metadata, true, loweredType.getAddressType());
   }
 
   return metadata;
@@ -4588,7 +4623,7 @@
 
     void addValueWitnessTable() {
       auto type = this->Target->getDeclaredType()->getCanonicalType();
-      B.add(emitValueWitnessTable(IGM, type));
+      B.add(emitValueWitnessTable(IGM, type, false));
     }
 
     void createMetadataAccessFunction() {
@@ -4606,11 +4641,8 @@
     CanType unboundType
       = decl->getDeclaredType()->getCanonicalType();
     
-    dependent = hasDependentValueWitnessTable(IGM, unboundType);    
-    if (dependent)
-      return llvm::ConstantPointerNull::get(IGM.Int8PtrTy);
-    else
-      return emitValueWitnessTable(IGM, unboundType);
+    dependent = hasDependentValueWitnessTable(IGM, unboundType);
+    return emitValueWitnessTable(IGM, unboundType, dependent);
   }
   
   /// A builder for metadata templates.
@@ -4641,18 +4673,13 @@
                                                     HasDependentVWT));
     }
                         
-    void addDependentValueWitnessTablePattern() {
-      emitDependentValueWitnessTablePattern(IGM, B,
-                        Target->getDeclaredType()->getCanonicalType());
-    }
-                        
     void emitInitializeMetadata(IRGenFunction &IGF,
                                 llvm::Value *metadata,
-                                llvm::Value *vwtable) {
+                                bool isVWTMutable) {
       // Nominal types are always preserved through SIL lowering.
       auto structTy = Target->getDeclaredTypeInContext()->getCanonicalType();
       IGM.getTypeInfoForUnlowered(structTy)
-        .initializeMetadata(IGF, metadata, vwtable,
+        .initializeMetadata(IGF, metadata, isVWTMutable,
                             IGF.IGM.getLoweredType(structTy));
     }
   };
@@ -4743,7 +4770,7 @@
 
     void addValueWitnessTable() {
       auto type = Target->getDeclaredType()->getCanonicalType();
-      B.add(emitValueWitnessTable(IGM, type));
+      B.add(emitValueWitnessTable(IGM, type, false));
     }
 
     void addPayloadSize() {
@@ -4791,11 +4818,6 @@
                                                     HasDependentVWT));
     }
 
-    void addDependentValueWitnessTablePattern() {
-      emitDependentValueWitnessTablePattern(IGM, B,
-                          Target->getDeclaredType()->getCanonicalType());
-    }
-
     void addPayloadSize() {
       // In all cases where a payload size is demanded in the metadata, it's
       // runtime-dependent, so fill in a zero here.
@@ -4809,11 +4831,11 @@
 
     void emitInitializeMetadata(IRGenFunction &IGF,
                                 llvm::Value *metadata,
-                                llvm::Value *vwtable) {
+                                bool isVWTMutable) {
       // Nominal types are always preserved through SIL lowering.
       auto enumTy = Target->getDeclaredTypeInContext()->getCanonicalType();
       IGM.getTypeInfoForUnlowered(enumTy)
-        .initializeMetadata(IGF, metadata, vwtable,
+        .initializeMetadata(IGF, metadata, isVWTMutable,
                             IGF.IGM.getLoweredType(enumTy));
     }
   };
@@ -4904,7 +4926,14 @@
   };
   
   /// An adapter that turns a metadata layout class into a foreign metadata
-  /// layout class. Foreign metadata has an additional header that
+  /// layout class.
+  ///
+  /// Foreign metadata is generated for declarations that are
+  /// synthesized by the Clang importer from C declarations, meaning they don't
+  /// have a single Swift binary that is responsible for their emission.
+  /// In this case, we emit the record into every binary that needs it, with
+  /// a header with a unique identifier string that the runtime can use to pick
+  /// the first-used instance as the canonical instance for a process.
   template<typename Impl, typename Base>
   class ForeignMetadataBuilderBase : public Base {
     typedef Base super;
@@ -4923,8 +4952,9 @@
     void layout() {
       if (asImpl().requiresInitializationFunction())
         asImpl().addInitializationFunction();
+      else
+        asImpl().addPaddingForInitializationFunction();
       asImpl().addForeignName();
-      asImpl().addUniquePointer();
       asImpl().addForeignFlags();
       super::layout();
     }
@@ -4937,11 +4967,8 @@
 
     void addForeignName() {
       CanType targetType = asImpl().getTargetType();
-      B.add(getMangledTypeName(IGM, targetType));
-    }
-
-    void addUniquePointer() {
-      B.addNullPointer(IGM.TypeMetadataPtrTy);
+      B.addRelativeAddress(getMangledTypeName(IGM, targetType,
+                                              /*relative addressed?*/ true));
     }
 
     void addInitializationFunction() {
@@ -4967,7 +4994,23 @@
 
       IGF.Builder.CreateRetVoid();
 
-      B.add(fn);
+      B.addRelativeAddress(fn);
+    }
+    
+    void addPaddingForInitializationFunction() {
+      // The initialization function field is placed at the least offset of the
+      // record so it can be omitted when not needed. However, the metadata
+      // record is still pointer-aligned, so on 64 bit platforms we need to
+      // occupy the space to keep the rest of the record with the right layout.
+      switch (IGM.getPointerSize().getValue()) {
+      case 4:
+        break;
+      case 8:
+        B.addInt32(0);
+        break;
+      default:
+        llvm_unreachable("unsupported word size");
+      }
     }
 
     void noteAddressPoint() {
@@ -5049,7 +5092,7 @@
 
     void addValueWitnessTable() {
       auto type = this->Target->getDeclaredType()->getCanonicalType();
-      B.add(emitValueWitnessTable(IGM, type));
+      B.add(emitValueWitnessTable(IGM, type, false));
     }
 
     void flagUnfilledFieldOffset() {
@@ -5078,7 +5121,7 @@
 
     void addValueWitnessTable() {
       auto type = this->Target->getDeclaredType()->getCanonicalType();
-      B.add(emitValueWitnessTable(IGM, type));
+      B.add(emitValueWitnessTable(IGM, type, false));
     }
     
     void addPayloadSize() const {
diff --git a/lib/IRGen/GenMeta.h b/lib/IRGen/GenMeta.h
index 62af738..decfc83 100644
--- a/lib/IRGen/GenMeta.h
+++ b/lib/IRGen/GenMeta.h
@@ -258,7 +258,7 @@
   void emitInitializeFieldOffsetVector(IRGenFunction &IGF,
                                        SILType T,
                                        llvm::Value *metadata,
-                                       llvm::Value *vwtable);
+                                       bool isVWTMutable);
 
   /// Adjustment indices for the address points of various metadata.
   /// Size is in words.
diff --git a/lib/IRGen/GenOpaque.cpp b/lib/IRGen/GenOpaque.cpp
index 3338f58..f5b27dc 100644
--- a/lib/IRGen/GenOpaque.cpp
+++ b/lib/IRGen/GenOpaque.cpp
@@ -443,39 +443,47 @@
 /// Emit a dynamic alloca call to allocate enough memory to hold an object of
 /// type 'T' and an optional llvm.stackrestore point if 'isInEntryBlock' is
 /// false.
-DynamicAlloca irgen::emitDynamicAlloca(IRGenFunction &IGF, SILType T,
-                                       bool isInEntryBlock) {
+StackAddress IRGenFunction::emitDynamicAlloca(SILType T,
+                                              const llvm::Twine &name) {
+  llvm::Value *size = emitLoadOfSize(*this, T);
+  return emitDynamicAlloca(IGM.Int8Ty, size, Alignment(16), name);
+}
+
+StackAddress IRGenFunction::emitDynamicAlloca(llvm::Type *eltTy,
+                                              llvm::Value *arraySize,
+                                              Alignment align,
+                                              const llvm::Twine &name) {
   llvm::Value *stackRestorePoint = nullptr;
 
   // Save the stack pointer if we are not in the entry block (we could be
   // executed more than once).
+  bool isInEntryBlock = (Builder.GetInsertBlock() == &*CurFn->begin());
   if (!isInEntryBlock) {
     auto *stackSaveFn = llvm::Intrinsic::getDeclaration(
-        &IGF.IGM.Module, llvm::Intrinsic::ID::stacksave);
+        &IGM.Module, llvm::Intrinsic::ID::stacksave);
 
-    stackRestorePoint =  IGF.Builder.CreateCall(stackSaveFn, {}, "spsave");
+    stackRestorePoint =  Builder.CreateCall(stackSaveFn, {}, "spsave");
   }
 
   // Emit the dynamic alloca.
-  llvm::Value *size = emitLoadOfSize(IGF, T);
-  auto *alloca = IGF.Builder.CreateAlloca(IGF.IGM.Int8Ty, size, "alloca");
-  alloca->setAlignment(16);
+  auto *alloca = Builder.IRBuilderBase::CreateAlloca(eltTy, arraySize, name);
+  alloca->setAlignment(align.getValue());
+
   assert(!isInEntryBlock ||
-         IGF.getActiveDominancePoint().isUniversal() &&
+         getActiveDominancePoint().isUniversal() &&
              "Must be in entry block if we insert dynamic alloca's without "
              "stackrestores");
-  return {alloca, stackRestorePoint};
+  return {Address(alloca, align), stackRestorePoint};
 }
 
 /// Deallocate dynamic alloca's memory if requested by restoring the stack
 /// location before the dynamic alloca's call.
-void irgen::emitDeallocateDynamicAlloca(IRGenFunction &IGF,
-                                        StackAddress address) {
+void IRGenFunction::emitDeallocateDynamicAlloca(StackAddress address) {
   if (!address.needsSPRestore())
     return;
   auto *stackRestoreFn = llvm::Intrinsic::getDeclaration(
-      &IGF.IGM.Module, llvm::Intrinsic::ID::stackrestore);
-  IGF.Builder.CreateCall(stackRestoreFn, address.getSavedSP());
+      &IGM.Module, llvm::Intrinsic::ID::stackrestore);
+  Builder.CreateCall(stackRestoreFn, address.getSavedSP());
 }
 
 /// Emit a call to do an 'initializeArrayWithCopy' operation.
diff --git a/lib/IRGen/GenOpaque.h b/lib/IRGen/GenOpaque.h
index 3cda5ed..b20da8c 100644
--- a/lib/IRGen/GenOpaque.h
+++ b/lib/IRGen/GenOpaque.h
@@ -29,7 +29,6 @@
   class IRGenFunction;
   class IRGenModule;
   enum class ValueWitness : unsigned;
-  class StackAddress;
   class WitnessIndex;
 
   /// Return the size of a fixed buffer.
@@ -235,21 +234,6 @@
   /// The type must be dynamically known to have extra inhabitant witnesses.
   llvm::Value *emitLoadOfExtraInhabitantCount(IRGenFunction &IGF, SILType T);
 
-  /// Emit a dynamic alloca call to allocate enough memory to hold an object of
-  /// type 'T' and an optional llvm.stackrestore point if 'isInEntryBlock' is
-  /// false.
-  struct DynamicAlloca {
-    llvm::Value *Alloca;
-    llvm::Value *SavedSP;
-    DynamicAlloca(llvm::Value *A, llvm::Value *SP) : Alloca(A), SavedSP(SP) {}
-  };
-  DynamicAlloca emitDynamicAlloca(IRGenFunction &IGF, SILType T,
-                                  bool isInEntryBlock);
-
-  /// Deallocate dynamic alloca's memory if the stack address has an SP restore
-  /// point associated with it.
-  void emitDeallocateDynamicAlloca(IRGenFunction &IGF, StackAddress address);
-
   /// Returns the IsInline flag and the loaded flags value.
   std::pair<llvm::Value *, llvm::Value *>
   emitLoadOfIsInline(IRGenFunction &IGF, llvm::Value *metadata);
diff --git a/lib/IRGen/GenStruct.cpp b/lib/IRGen/GenStruct.cpp
index c120fcf..92db298 100644
--- a/lib/IRGen/GenStruct.cpp
+++ b/lib/IRGen/GenStruct.cpp
@@ -512,9 +512,9 @@
 
     void initializeMetadata(IRGenFunction &IGF,
                             llvm::Value *metadata,
-                            llvm::Value *vwtable,
+                            bool isVWTMutable,
                             SILType T) const override {
-      emitInitializeFieldOffsetVector(IGF, T, metadata, vwtable);
+      emitInitializeFieldOffsetVector(IGF, T, metadata, isVWTMutable);
     }
   };
 
diff --git a/lib/IRGen/GenTuple.cpp b/lib/IRGen/GenTuple.cpp
index 5b2e96a..470ff9e 100644
--- a/lib/IRGen/GenTuple.cpp
+++ b/lib/IRGen/GenTuple.cpp
@@ -343,7 +343,7 @@
 
     void initializeMetadata(IRGenFunction &IGF,
                             llvm::Value *metadata,
-                            llvm::Value *vwtable,
+                            bool isVWTMutable,
                             SILType T) const override {
       // Tuple value witness tables are instantiated by the runtime along with
       // their metadata. We should never try to initialize one in the compiler.
diff --git a/lib/IRGen/GenType.cpp b/lib/IRGen/GenType.cpp
index 1317565..1c0213e 100644
--- a/lib/IRGen/GenType.cpp
+++ b/lib/IRGen/GenType.cpp
@@ -346,7 +346,7 @@
 }
 
 static llvm::Value *computeExtraTagBytes(IRGenFunction &IGF, IRBuilder &Builder,
-                                         size_t fixedSize,
+                                         Size fixedSize,
                                          llvm::Value *numEmptyCases) {
   // We can use the payload area with a tag bit set somewhere outside of the
   // payload area to represent cases. See how many bytes we need to cover
@@ -371,12 +371,12 @@
   auto *int32Ty = IGM.Int32Ty;
 
   auto *one = llvm::ConstantInt::get(int32Ty, 1U);
-  if (fixedSize >= 4) {
+  if (fixedSize >= Size(4)) {
     return one;
   }
 
   auto *entryBB = Builder.GetInsertBlock();
-  llvm::Value *size = asSizeConstant(IGM, Size(fixedSize));
+  llvm::Value *size = asSizeConstant(IGM, fixedSize);
   auto *returnBB = llvm::BasicBlock::Create(Ctx);
   size = Builder.CreateTrunc(size, int32Ty); // We know size < 4.
 
@@ -418,7 +418,7 @@
   auto &Builder = IGF.Builder;
 
   auto *size = getSize(IGF, T);
-  auto fixedSize = getFixedSize().getValue();
+  Size fixedSize = getFixedSize();
   auto *numExtraInhabitants =
       llvm::ConstantInt::get(IGM.Int32Ty, getFixedExtraInhabitantCount(IGM));
 
@@ -444,8 +444,8 @@
 
   // There are extra tag bits to check.
   Builder.emitBlock(extraTagBitsBB);
-  llvm::Value *extraTagBits = Builder.CreateAlloca(IGM.Int32Ty, nullptr);
-  Builder.CreateStore(zero, extraTagBits, Alignment(0));
+  Address extraTagBitsSlot = IGF.createAlloca(IGM.Int32Ty, Alignment(4));
+  Builder.CreateStore(zero, extraTagBitsSlot);
 
   // Compute the number of extra tag bytes.
   auto *emptyCases = Builder.CreateSub(numEmptyCases, numExtraInhabitants);
@@ -456,13 +456,14 @@
   auto *valueAddr =
       Builder.CreateBitOrPointerCast(enumAddr.getAddress(), IGM.Int8PtrTy);
   auto *extraTagBitsAddr =
-      Builder.CreateConstInBoundsGEP1_32(IGM.Int8Ty, valueAddr, fixedSize);
+      Builder.CreateConstInBoundsGEP1_32(IGM.Int8Ty, valueAddr,
+                                         fixedSize.getValue());
 
   // TODO: big endian.
   Builder.CreateMemCpy(
-      Builder.CreateBitOrPointerCast(extraTagBits, IGM.Int8PtrTy),
+      Builder.CreateBitCast(extraTagBitsSlot, IGM.Int8PtrTy).getAddress(),
       extraTagBitsAddr, numExtraTagBytes, 1);
-  extraTagBits = Builder.CreateLoad(extraTagBits, Alignment(0));
+  auto extraTagBits = Builder.CreateLoad(extraTagBitsSlot);
 
   extraTagBitsBB = llvm::BasicBlock::Create(Ctx);
   Builder.CreateCondBr(Builder.CreateICmpEQ(extraTagBits, zero),
@@ -473,8 +474,8 @@
   Builder.emitBlock(extraTagBitsBB);
 
   auto *truncSize = Builder.CreateTrunc(size, IGM.Int32Ty);
-  llvm::Value *caseIndexFromValue = Builder.CreateAlloca(IGM.Int32Ty, nullptr);
-  Builder.CreateStore(zero, caseIndexFromValue, Alignment(0));
+  Address caseIndexFromValueSlot = IGF.createAlloca(IGM.Int32Ty, Alignment(4));
+  Builder.CreateStore(zero, caseIndexFromValueSlot);
 
   auto *caseIndexFromExtraTagBits = Builder.CreateSelect(
       Builder.CreateICmpUGE(truncSize, four), zero,
@@ -483,9 +484,10 @@
 
   // TODO: big endian.
   Builder.CreateMemCpy(
-      Builder.CreateBitOrPointerCast(caseIndexFromValue, IGM.Int8PtrTy),
-      valueAddr, std::min(Size(4U).getValue(), fixedSize), 1);
-  caseIndexFromValue = Builder.CreateLoad(caseIndexFromValue, Alignment(0));
+      Builder.CreateBitCast(caseIndexFromValueSlot, IGM.Int8PtrTy),
+      Address(valueAddr, Alignment(1)),
+      std::min(Size(4U), fixedSize));
+  auto caseIndexFromValue = Builder.CreateLoad(caseIndexFromValueSlot);
 
   auto *result1 = Builder.CreateAdd(
       numExtraInhabitants,
@@ -521,7 +523,7 @@
 /// Emit a speciaize memory operation for a \p size of 0 to 4 bytes.
 static void emitSpecializedMemOperation(
     IRGenFunction &IGF,
-    llvm::function_ref<void(IRBuilder &, uint64_t)> emitMemOpFn,
+    llvm::function_ref<void(IRBuilder &, Size)> emitMemOpFn,
     llvm::Value *size) {
   auto &IGM = IGF.IGM;
   auto &Ctx = IGF.IGM.getLLVMContext();
@@ -549,37 +551,37 @@
   Builder.CreateCondBr(isTwo, twoBB, fourBB);
 
   Builder.emitBlock(oneBB);
-  emitMemOpFn(Builder, 1);
+  emitMemOpFn(Builder, Size(1));
   Builder.CreateBr(returnBB);
 
   Builder.emitBlock(twoBB);
-  emitMemOpFn(Builder, 2);
+  emitMemOpFn(Builder, Size(2));
   Builder.CreateBr(returnBB);
 
   Builder.emitBlock(fourBB);
-  emitMemOpFn(Builder, 4);
+  emitMemOpFn(Builder, Size(4));
   Builder.CreateBr(returnBB);
 
   Builder.emitBlock(returnBB);
 }
 
 /// Emit a memset of zero operation for a \p size of 0 to 4 bytes.
-static void emitMemZero(IRGenFunction &IGF, llvm::Value *addr,
+static void emitMemZero(IRGenFunction &IGF, Address addr,
                         llvm::Value *size) {
   auto *zeroByte = llvm::ConstantInt::get(IGF.IGM.Int8Ty, 0U);
   emitSpecializedMemOperation(IGF,
-                              [=](IRBuilder &B, uint64_t numBytes) {
-                                B.CreateMemSet(addr, zeroByte, numBytes, 1);
+                              [=](IRBuilder &B, Size numBytes) {
+                                B.CreateMemSet(addr, zeroByte, numBytes);
                               },
                               size);
 }
 
 /// Emit a memcpy operation for a \p size of 0 to 4 bytes.
-static void emitMemCpy(IRGenFunction &IGF, llvm::Value *to, llvm::Value *from,
+static void emitMemCpy(IRGenFunction &IGF, Address to, Address from,
                        llvm::Value *size) {
   emitSpecializedMemOperation(IGF,
-                              [=](IRBuilder &B, uint64_t numBytes) {
-                                B.CreateMemCpy(to, from, numBytes, 1);
+                              [=](IRBuilder &B, Size numBytes) {
+                                B.CreateMemCpy(to, from, numBytes);
                               },
                               size);
 }
@@ -599,12 +601,11 @@
   auto *four = llvm::ConstantInt::get(int32Ty, 4U);
   auto *eight = llvm::ConstantInt::get(int32Ty, 8U);
 
-  auto fixedSize = getFixedSize().getValue();
+  auto fixedSize = getFixedSize();
 
-  auto *valueAddr =
-      Builder.CreateBitOrPointerCast(enumAddr.getAddress(), IGM.Int8PtrTy);
-  auto *extraTagBitsAddr =
-      Builder.CreateConstInBoundsGEP1_32(IGM.Int8Ty, valueAddr, fixedSize);
+  Address valueAddr = Builder.CreateElementBitCast(enumAddr, IGM.Int8Ty);
+  Address extraTagBitsAddr =
+    Builder.CreateConstByteArrayGEP(valueAddr, fixedSize);
 
   auto *numExtraInhabitants =
       llvm::ConstantInt::get(IGM.Int32Ty, getFixedExtraInhabitantCount(IGM));
@@ -685,21 +686,20 @@
   payloadIndex->addIncoming(caseIndex, payloadGE4BB);
   payloadIndex->addIncoming(payloadIndex0, payloadLT4BB);
 
-  auto *payloadIndexAddr = Builder.CreateAlloca(int32Ty, nullptr);
-  Builder.CreateStore(payloadIndex, payloadIndexAddr, Alignment(0));
-  auto *extraTagIndexAddr = Builder.CreateAlloca(int32Ty, nullptr);
-  Builder.CreateStore(extraTagIndex, extraTagIndexAddr, Alignment(0));
+  Address payloadIndexAddr = IGF.createAlloca(int32Ty, Alignment(4));
+  Builder.CreateStore(payloadIndex, payloadIndexAddr);
+  Address extraTagIndexAddr = IGF.createAlloca(int32Ty, Alignment(4));
+  Builder.CreateStore(extraTagIndex, extraTagIndexAddr);
   // TODO: big endian
   Builder.CreateMemCpy(
       valueAddr,
-      Builder.CreateBitOrPointerCast(payloadIndexAddr, IGM.Int8PtrTy),
-      std::min(Size(4U).getValue(), fixedSize), 1);
-  auto *extraZeroAddr =
-      Builder.CreateConstInBoundsGEP1_32(IGM.Int8Ty, valueAddr, 4);
-  if (fixedSize > 4)
+      Builder.CreateBitCast(payloadIndexAddr, IGM.Int8PtrTy),
+      std::min(Size(4U), fixedSize));
+  Address extraZeroAddr = Builder.CreateConstByteArrayGEP(valueAddr, Size(4));
+  if (fixedSize > Size(4))
     Builder.CreateMemSet(
         extraZeroAddr, llvm::ConstantInt::get(IGM.Int8Ty, 0),
-        Builder.CreateSub(size, llvm::ConstantInt::get(size->getType(), 4)), 1);
+        Builder.CreateSub(size, llvm::ConstantInt::get(size->getType(), 4)));
   emitMemCpy(IGF, extraTagBitsAddr, extraTagIndexAddr, numExtraTagBytes);
   Builder.CreateBr(returnBB);
 
diff --git a/lib/IRGen/GenValueWitness.cpp b/lib/IRGen/GenValueWitness.cpp
index 84247a4..c8cea57 100644
--- a/lib/IRGen/GenValueWitness.cpp
+++ b/lib/IRGen/GenValueWitness.cpp
@@ -1063,17 +1063,28 @@
 /// Emit a value-witness table for the given type, which is assumed to
 /// be non-dependent.
 llvm::Constant *irgen::emitValueWitnessTable(IRGenModule &IGM,
-                                             CanType abstractType) {
+                                             CanType abstractType,
+                                             bool isPattern) {
   // We shouldn't emit global value witness tables for generic type instances.
   assert(!isa<BoundGenericType>(abstractType) &&
          "emitting VWT for generic instance");
 
+  // We should never be making a pattern if the layout isn't fixed.
+  // The reverse can be true for types whose layout depends on
+  // resilient types.
+  assert((!isPattern || hasDependentValueWitnessTable(IGM, abstractType)) &&
+         "emitting VWT pattern for fixed-layout type");
+
   ConstantInitBuilder builder(IGM);
   auto witnesses = builder.beginArray(IGM.Int8PtrTy);
 
   bool canBeConstant = false;
   addValueWitnessesForAbstractType(IGM, witnesses, abstractType, canBeConstant);
 
+  // If this is just an instantiation pattern, we should never be modifying
+  // it in-place.
+  if (isPattern) canBeConstant = true;
+
   auto addr = IGM.getAddrOfValueWitnessTable(abstractType,
                                              witnesses.finishAndCreateFuture());
   auto global = cast<llvm::GlobalVariable>(addr);
@@ -1163,25 +1174,6 @@
   return layout;
 }
 
-/// Emit the elements of a dependent value witness table template into a
-/// vector.
-void irgen::emitDependentValueWitnessTablePattern(IRGenModule &IGM,
-                                                  ConstantStructBuilder &B,
-                                                  CanType abstractType) {
-  // We shouldn't emit global value witness tables for generic type instances.
-  assert(!isa<BoundGenericType>(abstractType) &&
-         "emitting VWT for generic instance");
-
-  // We shouldn't emit global value witness tables for fixed-layout types.
-  assert(hasDependentValueWitnessTable(IGM, abstractType) &&
-         "emitting VWT pattern for fixed-layout type");
-
-  bool canBeConstant = false;
-  auto witnesses = B.beginArray(IGM.Int8PtrTy);
-  addValueWitnessesForAbstractType(IGM, witnesses, abstractType, canBeConstant);
-  witnesses.finishAndAddTo(B);
-}
-
 FixedPacking TypeInfo::getFixedPacking(IRGenModule &IGM) const {
   auto fixedTI = dyn_cast<FixedTypeInfo>(this);
 
diff --git a/lib/IRGen/GenValueWitness.h b/lib/IRGen/GenValueWitness.h
index db435a7..f12ca5d 100644
--- a/lib/IRGen/GenValueWitness.h
+++ b/lib/IRGen/GenValueWitness.h
@@ -37,16 +37,13 @@
   /// dependent on its generic parameters.
   bool hasDependentValueWitnessTable(IRGenModule &IGM, CanType ty);
 
-  /// Emit a value-witness table for the given type, which is assumed
-  /// to be non-dependent.
-  llvm::Constant *emitValueWitnessTable(IRGenModule &IGM, CanType type);
-
-  /// Emit the elements of a dependent value witness table template into a
-  /// vector.
-  void emitDependentValueWitnessTablePattern(IRGenModule &IGM,
-                                             ConstantStructBuilder &B,
-                                             CanType abstractType);
-
+  /// Emit a value-witness table for the given type.
+  ///
+  /// \param isPattern - true if the table just serves as an instantiation
+  ///   pattern and does not need to be modifiable in-place (if the type
+  ///   does not have static layout for some reason)
+  llvm::Constant *emitValueWitnessTable(IRGenModule &IGM, CanType type,
+                                        bool isPattern);
 }
 }
 
diff --git a/lib/IRGen/IRBuilder.h b/lib/IRGen/IRBuilder.h
index 8b17048..43e65d8 100644
--- a/lib/IRGen/IRBuilder.h
+++ b/lib/IRGen/IRBuilder.h
@@ -31,10 +31,12 @@
 typedef llvm::IRBuilder<> IRBuilderBase;
 
 class IRBuilder : public IRBuilderBase {
+public:
   // Without this, it keeps resolving to llvm::IRBuilderBase because
   // of the injected class name.
   typedef irgen::IRBuilderBase IRBuilderBase;
 
+private:
   /// The block containing the insertion point when the insertion
   /// point was last cleared.  Used only for preserving block
   /// ordering.
@@ -161,6 +163,11 @@
     return StableIP(*this);
   }
 
+  /// Don't create allocas this way; you'll get a dynamic alloca.
+  /// Use IGF::createAlloca or IGF::emitDynamicAlloca.
+  llvm::Value *CreateAlloca(llvm::Type *type, llvm::Value *arraySize,
+                            const llvm::Twine &name = "") = delete;
+
   llvm::LoadInst *CreateLoad(llvm::Value *addr, Alignment align,
                              const llvm::Twine &name = "") {
     llvm::LoadInst *load = IRBuilderBase::CreateLoad(addr, name);
@@ -252,6 +259,17 @@
                         std::min(dest.getAlignment(),
                                  src.getAlignment()).getValue());
   }
+
+  using IRBuilderBase::CreateMemSet;
+  llvm::CallInst *CreateMemSet(Address dest, llvm::Value *value, Size size) {
+    return CreateMemSet(dest.getAddress(), value, size.getValue(),
+                        dest.getAlignment().getValue());
+  }
+  llvm::CallInst *CreateMemSet(Address dest, llvm::Value *value,
+                               llvm::Value *size) {
+    return CreateMemSet(dest.getAddress(), value, size,
+                        dest.getAlignment().getValue());
+  }
   
   using IRBuilderBase::CreateLifetimeStart;
   llvm::CallInst *CreateLifetimeStart(Address buf, Size size) {
diff --git a/lib/IRGen/IRGen.cpp b/lib/IRGen/IRGen.cpp
index ec76528..9e2b18f 100644
--- a/lib/IRGen/IRGen.cpp
+++ b/lib/IRGen/IRGen.cpp
@@ -1066,10 +1066,10 @@
                     std::unique_ptr<SILModule> SILMod,
                     StringRef ModuleName, llvm::LLVMContext &LLVMContext,
                     llvm::GlobalVariable **outModuleHash) {
-  int numThreads = SILMod->getOptions().NumThreads;
-  if (numThreads != 0) {
-    ::performParallelIRGeneration(Opts, M, std::move(SILMod),
-                                  ModuleName, numThreads);
+  if (SILMod->getOptions().shouldPerformIRGenerationInParallel()) {
+    auto NumThreads = SILMod->getOptions().NumThreads;
+    ::performParallelIRGeneration(Opts, M, std::move(SILMod), ModuleName,
+                                  NumThreads);
     // TODO: Parallel LLVM compilation cannot be used if a (single) module is
     // needed as return value.
     return nullptr;
diff --git a/lib/IRGen/IRGenFunction.h b/lib/IRGen/IRGenFunction.h
index 72fa6ce..d28a7f2 100644
--- a/lib/IRGen/IRGenFunction.h
+++ b/lib/IRGen/IRGenFunction.h
@@ -127,11 +127,17 @@
   }
 
   Address createAlloca(llvm::Type *ty, Alignment align,
-                       const llvm::Twine &name);
-  Address createAlloca(llvm::Type *ty, llvm::Value *ArraySize, Alignment align,
-                       const llvm::Twine &name);
+                       const llvm::Twine &name = "");
+  Address createAlloca(llvm::Type *ty, llvm::Value *arraySize, Alignment align,
+                       const llvm::Twine &name = "");
   Address createFixedSizeBufferAlloca(const llvm::Twine &name);
 
+  StackAddress emitDynamicAlloca(SILType type, const llvm::Twine &name = "");
+  StackAddress emitDynamicAlloca(llvm::Type *eltTy, llvm::Value *arraySize,
+                                 Alignment align,
+                                 const llvm::Twine &name = "");
+  void emitDeallocateDynamicAlloca(StackAddress address);
+
   llvm::BasicBlock *createBasicBlock(const llvm::Twine &Name);
   const TypeInfo &getTypeInfoForUnlowered(Type subst);
   const TypeInfo &getTypeInfoForUnlowered(AbstractionPattern orig, Type subst);
diff --git a/lib/IRGen/IRGenModule.cpp b/lib/IRGen/IRGenModule.cpp
index bbf67c7..3da9183 100644
--- a/lib/IRGen/IRGenModule.cpp
+++ b/lib/IRGen/IRGenModule.cpp
@@ -397,8 +397,7 @@
   else
     RegisterPreservingCC = DefaultCC;
 
-  SwiftCC = SWIFT_LLVM_CC(SwiftCC);
-  UseSwiftCC = (SwiftCC == llvm::CallingConv::Swift);
+  SwiftCC = llvm::CallingConv::Swift;
 
   if (IRGen.Opts.DebugInfoKind > IRGenDebugInfoKind::None)
     DebugInfo = IRGenDebugInfo::createIRGenDebugInfo(IRGen.Opts, *CI, *this,
diff --git a/lib/IRGen/IRGenModule.h b/lib/IRGen/IRGenModule.h
index 808b3e7..73ef85b 100644
--- a/lib/IRGen/IRGenModule.h
+++ b/lib/IRGen/IRGenModule.h
@@ -509,7 +509,6 @@
   llvm::CallingConv::ID DefaultCC;     /// default calling convention
   llvm::CallingConv::ID RegisterPreservingCC; /// lightweight calling convention
   llvm::CallingConv::ID SwiftCC;     /// swift calling convention
-  bool UseSwiftCC;
 
   Signature getAssociatedTypeMetadataAccessFunctionSignature();
   Signature getAssociatedTypeWitnessTableAccessFunctionSignature();
diff --git a/lib/IRGen/IRGenSIL.cpp b/lib/IRGen/IRGenSIL.cpp
index 8103061..d91674d 100644
--- a/lib/IRGen/IRGenSIL.cpp
+++ b/lib/IRGen/IRGenSIL.cpp
@@ -2106,16 +2106,21 @@
 }
 
 void IRGenSILFunction::visitBuiltinInst(swift::BuiltinInst *i) {
+  const BuiltinInfo &builtin = getSILModule().getBuiltinInfo(i->getName());
+
   auto argValues = i->getArguments();
   Explosion args;
-  for (auto argValue : argValues) {
+
+  for (auto idx : indices(argValues)) {
+    auto argValue = argValues[idx];
+
     // Builtin arguments should never be substituted, so use the value's type
     // as the parameter type.
     emitApplyArgument(*this, argValue, argValue->getType(), args);
   }
   
   Explosion result;
-  emitBuiltinCall(*this, i->getName(), i->getType(),
+  emitBuiltinCall(*this, builtin, i->getName(), i->getType(),
                   args, result, i->getSubstitutions());
   
   setLoweredExplosion(i, result);
@@ -3751,9 +3756,7 @@
 
   (void) Decl;
 
-  bool isEntryBlock = (i->getParent() == i->getFunction()->getEntryBlock());
-  auto addr =
-      type.allocateStack(*this, i->getElementType(), isEntryBlock, dbgname);
+  auto addr = type.allocateStack(*this, i->getElementType(), dbgname);
 
   emitDebugInfoForAllocStack(i, type, addr.getAddress().getAddress());
   
@@ -4656,6 +4659,7 @@
 void IRGenSILFunction::visitKeyPathInst(swift::KeyPathInst *I) {
   auto pattern = IGM.getAddrOfKeyPathPattern(I->getPattern(), I->getLoc());
   // Build up the argument vector to instantiate the pattern here.
+  Optional<StackAddress> dynamicArgsBuf;
   llvm::Value *args;
   if (!I->getSubstitutions().empty() || !I->getAllOperands().empty()) {
     auto sig = I->getPattern()->getGenericSignature();
@@ -4697,11 +4701,9 @@
       argsBufAlign = Builder.CreateOr(argsBufAlign, alignMask);
     }
 
-    auto argsBufInst = Builder.CreateAlloca(IGM.Int8Ty, argsBufSize);
-    // TODO: over-alignment?
-    argsBufInst->setAlignment(16);
+    dynamicArgsBuf = emitDynamicAlloca(IGM.Int8Ty, argsBufSize, Alignment(16));
     
-    Address argsBuf(argsBufInst, Alignment(16));
+    Address argsBuf = dynamicArgsBuf->getAddress();
     
     if (!I->getSubstitutions().empty()) {
       emitInitOfGenericRequirementsBuffer(*this, requirements, argsBuf,
@@ -4715,7 +4717,8 @@
     for (unsigned i : indices(I->getAllOperands())) {
       auto operand = I->getAllOperands()[i].get();
       auto &ti = getTypeInfo(operand->getType());
-      auto ptr = Builder.CreateInBoundsGEP(argsBufInst, operandOffsets[i]);
+      auto ptr = Builder.CreateInBoundsGEP(argsBuf.getAddress(),
+                                           operandOffsets[i]);
       auto addr = ti.getAddressForPointer(
         Builder.CreateBitCast(ptr, ti.getStorageType()->getPointerTo()));
       if (operand->getType().isAddress()) {
@@ -4726,7 +4729,7 @@
         cast<LoadableTypeInfo>(ti).initialize(*this, operandValue, addr, false);
       }
     }
-    args = argsBufInst;
+    args = argsBuf.getAddress();
   } else {
     // No arguments necessary, so the argument ought to be ignored by any
     // callbacks in the pattern.
@@ -4737,6 +4740,10 @@
   auto call = Builder.CreateCall(IGM.getGetKeyPathFn(), {patternPtr, args});
   call->setDoesNotThrow();
 
+  if (dynamicArgsBuf) {
+    emitDeallocateDynamicAlloca(*dynamicArgsBuf);
+  }
+
   auto resultStorageTy = IGM.getTypeInfo(I->getType()).getStorageType();
 
   Explosion e;
diff --git a/lib/IRGen/LoadableByAddress.cpp b/lib/IRGen/LoadableByAddress.cpp
index 1249362..5ad86c3 100644
--- a/lib/IRGen/LoadableByAddress.cpp
+++ b/lib/IRGen/LoadableByAddress.cpp
@@ -28,8 +28,7 @@
 #include "swift/SIL/SILBuilder.h"
 #include "swift/SILOptimizer/PassManager/Transforms.h"
 #include "swift/SILOptimizer/Utils/Local.h"
-#include "llvm/ADT/DenseMap.h"
-#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/MapVector.h"
 #include "llvm/ADT/SetVector.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
@@ -349,11 +348,11 @@
   // All modified function signature function arguments
   SmallVector<SILValue, 16> funcSigArgs;
   // All args for which we did a load
-  llvm::DenseMap<SILValue, SILValue> argsToLoadedValueMap;
+  llvm::MapVector<SILValue, SILValue> argsToLoadedValueMap;
   // All applies for which we did an alloc
-  llvm::DenseMap<SILInstruction *, SILValue> applyRetToAllocMap;
+  llvm::MapVector<SILInstruction *, SILValue> applyRetToAllocMap;
   // recerse map of the one above
-  llvm::DenseMap<SILInstruction *, SILInstruction*> allocToApplyRetMap;
+  llvm::MapVector<SILInstruction *, SILInstruction *> allocToApplyRetMap;
   // All call sites with SILArgument that needs to be re-written
   // Calls are removed from the set when rewritten.
   SmallVector<SILInstruction *, 16> applies;
@@ -1438,8 +1437,8 @@
   llvm::SetVector<UncheckedTakeEnumDataAddrInst *>
       uncheckedTakeEnumDataAddrOfFunc;
   llvm::SetVector<StoreInst *> storeToBlockStorageInstrs;
-  llvm::DenseSet<SILInstruction *> modApplies;
-  llvm::DenseMap<SILInstruction *, SILValue> allApplyRetToAllocMap;
+  llvm::SetVector<SILInstruction *> modApplies;
+  llvm::MapVector<SILInstruction *, SILValue> allApplyRetToAllocMap;
 };
 } // end anonymous namespace
 
@@ -1673,7 +1672,7 @@
     genEnv = getGenericEnvironment(pass.F->getModule(), loweredTy);
   }
   bool repeat = false;
-  llvm::DenseSet<SILInstruction *> currentModApplies;
+  llvm::SetVector<SILInstruction *> currentModApplies;
   do {
     while (!pass.switchEnumInstsToMod.empty()) {
       auto *instr = pass.switchEnumInstsToMod.pop_back_val();
@@ -2149,8 +2148,9 @@
     modApplies.insert(pass.applies.begin(), pass.applies.end());
   }
   if (!pass.applyRetToAllocMap.empty()) {
-    allApplyRetToAllocMap.insert(pass.applyRetToAllocMap.begin(),
-                                 pass.applyRetToAllocMap.end());
+    for (auto elm : pass.applyRetToAllocMap) {
+      allApplyRetToAllocMap.insert(elm);
+    }
   }
 }
 
@@ -2215,9 +2215,8 @@
     // We need to re-create the callee's apply before recreating this one
     // else verification will fail with wrong SubstCalleeType
     auto calleInstr = site.getInstruction();
-    if (modApplies.find(calleInstr) != modApplies.end()) {
+    if (modApplies.remove(calleInstr)) {
       recreateSingleApply(calleInstr);
-      modApplies.erase(calleInstr);
       callee = applySite.getCallee();
     }
   }
@@ -2297,9 +2296,8 @@
 
 void LoadableByAddress::recreateApplies() {
   while (!modApplies.empty()) {
-    auto *applyInst = *modApplies.begin();
+    auto *applyInst = modApplies.pop_back_val();
     recreateSingleApply(applyInst);
-    modApplies.erase(applyInst);
   }
 }
 
diff --git a/lib/IRGen/MetadataLayout.cpp b/lib/IRGen/MetadataLayout.cpp
index 1841895..e3da15c 100644
--- a/lib/IRGen/MetadataLayout.cpp
+++ b/lib/IRGen/MetadataLayout.cpp
@@ -203,7 +203,7 @@
 /********************************** CLASSES ***********************************/
 
 ClassMetadataLayout::ClassMetadataLayout(IRGenModule &IGM, ClassDecl *decl)
-    : NominalMetadataLayout(Kind::Class), NumImmediateMembers(0) {
+    : NominalMetadataLayout(Kind::Class, decl), NumImmediateMembers(0) {
 
   struct Scanner : LayoutScanner<Scanner, ClassMetadataScanner> {
     using super = LayoutScanner;
@@ -212,6 +212,15 @@
     Scanner(IRGenModule &IGM, ClassDecl *decl, ClassMetadataLayout &layout)
       : super(IGM, decl), Layout(layout) {}
 
+    void noteResilientSuperclass() {}
+
+    void noteStartOfImmediateMembers(ClassDecl *theClass) {}
+
+    void addClassSize() {
+      Layout.MetadataSize = getNextOffset();
+      super::addClassSize();
+    }
+
     void addInstanceSize() {
       Layout.InstanceSize = getNextOffset();
       super::addInstanceSize();
@@ -288,6 +297,11 @@
   Scanner(IGM, decl, *this).layout();
 }
 
+Size ClassMetadataLayout::getMetadataSizeOffset() const {
+  assert(MetadataSize.isStatic());
+  return MetadataSize.getStaticOffset();
+}
+
 Size ClassMetadataLayout::getInstanceSizeOffset() const {
   assert(InstanceSize.isStatic());
   return InstanceSize.getStaticOffset();
@@ -387,7 +401,7 @@
 /*********************************** ENUMS ************************************/
 
 EnumMetadataLayout::EnumMetadataLayout(IRGenModule &IGM, EnumDecl *decl)
-    : NominalMetadataLayout(Kind::Enum) {
+    : NominalMetadataLayout(Kind::Enum, decl) {
 
   struct Scanner : LayoutScanner<Scanner, EnumMetadataScanner> {
     using super = LayoutScanner;
@@ -424,7 +438,7 @@
 /********************************** STRUCTS ***********************************/
 
 StructMetadataLayout::StructMetadataLayout(IRGenModule &IGM, StructDecl *decl)
-    : NominalMetadataLayout(Kind::Struct) {
+    : NominalMetadataLayout(Kind::Struct, decl) {
 
   struct Scanner : LayoutScanner<Scanner, StructMetadataScanner> {
     using super = LayoutScanner;
diff --git a/lib/IRGen/MetadataLayout.h b/lib/IRGen/MetadataLayout.h
index 2df5f64..b1d715c 100644
--- a/lib/IRGen/MetadataLayout.h
+++ b/lib/IRGen/MetadataLayout.h
@@ -119,11 +119,17 @@
 /// Base class for nominal type metadata layouts.
 class NominalMetadataLayout : public MetadataLayout {
 protected:
+  NominalTypeDecl *Nominal;
   StoredOffset GenericRequirements;
 
-  NominalMetadataLayout(Kind kind) : MetadataLayout(kind) {}
+  NominalMetadataLayout(Kind kind, NominalTypeDecl *nominal)
+      : MetadataLayout(kind), Nominal(nominal) {}
 
 public:
+  NominalTypeDecl *getDecl() const {
+    return Nominal;
+  }
+
   bool hasGenericRequirements() const {
     return GenericRequirements.isValid();
   }
@@ -150,6 +156,8 @@
   };
 
 private:
+  StoredOffset MetadataSize;
+
   StoredOffset InstanceSize;
   StoredOffset InstanceAlignMask;
 
@@ -187,6 +195,12 @@
   ClassMetadataLayout(IRGenModule &IGM, ClassDecl *theClass);
 
 public:
+  ClassDecl *getDecl() const {
+    return cast<ClassDecl>(Nominal);
+  }
+
+  Size getMetadataSizeOffset() const;
+
   Size getInstanceSizeOffset() const;
 
   Size getInstanceAlignMaskOffset() const;
@@ -249,6 +263,10 @@
   EnumMetadataLayout(IRGenModule &IGM, EnumDecl *theEnum);
 
 public:
+  EnumDecl *getDecl() const {
+    return cast<EnumDecl>(Nominal);
+  }
+
   bool hasPayloadSizeOffset() const {
     return PayloadSizeOffset.isValid();
   }
@@ -277,6 +295,9 @@
   StructMetadataLayout(IRGenModule &IGM, StructDecl *theStruct);
 
 public:
+  StructDecl *getDecl() const {
+    return cast<StructDecl>(Nominal);
+  }
 
   Offset getFieldOffset(IRGenFunction &IGF, VarDecl *field) const;
 
diff --git a/lib/IRGen/NativeConventionSchema.h b/lib/IRGen/NativeConventionSchema.h
index 135a747..218786c 100644
--- a/lib/IRGen/NativeConventionSchema.h
+++ b/lib/IRGen/NativeConventionSchema.h
@@ -26,13 +26,14 @@
 namespace swift {
 namespace irgen {
 
+using SwiftAggLowering = clang::CodeGen::swiftcall::SwiftAggLowering;
+
 class NativeConventionSchema {
-  clang::CodeGen::swiftcall::SwiftAggLowering Lowering;
+  SwiftAggLowering Lowering;
   bool RequiresIndirect;
 
 public:
-  using EnumerationCallback =
-      clang::CodeGen::swiftcall::SwiftAggLowering::EnumerationCallback;
+  using EnumerationCallback = SwiftAggLowering::EnumerationCallback;
 
   NativeConventionSchema(IRGenModule &IGM, const TypeInfo *TI, bool isResult);
 
diff --git a/lib/IRGen/NonFixedTypeInfo.h b/lib/IRGen/NonFixedTypeInfo.h
index 0ae4ef6..c7d78ea 100644
--- a/lib/IRGen/NonFixedTypeInfo.h
+++ b/lib/IRGen/NonFixedTypeInfo.h
@@ -68,24 +68,19 @@
   // This is useful for metaprogramming.
   static bool isFixed() { return false; }
 
-  StackAddress allocateStack(IRGenFunction &IGF,
-                                 SILType T,
-                                 bool isInEntryBlock,
-                                 const llvm::Twine &name) const override {
+  StackAddress allocateStack(IRGenFunction &IGF, SILType T,
+                             const llvm::Twine &name) const override {
     // Allocate memory on the stack.
-    auto alloca = emitDynamicAlloca(IGF, T, isInEntryBlock);
-    assert((isInEntryBlock && alloca.SavedSP == nullptr) ||
-           (!isInEntryBlock && alloca.SavedSP != nullptr) &&
-               "stacksave/restore operations can only be skipped in the entry "
-               "block");
-    IGF.Builder.CreateLifetimeStart(alloca.Alloca);
-    return { getAsBitCastAddress(IGF, alloca.Alloca), alloca.SavedSP };
+    auto alloca = IGF.emitDynamicAlloca(T, name);
+    IGF.Builder.CreateLifetimeStart(alloca.getAddressPointer());
+    return alloca.withAddress(
+             getAsBitCastAddress(IGF, alloca.getAddressPointer()));
   }
 
   void deallocateStack(IRGenFunction &IGF, StackAddress stackAddress,
                        SILType T) const override {
     IGF.Builder.CreateLifetimeEnd(stackAddress.getAddress().getAddress());
-    emitDeallocateDynamicAlloca(IGF, stackAddress);
+    IGF.emitDeallocateDynamicAlloca(stackAddress);
   }
 
   void destroyStack(IRGenFunction &IGF, StackAddress stackAddress, SILType T,
diff --git a/lib/IRGen/ResilientTypeInfo.h b/lib/IRGen/ResilientTypeInfo.h
index 7edc2d9..0cd02c1 100644
--- a/lib/IRGen/ResilientTypeInfo.h
+++ b/lib/IRGen/ResilientTypeInfo.h
@@ -157,7 +157,7 @@
 
   void initializeMetadata(IRGenFunction &IGF,
                           llvm::Value *metadata,
-                          llvm::Value *vwtable,
+                          bool isVWTMutable,
                           SILType T) const override {
     // Resilient value types and archetypes always refer to an existing type.
     // A witness table should never be independently initialized for one.
diff --git a/lib/IRGen/TypeInfo.h b/lib/IRGen/TypeInfo.h
index e2b6288..907bb89 100644
--- a/lib/IRGen/TypeInfo.h
+++ b/lib/IRGen/TypeInfo.h
@@ -261,7 +261,6 @@
 
   /// Allocate a variable of this type on the stack.
   virtual StackAddress allocateStack(IRGenFunction &IGF, SILType T,
-                                     bool isInEntryBlock,
                                      const llvm::Twine &name) const = 0;
 
   /// Deallocate a variable of this type.
@@ -393,7 +392,7 @@
   /// for fixed-size types.
   virtual void initializeMetadata(IRGenFunction &IGF,
                                   llvm::Value *metadata,
-                                  llvm::Value *vwtable,
+                                  bool isVWTMutable,
                                   SILType T) const = 0;
 
   /// Get the tag of a single payload enum with a payload of this type (\p T) e.g
diff --git a/lib/LLVMPasses/LLVMMergeFunctions.cpp b/lib/LLVMPasses/LLVMMergeFunctions.cpp
index 54664d1..486ff71 100644
--- a/lib/LLVMPasses/LLVMMergeFunctions.cpp
+++ b/lib/LLVMPasses/LLVMMergeFunctions.cpp
@@ -75,7 +75,7 @@
     "swiftmergefunc-threshold",
     cl::desc("Functions larger than the threshold are considered for merging."
              "'0' disables function merging at all."),
-    cl::init(30), cl::Hidden);
+    cl::init(15), cl::Hidden);
 
 namespace {
 
diff --git a/lib/Migrator/Migrator.cpp b/lib/Migrator/Migrator.cpp
index 654721c..5b1f187 100644
--- a/lib/Migrator/Migrator.cpp
+++ b/lib/Migrator/Migrator.cpp
@@ -118,7 +118,7 @@
     llvm::MemoryBuffer::getMemBufferCopy(InputText, getInputFilename());
 
   CompilerInvocation Invocation { StartInvocation };
-  Invocation.clearInputs();
+  Invocation.getFrontendOptions().Inputs.clearInputs();
   Invocation.getLangOptions().EffectiveLanguageVersion = SwiftLanguageVersion;
   auto &LLVMArgs = Invocation.getFrontendOptions().LLVMArgs;
   auto aarch64_use_tbi = std::find(LLVMArgs.begin(), LLVMArgs.end(),
@@ -144,24 +144,14 @@
 
   const auto &OrigFrontendOpts = StartInvocation.getFrontendOptions();
 
-  auto InputBuffers = OrigFrontendOpts.Inputs.getInputBuffers();
-  auto InputFilenames = OrigFrontendOpts.Inputs.getInputFilenames();
-
-  for (const auto &Buffer : InputBuffers) {
-    Invocation.addInputBuffer(Buffer);
+  assert(OrigFrontendOpts.Inputs.hasPrimaryInputs() &&
+         "Migration must have a primary");
+  for (const auto &input : OrigFrontendOpts.Inputs.getAllFiles()) {
+    Invocation.getFrontendOptions().Inputs.addInput(
+        InputFile(input.file(), input.isPrimary(),
+                  input.isPrimary() ? InputBuffer.get() : input.buffer()));
   }
 
-  for (const auto &Filename : InputFilenames) {
-    Invocation.addInputFilename(Filename);
-  }
-
-  const unsigned PrimaryIndex =
-      Invocation.getFrontendOptions().Inputs.getInputBuffers().size();
-
-  Invocation.addInputBuffer(InputBuffer.get());
-  Invocation.getFrontendOptions().Inputs.setPrimaryInput(
-      {PrimaryIndex, SelectedInput::InputKind::Buffer});
-
   auto Instance = llvm::make_unique<swift::CompilerInstance>();
   if (Instance->setup(Invocation)) {
     return nullptr;
@@ -447,8 +437,7 @@
 }
 
 const StringRef Migrator::getInputFilename() const {
-  auto PrimaryInput = StartInvocation.getFrontendOptions()
-                          .Inputs.getRequiredUniquePrimaryInput();
-  return StartInvocation.getFrontendOptions()
-      .Inputs.getInputFilenames()[PrimaryInput.Index];
+  auto &PrimaryInput = StartInvocation.getFrontendOptions()
+                           .Inputs.getRequiredUniquePrimaryInput();
+  return PrimaryInput.file();
 }
diff --git a/lib/Migrator/overlay.json b/lib/Migrator/overlay.json
index 57877a8..3f6b069 100644
--- a/lib/Migrator/overlay.json
+++ b/lib/Migrator/overlay.json
@@ -112,22 +112,22 @@
   },
   {
     "DiffItemKind": "SpecialCaseDiffItem",
-    "Usr": "s:12CoreGraphics7CGFloatV3absA2CFZ",
+    "Usr": "s:12CoreGraphics7CGFloatV3absyA2CFZ",
     "SpecialCaseId": "StaticAbsToSwiftAbs"
   },
   {
     "DiffItemKind": "SpecialCaseDiffItem",
-    "Usr": "s:Sf3absS2fFZ",
+    "Usr": "s:Sf3absyS2fFZ",
     "SpecialCaseId": "StaticAbsToSwiftAbs"
   },
   {
     "DiffItemKind": "SpecialCaseDiffItem",
-    "Usr": "s:s7Float80V3absA2BFZ",
+    "Usr": "s:s7Float80V3absyA2BFZ",
     "SpecialCaseId": "StaticAbsToSwiftAbs"
   },
   {
     "DiffItemKind": "SpecialCaseDiffItem",
-    "Usr": "s:Sd3absS2dFZ",
+    "Usr": "s:Sd3absyS2dFZ",
     "SpecialCaseId": "StaticAbsToSwiftAbs"
   },
   {
diff --git a/lib/Parse/Lexer.cpp b/lib/Parse/Lexer.cpp
index 14f843c..92c478d 100644
--- a/lib/Parse/Lexer.cpp
+++ b/lib/Parse/Lexer.cpp
@@ -191,6 +191,7 @@
   // Since the UTF-8 BOM doesn't carry information (UTF-8 has no dependency
   // on byte order), throw it away.
   CurPtr = BufferStart + BOMLength;
+  ContentStart = BufferStart + BOMLength;
 
   // Initialize code completion.
   if (BufferID == SM.getCodeCompletionBufferID()) {
@@ -274,7 +275,7 @@
   const char *Ptr = getBufferPtrForSourceLoc(Loc);
   // Skip whitespace backwards until we hit a newline.  This is needed to
   // correctly lex the token if it is at the beginning of the line.
-  while (Ptr >= BufferStart + 1) {
+  while (Ptr >= ContentStart + 1) {
     char C = Ptr[-1];
     if (C == ' ' || C == '\t') {
       Ptr--;
@@ -314,43 +315,16 @@
       .fixItRemoveChars(NulLoc, NulEndLoc);
 }
 
-void Lexer::skipUpToEndOfLine() {
-  while (1) {
-    switch (*CurPtr) {
-      case '\n':
-      case '\r':
-        return;
-      default:
-        // If this is a "high" UTF-8 character, validate it.
-        if (*reinterpret_cast<const signed char *>(CurPtr) < 0) {
-          const char *CharStart = CurPtr;
-          if (validateUTF8CharacterAndAdvance(CurPtr, BufferEnd) == ~0U)
-            diagnose(CharStart, diag::lex_invalid_utf8);
-          else
-            continue;
-        }
-        break;   // Otherwise, eat other characters.
-      case 0:
-        // If this is a random nul character in the middle of a buffer, skip it as
-        // whitespace.
-        if (CurPtr != BufferEnd) {
-          diagnoseEmbeddedNul(Diags, CurPtr);
-          break;
-        }
-
-        // Otherwise, the last line of the file does not have a newline.
-        return;
-    }
-    ++CurPtr;
-  }
-}
-
-void Lexer::skipToEndOfLine() {
+void Lexer::skipToEndOfLine(bool EatNewline) {
   while (1) {
     switch (*CurPtr++) {
     case '\n':
     case '\r':
-      NextToken.setAtStartOfLine(true);
+      if (EatNewline) {
+        NextToken.setAtStartOfLine(true);
+      } else {
+        --CurPtr;
+      }
       return;  // If we found the end of the line, return.
     default:
       // If this is a "high" UTF-8 character, validate it.
@@ -376,15 +350,15 @@
   }
 }
 
-void Lexer::skipSlashSlashComment() {
+void Lexer::skipSlashSlashComment(bool EatNewline) {
   assert(CurPtr[-1] == '/' && CurPtr[0] == '/' && "Not a // comment");
-  skipToEndOfLine();
+  skipToEndOfLine(EatNewline);
 }
 
-void Lexer::skipHashbang() {
-  assert(CurPtr == BufferStart && CurPtr[0] == '#' && CurPtr[1] == '!' &&
+void Lexer::skipHashbang(bool EatNewline) {
+  assert(CurPtr == ContentStart && CurPtr[0] == '#' && CurPtr[1] == '!' &&
          "Not a hashbang");
-  skipToEndOfLine();
+  skipToEndOfLine(EatNewline);
 }
 
 /// skipSlashStarComment - /**/ comments are skipped (treated as whitespace).
@@ -629,11 +603,11 @@
   }
   
   // Allow a hashbang #! line at the beginning of the file.
-  if (CurPtr - 1 == BufferStart && *CurPtr == '!') {
+  if (CurPtr - 1 == ContentStart && *CurPtr == '!') {
     CurPtr--;
     if (BufferID != SourceMgr.getHashbangBufferID())
       diagnose(CurPtr, diag::lex_hashbang_not_allowed);
-    skipHashbang();
+    skipHashbang(/*EatNewline=*/true);
     return lexImpl();
   }
 
@@ -773,7 +747,7 @@
   // Decide between the binary, prefix, and postfix cases.
   // It's binary if either both sides are bound or both sides are not bound.
   // Otherwise, it's postfix if left-bound and prefix if right-bound.
-  bool leftBound = isLeftBound(TokStart, BufferStart);
+  bool leftBound = isLeftBound(TokStart, ContentStart);
   bool rightBound = isRightBound(CurPtr, leftBound, CodeCompletionPtr);
 
   // Match various reserved words.
@@ -1839,11 +1813,11 @@
   return nullptr;
 }
 
-bool Lexer::tryLexConflictMarker() {
+bool Lexer::tryLexConflictMarker(bool EatNewline) {
   const char *Ptr = CurPtr - 1;
 
   // Only a conflict marker if it starts at the beginning of a line.
-  if (Ptr != BufferStart && Ptr[-1] != '\n' && Ptr[-1] != '\r')
+  if (Ptr != ContentStart && Ptr[-1] != '\n' && Ptr[-1] != '\r')
     return false;
   
   // Check to see if we have <<<<<<< or >>>>.
@@ -1860,7 +1834,7 @@
     
     // Skip ahead to the end of the marker.
     if (CurPtr != BufferEnd)
-      skipToEndOfLine();
+      skipToEndOfLine(EatNewline);
     
     return true;
   }
@@ -2062,7 +2036,7 @@
     LeadingTrivia.clear();
     TrailingTrivia.clear();
   }
-  NextToken.setAtStartOfLine(CurPtr == BufferStart);
+  NextToken.setAtStartOfLine(CurPtr == ContentStart);
 
   // Remember where we started so that we can find the comment range.
   LastCommentBlockStart = CurPtr;
@@ -2209,7 +2183,7 @@
       // Operator characters.
   case '/':
     if (CurPtr[0] == '/') {  // "//"
-      skipSlashSlashComment();
+      skipSlashSlashComment(/*EatNewline=*/true);
       SeenComment = true;
       if (isKeepingComments())
         return formToken(tok::comment, TokStart);
@@ -2237,24 +2211,24 @@
   case '!':
     if (InSILBody)
       return formToken(tok::sil_exclamation, TokStart);
-    if (isLeftBound(TokStart, BufferStart))
+    if (isLeftBound(TokStart, ContentStart))
       return formToken(tok::exclaim_postfix, TokStart);
     return lexOperatorIdentifier();
   
   case '?':
-    if (isLeftBound(TokStart, BufferStart))
+    if (isLeftBound(TokStart, ContentStart))
       return formToken(tok::question_postfix, TokStart);
     return lexOperatorIdentifier();
 
   case '<':
     if (CurPtr[0] == '#')
       return tryLexEditorPlaceholder();
-    else if (CurPtr[0] == '<' && tryLexConflictMarker())
+    else if (CurPtr[0] == '<' && tryLexConflictMarker(/*EatNewline=*/true))
       goto Restart;
     return lexOperatorIdentifier();
 
   case '>':
-    if (CurPtr[0] == '>' && tryLexConflictMarker())
+    if (CurPtr[0] == '>' && tryLexConflictMarker(/*EatNewline=*/true))
       goto Restart;
     return lexOperatorIdentifier();
  
@@ -2344,11 +2318,12 @@
       Pieces.push_back(TriviaPiece::spaces(Length));
       break;
     case '\n':
-    case '\r':
-      // FIXME: Distinguish CR and LF
       // FIXME: CR+LF shoud form one trivia piece
       Pieces.push_back(TriviaPiece::newlines(Length));
       break;
+    case '\r':
+      Pieces.push_back(TriviaPiece::carriageReturns(Length));
+      break;
     case '\t':
       Pieces.push_back(TriviaPiece::tabs(Length));
       break;
@@ -2372,8 +2347,7 @@
       // '// ...' comment.
       SeenComment = true;
       bool isDocComment = CurPtr[1] == '/';
-      skipUpToEndOfLine(); // NOTE: Don't use skipSlashSlashComment() here
-                           // because it consumes trailing newline.
+      skipSlashSlashComment(/*EatNewline=*/false);
       size_t Length = CurPtr - TriviaStart;
       Pieces.push_back(isDocComment
                            ? TriviaPiece::docLineComment({TriviaStart, Length})
@@ -2392,12 +2366,21 @@
     }
     break;
   case '#':
-    if (TriviaStart == BufferStart && *CurPtr == '!') {
+    if (TriviaStart == ContentStart && *CurPtr == '!') {
       // Hashbang '#!/path/to/swift'.
+      --CurPtr;
       if (BufferID != SourceMgr.getHashbangBufferID())
         diagnose(TriviaStart, diag::lex_hashbang_not_allowed);
-      skipUpToEndOfLine(); // NOTE: Don't use skipHashbang() here because it
-                           // consumes trailing newline.
+      skipHashbang(/*EatNewline=*/false);
+      size_t Length = CurPtr - TriviaStart;
+      Pieces.push_back(TriviaPiece::garbageText({TriviaStart, Length}));
+      goto Restart;
+    }
+    break;
+  case '<':
+  case '>':
+    if (tryLexConflictMarker(/*EatNewline=*/false)) {
+      // Conflict marker.
       size_t Length = CurPtr - TriviaStart;
       Pieces.push_back(TriviaPiece::garbageText({TriviaStart, Length}));
       goto Restart;
@@ -2556,7 +2539,7 @@
   Lexer L(FakeLangOpts, SM, BufferID, nullptr, /*InSILMode=*/ false,
           CommentRetentionMode::ReturnAsTokens);
   L.restoreState(State(Loc));
-  L.skipToEndOfLine();
+  L.skipToEndOfLine(/*EatNewline=*/true);
   return getSourceLoc(L.CurPtr);
 }
 
diff --git a/lib/Parse/ParseDecl.cpp b/lib/Parse/ParseDecl.cpp
index f299ea2..d391b9c 100644
--- a/lib/Parse/ParseDecl.cpp
+++ b/lib/Parse/ParseDecl.cpp
@@ -270,7 +270,7 @@
 
   // Next time start relexing from the beginning of the comment so that we can
   // attach it to the token.
-  State->markParserPosition(Tok.getCommentRange().getStart(), PreviousLoc,
+  State->markParserPosition(getParserPosition(),
                             InPoundLineEnvironment);
 
   // If we are done parsing the whole file, finalize the token receiver.
@@ -1618,6 +1618,8 @@
     
     // Recover by eating @foo(...) when foo is not known.
     consumeToken();
+    SyntaxParsingContext TokListContext(SyntaxContext, SyntaxKind::TokenList);
+
     if (Tok.is(tok::l_paren) && getEndOfPreviousLoc() == Tok.getLoc()) {
       ParserPosition LParenPosition = getParserPosition();
       skipSingle();
@@ -1633,6 +1635,9 @@
   // Ok, it is a valid attribute, eat it, and then process it.
   StringRef Text = Tok.getText();
   SourceLoc Loc = consumeToken();
+  
+  // Accumulate attribute argument '( ... )' as a token list.
+  SyntaxParsingContext TokListContext(SyntaxContext, SyntaxKind::TokenList);
 
   bool isAutoclosureEscaping = false;
   SourceRange autoclosureEscapingParenRange;
@@ -1916,9 +1921,11 @@
     SpecifierLoc = consumeToken();
   }
 
+  SyntaxParsingContext AttrListCtx(SyntaxContext, SyntaxKind::AttributeList);
   while (Tok.is(tok::at_sign)) {
     if (Attributes.AtLoc.isInvalid())
       Attributes.AtLoc = Tok.getLoc();
+    SyntaxParsingContext AttrCtx(SyntaxContext, SyntaxKind::Attribute);
     consumeToken();
     if (parseTypeAttribute(Attributes))
       return true;
@@ -2316,6 +2323,7 @@
 
       consumeToken(tok::kw_class);
       // Otherwise this is the start of a class declaration.
+      DeclParsingContext.setCreateSyntax(SyntaxKind::ClassDecl);
       DeclResult = parseDeclClass(ClassLoc, Flags, Attributes);
       break;
     }
@@ -2418,6 +2426,7 @@
 
     // Unambiguous top level decls.
     case tok::kw_import:
+      DeclParsingContext.setCreateSyntax(SyntaxKind::ImportDecl);
       DeclResult = parseDeclImport(Flags, Attributes);
       break;
     case tok::kw_extension:
@@ -2425,6 +2434,9 @@
       break;
     case tok::kw_let:
     case tok::kw_var: {
+      // Collect all modifiers into a modifier list.
+      DeclParsingContext.collectNodesInPlace(SyntaxKind::ModifierList);
+      DeclParsingContext.setCreateSyntax(SyntaxKind::VariableDecl);
       llvm::SmallVector<Decl *, 4> Entries;
       DeclResult = parseDeclVar(Flags, Attributes, Entries, StaticLoc,
                                 StaticSpelling, tryLoc);
@@ -2436,6 +2448,7 @@
       break;
     }
     case tok::kw_typealias:
+      DeclParsingContext.setCreateSyntax(SyntaxKind::TypealiasDecl);
       DeclResult = parseDeclTypeAlias(Flags, Attributes);
       MayNeedOverrideCompletion = true;
       break;
@@ -2470,10 +2483,11 @@
     case tok::kw_precedencegroup:
       DeclResult = parseDeclPrecedenceGroup(Flags, Attributes);
       break;
-    case tok::kw_protocol:
+    case tok::kw_protocol: {
+      DeclParsingContext.setCreateSyntax(SyntaxKind::ProtocolDecl);
       DeclResult = parseDeclProtocol(Flags, Attributes);
       break;
-
+    }
     case tok::kw_func:
       // Collect all modifiers into a modifier list.
       DeclParsingContext.collectNodesInPlace(SyntaxKind::ModifierList);
@@ -2682,7 +2696,10 @@
   }
 
   std::vector<std::pair<Identifier, SourceLoc>> ImportPath;
+  bool HasNext;
   do {
+    SyntaxParsingContext AccessCompCtx(SyntaxContext,
+                                       SyntaxKind::AccessPathComponent);
     if (Tok.is(tok::code_complete)) {
       consumeToken();
       if (CodeCompletion) {
@@ -2694,7 +2711,11 @@
     if (parseAnyIdentifier(ImportPath.back().first,
                            diag::expected_identifier_in_decl, "import"))
       return nullptr;
-  } while (consumeIf(tok::period));
+    HasNext = consumeIf(tok::period);
+  } while (HasNext);
+
+  // Collect all access path components to an access path.
+  SyntaxContext->collectNodesInPlace(SyntaxKind::AccessPath);
 
   if (Tok.is(tok::code_complete)) {
     // We omit the code completion token if it immediately follows the module
@@ -3274,6 +3295,8 @@
   ParserResult<TypeRepr> UnderlyingTy;
 
   if (Tok.is(tok::colon) || Tok.is(tok::equal)) {
+    SyntaxParsingContext InitCtx(SyntaxContext,
+                                 SyntaxKind::TypeInitializerClause);
     if (Tok.is(tok::colon)) {
       // It is a common mistake to write "typealias A : Int" instead of = Int.
       // Recognize this and produce a fixit.
@@ -3571,6 +3594,7 @@
   // If the SpecifierLoc is invalid, then the caller just wants us to synthesize
   // the default, not actually try to parse something.
   if (SpecifierLoc.isValid() && P.Tok.is(tok::l_paren)) {
+    SyntaxParsingContext ParamCtx(P.SyntaxContext, SyntaxKind::AccessorParameter);
     StartLoc = P.consumeToken(tok::l_paren);
     if (P.Tok.isNot(tok::identifier)) {
       P.diagnose(P.Tok, diag::expected_accessor_name, (unsigned)Kind);
@@ -3735,6 +3759,23 @@
              getAccessorNameForDiagnostic(accessorKind, addressorKind));
 }
 
+void Parser::parseAccessorAttributes(DeclAttributes &Attributes) {
+  bool FoundCCToken;
+  parseDeclAttributeList(Attributes, FoundCCToken);
+  SyntaxParsingContext ModifierCtx(SyntaxContext, SyntaxKind::DeclModifier);
+  // Parse the contextual keywords for 'mutating' and 'nonmutating' before
+  // get and set.
+  if (Tok.isContextualKeyword("mutating")) {
+    parseNewDeclAttribute(Attributes, /*AtLoc*/ {}, DAK_Mutating);
+  } else if (Tok.isContextualKeyword("nonmutating")) {
+    parseNewDeclAttribute(Attributes, /*AtLoc*/ {}, DAK_NonMutating);
+  } else if (Tok.isContextualKeyword("__consuming")) {
+    parseNewDeclAttribute(Attributes, /*AtLoc*/ {}, DAK_Consuming);
+  } else {
+    ModifierCtx.setTransparent();
+  }
+}
+
 /// \brief Parse a get-set clause, optionally containing a getter, setter,
 /// willSet, and/or didSet clauses.  'Indices' is a paren or tuple pattern,
 /// specifying the index list for a subscript.
@@ -3745,29 +3786,21 @@
                              SourceLoc &LastValidLoc, SourceLoc StaticLoc,
                              SourceLoc VarLBLoc,
                              SmallVectorImpl<Decl *> &Decls) {
-
   // Properties in protocols use sufficiently limited syntax that we have a
   // special parsing loop for them.  SIL mode uses the same syntax.
   if (Flags.contains(PD_InProtocol) || isInSILMode()) {
+    if (Tok.is(tok::r_brace)) {
+      // Give syntax node an empty statement list.
+      SyntaxParsingContext StmtListContext(SyntaxContext, SyntaxKind::StmtList);
+    }
     while (Tok.isNot(tok::r_brace)) {
       if (Tok.is(tok::eof))
         return true;
 
+      SyntaxParsingContext AccessorCtx(SyntaxContext, SyntaxKind::AccessorDecl);
       // Parse any leading attributes.
       DeclAttributes Attributes;
-      bool FoundCCToken;
-      parseDeclAttributeList(Attributes, FoundCCToken);
-
-      // Parse the contextual keywords for 'mutating' and 'nonmutating' before
-      // get and set.
-      if (Tok.isContextualKeyword("mutating")) {
-        parseNewDeclAttribute(Attributes, /*AtLoc*/ {}, DAK_Mutating);
-      } else if (Tok.isContextualKeyword("nonmutating")) {
-        parseNewDeclAttribute(Attributes, /*AtLoc*/ {}, DAK_NonMutating);
-      } else if (Tok.isContextualKeyword("__consuming")) {
-        parseNewDeclAttribute(Attributes, /*AtLoc*/ {}, DAK_Consuming);
-      }
-
+      parseAccessorAttributes(Attributes);
       AccessorKind Kind;
       AddressorKind addressorKind = AddressorKind::NotAddressor;
       FuncDecl **TheDeclPtr;
@@ -3789,6 +3822,7 @@
         Kind = AccessorKind::IsMutableAddressor;
         TheDeclPtr = &accessors.MutableAddressor;
       } else {
+        AccessorCtx.setTransparent();
         AccessorKeywordLoc = SourceLoc();
         diagnose(Tok, diag::expected_getset_in_protocol);
         return true;
@@ -3833,13 +3867,14 @@
     return false;
   }
 
-
   // Otherwise, we have a normal var or subscript declaration, parse the full
   // complement of specifiers, along with their bodies.
 
   // If the body is completely empty, preserve it.  This is at best a getter with
   // an implicit fallthrough off the end.
   if (Tok.is(tok::r_brace)) {
+    // Give syntax node an empty statement list.
+    SyntaxParsingContext StmtListContext(SyntaxContext, SyntaxKind::StmtList);
     diagnose(Tok, diag::computed_property_no_accessors);
     return true;
   }
@@ -3848,7 +3883,7 @@
   while (Tok.isNot(tok::r_brace)) {
     if (Tok.is(tok::eof))
       return true;
-
+    SyntaxParsingContext AccessorCtx(SyntaxContext, SyntaxKind::AccessorDecl);
     // If there are any attributes, we are going to parse them.  Because these
     // attributes might not be appertaining to the accessor, but to the first
     // declaration inside the implicit getter, we need to save the parser
@@ -3859,19 +3894,7 @@
 
     // Parse any leading attributes.
     DeclAttributes Attributes;
-    bool FoundCCToken;
-    parseDeclAttributeList(Attributes, FoundCCToken);
-
-    // Parse the contextual keywords for 'mutating' and 'nonmutating' before
-    // get and set.
-    if (Tok.isContextualKeyword("mutating")) {
-      parseNewDeclAttribute(Attributes, /*AtLoc*/ {}, DAK_Mutating);
-    } else if (Tok.isContextualKeyword("nonmutating")) {
-      parseNewDeclAttribute(Attributes, /*AtLoc*/ {}, DAK_NonMutating);
-    } else if (Tok.isContextualKeyword("__consuming")) {
-      parseNewDeclAttribute(Attributes, /*AtLoc*/ {}, DAK_Consuming);
-    }
-    
+    parseAccessorAttributes(Attributes);
     bool isImplicitGet = false;
     AccessorKind Kind;
     AddressorKind addressorKind = AddressorKind::NotAddressor;
@@ -3946,6 +3969,13 @@
     auto *ValueNamePattern =
       parseOptionalAccessorArgument(Loc, *this, Kind);
 
+    SyntaxParsingContext BlockCtx(SyntaxContext, SyntaxKind::CodeBlock);
+    if (AccessorKeywordLoc.isInvalid()) {
+      // If the keyword is absent, we shouldn't make these sub-nodes.
+      BlockCtx.setTransparent();
+      AccessorCtx.setTransparent();
+    }
+
     SourceLoc LBLoc = isImplicitGet ? VarLBLoc : Tok.getLoc();
     // FIXME: Use outer '{' loc if isImplicitGet.
     bool ExternalAsmName = false;
@@ -4018,12 +4048,15 @@
                          TypeLoc ElementTy, ParsedAccessors &accessors,
                          SourceLoc StaticLoc,
                          SmallVectorImpl<Decl *> &Decls) {
+  SyntaxParsingContext AccessorsCtx(SyntaxContext, SyntaxKind::AccessorBlock);
   accessors.LBLoc = consumeToken(tok::l_brace);
   SourceLoc LastValidLoc = accessors.LBLoc;
   bool Invalid = parseGetSetImpl(Flags, GenericParams, Indices, ElementTy,
                                  accessors, LastValidLoc, StaticLoc,
                                  accessors.LBLoc, Decls);
 
+  // Collect all explicit accessors to a list.
+  AccessorsCtx.collectNodesInPlace(SyntaxKind::AccessorList);
   // Parse the final '}'.
   if (Invalid)
     skipUntil(tok::r_brace);
@@ -4505,8 +4538,11 @@
     // Always return the result for PBD.
     return makeParserResult(Status, PBD);
   };
-  
+  SyntaxParsingContext PBListCtx(SyntaxContext, SyntaxKind::PatternBindingList);
+  bool HasNext;
   do {
+    SyntaxParsingContext PatternBindingCtx(SyntaxContext,
+                                           SyntaxKind::PatternBinding);
     Pattern *pattern;
     {
       // In our recursive parse, remember that we're in a var/let pattern.
@@ -4537,6 +4573,7 @@
     
     // Parse an initializer if present.
     if (Tok.is(tok::equal)) {
+      SyntaxParsingContext InitCtx(SyntaxContext, SyntaxKind::InitializerClause);
       // If we're not in a local context, we'll need a context to parse initializers
       // into (should we have one).  This happens for properties and global
       // variables in libraries.
@@ -4727,8 +4764,9 @@
         }
       }
     }
-  } while (consumeIf(tok::comma));
-  
+     HasNext = consumeIf(tok::comma);
+  } while (HasNext);
+
   if (HasAccessors && PBDEntries.size() > 1) {
     diagnose(VarLoc, diag::disallowed_var_multiple_getset);
     Status.setIsParseError();
@@ -5468,6 +5506,7 @@
 
   CD->setGenericParams(GenericParams);
 
+  SyntaxParsingContext BlockContext(SyntaxContext, SyntaxKind::MemberDeclBlock);
   SourceLoc LBLoc, RBLoc;
   if (parseToken(tok::l_brace, LBLoc, diag::expected_lbrace_class)) {
     LBLoc = PreviousLoc;
@@ -5564,6 +5603,7 @@
 
   // Parse the body.
   {
+    SyntaxParsingContext BlockContext(SyntaxContext, SyntaxKind::MemberDeclBlock);
     SourceLoc LBraceLoc;
     SourceLoc RBraceLoc;
     if (parseToken(tok::l_brace, LBraceLoc, diag::expected_lbrace_protocol)) {
@@ -5620,21 +5660,37 @@
   ParserResult<ParameterList> Indices
     = parseSingleParameterClause(ParameterContextKind::Subscript,
                                  &argumentNames);
-  if (Indices.isNull() || Indices.hasCodeCompletion())
-    return ParserStatus(Indices);
+  Status |= Indices;
+
+  SignatureHasCodeCompletion |= Indices.hasCodeCompletion();
+  if (SignatureHasCodeCompletion && !CodeCompletion)
+    return makeParserCodeCompletionStatus();
   
   // '->'
-  if (!Tok.is(tok::arrow)) {
+  SourceLoc ArrowLoc;
+  if (!consumeIf(tok::arrow, ArrowLoc)) {
     if (!Indices.isParseError())
       diagnose(Tok, diag::expected_arrow_subscript);
-    return makeParserError();
+    Status.setIsParseError();
   }
-  SourceLoc ArrowLoc = consumeToken();
+
+  if (!ArrowLoc.isValid() && (Indices.isNull() || Indices.get()->size() == 0)) {
+    // This doesn't look much like a subscript, so let regular recovery take
+    // care of it.
+    return Status;
+  }
   
   // type
   ParserResult<TypeRepr> ElementTy = parseType(diag::expected_type_subscript);
-  if (ElementTy.isNull() || ElementTy.hasCodeCompletion())
-    return ParserStatus(ElementTy);
+  Status |= ElementTy;
+  SignatureHasCodeCompletion |= ElementTy.hasCodeCompletion();
+  if (SignatureHasCodeCompletion && !CodeCompletion) {
+    return makeParserCodeCompletionStatus();
+  }
+  if (ElementTy.isNull()) {
+    // Always set an element type.
+    ElementTy = makeParserResult(ElementTy, new (Context) ErrorTypeRepr());
+  }
 
   diagnoseWhereClauseInGenericParamList(GenericParams);
 
@@ -5663,8 +5719,9 @@
   Subscript->setGenericParams(GenericParams);
 
   // Pass the function signature to code completion.
-  if (SignatureHasCodeCompletion)
+  if (SignatureHasCodeCompletion && CodeCompletion) {
     CodeCompletion->setParsedDecl(Subscript);
+  }
 
   Decls.push_back(Subscript);
 
@@ -5674,12 +5731,15 @@
   if (Tok.isNot(tok::l_brace)) {
     // Subscript declarations must always have at least a getter, so they need
     // to be followed by a {.
-    if (Flags.contains(PD_InProtocol))
-      diagnose(Tok, diag::expected_lbrace_subscript_protocol)
-        .fixItInsertAfter(ElementTy.get()->getEndLoc(), " { get set }");
-    else
-      diagnose(Tok, diag::expected_lbrace_subscript);
-    Status.setIsParseError();
+    if (!Status.isError()) {
+      if (Flags.contains(PD_InProtocol)) {
+        diagnose(Tok, diag::expected_lbrace_subscript_protocol)
+            .fixItInsertAfter(ElementTy.get()->getEndLoc(), " { get set }");
+      } else {
+        diagnose(Tok, diag::expected_lbrace_subscript);
+      }
+      Status.setIsParseError();
+    }
   } else {
     if (parseGetSet(Flags, GenericParams,
                     Indices.get(), ElementTy.get(),
@@ -5698,11 +5758,6 @@
                    Flags, /*static*/ SourceLoc(), Attributes,
                    ElementTy.get(), Indices.get(), Decls);
 
-  if (Invalid) {
-    Subscript->setInterfaceType(ErrorType::get(Context));
-    Subscript->setInvalid();
-  }
-
   // No need to setLocalDiscriminator because subscripts cannot
   // validly appear outside of type decls.
   return makeParserResult(Status, Subscript);
diff --git a/lib/Parse/ParseExpr.cpp b/lib/Parse/ParseExpr.cpp
index d9d0bc0..7a49db4 100644
--- a/lib/Parse/ParseExpr.cpp
+++ b/lib/Parse/ParseExpr.cpp
@@ -25,6 +25,7 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/Twine.h"
+#include "swift/Basic/Defer.h"
 #include "swift/Basic/StringExtras.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/SaveAndRestore.h"
@@ -56,6 +57,7 @@
       return makeParserCodeCompletionResult<Expr>();
     if (pattern.isNull())
       return nullptr;
+    SyntaxContext->setCreateSyntax(SyntaxKind::UnresolvedPatternExpr);
     return makeParserResult(new (Context) UnresolvedPatternExpr(pattern.get()));
   }
   
@@ -418,6 +420,7 @@
   ParserResult<Expr> sub = parseExprUnary(message, isExprBasic);
 
   if (hadTry && !sub.hasCodeCompletion() && !sub.isNull()) {
+    ElementContext.setCreateSyntax(SyntaxKind::TryExpr);
     switch (trySuffix ? trySuffix->getKind() : tok::NUM_TOKENS) {
     case tok::exclaim_postfix:
       sub = makeParserResult(
@@ -1209,8 +1212,8 @@
         SmallVector<TypeLoc, 8> locArgs;
         for (auto ty : args)
           locArgs.push_back(ty);
-        Result = makeParserResult(new (Context) UnresolvedSpecializeExpr(
-            Result.get(), LAngleLoc, Context.AllocateCopy(locArgs), RAngleLoc));
+        Result = makeParserResult(UnresolvedSpecializeExpr::create(Context,
+                                  Result.get(), LAngleLoc, locArgs, RAngleLoc));
       }
 
       continue;
@@ -1544,6 +1547,13 @@
                      ? VarDecl::Specifier::Let
                      : VarDecl::Specifier::Var;
       auto pattern = createBindingFromPattern(loc, name, specifier);
+      if (SyntaxContext->isEnabled()) {
+        PatternSyntax PatternNode =
+            SyntaxFactory::makeIdentifierPattern(SyntaxContext->popToken());
+        ExprSyntax ExprNode =
+            SyntaxFactory::makeUnresolvedPatternExpr(PatternNode);
+        SyntaxContext->addSyntax(ExprNode);
+      }
       Result = makeParserResult(new (Context) UnresolvedPatternExpr(pattern));
       break;
     }
@@ -1926,13 +1936,13 @@
       TmpContext.setDiscard();
 
       // Create a temporary lexer that lexes from the body of the string.
-      Lexer::State BeginState =
+      LexerState BeginState =
           L->getStateForBeginningOfTokenLoc(Segment.Loc);
       // We need to set the EOF at r_paren, to prevent the Lexer from eagerly
       // trying to lex the token beyond it. Parser::parseList() does a special
       // check for a tok::EOF that is spelled with a ')'.
       // FIXME: This seems like a hack, there must be a better way..
-      Lexer::State EndState = BeginState.advance(Segment.Length-1);
+      LexerState EndState = BeginState.advance(Segment.Length-1);
       Lexer LocalLex(*L, BeginState, EndState);
 
       // Temporarily swap out the parser's current lexer with our new one.
@@ -2205,9 +2215,8 @@
     SmallVector<TypeLoc, 8> locArgs;
     for (auto ty : args)
       locArgs.push_back(ty);
-    E = new (Context) UnresolvedSpecializeExpr(E, LAngleLoc,
-                                               Context.AllocateCopy(locArgs),
-                                               RAngleLoc);
+    E = UnresolvedSpecializeExpr::create(Context, E, LAngleLoc, locArgs,
+                                         RAngleLoc);
   }
   return E;
 }
@@ -2235,14 +2244,21 @@
       SourceLoc TypeStartLoc = PlaceholderTok.getLoc().getAdvancedLoc(Offset);
       SourceLoc TypeEndLoc = TypeStartLoc.getAdvancedLoc(TyStr.size());
 
-      Lexer::State StartState = L->getStateForBeginningOfTokenLoc(TypeStartLoc);
-      Lexer::State EndState = L->getStateForBeginningOfTokenLoc(TypeEndLoc);
+      LexerState StartState = L->getStateForBeginningOfTokenLoc(TypeStartLoc);
+      LexerState EndState = L->getStateForBeginningOfTokenLoc(TypeEndLoc);
 
       // Create a lexer for the type sub-string.
       Lexer LocalLex(*L, StartState, EndState);
 
       // Temporarily swap out the parser's current lexer with our new one.
       llvm::SaveAndRestore<Lexer *> T(L, &LocalLex);
+
+      // Don't feed to syntax token recorder.
+      ConsumeTokenReceiver DisabledRec;
+      llvm::SaveAndRestore<ConsumeTokenReceiver *> R(TokReceiver, &DisabledRec);
+      SyntaxParsingContext SContext(SyntaxContext);
+      SContext.disable();
+
       Tok.setKind(tok::unknown); // we might be at tok::eof now.
       consumeTokenWithoutFeedingReceiver();
       return parseType().getPtrOrNull();
@@ -2373,12 +2389,23 @@
     // No closure signature.
     return false;
   }
-
-  // At this point, we know we have a closure signature. Parse the capture list
-  // and parameters.
-  if (consumeIf(tok::l_square) &&
-      !consumeIf(tok::r_square)) {
+  SyntaxParsingContext ClosureSigCtx(SyntaxContext, SyntaxKind::ClosureSignature);
+  if (Tok.is(tok::l_square) && peekToken().is(tok::r_square)) {
+    SyntaxParsingContext CaptureCtx(SyntaxContext,
+                                    SyntaxKind::ClosureCaptureSignature);
+    consumeToken(tok::l_square);
+    consumeToken(tok::r_square);
+  } else if (Tok.is(tok::l_square) && !peekToken().is(tok::r_square)) {
+    SyntaxParsingContext CaptureCtx(SyntaxContext,
+                                    SyntaxKind::ClosureCaptureSignature);
+    consumeToken(tok::l_square);
+    // At this point, we know we have a closure signature. Parse the capture list
+    // and parameters.
+    bool HasNext;
     do {
+      SyntaxParsingContext CapturedItemCtx(SyntaxContext,
+                                           SyntaxKind::ClosureCaptureItem);
+      SWIFT_DEFER { HasNext = consumeIf(tok::comma); };
       // Check for the strength specifier: "weak", "unowned", or
       // "unowned(safe/unsafe)".
       SourceLoc loc;
@@ -2418,6 +2445,9 @@
         continue;
       }
 
+      // Squash all tokens, if any, as the specifier of the captured item.
+      CapturedItemCtx.collectNodesInPlace(SyntaxKind::TokenList);
+
       // The thing being capture specified is an identifier, or as an identifier
       // followed by an expression.
       Expr *initializer;
@@ -2471,8 +2501,9 @@
                                              CurDeclContext);
 
       captureList.push_back(CaptureListEntry(VD, PBD));
-    } while (consumeIf(tok::comma));
+    } while (HasNext);
 
+    SyntaxContext->collectNodesInPlace(SyntaxKind::ClosureCaptureItemList);
     // The capture list needs to be closed off with a ']'.
     if (!consumeIf(tok::r_square)) {
       diagnose(Tok, diag::expected_capture_list_end_rsquare);
@@ -2492,9 +2523,13 @@
       else
         invalid = true;
     } else {
+      SyntaxParsingContext ClParamListCtx(SyntaxContext,
+                                          SyntaxKind::ClosureParamList);
       // Parse identifier (',' identifier)*
       SmallVector<ParamDecl*, 4> elements;
+      bool HasNext;
       do {
+        SyntaxParsingContext ClParamCtx(SyntaxContext, SyntaxKind::ClosureParam);
         if (Tok.isNot(tok::identifier, tok::kw__)) {
           diagnose(Tok, diag::expected_closure_parameter_name);
           invalid = true;
@@ -2508,9 +2543,10 @@
                                            Tok.getLoc(), name, Type(), nullptr);
         elements.push_back(var);
         consumeToken();
- 
+
         // Consume a comma to continue.
-      } while (consumeIf(tok::comma));
+        HasNext = consumeIf(tok::comma);
+      } while (HasNext);
 
       params = ParameterList::create(Context, elements);
     }
@@ -2525,6 +2561,7 @@
 
     // Parse the optional explicit return type.
     if (Tok.is(tok::arrow)) {
+      SyntaxParsingContext ReturnCtx(SyntaxContext, SyntaxKind::ReturnClause);
       // Consume the '->'.
       arrowLoc = consumeToken();
 
@@ -2619,7 +2656,7 @@
 
 ParserResult<Expr> Parser::parseExprClosure() {
   assert(Tok.is(tok::l_brace) && "Not at a left brace?");
-
+  SyntaxParsingContext ClosureContext(SyntaxContext, SyntaxKind::ClosureExpr);
   // We may be parsing this closure expr in a matching pattern context.  If so,
   // reset our state to not be in a pattern for any recursive pattern parses.
   llvm::SaveAndRestore<decltype(InVarOrLetPattern)>
@@ -2750,8 +2787,7 @@
   // If the closure includes a capture list, create an AST node for it as well.
   Expr *result = closure;
   if (!captureList.empty())
-    result = new (Context) CaptureListExpr(Context.AllocateCopy(captureList),
-                                           closure);
+    result = CaptureListExpr::create(Context, captureList, closure);
 
   return makeParserResult(Status, result);
 }
@@ -3187,7 +3223,7 @@
     SourceLoc RSquareLoc = consumeToken(tok::r_square);
     ArrayOrDictContext.setCreateSyntax(SyntaxKind::DictionaryExpr);
     return makeParserResult(
-                  DictionaryExpr::create(Context, LSquareLoc, {}, RSquareLoc));
+               DictionaryExpr::create(Context, LSquareLoc, {}, {}, RSquareLoc));
   }
 
   bool ParseDict;
@@ -3281,6 +3317,7 @@
   // Each subexpression is a (key, value) tuple.
   // FIXME: We're not tracking the colon locations in the AST.
   SmallVector<Expr *, 8> SubExprs;
+  SmallVector<SourceLoc, 8> CommaLocs;
   SourceLoc RSquareLoc;
 
   // Function that adds a new key/value pair.
@@ -3319,12 +3356,17 @@
 
     // Add this key/value pair.
     addKeyValuePair(Key.get(), Value.get());
+
+    if (Tok.is(tok::comma))
+      CommaLocs.push_back(Tok.getLoc());
+
     return ParserStatus(Key) | ParserStatus(Value);
   });
 
   assert(SubExprs.size() >= 1);
   return makeParserResult(Status, DictionaryExpr::create(Context, LSquareLoc,
-                                                         SubExprs, RSquareLoc));
+                                                         SubExprs, CommaLocs,
+                                                         RSquareLoc));
 }
 
 void Parser::addPatternVariablesToScope(ArrayRef<Pattern *> Patterns) {
diff --git a/lib/Parse/ParseIfConfig.cpp b/lib/Parse/ParseIfConfig.cpp
index a09142e..3b9eaf2 100644
--- a/lib/Parse/ParseIfConfig.cpp
+++ b/lib/Parse/ParseIfConfig.cpp
@@ -23,8 +23,12 @@
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/SaveAndRestore.h"
+#include "swift/Syntax/SyntaxFactory.h"
+#include "swift/Syntax/TokenSyntax.h"
+#include "swift/Syntax/SyntaxParsingContext.h"
 
 using namespace swift;
+using namespace swift::syntax;
 
 namespace {
 
@@ -642,22 +646,47 @@
 /// Delegate callback function to parse elements in the blocks.
 ParserResult<IfConfigDecl> Parser::parseIfConfig(
     llvm::function_ref<void(SmallVectorImpl<ASTNode> &, bool)> parseElements) {
-
+  SyntaxParsingContext IfConfigCtx(SyntaxContext, SyntaxKind::IfConfigDecl);
   SmallVector<IfConfigClause, 4> Clauses;
   Parser::StructureMarkerRAII ParsingDecl(
       *this, Tok.getLoc(), Parser::StructureMarkerKind::IfConfig);
 
   bool foundActive = false;
   bool isVersionCondition = false;
+  enum class ClauseKind {
+    If,
+    ElseIf,
+    Else,
+  };
   while (1) {
-    bool isElse = Tok.is(tok::pound_else);
+    ClauseKind ClKind;
+    if (Tok.is(tok::pound_if)) {
+      ClKind = ClauseKind::If;
+    } else if (Tok.is(tok::pound_elseif)) {
+      ClKind = ClauseKind::ElseIf;
+    } else {
+      ClKind = ClauseKind::Else;
+    }
+    if (ClKind == ClauseKind::Else) {
+      // Collect all #elseif to a list.
+      SyntaxContext->collectNodesInPlace(SyntaxKind::ElseifDirectiveClauseList);
+    }
+    SyntaxParsingContext ClauseContext(SyntaxContext,
+                                       ClKind == ClauseKind::Else ?
+                                        SyntaxKind::ElseDirectiveClause :
+                                        SyntaxKind::ElseifDirectiveClause);
+    SWIFT_DEFER {
+      // Avoid making a clause for if
+      if (ClKind == ClauseKind::If)
+        ClauseContext.setTransparent();
+    };
     SourceLoc ClauseLoc = consumeToken();
     Expr *Condition = nullptr;
     bool isActive = false;
 
     // Parse the condition.  Evaluate it to determine the active
     // clause unless we're doing a parse-only pass.
-    if (isElse) {
+    if (ClKind == ClauseKind::Else) {
       isActive = !foundActive && State->PerformConditionEvaluation;
     } else {
       llvm::SaveAndRestore<bool> S(InPoundIfEnvironment, true);
@@ -709,7 +738,7 @@
     if (Tok.isNot(tok::pound_elseif, tok::pound_else))
       break;
 
-    if (isElse)
+    if (ClKind == ClauseKind::Else)
       diagnose(Tok, diag::expected_close_after_else_directive);
   }
 
diff --git a/lib/Parse/ParsePattern.cpp b/lib/Parse/ParsePattern.cpp
index ad96156..169362d 100644
--- a/lib/Parse/ParsePattern.cpp
+++ b/lib/Parse/ParsePattern.cpp
@@ -66,6 +66,8 @@
                                    unsigned argIndex,
                                    Expr *&init,
                                  Parser::ParameterContextKind paramContext) {
+  SyntaxParsingContext DefaultArgContext(P.SyntaxContext,
+                                         SyntaxKind::InitializerClause);
   SourceLoc equalLoc = P.consumeToken(tok::equal);
 
   // Enter a fresh default-argument context with a meaningless parent.
@@ -152,6 +154,7 @@
                              ParameterContextKind paramContext) {
   assert(params.empty() && leftParenLoc.isInvalid() &&
          rightParenLoc.isInvalid() && "Must start with empty state");
+  SyntaxParsingContext ParamClauseCtx(SyntaxContext, SyntaxKind::ParameterClause);
 
   // Consume the starting '(';
   leftParenLoc = consumeToken(tok::l_paren);
@@ -719,6 +722,7 @@
 
   // If there's a trailing arrow, parse the rest as the result type.
   if (Tok.isAny(tok::arrow, tok::colon)) {
+    SyntaxParsingContext ReturnCtx(SyntaxContext, SyntaxKind::ReturnClause);
     if (!consumeIf(tok::arrow, arrowLoc)) {
       // FixIt ':' to '->'.
       diagnose(Tok, diag::func_decl_expected_arrow)
@@ -773,6 +777,7 @@
   
   // Now parse an optional type annotation.
   if (Tok.is(tok::colon)) {
+    SyntaxParsingContext TypeAnnoCtx(SyntaxContext, SyntaxKind::TypeAnnotation);
     SourceLoc colonLoc = consumeToken(tok::colon);
     
     if (result.isNull())  // Recover by creating AnyPattern.
@@ -837,14 +842,17 @@
 ///   pattern ::= 'let' pattern
 ///
 ParserResult<Pattern> Parser::parsePattern() {
+  SyntaxParsingContext PatternCtx(SyntaxContext, SyntaxContextKind::Pattern);
   switch (Tok.getKind()) {
   case tok::l_paren:
     return parsePatternTuple();
     
   case tok::kw__:
+    PatternCtx.setCreateSyntax(SyntaxKind::WildcardPattern);
     return makeParserResult(new (Context) AnyPattern(consumeToken(tok::kw__)));
     
   case tok::identifier: {
+    PatternCtx.setCreateSyntax(SyntaxKind::IdentifierPattern);
     Identifier name;
     SourceLoc loc = consumeIdentifier(&name);
     bool isLet = (InVarOrLetPattern != IVOLP_InVar);
@@ -867,6 +875,7 @@
     
   case tok::kw_var:
   case tok::kw_let: {
+    PatternCtx.setCreateSyntax(SyntaxKind::ValueBindingPattern);
     bool isLet = Tok.is(tok::kw_let);
     SourceLoc varLoc = consumeToken();
     
@@ -949,6 +958,8 @@
 ///   pattern-tuple-body:
 ///     pattern-tuple-element (',' pattern-tuple-body)*
 ParserResult<Pattern> Parser::parsePatternTuple() {
+  SyntaxParsingContext TuplePatternCtxt(SyntaxContext,
+                                        SyntaxKind::TuplePattern);
   StructureMarkerRAII ParsingPatternTuple(*this, Tok);
   SourceLoc LPLoc = consumeToken(tok::l_paren);
   SourceLoc RPLoc;
@@ -959,7 +970,7 @@
     parseList(tok::r_paren, LPLoc, RPLoc,
               /*AllowSepAfterLast=*/false,
               diag::expected_rparen_tuple_pattern_list,
-              SyntaxKind::Unknown,
+              SyntaxKind::TuplePatternElementList,
               [&] () -> ParserStatus {
     // Parse the pattern tuple element.
     ParserStatus EltStatus;
@@ -1025,9 +1036,11 @@
   // parse pattern nodes for productions shared by pattern and expression
   // grammar. For short-term ease of initial implementation, we always go
   // through the expr parser for ambiguous productions.
+  SyntaxParsingContext PatternCtx(SyntaxContext, SyntaxContextKind::Pattern);
 
   // Parse productions that can only be patterns.
   if (Tok.isAny(tok::kw_var, tok::kw_let)) {
+    PatternCtx.setCreateSyntax(SyntaxKind::ValueBindingPattern);
     assert(Tok.isAny(tok::kw_let, tok::kw_var) && "expects var or let");
     bool isLet = Tok.is(tok::kw_let);
     SourceLoc varLoc = consumeToken();
@@ -1037,6 +1050,7 @@
   
   // matching-pattern ::= 'is' type
   if (Tok.is(tok::kw_is)) {
+    PatternCtx.setCreateSyntax(SyntaxKind::IsTypePattern);
     SourceLoc isLoc = consumeToken(tok::kw_is);
     ParserResult<TypeRepr> castType = parseType();
     if (castType.isNull() || castType.hasCodeCompletion())
@@ -1055,7 +1069,14 @@
     return makeParserCodeCompletionStatus();
   if (subExpr.isNull())
     return nullptr;
-  
+
+  if (SyntaxContext->isEnabled()) {
+    if (auto UPES = PatternCtx.popIf<UnresolvedPatternExprSyntax>()) {
+      PatternCtx.addSyntax(UPES->getPattern());
+    } else {
+      PatternCtx.setCreateSyntax(SyntaxKind::ExpressionPattern);
+    }
+  }
   // The most common case here is to parse something that was a lexically
   // obvious pattern, which will come back wrapped in an immediate
   // UnresolvedPatternExpr.  Transform this now to simplify later code.
@@ -1141,5 +1162,3 @@
     return canParseType();
   return true;
 }
-
-
diff --git a/lib/Parse/ParseStmt.cpp b/lib/Parse/ParseStmt.cpp
index 9a685c6..372e98b 100644
--- a/lib/Parse/ParseStmt.cpp
+++ b/lib/Parse/ParseStmt.cpp
@@ -569,12 +569,15 @@
     if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
     if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
     return parseStmtContinue();
-  case tok::kw_fallthrough:
+  case tok::kw_fallthrough: {
     if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
     if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
+
+    SyntaxContext->setCreateSyntax(SyntaxKind::FallthroughStmt);
     return makeParserResult(
         new (Context) FallthroughStmt(consumeToken(tok::kw_fallthrough)));
   }
+  }
 }
 
 /// parseBraceItemList - A brace enclosed expression/statement/decl list.  For
@@ -615,6 +618,7 @@
 ///     'break' identifier?
 ///
 ParserResult<Stmt> Parser::parseStmtBreak() {
+  SyntaxContext->setCreateSyntax(SyntaxKind::BreakStmt);
   SourceLoc Loc = consumeToken(tok::kw_break);
   SourceLoc TargetLoc;
   Identifier Target;
@@ -637,6 +641,7 @@
 ///     'continue' identifier?
 ///
 ParserResult<Stmt> Parser::parseStmtContinue() {
+  SyntaxContext->setCreateSyntax(SyntaxKind::ContinueStmt);
   SourceLoc Loc = consumeToken(tok::kw_continue);
   SourceLoc TargetLoc;
   Identifier Target;
@@ -660,7 +665,7 @@
 ///     'return' expr?
 ///   
 ParserResult<Stmt> Parser::parseStmtReturn(SourceLoc tryLoc) {
-  SyntaxParsingContext LocalContext(SyntaxContext, SyntaxKind::ReturnStmt);
+  SyntaxContext->setCreateSyntax(SyntaxKind::ReturnStmt);
   SourceLoc ReturnLoc = consumeToken(tok::kw_return);
 
   if (Tok.is(tok::code_complete)) {
@@ -725,6 +730,7 @@
 ///   'throw' expr
 ///
 ParserResult<Stmt> Parser::parseStmtThrow(SourceLoc tryLoc) {
+  SyntaxContext->setCreateSyntax(SyntaxKind::ThrowStmt);
   SourceLoc throwLoc = consumeToken(tok::kw_throw);
   SourceLoc exprLoc;
   if (Tok.isNot(tok::eof))
@@ -759,6 +765,7 @@
 ///     'defer' brace-stmt
 ///
 ParserResult<Stmt> Parser::parseStmtDefer() {
+  SyntaxContext->setCreateSyntax(SyntaxKind::DeferStmt);
   SourceLoc DeferLoc = consumeToken(tok::kw_defer);
   
   // Macro expand out the defer into a closure and call, which we can typecheck
@@ -991,7 +998,10 @@
     VD->setHasNonPatternBindingInit();
 
   // Parse the optional 'where' guard.
-  if (P.consumeIf(tok::kw_where, result.WhereLoc)) {
+  if (P.Tok.is(tok::kw_where)) {
+    SyntaxParsingContext WhereClauseCtxt(P.SyntaxContext,
+                                         SyntaxKind::WhereClause);
+    result.WhereLoc = P.consumeToken(tok::kw_where);
     SourceLoc startOfGuard = P.Tok.getLoc();
 
     auto diagKind = [=]() -> Diag<> {
@@ -1615,6 +1625,7 @@
 ///   stmt-repeat:
 ///     (identifier ':')? 'repeat' stmt-brace 'while' expr
 ParserResult<Stmt> Parser::parseStmtRepeat(LabeledStmtInfo labelInfo) {
+  SyntaxContext->setCreateSyntax(SyntaxKind::RepeatWhileStmt);
   SourceLoc repeatLoc = consumeToken(tok::kw_repeat);
 
   ParserStatus status;
@@ -1658,6 +1669,7 @@
 ///     (identifier ':')? 'do' stmt-brace
 ///     (identifier ':')? 'do' stmt-brace stmt-catch+
 ParserResult<Stmt> Parser::parseStmtDo(LabeledStmtInfo labelInfo) {
+  SyntaxContext->setCreateSyntax(SyntaxKind::DoStmt);
   SourceLoc doLoc = consumeToken(tok::kw_do);
 
   ParserStatus status;
@@ -1671,6 +1683,8 @@
 
   // If the next token is 'catch', this is a 'do'/'catch' statement.
   if (Tok.is(tok::kw_catch)) {
+    SyntaxParsingContext CatchListCtxt(SyntaxContext,
+                                       SyntaxKind::CatchClauseList);
     // Parse 'catch' clauses 
     SmallVector<CatchStmt*, 4> allClauses;
     do {
@@ -1736,6 +1750,7 @@
 /// This routine promises to return a non-null result unless there was
 /// a code-completion token in the pattern.
 ParserResult<CatchStmt> Parser::parseStmtCatch() {
+  SyntaxParsingContext CatchClauseCtxt(SyntaxContext, SyntaxKind::CatchClause);
   // A catch block has its own scope for variables bound out of the pattern.
   Scope S(this, ScopeKind::CatchVars);
 
diff --git a/lib/Parse/ParseType.cpp b/lib/Parse/ParseType.cpp
index 1ee1d72..a81f93c 100644
--- a/lib/Parse/ParseType.cpp
+++ b/lib/Parse/ParseType.cpp
@@ -427,6 +427,8 @@
         diag::rethrowing_function_type : diag::throw_in_function_type;
       diagnose(Tok.getLoc(), DiagID)
         .fixItReplace(Tok.getLoc(), "throws");
+      if (Tok.is(tok::kw_throw))
+        Tok.setKind(tok::kw_throws);
     }
     throwsLoc = consumeToken();
   }
@@ -440,6 +442,27 @@
       return makeParserCodeCompletionResult<TypeRepr>();
     if (SecondHalf.isNull())
       return nullptr;
+
+    if (SyntaxContext->isEnabled()) {
+      FunctionTypeSyntaxBuilder Builder;
+      Builder.useReturnType(SyntaxContext->popIf<TypeSyntax>().getValue());
+      Builder.useArrow(SyntaxContext->popToken());
+      if (throwsLoc.isValid())
+        Builder.useThrowsOrRethrowsKeyword(SyntaxContext->popToken());
+
+      auto InputNode = SyntaxContext->popIf<TypeSyntax>().getValue();
+      if (auto TupleTypeNode = InputNode.getAs<TupleTypeSyntax>()) {
+        // Decompose TupleTypeSyntax and repack into FunctionType.
+        Builder
+          .useLeftParen(TupleTypeNode->getLeftParen())
+          .useArguments(TupleTypeNode->getElements())
+          .useRightParen(TupleTypeNode->getRightParen());
+      } else {
+        Builder
+          .addTupleTypeElement(SyntaxFactory::makeTupleTypeElement(InputNode));
+      }
+      SyntaxContext->addSyntax(Builder.build());
+    }
     tyR = new (Context) FunctionTypeRepr(generics, tyR, throwsLoc, arrowLoc,
                                          SecondHalf.get());
   } else if (generics) {
@@ -466,6 +489,8 @@
     if (tyR)
       tyR->walk(walker);
   }
+  if (specifierLoc.isValid() || !attrs.empty())
+    SyntaxContext->setCreateSyntax(SyntaxKind::AttributedType);
 
   return makeParserResult(applyAttributeToType(tyR, attrs, specifier,
                                                specifierLoc));
@@ -655,6 +680,7 @@
 ParserResult<TypeRepr>
 Parser::parseTypeSimpleOrComposition(Diag<> MessageID,
                                      bool HandleCodeCompletion) {
+  SyntaxParsingContext CompositionContext(SyntaxContext, SyntaxContextKind::Type);
   // Parse the first type
   ParserResult<TypeRepr> FirstType = parseTypeSimple(MessageID,
                                                      HandleCodeCompletion);
@@ -662,7 +688,7 @@
     return makeParserCodeCompletionResult<TypeRepr>();
   if (FirstType.isNull() || !Tok.isContextualPunctuator("&"))
     return FirstType;
-  
+
   SmallVector<TypeRepr *, 4> Types;
   ParserStatus Status(FirstType);
   SourceLoc FirstTypeLoc = FirstType.get()->getStartLoc();
@@ -681,16 +707,34 @@
   };
 
   addType(FirstType.get());
-  
-  while (Tok.isContextualPunctuator("&")) {
+  SyntaxContext->setCreateSyntax(SyntaxKind::CompositionType);
+  assert(Tok.isContextualPunctuator("&"));
+  do {
     consumeToken(); // consume '&'
+
+    if (SyntaxContext->isEnabled() && Status.isSuccess()) {
+      CompositionTypeElementSyntaxBuilder Builder;
+      Builder
+        .useAmpersand(SyntaxContext->popToken())
+        .useType(SyntaxContext->popIf<TypeSyntax>().getValue());
+      SyntaxContext->addSyntax(Builder.build());
+    }
+
+    // Parse next type.
     ParserResult<TypeRepr> ty =
       parseTypeSimple(diag::expected_identifier_for_type, HandleCodeCompletion);
     if (ty.hasCodeCompletion())
       return makeParserCodeCompletionResult<TypeRepr>();
     Status |= ty;
     addType(ty.getPtrOrNull());
-  };
+  } while (Tok.isContextualPunctuator("&"));
+
+  if (SyntaxContext->isEnabled() && Status.isSuccess()) {
+    auto LastNode = SyntaxFactory::makeCompositionTypeElement(
+        SyntaxContext->popIf<TypeSyntax>().getValue(), None);
+    SyntaxContext->addSyntax(LastNode);
+  }
+  SyntaxContext->collectNodesInPlace(SyntaxKind::CompositionTypeElementList);
   
   return makeParserResult(Status, CompositionTypeRepr::create(
     Context, Types, FirstTypeLoc, {FirstAmpersandLoc, PreviousLoc}));
@@ -719,7 +763,6 @@
 ///     type-identifier
 ///     type-composition-list-deprecated ',' type-identifier
 ParserResult<TypeRepr> Parser::parseOldStyleProtocolComposition() {
-  SyntaxParsingContext TypeContext(SyntaxContext, SyntaxContextKind::Type);
   assert(Tok.is(tok::kw_protocol) && startsWithLess(peekToken()));
 
   // Start a context for creating type syntax.
@@ -829,7 +872,7 @@
 ///     identifier ':' type
 ///     type
 ParserResult<TupleTypeRepr> Parser::parseTypeTupleBody() {
-  SyntaxParsingContext TypeContext(SyntaxContext, SyntaxContextKind::Type);
+  SyntaxParsingContext TypeContext(SyntaxContext, SyntaxKind::TupleType);
   Parser::StructureMarkerRAII ParsingTypeTuple(*this, Tok);
   SourceLoc RPLoc, LPLoc = consumeToken(tok::l_paren);
   SourceLoc EllipsisLoc;
@@ -839,21 +882,30 @@
   ParserStatus Status = parseList(tok::r_paren, LPLoc, RPLoc,
                                   /*AllowSepAfterLast=*/false,
                                   diag::expected_rparen_tuple_type_list,
-                                  SyntaxKind::Unknown,
+                                  SyntaxKind::TupleTypeElementList,
                                   [&] () -> ParserStatus {
     TupleTypeReprElement element;
 
-    // If this is a deprecated use of the inout marker in an argument list,
-    // consume the inout.
-    SourceLoc SpecifierLoc;
-    consumeIf(tok::kw_inout, SpecifierLoc);
+    // 'inout' here can be a obsoleted use of the marker in an argument list,
+    // consume it in backtracking context so we can determine it's really a
+    // deprecated use of it.
+    llvm::Optional<BacktrackingScope> Backtracking;
+    SourceLoc ObsoletedInOutLoc;
+    if (Tok.is(tok::kw_inout)) {
+      Backtracking.emplace(*this);
+      ObsoletedInOutLoc = consumeToken(tok::kw_inout);
+    }
 
     // If the tuple element starts with a potential argument label followed by a
     // ':' or another potential argument label, then the identifier is an
     // element tag, and it is followed by a type annotation.
     if (Tok.canBeArgumentLabel() &&
         (peekToken().is(tok::colon) || peekToken().canBeArgumentLabel())) {
-      // Consume the name
+      if (Backtracking)
+        // Found obsoleted 'inout' use.
+        Backtracking->cancelBacktrack();
+
+      // Consume a name.
       if (!Tok.is(tok::kw__))
         element.Name = Context.getIdentifier(Tok.getText());
       element.NameLoc = consumeToken();
@@ -866,54 +918,59 @@
       }
 
       // Consume the ':'.
-      SourceLoc colonLoc;
-      if (Tok.is(tok::colon)) {
-        colonLoc = consumeToken();
-      } else {
+      if (!consumeIf(tok::colon, element.ColonLoc))
         diagnose(Tok, diag::expected_parameter_colon);
-      }
 
-      SourceLoc postColonLoc = Tok.getLoc();
-
-      // Parse the type annotation.
-      auto type = parseType(diag::expected_type);
-      if (type.hasCodeCompletion())
-        return makeParserCodeCompletionStatus();
-      if (type.isNull())
-        return makeParserError();
-      element.Type = type.get();
-
-      // Complain obsoleted 'inout' position; (inout name: Ty)
-      if (SpecifierLoc.isValid() && !isa<InOutTypeRepr>(element.Type))
-        diagnose(Tok.getLoc(), diag::inout_as_attr_disallowed, "'inout'")
-          .fixItRemove(SpecifierLoc)
-          .fixItInsert(postColonLoc, "inout ");
-    } else {
-      // Otherwise, this has to be a type.
-      auto type = parseType();
-      if (type.hasCodeCompletion())
-        return makeParserCodeCompletionStatus();
-      if (type.isNull())
-        return makeParserError();
-      element.Type = type.get();
+    } else if (Backtracking) {
+      // If we don't have labels, 'inout' is not a obsoleted use.
+      ObsoletedInOutLoc = SourceLoc();
     }
+    Backtracking.reset();
 
-    // If an 'inout' marker was specified, build inout type.
-    // Note that we bury the inout locator within the named locator.
-    // This is weird but required by Sema apparently.
-    if (SpecifierLoc.isValid()) {
-      if (isa<InOutTypeRepr>(element.Type) || isa<SharedTypeRepr>(element.Type))
+    // Parse the type annotation.
+    auto type = parseType(diag::expected_type);
+    if (type.hasCodeCompletion())
+      return makeParserCodeCompletionStatus();
+    if (type.isNull())
+      return makeParserError();
+    element.Type = type.get();
+
+    // Complain obsoleted 'inout' position; (inout name: Ty)
+    if (ObsoletedInOutLoc.isValid()) {
+      if (isa<InOutTypeRepr>(element.Type) ||
+          isa<SharedTypeRepr>(element.Type)) {
+        // If the parsed type is already a inout type et al, just remove it.
         diagnose(Tok, diag::parameter_specifier_repeated)
-          .fixItRemove(SpecifierLoc);
-      else
-        element.Type = new (Context) InOutTypeRepr(element.Type, SpecifierLoc);
+            .fixItRemove(ObsoletedInOutLoc);
+      } else {
+        diagnose(ObsoletedInOutLoc, diag::inout_as_attr_disallowed, "'inout'")
+            .fixItRemove(ObsoletedInOutLoc)
+            .fixItInsert(element.Type->getStartLoc(), "inout ");
+        // Build inout type. Note that we bury the inout locator within the
+        // named locator. This is weird but required by Sema apparently.
+        element.Type =
+            new (Context) InOutTypeRepr(element.Type, ObsoletedInOutLoc);
+      }
     }
 
-    ElementsR.push_back(element);
+    // Parse optional '...'.
+    if (Tok.isEllipsis()) {
+      auto ElementEllipsisLoc = consumeToken();
+      if (EllipsisLoc.isInvalid()) {
+        EllipsisLoc = ElementEllipsisLoc;
+        EllipsisIdx = ElementsR.size();
+      } else {
+        diagnose(ElementEllipsisLoc, diag::multiple_ellipsis_in_tuple)
+          .highlight(EllipsisLoc)
+          .fixItRemove(ElementEllipsisLoc);
+      }
+    }
 
     // Parse '= expr' here so we can complain about it directly, rather
     // than dying when we see it.
     if (Tok.is(tok::equal)) {
+      SyntaxParsingContext InitContext(SyntaxContext,
+                                       SyntaxKind::InitializerClause);
       SourceLoc equalLoc = consumeToken(tok::equal);
       auto init = parseExpr(diag::expected_init_value);
       auto inFlight = diagnose(equalLoc, diag::tuple_type_init);
@@ -921,36 +978,22 @@
         inFlight.fixItRemove(SourceRange(equalLoc, init.get()->getEndLoc()));
     }
 
-    if (Tok.isEllipsis()) {
-      if (EllipsisLoc.isValid()) {
-        diagnose(Tok, diag::multiple_ellipsis_in_tuple)
-          .highlight(EllipsisLoc)
-          .fixItRemove(Tok.getLoc());
-        (void)consumeToken();
-      } else {
-        EllipsisLoc = consumeToken();
-        EllipsisIdx = ElementsR.size() - 1;
-      }
-    }
-    if (Tok.is(tok::comma)) {
+    // Record the ',' location.
+    if (Tok.is(tok::comma))
       element.TrailingCommaLoc = Tok.getLoc();
-    }
+
+    ElementsR.push_back(element);
     return makeParserSuccess();
   });
 
-  if (EllipsisLoc.isValid() && ElementsR.empty()) {
-    EllipsisLoc = SourceLoc();
-  }
-
   if (EllipsisLoc.isInvalid())
     EllipsisIdx = ElementsR.size();
 
-  // If there were any labels, figure out which labels should go into the type
-  // representation.
-
   bool isFunctionType = Tok.isAny(tok::arrow, tok::kw_throws,
                                   tok::kw_rethrows);
 
+  // If there were any labels, figure out which labels should go into the type
+  // representation.
   for (auto &element : ElementsR) {
     // True tuples have labels.
     if (!isFunctionType) {
@@ -983,11 +1026,11 @@
         diag.fixItReplace(SourceRange(element.NameLoc), "_");
     }
 
-    if (element.NameLoc.isValid() || element.SecondNameLoc.isValid()) {
+    if (element.SecondNameLoc.isValid()) {
       // Form the named parameter type representation.
+      element.UnderscoreLoc = element.NameLoc;
       element.Name = element.SecondName;
       element.NameLoc = element.SecondNameLoc;
-      element.UnderscoreLoc = element.NameLoc;
     }
   }
 
diff --git a/lib/Parse/Parser.cpp b/lib/Parse/Parser.cpp
index b910327..f09cf19 100644
--- a/lib/Parse/Parser.cpp
+++ b/lib/Parse/Parser.cpp
@@ -460,9 +460,8 @@
 
   auto ParserPos = State->takeParserPosition();
   if (ParserPos.isValid() &&
-      SourceMgr.findBufferContainingLoc(ParserPos.Loc) == L->getBufferID()) {
-    auto BeginParserPosition = getParserPosition(ParserPos);
-    restoreParserPosition(BeginParserPosition);
+      L->isStateForCurrentBuffer(ParserPos.LS)) {
+    restoreParserPosition(ParserPos);
     InPoundLineEnvironment = State->InPoundLineEnvironment;
   }
 }
@@ -844,6 +843,10 @@
     return SyntaxKind::TupleElement;
   case SyntaxKind::FunctionParameterList:
     return SyntaxKind::FunctionParameter;
+  case SyntaxKind::TupleTypeElementList:
+    return SyntaxKind::TupleTypeElement;
+  case SyntaxKind::TuplePatternElementList:
+    return SyntaxKind::TuplePatternElement;
   default:
     return SyntaxKind::Unknown;
   }
@@ -859,6 +862,7 @@
   SyntaxKind ElementKind = getListElementKind(Kind);
 
   if (Tok.is(RightK)) {
+    ListContext.reset();
     RightLoc = consumeToken(RightK);
     return makeParserSuccess();
   }
diff --git a/lib/PrintAsObjC/PrintAsObjC.cpp b/lib/PrintAsObjC/PrintAsObjC.cpp
index 9d64c74..845e199 100644
--- a/lib/PrintAsObjC/PrintAsObjC.cpp
+++ b/lib/PrintAsObjC/PrintAsObjC.cpp
@@ -679,7 +679,14 @@
 
     if (makeNewUnavailable) {
       assert(!makeNewExplicitlyAvailable);
-      os << "+ (nonnull instancetype)new SWIFT_UNAVAILABLE;\n";
+      // Downgrade this to a warning in pre-Swift-5 mode. This isn't perfect
+      // because it's a diagnostic inflicted on /clients/, but it's close
+      // enough. It really is invalid to call +new when -init is unavailable.
+      StringRef annotationName = "SWIFT_UNAVAILABLE_MSG";
+      if (!M.getASTContext().isSwiftVersionAtLeast(5))
+        annotationName = "SWIFT_DEPRECATED_MSG";
+      os << "+ (nonnull instancetype)new " << annotationName
+         << "(\"-init is unavailable\");\n";
     } else if (makeNewExplicitlyAvailable) {
       os << "+ (nonnull instancetype)new;\n";
     }
diff --git a/lib/SIL/DynamicCasts.cpp b/lib/SIL/DynamicCasts.cpp
index 48e6546..072055e 100644
--- a/lib/SIL/DynamicCasts.cpp
+++ b/lib/SIL/DynamicCasts.cpp
@@ -737,6 +737,8 @@
 
     bool isAddress() const { return Value->getType().isAddress(); }
 
+    SILType getSILType() const { return Value->getType(); }
+
     Source() = default;
     Source(SILValue value, CanType formalType)
       : Value(value), FormalType(formalType) {}
@@ -758,6 +760,12 @@
       assert(!value->getType().isAddress());
       return { value, FormalType };
     }
+    SILType getSILType() const {
+      if (isAddress())
+        return Address->getType();
+      else
+        return LoweredType;
+    }
 
     Target() = default;
     Target(SILValue address, CanType formalType)
@@ -813,7 +821,8 @@
     }
 
     Source emitSameType(Source source, Target target) {
-      assert(source.FormalType == target.FormalType);
+      assert(source.FormalType == target.FormalType ||
+             source.getSILType() == target.getSILType());
 
       auto &srcTL = getTypeLowering(source.Value->getType());
 
@@ -845,15 +854,15 @@
     }
 
     Source emit(Source source, Target target) {
-      if (source.FormalType == target.FormalType)
+      if (source.FormalType == target.FormalType ||
+          source.getSILType() == target.getSILType())
         return emitSameType(source, target);
 
       // Handle subtype conversions involving optionals.
       OptionalTypeKind sourceOptKind;
       if (auto sourceObjectType =
             source.FormalType.getAnyOptionalObjectType(sourceOptKind)) {
-        return emitOptionalToOptional(source, sourceOptKind, sourceObjectType,
-                                      target);
+        return emitOptionalToOptional(source, sourceObjectType, target);
       }
       assert(!target.FormalType.getAnyOptionalObjectType());
 
@@ -893,7 +902,6 @@
     }
 
     Source emitOptionalToOptional(Source source,
-                                  OptionalTypeKind sourceOptKind,
                                   CanType sourceObjectType,
                                   Target target) {
       // Switch on the incoming value.
@@ -903,8 +911,8 @@
 
       // Emit the switch.
       std::pair<EnumElementDecl*, SILBasicBlock*> cases[] = {
-        { Ctx.getOptionalSomeDecl(sourceOptKind), someBB },
-        { Ctx.getOptionalNoneDecl(sourceOptKind), noneBB },
+        { Ctx.getOptionalSomeDecl(), someBB },
+        { Ctx.getOptionalNoneDecl(), noneBB },
       };
       if (source.isAddress()) {
         B.createSwitchEnumAddr(Loc, source.Value, /*default*/ nullptr, cases);
@@ -915,7 +923,7 @@
       // Create the Some block, which recurses.
       B.setInsertionPoint(someBB);
       {
-        auto sourceSomeDecl = Ctx.getOptionalSomeDecl(sourceOptKind);
+        auto sourceSomeDecl = Ctx.getOptionalSomeDecl();
 
         SILType loweredSourceObjectType =
           source.Value->getType().getEnumElementType(sourceSomeDecl, M);
diff --git a/lib/SIL/Linker.cpp b/lib/SIL/Linker.cpp
index ba0962f..b51f426 100644
--- a/lib/SIL/Linker.cpp
+++ b/lib/SIL/Linker.cpp
@@ -311,6 +311,13 @@
   while (!Worklist.empty()) {
     auto *Fn = Worklist.pop_back_val();
 
+    if (Fn->getModule().isSerialized()) {
+      // If the containing module has been serialized,
+      // Remove The Serialized state (if any)
+      //  This allows for more optimizations
+      Fn->setSerialized(IsSerialized_t::IsNotSerialized);
+    }
+
     DEBUG(llvm::dbgs() << "Process imports in function: "
                        << Fn->getName() << "\n");
 
diff --git a/lib/SIL/OptimizationRemark.cpp b/lib/SIL/OptimizationRemark.cpp
index beaddae..0edbcea 100644
--- a/lib/SIL/OptimizationRemark.cpp
+++ b/lib/SIL/OptimizationRemark.cpp
@@ -58,6 +58,11 @@
         Loc = F->getLocation().getSourceLoc();
 }
 
+Argument::Argument(StringRef Key, SILType *Ty) : Key(Key) {
+  llvm::raw_string_ostream OS(Val);
+  Ty->print(OS);
+}
+
 template <typename DerivedT> std::string Remark<DerivedT>::getMsg() const {
   std::string Str;
   llvm::raw_string_ostream OS(Str);
diff --git a/lib/SIL/SILArgument.cpp b/lib/SIL/SILArgument.cpp
index 87ed4af..f6a36fc 100644
--- a/lib/SIL/SILArgument.cpp
+++ b/lib/SIL/SILArgument.cpp
@@ -27,7 +27,8 @@
                          SILType Ty, ValueOwnershipKind OwnershipKind,
                          const ValueDecl *D)
     : ValueBase(ChildKind, Ty, IsRepresentative::Yes), ParentBB(ParentBB),
-      Decl(D), OwnershipKind(OwnershipKind) {
+      Decl(D) {
+  Bits.SILArgument.VOKind = static_cast<unsigned>(OwnershipKind);
   ParentBB->insertArgument(ParentBB->args_end(), this);
 }
 
@@ -35,7 +36,8 @@
                          SILBasicBlock::arg_iterator Pos, SILType Ty,
                          ValueOwnershipKind OwnershipKind, const ValueDecl *D)
     : ValueBase(ChildKind, Ty, IsRepresentative::Yes), ParentBB(ParentBB),
-      Decl(D), OwnershipKind(OwnershipKind) {
+      Decl(D) {
+  Bits.SILArgument.VOKind = static_cast<unsigned>(OwnershipKind);
   // Function arguments need to have a decl.
   assert(
     !ParentBB->getParent()->isBare() &&
diff --git a/lib/SIL/SILBasicBlock.cpp b/lib/SIL/SILBasicBlock.cpp
index 957136d..300230d 100644
--- a/lib/SIL/SILBasicBlock.cpp
+++ b/lib/SIL/SILBasicBlock.cpp
@@ -63,7 +63,7 @@
   InstList.clearAndLeakNodesUnsafely();
 }
 
-int SILBasicBlock::getDebugID() {
+int SILBasicBlock::getDebugID() const {
   if (!getParent())
     return -1;
   int idx = 0;
diff --git a/lib/SIL/SILBuilder.cpp b/lib/SIL/SILBuilder.cpp
index 43f9a26..8dc3d5b 100644
--- a/lib/SIL/SILBuilder.cpp
+++ b/lib/SIL/SILBuilder.cpp
@@ -417,8 +417,9 @@
 
   while (I && I->getNumOperands() == 1 &&
          I->getNumTypeDependentOperands() == 0) {
-    // All the open instructions are single-value instructions.
-    auto SVI = dyn_cast<SingleValueInstruction>(I->getOperand(0));
+    // All the open instructions are single-value instructions.  Operands may
+    // be null when code is being transformed.
+    auto SVI = dyn_cast_or_null<SingleValueInstruction>(I->getOperand(0));
     // Within SimplifyCFG this function may be called for an instruction
     // within unreachable code. And within an unreachable block it can happen
     // that defs do not dominate uses (because there is no dominance defined).
diff --git a/lib/SIL/SILDeclRef.cpp b/lib/SIL/SILDeclRef.cpp
index 1ddfd37..29b41c2 100644
--- a/lib/SIL/SILDeclRef.cpp
+++ b/lib/SIL/SILDeclRef.cpp
@@ -844,6 +844,18 @@
   return SILDeclRef();
 }
 
+SILDeclRef SILDeclRef::getOverriddenVTableEntry() const {
+  SILDeclRef cur = *this, next = *this;
+  do {
+    cur = next;
+    if (cur.requiresNewVTableEntry())
+      return cur;
+    next = cur.getNextOverriddenVTableEntry();
+  } while (next);
+
+  return cur;
+}
+
 SILLocation SILDeclRef::getAsRegularLocation() const {
   if (hasDecl())
     return RegularLocation(getDecl());
diff --git a/lib/SIL/SILFunction.cpp b/lib/SIL/SILFunction.cpp
index 51ea498..4c1e8be 100644
--- a/lib/SIL/SILFunction.cpp
+++ b/lib/SIL/SILFunction.cpp
@@ -444,6 +444,11 @@
   if (hasValidLinkageForFragileInline())
     return true;
 
+  // If the containing module has been serialized
+  if (getModule().isSerialized()) {
+    return true;
+  }
+
   // Otherwise, only public functions can be referenced.
   return hasPublicVisibility(getLinkage());
 }
diff --git a/lib/SIL/SILFunctionType.cpp b/lib/SIL/SILFunctionType.cpp
index a3a887d..bef4d13 100644
--- a/lib/SIL/SILFunctionType.cpp
+++ b/lib/SIL/SILFunctionType.cpp
@@ -206,6 +206,29 @@
                               witnessMethodConformance);
 }
 
+CanSILFunctionType
+SILFunctionType::getWithRepresentation(Representation repr) {
+  return getWithExtInfo(getExtInfo().withRepresentation(repr));
+}
+
+CanSILFunctionType SILFunctionType::getWithExtInfo(ExtInfo newExt) {
+  auto oldExt = getExtInfo();
+  if (newExt == oldExt)
+    return CanSILFunctionType(this);
+
+  auto calleeConvention =
+    (newExt.hasContext()
+       ? (oldExt.hasContext()
+            ? getCalleeConvention()
+            : Lowering::DefaultThickCalleeConvention)
+       : ParameterConvention::Direct_Unowned);
+
+  return get(getGenericSignature(), newExt, getCoroutineKind(),
+             calleeConvention, getParameters(), getYields(),
+             getResults(), getOptionalErrorResult(), getASTContext(),
+             getWitnessMethodConformanceOrNone());
+}
+
 namespace {
 
 enum class ConventionsKind : uint8_t {
@@ -2119,18 +2142,6 @@
                          /*resolver*/nullptr);
 }
 
-SILDeclRef TypeConverter::getOverriddenVTableEntry(SILDeclRef method) {
-  SILDeclRef cur = method, next = method;
-  do {
-    cur = next;
-    if (cur.requiresNewVTableEntry())
-      return cur;
-    next = cur.getNextOverriddenVTableEntry();
-  } while (next);
-
-  return cur;
-}
-
 // FIXME: This makes me very upset. Can we do without this?
 static CanType copyOptionalityFromDerivedToBase(TypeConverter &tc,
                                                 CanType derived,
diff --git a/lib/SIL/SILInstruction.cpp b/lib/SIL/SILInstruction.cpp
index 998f777..b2aa996 100644
--- a/lib/SIL/SILInstruction.cpp
+++ b/lib/SIL/SILInstruction.cpp
@@ -1388,33 +1388,17 @@
 
 void MultipleValueInstructionResult::setOwnershipKind(
     ValueOwnershipKind NewKind) {
-  // Get the original data, merge in our new lower values and then reset the
-  // value in our data.
-  //
-  // *NOTE* This is a two phase set so if this code ever needs to be used in a
-  // concurrent context, a this will need to be updated.
-  uint64_t OriginalData = getSubclassData();
-  uint64_t NewData =
-      (OriginalData & ~ValueOwnershipKind::Mask) | uint64_t(NewKind);
-  setSubclassData(NewData);
+  Bits.MultipleValueInstructionResult.VOKind = unsigned(NewKind);
 }
 
 void MultipleValueInstructionResult::setIndex(unsigned NewIndex) {
-  // We only take the last 3 bytes for simplicity. If more bits are needed at
-  // some point, we can take 5 bits we are burning here and combine them with
-  // 6 bits from SILType, Operand to get more storage. But to do so now would
-  // be premature optimization since we could potentially use those bits for
-  // flags. 500k fields is probably enough.
-  assert(NewIndex < (1 << NumIndexBits) && "Unrepresentable index");
-  uint64_t OriginalData = getSubclassData();
-  uint64_t NewData = (OriginalData & ~(IndexMask << IndexBitOffset)) |
-                     (NewIndex << IndexBitOffset);
-  setSubclassData(NewData);
+  // We currently use 32 bits to store the Index. A previous comment wrote
+  // that "500k fields is probably enough".
+  Bits.MultipleValueInstructionResult.Index = NewIndex;
 }
 
 ValueOwnershipKind MultipleValueInstructionResult::getOwnershipKind() const {
-  uint64_t Data = getSubclassData() & ValueOwnershipKind::Mask;
-  return ValueOwnershipKind(Data);
+  return ValueOwnershipKind(Bits.MultipleValueInstructionResult.VOKind);
 }
 
 MultipleValueInstruction *MultipleValueInstructionResult::getParent() {
diff --git a/lib/SIL/SILInstructions.cpp b/lib/SIL/SILInstructions.cpp
index ec236c0..7d00386 100644
--- a/lib/SIL/SILInstructions.cpp
+++ b/lib/SIL/SILInstructions.cpp
@@ -125,24 +125,30 @@
 }
 
 TailAllocatedDebugVariable::TailAllocatedDebugVariable(SILDebugVariable Var,
-                                                       char *buf)
-    : ArgNo(Var.ArgNo), NameLength(Var.Name.size()), Constant(Var.Constant) {
-  assert((Var.ArgNo < (2<<16)) && "too many arguments");
-  assert((NameLength < (2<<15)) && "variable name too long");
-  memcpy(buf, Var.Name.data(), NameLength);
+                                                       char *buf) {
+  Data.ArgNo = Var.ArgNo;
+  Data.Constant = Var.Constant;
+  Data.NameLength = Var.Name.size();
+  assert(Data.ArgNo == Var.ArgNo && "Truncation");
+  assert(Data.NameLength == Var.Name.size() && "Truncation");
+  memcpy(buf, Var.Name.data(), Var.Name.size());
 }
 
 StringRef TailAllocatedDebugVariable::getName(const char *buf) const {
-  return NameLength ? StringRef(buf, NameLength) : StringRef();
+  return Data.NameLength ? StringRef(buf, Data.NameLength) : StringRef();
 }
 
 AllocStackInst::AllocStackInst(SILDebugLocation Loc, SILType elementType,
                                ArrayRef<SILValue> TypeDependentOperands,
                                SILFunction &F,
                                SILDebugVariable Var)
-    : InstructionBase(Loc, elementType.getAddressType()),
-      NumOperands(TypeDependentOperands.size()),
-      VarInfo(Var, getTrailingObjects<char>()) {
+    : InstructionBase(Loc, elementType.getAddressType()) {
+  SILInstruction::Bits.AllocStackInst.NumOperands =
+    TypeDependentOperands.size();
+  assert(SILInstruction::Bits.AllocStackInst.NumOperands ==
+         TypeDependentOperands.size() && "Truncation");
+  SILInstruction::Bits.AllocStackInst.VarInfo =
+    TailAllocatedDebugVariable(Var, getTrailingObjects<char>()).getRawValue();
   TrailingOperandsList::InitOperandsList(getAllOperands().begin(), this,
                                          TypeDependentOperands);
 }
@@ -173,11 +179,10 @@
                                    bool objc, bool canBeOnStack,
                                    ArrayRef<SILType> ElementTypes,
                                    ArrayRef<SILValue> AllOperands)
-    : AllocationInst(Kind, Loc, ObjectType),
-      StackPromotable(canBeOnStack),
-      NumTailTypes(ElementTypes.size()),
-      ObjC(objc),
-      Operands(this, AllOperands) {
+    : AllocationInst(Kind, Loc, ObjectType), Operands(this, AllOperands) {
+  SILInstruction::Bits.AllocRefInstBase.ObjC = objc;
+  SILInstruction::Bits.AllocRefInstBase.OnStack = canBeOnStack;
+  SILInstruction::Bits.AllocRefInstBase.NumTailTypes = ElementTypes.size();
   static_assert(IsTriviallyCopyable<SILType>::value,
                 "assuming SILType is trivially copyable");
   assert(!objc || ElementTypes.size() == 0);
@@ -640,8 +645,8 @@
 
 IntegerLiteralInst::IntegerLiteralInst(SILDebugLocation Loc, SILType Ty,
                                        const llvm::APInt &Value)
-    : InstructionBase(Loc, Ty),
-      numBits(Value.getBitWidth()) {
+    : InstructionBase(Loc, Ty) {
+  SILInstruction::Bits.IntegerLiteralInst.numBits = Value.getBitWidth();
   std::uninitialized_copy_n(Value.getRawData(), Value.getNumWords(),
                             getTrailingObjects<llvm::APInt::WordType>());
 }
@@ -679,16 +684,17 @@
 
 /// getValue - Return the APInt for the underlying integer literal.
 APInt IntegerLiteralInst::getValue() const {
+  auto numBits = SILInstruction::Bits.IntegerLiteralInst.numBits;
   return APInt(numBits, {getTrailingObjects<llvm::APInt::WordType>(),
                          getWordsForBitWidth(numBits)});
 }
 
 FloatLiteralInst::FloatLiteralInst(SILDebugLocation Loc, SILType Ty,
                                    const APInt &Bits)
-    : InstructionBase(Loc, Ty),
-      numBits(Bits.getBitWidth()) {
-        std::uninitialized_copy_n(Bits.getRawData(), Bits.getNumWords(),
-                                  getTrailingObjects<llvm::APInt::WordType>());
+    : InstructionBase(Loc, Ty) {
+  SILInstruction::Bits.FloatLiteralInst.numBits = Bits.getBitWidth();
+  std::uninitialized_copy_n(Bits.getRawData(), Bits.getNumWords(),
+                            getTrailingObjects<llvm::APInt::WordType>());
 }
 
 FloatLiteralInst *FloatLiteralInst::create(SILDebugLocation Loc, SILType Ty,
@@ -718,6 +724,7 @@
 }
 
 APInt FloatLiteralInst::getBits() const {
+  auto numBits = SILInstruction::Bits.FloatLiteralInst.numBits;
   return APInt(numBits, {getTrailingObjects<llvm::APInt::WordType>(),
                          getWordsForBitWidth(numBits)});
 }
@@ -778,8 +785,9 @@
 StoreInst::StoreInst(
     SILDebugLocation Loc, SILValue Src, SILValue Dest,
     StoreOwnershipQualifier Qualifier = StoreOwnershipQualifier::Unqualified)
-    : InstructionBase(Loc), Operands(this, Src, Dest),
-      OwnershipQualifier(Qualifier) {}
+    : InstructionBase(Loc), Operands(this, Src, Dest) {
+  SILInstruction::Bits.StoreInst.OwnershipQualifier = unsigned(Qualifier);
+}
 
 StoreBorrowInst::StoreBorrowInst(SILDebugLocation DebugLoc, SILValue Src,
                                  SILValue Dest)
@@ -846,9 +854,11 @@
 CopyAddrInst::CopyAddrInst(SILDebugLocation Loc, SILValue SrcLValue,
                            SILValue DestLValue, IsTake_t isTakeOfSrc,
                            IsInitialization_t isInitializationOfDest)
-    : InstructionBase(Loc), IsTakeOfSrc(isTakeOfSrc),
-      IsInitializationOfDest(isInitializationOfDest),
-      Operands(this, SrcLValue, DestLValue) {}
+    : InstructionBase(Loc), Operands(this, SrcLValue, DestLValue) {
+    SILInstruction::Bits.CopyAddrInst.IsTakeOfSrc = bool(isTakeOfSrc);
+    SILInstruction::Bits.CopyAddrInst.IsInitializationOfDest =
+      bool(isInitializationOfDest);
+  }
 
 BindMemoryInst *
 BindMemoryInst::create(SILDebugLocation Loc, SILValue Base, SILValue Index,
@@ -932,8 +942,8 @@
 
 MetatypeInst::MetatypeInst(SILDebugLocation Loc, SILType Metatype,
                            ArrayRef<SILValue> TypeDependentOperands)
-    : InstructionBase(Loc, Metatype),
-      NumOperands(TypeDependentOperands.size()) {
+    : InstructionBase(Loc, Metatype) {
+  SILInstruction::Bits.MetatypeInst.NumOperands = TypeDependentOperands.size();
   TrailingOperandsList::InitOperandsList(getAllOperands().begin(), this,
                                          TypeDependentOperands);
 }
@@ -1304,9 +1314,9 @@
                                  SILBasicBlock *DefaultBB,
                                  ArrayRef<SILValue> Cases,
                                  ArrayRef<SILBasicBlock *> BBs)
-    : InstructionBase(Loc), NumCases(Cases.size()),
-      HasDefault(bool(DefaultBB)), Operands(this, Cases, Operand) {
-
+    : InstructionBase(Loc), Operands(this, Cases, Operand) {
+  SILInstruction::Bits.SwitchValueInst.HasDefault = bool(DefaultBB);
+  SILInstruction::Bits.SwitchValueInst.NumCases = Cases.size();
   // Initialize the successor array.
   auto *succs = getSuccessorBuf();
   unsigned OperandBitWidth = 0;
@@ -1340,14 +1350,14 @@
     ::new (succs + i) SILSuccessor(this, BBs[i]);
   }
 
-  if (HasDefault)
-    ::new (succs + NumCases) SILSuccessor(this, DefaultBB);
+  if (hasDefault())
+    ::new (succs + getNumCases()) SILSuccessor(this, DefaultBB);
 }
 
 SwitchValueInst::~SwitchValueInst() {
   // Destroy the successor records to keep the CFG up to date.
   auto *succs = getSuccessorBuf();
-  for (unsigned i = 0, end = NumCases + HasDefault; i < end; ++i) {
+  for (unsigned i = 0, end = getNumCases() + hasDefault(); i < end; ++i) {
     succs[i].~SILSuccessor();
   }
 }
@@ -1486,8 +1496,9 @@
     SILBasicBlock *DefaultBB,
     ArrayRef<std::pair<EnumElementDecl *, SILBasicBlock *>> CaseBBs,
     Optional<ArrayRef<ProfileCounter>> CaseCounts, ProfileCounter DefaultCount)
-    : TermInst(Kind, Loc), Operands(this, Operand), NumCases(CaseBBs.size()),
-      HasDefault(bool(DefaultBB)) {
+    : TermInst(Kind, Loc), Operands(this, Operand) {
+  SILInstruction::Bits.SwitchEnumInstBase.HasDefault = bool(DefaultBB);
+  SILInstruction::Bits.SwitchEnumInstBase.NumCases = CaseBBs.size();
   // Initialize the case and successor arrays.
   auto *cases = getCaseBuf();
   auto *succs = getSuccessorBuf();
@@ -1501,8 +1512,8 @@
     }
   }
 
-  if (HasDefault) {
-    ::new (succs + NumCases) SILSuccessor(this, DefaultBB, DefaultCount);
+  if (hasDefault()) {
+    ::new (succs + getNumCases()) SILSuccessor(this, DefaultBB, DefaultCount);
   }
 }
 
@@ -1592,7 +1603,7 @@
 SwitchEnumInstBase::~SwitchEnumInstBase() {
   // Destroy the successor records to keep the CFG up to date.
   auto *succs = getSuccessorBuf();
-  for (unsigned i = 0, end = NumCases + HasDefault; i < end; ++i) {
+  for (unsigned i = 0, end = getNumCases() + hasDefault(); i < end; ++i) {
     succs[i].~SILSuccessor();
   }
 }
@@ -2108,15 +2119,21 @@
   void *Buffer = Mod.allocateInst(size, alignof(ConvertFunctionInst));
   auto *CFI = ::new (Buffer)
       ConvertFunctionInst(DebugLoc, Operand, TypeDependentOperands, Ty);
-  // Make sure we are not performing ABI-incompatible conversions.
-  CanSILFunctionType opTI =
-      CFI->getOperand()->getType().castTo<SILFunctionType>();
-  (void)opTI;
-  CanSILFunctionType resTI =
-      CFI->getOperand()->getType().castTo<SILFunctionType>();
-  (void)resTI;
-  assert(opTI->isABICompatibleWith(resTI).isCompatible() &&
-         "Can not convert in between ABI incompatible function types");
+  // If we do not have lowered SIL, make sure that are not performing
+  // ABI-incompatible conversions.
+  //
+  // *NOTE* We purposely do not use an early return here to ensure that in
+  // builds without assertions this whole if statement is optimized out.
+  if (F.getModule().getStage() != SILStage::Lowered) {
+    // Make sure we are not performing ABI-incompatible conversions.
+    CanSILFunctionType opTI =
+        CFI->getOperand()->getType().castTo<SILFunctionType>();
+    (void)opTI;
+    CanSILFunctionType resTI = CFI->getType().castTo<SILFunctionType>();
+    (void)resTI;
+    assert(opTI->isABICompatibleWith(resTI).isCompatible() &&
+           "Can not convert in between ABI incompatible function types");
+  }
   return CFI;
 }
 
diff --git a/lib/SIL/SILValue.cpp b/lib/SIL/SILValue.cpp
index 8123ae6..42de105 100644
--- a/lib/SIL/SILValue.cpp
+++ b/lib/SIL/SILValue.cpp
@@ -29,13 +29,6 @@
 /// changes that cause the asserts the fire, please update them. The purpose is
 /// to prevent these predicates from changing values by mistake.
 
-// SILNode uses its padding bits to delegate space to its subclasses. That being
-// said, we do not want to by mistake increase the size as our usage of the
-// padding bits changes over time. So we assert that our value is still exactly
-// 8 bytes in size.
-static_assert((sizeof(SILNode) * 8) == SILNode::NumTotalSILNodeBits,
-              "Expected SILNode to be exactly 8 bytes in size");
-
 //===----------------------------------------------------------------------===//
 //                       Check SILValue Type Properties
 //===----------------------------------------------------------------------===//
diff --git a/lib/SILGen/SILGenApply.cpp b/lib/SILGen/SILGenApply.cpp
index 285db67..7a39dc0 100644
--- a/lib/SILGen/SILGenApply.cpp
+++ b/lib/SILGen/SILGenApply.cpp
@@ -357,7 +357,7 @@
   static Callee forClassMethod(SILGenFunction &SGF,
                                SILDeclRef c, SubstitutionList subs,
                                SILLocation l) {
-    auto base = SGF.SGM.Types.getOverriddenVTableEntry(c);
+    auto base = c.getOverriddenVTableEntry();
     auto &baseCI = SGF.getConstantInfo(base);
     auto &derivedCI = SGF.getConstantInfo(c);
     return Callee(Kind::ClassMethod, SGF, c,
@@ -563,7 +563,7 @@
       ManagedValue castValue = borrowedCastToOriginalSelfType(
         SGF, Loc, *borrowedSelf);
 
-      auto base = SGF.SGM.Types.getOverriddenVTableEntry(*constant);
+      auto base = constant->getOverriddenVTableEntry();
       auto constantInfo =
           SGF.SGM.Types.getConstantOverrideInfo(*constant, base);
 
@@ -642,7 +642,7 @@
       return createCalleeTypeInfo(SGF, constant, constantInfo.getSILType());
     }
     case Kind::SuperMethod: {
-      auto base = SGF.SGM.Types.getOverriddenVTableEntry(*constant);
+      auto base = constant->getOverriddenVTableEntry();
       auto constantInfo =
           SGF.SGM.Types.getConstantOverrideInfo(*constant, base);
       return createCalleeTypeInfo(SGF, constant, constantInfo.getSILType());
diff --git a/lib/SILGen/SILGenBuilder.cpp b/lib/SILGen/SILGenBuilder.cpp
index a3fcc38..e7d6b73 100644
--- a/lib/SILGen/SILGenBuilder.cpp
+++ b/lib/SILGen/SILGenBuilder.cpp
@@ -110,6 +110,30 @@
       closureTy.getAs<SILFunctionType>()->getCalleeConvention());
 }
 
+ManagedValue SILGenBuilder::createPartialApply(SILLocation loc, SILValue fn,
+                                               SILType substFnTy,
+                                               SubstitutionList subs,
+                                               ArrayRef<ManagedValue> args,
+                                               SILType closureTy) {
+  llvm::SmallVector<SILValue, 8> values;
+  transform(args, std::back_inserter(values), [&](ManagedValue mv) -> SILValue {
+    return mv.forward(getSILGenFunction());
+  });
+  SILValue result = SILGenBuilder::createPartialApply(loc, fn, substFnTy, subs,
+                                                      values, closureTy);
+  // Partial apply instructions create a box, so we need to put on a cleanup.
+  return getSILGenFunction().emitManagedRValueWithCleanup(result);
+}
+
+ManagedValue SILGenBuilder::createConvertFunction(SILLocation loc,
+                                                  ManagedValue fn,
+                                                  SILType resultTy) {
+  CleanupCloner cloner(*this, fn);
+  SILValue result = SILBuilder::createConvertFunction(
+      loc, fn.forward(getSILGenFunction()), resultTy);
+  return cloner.clone(result);
+}
+
 BuiltinInst *SILGenBuilder::createBuiltin(SILLocation loc, Identifier name,
                                           SILType resultTy,
                                           SubstitutionList subs,
@@ -601,6 +625,11 @@
   return ManagedValue::forUnmanaged(tempResult);
 }
 
+ManagedValue SILGenBuilder::createManagedFunctionRef(SILLocation loc,
+                                                     SILFunction *f) {
+  return ManagedValue::forUnmanaged(SILBuilder::createFunctionRef(loc, f));
+}
+
 ManagedValue SILGenBuilder::createTupleElementAddr(SILLocation Loc,
                                                    ManagedValue Base,
                                                    unsigned Index,
diff --git a/lib/SILGen/SILGenBuilder.h b/lib/SILGen/SILGenBuilder.h
index 6c34186..34871aa 100644
--- a/lib/SILGen/SILGenBuilder.h
+++ b/lib/SILGen/SILGenBuilder.h
@@ -88,6 +88,10 @@
                                        SILType substFnTy, SubstitutionList subs,
                                        ArrayRef<SILValue> args,
                                        SILType closureTy);
+  ManagedValue createPartialApply(SILLocation loc, SILValue fn,
+                                  SILType substFnTy, SubstitutionList subs,
+                                  ArrayRef<ManagedValue> args,
+                                  SILType closureTy);
 
   BuiltinInst *createBuiltin(SILLocation loc, Identifier name, SILType resultTy,
                              SubstitutionList subs, ArrayRef<SILValue> args);
@@ -310,6 +314,14 @@
   ManagedValue createOptionalSome(SILLocation Loc, ManagedValue Arg);
   ManagedValue createManagedOptionalNone(SILLocation Loc, SILType Type);
 
+  // TODO: Rename this to createFunctionRef once all calls to createFunctionRef
+  // are removed.
+  ManagedValue createManagedFunctionRef(SILLocation loc, SILFunction *f);
+
+  using SILBuilder::createConvertFunction;
+  ManagedValue createConvertFunction(SILLocation loc, ManagedValue fn,
+                                     SILType resultTy);
+
   /// Forward \p value into \p address.
   ///
   /// This will forward value's cleanup (if it has one) into the equivalent
diff --git a/lib/SILGen/SILGenExpr.cpp b/lib/SILGen/SILGenExpr.cpp
index 6fe8722..78b5c9f 100644
--- a/lib/SILGen/SILGenExpr.cpp
+++ b/lib/SILGen/SILGenExpr.cpp
@@ -1906,8 +1906,9 @@
     case SILFunctionType::Representation::Thin: {
       auto v = SGF.B.createThinToThickFunction(
           loc, source.getValue(),
-          SILType::getPrimitiveObjectType(adjustFunctionType(
-              sourceTy, SILFunctionType::Representation::Thick)));
+          SILType::getPrimitiveObjectType(
+            sourceTy->getWithRepresentation(
+              SILFunctionTypeRepresentation::Thick)));
       // FIXME: what if other reabstraction is required?
       return ManagedValue(v, source.getCleanup());
     }
@@ -1933,8 +1934,9 @@
       // Make thick first.
       auto v = SGF.B.createThinToThickFunction(
           loc, source.getValue(),
-          SILType::getPrimitiveObjectType(adjustFunctionType(
-              sourceTy, SILFunctionType::Representation::Thick)));
+          SILType::getPrimitiveObjectType(
+            sourceTy->getWithRepresentation(
+              SILFunctionTypeRepresentation::Thick)));
       source = ManagedValue(v, source.getCleanup());
       LLVM_FALLTHROUGH;
     }
diff --git a/lib/SILGen/SILGenPattern.cpp b/lib/SILGen/SILGenPattern.cpp
index 27910a1..5b94bbc 100644
--- a/lib/SILGen/SILGenPattern.cpp
+++ b/lib/SILGen/SILGenPattern.cpp
@@ -1031,7 +1031,8 @@
         } else {
           Loc = clauses[firstRow].getCasePattern()->getStartLoc();
         }
-        SGF.SGM.diagnose(Loc, diag::unreachable_case, isDefault);
+        if (!isDefault)
+          SGF.SGM.diagnose(Loc, diag::unreachable_case);
       }
     }
   }
diff --git a/lib/SILGen/SILGenPoly.cpp b/lib/SILGen/SILGenPoly.cpp
index 97650fe..ea28a41 100644
--- a/lib/SILGen/SILGenPoly.cpp
+++ b/lib/SILGen/SILGenPoly.cpp
@@ -3001,8 +3001,7 @@
   // Apply any ABI-compatible conversions before doing thin-to-thick.
   if (fnType != newFnType) {
     SILType resTy = SILType::getPrimitiveObjectType(newFnType);
-    fn = SGF.emitManagedRValueWithCleanup(
-        SGF.B.createConvertFunction(Loc, fn.forward(SGF), resTy));
+    fn = SGF.B.createConvertFunction(Loc, fn, resTy);
   }
 
   // Now do thin-to-thick if necessary.
diff --git a/lib/SILGen/SILGenThunk.cpp b/lib/SILGen/SILGenThunk.cpp
index b551a5b..8d1a608 100644
--- a/lib/SILGen/SILGenThunk.cpp
+++ b/lib/SILGen/SILGenThunk.cpp
@@ -120,7 +120,7 @@
 
   // Not every override gets a dispatch thunk; find the least derived one
   // that does.
-  auto base = SGM.M.Types.getOverriddenVTableEntry(constant);
+  auto base = constant.getOverriddenVTableEntry();
 
   if (shouldUseDispatchThunk(base, &F, SGM.M)) {
     auto *thunkFn = SGM.getDispatchThunk(base, NotForDefinition);
@@ -358,8 +358,7 @@
   // The reference to the thunk is likely @noescape, but declarations are always
   // escaping.
   auto thunkDeclType =
-      adjustFunctionType(thunkType, thunkType->getExtInfo().withNoEscape(false),
-                         thunkType->getWitnessMethodConformanceOrNone());
+      thunkType->getWithExtInfo(thunkType->getExtInfo().withNoEscape(false));
 
   // Mangle the reabstraction thunk.
   // Substitute context parameters out of the "from" and "to" types.
diff --git a/lib/SILGen/SILGenType.cpp b/lib/SILGen/SILGenType.cpp
index 3eff408..d1244df 100644
--- a/lib/SILGen/SILGenType.cpp
+++ b/lib/SILGen/SILGenType.cpp
@@ -179,7 +179,7 @@
   SmallVector<std::pair<SILDeclRef, SILDeclRef>, 8> vtableMethods;
 
   SILGenVTable(SILGenModule &SGM, ClassDecl *theClass)
-    : SILVTableVisitor(SGM.Types), SGM(SGM), theClass(theClass) {
+    : SGM(SGM), theClass(theClass) {
     hasFixedLayout = theClass->hasFixedLayout();
   }
 
@@ -827,7 +827,8 @@
 
     // Build a default witness table if this is a protocol.
     if (auto protocol = dyn_cast<ProtocolDecl>(theType)) {
-      if (!protocol->isObjC())
+      if (!protocol->isObjC() &&
+          !protocol->hasFixedLayout())
         SGM.emitDefaultWitnessTable(protocol);
       return;
     }
diff --git a/lib/SILOptimizer/Analysis/CFG.cpp b/lib/SILOptimizer/Analysis/CFG.cpp
index e0e84de..ae8e276 100644
--- a/lib/SILOptimizer/Analysis/CFG.cpp
+++ b/lib/SILOptimizer/Analysis/CFG.cpp
@@ -48,7 +48,7 @@
 
 static bool isTrapNoReturnFunction(ApplyInst *AI) {
   const char *fatalName =
-    MANGLE_AS_STRING(MANGLE_SYM(s18_fatalErrorMessageys12StaticStringV_AcCSutF));
+    MANGLE_AS_STRING(MANGLE_SYM(s18_fatalErrorMessageyys12StaticStringV_AcCSutF));
   auto *Fn = AI->getReferencedFunction();
 
   // We use endswith here since if we specialize fatal error we will always
diff --git a/lib/SILOptimizer/IPO/CapturePropagation.cpp b/lib/SILOptimizer/IPO/CapturePropagation.cpp
index 70c507d..7710a21 100644
--- a/lib/SILOptimizer/IPO/CapturePropagation.cpp
+++ b/lib/SILOptimizer/IPO/CapturePropagation.cpp
@@ -250,8 +250,7 @@
   // expressed as literals. So its callee signature will be the same as its
   // return signature.
   auto NewFTy = getPartialApplyInterfaceResultType(PAI);
-  NewFTy = Lowering::adjustFunctionType(NewFTy,
-                                        SILFunctionType::Representation::Thin);
+  NewFTy = NewFTy->getWithRepresentation(SILFunctionType::Representation::Thin);
 
   GenericEnvironment *GenericEnv = nullptr;
   if (NewFTy->getGenericSignature())
diff --git a/lib/SILOptimizer/Mandatory/DiagnoseStaticExclusivity.cpp b/lib/SILOptimizer/Mandatory/DiagnoseStaticExclusivity.cpp
index 5eef591..7f27ecb 100644
--- a/lib/SILOptimizer/Mandatory/DiagnoseStaticExclusivity.cpp
+++ b/lib/SILOptimizer/Mandatory/DiagnoseStaticExclusivity.cpp
@@ -957,9 +957,62 @@
   }
 }
 
+/// Given a block used as a noescape function argument, attempt to find
+/// the Swift closure that invoking the block will call.
+static SILValue findClosureStoredIntoBlock(SILValue V) {
+  auto FnType = V->getType().castTo<SILFunctionType>();
+  assert(FnType->getRepresentation() == SILFunctionTypeRepresentation::Block);
+
+  // Given a no escape block argument to a function,
+  // pattern match to find the noescape closure that invoking the block
+  // will call:
+  //     %noescape_closure = ...
+  //     %storage = alloc_stack
+  //     %storage_address = project_block_storage %storage
+  //     store %noescape_closure to [init] %storage_address
+  //     %block = init_block_storage_header %storage invoke %thunk
+  //     %arg = copy_block %block
+
+  InitBlockStorageHeaderInst *IBSHI = nullptr;
+
+  // Look through block copies to find the initialization of block storage.
+  while (true) {
+    if (auto *CBI = dyn_cast<CopyBlockInst>(V)) {
+      V = CBI->getOperand();
+      continue;
+    }
+
+    IBSHI = dyn_cast<InitBlockStorageHeaderInst>(V);
+    break;
+  }
+
+  if (!IBSHI)
+    return nullptr;
+
+  SILValue BlockStorage = IBSHI->getBlockStorage();
+  auto *PBSI = BlockStorage->getSingleUserOfType<ProjectBlockStorageInst>();
+  assert(PBSI && "Couldn't find block storage projection");
+
+  auto *SI = PBSI->getSingleUserOfType<StoreInst>();
+  assert(SI && "Couldn't find single store of function into block storage");
+
+  return SI->getSrc();
+}
+
 /// Look through a value passed as a function argument to determine whether
 /// it is a partial_apply.
 static PartialApplyInst *lookThroughForPartialApply(SILValue V) {
+  auto ArgumentFnType = V->getType().castTo<SILFunctionType>();
+  assert(ArgumentFnType->isNoEscape());
+
+  if (ArgumentFnType->getRepresentation() ==
+        SILFunctionTypeRepresentation::Block) {
+    V = findClosureStoredIntoBlock(V);
+
+    if (!V)
+      return nullptr;
+  }
+
   while (true) {
     if (auto CFI = dyn_cast<ConvertFunctionInst>(V)) {
       V = CFI->getOperand();
@@ -977,11 +1030,6 @@
 /// if any of the @inout_aliasable captures passed to those closures have
 /// in-progress accesses that would conflict with any access the summary
 /// says the closure would perform.
-//
-/// TODO: We currently fail to statically diagnose non-escaping closures pased
-/// via @block_storage convention. To enforce this case, we should statically
-/// recognize when the apply takes a block argument that has been initialized to
-/// a non-escaping closure.
 static void checkForViolationsInNoEscapeClosureArguments(
     const StorageMap &Accesses, ApplySite AS, AccessSummaryAnalysis *ASA,
     llvm::SmallVectorImpl<ConflictingAccess> &ConflictingAccesses,
@@ -1023,12 +1071,20 @@
     if (Callee->empty())
       continue;
 
+
+    // For source compatibility reasons, treat conflicts found by
+    // looking through noescape blocks as warnings. A future compiler
+    // will upgrade these to errors.
+    bool ArgumentIsBlock = (ArgumentFnType->getRepresentation() ==
+                            SILFunctionTypeRepresentation::Block);
+
     // Check the closure's captures, which are a suffix of the closure's
     // parameters.
     unsigned StartIndex =
         Callee->getArguments().size() - PAI->getNumArguments();
     checkForViolationWithCall(Accesses, Callee, StartIndex,
-                              PAI->getArguments(), ASA, DiagnoseAsWarning,
+                              PAI->getArguments(), ASA,
+                              DiagnoseAsWarning || ArgumentIsBlock,
                               ConflictingAccesses);
   }
 }
diff --git a/lib/SILOptimizer/Mandatory/MandatoryInlining.cpp b/lib/SILOptimizer/Mandatory/MandatoryInlining.cpp
index 3ddcc14..f0f7a44 100644
--- a/lib/SILOptimizer/Mandatory/MandatoryInlining.cpp
+++ b/lib/SILOptimizer/Mandatory/MandatoryInlining.cpp
@@ -330,9 +330,8 @@
     // matters here is @noescape, so just check for that.
     auto FromCalleeTy = CFI->getOperand()->getType().castTo<SILFunctionType>();
     auto ToCalleeTy = CFI->getType().castTo<SILFunctionType>();
-    auto EscapingCalleeTy = Lowering::adjustFunctionType(
-        ToCalleeTy, ToCalleeTy->getExtInfo().withNoEscape(false),
-        ToCalleeTy->getWitnessMethodConformanceOrNone());
+    auto EscapingCalleeTy =
+      ToCalleeTy->getWithExtInfo(ToCalleeTy->getExtInfo().withNoEscape(false));
     if (FromCalleeTy != EscapingCalleeTy)
       return CalleeValue;
 
diff --git a/lib/SILOptimizer/SILCombiner/SILCombinerApplyVisitors.cpp b/lib/SILOptimizer/SILCombiner/SILCombinerApplyVisitors.cpp
index 9e945dd..3dfef0c 100644
--- a/lib/SILOptimizer/SILCombiner/SILCombinerApplyVisitors.cpp
+++ b/lib/SILOptimizer/SILCombiner/SILCombinerApplyVisitors.cpp
@@ -386,9 +386,9 @@
       // For now, just handle conversion to @noescape, which is irrelevant for
       // direct application of the closure.
       auto ConvertCalleeTy = CFI->getType().castTo<SILFunctionType>();
-      auto EscapingCalleeTy = Lowering::adjustFunctionType(
-          ConvertCalleeTy, ConvertCalleeTy->getExtInfo().withNoEscape(false),
-          ConvertCalleeTy->getWitnessMethodConformanceOrNone());
+      auto EscapingCalleeTy =
+          ConvertCalleeTy->getWithExtInfo(
+            ConvertCalleeTy->getExtInfo().withNoEscape(false));
       if (Use->get()->getType().castTo<SILFunctionType>() == EscapingCalleeTy)
         Uses.append(CFI->getUses().begin(), CFI->getUses().end());
 
diff --git a/lib/SILOptimizer/Transforms/CopyForwarding.cpp b/lib/SILOptimizer/Transforms/CopyForwarding.cpp
index ec8ce27..9cb9245 100644
--- a/lib/SILOptimizer/Transforms/CopyForwarding.cpp
+++ b/lib/SILOptimizer/Transforms/CopyForwarding.cpp
@@ -58,6 +58,7 @@
 //===----------------------------------------------------------------------===//
 
 #define DEBUG_TYPE "copy-forwarding"
+#include "swift/SIL/DebugUtils.h"
 #include "swift/SIL/SILArgument.h"
 #include "swift/SIL/SILBuilder.h"
 #include "swift/SIL/SILVisitor.h"
@@ -67,7 +68,7 @@
 #include "swift/SILOptimizer/PassManager/Passes.h"
 #include "swift/SILOptimizer/PassManager/Transforms.h"
 #include "swift/SILOptimizer/Utils/CFG.h"
-#include "swift/SIL/DebugUtils.h"
+#include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
@@ -158,7 +159,7 @@
     FoundArgIdx = ArgIdx;
     assert(!Oper && "Address can only be passed once as an indirection.");
     Oper = &Args[ArgIdx];
-#ifndef NDEBUG
+#ifdef NDEBUG
     break;
 #endif
   }
@@ -170,6 +171,117 @@
 //                 Forward and backward copy propagation
 //===----------------------------------------------------------------------===//
 
+// Visitor for visitAddressUsers.
+namespace {
+class AddressUserVisitor {
+public:
+  virtual ~AddressUserVisitor() {}
+
+  virtual bool visitNormalUse(SILInstruction *user) = 0;
+  virtual bool visitTake(CopyAddrInst *copy) = 0;
+  virtual bool visitDestroy(DestroyAddrInst *destroy) = 0;
+  virtual bool visitDebugValue(DebugValueAddrInst *debugValue) = 0;
+};
+} // namespace
+
+/// Gather all instructions that use the given `address`
+///
+/// "Normal" uses are a whitelisted set of uses that guarantees the address is
+/// only used as if it refers to a single value and all uses are accounted for
+/// (no address projections).
+///
+/// Takes are "copy_addr [take]"
+///
+/// Destroys are "destroy_addr"
+/// -
+///
+/// If we are unable to find all uses, for example, because we don't look
+/// through struct_element_addr, then return false.
+///
+/// The collected use points will be consulted during forward and backward
+/// copy propagation.
+///
+/// \param ignoredUser will be ignored if it is is non-null.
+static bool visitAddressUsers(SILValue address, SILInstruction *ignoredUser,
+                              AddressUserVisitor &visitor) {
+  for (Operand *use : address->getUses()) {
+    SILInstruction *UserInst = use->getUser();
+    if (UserInst == ignoredUser)
+      continue;
+
+    if (auto *Apply = dyn_cast<ApplyInst>(UserInst)) {
+      /// A call to materializeForSet exposes an address within the parent
+      /// object. However, we can rely on a subsequent mark_dependent
+      /// instruction to take that object as an operand, causing it to escape
+      /// for the purpose of this analysis.
+      assert(Apply->getSubstCalleeConv()
+                 .getSILArgumentConvention(use->getOperandNumber()
+                                           - Apply->getArgumentOperandNumber())
+                 .isIndirectConvention()
+             && "copy_addr location should be passed indirect");
+      if (!visitor.visitNormalUse(UserInst))
+        return false;
+
+      continue;
+    }
+    if (auto *CopyInst = dyn_cast<CopyAddrInst>(UserInst)) {
+      if (CopyInst->getSrc() == use->get() && CopyInst->isTakeOfSrc()) {
+        if (!visitor.visitTake(CopyInst))
+          return false;
+      } else {
+        if (!visitor.visitNormalUse(CopyInst))
+          return false;
+      }
+      continue;
+    }
+    if (auto *Destroy = dyn_cast<DestroyAddrInst>(UserInst)) {
+      if (!visitor.visitDestroy(Destroy))
+        return false;
+
+      continue;
+    }
+    switch (UserInst->getKind()) {
+    case SILInstructionKind::LoadInst:
+      if (!visitor.visitNormalUse(UserInst))
+        return false;
+
+      break;
+    case SILInstructionKind::ExistentialMetatypeInst:
+    case SILInstructionKind::InjectEnumAddrInst:
+    case SILInstructionKind::StoreInst:
+      if (!visitor.visitNormalUse(UserInst))
+        return false;
+
+      break;
+    case SILInstructionKind::DebugValueAddrInst:
+      if (!visitor.visitDebugValue(cast<DebugValueAddrInst>(UserInst)))
+        return false;
+
+      break;
+    case SILInstructionKind::DeallocStackInst:
+      break;
+    default:
+      // Most likely one of:
+      //   init_enum_data_addr
+      //   open_existential_addr
+      //   partial_apply
+      //   struct_element_addr
+      //   unchecked_take_enum_data_addr
+      //
+      // TODO: Peek through struct element users like COWArrayOpts.
+      //
+      // TODO: Attempt to analyze partial applies or run closure propagation
+      // first.
+      //
+      // TODO: assert that this list is consistent with
+      // isTransitiveEscapeInst().
+      DEBUG(llvm::dbgs() << "  Skipping copy: use exposes def" << *UserInst);
+      return false;
+    }
+  }
+  return true;
+}
+
 namespace {
 /// Analyze an instruction that operates on the Address of a forward propagated
 /// value.
@@ -373,13 +485,15 @@
   bool HasChanged;
   bool HasChangedCFG;
 
+  // --- Per copied-def state ---
+
   // Transient state for the current Def valid during forwardCopiesOf.
   SILValue CurrentDef;
 
   // Is the addressed defined by CurrentDef ever loaded from?
   // This indicates that lifetime of any transitively referenced objects lives
   // beyond the value's immediate uses.
-  bool IsLoadedFrom;
+  bool IsSrcLoadedFrom;
 
   bool HasForwardedToCopy;
   SmallPtrSet<SILInstruction*, 16> SrcUserInsts;
@@ -387,11 +501,43 @@
   SmallVector<CopyAddrInst*, 4> TakePoints;
   SmallVector<DestroyAddrInst*, 4> DestroyPoints;
   SmallPtrSet<SILBasicBlock*, 32> DeadInBlocks;
+
+  // --- Per copy_addr state ---
+  CopyAddrInst *CurrentCopy = nullptr;
+
+  class CopySrcUserVisitor : public AddressUserVisitor {
+    CopyForwarding &CPF;
+  public:
+    CopySrcUserVisitor(CopyForwarding &CPF) : CPF(CPF) {}
+
+    virtual bool visitNormalUse(SILInstruction *user) {
+      if (isa<LoadInst>(user))
+        CPF.IsSrcLoadedFrom = true;
+
+      // Bail on multiple uses in the same instruction to avoid complexity.
+      return CPF.SrcUserInsts.insert(user).second;
+    }
+    virtual bool visitTake(CopyAddrInst *take) {
+      if (take->getSrc() == take->getDest())
+        return false;
+
+      CPF.TakePoints.push_back(take);
+      return true;
+    }
+    virtual bool visitDestroy(DestroyAddrInst *destroy) {
+      CPF.DestroyPoints.push_back(destroy);
+      return true;
+    }
+    virtual bool visitDebugValue(DebugValueAddrInst *debugValue) {
+      return CPF.SrcDebugValueInsts.insert(debugValue).second;
+    }
+  };
+
 public:
   CopyForwarding(PostOrderAnalysis *PO, DominanceAnalysis *DA)
       : PostOrder(PO), DomAnalysis(DA), DoGlobalHoisting(false),
-        HasChanged(false), HasChangedCFG(false), IsLoadedFrom(false),
-        HasForwardedToCopy(false) {}
+        HasChanged(false), HasChangedCFG(false), IsSrcLoadedFrom(false),
+        HasForwardedToCopy(false), CurrentCopy(nullptr) {}
 
   void reset(SILFunction *F) {
     // Don't hoist destroy_addr globally in transparent functions. Avoid cloning
@@ -408,13 +554,14 @@
       PostOrder->invalidate(F, SILAnalysis::InvalidationKind::Everything);
     }
     CurrentDef = SILValue();
-    IsLoadedFrom = false;
+    IsSrcLoadedFrom = false;
     HasForwardedToCopy = false;
     SrcUserInsts.clear();
     SrcDebugValueInsts.clear();
     TakePoints.clear();
     DestroyPoints.clear();
     DeadInBlocks.clear();
+    CurrentCopy = nullptr;
   }
 
   bool hasChanged() const { return HasChanged; }
@@ -427,96 +574,42 @@
   void forwardCopiesOf(SILValue Def, SILFunction *F);
 
 protected:
-  bool collectUsers();
   bool propagateCopy(CopyAddrInst *CopyInst, bool hoistingDestroy);
   CopyAddrInst *findCopyIntoDeadTemp(CopyAddrInst *destCopy);
   bool forwardDeadTempCopy(CopyAddrInst *srcCopy, CopyAddrInst *destCopy);
-  bool forwardPropagateCopy(CopyAddrInst *CopyInst,
-                            SmallPtrSetImpl<SILInstruction*> &DestUserInsts);
-  bool backwardPropagateCopy(CopyAddrInst *CopyInst,
-                             SmallPtrSetImpl<SILInstruction*> &DestUserInsts);
+  bool forwardPropagateCopy();
+  bool backwardPropagateCopy();
   bool hoistDestroy(SILInstruction *DestroyPoint, SILLocation DestroyLoc);
 
-  bool isSourceDeadAtCopy(CopyAddrInst *);
-  bool areCopyDestUsersDominatedBy(CopyAddrInst *,
-                                   SmallVectorImpl<Operand *> &);
+  bool isSourceDeadAtCopy();
+
+  typedef llvm::SmallSetVector<SILInstruction *, 16> UserVector;
+  bool doesCopyDominateDestUsers(const UserVector &DirectDestUses);
+};
+
+class CopyDestUserVisitor : public AddressUserVisitor {
+  SmallPtrSetImpl<SILInstruction *> &DestUsers;
+
+public:
+  CopyDestUserVisitor(SmallPtrSetImpl<SILInstruction *> &DestUsers)
+      : DestUsers(DestUsers) {}
+
+  virtual bool visitNormalUse(SILInstruction *user) {
+    // Bail on multiple uses in the same instruction to avoid complexity.
+    return DestUsers.insert(user).second;
+  }
+  virtual bool visitTake(CopyAddrInst *take) {
+    return DestUsers.insert(take).second;
+  }
+  virtual bool visitDestroy(DestroyAddrInst *destroy) {
+    return DestUsers.insert(destroy).second;
+  }
+  virtual bool visitDebugValue(DebugValueAddrInst *debugValue) {
+    return DestUsers.insert(debugValue).second;
+  }
 };
 } // end anonymous namespace
 
-/// Gather all instructions that use CurrentDef:
-/// - DestroyPoints records 'destroy'
-/// - TakePoints records 'copy_addr [take] src'
-/// - SrcUserInsts records other users.
-///
-/// If we are unable to find all uses, for example, because we don't look
-/// through struct_element_addr, then return false.
-///
-/// The collected use points will be consulted during forward and backward
-/// copy propagation.
-bool CopyForwarding::collectUsers() {
-  for (auto UI : CurrentDef->getUses()) {
-    SILInstruction *UserInst = UI->getUser();
-    if (auto *Apply = dyn_cast<ApplyInst>(UserInst)) {
-      /// A call to materializeForSet exposes an address within the parent
-      /// object. However, we can rely on a subsequent mark_dependent
-      /// instruction to take that object as an operand, causing it to escape
-      /// for the purpose of this analysis.
-      assert(Apply->getSubstCalleeConv()
-                 .getSILArgumentConvention(UI->getOperandNumber()
-                                           - Apply->getArgumentOperandNumber())
-                 .isIndirectConvention()
-             && "copy_addr location should be passed indirect");
-      SrcUserInsts.insert(Apply);
-      continue;
-    }
-    if (auto *CopyInst = dyn_cast<CopyAddrInst>(UserInst)) {
-      if (CopyInst->getSrc() == UI->get() && CopyInst->isTakeOfSrc())
-        TakePoints.push_back(CopyInst);
-      else
-        SrcUserInsts.insert(CopyInst);
-      continue;
-    }
-    if (auto *Destroy = dyn_cast<DestroyAddrInst>(UserInst)) {
-      DestroyPoints.push_back(Destroy);
-      continue;
-    }
-    switch (UserInst->getKind()) {
-    case SILInstructionKind::LoadInst:
-      IsLoadedFrom = true;
-      SrcUserInsts.insert(UserInst);
-      break;
-    case SILInstructionKind::ExistentialMetatypeInst:
-    case SILInstructionKind::InjectEnumAddrInst:
-    case SILInstructionKind::StoreInst:
-      SrcUserInsts.insert(UserInst);
-      break;
-    case SILInstructionKind::DebugValueAddrInst:
-      SrcDebugValueInsts.insert(cast<DebugValueAddrInst>(UserInst));
-      break;
-    case SILInstructionKind::DeallocStackInst:
-      break;
-    default:
-      // Most likely one of:
-      //   init_enum_data_addr
-      //   open_existential_addr
-      //   partial_apply
-      //   struct_element_addr
-      //   unchecked_take_enum_data_addr
-      //
-      // TODO: Peek through struct element users like COWArrayOpts.
-      //
-      // TODO: Attempt to analyze partial applies or run closure propagation
-      // first.
-      //
-      // TODO: assert that this list is consistent with
-      // isTransitiveEscapeInst().
-      DEBUG(llvm::dbgs() << "  Skipping copy: use exposes def" << *UserInst);
-      return false;
-    }
-  }
-  return true;
-}
-
 /// Attempt to forward, then backward propagate this copy.
 ///
 /// The caller has already proven that lifetime of the value being copied ends
@@ -530,47 +623,50 @@
   if (!EnableCopyForwarding)
     return false;
 
+  // CopyForwarding should be split into per-def-state vs. per-copy-state, but
+  // this hack is good enough for a pass that's going away "soon".
+  struct RAIISetCurrentCopy {
+    CopyAddrInst *&CurrentCopy;
+
+    RAIISetCurrentCopy(CopyAddrInst *&CurrentCopy, CopyAddrInst *CopyInst)
+      : CurrentCopy(CurrentCopy) {
+      assert(!CurrentCopy);
+      CurrentCopy = CopyInst;
+    }
+    ~RAIISetCurrentCopy() {
+      CurrentCopy = nullptr;
+    }
+  };
+  RAIISetCurrentCopy setCurrentCopy(CurrentCopy, CopyInst);
+
   // Handle copy-of-copy without analyzing uses.
-  // Assumes that CopyInst->getSrc() is dead after CopyInst.
-  assert(CopyInst->isTakeOfSrc() || hoistingDestroy);
-  if (auto *srcCopy = findCopyIntoDeadTemp(CopyInst)) {
-    if (forwardDeadTempCopy(srcCopy, CopyInst)) {
+  // Assumes that CurrentCopy->getSrc() is dead after CurrentCopy.
+  assert(CurrentCopy->isTakeOfSrc() || hoistingDestroy);
+  if (auto *srcCopy = findCopyIntoDeadTemp(CurrentCopy)) {
+    if (forwardDeadTempCopy(srcCopy, CurrentCopy)) {
       HasChanged = true;
       ++NumDeadTemp;
       return true;
     }
   }
 
-  SILValue CopyDest = CopyInst->getDest();
-  SILBasicBlock *BB = CopyInst->getParent();
-
-  // Gather a list of CopyDest users in this block.
-  SmallPtrSet<SILInstruction*, 16> DestUserInsts;
-  for (auto UI : CopyDest->getUses()) {
-    SILInstruction *UserInst = UI->getUser();
-    if (UserInst != CopyInst && UI->getUser()->getParent() == BB)
-      DestUserInsts.insert(UI->getUser());
-  }
-  // Note that DestUserInsts is likely empty when the dest is an 'out' argument,
-  // allowing us to go straight to backward propagation.
-  if (forwardPropagateCopy(CopyInst, DestUserInsts)) {
-    DEBUG(llvm::dbgs() << "  Forwarding Copy:" << *CopyInst);
-    if (!CopyInst->isInitializationOfDest()) {
+  if (forwardPropagateCopy()) {
+    DEBUG(llvm::dbgs() << "  Forwarding Copy:" << *CurrentCopy);
+    if (!CurrentCopy->isInitializationOfDest()) {
       // Replace the original copy with a destroy. We may be able to hoist it
       // more in another pass but don't currently iterate.
-      SILBuilderWithScope(CopyInst)
-          .createDestroyAddr(CopyInst->getLoc(), CopyInst->getDest());
+      SILBuilderWithScope(CurrentCopy)
+          .createDestroyAddr(CurrentCopy->getLoc(), CurrentCopy->getDest());
     }
-    CopyInst->eraseFromParent();
+    CurrentCopy->eraseFromParent();
     HasChanged = true;
     ++NumCopyForward;
     return true;
   }
   // Forward propagation failed. Attempt to backward propagate.
-  if (CopyInst->isInitializationOfDest()
-      && backwardPropagateCopy(CopyInst, DestUserInsts)) {
-    DEBUG(llvm::dbgs() << "  Reversing Copy:" << *CopyInst);
-    CopyInst->eraseFromParent();
+  if (CurrentCopy->isInitializationOfDest() && backwardPropagateCopy()) {
+    DEBUG(llvm::dbgs() << "  Reversing Copy:" << *CurrentCopy);
+    CurrentCopy->eraseFromParent();
     HasChanged = true;
     ++NumCopyBackward;
     return true;
@@ -681,57 +777,30 @@
 
 /// Check that the lifetime of %src ends at the copy and is not reinitialized
 /// thereafter with a new value.
-bool CopyForwarding::isSourceDeadAtCopy(CopyAddrInst *Copy) {
+bool CopyForwarding::isSourceDeadAtCopy() {
   // A single copy_addr [take] %Src.
   if (TakePoints.size() == 1 && DestroyPoints.empty() && SrcUserInsts.empty())
     return true;
 
   if (TakePoints.empty() && DestroyPoints.size() == 1 &&
       SrcUserInsts.size() == 1) {
-    assert(*SrcUserInsts.begin() == Copy);
+    assert(*SrcUserInsts.begin() == CurrentCopy);
     return true;
   }
   // For now just check for a single copy_addr that destroys its source.
   return false;
 }
 
-/// Check that all users of the destination address of the copy are dominated by
-/// the copy. There is no path around copy that could initialize %dest with a
-/// different value.
-bool CopyForwarding::areCopyDestUsersDominatedBy(
-    CopyAddrInst *Copy, SmallVectorImpl<Operand *> &DestUses) {
-
-  SILValue CopyDest = Copy->getDest();
-  DominanceInfo *DT = nullptr;
-
-  for (auto *Use : CopyDest->getUses()) {
-    auto *UserInst = Use->getUser();
-    if (UserInst == Copy)
-      continue;
-    if (isa<DeallocStackInst>(UserInst))
-      continue;
-
-    // Initialize the dominator tree info.
-    if (!DT)
-      DT = DomAnalysis->get(Copy->getFunction());
-
+/// Check that all immediate users of the destination address of the copy are
+/// dominated by the copy. There is no path around copy that could initialize
+/// %dest with a different value.
+bool CopyForwarding::doesCopyDominateDestUsers(
+    const UserVector &DirectDestUsers) {
+  DominanceInfo *DT = DomAnalysis->get(CurrentCopy->getFunction());
+  for (auto *user : DirectDestUsers) {
     // Check dominance of the parent blocks.
-    if (!DT->dominates(Copy->getParent(), UserInst->getParent()))
+    if (!DT->properlyDominates(CurrentCopy, user))
       return false;
-
-    bool CheckDominanceInBlock = Copy->getParent() == UserInst->getParent();
-    // Check whether Copy is before UserInst.
-    if (CheckDominanceInBlock) {
-      auto SI = Copy->getIterator(), SE = Copy->getParent()->end();
-      for (++SI; SI != SE; ++SI)
-        if (&*SI == UserInst)
-          break;
-      if (SI == SE)
-        return false;
-    }
-
-    // We can forward to this use.
-    DestUses.push_back(Use);
   }
   return true;
 }
@@ -756,18 +825,6 @@
   return SingleDSI;
 }
 
-/// Replace all uses of \p ASI by \p RHS, except the dealloc_stack.
-static void replaceAllUsesExceptDealloc(AllocStackInst *ASI, ValueBase *RHS) {
-  llvm::SmallVector<Operand *, 8> Uses;
-  for (Operand *Use : ASI->getUses()) {
-    if (!isa<DeallocStackInst>(Use->getUser()))
-      Uses.push_back(Use);
-  }
-  for (Operand *Use : Uses) {
-    Use->set(RHS);
-  }
-}
-
 /// Perform forward copy-propagation. Find a set of uses that the given copy can
 /// forward to and replace them with the copy's source.
 ///
@@ -789,16 +846,31 @@
 /// The caller has already guaranteed that the lifetime of the copy's source
 /// ends at this copy. Either the copy is a [take] or a destroy can be hoisted
 /// to the copy.
-bool CopyForwarding::forwardPropagateCopy(
-  CopyAddrInst *CopyInst,
-  SmallPtrSetImpl<SILInstruction*> &DestUserInsts) {
+bool CopyForwarding::forwardPropagateCopy() {
 
-  SILValue CopyDest = CopyInst->getDest();
+  SILValue CopyDest = CurrentCopy->getDest();
   // Require the copy dest to be a simple alloc_stack. This ensures that all
   // instructions that may read from the destination address depend on CopyDest.
   if (!isa<AllocStackInst>(CopyDest))
     return false;
 
+  // Record all direct dest uses. Forward propagation doesn't care if they are
+  // projections or propagate the address in any way--their operand only needs
+  // to be substituted with the copy's source.
+  UserVector DirectDestUsers;
+  for (auto *Use : CopyDest->getUses()) {
+    auto *UserInst = Use->getUser();
+    if (UserInst == CurrentCopy)
+      continue;
+
+    if (isa<DeallocStackInst>(UserInst))
+      continue;
+
+    // Bail on multiple uses in the same instruction so that AnalyzeForwardUse
+    // does not need to deal with it.
+    if (!DirectDestUsers.insert(UserInst))
+      return false;
+  }
   // Looking at
   //
   //    copy_addr %Src, [init] %Dst
@@ -810,20 +882,23 @@
   // not).  Additionally, we must know that all accesses to %Dst further on must
   // have had this copy on their path (there might be reinitialization of %Dst
   // later, but there must not be a path around this copy that reads from %Dst).
-  SmallVector<Operand *, 16> DestUses;
-  if (isSourceDeadAtCopy(CopyInst) &&
-      areCopyDestUsersDominatedBy(CopyInst, DestUses)) {
-
+  if (isSourceDeadAtCopy() && doesCopyDominateDestUsers(DirectDestUsers)) {
+    SILValue CopySrc = CurrentCopy->getSrc();
     // Replace all uses of Dest with a use of Src.
-    for (auto *Oper : DestUses) {
-      Oper->set(CopyInst->getSrc());
-      if (isa<CopyAddrInst>(Oper->getUser()))
+    for (SILInstruction *user : DirectDestUsers) {
+      for (Operand &oper : user->getAllOperands()) {
+        if (oper.get() != CopyDest)
+          continue;
+
+        // Rewrite both read and writes of CopyDest as CopySrc.
+        oper.set(CopySrc);
+      }
+      if (isa<CopyAddrInst>(user))
         HasForwardedToCopy = true;
     }
-
     // The caller will Remove the destroy_addr of %src.
     assert((DestroyPoints.empty() ||
-            (!CopyInst->isTakeOfSrc() && DestroyPoints.size() == 1)) &&
+            (!CurrentCopy->isTakeOfSrc() && DestroyPoints.size() == 1)) &&
            "Must only have one destroy");
 
     // The caller will remove the copy_addr.
@@ -834,7 +909,7 @@
   if (auto *ASI = dyn_cast<AllocStackInst>(CurrentDef)) {
     DefDealloc = getSingleDealloc(ASI);
     if (!DefDealloc) {
-      DEBUG(llvm::dbgs() << "  Skipping copy" << *CopyInst
+      DEBUG(llvm::dbgs() << "  Skipping copy" << *CurrentCopy
             << "  stack address has multiple uses.\n");
       return false;
     }
@@ -843,23 +918,23 @@
   // Scan forward recording all operands that use CopyDest until we see the
   // next deinit of CopyDest.
   SmallVector<Operand*, 16> ValueUses;
-  auto SI = CopyInst->getIterator(), SE = CopyInst->getParent()->end();
+  auto SI = CurrentCopy->getIterator(), SE = CurrentCopy->getParent()->end();
   for (++SI; SI != SE; ++SI) {
     SILInstruction *UserInst = &*SI;
     // If we see another use of Src, then the source location is reinitialized
     // before the Dest location is deinitialized. So we really need the copy.
     if (SrcUserInsts.count(UserInst)) {
-      DEBUG(llvm::dbgs() << "  Skipping copy" << *CopyInst
+      DEBUG(llvm::dbgs() << "  Skipping copy" << *CurrentCopy
             << "  source used by" << *UserInst);
       return false;
     }
     if (UserInst == DefDealloc) {
-      DEBUG(llvm::dbgs() << "  Skipping copy" << *CopyInst
+      DEBUG(llvm::dbgs() << "  Skipping copy" << *CurrentCopy
             << "    dealloc_stack before dest use.\n");
       return false;
     }
     // Early check to avoid scanning unrelated instructions.
-    if (!DestUserInsts.count(UserInst))
+    if (!DirectDestUsers.count(UserInst))
       continue;
 
     AnalyzeForwardUse AnalyzeUse(CopyDest);
@@ -895,7 +970,7 @@
   // Now that a deinit was found, it is safe to substitute all recorded uses
   // with the copy's source.
   for (auto *Oper : ValueUses) {
-    Oper->set(CopyInst->getSrc());
+    Oper->set(CurrentCopy->getSrc());
     if (isa<CopyAddrInst>(Oper->getUser()))
       HasForwardedToCopy = true;
   }
@@ -906,6 +981,10 @@
 /// not including:
 /// - 'Def' itself
 /// - Transitive uses of 'Def' (listed elsewhere in DestUserInsts)
+///
+/// i.e. If Def is returned directly, RootUserInsts will be empty.
+///
+/// Return nullptr when the root != Def, and root has unrecognized uses.
 /// 
 /// If the returned root is not 'Def' itself, then 'Def' must be an address
 /// projection that can be trivially rematerialized with the root as its
@@ -913,30 +992,39 @@
 static ValueBase *
 findAddressRootAndUsers(ValueBase *Def,
                         SmallPtrSetImpl<SILInstruction*> &RootUserInsts) {
-  if (isa<InitEnumDataAddrInst>(Def) || isa<InitExistentialAddrInst>(Def)) {
+  switch (Def->getKind()) {
+  default:
+    return Def;
+  case ValueKind::InitEnumDataAddrInst:
+  case ValueKind::InitExistentialAddrInst:
     auto InitInst = cast<SingleValueInstruction>(Def);
     SILValue InitRoot = InitInst->getOperand(0);
-    for (auto *Use : InitRoot->getUses()) {
-      auto *UserInst = Use->getUser();
-      if (UserInst == InitInst)
-        continue;
-      RootUserInsts.insert(UserInst);
-    }
+
+    CopyDestUserVisitor visitor(RootUserInsts);
+    if (!visitAddressUsers(InitRoot, InitInst, visitor))
+      return nullptr;
     return InitRoot;
   }
-  return Def;
 }
 
 /// Perform backward copy-propagation. Find the initialization point of the
 /// copy's source and replace the initializer's address with the copy's dest.
-bool CopyForwarding::backwardPropagateCopy(
-  CopyAddrInst *CopyInst,
-  SmallPtrSetImpl<SILInstruction*> &DestUserInsts) {
+bool CopyForwarding::backwardPropagateCopy() {
 
-  SILValue CopySrc = CopyInst->getSrc();
-  ValueBase *CopyDestDef = CopyInst->getDest();
+  SILValue CopySrc = CurrentCopy->getSrc();
+  ValueBase *CopyDestDef = CurrentCopy->getDest();
+
+  SmallPtrSet<SILInstruction *, 16> DestUserInsts;
+  CopyDestUserVisitor visitor(DestUserInsts);
+  if (!visitAddressUsers(CopyDestDef, CurrentCopy, visitor))
+    return false;
+
+  // RootUserInsts will contain any users of the same object not covered by
+  // DestUserInsts.
   SmallPtrSet<SILInstruction*, 8> RootUserInsts;
   ValueBase *CopyDestRoot = findAddressRootAndUsers(CopyDestDef, RootUserInsts);
+  if (!CopyDestRoot)
+    return false;
 
   // Require the copy dest value to be identified by this address. This ensures
   // that all instructions that may write to destination address depend on
@@ -951,7 +1039,7 @@
   // ValueUses records the uses of CopySrc in reverse order.
   SmallVector<Operand*, 16> ValueUses;
   SmallVector<DebugValueAddrInst*, 4> DebugValueInstsToDelete;
-  auto SI = CopyInst->getIterator(), SE = CopyInst->getParent()->begin();
+  auto SI = CurrentCopy->getIterator(), SE = CurrentCopy->getParent()->begin();
   while (SI != SE) {
     --SI;
     SILInstruction *UserInst = &*SI;
@@ -967,7 +1055,7 @@
         DebugValueInstsToDelete.push_back(DVAI);
         continue;
       }
-      DEBUG(llvm::dbgs() << "  Skipping copy" << *CopyInst
+      DEBUG(llvm::dbgs() << "  Skipping copy" << *CurrentCopy
             << "    dest used by " << *UserInst);
       return false;
     }
@@ -1011,7 +1099,7 @@
   // Now that an init was found, it is safe to substitute all recorded uses
   // with the copy's dest.
   for (auto *Oper : ValueUses) {
-    Oper->set(CopyInst->getDest());
+    Oper->set(CurrentCopy->getDest());
     if (isa<CopyAddrInst>(Oper->getUser()))
       HasForwardedToCopy = true;
   }
@@ -1083,20 +1171,21 @@
   reset(F);
   CurrentDef = Def;
   DEBUG(llvm::dbgs() << "Analyzing copies of Def: " << Def);
-  if (!collectUsers())
+  CopySrcUserVisitor visitor(*this);
+  if (!visitAddressUsers(Def, nullptr, visitor))
     return;
 
   // First forward any copies that implicitly destroy CurrentDef. There is no
   // need to hoist Destroy for these.
-  for (auto *CopyInst : TakePoints)
+  for (auto *CopyInst : TakePoints) {
     propagateCopy(CopyInst, /*hoistingDestroy=*/false);
-
+  }
   // If the copied address is also loaded from, then destroy hoisting is unsafe.
   //
   // TODO: Record all loads during collectUsers. Implement findRetainPoints to
   // peek though projections of the load, like unchecked_enum_data to find the
   // true extent of the lifetime including transitively referenced objects.
-  if (IsLoadedFrom)
+  if (IsSrcLoadedFrom)
     return;
 
   bool HoistedDestroyFound = false;
@@ -1242,6 +1331,18 @@
   return true;
 }
 
+/// Replace all uses of \p ASI by \p RHS, except the dealloc_stack.
+static void replaceAllUsesExceptDealloc(AllocStackInst *ASI, ValueBase *RHS) {
+  llvm::SmallVector<Operand *, 8> Uses;
+  for (Operand *Use : ASI->getUses()) {
+    if (!isa<DeallocStackInst>(Use->getUser()))
+      Uses.push_back(Use);
+  }
+  for (Operand *Use : Uses) {
+    Use->set(RHS);
+  }
+}
+
 /// Remove a copy for which canNRVO returned true.
 static void performNRVO(CopyAddrInst *CopyInst) {
   DEBUG(llvm::dbgs() << "NRVO eliminates copy" << *CopyInst);
diff --git a/lib/SILOptimizer/Transforms/Devirtualizer.cpp b/lib/SILOptimizer/Transforms/Devirtualizer.cpp
index 922969a..691acb8 100644
--- a/lib/SILOptimizer/Transforms/Devirtualizer.cpp
+++ b/lib/SILOptimizer/Transforms/Devirtualizer.cpp
@@ -17,6 +17,7 @@
 
 #define DEBUG_TYPE "sil-devirtualizer"
 
+#include "swift/SIL/OptimizationRemark.h"
 #include "swift/SIL/SILFunction.h"
 #include "swift/SIL/SILInstruction.h"
 #include "swift/SILOptimizer/Analysis/ClassHierarchyAnalysis.h"
@@ -53,6 +54,7 @@
   bool Changed = false;
   llvm::SmallVector<SILInstruction *, 8> DeadApplies;
   llvm::SmallVector<ApplySite, 8> NewApplies;
+  OptRemark::Emitter ORE(DEBUG_TYPE, F.getModule());
 
   SmallVector<ApplySite, 16> Applies;
   for (auto &BB : F) {
@@ -68,7 +70,7 @@
    }
   }
   for (auto Apply : Applies) {
-    auto NewInstPair = tryDevirtualizeApply(Apply, CHA);
+    auto NewInstPair = tryDevirtualizeApply(Apply, CHA, &ORE);
     if (!NewInstPair.second)
       continue;
 
diff --git a/lib/SILOptimizer/Transforms/SILCodeMotion.cpp b/lib/SILOptimizer/Transforms/SILCodeMotion.cpp
index bdb57cb..570d123 100644
--- a/lib/SILOptimizer/Transforms/SILCodeMotion.cpp
+++ b/lib/SILOptimizer/Transforms/SILCodeMotion.cpp
@@ -105,6 +105,752 @@
 }
 
 //===----------------------------------------------------------------------===//
+//                             Enum Tag Dataflow
+//===----------------------------------------------------------------------===//
+
+namespace {
+
+class EnumCaseDataflowContext;
+
+using EnumBBCaseList =
+    llvm::SmallVector<std::pair<SILBasicBlock *, EnumElementDecl *>, 2>;
+
+/// Class that performs enum tag state dataflow on the given BB.
+class BBEnumTagDataflowState
+    : public SILInstructionVisitor<BBEnumTagDataflowState, bool> {
+  EnumCaseDataflowContext *Context;
+  NullablePtr<SILBasicBlock> BB;
+
+  SmallBlotMapVector<unsigned, EnumElementDecl *, 4> ValueToCaseMap;
+  SmallBlotMapVector<unsigned, EnumBBCaseList, 4> EnumToEnumBBCaseListMap;
+
+public:
+  BBEnumTagDataflowState() = default;
+  BBEnumTagDataflowState(const BBEnumTagDataflowState &Other) = default;
+  ~BBEnumTagDataflowState() = default;
+
+  LLVM_ATTRIBUTE_DEPRECATED(void dump() const LLVM_ATTRIBUTE_USED,
+                            "only for use within the debugger");
+
+  bool init(EnumCaseDataflowContext &Context, SILBasicBlock *NewBB);
+
+  SILBasicBlock *getBB() { return BB.get(); }
+
+  using iterator = decltype(ValueToCaseMap)::iterator;
+  iterator begin() { return ValueToCaseMap.getItems().begin(); }
+  iterator end() { return ValueToCaseMap.getItems().begin(); }
+
+  void clear() { ValueToCaseMap.clear(); }
+
+  bool visitSILInstruction(SILInstruction *I) { return false; }
+
+  bool visitEnumInst(EnumInst *EI);
+  bool visitUncheckedEnumDataInst(UncheckedEnumDataInst *UEDI);
+  bool visitRetainValueInst(RetainValueInst *RVI);
+  bool visitReleaseValueInst(ReleaseValueInst *RVI);
+  bool process();
+  bool hoistDecrementsIntoSwitchRegions(AliasAnalysis *AA);
+  bool sinkIncrementsOutOfSwitchRegions(AliasAnalysis *AA,
+                                        RCIdentityFunctionInfo *RCIA);
+  void handlePredSwitchEnum(SwitchEnumInst *S);
+  void handlePredCondSelectEnum(CondBranchInst *CondBr);
+
+  /// Helper method which initializes this state map with the data from the
+  /// first predecessor BB.
+  ///
+  /// We will be performing an intersection in a later step of the merging.
+  bool initWithFirstPred(SILBasicBlock *FirstPredBB);
+
+  /// Top level merging function for predecessors.
+  void mergePredecessorStates();
+
+  /// If we have a single predecessor, see if the predecessor's terminator was a
+  /// switch_enum or a (cond_br + select_enum). If so, track in this block the
+  /// enum state of the operand.
+  void mergeSinglePredTermInfoIntoState(SILBasicBlock *Pred);
+
+private:
+  EnumCaseDataflowContext &getContext() const;
+  unsigned getIDForValue(SILValue V) const;
+  SILValue getValueForID(unsigned ID) const;
+};
+
+/// Map all blocks to BBEnumTagDataflowState in RPO order.
+class EnumCaseDataflowContext {
+  PostOrderFunctionInfo *PO;
+  std::vector<BBEnumTagDataflowState> BBToStateVec;
+  std::vector<SILValue> IDToEnumValueMap;
+  llvm::DenseMap<SILValue, unsigned> EnumValueToIDMap;
+
+public:
+  EnumCaseDataflowContext(PostOrderFunctionInfo *PO) : PO(PO), BBToStateVec() {
+    BBToStateVec.resize(PO->size());
+    unsigned RPOIdx = 0;
+    for (SILBasicBlock *BB : PO->getReversePostOrder()) {
+      BBToStateVec[RPOIdx].init(*this, BB);
+      ++RPOIdx;
+    }
+  }
+
+  /// Return true if we have a valid value for the given ID;
+  bool hasValueForID(unsigned ID) const {
+    return ID < IDToEnumValueMap.size() && IDToEnumValueMap[ID];
+  }
+
+  SILValue getValueForID(unsigned ID) const { return IDToEnumValueMap[ID]; }
+
+  unsigned getIDForValue(SILValue V) const {
+    // We are being a little tricky here. Here is what is happening:
+    //
+    // 1. When we start we do not know if we are already tracking V, so we
+    // prepare /as if/ V was new.
+    //
+    // 2. When we perform the insertion, if V already has a value associated
+    // with it, we return the iterator to that value. The iterator contains
+    // inside of it the actual index.
+    //
+    // 3. Otherwise, we initialize V in EnumValueToIDMap with NewID. Rather than
+    // re-accessing the iterator, we just return the value we have already
+    // computed.
+    unsigned NewID = IDToEnumValueMap.size();
+    auto &This = const_cast<EnumCaseDataflowContext &>(*this);
+    auto Iter = This.EnumValueToIDMap.insert({V, NewID});
+    if (!Iter.second)
+      return Iter.first->second;
+    This.IDToEnumValueMap.emplace_back(V);
+    return NewID;
+  }
+
+  void blotValue(SILValue V) {
+    unsigned ID = getIDForValue(V);
+    IDToEnumValueMap[ID] = SILValue();
+  }
+
+  unsigned size() const { return BBToStateVec.size(); }
+  BBEnumTagDataflowState &getRPOState(unsigned RPOIdx) {
+    return BBToStateVec[RPOIdx];
+  }
+  /// \return BBEnumTagDataflowState or NULL for unreachable blocks.
+  BBEnumTagDataflowState *getBBState(SILBasicBlock *BB) {
+    if (auto ID = PO->getRPONumber(BB)) {
+      return &getRPOState(*ID);
+    }
+    return nullptr;
+  }
+};
+
+} // end anonymous namespace
+
+EnumCaseDataflowContext &BBEnumTagDataflowState::getContext() const {
+  // Context and BB are initialized together, so we only need to check one.
+  assert(BB.isNonNull() && "Uninitialized state?!");
+  return *Context;
+}
+
+unsigned BBEnumTagDataflowState::getIDForValue(SILValue V) const {
+  return getContext().getIDForValue(V);
+}
+
+SILValue BBEnumTagDataflowState::getValueForID(unsigned ID) const {
+  return getContext().getValueForID(ID);
+}
+
+void BBEnumTagDataflowState::handlePredSwitchEnum(SwitchEnumInst *S) {
+
+  // Find the tag associated with our BB and set the state of the
+  // enum we switch on to that value. This is important so we can determine
+  // covering switches for enums that have cases without payload.
+
+  // Next check if we are the target of a default switch_enum case. If we are,
+  // no interesting information can be extracted, so bail...
+  if (S->hasDefault() && S->getDefaultBB() == getBB())
+    return;
+
+  // Otherwise, attempt to find the tag associated with this BB in the switch
+  // enum...
+  for (unsigned i = 0, e = S->getNumCases(); i != e; ++i) {
+    auto P = S->getCase(i);
+
+    // If this case of the switch is not matched up with this BB, skip the
+    // case...
+    if (P.second != getBB())
+      continue;
+
+    // Ok, we found the case for our BB. If we don't have an enum tag (which can
+    // happen if we have a default statement), return. There is nothing more we
+    // can do.
+    if (!P.first)
+      return;
+
+    // Ok, we have a matching BB and a matching enum tag. Set the state and
+    // return.
+    ValueToCaseMap[getIDForValue(S->getOperand())] = P.first;
+    return;
+  }
+  llvm_unreachable("A successor of a switch_enum terminated BB should be in "
+                   "the switch_enum.");
+}
+
+void BBEnumTagDataflowState::handlePredCondSelectEnum(CondBranchInst *CondBr) {
+
+  auto *EITI = dyn_cast<SelectEnumInst>(CondBr->getCondition());
+  if (!EITI)
+    return;
+
+  NullablePtr<EnumElementDecl> TrueElement = EITI->getSingleTrueElement();
+  if (TrueElement.isNull())
+    return;
+
+  // Find the tag associated with our BB and set the state of the
+  // enum we switch on to that value. This is important so we can determine
+  // covering switches for enums that have cases without payload.
+
+  // Check if we are the true case, ie, we know that we are the given tag.
+  const auto &Operand = EITI->getEnumOperand();
+  if (CondBr->getTrueBB() == getBB()) {
+    ValueToCaseMap[getIDForValue(Operand)] = TrueElement.get();
+    return;
+  }
+
+  // If the enum only has 2 values and its tag isn't the true branch, then we
+  // know the true branch must be the other tag.
+  if (EnumDecl *E = Operand->getType().getEnumOrBoundGenericEnum()) {
+    // Look for a single other element on this enum.
+    EnumElementDecl *OtherElt = nullptr;
+    for (EnumElementDecl *Elt : E->getAllElements()) {
+      // Skip the case where we find the select_enum element
+      if (Elt == TrueElement.get())
+        continue;
+      // If we find another element, then we must have more than 2, so bail.
+      if (OtherElt)
+        return;
+      OtherElt = Elt;
+    }
+    // Only a single enum element?  How would this even get here?  We should
+    // handle it in SILCombine.
+    if (!OtherElt)
+      return;
+    // FIXME: Can we ever not be the false BB here?
+    if (CondBr->getTrueBB() != getBB()) {
+      ValueToCaseMap[getIDForValue(Operand)] = OtherElt;
+      return;
+    }
+  }
+}
+
+bool BBEnumTagDataflowState::initWithFirstPred(SILBasicBlock *FirstPredBB) {
+  // Try to look up the state for the first pred BB.
+  BBEnumTagDataflowState *FirstPredState = getContext().getBBState(FirstPredBB);
+
+  // If we fail, we found an unreachable block, bail.
+  if (FirstPredState == nullptr) {
+    DEBUG(llvm::dbgs() << "        Found an unreachable block!\n");
+    return false;
+  }
+
+  // Ok, our state is in the map, copy in the predecessors value to case map.
+  ValueToCaseMap = FirstPredState->ValueToCaseMap;
+
+  // If we are predecessors only successor, we can potentially hoist releases
+  // into it, so associate the first pred BB and the case for each value that we
+  // are tracking with it.
+  //
+  // TODO: I am writing this too fast. Clean this up later.
+  if (FirstPredBB->getSingleSuccessorBlock()) {
+    for (auto P : ValueToCaseMap.getItems()) {
+      if (!P.hasValue())
+        continue;
+      EnumToEnumBBCaseListMap[P->first].push_back({FirstPredBB, P->second});
+    }
+  }
+
+  return true;
+}
+
+void BBEnumTagDataflowState::mergeSinglePredTermInfoIntoState(
+    SILBasicBlock *Pred) {
+  // Grab the terminator of our one predecessor and if it is a switch enum, mix
+  // it into this state.
+  TermInst *PredTerm = Pred->getTerminator();
+  if (auto *S = dyn_cast<SwitchEnumInst>(PredTerm)) {
+    handlePredSwitchEnum(S);
+    return;
+  }
+
+  auto *CondBr = dyn_cast<CondBranchInst>(PredTerm);
+  if (!CondBr)
+    return;
+
+  handlePredCondSelectEnum(CondBr);
+}
+
+void BBEnumTagDataflowState::mergePredecessorStates() {
+
+  // If we have no predecessors, there is nothing to do so return early...
+  if (getBB()->pred_empty()) {
+    DEBUG(llvm::dbgs() << "            No Preds.\n");
+    return;
+  }
+
+  auto PI = getBB()->pred_begin(), PE = getBB()->pred_end();
+  if (*PI == getBB()) {
+    DEBUG(llvm::dbgs() << "            Found a self loop. Bailing!\n");
+    return;
+  }
+
+  // Grab the first predecessor BB.
+  SILBasicBlock *FirstPred = *PI;
+  ++PI;
+
+  // Attempt to initialize our state with our first predecessor's state by just
+  // copying. We will be doing an intersection with all of the other BB.
+  if (!initWithFirstPred(FirstPred))
+    return;
+
+  // If we only have one predecessor see if we can gain any information and or
+  // knowledge from the terminator of our one predecessor. There is nothing more
+  // that we can do, return.
+  //
+  // This enables us to get enum information from switch_enum and cond_br about
+  // the value that an enum can take in our block. This is a common case that
+  // comes up.
+  if (PI == PE) {
+    mergeSinglePredTermInfoIntoState(FirstPred);
+    return;
+  }
+
+  DEBUG(llvm::dbgs() << "            Merging in rest of predecessors...\n");
+
+  // Enum values that while merging we found conflicting values for. We blot
+  // them after the loop in order to ensure that we can still find the ends of
+  // switch regions.
+  llvm::SmallVector<unsigned, 4> CurBBValuesToBlot;
+
+  // If we do not find state for a specific value in any of our predecessor BBs,
+  // we cannot be the end of a switch region since we cannot cover our
+  // predecessor BBs with enum decls. Blot after the loop.
+  llvm::SmallVector<unsigned, 4> PredBBValuesToBlot;
+
+  // And for each remaining predecessor...
+  do {
+    // If we loop on ourselves, bail...
+    if (*PI == getBB()) {
+      DEBUG(llvm::dbgs() << "            Found a self loop. Bailing!\n");
+      return;
+    }
+
+    // Grab the predecessors state...
+    SILBasicBlock *PredBB = *PI;
+
+    BBEnumTagDataflowState *PredBBState = getContext().getBBState(PredBB);
+    if (PredBBState == nullptr) {
+      DEBUG(llvm::dbgs() << "            Found an unreachable block!\n");
+      return;
+    }
+
+    ++PI;
+
+    // Then for each (SILValue, Enum Tag) that we are tracking...
+    for (auto P : ValueToCaseMap.getItems()) {
+      // If this SILValue was blotted, there is nothing left to do, we found
+      // some sort of conflicting definition and are being conservative.
+      if (!P.hasValue())
+        continue;
+
+      // Then attempt to look up the enum state associated in our SILValue in
+      // the predecessor we are processing.
+      auto PredIter = PredBBState->ValueToCaseMap.find(P->first);
+
+      // If we cannot find the state associated with this SILValue in this
+      // predecessor or the ID in the corresponding predecessor was blotted, we
+      // cannot find a covering switch for this BB or forward any enum tag
+      // information for this enum value.
+      if (PredIter == PredBBState->ValueToCaseMap.end() ||
+          !(*PredIter).hasValue()) {
+        // Otherwise, we are conservative and do not forward the EnumTag that we
+        // are tracking. Blot it!
+        DEBUG(llvm::dbgs() << "                Blotting: " << P->first);
+        CurBBValuesToBlot.push_back(P->first);
+        PredBBValuesToBlot.push_back(P->first);
+        continue;
+      }
+
+      // Then try to lookup the actual value associated with the ID. If we do
+      // not find one, then the enum was destroyed by another part of the pass.
+      SILValue PredValue = getValueForID((*PredIter)->first);
+      if (!PredValue)
+        continue;
+
+      // Check if out predecessor has any other successors. If that is true we
+      // clear all the state since we cannot hoist safely.
+      if (!PredBB->getSingleSuccessorBlock()) {
+        EnumToEnumBBCaseListMap.clear();
+        DEBUG(llvm::dbgs() << "                Predecessor has other "
+                              "successors. Clearing BB cast list map.\n");
+      } else {
+        // Otherwise, add this case to our predecessor case list. We will unique
+        // this after we have finished processing all predecessors.
+        auto Case = std::make_pair(PredBB, (*PredIter)->second);
+        EnumToEnumBBCaseListMap[(*PredIter)->first].push_back(Case);
+      }
+
+      // And the states match, the enum state propagates to this BB.
+      if ((*PredIter)->second == P->second)
+        continue;
+
+      // Otherwise, we are conservative and do not forward the EnumTag that we
+      // are tracking. Blot it!
+      DEBUG(llvm::dbgs() << "                Blotting: " << P->first);
+      CurBBValuesToBlot.push_back(P->first);
+    }
+  } while (PI != PE);
+
+  for (unsigned ID : CurBBValuesToBlot) {
+    ValueToCaseMap.blot(ID);
+  }
+  for (unsigned ID : PredBBValuesToBlot) {
+    EnumToEnumBBCaseListMap.blot(ID);
+  }
+}
+
+bool BBEnumTagDataflowState::visitEnumInst(EnumInst *EI) {
+  unsigned ID = getIDForValue(SILValue(EI));
+  DEBUG(llvm::dbgs() << "    Storing enum into map. ID: " << ID
+                     << ". Value: " << *EI);
+  ValueToCaseMap[ID] = EI->getElement();
+  return false;
+}
+
+bool BBEnumTagDataflowState::visitUncheckedEnumDataInst(
+    UncheckedEnumDataInst *UEDI) {
+  unsigned ID = getIDForValue(UEDI->getOperand());
+  DEBUG(llvm::dbgs() << "    Storing unchecked enum data into map. ID: " << ID
+                     << ". Value: " << *UEDI);
+  ValueToCaseMap[ID] = UEDI->getElement();
+  return false;
+}
+
+bool BBEnumTagDataflowState::visitRetainValueInst(RetainValueInst *RVI) {
+  auto FindResult = ValueToCaseMap.find(getIDForValue(RVI->getOperand()));
+  if (FindResult == ValueToCaseMap.end())
+    return false;
+
+  // If we do not have any argument, kill the retain_value.
+  if (!(*FindResult)->second->hasAssociatedValues()) {
+    RVI->eraseFromParent();
+    return true;
+  }
+
+  DEBUG(llvm::dbgs() << "    Found RetainValue: " << *RVI);
+  DEBUG(llvm::dbgs() << "        Paired to Enum Oracle: "
+                     << (*FindResult)->first);
+
+  SILBuilderWithScope Builder(RVI);
+  createRefCountOpForPayload(Builder, RVI, (*FindResult)->second);
+  RVI->eraseFromParent();
+  return true;
+}
+
+bool BBEnumTagDataflowState::visitReleaseValueInst(ReleaseValueInst *RVI) {
+  auto FindResult = ValueToCaseMap.find(getIDForValue(RVI->getOperand()));
+  if (FindResult == ValueToCaseMap.end())
+    return false;
+
+  // If we do not have any argument, just delete the release value.
+  if (!(*FindResult)->second->hasAssociatedValues()) {
+    RVI->eraseFromParent();
+    return true;
+  }
+
+  DEBUG(llvm::dbgs() << "    Found ReleaseValue: " << *RVI);
+  DEBUG(llvm::dbgs() << "        Paired to Enum Oracle: "
+                     << (*FindResult)->first);
+
+  SILBuilderWithScope Builder(RVI);
+  createRefCountOpForPayload(Builder, RVI, (*FindResult)->second);
+  RVI->eraseFromParent();
+  return true;
+}
+
+bool BBEnumTagDataflowState::process() {
+  bool Changed = false;
+
+  auto SI = getBB()->begin();
+  while (SI != getBB()->end()) {
+    SILInstruction *I = &*SI;
+    ++SI;
+    Changed |= visit(I);
+  }
+
+  return Changed;
+}
+
+bool BBEnumTagDataflowState::hoistDecrementsIntoSwitchRegions(
+    AliasAnalysis *AA) {
+  bool Changed = false;
+  unsigned NumPreds = std::distance(getBB()->pred_begin(), getBB()->pred_end());
+
+  for (auto II = getBB()->begin(), IE = getBB()->end(); II != IE;) {
+    auto *RVI = dyn_cast<ReleaseValueInst>(&*II);
+    ++II;
+
+    // If this instruction is not a release, skip it...
+    if (!RVI)
+      continue;
+
+    DEBUG(llvm::dbgs() << "        Visiting release: " << *RVI);
+
+    // Grab the operand of the release value inst.
+    SILValue Op = RVI->getOperand();
+
+    // Lookup the [(BB, EnumTag)] list for this operand.
+    unsigned ID = getIDForValue(Op);
+    auto R = EnumToEnumBBCaseListMap.find(ID);
+    // If we don't have one, skip this release value inst.
+    if (R == EnumToEnumBBCaseListMap.end()) {
+      DEBUG(llvm::dbgs() << "            Could not find [(BB, EnumTag)] "
+                            "list for release_value's operand. Bailing!\n");
+      continue;
+    }
+
+    auto &EnumBBCaseList = (*R)->second;
+    // If we don't have an enum tag for each predecessor of this BB, bail since
+    // we do not know how to handle that BB.
+    if (EnumBBCaseList.size() != NumPreds) {
+      DEBUG(llvm::dbgs() << "            Found [(BB, EnumTag)] list for "
+                            "release_value's operand, but we do not have an "
+                            "enum tag for each predecessor. Bailing!\n");
+      DEBUG(llvm::dbgs() << "            List:\n");
+      DEBUG(for (auto P
+                 : EnumBBCaseList) {
+        llvm::dbgs() << "                ";
+        P.second->dump(llvm::dbgs());
+      });
+      continue;
+    }
+
+    // Finally ensure that we have no users of this operand preceding the
+    // release_value in this BB. If we have users like that we cannot hoist the
+    // release past them unless we know that there is an additional set of
+    // releases that together post-dominate this release. If we cannot do this,
+    // skip this release.
+    //
+    // TODO: We need information from the ARC optimizer to prove that property
+    // if we are going to use it.
+    if (valueHasARCUsesInInstructionRange(Op, getBB()->begin(),
+                                          SILBasicBlock::iterator(RVI), AA)) {
+      DEBUG(llvm::dbgs() << "            Release value has use that stops "
+                            "hoisting! Bailing!\n");
+      continue;
+    }
+
+    DEBUG(llvm::dbgs() << "            Its safe to perform the "
+                          "transformation!\n");
+
+    // Otherwise perform the transformation.
+    for (auto P : EnumBBCaseList) {
+      // If we don't have an argument for this case, there is nothing to
+      // do... continue...
+      if (!P.second->hasAssociatedValues())
+        continue;
+
+      // Otherwise create the release_value before the terminator of the
+      // predecessor.
+      assert(P.first->getSingleSuccessorBlock() &&
+             "Cannot hoist release into BB that has multiple successors");
+      SILBuilderWithScope Builder(P.first->getTerminator(), RVI);
+      createRefCountOpForPayload(Builder, RVI, P.second);
+    }
+
+    RVI->eraseFromParent();
+    ++NumHoisted;
+    Changed = true;
+  }
+
+  return Changed;
+}
+
+static SILInstruction *findLastSinkableMatchingEnumValueRCIncrementInPred(
+    AliasAnalysis *AA, RCIdentityFunctionInfo *RCIA, SILValue EnumValue,
+    SILBasicBlock *BB) {
+  // Otherwise, see if we can find a retain_value or strong_retain associated
+  // with that enum in the relevant predecessor.
+  auto FirstInc = std::find_if(
+      BB->rbegin(), BB->rend(),
+      [&RCIA, &EnumValue](const SILInstruction &I) -> bool {
+        // If I is not an increment, ignore it.
+        if (!isa<StrongRetainInst>(I) && !isa<RetainValueInst>(I))
+          return false;
+
+        // Otherwise, if the increments operand stripped of RC identity
+        // preserving
+        // ops matches EnumValue, it is the first increment we are interested
+        // in.
+        return EnumValue == RCIA->getRCIdentityRoot(I.getOperand(0));
+      });
+
+  // If we do not find a ref count increment in the relevant BB, skip this
+  // enum since there is nothing we can do.
+  if (FirstInc == BB->rend())
+    return nullptr;
+
+  // Otherwise, see if there are any instructions in between FirstPredInc and
+  // the end of the given basic block that could decrement first pred. If such
+  // an instruction exists, we cannot perform this optimization so continue.
+  if (valueHasARCDecrementOrCheckInInstructionRange(
+          EnumValue, (*FirstInc).getIterator(),
+          BB->getTerminator()->getIterator(), AA))
+    return nullptr;
+
+  return &*FirstInc;
+}
+
+static bool findRetainsSinkableFromSwitchRegionForEnum(
+    AliasAnalysis *AA, RCIdentityFunctionInfo *RCIA, SILValue EnumValue,
+    EnumBBCaseList &Map, SmallVectorImpl<SILInstruction *> &DeleteList) {
+
+  // For each predecessor with argument type...
+  for (auto &P : Map) {
+    SILBasicBlock *PredBB = P.first;
+    EnumElementDecl *Decl = P.second;
+
+    // If the case does not have an argument type, skip the predecessor since
+    // there will not be a retain to sink.
+    if (!Decl->hasAssociatedValues())
+      continue;
+
+    // Ok, we found a payloaded predecessor. Look backwards through the
+    // predecessor for the first ref count increment on EnumValue. If there
+    // are no ref count decrements in between the increment and the terminator
+    // of the BB, then we can sink the retain out of the switch enum.
+    auto *Inc = findLastSinkableMatchingEnumValueRCIncrementInPred(
+        AA, RCIA, EnumValue, PredBB);
+    // If we do not find such an increment, there is nothing we can do, bail.
+    if (!Inc)
+      return false;
+
+    // Otherwise add the increment to the delete list.
+    DeleteList.push_back(Inc);
+  }
+
+  // If we were able to process each predecessor successfully, return true.
+  return true;
+}
+
+bool BBEnumTagDataflowState::sinkIncrementsOutOfSwitchRegions(
+    AliasAnalysis *AA, RCIdentityFunctionInfo *RCIA) {
+  bool Changed = false;
+  unsigned NumPreds = std::distance(getBB()->pred_begin(), getBB()->pred_end());
+  llvm::SmallVector<SILInstruction *, 4> DeleteList;
+
+  // For each (EnumValue, [(BB, EnumTag)]) that we are tracking...
+  for (auto &P : EnumToEnumBBCaseListMap) {
+    // Clear our delete list.
+    DeleteList.clear();
+
+    // If EnumValue is null, we deleted this entry. There is nothing to do for
+    // this value... Skip it.
+    if (!P.hasValue())
+      continue;
+
+    // Look up the actual enum value using our index to make sure that other
+    // parts of the pass have not destroyed the value. In such a case, just
+    // continue.
+    SILValue EnumValue = getContext().getValueForID(P->first);
+    if (!EnumValue)
+      continue;
+    EnumValue = RCIA->getRCIdentityRoot(EnumValue);
+    EnumBBCaseList &Map = P->second;
+
+    // If we do not have a tag associated with this enum value for each
+    // predecessor, we are not a switch region exit for this enum value. Skip
+    // this value.
+    if (Map.size() != NumPreds)
+      continue;
+
+    // Look through our predecessors for a set of ref count increments on our
+    // enum value for every payloaded case that *could* be sunk. If we miss an
+    // increment from any of the payloaded case there is nothing we can do here,
+    // so skip this enum value.
+    if (!findRetainsSinkableFromSwitchRegionForEnum(AA, RCIA, EnumValue, Map,
+                                                    DeleteList))
+      continue;
+
+    // If we do not have any payload arguments, then we should have an empty
+    // delete list and there is nothing to do here.
+    if (DeleteList.empty())
+      continue;
+
+    // Ok, we can perform this transformation! Insert the new retain_value and
+    // delete all of the ref count increments from the predecessor BBs.
+    //
+    // TODO: Which debug loc should we use here? Using one of the locs from the
+    // delete list seems reasonable for now...
+    SILBuilder Builder(getBB()->begin());
+    Builder.createRetainValue(
+        DeleteList[0]->getLoc(), EnumValue,
+        cast<RefCountingInst>(DeleteList[0])->getAtomicity());
+    for (auto *I : DeleteList)
+      I->eraseFromParent();
+    ++NumSunk;
+    Changed = true;
+  }
+
+  return Changed;
+}
+
+void BBEnumTagDataflowState::dump() const {
+#ifndef NDEBUG
+  llvm::dbgs() << "Dumping state for BB" << BB.get()->getDebugID() << "\n";
+  llvm::dbgs() << "Block States:\n";
+  for (auto &P : ValueToCaseMap) {
+    if (!P.hasValue()) {
+      llvm::dbgs() << "  Skipping blotted value.\n";
+      continue;
+    }
+    unsigned ID = P->first;
+    SILValue V = getContext().getValueForID(ID);
+    if (!V) {
+      llvm::dbgs() << "  ID: " << ID << ". Value: BLOTTED.\n";
+      continue;
+    }
+    llvm::dbgs() << "  ID: " << ID << ". Value: " << V;
+  }
+
+  llvm::dbgs() << "Predecessor States:\n";
+  // For each (EnumValue, [(BB, EnumTag)]) that we are tracking...
+  for (auto &P : EnumToEnumBBCaseListMap) {
+    if (!P.hasValue()) {
+      llvm::dbgs() << "  Skipping blotted value.\n";
+      continue;
+    }
+    unsigned ID = P->first;
+    SILValue V = getContext().getValueForID(ID);
+    if (!V) {
+      llvm::dbgs() << "  ID: " << ID << ". Value: BLOTTED.\n";
+      continue;
+    }
+    llvm::dbgs() << "  ID: " << ID << ". Value: " << V;
+    llvm::dbgs() << "  Case List:\n";
+    for (auto &P2 : P->second) {
+      llvm::dbgs() << "    BB" << P2.first->getDebugID() << ": ";
+      P2.second->dump(llvm::dbgs());
+      llvm::dbgs() << "\n";
+    }
+    llvm::dbgs() << "  End Case List.\n";
+  }
+#endif
+}
+
+bool BBEnumTagDataflowState::init(EnumCaseDataflowContext &NewContext,
+                                  SILBasicBlock *NewBB) {
+  assert(NewBB && "NewBB should not be null");
+  Context = &NewContext;
+  BB = NewBB;
+  return true;
+}
+
+//===----------------------------------------------------------------------===//
 //                            Generic Sinking Code
 //===----------------------------------------------------------------------===//
 
@@ -114,7 +860,8 @@
   if (BB->pred_empty())
     return false;
 
-  // Only try to hoist the first instruction. RRCM should have hoisted the release
+  // Only try to hoist the first instruction. RRCM should have hoisted the
+  // release
   // to the beginning of the block if it can.
   auto Head = &*BB->begin();
   // Make sure it is a release instruction.
@@ -127,14 +874,15 @@
     return false;
 
   // Make sure the release will not be blocked by the terminator instructions
-  // Make sure the terminator does not block, nor is a branch with multiple targets.
+  // Make sure the terminator does not block, nor is a branch with multiple
+  // targets.
   for (auto P : BB->getPredecessorBlocks()) {
     if (!isa<BranchInst>(P->getTerminator()))
       return false;
   }
 
   // Make sure we can get all the incoming values.
-  llvm::SmallVector<SILValue , 4> PredValues;
+  llvm::SmallVector<SILValue, 4> PredValues;
   if (!SA->getIncomingValues(PredValues))
     return false;
 
@@ -174,10 +922,10 @@
 enum OperandRelation {
   /// Uninitialized state.
   NotDeterminedYet,
-  
+
   /// The original operand values are equal.
   AlwaysEqual,
-  
+
   /// The operand values are equal after replacing with the successor block
   /// arguments.
   EqualAfterMove
@@ -205,7 +953,8 @@
   if (auto *Arg = dyn_cast<SILArgument>(In)) {
     SILBasicBlock *Parent = Arg->getParent();
     SILBasicBlock *Pred = Parent->getSinglePredecessorBlock();
-    if (!Pred) return In;
+    if (!Pred)
+      return In;
 
     // If the terminator is a cast instruction then use the pre-cast value.
     if (auto CCBI = dyn_cast<CheckedCastBranchInst>(Pred->getTerminator())) {
@@ -231,7 +980,6 @@
     if (auto CBI = dyn_cast<CondBranchInst>(Pred->getTerminator())) {
       return CBI->getArgForDestBB(Parent, Arg);
     }
-
   }
   return In;
 }
@@ -240,16 +988,16 @@
 /// \p BB starting at the end of the block, stopping on sink barriers.
 /// The \p opRelation must be consistent for all operand comparisons.
 SILInstruction *findIdenticalInBlock(SILBasicBlock *BB, SILInstruction *Iden,
-                                   const ValueToBBArgIdxMap &valueToArgIdxMap,
-                                   OperandRelation &opRelation) {
+                                     const ValueToBBArgIdxMap &valueToArgIdxMap,
+                                     OperandRelation &opRelation) {
   int SkipBudget = SinkSearchWindow;
 
   SILBasicBlock::iterator InstToSink = BB->getTerminator()->getIterator();
   SILBasicBlock *IdenBlock = Iden->getParent();
-  
+
   // The compare function for instruction operands.
   auto operandCompare = [&](const SILValue &Op1, const SILValue &Op2) -> bool {
-    
+
     if (opRelation != EqualAfterMove && Op1 == Op2) {
       // The trivial case.
       opRelation = AlwaysEqual;
@@ -271,7 +1019,7 @@
     }
     return false;
   };
-  
+
   while (SkipBudget) {
     // If we found a sinkable instruction that is identical to our goal
     // then return it.
@@ -400,7 +1148,7 @@
 }
 
 // Try to sink values from the Nth argument \p ArgNum.
-static bool sinkArgument(SILBasicBlock *BB, unsigned ArgNum) {
+static bool sinkArgument(EnumCaseDataflowContext &Context, SILBasicBlock *BB, unsigned ArgNum) {
   assert(ArgNum < BB->getNumArguments() && "Invalid argument");
 
   // Find the first predecessor, the first terminator and the Nth argument.
@@ -415,7 +1163,7 @@
     return false;
 
   // The list of identical instructions.
-  SmallVector<SingleValueInstruction*, 8> Clones;
+  SmallVector<SingleValueInstruction *, 8> Clones;
   Clones.push_back(FSI);
 
   // Don't move instructions that are sensitive to their location.
@@ -423,8 +1171,8 @@
   // If this instruction can read memory, we try to be conservatively not to
   // move it, as there may be instructions that can clobber the read memory
   // from current place to the place where it is moved to.
-  if (FSI->mayReadFromMemory() || (FSI->mayHaveSideEffects() &&
-      !isa<AllocationInst>(FSI)))
+  if (FSI->mayReadFromMemory() ||
+      (FSI->mayHaveSideEffects() && !isa<AllocationInst>(FSI)))
     return false;
 
   // If the instructions are different, but only in terms of a cheap operand
@@ -524,18 +1272,21 @@
 
   // The argument is no longer in use. Replace all incoming inputs with undef
   // and try to delete the instruction.
-  for (auto S : Clones)
+  for (auto S : Clones) {
     if (S != FSI) {
       deleteAllDebugUses(S);
       S->replaceAllUsesWith(Undef);
       auto DeadArgInst = cast<SILInstruction>(S);
-      recursivelyDeleteTriviallyDeadInstructions(DeadArgInst);
+      for (SILValue Result : DeadArgInst->getResults()) {
+        Context.blotValue(Result);
+      }
+      DeadArgInst->eraseFromParent();
     }
+  }
 
   return true;
 }
 
-
 /// Try to sink literals that are passed to arguments that are coming from
 /// multiple predecessors.
 /// Notice that unlike other sinking methods in this file we do allow sinking
@@ -553,7 +1304,8 @@
 }
 
 /// Try to sink identical arguments coming from multiple predecessors.
-static bool sinkArgumentsFromPredecessors(SILBasicBlock *BB) {
+static bool sinkArgumentsFromPredecessors(EnumCaseDataflowContext &Context,
+                                          SILBasicBlock *BB) {
   if (BB->pred_empty() || BB->getSinglePredecessorBlock())
     return false;
 
@@ -565,7 +1317,7 @@
   // Try to sink values from each of the arguments to the basic block.
   bool Changed = false;
   for (int i = 0, e = BB->getNumArguments(); i < e; ++i)
-    Changed |= sinkArgument(BB, i);
+    Changed |= sinkArgument(Context, BB, i);
 
   return Changed;
 }
@@ -578,23 +1330,24 @@
 /// values that come from basic block arguments with the caller values and
 /// strip casts.
 static bool canonicalizeRefCountInstrs(SILBasicBlock *BB) {
- bool Changed = false;
- for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
-   if (!isa<StrongReleaseInst>(I) && !isa<StrongRetainInst>(I))
-     continue;
+  bool Changed = false;
+  for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
+    if (!isa<StrongReleaseInst>(I) && !isa<StrongRetainInst>(I))
+      continue;
 
-   SILValue Ref = I->getOperand(0);
-   SILValue Root = findValueShallowRoot(Ref);
-   if (Ref != Root) {
-     I->setOperand(0, Root);
-     Changed = true;
-   }
- }
+    SILValue Ref = I->getOperand(0);
+    SILValue Root = findValueShallowRoot(Ref);
+    if (Ref != Root) {
+      I->setOperand(0, Root);
+      Changed = true;
+    }
+  }
 
- return Changed;
+  return Changed;
 }
 
-static bool sinkCodeFromPredecessors(SILBasicBlock *BB) {
+static bool sinkCodeFromPredecessors(EnumCaseDataflowContext &Context,
+                                     SILBasicBlock *BB) {
   bool Changed = false;
   if (BB->pred_empty())
     return Changed;
@@ -681,6 +1434,9 @@
         Changed = true;
         for (auto I : Dups) {
           I->replaceAllUsesPairwiseWith(&*InstToSink);
+          for (SILValue Result : I->getResults()) {
+            Context.blotValue(Result);
+          }
           I->eraseFromParent();
           NumSunk++;
         }
@@ -733,8 +1489,7 @@
   // not move it.
   auto SwitchIter = Switch->getIterator();
   if (auto B = valueHasARCDecrementOrCheckInInstructionRange(Ptr, RV,
-                                                             SwitchIter,
-                                                             AA)) {
+                                                             SwitchIter, AA)) {
     RV->moveBefore(&**B);
     return true;
   }
@@ -795,7 +1550,7 @@
   NullablePtr<EnumElementDecl> TrueElement = SEI->getSingleTrueElement();
   if (TrueElement.isNull())
     return false;
-  
+
   // Next go over all instructions after I in the basic block. If none of them
   // can decrement our ptr value, we can move the retain over the ref count
   // inst. If any of them do potentially decrement the ref count of Ptr, we can
@@ -814,7 +1569,7 @@
   if (RCIA->getRCIdentityRoot(Ptr) !=
       RCIA->getRCIdentityRoot(SEI->getEnumOperand()))
     return false;
-  
+
   // Work out which enum element is the true branch, and which is false.
   // If the enum only has 2 values and its tag isn't the true branch, then we
   // know the true branch must be the other tag.
@@ -887,17 +1642,18 @@
 
 /// Try sink a retain as far as possible.  This is either to successor BBs,
 /// or as far down the current BB as possible
-static bool sinkIncrementsIntoSwitchRegions(SILBasicBlock *BB, AliasAnalysis *AA,
+static bool sinkIncrementsIntoSwitchRegions(SILBasicBlock *BB,
+                                            AliasAnalysis *AA,
                                             RCIdentityFunctionInfo *RCIA) {
   // Make sure that each one of our successors only has one predecessor,
   // us.
   // If that condition is not true, we can still sink to the end of this BB,
   // but not to successors.
-  bool CanSinkToSuccessor = std::none_of(BB->succ_begin(), BB->succ_end(),
-    [](const SILSuccessor &S) -> bool {
-      SILBasicBlock *SuccBB = S.getBB();
-      return !SuccBB || !SuccBB->getSinglePredecessorBlock();
-  });
+  bool CanSinkToSuccessor = std::none_of(
+      BB->succ_begin(), BB->succ_end(), [](const SILSuccessor &S) -> bool {
+        SILBasicBlock *SuccBB = S.getBB();
+        return !SuccBB || !SuccBB->getSinglePredecessorBlock();
+      });
 
   SILInstruction *S = BB->getTerminator();
   auto SI = S->getIterator(), SE = BB->begin();
@@ -920,649 +1676,13 @@
     //      terminator, sink the ref count inst into either our successors.
     //   2. If there are such decrements, move the retain right before that
     //      decrement.
-    Changed |= tryTosinkIncrementsIntoSwitchRegions(S->getIterator(),
-                                                    Inst->getIterator(),
-                                                    CanSinkToSuccessor, 
-                                                    AA, RCIA);
+    Changed |= tryTosinkIncrementsIntoSwitchRegions(
+        S->getIterator(), Inst->getIterator(), CanSinkToSuccessor, AA, RCIA);
   }
 
   // Handle the first instruction in the BB.
-  Changed |=
-      tryTosinkIncrementsIntoSwitchRegions(S->getIterator(), SI,
-                                           CanSinkToSuccessor, AA, RCIA);
-  return Changed;
-}
-
-//===----------------------------------------------------------------------===//
-//                             Enum Tag Dataflow
-//===----------------------------------------------------------------------===//
-
-namespace {
-
-class BBToDataflowStateMap;
-
-using EnumBBCaseList = llvm::SmallVector<std::pair<SILBasicBlock *,
-                                                   EnumElementDecl *>, 2>;
-
-/// Class that performs enum tag state dataflow on the given BB.
-class BBEnumTagDataflowState
-    : public SILInstructionVisitor<BBEnumTagDataflowState, bool> {
-  NullablePtr<SILBasicBlock> BB;
-
-  using ValueToCaseSmallBlotMapVectorTy =
-    SmallBlotMapVector<SILValue, EnumElementDecl *, 4>;
-  ValueToCaseSmallBlotMapVectorTy ValueToCaseMap;
-
-  using EnumToEnumBBCaseListMapTy =
-    SmallBlotMapVector<SILValue, EnumBBCaseList, 4>;
-
-  EnumToEnumBBCaseListMapTy EnumToEnumBBCaseListMap;
-
-public:
-  BBEnumTagDataflowState() = default;
-  BBEnumTagDataflowState(const BBEnumTagDataflowState &Other) = default;
-  ~BBEnumTagDataflowState() = default;
-
-  bool init(SILBasicBlock *NewBB) {
-    assert(NewBB && "NewBB should not be null");
-    BB = NewBB;
-    return true;
-  }
-
-  SILBasicBlock *getBB() { return BB.get(); }
-
-  using iterator = decltype(ValueToCaseMap)::iterator;
-  iterator begin() { return ValueToCaseMap.getItems().begin(); }
-  iterator end() { return ValueToCaseMap.getItems().begin(); }
-
-  void clear() { ValueToCaseMap.clear(); }
-
-  bool visitSILInstruction(SILInstruction *I) { return false; }
-
-  bool visitEnumInst(EnumInst *EI) {
-    DEBUG(llvm::dbgs() << "    Storing enum into map: " << *EI);
-    ValueToCaseMap[SILValue(EI)] = EI->getElement();
-    return false;
-  }
-
-  bool visitUncheckedEnumDataInst(UncheckedEnumDataInst *UEDI) {
-    DEBUG(
-        llvm::dbgs() << "    Storing unchecked enum data into map: " << *UEDI);
-    ValueToCaseMap[SILValue(UEDI->getOperand())] = UEDI->getElement();
-    return false;
-  }
-
-  bool visitRetainValueInst(RetainValueInst *RVI);
-  bool visitReleaseValueInst(ReleaseValueInst *RVI);
-  bool process();
-  bool hoistDecrementsIntoSwitchRegions(AliasAnalysis *AA);
-  bool sinkIncrementsOutOfSwitchRegions(AliasAnalysis *AA,
-                                        RCIdentityFunctionInfo *RCIA);
-  void handlePredSwitchEnum(SwitchEnumInst *S);
-  void handlePredCondSelectEnum(CondBranchInst *CondBr);
-
-  /// Helper method which initializes this state map with the data from the
-  /// first predecessor BB.
-  ///
-  /// We will be performing an intersection in a later step of the merging.
-  bool initWithFirstPred(BBToDataflowStateMap &BBToStateMap,
-                         SILBasicBlock *FirstPredBB);
-
-  /// Top level merging function for predecessors.
-  void mergePredecessorStates(BBToDataflowStateMap &BBToStateMap);
-
-  /// 
-  void mergeSinglePredTermInfoIntoState(BBToDataflowStateMap &BBToStateMap,
-                                        SILBasicBlock *Pred);
-
-};
-
-/// Map all blocks to BBEnumTagDataflowState in RPO order.
-class BBToDataflowStateMap {
-  PostOrderFunctionInfo *PO;
-  std::vector<BBEnumTagDataflowState> BBToStateVec;
-public:
-  BBToDataflowStateMap(PostOrderFunctionInfo *PO) : PO(PO), BBToStateVec() {
-    BBToStateVec.resize(PO->size());
-    unsigned RPOIdx = 0;
-    for (SILBasicBlock *BB : PO->getReversePostOrder()) {
-      BBToStateVec[RPOIdx].init(BB);
-      ++RPOIdx;
-    }
-  }
-  unsigned size() const {
-    return BBToStateVec.size();
-  }
-  BBEnumTagDataflowState &getRPOState(unsigned RPOIdx) {
-    return BBToStateVec[RPOIdx];
-  }
-  /// \return BBEnumTagDataflowState or NULL for unreachable blocks.
-  BBEnumTagDataflowState *getBBState(SILBasicBlock *BB) {
-    if (auto ID = PO->getRPONumber(BB)) {
-      return &getRPOState(*ID);
-    }
-    return nullptr;
-  }
-};
-
-} // end anonymous namespace
-
-void BBEnumTagDataflowState::handlePredSwitchEnum(SwitchEnumInst *S) {
-
-  // Find the tag associated with our BB and set the state of the
-  // enum we switch on to that value. This is important so we can determine
-  // covering switches for enums that have cases without payload.
-
-  // Next check if we are the target of a default switch_enum case. If we are,
-  // no interesting information can be extracted, so bail...
-  if (S->hasDefault() && S->getDefaultBB() == getBB())
-    return;
-
-  // Otherwise, attempt to find the tag associated with this BB in the switch
-  // enum...
-  for (unsigned i = 0, e = S->getNumCases(); i != e; ++i) {
-    auto P = S->getCase(i);
-
-    // If this case of the switch is not matched up with this BB, skip the
-    // case...
-    if (P.second != getBB())
-      continue;
-
-    // Ok, we found the case for our BB. If we don't have an enum tag (which can
-    // happen if we have a default statement), return. There is nothing more we
-    // can do.
-    if (!P.first)
-      return;
-
-    // Ok, we have a matching BB and a matching enum tag. Set the state and
-    // return.
-    ValueToCaseMap[S->getOperand()] = P.first;
-    return;
-  }
-  llvm_unreachable("A successor of a switch_enum terminated BB should be in "
-                   "the switch_enum.");
-}
-
-void BBEnumTagDataflowState::handlePredCondSelectEnum(CondBranchInst *CondBr) {
-
-  auto *EITI = dyn_cast<SelectEnumInst>(CondBr->getCondition());
-  if (!EITI)
-    return;
-
-  NullablePtr<EnumElementDecl> TrueElement = EITI->getSingleTrueElement();
-  if (TrueElement.isNull())
-    return;
-
-  // Find the tag associated with our BB and set the state of the
-  // enum we switch on to that value. This is important so we can determine
-  // covering switches for enums that have cases without payload.
-
-  // Check if we are the true case, ie, we know that we are the given tag.
-  const auto &Operand = EITI->getEnumOperand();
-  if (CondBr->getTrueBB() == getBB()) {
-    ValueToCaseMap[Operand] = TrueElement.get();
-    return;
-  }
-
-  // If the enum only has 2 values and its tag isn't the true branch, then we
-  // know the true branch must be the other tag.
-  if (EnumDecl *E = Operand->getType().getEnumOrBoundGenericEnum()) {
-    // Look for a single other element on this enum.
-    EnumElementDecl *OtherElt = nullptr;
-    for (EnumElementDecl *Elt : E->getAllElements()) {
-      // Skip the case where we find the select_enum element
-      if (Elt == TrueElement.get())
-        continue;
-      // If we find another element, then we must have more than 2, so bail.
-      if (OtherElt)
-        return;
-      OtherElt = Elt;
-    }
-    // Only a single enum element?  How would this even get here?  We should
-    // handle it in SILCombine.
-    if (!OtherElt)
-      return;
-    // FIXME: Can we ever not be the false BB here?
-    if (CondBr->getTrueBB() != getBB()) {
-      ValueToCaseMap[Operand] = OtherElt;
-      return;
-    }
-  }
-}
-
-bool
-BBEnumTagDataflowState::
-initWithFirstPred(BBToDataflowStateMap &BBToStateMap,
-                  SILBasicBlock *FirstPredBB) {
-  // Try to look up the state for the first pred BB.
-  BBEnumTagDataflowState *FirstPredState = BBToStateMap.getBBState(FirstPredBB);
-
-  // If we fail, we found an unreachable block, bail.
-  if (FirstPredState == nullptr) {
-    DEBUG(llvm::dbgs() << "        Found an unreachable block!\n");
-    return false;
-  }
-
-  // Ok, our state is in the map, copy in the predecessors value to case map.
-  ValueToCaseMap = FirstPredState->ValueToCaseMap;
-
-  // If we are predecessors only successor, we can potentially hoist releases
-  // into it, so associate the first pred BB and the case for each value that we
-  // are tracking with it.
-  //
-  // TODO: I am writing this too fast. Clean this up later.
-  if (FirstPredBB->getSingleSuccessorBlock()) {
-    for (auto P : ValueToCaseMap.getItems()) {
-      if (!P.hasValue())
-        continue;
-      EnumToEnumBBCaseListMap[P->first].push_back({FirstPredBB, P->second});
-    }
-  }
-
-  return true;
-}
-
-void
-BBEnumTagDataflowState::
-mergeSinglePredTermInfoIntoState(BBToDataflowStateMap &BBToStateMap,
-                                 SILBasicBlock *Pred) {
-  // Grab the terminator of our one predecessor and if it is a switch enum, mix
-  // it into this state.
-  TermInst *PredTerm = Pred->getTerminator();
-  if (auto *S = dyn_cast<SwitchEnumInst>(PredTerm)) {
-    handlePredSwitchEnum(S);
-    return;
-  }
-
-  auto *CondBr = dyn_cast<CondBranchInst>(PredTerm);
-  if (!CondBr)
-    return;
-
-  handlePredCondSelectEnum(CondBr);
-}
-
-void
-BBEnumTagDataflowState::
-mergePredecessorStates(BBToDataflowStateMap &BBToStateMap) {
-
-  // If we have no predecessors, there is nothing to do so return early...
-  if (getBB()->pred_empty()) {
-    DEBUG(llvm::dbgs() << "            No Preds.\n");
-    return;
-  }
-
-  auto PI = getBB()->pred_begin(), PE = getBB()->pred_end();
-  if (*PI == getBB()) {
-    DEBUG(llvm::dbgs() << "            Found a self loop. Bailing!\n");
-    return;
-  }
-
-  // Grab the first predecessor BB.
-  SILBasicBlock *FirstPred = *PI;
-  ++PI;
-
-  // Attempt to initialize our state with our first predecessor's state by just
-  // copying. We will be doing an intersection with all of the other BB.
-  if (!initWithFirstPred(BBToStateMap, FirstPred))
-    return;
-
-  // If we only have one predecessor see if we can gain any information and or
-  // knowledge from the terminator of our one predecessor. There is nothing more
-  // that we can do, return.
-  //
-  // This enables us to get enum information from switch_enum and cond_br about
-  // the value that an enum can take in our block. This is a common case that
-  // comes up.
-  if (PI == PE) {
-    mergeSinglePredTermInfoIntoState(BBToStateMap, FirstPred);
-    return;
-  }
-
-  DEBUG(llvm::dbgs() << "            Merging in rest of predecessors...\n");
-
-  // Enum values that while merging we found conflicting values for. We blot
-  // them after the loop in order to ensure that we can still find the ends of
-  // switch regions.
-  llvm::SmallVector<SILValue, 4> CurBBValuesToBlot;
-
-  // If we do not find state for a specific value in any of our predecessor BBs,
-  // we cannot be the end of a switch region since we cannot cover our
-  // predecessor BBs with enum decls. Blot after the loop.
-  llvm::SmallVector<SILValue, 4> PredBBValuesToBlot;
-
-  // And for each remaining predecessor...
-  do {
-    // If we loop on ourselves, bail...
-    if (*PI == getBB()) {
-      DEBUG(llvm::dbgs() << "            Found a self loop. Bailing!\n");
-      return;
-    }
-
-    // Grab the predecessors state...
-    SILBasicBlock *PredBB = *PI;
-
-    BBEnumTagDataflowState *PredBBState = BBToStateMap.getBBState(PredBB);
-    if (PredBBState == nullptr) {
-      DEBUG(llvm::dbgs() << "            Found an unreachable block!\n");
-      return;
-    }
-
-    ++PI;
-
-    // Then for each (SILValue, Enum Tag) that we are tracking...
-    for (auto P : ValueToCaseMap.getItems()) {
-      // If this SILValue was blotted, there is nothing left to do, we found
-      // some sort of conflicting definition and are being conservative.
-      if (!P.hasValue())
-        continue;
-
-      // Then attempt to look up the enum state associated in our SILValue in
-      // the predecessor we are processing.
-      auto PredValue = PredBBState->ValueToCaseMap.find(P->first);
-
-      // If we cannot find the state associated with this SILValue in this
-      // predecessor or the value in the corresponding predecessor was blotted,
-      // we cannot find a covering switch for this BB or forward any enum tag
-      // information for this enum value.
-      if (PredValue == PredBBState->ValueToCaseMap.end() || !(*PredValue)->first) {
-        // Otherwise, we are conservative and do not forward the EnumTag that we
-        // are tracking. Blot it!
-        DEBUG(llvm::dbgs() << "                Blotting: " << P->first);
-        CurBBValuesToBlot.push_back(P->first);
-        PredBBValuesToBlot.push_back(P->first);
-        continue;
-      }
-
-      // Check if out predecessor has any other successors. If that is true we
-      // clear all the state since we cannot hoist safely.
-      if (!PredBB->getSingleSuccessorBlock()) {
-        EnumToEnumBBCaseListMap.clear();
-        DEBUG(llvm::dbgs() << "                Predecessor has other "
-              "successors. Clearing BB cast list map.\n");
-      } else {
-        // Otherwise, add this case to our predecessor case list. We will unique
-        // this after we have finished processing all predecessors.
-        auto Case = std::make_pair(PredBB, (*PredValue)->second);
-        EnumToEnumBBCaseListMap[(*PredValue)->first].push_back(Case);
-      }
-
-      // And the states match, the enum state propagates to this BB.
-      if ((*PredValue)->second == P->second)
-        continue;
-
-      // Otherwise, we are conservative and do not forward the EnumTag that we
-      // are tracking. Blot it!
-      DEBUG(llvm::dbgs() << "                Blotting: " << P->first);
-      CurBBValuesToBlot.push_back(P->first);
-    }
-  } while (PI != PE);
-
-  for (SILValue V : CurBBValuesToBlot) {
-    ValueToCaseMap.blot(V);
-  }
-  for (SILValue V : PredBBValuesToBlot) {
-    EnumToEnumBBCaseListMap.blot(V);
-  }
-}
-
-bool BBEnumTagDataflowState::visitRetainValueInst(RetainValueInst *RVI) {
-  auto FindResult = ValueToCaseMap.find(RVI->getOperand());
-  if (FindResult == ValueToCaseMap.end())
-    return false;
-
-  // If we do not have any argument, kill the retain_value.
-  if (!(*FindResult)->second->hasAssociatedValues()) {
-    RVI->eraseFromParent();
-    return true;
-  }
-
-  DEBUG(llvm::dbgs() << "    Found RetainValue: " << *RVI);
-  DEBUG(llvm::dbgs() << "        Paired to Enum Oracle: " << (*FindResult)->first);
-
-  SILBuilderWithScope Builder(RVI);
-  createRefCountOpForPayload(Builder, RVI, (*FindResult)->second);
-  RVI->eraseFromParent();
-  return true;
-}
-
-bool BBEnumTagDataflowState::visitReleaseValueInst(ReleaseValueInst *RVI) {
-  auto FindResult = ValueToCaseMap.find(RVI->getOperand());
-  if (FindResult == ValueToCaseMap.end())
-    return false;
-
-  // If we do not have any argument, just delete the release value.
-  if (!(*FindResult)->second->hasAssociatedValues()) {
-    RVI->eraseFromParent();
-    return true;
-  }
-
-  DEBUG(llvm::dbgs() << "    Found ReleaseValue: " << *RVI);
-  DEBUG(llvm::dbgs() << "        Paired to Enum Oracle: " << (*FindResult)->first);
-
-  SILBuilderWithScope Builder(RVI);
-  createRefCountOpForPayload(Builder, RVI, (*FindResult)->second);
-  RVI->eraseFromParent();
-  return true;
-}
-
-bool BBEnumTagDataflowState::process() {
-  bool Changed = false;
-
-  auto SI = getBB()->begin();
-  while (SI != getBB()->end()) {
-    SILInstruction *I = &*SI;
-    ++SI;
-    Changed |= visit(I);
-  }
-
-  return Changed;
-}
-
-bool
-BBEnumTagDataflowState::hoistDecrementsIntoSwitchRegions(AliasAnalysis *AA) {
-  bool Changed = false;
-  unsigned NumPreds = std::distance(getBB()->pred_begin(), getBB()->pred_end());
-
-  for (auto II = getBB()->begin(), IE = getBB()->end(); II != IE;) {
-    auto *RVI = dyn_cast<ReleaseValueInst>(&*II);
-    ++II;
-
-    // If this instruction is not a release, skip it...
-    if (!RVI)
-      continue;
-
-    DEBUG(llvm::dbgs() << "        Visiting release: " << *RVI);
-
-    // Grab the operand of the release value inst.
-    SILValue Op = RVI->getOperand();
-
-    // Lookup the [(BB, EnumTag)] list for this operand.
-    auto R = EnumToEnumBBCaseListMap.find(Op);
-    // If we don't have one, skip this release value inst.
-    if (R == EnumToEnumBBCaseListMap.end()) {
-      DEBUG(llvm::dbgs() << "            Could not find [(BB, EnumTag)] "
-            "list for release_value's operand. Bailing!\n");
-      continue;
-    }
-
-    auto &EnumBBCaseList = (*R)->second;
-    // If we don't have an enum tag for each predecessor of this BB, bail since
-    // we do not know how to handle that BB.
-    if (EnumBBCaseList.size() != NumPreds) {
-      DEBUG(llvm::dbgs() << "            Found [(BB, EnumTag)] "
-            "list for release_value's operand, but we do not have an enum tag "
-            "for each predecessor. Bailing!\n");
-      DEBUG(llvm::dbgs() << "            List:\n");
-      DEBUG(for (auto P : EnumBBCaseList) {
-          llvm::dbgs() << "                "; P.second->dump(llvm::dbgs());
-        });
-      continue;
-    }
-
-    // Finally ensure that we have no users of this operand preceding the
-    // release_value in this BB. If we have users like that we cannot hoist the
-    // release past them unless we know that there is an additional set of
-    // releases that together post-dominate this release. If we cannot do this,
-    // skip this release.
-    //
-    // TODO: We need information from the ARC optimizer to prove that property
-    // if we are going to use it.
-    if (valueHasARCUsesInInstructionRange(Op, getBB()->begin(),
-                                          SILBasicBlock::iterator(RVI),
-                                          AA)) {
-      DEBUG(llvm::dbgs() << "            Release value has use that stops "
-            "hoisting! Bailing!\n");
-      continue;
-    }
-
-    DEBUG(llvm::dbgs() << "            Its safe to perform the "
-          "transformation!\n");
-
-    // Otherwise perform the transformation.
-    for (auto P : EnumBBCaseList) {
-      // If we don't have an argument for this case, there is nothing to
-      // do... continue...
-      if (!P.second->hasAssociatedValues())
-        continue;
-
-      // Otherwise create the release_value before the terminator of the
-      // predecessor.
-      assert(P.first->getSingleSuccessorBlock() &&
-             "Cannot hoist release into BB that has multiple successors");
-      SILBuilderWithScope Builder(P.first->getTerminator(), RVI);
-      createRefCountOpForPayload(Builder, RVI, P.second);
-    }
-
-    RVI->eraseFromParent();
-    ++NumHoisted;
-    Changed = true;
-  }
-
-  return Changed;
-}
-
-static SILInstruction *
-findLastSinkableMatchingEnumValueRCIncrementInPred(AliasAnalysis *AA,
-                                                   RCIdentityFunctionInfo *RCIA,
-                                                   SILValue EnumValue,
-                                                   SILBasicBlock *BB) {
-    // Otherwise, see if we can find a retain_value or strong_retain associated
-    // with that enum in the relevant predecessor.
-    auto FirstInc = std::find_if(BB->rbegin(), BB->rend(),
-      [&RCIA, &EnumValue](const SILInstruction &I) -> bool {
-      // If I is not an increment, ignore it.
-      if (!isa<StrongRetainInst>(I) && !isa<RetainValueInst>(I))
-        return false;
-
-      // Otherwise, if the increments operand stripped of RC identity preserving
-      // ops matches EnumValue, it is the first increment we are interested in.
-      return EnumValue == RCIA->getRCIdentityRoot(I.getOperand(0));
-    });
-
-    // If we do not find a ref count increment in the relevant BB, skip this
-    // enum since there is nothing we can do.
-    if (FirstInc == BB->rend())
-      return nullptr;
-
-    // Otherwise, see if there are any instructions in between FirstPredInc and
-    // the end of the given basic block that could decrement first pred. If such
-    // an instruction exists, we cannot perform this optimization so continue.
-    if (valueHasARCDecrementOrCheckInInstructionRange(
-            EnumValue, (*FirstInc).getIterator(),
-            BB->getTerminator()->getIterator(), AA))
-      return nullptr;
-
-    return &*FirstInc;
-}
-
-static bool
-findRetainsSinkableFromSwitchRegionForEnum(
-  AliasAnalysis *AA, RCIdentityFunctionInfo *RCIA, SILValue EnumValue,
-  EnumBBCaseList &Map, SmallVectorImpl<SILInstruction *> &DeleteList) {
-
-  // For each predecessor with argument type...
-  for (auto &P : Map) {
-    SILBasicBlock *PredBB = P.first;
-    EnumElementDecl *Decl = P.second;
-
-    // If the case does not have an argument type, skip the predecessor since
-    // there will not be a retain to sink.
-    if (!Decl->hasAssociatedValues())
-      continue;
-
-    // Ok, we found a payloaded predecessor. Look backwards through the
-    // predecessor for the first ref count increment on EnumValue. If there
-    // are no ref count decrements in between the increment and the terminator
-    // of the BB, then we can sink the retain out of the switch enum.
-    auto *Inc = findLastSinkableMatchingEnumValueRCIncrementInPred(AA,
-                                                                   RCIA,
-                                                                   EnumValue,
-                                                                   PredBB);
-    // If we do not find such an increment, there is nothing we can do, bail.
-    if (!Inc)
-      return false;
-
-    // Otherwise add the increment to the delete list.
-    DeleteList.push_back(Inc);
-  }
-
-  // If we were able to process each predecessor successfully, return true.
-  return true;
-}
-
-bool
-BBEnumTagDataflowState::
-sinkIncrementsOutOfSwitchRegions(AliasAnalysis *AA,
-                                 RCIdentityFunctionInfo *RCIA) {
-  bool Changed = false;
-  unsigned NumPreds = std::distance(getBB()->pred_begin(), getBB()->pred_end());
-  llvm::SmallVector<SILInstruction *, 4> DeleteList;
-
-  // For each (EnumValue, [(BB, EnumTag)]) that we are tracking...
-  for (auto &P : EnumToEnumBBCaseListMap) {
-    // Clear our delete list.
-    DeleteList.clear();
-
-    // If EnumValue is null, we deleted this entry. There is nothing to do for
-    // this value... Skip it.
-    if (!P.hasValue())
-      continue;
-    SILValue EnumValue = RCIA->getRCIdentityRoot(P->first);
-    EnumBBCaseList &Map = P->second;
-
-    // If we do not have a tag associated with this enum value for each
-    // predecessor, we are not a switch region exit for this enum value. Skip
-    // this value.
-    if (Map.size() != NumPreds)
-      continue;
-
-    // Look through our predecessors for a set of ref count increments on our
-    // enum value for every payloaded case that *could* be sunk. If we miss an
-    // increment from any of the payloaded case there is nothing we can do here,
-    // so skip this enum value.
-    if (!findRetainsSinkableFromSwitchRegionForEnum(AA, RCIA, EnumValue, Map,
-                                                    DeleteList))
-      continue;
-
-    // If we do not have any payload arguments, then we should have an empty
-    // delete list and there is nothing to do here.
-    if (DeleteList.empty())
-      continue;
-
-    // Ok, we can perform this transformation! Insert the new retain_value and
-    // delete all of the ref count increments from the predecessor BBs.
-    //
-    // TODO: Which debug loc should we use here? Using one of the locs from the
-    // delete list seems reasonable for now...
-    SILBuilder Builder(getBB()->begin());
-    Builder.createRetainValue(DeleteList[0]->getLoc(), EnumValue,
-                              cast<RefCountingInst>(DeleteList[0])->getAtomicity());
-    for (auto *I : DeleteList)
-      I->eraseFromParent();
-    ++NumSunk;
-    Changed = true;
-  }
-
+  Changed |= tryTosinkIncrementsIntoSwitchRegions(S->getIterator(), SI,
+                                                  CanSinkToSuccessor, AA, RCIA);
   return Changed;
 }
 
@@ -1577,7 +1697,7 @@
 
   bool Changed = false;
 
-  BBToDataflowStateMap BBToStateMap(PO);
+  EnumCaseDataflowContext BBToStateMap(PO);
   for (unsigned RPOIdx = 0, RPOEnd = BBToStateMap.size(); RPOIdx < RPOEnd;
        ++RPOIdx) {
 
@@ -1596,7 +1716,7 @@
     // predecessors to avoid memory invalidation issues due to copying in the
     // dense map.
     DEBUG(llvm::dbgs() << "    Merging predecessors!\n");
-    State.mergePredecessorStates(BBToStateMap);
+    State.mergePredecessorStates();
 
     // If our predecessors cover any of our enum values, attempt to hoist
     // releases up the CFG onto enum payloads or sink retains out of switch
@@ -1621,8 +1741,8 @@
     // predecessors since the hoisted releases will be on the enum payload
     // instead of the enum itself.
     Changed |= canonicalizeRefCountInstrs(State.getBB());
-    Changed |= sinkCodeFromPredecessors(State.getBB());
-    Changed |= sinkArgumentsFromPredecessors(State.getBB());
+    Changed |= sinkCodeFromPredecessors(BBToStateMap, State.getBB());
+    Changed |= sinkArgumentsFromPredecessors(BBToStateMap, State.getBB());
     Changed |= sinkLiteralsFromPredecessors(State.getBB());
     // Try to hoist release of a SILArgument to predecessors.
     Changed |= hoistSILArgumentReleaseInst(State.getBB());
diff --git a/lib/SILOptimizer/Transforms/SpeculativeDevirtualizer.cpp b/lib/SILOptimizer/Transforms/SpeculativeDevirtualizer.cpp
index f96b3bd..a682885 100644
--- a/lib/SILOptimizer/Transforms/SpeculativeDevirtualizer.cpp
+++ b/lib/SILOptimizer/Transforms/SpeculativeDevirtualizer.cpp
@@ -23,6 +23,7 @@
 #include "swift/SIL/SILInstruction.h"
 #include "swift/SIL/SILModule.h"
 #include "swift/SIL/InstructionUtils.h"
+#include "swift/SIL/OptimizationRemark.h"
 #include "swift/SILOptimizer/Analysis/ClassHierarchyAnalysis.h"
 #include "swift/SILOptimizer/Utils/Generics.h"
 #include "swift/SILOptimizer/PassManager/Passes.h"
@@ -181,7 +182,8 @@
   NumTargetsPredicted++;
 
   // Devirtualize the apply instruction on the identical path.
-  auto NewInstPair = devirtualizeClassMethod(IdenAI, DownCastedClassInstance);
+  auto NewInstPair =
+      devirtualizeClassMethod(IdenAI, DownCastedClassInstance, nullptr);
   assert(NewInstPair.first && "Expected to be able to devirtualize apply!");
   replaceDeadApply(IdenAI, NewInstPair.first);
 
@@ -322,8 +324,8 @@
 
 /// \brief Try to speculate the call target for the call \p AI. This function
 /// returns true if a change was made.
-static bool tryToSpeculateTarget(FullApplySite AI,
-                                 ClassHierarchyAnalysis *CHA) {
+static bool tryToSpeculateTarget(FullApplySite AI, ClassHierarchyAnalysis *CHA,
+                                 OptRemark::Emitter &ORE) {
   ClassMethodInst *CMI = cast<ClassMethodInst>(AI.getCallee());
 
   // Don't devirtualize withUnsafeGuaranteed 'self' as this would prevent
@@ -364,7 +366,7 @@
     // try to devirtualize it completely.
     ClassHierarchyAnalysis::ClassList Subs;
     if (isDefaultCaseKnown(CHA, AI, CD, Subs)) {
-      auto NewInstPair = tryDevirtualizeClassMethod(AI, SubTypeValue);
+      auto NewInstPair = tryDevirtualizeClassMethod(AI, SubTypeValue, &ORE);
       if (NewInstPair.first)
         replaceDeadApply(AI, NewInstPair.first);
       return NewInstPair.second.getInstruction() != nullptr;
@@ -481,6 +483,7 @@
     Changed = true;
   }
 
+  using namespace OptRemark;
   // Check if there is only a single statically known implementation
   // of the method which can be called by the default case handler.
   if (NotHandledSubsNum || !isDefaultCaseKnown(CHA, AI, CD, Subs)) {
@@ -489,9 +492,28 @@
     // needs to be handled here. Thus, an indirect call through
     // the class_method cannot be eliminated completely.
     //
+    if (Changed)
+      ORE.emit([&]() {
+        RemarkPassed R("PartialSpecDevirt", *AI.getInstruction());
+        R << "Partially devirtualized call with run-time checks for "
+          << NV("NumSubTypesChecked", Subs.size()) << " subclasses of "
+          << NV("ClassType", &ClassType);
+        if (NotHandledSubsNum)
+          R << ", number of subclasses not devirtualized: "
+            << NV("NotHandledSubsNum", NotHandledSubsNum);
+        if (!isDefaultCaseKnown(CHA, AI, CD, Subs))
+          R << ", not all subclasses are known";
+        return R;
+      });
     return Changed;
   }
 
+  auto RB = [&]() {
+    return RemarkPassed("SpecDevirt", *AI.getInstruction())
+           << "Devirtualized call with run-time checks for the derived classes "
+              "of " << NV("ClassType", &ClassType);
+  };
+
   // At this point it is known that there is only one remaining method
   // implementation which is not covered by checked_cast_br checks yet.
   // So, it is safe to replace a class_method invocation by
@@ -504,13 +526,18 @@
                                                 LastCCBI->getCastType());
     B.createBranch(LastCCBI->getLoc(), LastCCBI->getSuccessBB(), {CastedValue});
     LastCCBI->eraseFromParent();
+    ORE.emit(RB);
     return true;
   }
-  auto NewInstPair = tryDevirtualizeClassMethod(AI, SubTypeValue);
+  auto NewInstPair = tryDevirtualizeClassMethod(AI, SubTypeValue, nullptr);
   if (NewInstPair.first) {
+    ORE.emit(RB);
     replaceDeadApply(AI, NewInstPair.first);
     return true;
   }
+
+  if (Changed)
+    ORE.emit(RB);
   return Changed;
 }
 
@@ -546,9 +573,10 @@
         }
       }
 
+      OptRemark::Emitter ORE(DEBUG_TYPE, CurFn.getModule());
       // Go over the collected calls and try to insert speculative calls.
       for (auto AI : ToSpecialize)
-        Changed |= tryToSpeculateTarget(AI, CHA);
+        Changed |= tryToSpeculateTarget(AI, CHA, ORE);
 
       if (Changed) {
         invalidateAnalysis(SILAnalysis::InvalidationKind::FunctionBody);
diff --git a/lib/SILOptimizer/Utils/Devirtualize.cpp b/lib/SILOptimizer/Utils/Devirtualize.cpp
index 55b41ff..427a00e 100644
--- a/lib/SILOptimizer/Utils/Devirtualize.cpp
+++ b/lib/SILOptimizer/Utils/Devirtualize.cpp
@@ -18,6 +18,7 @@
 #include "swift/AST/ProtocolConformance.h"
 #include "swift/AST/SubstitutionMap.h"
 #include "swift/AST/Types.h"
+#include "swift/SIL/OptimizationRemark.h"
 #include "swift/SIL/SILDeclRef.h"
 #include "swift/SIL/SILFunction.h"
 #include "swift/SIL/SILInstruction.h"
@@ -494,7 +495,8 @@
 ///    devirtualizing for.
 /// return true if it is possible to devirtualize, false - otherwise.
 bool swift::canDevirtualizeClassMethod(FullApplySite AI,
-                                       SILType ClassOrMetatypeType) {
+                                       SILType ClassOrMetatypeType,
+                                       OptRemark::Emitter *ORE) {
 
   DEBUG(llvm::dbgs() << "    Trying to devirtualize : " << *AI.getInstruction());
 
@@ -545,7 +547,8 @@
 ///    self argument of the apply we will devirtualize.
 /// return the result value of the new ApplyInst if created one or null.
 DevirtualizationResult swift::devirtualizeClassMethod(FullApplySite AI,
-                                                     SILValue ClassOrMetatype) {
+                                                      SILValue ClassOrMetatype,
+                                                      OptRemark::Emitter *ORE) {
   DEBUG(llvm::dbgs() << "    Trying to devirtualize : " << *AI.getInstruction());
 
   SILModule &Mod = AI.getModule();
@@ -669,6 +672,12 @@
                                              ResultTy, AI.getType());
 
   DEBUG(llvm::dbgs() << "        SUCCESS: " << F->getName() << "\n");
+  if (ORE)
+    ORE->emit([&]() {
+        using namespace OptRemark;
+        return RemarkPassed("ClassMethodDevirtualized", *AI.getInstruction())
+               << "Devirtualized call to class method " << NV("Method", F);
+      });
   NumClassDevirt++;
 
   if (NormalBB) {
@@ -693,10 +702,11 @@
 }
 
 DevirtualizationResult swift::tryDevirtualizeClassMethod(FullApplySite AI,
-                                                   SILValue ClassInstance) {
-  if (!canDevirtualizeClassMethod(AI, ClassInstance->getType()))
+                                                         SILValue ClassInstance,
+                                                         OptRemark::Emitter *ORE) {
+  if (!canDevirtualizeClassMethod(AI, ClassInstance->getType(), ORE))
     return std::make_pair(nullptr, FullApplySite());
-  return devirtualizeClassMethod(AI, ClassInstance);
+  return devirtualizeClassMethod(AI, ClassInstance, ORE);
 }
 
 
@@ -841,7 +851,7 @@
 /// up calling.
 static DevirtualizationResult
 devirtualizeWitnessMethod(ApplySite AI, SILFunction *F,
-                          ProtocolConformanceRef C) {
+                          ProtocolConformanceRef C, OptRemark::Emitter *ORE) {
   // We know the witness thunk and the corresponding set of substitutions
   // required to invoke the protocol method at this point.
   auto &Module = AI.getModule();
@@ -912,6 +922,12 @@
     SAI = NewPAI;
   }
 
+  if (ORE)
+    ORE->emit([&]() {
+        using namespace OptRemark;
+        return RemarkPassed("WitnessMethodDevirtualized", *AI.getInstruction())
+               << "Devirtualized call to " << NV("Method", F);
+      });
   NumWitnessDevirt++;
   return std::make_pair(ResultValue, SAI);
 }
@@ -942,7 +958,8 @@
 /// In the cases where we can statically determine the function that
 /// we'll call to, replace an apply of a witness_method with an apply
 /// of a function_ref, returning the new apply.
-DevirtualizationResult swift::tryDevirtualizeWitnessMethod(ApplySite AI) {
+DevirtualizationResult
+swift::tryDevirtualizeWitnessMethod(ApplySite AI, OptRemark::Emitter *ORE) {
   if (!canDevirtualizeWitnessMethod(AI))
     return std::make_pair(nullptr, FullApplySite());
 
@@ -955,7 +972,7 @@
     AI.getModule().lookUpFunctionInWitnessTable(WMI->getConformance(),
                                                 WMI->getMember());
 
-  return devirtualizeWitnessMethod(AI, F, WMI->getConformance());
+  return devirtualizeWitnessMethod(AI, F, WMI->getConformance(), ORE);
 }
 
 //===----------------------------------------------------------------------===//
@@ -964,8 +981,9 @@
 
 /// Attempt to devirtualize the given apply if possible, and return a
 /// new instruction in that case, or nullptr otherwise.
-DevirtualizationResult
-swift::tryDevirtualizeApply(ApplySite AI, ClassHierarchyAnalysis *CHA) {
+DevirtualizationResult swift::tryDevirtualizeApply(ApplySite AI,
+                                                   ClassHierarchyAnalysis *CHA,
+                                                   OptRemark::Emitter *ORE) {
   DEBUG(llvm::dbgs() << "    Trying to devirtualize: " << *AI.getInstruction());
 
   // Devirtualize apply instructions that call witness_method instructions:
@@ -974,7 +992,7 @@
   //   %9 = apply %8<Self = CodeUnit?>(%6#1) : ...
   //
   if (isa<WitnessMethodInst>(AI.getCallee()))
-    return tryDevirtualizeWitnessMethod(AI);
+    return tryDevirtualizeWitnessMethod(AI, ORE);
 
   // TODO: check if we can also de-virtualize partial applies of class methods.
   FullApplySite FAS = FullApplySite::isa(AI.getInstruction());
@@ -1007,30 +1025,30 @@
     auto *CD = ClassType.getClassOrBoundGenericClass();
 
     if (isEffectivelyFinalMethod(FAS, ClassType, CD, CHA))
-      return tryDevirtualizeClassMethod(FAS, Instance);
+      return tryDevirtualizeClassMethod(FAS, Instance, ORE);
 
     // Try to check if the exact dynamic type of the instance is statically
     // known.
     if (auto Instance = getInstanceWithExactDynamicType(CMI->getOperand(),
                                                         CMI->getModule(),
                                                         CHA))
-      return tryDevirtualizeClassMethod(FAS, Instance);
+      return tryDevirtualizeClassMethod(FAS, Instance, ORE);
 
     if (auto ExactTy = getExactDynamicType(CMI->getOperand(), CMI->getModule(),
                                            CHA)) {
       if (ExactTy == CMI->getOperand()->getType())
-        return tryDevirtualizeClassMethod(FAS, CMI->getOperand());
+        return tryDevirtualizeClassMethod(FAS, CMI->getOperand(), ORE);
     }
   }
 
   if (isa<SuperMethodInst>(FAS.getCallee())) {
     if (FAS.hasSelfArgument()) {
-      return tryDevirtualizeClassMethod(FAS, FAS.getSelfArgument());
+      return tryDevirtualizeClassMethod(FAS, FAS.getSelfArgument(), ORE);
     }
 
     // It is an invocation of a class method.
     // Last operand is the metatype that should be used for dispatching.
-    return tryDevirtualizeClassMethod(FAS, FAS.getArguments().back());
+    return tryDevirtualizeClassMethod(FAS, FAS.getArguments().back(), ORE);
   }
 
   return std::make_pair(nullptr, ApplySite());
diff --git a/lib/SILOptimizer/Utils/Generics.cpp b/lib/SILOptimizer/Utils/Generics.cpp
index e7bf2a8..6389488 100644
--- a/lib/SILOptimizer/Utils/Generics.cpp
+++ b/lib/SILOptimizer/Utils/Generics.cpp
@@ -245,9 +245,6 @@
   for (unsigned idx = 0, e = Subs1.size(); idx < e; ++idx) {
     auto Type1 = Subs1[idx].getReplacement()->getCanonicalType();
     auto Type2 = Subs2[idx].getReplacement()->getCanonicalType();
-    // Replacement types should be concrete.
-    assert(!Type1->hasArchetype());
-    assert(!Type2->hasArchetype());
     // If types are the same, the substitution type does not grow.
     if (TypeCmp.isEqual(Type2, Type1))
       continue;
diff --git a/lib/SILOptimizer/Utils/Local.cpp b/lib/SILOptimizer/Utils/Local.cpp
index 4fceeb1..9469e5d 100644
--- a/lib/SILOptimizer/Utils/Local.cpp
+++ b/lib/SILOptimizer/Utils/Local.cpp
@@ -1571,6 +1571,40 @@
   return (NewI) ? NewI : AI;
 }
 
+static bool canOptimizeCast(const swift::Type &BridgedTargetTy,
+                            swift::SILModule &M,
+                            swift::SILFunctionConventions &substConv) {
+  // DestTy is the type which we want to convert to
+  SILType DestTy =
+      SILType::getPrimitiveObjectType(BridgedTargetTy->getCanonicalType());
+  // ConvTy  is the return type of the _bridgeToObjectiveCImpl()
+  auto ConvTy = substConv.getSILResultType().getObjectType();
+  if (ConvTy == DestTy) {
+    // Destination is the same type
+    return true;
+  }
+  // Check if a superclass/subclass of the source operand
+  if (DestTy.isExactSuperclassOf(ConvTy)) {
+    return true;
+  }
+  if (ConvTy.isExactSuperclassOf(DestTy)) {
+    return true;
+  }
+  // check if it is a bridgeable CF type
+  if (ConvTy.getSwiftRValueType() ==
+      getNSBridgedClassOfCFClass(M.getSwiftModule(),
+                                 DestTy.getSwiftRValueType())) {
+    return true;
+  }
+  if (DestTy.getSwiftRValueType() ==
+      getNSBridgedClassOfCFClass(M.getSwiftModule(),
+                                 ConvTy.getSwiftRValueType())) {
+    return true;
+  }
+  // All else failed - can't optimize this case
+  return false;
+}
+
 /// Create a call of _bridgeToObjectiveC which converts an _ObjectiveCBridgeable
 /// instance into a bridged ObjC type.
 SILInstruction *
@@ -1646,7 +1680,8 @@
   if (ResultsRef.size() != 1)
     return nullptr;
 
-  auto MemberDeclRef = SILDeclRef(Results.front());
+  auto *resultDecl = Results.front();
+  auto MemberDeclRef = SILDeclRef(resultDecl);
   auto *BridgedFunc = M.getOrCreateFunction(Loc, MemberDeclRef,
                                             ForDefinition_t::NotForDefinition);
 
@@ -1677,6 +1712,11 @@
   SILType SubstFnTy = SILFnTy.substGenericArgs(M, SubMap);
   SILFunctionConventions substConv(SubstFnTy.castTo<SILFunctionType>(), M);
 
+  // check that we can go through with the optimization
+  if (!canOptimizeCast(BridgedTargetTy, M, substConv)) {
+    return nullptr;
+  }
+
   auto FnRef = Builder.createFunctionRef(Loc, BridgedFunc);
   if (Src->getType().isAddress() && !substConv.isSILIndirect(ParamTypes[0])) {
     // Create load
@@ -1811,6 +1851,9 @@
     // If it is addr cast then store the result.
     auto ConvTy = NewAI->getType();
     auto DestTy = Dest->getType().getObjectType();
+    assert(DestTy == SILType::getPrimitiveObjectType(
+                         BridgedTargetTy->getCanonicalType()) &&
+           "Expected Dest Type to be the same as BridgedTargetTy");
     SILValue CastedValue;
     if (ConvTy == DestTy) {
       CastedValue = NewAI;
@@ -1842,9 +1885,11 @@
       CastedValue =
           SILValue(Builder.createUncheckedRefCast(Loc, NewAI, DestTy));
     } else {
-      llvm_unreachable(
-          "Destination should have the same type, be bridgeable CF "
-          "type or be a superclass/subclass of the source operand");
+      llvm_unreachable("optimizeBridgedSwiftToObjCCast: should never reach "
+                       "this condition: if the Destination does not have the "
+                       "same type, is not a bridgeable CF type and isn't a "
+                       "superclass/subclass of the source operand we should "
+                       "have bailed earlier");
     }
     NewI = Builder.createStore(Loc, CastedValue, Dest,
                                StoreOwnershipQualifier::Unqualified);
diff --git a/lib/Sema/CSApply.cpp b/lib/Sema/CSApply.cpp
index ac9a650..2c4d895 100644
--- a/lib/Sema/CSApply.cpp
+++ b/lib/Sema/CSApply.cpp
@@ -503,8 +503,7 @@
     /// \brief Coerce an expression of implicitly unwrapped optional type to its
     /// underlying value type, in the correct way for an implicit
     /// look-through.
-    Expr *coerceImplicitlyUnwrappedOptionalToValue(Expr *expr, Type objTy,
-                                         ConstraintLocatorBuilder locator);
+    Expr *coerceImplicitlyUnwrappedOptionalToValue(Expr *expr, Type objTy);
 
     /// \brief Build a collection upcast expression.
     ///
@@ -893,7 +892,7 @@
       // through ImplicitlyUnwrappedOptional<T>.
       if (!Implicit) {
         if (auto objTy = cs.lookThroughImplicitlyUnwrappedOptionalType(baseTy)) {
-          base = coerceImplicitlyUnwrappedOptionalToValue(base, objTy, locator);
+          base = coerceImplicitlyUnwrappedOptionalToValue(base, objTy);
           baseTy = objTy;
         }
       }
@@ -921,12 +920,7 @@
           memberLocator, substitutions);
       auto memberRef = ConcreteDeclRef(context, member, substitutions);
 
-      // Class members might be virtually dispatched, so we need to know
-      // the full layout of the class.
-      if (auto *classDecl = dyn_cast<ClassDecl>(member->getDeclContext()))
-        tc.requestNominalLayout(classDecl);
-      if (auto *protocolDecl = dyn_cast<ProtocolDecl>(member->getDeclContext()))
-        tc.requestNominalLayout(protocolDecl);
+      cs.TC.requestMemberLayout(member);
 
       auto refTy = solution.simplifyType(openedFullType);
 
@@ -1410,7 +1404,7 @@
         if (auto pathTy = cs.lookThroughImplicitlyUnwrappedOptionalType(keyPathExprTy)) {
           keyPathExprTy = pathTy;
           indexKP = coerceImplicitlyUnwrappedOptionalToValue(
-            indexKP, keyPathExprTy, locator);
+            indexKP, keyPathExprTy);
         }
 
         Type valueTy;
@@ -1495,7 +1489,7 @@
 
       // Handle accesses that implicitly look through ImplicitlyUnwrappedOptional<T>.
       if (auto objTy = cs.lookThroughImplicitlyUnwrappedOptionalType(baseTy)) {
-        base = coerceImplicitlyUnwrappedOptionalToValue(base, objTy, locator);
+        base = coerceImplicitlyUnwrappedOptionalToValue(base, objTy);
         baseTy = cs.getType(base);
       }
 
@@ -2654,8 +2648,7 @@
         // Look through an implicitly unwrapped optional.
         auto baseTy = cs.getType(base);
         if (auto objTy = cs.lookThroughImplicitlyUnwrappedOptionalType(baseTy)){
-          base = coerceImplicitlyUnwrappedOptionalToValue(base, objTy,
-                                         cs.getConstraintLocator(base));
+          base = coerceImplicitlyUnwrappedOptionalToValue(base, objTy);
           baseTy = objTy;
         }
 
@@ -2703,8 +2696,7 @@
       case OverloadChoiceKind::TupleIndex: {
         auto baseTy = cs.getType(base)->getRValueType();
         if (auto objTy = cs.lookThroughImplicitlyUnwrappedOptionalType(baseTy)){
-          base = coerceImplicitlyUnwrappedOptionalToValue(base, objTy,
-                                         cs.getConstraintLocator(base));
+          base = coerceImplicitlyUnwrappedOptionalToValue(base, objTy);
         }
 
         Type toType = simplifyType(cs.getType(expr));
@@ -2960,8 +2952,7 @@
       auto base = expr->getBase();
       auto baseTy = cs.getType(base)->getRValueType();
       if (auto objTy = cs.lookThroughImplicitlyUnwrappedOptionalType(baseTy)) {
-        base = coerceImplicitlyUnwrappedOptionalToValue(base, objTy,
-                                              cs.getConstraintLocator(base));
+        base = coerceImplicitlyUnwrappedOptionalToValue(base, objTy);
         expr->setBase(base);
       }
 
@@ -4129,8 +4120,11 @@
             resolvedComponents.push_back(
                  KeyPathExpr::Component::forOptionalForce(baseTy, SourceLoc()));
           }
-          
+
+          cs.TC.requestMemberLayout(property);
+
           auto dc = property->getInnermostDeclContext();
+
           SmallVector<Substitution, 4> subs;
           if (auto sig = dc->getGenericSignatureOfContext()) {
             // Compute substitutions to refer to the member.
@@ -4174,7 +4168,9 @@
             resolvedComponents.push_back(
                  KeyPathExpr::Component::forOptionalForce(baseTy, SourceLoc()));
           }
-          
+
+          cs.TC.requestMemberLayout(subscript);
+
           auto dc = subscript->getInnermostDeclContext();
           SmallVector<Substitution, 4> subs;
           SubstitutionMap subMap;
@@ -4739,7 +4735,7 @@
     break;
 
   case DefaultArgumentKind::EmptyDictionary:
-    init = DictionaryExpr::create(tc.Context, loc, {}, loc);
+    init = DictionaryExpr::create(tc.Context, loc, {}, {}, loc);
     init->setImplicit();
     break;
   }
@@ -4979,16 +4975,14 @@
   }
   
   // Create the tuple shuffle.
-  ArrayRef<int> mapping = tc.Context.AllocateCopy(sources);
-  auto callerDefaultArgsCopy = tc.Context.AllocateCopy(callerDefaultArgs);
   return
-    cs.cacheType(new (tc.Context) TupleShuffleExpr(
-                     expr, mapping,
+    cs.cacheType(TupleShuffleExpr::create(tc.Context,
+                     expr, sources,
                      TupleShuffleExpr::TupleToTuple,
                      callee,
-                     tc.Context.AllocateCopy(variadicArgs),
+                     variadicArgs,
                      arrayType,
-                     callerDefaultArgsCopy,
+                     callerDefaultArgs,
                      toSugarType));
 }
 
@@ -5077,13 +5071,13 @@
   Type destSugarTy = hasInit? toTuple
                             : TupleType::get(sugarFields, tc.Context);
                             
-  return cs.cacheType(new (tc.Context) TupleShuffleExpr(expr,
-                                        tc.Context.AllocateCopy(elements),
+  return cs.cacheType(TupleShuffleExpr::create(tc.Context, expr,
+                                        elements,
                                         TupleShuffleExpr::ScalarToTuple,
                                         callee,
-                                        tc.Context.AllocateCopy(variadicArgs),
+                                        variadicArgs,
                                         arrayType,
-                                     tc.Context.AllocateCopy(callerDefaultArgs),
+                                        callerDefaultArgs,
                                         destSugarTy));
 }
 
@@ -5191,7 +5185,7 @@
     // FIXME: Hack. We shouldn't try to coerce existential when there is no
     // existential upcast to perform.
     if (ty->isEqual(toType)) {
-      return coerceImplicitlyUnwrappedOptionalToValue(expr, ty, locator);
+      return coerceImplicitlyUnwrappedOptionalToValue(expr, ty);
     }
   }
 
@@ -5219,8 +5213,8 @@
           new (ctx) OpaqueValueExpr(expr->getLoc(),
                                     fromType));
     
-    auto *result =
-      cs.cacheType(new (ctx) ErasureExpr(archetypeVal, toType, conformances));
+    auto *result = cs.cacheType(ErasureExpr::create(ctx, archetypeVal, toType,
+                                                    conformances));
     return cs.cacheType(
         new (ctx) OpenExistentialExpr(expr, archetypeVal, result,
                                       cs.getType(result)));
@@ -5242,7 +5236,7 @@
     }
   }
 
-  return cs.cacheType(new (ctx) ErasureExpr(expr, toType, conformances));
+  return cs.cacheType(ErasureExpr::create(ctx, expr, toType, conformances));
 }
 
 /// Given that the given expression is an implicit conversion added
@@ -5337,8 +5331,7 @@
   return expr;
 }
 
-Expr *ExprRewriter::coerceImplicitlyUnwrappedOptionalToValue(Expr *expr, Type objTy,
-                                            ConstraintLocatorBuilder locator) {
+Expr *ExprRewriter::coerceImplicitlyUnwrappedOptionalToValue(Expr *expr, Type objTy) {
   auto optTy = cs.getType(expr);
   // Coerce to an r-value.
   if (optTy->is<LValueType>())
@@ -5709,17 +5702,10 @@
   }
 
   // Create the tuple shuffle.
-  ArrayRef<int> mapping = tc.Context.AllocateCopy(sources);
-  auto callerDefaultArgsCopy = tc.Context.AllocateCopy(callerDefaultArgs);
-  return
-    cs.cacheType(new (tc.Context) TupleShuffleExpr(
-                     arg, mapping,
-                     typeImpact,
-                     callee,
-                     tc.Context.AllocateCopy(variadicArgs),
-                     sliceType,
-                     callerDefaultArgsCopy,
-                     paramType));
+  return cs.cacheType(TupleShuffleExpr::create(tc.Context, arg, sources,
+                                               typeImpact, callee, variadicArgs,
+                                               sliceType, callerDefaultArgs,
+                                               paramType));
 }
 
 static ClosureExpr *getClosureLiteralExpr(Expr *expr) {
@@ -6172,14 +6158,14 @@
     case ConversionRestrictionKind::ForceUnchecked: {
       auto valueTy = fromType->getImplicitlyUnwrappedOptionalObjectType();
       assert(valueTy);
-      expr = coerceImplicitlyUnwrappedOptionalToValue(expr, valueTy, locator);
+      expr = coerceImplicitlyUnwrappedOptionalToValue(expr, valueTy);
       return coerceToType(expr, toType, locator);
     }
 
     case ConversionRestrictionKind::ArrayUpcast: {
       // Look through implicitly unwrapped optionals.
       if (auto objTy= cs.lookThroughImplicitlyUnwrappedOptionalType(fromType)) {
-        expr = coerceImplicitlyUnwrappedOptionalToValue(expr, objTy, locator);
+        expr = coerceImplicitlyUnwrappedOptionalToValue(expr, objTy);
       }
 
       // Build the value conversion.
@@ -6191,7 +6177,7 @@
       // Look through implicitly unwrapped optionals.
       if (auto objTy
           = cs.lookThroughImplicitlyUnwrappedOptionalType(cs.getType(expr))) {
-        expr = coerceImplicitlyUnwrappedOptionalToValue(expr, objTy, locator);
+        expr = coerceImplicitlyUnwrappedOptionalToValue(expr, objTy);
       }
 
       // We want to check conformance on the rvalue, as that's what has
@@ -6215,7 +6201,7 @@
       // Look through implicitly unwrapped optionals.
       if (auto objTy
           = cs.lookThroughImplicitlyUnwrappedOptionalType(cs.getType(expr))) {
-        expr = coerceImplicitlyUnwrappedOptionalToValue(expr, objTy, locator);
+        expr = coerceImplicitlyUnwrappedOptionalToValue(expr, objTy);
       }
 
       // Build the value conversion.
@@ -6227,7 +6213,7 @@
       // Look through implicitly unwrapped optionals.
       if (auto objTy
           = cs.lookThroughImplicitlyUnwrappedOptionalType(cs.getType(expr))) {
-        expr = coerceImplicitlyUnwrappedOptionalToValue(expr, objTy, locator);
+        expr = coerceImplicitlyUnwrappedOptionalToValue(expr, objTy);
       }
 
       // Build the value conversion.
@@ -6496,7 +6482,7 @@
 
   // Look through ImplicitlyUnwrappedOptional<T> before coercing expression.
   if (auto ty = cs.lookThroughImplicitlyUnwrappedOptionalType(fromType)) {
-    expr = coerceImplicitlyUnwrappedOptionalToValue(expr, ty, locator);
+    expr = coerceImplicitlyUnwrappedOptionalToValue(expr, ty);
     return coerceToType(expr, toType, locator);
   }
 
@@ -7053,7 +7039,7 @@
   
   // Handle applications that look through ImplicitlyUnwrappedOptional<T>.
   if (auto fnTy = cs.lookThroughImplicitlyUnwrappedOptionalType(cs.getType(fn)))
-    fn = coerceImplicitlyUnwrappedOptionalToValue(fn, fnTy, locator);
+    fn = coerceImplicitlyUnwrappedOptionalToValue(fn, fnTy);
 
   // If we're applying a function that resulted from a covariant
   // function conversion, strip off that conversion.
diff --git a/lib/Sema/CSDiag.cpp b/lib/Sema/CSDiag.cpp
index 3c6a830..e10ec37 100644
--- a/lib/Sema/CSDiag.cpp
+++ b/lib/Sema/CSDiag.cpp
@@ -6968,108 +6968,86 @@
   return diagnoseKeyPathComponents(CS, KPE, rootType);
 }
 
-static bool isDictionaryLiteralCompatible(Type ty, ConstraintSystem &CS,
-                                          SourceLoc loc) {
-  auto DLC =
-      CS.TC.getProtocol(loc, KnownProtocolKind::ExpressibleByDictionaryLiteral);
-  if (!DLC) return false;
-  return CS.TC
-      .conformsToProtocol(ty, DLC, CS.DC, ConformanceCheckFlags::InExpression)
-      .hasValue();
-}
-
 bool FailureDiagnosis::visitArrayExpr(ArrayExpr *E) {
-  Type contextualElementType;
-  auto elementTypePurpose = CTP_Unused;
-
   // If we had a contextual type, then it either conforms to
   // ExpressibleByArrayLiteral or it is an invalid contextual type.
-  if (auto contextualType = CS.getContextualType()) {
-    // If our contextual type is an optional, look through them, because we're
-    // surely initializing whatever is inside.
-    contextualType = contextualType->lookThroughAllAnyOptionalTypes();
+  auto contextualType = CS.getContextualType();
+  if (!contextualType) {
+    return false;
+  }
 
-    // Validate that the contextual type conforms to ExpressibleByArrayLiteral and
-    // figure out what the contextual element type is in place.
-    auto ALC = CS.TC.getProtocol(E->getLoc(),
-                                 KnownProtocolKind::ExpressibleByArrayLiteral);
-    if (!ALC)
-      return visitExpr(E);
+  // If our contextual type is an optional, look through them, because we're
+  // surely initializing whatever is inside.
+  contextualType = contextualType->lookThroughAllAnyOptionalTypes();
 
-    // Check to see if the contextual type conforms.
-    auto Conformance = CS.TC.conformsToProtocol(
-        contextualType, ALC, CS.DC, ConformanceCheckFlags::InExpression);
+  // Validate that the contextual type conforms to ExpressibleByArrayLiteral and
+  // figure out what the contextual element type is in place.
+  auto ALC = CS.TC.getProtocol(E->getLoc(),
+                               KnownProtocolKind::ExpressibleByArrayLiteral);
+  if (!ALC)
+    return visitExpr(E);
 
-    // If not, we may have an implicit conversion going on.  If the contextual
-    // type is an UnsafePointer or UnsafeMutablePointer, then that is probably
-    // what is happening.
-    if (!Conformance) {
-      // TODO: Not handling various string conversions or void conversions.
-      Type unwrappedTy = contextualType;
-      if (Type unwrapped = contextualType->getAnyOptionalObjectType())
-        unwrappedTy = unwrapped;
-      PointerTypeKind pointerKind;
-      if (Type pointeeTy = unwrappedTy->getAnyPointerElementType(pointerKind)) {
-        if (pointerKind == PTK_UnsafePointer) {
-          auto arrayTy = ArraySliceType::get(pointeeTy);
-          Conformance = CS.TC.conformsToProtocol(
-              arrayTy, ALC, CS.DC, ConformanceCheckFlags::InExpression);
-
-          if (Conformance)
-            contextualType = arrayTy;
-        }
-      }
-    }
-
-    auto numElements = E->getNumElements();
-    if (!Conformance) {
-      // If the contextual type conforms to ExpressibleByDictionaryLiteral and
-      // this is an empty array, then they meant "[:]".
-      if (numElements == 0 &&
-          isDictionaryLiteralCompatible(contextualType, CS, E->getLoc())) {
-        diagnose(E->getStartLoc(), diag::should_use_empty_dictionary_literal)
-          .fixItInsert(E->getEndLoc(), ":");
-        return true;
-      }
-
-
-      diagnose(E->getStartLoc(), diag::type_is_not_array, contextualType)
-        .highlight(E->getSourceRange());
-
-      // If the contextual type conforms to ExpressibleByDictionaryLiteral, then
-      // they wrote "x = [1,2]" but probably meant "x = [1:2]".
-      if ((numElements & 1) == 0 && numElements > 0 &&
-          isDictionaryLiteralCompatible(contextualType, CS, E->getLoc())) {
-        auto diag = diagnose(E->getStartLoc(), diag::meant_dictionary_lit);
-
-        // Change every other comma into a colon, only if the number
-        // of commas present matches the number of elements, because
-        // otherwise it might a structural problem with the expression
-        // e.g. ["a""b": 1].
-        const auto commaLocs = E->getCommaLocs();
-        if (commaLocs.size() == numElements - 1) {
-          for (unsigned i = 0, e = numElements / 2; i != e; ++i)
-            diag.fixItReplace(commaLocs[i*2], ":");
-        }
-      }
-
-      return true;
-    }
-
-    contextualElementType =
+  // Check to see if the contextual type conforms.
+  if (auto Conformance
+        = CS.TC.conformsToProtocol(contextualType, ALC, CS.DC,
+                                   ConformanceCheckFlags::InExpression)) {
+    Type contextualElementType =
         ProtocolConformanceRef::getTypeWitnessByName(
             contextualType, *Conformance,
             CS.getASTContext().Id_ArrayLiteralElement, &CS.TC)
             ->getDesugaredType();
-    elementTypePurpose = CTP_ArrayElement;
+
+    // Type check each of the subexpressions in place, passing down the contextual
+    // type information if we have it.
+    for (auto elt : E->getElements()) {
+      if (typeCheckChildIndependently(elt, contextualElementType,
+                                      CTP_ArrayElement) == nullptr) {
+        return true;
+      }
+    }
+
+    return false;
   }
 
-  // Type check each of the subexpressions in place, passing down the contextual
-  // type information if we have it.
-  for (auto elt : E->getElements()) {
-    if (typeCheckChildIndependently(elt, contextualElementType,
-                                    elementTypePurpose) == nullptr)
+  auto DLC
+    = CS.TC.getProtocol(E->getLoc(),
+                        KnownProtocolKind::ExpressibleByDictionaryLiteral);
+  if (!DLC)
+    return visitExpr(E);
+
+  if (auto Conformance
+        = CS.TC.conformsToProtocol(contextualType, DLC, CS.DC,
+                                   ConformanceCheckFlags::InExpression)) {
+    // If the contextual type conforms to ExpressibleByDictionaryLiteral and
+    // this is an empty array, then they meant "[:]".
+    auto numElements = E->getNumElements();
+    if (numElements == 0) {
+      diagnose(E->getStartLoc(), diag::should_use_empty_dictionary_literal)
+      .fixItInsert(E->getEndLoc(), ":");
       return true;
+    }
+
+    // If the contextual type conforms to ExpressibleByDictionaryLiteral, then
+    // they wrote "x = [1,2]" but probably meant "x = [1:2]".
+    if ((numElements & 1) == 0 && numElements > 0) {
+      bool isIniting = CS.getContextualTypePurpose() == CTP_Initialization;
+      diagnose(E->getStartLoc(), diag::should_use_dictionary_literal,
+               contextualType, isIniting);
+      auto diag = diagnose(E->getStartLoc(), diag::meant_dictionary_lit);
+
+      // Change every other comma into a colon, only if the number
+      // of commas present matches the number of elements, because
+      // otherwise it might a structural problem with the expression
+      // e.g. ["a""b": 1].
+      const auto commaLocs = E->getCommaLocs();
+      if (commaLocs.size() == numElements - 1) {
+        for (unsigned i = 0, e = numElements / 2; i != e; ++i)
+          diag.fixItReplace(commaLocs[i*2], ":");
+      }
+      return true;
+    }
+
+    return false;
   }
 
   // If that didn't turn up an issue, then we don't know what to do.
@@ -7276,7 +7254,7 @@
     case CC_SelfMismatch:         // Self argument mismatches.
     case CC_ArgumentNearMismatch: // Argument list mismatch.
     case CC_ArgumentMismatch:     // Argument list mismatch.
-      assert(0 && "These aren't produced by filterContextualMemberList");
+      llvm_unreachable("These aren't produced by filterContextualMemberList");
       return false;
 
     case CC_ExactMatch: { // This is a perfect match for the arguments.
diff --git a/lib/Sema/CSGen.cpp b/lib/Sema/CSGen.cpp
index 7f3e83b..871f717 100644
--- a/lib/Sema/CSGen.cpp
+++ b/lib/Sema/CSGen.cpp
@@ -2512,7 +2512,7 @@
       expr->getCastTypeLoc().setType(toType, /*validated=*/true);
 
       auto fromType = CS.getType(fromExpr);
-      auto locator = CS.getConstraintLocator(fromExpr);
+      auto locator = CS.getConstraintLocator(expr);
 
       // The source type can be checked-cast to the destination type.
       CS.addConstraint(ConstraintKind::CheckedCast, fromType, toType, locator);
@@ -2560,7 +2560,7 @@
       expr->getCastTypeLoc().setType(toType, /*validated=*/true);
 
       auto fromType = CS.getType(fromExpr);
-      auto locator = CS.getConstraintLocator(fromExpr);
+      auto locator = CS.getConstraintLocator(expr);
       CS.addConstraint(ConstraintKind::CheckedCast, fromType, toType, locator);
       return OptionalType::get(toType);
     }
@@ -3452,14 +3452,15 @@
 
 bool swift::isExtensionApplied(DeclContext &DC, Type BaseTy,
                                const ExtensionDecl *ED) {
-  ConstraintSystemOptions Options;
-  NominalTypeDecl *Nominal = BaseTy->getNominalOrBoundGenericNominal();
-  if (!Nominal || !BaseTy->isSpecialized() ||
-      ED->getGenericRequirements().empty() ||
+  if (!ED->isConstrainedExtension() ||
       // We'll crash if we leak type variables from one constraint
       // system into the new one created below.
-      BaseTy->hasTypeVariable())
+      BaseTy->hasTypeVariable() ||
+      // We can't do anything if the base type has unbound generic
+      // parameters either.
+      BaseTy->hasUnboundGenericType())
     return true;
+
   std::unique_ptr<TypeChecker> CreatedTC;
   // If the current ast context has no type checker, create one for it.
   auto *TC = static_cast<TypeChecker*>(DC.getASTContext().getLazyResolver());
@@ -3467,11 +3468,10 @@
     CreatedTC.reset(new TypeChecker(DC.getASTContext()));
     TC = CreatedTC.get();
   }
-  if (ED->getAsProtocolExtensionContext())
-    return TC->isProtocolExtensionUsable(&DC, BaseTy, const_cast<ExtensionDecl*>(ED));
+
+  ConstraintSystemOptions Options;
   ConstraintSystem CS(*TC, &DC, Options);
   auto Loc = CS.getConstraintLocator(nullptr);
-  bool Failed = false;
 
   // Prepare type substitution map.
   SubstitutionMap Substitutions = BaseTy->getContextSubstitutionMap(
@@ -3482,11 +3482,9 @@
     if (auto resolved = Req.subst(Substitutions)) {
       CS.addConstraint(*resolved, Loc);
     } else {
-      Failed = true;
+      return false;
     }
   }
-  if (Failed)
-    return true;
 
   // Having a solution implies the extension's requirements have been fulfilled.
   return CS.solveSingle().hasValue();
diff --git a/lib/Sema/CSSimplify.cpp b/lib/Sema/CSSimplify.cpp
index b63727a..6d58ab8 100644
--- a/lib/Sema/CSSimplify.cpp
+++ b/lib/Sema/CSSimplify.cpp
@@ -3121,17 +3121,14 @@
     // the candidate should be favored.
     if (isa<ConstructorDecl>(decl) && favoredType &&
         result.FavoredChoice == ~0U) {
+      auto *ctor = cast<ConstructorDecl>(decl);
+
       // Only try and favor monomorphic initializers.
-      if (auto fnTypeWithSelf = decl->getInterfaceType()
-                                                     ->getAs<FunctionType>()) {
-        if (auto fnType = fnTypeWithSelf->getResult()->getAs<FunctionType>()) {
-          auto argType = fnType->getInput()->getWithoutParens();
-          argType = decl->getInnermostDeclContext()
-                                                  ->mapTypeIntoContext(argType);
-          if (argType->isEqual(favoredType))
-            if (!decl->getAttrs().isUnavailable(getASTContext()))
-              result.FavoredChoice = result.ViableCandidates.size();
-        }
+      if (!ctor->isGenericContext()) {
+        auto argType = ctor->getArgumentInterfaceType();
+        if (argType->isEqual(favoredType))
+          if (!decl->getAttrs().isUnavailable(getASTContext()))
+            result.FavoredChoice = result.ViableCandidates.size();
       }
     }
 
@@ -3183,13 +3180,6 @@
         }
       }
     }
-    
-    // If the result's type contains delayed members, we need to force them now.
-    if (auto NT = dyn_cast<NominalType>(decl->getInterfaceType().getPointer())){
-      if (auto *NTD = dyn_cast<NominalTypeDecl>(NT->getDecl())) {
-        TC.forceExternalDeclMembers(NTD);
-      }
-    }
 
     // Otherwise, we're good, add the candidate to the list.
     result.addViable(candidate);
diff --git a/lib/Sema/CodeSynthesis.cpp b/lib/Sema/CodeSynthesis.cpp
index 3e6715d..3094c26 100644
--- a/lib/Sema/CodeSynthesis.cpp
+++ b/lib/Sema/CodeSynthesis.cpp
@@ -172,6 +172,10 @@
   if (storage->isStatic())
     getter->setStatic();
 
+  if (auto *overridden = storage->getOverriddenDecl())
+    if (auto *overriddenAccessor = overridden->getGetter())
+      getter->setOverriddenDecl(overriddenAccessor);
+
   return getter;
 }
 
@@ -219,6 +223,14 @@
   if (isStatic)
     setter->setStatic();
 
+  if (auto *overridden = storage->getOverriddenDecl()) {
+    auto *overriddenAccessor = overridden->getSetter();
+    if (overriddenAccessor &&
+        overridden->isSetterAccessibleFrom(storage->getDeclContext())) {
+      setter->setOverriddenDecl(overriddenAccessor);
+    }
+  }
+
   return setter;
 }
 
@@ -351,7 +363,15 @@
   // materializeForSet is final if the storage is.
   if (storage->isFinal())
     makeFinal(ctx, materializeForSet);
-  
+
+  if (auto *overridden = storage->getOverriddenDecl()) {
+    auto *overriddenAccessor = overridden->getMaterializeForSetFunc();
+    if (overriddenAccessor && !overriddenAccessor->hasForcedStaticDispatch() &&
+        overridden->isSetterAccessibleFrom(storage->getDeclContext())) {
+      materializeForSet->setOverriddenDecl(overriddenAccessor);
+    }
+  }
+
   // If the storage is dynamic or ObjC-native, we can't add a dynamically-
   // dispatched method entry for materializeForSet, so force it to be
   // statically dispatched. ("final" would be inappropriate because the
@@ -709,11 +729,6 @@
   SourceLoc loc = storage->getLoc();
   getter->setBody(BraceStmt::create(ctx, loc, returnStmt, loc, true));
 
-  // Record the getter as an override, which can happen with addressors.
-  if (auto *baseASD = storage->getOverriddenDecl())
-    if (baseASD->isAccessibleFrom(storage->getDeclContext()))
-      getter->setOverriddenDecl(baseASD->getGetter());
-
   // Register the accessor as an external decl if the storage was imported.
   if (needsToBeRegisteredAsExternalDecl(storage))
     TC.Context.addExternalDecl(getter);
@@ -734,15 +749,6 @@
                                             setterBody, TC);
   setter->setBody(BraceStmt::create(ctx, loc, setterBody, loc, true));
 
-  // Record the setter as an override, which can happen with addressors.
-  if (auto *baseASD = storage->getOverriddenDecl()) {
-    auto *baseSetter = baseASD->getSetter();
-    if (baseSetter != nullptr &&
-        baseASD->isSetterAccessibleFrom(storage->getDeclContext())) {
-      setter->setOverriddenDecl(baseSetter);
-    }
-  }
-
   // Register the accessor as an external decl if the storage was imported.
   if (needsToBeRegisteredAsExternalDecl(storage))
     TC.Context.addExternalDecl(setter);
@@ -848,21 +854,6 @@
                              storage->getSetter());
   storage->setMaterializeForSetFunc(materializeForSet);
 
-  // Make sure we record the override.
-  //
-  // FIXME: Instead, we should just not call checkOverrides() on
-  // storage until all accessors are in place.
-  if (auto *baseASD = storage->getOverriddenDecl()) {
-    // If the base storage has a private setter, we're not overriding
-    // materializeForSet either.
-    auto *baseMFS = baseASD->getMaterializeForSetFunc();
-    if (baseMFS != nullptr &&
-        !baseMFS->hasForcedStaticDispatch() &&
-        baseASD->isSetterAccessibleFrom(storage->getDeclContext())) {
-      materializeForSet->setOverriddenDecl(baseMFS);
-    }
-  }
-
   return materializeForSet;
 }
 
diff --git a/lib/Sema/ConstraintLocator.h b/lib/Sema/ConstraintLocator.h
index b8f3794..23a3bbd 100644
--- a/lib/Sema/ConstraintLocator.h
+++ b/lib/Sema/ConstraintLocator.h
@@ -231,8 +231,6 @@
     llvm_unreachable("Unhandled PathElementKind in switch.");
   }
 
-  template<unsigned N> struct incomplete;
-  
   /// \brief One element in the path of a locator, which can include both
   /// a kind (PathElementKind) and a value used to describe specific
   /// kinds further (e.g., the position of a tuple element).
diff --git a/lib/Sema/ConstraintSystem.h b/lib/Sema/ConstraintSystem.h
index 506a3d3..26e39e7 100644
--- a/lib/Sema/ConstraintSystem.h
+++ b/lib/Sema/ConstraintSystem.h
@@ -177,9 +177,6 @@
 /// to, what specific types it might be and, eventually, the fixed type to
 /// which it is assigned.
 class TypeVariableType::Implementation {
-  /// Type variable options.
-  unsigned Options : 3;
-
   /// \brief The locator that describes where this type variable was generated.
   constraints::ConstraintLocator *locator;
 
@@ -191,37 +188,9 @@
   /// The corresponding node in the constraint graph.
   constraints::ConstraintGraphNode *GraphNode = nullptr;
 
-  ///  Index into the list of type variables, as used by the
-  ///  constraint graph.
-  unsigned GraphIndex;
-
   friend class constraints::SavedTypeVariableBinding;
 
 public:
-  explicit Implementation(constraints::ConstraintLocator *locator,
-                          unsigned options)
-    : Options(options), locator(locator),
-      ParentOrFixed(getTypeVariable()) { }
-
-  /// \brief Retrieve the unique ID corresponding to this type variable.
-  unsigned getID() const { return getTypeVariable()->getID(); }
-
-  /// Whether this type variable can bind to an lvalue type.
-  bool canBindToLValue() const { return Options & TVO_CanBindToLValue; }
-
-  /// Whether this type variable can bind to an inout type.
-  bool canBindToInOut() const { return Options & TVO_CanBindToInOut; }
-
-  /// Whether this type variable prefers a subtype binding over a supertype
-  /// binding.
-  bool prefersSubtypeBinding() const {
-    return Options & TVO_PrefersSubtypeBinding;
-  }
-
-  bool mustBeMaterializable() const {
-    return !(Options & TVO_CanBindToInOut) && !(Options & TVO_CanBindToLValue);
-  }
-
   /// \brief Retrieve the type variable associated with this implementation.
   TypeVariableType *getTypeVariable() {
     return reinterpret_cast<TypeVariableType *>(this) - 1;
@@ -232,6 +201,42 @@
     return reinterpret_cast<const TypeVariableType *>(this) - 1;
   }
 
+  explicit Implementation(constraints::ConstraintLocator *locator,
+                          unsigned options)
+    : locator(locator), ParentOrFixed(getTypeVariable()) {
+    getTypeVariable()->Bits.TypeVariableType.Options = options;
+  }
+
+  /// \brief Retrieve the unique ID corresponding to this type variable.
+  unsigned getID() const { return getTypeVariable()->getID(); }
+
+  unsigned getRawOptions() const {
+    return getTypeVariable()->Bits.TypeVariableType.Options;
+  }
+
+  void setRawOptions(unsigned bits) {
+    getTypeVariable()->Bits.TypeVariableType.Options = bits;
+    assert(getTypeVariable()->Bits.TypeVariableType.Options == bits
+           && "Trucation");
+  }
+
+  /// Whether this type variable can bind to an lvalue type.
+  bool canBindToLValue() const { return getRawOptions() & TVO_CanBindToLValue; }
+
+  /// Whether this type variable can bind to an inout type.
+  bool canBindToInOut() const { return getRawOptions() & TVO_CanBindToInOut; }
+
+  /// Whether this type variable prefers a subtype binding over a supertype
+  /// binding.
+  bool prefersSubtypeBinding() const {
+    return getRawOptions() & TVO_PrefersSubtypeBinding;
+  }
+
+  bool mustBeMaterializable() const {
+    return !(getRawOptions() & TVO_CanBindToInOut) &&
+           !(getRawOptions() & TVO_CanBindToLValue);
+  }
+
   /// Retrieve the corresponding node in the constraint graph.
   constraints::ConstraintGraphNode *getGraphNode() const { return GraphNode; }
 
@@ -243,11 +248,13 @@
   /// Retrieve the index into the constraint graph's list of type variables.
   unsigned getGraphIndex() const { 
     assert(GraphNode && "Graph node isn't set");
-    return GraphIndex; 
+    return getTypeVariable()->Bits.TypeVariableType.GraphIndex; 
   }
 
   /// Set the index into the constraint graph's list of type variables.
-  void setGraphIndex(unsigned newIndex) { GraphIndex = newIndex; }
+  void setGraphIndex(unsigned newIndex) {
+    getTypeVariable()->Bits.TypeVariableType.GraphIndex = newIndex;
+  }
   
   /// \brief Check whether this type variable either has a representative that
   /// is not itself or has a fixed type binding.
@@ -339,8 +346,8 @@
     if (!mustBeMaterializable() && otherRep->getImpl().mustBeMaterializable()) {
       if (record)
         recordBinding(*record);
-      Options &= ~TVO_CanBindToLValue;
-      Options &= ~TVO_CanBindToInOut;
+      getTypeVariable()->Bits.TypeVariableType.Options &= ~TVO_CanBindToLValue;
+      getTypeVariable()->Bits.TypeVariableType.Options &= ~TVO_CanBindToInOut;
     }
   }
 
@@ -381,8 +388,10 @@
     if (!rep->getImpl().mustBeMaterializable()) {
       if (record)
         rep->getImpl().recordBinding(*record);
-      rep->getImpl().Options &= ~TVO_CanBindToLValue;
-      rep->getImpl().Options &= ~TVO_CanBindToInOut;
+      rep->getImpl().getTypeVariable()->Bits.TypeVariableType.Options
+        &= ~TVO_CanBindToLValue;
+      rep->getImpl().getTypeVariable()->Bits.TypeVariableType.Options
+        &= ~TVO_CanBindToInOut;
     }
   }
 
diff --git a/lib/Sema/TypeCheckAttr.cpp b/lib/Sema/TypeCheckAttr.cpp
index eeebf92..0b57a8c 100644
--- a/lib/Sema/TypeCheckAttr.cpp
+++ b/lib/Sema/TypeCheckAttr.cpp
@@ -659,6 +659,7 @@
   // Or within protocols.
   if (isa<ProtocolDecl>(D->getDeclContext())) {
     diagnoseAndRemoveAttr(attr, diag::access_control_in_protocol, attr);
+    TC.diagnose(attr->getLocation(), diag::access_control_in_protocol_detail);
     return true;
   }
 
diff --git a/lib/Sema/TypeCheckConstraints.cpp b/lib/Sema/TypeCheckConstraints.cpp
index ab4641d..170c01d 100644
--- a/lib/Sema/TypeCheckConstraints.cpp
+++ b/lib/Sema/TypeCheckConstraints.cpp
@@ -61,12 +61,12 @@
 }
 
 SavedTypeVariableBinding::SavedTypeVariableBinding(TypeVariableType *typeVar)
-  : TypeVarAndOptions(typeVar, typeVar->getImpl().Options),
+  : TypeVarAndOptions(typeVar, typeVar->getImpl().getRawOptions()),
     ParentOrFixed(typeVar->getImpl().ParentOrFixed) { }
 
 void SavedTypeVariableBinding::restore() {
   auto *typeVar = getTypeVariable();
-  typeVar->getImpl().Options = getOptions();
+  typeVar->getImpl().setRawOptions(getOptions());
   typeVar->getImpl().ParentOrFixed = ParentOrFixed;
 }
 
diff --git a/lib/Sema/TypeCheckDecl.cpp b/lib/Sema/TypeCheckDecl.cpp
index 78c37a2..276ee94 100644
--- a/lib/Sema/TypeCheckDecl.cpp
+++ b/lib/Sema/TypeCheckDecl.cpp
@@ -3969,6 +3969,10 @@
       if (auto nominal = dyn_cast<NominalTypeDecl>(decl)) {
         TC.checkDeclCircularity(nominal);
       }
+      if (auto protocol = dyn_cast<ProtocolDecl>(decl)) {
+        if (!protocol->hasFixedLayout())
+          TC.inferDefaultWitnesses(protocol);
+      }
     }
   }
 
@@ -4250,8 +4254,6 @@
     SD->setIsBeingValidated();
 
     auto dc = SD->getDeclContext();
-    assert(dc->isTypeContext() &&
-           "Decl parsing must prevent subscripts outside of types!");
 
     if (auto gp = SD->getGenericParams()) {
       // Write up generic parameters and check the generic parameter list.
@@ -6623,18 +6625,22 @@
       
       // Make sure that the overriding property doesn't have storage.
       if (overrideASD->hasStorage() && !overrideASD->hasObservers()) {
-        auto diagID = diag::override_with_stored_property;
+        bool downgradeToWarning = false;
         if (!TC.Context.isSwiftVersionAtLeast(5) &&
             overrideASD->getAttrs().hasAttribute<LazyAttr>()) {
           // Swift 4.0 had a bug where lazy properties were considered
           // computed by the time of this check. Downgrade this diagnostic to
           // a warning.
-          diagID = diag::override_with_stored_property_warn;
+          downgradeToWarning = true;
         }
+        auto diagID = downgradeToWarning ?
+            diag::override_with_stored_property_warn :
+            diag::override_with_stored_property;
         TC.diagnose(overrideASD, diagID,
                     overrideASD->getBaseName().getIdentifier());
         TC.diagnose(baseASD, diag::property_override_here);
-        return true;
+        if (!downgradeToWarning)
+          return true;
       }
 
       // Make sure that an observing property isn't observing something
@@ -6681,9 +6687,18 @@
     if ((base->getDeclContext()->isExtensionContext() ||
          override->getDeclContext()->isExtensionContext()) &&
         !base->isObjC() && !isKnownObjC) {
-      TC.diagnose(override, diag::override_decl_extension,
-                  !override->getDeclContext()->isExtensionContext());
-      TC.diagnose(base, diag::overridden_here);
+      bool baseCanBeObjC = TC.canBeRepresentedInObjC(base);
+      TC.diagnose(override, diag::override_decl_extension, baseCanBeObjC,
+                  !base->getDeclContext()->isExtensionContext());
+      if (baseCanBeObjC) {
+        SourceLoc insertionLoc =
+          override->getAttributeInsertionLoc(/*forModifier=*/false);
+        TC.diagnose(base, diag::overridden_here_can_be_objc)
+          .fixItInsert(insertionLoc, "@objc ");
+      } else {
+        TC.diagnose(base, diag::overridden_here);
+      }
+
       return true;
     }
     
@@ -7903,6 +7918,14 @@
   return false;
 }
 
+void TypeChecker::requestMemberLayout(ValueDecl *member) {
+  auto *dc = member->getDeclContext();
+  if (auto *classDecl = dyn_cast<ClassDecl>(dc))
+    requestNominalLayout(classDecl);
+  if (auto *protocolDecl = dyn_cast<ProtocolDecl>(dc))
+    requestNominalLayout(protocolDecl);
+}
+
 void TypeChecker::requestNominalLayout(NominalTypeDecl *nominalDecl) {
   if (nominalDecl->hasValidatedLayout())
     return;
diff --git a/lib/Sema/TypeCheckGeneric.cpp b/lib/Sema/TypeCheckGeneric.cpp
index 038d024..e100ab9 100644
--- a/lib/Sema/TypeCheckGeneric.cpp
+++ b/lib/Sema/TypeCheckGeneric.cpp
@@ -204,8 +204,8 @@
             ->getAsProtocolOrProtocolExtensionContext()) {
       // Fast path: if there are no type parameters in the concrete type, just
       // return it.
-      if (!concrete->getInterfaceType()->hasTypeParameter())
-        return concrete->getInterfaceType();
+      if (!concrete->getDeclaredInterfaceType()->hasTypeParameter())
+        return concrete->getDeclaredInterfaceType();
 
       tc.validateDecl(proto);
       auto subMap = SubstitutionMap::getProtocolSubstitutions(
@@ -1307,6 +1307,13 @@
         secondType = req.getSecondType();
       }
 
+      // Don't do further checking on error types.
+      if (firstType->hasError() || (secondType && secondType->hasError())) {
+        // Another requirement will fail later; just continue.
+        valid = false;
+        continue;
+      }
+
       bool requirementFailure = false;
       if (listener && !listener->shouldCheck(kind, firstType, secondType))
         continue;
diff --git a/lib/Sema/TypeCheckProtocol.cpp b/lib/Sema/TypeCheckProtocol.cpp
index baa636b..0bd9ae9 100644
--- a/lib/Sema/TypeCheckProtocol.cpp
+++ b/lib/Sema/TypeCheckProtocol.cpp
@@ -49,294 +49,9 @@
 #define DEBUG_TYPE "Protocol conformance checking"
 #include "llvm/Support/Debug.h"
 
-STATISTIC(NumRequirementEnvironments, "# of requirement environments");
-
 using namespace swift;
 
 namespace {
-  /// Describes the environment of a requirement that will be used when
-  /// matching witnesses against the requirement and to form the resulting
-  /// \c Witness value.
-  ///
-  /// The produced generic environment will have a fresh set of archetypes that
-  /// describe the combined constraints of the requirement (because those
-  /// are available to all potential witnesses) as well as the constraints from
-  /// the context to which the protocol conformance is ascribed, which may
-  /// include additional constraints beyond those of the extended type if the
-  /// conformance is conditional. The type parameters for the generic
-  /// environment are the type parameters of the conformance context
-  /// (\c conformanceDC) with another (deeper) level of type parameters for
-  /// generic requirements. See the \c Witness class for more information about
-  /// this synthetic environment.
-  class RequirementEnvironment {
-    /// A generic signature that combines the generic parameters of the
-    /// concrete conforming type with the generic parameters of the
-    /// requirement.
-    ///
-    ///
-    /// For example, if you have:
-    ///
-    /// protocol P { func f<T>(_: T) }
-    /// struct S<A, B> : P { func f<T>(_: T) }
-    ///
-    /// The requirement and witness signatures are, respectively:
-    ///
-    /// <Self : P, T>
-    /// <A, B, T>
-    ///
-    /// The synthetic signature in this case is just the witness signature.
-    ///
-    /// It may be that the witness is more generic than the requirement,
-    /// for example:
-    ///
-    /// protocol P { func f(_: Int) }
-    /// struct S<A, B> : P { func f<T>(_: T) { } }
-    ///
-    /// Here, the requirement signature and witness signatures are:
-    ///
-    /// <Self : P>
-    /// <A, B, T>
-    ///
-    /// The synthetic signature is just:
-    ///
-    /// <A, B>
-    ///
-    /// The witness thunk emitted by SILGen uses the synthetic signature.
-    /// Therefore one invariant we preserve is that the witness thunk is
-    /// ABI compatible with the requirement's function type.
-    GenericSignature *syntheticSignature = nullptr;
-    GenericEnvironment *syntheticEnvironment = nullptr;
-
-    /// The generic signature of the protocol requirement member.
-    GenericSignature *reqSig = nullptr;
-
-    /// A substitution map mapping the requirement signature to the
-    /// generic parameters of the synthetic signature.
-    SubstitutionMap reqToSyntheticEnvMap;
-
-  public:
-    /// Create a new environment for matching the given requirement within a
-    /// particular conformance.
-    ///
-    /// \param conformanceDC The \c DeclContext to which the protocol
-    /// conformance is ascribed, which provides additional constraints.
-    ///
-    /// \param reqSig The generic signature of the requirement for which we
-    /// are creating a generic environment.
-    ///
-    /// \param proto The protocol containing the requirement.
-    ///
-    /// \param conformance The protocol conformance, or null if there is no
-    /// conformance (because we're finding default implementations).
-    RequirementEnvironment(TypeChecker &tc,
-                           DeclContext *conformanceDC,
-                           GenericSignature *reqSig,
-                           ProtocolDecl *proto,
-                           ClassDecl *covariantSelf,
-                           ProtocolConformance *conformance);
-
-    /// Retrieve the synthetic generic environment.
-    GenericEnvironment *getSyntheticEnvironment() const {
-      return syntheticEnvironment;
-    }
-
-    /// Retrieve the generic signature of the requirement.
-    const GenericSignature *getRequirementSignature() const {
-      return reqSig;
-    }
-
-    /// Retrieve the substitution map that maps the interface types of the
-    /// requirement to the interface types of the synthetic environment.
-    const SubstitutionMap &getRequirementToSyntheticMap() const {
-      return reqToSyntheticEnvMap;
-    }
-  };
-
-  /// \brief The result of matching a particular declaration to a given
-  /// requirement.
-  enum class MatchKind : unsigned char {
-    /// \brief The witness matched the requirement exactly.
-    ExactMatch,
-
-    /// \brief There is a difference in optionality.
-    OptionalityConflict,
-
-    /// \brief The witness matched the requirement with some renaming.
-    RenamedMatch,
-
-    /// \brief The witness is invalid or has an invalid type.
-    WitnessInvalid,
-
-    /// \brief The kind of the witness and requirement differ, e.g., one
-    /// is a function and the other is a variable.
-    KindConflict,
-
-    /// \brief The types conflict.
-    TypeConflict,
-
-    /// The witness throws, but the requirement does not.
-    ThrowsConflict,
-
-    /// \brief The witness did not match due to static/non-static differences.
-    StaticNonStaticConflict,
-    
-    /// \brief The witness is not settable, but the requirement is.
-    SettableConflict,
-
-    /// \brief The witness did not match due to prefix/non-prefix differences.
-    PrefixNonPrefixConflict,
-
-    /// \brief The witness did not match due to postfix/non-postfix differences.
-    PostfixNonPostfixConflict,
-    
-    /// \brief The witness did not match because of mutating conflicts.
-    MutatingConflict,
-    
-    /// \brief The witness did not match because of nonmutating conflicts.
-    NonMutatingConflict,
-    
-    /// \brief The witness did not match because of __consuming conflicts.
-    ConsumingConflict,
-
-    /// The witness is not rethrows, but the requirement is.
-    RethrowsConflict,
-
-    /// The witness is explicitly @nonobjc but the requirement is @objc.
-    NonObjC,
-  };
-
-  /// Describes the kind of optional adjustment performed when
-  /// comparing two types.
-  enum class OptionalAdjustmentKind {
-    // No adjustment required.
-    None,
-
-    /// The witness can produce a 'nil' that won't be handled by
-    /// callers of the requirement. This is a type-safety problem.
-    ProducesUnhandledNil,
-
-    /// Callers of the requirement can provide 'nil', but the witness
-    /// does not handle it. This is a type-safety problem.
-    ConsumesUnhandledNil,
-
-    /// The witness handles 'nil', but won't ever be given a 'nil'.
-    /// This is not a type-safety problem.
-    WillNeverConsumeNil,
-      
-    /// Callers of the requirement can expect to receive 'nil', but
-    /// the witness will never produce one. This is not a type-safety
-    /// problem.
-    WillNeverProduceNil,
-
-    /// The witness has an IUO that can be removed, because the
-    /// protocol doesn't need it. This is not a type-safety problem.
-    RemoveIUO,
-
-    /// The witness has an IUO that should be translated into a true
-    /// optional. This is not a type-safety problem.
-    IUOToOptional,
-  };
-
-  /// Once a witness has been found, there are several reasons it may
-  /// not be usable.
-  enum class CheckKind : unsigned {
-    /// The witness is OK.
-    Success,
-
-    /// The witness is less accessible than the requirement.
-    Access,
-
-    /// The witness is storage whose setter is less accessible than the
-    /// requirement.
-    AccessOfSetter,
-
-    /// The witness is less available than the requirement.
-    Availability,
-
-    /// The requirement was marked explicitly unavailable.
-    Unavailable,
-
-    /// The witness requires optional adjustments.
-    OptionalityConflict,
-
-    /// The witness is a constructor which is more failable than the
-    /// requirement.
-    ConstructorFailability,
-
-    /// The witness itself is inaccessible.
-    WitnessUnavailable,
-  };
-
-  /// Describes an optional adjustment made to a witness.
-  class OptionalAdjustment {
-    /// The kind of adjustment.
-    unsigned Kind : 16;
-
-    /// Whether this is a parameter adjustment (with an index) vs. a
-    /// result or value type adjustment (no index needed).
-    unsigned IsParameterAdjustment : 1;
-
-    /// The adjustment index, for parameter adjustments.
-    unsigned ParameterAdjustmentIndex : 15;
-
-  public:
-    /// Create a non-parameter optional adjustment.
-    explicit OptionalAdjustment(OptionalAdjustmentKind kind) 
-      : Kind(static_cast<unsigned>(kind)), IsParameterAdjustment(false),
-        ParameterAdjustmentIndex(0) { }
-
-    /// Create an optional adjustment to a parameter.
-    OptionalAdjustment(OptionalAdjustmentKind kind,
-                       unsigned parameterIndex)
-      : Kind(static_cast<unsigned>(kind)), IsParameterAdjustment(true),
-        ParameterAdjustmentIndex(parameterIndex) { }
-
-    /// Determine the kind of optional adjustment.
-    OptionalAdjustmentKind getKind() const { 
-      return static_cast<OptionalAdjustmentKind>(Kind);
-    }
-
-    /// Determine whether this is a parameter adjustment.
-    bool isParameterAdjustment() const {
-      return IsParameterAdjustment;
-    }
-
-    /// Return the index of a parameter adjustment.
-    unsigned getParameterIndex() const {
-      assert(isParameterAdjustment() && "Not a parameter adjustment");
-      return ParameterAdjustmentIndex;
-    }
-
-    /// Determines whether the optional adjustment is an error.
-    bool isError() const {
-      switch (getKind()) {
-      case OptionalAdjustmentKind::None:
-        return false;
-
-      case OptionalAdjustmentKind::ProducesUnhandledNil:
-      case OptionalAdjustmentKind::ConsumesUnhandledNil:
-        return true;
-
-      case OptionalAdjustmentKind::WillNeverConsumeNil:
-      case OptionalAdjustmentKind::WillNeverProduceNil:
-      case OptionalAdjustmentKind::RemoveIUO:
-      case OptionalAdjustmentKind::IUOToOptional:
-        // Warnings at most.
-        return false;
-      }
-
-      llvm_unreachable("Unhandled OptionalAdjustmentKind in switch.");
-    }
-
-    /// Retrieve the source location at which the optional is
-    /// specified or would be inserted.
-    SourceLoc getOptionalityLoc(ValueDecl *witness) const;
-
-    /// Retrieve the optionality location for the given type
-    /// representation.
-    SourceLoc getOptionalityLoc(TypeRepr *tyR) const;
-  };
-
   /// Whether any of the given optional adjustments is an error (vs. a
   /// warning).
   bool hasAnyError(ArrayRef<OptionalAdjustment> adjustments) {
@@ -348,109 +63,6 @@
   }
 }
 
-/// \brief Describes a match between a requirement and a witness.
-struct swift::RequirementMatch {
-  RequirementMatch(ValueDecl *witness, MatchKind kind,
-                   Optional<RequirementEnvironment> &&env = None)
-    : Witness(witness), Kind(kind), WitnessType(), ReqEnv(std::move(env)) {
-    assert(!hasWitnessType() && "Should have witness type");
-  }
-
-  RequirementMatch(ValueDecl *witness, MatchKind kind,
-                   Type witnessType,
-                   Optional<RequirementEnvironment> &&env = None,
-                   ArrayRef<OptionalAdjustment> optionalAdjustments = {})
-    : Witness(witness), Kind(kind), WitnessType(witnessType),
-      ReqEnv(std::move(env)),
-      OptionalAdjustments(optionalAdjustments.begin(),
-                          optionalAdjustments.end())
-  {
-    assert(hasWitnessType() == !witnessType.isNull() &&
-           "Should (or should not) have witness type");
-  }
-
-  /// \brief The witness that matches the (implied) requirement.
-  ValueDecl *Witness;
-
-  /// \brief The kind of match.
-  MatchKind Kind;
-
-  /// \brief The type of the witness when it is referenced.
-  Type WitnessType;
-
-  /// \brief The requirement environment to use for the witness thunk.
-  Optional<RequirementEnvironment> ReqEnv;
-
-  /// The set of optional adjustments performed on the witness.
-  SmallVector<OptionalAdjustment, 2> OptionalAdjustments;
-
-  /// \brief Determine whether this match is viable.
-  bool isViable() const {
-    switch(Kind) {
-    case MatchKind::ExactMatch:
-    case MatchKind::OptionalityConflict:
-    case MatchKind::RenamedMatch:
-      return true;
-
-    case MatchKind::WitnessInvalid:
-    case MatchKind::KindConflict:
-    case MatchKind::TypeConflict:
-    case MatchKind::StaticNonStaticConflict:
-    case MatchKind::SettableConflict:
-    case MatchKind::PrefixNonPrefixConflict:
-    case MatchKind::PostfixNonPostfixConflict:
-    case MatchKind::MutatingConflict:
-    case MatchKind::NonMutatingConflict:
-    case MatchKind::ConsumingConflict:
-    case MatchKind::RethrowsConflict:
-    case MatchKind::ThrowsConflict:
-    case MatchKind::NonObjC:
-      return false;
-    }
-
-    llvm_unreachable("Unhandled MatchKind in switch.");
-  }
-
-  /// \brief Determine whether this requirement match has a witness type.
-  bool hasWitnessType() const {
-    switch(Kind) {
-    case MatchKind::ExactMatch:
-    case MatchKind::RenamedMatch:
-    case MatchKind::TypeConflict:
-    case MatchKind::OptionalityConflict:
-      return true;
-
-    case MatchKind::WitnessInvalid:
-    case MatchKind::KindConflict:
-    case MatchKind::StaticNonStaticConflict:
-    case MatchKind::SettableConflict:
-    case MatchKind::PrefixNonPrefixConflict:
-    case MatchKind::PostfixNonPostfixConflict:
-    case MatchKind::MutatingConflict:
-    case MatchKind::NonMutatingConflict:
-    case MatchKind::ConsumingConflict:
-    case MatchKind::RethrowsConflict:
-    case MatchKind::ThrowsConflict:
-    case MatchKind::NonObjC:
-      return false;
-    }
-
-    llvm_unreachable("Unhandled MatchKind in switch.");
-  }
-
-  SmallVector<Substitution, 2> WitnessSubstitutions;
-
-  swift::Witness getWitness(ASTContext &ctx) const {
-    SmallVector<Substitution, 2> syntheticSubs;
-    auto syntheticEnv = ReqEnv->getSyntheticEnvironment();
-    ReqEnv->getRequirementSignature()->getSubstitutions(
-        ReqEnv->getRequirementToSyntheticMap(),
-        syntheticSubs);
-    return swift::Witness(this->Witness, WitnessSubstitutions,
-                          syntheticEnv, syntheticSubs);
-  }
-};
-
 /// \brief Describes the suitability of the chosen witness for
 /// the requirement.
 struct swift::RequirementCheck {
@@ -477,10 +89,19 @@
       RequiredAvailability(requiredAvailability) { }
 };
 
-/// If the given type is a direct reference to an associated type of
-/// the given protocol, return the referenced associated type.
-static AssociatedTypeDecl *
-getReferencedAssocTypeOfProtocol(Type type, ProtocolDecl *proto) {
+swift::Witness RequirementMatch::getWitness(ASTContext &ctx) const {
+  SmallVector<Substitution, 2> syntheticSubs;
+  auto syntheticEnv = ReqEnv->getSyntheticEnvironment();
+  ReqEnv->getRequirementSignature()->getSubstitutions(
+      ReqEnv->getRequirementToSyntheticMap(),
+      syntheticSubs);
+  return swift::Witness(this->Witness, WitnessSubstitutions,
+                        syntheticEnv, syntheticSubs);
+}
+
+
+AssociatedTypeDecl *
+swift::getReferencedAssocTypeOfProtocol(Type type, ProtocolDecl *proto) {
   if (auto dependentMember = type->getAs<DependentMemberType>()) {
     if (auto assocType = dependentMember->getAssocType()) {
       if (dependentMember->getBase()->isEqual(proto->getSelfInterfaceType())) {
@@ -723,11 +344,9 @@
   return false;
 }
 
-/// \brief Match the given witness to the given requirement.
-///
-/// \returns the result of performing the match.
-static RequirementMatch
-matchWitness(TypeChecker &tc,
+RequirementMatch
+swift::matchWitness(
+             TypeChecker &tc,
              DeclContext *dc, ValueDecl *req, ValueDecl *witness,
              const std::function<
                      std::tuple<Optional<RequirementMatch>, Type, Type>(void)> 
@@ -957,211 +576,12 @@
   return finalize(anyRenaming, optionalAdjustments);
 }
 
-RequirementEnvironment::RequirementEnvironment(
-                                           TypeChecker &tc,
-                                           DeclContext *conformanceDC,
-                                           GenericSignature *reqSig,
-                                           ProtocolDecl *proto,
-                                           ClassDecl *covariantSelf,
-                                           ProtocolConformance *conformance)
-    : reqSig(reqSig) {
-  ASTContext &ctx = tc.Context;
-
-  auto concreteType = conformanceDC->getSelfInterfaceType();
-  auto *conformanceSig = conformanceDC->getGenericSignatureOfContext();
-
-  // Build a substitution map from the generic parameters of the conforming
-  // type to the synthetic environment.
-  //
-  // For structs, enums and protocols, this is a 1:1 mapping; for classes,
-  // we increase the depth of each generic parameter by 1 so that we can
-  // introduce a class-bound 'Self' parameter.
-  auto substConcreteType = concreteType;
-  SubstitutionMap conformanceToSyntheticEnvMap;
-  if (conformanceSig) {
-    conformanceToSyntheticEnvMap = conformanceSig->getSubstitutionMap(
-      [&](SubstitutableType *type) {
-        auto *genericParam = cast<GenericTypeParamType>(type);
-        if (covariantSelf) {
-          return GenericTypeParamType::get(
-              genericParam->getDepth() + 1,
-              genericParam->getIndex(),
-              ctx);
-        }
-
-        return GenericTypeParamType::get(
-            genericParam->getDepth(),
-            genericParam->getIndex(),
-            ctx);
-      },
-      MakeAbstractConformanceForGenericType());
-
-    substConcreteType = concreteType.subst(conformanceToSyntheticEnvMap);
-  }
-
-  // Calculate the depth at which the requirement's generic parameters
-  // appear in the synthetic signature.
-  unsigned depth = 0;
-  if (covariantSelf) {
-    depth++;
-  }
-  if (conformanceSig) {
-    depth += conformanceSig->getGenericParams().back()->getDepth() + 1;
-  }
-
-  // Build a substitution map to replace the protocol's \c Self and the type
-  // parameters of the requirement into a combined context that provides the
-  // type parameters of the conformance context and the parameters of the
-  // requirement.
-  auto selfType = cast<GenericTypeParamType>(
-      proto->getSelfInterfaceType()->getCanonicalType());
-
-  reqToSyntheticEnvMap = reqSig->getSubstitutionMap(
-    [selfType, substConcreteType, depth, covariantSelf, &ctx]
-    (SubstitutableType *type) -> Type {
-      // If the conforming type is a class, the protocol 'Self' maps to
-      // the class-constrained 'Self'. Otherwise, it maps to the concrete
-      // type.
-      if (type->isEqual(selfType)) {
-        if (covariantSelf)
-          return GenericTypeParamType::get(/*depth=*/0, /*index=*/0, ctx);
-        return substConcreteType;
-      }
-      // Other requirement generic parameters map 1:1 with their depth
-      // increased appropriately.
-      auto *genericParam = cast<GenericTypeParamType>(type);
-      // In a protocol requirement, the only generic parameter at depth 0
-      // should be 'Self', and all others at depth 1. Anything else is
-      // invalid code.
-      if (genericParam->getDepth() != 1)
-        return Type();
-      auto substGenericParam =
-        GenericTypeParamType::get(depth, genericParam->getIndex(), ctx);
-      return substGenericParam;
-    },
-    [selfType, substConcreteType, conformance, conformanceDC, &ctx](
-        CanType type, Type replacement, ProtocolType *protoType)
-          -> Optional<ProtocolConformanceRef> {
-      auto proto = protoType->getDecl();
-
-      // The protocol 'Self' conforms concretely to the conforming type.
-      if (type->isEqual(selfType)) {
-        ProtocolConformance *specialized = conformance;
-        if (conformance && conformance->getGenericSignature()) {
-          auto concreteSubs =
-            substConcreteType->getContextSubstitutionMap(
-              conformanceDC->getParentModule(), conformanceDC);
-          specialized =
-            ctx.getSpecializedConformance(substConcreteType, conformance,
-                                          concreteSubs);
-        }
-
-        if (specialized)
-          return ProtocolConformanceRef(specialized);
-      }
-
-      // All other generic parameters come from the requirement itself
-      // and conform abstractly.
-      return ProtocolConformanceRef(proto);
-    });
-
-  // If the requirement itself is non-generic, the synthetic signature
-  // is that of the conformance context.
-  if (!covariantSelf &&
-      reqSig->getGenericParams().size() == 1 &&
-      reqSig->getRequirements().size() == 1) {
-    syntheticSignature = conformanceDC->getGenericSignatureOfContext();
-    if (syntheticSignature) {
-      syntheticSignature = syntheticSignature->getCanonicalSignature();
-      syntheticEnvironment =
-        syntheticSignature->createGenericEnvironment();
-    }
-
-    return;
-  }
-
-  // Construct a generic signature builder by collecting the constraints
-  // from the requirement and the context of the conformance together,
-  // because both define the capabilities of the requirement.
-  GenericSignatureBuilder builder(ctx);
-
-  auto source =
-    GenericSignatureBuilder::FloatingRequirementSource::forAbstract();
-
-  // If the conforming type is a class, add a class-constrained 'Self'
-  // parameter.
-  if (covariantSelf) {
-    auto paramTy = GenericTypeParamType::get(/*depth=*/0, /*index=*/0, ctx);
-    builder.addGenericParameter(paramTy);
-  }
-
-  // Now, add all generic parameters from the conforming type.
-  if (conformanceSig) {
-    for (auto param : conformanceSig->getGenericParams()) {
-      builder.addGenericParameter(
-          Type(param).subst(conformanceToSyntheticEnvMap)
-              ->castTo<GenericTypeParamType>());
-    }
-  }
-
-  // Next, add requirements.
-  if (covariantSelf) {
-    auto paramTy = GenericTypeParamType::get(/*depth=*/0, /*index=*/0, ctx);
-    Requirement reqt(RequirementKind::Superclass, paramTy, substConcreteType);
-    builder.addRequirement(reqt, source, nullptr);
-  }
-
-  if (conformanceSig) {
-    for (auto &rawReq : conformanceSig->getRequirements()) {
-      if (auto req = rawReq.subst(conformanceToSyntheticEnvMap))
-        builder.addRequirement(*req, source, nullptr);
-    }
-  }
-
-  // Finally, add the generic parameters from the requirement.
-  for (auto genericParam : reqSig->getGenericParams().slice(1)) {
-    // The only depth that makes sense is depth == 1, the generic parameters
-    // of the requirement itself. Anything else is from invalid code.
-    if (genericParam->getDepth() != 1) {
-      return;
-    }
-
-    // Create an equivalent generic parameter at the next depth.
-    auto substGenericParam =
-      GenericTypeParamType::get(depth, genericParam->getIndex(), ctx);
-
-    builder.addGenericParameter(substGenericParam);
-  }
-
-  ++NumRequirementEnvironments;
-
-  // Next, add each of the requirements (mapped from the requirement's
-  // interface types into the abstract type parameters).
-  for (auto &rawReq : reqSig->getRequirements()) {
-    // FIXME: This should not be necessary, since the constraint is redundant,
-    // but we need it to work around some crashes for now.
-    if (rawReq.getKind() == RequirementKind::Conformance &&
-        rawReq.getFirstType()->isEqual(selfType) &&
-        rawReq.getSecondType()->isEqual(proto->getDeclaredType()))
-      continue;
-
-    if (auto req = rawReq.subst(reqToSyntheticEnvMap))
-      builder.addRequirement(*req, source, conformanceDC->getParentModule());
-  }
-
-  // Produce the generic signature and environment.
-  // FIXME: Pass in a source location for the conformance, perhaps? It seems
-  // like this could fail.
-  syntheticSignature =
-    std::move(builder).computeGenericSignature(SourceLoc());
-  syntheticEnvironment = syntheticSignature->createGenericEnvironment();
-}
-
-static RequirementMatch
-matchWitness(TypeChecker &tc,
-             ProtocolDecl *proto,
-             ProtocolConformance *conformance,
-             DeclContext *dc, ValueDecl *req, ValueDecl *witness) {
+RequirementMatch swift::matchWitness(TypeChecker &tc,
+                                     ProtocolDecl *proto,
+                                     ProtocolConformance *conformance,
+                                     DeclContext *dc,
+                                     ValueDecl *req,
+                                     ValueDecl *witness) {
   using namespace constraints;
 
   // Initialized by the setup operation.
@@ -1230,8 +650,7 @@
   }
 
   Optional<RequirementEnvironment> reqEnvironment(
-      RequirementEnvironment(tc, dc, reqSig, proto, covariantSelf,
-                             conformance));
+      RequirementEnvironment(dc, reqSig, proto, covariantSelf, conformance));
 
   // Set up the constraint system for matching.
   auto setup = [&]() -> std::tuple<Optional<RequirementMatch>, Type, Type> {
@@ -2479,6 +1898,32 @@
 
   // Record the type witness.
   Conformance->setTypeWitness(assocType, type, typeDecl);
+
+  // Record type witnesses for any "overridden" associated types.
+  llvm::SetVector<AssociatedTypeDecl *> overriddenAssocTypes;
+  overriddenAssocTypes.insert(assocType->getOverriddenDecls().begin(),
+                              assocType->getOverriddenDecls().end());
+  for (unsigned idx = 0; idx < overriddenAssocTypes.size(); ++idx) {
+    auto overridden = overriddenAssocTypes[idx];
+
+    // Note all of the newly-discovered overridden associated types.
+    overriddenAssocTypes.insert(overridden->getOverriddenDecls().begin(),
+                                overridden->getOverriddenDecls().end());
+
+    // Find the conformance for this overridden protocol.
+    auto overriddenConformance =
+      DC->getParentModule()->lookupConformance(Adoptee,
+                                               overridden->getProtocol());
+    if (!overriddenConformance ||
+        !overriddenConformance->isConcrete())
+      continue;
+
+    auto overriddenRootConformance =
+      overriddenConformance->getConcrete()->getRootNormalConformance();
+    ConformanceChecker(TC, overriddenRootConformance, GlobalMissingWitnesses)
+      .recordTypeWitness(overridden, type, typeDecl,
+                         /*performRedeclarationCheck=*/true);
+  }
 }
 
 bool swift::
@@ -3349,505 +2794,6 @@
   return ResolveWitnessResult::ExplicitFailed;
 }
 
-static bool associatedTypesAreSameEquivalenceClass(AssociatedTypeDecl *a,
-                                                   AssociatedTypeDecl *b) {
-  if (a == b)
-    return true;
-  
-  // TODO: Do a proper equivalence check here by looking for some relationship
-  // between a and b's protocols. In practice today, it's unlikely that
-  // two same-named associated types can currently be independent, since we
-  // don't have anything like `@implements(P.foo)` to rename witnesses (and
-  // we still fall back to name lookup for witnesses in more cases than we
-  // should).
-  if (a->getName() == b->getName())
-    return true;
-
-  return false;
-}
-
-InferredAssociatedTypesByWitnesses
-ConformanceChecker::inferTypeWitnessesViaValueWitnesses(
-                    const llvm::SetVector<AssociatedTypeDecl *> &allUnresolved,
-                    ValueDecl *req) {
-  // Conformances constructed by the ClangImporter should have explicit type
-  // witnesses already.
-  if (isa<ClangModuleUnit>(Conformance->getDeclContext()->getModuleScopeContext())) {
-    llvm::errs() << "Cannot infer associated types for imported conformance:\n";
-    Conformance->getType().dump(llvm::errs());
-    for (auto assocTypeDecl : allUnresolved)
-      assocTypeDecl->dump(llvm::errs());
-    abort();
-  }
-
-  InferredAssociatedTypesByWitnesses result;
-
-  auto isExtensionUsableForInference = [&](ExtensionDecl *extension) -> bool {
-    // Assume unconstrained concrete extensions we found witnesses in are
-    // always viable.
-    if (!extension->getExtendedType()->isAnyExistentialType()) {
-      // TODO: When constrained extensions are a thing, we'll need an "is
-      // as specialized as" kind of check here.
-      return !extension->isConstrainedExtension();
-    }
-    
-    // The extension may not have a generic signature set up yet, as a
-    // recursion breaker, in which case we can't yet confidently reject its
-    // witnesses.
-    if (!extension->getGenericSignature())
-      return true;
-    
-    // The condition here is a bit more fickle than
-    // `isProtocolExtensionUsable`. That check would prematurely reject
-    // extensions like `P where AssocType == T` if we're relying on a
-    // default implementation inside the extension to infer `AssocType == T`
-    // in the first place. Only check conformances on the `Self` type,
-    // because those have to be explicitly declared on the type somewhere
-    // so won't be affected by whatever answer inference comes up with.
-    auto selfTy = GenericTypeParamType::get(0, 0, TC.Context);
-    for (const Requirement &reqt
-         : extension->getGenericSignature()->getRequirements()) {
-      switch (reqt.getKind()) {
-      case RequirementKind::Conformance:
-      case RequirementKind::Superclass:
-        // FIXME: This is the wrong check
-        if (selfTy->isEqual(reqt.getFirstType())
-            && !TC.isSubtypeOf(Conformance->getType(),reqt.getSecondType(), DC))
-          return false;
-        break;
-      
-      case RequirementKind::Layout:
-      case RequirementKind::SameType:
-        break;
-      }
-    }
-    
-    return true;
-  };
-
-  auto typeInContext =
-    Conformance->getDeclContext()->mapTypeIntoContext(Conformance->getType());
-
-  for (auto witness : lookupValueWitnesses(req, /*ignoringNames=*/nullptr)) {
-    DEBUG(llvm::dbgs() << "Inferring associated types from decl:\n";
-          witness->dump(llvm::dbgs()));
-  
-    // If the potential witness came from an extension, and our `Self`
-    // type can't use it regardless of what associated types we end up
-    // inferring, skip the witness.
-    if (auto extension = dyn_cast<ExtensionDecl>(witness->getDeclContext()))
-      if (!isExtensionUsableForInference(extension))
-        continue;
-  
-    // Try to resolve the type witness via this value witness.
-    auto witnessResult = inferTypeWitnessesViaValueWitness(req, witness);
-
-    // Filter out duplicated inferred types as well as inferred types
-    // that don't meet the requirements placed on the associated type.
-    llvm::DenseSet<std::pair<AssociatedTypeDecl *, CanType>> known;
-    for (unsigned i = 0; i < witnessResult.Inferred.size(); /*nothing*/) {
-#define REJECT {\
-  witnessResult.Inferred.erase(witnessResult.Inferred.begin() + i); \
-  continue; \
-}
-      auto &result = witnessResult.Inferred[i];
-
-      DEBUG(llvm::dbgs() << "Considering whether " << result.first->getName()
-                         << " can infer to:\n";
-            result.second->dump(llvm::dbgs()));
-
-      // Filter out errors.
-      if (result.second->hasError()) {
-        DEBUG(llvm::dbgs() << "-- has error type\n");
-        REJECT;
-      }
-
-      // Filter out duplicates.
-      if (!known.insert({result.first, result.second->getCanonicalType()})
-                .second) {
-        DEBUG(llvm::dbgs() << "-- duplicate\n");
-        REJECT;
-      }
-     
-      // Filter out circular possibilities, e.g. that
-      // AssocType == S.AssocType or
-      // AssocType == Foo<S.AssocType>.
-      bool canInferFromOtherAssociatedType = false;
-      bool containsTautologicalType =
-        result.second.findIf([&](Type t) -> bool {
-          auto dmt = t->getAs<DependentMemberType>();
-          if (!dmt)
-            return false;
-          if (!associatedTypesAreSameEquivalenceClass(dmt->getAssocType(),
-                                                      result.first))
-            return false;
-          if (!dmt->getBase()->isEqual(typeInContext))
-            return false;
-          
-          // If this associated type is same-typed to another associated type
-          // on `Self`, then it may still be an interesting candidate if we find
-          // an answer for that other type.
-          auto witnessContext = witness->getDeclContext();
-          if (witnessContext->getAsProtocolExtensionContext()
-              && witnessContext->getGenericSignatureOfContext()) {
-            auto selfTy = witnessContext->getSelfInterfaceType();
-            auto selfAssocTy = DependentMemberType::get(selfTy,
-                                                        dmt->getAssocType());
-            for (auto &reqt : witnessContext->getGenericSignatureOfContext()
-                                            ->getRequirements()) {
-              switch (reqt.getKind()) {
-              case RequirementKind::Conformance:
-              case RequirementKind::Superclass:
-              case RequirementKind::Layout:
-                break;
-              
-              case RequirementKind::SameType:
-                Type other;
-                if (reqt.getFirstType()->isEqual(selfAssocTy)) {
-                  other = reqt.getSecondType();
-                } else if (reqt.getSecondType()->isEqual(selfAssocTy)) {
-                  other = reqt.getFirstType();
-                } else {
-                  break;
-                }
-                
-                if (auto otherAssoc = other->getAs<DependentMemberType>()) {
-                  if (otherAssoc->getBase()->isEqual(selfTy)) {
-                    auto otherDMT = DependentMemberType::get(dmt->getBase(),
-                                                    otherAssoc->getAssocType());
-                    
-                    // We may be able to infer one associated type from the
-                    // other.
-                    result.second = result.second.transform([&](Type t) -> Type{
-                      if (t->isEqual(dmt))
-                        return otherDMT;
-                      return t;
-                    });
-                    canInferFromOtherAssociatedType = true;
-                    DEBUG(llvm::dbgs() << "++ we can same-type to:\n";
-                          result.second->dump(llvm::dbgs()));
-                    return false;
-                  }
-                }
-                break;
-              }
-            }
-          }
-          
-          return true;
-        });
-      
-      if (containsTautologicalType) {
-        DEBUG(llvm::dbgs() << "-- tautological\n");
-        REJECT;
-      }
-      
-      // Check that the type witness doesn't contradict an
-      // explicitly-given type witness. If it does contradict, throw out the
-      // witness completely.
-      if (!allUnresolved.count(result.first)) {
-        auto existingWitness =
-          Conformance->getTypeWitness(result.first, nullptr);
-        existingWitness =
-          Conformance->getDeclContext()->mapTypeIntoContext(existingWitness);
-
-        // If the deduced type contains an irreducible
-        // DependentMemberType, that indicates a dependency
-        // on another associated type we haven't deduced,
-        // so we can't tell whether there's a contradiction
-        // yet.
-        auto newWitness = result.second->getCanonicalType();
-        if (!newWitness->hasTypeParameter() &&
-            !newWitness->hasDependentMember() &&
-            !existingWitness->isEqual(newWitness)) {
-          DEBUG(llvm::dbgs() << "** contradicts explicit type witness, "
-                                "rejecting inference from this decl\n");
-          goto next_witness;
-        }
-      }
-      
-      // If we same-typed to another unresolved associated type, we won't
-      // be able to check conformances yet.
-      if (!canInferFromOtherAssociatedType) {
-        // Check that the type witness meets the
-        // requirements on the associated type.
-        if (auto failed = checkTypeWitness(TC, DC, Proto, result.first,
-                                           result.second)) {
-          witnessResult.NonViable.push_back(
-                              std::make_tuple(result.first,result.second,failed));
-          DEBUG(llvm::dbgs() << "-- doesn't fulfill requirements\n");
-          REJECT;
-        }
-      }
-      
-      DEBUG(llvm::dbgs() << "++ seems legit\n");
-      ++i;
-    }
-#undef REJECT
-
-    // If no inferred types remain, skip this witness.
-    if (witnessResult.Inferred.empty() && witnessResult.NonViable.empty())
-      continue;
-
-    // If there were any non-viable inferred associated types, don't
-    // infer anything from this witness.
-    if (!witnessResult.NonViable.empty())
-      witnessResult.Inferred.clear();
-
-    result.push_back(std::move(witnessResult));
-next_witness:;
-  }
-
-  return result;
-}
-
-InferredAssociatedTypes
-ConformanceChecker::inferTypeWitnessesViaValueWitnesses(
-  const llvm::SetVector<AssociatedTypeDecl *> &assocTypes)
-{
-  InferredAssociatedTypes result;
-  for (auto member : Proto->getMembers()) {
-    auto req = dyn_cast<ValueDecl>(member);
-    if (!req)
-      continue;
-
-    // We only look at value witnesses.
-    if (isa<AssociatedTypeDecl>(req))
-      continue;
-
-    // Skip operator requirements, because they match globally and 
-    // therefore tend to cause deduction mismatches.
-    // FIXME: If we had some basic sanity checking of Self, we might be able to
-    // use these.
-    if (auto func = dyn_cast<FuncDecl>(req)) {
-      if (func->isOperator() || func->isAccessor())
-        continue;
-    }
-
-    // Validate the requirement.
-    TC.validateDecl(req);
-    if (req->isInvalid() || !req->hasValidSignature())
-      continue;
-      
-    // Check whether any of the associated types we care about are
-    // referenced in this value requirement.
-    bool anyAssocTypeMatches = false;
-    for (auto assocType : getReferencedAssociatedTypes(req)) {
-      if (assocTypes.count(assocType) > 0) {
-        anyAssocTypeMatches = true;
-        break;
-      }
-    }
-
-    // We cannot deduce anything from the witnesses of this
-    // requirement; skip it.
-    if (!anyAssocTypeMatches)
-      continue;
-
-    // Infer associated types from the potential value witnesses for
-    // this requirement.
-    auto reqInferred = inferTypeWitnessesViaValueWitnesses(assocTypes, req);
-    if (reqInferred.empty())
-      continue;
-
-    result.push_back({req, std::move(reqInferred)});
-  }
-
-  return result;
-}
-
-/// Map error types back to their original types.
-static Type mapErrorTypeToOriginal(Type type) {
-  if (auto errorType = type->getAs<ErrorType>()) {
-    if (auto originalType = errorType->getOriginalType())
-      return originalType.transform(mapErrorTypeToOriginal);
-  }
-
-  return type;
-}
-
-/// Produce the type when matching a witness.
-static Type getWitnessTypeForMatching(TypeChecker &tc,
-                                      NormalProtocolConformance *conformance,
-                                      ValueDecl *witness) {
-  if (!witness->hasInterfaceType())
-    tc.validateDecl(witness);
-
-  if (witness->isInvalid() || !witness->hasValidSignature())
-    return Type();
-
-  if (!witness->getDeclContext()->isTypeContext()) {
-    // FIXME: Could we infer from 'Self' to make these work?
-    return witness->getInterfaceType();
-  }
-
-  // Retrieve the set of substitutions to be applied to the witness.
-  Type model =
-    conformance->getDeclContext()->mapTypeIntoContext(conformance->getType());
-  TypeSubstitutionMap substitutions = model->getMemberSubstitutions(witness);
-  Type type = witness->getInterfaceType()->getReferenceStorageReferent();
-  
-  if (substitutions.empty())
-    return type;
-  
-  // Strip off the requirements of a generic function type.
-  // FIXME: This doesn't actually break recursion when substitution
-  // looks for an inferred type witness, but it makes it far less
-  // common, because most of the recursion involves the requirements
-  // of the generic type.
-  if (auto genericFn = type->getAs<GenericFunctionType>()) {
-    type = FunctionType::get(genericFn->getInput(),
-                             genericFn->getResult(),
-                             genericFn->getExtInfo());
-  }
-
-  // Remap associated types that reference other protocols into this
-  // protocol.
-  auto proto = conformance->getProtocol();
-  type = type.transformRec([proto](TypeBase *type) -> Optional<Type> {
-    if (auto depMemTy = dyn_cast<DependentMemberType>(type)) {
-      if (depMemTy->getAssocType() &&
-          depMemTy->getAssocType()->getProtocol() != proto) {
-        for (auto member : proto->lookupDirect(depMemTy->getName())) {
-          if (auto assocType = dyn_cast<AssociatedTypeDecl>(member)) {
-            auto origProto = depMemTy->getAssocType()->getProtocol();
-            if (proto->inheritsFrom(origProto))
-              return Type(DependentMemberType::get(depMemTy->getBase(),
-                                                   assocType));
-          }
-        }
-      }
-    }
-
-    return None;
-  });
-
-  ModuleDecl *module = conformance->getDeclContext()->getParentModule();
-  auto resultType = type.subst(QueryTypeSubstitutionMap{substitutions},
-                               LookUpConformanceInModule(module),
-                               SubstFlags::UseErrorType);
-  if (!resultType->hasError()) return resultType;
-
-  // Map error types with original types *back* to the original, dependent type.
-  return resultType.transform(mapErrorTypeToOriginal);
-}
-
-/// Remove the 'self' type from the given type, if it's a method type.
-static Type removeSelfParam(ValueDecl *value, Type type) {
-  if (auto func = dyn_cast<AbstractFunctionDecl>(value)) {
-    if (func->getDeclContext()->isTypeContext())
-      return type->castTo<AnyFunctionType>()->getResult();
-  }
-
-  return type;
-}
-
-/// Attempt to resolve a type witness via a specific value witness.
-InferredAssociatedTypesByWitness
-ConformanceChecker::inferTypeWitnessesViaValueWitness(ValueDecl *req,
-                                                      ValueDecl *witness) {
-  InferredAssociatedTypesByWitness inferred;
-  inferred.Witness = witness;
-
-  // Compute the requirement and witness types we'll use for matching.
-  Type fullWitnessType = getWitnessTypeForMatching(TC, Conformance, witness);
-  if (!fullWitnessType) {
-    return inferred;
-  }
-
-  auto setup = [&]() -> std::tuple<Optional<RequirementMatch>, Type, Type> {
-    fullWitnessType = removeSelfParam(witness, fullWitnessType);
-    return std::make_tuple(
-        None,
-        removeSelfParam(req, req->getInterfaceType()),
-        fullWitnessType);
-  };
-
-  /// Visits a requirement type to match it to a potential witness for
-  /// the purpose of deducing associated types.
-  ///
-  /// The visitor argument is the witness type. If there are any
-  /// obvious conflicts between the structure of the two types,
-  /// returns true. The conflict checking is fairly conservative, only
-  /// considering rough structure.
-  class MatchVisitor : public TypeMatcher<MatchVisitor> {
-    NormalProtocolConformance *Conformance;
-    InferredAssociatedTypesByWitness &Inferred;
-
-  public:
-    MatchVisitor(NormalProtocolConformance *conformance,
-                 InferredAssociatedTypesByWitness &inferred)
-      : Conformance(conformance), Inferred(inferred) { }
-
-    /// Structural mismatches imply that the witness cannot match.
-    bool mismatch(TypeBase *firstType, TypeBase *secondType,
-                  Type sugaredFirstType) {
-      // If either type hit an error, don't stop yet.
-      if (firstType->hasError() || secondType->hasError())
-        return true;
-
-      // FIXME: Check whether one of the types is dependent?
-      return false;
-    }
-
-    /// Deduce associated types from dependent member types in the witness.
-    bool mismatch(DependentMemberType *firstDepMember,
-                  TypeBase *secondType, Type sugaredFirstType) {
-      // If the second type is an error, don't look at it further.
-      if (secondType->hasError())
-        return true;
-
-      auto proto = Conformance->getProtocol();
-      if (auto assocType = getReferencedAssocTypeOfProtocol(firstDepMember,
-                                                            proto)) {
-        Inferred.Inferred.push_back({assocType, secondType});
-      }
-
-      // Always allow mismatches here.
-      return true;
-    }
-
-    /// FIXME: Recheck the type of Self against the second type?
-    bool mismatch(GenericTypeParamType *selfParamType,
-                  TypeBase *secondType, Type sugaredFirstType) {
-      return true;
-    }
-  };
-
-  // Match a requirement and witness type.
-  MatchVisitor matchVisitor(Conformance, inferred);
-  auto matchTypes = [&](Type reqType, Type witnessType)
-                      -> Optional<RequirementMatch> {
-    if (!matchVisitor.match(reqType, witnessType)) {
-      return RequirementMatch(witness, MatchKind::TypeConflict,
-                              fullWitnessType);
-    }
-
-    return None;
-  };
-
-  // Finalization of the checking is pretty trivial; just bundle up a
-  // result we can look at.
-  auto finalize = [&](bool anyRenaming, ArrayRef<OptionalAdjustment>)
-                    -> RequirementMatch {
-    return RequirementMatch(witness, 
-                            anyRenaming ? MatchKind::RenamedMatch
-                                        : MatchKind::ExactMatch,
-                            fullWitnessType);
-
-  };
-
-  // Match the witness. If we don't succeed, throw away the inference
-  // information.
-  // FIXME: A renamed match might be useful to retain for the failure case.
-  if (matchWitness(TC, DC, req, witness, setup, matchTypes, finalize)
-          .Kind != MatchKind::ExactMatch) {
-    inferred.Inferred.clear();
-  }
-
-  return inferred;
-}
-
 static void recordConformanceDependency(DeclContext *DC,
                                         NominalTypeDecl *Adoptee,
                                         ProtocolConformance *Conformance,
@@ -3901,7 +2847,8 @@
   addUsedConformances(conformance, visited);
 }
 
-void ConformanceChecker::ensureRequirementsAreSatisfied() {
+void ConformanceChecker::ensureRequirementsAreSatisfied(
+                                                     bool failUnsubstituted) {
   auto proto = Conformance->getProtocol();
   // Some other problem stopped the signature being computed.
   if (!proto->isRequirementSignatureComputed()) {
@@ -3928,13 +2875,14 @@
 
   class GatherConformancesListener : public GenericRequirementsCheckListener {
     TypeChecker &tc;
-    DeclContext *dc;
+    NormalProtocolConformance *conformance;
     std::function<void(ProtocolConformanceRef)> &writer;
   public:
     GatherConformancesListener(
-                         TypeChecker &tc, DeclContext *dc,
+                         TypeChecker &tc,
+                        NormalProtocolConformance *conformance,
                          std::function<void(ProtocolConformanceRef)> &writer)
-      : tc(tc), dc(dc), writer(writer) { }
+      : tc(tc), conformance(conformance), writer(writer) { }
 
     void satisfiedConformance(Type depTy, Type replacementTy,
                               ProtocolConformanceRef conformance) override {
@@ -3966,7 +2914,7 @@
         conformance = *tc.conformsToProtocol(
                          interfaceType,
                          conformance.getRequirement(),
-                         dc,
+                         this->conformance->getDeclContext(),
                          (ConformanceCheckFlags::SuppressDependencyTracking|
                           ConformanceCheckFlags::SkipConditionalRequirements));
 
@@ -3981,7 +2929,18 @@
 
       writer(conformance);
     }
-  } listener(TC, DC, writer);
+
+    bool diagnoseUnsatisfiedRequirement(
+                      const Requirement &req, Type first, Type second,
+                      ArrayRef<ParentConditionalConformance> parents) override {
+      // Invalidate the conformance to suppress further diagnostics.
+      if (conformance->getLoc().isValid()) {
+        conformance->setInvalid();
+      }
+
+      return false;
+    }
+  } listener(TC, Conformance, writer);
 
   auto result = TC.checkGenericArguments(
       DC, Loc, Loc,
@@ -3994,9 +2953,33 @@
       nullptr,
       ConformanceCheckFlags::Used, &listener);
 
-  // If there were errors, mark the conformance as invalid.
-  if (result != RequirementCheckResult::Success) {
+  switch (result) {
+  case RequirementCheckResult::Success:
+    return;
+
+  case RequirementCheckResult::Failure:
     Conformance->setInvalid();
+    return;
+
+  case RequirementCheckResult::UnsatisfiedDependency:
+    llvm_unreachable("Cannot handle unsatisfied dependencies here");
+
+  case RequirementCheckResult::SubstitutionFailure:
+    // If we're not allowed to fail, record this as a partially-checked
+    // conformance.
+    if (!failUnsubstituted) {
+      TC.PartiallyCheckedConformances.insert(Conformance);
+      return;
+    }
+
+    // Diagnose the failure generically.
+    // FIXME: Would be nice to give some more context here!
+    if (!Conformance->isInvalid()) {
+      TC.diagnose(Loc, diag::type_does_not_conform,
+                  Adoptee, Proto->getDeclaredType());
+      Conformance->setInvalid();
+    }
+    return;
   }
 }
 
@@ -4714,6 +3697,19 @@
   checker.checkAllConformances();
 }
 
+void TypeChecker::checkConformanceRequirements(
+                                     NormalProtocolConformance *conformance) {
+  // If the conformance is already invalid, there's nothing to do here.
+  if (conformance->isInvalid())
+    return;
+
+  conformance->setSignatureConformances({ });
+
+  llvm::SetVector<ValueDecl *> globalMissingWitnesses;
+  ConformanceChecker checker(*this, conformance, globalMissingWitnesses);
+  checker.ensureRequirementsAreSatisfied(/*failUnsubstituted=*/true);
+}
+
 /// Determine the score when trying to match two identifiers together.
 static unsigned scoreIdentifiers(Identifier lhs, Identifier rhs,
                                  unsigned limit) {
@@ -5459,20 +4455,6 @@
       }
     }
   }
-
-  // If conditional conformances are disabled, complain about any that
-  // occur.
-  if (!Context.LangOpts.EnableConditionalConformances) {
-    for (auto conformance : conformances) {
-      auto normal = dyn_cast<NormalProtocolConformance>(conformance);
-      if (!normal) continue;
-
-      if (normal->getConditionalRequirements().empty()) continue;
-
-      diagnose(normal->getLoc(), diag::experimental_conditional_conformances,
-               normal->getType(), normal->getProtocol()->getDeclaredType());
-    }
-  }
 }
 
 llvm::TinyPtrVector<ValueDecl *>
@@ -5788,48 +4770,6 @@
   }
 }
 
-bool TypeChecker::isProtocolExtensionUsable(DeclContext *dc, Type type,
-                                            ExtensionDecl *protocolExtension) {
-  using namespace constraints;
-
-  assert(protocolExtension->getAsProtocolExtensionContext() &&
-         "Only intended for protocol extensions");
-
-  resolveExtension(protocolExtension);
-
-  // Dig down to the type we care about.
-  type = type->getInOutObjectType()->getRValueType();
-  if (auto metaTy = type->getAs<AnyMetatypeType>())
-    type = metaTy->getInstanceType();
-
-  // Unconstrained protocol extensions are always usable.
-  if (!protocolExtension->isConstrainedExtension())
-    return true;
-
-  // If the type still has parameters, the constrained extension is considered
-  // unusable.
-  if (type->hasTypeParameter() || type->hasTypeVariable())
-    return false;
-
-  // Set up a constraint system where we open the generic parameters of the
-  // protocol extension.
-  ConstraintSystem cs(*this, dc, None);
-  OpenedTypeMap replacements;
-  auto genericSig = protocolExtension->getGenericSignature();
-  
-  cs.openGeneric(protocolExtension, protocolExtension, genericSig, false,
-                 ConstraintLocatorBuilder(nullptr), replacements);
-
-  // Bind the 'Self' type variable to the provided type.
-  auto selfType = cast<GenericTypeParamType>(
-    genericSig->getGenericParams().back()->getCanonicalType());
-  auto selfTypeVar = replacements[selfType];
-  cs.addConstraint(ConstraintKind::Bind, selfTypeVar, type, nullptr);
-
-  // If we can solve the solution, the protocol extension is usable.
-  return cs.solveSingle().hasValue();
-}
-
 void TypeChecker::recordKnownWitness(NormalProtocolConformance *conformance,
                                      ValueDecl *req, ValueDecl *witness) {
   // Match the witness. This should never fail, but it does allow renaming
diff --git a/lib/Sema/TypeCheckProtocol.h b/lib/Sema/TypeCheckProtocol.h
index e84fac6..375dd9d 100644
--- a/lib/Sema/TypeCheckProtocol.h
+++ b/lib/Sema/TypeCheckProtocol.h
@@ -18,8 +18,10 @@
 #ifndef SWIFT_SEMA_PROTOCOL_H
 #define SWIFT_SEMA_PROTOCOL_H
 
+#include "swift/AST/RequirementEnvironment.h"
 #include "swift/AST/Type.h"
 #include "swift/AST/Types.h"
+#include "swift/AST/Witness.h"
 #include "llvm/ADT/ScopedHashTable.h"
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/SmallPtrSet.h"
@@ -34,6 +36,7 @@
 class NormalProtocolConformance;
 class ProtocolDecl;
 class TypeChecker;
+class TypeRepr;
 class ValueDecl;
 
 /// A conflict between two inferred type witnesses for the same
@@ -136,10 +139,293 @@
 #ifndef NDEBUG
   LLVM_ATTRIBUTE_USED
 #endif
-  void dump();
+  void dump() const;
 };
 
-struct RequirementMatch;
+class RequirementEnvironment;
+
+/// \brief The result of matching a particular declaration to a given
+/// requirement.
+enum class MatchKind : unsigned char {
+  /// \brief The witness matched the requirement exactly.
+  ExactMatch,
+
+  /// \brief There is a difference in optionality.
+  OptionalityConflict,
+
+  /// \brief The witness matched the requirement with some renaming.
+  RenamedMatch,
+
+  /// \brief The witness is invalid or has an invalid type.
+  WitnessInvalid,
+
+  /// \brief The kind of the witness and requirement differ, e.g., one
+  /// is a function and the other is a variable.
+  KindConflict,
+
+  /// \brief The types conflict.
+  TypeConflict,
+
+  /// The witness throws, but the requirement does not.
+  ThrowsConflict,
+
+  /// \brief The witness did not match due to static/non-static differences.
+  StaticNonStaticConflict,
+
+  /// \brief The witness is not settable, but the requirement is.
+  SettableConflict,
+
+  /// \brief The witness did not match due to prefix/non-prefix differences.
+  PrefixNonPrefixConflict,
+
+  /// \brief The witness did not match due to postfix/non-postfix differences.
+  PostfixNonPostfixConflict,
+
+  /// \brief The witness did not match because of mutating conflicts.
+  MutatingConflict,
+
+  /// \brief The witness did not match because of nonmutating conflicts.
+  NonMutatingConflict,
+
+  /// \brief The witness did not match because of __consuming conflicts.
+  ConsumingConflict,
+
+  /// The witness is not rethrows, but the requirement is.
+  RethrowsConflict,
+
+  /// The witness is explicitly @nonobjc but the requirement is @objc.
+  NonObjC,
+};
+
+/// Describes the kind of optional adjustment performed when
+/// comparing two types.
+enum class OptionalAdjustmentKind {
+  // No adjustment required.
+  None,
+
+  /// The witness can produce a 'nil' that won't be handled by
+  /// callers of the requirement. This is a type-safety problem.
+  ProducesUnhandledNil,
+
+  /// Callers of the requirement can provide 'nil', but the witness
+  /// does not handle it. This is a type-safety problem.
+  ConsumesUnhandledNil,
+
+  /// The witness handles 'nil', but won't ever be given a 'nil'.
+  /// This is not a type-safety problem.
+  WillNeverConsumeNil,
+
+  /// Callers of the requirement can expect to receive 'nil', but
+  /// the witness will never produce one. This is not a type-safety
+  /// problem.
+  WillNeverProduceNil,
+
+  /// The witness has an IUO that can be removed, because the
+  /// protocol doesn't need it. This is not a type-safety problem.
+  RemoveIUO,
+
+  /// The witness has an IUO that should be translated into a true
+  /// optional. This is not a type-safety problem.
+  IUOToOptional,
+};
+
+/// Once a witness has been found, there are several reasons it may
+/// not be usable.
+enum class CheckKind : unsigned {
+  /// The witness is OK.
+  Success,
+
+  /// The witness is less accessible than the requirement.
+  Access,
+
+  /// The witness is storage whose setter is less accessible than the
+  /// requirement.
+  AccessOfSetter,
+
+  /// The witness is less available than the requirement.
+  Availability,
+
+  /// The requirement was marked explicitly unavailable.
+  Unavailable,
+
+  /// The witness requires optional adjustments.
+  OptionalityConflict,
+
+  /// The witness is a constructor which is more failable than the
+  /// requirement.
+  ConstructorFailability,
+
+  /// The witness itself is inaccessible.
+  WitnessUnavailable,
+};
+
+/// Describes an optional adjustment made to a witness.
+class OptionalAdjustment {
+  /// The kind of adjustment.
+  unsigned Kind : 16;
+
+  /// Whether this is a parameter adjustment (with an index) vs. a
+  /// result or value type adjustment (no index needed).
+  unsigned IsParameterAdjustment : 1;
+
+  /// The adjustment index, for parameter adjustments.
+  unsigned ParameterAdjustmentIndex : 15;
+
+public:
+  /// Create a non-parameter optional adjustment.
+  explicit OptionalAdjustment(OptionalAdjustmentKind kind)
+    : Kind(static_cast<unsigned>(kind)), IsParameterAdjustment(false),
+      ParameterAdjustmentIndex(0) { }
+
+  /// Create an optional adjustment to a parameter.
+  OptionalAdjustment(OptionalAdjustmentKind kind,
+                     unsigned parameterIndex)
+    : Kind(static_cast<unsigned>(kind)), IsParameterAdjustment(true),
+      ParameterAdjustmentIndex(parameterIndex) { }
+
+  /// Determine the kind of optional adjustment.
+  OptionalAdjustmentKind getKind() const {
+    return static_cast<OptionalAdjustmentKind>(Kind);
+  }
+
+  /// Determine whether this is a parameter adjustment.
+  bool isParameterAdjustment() const {
+    return IsParameterAdjustment;
+  }
+
+  /// Return the index of a parameter adjustment.
+  unsigned getParameterIndex() const {
+    assert(isParameterAdjustment() && "Not a parameter adjustment");
+    return ParameterAdjustmentIndex;
+  }
+
+  /// Determines whether the optional adjustment is an error.
+  bool isError() const {
+    switch (getKind()) {
+    case OptionalAdjustmentKind::None:
+      return false;
+
+    case OptionalAdjustmentKind::ProducesUnhandledNil:
+    case OptionalAdjustmentKind::ConsumesUnhandledNil:
+      return true;
+
+    case OptionalAdjustmentKind::WillNeverConsumeNil:
+    case OptionalAdjustmentKind::WillNeverProduceNil:
+    case OptionalAdjustmentKind::RemoveIUO:
+    case OptionalAdjustmentKind::IUOToOptional:
+      // Warnings at most.
+      return false;
+    }
+
+    llvm_unreachable("Unhandled OptionalAdjustmentKind in switch.");
+  }
+
+  /// Retrieve the source location at which the optional is
+  /// specified or would be inserted.
+  SourceLoc getOptionalityLoc(ValueDecl *witness) const;
+
+  /// Retrieve the optionality location for the given type
+  /// representation.
+  SourceLoc getOptionalityLoc(TypeRepr *tyR) const;
+};
+
+/// \brief Describes a match between a requirement and a witness.
+struct RequirementMatch {
+  RequirementMatch(ValueDecl *witness, MatchKind kind,
+                   Optional<RequirementEnvironment> &&env = None)
+    : Witness(witness), Kind(kind), WitnessType(), ReqEnv(std::move(env)) {
+    assert(!hasWitnessType() && "Should have witness type");
+  }
+
+  RequirementMatch(ValueDecl *witness, MatchKind kind,
+                   Type witnessType,
+                   Optional<RequirementEnvironment> &&env = None,
+                   ArrayRef<OptionalAdjustment> optionalAdjustments = {})
+    : Witness(witness), Kind(kind), WitnessType(witnessType),
+      ReqEnv(std::move(env)),
+      OptionalAdjustments(optionalAdjustments.begin(),
+                          optionalAdjustments.end())
+  {
+    assert(hasWitnessType() == !witnessType.isNull() &&
+           "Should (or should not) have witness type");
+  }
+
+  /// \brief The witness that matches the (implied) requirement.
+  ValueDecl *Witness;
+
+  /// \brief The kind of match.
+  MatchKind Kind;
+
+  /// \brief The type of the witness when it is referenced.
+  Type WitnessType;
+
+  /// \brief The requirement environment to use for the witness thunk.
+  Optional<RequirementEnvironment> ReqEnv;
+
+  /// The set of optional adjustments performed on the witness.
+  SmallVector<OptionalAdjustment, 2> OptionalAdjustments;
+
+  /// Substitutions mapping the type of the witness to the requirement
+  /// environment.
+  SmallVector<Substitution, 2> WitnessSubstitutions;
+
+  /// \brief Determine whether this match is viable.
+  bool isViable() const {
+    switch(Kind) {
+    case MatchKind::ExactMatch:
+    case MatchKind::OptionalityConflict:
+    case MatchKind::RenamedMatch:
+      return true;
+
+    case MatchKind::WitnessInvalid:
+    case MatchKind::KindConflict:
+    case MatchKind::TypeConflict:
+    case MatchKind::StaticNonStaticConflict:
+    case MatchKind::SettableConflict:
+    case MatchKind::PrefixNonPrefixConflict:
+    case MatchKind::PostfixNonPostfixConflict:
+    case MatchKind::MutatingConflict:
+    case MatchKind::NonMutatingConflict:
+    case MatchKind::ConsumingConflict:
+    case MatchKind::RethrowsConflict:
+    case MatchKind::ThrowsConflict:
+    case MatchKind::NonObjC:
+      return false;
+    }
+
+    llvm_unreachable("Unhandled MatchKind in switch.");
+  }
+
+  /// \brief Determine whether this requirement match has a witness type.
+  bool hasWitnessType() const {
+    switch(Kind) {
+    case MatchKind::ExactMatch:
+    case MatchKind::RenamedMatch:
+    case MatchKind::TypeConflict:
+    case MatchKind::OptionalityConflict:
+      return true;
+
+    case MatchKind::WitnessInvalid:
+    case MatchKind::KindConflict:
+    case MatchKind::StaticNonStaticConflict:
+    case MatchKind::SettableConflict:
+    case MatchKind::PrefixNonPrefixConflict:
+    case MatchKind::PostfixNonPostfixConflict:
+    case MatchKind::MutatingConflict:
+    case MatchKind::NonMutatingConflict:
+    case MatchKind::ConsumingConflict:
+    case MatchKind::RethrowsConflict:
+    case MatchKind::ThrowsConflict:
+    case MatchKind::NonObjC:
+      return false;
+    }
+
+    llvm_unreachable("Unhandled MatchKind in switch.");
+  }
+
+  swift::Witness getWitness(ASTContext &ctx) const;
+};
+
 struct RequirementCheck;
 
 class WitnessChecker {
@@ -292,24 +578,6 @@
   ResolveWitnessResult resolveTypeWitnessViaLookup(
                          AssociatedTypeDecl *assocType);
 
-  /// Infer associated type witnesses for the given tentative
-  /// requirement/witness match.
-  InferredAssociatedTypesByWitness inferTypeWitnessesViaValueWitness(
-                                     ValueDecl *req,
-                                     ValueDecl *witness);
-
-  /// Infer associated type witnesses for the given value requirement.
-  InferredAssociatedTypesByWitnesses inferTypeWitnessesViaValueWitnesses(
-                   const llvm::SetVector<AssociatedTypeDecl *> &allUnresolved,
-                   ValueDecl *req);
-
-  /// Infer associated type witnesses for all relevant value requirements.
-  ///
-  /// \param assocTypes The set of associated types we're interested in.
-  InferredAssociatedTypes
-  inferTypeWitnessesViaValueWitnesses(
-    const llvm::SetVector<AssociatedTypeDecl *> &assocTypes);
-
   /// Diagnose or defer a diagnostic, as appropriate.
   ///
   /// \param requirement The requirement with which this diagnostic is
@@ -368,12 +636,18 @@
 
   /// Check all of the protocols requirements are actually satisfied by a
   /// the chosen type witnesses.
-  void ensureRequirementsAreSatisfied();
+  ///
+  /// \param failUnsubstituted Whether to fail when the requirements of the
+  /// protocol could not be substituted (e.g., due to missing information).
+  /// When true, emits a diagnostic in such cases; when false, enqueues the
+  /// conformance for later checking.
+  void ensureRequirementsAreSatisfied(bool failUnsubstituted);
 
   /// Check the entire protocol conformance, ensuring that all
   /// witnesses are resolved and emitting any diagnostics.
   void checkConformance(MissingWitnessDiagnosisKind Kind);
 };
+
 /// Captures the state needed to infer associated types.
 class AssociatedTypeInference {
   /// The type checker we'll need to validate declarations etc.
@@ -421,6 +695,37 @@
                           NormalProtocolConformance *conformance);
 
 private:
+  /// Infer associated type witnesses for the given tentative
+  /// requirement/witness match.
+  InferredAssociatedTypesByWitness inferTypeWitnessesViaValueWitness(
+                                     ValueDecl *req,
+                                     ValueDecl *witness);
+
+  /// Infer associated type witnesses for the given value requirement.
+  InferredAssociatedTypesByWitnesses inferTypeWitnessesViaValueWitnesses(
+                   ConformanceChecker &checker,
+                   const llvm::SetVector<AssociatedTypeDecl *> &allUnresolved,
+                   ValueDecl *req);
+
+  /// Infer associated type witnesses for the given associated type.
+  InferredAssociatedTypesByWitnesses inferTypeWitnessesViaAssociatedType(
+                   ConformanceChecker &checker,
+                   const llvm::SetVector<AssociatedTypeDecl *> &allUnresolved,
+                   AssociatedTypeDecl *assocType);
+
+  /// Infer associated type witnesses for all relevant value requirements.
+  ///
+  /// \param assocTypes The set of associated types we're interested in.
+  InferredAssociatedTypes
+  inferTypeWitnessesViaValueWitnesses(
+    ConformanceChecker &checker,
+    const llvm::SetVector<AssociatedTypeDecl *> &assocTypes);
+
+  /// Compute a "fixed" type witness for an associated type, e.g.,
+  /// if the refined protocol requires it to be equivalent to some other
+  /// concrete type.
+  Type computeFixedTypeWitness(AssociatedTypeDecl *assocType);
+
   /// Compute the default type witness from an associated type default,
   /// if there is one.
   Type computeDefaultTypeWitness(AssociatedTypeDecl *assocType);
@@ -429,12 +734,30 @@
   /// known to the compiler.
   Type computeDerivedTypeWitness(AssociatedTypeDecl *assocType);
 
+  /// Compute a type witness without using a specific potential witness,
+  /// e.g., using a fixed type (from a refined protocol), default type
+  /// on an associated type, or deriving the type.
+  ///
+  /// \param allowDerived Whether to allow "derived" type witnesses.
+  Type computeAbstractTypeWitness(AssociatedTypeDecl *assocType,
+                                  bool allowDerived);
+
   /// Substitute the current type witnesses into the given interface type.
   Type substCurrentTypeWitnesses(Type type);
 
+  /// Retrieve substitution options with a tentative type witness
+  /// operation that queries the current set of type witnesses.
+  SubstOptions getSubstOptionsWithCurrentTypeWitnesses();
+
   /// Check whether the current set of type witnesses meets the
   /// requirements of the protocol.
-  bool checkCurrentTypeWitnesses();
+  bool checkCurrentTypeWitnesses(
+         const SmallVectorImpl<std::pair<ValueDecl *, ValueDecl *>>
+           &valueWitnesses);
+
+  /// Check the current type witnesses against the
+  /// requirements of the given constrained extension.
+  bool checkConstrainedExtension(ExtensionDecl *ext);
 
   /// Top-level operation to find solutions for the given unresolved
   /// associated types.
@@ -495,6 +818,33 @@
   Optional<InferredTypeWitnesses> solve(ConformanceChecker &checker);
 };
 
+/// \brief Match the given witness to the given requirement.
+///
+/// \returns the result of performing the match.
+RequirementMatch matchWitness(
+             TypeChecker &tc,
+             DeclContext *dc, ValueDecl *req, ValueDecl *witness,
+             const std::function<
+                     std::tuple<Optional<RequirementMatch>, Type, Type>(void)>
+               &setup,
+             const std::function<Optional<RequirementMatch>(Type, Type)>
+               &matchTypes,
+             const std::function<
+                     RequirementMatch(bool, ArrayRef<OptionalAdjustment>)
+                   > &finalize);
+
+RequirementMatch matchWitness(TypeChecker &tc,
+                              ProtocolDecl *proto,
+                              ProtocolConformance *conformance,
+                              DeclContext *dc,
+                              ValueDecl *req,
+                              ValueDecl *witness);
+
+/// If the given type is a direct reference to an associated type of
+/// the given protocol, return the referenced associated type.
+AssociatedTypeDecl *getReferencedAssocTypeOfProtocol(Type type,
+                                                     ProtocolDecl *proto);
+
 }
 
 #endif // SWIFT_SEMA_PROTOCOL_H
diff --git a/lib/Sema/TypeCheckProtocolInference.cpp b/lib/Sema/TypeCheckProtocolInference.cpp
index 74b7e29..ffb1263 100644
--- a/lib/Sema/TypeCheckProtocolInference.cpp
+++ b/lib/Sema/TypeCheckProtocolInference.cpp
@@ -21,8 +21,10 @@
 #include "swift/AST/GenericSignature.h"
 #include "swift/AST/ProtocolConformance.h"
 #include "swift/AST/SubstitutionMap.h"
+#include "swift/AST/TypeMatcher.h"
 #include "swift/AST/Types.h"
 #include "swift/Basic/Defer.h"
+#include "swift/ClangImporter/ClangModule.h"
 #include "llvm/ADT/TinyPtrVector.h"
 
 #define DEBUG_TYPE "Associated type inference"
@@ -61,7 +63,7 @@
   out << ")";
 }
 
-void InferredTypeWitnessesSolution::dump() {
+void InferredTypeWitnessesSolution::dump() const {
   llvm::errs() << "Type Witnesses:\n";
   for (auto &typeWitness : TypeWitnesses) {
     llvm::errs() << "  " << typeWitness.first->getName() << " := ";
@@ -124,14 +126,649 @@
                                        NormalProtocolConformance *conformance)
   : tc(tc), conformance(conformance), proto(conformance->getProtocol()),
     dc(conformance->getDeclContext()),
-    adoptee(conformance->getType()) { }
+    adoptee(conformance->getType())
+{
+}
+
+static bool associatedTypesAreSameEquivalenceClass(AssociatedTypeDecl *a,
+                                                   AssociatedTypeDecl *b) {
+  if (a == b)
+    return true;
+
+  // TODO: Do a proper equivalence check here by looking for some relationship
+  // between a and b's protocols. In practice today, it's unlikely that
+  // two same-named associated types can currently be independent, since we
+  // don't have anything like `@implements(P.foo)` to rename witnesses (and
+  // we still fall back to name lookup for witnesses in more cases than we
+  // should).
+  if (a->getName() == b->getName())
+    return true;
+
+  return false;
+}
+
+InferredAssociatedTypesByWitnesses
+AssociatedTypeInference::inferTypeWitnessesViaValueWitnesses(
+                    ConformanceChecker &checker,
+                    const llvm::SetVector<AssociatedTypeDecl *> &allUnresolved,
+                    ValueDecl *req) {
+  // Conformances constructed by the ClangImporter should have explicit type
+  // witnesses already.
+  if (isa<ClangModuleUnit>(conformance->getDeclContext()->getModuleScopeContext())) {
+    llvm::errs() << "Cannot infer associated types for imported conformance:\n";
+    conformance->getType().dump(llvm::errs());
+    for (auto assocTypeDecl : allUnresolved)
+      assocTypeDecl->dump(llvm::errs());
+    abort();
+  }
+
+  InferredAssociatedTypesByWitnesses result;
+
+  auto isExtensionUsableForInference = [&](ExtensionDecl *extension) -> bool {
+    // Assume unconstrained concrete extensions we found witnesses in are
+    // always viable.
+    if (!extension->getExtendedType()->isAnyExistentialType()) {
+      // TODO: When constrained extensions are a thing, we'll need an "is
+      // as specialized as" kind of check here.
+      return !extension->isConstrainedExtension();
+    }
+
+    // The extension may not have a generic signature set up yet, as a
+    // recursion breaker, in which case we can't yet confidently reject its
+    // witnesses.
+    if (!extension->getGenericSignature())
+      return true;
+
+    // The condition here is a bit more fickle than
+    // `isExtensionApplied`. That check would prematurely reject
+    // extensions like `P where AssocType == T` if we're relying on a
+    // default implementation inside the extension to infer `AssocType == T`
+    // in the first place. Only check conformances on the `Self` type,
+    // because those have to be explicitly declared on the type somewhere
+    // so won't be affected by whatever answer inference comes up with.
+    auto selfTy = extension->getSelfInterfaceType();
+    for (const Requirement &reqt
+         : extension->getGenericSignature()->getRequirements()) {
+      switch (reqt.getKind()) {
+      case RequirementKind::Conformance:
+      case RequirementKind::Superclass:
+        // FIXME: This is the wrong check
+        if (selfTy->isEqual(reqt.getFirstType())
+            && !tc.isSubtypeOf(conformance->getType(),reqt.getSecondType(), dc))
+          return false;
+        break;
+
+      case RequirementKind::Layout:
+      case RequirementKind::SameType:
+        break;
+      }
+    }
+
+    return true;
+  };
+
+  auto typeInContext =
+    conformance->getDeclContext()->mapTypeIntoContext(conformance->getType());
+
+  for (auto witness : checker.lookupValueWitnesses(req,
+                                                   /*ignoringNames=*/nullptr)) {
+    DEBUG(llvm::dbgs() << "Inferring associated types from decl:\n";
+          witness->dump(llvm::dbgs()));
+
+    // If the potential witness came from an extension, and our `Self`
+    // type can't use it regardless of what associated types we end up
+    // inferring, skip the witness.
+    if (auto extension = dyn_cast<ExtensionDecl>(witness->getDeclContext()))
+      if (!isExtensionUsableForInference(extension))
+        continue;
+
+    // Try to resolve the type witness via this value witness.
+    auto witnessResult = inferTypeWitnessesViaValueWitness(req, witness);
+
+    // Filter out duplicated inferred types as well as inferred types
+    // that don't meet the requirements placed on the associated type.
+    llvm::DenseSet<std::pair<AssociatedTypeDecl *, CanType>> known;
+    for (unsigned i = 0; i < witnessResult.Inferred.size(); /*nothing*/) {
+#define REJECT {\
+  witnessResult.Inferred.erase(witnessResult.Inferred.begin() + i); \
+  continue; \
+}
+      auto &result = witnessResult.Inferred[i];
+
+      DEBUG(llvm::dbgs() << "Considering whether " << result.first->getName()
+                         << " can infer to:\n";
+            result.second->dump(llvm::dbgs()));
+
+      // Filter out errors.
+      if (result.second->hasError()) {
+        DEBUG(llvm::dbgs() << "-- has error type\n");
+        REJECT;
+      }
+
+      // Filter out duplicates.
+      if (!known.insert({result.first, result.second->getCanonicalType()})
+                .second) {
+        DEBUG(llvm::dbgs() << "-- duplicate\n");
+        REJECT;
+      }
+
+      // Filter out circular possibilities, e.g. that
+      // AssocType == S.AssocType or
+      // AssocType == Foo<S.AssocType>.
+      bool canInferFromOtherAssociatedType = false;
+      bool containsTautologicalType =
+        result.second.findIf([&](Type t) -> bool {
+          auto dmt = t->getAs<DependentMemberType>();
+          if (!dmt)
+            return false;
+          if (!associatedTypesAreSameEquivalenceClass(dmt->getAssocType(),
+                                                      result.first))
+            return false;
+          if (!dmt->getBase()->isEqual(typeInContext))
+            return false;
+
+          // If this associated type is same-typed to another associated type
+          // on `Self`, then it may still be an interesting candidate if we find
+          // an answer for that other type.
+          auto witnessContext = witness->getDeclContext();
+          if (witnessContext->getAsProtocolExtensionContext()
+              && witnessContext->getGenericSignatureOfContext()) {
+            auto selfTy = witnessContext->getSelfInterfaceType();
+            auto selfAssocTy = DependentMemberType::get(selfTy,
+                                                        dmt->getAssocType());
+            for (auto &reqt : witnessContext->getGenericSignatureOfContext()
+                                            ->getRequirements()) {
+              switch (reqt.getKind()) {
+              case RequirementKind::Conformance:
+              case RequirementKind::Superclass:
+              case RequirementKind::Layout:
+                break;
+
+              case RequirementKind::SameType:
+                Type other;
+                if (reqt.getFirstType()->isEqual(selfAssocTy)) {
+                  other = reqt.getSecondType();
+                } else if (reqt.getSecondType()->isEqual(selfAssocTy)) {
+                  other = reqt.getFirstType();
+                } else {
+                  break;
+                }
+
+                if (auto otherAssoc = other->getAs<DependentMemberType>()) {
+                  if (otherAssoc->getBase()->isEqual(selfTy)) {
+                    auto otherDMT = DependentMemberType::get(dmt->getBase(),
+                                                    otherAssoc->getAssocType());
+
+                    // We may be able to infer one associated type from the
+                    // other.
+                    result.second = result.second.transform([&](Type t) -> Type{
+                      if (t->isEqual(dmt))
+                        return otherDMT;
+                      return t;
+                    });
+                    canInferFromOtherAssociatedType = true;
+                    DEBUG(llvm::dbgs() << "++ we can same-type to:\n";
+                          result.second->dump(llvm::dbgs()));
+                    return false;
+                  }
+                }
+                break;
+              }
+            }
+          }
+
+          return true;
+        });
+
+      if (containsTautologicalType) {
+        DEBUG(llvm::dbgs() << "-- tautological\n");
+        REJECT;
+      }
+
+      // Check that the type witness doesn't contradict an
+      // explicitly-given type witness. If it does contradict, throw out the
+      // witness completely.
+      if (!allUnresolved.count(result.first)) {
+        auto existingWitness =
+        conformance->getTypeWitness(result.first, nullptr);
+        existingWitness = dc->mapTypeIntoContext(existingWitness);
+
+        // If the deduced type contains an irreducible
+        // DependentMemberType, that indicates a dependency
+        // on another associated type we haven't deduced,
+        // so we can't tell whether there's a contradiction
+        // yet.
+        auto newWitness = result.second->getCanonicalType();
+        if (!newWitness->hasTypeParameter() &&
+            !newWitness->hasDependentMember() &&
+            !existingWitness->isEqual(newWitness)) {
+          DEBUG(llvm::dbgs() << "** contradicts explicit type witness, "
+                                "rejecting inference from this decl\n");
+          goto next_witness;
+        }
+      }
+
+      // If we same-typed to another unresolved associated type, we won't
+      // be able to check conformances yet.
+      if (!canInferFromOtherAssociatedType) {
+        // Check that the type witness meets the
+        // requirements on the associated type.
+        if (auto failed = checkTypeWitness(tc, dc, proto, result.first,
+                                           result.second)) {
+          witnessResult.NonViable.push_back(
+                          std::make_tuple(result.first,result.second,failed));
+          DEBUG(llvm::dbgs() << "-- doesn't fulfill requirements\n");
+          REJECT;
+        }
+      }
+
+      DEBUG(llvm::dbgs() << "++ seems legit\n");
+      ++i;
+    }
+#undef REJECT
+
+    // If no inferred types remain, skip this witness.
+    if (witnessResult.Inferred.empty() && witnessResult.NonViable.empty())
+      continue;
+
+    // If there were any non-viable inferred associated types, don't
+    // infer anything from this witness.
+    if (!witnessResult.NonViable.empty())
+      witnessResult.Inferred.clear();
+
+    result.push_back(std::move(witnessResult));
+next_witness:;
+  }
+
+  return result;
+}
+
+InferredAssociatedTypes
+AssociatedTypeInference::inferTypeWitnessesViaValueWitnesses(
+  ConformanceChecker &checker,
+  const llvm::SetVector<AssociatedTypeDecl *> &assocTypes)
+{
+  InferredAssociatedTypes result;
+  for (auto member : proto->getMembers()) {
+    auto req = dyn_cast<ValueDecl>(member);
+    if (!req)
+      continue;
+
+    // Infer type witnesses for associated types.
+    if (auto assocType = dyn_cast<AssociatedTypeDecl>(req)) {
+      // If this is not one of the associated types we are trying to infer,
+      // just continue.
+      if (assocTypes.count(assocType) == 0)
+        continue;
+
+      auto reqInferred = inferTypeWitnessesViaAssociatedType(checker,
+                                                             assocTypes,
+                                                             assocType);
+      if (!reqInferred.empty())
+        result.push_back({req, std::move(reqInferred)});
+
+      continue;
+    }
+
+    // Skip operator requirements, because they match globally and
+    // therefore tend to cause deduction mismatches.
+    // FIXME: If we had some basic sanity checking of Self, we might be able to
+    // use these.
+    if (auto func = dyn_cast<FuncDecl>(req)) {
+      if (func->isOperator() || func->isAccessor())
+        continue;
+    }
+
+    // Validate the requirement.
+    tc.validateDecl(req);
+    if (req->isInvalid() || !req->hasValidSignature())
+      continue;
+
+    // Check whether any of the associated types we care about are
+    // referenced in this value requirement.
+    bool anyAssocTypeMatches = false;
+    for (auto assocType : checker.getReferencedAssociatedTypes(req)) {
+      if (assocTypes.count(assocType) > 0) {
+        anyAssocTypeMatches = true;
+        break;
+      }
+    }
+
+    // We cannot deduce anything from the witnesses of this
+    // requirement; skip it.
+    if (!anyAssocTypeMatches)
+      continue;
+
+    // Infer associated types from the potential value witnesses for
+    // this requirement.
+    auto reqInferred =
+      inferTypeWitnessesViaValueWitnesses(checker, assocTypes, req);
+    if (reqInferred.empty())
+      continue;
+
+    result.push_back({req, std::move(reqInferred)});
+  }
+
+  return result;
+}
+
+/// Map error types back to their original types.
+static Type mapErrorTypeToOriginal(Type type) {
+  if (auto errorType = type->getAs<ErrorType>()) {
+    if (auto originalType = errorType->getOriginalType())
+      return originalType.transform(mapErrorTypeToOriginal);
+  }
+
+  return type;
+}
+
+/// Produce the type when matching a witness.
+static Type getWitnessTypeForMatching(TypeChecker &tc,
+                                      NormalProtocolConformance *conformance,
+                                      ValueDecl *witness) {
+  if (!witness->hasInterfaceType())
+    tc.validateDecl(witness);
+
+  if (witness->isInvalid() || !witness->hasValidSignature())
+    return Type();
+
+  if (!witness->getDeclContext()->isTypeContext()) {
+    // FIXME: Could we infer from 'Self' to make these work?
+    return witness->getInterfaceType();
+  }
+
+  // Retrieve the set of substitutions to be applied to the witness.
+  Type model =
+    conformance->getDeclContext()->mapTypeIntoContext(conformance->getType());
+  TypeSubstitutionMap substitutions = model->getMemberSubstitutions(witness);
+  Type type = witness->getInterfaceType()->getReferenceStorageReferent();
+
+  if (substitutions.empty())
+    return type;
+
+  // Strip off the requirements of a generic function type.
+  // FIXME: This doesn't actually break recursion when substitution
+  // looks for an inferred type witness, but it makes it far less
+  // common, because most of the recursion involves the requirements
+  // of the generic type.
+  if (auto genericFn = type->getAs<GenericFunctionType>()) {
+    type = FunctionType::get(genericFn->getInput(),
+                             genericFn->getResult(),
+                             genericFn->getExtInfo());
+  }
+
+  // Remap associated types that reference other protocols into this
+  // protocol.
+  auto proto = conformance->getProtocol();
+  type = type.transformRec([proto](TypeBase *type) -> Optional<Type> {
+    if (auto depMemTy = dyn_cast<DependentMemberType>(type)) {
+      if (depMemTy->getAssocType() &&
+          depMemTy->getAssocType()->getProtocol() != proto) {
+        for (auto member : proto->lookupDirect(depMemTy->getName())) {
+          if (auto assocType = dyn_cast<AssociatedTypeDecl>(member)) {
+            auto origProto = depMemTy->getAssocType()->getProtocol();
+            if (proto->inheritsFrom(origProto))
+              return Type(DependentMemberType::get(depMemTy->getBase(),
+                                                   assocType));
+          }
+        }
+      }
+    }
+
+    return None;
+  });
+
+  ModuleDecl *module = conformance->getDeclContext()->getParentModule();
+  auto resultType = type.subst(QueryTypeSubstitutionMap{substitutions},
+                               LookUpConformanceInModule(module),
+                               SubstFlags::UseErrorType);
+  if (!resultType->hasError()) return resultType;
+
+  // Map error types with original types *back* to the original, dependent type.
+  return resultType.transform(mapErrorTypeToOriginal);
+}
+
+
+/// Remove the 'self' type from the given type, if it's a method type.
+static Type removeSelfParam(ValueDecl *value, Type type) {
+  if (auto func = dyn_cast<AbstractFunctionDecl>(value)) {
+    if (func->getDeclContext()->isTypeContext())
+      return type->castTo<AnyFunctionType>()->getResult();
+  }
+
+  return type;
+}
+
+InferredAssociatedTypesByWitnesses
+AssociatedTypeInference::inferTypeWitnessesViaAssociatedType(
+                   ConformanceChecker &checker,
+                   const llvm::SetVector<AssociatedTypeDecl *> &allUnresolved,
+                   AssociatedTypeDecl *assocType) {
+  auto &tc = checker.TC;
+
+  // Form the default name _Default_Foo.
+  Identifier defaultName;
+  {
+    SmallString<32> defaultNameStr;
+    {
+      llvm::raw_svector_ostream out(defaultNameStr);
+      out << "_Default_";
+      out << assocType->getName().str();
+    }
+
+    defaultName = tc.Context.getIdentifier(defaultNameStr);
+  }
+
+  // Look for types with the given default name that have appropriate
+  // @_implements attributes.
+  InferredAssociatedTypesByWitnesses result;
+  auto lookupOptions = defaultMemberTypeLookupOptions;
+  lookupOptions -= NameLookupFlags::PerformConformanceCheck;
+  for (auto candidate : tc.lookupMember(dc, adoptee, defaultName,
+                                        lookupOptions)) {
+    // We want type declarations.
+    auto typeDecl = dyn_cast<TypeDecl>(candidate.getValueDecl());
+    if (!typeDecl || isa<AssociatedTypeDecl>(typeDecl))
+      continue;
+
+    // We only find these within a protocol extension.
+    auto defaultProto = typeDecl->getDeclContext()
+                          ->getAsProtocolOrProtocolExtensionContext();
+    if (!defaultProto)
+      continue;
+
+    // Determine the witness type.
+    Type witnessType = getWitnessTypeForMatching(tc, conformance, typeDecl);
+    if (!witnessType) continue;
+
+    if (auto witnessMetaType = witnessType->getAs<AnyMetatypeType>())
+      witnessType = witnessMetaType->getInstanceType();
+    else
+      continue;
+
+    // Add this result.
+    InferredAssociatedTypesByWitness inferred;
+    inferred.Witness = typeDecl;
+    inferred.Inferred.push_back({assocType, witnessType});
+    result.push_back(std::move(inferred));
+  }
+
+  return result;
+}
+
+/// Attempt to resolve a type witness via a specific value witness.
+InferredAssociatedTypesByWitness
+AssociatedTypeInference::inferTypeWitnessesViaValueWitness(ValueDecl *req,
+                                                           ValueDecl *witness) {
+  InferredAssociatedTypesByWitness inferred;
+  inferred.Witness = witness;
+
+  // Compute the requirement and witness types we'll use for matching.
+  Type fullWitnessType = getWitnessTypeForMatching(tc, conformance, witness);
+  if (!fullWitnessType) {
+    return inferred;
+  }
+
+  auto setup = [&]() -> std::tuple<Optional<RequirementMatch>, Type, Type> {
+    fullWitnessType = removeSelfParam(witness, fullWitnessType);
+    return std::make_tuple(
+        None,
+        removeSelfParam(req, req->getInterfaceType()),
+        fullWitnessType);
+  };
+
+  /// Visits a requirement type to match it to a potential witness for
+  /// the purpose of deducing associated types.
+  ///
+  /// The visitor argument is the witness type. If there are any
+  /// obvious conflicts between the structure of the two types,
+  /// returns true. The conflict checking is fairly conservative, only
+  /// considering rough structure.
+  class MatchVisitor : public TypeMatcher<MatchVisitor> {
+    NormalProtocolConformance *Conformance;
+    InferredAssociatedTypesByWitness &Inferred;
+
+  public:
+    MatchVisitor(NormalProtocolConformance *conformance,
+                 InferredAssociatedTypesByWitness &inferred)
+      : Conformance(conformance), Inferred(inferred) { }
+
+    /// Structural mismatches imply that the witness cannot match.
+    bool mismatch(TypeBase *firstType, TypeBase *secondType,
+                  Type sugaredFirstType) {
+      // If either type hit an error, don't stop yet.
+      if (firstType->hasError() || secondType->hasError())
+        return true;
+
+      // FIXME: Check whether one of the types is dependent?
+      return false;
+    }
+
+    /// Deduce associated types from dependent member types in the witness.
+    bool mismatch(DependentMemberType *firstDepMember,
+                  TypeBase *secondType, Type sugaredFirstType) {
+      // If the second type is an error, don't look at it further.
+      if (secondType->hasError())
+        return true;
+
+      auto proto = Conformance->getProtocol();
+      if (auto assocType = getReferencedAssocTypeOfProtocol(firstDepMember,
+                                                            proto)) {
+        Inferred.Inferred.push_back({assocType, secondType});
+      }
+
+      // Always allow mismatches here.
+      return true;
+    }
+
+    /// FIXME: Recheck the type of Self against the second type?
+    bool mismatch(GenericTypeParamType *selfParamType,
+                  TypeBase *secondType, Type sugaredFirstType) {
+      return true;
+    }
+  };
+
+  // Match a requirement and witness type.
+  MatchVisitor matchVisitor(conformance, inferred);
+  auto matchTypes = [&](Type reqType, Type witnessType)
+                      -> Optional<RequirementMatch> {
+    if (!matchVisitor.match(reqType, witnessType)) {
+      return RequirementMatch(witness, MatchKind::TypeConflict,
+                              fullWitnessType);
+    }
+
+    return None;
+  };
+
+  // Finalization of the checking is pretty trivial; just bundle up a
+  // result we can look at.
+  auto finalize = [&](bool anyRenaming, ArrayRef<OptionalAdjustment>)
+                    -> RequirementMatch {
+    return RequirementMatch(witness,
+                            anyRenaming ? MatchKind::RenamedMatch
+                                        : MatchKind::ExactMatch,
+                            fullWitnessType);
+
+  };
+
+  // Match the witness. If we don't succeed, throw away the inference
+  // information.
+  // FIXME: A renamed match might be useful to retain for the failure case.
+  if (matchWitness(tc, dc, req, witness, setup, matchTypes, finalize)
+          .Kind != MatchKind::ExactMatch) {
+    inferred.Inferred.clear();
+  }
+
+  return inferred;
+}
+
+/// Find an associated type declarations that provides a default definition.
+static AssociatedTypeDecl *findDefaultedAssociatedType(
+                                             TypeChecker &tc,
+                                             AssociatedTypeDecl *assocType) {
+  // If this associated type has a default, we're done.
+  tc.validateDecl(assocType);
+  if (!assocType->getDefaultDefinitionLoc().isNull())
+    return assocType;
+
+  // Look at overridden associated types.
+  SmallPtrSet<CanType, 4> canonicalTypes;
+  SmallVector<AssociatedTypeDecl *, 2> results;
+  for (auto overridden : assocType->getOverriddenDecls()) {
+    auto overriddenDefault = findDefaultedAssociatedType(tc, overridden);
+    if (!overriddenDefault) continue;
+
+    Type overriddenType =
+      overriddenDefault->getDefaultDefinitionLoc().getType();
+    assert(overriddenType);
+    if (!overriddenType) continue;
+
+    CanType key = overriddenType->mapTypeOutOfContext()->getCanonicalType();
+    if (canonicalTypes.insert(key).second)
+      results.push_back(overriddenDefault);
+  }
+
+  // If there was a single result, return it.
+  // FIXME: We could find *all* of the non-covered, defaulted associated types.
+  return results.size() == 1 ? results.front() : nullptr;
+}
+
+Type AssociatedTypeInference::computeFixedTypeWitness(
+                                            AssociatedTypeDecl *assocType) {
+  // Look at all of the inherited protocols to determine whether they
+  // require a fixed type for this associated type.
+  Type dependentType = assocType->getDeclaredInterfaceType();
+  Type resultType;
+  for (auto conformedProto : adoptee->getAnyNominal()->getAllProtocols()) {
+    if (!conformedProto->inheritsFrom(assocType->getProtocol()))
+      continue;
+
+    auto genericSig = conformedProto->getGenericSignature();
+    if (!genericSig) return Type();
+
+    Type concreteType = genericSig->getConcreteType(dependentType);
+    if (!concreteType) continue;
+
+    if (!resultType) {
+      resultType = concreteType;
+      continue;
+    }
+
+    // FIXME: Bailing out on ambiguity.
+    if (!resultType->isEqual(concreteType))
+      return Type();
+  }
+
+  return resultType;
+}
 
 Type AssociatedTypeInference::computeDefaultTypeWitness(
                                               AssociatedTypeDecl *assocType) {
-  // If we don't have a default definition, we're done.
-  if (assocType->getDefaultDefinitionLoc().isNull())
-    return Type();
+  // Go find a default definition.
+  auto defaultedAssocType = findDefaultedAssociatedType(tc, assocType);
+  if (!defaultedAssocType) return Type();
 
+  // If we don't have a default definition, we're done.
   auto selfType = proto->getSelfInterfaceType();
 
   // Create a set of type substitutions for all known associated type.
@@ -158,13 +795,20 @@
     }
   }
 
-  tc.validateDecl(assocType);
-  Type defaultType = assocType->getDefaultDefinitionLoc().getType();
+  Type defaultType = defaultedAssocType->getDefaultDefinitionLoc().getType();
 
   // FIXME: Circularity
   if (!defaultType)
     return Type();
 
+  // If the associated type came from a different protocol, map it into our
+  // protocol's context.
+  if (defaultedAssocType->getDeclContext() != proto) {
+    defaultType = defaultType->mapTypeOutOfContext();
+    defaultType = proto->mapTypeIntoContext(defaultType);
+    if (!defaultType) return Type();
+  }
+
   defaultType = defaultType.subst(
                           QueryTypeSubstitutionMap{substitutions},
                           LookUpConformanceInModule(dc->getParentModule()));
@@ -175,7 +819,7 @@
   if (auto failed = checkTypeWitness(tc, dc, proto, assocType, defaultType)) {
     // Record the failure, if we haven't seen one already.
     if (!failedDefaultedAssocType) {
-      failedDefaultedAssocType = assocType;
+      failedDefaultedAssocType = defaultedAssocType;
       failedDefaultedWitness = defaultType;
       failedDefaultedResult = failed;
     }
@@ -213,6 +857,42 @@
   return derivedType;
 }
 
+Type
+AssociatedTypeInference::computeAbstractTypeWitness(
+                                              AssociatedTypeDecl *assocType,
+                                              bool allowDerived) {
+  // We don't have a type witness for this associated type, so go
+  // looking for more options.
+  if (Type concreteType = computeFixedTypeWitness(assocType))
+    return concreteType;
+
+  // If we can form a default type, do so.
+  if (Type defaultType = computeDefaultTypeWitness(assocType))
+    return defaultType;
+
+  // If we can derive a type witness, do so.
+  if (allowDerived) {
+    if (Type derivedType = computeDerivedTypeWitness(assocType))
+      return derivedType;
+  }
+
+  // If there is a generic parameter of the named type, use that.
+  if (auto gpList = dc->getGenericParamsOfContext()) {
+    GenericTypeParamDecl *foundGP = nullptr;
+    for (auto gp : *gpList) {
+      if (gp->getName() == assocType->getName()) {
+        foundGP = gp;
+        break;
+      }
+    }
+
+    if (foundGP)
+      return dc->mapTypeIntoContext(foundGP->getDeclaredInterfaceType());
+  }
+
+  return Type();
+}
+
 Type AssociatedTypeInference::substCurrentTypeWitnesses(Type type) {
   // Local function that folds dependent member types with non-dependent
   // bases into actual member references.
@@ -324,7 +1004,44 @@
   }
 }
 
-bool AssociatedTypeInference::checkCurrentTypeWitnesses() {
+SubstOptions
+AssociatedTypeInference::getSubstOptionsWithCurrentTypeWitnesses() {
+  SubstOptions options(None);
+  AssociatedTypeInference *self = this;
+  options.getTentativeTypeWitness =
+    [self](const NormalProtocolConformance *conformance,
+           AssociatedTypeDecl *assocType) -> TypeBase * {
+      auto thisProto = self->conformance->getProtocol();
+      if (conformance == self->conformance) {
+        // Okay: we have the associated type we need.
+      } else if (conformance->getType()->isEqual(
+                   self->conformance->getType()) &&
+                 thisProto->inheritsFrom(conformance->getProtocol())) {
+        // Find an associated type with the same name in the given
+        // protocol.
+        AssociatedTypeDecl *foundAssocType = nullptr;
+        for (auto result : thisProto->lookupDirect(
+                                             assocType->getName(),
+                                             /*ignoreNewExtensions=*/true)) {
+          foundAssocType = dyn_cast<AssociatedTypeDecl>(result);
+          if (foundAssocType) break;
+        }
+
+      if (!foundAssocType) return nullptr;
+      assocType = foundAssocType;
+    } else {
+      return nullptr;
+    }
+
+    Type type = self->typeWitnesses.begin(assocType)->first;
+    return type->mapTypeOutOfContext().getPointer();
+  };
+  return options;
+}
+
+bool AssociatedTypeInference::checkCurrentTypeWitnesses(
+       const SmallVectorImpl<std::pair<ValueDecl *, ValueDecl *>>
+         &valueWitnesses) {
   // Fold the dependent member types within this type.
   for (auto assocType : proto->getAssociatedTypeMembers()) {
     if (conformance->hasTypeWitness(assocType))
@@ -350,15 +1067,7 @@
   if (!proto->isRequirementSignatureComputed()) return false;
 
   // Check any same-type requirements in the protocol's requirement signature.
-  SubstOptions options(None);
-  options.getTentativeTypeWitness =
-    [&](const NormalProtocolConformance *conformance,
-        AssociatedTypeDecl *assocType) -> TypeBase * {
-      if (conformance != this->conformance) return nullptr;
-
-      auto type = typeWitnesses.begin(assocType)->first;
-      return type->mapTypeOutOfContext().getPointer();
-    };
+  SubstOptions options = getSubstOptionsWithCurrentTypeWitnesses();
 
   auto typeInContext = dc->mapTypeIntoContext(adoptee);
 
@@ -385,12 +1094,55 @@
 
   case RequirementCheckResult::Success:
   case RequirementCheckResult::SubstitutionFailure:
-    return false;
+    break;
+  }
+
+  // Check for extra requirements in the constrained extensions that supply
+  // defaults.
+  SmallPtrSet<ExtensionDecl *, 4> checkedExtensions;
+  for (const auto &valueWitness : valueWitnesses) {
+    // We only perform this additional checking for default associated types.
+    if (!isa<TypeDecl>(valueWitness.first)) continue;
+
+    auto witness = valueWitness.second;
+    if (!witness) continue;
+
+    auto ext = dyn_cast<ExtensionDecl>(witness->getDeclContext());
+    if (!ext) continue;
+
+    if (!ext->isConstrainedExtension()) continue;
+    if (!checkedExtensions.insert(ext).second) continue;
+
+    if (checkConstrainedExtension(ext)) return true;
   }
 
   return false;
 }
 
+bool AssociatedTypeInference::checkConstrainedExtension(ExtensionDecl *ext) {
+  auto typeInContext = dc->mapTypeIntoContext(adoptee);
+  auto subs = typeInContext->getContextSubstitutions(ext);
+
+  SubstOptions options = getSubstOptionsWithCurrentTypeWitnesses();
+  switch (tc.checkGenericArguments(
+                       dc, SourceLoc(), SourceLoc(), adoptee,
+                       ext->getGenericSignature()->getGenericParams(),
+                       ext->getGenericSignature()->getRequirements(),
+                       QueryTypeSubstitutionMap{subs},
+                       LookUpConformanceInModule(ext->getModuleContext()),
+                                   nullptr, ConformanceCheckFlags::InExpression,
+                                   nullptr,
+                                   options)) {
+  case RequirementCheckResult::Success:
+  case RequirementCheckResult::SubstitutionFailure:
+    return false;
+
+  case RequirementCheckResult::Failure:
+  case RequirementCheckResult::UnsatisfiedDependency:
+    return true;
+  }
+}
+
 void AssociatedTypeInference::findSolutions(
                    ArrayRef<AssociatedTypeDecl *> unresolvedAssocTypes,
                    SmallVectorImpl<InferredTypeWitnessesSolution> &solutions) {
@@ -434,55 +1186,26 @@
         continue;
       }
 
-      // We don't have a type witness for this associated type.
-
-      // If we can form a default type, do so.
-      if (Type defaultType = computeDefaultTypeWitness(assocType)) {
-        if (defaultType->hasError()) {
+      // Try to compute the type without the aid of a specific potential
+      // witness.
+      if (Type type = computeAbstractTypeWitness(assocType,
+                                                 /*allowDerived=*/true)) {
+        if (type->hasError()) {
           recordMissing();
           return;
         }
 
-        typeWitnesses.insert(assocType, {defaultType, reqDepth});
+        typeWitnesses.insert(assocType, {type, reqDepth});
         continue;
       }
 
-      // If we can derive a type witness, do so.
-      if (Type derivedType = computeDerivedTypeWitness(assocType)) {
-        if (derivedType->hasError()) {
-          recordMissing();
-          return;
-        }
-
-        typeWitnesses.insert(assocType, {derivedType, reqDepth});
-        continue;
-      }
-
-      // If there is a generic parameter of the named type, use that.
-      if (auto gpList = dc->getGenericParamsOfContext()) {
-        GenericTypeParamDecl *foundGP = nullptr;
-        for (auto gp : *gpList) {
-          if (gp->getName() == assocType->getName()) {
-            foundGP = gp;
-            break;
-          }
-        }
-
-        if (foundGP) {
-          auto gpType = dc->mapTypeIntoContext(
-                          foundGP->getDeclaredInterfaceType());
-          typeWitnesses.insert(assocType, {gpType, reqDepth});
-          continue;
-        }
-      }
-
       // The solution is incomplete.
       recordMissing();
       return;
     }
 
     /// Check the current set of type witnesses.
-    bool invalid = checkCurrentTypeWitnesses();
+    bool invalid = checkCurrentTypeWitnesses(valueWitnesses);
 
     // Determine whether there is already a solution with the same
     // bindings.
@@ -525,17 +1248,50 @@
   // looking for solutions involving each one.
   const auto &inferredReq = inferred[reqDepth];
   for (const auto &witnessReq : inferredReq.second) {
+    llvm::SaveAndRestore<unsigned> savedNumTypeWitnesses(numTypeWitnesses);
+
+    // If we inferred a type witness via a default, try both with and without
+    // the default.
+    if (isa<TypeDecl>(inferredReq.first)) {
+      // Recurse without considering this type.
+      valueWitnesses.push_back({inferredReq.first, nullptr});
+      findSolutionsRec(unresolvedAssocTypes, solutions, nonViableSolutions,
+                       valueWitnesses, numTypeWitnesses,
+                       numValueWitnessesInProtocolExtensions, reqDepth + 1);
+      valueWitnesses.pop_back();
+
+      ++numTypeWitnesses;
+      for (const auto &typeWitness : witnessReq.Inferred) {
+        auto known = typeWitnesses.begin(typeWitness.first);
+        if (known != typeWitnesses.end()) continue;
+
+        // Enter a new scope for the type witnesses hash table.
+        TypeWitnessesScope typeWitnessesScope(typeWitnesses);
+        typeWitnesses.insert(typeWitness.first, {typeWitness.second, reqDepth});
+
+        valueWitnesses.push_back({inferredReq.first, witnessReq.Witness});
+        findSolutionsRec(unresolvedAssocTypes, solutions, nonViableSolutions,
+                         valueWitnesses, numTypeWitnesses,
+                         numValueWitnessesInProtocolExtensions, reqDepth + 1);
+        valueWitnesses.pop_back();
+      }
+
+      continue;
+    }
+
     // Enter a new scope for the type witnesses hash table.
     TypeWitnessesScope typeWitnessesScope(typeWitnesses);
-    llvm::SaveAndRestore<unsigned> savedNumTypeWitnesses(numTypeWitnesses);
 
     // Record this value witness, popping it when we exit the current scope.
     valueWitnesses.push_back({inferredReq.first, witnessReq.Witness});
-    if (witnessReq.Witness->getDeclContext()->getAsProtocolExtensionContext())
+    if (!isa<TypeDecl>(inferredReq.first) &&
+        witnessReq.Witness->getDeclContext()->getAsProtocolExtensionContext())
       ++numValueWitnessesInProtocolExtensions;
     SWIFT_DEFER {
-      if (witnessReq.Witness->getDeclContext()->getAsProtocolExtensionContext())
+      if (!isa<TypeDecl>(inferredReq.first) &&
+          witnessReq.Witness->getDeclContext()->getAsProtocolExtensionContext())
         --numValueWitnessesInProtocolExtensions;
+
       valueWitnesses.pop_back();
     };
 
@@ -546,7 +1302,11 @@
       // conflicts, there is no solution.
       auto known = typeWitnesses.begin(typeWitness.first);
       if (known != typeWitnesses.end()) {
-        // If witnesses for two difference requirements inferred the same
+        // Don't overwrite a defaulted associated type witness.
+        if (isa<TypeDecl>(valueWitnesses[known->second].second))
+          continue;
+
+        // If witnesses for two different requirements inferred the same
         // type, we're okay.
         if (known->first->isEqual(typeWitness.second))
           continue;
@@ -608,6 +1368,22 @@
   // consider these unordered since neither extension's generic signature
   // is a superset of the other.
 
+  // If one of the declarations is null, it implies that we're working with
+  // a skipped associated type default. Prefer that default to something
+  // that came from a protocol extension.
+  if (!decl1 || !decl2) {
+    if (!decl1 &&
+        decl2 && decl2->getDeclContext()->getAsProtocolExtensionContext())
+      return Comparison::Worse;
+
+    if (!decl2 &&
+        decl1 && decl1->getDeclContext()->getAsProtocolExtensionContext())
+      return Comparison::Better;
+
+    return Comparison::Unordered;
+  }
+
+
   // If the witnesses come from the same decl context, score normally.
   auto dc1 = decl1->getDeclContext();
   auto dc2 = decl2->getDeclContext();
@@ -1068,7 +1844,8 @@
     return result;
 
   // Infer potential type witnesses from value witnesses.
-  inferred = checker.inferTypeWitnessesViaValueWitnesses(unresolvedAssocTypes);
+  inferred = inferTypeWitnessesViaValueWitnesses(checker,
+                                                 unresolvedAssocTypes);
   DEBUG(llvm::dbgs() << "Candidates for inference:\n";
         dumpInferredAssociatedTypes(inferred));
 
@@ -1141,7 +1918,7 @@
   SWIFT_DEFER {
     // Resolution attempts to have the witnesses be correct by construction, but
     // this isn't guaranteed, so let's double check.
-    ensureRequirementsAreSatisfied();
+    ensureRequirementsAreSatisfied(/*failUnsubstituted=*/false);
   };
 
   // Attempt to infer associated type witnesses.
@@ -1150,10 +1927,10 @@
     for (const auto &inferredWitness : *inferred) {
       recordTypeWitness(inferredWitness.first, inferredWitness.second,
                         /*typeDecl=*/nullptr,
-      /*performRedeclarationCheck=*/true);
+                        /*performRedeclarationCheck=*/true);
     }
 
-    ensureRequirementsAreSatisfied();
+    ensureRequirementsAreSatisfied(/*failUnsubstituted=*/false);
     return;
   }
 
@@ -1169,11 +1946,6 @@
 
     recordTypeWitness(assocType, ErrorType::get(TC.Context), nullptr, true);
   }
-
-  return;
-
-  // Multiple solutions. Diagnose the ambiguity.
-
 }
 
 void ConformanceChecker::resolveSingleTypeWitness(
diff --git a/lib/Sema/TypeCheckSwitchStmt.cpp b/lib/Sema/TypeCheckSwitchStmt.cpp
index a95a942..296856c 100644
--- a/lib/Sema/TypeCheckSwitchStmt.cpp
+++ b/lib/Sema/TypeCheckSwitchStmt.cpp
@@ -169,6 +169,7 @@
         }
         }
       }
+
       
     public:
       explicit Space(Type T, Identifier NameForPrinting)
@@ -201,6 +202,29 @@
         return computeSize(TC, cache);
       }
 
+      // Walk one level deep into the space to return whether it is
+      // composed entirely of irrefutable patterns - these are quick to check
+      // regardless of the size of the total type space.
+      bool isAllIrrefutable() const {
+        switch (getKind()) {
+        case SpaceKind::Empty:
+        case SpaceKind::Type:
+          return true;
+        case SpaceKind::BooleanConstant:
+          return false;
+        case SpaceKind::Constructor:
+          return llvm::all_of(getSpaces(), [](const Space &sp) {
+            return sp.getKind() == SpaceKind::Type
+                || sp.getKind() == SpaceKind::Empty;
+          });
+        case SpaceKind::Disjunct: {
+          return llvm::all_of(getSpaces(), [](const Space &sp) {
+            return sp.isAllIrrefutable();
+          });
+        }
+        }
+      }
+
       static size_t getMaximumSize() {
         return MAX_SPACE_SIZE;
       }
@@ -750,7 +774,7 @@
           break;
         case SpaceKind::Disjunct: {
           if (forDisplay) {
-            assert(false && "Attempted to display disjunct to user!");
+            llvm_unreachable("Attempted to display disjunct to user!");
           } else {
             buffer << "DISJOIN(";
             for (auto &sp : Spaces) {
@@ -1011,14 +1035,16 @@
       if (subjectType && subjectType->isStructurallyUninhabited()) {
         return;
       }
-      
+
+      // Reject switch statements with empty blocks.
+      if (limitedChecking && Switch->getCases().empty()) {
+        SpaceEngine::diagnoseMissingCases(TC, Switch,
+                                          RequiresDefault::EmptySwitchBody,
+                                          SpaceEngine::Space());
+      }
+
+      // If the switch body fails to typecheck, end analysis here.
       if (limitedChecking) {
-        // Reject switch statements with empty blocks.
-        if (Switch->getCases().empty()) {
-          SpaceEngine::diagnoseMissingCases(TC, Switch,
-                                            /*justNeedsDefault*/true,
-                                            SpaceEngine::Space());
-        }
         return;
       }
 
@@ -1063,23 +1089,18 @@
       
       Space totalSpace(subjectType, Identifier());
       Space coveredSpace(spaces);
-      size_t totalSpaceSize = totalSpace.getSize(TC);
-      if (totalSpaceSize > Space::getMaximumSize()) {
-        // Because the space is large, we have to extend the size
-        // heuristic to compensate for actually exhaustively pattern matching
-        // over enormous spaces.  In this case, if the covered space covers
-        // as much as the total space, and there were no duplicates, then we
-        // can assume the user did the right thing and that they don't need
-        // a 'default' to be inserted.
-        if (!sawRedundantPattern
-            && coveredSpace.getSize(TC) >= totalSpaceSize) {
-          return;
-        }
 
-        diagnoseMissingCases(TC, Switch, /*justNeedsDefault*/true, Space());
+      size_t totalSpaceSize = totalSpace.getSize(TC);
+      if (totalSpaceSize > Space::getMaximumSize() && !coveredSpace.isAllIrrefutable()) {
+        // Because the space is large, fall back to requiring 'default'.
+        //
+        // FIXME: Explore ways of reducing runtime of this analysis or doing
+        // partial analysis to recover this case.
+        diagnoseMissingCases(TC, Switch,
+                             RequiresDefault::SpaceTooLarge, Space());
         return;
       }
-      
+
       auto uncovered = totalSpace.minus(coveredSpace, TC).simplify(TC);
       if (uncovered.isEmpty()) {
         return;
@@ -1092,11 +1113,12 @@
         if (Space::canDecompose(uncovered.getType())) {
           SmallVector<Space, 4> spaces;
           Space::decompose(TC, uncovered.getType(), spaces);
-          diagnoseMissingCases(TC, Switch,
-                               /*justNeedsDefault*/ false, Space(spaces));
+          diagnoseMissingCases(TC, Switch, RequiresDefault::No, Space(spaces));
         } else {
-          diagnoseMissingCases(TC, Switch,
-                               /*justNeedsDefault*/ true, Space());
+          diagnoseMissingCases(TC, Switch, Switch->getCases().empty()
+                                            ? RequiresDefault::EmptySwitchBody
+                                            : RequiresDefault::UncoveredSwitch,
+                               Space());
         }
         return;
       }
@@ -1107,7 +1129,7 @@
         uncovered = Space(spaces);
       }
 
-      diagnoseMissingCases(TC, Switch, /*justNeedsDefault*/ false, uncovered,
+      diagnoseMissingCases(TC, Switch, RequiresDefault::No, uncovered,
                            sawDowngradablePattern);
     }
     
@@ -1139,8 +1161,15 @@
       }
     }
 
+    enum class RequiresDefault {
+      No,
+      EmptySwitchBody,
+      UncoveredSwitch,
+      SpaceTooLarge,
+    };
+
     static void diagnoseMissingCases(TypeChecker &TC, const SwitchStmt *SS,
-                                     bool justNeedsDefault,
+                                     RequiresDefault defaultReason,
                                      Space uncovered,
                                      bool sawDowngradablePattern = false) {
       SourceLoc startLoc = SS->getStartLoc();
@@ -1149,20 +1178,30 @@
       llvm::SmallString<128> buffer;
       llvm::raw_svector_ostream OS(buffer);
 
-      bool InEditor = TC.Context.LangOpts.DiagnosticsEditorMode;
-
-      if (justNeedsDefault) {
+      switch (defaultReason) {
+      case RequiresDefault::EmptySwitchBody: {
         OS << tok::kw_default << ":\n" << placeholder << "\n";
-        if (SS->getCases().empty()) {
-          TC.Context.Diags.diagnose(startLoc, diag::empty_switch_stmt)
-             .fixItInsert(endLoc, buffer.str());
-        } else {
-          TC.Context.Diags.diagnose(startLoc, diag::non_exhaustive_switch);
-          TC.Context.Diags.diagnose(startLoc, diag::missing_several_cases,
-                                    uncovered.isEmpty()).fixItInsert(endLoc,
-                                                              buffer.str());
-        }
+        TC.diagnose(startLoc, diag::empty_switch_stmt)
+          .fixItInsert(endLoc, buffer.str());
+      }
         return;
+      case RequiresDefault::UncoveredSwitch: {
+        OS << tok::kw_default << ":\n" << placeholder << "\n";
+        TC.diagnose(startLoc, diag::non_exhaustive_switch);
+        TC.diagnose(startLoc, diag::missing_several_cases, uncovered.isEmpty())
+          .fixItInsert(endLoc, buffer.str());
+      }
+        return;
+      case RequiresDefault::SpaceTooLarge: {
+        OS << tok::kw_default << ":\n" << "<#fatalError()#>" << "\n";
+        TC.diagnose(startLoc,  diag::cannot_prove_exhaustive_switch);
+        TC.diagnose(startLoc, diag::missing_several_cases, uncovered.isEmpty())
+          .fixItInsert(endLoc, buffer.str());
+      }
+        return;
+      case RequiresDefault::No:
+        // Break out to diagnose below.
+        break;
       }
 
       // If there's nothing else to diagnose, bail.
@@ -1189,7 +1228,7 @@
       //
       // missing case '(.none, .some(_))'
       // missing case '(.some(_), .none)'
-      if (InEditor) {
+      if (TC.Context.LangOpts.DiagnosticsEditorMode) {
         buffer.clear();
         SmallVector<Space, 8> emittedSpaces;
         for (auto &uncoveredSpace : uncovered.getSpaces()) {
@@ -1212,7 +1251,7 @@
         TC.diagnose(startLoc, diag::missing_several_cases, false)
           .fixItInsert(endLoc, buffer.str());
       } else {
-        TC.Context.Diags.diagnose(startLoc, mainDiagType);
+        TC.diagnose(startLoc, mainDiagType);
 
         SmallVector<Space, 8> emittedSpaces;
         for (auto &uncoveredSpace : uncovered.getSpaces()) {
diff --git a/lib/Sema/TypeCheckType.cpp b/lib/Sema/TypeCheckType.cpp
index a959a69..6d40eae 100644
--- a/lib/Sema/TypeCheckType.cpp
+++ b/lib/Sema/TypeCheckType.cpp
@@ -234,14 +234,6 @@
   return Context.getBridgedToObjC(dc, valueType);
 }
 
-void TypeChecker::forceExternalDeclMembers(NominalTypeDecl *nominalDecl) {
-  // Force any delayed members added to the nominal type declaration.
-  if (nominalDecl->hasDelayedMembers()) {
-    this->handleExternalDecl(nominalDecl);
-    nominalDecl->setHasDelayedMembers(false);
-  }
-}
-
 Type TypeChecker::resolveTypeInContext(
        TypeDecl *typeDecl,
        DeclContext *foundDC,
@@ -265,7 +257,6 @@
   if (auto nominalType = dyn_cast<NominalTypeDecl>(typeDecl)) {
     if (!isa<ProtocolDecl>(nominalType) &&
         (!nominalType->getGenericParams() || !isSpecialized)) {
-      forceExternalDeclMembers(nominalType);
       for (auto parentDC = fromDC;
            !parentDC->isModuleScopeContext();
            parentDC = parentDC->getParent()) {
@@ -1151,11 +1142,6 @@
     auto *foundDC = entry.getDeclContext();
     auto *typeDecl = cast<TypeDecl>(entry.getValueDecl());
 
-    // If necessary, add delayed members to the declaration.
-    if (auto nomDecl = dyn_cast<NominalTypeDecl>(typeDecl)) {
-      TC.forceExternalDeclMembers(nomDecl);
-    }
-
     Type type = resolveTypeDecl(TC, typeDecl, comp->getIdLoc(),
                                 foundDC, DC,
                                 dyn_cast<GenericIdentTypeRepr>(comp), options,
@@ -3959,6 +3945,26 @@
   return Result;
 }
 
+bool TypeChecker::canBeRepresentedInObjC(const ValueDecl *decl) {
+  if (!Context.LangOpts.EnableObjCInterop)
+    return false;
+
+  if (auto func = dyn_cast<AbstractFunctionDecl>(decl)) {
+    Optional<ForeignErrorConvention> errorConvention;
+    return isRepresentableInObjC(func, ObjCReason::MemberOfObjCMembersClass,
+                                 errorConvention);
+  }
+
+  if (auto var = dyn_cast<VarDecl>(decl))
+    return isRepresentableInObjC(var, ObjCReason::MemberOfObjCMembersClass);
+
+  if (auto subscript = dyn_cast<SubscriptDecl>(decl))
+    return isRepresentableInObjC(subscript,
+                                 ObjCReason::MemberOfObjCMembersClass);
+
+  return false;
+}
+
 void TypeChecker::diagnoseTypeNotRepresentableInObjC(const DeclContext *DC,
                                                      Type T,
                                                      SourceRange TypeRange) {
diff --git a/lib/Sema/TypeChecker.cpp b/lib/Sema/TypeChecker.cpp
index cb30575..e0f1e12 100644
--- a/lib/Sema/TypeChecker.cpp
+++ b/lib/Sema/TypeChecker.cpp
@@ -471,6 +471,14 @@
       TC.finalizeDecl(decl);
     }
 
+    // Ensure that the requirements of the given conformance are
+    // fully checked.
+    for (unsigned i = 0; i != TC.PartiallyCheckedConformances.size(); ++i) {
+      auto conformance = TC.PartiallyCheckedConformances[i];
+      TC.checkConformanceRequirements(conformance);
+    }
+    TC.PartiallyCheckedConformances.clear();
+
     // Complete any conformances that we used.
     for (unsigned i = 0; i != TC.UsedConformances.size(); ++i) {
       auto conformance = TC.UsedConformances[i];
@@ -483,7 +491,8 @@
            currentExternalDef < TC.Context.ExternalDefinitions.size() ||
            !TC.DeclsToFinalize.empty() ||
            !TC.DelayedRequirementSignatures.empty() ||
-           !TC.UsedConformances.empty());
+           !TC.UsedConformances.empty() ||
+           !TC.PartiallyCheckedConformances.empty());
 
   // FIXME: Horrible hack. Store this somewhere more appropriate.
   TC.Context.LastCheckedExternalDefinition = currentExternalDef;
@@ -672,15 +681,6 @@
   }
 }
 
-void swift::finishTypeCheckingFile(SourceFile &SF) {
-  auto &Ctx = SF.getASTContext();
-  TypeChecker TC(Ctx);
-
-  for (auto D : SF.Decls)
-    if (auto PD = dyn_cast<ProtocolDecl>(D))
-      TC.inferDefaultWitnesses(PD);
-}
-
 void swift::performWholeModuleTypeChecking(SourceFile &SF) {
   SharedTimer("performWholeModuleTypeChecking");
   auto &Ctx = SF.getASTContext();
diff --git a/lib/Sema/TypeChecker.h b/lib/Sema/TypeChecker.h
index 9bab480..7ff6a11 100644
--- a/lib/Sema/TypeChecker.h
+++ b/lib/Sema/TypeChecker.h
@@ -712,6 +712,11 @@
   /// completed before type checking is considered complete.
   llvm::SetVector<NormalProtocolConformance *> UsedConformances;
 
+  /// The list of protocol conformances whose requirements could not be
+  /// fully checked and, therefore, should be checked again at the top
+  /// level.
+  llvm::SetVector<NormalProtocolConformance *> PartiallyCheckedConformances;
+
   /// The list of declarations that we've done at least partial validation
   /// of during type-checking, but which will need to be finalized before
   /// we can hand them off to SILGen etc.
@@ -1073,6 +1078,11 @@
   /// properly extends the nominal type it names.
   void validateExtension(ExtensionDecl *ext);
 
+  /// Request that type containing the given member needs to have all
+  /// members validated after everythign in the translation unit has
+  /// been processed.
+  void requestMemberLayout(ValueDecl *member);
+
   /// Request that the given class needs to have all members validated
   /// after everything in the translation unit has been processed.
   void requestNominalLayout(NominalTypeDecl *nominalDecl);
@@ -1086,10 +1096,6 @@
   /// translation unit has been processed.
   void finalizeDecl(ValueDecl *D);
 
-  /// \brief Force all members of an external decl, and also add its
-  /// conformances.
-  void forceExternalDeclMembers(NominalTypeDecl *NTD);
-
   /// Resolve a reference to the given type declaration within a particular
   /// context.
   ///
@@ -1339,19 +1345,9 @@
     synthesizeMemberForLookup(nominal, member);
   }
 
-  virtual void
-  resolveExternalDeclImplicitMembers(NominalTypeDecl *nominal) override {
-    handleExternalDecl(nominal);
-  }
-
   /// Infer default value witnesses for all requirements in the given protocol.
   void inferDefaultWitnesses(ProtocolDecl *proto);
 
-  /// Determine whether the given (potentially constrained) protocol extension
-  /// is usable for the given type.
-  bool isProtocolExtensionUsable(DeclContext *dc, Type type,
-                                 ExtensionDecl *protocolExtension) override;
- 
   /// Perform semantic checks on the given generic parameter list.
   void prepareGenericParamList(GenericParamList *genericParams,
                                DeclContext *dc);
@@ -2037,6 +2033,9 @@
   /// Completely check the given conformance.
   void checkConformance(NormalProtocolConformance *conformance);
 
+  /// Check the requirement signature of the given conformance.
+  void checkConformanceRequirements(NormalProtocolConformance *conformance);
+
   /// Check all of the conformances in the given context.
   void checkConformancesInContext(DeclContext *dc,
                                   IterableDeclContext *idc);
@@ -2279,6 +2278,8 @@
   bool isRepresentableInObjC(const VarDecl *VD, ObjCReason Reason);
   bool isRepresentableInObjC(const SubscriptDecl *SD, ObjCReason Reason);
 
+  bool canBeRepresentedInObjC(const ValueDecl *decl);
+
   void diagnoseTypeNotRepresentableInObjC(const DeclContext *DC,
                                           Type T, SourceRange TypeRange);
 
diff --git a/lib/Serialization/Deserialization.cpp b/lib/Serialization/Deserialization.cpp
index 5068847..d31552f 100644
--- a/lib/Serialization/Deserialization.cpp
+++ b/lib/Serialization/Deserialization.cpp
@@ -619,8 +619,8 @@
     return nullptr;
   }
   NormalProtocolConformanceLayout::readRecord(scratch, protoID,
-                                              contextID, valueCount,
-                                              typeCount, conformanceCount,
+                                              contextID, typeCount,
+                                              valueCount, conformanceCount,
                                               rawIDs);
 
   ASTContext &ctx = getContext();
@@ -4898,8 +4898,8 @@
   assert(kind == NORMAL_PROTOCOL_CONFORMANCE &&
          "registered lazy loader incorrectly");
   NormalProtocolConformanceLayout::readRecord(scratch, protoID,
-                                              contextID, valueCount,
-                                              typeCount, conformanceCount,
+                                              contextID, typeCount,
+                                              valueCount, conformanceCount,
                                               rawIDs);
 
   // Read requirement signature conformances.
@@ -4958,6 +4958,34 @@
 
   ArrayRef<uint64_t>::iterator rawIDIter = rawIDs.begin();
 
+  TypeWitnessMap typeWitnesses;
+  while (typeCount--) {
+    // FIXME: We don't actually want to allocate an archetype here; we just
+    // want to get an access path within the protocol.
+    auto first = cast<AssociatedTypeDecl>(getDecl(*rawIDIter++));
+    auto second = getType(*rawIDIter++);
+    auto third = cast_or_null<TypeDecl>(getDecl(*rawIDIter++));
+    if (third &&
+        isa<TypeAliasDecl>(third) &&
+        third->getModuleContext() != getAssociatedModule() &&
+        !third->getDeclaredInterfaceType()->isEqual(second)) {
+      // Conservatively drop references to typealiases in other modules
+      // that may have changed. This may also drop references to typealiases
+      // that /haven't/ changed but just happen to have generics in them, but
+      // in practice having a declaration here isn't actually required by the
+      // rest of the compiler.
+      third = nullptr;
+    }
+    typeWitnesses[first] = std::make_pair(second, third);
+  }
+  assert(rawIDIter <= rawIDs.end() && "read too much");
+
+  // Set type witnesses.
+  for (auto typeWitness : typeWitnesses) {
+    conformance->setTypeWitness(typeWitness.first, typeWitness.second.first,
+                                typeWitness.second.second);
+  }
+
   // An imported requirement may have changed type between Swift versions.
   // In this situation we need to do a post-pass to fill in missing
   // requirements with opaque witnesses.
@@ -5064,35 +5092,6 @@
                           syntheticEnv, reqToSyntheticSubs));
   }
   assert(rawIDIter <= rawIDs.end() && "read too much");
-
-  TypeWitnessMap typeWitnesses;
-  while (typeCount--) {
-    // FIXME: We don't actually want to allocate an archetype here; we just
-    // want to get an access path within the protocol.
-    auto first = cast<AssociatedTypeDecl>(getDecl(*rawIDIter++));
-    auto second = getType(*rawIDIter++);
-    auto third = cast_or_null<TypeDecl>(getDecl(*rawIDIter++));
-    if (third &&
-        isa<TypeAliasDecl>(third) &&
-        third->getModuleContext() != getAssociatedModule() &&
-        !third->getDeclaredInterfaceType()->isEqual(second)) {
-      // Conservatively drop references to typealiases in other modules
-      // that may have changed. This may also drop references to typealiases
-      // that /haven't/ changed but just happen to have generics in them, but
-      // in practice having a declaration here isn't actually required by the
-      // rest of the compiler.
-      third = nullptr;
-    }
-    typeWitnesses[first] = std::make_pair(second, third);
-  }
-  assert(rawIDIter <= rawIDs.end() && "read too much");
-
-
-  // Set type witnesses.
-  for (auto typeWitness : typeWitnesses) {
-    conformance->setTypeWitness(typeWitness.first, typeWitness.second.first,
-                                typeWitness.second.second);
-  }
   
   // Fill in opaque value witnesses if we need to.
   if (needToFillInOpaqueValueWitnesses) {
diff --git a/lib/Serialization/DeserializeSIL.cpp b/lib/Serialization/DeserializeSIL.cpp
index 91e3d85..d2c8235 100644
--- a/lib/Serialization/DeserializeSIL.cpp
+++ b/lib/Serialization/DeserializeSIL.cpp
@@ -13,8 +13,10 @@
 #define DEBUG_TYPE "deserialize"
 #include "DeserializeSIL.h"
 #include "swift/Basic/Defer.h"
+#include "swift/Basic/PrettyStackTrace.h"
 #include "swift/AST/GenericSignature.h"
 #include "swift/AST/ProtocolConformance.h"
+#include "swift/AST/PrettyStackTrace.h"
 #include "swift/Serialization/ModuleFile.h"
 #include "SILFormat.h"
 #include "swift/SIL/SILArgument.h"
@@ -382,6 +384,8 @@
     return nullptr;
   assert(FID <= Funcs.size() && "invalid SILFunction ID");
 
+  PrettyStackTraceStringAction trace("deserializing SIL function", name);
+
   auto &cacheEntry = Funcs[FID-1];
   if (cacheEntry.isFullyDeserialized() ||
       (cacheEntry.isDeserialized() && declarationOnly))
@@ -1183,7 +1187,7 @@
     // FIXME: Why the arbitrary order difference in IRBuilder type argument?
     ResultVal = Builder.createPartialApply(
         Loc, FnVal, Substitutions, Args,
-        closureTy.getAs<SILFunctionType>()->getCalleeConvention());
+        closureTy.castTo<SILFunctionType>()->getCalleeConvention());
     break;
   }
   case SILInstructionKind::BuiltinInst: {
@@ -1317,7 +1321,7 @@
   }
   case SILInstructionKind::IntegerLiteralInst: {
     auto Ty = MF->getType(TyID);
-    auto intTy = Ty->getAs<BuiltinIntegerType>();
+    auto intTy = Ty->castTo<BuiltinIntegerType>();
     Identifier StringVal = MF->getIdentifier(ValID);
     // Build APInt from string.
     APInt value(intTy->getGreatestWidth(), StringVal.str(), 10);
@@ -1328,7 +1332,7 @@
   }
   case SILInstructionKind::FloatLiteralInst: {
     auto Ty = MF->getType(TyID);
-    auto floatTy = Ty->getAs<BuiltinFloatType>();
+    auto floatTy = Ty->castTo<BuiltinFloatType>();
     Identifier StringVal = MF->getIdentifier(ValID);
     // Build APInt from string.
     APInt bits(floatTy->getBitWidth(), StringVal.str(), 16);
@@ -1558,7 +1562,7 @@
   case SILInstructionKind::StoreUnownedInst: {
     auto Ty = MF->getType(TyID);
     SILType addrType = getSILType(Ty, (SILValueCategory)TyCategory);
-    auto refType = addrType.getAs<WeakStorageType>();
+    auto refType = addrType.castTo<UnownedStorageType>();
     auto ValType = SILType::getPrimitiveObjectType(refType.getReferentType());
     bool isInit = (Attr > 0);
     ResultVal = Builder.createStoreUnowned(Loc,
@@ -1570,7 +1574,7 @@
   case SILInstructionKind::StoreWeakInst: {
     auto Ty = MF->getType(TyID);
     SILType addrType = getSILType(Ty, (SILValueCategory)TyCategory);
-    auto refType = addrType.getAs<WeakStorageType>();
+    auto refType = addrType.castTo<WeakStorageType>();
     auto ValType = SILType::getPrimitiveObjectType(refType.getReferentType());
     bool isInit = (Attr > 0);
     ResultVal = Builder.createStoreWeak(Loc,
@@ -1652,7 +1656,7 @@
     // Use OneTypeOneOperand layout where the field number is stored in TypeID.
     auto Ty2 = MF->getType(TyID2);
     SILType ST = getSILType(Ty2, (SILValueCategory)TyCategory2);
-    TupleType *TT = ST.getAs<TupleType>();
+    TupleType *TT = ST.castTo<TupleType>();
 
     auto ResultTy = TT->getElement(TyID).getType();
     switch (OpCode) {
@@ -1675,7 +1679,7 @@
     // Format: a type followed by a list of values. A value is expressed by
     // 2 IDs: ValueID, ValueResultNumber.
     auto Ty = MF->getType(TyID);
-    TupleType *TT = Ty->getAs<TupleType>();
+    TupleType *TT = Ty->castTo<TupleType>();
     assert(TT && "Type of a TupleInst should be TupleType");
     SmallVector<SILValue, 4> OpList;
     for (unsigned I = 0, E = ListOfValues.size(); I < E; I++) {
@@ -2419,6 +2423,8 @@
   if (!GlobalVarList)
     return nullptr;
 
+  PrettyStackTraceStringAction trace("deserializing SIL global", Name);
+
   // If we already deserialized this global variable, just return it.
   if (auto *GV = SILMod.lookUpGlobalVariable(Name))
     return GV;
@@ -2543,6 +2549,9 @@
   }
 
   ClassDecl *theClass = cast<ClassDecl>(MF->getDecl(ClassID));
+
+  PrettyStackTraceDecl trace("deserializing SIL vtable for", theClass);
+
   // Fetch the next record.
   scratch.clear();
   entry = SILCursor.advance(AF_DontPopBlockAtEnd);
@@ -2662,6 +2671,11 @@
   auto theConformance = cast<NormalProtocolConformance>(
                           MF->readConformance(SILCursor).getConcrete());
 
+  PrettyStackTraceType trace(SILMod.getASTContext(),
+                             "deserializing SIL witness table for",
+                             theConformance->getType());
+  PrettyStackTraceDecl trace2("... to", theConformance->getProtocol());
+
   if (!existingWt)
     existingWt = SILMod.lookUpWitnessTable(theConformance, false);
   auto wT = existingWt;
@@ -2856,6 +2870,8 @@
     return nullptr;
   }
 
+  PrettyStackTraceDecl trace("deserializing default witness table for", proto);
+
   if (!existingWt)
     existingWt = SILMod.lookUpDefaultWitnessTable(proto, /*deserializeLazily=*/ false);
   auto wT = existingWt;
diff --git a/lib/Serialization/ModuleFile.cpp b/lib/Serialization/ModuleFile.cpp
index cdb3c60..44f85ce 100644
--- a/lib/Serialization/ModuleFile.cpp
+++ b/lib/Serialization/ModuleFile.cpp
@@ -1793,7 +1793,7 @@
 }
 
 Optional<TinyPtrVector<ValueDecl *>>
-ModuleFile::loadNamedMembers(const IterableDeclContext *IDC, DeclName N,
+ModuleFile::loadNamedMembers(const IterableDeclContext *IDC, DeclBaseName N,
                              uint64_t contextData) {
   PrettyStackTraceDecl trace("loading members for", IDC->getDecl());
 
@@ -1801,7 +1801,7 @@
   assert(DeclMemberNames);
 
   TinyPtrVector<ValueDecl *> results;
-  auto i = DeclMemberNames->find(N.getBaseName());
+  auto i = DeclMemberNames->find(N);
   if (i == DeclMemberNames->end())
     return results;
 
diff --git a/lib/Serialization/Serialization.cpp b/lib/Serialization/Serialization.cpp
index bbb8eef..9e781f3 100644
--- a/lib/Serialization/Serialization.cpp
+++ b/lib/Serialization/Serialization.cpp
@@ -1492,6 +1492,17 @@
   unsigned numValueWitnesses = 0;
   unsigned numTypeWitnesses = 0;
 
+  conformance->forEachTypeWitness(/*resolver=*/nullptr,
+                                  [&](AssociatedTypeDecl *assocType,
+                                      Type type, TypeDecl *typeDecl) {
+    data.push_back(addDeclRef(assocType));
+    data.push_back(addTypeRef(type));
+    data.push_back(addDeclRef(typeDecl, /*forceSerialization*/false,
+                              /*allowTypeAliasXRef*/true));
+    ++numTypeWitnesses;
+    return false;
+  });
+
   conformance->forEachValueWitness(nullptr,
     [&](ValueDecl *req, Witness witness) {
       ++numValueWitnesses;
@@ -1519,17 +1530,6 @@
       data.push_back(witness.getSubstitutions().size());
   });
 
-  conformance->forEachTypeWitness(/*resolver=*/nullptr,
-                                  [&](AssociatedTypeDecl *assocType,
-                                      Type type, TypeDecl *typeDecl) {
-    data.push_back(addDeclRef(assocType));
-    data.push_back(addTypeRef(type));
-    data.push_back(addDeclRef(typeDecl, /*forceSerialization*/false,
-                              /*allowTypeAliasXRef*/true));
-    ++numTypeWitnesses;
-    return false;
-  });
-
   unsigned numSignatureConformances =
       conformance->getSignatureConformances().size();
 
@@ -1538,8 +1538,8 @@
   auto ownerID = addDeclContextRef(conformance->getDeclContext());
   NormalProtocolConformanceLayout::emitRecord(Out, ScratchRecord, abbrCode,
                                               addDeclRef(protocol), ownerID,
-                                              numValueWitnesses,
                                               numTypeWitnesses,
+                                              numValueWitnesses,
                                               numSignatureConformances,
                                               data);
 
diff --git a/lib/Serialization/SerializedModuleLoader.cpp b/lib/Serialization/SerializedModuleLoader.cpp
index dfe6aa3..63421b1 100644
--- a/lib/Serialization/SerializedModuleLoader.cpp
+++ b/lib/Serialization/SerializedModuleLoader.cpp
@@ -67,7 +67,7 @@
   Scratch.clear();
   llvm::sys::path::append(Scratch, DirName, ModuleDocFilename);
   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ModuleDocOrErr =
-  llvm::MemoryBuffer::getFile(StringRef(Scratch.data(), Scratch.size()));
+      llvm::MemoryBuffer::getFile(StringRef(Scratch.data(), Scratch.size()));
   if (!ModuleDocOrErr &&
       ModuleDocOrErr.getError() != std::errc::no_such_file_or_directory) {
     return ModuleDocOrErr.getError();
diff --git a/lib/Syntax/Status.md b/lib/Syntax/Status.md
index a2ed705..8a66126 100644
--- a/lib/Syntax/Status.md
+++ b/lib/Syntax/Status.md
@@ -1,479 +1,135 @@
-# Swift Syntax Library Implementation Status
+# libSyntax nodes status
 
-## Represented Grammar Productions
+## Expression
 
-Include the following in each entry:
+### Done:
+  * NilLiteralExpr
+  * IntegerLiteralExpr
+  * FloatLiteralExpr
+  * BooleanLiteralExpr
+  * StringLiteralExpr
+  * DiscardAssignmentExpr
+  * DeclRefExpr
+  * IfExpr
+  * AssignExpr
+  * TypeExpr
+  * UnresolvedMemberExpr
+  * SequenceExpr
+  * TupleElementExpr
+  * TupleExpr
+  * ArrayExpr
+  * DictionaryExpr
+  * PrefixUnaryExpr
+  * TryExpr
+  * ForceTryExpr
+  * OptionalTryExpr
+  * ClosureExpr
 
-- Grammar production(s)
-  - See [Summary of the Swift Grammar](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/zzSummaryOfTheGrammar.html)
-- C++ types representing the productions
-- Testing status
-  - With APIs
-  - Make APIs
-  - Builder APIs (if applicable)
-- SR links
-  - Related lib/AST changes
+### In-progress (UnknownExpr):
+  * InterpolatedStringLiteralExpr
+  * ObjectLiteralExpr
+  * MagicIdentifierLiteralExpr
+  * CallExpr
+  * UnresolvedDotExpr
+  * InOutExpr
+  * KeyPathExpr
+  * KeyPathDotExpr
+  * EditorPlaceholderExpr
 
-### Declarations
+### Not-started (UnknownExpr):
+  * SuperRefExpr
+  * UnresolvedSpecializeExpr
+  * DotSelfExpr
+  * SubscriptExpr
+  * KeyPathApplicationExpr
+  * CaptureListExpr
+  * AutoClosureExpr
+  * DynamicTypeExpr
+  * BindOptionalExpr
+  * OptionalEvaluationExpr
+  * ForceValueExpr
+  * PostfixUnaryExpr
+  * ForcedCheckedCastExpr
+  * ConditionalCheckedCastExpr
+  * IsExpr
+  * CoerceExpr
+  * ArrowExpr
+  * UnresolvedPatternExpr
+  * ObjCSelectorExpr
 
-- declaration-modifiers
-  - `DeclModifierListSyntax`
+## Declaration
 
-- declaration-modifier
-  - `DeclModifierSyntax`
+### Done:
+  * TopLevelCodeDecl
+  * ClassDecl
+  * StructDecl
+  * FuncDecl
+  * ProtocolDecl
+  * ImportDecl
+  * TypeAliasDecl
+  * IfConfigDecl
+  * PatternBindingDecl
+  * VarDecl
 
-- struct-declaration
-  - `StructDeclSyntax`
+### In-progress (UnknownDecl):
+  * ExtensionDecl (SR-6572)
 
-- typealias-assignment  
-  typealias-declaration
-  - `TypeAliasDeclSyntax`
+### Not-started (UnknownDecl):
+  * EnumCaseDecl
+  * PrecedenceGroupDecl
+  * InfixOperatorDecl
+  * PrefixOperatorDecl
+  * PostfixOperatorDecl
+  * AssociatedTypeDecl
+  * EnumDecl
+  * SubscriptDecl
+  * ConstructorDecl
+  * DestructorDecl
+  * EnumElementDecl
 
-- class-body  
-  class-members
+## Statement
+### Done:
+  * BraceStmt
+  * ReturnStmt
+  * DeferStmt
+  * DoStmt
+  * RepeatWhileStmt
+  * BreakStmt
+  * ContinueStmt
+  * FallthroughStmt
+  * ThrowStmt
 
-  - `DeclMembersSyntax`
-  - `ClassDeclSyntax` used for the `{` `}` braces.
+### Not-started (UnknownStmt):
+  * IfStmt
+  * GuardStmt
+  * WhileStmt
+  * ForEachStmt
+  * SwitchStmt
 
-- extension-body
-  - `DeclMembersSyntax`
+## Pattern
+### Done:
+  * IdentifierPattern
+  * WildcardPattern
+  * TuplePattern
+  * ExpressionPattern
+  * ValueBindingPattern
+  * IsTypePattern
 
-- protocol-body
-  - `DeclMembersSyntax`
+### Not-started:
+  * AsTypePattern
+  * OptionalPattern
+  * EnumCasePattern
 
-- struct-body  
-  struct-members
-  - `DeclMembersSyntax`
-  - `StructDeclSyntax` used for the `{` `}` braces.
-
-- function-declaration
-  - `FunctionDeclSyntax`
-
-- function-body
-  - `CodeBlockSyntax`
-
-- function-result
-  - `TypeSyntax`
-
-- function-signature
-  - `FunctionSignatureSyntax`
-
-- parameter-clause
-  - `FunctionParameterClauseSyntax`
-
-- parameter-list
-  - `FunctionParameterListSyntax`
-
-- parameter
-  - `FunctionParameterSyntax`
-
-### Statements
-
-- statement
-  - `StmtSyntax` (Abstract base class)
-
-- statements
-  - `StmtListSyntax`
-
-- code-block
-  - `CodeBlockSyntax`
-
-- fallthrough-statement
-  - `FallthroughStmtSyntax`
-
-- break-statement
-  - `BreakStmtSyntax`
-
-- continue-statement
-  - `ContinueStmtSyntax`
-
-- return-statement
-  - `ReturnStmtSyntax`
-
-### Expressions
-
-- binary-literal
-- decimal-literal
-- hexadecimal-literal
-- integer-literal
-- octal-literal
-  - `IntegerLiteralExprSyntax`
-
-- function-call-argument
-  - `FunctionCallArgumentSyntax`
-
-- function-call-argument-list
-  - `FunctionCallArgumentListSyntax`
-
-- function-call-expression
-- function-call-argument-clause
-  - `FunctionCallExprSyntax`
-
-### Types
-
-- type
-- type-annotation
-  - `TypeSyntax` (Abstract base class)
-
-- protocol-identifier
-- type-identifier
-  - `TypeIdentifierSyntax`
-
-- optional-type
-  - `OptionalTypeSyntax`
-
-- implicitly-unwrapped-optional-type
-  - `ImplicitlyUnwrappedOptionalTypeSyntax`
-
-- array-type
-  - `ArrayTypeSyntax`
-
-- dictionary-type
-  - `DictionaryTypeSyntax`
-
-- function-type
-- function-type-argument
-- function-type-argument-clause
-  - `FunctionTypeSyntax`
-
-- function-type-argument-list
-  - `TypeArgumentListSyntax`
-
-- metatype-type
-  - `MetatypeTypeSyntax`
-
-- tuple-type
-  - `TupleTypeSyntax`
-
-- tuple-type-element
-  - `TupleTypeElementSyntax`
-
-- tuple-type-element-list
-  - `TupleTypeElementListSyntax`
-
-### Type Attributes
-
-- attribute
-- attribute-argument-clause
-  - `TypeAttributeSyntax`
-
-- attributes
-  - `TypeAttributesSyntax`
-
-- balanced-token
-  - `BalancedTokenSyntax`
-
-- balanced-tokens
-  - `BalancedTokensSyntax`
-
-### Generics
-
-- generic-argument-clause
-  - `GenericArgumentClauseSyntax`
-
-- generic-argument-list
-  - `GenericArgumentListSyntax`
-
-- generic-parameter-clause
-  - `GenericParameterClauseSyntax`
-
-- generic-parameter
-  - `GenericParameterSyntax`
-
-- generic-parameter-list
-  - `GenericParameterListSyntax`
-
-- conformance-requirement
-  - `ConformanceRequirementSyntax`
-
-- same-type-requirement
-  - `SameTypeRequirementSyntax`
-
-- generic-where-clause
-  - `GenericWhereClauseSyntax`
-
-- requirement-list
-  - `GenericRequirementListSyntax`
-
-### Identifiers and Terminal Tokens
-
-- access-level-modifier
-- argument-label
-- attribute-name
-- boolean-literal
-- class-name
-- closure-parameter-name
-- element-name
-- enum-case-name
-- enum-name
-- external-parameter-name
-- function-name
-- identifier-pattern
-- import-kind
-- import-path-identifier
-- label-name
-- local-parameter-name
-- mutation-modifier
-- platform-name
-- precedence-group-name
-- protocol-name
-- sign
-- struct-name
-- type-name
-- typealias-name
-- variable-name
-  - identifier
-    - `TokenSyntax`
-
-## Unrepresented Grammar Productions
-
-These are categorized somewhat by difficulty and priority.
-
-### Easy
-
-- array-literal
-- array-literal-items
-- as-pattern
-- case-condition
-- case-label
-- dynamic-type-expression
-- floating-point-literal
-- forced-value-expression
-- identifier-list
-- implicit-member-expression
-- import-path
-- in-out-expression
-- interpolated-text
-- interpolated-text-item
-- is-pattern
-- key-path-expression
-- line-control-statement
-- optional-chaining-expression
-- optional-pattern
-- parenthesized-expression
-- platform-condition
-- platform-version
-- postfix-operator-declaration
-- precedence-group-assignment
-- precedence-group-associativity
-- precedence-group-names
-- statement-label
-- static-string-literal
-- swift-version
-- throw-statement
-- value-binding-pattern
-- where-clause
-- dictionary-literal
-  - dictionary-literal-items
-    - dictionary-literal-item
-- capture-list
-    - capture-list-items
-      - capture-list-item
-- defer-statement
-
-### Medium
-
-- else-directive-clause
-- elseif-directive-clauses
-  - elseif-directive-clause
-- precedence-group-declaration
-- precedence-group-relation
-- expression-list
-- availability-condition
-  - availability-arguments
-    - availability-argument
-- switch-cases
-  - switch-case
-- constant-declaration
-- catch-clauses
-  - catch-clause
-- variable-declaration
-- do-statement
-- for-in-statement
-- guard-statement
-- case-item-list
-- import-declaration
-- if-directive-clause
-- if-statement
-  - else-clause
-- protocol-associated-type-declaration
-- repeat-while-statement
-- while-statement
-- tuple-expression
-  - tuple-element-list
-    - tuple-element
-- tuple-pattern
-  - tuple-pattern-element-list
-    - tuple-pattern-element
-- switch-statement
-- explicit-member-expression
-- optional-binding-condition
-- operator-declaration
-- selector-expression
-- protocol-composition-type
-- conditional-operator
-- deinitializer-declaration
-- didSet-clause
-- willSet-clause
-- pattern-initializer-list
-  - pattern-initializer
-- prefix-expression
-- prefix-operator-declaration
-- infix-operator-declaration
-  - infix-operator-group
-- binary-expression
-
-### Hard
-
-- protocol-declaration
-- closure-expression
-  - closure-signature
-    - closure-parameter-clause
-      - closure-parameter-list
-        - closure-parameter
-- extension-declaration
-- enum-declaration
-- class-declaration
-- getter-setter-block
-  - getter-setter-keyword-block
-  - getter-keyword-clause
-    - getter-clause
-  - setter-keyword-clause
-    - setter-clause
-      - setter-name
-- subscript-declaration
-- enum-case-pattern
-- initializer-declaration
-  - initializer-head
-- interpolated-string-literal
-- conditional-compilation-block
-
-## Trivial and Intermediate Grammar Productions
-
-- binary-expressions
-- binary-operator
-- compilation-condition
-- capture-specifier
-- precedence-group-attributes
-- precedence-group-attribute
-- prefix-operator
-- type-casting-operator
-- willSet-didSet-block
-- architecture
-- string-literal
-- argument-names
-- array-literal-item
-- type-casting-pattern
-- assignment-operator
-- expression-pattern
-- binary-digit
-- binary-literal-character
-- binary-literal-characters
-- branch-statement
-- class-member
-- class-requirement
-- condition
-- condition-list
-- compiler-control-statement
-- control-transfer-statement
-- decimal-digit
-- decimal-digits
-- decimal-exponent
-- decimal-fraction
-- decimal-literal-character
-- decimal-literal-characters
-- default-argument-clause
-- default-label
-- dot-operator-character
-- dot-operator-characters
-- dot-operator-head
-- else-directive
-- elseif-directive
-- endif-directive
-- escaped-character
-- expression
-- extension-member
-- file-name
-- floating-point-e
-- floating-point-p
-- function-head
-- hexadecimal-digit
-- hexadecimal-exponent
-- hexadecimal-fraction
-- identifier-character
-- identifier-characters
-- identifier-head
-- if-directive
-- where-expression
-- implicit-parameter-name
-- initializer
-- initializer-body
-- initializer-expression
-- labeled-statement (TODO: Put in loop-, if-, switch-, do-statement layout)
-- line-number
-- literal
-- literal-expression
-- loop-statement
-- nil-literal
-- numeric-literal
-- octal-digit
-- octal-literal-character
-- octal-literal-characters
-- operating-system
-- operator
-- operator-character
-- operator-characters
-- operator-head
-- pattern
-- postfix-expression
-- postfix-operator
-- postfix-self-expression
-- protocol-composition-continuation
-- protocol-initializer-declaration
-- protocol-member
-- protocol-member-declaration
-- protocol-members
-- extension-members
-- protocol-method-declaration
-- protocol-property-declaration
-- protocol-subscript-declaration
-- quoted-text
-- quoted-text-item
-- raw-value-assignment
-- raw-value-literal
-- raw-value-style-enum
-- raw-value-style-enum-case
-- raw-value-style-enum-case-clause
-- raw-value-style-enum-case-list
-- playground-literal
-- raw-value-style-enum-member
-- raw-value-style-enum-members
-- requirement
-- self-expression
-- self-initializer-expression
-- self-method-expression
-- self-subscript-expression
-- struct-member
-- subscript-expression
-- subscript-head
-- subscript-result
-- superclass-expression
-- superclass-initializer-expression
-- superclass-method-expression
-- superclass-subscript-expression
-- top-level-declaration
-- try-operator
-- type-inheritance-clause
-- type-inheritance-list
-- unicode-scalar-digits
-- union-style-enum
-- union-style-enum-case
-- union-style-enum-case-clause
-- union-style-enum-case-list
-- union-style-enum-member
-- union-style-enum-members
-- variable-declaration-head
-- wildcard-expression
-- wildcard-pattern
-- primary-expression
-- generic-argument
+## TypeRepr
+### Done:
+  * SimpleTypeIdentifier
+  * MemberTypeIdentifier
+  * ArrayType
+  * DictionaryType
+  * MetatypeType
+  * OptionalType
+  * ImplicitlyUnwrappedOptionalType
+  * CompositionType
+  * TupleType
+  * FunctionType
+  * AttributedType
diff --git a/lib/Syntax/SyntaxBuilders.cpp.gyb b/lib/Syntax/SyntaxBuilders.cpp.gyb
index 389292a..0c6a46c 100644
--- a/lib/Syntax/SyntaxBuilders.cpp.gyb
+++ b/lib/Syntax/SyntaxBuilders.cpp.gyb
@@ -28,6 +28,12 @@
 % for node in SYNTAX_NODES:
 %   if node.is_buildable():
 %     for child in node.children:
+${node.name}Builder &
+${node.name}Builder::use${child.name}(${child.type_name} ${child.name}) {
+  Layout[cursorIndex(${node.name}::Cursor::${child.name})] =
+    ${child.name}.getRaw();
+  return *this;
+}
 %       child_node = NODE_MAP.get(child.syntax_kind)
 %       if child_node and child_node.is_syntax_collection():
 %         child_elt = child_node.collection_element_name
@@ -38,13 +44,6 @@
   raw = raw->append(${child_elt}.getRaw());
   return *this;
 }
-%       else:
-${node.name}Builder &
-${node.name}Builder::use${child.name}(${child.type_name} ${child.name}) {
-  Layout[cursorIndex(${node.name}::Cursor::${child.name})] =
-    ${child.name}.getRaw();
-  return *this;
-}
 %       end
 %     end
 ${node.name}
@@ -55,4 +54,4 @@
 }
 
 %   end
-% end
\ No newline at end of file
+% end
diff --git a/lib/Syntax/SyntaxData.cpp b/lib/Syntax/SyntaxData.cpp
index 75edefd..52804c8 100644
--- a/lib/Syntax/SyntaxData.cpp
+++ b/lib/Syntax/SyntaxData.cpp
@@ -41,7 +41,7 @@
 }
 
 bool SyntaxData::isPattern() const {
-  return false; // FIXME: Raw->isPattern();
+  return Raw->isPattern();
 }
 
 bool SyntaxData::isUnknown() const {
diff --git a/lib/Syntax/SyntaxFactory.cpp.gyb b/lib/Syntax/SyntaxFactory.cpp.gyb
index 08da63e..ae273d8 100644
--- a/lib/Syntax/SyntaxFactory.cpp.gyb
+++ b/lib/Syntax/SyntaxFactory.cpp.gyb
@@ -130,6 +130,28 @@
               return false;
             }
         },
+%       elif child.text_choices:
+        {   ${option},
+            [](const Syntax &S) {
+              // check ${child.name}.
+              if (auto Tok = S.getAs<TokenSyntax>()) {
+                auto Text = Tok->getText();
+%           tok_checks = []
+%           for choice in child.text_choices:
+%             tok_checks.append("Text == \"%s\"" % choice)
+%           end
+%           all_checks = ' || '.join(tok_checks)
+                return ${all_checks};
+              }
+              return false;
+            }
+        },
+%       elif child.node_choices:
+        {   ${option},
+            [] (const Syntax &S) {
+              return check${child.name}In${node.syntax_kind}(S);
+            }
+        },
 %       else:
         {   ${option},
             [](const Syntax &S) {
@@ -203,28 +225,6 @@
   }
 }
 
-SyntaxKind
-SyntaxFactory::getUnknownKind(SyntaxKind Kind) {
-  switch(Kind) {
-% for node in SYNTAX_NODES:
-%   if node.syntax_kind.endswith('Expr'):
-%     Result = 'SyntaxKind::UnknownExpr'
-%   elif node.syntax_kind.endswith('Stmt'):
-%     Result = 'SyntaxKind::UnknownStmt'
-%   elif node.syntax_kind.endswith('Decl'):
-%     Result = 'SyntaxKind::UnknownDecl'
-%   elif node.syntax_kind.endswith('Token'):
-%     Result = 'SyntaxKind::UnknownToken'
-%   else:
-%     Result = 'SyntaxKind::Unknown'
-%   end
-  case SyntaxKind::${node.syntax_kind}: return ${Result};
-% end
-  default:
-    return SyntaxKind::Unknown;
-  }
-}
-
 % for node in SYNTAX_NODES:
 %   if node.children:
 %     child_params = []
@@ -307,17 +307,20 @@
                        makeRightParenToken({}, {}));
 }
 
-TupleTypeElementSyntax SyntaxFactory::makeTupleTypeElement(
-    llvm::Optional<TokenSyntax> Label,
-    llvm::Optional<TokenSyntax> Colon, TypeSyntax Type,
-    llvm::Optional<TokenSyntax> TrailingComma) {
-  auto annotation = makeTypeAnnotation(makeBlankAttributeList(), None, Type);
-  return makeTupleTypeElement(Label, Colon, annotation, TrailingComma);
+TupleTypeElementSyntax
+SyntaxFactory::makeTupleTypeElement(llvm::Optional<TokenSyntax> Label,
+                                    llvm::Optional<TokenSyntax> Colon,
+                                    TypeSyntax Type,
+                                    llvm::Optional<TokenSyntax> TrailingComma) {
+  return makeTupleTypeElement(None, Label, None, Colon, Type, None, None,
+                              TrailingComma);
 }
 
-TupleTypeElementSyntax SyntaxFactory::makeTupleTypeElement(TypeSyntax Type,
-    llvm::Optional<TokenSyntax> TrailingComma) {
-  return makeTupleTypeElement(None, None, Type, TrailingComma);
+TupleTypeElementSyntax
+SyntaxFactory::makeTupleTypeElement(TypeSyntax Type,
+                                    llvm::Optional<TokenSyntax> TrailingComma) {
+  return makeTupleTypeElement(None, None, None, None, Type, None, None,
+                              TrailingComma);
 }
 
 GenericParameterSyntax
diff --git a/lib/Syntax/SyntaxKind.cpp.gyb b/lib/Syntax/SyntaxKind.cpp.gyb
index f45ceee..b7e09ad 100644
--- a/lib/Syntax/SyntaxKind.cpp.gyb
+++ b/lib/Syntax/SyntaxKind.cpp.gyb
@@ -84,5 +84,19 @@
          Kind == SyntaxKind::UnknownType ||
          Kind == SyntaxKind::UnknownPattern;
 }
+
+SyntaxKind getUnknownKind(SyntaxKind Kind) {
+  if (isExprKind(Kind))
+    return SyntaxKind::UnknownExpr;
+  if (isStmtKind(Kind))
+    return SyntaxKind::UnknownStmt;
+  if (isDeclKind(Kind))
+    return SyntaxKind::UnknownDecl;
+  if (isTypeKind(Kind))
+    return SyntaxKind::UnknownType;
+  if (isPatternKind(Kind))
+    return SyntaxKind::UnknownPattern;
+  return SyntaxKind::Unknown;
+}
 } // end namespace syntax
 } // end namespace swift
diff --git a/lib/Syntax/SyntaxNodes.cpp.gyb b/lib/Syntax/SyntaxNodes.cpp.gyb
index 9b51cf9..8333d23 100644
--- a/lib/Syntax/SyntaxNodes.cpp.gyb
+++ b/lib/Syntax/SyntaxNodes.cpp.gyb
@@ -24,6 +24,25 @@
 using namespace swift;
 using namespace swift::syntax;
 
+
+bool swift::syntax::
+checkAccessorListOrStmtListInAccessorBlock(const Syntax &S) {
+  return S.getKind() == SyntaxKind::AccessorList ||
+    S.getKind() == SyntaxKind::StmtList;
+}
+
+bool swift::syntax::checkInputInClosureSignature(const Syntax &S) {
+  return S.getKind() == SyntaxKind::ClosureParamList ||
+    S.getKind() == SyntaxKind::ParameterClause;
+}
+
+bool swift::syntax::checkContentInDictionaryExpr(const Syntax &S) {
+  if (auto Tok = S.getAs<TokenSyntax>()) {
+    return Tok->getTokenKind() == tok::colon;
+  }
+  return S.getKind() == SyntaxKind::DictionaryElementList;
+}
+
 % for node in SYNTAX_NODES:
 %   if node.requires_validation():
 void ${node.name}::validate() const {
@@ -41,9 +60,12 @@
 %         token_kind = child.main_token().kind
 %         choices = ", ".join("\"%s\"" % choice
 %                             for choice in child.text_choices)
-  syntax_assert_child_token_text(raw, ${child.name}, 
+  syntax_assert_child_token_text(raw, ${child.name},
                                  tok::${token_kind}, ${choices});
 %       end
+%       if child.node_choices:
+  syntax_assert_node_choice(raw, ${child.name}, ${node.syntax_kind});
+%       end
 %     end
 }
 %   end
diff --git a/lib/Syntax/SyntaxParsingContext.cpp b/lib/Syntax/SyntaxParsingContext.cpp
index 70bd8e9..4ad4542 100644
--- a/lib/Syntax/SyntaxParsingContext.cpp
+++ b/lib/Syntax/SyntaxParsingContext.cpp
@@ -47,7 +47,7 @@
     return Node->getRaw();
 
   // Fallback to unknown syntax for the category.
-  return makeUnknownSyntax(SyntaxFactory::getUnknownKind(Kind), Parts);
+  return makeUnknownSyntax(getUnknownKind(Kind), Parts);
 }
 
 } // End of anonymous namespace
diff --git a/lib/Syntax/Trivia.cpp b/lib/Syntax/Trivia.cpp
index e8ae752..a2f49f1 100644
--- a/lib/Syntax/Trivia.cpp
+++ b/lib/Syntax/Trivia.cpp
@@ -55,6 +55,9 @@
   case TriviaKind::Newline:
     OS << "newline " << Count;
     break;
+  case TriviaKind::CarriageReturn:
+    OS << "carriage_return " << Count;
+    break;
   case TriviaKind::LineComment:
     OS << "line_comment" << Text.str();
     break;
@@ -97,6 +100,7 @@
     Pos.addText(Text.str());
     break;
   case TriviaKind::Newline:
+  case TriviaKind::CarriageReturn:
     Pos.addNewlines(Count);
     break;
   case TriviaKind::Space:
@@ -126,6 +130,9 @@
   case TriviaKind::Newline:
     printRepeated(OS, '\n', Count);
     break;
+  case TriviaKind::CarriageReturn:
+    printRepeated(OS, '\r', Count);
+    break;
   case TriviaKind::LineComment:
   case TriviaKind::BlockComment:
   case TriviaKind::DocLineComment:
diff --git a/lib/TBDGen/TBDGen.cpp b/lib/TBDGen/TBDGen.cpp
index 46f8bbc..5767084 100644
--- a/lib/TBDGen/TBDGen.cpp
+++ b/lib/TBDGen/TBDGen.cpp
@@ -25,6 +25,7 @@
 #include "swift/SIL/FormalLinkage.h"
 #include "swift/SIL/SILDeclRef.h"
 #include "swift/SIL/SILWitnessTable.h"
+#include "swift/SIL/SILVTableVisitor.h"
 #include "swift/SIL/TypeLowering.h"
 #include "llvm/ADT/StringSet.h"
 
@@ -285,6 +286,37 @@
   }
 
   visitNominalTypeDecl(CD);
+
+  // The below symbols are only emitted if the class is resilient.
+  if (CD->hasFixedLayout())
+    return;
+
+  addSymbol(LinkEntity::forClassMetadataBaseOffset(CD));
+
+  // Emit dispatch thunks for every new vtable entry.
+  struct VTableVisitor : public SILVTableVisitor<VTableVisitor> {
+    TBDGenVisitor &TBD;
+    ClassDecl *CD;
+
+  public:
+    VTableVisitor(TBDGenVisitor &TBD, ClassDecl *CD)
+        : TBD(TBD), CD(CD) {}
+
+    void addMethod(SILDeclRef method) {
+      if (method.getDecl()->getDeclContext() == CD)
+        TBD.addSymbol(method.mangle(SILDeclRef::ManglingKind::SwiftDispatchThunk));
+    }
+
+    void addMethodOverride(SILDeclRef baseRef, SILDeclRef derivedRef) {}
+
+    void addPlaceholder(MissingMemberDecl *) {}
+
+    void doIt() {
+      addVTableEntries(CD);
+    }
+  };
+
+  VTableVisitor(*this, CD).doIt();
 }
 
 void TBDGenVisitor::visitConstructorDecl(ConstructorDecl *CD) {
@@ -327,12 +359,12 @@
 
 static void enumeratePublicSymbolsAndWrite(ModuleDecl *M, FileUnit *singleFile,
                                            StringSet &symbols,
-                                           bool hasMultipleIRGenThreads,
+                                           bool hasMultipleIGMs,
                                            llvm::raw_ostream *os,
                                            StringRef installName) {
   auto isWholeModule = singleFile == nullptr;
   const auto &target = M->getASTContext().LangOpts.Target;
-  UniversalLinkageInfo linkInfo(target, hasMultipleIRGenThreads, isWholeModule);
+  UniversalLinkageInfo linkInfo(target, hasMultipleIGMs, isWholeModule);
 
   TBDGenVisitor visitor(symbols, target, linkInfo, M, installName);
 
@@ -369,20 +401,18 @@
 }
 
 void swift::enumeratePublicSymbols(FileUnit *file, StringSet &symbols,
-                                   bool hasMultipleIRGenThreads) {
-  enumeratePublicSymbolsAndWrite(
-      file->getParentModule(), file, symbols, hasMultipleIRGenThreads,
-      nullptr, StringRef());
+                                   bool hasMultipleIGMs) {
+  enumeratePublicSymbolsAndWrite(file->getParentModule(), file, symbols,
+                                 hasMultipleIGMs, nullptr, StringRef());
 }
 void swift::enumeratePublicSymbols(ModuleDecl *M, StringSet &symbols,
-                                   bool hasMultipleIRGenThreads) {
-  enumeratePublicSymbolsAndWrite(M, nullptr, symbols, hasMultipleIRGenThreads,
-                                 nullptr, StringRef());
+                                   bool hasMultipleIGMs) {
+  enumeratePublicSymbolsAndWrite(M, nullptr, symbols, hasMultipleIGMs, nullptr,
+                                 StringRef());
 }
 void swift::writeTBDFile(ModuleDecl *M, llvm::raw_ostream &os,
-                         bool hasMultipleIRGenThreads,
-                         StringRef installName) {
+                         bool hasMultipleIGMs, StringRef installName) {
   StringSet symbols;
-  enumeratePublicSymbolsAndWrite(M, nullptr, symbols, hasMultipleIRGenThreads,
-                                 &os, installName);
+  enumeratePublicSymbolsAndWrite(M, nullptr, symbols, hasMultipleIGMs, &os,
+                                 installName);
 }
diff --git a/stdlib/private/StdlibCollectionUnittest/CheckCollectionType.swift.gyb b/stdlib/private/StdlibCollectionUnittest/CheckCollectionType.swift.gyb
index 00843b0..7e597d6 100644
--- a/stdlib/private/StdlibCollectionUnittest/CheckCollectionType.swift.gyb
+++ b/stdlib/private/StdlibCollectionUnittest/CheckCollectionType.swift.gyb
@@ -1584,6 +1584,11 @@
       .forEach(in: distanceFromToTests) {
       test in
       let c = toCollection(0..<20)
+      let backwards = (test.startOffset > test.endOffset)
+      if backwards && !collectionIsBidirectional {
+        expectCrashLater()
+      }
+
       let d = c.distance(
         from: c.nthIndex(test.startOffset), to: c.nthIndex(test.endOffset))
       expectEqual(
diff --git a/stdlib/private/StdlibCollectionUnittest/CheckMutableCollectionType.swift.gyb b/stdlib/private/StdlibCollectionUnittest/CheckMutableCollectionType.swift.gyb
index 75b39d1..00e5940 100644
--- a/stdlib/private/StdlibCollectionUnittest/CheckMutableCollectionType.swift.gyb
+++ b/stdlib/private/StdlibCollectionUnittest/CheckMutableCollectionType.swift.gyb
@@ -506,11 +506,6 @@
         let first = extractedResult[i].value
         let second = extractedResult[extractedResult.index(after: i)].value
         let result = lessImpl(second, first)
-        if result {
-          print("yep ** Result should be true \(result)")
-        } else {
-          print("yep ** Test passed result is false")
-        }
         expectFalse(result)
       }
     }
diff --git a/stdlib/private/StdlibCollectionUnittest/MinimalCollections.swift.gyb b/stdlib/private/StdlibCollectionUnittest/MinimalCollections.swift.gyb
index ae11f3c..ee364bf 100644
--- a/stdlib/private/StdlibCollectionUnittest/MinimalCollections.swift.gyb
+++ b/stdlib/private/StdlibCollectionUnittest/MinimalCollections.swift.gyb
@@ -657,6 +657,8 @@
   public func distance(from start: ${Index}, to end: ${Index})
     -> Int {
 %     if Traversal == 'Forward':
+    _precondition(start <= end,
+      "Only BidirectionalCollections can have end come before start")
 %     end
     // FIXME: swift-3-indexing-model: perform a range check properly.
     if start != endIndex {
diff --git a/stdlib/private/StdlibUnittest/StdlibUnittest.swift.gyb b/stdlib/private/StdlibUnittest/StdlibUnittest.swift.gyb
index f4a028f..00d5acb 100644
--- a/stdlib/private/StdlibUnittest/StdlibUnittest.swift.gyb
+++ b/stdlib/private/StdlibUnittest/StdlibUnittest.swift.gyb
@@ -542,6 +542,13 @@
   _seenExpectCrash = true
 }
 
+public func expectCrash(executing: () -> Void) -> Never {
+  expectCrashLater()
+  executing()
+  expectUnreachable()
+  fatalError()
+}
+
 func _defaultTestSuiteFailedCallback() {
   abort()
 }
diff --git a/stdlib/private/SwiftReflectionTest/SwiftReflectionTest.swift b/stdlib/private/SwiftReflectionTest/SwiftReflectionTest.swift
index 7661ed6..7b769eb 100644
--- a/stdlib/private/SwiftReflectionTest/SwiftReflectionTest.swift
+++ b/stdlib/private/SwiftReflectionTest/SwiftReflectionTest.swift
@@ -179,7 +179,7 @@
 /// process.
 internal func sendReflectionInfos() {
   debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
-  let infos = (0..<_dyld_image_count()).flatMap(getReflectionInfoForImage)
+  let infos = (0..<_dyld_image_count()).compactMap(getReflectionInfoForImage)
 
   var numInfos = infos.count
   debugLog("\(numInfos) reflection info bundles.")
diff --git a/stdlib/public/Reflection/TypeLowering.cpp b/stdlib/public/Reflection/TypeLowering.cpp
index d0de9e3..d2a55bb 100644
--- a/stdlib/public/Reflection/TypeLowering.cpp
+++ b/stdlib/public/Reflection/TypeLowering.cpp
@@ -975,7 +975,7 @@
       // further.
       if (CaseTI != nullptr) {
         // Below logic should match the runtime function
-        // swift_initEnumValueWitnessTableSinglePayload().
+        // swift_initEnumMetadataSinglePayload().
         NumExtraInhabitants = CaseTI->getNumExtraInhabitants();
         if (NumExtraInhabitants >= NoPayloadCases) {
           // Extra inhabitants can encode all no-payload cases.
diff --git a/stdlib/public/SDK/Accelerate/BNNS.swift.gyb b/stdlib/public/SDK/Accelerate/BNNS.swift.gyb
index 898e0a8..c2be935 100644
--- a/stdlib/public/SDK/Accelerate/BNNS.swift.gyb
+++ b/stdlib/public/SDK/Accelerate/BNNS.swift.gyb
@@ -23,13 +23,19 @@
   ('OSX','10.13'), ('iOS','11.0'), ('tvOS','11.0'), ('watchOS','4.0')
 ]
 
-def available(releases):
-  return '@available(' + ', '.join([
+def relString(releases):
+  if not releases:
+    return '*'
+  return ', '.join([
     r[0] + ' ' + r[1] for r in releases
-  ]) + ', *)'
+  ] + ['*'])
 
-def renamed(name):
+def available(releases):
+  return '@available(' + relString(releases) + ')'
+
+def renamed(name, rel=None):
   return '\n'.join([
+    available(rel),
     '@available(*, deprecated, renamed: "' + name + '")'
   ])
 
@@ -38,17 +44,18 @@
   impl = '    return __' + base + old + '\n  }'
   return '  ' + available(rel) + '\n' + decl + impl
 
-def oldEnumValue(base, new, old):
-  return renamed(base + '.' + new) + '\n' + \
+def oldEnumValue(base, new, old, oldRel):
+  return renamed(base + '.' + new, oldRel) + '\n' + \
   'public var ' + base + old + ' = __' + base + old
 
-def renameEnumMembers(base, names):
-  return 'extension ' + base + ' {\n' + \
+def renameEnumMembers(base, baseRel, names):
+  return available(baseRel) + \
+  '\nextension ' + base + ' {\n' + \
   '\n'.join([newEnumValue(base, new, old, rel) for new, old, rel in names]) + '\n}\n' + \
-  '\n'.join([oldEnumValue(base, new, old) for new, old, rel in names if rel != bnns2017])
+  '\n'.join([oldEnumValue(base, new, old, rel) for new, old, rel in names if rel != bnns2017])
 }%
 
-${renameEnumMembers('BNNSDataType', [
+${renameEnumMembers('BNNSDataType', bnns2016, [
   ('float16', 'Float16', bnns2016),
   ('float',   'Float32', bnns2016),
   ('int8',    'Int8',    bnns2016),
@@ -60,12 +67,12 @@
   ('indexed8','Indexed8',bnns2016),
 ])}
 
-${renameEnumMembers('BNNSPoolingFunction', [
+${renameEnumMembers('BNNSPoolingFunction', bnns2016, [
   ('max',     'Max',     bnns2016),
   ('average', 'Average', bnns2016),
 ])}
 
-${renameEnumMembers('BNNSActivationFunction', [
+${renameEnumMembers('BNNSActivationFunction', bnns2016, [
   ('identity', 'Identity', bnns2016),
   ('rectifiedLinear', 'RectifiedLinear', bnns2016),
   ('leakyRectifiedLinear', 'LeakyRectifiedLinear', bnns2016),
@@ -80,8 +87,9 @@
   ('softmax', 'Softmax', bnns2017),
 ])}
 
-${renameEnumMembers('BNNSFlags', [('useClientPointer', 'UseClientPtr', bnns2016)])}
+${renameEnumMembers('BNNSFlags', bnns2016, [('useClientPointer', 'UseClientPtr', bnns2016)])}
 
+${available(bnns2016)}
 extension BNNSImageStackDescriptor {
   ${available(bnns2016)}
   public init(width: Int,
@@ -105,6 +113,7 @@
   }
 }
 
+${available(bnns2016)}
 extension BNNSVectorDescriptor {
   ${available(bnns2016)}
   public init(size: Int,
@@ -120,6 +129,7 @@
   }
 }
 
+${available(bnns2016)}
 extension BNNSLayerData {
   ${available(bnns2016)}
   public init(data: UnsafeRawPointer?,
@@ -155,6 +165,7 @@
   }
 }
 
+${available(bnns2016)}
 extension BNNSActivation {
 
   ${available(bnns2016)}
@@ -226,6 +237,7 @@
   }
 }
 
+${available(bnns2016)}
 extension BNNSConvolutionLayerParameters {
   ${available(bnns2016)}
   public init(x_stride: Int,
@@ -251,6 +263,7 @@
   }
 }
 
+${available(bnns2016)}
 extension BNNSPoolingLayerParameters {
   ${available(bnns2016)}
   public init(x_stride: Int,
@@ -276,6 +289,7 @@
   }
 }
 
+${available(bnns2016)}
 extension BNNSFullyConnectedLayerParameters {
   ${available(bnns2016)}
   public init(in_size: Int,
diff --git a/stdlib/public/SDK/Foundation/JSONEncoder.swift b/stdlib/public/SDK/Foundation/JSONEncoder.swift
index 63ef116..dd40553 100644
--- a/stdlib/public/SDK/Foundation/JSONEncoder.swift
+++ b/stdlib/public/SDK/Foundation/JSONEncoder.swift
@@ -1212,7 +1212,7 @@
     // MARK: - KeyedDecodingContainerProtocol Methods
 
     public var allKeys: [Key] {
-        return self.container.keys.flatMap { Key(stringValue: $0) }
+        return self.container.keys.compactMap { Key(stringValue: $0) }
     }
 
     public func contains(_ key: Key) -> Bool {
diff --git a/stdlib/public/SDK/Foundation/PlistEncoder.swift b/stdlib/public/SDK/Foundation/PlistEncoder.swift
index 9544870..a480394 100644
--- a/stdlib/public/SDK/Foundation/PlistEncoder.swift
+++ b/stdlib/public/SDK/Foundation/PlistEncoder.swift
@@ -779,7 +779,7 @@
     // MARK: - KeyedDecodingContainerProtocol Methods
 
     public var allKeys: [Key] {
-        return self.container.keys.flatMap { Key(stringValue: $0) }
+        return self.container.keys.compactMap { Key(stringValue: $0) }
     }
 
     public func contains(_ key: Key) -> Bool {
diff --git a/stdlib/public/SwiftShims/RefCount.h b/stdlib/public/SwiftShims/RefCount.h
index e1cd7aa..8cec6d3 100644
--- a/stdlib/public/SwiftShims/RefCount.h
+++ b/stdlib/public/SwiftShims/RefCount.h
@@ -376,39 +376,6 @@
     setField(UseSlowRC, value);
   }
 
-    
-  // Returns true if the decrement is a fast-path result.
-  // Returns false if the decrement should fall back to some slow path
-  // (for example, because UseSlowRC is set
-  // or because the refcount is now zero and should deinit).
-  template <ClearPinnedFlag clearPinnedFlag>
-  LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE
-  bool doDecrementStrongExtraRefCount(uint32_t dec) {
-#ifndef NDEBUG
-    if (!hasSideTable()) {
-      // Can't check these assertions with side table present.
-      
-      // clearPinnedFlag assumes the flag is already set.
-      if (clearPinnedFlag)
-        assert(getIsPinned() && "unpinning reference that was not pinned");
-
-      if (getIsDeiniting())
-        assert(getStrongExtraRefCount() >= dec  &&  
-               "releasing reference whose refcount is already zero");
-      else 
-        assert(getStrongExtraRefCount() + 1 >= dec  &&  
-               "releasing reference whose refcount is already zero");
-    }
-#endif
-
-    BitsType unpin = (clearPinnedFlag
-                      ? (BitsType(1) << Offsets::IsPinnedShift)
-                      : 0);
-    // This deliberately underflows by borrowing from the UseSlowRC field.
-    bits -= unpin + (BitsType(dec) << Offsets::StrongExtraRefCountShift);
-    return (SignedBitsType(bits) >= 0);
-  }
-
   public:
 
   LLVM_ATTRIBUTE_ALWAYS_INLINE
@@ -553,15 +520,38 @@
     return (SignedBitsType(bits) >= 0);
   }
 
-  // FIXME: I don't understand why I can't make clearPinned a template argument
-  // (compiler balks at calls from class RefCounts that way)
+  // Returns true if the decrement is a fast-path result.
+  // Returns false if the decrement should fall back to some slow path
+  // (for example, because UseSlowRC is set
+  // or because the refcount is now zero and should deinit).
+  template <ClearPinnedFlag clearPinnedFlag>
   LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE
-  bool decrementStrongExtraRefCount(uint32_t dec, bool clearPinned = false) {
-    if (clearPinned) 
-      return doDecrementStrongExtraRefCount<DoClearPinnedFlag>(dec);
-    else
-      return doDecrementStrongExtraRefCount<DontClearPinnedFlag>(dec);
+  bool decrementStrongExtraRefCount(uint32_t dec) {
+#ifndef NDEBUG
+    if (!hasSideTable()) {
+      // Can't check these assertions with side table present.
+
+      // clearPinnedFlag assumes the flag is already set.
+      if (clearPinnedFlag)
+        assert(getIsPinned() && "unpinning reference that was not pinned");
+
+      if (getIsDeiniting())
+        assert(getStrongExtraRefCount() >= dec  &&
+               "releasing reference whose refcount is already zero");
+      else
+        assert(getStrongExtraRefCount() + 1 >= dec  &&
+               "releasing reference whose refcount is already zero");
+    }
+#endif
+
+    BitsType unpin = (clearPinnedFlag
+                      ? (BitsType(1) << Offsets::IsPinnedShift)
+                      : 0);
+    // This deliberately underflows by borrowing from the UseSlowRC field.
+    bits -= unpin + (BitsType(dec) << Offsets::StrongExtraRefCountShift);
+    return (SignedBitsType(bits) >= 0);
   }
+
   // Returns the old reference count before the increment.
   LLVM_ATTRIBUTE_ALWAYS_INLINE
   uint32_t incrementUnownedRefCount(uint32_t inc) {
@@ -1023,7 +1013,8 @@
     do {
       newbits = oldbits;
       
-      bool fast = newbits.decrementStrongExtraRefCount(dec, clearPinnedFlag);
+      bool fast =
+        newbits.template decrementStrongExtraRefCount<clearPinnedFlag>(dec);
       if (fast) {
         // Decrement completed normally. New refcount is not zero.
         deinitNow = false;
@@ -1062,7 +1053,8 @@
     bool deinitNow;
     auto newbits = oldbits;
 
-    bool fast = newbits.decrementStrongExtraRefCount(dec, clearPinnedFlag);
+    bool fast =
+      newbits.template decrementStrongExtraRefCount<clearPinnedFlag>(dec);
     if (fast) {
       // Decrement completed normally. New refcount is not zero.
       deinitNow = false;
@@ -1104,7 +1096,8 @@
     
     do {
       newbits = oldbits;
-      bool fast = newbits.decrementStrongExtraRefCount(dec, clearPinnedFlag);
+      bool fast =
+        newbits.template decrementStrongExtraRefCount<clearPinnedFlag>(dec);
       if (!fast)
         // Slow paths include side table; deinit; underflow
         return doDecrementSlow<clearPinnedFlag, performDeinit>(oldbits, dec);
@@ -1488,7 +1481,7 @@
     return doDecrementNonAtomicSlow<clearPinnedFlag, performDeinit>(oldbits, dec);
 
   auto newbits = oldbits;
-  bool fast = newbits.decrementStrongExtraRefCount(dec, clearPinnedFlag);
+  bool fast = newbits.decrementStrongExtraRefCount<clearPinnedFlag>(dec);
   if (!fast)
     return doDecrementNonAtomicSlow<clearPinnedFlag, performDeinit>(oldbits, dec);
 
diff --git a/stdlib/public/core/BidirectionalCollection.swift b/stdlib/public/core/BidirectionalCollection.swift
index da743bb..1e3d408 100644
--- a/stdlib/public/core/BidirectionalCollection.swift
+++ b/stdlib/public/core/BidirectionalCollection.swift
@@ -53,10 +53,10 @@
   associatedtype Index
 
   // FIXME(ABI): Associated type inference requires this.
-  associatedtype SubSequence = Slice<Self>
+  associatedtype SubSequence
 
   // FIXME(ABI): Associated type inference requires this.
-  associatedtype Indices = DefaultIndices<Self>
+  associatedtype Indices
 
   /// Returns the position immediately before the given index.
   ///
diff --git a/stdlib/public/core/CMakeLists.txt b/stdlib/public/core/CMakeLists.txt
index e91c0b9..3d41f4e 100644
--- a/stdlib/public/core/CMakeLists.txt
+++ b/stdlib/public/core/CMakeLists.txt
@@ -57,7 +57,7 @@
   Filter.swift
   FixedArray.swift.gyb
   FlatMap.swift
-  Flatten.swift.gyb
+  Flatten.swift
   FloatingPoint.swift.gyb
   FloatingPointParsing.swift.gyb
   FloatingPointTypes.swift.gyb
@@ -78,7 +78,7 @@
   Integers.swift.gyb
   Join.swift
   KeyPath.swift
-  LazyCollection.swift.gyb
+  LazyCollection.swift
   LazySequence.swift
   LifetimeManager.swift
   ManagedBuffer.swift
@@ -227,8 +227,6 @@
 list(APPEND swift_stdlib_compile_flags "-Xllvm" "-sil-inline-generics")
 list(APPEND swift_stdlib_compile_flags "-Xllvm" "-sil-partial-specialization")
 list(APPEND swift_stdlib_compile_flags "-Xfrontend" "-enable-sil-ownership")
-list(APPEND swift_stdlib_compile_flags
-     "-enable-experimental-conditional-conformances")
 
 if(SWIFT_CHECK_ESSENTIAL_STDLIB)
   add_swift_library(swift_stdlib_essential ${SWIFT_STDLIB_LIBRARY_BUILD_TYPES} IS_STDLIB IS_STDLIB_CORE
diff --git a/stdlib/public/core/Collection.swift b/stdlib/public/core/Collection.swift
index abd0980..0667050 100644
--- a/stdlib/public/core/Collection.swift
+++ b/stdlib/public/core/Collection.swift
@@ -701,11 +701,16 @@
 
   /// Returns the distance between two indices.
   ///
+  /// Unless the collection conforms to the `BidirectionalCollection` protocol,
+  /// `start` must be less than or equal to `end`.
+  ///
   /// - Parameters:
   ///   - start: A valid index of the collection.
   ///   - end: Another valid index of the collection. If `end` is equal to
   ///     `start`, the result is zero.
-  /// - Returns: The distance between `start` and `end`.
+  /// - Returns: The distance between `start` and `end`. The result can be
+  ///   negative only if the collection conforms to the
+  ///   `BidirectionalCollection` protocol.
   ///
   /// - Complexity: O(1) if the collection conforms to
   ///   `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
@@ -957,34 +962,30 @@
 
   /// Returns the distance between two indices.
   ///
+  /// Unless the collection conforms to the `BidirectionalCollection` protocol,
+  /// `start` must be less than or equal to `end`.
+  ///
   /// - Parameters:
   ///   - start: A valid index of the collection.
   ///   - end: Another valid index of the collection. If `end` is equal to
   ///     `start`, the result is zero.
-  /// - Returns: The distance between `start` and `end`.
+  /// - Returns: The distance between `start` and `end`. The result can be
+  ///   negative only if the collection conforms to the
+  ///   `BidirectionalCollection` protocol.
   ///
   /// - Complexity: O(1) if the collection conforms to
   ///   `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
   ///   resulting distance.
   @_inlineable
   public func distance(from start: Index, to end: Index) -> Int {
-    var _start: Index
-    let _end: Index
-    let step: Int
-    if start > end {
-      _start = end
-      _end = start
-      step = -1
-    }
-    else {
-      _start = start
-      _end = end
-      step = 1
-    }
+    _precondition(start <= end,
+      "Only BidirectionalCollections can have end come before start")
+
+    var start = start
     var count = 0
-    while _start != _end {
-      count += step
-      formIndex(after: &_start)
+    while start != end {
+      count = count + 1
+      formIndex(after: &start)
     }
     return count
   }
@@ -1705,7 +1706,6 @@
   public func index<T: BinaryInteger>(_ i: Index, offsetBy n: T) -> Index {
     return index(i, offsetBy: Int(n))
   }
-  /* FIXME: crashes the compiler
   @available(*, deprecated, message: "all index distances are now of type Int")
   public func formIndex<T: BinaryInteger>(_ i: Index, offsetBy n: T) {
     return formIndex(i, offsetBy: Int(n))
@@ -1714,7 +1714,6 @@
   public func index<T: BinaryInteger>(_ i: Index, offsetBy n: T, limitedBy limit: Index) -> Index {
     return index(i, offsetBy: Int(n), limitedBy: limit)
   }
-  */
   @available(*, deprecated, message: "all index distances are now of type Int")
   public func formIndex<T: BinaryInteger>(_ i: inout Index, offsetBy n: T, limitedBy limit: Index) -> Bool {
     return formIndex(&i, offsetBy: Int(n), limitedBy: limit)
diff --git a/stdlib/public/core/DoubleWidth.swift.gyb b/stdlib/public/core/DoubleWidth.swift.gyb
index 304f875..ff6f8c6 100644
--- a/stdlib/public/core/DoubleWidth.swift.gyb
+++ b/stdlib/public/core/DoubleWidth.swift.gyb
@@ -18,9 +18,14 @@
   public typealias High = Base
   public typealias Low = Base.Magnitude
 
+#if _endian(big)
   @_versioned // FIXME(sil-serialize-all)
-  internal var _storage: (high: Base, low: Base.Magnitude)
-  
+  internal var _storage: (high: High, low: Low)
+#else
+  @_versioned // FIXME(sil-serialize-all)
+  internal var _storage: (low: Low, high: High)
+#endif
+
   @_inlineable // FIXME(sil-serialize-all)
   public var high: High {
     return _storage.high
@@ -34,7 +39,11 @@
   @_inlineable // FIXME(sil-serialize-all)
   public // @testable
   init(_ _value: (High, Low)) {
+#if _endian(big)
     self._storage = (high: _value.0, low: _value.1)
+#else
+    self._storage = (low: _value.1, high: _value.0)
+#endif
   }
 
   @_inlineable // FIXME(sil-serialize-all)
@@ -187,8 +196,8 @@
   @_fixed_layout // FIXME(sil-serialize-all)
   public struct Words : Collection {
     public enum _IndexValue {
-      case low(Base.Magnitude.Words.Index)
-      case high(Base.Words.Index)
+      case low(Low.Words.Index)
+      case high(High.Words.Index)
     }
     
     @_fixed_layout // FIXME(sil-serialize-all)
@@ -218,8 +227,8 @@
       }
     }
 
-    public var _high: Base.Words
-    public var _low: Base.Magnitude.Words
+    public var _high: High.Words
+    public var _low: Low.Words
 
     @_inlineable // FIXME(sil-serialize-all)
     public init(_ value: DoubleWidth<Base>) {
diff --git a/stdlib/public/core/EmptyCollection.swift b/stdlib/public/core/EmptyCollection.swift
index d893877..3036907 100644
--- a/stdlib/public/core/EmptyCollection.swift
+++ b/stdlib/public/core/EmptyCollection.swift
@@ -17,24 +17,6 @@
 //
 //===----------------------------------------------------------------------===//
 
-/// An iterator that never produces an element.
-@_fixed_layout // FIXME(sil-serialize-all)
-public struct EmptyIterator<Element> {
-  // no properties
-  
-  /// Creates an instance.
-  @_inlineable // FIXME(sil-serialize-all)
-  public init() {}
-}
-
-extension EmptyIterator: IteratorProtocol, Sequence {
-  /// Returns `nil`, indicating that there are no more elements.
-  @_inlineable // FIXME(sil-serialize-all)
-  public mutating func next() -> Element? {
-    return nil
-  }
-}
-
 /// A collection whose element type is `Element` but that is always empty.
 @_fixed_layout // FIXME(sil-serialize-all)
 public struct EmptyCollection<Element> {
@@ -45,6 +27,34 @@
   public init() {}
 }
 
+extension EmptyCollection {
+  /// An iterator that never produces an element.
+  @_fixed_layout // FIXME(sil-serialize-all)
+  public struct Iterator {
+    // no properties
+  
+    /// Creates an instance.
+    @_inlineable // FIXME(sil-serialize-all)
+    public init() {}
+  }  
+}
+
+extension EmptyCollection.Iterator: IteratorProtocol, Sequence {
+  /// Returns `nil`, indicating that there are no more elements.
+  @_inlineable // FIXME(sil-serialize-all)
+  public mutating func next() -> Element? {
+    return nil
+  }
+}
+
+extension EmptyCollection: Sequence {
+  /// Returns an empty iterator.
+  @_inlineable // FIXME(sil-serialize-all)
+  public func makeIterator() -> Iterator {
+    return Iterator()
+  }
+}
+
 extension EmptyCollection: RandomAccessCollection, MutableCollection {
   /// A type that represents a valid position in the collection.
   ///
@@ -84,12 +94,6 @@
     _preconditionFailure("EmptyCollection can't advance indices")
   }
 
-  /// Returns an empty iterator.
-  @_inlineable // FIXME(sil-serialize-all)
-  public func makeIterator() -> EmptyIterator<Element> {
-    return EmptyIterator()
-  }
-
   /// Accesses the element at the given position.
   ///
   /// Must never be called, since this collection is always empty.
@@ -104,7 +108,7 @@
   }
 
   @_inlineable // FIXME(sil-serialize-all)
-  public subscript(bounds: Range<Index>) -> EmptyCollection<Element> {
+  public subscript(bounds: Range<Index>) -> SubSequence {
     get {
       _debugPrecondition(bounds.lowerBound == 0 && bounds.upperBound == 0,
         "Index out of range")
@@ -171,3 +175,6 @@
     return true
   }
 }
+
+// @available(*, deprecated, renamed: "EmptyCollection.Iterator")
+public typealias EmptyIterator<T> = EmptyCollection<T>.Iterator
diff --git a/stdlib/public/core/Filter.swift b/stdlib/public/core/Filter.swift
index 668311c..1180a98 100644
--- a/stdlib/public/core/Filter.swift
+++ b/stdlib/public/core/Filter.swift
@@ -10,15 +10,62 @@
 //
 //===----------------------------------------------------------------------===//
 
-/// An iterator over the elements traversed by some base iterator that also
-/// satisfy a given predicate.
+
+/// A sequence whose elements consist of the elements of some base
+/// sequence that also satisfy a given predicate.
 ///
-/// - Note: This is the associated `Iterator` of `LazyFilterSequence`
-/// and `LazyFilterCollection`.
+/// - Note: `s.lazy.filter { ... }`, for an arbitrary sequence `s`,
+///   is a `LazyFilterSequence`.
 @_fixed_layout // FIXME(sil-serialize-all)
-public struct LazyFilterIterator<
-  Base : IteratorProtocol
-> : IteratorProtocol, Sequence {
+public struct LazyFilterSequence<Base: Sequence> {
+  @_versioned // FIXME(sil-serialize-all)
+  internal var _base: Base
+
+  /// The predicate used to determine which elements produced by
+  /// `base` are also produced by `self`.
+  @_versioned // FIXME(sil-serialize-all)
+  internal let _predicate: (Base.Element) -> Bool
+
+  /// Creates an instance consisting of the elements `x` of `base` for
+  /// which `isIncluded(x) == true`.
+  @_inlineable // FIXME(sil-serialize-all)
+  public // @testable
+  init(_base base: Base, _ isIncluded: @escaping (Base.Element) -> Bool) {
+    self._base = base
+    self._predicate = isIncluded
+  }
+}
+
+extension LazyFilterSequence {
+  /// An iterator over the elements traversed by some base iterator that also
+  /// satisfy a given predicate.
+  ///
+  /// - Note: This is the associated `Iterator` of `LazyFilterSequence`
+  /// and `LazyFilterCollection`.
+  @_fixed_layout // FIXME(sil-serialize-all)
+  public struct Iterator {
+    /// The underlying iterator whose elements are being filtered.
+    public var base: Base.Iterator { return _base }
+
+    @_versioned // FIXME(sil-serialize-all)
+    internal var _base: Base.Iterator
+    @_versioned // FIXME(sil-serialize-all)
+    internal let _predicate: (Base.Element) -> Bool
+
+    /// Creates an instance that produces the elements `x` of `base`
+    /// for which `isIncluded(x) == true`.
+    @_inlineable // FIXME(sil-serialize-all)
+    @_versioned // FIXME(sil-serialize-all)
+    internal init(_base: Base.Iterator, _ isIncluded: @escaping (Base.Element) -> Bool) {
+      self._base = _base
+      self._predicate = isIncluded
+    }
+  }
+}
+
+extension LazyFilterSequence.Iterator: IteratorProtocol, Sequence {
+  public typealias Element = Base.Element
+  
   /// Advances to the next element and returns it, or `nil` if no next element
   /// exists.
   ///
@@ -27,7 +74,7 @@
   /// - Precondition: `next()` has not been applied to a copy of `self`
   ///   since the copy was made.
   @_inlineable // FIXME(sil-serialize-all)
-  public mutating func next() -> Base.Element? {
+  public mutating func next() -> Element? {
     while let n = _base.next() {
       if _predicate(n) {
         return n
@@ -35,87 +82,25 @@
     }
     return nil
   }
-
-  /// Creates an instance that produces the elements `x` of `base`
-  /// for which `isIncluded(x) == true`.
-  @_inlineable // FIXME(sil-serialize-all)
-  @_versioned // FIXME(sil-serialize-all)
-  internal init(
-    _base: Base,
-    _ isIncluded: @escaping (Base.Element) -> Bool
-  ) {
-    self._base = _base
-    self._predicate = isIncluded
-  }
-
-  /// The underlying iterator whose elements are being filtered.
-  public var base: Base { return _base }
-
-  @_versioned // FIXME(sil-serialize-all)
-  internal var _base: Base
-
-  /// The predicate used to determine which elements produced by
-  /// `base` are also produced by `self`.
-  @_versioned // FIXME(sil-serialize-all)
-  internal let _predicate: (Base.Element) -> Bool
 }
 
-/// A sequence whose elements consist of the elements of some base
-/// sequence that also satisfy a given predicate.
-///
-/// - Note: `s.lazy.filter { ... }`, for an arbitrary sequence `s`,
-///   is a `LazyFilterSequence`.
-@_fixed_layout // FIXME(sil-serialize-all)
-public struct LazyFilterSequence<Base : Sequence>
-  : LazySequenceProtocol {
-
+extension LazyFilterSequence: LazySequenceProtocol {
   /// Returns an iterator over the elements of this sequence.
   ///
   /// - Complexity: O(1).
   @_inlineable // FIXME(sil-serialize-all)
-  public func makeIterator() -> LazyFilterIterator<Base.Iterator> {
-    return LazyFilterIterator(
-      _base: base.makeIterator(), _include)
+  public func makeIterator() -> Iterator {
+    return Iterator(_base: _base.makeIterator(), _predicate)
   }
 
   @_inlineable
-  public func _customContainsEquatableElement(
-    _ element: Element
-  ) -> Bool? {
-    if !_include(element) {
-      return false
-    }
-    if let baseContains = base._customContainsEquatableElement(element) {
-      return baseContains
-    }
-    return nil
+  public func _customContainsEquatableElement(_ element: Element) -> Bool? {
+    // optimization to check the element first matches the predicate
+    guard _predicate(element) else { return false }
+    return _base._customContainsEquatableElement(element)
   }
-
-  /// Creates an instance consisting of the elements `x` of `base` for
-  /// which `isIncluded(x) == true`.
-  @_inlineable // FIXME(sil-serialize-all)
-  public // @testable
-  init(
-    _base base: Base,
-    _ isIncluded: @escaping (Base.Element) -> Bool
-  ) {
-    self.base = base
-    self._include = isIncluded
-  }
-
-  /// The underlying sequence whose elements are being filtered
-  public let base: Base
-
-  /// The predicate used to determine which elements of `base` are
-  /// also elements of `self`.
-  @_versioned // FIXME(sil-serialize-all)
-  internal let _include: (Base.Element) -> Bool
 }
 
-/// The `Index` used for subscripting a `LazyFilterCollection`.
-@available(swift, deprecated: 3.1, obsoleted: 4.0, message: "Use Base.Index")
-public typealias LazyFilterIndex<Base : Collection> = Base.Index
-
 /// A lazy `Collection` wrapper that includes the elements of an
 /// underlying collection that satisfy a predicate.
 ///
@@ -136,18 +121,16 @@
   /// satisfy `isIncluded`.
   @_inlineable // FIXME(sil-serialize-all)
   public // @testable
-  init(
-    _base: Base,
-    _ isIncluded: @escaping (Base.Element) -> Bool
-  ) {
+  init(_base: Base, _ isIncluded: @escaping (Base.Element) -> Bool) {
     self._base = _base
     self._predicate = isIncluded
   }
 }
 
-extension LazyFilterCollection : Sequence {
-  public typealias SubSequence = LazyFilterCollection<Base.SubSequence>
+extension LazyFilterCollection : LazySequenceProtocol {
   public typealias Element = Base.Element
+  public typealias Iterator = LazyFilterSequence<Base>.Iterator
+  public typealias SubSequence = LazyFilterCollection<Base.SubSequence>
 
   // Any estimate of the number of elements that pass `_predicate` requires
   // iterating the collection and evaluating each element, which can be costly,
@@ -157,8 +140,7 @@
   public var underestimatedCount: Int { return 0 }
 
   @_inlineable // FIXME(sil-serialize-all)
-  public func _copyToContiguousArray()
-    -> ContiguousArray<Base.Iterator.Element> {
+  public func _copyToContiguousArray() -> ContiguousArray<Base.Element> {
 
     // The default implementation of `_copyToContiguousArray` queries the
     // `count` property, which evaluates `_predicate` for every element --
@@ -171,26 +153,18 @@
   ///
   /// - Complexity: O(1).
   @_inlineable // FIXME(sil-serialize-all)
-  public func makeIterator() -> LazyFilterIterator<Base.Iterator> {
-    return LazyFilterIterator(
-      _base: _base.makeIterator(), _predicate)
+  public func makeIterator() -> Iterator {
+    return Iterator(_base: _base.makeIterator(), _predicate)
   }
 
   @_inlineable
-  public func _customContainsEquatableElement(
-    _ element: Element
-  ) -> Bool? {
-    if !_predicate(element) {
-      return false
-    }
-    if let baseContains = _base._customContainsEquatableElement(element) {
-      return baseContains
-    }
-    return nil
+  public func _customContainsEquatableElement(_ element: Element) -> Bool? {
+    guard _predicate(element) else { return false }
+    return _base._customContainsEquatableElement(element)
   }
 }
 
-extension LazyFilterCollection : LazyCollectionProtocol, Collection {
+extension LazyFilterCollection : LazyCollectionProtocol {
   /// A type that represents a valid position in the collection.
   ///
   /// Valid indices consist of the position of every element and a
@@ -245,9 +219,9 @@
   @_inlineable // FIXME(sil-serialize-all)
   @_versioned // FIXME(sil-serialize-all)
   internal func _advanceIndex(_ i: inout Index, step: Int) {
-      repeat {
-        _base.formIndex(&i, offsetBy: step)
-      } while i != _base.endIndex && !_predicate(_base[i])
+    repeat {
+      _base.formIndex(&i, offsetBy: step)
+    } while i != _base.endIndex && !_predicate(_base[i])
   }
 
   @inline(__always)
@@ -266,6 +240,33 @@
   }
 
   @_inlineable // FIXME(sil-serialize-all)
+  public func distance(from start: Index, to end: Index) -> Int {
+    // The following line makes sure that distance(from:to:) is invoked on the
+    // _base at least once, to trigger a _precondition in forward only
+    // collections.
+    _ = _base.distance(from: start, to: end)
+    var _start: Index
+    let _end: Index
+    let step: Int
+    if start > end {
+      _start = end
+      _end = start
+      step = -1
+    }
+    else {
+      _start = start
+      _end = end
+      step = 1
+    }
+    var count = 0
+    while _start != _end {
+      count += step
+      formIndex(after: &_start)
+    }
+    return count
+  }
+
+  @_inlineable // FIXME(sil-serialize-all)
   public func index(_ i: Index, offsetBy n: Int) -> Index {
     var i = i
     let step = n.signum()
@@ -320,7 +321,7 @@
   /// - Precondition: `position` is a valid position in `self` and
   /// `position != endIndex`.
   @_inlineable // FIXME(sil-serialize-all)
-  public subscript(position: Index) -> Base.Element {
+  public subscript(position: Index) -> Element {
     return _base[position]
   }
 
@@ -382,5 +383,10 @@
   }
 }
 
+// @available(*, deprecated, renamed: "LazyFilterSequence.Iterator")
+public typealias LazyFilterIterator<T: Sequence> = LazyFilterSequence<T>.Iterator
+// @available(swift, deprecated: 3.1, obsoleted: 4.0, message: "Use Base.Index")
+public typealias LazyFilterIndex<Base: Collection> = Base.Index
 @available(*, deprecated, renamed: "LazyFilterCollection")
 public typealias LazyFilterBidirectionalCollection<T> = LazyFilterCollection<T> where T : BidirectionalCollection
+
diff --git a/stdlib/public/core/FlatMap.swift b/stdlib/public/core/FlatMap.swift
index 33b2757..6b3fac5 100644
--- a/stdlib/public/core/FlatMap.swift
+++ b/stdlib/public/core/FlatMap.swift
@@ -27,7 +27,7 @@
     FlattenSequence<LazyMapSequence<Elements, SegmentOfResult>>> {
     return self.map(transform).joined()
   }
-  
+
   /// Returns the non-`nil` results of mapping the given transformation over
   /// this sequence.
   ///
@@ -39,7 +39,7 @@
   ///
   /// - Complexity: O(1)
   @_inlineable // FIXME(sil-serialize-all)
-  public func flatMap<ElementOfResult>(
+  public func compactMap<ElementOfResult>(
     _ transform: @escaping (Elements.Element) -> ElementOfResult?
   ) -> LazyMapSequence<
     LazyFilterSequence<
@@ -48,6 +48,28 @@
   > {
     return self.map(transform).filter { $0 != nil }.map { $0! }
   }
+
+  /// Returns the non-`nil` results of mapping the given transformation over
+  /// this sequence.
+  ///
+  /// Use this method to receive a sequence of nonoptional values when your
+  /// transformation produces an optional value.
+  ///
+  /// - Parameter transform: A closure that accepts an element of this sequence
+  ///   as its argument and returns an optional value.
+  ///
+  /// - Complexity: O(1)
+  @inline(__always)
+  @available(*, deprecated, renamed: "compactMap(_:)")
+  public func flatMap<ElementOfResult>(
+    _ transform: @escaping (Elements.Element) -> ElementOfResult?
+  ) -> LazyMapSequence<
+    LazyFilterSequence<
+      LazyMapSequence<Elements, ElementOfResult?>>,
+    ElementOfResult
+  > {
+    return self.compactMap(transform)
+  }
 }
 
 extension LazyCollectionProtocol {
@@ -69,7 +91,7 @@
   > {
     return self.map(transform).joined()
   }
-  
+
   /// Returns the non-`nil` results of mapping the given transformation over
   /// this collection.
   ///
@@ -81,7 +103,7 @@
   ///
   /// - Complexity: O(1)
   @_inlineable // FIXME(sil-serialize-all)
-  public func flatMap<ElementOfResult>(
+  public func compactMap<ElementOfResult>(
     _ transform: @escaping (Elements.Element) -> ElementOfResult?
   ) -> LazyMapCollection<
     LazyFilterCollection<
@@ -90,30 +112,7 @@
   > {
     return self.map(transform).filter { $0 != nil }.map { $0! }
   }
-}
 
-extension LazyCollectionProtocol
-  where
-  Self : BidirectionalCollection,
-  Elements : BidirectionalCollection {
-  /// Returns the concatenated results of mapping the given transformation over
-  /// this collection.
-  ///
-  /// Use this method to receive a single-level collection when your
-  /// transformation produces a collection for each element.
-  /// Calling `flatMap(_:)` on a collection `c` is equivalent to calling
-  /// `c.map(transform).joined()`.
-  ///
-  /// - Complexity: O(1)
-  @_inlineable // FIXME(sil-serialize-all)
-  public func flatMap<SegmentOfResult>(
-    _ transform: @escaping (Elements.Element) -> SegmentOfResult
-  ) -> LazyCollection<
-    FlattenBidirectionalCollection<
-      LazyMapCollection<Elements, SegmentOfResult>>> {
-    return self.map(transform).joined()
-  }
-  
   /// Returns the non-`nil` results of mapping the given transformation over
   /// this collection.
   ///
@@ -124,6 +123,7 @@
   ///   collection as its argument and returns an optional value.
   ///
   /// - Complexity: O(1)
+  @available(*, deprecated, renamed: "compactMap(_:)")
   @_inlineable // FIXME(sil-serialize-all)
   public func flatMap<ElementOfResult>(
     _ transform: @escaping (Elements.Element) -> ElementOfResult?
diff --git a/stdlib/public/core/Flatten.swift b/stdlib/public/core/Flatten.swift
new file mode 100644
index 0000000..9a2733c
--- /dev/null
+++ b/stdlib/public/core/Flatten.swift
@@ -0,0 +1,573 @@
+//===--- Flatten.swift ----------------------------------------*- swift -*-===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+
+/// A sequence consisting of all the elements contained in each segment
+/// contained in some `Base` sequence.
+///
+/// The elements of this view are a concatenation of the elements of
+/// each sequence in the base.
+///
+/// The `joined` method is always lazy, but does not implicitly
+/// confer laziness on algorithms applied to its result.  In other
+/// words, for ordinary sequences `s`:
+///
+/// * `s.joined()` does not create new storage
+/// * `s.joined().map(f)` maps eagerly and returns a new array
+/// * `s.lazy.joined().map(f)` maps lazily and returns a `LazyMapSequence`
+///
+/// - See also: `FlattenCollection`
+@_fixed_layout // FIXME(sil-serialize-all)
+public struct FlattenSequence<Base: Sequence> where Base.Element: Sequence {
+
+  @_versioned // FIXME(sil-serialize-all)
+  internal var _base: Base
+
+  /// Creates a concatenation of the elements of the elements of `base`.
+  ///
+  /// - Complexity: O(1)
+  @_inlineable // FIXME(sil-serialize-all)
+  @_versioned // FIXME(sil-serialize-all)
+  internal init(_base: Base) {
+    self._base = _base
+  }
+}
+
+extension FlattenSequence {
+  @_fixed_layout // FIXME(sil-serialize-all)
+  public struct Iterator {
+    @_versioned // FIXME(sil-serialize-all)
+    internal var _base: Base.Iterator
+    @_versioned // FIXME(sil-serialize-all)
+    internal var _inner: Base.Element.Iterator?
+
+    /// Construct around a `base` iterator.
+    @_inlineable // FIXME(sil-serialize-all)
+    @_versioned // FIXME(sil-serialize-all)
+    internal init(_base: Base.Iterator) {
+      self._base = _base
+    }
+  }
+}
+
+extension FlattenSequence.Iterator: IteratorProtocol {
+  public typealias Element = Base.Element.Element
+  
+  /// Advances to the next element and returns it, or `nil` if no next element
+  /// exists.
+  ///
+  /// Once `nil` has been returned, all subsequent calls return `nil`.
+  ///
+  /// - Precondition: `next()` has not been applied to a copy of `self`
+  ///   since the copy was made.
+  @_inlineable // FIXME(sil-serialize-all)
+  public mutating func next() -> Element? {
+    repeat {
+      if _fastPath(_inner != nil) {
+        let ret = _inner!.next()
+        if _fastPath(ret != nil) {
+          return ret
+        }
+      }
+      let s = _base.next()
+      if _slowPath(s == nil) {
+        return nil
+      }
+      _inner = s!.makeIterator()
+    }
+    while true
+  }
+}
+
+extension FlattenSequence: Sequence {
+  /// Returns an iterator over the elements of this sequence.
+  ///
+  /// - Complexity: O(1).
+  @_inlineable // FIXME(sil-serialize-all)
+  public func makeIterator() -> Iterator {
+    return Iterator(_base: _base.makeIterator())
+  }
+}
+
+extension Sequence where Element : Sequence {
+  /// Returns the elements of this sequence of sequences, concatenated.
+  ///
+  /// In this example, an array of three ranges is flattened so that the
+  /// elements of each range can be iterated in turn.
+  ///
+  ///     let ranges = [0..<3, 8..<10, 15..<17]
+  ///
+  ///     // A for-in loop over 'ranges' accesses each range:
+  ///     for range in ranges {
+  ///       print(range)
+  ///     }
+  ///     // Prints "0..<3"
+  ///     // Prints "8..<10"
+  ///     // Prints "15..<17"
+  ///
+  ///     // Use 'joined()' to access each element of each range:
+  ///     for index in ranges.joined() {
+  ///         print(index, terminator: " ")
+  ///     }
+  ///     // Prints: "0 1 2 8 9 15 16"
+  ///
+  /// - Returns: A flattened view of the elements of this
+  ///   sequence of sequences.
+  @_inlineable // FIXME(sil-serialize-all)
+  public func joined() -> FlattenSequence<Self> {
+    return FlattenSequence(_base: self)
+  }
+}
+
+extension LazySequenceProtocol where Element : Sequence {
+  /// Returns a lazy sequence that concatenates the elements of this sequence of
+  /// sequences.
+  @_inlineable // FIXME(sil-serialize-all)
+  public func joined() -> LazySequence<FlattenSequence<Elements>> {
+    return FlattenSequence(_base: elements).lazy
+  }
+}
+
+/// A flattened view of a base collection of collections.
+///
+/// The elements of this view are a concatenation of the elements of
+/// each collection in the base.
+///
+/// The `joined` method is always lazy, but does not implicitly
+/// confer laziness on algorithms applied to its result.  In other
+/// words, for ordinary collections `c`:
+///
+/// * `c.joined()` does not create new storage
+/// * `c.joined().map(f)` maps eagerly and returns a new array
+/// * `c.lazy.joined().map(f)` maps lazily and returns a `LazyMapCollection`
+///
+/// - Note: The performance of accessing `startIndex`, `first`, any methods
+///   that depend on `startIndex`, or of advancing an `Index`
+///   depends on how many empty subcollections are found in the base
+///   collection, and may not offer the usual performance given by `Collection`
+///   or `Index`. Be aware, therefore, that general operation on
+///   `FlattenCollection` instances may not have the documented complexity.
+///
+/// - See also: `FlattenSequence`
+@_fixed_layout // FIXME(sil-serialize-all)
+public struct FlattenCollection<Base>
+  where Base : Collection, Base.Element : Collection {
+  @_versioned // FIXME(sil-serialize-all)
+  internal var _base: Base
+
+  /// Creates a flattened view of `base`.
+  @_inlineable // FIXME(sil-serialize-all)
+  public init(_ base: Base) {
+    self._base = base
+  }
+}
+
+extension FlattenCollection {
+  /// A position in a FlattenCollection
+  @_fixed_layout // FIXME(sil-serialize-all)
+  public struct Index {
+    /// The position in the outer collection of collections.
+    @_versioned // FIXME(sil-serialize-all)
+    internal let _outer: Base.Index
+
+    /// The position in the inner collection at `base[_outer]`, or `nil` if
+    /// `_outer == base.endIndex`.
+    ///
+    /// When `_inner != nil`, `_inner!` is a valid subscript of `base[_outer]`;
+    /// when `_inner == nil`, `_outer == base.endIndex` and this index is
+    /// `endIndex` of the `FlattenCollection`.
+    @_versioned // FIXME(sil-serialize-all)
+    internal let _inner: Base.Element.Index?
+
+    @_inlineable // FIXME(sil-serialize-all)
+    @_versioned // FIXME(sil-serialize-all)
+    internal init(_ _outer: Base.Index, _ inner: Base.Element.Index?) {
+      self._outer = _outer
+      self._inner = inner
+    }
+  }
+}
+
+extension FlattenCollection.Index : Equatable {
+  @_inlineable // FIXME(sil-serialize-all)
+  public static func == (
+    lhs: FlattenCollection<Base>.Index,
+    rhs: FlattenCollection<Base>.Index
+  ) -> Bool {
+    return lhs._outer == rhs._outer && lhs._inner == rhs._inner
+  }
+}
+
+extension FlattenCollection.Index : Comparable {
+  @_inlineable // FIXME(sil-serialize-all)
+  public static func < (
+    lhs: FlattenCollection<Base>.Index,
+    rhs: FlattenCollection<Base>.Index
+  ) -> Bool {
+    // FIXME: swift-3-indexing-model: tests.
+    if lhs._outer != rhs._outer {
+      return lhs._outer < rhs._outer
+    }
+
+    if let lhsInner = lhs._inner, let rhsInner = rhs._inner {
+      return lhsInner < rhsInner
+    }
+
+    // When combined, the two conditions above guarantee that both
+    // `_outer` indices are `_base.endIndex` and both `_inner` indices
+    // are `nil`, since `_inner` is `nil` iff `_outer == base.endIndex`.
+    _precondition(lhs._inner == nil && rhs._inner == nil)
+
+    return false
+  }
+}
+
+extension FlattenCollection.Index : Hashable
+  where Base.Index : Hashable, Base.Element.Index : Hashable {
+  public var hashValue: Int {
+    return _mixInt(_inner?.hashValue ?? 0) ^ _outer.hashValue
+  }
+}
+
+extension FlattenCollection : Sequence {
+  public typealias Iterator = FlattenSequence<Base>.Iterator
+  public typealias SubSequence = Slice<FlattenCollection>
+
+  /// Returns an iterator over the elements of this sequence.
+  ///
+  /// - Complexity: O(1).
+  @_inlineable // FIXME(sil-serialize-all)
+  public func makeIterator() -> Iterator {
+    return Iterator(_base: _base.makeIterator())
+  }
+
+  // To return any estimate of the number of elements, we have to start
+  // evaluating the collections.  That is a bad default for `flatMap()`, so
+  // just return zero.
+  public var underestimatedCount: Int { return 0 }
+
+  @_inlineable // FIXME(sil-serialize-all)
+  public func _copyToContiguousArray() -> ContiguousArray<Base.Element.Element> {
+    // The default implementation of `_copyToContiguousArray` queries the
+    // `count` property, which materializes every inner collection.  This is a
+    // bad default for `flatMap()`.  So we treat `self` as a sequence and only
+    // rely on underestimated count.
+    return _copySequenceToContiguousArray(self)
+  }
+
+  // TODO: swift-3-indexing-model - add docs
+  @_inlineable // FIXME(sil-serialize-all)
+  public func forEach(
+    _ body: (Base.Element.Element) throws -> Void
+  ) rethrows {
+    // FIXME: swift-3-indexing-model: tests.
+    for innerCollection in _base {
+      try innerCollection.forEach(body)
+    }
+  }
+}
+
+extension FlattenCollection : Collection {
+  /// The position of the first element in a non-empty collection.
+  ///
+  /// In an empty collection, `startIndex == endIndex`.
+  @_inlineable // FIXME(sil-serialize-all)
+  public var startIndex: Index {
+    let end = _base.endIndex
+    var outer = _base.startIndex
+    while outer != end {
+      let innerCollection = _base[outer]
+      if !innerCollection.isEmpty {
+        return Index(outer, innerCollection.startIndex)
+      }
+      _base.formIndex(after: &outer)
+    }
+
+    return endIndex
+  }
+
+  /// The collection's "past the end" position.
+  ///
+  /// `endIndex` is not a valid argument to `subscript`, and is always
+  /// reachable from `startIndex` by zero or more applications of
+  /// `index(after:)`.
+  @_inlineable // FIXME(sil-serialize-all)
+  public var endIndex: Index {
+    return Index(_base.endIndex, nil)
+  }
+
+  @_inlineable // FIXME(sil-serialize-all)
+  @_versioned // FIXME(sil-serialize-all)
+  internal func _index(after i: Index) -> Index {
+    let innerCollection = _base[i._outer]
+    let nextInner = innerCollection.index(after: i._inner!)
+    if _fastPath(nextInner != innerCollection.endIndex) {
+      return Index(i._outer, nextInner)
+    }
+
+    var nextOuter = _base.index(after: i._outer)
+    while nextOuter != _base.endIndex {
+      let nextInnerCollection = _base[nextOuter]
+      if !nextInnerCollection.isEmpty {
+        return Index(nextOuter, nextInnerCollection.startIndex)
+      }
+      _base.formIndex(after: &nextOuter)
+    }
+
+    return endIndex
+  }
+
+  @_inlineable // FIXME(sil-serialize-all)
+  @_versioned // FIXME(sil-serialize-all)
+  internal func _index(before i: Index) -> Index {
+    var prevOuter = i._outer
+    if prevOuter == _base.endIndex {
+      prevOuter = _base.index(prevOuter, offsetBy: -1)
+    }
+    var prevInnerCollection = _base[prevOuter]
+    var prevInner = i._inner ?? prevInnerCollection.endIndex
+
+    while prevInner == prevInnerCollection.startIndex {
+      prevOuter = _base.index(prevOuter, offsetBy: -1)
+      prevInnerCollection = _base[prevOuter]
+      prevInner = prevInnerCollection.endIndex
+    }
+
+    return Index(prevOuter, prevInnerCollection.index(prevInner, offsetBy: -1))
+  }
+
+  // TODO: swift-3-indexing-model - add docs
+  @_inlineable // FIXME(sil-serialize-all)
+  public func index(after i: Index) -> Index {
+    return _index(after: i)
+  }
+
+  @_inlineable // FIXME(sil-serialize-all)
+  public func formIndex(after i: inout Index) {
+    i = index(after: i)
+  }
+
+  @_inlineable // FIXME(sil-serialize-all)
+  public func distance(from start: Index, to end: Index) -> Int {
+    // The following check makes sure that distance(from:to:) is invoked on the
+    // _base at least once, to trigger a _precondition in forward only
+    // collections.
+    if end < start {
+      _ = _base.distance(from: _base.endIndex, to: _base.startIndex)
+    }
+    var _start: Index
+    let _end: Index
+    let step: Int
+    if start > end {
+      _start = end
+      _end = start
+      step = -1
+    }
+    else {
+      _start = start
+      _end = end
+      step = 1
+    }
+    var count = 0
+    while _start != _end {
+      count += step
+      formIndex(after: &_start)
+    }
+    return count
+  }
+
+  @inline(__always)
+  @_inlineable // FIXME(sil-serialize-all)
+  @_versioned // FIXME(sil-serialize-all)
+  internal func _advanceIndex(_ i: inout Index, step: Int) {
+    _sanityCheck(-1...1 ~= step, "step should be within the -1...1 range")
+    i = step < 0 ? _index(before: i) : _index(after: i)
+  }
+
+  @inline(__always)
+  @_inlineable // FIXME(sil-serialize-all)
+  @_versioned // FIXME(sil-serialize-all)
+  internal func _ensureBidirectional(step: Int) {
+    // FIXME: This seems to be the best way of checking whether _base is
+    // forward only without adding an extra protocol requirement.
+    // index(_:offsetBy:limitedBy:) is chosen becuase it is supposed to return
+    // nil when the resulting index lands outside the collection boundaries,
+    // and therefore likely does not trap in these cases.
+    if step < 0 {
+      _ = _base.index(
+        _base.endIndex, offsetBy: step, limitedBy: _base.startIndex)
+    }
+  }
+
+  @_inlineable // FIXME(sil-serialize-all)
+  public func index(_ i: Index, offsetBy n: Int) -> Index {
+    var i = i
+    let step = n.signum()
+    _ensureBidirectional(step: step)
+    for _ in 0 ..< abs(n) {
+      _advanceIndex(&i, step: step)
+    }
+    return i
+  }
+
+  @_inlineable // FIXME(sil-serialize-all)
+  public func formIndex(_ i: inout Index, offsetBy n: Int) {
+    i = index(i, offsetBy: n)
+  }
+
+  @_inlineable // FIXME(sil-serialize-all)
+  public func index(
+    _ i: Index, offsetBy n: Int, limitedBy limit: Index
+  ) -> Index? {
+    var i = i
+    let step = n.signum()
+    // The following line makes sure that index(_:offsetBy:limitedBy:) is
+    // invoked on the _base at least once, to trigger a _precondition in
+    // forward only collections.
+    _ensureBidirectional(step: step)
+    for _ in 0 ..< abs(n) {
+      if i == limit {
+        return nil
+      }
+      _advanceIndex(&i, step: step)
+    }
+    return i
+  }
+
+  @_inlineable // FIXME(sil-serialize-all)
+  public func formIndex(
+    _ i: inout Index, offsetBy n: Int, limitedBy limit: Index
+  ) -> Bool {
+    if let advancedIndex = index(i, offsetBy: n, limitedBy: limit) {
+      i = advancedIndex
+      return true
+    }
+    i = limit
+    return false
+  }
+
+  /// Accesses the element at `position`.
+  ///
+  /// - Precondition: `position` is a valid position in `self` and
+  ///   `position != endIndex`.
+  @_inlineable // FIXME(sil-serialize-all)
+  public subscript(position: Index) -> Base.Element.Element {
+    return _base[position._outer][position._inner!]
+  }
+
+  @_inlineable // FIXME(sil-serialize-all)
+  public subscript(bounds: Range<Index>) -> SubSequence {
+    return Slice(base: self, bounds: bounds)
+  }
+}
+
+extension FlattenCollection : BidirectionalCollection
+  where Base : BidirectionalCollection, Base.Element : BidirectionalCollection {
+
+  // FIXME(performance): swift-3-indexing-model: add custom advance/distance
+  // methods that skip over inner collections when random-access
+
+  // TODO: swift-3-indexing-model - add docs
+  @_inlineable // FIXME(sil-serialize-all)
+  public func index(before i: Index) -> Index {
+    return _index(before: i)
+  }
+
+  @_inlineable // FIXME(sil-serialize-all)
+  public func formIndex(before i: inout Index) {
+    i = index(before: i)
+  }
+}
+
+extension Collection where Element : Collection {
+  /// Returns the elements of this collection of collections, concatenated.
+  ///
+  /// In this example, an array of three ranges is flattened so that the
+  /// elements of each range can be iterated in turn.
+  ///
+  ///     let ranges = [0..<3, 8..<10, 15..<17]
+  ///
+  ///     // A for-in loop over 'ranges' accesses each range:
+  ///     for range in ranges {
+  ///       print(range)
+  ///     }
+  ///     // Prints "0..<3"
+  ///     // Prints "8..<10"
+  ///     // Prints "15..<17"
+  ///
+  ///     // Use 'joined()' to access each element of each range:
+  ///     for index in ranges.joined() {
+  ///         print(index, terminator: " ")
+  ///     }
+  ///     // Prints: "0 1 2 8 9 15 16"
+  ///
+  /// - Returns: A flattened view of the elements of this
+  ///   collection of collections.
+  @_inlineable // FIXME(sil-serialize-all)
+  public func joined() -> FlattenCollection<Self> {
+    return FlattenCollection(self)
+  }
+}
+
+extension BidirectionalCollection where Element : BidirectionalCollection {
+  /// Returns the elements of this collection of collections, concatenated.
+  ///
+  /// In this example, an array of three ranges is flattened so that the
+  /// elements of each range can be iterated in turn.
+  ///
+  ///     let ranges = [0..<3, 8..<10, 15..<17]
+  ///
+  ///     // A for-in loop over 'ranges' accesses each range:
+  ///     for range in ranges {
+  ///       print(range)
+  ///     }
+  ///     // Prints "0..<3"
+  ///     // Prints "8..<10"
+  ///     // Prints "15..<17"
+  ///
+  ///     // Use 'joined()' to access each element of each range:
+  ///     for index in ranges.joined() {
+  ///         print(index, terminator: " ")
+  ///     }
+  ///     // Prints: "0 1 2 8 9 15 16"
+  ///
+  /// - Returns: A flattened view of the elements of this
+  ///   collection of collections.
+  @_inlineable // FIXME(sil-serialize-all)
+  public func joined() -> FlattenCollection<Self> {
+    return FlattenCollection(self)
+  }
+}
+
+extension LazyCollectionProtocol
+  where Self : Collection, Element : Collection {
+  /// A concatenation of the elements of `self`.
+  @_inlineable // FIXME(sil-serialize-all)
+  public func joined() -> LazyCollection<FlattenCollection<Elements>> {
+    return FlattenCollection(elements).lazy
+  }
+}
+
+extension LazyCollectionProtocol
+  where Self : BidirectionalCollection, Element : BidirectionalCollection {
+  /// A concatenation of the elements of `self`.
+  @_inlineable // FIXME(sil-serialize-all)
+  public func joined() -> LazyCollection<FlattenCollection<Elements>> {
+    return FlattenCollection(elements).lazy
+  }
+}
+
+// @available(*, deprecated, renamed: "FlattenCollection.Index")
+public typealias FlattenCollectionIndex<T> = FlattenCollection<T>.Index where T : BidirectionalCollection, T.Element : BidirectionalCollection
+@available(*, deprecated, renamed: "FlattenCollection.Index")
+public typealias FlattenBidirectionalCollectionIndex<T> = FlattenCollection<T>.Index where T : BidirectionalCollection, T.Element : BidirectionalCollection
+@available(*, deprecated, renamed: "FlattenCollection")
+public typealias FlattenBidirectionalCollection<T> = FlattenCollection<T> where T : BidirectionalCollection, T.Element : BidirectionalCollection
diff --git a/stdlib/public/core/Flatten.swift.gyb b/stdlib/public/core/Flatten.swift.gyb
deleted file mode 100644
index 6dfa55a..0000000
--- a/stdlib/public/core/Flatten.swift.gyb
+++ /dev/null
@@ -1,445 +0,0 @@
-//===--- Flatten.swift.gyb ------------------------------------*- swift -*-===//
-//
-// This source file is part of the Swift.org open source project
-//
-// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
-// Licensed under Apache License v2.0 with Runtime Library Exception
-//
-// See https://swift.org/LICENSE.txt for license information
-// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
-//
-//===----------------------------------------------------------------------===//
-
-%{
-from gyb_stdlib_support import (
-    TRAVERSALS,
-    collectionForTraversal,
-)
-}%
-
-/// An iterator that produces the elements contained in each segment
-/// produced by some `Base` Iterator.
-///
-/// The elements traversed are the concatenation of those in each
-/// segment produced by the base iterator.
-///
-/// - Note: This is the `IteratorProtocol` used by `FlattenSequence`,
-///   `FlattenCollection`, and `BidirectionalFlattenCollection`.
-@_fixed_layout // FIXME(sil-serialize-all)
-public struct FlattenIterator<Base : IteratorProtocol> : IteratorProtocol, Sequence
-  where Base.Element : Sequence {
-
-  /// Construct around a `base` iterator.
-  @_inlineable // FIXME(sil-serialize-all)
-  @_versioned // FIXME(sil-serialize-all)
-  internal init(_base: Base) {
-    self._base = _base
-  }
-
-  /// Advances to the next element and returns it, or `nil` if no next element
-  /// exists.
-  ///
-  /// Once `nil` has been returned, all subsequent calls return `nil`.
-  ///
-  /// - Precondition: `next()` has not been applied to a copy of `self`
-  ///   since the copy was made.
-  @_inlineable // FIXME(sil-serialize-all)
-  public mutating func next() -> Base.Element.Element? {
-    repeat {
-      if _fastPath(_inner != nil) {
-        let ret = _inner!.next()
-        if _fastPath(ret != nil) {
-          return ret
-        }
-      }
-      let s = _base.next()
-      if _slowPath(s == nil) {
-        return nil
-      }
-      _inner = s!.makeIterator()
-    }
-    while true
-  }
-
-  @_versioned // FIXME(sil-serialize-all)
-  internal var _base: Base
-  @_versioned // FIXME(sil-serialize-all)
-  internal var _inner: Base.Element.Iterator?
-}
-
-/// A sequence consisting of all the elements contained in each segment
-/// contained in some `Base` sequence.
-///
-/// The elements of this view are a concatenation of the elements of
-/// each sequence in the base.
-///
-/// The `joined` method is always lazy, but does not implicitly
-/// confer laziness on algorithms applied to its result.  In other
-/// words, for ordinary sequences `s`:
-///
-/// * `s.joined()` does not create new storage
-/// * `s.joined().map(f)` maps eagerly and returns a new array
-/// * `s.lazy.joined().map(f)` maps lazily and returns a `LazyMapSequence`
-///
-/// - See also: `FlattenCollection`
-@_fixed_layout // FIXME(sil-serialize-all)
-public struct FlattenSequence<Base : Sequence> : Sequence
-  where Base.Element : Sequence {
-
-  /// Creates a concatenation of the elements of the elements of `base`.
-  ///
-  /// - Complexity: O(1)
-  @_inlineable // FIXME(sil-serialize-all)
-  @_versioned // FIXME(sil-serialize-all)
-  internal init(_base: Base) {
-    self._base = _base
-  }
-
-  /// Returns an iterator over the elements of this sequence.
-  ///
-  /// - Complexity: O(1).
-  @_inlineable // FIXME(sil-serialize-all)
-  public func makeIterator() -> FlattenIterator<Base.Iterator> {
-    return FlattenIterator(_base: _base.makeIterator())
-  }
-
-  @_versioned // FIXME(sil-serialize-all)
-  internal var _base: Base
-}
-
-extension Sequence where Element : Sequence {
-  /// Returns the elements of this sequence of sequences, concatenated.
-  ///
-  /// In this example, an array of three ranges is flattened so that the
-  /// elements of each range can be iterated in turn.
-  ///
-  ///     let ranges = [0..<3, 8..<10, 15..<17]
-  ///
-  ///     // A for-in loop over 'ranges' accesses each range:
-  ///     for range in ranges {
-  ///       print(range)
-  ///     }
-  ///     // Prints "0..<3"
-  ///     // Prints "8..<10"
-  ///     // Prints "15..<17"
-  ///
-  ///     // Use 'joined()' to access each element of each range:
-  ///     for index in ranges.joined() {
-  ///         print(index, terminator: " ")
-  ///     }
-  ///     // Prints: "0 1 2 8 9 15 16"
-  ///
-  /// - Returns: A flattened view of the elements of this
-  ///   sequence of sequences.
-  @_inlineable // FIXME(sil-serialize-all)
-  public func joined() -> FlattenSequence<Self> {
-    return FlattenSequence(_base: self)
-  }
-}
-
-extension LazySequenceProtocol where Element : Sequence {
-
-  /// Returns a lazy sequence that concatenates the elements of this sequence of
-  /// sequences.
-  @_inlineable // FIXME(sil-serialize-all)
-  public func joined() -> LazySequence<
-    FlattenSequence<Elements>
-  > {
-    return FlattenSequence(_base: elements).lazy
-  }
-}
-
-% for traversal in ['Forward', 'Bidirectional']:
-%   Collection = 'Flatten' + collectionForTraversal(traversal)
-%   if traversal == 'Forward':
-%     constraints = '%(Base)sIterator.Element : Collection'
-%   if traversal == 'Bidirectional':
-%     constraints = '%(Base)sIterator.Element : BidirectionalCollection'
-%   Index = Collection + 'Index'
-/// A position in a `${Collection}`.
-@_fixed_layout // FIXME(sil-serialize-all)
-public struct ${Index}<BaseElements>
-  where
-  BaseElements : ${collectionForTraversal(traversal)},
-  ${constraints % {'Base': 'BaseElements.'}} {
-
-  @_inlineable // FIXME(sil-serialize-all)
-  @_versioned // FIXME(sil-serialize-all)
-  internal init(
-    _ _outer: BaseElements.Index,
-    _ inner: BaseElements.Element.Index?) {
-    self._outer = _outer
-    self._inner = inner
-  }
-
-  /// The position in the outer collection of collections.
-  @_versioned // FIXME(sil-serialize-all)
-  internal let _outer: BaseElements.Index
-
-  /// The position in the inner collection at `base[_outer]`, or `nil` if
-  /// `_outer == base.endIndex`.
-  ///
-  /// When `_inner != nil`, `_inner!` is a valid subscript of `base[_outer]`;
-  /// when `_inner == nil`, `_outer == base.endIndex` and this index is
-  /// `endIndex` of the `${Collection}`.
-  @_versioned // FIXME(sil-serialize-all)
-  internal let _inner: BaseElements.Element.Index?
-}
-
-extension ${Index} : Comparable {
-  @_inlineable // FIXME(sil-serialize-all)
-  public static func == (
-    lhs: ${Index}<BaseElements>,
-    rhs: ${Index}<BaseElements>
-  ) -> Bool {
-    return lhs._outer == rhs._outer && lhs._inner == rhs._inner
-  }
-
-  @_inlineable // FIXME(sil-serialize-all)
-  public static func < (
-    lhs: ${Index}<BaseElements>,
-    rhs: ${Index}<BaseElements>
-  ) -> Bool {
-    // FIXME: swift-3-indexing-model: tests.
-    if lhs._outer != rhs._outer {
-      return lhs._outer < rhs._outer
-    }
-
-    if let lhsInner = lhs._inner, let rhsInner = rhs._inner {
-      return lhsInner < rhsInner
-    }
-
-    // When combined, the two conditions above guarantee that both
-    // `_outer` indices are `_base.endIndex` and both `_inner` indices
-    // are `nil`, since `_inner` is `nil` iff `_outer == base.endIndex`.
-    _precondition(lhs._inner == nil && rhs._inner == nil)
-
-    return false
-  }
-}
-
-extension ${Index} : Hashable
-  where BaseElements.Index : Hashable, BaseElements.Element.Index : Hashable
-{
-  public var hashValue: Int {
-    return _mixInt(_inner?.hashValue ?? 0) ^ _outer.hashValue
-  }
-}
-
-/// A flattened view of a base collection of collections.
-///
-/// The elements of this view are a concatenation of the elements of
-/// each collection in the base.
-///
-/// The `joined` method is always lazy, but does not implicitly
-/// confer laziness on algorithms applied to its result.  In other
-/// words, for ordinary collections `c`:
-///
-/// * `c.joined()` does not create new storage
-/// * `c.joined().map(f)` maps eagerly and returns a new array
-/// * `c.lazy.joined().map(f)` maps lazily and returns a `LazyMapCollection`
-///
-/// - Note: The performance of accessing `startIndex`, `first`, any methods
-///   that depend on `startIndex`, or of advancing a `${Collection}Index`
-///   depends on how many empty subcollections are found in the base
-///   collection, and may not offer the usual performance given by
-///   `Collection` or `${traversal}Index`. Be aware, therefore, that
-///   general operations on `${Collection}` instances may not have the
-///   documented complexity.
-///
-/// - See also: `FlattenSequence`
-@_fixed_layout // FIXME(sil-serialize-all)
-public struct ${Collection}<Base> : ${collectionForTraversal(traversal)}
-  where
-  Base : ${collectionForTraversal(traversal)},
-  ${constraints % {'Base': 'Base.'}} {
-  // FIXME: swift-3-indexing-model: check test coverage for collection.
-
-  /// A type that represents a valid position in the collection.
-  ///
-  /// Valid indices consist of the position of every element and a
-  /// "past the end" position that's not valid for use as a subscript.
-  public typealias Index = ${Index}<Base>
-
-  /// Creates a flattened view of `base`.
-  @_inlineable // FIXME(sil-serialize-all)
-  public init(_ base: Base) {
-    self._base = base
-  }
-
-  /// Returns an iterator over the elements of this sequence.
-  ///
-  /// - Complexity: O(1).
-  @_inlineable // FIXME(sil-serialize-all)
-  public func makeIterator() -> FlattenIterator<Base.Iterator> {
-    return FlattenIterator(_base: _base.makeIterator())
-  }
-
-  /// The position of the first element in a non-empty collection.
-  ///
-  /// In an empty collection, `startIndex == endIndex`.
-  @_inlineable // FIXME(sil-serialize-all)
-  public var startIndex: Index {
-    let end = _base.endIndex
-    var outer = _base.startIndex
-    while outer != end {
-      let innerCollection = _base[outer]
-      if !innerCollection.isEmpty {
-        return ${Index}(outer, innerCollection.startIndex)
-      }
-      _base.formIndex(after: &outer)
-    }
-
-    return endIndex
-  }
-
-  /// The collection's "past the end" position.
-  ///
-  /// `endIndex` is not a valid argument to `subscript`, and is always
-  /// reachable from `startIndex` by zero or more applications of
-  /// `index(after:)`.
-  @_inlineable // FIXME(sil-serialize-all)
-  public var endIndex: Index {
-    return ${Index}(_base.endIndex, nil)
-  }
-
-  // TODO: swift-3-indexing-model - add docs
-  @_inlineable // FIXME(sil-serialize-all)
-  public func index(after i: Index) -> Index {
-    let innerCollection = _base[i._outer]
-    let nextInner = innerCollection.index(after: i._inner!)
-    if _fastPath(nextInner != innerCollection.endIndex) {
-      return ${Index}(i._outer, nextInner)
-    }
-
-    var nextOuter = _base.index(after: i._outer)
-    while nextOuter != _base.endIndex {
-      let nextInnerCollection = _base[nextOuter]
-      if !nextInnerCollection.isEmpty {
-        return ${Index}(nextOuter, nextInnerCollection.startIndex)
-      }
-      _base.formIndex(after: &nextOuter)
-    }
-
-    return endIndex
-  }
-
-% if traversal == 'Bidirectional':
-  // TODO: swift-3-indexing-model - add docs
-  @_inlineable // FIXME(sil-serialize-all)
-  public func index(before i: Index) -> Index {
-    var prevOuter = i._outer
-    if prevOuter == _base.endIndex {
-      prevOuter = _base.index(before: prevOuter)
-    }
-    var prevInnerCollection = _base[prevOuter]
-    var prevInner = i._inner ?? prevInnerCollection.endIndex
-
-    while prevInner == prevInnerCollection.startIndex {
-      prevOuter = _base.index(before: prevOuter)
-      prevInnerCollection = _base[prevOuter]
-      prevInner = prevInnerCollection.endIndex
-    }
-
-    return ${Index}(prevOuter, prevInnerCollection.index(before: prevInner))
-  }
-% end
-
-  /// Accesses the element at `position`.
-  ///
-  /// - Precondition: `position` is a valid position in `self` and
-  ///   `position != endIndex`.
-  @_inlineable // FIXME(sil-serialize-all)
-  public subscript(
-    position: Index
-  ) -> Base.Element.Element {
-    return _base[position._outer][position._inner!]
-  }
-
-  @_inlineable // FIXME(sil-serialize-all)
-  public subscript(bounds: Range<Index>)
-    -> Slice<${Collection}> {
-    return Slice(base: self, bounds: bounds)
-  }
-
-  // To return any estimate of the number of elements, we have to start
-  // evaluating the collections.  That is a bad default for `flatMap()`, so
-  // just return zero.
-  public var underestimatedCount: Int { return 0 }
-
-  @_inlineable // FIXME(sil-serialize-all)
-  public func _copyToContiguousArray()
-    -> ContiguousArray<Base.Element.Element> {
-
-    // The default implementation of `_copyToContiguousArray` queries the
-    // `count` property, which materializes every inner collection.  This is a
-    // bad default for `flatMap()`.  So we treat `self` as a sequence and only
-    // rely on underestimated count.
-    return _copySequenceToContiguousArray(self)
-  }
-
-  // TODO: swift-3-indexing-model - add docs
-  @_inlineable // FIXME(sil-serialize-all)
-  public func forEach(
-    _ body: (Base.Element.Element) throws -> Void
-  ) rethrows {
-    // FIXME: swift-3-indexing-model: tests.
-    for innerCollection in _base {
-      try innerCollection.forEach(body)
-    }
-  }
-
-  // FIXME(performance): swift-3-indexing-model: add custom advance/distance
-  // methods that skip over inner collections when random-access
-
-  @_versioned // FIXME(sil-serialize-all)
-  internal var _base: Base
-}
-
-extension ${collectionForTraversal(traversal)}
-  where ${constraints % {'Base': ''}} {
-  /// Returns the elements of this collection of collections, concatenated.
-  ///
-  /// In this example, an array of three ranges is flattened so that the
-  /// elements of each range can be iterated in turn.
-  ///
-  ///     let ranges = [0..<3, 8..<10, 15..<17]
-  ///
-  ///     // A for-in loop over 'ranges' accesses each range:
-  ///     for range in ranges {
-  ///       print(range)
-  ///     }
-  ///     // Prints "0..<3"
-  ///     // Prints "8..<10"
-  ///     // Prints "15..<17"
-  ///
-  ///     // Use 'joined()' to access each element of each range:
-  ///     for index in ranges.joined() {
-  ///         print(index, terminator: " ")
-  ///     }
-  ///     // Prints: "0 1 2 8 9 15 16"
-  ///
-  /// - Returns: A flattened view of the elements of this
-  ///   collection of collections.
-  @_inlineable // FIXME(sil-serialize-all)
-  public func joined() -> ${Collection}<Self> {
-    return ${Collection}(self)
-  }
-}
-
-extension LazyCollectionProtocol
-  where
-%   if traversal != 'Forward':
-  Self : ${collectionForTraversal(traversal)},
-  Elements : ${collectionForTraversal(traversal)},
-%   end
-  ${constraints % {'Base': 'Elements.'}}
-{
-  /// A concatenation of the elements of `self`.
-  @_inlineable // FIXME(sil-serialize-all)
-  public func joined() -> LazyCollection<${Collection}<Elements>> {
-    return ${Collection}(elements).lazy
-  }
-}
-
-% end
diff --git a/stdlib/public/core/Join.swift b/stdlib/public/core/Join.swift
index 22bff43..b7c6418 100644
--- a/stdlib/public/core/Join.swift
+++ b/stdlib/public/core/Join.swift
@@ -10,19 +10,17 @@
 //
 //===----------------------------------------------------------------------===//
 
-@_versioned // FIXME(sil-serialize-all)
-internal enum _JoinIteratorState {
-  case start
-  case generatingElements
-  case generatingSeparator
-  case end
-}
-
-/// An iterator that presents the elements of the sequences traversed
-/// by a base iterator, concatenated using a given separator.
+/// A sequence that presents the elements of a base sequence of sequences
+/// concatenated using a given separator.
 @_fixed_layout // FIXME(sil-serialize-all)
-public struct JoinedIterator<Base : IteratorProtocol> : IteratorProtocol
-  where Base.Element : Sequence {
+public struct JoinedSequence<Base : Sequence> where Base.Element : Sequence {
+
+  public typealias Element = Base.Element.Element
+  
+  @_versioned // FIXME(sil-serialize-all)
+  internal var _base: Base
+  @_versioned // FIXME(sil-serialize-all)
+  internal var _separator: ContiguousArray<Element>
 
   /// Creates an iterator that presents the elements of the sequences
   /// traversed by `base`, concatenated using `separator`.
@@ -30,17 +28,58 @@
   /// - Complexity: O(`separator.count`).
   @_inlineable // FIXME(sil-serialize-all)
   public init<Separator : Sequence>(base: Base, separator: Separator)
-    where Separator.Element == Base.Element.Element {
+    where Separator.Element == Element {
     self._base = base
-    self._separatorData = ContiguousArray(separator)
+    self._separator = ContiguousArray(separator)
   }
+}
+
+extension JoinedSequence {
+  /// An iterator that presents the elements of the sequences traversed
+  /// by a base iterator, concatenated using a given separator.
+  @_fixed_layout // FIXME(sil-serialize-all)
+  public struct Iterator {
+    @_versioned // FIXME(sil-serialize-all)
+    internal var _base: Base.Iterator
+    @_versioned // FIXME(sil-serialize-all)
+    internal var _inner: Base.Element.Iterator?
+    @_versioned // FIXME(sil-serialize-all)
+    internal var _separatorData: ContiguousArray<Element>
+    @_versioned // FIXME(sil-serialize-all)
+    internal var _separator: ContiguousArray<Element>.Iterator?
+    
+    @_versioned // FIXME(sil-serialize-all)
+    internal enum JoinIteratorState {
+      case start
+      case generatingElements
+      case generatingSeparator
+      case end
+    }
+    @_versioned // FIXME(sil-serialize-all)
+    internal var _state: JoinIteratorState = .start
+
+    /// Creates a sequence that presents the elements of `base` sequences
+    /// concatenated using `separator`.
+    ///
+    /// - Complexity: O(`separator.count`).
+    @_inlineable // FIXME(sil-serialize-all)
+    public init<Separator: Sequence>(base: Base.Iterator, separator: Separator)
+      where Separator.Element == Element {
+      self._base = base
+      self._separatorData = ContiguousArray(separator)
+    }
+  }  
+}
+
+extension JoinedSequence.Iterator: IteratorProtocol {
+  public typealias Element = Base.Element.Element
 
   /// Advances to the next element and returns it, or `nil` if no next element
   /// exists.
   ///
   /// Once `nil` has been returned, all subsequent calls return `nil`.
   @_inlineable // FIXME(sil-serialize-all)
-  public mutating func next() -> Base.Element.Element? {
+  public mutating func next() -> Element? {
     while true {
       switch _state {
       case .start:
@@ -76,54 +115,22 @@
 
       case .end:
         return nil
-
       }
     }
   }
-
-  @_versioned // FIXME(sil-serialize-all)
-  internal var _base: Base
-  @_versioned // FIXME(sil-serialize-all)
-  internal var _inner: Base.Element.Iterator?
-  @_versioned // FIXME(sil-serialize-all)
-  internal var _separatorData: ContiguousArray<Base.Element.Element>
-  @_versioned // FIXME(sil-serialize-all)
-  internal var _separator:
-    ContiguousArray<Base.Element.Element>.Iterator?
-  @_versioned // FIXME(sil-serialize-all)
-  internal var _state: _JoinIteratorState = .start
 }
 
-/// A sequence that presents the elements of a base sequence of sequences
-/// concatenated using a given separator.
-@_fixed_layout // FIXME(sil-serialize-all)
-public struct JoinedSequence<Base : Sequence> : Sequence
-  where Base.Element : Sequence {
-
-  /// Creates a sequence that presents the elements of `base` sequences
-  /// concatenated using `separator`.
-  ///
-  /// - Complexity: O(`separator.count`).
-  @_inlineable // FIXME(sil-serialize-all)
-  public init<Separator : Sequence>(base: Base, separator: Separator)
-    where Separator.Element == Base.Element.Element {
-    self._base = base
-    self._separator = ContiguousArray(separator)
-  }
-
+extension JoinedSequence: Sequence {
   /// Return an iterator over the elements of this sequence.
   ///
   /// - Complexity: O(1).
   @_inlineable // FIXME(sil-serialize-all)
-  public func makeIterator() -> JoinedIterator<Base.Iterator> {
-    return JoinedIterator(
-      base: _base.makeIterator(),
-      separator: _separator)
+  public func makeIterator() -> Iterator {
+    return Iterator(base: _base.makeIterator(), separator: _separator)
   }
 
   @_inlineable // FIXME(sil-serialize-all)
-  public func _copyToContiguousArray()
-    -> ContiguousArray<Base.Element.Element> {
+  public func _copyToContiguousArray() -> ContiguousArray<Element> {
     var result = ContiguousArray<Element>()
     let separatorSize: Int = numericCast(_separator.count)
 
@@ -158,14 +165,8 @@
 
     return result
   }
-
-  @_versioned // FIXME(sil-serialize-all)
-  internal var _base: Base
-  @_versioned // FIXME(sil-serialize-all)
-  internal var _separator:
-    ContiguousArray<Base.Element.Element>
 }
-
+  
 extension Sequence where Element : Sequence {
   /// Returns the concatenated elements of this sequence of sequences,
   /// inserting the given separator between each element.
@@ -189,3 +190,6 @@
     return JoinedSequence(base: self, separator: separator)
   }
 }
+
+// @available(*, deprecated, renamed: "JoinedSequence.Iterator")
+public typealias JoinedIterator<T: Sequence> = JoinedSequence<T>.Iterator where T.Element: Sequence
diff --git a/stdlib/public/core/LazyCollection.swift.gyb b/stdlib/public/core/LazyCollection.swift
similarity index 79%
rename from stdlib/public/core/LazyCollection.swift.gyb
rename to stdlib/public/core/LazyCollection.swift
index c50d741..0798a5c 100644
--- a/stdlib/public/core/LazyCollection.swift.gyb
+++ b/stdlib/public/core/LazyCollection.swift
@@ -1,4 +1,4 @@
-//===--- LazyCollection.swift.gyb -----------------------------*- swift -*-===//
+//===--- LazyCollection.swift ---------------------------------*- swift -*-===//
 //
 // This source file is part of the Swift.org open source project
 //
@@ -10,8 +10,6 @@
 //
 //===----------------------------------------------------------------------===//
 
-% from gyb_stdlib_support import TRAVERSALS, collectionForTraversal
-
 /// A collection on which normally-eager operations such as `map` and
 /// `filter` are implemented lazily.
 ///
@@ -21,8 +19,7 @@
 /// To add new lazy collection operations, extend this protocol with
 /// methods that return lazy wrappers that are themselves
 /// `LazyCollectionProtocol`s.
-public protocol LazyCollectionProtocol
-  : Collection, LazySequenceProtocol {
+public protocol LazyCollectionProtocol: Collection, LazySequenceProtocol {
   /// A `Collection` that can contain the same elements as this one,
   /// possibly with a simpler type.
   ///
@@ -30,12 +27,20 @@
   associatedtype Elements : Collection = Self
 }
 
-/// When there's no special associated `Elements` type, the `elements`
-/// property is provided.
-extension LazyCollectionProtocol where Elements == Self {
-  /// Identical to `self`.
+extension LazyCollectionProtocol {
+  // Lazy things are already lazy
   @_inlineable // FIXME(sil-serialize-all)
-  public var elements: Self { return self }
+  public var lazy: LazyCollection<Elements> {
+    return elements.lazy
+  }
+}
+
+extension LazyCollectionProtocol where Elements: LazyCollectionProtocol {
+  // Lazy things are already lazy
+  @_inlineable // FIXME(sil-serialize-all)
+  public var lazy: Elements {
+    return elements
+  }
 }
 
 /// A collection containing the same elements as a `Base` collection,
@@ -44,21 +49,7 @@
 ///
 /// - See also: `LazySequenceProtocol`, `LazyCollection`
 @_fixed_layout
-public struct LazyCollection<Base : Collection> : LazyCollectionProtocol {
-
-  /// The type of the underlying collection.
-  public typealias Elements = Base
-
-  /// The underlying collection.
-  @_inlineable
-  public var elements: Elements { return _base }
-
-  /// A type that represents a valid position in the collection.
-  ///
-  /// Valid indices consist of the position of every element and a
-  /// "past the end" position that's not valid for use as a subscript.
-  public typealias Index = Base.Index
-
+public struct LazyCollection<Base : Collection> {
   /// Creates an instance with `base` as its underlying Collection
   /// instance.
   @_inlineable
@@ -69,12 +60,20 @@
 
   @_versioned
   internal var _base: Base
+} 
+
+extension LazyCollection: LazyCollectionProtocol {
+  /// The type of the underlying collection.
+  public typealias Elements = Base
+
+  /// The underlying collection.
+  @_inlineable
+  public var elements: Elements { return _base }
 }
 
 /// Forward implementations to the base collection, to pick up any
 /// optimizations it might implement.
 extension LazyCollection : Sequence {
-  
   public typealias Iterator = Base.Iterator
 
   /// Returns an iterator over the elements of this sequence.
@@ -114,13 +113,19 @@
 }
 
 extension LazyCollection : Collection {
+  /// A type that represents a valid position in the collection.
+  ///
+  /// Valid indices consist of the position of every element and a
+  /// "past the end" position that's not valid for use as a subscript.
+  public typealias Element = Base.Element
+  public typealias Index = Base.Index
+  public typealias Indices = Base.Indices
+
   /// The position of the first element in a non-empty collection.
   ///
   /// In an empty collection, `startIndex == endIndex`.
   @_inlineable
-  public var startIndex: Base.Index {
-    return _base.startIndex
-  }
+  public var startIndex: Index { return _base.startIndex }
 
   /// The collection's "past the end" position---that is, the position one
   /// greater than the last valid subscript argument.
@@ -128,18 +133,14 @@
   /// `endIndex` is always reachable from `startIndex` by zero or more
   /// applications of `index(after:)`.
   @_inlineable
-  public var endIndex: Base.Index {
-    return _base.endIndex
-  }
+  public var endIndex: Index { return _base.endIndex }
 
   @_inlineable
-  public var indices: Base.Indices {
-    return _base.indices
-  }
+  public var indices: Indices { return _base.indices }
 
   // TODO: swift-3-indexing-model - add docs
   @_inlineable
-  public func index(after i: Base.Index) -> Base.Index {
+  public func index(after i: Index) -> Index {
     return _base.index(after: i)
   }
 
@@ -148,19 +149,10 @@
   /// - Precondition: `position` is a valid position in `self` and
   ///   `position != endIndex`.
   @_inlineable
-  public subscript(position: Base.Index) -> Base.Element {
+  public subscript(position: Index) -> Element {
     return _base[position]
   }
 
-  /// Returns a collection representing a contiguous sub-range of
-  /// `self`'s elements.
-  ///
-  /// - Complexity: O(1)
-  @_inlineable
-  public subscript(bounds: Range<Index>) -> Slice<LazyCollection<Base>> {
-    return Slice(base: self, bounds: bounds)
-  }
-
   /// A Boolean value indicating whether the collection is empty.
   @_inlineable
   public var isEmpty: Bool {
@@ -190,14 +182,14 @@
   /// - Complexity: O(*n*)
   @_inlineable
   public func _customIndexOfEquatableElement(
-    _ element: Base.Iterator.Element
+    _ element: Element
   ) -> Index?? {
     return _base._customIndexOfEquatableElement(element)
   }
 
   /// Returns the first element of `self`, or `nil` if `self` is empty.
   @_inlineable
-  public var first: Base.Element? {
+  public var first: Element? {
     return _base.first
   }
 
@@ -226,12 +218,12 @@
 extension LazyCollection : BidirectionalCollection
   where Base : BidirectionalCollection {
   @_inlineable
-  public func index(before i: Base.Index) -> Base.Index {
+  public func index(before i: Index) -> Index {
     return _base.index(before: i)
   }
 
   @_inlineable
-  public var last: Base.Element? {
+  public var last: Element? {
     return _base.last
   }
 }
@@ -253,26 +245,12 @@
   }
 }
 
-% for Traversal in TRAVERSALS:
-%   TraversalCollection = collectionForTraversal(Traversal)
-// Without this specific overload the non-re-wrapping extension on
-// LazyCollectionProtocol (below) is not selected for some reason.
-extension ${TraversalCollection} where Self : LazyCollectionProtocol {
-  /// Identical to `self`.
-  @_inlineable
-  public var lazy: Self { // Don't re-wrap already-lazy collections
-    return self
-  }
-}
-% end
-
 extension Slice: LazySequenceProtocol where Base: LazySequenceProtocol { }
 extension Slice: LazyCollectionProtocol where Base: LazyCollectionProtocol { }
+extension ReversedCollection: LazySequenceProtocol where Base: LazySequenceProtocol { }
+extension ReversedCollection: LazyCollectionProtocol where Base: LazyCollectionProtocol { }
 
 @available(*, deprecated, renamed: "LazyCollection")
 public typealias LazyBidirectionalCollection<T> = LazyCollection<T> where T : BidirectionalCollection
 @available(*, deprecated, renamed: "LazyCollection")
 public typealias LazyRandomAccessCollection<T> = LazyCollection<T> where T : RandomAccessCollection
-// ${'Local Variables'}:
-// eval: (read-only-mode 1)
-// End:
diff --git a/stdlib/public/core/LazySequence.swift b/stdlib/public/core/LazySequence.swift
index 1100146..a89c101 100644
--- a/stdlib/public/core/LazySequence.swift
+++ b/stdlib/public/core/LazySequence.swift
@@ -158,14 +158,28 @@
   public var elements: Self { return self }
 }
 
+extension LazySequenceProtocol {
+  @_inlineable // FIXME(sil-serialize-all)
+  public var lazy: LazySequence<Elements> {
+    return elements.lazy
+  }
+}
+
+extension LazySequenceProtocol where Elements: LazySequenceProtocol {
+  @_inlineable // FIXME(sil-serialize-all)
+  public var lazy: Elements {
+    return elements
+  }
+}
+
 /// A sequence containing the same elements as a `Base` sequence, but
 /// on which some operations such as `map` and `filter` are
 /// implemented lazily.
 ///
 /// - See also: `LazySequenceProtocol`
 @_fixed_layout // FIXME(sil-serialize-all)
-public struct LazySequence<Base : Sequence>
-  : LazySequenceProtocol, _SequenceWrapper {
+public struct LazySequence<Base : Sequence>: _SequenceWrapper {
+  public var _base: Base
 
   /// Creates a sequence that has the same elements as `base`, but on
   /// which some operations such as `map` and `filter` are implemented
@@ -175,12 +189,14 @@
   internal init(_base: Base) {
     self._base = _base
   }
+}
 
-  public var _base: Base
+extension LazySequence: LazySequenceProtocol {
+  public typealias Elements = Base
 
   /// The `Base` (presumably non-lazy) sequence from which `self` was created.
   @_inlineable // FIXME(sil-serialize-all)
-  public var elements: Base { return _base }
+  public var elements: Elements { return _base }
 }
 
 extension Sequence {
@@ -192,13 +208,3 @@
     return LazySequence(_base: self)
   }
 }
-
-/// Avoid creating multiple layers of `LazySequence` wrapper.
-/// Anything conforming to `LazySequenceProtocol` is already lazy.
-extension LazySequenceProtocol {
-  /// Identical to `self`.
-  @_inlineable // FIXME(sil-serialize-all)
-  public var lazy: Self {
-    return self
-  }
-}
diff --git a/stdlib/public/core/Map.swift b/stdlib/public/core/Map.swift
index a8a0d90..a702b78 100644
--- a/stdlib/public/core/Map.swift
+++ b/stdlib/public/core/Map.swift
@@ -10,13 +10,54 @@
 //
 //===----------------------------------------------------------------------===//
 
-/// The `IteratorProtocol` used by `MapSequence` and `MapCollection`.
-/// Produces each element by passing the output of the `Base`
-/// `IteratorProtocol` through a transform function returning `Element`.
+/// A `Sequence` whose elements consist of those in a `Base`
+/// `Sequence` passed through a transform function returning `Element`.
+/// These elements are computed lazily, each time they're read, by
+/// calling the transform function on a base element.
 @_fixed_layout
-public struct LazyMapIterator<
-  Base : IteratorProtocol, Element
-> : IteratorProtocol, Sequence {
+public struct LazyMapSequence<Base : Sequence, Element> {
+
+  public typealias Elements = LazyMapSequence
+
+  @_versioned
+  internal var _base: Base
+  @_versioned
+  internal let _transform: (Base.Element) -> Element
+
+  /// Creates an instance with elements `transform(x)` for each element
+  /// `x` of base.
+  @_inlineable
+  @_versioned
+  internal init(_base: Base, transform: @escaping (Base.Element) -> Element) {
+    self._base = _base
+    self._transform = transform
+  }
+}
+
+extension LazyMapSequence {
+  @_fixed_layout
+  public struct Iterator {
+    @_versioned
+    internal var _base: Base.Iterator
+    @_versioned
+    internal let _transform: (Base.Element) -> Element
+
+    @_inlineable
+    public var base: Base.Iterator { return _base }
+
+    @_inlineable
+    @_versioned
+    internal init(
+      _base: Base.Iterator, 
+      _transform: @escaping (Base.Element) -> Element
+    ) {
+      self._base = _base
+      self._transform = _transform
+    }
+  }
+}
+
+extension LazyMapSequence.Iterator: IteratorProtocol, Sequence {
   /// Advances to the next element and returns it, or `nil` if no next element
   /// exists.
   ///
@@ -28,39 +69,15 @@
   public mutating func next() -> Element? {
     return _base.next().map(_transform)
   }
-
-  @_inlineable
-  public var base: Base { return _base }
-
-  @_versioned
-  internal var _base: Base
-  @_versioned
-  internal let _transform: (Base.Element) -> Element
-
-  @_inlineable
-  @_versioned
-  internal init(_base: Base, _transform: @escaping (Base.Element) -> Element) {
-    self._base = _base
-    self._transform = _transform
-  }
 }
 
-/// A `Sequence` whose elements consist of those in a `Base`
-/// `Sequence` passed through a transform function returning `Element`.
-/// These elements are computed lazily, each time they're read, by
-/// calling the transform function on a base element.
-@_fixed_layout
-public struct LazyMapSequence<Base : Sequence, Element>
-  : LazySequenceProtocol {
-
-  public typealias Elements = LazyMapSequence
-
+extension LazyMapSequence: LazySequenceProtocol {
   /// Returns an iterator over the elements of this sequence.
   ///
   /// - Complexity: O(1).
   @_inlineable
-  public func makeIterator() -> LazyMapIterator<Base.Iterator, Element> {
-    return LazyMapIterator(_base: _base.makeIterator(), _transform: _transform)
+  public func makeIterator() -> Iterator {
+    return Iterator(_base: _base.makeIterator(), _transform: _transform)
   }
 
   /// Returns a value less than or equal to the number of elements in
@@ -71,35 +88,50 @@
   public var underestimatedCount: Int {
     return _base.underestimatedCount
   }
-
-  /// Creates an instance with elements `transform(x)` for each element
-  /// `x` of base.
-  @_inlineable
-  @_versioned
-  internal init(_base: Base, transform: @escaping (Base.Element) -> Element) {
-    self._base = _base
-    self._transform = transform
-  }
-
-  @_versioned
-  internal var _base: Base
-  @_versioned
-  internal let _transform: (Base.Element) -> Element
 }
 
-//===--- Collections ------------------------------------------------------===//
-
 /// A `Collection` whose elements consist of those in a `Base`
 /// `Collection` passed through a transform function returning `Element`.
 /// These elements are computed lazily, each time they're read, by
 /// calling the transform function on a base element.
 @_fixed_layout
-public struct LazyMapCollection<
-  Base : Collection, Element
-> : LazyCollectionProtocol, Collection {
+public struct LazyMapCollection<Base: Collection, Element> {
+  @_versioned
+  internal var _base: Base
+  @_versioned
+  internal let _transform: (Base.Element) -> Element
 
-  // FIXME(compiler limitation): should be inferable.
+  /// Create an instance with elements `transform(x)` for each element
+  /// `x` of base.
+  @_inlineable
+  @_versioned
+  internal init(_base: Base, transform: @escaping (Base.Element) -> Element) {
+    self._base = _base
+    self._transform = transform
+  }  
+}
+
+extension LazyMapCollection: Sequence {
+  public typealias Iterator = LazyMapSequence<Base,Element>.Iterator
+
+  /// Returns an iterator over the elements of this sequence.
+  ///
+  /// - Complexity: O(1).
+  @_inlineable
+  public func makeIterator() -> Iterator {
+    return Iterator(_base: _base.makeIterator(), _transform: _transform)
+  }
+
+  @_inlineable
+  public var underestimatedCount: Int {
+    return _base.underestimatedCount
+  }
+}
+
+extension LazyMapCollection: LazyCollectionProtocol {
   public typealias Index = Base.Index
+  public typealias Indices = Base.Indices
+  public typealias SubSequence = LazyMapCollection<Base.SubSequence, Element>
 
   @_inlineable
   public var startIndex: Base.Index { return _base.startIndex }
@@ -108,11 +140,8 @@
 
   @_inlineable
   public func index(after i: Index) -> Index { return _base.index(after: i) }
-
   @_inlineable
-  public func formIndex(after i: inout Index) {
-    _base.formIndex(after: &i)
-  }
+  public func formIndex(after i: inout Index) { _base.formIndex(after: &i) }
 
   /// Accesses the element at `position`.
   ///
@@ -123,15 +152,11 @@
     return _transform(_base[position])
   }
 
-  public typealias SubSequence = LazyMapCollection<Base.SubSequence, Element>
-
   @_inlineable
   public subscript(bounds: Range<Base.Index>) -> SubSequence {
     return SubSequence(_base: _base[bounds], transform: _transform)
   }
 
-  public typealias Indices = Base.Indices
-
   @_inlineable
   public var indices: Indices {
     return _base.indices
@@ -174,33 +199,6 @@
   public func distance(from start: Index, to end: Index) -> Int {
     return _base.distance(from: start, to: end)
   }
-
-  /// Returns an iterator over the elements of this sequence.
-  ///
-  /// - Complexity: O(1).
-  @_inlineable
-  public func makeIterator() -> LazyMapIterator<Base.Iterator, Element> {
-    return LazyMapIterator(_base: _base.makeIterator(), _transform: _transform)
-  }
-
-  @_inlineable
-  public var underestimatedCount: Int {
-    return _base.underestimatedCount
-  }
-
-  /// Create an instance with elements `transform(x)` for each element
-  /// `x` of base.
-  @_inlineable
-  @_versioned
-  internal init(_base: Base, transform: @escaping (Base.Element) -> Element) {
-    self._base = _base
-    self._transform = transform
-  }
-
-  @_versioned
-  internal var _base: Base
-  @_versioned
-  internal let _transform: (Base.Element) -> Element
 }
 
 extension LazyMapCollection : BidirectionalCollection
@@ -219,8 +217,7 @@
 }
 
 extension LazyMapCollection : RandomAccessCollection
-  where Base : RandomAccessCollection {}
-
+  where Base : RandomAccessCollection { }
 
 //===--- Support for s.lazy -----------------------------------------------===//
 
@@ -264,6 +261,8 @@
   }
 }
 
+// @available(*, deprecated, renamed: "LazyMapSequence.Iterator")
+public typealias LazyMapIterator<T, E> = LazyMapSequence<T, E>.Iterator where T: Sequence
 @available(*, deprecated, renamed: "LazyMapCollection")
 public typealias LazyMapBidirectionalCollection<T, E> = LazyMapCollection<T, E> where T : BidirectionalCollection
 @available(*, deprecated, renamed: "LazyMapCollection")
diff --git a/stdlib/public/core/MutableCollection.swift b/stdlib/public/core/MutableCollection.swift
index 4612c42..6fccc48 100644
--- a/stdlib/public/core/MutableCollection.swift
+++ b/stdlib/public/core/MutableCollection.swift
@@ -75,7 +75,7 @@
   associatedtype Index
 
   // FIXME(ABI): Associated type inference requires this.
-  associatedtype SubSequence = Slice<Self>
+  associatedtype SubSequence
 
   /// Accesses the element at the specified position.
   ///
diff --git a/stdlib/public/core/RandomAccessCollection.swift b/stdlib/public/core/RandomAccessCollection.swift
index 98c1157..079f965 100644
--- a/stdlib/public/core/RandomAccessCollection.swift
+++ b/stdlib/public/core/RandomAccessCollection.swift
@@ -48,10 +48,10 @@
   associatedtype Index
 
   // FIXME(ABI): Associated type inference requires this.
-  associatedtype SubSequence = Slice<Self>
+  associatedtype SubSequence
 
   // FIXME(ABI): Associated type inference requires this.
-  associatedtype Indices = DefaultIndices<Self>
+  associatedtype Indices
 
   /// The indices that are valid for subscripting the collection, in ascending
   /// order.
@@ -166,6 +166,13 @@
   }
 }
 
+// Provides an alternative default associated type witness for Indices
+// for random access collections with strideable indices.
+extension RandomAccessCollection where Index : Strideable, Index.Stride == Int {
+  @_implements(Collection, Indices)
+  public typealias _Default_Indices = CountableRange<Index>
+}
+
 extension RandomAccessCollection
 where Index : Strideable, 
       Index.Stride == Int,
diff --git a/stdlib/public/core/RangeReplaceableCollection.swift b/stdlib/public/core/RangeReplaceableCollection.swift
index b326436..ca5b820 100644
--- a/stdlib/public/core/RangeReplaceableCollection.swift
+++ b/stdlib/public/core/RangeReplaceableCollection.swift
@@ -73,7 +73,7 @@
 public protocol RangeReplaceableCollection : Collection
   where SubSequence : RangeReplaceableCollection {
   // FIXME(ABI): Associated type inference requires this.
-  associatedtype SubSequence = Slice<Self>
+  associatedtype SubSequence
 
   //===--- Fundamental Requirements ---------------------------------------===//
 
diff --git a/stdlib/public/core/Reverse.swift b/stdlib/public/core/Reverse.swift
index da7c0c9..ad08943 100644
--- a/stdlib/public/core/Reverse.swift
+++ b/stdlib/public/core/Reverse.swift
@@ -10,7 +10,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-extension MutableCollection where Self : BidirectionalCollection {
+extension MutableCollection where Self: BidirectionalCollection {
   /// Reverses the elements of the collection in place.
   ///
   /// The following example reverses the elements of an array of characters:
@@ -35,118 +35,6 @@
   }
 }
 
-/// An iterator that can be much faster than the iterator of a reversed slice.
-// TODO: See about using this in more places
-@_fixed_layout
-public struct _ReverseIndexingIterator<
-  Elements : BidirectionalCollection
-> : IteratorProtocol, Sequence {
-
-  @_inlineable
-  @inline(__always)
-  /// Creates an iterator over the given collection.
-  public /// @testable
-  init(_elements: Elements, _position: Elements.Index) {
-    self._elements = _elements
-    self._position = _position
-  }
-  
-  @_inlineable
-  @inline(__always)
-  public mutating func next() -> Elements.Element? {
-    guard _fastPath(_position != _elements.startIndex) else { return nil }
-    _position = _elements.index(before: _position)
-    return _elements[_position]
-  }
-  
-  @_versioned
-  internal let _elements: Elements
-  @_versioned
-  internal var _position: Elements.Index
-}
-
-/// An index that traverses the same positions as an underlying index,
-/// with inverted traversal direction.
-@_fixed_layout
-public struct ReversedIndex<Base : Collection> : Comparable {
-  /// Creates a new index into a reversed collection for the position before
-  /// the specified index.
-  ///
-  /// When you create an index into a reversed collection using `base`, an
-  /// index from the underlying collection, the resulting index is the
-  /// position of the element *before* the element referenced by `base`. The
-  /// following example creates a new `ReversedIndex` from the index of the
-  /// `"a"` character in a string's character view.
-  ///
-  ///     let name = "Horatio"
-  ///     let aIndex = name.index(of: "a")!
-  ///     // name[aIndex] == "a"
-  ///
-  ///     let reversedName = name.reversed()
-  ///     let i = ReversedIndex<String>(aIndex)
-  ///     // reversedName[i] == "r"
-  ///
-  /// The element at the position created using `ReversedIndex<...>(aIndex)` is
-  /// `"r"`, the character before `"a"` in the `name` string.
-  ///
-  /// - Parameter base: The position after the element to create an index for.
-  @_inlineable
-  public init(_ base: Base.Index) {
-    self.base = base
-  }
-
-  /// The position after this position in the underlying collection.
-  ///
-  /// To find the position that corresponds with this index in the original,
-  /// underlying collection, use that collection's `index(before:)` method
-  /// with the `base` property.
-  ///
-  /// The following example declares a function that returns the index of the
-  /// last even number in the passed array, if one is found. First, the
-  /// function finds the position of the last even number as a `ReversedIndex`
-  /// in a reversed view of the array of numbers. Next, the function calls the
-  /// array's `index(before:)` method to return the correct position in the
-  /// passed array.
-  ///
-  ///     func indexOfLastEven(_ numbers: [Int]) -> Int? {
-  ///         let reversedNumbers = numbers.reversed()
-  ///         guard let i = reversedNumbers.index(where: { $0 % 2 == 0 })
-  ///             else { return nil }
-  ///
-  ///         return numbers.index(before: i.base)
-  ///     }
-  ///
-  ///     let numbers = [10, 20, 13, 19, 30, 52, 17, 40, 51]
-  ///     if let lastEven = indexOfLastEven(numbers) {
-  ///         print("Last even number: \(numbers[lastEven])")
-  ///     }
-  ///     // Prints "Last even number: 40"
-  public let base: Base.Index
-
-  @_inlineable
-  public static func == (
-    lhs: ReversedIndex<Base>,
-    rhs: ReversedIndex<Base>
-  ) -> Bool {
-    return lhs.base == rhs.base
-  }
-
-  @_inlineable
-  public static func < (
-    lhs: ReversedIndex<Base>,
-    rhs: ReversedIndex<Base>
-  ) -> Bool {
-    // Note ReversedIndex has inverted logic compared to base Base.Index
-    return lhs.base > rhs.base
-  }
-}
-
-extension ReversedIndex : Hashable where Base.Index : Hashable {
-  public var hashValue: Int {
-    return base.hashValue
-  }
-}
-
 /// A collection that presents the elements of its base collection
 /// in reverse order.
 ///
@@ -178,67 +66,164 @@
   }
 }
 
-extension ReversedCollection: BidirectionalCollection {
+extension ReversedCollection {
+  // An iterator that can be much faster than the iterator of a reversed slice.
+  @_fixed_layout
+  public struct Iterator {
+    @_versioned
+    internal let _base: Base
+    @_versioned
+    internal var _position: Base.Index
+
+    @_inlineable
+    @inline(__always)
+    /// Creates an iterator over the given collection.
+    public /// @testable
+    init(_base: Base) {
+      self._base = _base
+      self._position = _base.endIndex
+    }
+  }
+}
+ 
+extension ReversedCollection.Iterator: IteratorProtocol, Sequence {
+  public typealias Element = Base.Element
+  
+  @_inlineable
+  @inline(__always)
+  public mutating func next() -> Element? {
+    guard _fastPath(_position != _base.startIndex) else { return nil }
+    _base.formIndex(before: &_position)
+    return _base[_position]
+  }
+}
+
+extension ReversedCollection: Sequence {
   /// A type that represents a valid position in the collection.
   ///
   /// Valid indices consist of the position of every element and a
   /// "past the end" position that's not valid for use as a subscript.
-  public typealias Index = ReversedIndex<Base>
-
-  @_fixed_layout
-  public struct Iterator : IteratorProtocol, Sequence {
-    @_inlineable
-    @inline(__always)
-    public /// @testable
-    init(elements: Base, endPosition: Base.Index) {
-      self._elements = elements
-      self._position = endPosition
-    }
-    
-    @_inlineable
-    @inline(__always)
-    public mutating func next() -> Base.Iterator.Element? {
-      guard _fastPath(_position != _elements.startIndex) else { return nil }
-      _position = _elements.index(before: _position)
-      return _elements[_position]
-    }
-    
-    @_versioned
-    internal let _elements: Base
-    @_versioned
-    internal var _position: Base.Index
-  }
+  public typealias Element = Base.Element
 
   @_inlineable
   @inline(__always)
   public func makeIterator() -> Iterator {
-    return Iterator(elements: _base, endPosition: _base.endIndex)
+    return Iterator(_base: _base)
+  }
+}
+
+extension ReversedCollection {
+  /// An index that traverses the same positions as an underlying index,
+  /// with inverted traversal direction.
+  @_fixed_layout
+  public struct Index {
+    /// The position after this position in the underlying collection.
+    ///
+    /// To find the position that corresponds with this index in the original,
+    /// underlying collection, use that collection's `index(before:)` method
+    /// with the `base` property.
+    ///
+    /// The following example declares a function that returns the index of the
+    /// last even number in the passed array, if one is found. First, the
+    /// function finds the position of the last even number as a `ReversedIndex`
+    /// in a reversed view of the array of numbers. Next, the function calls the
+    /// array's `index(before:)` method to return the correct position in the
+    /// passed array.
+    ///
+    ///     func indexOfLastEven(_ numbers: [Int]) -> Int? {
+    ///         let reversedNumbers = numbers.reversed()
+    ///         guard let i = reversedNumbers.index(where: { $0 % 2 == 0 })
+    ///             else { return nil }
+    ///
+    ///         return numbers.index(before: i.base)
+    ///     }
+    ///
+    ///     let numbers = [10, 20, 13, 19, 30, 52, 17, 40, 51]
+    ///     if let lastEven = indexOfLastEven(numbers) {
+    ///         print("Last even number: \(numbers[lastEven])")
+    ///     }
+    ///     // Prints "Last even number: 40"
+    public let base: Base.Index
+
+    /// Creates a new index into a reversed collection for the position before
+    /// the specified index.
+    ///
+    /// When you create an index into a reversed collection using `base`, an
+    /// index from the underlying collection, the resulting index is the
+    /// position of the element *before* the element referenced by `base`. The
+    /// following example creates a new `ReversedIndex` from the index of the
+    /// `"a"` character in a string's character view.
+    ///
+    ///     let name = "Horatio"
+    ///     let aIndex = name.index(of: "a")!
+    ///     // name[aIndex] == "a"
+    ///
+    ///     let reversedName = name.reversed()
+    ///     let i = ReversedIndex<String>(aIndex)
+    ///     // reversedName[i] == "r"
+    ///
+    /// The element at the position created using `ReversedIndex<...>(aIndex)` is
+    /// `"r"`, the character before `"a"` in the `name` string.
+    ///
+    /// - Parameter base: The position after the element to create an index for.
+    @_inlineable
+    public init(_ base: Base.Index) {
+      self.base = base
+    }
+  }
+}
+
+extension ReversedCollection.Index: Comparable {
+  @_inlineable
+  public static func == (
+    lhs: ReversedCollection<Base>.Index,
+    rhs: ReversedCollection<Base>.Index
+  ) -> Bool {
+    // Note ReversedIndex has inverted logic compared to base Base.Index
+    return lhs.base == rhs.base
   }
 
   @_inlineable
+  public static func < (
+    lhs: ReversedCollection<Base>.Index,
+    rhs: ReversedCollection<Base>.Index
+  ) -> Bool {
+    // Note ReversedIndex has inverted logic compared to base Base.Index
+    return lhs.base > rhs.base
+  }
+}
+
+extension ReversedCollection.Index: Hashable where Base.Index: Hashable {
+  public var hashValue: Int {
+    return base.hashValue
+  }
+}
+
+extension ReversedCollection: BidirectionalCollection {  
+  @_inlineable
   public var startIndex: Index {
-    return ReversedIndex(_base.endIndex)
+    return Index(_base.endIndex)
   }
 
   @_inlineable
   public var endIndex: Index {
-    return ReversedIndex(_base.startIndex)
+    return Index(_base.startIndex)
   }
 
   @_inlineable
   public func index(after i: Index) -> Index {
-    return ReversedIndex(_base.index(before: i.base))
+    return Index(_base.index(before: i.base))
   }
 
   @_inlineable
   public func index(before i: Index) -> Index {
-    return ReversedIndex(_base.index(after: i.base))
+    return Index(_base.index(after: i.base))
   }
 
   @_inlineable
   public func index(_ i: Index, offsetBy n: Int) -> Index {
     // FIXME: swift-3-indexing-model: `-n` can trap on Int.min.
-    return ReversedIndex(_base.index(i.base, offsetBy: -n))
+    return Index(_base.index(i.base, offsetBy: -n))
   }
 
   @_inlineable
@@ -247,7 +232,7 @@
   ) -> Index? {
     // FIXME: swift-3-indexing-model: `-n` can trap on Int.min.
     return _base.index(i.base, offsetBy: -n, limitedBy: limit.base)
-                .map(ReversedIndex.init)
+                .map(Index.init)
   }
 
   @_inlineable
@@ -256,21 +241,13 @@
   }
 
   @_inlineable
-  public subscript(position: Index) -> Base.Element {
+  public subscript(position: Index) -> Element {
     return _base[_base.index(before: position.base)]
   }
-
-  @_inlineable
-  public subscript(bounds: Range<Index>) -> Slice<ReversedCollection> {
-    return Slice(base: self, bounds: bounds)
-  }
 }
 
 extension ReversedCollection: RandomAccessCollection where Base: RandomAccessCollection { }
 
-@available(*, deprecated, renamed: "ReversedCollection")
-public typealias ReversedRandomAccessCollection<T: RandomAccessCollection> = ReversedCollection<T>
-
 extension BidirectionalCollection {
   /// Returns a view presenting the elements of the collection in reverse
   /// order.
@@ -305,8 +282,8 @@
 
 extension LazyCollectionProtocol
   where
-  Self : BidirectionalCollection,
-  Elements : BidirectionalCollection {
+  Self: BidirectionalCollection,
+  Elements: BidirectionalCollection {
 
   /// Returns the elements of the collection in reverse order.
   ///
@@ -316,3 +293,9 @@
     return ReversedCollection(_base: elements).lazy
   }
 }
+
+// @available(*, deprecated, renamed: "ReversedCollection")
+public typealias ReversedRandomAccessCollection<T: RandomAccessCollection> = ReversedCollection<T>
+
+// @available(*, deprecated, renamed: "ReversedCollection.Index")
+public typealias ReversedIndex<T: BidirectionalCollection> = ReversedCollection<T>
diff --git a/stdlib/public/core/Sequence.swift b/stdlib/public/core/Sequence.swift
index deaf468..accf446 100644
--- a/stdlib/public/core/Sequence.swift
+++ b/stdlib/public/core/Sequence.swift
@@ -612,6 +612,13 @@
   ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index)
 }
 
+// Provides a default associated type witness for Iterator when the
+// Self type is both a Sequence and an Iterator.
+extension Sequence where Self: IteratorProtocol {
+  // @_implements(Sequence, Iterator)
+  public typealias _Default_Iterator = Self
+}
+
 /// A default makeIterator() function for `IteratorProtocol` instances that
 /// are declared to conform to `Sequence`
 extension Sequence where Self.Iterator == Self {
@@ -622,7 +629,6 @@
   }
 }
 
-
 /// A sequence that lazily consumes and drops `n` elements from an underlying
 /// `Base` iterator before possibly returning the first available element.
 ///
diff --git a/stdlib/public/core/SequenceAlgorithms.swift.gyb b/stdlib/public/core/SequenceAlgorithms.swift.gyb
index fbfb96e..6e70462 100644
--- a/stdlib/public/core/SequenceAlgorithms.swift.gyb
+++ b/stdlib/public/core/SequenceAlgorithms.swift.gyb
@@ -734,6 +734,37 @@
   /// transformation produces an optional value.
   ///
   /// In this example, note the difference in the result of using `map` and
+  /// `compactMap` with a transformation that returns an optional `Int` value.
+  ///
+  ///     let possibleNumbers = ["1", "2", "three", "///4///", "5"]
+  ///
+  ///     let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
+  ///     // [1, 2, nil, nil, 5]
+  ///
+  ///     let flatMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }
+  ///     // [1, 2, 5]
+  ///
+  /// - Parameter transform: A closure that accepts an element of this
+  ///   sequence as its argument and returns an optional value.
+  /// - Returns: An array of the non-`nil` results of calling `transform`
+  ///   with each element of the sequence.
+  ///
+  /// - Complexity: O(*m* + *n*), where *m* is the length of this sequence
+  ///   and *n* is the length of the result.
+  @_inlineable
+  public func compactMap<ElementOfResult>(
+    _ transform: (Element) throws -> ElementOfResult?
+  ) rethrows -> [ElementOfResult] {
+    return try _compactMap(transform)
+  }
+
+  /// Returns an array containing the non-`nil` results of calling the given
+  /// transformation with each element of this sequence.
+  ///
+  /// Use this method to receive an array of nonoptional values when your
+  /// transformation produces an optional value.
+  ///
+  /// In this example, note the difference in the result of using `map` and
   /// `flatMap` with a transformation that returns an optional `Int` value.
   ///
   ///     let possibleNumbers = ["1", "2", "three", "///4///", "5"]
@@ -751,11 +782,12 @@
   ///
   /// - Complexity: O(*m* + *n*), where *m* is the length of this sequence
   ///   and *n* is the length of the result.
-  @_inlineable
+  @inline(__always)
+  @available(*, deprecated, renamed: "compactMap(_:)")
   public func flatMap<ElementOfResult>(
     _ transform: (Element) throws -> ElementOfResult?
   ) rethrows -> [ElementOfResult] {
-    return try _flatMap(transform)
+    return try _compactMap(transform)
   }
 
   // The implementation of flatMap accepting a closure with an optional result.
@@ -763,7 +795,7 @@
   // overloads.
   @_inlineable // FIXME(sil-serialize-all)
   @inline(__always)
-  public func _flatMap<ElementOfResult>(
+  public func _compactMap<ElementOfResult>(
     _ transform: (Element) throws -> ElementOfResult?
   ) rethrows -> [ElementOfResult] {
     var result: [ElementOfResult] = []
diff --git a/stdlib/public/core/StringRangeReplaceableCollection.swift.gyb b/stdlib/public/core/StringRangeReplaceableCollection.swift.gyb
index 8796b21..42ade6d 100644
--- a/stdlib/public/core/StringRangeReplaceableCollection.swift.gyb
+++ b/stdlib/public/core/StringRangeReplaceableCollection.swift.gyb
@@ -438,10 +438,18 @@
 
 extension Collection {
   @_inlineable // FIXME(sil-serialize-all)
+  public func compactMap(
+    _ transform: (Element) throws -> String?
+  ) rethrows -> [String] {
+    return try _compactMap(transform)
+  }
+
+  @available(*, deprecated, renamed: "compactMap(_:)")
+  @inline(__always)
   public func flatMap(
     _ transform: (Element) throws -> String?
   ) rethrows -> [String] {
-    return try _flatMap(transform)
+    return try _compactMap(transform)
   }
 }
 //===----------------------------------------------------------------------===//
diff --git a/stdlib/public/core/StringUnicodeScalarView.swift b/stdlib/public/core/StringUnicodeScalarView.swift
index 8280515..ee364cd 100644
--- a/stdlib/public/core/StringUnicodeScalarView.swift
+++ b/stdlib/public/core/StringUnicodeScalarView.swift
@@ -257,9 +257,9 @@
       @_versioned // FIXME(sil-serialize-all)
       internal let _ascii: Bool
       @_versioned // FIXME(sil-serialize-all)
-      internal var _asciiBase: UnsafeBufferPointerIterator<UInt8>!
+      internal var _asciiBase: UnsafeBufferPointer<UInt8>.Iterator!
       @_versioned // FIXME(sil-serialize-all)
-      internal var _base: UnsafeBufferPointerIterator<UInt16>!
+      internal var _base: UnsafeBufferPointer<UInt16>.Iterator!
       @_versioned // FIXME(sil-serialize-all)
       internal var _iterator: IndexingIterator<_StringCore>
     }
diff --git a/stdlib/public/core/UnsafeBufferPointer.swift.gyb b/stdlib/public/core/UnsafeBufferPointer.swift.gyb
index df50805..596d034 100644
--- a/stdlib/public/core/UnsafeBufferPointer.swift.gyb
+++ b/stdlib/public/core/UnsafeBufferPointer.swift.gyb
@@ -10,34 +10,6 @@
 //
 //===----------------------------------------------------------------------===//
 
-/// An iterator for the elements in the buffer referenced by an
-/// `UnsafeBufferPointer` or `UnsafeMutableBufferPointer` instance.
-@_fixed_layout
-public struct UnsafeBufferPointerIterator<Element>
-  : IteratorProtocol, Sequence {
-
-  /// Advances to the next element and returns it, or `nil` if no next element
-  /// exists.
-  ///
-  /// Once `nil` has been returned, all subsequent calls return `nil`.
-  @_inlineable
-  public mutating func next() -> Element? {
-    if _position == _end { return nil }
-
-    let result = _position!.pointee
-    _position! += 1
-    return result
-  }
-
-  @_versioned
-  internal var _position, _end: UnsafePointer<Element>?
-
-  @_inlineable
-  public init(_position: UnsafePointer<Element>?, _end: UnsafePointer<Element>?) {
-      self._position = _position
-      self._end = _end
-  }
-}
 
 % for mutable in (True, False):
 %  Self = 'UnsafeMutableBufferPointer' if mutable else 'UnsafeBufferPointer'
@@ -57,24 +29,89 @@
 /// instances stored in the underlying memory. However, initializing another
 /// collection with an `${Self}` instance copies the instances out of the
 /// referenced memory and into the new collection.
+// FIXME: rdar://18157434 - until this is fixed, this has to be fixed layout
+// to avoid a hang in Foundation, which has the following setup:
+// struct A { struct B { let x: UnsafeMutableBufferPointer<...> } let b: B }
 @_fixed_layout
-public struct Unsafe${Mutable}BufferPointer<Element>
-  : ${Mutable}Collection, RandomAccessCollection {
-  // FIXME: rdar://18157434 - until this is fixed, this has to be fixed layout
-  // to avoid a hang in Foundation, which has the following setup:
-  // struct A { struct B { let x: UnsafeMutableBufferPointer<...> } let b: B }
+public struct Unsafe${Mutable}BufferPointer<Element> {
+  @_versioned
+  let _position, _end: Unsafe${Mutable}Pointer<Element>?
+}
 
+%if not mutable:
+extension UnsafeBufferPointer {
+  /// An iterator for the elements in the buffer referenced by an
+  /// `UnsafeBufferPointer` or `UnsafeMutableBufferPointer` instance.
+  @_fixed_layout
+  public struct Iterator {
+    @_versioned
+    internal var _position, _end: UnsafePointer<Element>?
+
+    @_inlineable
+    public init(_position: UnsafePointer<Element>?, _end: UnsafePointer<Element>?) {
+        self._position = _position
+        self._end = _end
+    }
+  }
+}
+
+extension UnsafeBufferPointer.Iterator: IteratorProtocol {
+  /// Advances to the next element and returns it, or `nil` if no next element
+  /// exists.
+  ///
+  /// Once `nil` has been returned, all subsequent calls return `nil`.
+  @_inlineable
+  public mutating func next() -> Element? {
+    if _position == _end { return nil }
+
+    let result = _position!.pointee
+    _position! += 1
+    return result
+  }
+}
+%else:
+extension UnsafeMutableBufferPointer {
+  public typealias Iterator = UnsafeBufferPointer<Element>.Iterator
+}
+%end
+
+extension Unsafe${Mutable}BufferPointer: Sequence {
+  /// Returns an iterator over the elements of this buffer.
+  ///
+  /// - Returns: An iterator over the elements of this buffer.
+  @_inlineable
+  public func makeIterator() -> Iterator {
+    return Iterator(_position: _position, _end: _end)
+  }
+
+  /// Initializes the memory at `destination.baseAddress` with elements of `self`,
+  /// stopping when either `self` or `destination` is exhausted.
+  ///
+  /// - Returns: an iterator over any remaining elements of `self` and the
+  ///   number of elements initialized.
+  @_inlineable // FIXME(sil-serialize-all)
+  public func _copyContents(
+    initializing destination: UnsafeMutableBufferPointer<Element>
+  ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {
+    guard !isEmpty && !destination.isEmpty else { return (makeIterator(), 0) }
+    let s = self.baseAddress._unsafelyUnwrappedUnchecked
+    let d = destination.baseAddress._unsafelyUnwrappedUnchecked
+    let n = Swift.min(destination.count, self.count)
+    d.initialize(from: s, count: n)
+    return (Iterator(_position: s + n, _end: _end), n)
+  }
+}
+
+extension Unsafe${Mutable}BufferPointer: ${Mutable}Collection, RandomAccessCollection {
   public typealias Index = Int
-  public typealias Iterator = UnsafeBufferPointerIterator<Element>
+  public typealias Indices = CountableRange<Int>
 
   /// The index of the first element in a nonempty buffer.
   ///
   /// The `startIndex` property of an `Unsafe${Mutable}BufferPointer` instance
   /// is always zero.
   @_inlineable
-  public var startIndex: Int {
-    return 0
-  }
+  public var startIndex: Int { return 0 }
 
   /// The "past the end" position---that is, the position one greater than the
   /// last valid subscript argument.
@@ -82,9 +119,7 @@
   /// The `endIndex` property of an `Unsafe${Mutable}BufferPointer` instance is
   /// always identical to `count`.
   @_inlineable
-  public var endIndex: Int {
-    return count
-  }
+  public var endIndex: Int { return count }
 
   @_inlineable
   public func index(after i: Int) -> Int {
@@ -137,9 +172,7 @@
   }
 
   @_inlineable
-  public func index(
-    _ i: Int, offsetBy n: Int, limitedBy limit: Int
-  ) -> Int? {
+  public func index(_ i: Int, offsetBy n: Int, limitedBy limit: Int) -> Int? {
     // NOTE: this is a manual specialization of index movement for a Strideable
     // index that is required for UnsafeBufferPointer performance. The
     // optimizer is not capable of creating partial specializations yet.
@@ -172,28 +205,22 @@
     // NOTE: This method is a no-op for performance reasons.
   }
 
-  public typealias Indices = CountableRange<Int>
-
   @_inlineable
   public var indices: Indices {
     return startIndex..<endIndex
   }
 
-  /// Initializes the memory at `destination.baseAddress` with elements of `self`,
-  /// stopping when either `self` or `destination` is exhausted.
+  /// The number of elements in the buffer.
   ///
-  /// - Returns: an iterator over any remaining elements of `self` and the
-  ///   number of elements initialized.
-  @_inlineable // FIXME(sil-serialize-all)
-  public func _copyContents(
-    initializing destination: UnsafeMutableBufferPointer<Element>
-  ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {
-    guard !isEmpty && !destination.isEmpty else { return (makeIterator(), 0) }
-    let s = self.baseAddress._unsafelyUnwrappedUnchecked
-    let d = destination.baseAddress._unsafelyUnwrappedUnchecked
-    let n = Swift.min(destination.count, self.count)
-    d.initialize(from: s, count: n)
-    return (Iterator(_position: s + n, _end: _end), n)
+  /// If the `baseAddress` of this buffer is `nil`, the count is zero. However,
+  /// a buffer can have a `count` of zero even with a non-`nil` base address.
+  @_inlineable
+  public var count: Int {
+    guard let start = _position, let end = _end else {
+      return 0
+    }
+    
+    return end - start
   }
 
   /// Accesses the element at the specified position.
@@ -267,7 +294,9 @@
     }
 %  end
   }
+}
 
+extension Unsafe${Mutable}BufferPointer {
   /// Creates a new buffer pointer over the specified number of contiguous
   /// instances beginning at the given pointer.
   ///
@@ -378,22 +407,12 @@
   ///
   /// - Parameter slice: The buffer slice to rebase.
   @_inlineable
-  public init(
-    rebasing slice:
-    Slice<UnsafeMutableBufferPointer<Element>>
-  ) {
-    self.init(start: slice.base.baseAddress! + slice.startIndex,
+  public init(rebasing slice: Slice<UnsafeMutableBufferPointer<Element>>) {
+    self.init(
+      start: slice.base.baseAddress! + slice.startIndex,
       count: slice.count)
   }
 
-  /// Returns an iterator over the elements of this buffer.
-  ///
-  /// - Returns: An iterator over the elements of this buffer.
-  @_inlineable
-  public func makeIterator() -> UnsafeBufferPointerIterator<Element> {
-    return UnsafeBufferPointerIterator(_position: _position, _end: _end)
-  }
-  
   /// Deallocates the memory block previously allocated at this buffer pointer’s 
   /// base address. 
   ///
@@ -539,22 +558,6 @@
   public var baseAddress: Unsafe${Mutable}Pointer<Element>? {
     return _position
   }
-
-  /// The number of elements in the buffer.
-  ///
-  /// If the `baseAddress` of this buffer is `nil`, the count is zero. However,
-  /// a buffer can have a `count` of zero even with a non-`nil` base address.
-  @_inlineable
-  public var count: Int {
-    guard let start = _position, let end = _end else {
-      return 0
-    }
-    
-    return end - start
-  }
-
-  @_versioned
-  let _position, _end: Unsafe${Mutable}Pointer<Element>?
 }
 
 extension Unsafe${Mutable}BufferPointer : CustomDebugStringConvertible {
@@ -596,6 +599,9 @@
   }
 }
 
+@available(*, deprecated, renamed: "UnsafeBufferPointer.Iterator")
+public typealias UnsafeBufferPointerIterator<T> = UnsafeBufferPointer<T>.Iterator
+
 // ${'Local Variables'}:
 // eval: (read-only-mode 1)
 // End:
diff --git a/stdlib/public/core/UnsafePointer.swift.gyb b/stdlib/public/core/UnsafePointer.swift.gyb
index f437211..01e308e 100644
--- a/stdlib/public/core/UnsafePointer.swift.gyb
+++ b/stdlib/public/core/UnsafePointer.swift.gyb
@@ -819,7 +819,7 @@
 %  if mutable:
   /// For a pointer `p`, the memory at `p + i` must be initialized when reading
   /// the value by using the subscript. When the subscript is used as the left
-  /// side of an assignment, the memory at `p + i` must be uninitialized or
+  /// side of an assignment, the memory at `p + i` must be initialized or
   /// the pointer's `Pointee` type must be a trivial type.
   ///
   /// Do not assign an instance of a nontrivial type through the subscript to
diff --git a/stdlib/public/core/UnsafeRawBufferPointer.swift.gyb b/stdlib/public/core/UnsafeRawBufferPointer.swift.gyb
index b1df79e..3db5064 100644
--- a/stdlib/public/core/UnsafeRawBufferPointer.swift.gyb
+++ b/stdlib/public/core/UnsafeRawBufferPointer.swift.gyb
@@ -98,28 +98,11 @@
   internal let _position, _end: Unsafe${Mutable}RawPointer?
 }
 
-extension Unsafe${Mutable}RawBufferPointer: Sequence {
-  public typealias SubSequence = Slice<${Self}>
-
+%if not mutable:
+extension UnsafeRawBufferPointer {
   /// An iterator over the bytes viewed by a raw buffer pointer.
   @_fixed_layout
-  public struct Iterator : IteratorProtocol, Sequence {
-    /// Advances to the next byte and returns it, or `nil` if no next byte
-    /// exists.
-    ///
-    /// Once `nil` has been returned, all subsequent calls return `nil`.
-    ///
-    /// - Returns: The next sequential byte in the raw buffer if another byte
-    ///   exists; otherwise, `nil`.
-    @_inlineable
-    public mutating func next() -> UInt8? {
-      if _position == _end { return nil }
-
-      let result = _position!.load(as: UInt8.self)
-      _position! += 1
-      return result
-    }
-
+  public struct Iterator {
     @_versioned
     internal var _position, _end: UnsafeRawPointer?
 
@@ -130,6 +113,33 @@
       self._end = _end
     }
   }
+}
+
+extension UnsafeRawBufferPointer.Iterator: IteratorProtocol, Sequence {
+  /// Advances to the next byte and returns it, or `nil` if no next byte
+  /// exists.
+  ///
+  /// Once `nil` has been returned, all subsequent calls return `nil`.
+  ///
+  /// - Returns: The next sequential byte in the raw buffer if another byte
+  ///   exists; otherwise, `nil`.
+  @_inlineable
+  public mutating func next() -> UInt8? {
+    if _position == _end { return nil }
+
+    let result = _position!.load(as: UInt8.self)
+    _position! += 1
+    return result
+  }
+}
+%else:
+extension UnsafeMutableRawBufferPointer {
+  public typealias Iterator = UnsafeRawBufferPointer.Iterator
+}
+%end
+
+extension Unsafe${Mutable}RawBufferPointer: Sequence {
+  public typealias SubSequence = Slice<${Self}>
 
   /// Returns an iterator over the bytes of this sequence.
   @_inlineable
@@ -666,8 +676,8 @@
 
 extension ${Self} {
   @_inlineable // FIXME(sil-serialize-all)
-  @available(*, unavailable, message:
-    "use 'Unsafe${Mutable}RawBufferPointer(rebasing:)' to convert a slice into a zero-based raw buffer.")
+  @available(*, unavailable, 
+    message: "use 'Unsafe${Mutable}RawBufferPointer(rebasing:)' to convert a slice into a zero-based raw buffer.")
   public subscript(bounds: Range<Int>) -> ${Self} {
     get { return ${Self}(start: nil, count: 0) }
 %  if mutable:
@@ -676,8 +686,8 @@
   }
 
 %  if mutable:
-  @available(*, unavailable, message:
-    "use 'UnsafeRawBufferPointer(rebasing:)' to convert a slice into a zero-based raw buffer.")
+  @available(*, unavailable, 
+    message: "use 'UnsafeRawBufferPointer(rebasing:)' to convert a slice into a zero-based raw buffer.")
   public subscript(bounds: Range<Int>) -> UnsafeRawBufferPointer {
     get { return UnsafeRawBufferPointer(start: nil, count: 0) }
     nonmutating set {}
@@ -740,3 +750,9 @@
     try body(UnsafeRawBufferPointer(start: $0, count: MemoryLayout<T>.size))
   }
 }
+
+// @available(*, deprecated, renamed: "UnsafeRawBufferPointer.Iterator")
+public typealias UnsafeRawBufferPointerIterator<T> = UnsafeBufferPointer<T>.Iterator
+
+// @available(*, deprecated, renamed: "UnsafeRawBufferPointer.Iterator")
+public typealias UnsafeMutableRawBufferPointerIterator<T> = UnsafeBufferPointer<T>.Iterator
diff --git a/stdlib/public/core/Zip.swift b/stdlib/public/core/Zip.swift
index 48fe444..6aaf7c4 100644
--- a/stdlib/public/core/Zip.swift
+++ b/stdlib/public/core/Zip.swift
@@ -48,54 +48,6 @@
   return Zip2Sequence(_sequence1: sequence1, _sequence2: sequence2)
 }
 
-/// An iterator for `Zip2Sequence`.
-@_fixed_layout // FIXME(sil-serialize-all)
-public struct Zip2Iterator<Iterator1: IteratorProtocol, Iterator2: IteratorProtocol> {
-  /// The type of element returned by `next()`.
-  public typealias Element = (Iterator1.Element, Iterator2.Element)
-
-  @_versioned // FIXME(sil-serialize-all)
-  internal var _baseStream1: Iterator1
-  @_versioned // FIXME(sil-serialize-all)
-  internal var _baseStream2: Iterator2
-  @_versioned // FIXME(sil-serialize-all)
-  internal var _reachedEnd: Bool = false
-
-  /// Creates an instance around a pair of underlying iterators.
-  @_inlineable // FIXME(sil-serialize-all)
-  @_versioned // FIXME(sil-serialize-all)
-  internal init(_ iterator1: Iterator1, _ iterator2: Iterator2) {
-    (_baseStream1, _baseStream2) = (iterator1, iterator2)
-  }
-}
-
-extension Zip2Iterator: IteratorProtocol {
-  /// Advances to the next element and returns it, or `nil` if no next element
-  /// exists.
-  ///
-  /// Once `nil` has been returned, all subsequent calls return `nil`.
-  @_inlineable // FIXME(sil-serialize-all)
-  public mutating func next() -> Element? {
-    // The next() function needs to track if it has reached the end.  If we
-    // didn't, and the first sequence is longer than the second, then when we
-    // have already exhausted the second sequence, on every subsequent call to
-    // next() we would consume and discard one additional element from the
-    // first sequence, even though next() had already returned nil.
-
-    if _reachedEnd {
-      return nil
-    }
-
-    guard let element1 = _baseStream1.next(),
-          let element2 = _baseStream2.next() else {
-      _reachedEnd = true
-      return nil
-    }
-
-    return (element1, element2)
-  }
-}
-
 /// A sequence of pairs built out of two underlying sequences.
 ///
 /// In a `Zip2Sequence` instance, the elements of the *i*th pair are the *i*th
@@ -136,10 +88,61 @@
   }
 }
 
+extension Zip2Sequence {
+  /// An iterator for `Zip2Sequence`.
+  @_fixed_layout // FIXME(sil-serialize-all)
+  public struct Iterator {
+    @_versioned // FIXME(sil-serialize-all)
+    internal var _baseStream1: Sequence1.Iterator
+    @_versioned // FIXME(sil-serialize-all)
+    internal var _baseStream2: Sequence2.Iterator
+    @_versioned // FIXME(sil-serialize-all)
+    internal var _reachedEnd: Bool = false
+
+    /// Creates an instance around a pair of underlying iterators.
+    @_inlineable // FIXME(sil-serialize-all)
+    @_versioned // FIXME(sil-serialize-all)
+    internal init(
+    _ iterator1: Sequence1.Iterator, 
+    _ iterator2: Sequence2.Iterator
+    ) {
+      (_baseStream1, _baseStream2) = (iterator1, iterator2)
+    }
+  }
+}
+
+extension Zip2Sequence.Iterator: IteratorProtocol {
+  /// The type of element returned by `next()`.
+  public typealias Element = (Sequence1.Element, Sequence2.Element)
+
+  /// Advances to the next element and returns it, or `nil` if no next element
+  /// exists.
+  ///
+  /// Once `nil` has been returned, all subsequent calls return `nil`.
+  @_inlineable // FIXME(sil-serialize-all)
+  public mutating func next() -> Element? {
+    // The next() function needs to track if it has reached the end.  If we
+    // didn't, and the first sequence is longer than the second, then when we
+    // have already exhausted the second sequence, on every subsequent call to
+    // next() we would consume and discard one additional element from the
+    // first sequence, even though next() had already returned nil.
+
+    if _reachedEnd {
+      return nil
+    }
+
+    guard let element1 = _baseStream1.next(),
+          let element2 = _baseStream2.next() else {
+      _reachedEnd = true
+      return nil
+    }
+
+    return (element1, element2)
+  }
+}
+
 extension Zip2Sequence: Sequence {
-  /// A type whose instances can produce the elements of this
-  /// sequence, in order.
-  public typealias Iterator = Zip2Iterator<Sequence1.Iterator, Sequence2.Iterator>
+  public typealias Element = (Sequence1.Element, Sequence2.Element)
 
   /// Returns an iterator over the elements of this sequence.
   @_inlineable // FIXME(sil-serialize-all)
@@ -149,3 +152,6 @@
       _sequence2.makeIterator())
   }
 }
+
+// @available(*, deprecated, renamed: "Zip2Sequence.Iterator")
+public typealias Zip2Iterator<T, U> = Zip2Sequence<T, U>.Iterator where T: Sequence, U: Sequence
diff --git a/stdlib/public/runtime/Casting.cpp b/stdlib/public/runtime/Casting.cpp
index 7b9381c..9c6ab68 100644
--- a/stdlib/public/runtime/Casting.cpp
+++ b/stdlib/public/runtime/Casting.cpp
@@ -629,7 +629,7 @@
 // internal func _getErrorEmbeddedNSErrorIndirect<T : Error>(
 //   _ x: UnsafePointer<T>) -> AnyObject?
 #define getErrorEmbeddedNSErrorIndirect \
-  MANGLE_SYM(s32_getErrorEmbeddedNSErrorIndirectyXlSgSPyxGs0B0RzlF)
+  MANGLE_SYM(s32_getErrorEmbeddedNSErrorIndirectyyXlSgSPyxGs0B0RzlF)
 SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
 id getErrorEmbeddedNSErrorIndirect(const OpaqueValue *error,
                                    const Metadata *T,
@@ -2973,7 +2973,7 @@
 /// public func _bridgeAnythingNonVerbatimToObjectiveC<T>(_ x: T) -> AnyObject
 /// Called by inlined stdlib code.
 #define _bridgeAnythingNonVerbatimToObjectiveC \
-  MANGLE_SYM(s38_bridgeAnythingNonVerbatimToObjectiveCyXlxlF)
+  MANGLE_SYM(s38_bridgeAnythingNonVerbatimToObjectiveCyyXlxlF)
 SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_API
 id _bridgeAnythingNonVerbatimToObjectiveC(OpaqueValue *src,
                                           const Metadata *srcType) {
@@ -3036,7 +3036,7 @@
 // public func _getBridgedNonVerbatimObjectiveCType<T>(_: T.Type) -> Any.Type?
 // Called by inlined stdlib code.
 #define _getBridgedNonVerbatimObjectiveCType \
-  MANGLE_SYM(s36_getBridgedNonVerbatimObjectiveCTypeypXpSgxmlF)
+  MANGLE_SYM(s36_getBridgedNonVerbatimObjectiveCTypeyypXpSgxmlF)
 SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_API
 const Metadata *_getBridgedNonVerbatimObjectiveCType(
   const Metadata *value, const Metadata *T
@@ -3105,14 +3105,14 @@
   return false;
 }
 
-// func _bridgeNonVerbatimFromObjectiveC<NativeType>(
-//     x: AnyObject, 
-//     nativeType: NativeType.Type
-//     inout result: T?
+// func _bridgeNonVerbatimFromObjectiveC<T>(
+//     _ x: AnyObject,
+//     _ nativeType: T.Type
+//     _ inout result: T?
 // )
 // Called by inlined stdlib code.
 #define _bridgeNonVerbatimFromObjectiveC \
-  MANGLE_SYM(s32_bridgeNonVerbatimFromObjectiveCyyXl_xmxSgztlF)
+  MANGLE_SYM(s32_bridgeNonVerbatimFromObjectiveCyyyXl_xmxSgztlF)
 SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_API
 void
 _bridgeNonVerbatimFromObjectiveC(
@@ -3150,11 +3150,11 @@
   swift::crash("value type is not bridged to Objective-C");
 }
 
-/// func _bridgeNonVerbatimFromObjectiveCConditional<NativeType>(
-///   x: AnyObject, nativeType: T.Type, inout result: T?) -> Bool
+/// func _bridgeNonVerbatimFromObjectiveCConditional<T>(
+///   _ x: AnyObject, _ nativeType: T.Type, _ result: inout T?) -> Bool
 /// Called by inlined stdlib code.
 #define _bridgeNonVerbatimFromObjectiveCConditional \
-  MANGLE_SYM(s43_bridgeNonVerbatimFromObjectiveCConditionalSbyXl_xmxSgztlF)
+  MANGLE_SYM(s43_bridgeNonVerbatimFromObjectiveCConditionalySbyXl_xmxSgztlF)
 SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_API
 bool
 _bridgeNonVerbatimFromObjectiveCConditional(
@@ -3198,10 +3198,10 @@
     destValue, nativeType, nativeType, bridgeWitness);
 }
 
-// func _isBridgedNonVerbatimToObjectiveC<T>(x: T.Type) -> Bool
+// func _isBridgedNonVerbatimToObjectiveC<T>(_: T.Type) -> Bool
 // Called by inlined stdlib code.
 #define _isBridgedNonVerbatimToObjectiveC \
-  MANGLE_SYM(s33_isBridgedNonVerbatimToObjectiveCSbxmlF)
+  MANGLE_SYM(s33_isBridgedNonVerbatimToObjectiveCySbxmlF)
 SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_API
 bool _isBridgedNonVerbatimToObjectiveC(const Metadata *value,
                                        const Metadata *T) {
diff --git a/stdlib/public/runtime/Demangle.cpp b/stdlib/public/runtime/Demangle.cpp
index 379151e..bc12dbe 100644
--- a/stdlib/public/runtime/Demangle.cpp
+++ b/stdlib/public/runtime/Demangle.cpp
@@ -76,7 +76,7 @@
 
   // See if we have any generic arguments at this depth.
   unsigned numArgumentsAtDepth =
-      description->GenericParams.getContext(depth - 1).NumPrimaryParams;
+      description->getGenericContext(depth - 1).NumPrimaryParams;
   if (numArgumentsAtDepth == 0) {
     // No arguments here, just return the original node (except we may have
     // replaced its parent type above).
@@ -88,7 +88,7 @@
   unsigned firstArgumentAtDepth = 0;
   for (unsigned i = 0; i < depth - 1; i++) {
     firstArgumentAtDepth +=
-        description->GenericParams.getContext(i).NumPrimaryParams;
+        description->getGenericContext(i).NumPrimaryParams;
   }
 
   // Demangle them.
@@ -317,8 +317,8 @@
       kind = Node::Kind::ThinFunctionType;
       break;
     }
-    
-    std::vector<NodePointer> inputs;
+
+    std::vector<std::pair<NodePointer, bool>> inputs;
     for (unsigned i = 0, e = func->getNumParameters(); i < e; ++i) {
       auto param = func->getParameter(i);
       auto flags = func->getParameterFlags(i);
@@ -333,27 +333,58 @@
         shared->addChild(input, Dem);
         input = shared;
       }
-      inputs.push_back(input);
+
+      inputs.push_back({input, flags.isVariadic()});
     }
 
     NodePointer totalInput = nullptr;
     switch (inputs.size()) {
-    case 1:
-      totalInput = inputs.front();
-      break;
+    case 1: {
+      auto &singleParam = inputs.front();
+      if (!singleParam.second) {
+        totalInput = singleParam.first;
+        break;
+      }
+
+      // If single parameter has a variadic marker it
+      // requires a tuple wrapper.
+      LLVM_FALLTHROUGH;
+    }
 
     // This covers both none and multiple parameters.
     default:
       auto tuple = Dem.createNode(Node::Kind::Tuple);
-      for (auto &input : inputs)
-        tuple->addChild(input, Dem);
+      for (auto &input : inputs) {
+        NodePointer eltType;
+        bool isVariadic;
+        std::tie(eltType, isVariadic) = input;
+
+        // Tuple element := variadic-marker label? type
+        auto tupleElt = Dem.createNode(Node::Kind::TupleElement);
+
+        if (isVariadic)
+          tupleElt->addChild(Dem.createNode(Node::Kind::VariadicMarker), Dem);
+
+        if (eltType->getKind() == Node::Kind::Type) {
+          tupleElt->addChild(eltType, Dem);
+        } else {
+          auto type = Dem.createNode(Node::Kind::Type);
+          type->addChild(eltType, Dem);
+          tupleElt->addChild(type, Dem);
+        }
+
+        tuple->addChild(tupleElt, Dem);
+      }
       totalInput = tuple;
       break;
     }
 
-    NodePointer args = Dem.createNode(Node::Kind::ArgumentTuple);
-    args->addChild(totalInput, Dem);
-    
+    NodePointer parameters = Dem.createNode(Node::Kind::ArgumentTuple);
+    NodePointer paramType = Dem.createNode(Node::Kind::Type);
+
+    paramType->addChild(totalInput, Dem);
+    parameters->addChild(paramType, Dem);
+
     NodePointer resultTy = _swift_buildDemanglingForMetadata(func->ResultType,
                                                              Dem);
     NodePointer result = Dem.createNode(Node::Kind::ReturnType);
@@ -362,7 +393,7 @@
     auto funcNode = Dem.createNode(kind);
     if (func->throws())
       funcNode->addChild(Dem.createNode(Node::Kind::ThrowsAnnotation), Dem);
-    funcNode->addChild(args, Dem);
+    funcNode->addChild(parameters, Dem);
     funcNode->addChild(result, Dem);
     return funcNode;
   }
@@ -403,7 +434,14 @@
       // Add the element type child.
       auto eltType =
         _swift_buildDemanglingForMetadata(tuple->getElement(i).Type, Dem);
-      elt->addChild(eltType, Dem);
+
+      if (eltType->getKind() == Node::Kind::Type) {
+        elt->addChild(eltType, Dem);
+      } else {
+        auto type = Dem.createNode(Node::Kind::Type);
+        type->addChild(eltType, Dem);
+        elt->addChild(type, Dem);
+      }
 
       // Add the completed element to the tuple.
       tupleNode->addChild(elt, Dem);
diff --git a/stdlib/public/runtime/Enum.cpp b/stdlib/public/runtime/Enum.cpp
index 21eef71..e547848 100644
--- a/stdlib/public/runtime/Enum.cpp
+++ b/stdlib/public/runtime/Enum.cpp
@@ -26,10 +26,45 @@
 
 using namespace swift;
 
+static EnumValueWitnessTable *getMutableVWTableForInit(EnumMetadata *self,
+                                                       EnumLayoutFlags flags) {
+  auto oldTable =
+    static_cast<const EnumValueWitnessTable *>(self->getValueWitnesses());
+
+  // If we can alter the existing table in-place, do so.
+  if (isValueWitnessTableMutable(flags))
+    return const_cast<EnumValueWitnessTable*>(oldTable);
+
+  // Otherwise, allocate permanent memory for it and copy the existing table.
+  void *memory = allocateMetadata(sizeof(EnumValueWitnessTable),
+                                  alignof(EnumValueWitnessTable));
+  auto newTable = new (memory) EnumValueWitnessTable(*oldTable);
+  self->setValueWitnesses(newTable);
+
+  return newTable;
+}
+
 void
-swift::swift_initEnumValueWitnessTableSinglePayload(ValueWitnessTable *vwtable,
-                                                const TypeLayout *payloadLayout,
-                                                unsigned emptyCases) {
+swift::swift_initEnumMetadataSingleCase(EnumMetadata *self,
+                                        EnumLayoutFlags layoutFlags,
+                                        const TypeLayout *payloadLayout) {
+  auto vwtable = getMutableVWTableForInit(self, layoutFlags);
+
+  vwtable->size = payloadLayout->size;
+  vwtable->stride = payloadLayout->stride;
+  vwtable->flags = payloadLayout->flags.withEnumWitnesses(true);
+
+  if (payloadLayout->flags.hasExtraInhabitants()) {
+    auto ew = static_cast<ExtraInhabitantsValueWitnessTable*>(vwtable);
+    ew->extraInhabitantFlags = payloadLayout->getExtraInhabitantFlags();
+  }
+}
+
+void
+swift::swift_initEnumMetadataSinglePayload(EnumMetadata *self,
+                                           EnumLayoutFlags layoutFlags,
+                                           const TypeLayout *payloadLayout,
+                                           unsigned emptyCases) {
   size_t payloadSize = payloadLayout->size;
   unsigned payloadNumExtraInhabitants
     = payloadLayout->getNumExtraInhabitants();
@@ -47,6 +82,8 @@
                                       emptyCases - payloadNumExtraInhabitants,
                                       1 /*payload case*/);
   }
+
+  auto vwtable = getMutableVWTableForInit(self, layoutFlags);
   
   size_t align = payloadLayout->flags.getAlignment();
   vwtable->size = size;
@@ -128,8 +165,8 @@
 }
 
 void
-swift::swift_initEnumMetadataMultiPayload(ValueWitnessTable *vwtable,
-                                     EnumMetadata *enumType,
+swift::swift_initEnumMetadataMultiPayload(EnumMetadata *enumType,
+                                     EnumLayoutFlags layoutFlags,
                                      unsigned numPayloads,
                                      const TypeLayout * const *payloadLayouts) {
   // Accumulate the layout requirements of the payloads.
@@ -151,7 +188,9 @@
   unsigned totalSize = payloadSize + getNumTagBytes(payloadSize,
                                 enumType->Description->Enum.getNumEmptyCases(),
                                 numPayloads);
-  
+
+  auto vwtable = getMutableVWTableForInit(enumType, layoutFlags);
+
   // Set up the layout info in the vwtable.
   vwtable->size = totalSize;
   vwtable->flags = ValueWitnessFlags()
diff --git a/stdlib/public/runtime/ErrorObject.mm b/stdlib/public/runtime/ErrorObject.mm
index 843c182..948d4df 100644
--- a/stdlib/public/runtime/ErrorObject.mm
+++ b/stdlib/public/runtime/ErrorObject.mm
@@ -340,17 +340,17 @@
 }
 
 // internal func _getErrorDomainNSString<T : Error>
-//   (x: UnsafePointer<T>) -> AnyObject
+//   (_ x: UnsafePointer<T>) -> AnyObject
 #define getErrorDomainNSString \
-  MANGLE_SYM(s23_getErrorDomainNSStringyXlSPyxGs0B0RzlF)
+  MANGLE_SYM(s23_getErrorDomainNSStringyyXlSPyxGs0B0RzlF)
 SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
 NSString *getErrorDomainNSString(const OpaqueValue *error,
                                  const Metadata *T,
                                  const WitnessTable *Error);
 
-// internal func _getErrorCode<T : Error>(x: UnsafePointer<T>) -> Int
+// internal func _getErrorCode<T : Error>(_ x: UnsafePointer<T>) -> Int
 #define getErrorCode \
-  MANGLE_SYM(s13_getErrorCodeSiSPyxGs0B0RzlF)
+  MANGLE_SYM(s13_getErrorCodeySiSPyxGs0B0RzlF)
 SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
 NSInteger getErrorCode(const OpaqueValue *error,
                        const Metadata *T,
@@ -358,7 +358,7 @@
 
 // internal func _getErrorUserInfoNSDictionary<T : Error>(_ x: UnsafePointer<T>) -> AnyObject
 #define getErrorUserInfoNSDictionary \
-  MANGLE_SYM(s29_getErrorUserInfoNSDictionaryyXlSgSPyxGs0B0RzlF)
+  MANGLE_SYM(s29_getErrorUserInfoNSDictionaryyyXlSgSPyxGs0B0RzlF)
 SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
 NSDictionary *getErrorUserInfoNSDictionary(
                 const OpaqueValue *error,
@@ -380,7 +380,7 @@
   //   -> AnyObject?
   auto foundationGetDefaultUserInfo = SWIFT_LAZY_CONSTANT(
     reinterpret_cast<GetDefaultFn*> (dlsym(RTLD_DEFAULT,
-    MANGLE_AS_STRING(MANGLE_SYM(10Foundation24_getErrorDefaultUserInfoyXlSgxs0C0RzlF)))));
+    MANGLE_AS_STRING(MANGLE_SYM(10Foundation24_getErrorDefaultUserInfoyyXlSgxs0C0RzlF)))));
   if (!foundationGetDefaultUserInfo) {
     T->vw_destroy(error);
     return nullptr;
@@ -468,7 +468,7 @@
                   const WitnessTable *);
   auto bridgeNSErrorToError = SWIFT_LAZY_CONSTANT(
     reinterpret_cast<BridgeFn*>(dlsym(RTLD_DEFAULT,
-    MANGLE_AS_STRING(MANGLE_SYM(10Foundation21_bridgeNSErrorToErrorSbSo0C0C_SpyxG3outtAA021_ObjectiveCBridgeableE0RzlF)))));
+    MANGLE_AS_STRING(MANGLE_SYM(10Foundation21_bridgeNSErrorToError_3outSbSo0C0C_SpyxGtAA021_ObjectiveCBridgeableE0RzlF)))));
   // protocol _ObjectiveCBridgeableError
   auto TheObjectiveCBridgeableError = SWIFT_LAZY_CONSTANT(
     reinterpret_cast<const ProtocolDescriptor *>(dlsym(RTLD_DEFAULT,
diff --git a/stdlib/public/runtime/HeapObject.cpp b/stdlib/public/runtime/HeapObject.cpp
index 605a752..8ca75ac 100644
--- a/stdlib/public/runtime/HeapObject.cpp
+++ b/stdlib/public/runtime/HeapObject.cpp
@@ -46,6 +46,22 @@
 
 using namespace swift;
 
+// Check to make sure the runtime is being built with a compiler that
+// supports the Swift calling convention.
+//
+// If the Swift calling convention is not in use, functions such as 
+// swift_allocBox and swift_makeBoxUnique that rely on their return value 
+// being passed in a register to be compatible with Swift may miscompile on
+// some platforms and silently fail.
+#if !__has_attribute(swiftcall)
+#error "The runtime must be built with a compiler that supports swiftcall."
+#endif
+
+// Check that the user isn't manually disabling SWIFTCALL.
+#if defined(SWIFT_USE_SWIFTCALL) && !SWIFT_USE_SWIFTCALL
+#error "SWIFT_USE_SWIFTCALL=0 is not supported; swiftcall must always be used."
+#endif
+
 /// Returns true if the pointer passed to a native retain or release is valid.
 /// If false, the operation should immediately return.
 static inline bool isValidPointerForNativeRetain(const void *p) {
diff --git a/stdlib/public/runtime/Metadata.cpp b/stdlib/public/runtime/Metadata.cpp
index cff3ad2..1fb82aa 100644
--- a/stdlib/public/runtime/Metadata.cpp
+++ b/stdlib/public/runtime/Metadata.cpp
@@ -1278,25 +1278,57 @@
 /*** Structs ***************************************************************/
 /***************************************************************************/
 
+static ValueWitnessTable *getMutableVWTableForInit(StructMetadata *self,
+                                                   StructLayoutFlags flags,
+                                                   bool hasExtraInhabitants) {
+  auto oldTable = self->getValueWitnesses();
+
+  // If we can alter the existing table in-place, do so.
+  if (isValueWitnessTableMutable(flags))
+    return const_cast<ValueWitnessTable*>(oldTable);
+
+  // Otherwise, allocate permanent memory for it and copy the existing table.
+  ValueWitnessTable *newTable;
+  if (hasExtraInhabitants) {
+    void *memory = allocateMetadata(sizeof(ExtraInhabitantsValueWitnessTable),
+                                    alignof(ExtraInhabitantsValueWitnessTable));
+    newTable = new (memory) ExtraInhabitantsValueWitnessTable(
+              *static_cast<const ExtraInhabitantsValueWitnessTable*>(oldTable));
+  } else {
+    void *memory = allocateMetadata(sizeof(ValueWitnessTable),
+                                    alignof(ValueWitnessTable));
+    newTable = new (memory) ValueWitnessTable(*oldTable);
+  }
+  self->setValueWitnesses(newTable);
+
+  return newTable;
+}
+
 /// Initialize the value witness table and struct field offset vector for a
 /// struct, using the "Universal" layout strategy.
-void swift::swift_initStructMetadata_UniversalStrategy(size_t numFields,
+void swift::swift_initStructMetadata(StructMetadata *structType,
+                                     StructLayoutFlags layoutFlags,
+                                     size_t numFields,
                                      const TypeLayout * const *fieldTypes,
-                                     size_t *fieldOffsets,
-                                     ValueWitnessTable *vwtable) {
+                                     size_t *fieldOffsets) {
   auto layout = BasicLayout::initialForValueType();
   performBasicLayout(layout, fieldTypes, numFields,
     [&](size_t i, const TypeLayout *fieldType, size_t offset) {
       assignUnlessEqual(fieldOffsets[i], offset);
     });
 
+  bool hasExtraInhabitants = fieldTypes[0]->flags.hasExtraInhabitants();
+
+  auto vwtable =
+    getMutableVWTableForInit(structType, layoutFlags, hasExtraInhabitants);
+
   vwtable->size = layout.size;
   vwtable->flags = layout.flags;
   vwtable->stride = layout.stride;
   
   // We have extra inhabitants if the first element does.
   // FIXME: generalize this.
-  if (fieldTypes[0]->flags.hasExtraInhabitants()) {
+  if (hasExtraInhabitants) {
     vwtable->flags = vwtable->flags.withExtraInhabitants(true);
     auto xiVWT = cast<ExtraInhabitantsValueWitnessTable>(vwtable);
     xiVWT->extraInhabitantFlags = fieldTypes[0]->getExtraInhabitantFlags();
@@ -1415,7 +1447,7 @@
     if (genericParams.Flags.hasVTable()) {
       auto *vtable = description->getVTableDescriptor();
       for (unsigned i = 0, e = vtable->VTableSize; i < e; ++i) {
-        classWords[vtable->VTableOffset + i] = vtable->getMethod(i);
+        classWords[vtable->VTableOffset + i] = description->getMethod(i);
       }
     }
   }
@@ -2464,14 +2496,15 @@
 const ForeignTypeMetadata *
 swift::swift_getForeignTypeMetadata(ForeignTypeMetadata *nonUnique) {
   // Fast path: check the invasive cache.
-  if (auto unique = nonUnique->getCachedUniqueMetadata()) {
-    return unique;
+  auto cache = nonUnique->getCacheValue();
+  if (cache.isInitialized()) {
+    return cache.getCachedUniqueMetadata();
   }
 
   // Okay, check the global map.
   auto &foreignTypes = ForeignTypes.get();
   GlobalString key(nonUnique->getName());
-  bool hasInit = nonUnique->hasInitializationFunction();
+  bool hasInit = cache.hasInitializationFunction();
 
   const ForeignTypeMetadata *uniqueMetadata;
   bool inserted;
@@ -2900,3 +2933,6 @@
                                                  std::memory_order_relaxed);
 }
 
+void *swift::allocateMetadata(size_t size, size_t alignment) {
+  return MetadataAllocator().Allocate(size, alignment);
+}
diff --git a/stdlib/public/runtime/MetadataLookup.cpp b/stdlib/public/runtime/MetadataLookup.cpp
index 06ec92d..f75c8ba 100644
--- a/stdlib/public/runtime/MetadataLookup.cpp
+++ b/stdlib/public/runtime/MetadataLookup.cpp
@@ -262,7 +262,7 @@
 /// internal func _getTypeByName(_ name: UnsafePointer<UInt8>,
 ///                              _ nameLength: UInt)  -> Any.Type?
 #define _getTypeByName \
-  MANGLE_SYM(s14_getTypeByNameypXpSgSPys5UInt8VG_SutF)
+  MANGLE_SYM(s14_getTypeByNameyypXpSgSPys5UInt8VG_SutF)
 SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
 const Metadata *
 _getTypeByName(const char *typeName, size_t typeNameLength) {
diff --git a/stdlib/public/runtime/Private.h b/stdlib/public/runtime/Private.h
index 0e350e7..fd48475 100644
--- a/stdlib/public/runtime/Private.h
+++ b/stdlib/public/runtime/Private.h
@@ -193,6 +193,8 @@
 #endif
   }
 
+  void *allocateMetadata(size_t size, size_t align);
+
 } // end namespace swift
 
 #endif /* SWIFT_RUNTIME_PRIVATE_H */
diff --git a/stdlib/public/runtime/ProtocolConformance.cpp b/stdlib/public/runtime/ProtocolConformance.cpp
index dfd4710..af49111 100644
--- a/stdlib/public/runtime/ProtocolConformance.cpp
+++ b/stdlib/public/runtime/ProtocolConformance.cpp
@@ -16,8 +16,10 @@
 
 #include "swift/Basic/LLVM.h"
 #include "swift/Basic/Lazy.h"
+#include "swift/Demangling/Demangle.h"
 #include "swift/Runtime/Casting.h"
 #include "swift/Runtime/Concurrent.h"
+#include "swift/Runtime/HeapObject.h"
 #include "swift/Runtime/Metadata.h"
 #include "swift/Runtime/Mutex.h"
 #include "swift/Runtime/Unreachable.h"
@@ -142,11 +144,28 @@
   case ProtocolConformanceReferenceKind::WitnessTableAccessor:
     return getWitnessTableAccessor()(type, nullptr, 0);
 
-  case ProtocolConformanceReferenceKind::ConditionalWitnessTableAccessor:
+  case ProtocolConformanceReferenceKind::ConditionalWitnessTableAccessor: {
     // FIXME: this needs to query the conditional requirements to form the
     // array of witness tables to pass along to the accessor.
+
+    // Pretty-print the type name.
+    auto typeNamePair = swift_getTypeName(type, /*qualified=*/true);
+    std::string typeName(typeNamePair.data,
+                         typeNamePair.data + typeNamePair.length);
+
+    // Demangle the protocol name.
+    DemangleOptions options;
+    options.DisplayEntityTypes = false;
+    std::string demangledProtocolName =
+      demangleSymbolAsString(StringRef(getProtocol()->Name), options);
+
+    warning(/*flag=*/0,
+            "warning: Swift runtime does not yet support dynamically "
+            "querying conditional conformance ('%s': '%s')\n",
+            typeName.c_str(), demangledProtocolName.c_str());
     return nullptr;
   }
+  }
 
   swift_runtime_unreachable(
       "Unhandled ProtocolConformanceReferenceKind in switch.");
diff --git a/stdlib/public/runtime/SwiftObject.mm b/stdlib/public/runtime/SwiftObject.mm
index 59085b6..9b1c7d1 100644
--- a/stdlib/public/runtime/SwiftObject.mm
+++ b/stdlib/public/runtime/SwiftObject.mm
@@ -152,7 +152,7 @@
   typedef SWIFT_CC(swift) NSString *ConversionFn(void *sx, void *sy, void *sz);
   auto convertStringToNSString = SWIFT_LAZY_CONSTANT(
     reinterpret_cast<ConversionFn*>(dlsym(RTLD_DEFAULT,
-    MANGLE_AS_STRING(MANGLE_SYM(10Foundation24_convertStringToNSStringSo0E0CSSF)))));
+    MANGLE_AS_STRING(MANGLE_SYM(10Foundation24_convertStringToNSStringySo0E0CSSF)))));
 
   // If Foundation hasn't loaded yet, fall back to returning the static string
   // "SwiftObject". The likelihood of someone invoking -description without
diff --git a/test/APINotes/versioned.swift b/test/APINotes/versioned.swift
index 69e542f..6a789c8 100644
--- a/test/APINotes/versioned.swift
+++ b/test/APINotes/versioned.swift
@@ -251,14 +251,14 @@
 #if !swift(>=4)
 
 func useSwift3Name(_: ImportantCStruct) {}
-// CHECK-SILGEN-3: sil hidden @_T09versioned13useSwift3NameySC20VeryImportantCStructVF
+// CHECK-SILGEN-3: sil hidden @_T09versioned13useSwift3NameyySC20VeryImportantCStructVF
 
 func useNewlyNested(_: InnerInSwift4) {}
-// CHECK-SILGEN-3: sil hidden @_T09versioned14useNewlyNestedySC5OuterV5InnerVF
+// CHECK-SILGEN-3: sil hidden @_T09versioned14useNewlyNestedyySC5OuterV5InnerVF
 #endif
 
 func useSwift4Name(_: VeryImportantCStruct) {}
-// CHECK-SILGEN: sil hidden @_T09versioned13useSwift4NameySC20VeryImportantCStructVF
+// CHECK-SILGEN: sil hidden @_T09versioned13useSwift4NameyySC20VeryImportantCStructVF
 
 
 
diff --git a/test/ClangImporter/Inputs/custom-modules/ObjCSubscripts.h b/test/ClangImporter/Inputs/custom-modules/ObjCSubscripts.h
index 7b62007..f73cda8 100644
--- a/test/ClangImporter/Inputs/custom-modules/ObjCSubscripts.h
+++ b/test/ClangImporter/Inputs/custom-modules/ObjCSubscripts.h
@@ -29,3 +29,34 @@
 - (NSString *)objectForKeyedSubscript:(NSString *)subscript;
 - (void)setObject:(NSString *)object forKeyedSubscript:(NSString *)key;
 @end
+
+
+// rdar://problem/36033356 failed specifically when the base class was never
+// subscripted, so please don't mention this class in the .swift file.
+@interface KeySubscriptBase
+- (id)objectForKeyedSubscript:(NSString *)subscript;
+- (void)setObject:(id)object forKeyedSubscript:(NSString *)key;
+@end
+
+@interface KeySubscriptOverrideGetter : KeySubscriptBase
+- (id)objectForKeyedSubscript:(NSString *)subscript;
+@end
+
+@interface KeySubscriptOverrideSetter : KeySubscriptBase
+- (void)setObject:(id)object forKeyedSubscript:(NSString *)key;
+@end
+
+// rdar://problem/36033356 failed specifically when the base class was never
+// subscripted, so please don't mention this class in the .swift file.
+@interface KeySubscriptReversedBase
+- (void)setObject:(id)object forKeyedSubscript:(NSString *)key;
+- (id)objectForKeyedSubscript:(NSString *)subscript;
+@end
+
+@interface KeySubscriptReversedOverrideGetter : KeySubscriptReversedBase
+- (id)objectForKeyedSubscript:(NSString *)subscript;
+@end
+
+@interface KeySubscriptReversedOverrideSetter : KeySubscriptReversedBase
+- (void)setObject:(id)object forKeyedSubscript:(NSString *)key;
+@end
diff --git a/test/ClangImporter/attr-swift_private.swift b/test/ClangImporter/attr-swift_private.swift
index f2e70f1..6028aed 100644
--- a/test/ClangImporter/attr-swift_private.swift
+++ b/test/ClangImporter/attr-swift_private.swift
@@ -95,14 +95,14 @@
 // CHECK: %objc_class** @"OBJC_CLASS_REF_$_PrivFooSub"
 // CHECK: }
 
-// CHECK-LABEL: define linkonce_odr hidden {{.+}} @_T0So3BarCSQyABGs5Int32V2___tcfcTO
-// CHECK: @"\01L_selector(init:)"
-// CHECK-LABEL: define linkonce_odr hidden {{.+}} @_T0So3BarCSQyABGs5Int32V9__twoArgs_AE5othertcfcTO
-// CHECK: @"\01L_selector(initWithTwoArgs:other:)"
-// CHECK-LABEL: define linkonce_odr hidden {{.+}} @_T0So3BarCSQyABGs5Int32V8__oneArg_tcfcTO
-// CHECK: @"\01L_selector(initWithOneArg:)"
-// CHECK-LABEL: define linkonce_odr hidden {{.+}} @_T0So3BarCSQyABGyt8__noArgs_tcfcTO
+// CHECK-LABEL: define linkonce_odr hidden {{.+}} @_T0So3BarC8__noArgsSQyABGyt_tcfcTO
 // CHECK: @"\01L_selector(initWithNoArgs)"
+// CHECK-LABEL: define linkonce_odr hidden {{.+}} @_T0So3BarC8__oneArgSQyABGs5Int32V_tcfcTO
+// CHECK: @"\01L_selector(initWithOneArg:)"
+// CHECK-LABEL: define linkonce_odr hidden {{.+}} @_T0So3BarC9__twoArgs5otherSQyABGs5Int32V_AGtcfcTO
+// CHECK: @"\01L_selector(initWithTwoArgs:other:)"
+// CHECK-LABEL: define linkonce_odr hidden {{.+}} @_T0So3BarC2__SQyABGs5Int32V_tcfcTO
+// CHECK: @"\01L_selector(init:)"
 
 _ = __PrivAnonymousA
 _ = __E0PrivA
diff --git a/test/ClangImporter/ctypes_ir.swift b/test/ClangImporter/ctypes_ir.swift
index edcb3a8..76e4631 100644
--- a/test/ClangImporter/ctypes_ir.swift
+++ b/test/ClangImporter/ctypes_ir.swift
@@ -27,7 +27,7 @@
 }
 
 // Make sure flexible array struct member isn't represented in IR function signature as i0 (or at all). rdar://problem/18510461
-// CHECK-LABEL: define hidden swiftcc void @_T09ctypes_ir27testStructWithFlexibleArrayySC0defG0VF(i32)
+// CHECK-LABEL: define hidden swiftcc void @_T09ctypes_ir27testStructWithFlexibleArrayyySC0defG0VF(i32)
 
 typealias EightUp = (Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8)
 
diff --git a/test/ClangImporter/objc_ir.swift b/test/ClangImporter/objc_ir.swift
index 33bf9fd..7b01e64 100644
--- a/test/ClangImporter/objc_ir.swift
+++ b/test/ClangImporter/objc_ir.swift
@@ -18,7 +18,7 @@
 // CHECK: @"\01L_selector_data(method:separateExtMethod:)" = private global [26 x i8] c"method:separateExtMethod:\00", section "__TEXT,__objc_methname,cstring_literals"
 
 // Instance method invocation
-// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir15instanceMethodsySo1BCF(%TSo1BC*
+// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir15instanceMethodsyySo1BCF(%TSo1BC*
 func instanceMethods(_ b: B) {
   // CHECK: load i8*, i8** @"\01L_selector(method:withFloat:)"
   // CHECK: call i32 bitcast (void ()* @objc_msgSend to i32
@@ -28,7 +28,7 @@
   i = i + b.method(1, with: 2.5 as Double)
 }
 
-// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir16extensionMethodsySo1BC1b_tF
+// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir16extensionMethods1bySo1BC_tF
 func extensionMethods(b b: B) {
   // CHECK:      load i8*, i8** @"\01L_selector(method:separateExtMethod:)", align 8
   // CHECK:      [[T0:%.*]] = call i8* bitcast (void ()* @objc_msgSend to i8*
@@ -38,18 +38,18 @@
   b.method(1, separateExtMethod:1.5)
 }
 
-// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir19initCallToAllocInitys5Int32V1i_tF
+// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir19initCallToAllocInit1iys5Int32V_tF
 func initCallToAllocInit(i i: CInt) {
-  // CHECK: call {{.*}} @_T0So1BCSQyABGs5Int32V3int_tcfC
+  // CHECK: call {{.*}} @_T0So1BC3intSQyABGs5Int32V_tcfC
  
   B(int: i)
 }
 
-// CHECK-LABEL: linkonce_odr hidden {{.*}} @_T0So1BCSQyABGs5Int32V3int_tcfC
+// CHECK-LABEL: linkonce_odr hidden {{.*}} @_T0So1BC3intSQyABGs5Int32V_tcfC
 // CHECK: call [[OPAQUE:%.*]]* @objc_allocWithZone
 
 // Indexed subscripting
-// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir19indexedSubscriptingySo1BC1b_Si3idxSo1AC1atF
+// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir19indexedSubscripting1b3idx1aySo1BC_SiSo1ACtF
 func indexedSubscripting(b b: B, idx: Int, a: A) {
   // CHECK: load i8*, i8** @"\01L_selector(setObject:atIndexedSubscript:)", align 8
   b[idx] = a
@@ -58,7 +58,7 @@
   var a2 = b[idx] as! A
 }
 
-// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir17keyedSubscriptingySo1BC1b_So1AC3idxAG1atF
+// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir17keyedSubscripting1b3idx1aySo1BC_So1ACAItF
 func keyedSubscripting(b b: B, idx: A, a: A) {
   // CHECK: load i8*, i8** @"\01L_selector(setObject:forKeyedSubscript:)"
   b[a] = a
@@ -66,7 +66,7 @@
   var a2 = b[a] as! A
 }
 
-// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir14propertyAccessySo1BC1b_tF
+// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir14propertyAccess1bySo1BC_tF
 func propertyAccess(b b: B) {
    // CHECK: load i8*, i8** @"\01L_selector(counter)"
    // CHECK: load i8*, i8** @"\01L_selector(setCounter:)"
@@ -78,7 +78,7 @@
    B.sharedCounter = B.sharedCounter + 1
 }
 
-// CHECK-LABEL: define hidden swiftcc %TSo1BC* @_T07objc_ir8downcastSo1BCSo1AC1a_tF(
+// CHECK-LABEL: define hidden swiftcc %TSo1BC* @_T07objc_ir8downcast1aSo1BCSo1AC_tF(
 func downcast(a a: A) -> B {
   // CHECK: [[CLASS:%.*]] = load %objc_class*, %objc_class** @"OBJC_CLASS_REF_$_B"
   // CHECK: [[T0:%.*]] = call %objc_class* @swift_rt_swift_getInitializedObjCClass(%objc_class* [[CLASS]])
@@ -87,12 +87,12 @@
   return a as! B
 }
 
-// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir19almostSubscriptableySo06AlmostD0C3as1_So1AC1atF
+// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir19almostSubscriptable3as11aySo06AlmostD0C_So1ACtF
 func almostSubscriptable(as1 as1: AlmostSubscriptable, a: A) {
   as1.objectForKeyedSubscript(a)
 }
 
-// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir13protocolTypesySo7NSMinceC1a_So9NSRuncing_p1btF(%TSo7NSMinceC*, %objc_object*) {{.*}} {
+// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir13protocolTypes1a1bySo7NSMinceC_So9NSRuncing_ptF(%TSo7NSMinceC*, %objc_object*) {{.*}} {
 func protocolTypes(a a: NSMince, b: NSRuncing) {
   // - (void)eatWith:(id <NSRuncing>)runcer;
   a.eat(with: b)
@@ -100,7 +100,7 @@
   // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OPAQUE:%.*]]*, i8*, i8*)*)([[OPAQUE:%.*]]* {{%.*}}, i8* [[SEL]], i8* {{%.*}})
 }
 
-// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir6getsetySo8FooProto_p1p_tF(%objc_object*) {{.*}} {
+// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir6getset1pySo8FooProto_p_tF(%objc_object*) {{.*}} {
 func getset(p p: FooProto) {
   // CHECK: load i8*, i8** @"\01L_selector(bar)"
   // CHECK: load i8*, i8** @"\01L_selector(setBar:)"
@@ -108,7 +108,7 @@
   p.bar = prop
 }
 
-// CHECK-LABEL: define hidden swiftcc %swift.type* @_T07objc_ir16protocolMetatypeSo8FooProto_pXpSoAC_p1p_tF(%objc_object*) {{.*}} {
+// CHECK-LABEL: define hidden swiftcc %swift.type* @_T07objc_ir16protocolMetatype1pSo8FooProto_pXpSoAD_p_tF(%objc_object*) {{.*}} {
 func protocolMetatype(p: FooProto) -> FooProto.Type {
   // CHECK: = call %swift.type* @swift_getObjectType(%objc_object* %0)
   // CHECK-NOT: {{retain|release}}
@@ -125,7 +125,7 @@
   @objc var bar: Int32 = 0
 }
 
-// CHECK-LABEL: define hidden swiftcc %swift.type* @_T07objc_ir27protocolCompositionMetatypeSo12AnotherProto_So03FooG0pXpAA4ImplC1p_tF(%T7objc_ir4ImplC*) {{.*}} {
+// CHECK-LABEL: define hidden swiftcc %swift.type* @_T07objc_ir27protocolCompositionMetatype1pSo12AnotherProto_So03FooG0pXpAA4ImplC_tF(%T7objc_ir4ImplC*) {{.*}} {
 func protocolCompositionMetatype(p: Impl) -> (FooProto & AnotherProto).Type {
   // CHECK: = getelementptr inbounds %T7objc_ir4ImplC, %T7objc_ir4ImplC* %0, i32 0, i32 0, i32 0
   // CHECK-NOT: {{retain|release}}
@@ -138,7 +138,7 @@
   return type
 } // CHECK: }
 
-// CHECK-LABEL: define hidden swiftcc %swift.type* @_T07objc_ir28protocolCompositionMetatype2So12AnotherProto_So03FooG0pXpAA4ImplC1p_tF(%T7objc_ir4ImplC*) {{.*}} {
+// CHECK-LABEL: define hidden swiftcc %swift.type* @_T07objc_ir28protocolCompositionMetatype21pSo12AnotherProto_So03FooG0pXpAA4ImplC_tF(%T7objc_ir4ImplC*) {{.*}} {
 func protocolCompositionMetatype2(p: Impl) -> (FooProto & AnotherProto).Type {
   // CHECK: = getelementptr inbounds %T7objc_ir4ImplC, %T7objc_ir4ImplC* %0, i32 0, i32 0, i32 0
   // CHECK-NOT: {{retain|release}}
@@ -151,7 +151,7 @@
   return type
 } // CHECK: }
 
-// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir17pointerPropertiesySo14PointerWrapperCF(%TSo14PointerWrapperC*) {{.*}} {
+// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir17pointerPropertiesyySo14PointerWrapperCF(%TSo14PointerWrapperC*) {{.*}} {
 func pointerProperties(_ obj: PointerWrapper) {
   // CHECK: load i8*, i8** @"\01L_selector(setVoidPtr:)"
   // CHECK: load i8*, i8** @"\01L_selector(setIntPtr:)"
@@ -161,7 +161,7 @@
   obj.idPtr = nil as AutoreleasingUnsafeMutablePointer?
 }
 
-// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir16strangeSelectorsySo13SwiftNameTestCF(%TSo13SwiftNameTestC*) {{.*}} {
+// CHECK-LABEL: define hidden swiftcc void @_T07objc_ir16strangeSelectorsyySo13SwiftNameTestCF(%TSo13SwiftNameTestC*) {{.*}} {
 func strangeSelectors(_ obj: SwiftNameTest) {
   // CHECK: load i8*, i8** @"\01L_selector(:b:)"
   obj.empty(a: 0, b: 0)
@@ -169,9 +169,9 @@
 
 // CHECK-LABEL: define hidden swiftcc void @_T07objc_ir20customFactoryMethodsyyF() {{.*}} {
 func customFactoryMethods() {
-  // CHECK: call swiftcc %TSo13SwiftNameTestC* @_T0So13SwiftNameTestCAByt10dummyParam_tcfCTO
-  // CHECK: call swiftcc %TSo13SwiftNameTestC* @_T0So13SwiftNameTestCABypSg2cc_tcfCTO
-  // CHECK: call swiftcc %TSo13SwiftNameTestC* @_T0So13SwiftNameTestCABs5Int32V5empty_tcfCTO
+  // CHECK: call swiftcc %TSo13SwiftNameTestC* @_T0So13SwiftNameTestC10dummyParamAByt_tcfCTO
+  // CHECK: call swiftcc %TSo13SwiftNameTestC* @_T0So13SwiftNameTestC2ccABypSg_tcfCTO
+  // CHECK: call swiftcc %TSo13SwiftNameTestC* @_T0So13SwiftNameTestC5emptyABs5Int32V_tcfCTO
   _ = SwiftNameTest(dummyParam: ())
   _ = SwiftNameTest(cc: nil)
   _ = SwiftNameTest(empty: 0)
@@ -186,13 +186,13 @@
   _ = SwiftNameTest.empty(1, 2)
 
   do {
-    // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorCAByt5error_tKcfCTO
-    // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorCABypSg2aa_yt5errortKcfCTO
-    // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorCABypSg2aa_yt5erroryyc5blocktKcfCTO
-    // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorCAByt5error_yyc5blocktKcfCTO
-    // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorCABypSg2aa_tKcfCTO
-    // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorCABypSg2aa_yyc5blocktKcfCTO
-    // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorCAByyc5block_tKcfCTO
+    // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorC5errorAByt_tKcfCTO
+    // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorC2aa5errorABypSg_yttKcfCTO
+    // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorC2aa5error5blockABypSg_ytyyctKcfCTO
+    // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorC5error5blockAByt_yyctKcfCTO
+    // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorC2aaABypSg_tKcfCTO
+    // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorC2aa5blockABypSg_yyctKcfCTO
+    // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorC5blockAByyc_tKcfCTO
     _ = try SwiftNameTestError(error: ())
     _ = try SwiftNameTestError(aa: nil, error: ())
     _ = try SwiftNameTestError(aa: nil, error: (), block: {})
@@ -214,46 +214,46 @@
   }
 }
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo13SwiftNameTestC* @_T0So13SwiftNameTestCAByt10dummyParam_tcfCTO
+// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo13SwiftNameTestC* @_T0So13SwiftNameTestC10dummyParamAByt_tcfCTO
 // CHECK: load i8*, i8** @"\01L_selector(b)"
 // CHECK: }
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo13SwiftNameTestC* @_T0So13SwiftNameTestCABypSg2cc_tcfCTO
+// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo13SwiftNameTestC* @_T0So13SwiftNameTestC2ccABypSg_tcfCTO
 // CHECK: load i8*, i8** @"\01L_selector(c:)"
 // CHECK: }
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorCAByt5error_tKcfCTO
+// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorC5errorAByt_tKcfCTO
 // CHECK: load i8*, i8** @"\01L_selector(err1:)"
 // CHECK: }
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorCABypSg2aa_yt5errortKcfCTO
+// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorC2aa5errorABypSg_yttKcfCTO
 // CHECK: load i8*, i8** @"\01L_selector(err2:error:)"
 // CHECK: }
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorCABypSg2aa_yt5erroryyc5blocktKcfCTO
+// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorC2aa5error5blockABypSg_ytyyctKcfCTO
 // CHECK: load i8*, i8** @"\01L_selector(err3:error:callback:)"
 // CHECK: }
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorCAByt5error_yyc5blocktKcfCTO
+// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorC5error5blockAByt_yyctKcfCTO
 // CHECK: load i8*, i8** @"\01L_selector(err4:callback:)"
 // CHECK: }
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorCABypSg2aa_tKcfCTO
+// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorC2aaABypSg_tKcfCTO
 // CHECK: load i8*, i8** @"\01L_selector(err5:error:)"
 // CHECK: }
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorCABypSg2aa_yyc5blocktKcfCTO
+// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorC2aa5blockABypSg_yyctKcfCTO
 // CHECK: load i8*, i8** @"\01L_selector(err6:error:callback:)"
 // CHECK: }
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorCAByyc5block_tKcfCTO
+// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @_T0So18SwiftNameTestErrorC5blockAByyc_tKcfCTO
 // CHECK: load i8*, i8** @"\01L_selector(err7:callback:)"
 // CHECK: }
 
 // CHECK-LABEL: define hidden swiftcc void @_T07objc_ir29customFactoryMethodsInheritedyyF() {{.*}} {
 func customFactoryMethodsInherited() {
-  // CHECK: call swiftcc %TSo16SwiftNameTestSubC* @_T0So16SwiftNameTestSubCAByt10dummyParam_tcfCTO
-  // CHECK: call swiftcc %TSo16SwiftNameTestSubC* @_T0So16SwiftNameTestSubCABypSg2cc_tcfCTO
+  // CHECK: call swiftcc %TSo16SwiftNameTestSubC* @_T0So16SwiftNameTestSubC10dummyParamAByt_tcfCTO
+  // CHECK: call swiftcc %TSo16SwiftNameTestSubC* @_T0So16SwiftNameTestSubC2ccABypSg_tcfCTO
   _ = SwiftNameTestSub(dummyParam: ())
   _ = SwiftNameTestSub(cc: nil)
 
@@ -265,13 +265,13 @@
   _ = SwiftNameTestSub.xx(nil, bb: nil)
 
   do {
-    // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubCAByt5error_tKcfCTO
-    // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubCABypSg2aa_yt5errortKcfCTO
-    // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubCABypSg2aa_yt5erroryyc5blocktKcfCTO
-    // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubCAByt5error_yyc5blocktKcfCTO
-    // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubCABypSg2aa_tKcfCTO
-    // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubCABypSg2aa_yyc5blocktKcfCTO
-    // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubCAByyc5block_tKcfCTO
+    // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubC5errorAByt_tKcfCTO
+    // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubC2aa5errorABypSg_yttKcfCTO
+    // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubC2aa5error5blockABypSg_ytyyctKcfCTO
+    // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubC5error5blockAByt_yyctKcfCTO
+    // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubC2aaABypSg_tKcfCTO
+    // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubC2aa5blockABypSg_yyctKcfCTO
+    // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubC5blockAByyc_tKcfCTO
     _ = try SwiftNameTestErrorSub(error: ())
     _ = try SwiftNameTestErrorSub(aa: nil, error: ())
     _ = try SwiftNameTestErrorSub(aa: nil, error: (), block: {})
@@ -293,43 +293,43 @@
   }
 }
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo16SwiftNameTestSubC* @_T0So16SwiftNameTestSubCAByt10dummyParam_tcfCTO
+// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo16SwiftNameTestSubC* @_T0So16SwiftNameTestSubC10dummyParamAByt_tcfCTO
 // CHECK: load i8*, i8** @"\01L_selector(b)"
 // CHECK: }
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo16SwiftNameTestSubC* @_T0So16SwiftNameTestSubCABypSg2cc_tcfCTO
+// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo16SwiftNameTestSubC* @_T0So16SwiftNameTestSubC2ccABypSg_tcfCTO
 // CHECK: load i8*, i8** @"\01L_selector(c:)"
 // CHECK: }
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubCAByt5error_tKcfCTO
+// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubC5errorAByt_tKcfCTO
 // CHECK: load i8*, i8** @"\01L_selector(err1:)"
 // CHECK: }
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubCABypSg2aa_yt5errortKcfCTO
+// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubC2aa5errorABypSg_yttKcfCTO
 // CHECK: load i8*, i8** @"\01L_selector(err2:error:)"
 // CHECK: }
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubCABypSg2aa_yt5erroryyc5blocktKcfCTO
+// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubC2aa5error5blockABypSg_ytyyctKcfCTO
 // CHECK: load i8*, i8** @"\01L_selector(err3:error:callback:)"
 // CHECK: }
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubCAByt5error_yyc5blocktKcfCTO
+// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubC5error5blockAByt_yyctKcfCTO
 // CHECK: load i8*, i8** @"\01L_selector(err4:callback:)"
 // CHECK: }
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubCABypSg2aa_tKcfCTO
+// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubC2aaABypSg_tKcfCTO
 // CHECK: load i8*, i8** @"\01L_selector(err5:error:)"
 // CHECK: }
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubCABypSg2aa_yyc5blocktKcfCTO
+// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubC2aa5blockABypSg_yyctKcfCTO
 // CHECK: load i8*, i8** @"\01L_selector(err6:error:callback:)"
 // CHECK: }
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubCAByyc5block_tKcfCTO
+// CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @_T0So21SwiftNameTestErrorSubC5blockAByyc_tKcfCTO
 // CHECK: load i8*, i8** @"\01L_selector(err7:callback:)"
 // CHECK: }
 
-// CHECK: linkonce_odr hidden {{.*}} @_T0So1BCSQyABGs5Int32V3int_tcfcTO
+// CHECK: linkonce_odr hidden {{.*}} @_T0So1BC3intSQyABGs5Int32V_tcfcTO
 // CHECK: load i8*, i8** @"\01L_selector(initWithInt:)"
 // CHECK: call [[OPAQUE:%.*]]* bitcast (void ()* @objc_msgSend
 
diff --git a/test/ClangImporter/objc_subscript.swift b/test/ClangImporter/objc_subscript.swift
index 7a1eeb2..e7d73a9 100644
--- a/test/ClangImporter/objc_subscript.swift
+++ b/test/ClangImporter/objc_subscript.swift
@@ -48,3 +48,24 @@
     set { }
   }
 }
+
+func testOverridesWithoutBase(
+  o1: KeySubscriptOverrideGetter,
+  o2: KeySubscriptOverrideSetter,
+  o3: KeySubscriptReversedOverrideGetter,
+  o4: KeySubscriptReversedOverrideSetter
+) {
+  // rdar://problem/36033356 failed specifically when the base class was never
+  // subscripted, so please don't mention the base classes here.
+  _ = o1["abc"]
+  o1["abc"] = "xyz"
+
+  _ = o2["abc"]
+  o2["abc"] = "xyz"
+
+  _ = o3["abc"]
+  o3["abc"] = "xyz"
+
+  _ = o4["abc"]
+  o4["abc"] = "xyz"
+}
diff --git a/test/ClangImporter/optional.swift b/test/ClangImporter/optional.swift
index 3283877..0004960 100644
--- a/test/ClangImporter/optional.swift
+++ b/test/ClangImporter/optional.swift
@@ -40,7 +40,7 @@
 // CHECK-NEXT: return [[T0]]
 
   @objc func bar(x x : String?) {}
-// CHECK-LABEL:    sil hidden [thunk] @_T08optional1AC3barySSSg1x_tFTo : $@convention(objc_method) (Optional<NSString>, A) -> ()
+// CHECK-LABEL:    sil hidden [thunk] @_T08optional1AC3bar1xySSSg_tFTo : $@convention(objc_method) (Optional<NSString>, A) -> ()
 // CHECK:    bb0([[ARG:%.*]] : $Optional<NSString>, [[SELF:%.*]] : $A):
 // CHECK:      [[ARG_COPY:%.*]] = copy_value [[ARG]]
 // CHECK:      [[SELF_COPY:%.*]] = copy_value [[SELF]]
@@ -48,7 +48,7 @@
 //
 //   Something branch: project value, translate, inject into result.
 // CHECK:    [[SOME_BB]]([[NSSTR:%.*]] : $NSString):
-// CHECK:      [[T0:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+// CHECK:      [[T0:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
 //   Make a temporary initialized string that we're going to clobber as part of the conversion process (?).
 // CHECK-NEXT: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR]] : $NSString
 // CHECK-NEXT: [[STRING_META:%.*]] = metatype $@thin String.Type
@@ -63,7 +63,7 @@
 //   Continuation.
 // CHECK:      bb3([[T0:%.*]] : $Optional<String>):
 // CHECK:      [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
-// CHECK:      [[T1:%.*]] = function_ref @_T08optional1AC3barySSSg1x_tF
+// CHECK:      [[T1:%.*]] = function_ref @_T08optional1AC3bar1xySSSg_tF
 // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[BORROWED_SELF_COPY]])
 // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
 // CHECK-NEXT: destroy_value [[SELF_COPY]]
diff --git a/test/ClangImporter/pch-bridging-header-deps.swift b/test/ClangImporter/pch-bridging-header-deps.swift
index 2de7168..1884620 100644
--- a/test/ClangImporter/pch-bridging-header-deps.swift
+++ b/test/ClangImporter/pch-bridging-header-deps.swift
@@ -5,12 +5,12 @@
 // mention the .h the PCH was generated from, and any .h files included in it.
 //
 // RUN: %target-swift-frontend -emit-pch -o %t.pch %S/Inputs/chained-unit-test-bridging-header-to-pch.h
-// RUN: %target-swift-frontend -module-name test -c -emit-dependencies-path %t.d -emit-reference-dependencies-path %t.swiftdeps -primary-file %s %s -import-objc-header %t.pch
+// RUN: %target-swift-frontend -module-name test -c -emit-dependencies-path %t.d -emit-reference-dependencies-path %t.swiftdeps -primary-file %s -import-objc-header %t.pch
 // RUN: %FileCheck --check-prefix CHECK-DEPS %s < %t.d
 // RUN: %FileCheck --check-prefix CHECK-SWIFTDEPS %s < %t.swiftdeps
 // RUN: %FileCheck --check-prefix CHECK-SWIFTDEPS2 %s < %t.swiftdeps
 
-// RUN: %target-swift-frontend -module-name test -c -emit-dependencies-path %t.persistent.d -emit-reference-dependencies-path %t.persistent.swiftdeps -primary-file %s %s -import-objc-header %S/Inputs/chained-unit-test-bridging-header-to-pch.h -pch-output-dir %t/pch
+// RUN: %target-swift-frontend -module-name test -c -emit-dependencies-path %t.persistent.d -emit-reference-dependencies-path %t.persistent.swiftdeps -primary-file %s -import-objc-header %S/Inputs/chained-unit-test-bridging-header-to-pch.h -pch-output-dir %t/pch
 // RUN: %FileCheck --check-prefix CHECK-DEPS %s < %t.persistent.d
 // RUN: %FileCheck --check-prefix CHECK-SWIFTDEPS %s < %t.persistent.swiftdeps
 // RUN: %FileCheck --check-prefix CHECK-SWIFTDEPS2 %s < %t.persistent.swiftdeps
diff --git a/test/ClangImporter/serialization-sil.swift b/test/ClangImporter/serialization-sil.swift
index 3e15366..b6f9f2b 100644
--- a/test/ClangImporter/serialization-sil.swift
+++ b/test/ClangImporter/serialization-sil.swift
@@ -1,13 +1,13 @@
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module-path %t/Test.swiftmodule -emit-sil -o /dev/null -module-name Test %s -sdk "" -import-objc-header %S/Inputs/serialization-sil.h
-// RUN: %target-sil-func-extractor %t/Test.swiftmodule -sil-print-debuginfo  -func=_T04Test16testPartialApplyySoAA_pF -o - | %FileCheck %s
+// RUN: %target-sil-func-extractor %t/Test.swiftmodule -sil-print-debuginfo  -func=_T04Test16testPartialApplyyySoAA_pF -o - | %FileCheck %s
 
 // REQUIRES: objc_interop
 
 // @_transparent to force serialization.
 @_transparent
 public func testPartialApply(_ obj: Test) {
-  // CHECK-LABEL: @_T04Test16testPartialApplyySoAA_pF : $@convention(thin) (@owned Test) -> () {
+  // CHECK-LABEL: @_T04Test16testPartialApplyyySoAA_pF : $@convention(thin) (@owned Test) -> () {
   if let curried1 = obj.normalObject {
     // CHECK: dynamic_method_br [[CURRIED1_OBJ:%.+]] : $@opened([[CURRIED1_EXISTENTIAL:.+]]) Test, #Test.normalObject!1.foreign, [[CURRIED1_TRUE:[^,]+]], [[CURRIED1_FALSE:[^,]+]]
     // CHECK: [[CURRIED1_FALSE]]:
@@ -40,4 +40,4 @@
     // CHECK: = apply [[PROP2_PARTIAL]]() : $@callee_guaranteed () -> UnsafeMutableRawPointer
     _ = prop2
   }
-} // CHECK: // end sil function '_T04Test16testPartialApplyySoAA_pF'
+} // CHECK: // end sil function '_T04Test16testPartialApplyyySoAA_pF'
diff --git a/test/ClangImporter/static_inline.swift b/test/ClangImporter/static_inline.swift
index 240a22f..90343f3 100644
--- a/test/ClangImporter/static_inline.swift
+++ b/test/ClangImporter/static_inline.swift
@@ -8,7 +8,7 @@
 
 // CHECK: sil shared [serializable] [clang c_inline_func] @c_inline_func : $@convention(c) (Int32) -> Int32
 
-// CHECK-IR-LABEL: define{{.*}} i32 @_T04test6testits5Int32VAD1x_tF(i32)
+// CHECK-IR-LABEL: define{{.*}} i32 @_T04test6testit1xs5Int32VAE_tF(i32)
 // CHECK-IR: = add {{.*}}, 27
 // CHECK-IR: ret
 
diff --git a/test/Compatibility/attr_override.swift b/test/Compatibility/attr_override.swift
index eee9994..5bc7c4d 100644
--- a/test/Compatibility/attr_override.swift
+++ b/test/Compatibility/attr_override.swift
@@ -67,7 +67,7 @@
     set { }
   }
 
-  func overriddenInExtension() {} // expected-note {{overridden declaration is here}}
+  func overriddenInExtension() {} // expected-note {{overri}}
 }
 
 class B : A {
@@ -140,7 +140,7 @@
 }
 
 extension B {
-  override func overriddenInExtension() {} // expected-error{{overriding declarations in extensions is not supported}}
+  override func overriddenInExtension() {} // expected-error{{overri}}
 }
 
 struct S {
diff --git a/test/Compatibility/attr_override_lazy.swift b/test/Compatibility/attr_override_lazy.swift
new file mode 100644
index 0000000..4d37834
--- /dev/null
+++ b/test/Compatibility/attr_override_lazy.swift
@@ -0,0 +1,25 @@
+// RUN: %target-swift-frontend -swift-version 4 -emit-silgen %s | %FileCheck %s
+
+class Base {
+  var foo: Int { return 0 }
+  var bar: Int = 0
+}
+
+class Sub : Base {
+  lazy override var foo: Int = 1
+  lazy override var bar: Int = 1
+  func test() -> Int {
+    // CHECK-LABEL: sil {{.*}}@_T018attr_override_lazy3SubC4testSiyF
+    // CHECK: class_method %0 : $Sub, #Sub.foo!getter.1
+    // CHECK: class_method %0 : $Sub, #Sub.bar!getter.1
+    // CHECK: // end sil function '_T018attr_override_lazy3SubC4testSiyF'
+    return foo + bar // no ambiguity error here
+  }
+}
+
+// CHECK-LABEL: sil_vtable Sub {
+// CHECK: #Base.foo!getter.1: (Base) -> () -> Int : {{.*}} // Sub.foo.getter
+// CHECK: #Base.bar!getter.1: (Base) -> () -> Int : {{.*}} // Sub.bar.getter
+// CHECK: #Base.bar!setter.1: (Base) -> (Int) -> () : {{.*}} // Sub.bar.setter
+// CHECK: #Base.bar!materializeForSet.1: (Base) -> {{.*}} : {{.*}} // Sub.bar.materializeForSet
+// CHECK: }
diff --git a/test/Constraints/array_literal.swift b/test/Constraints/array_literal.swift
index e5c212e..09c17ba 100644
--- a/test/Constraints/array_literal.swift
+++ b/test/Constraints/array_literal.swift
@@ -1,4 +1,4 @@
-// RUN: %target-typecheck-verify-swift -enable-experimental-conditional-conformances
+// RUN: %target-typecheck-verify-swift
 
 struct IntList : ExpressibleByArrayLiteral {
   typealias Element = Int
@@ -338,5 +338,5 @@
 
 func testConditional(i: Int, s: String) {
   let _: PArray<Int> = [i, i, i]
-  let _: PArray<String> = [s, s, s] // expected-error{{contextual type 'PArray<String>' cannot be used with array literal}}
+  let _: PArray<String> = [s, s, s] // expected-error{{cannot convert value of type '[String]' to specified type 'PArray<String>'}}
 }
diff --git a/test/Constraints/bridging.swift b/test/Constraints/bridging.swift
index 3f28f46..3f4ea44 100644
--- a/test/Constraints/bridging.swift
+++ b/test/Constraints/bridging.swift
@@ -15,7 +15,7 @@
 
 // Attempt to bridge to a type from another module. We only allow this for a
 // few specific types, like String.
-extension LazyFilterIterator : _ObjectiveCBridgeable { // expected-error{{conformance of 'LazyFilterIterator' to '_ObjectiveCBridgeable' can only be written in module 'Swift'}}
+extension LazyFilterSequence.Iterator : _ObjectiveCBridgeable { // expected-error{{conformance of 'Iterator' to '_ObjectiveCBridgeable' can only be written in module 'Swift'}}
   public typealias _ObjectiveCType = BridgedClassSub
 
   public func _bridgeToObjectiveC() -> _ObjectiveCType {
@@ -24,19 +24,19 @@
 
   public static func _forceBridgeFromObjectiveC(
     _ source: _ObjectiveCType,
-    result: inout LazyFilterIterator?
+    result: inout LazyFilterSequence.Iterator?
   ) { }
 
   public static func _conditionallyBridgeFromObjectiveC(
     _ source: _ObjectiveCType,
-    result: inout LazyFilterIterator?
+    result: inout LazyFilterSequence.Iterator?
   ) -> Bool {
     return true
   }
 
   public static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-      -> LazyFilterIterator {
-    let result: LazyFilterIterator?
+      -> LazyFilterSequence.Iterator {
+    let result: LazyFilterSequence.Iterator?
     return result!
   }
 }
diff --git a/test/Constraints/casts.swift b/test/Constraints/casts.swift
index fc50ac0..d7be38e 100644
--- a/test/Constraints/casts.swift
+++ b/test/Constraints/casts.swift
@@ -208,7 +208,7 @@
 _ = seven as Int // expected-error {{cannot convert value of type 'Double' to type 'Int' in coercion}}
 
 func rdar29894174(v: B?) {
-  let _ = [v].flatMap { $0 as? D }
+  let _ = [v].compactMap { $0 as? D }
 }
 
 // When re-typechecking a solution with an 'is' cast applied,
diff --git a/test/Constraints/closures.swift b/test/Constraints/closures.swift
index d19b9a2..005ba6c 100644
--- a/test/Constraints/closures.swift
+++ b/test/Constraints/closures.swift
@@ -511,12 +511,12 @@
 // () -> T to () -> Optional<()>.
 func returnsArray() -> [Int] { return [] }
 
-returnsArray().flatMap { $0 }.flatMap { }
+returnsArray().compactMap { $0 }.compactMap { }
 // expected-warning@-1 {{expression of type 'Int' is unused}}
-// expected-warning@-2 {{result of call to 'flatMap' is unused}}
+// expected-warning@-2 {{result of call to 'compactMap' is unused}}
 
 // rdar://problem/30271695
-_ = ["hi"].flatMap { $0.isEmpty ? nil : $0 }
+_ = ["hi"].compactMap { $0.isEmpty ? nil : $0 }
 
 // rdar://problem/32432145 - compiler should emit fixit to remove "_ in" in closures if 0 parameters is expected
 
@@ -645,3 +645,10 @@
  let arr = [C_33429010()]
  let _ = arr.map({ ($0.name, $0 as P_33429010) }) // Ok
 }
+
+func rdar36054961() {
+  func bar(dict: [String: (inout String, Range<String.Index>, String) -> Void]) {}
+  bar(dict: ["abc": { str, range, _ in
+     str.replaceSubrange(range, with: str[range].reversed())
+  }])
+}
diff --git a/test/Constraints/dictionary_literal.swift b/test/Constraints/dictionary_literal.swift
index efac19a..47fbc6d 100644
--- a/test/Constraints/dictionary_literal.swift
+++ b/test/Constraints/dictionary_literal.swift
@@ -43,18 +43,18 @@
 // <rdar://problem/22584076> QoI: Using array literal init with dictionary produces bogus error
 
 // expected-note @+1 {{did you mean to use a dictionary literal instead?}}
-var _: Dictionary<String, (Int) -> Int>? = [  // expected-error {{contextual type 'Dictionary<String, (Int) -> Int>' cannot be used with array literal}}
+var _: Dictionary<String, (Int) -> Int>? = [  // expected-error {{dictionary of type 'Dictionary<String, (Int) -> Int>' cannot be initialized with array literal}}
   "closure_1" as String, {(Int) -> Int in 0},
   "closure_2", {(Int) -> Int in 0}]
 
 
-var _: Dictionary<String, Int>? = ["foo", 1]  // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}}
+var _: Dictionary<String, Int>? = ["foo", 1]  // expected-error {{dictionary of type 'Dictionary<String, Int>' cannot be initialized with array literal}}
 // expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{41-42=:}}
 
-var _: Dictionary<String, Int>? = ["foo", 1, "bar", 42]  // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}}
+var _: Dictionary<String, Int>? = ["foo", 1, "bar", 42]  // expected-error {{dictionary of type 'Dictionary<String, Int>' cannot be initialized with array literal}}
 // expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{41-42=:}} {{51-52=:}}
 
-var _: Dictionary<String, Int>? = ["foo", 1.0, 2]  // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}}
+var _: Dictionary<String, Int>? = ["foo", 1.0, 2]  // expected-error {{cannot convert value of type '[Any]' to specified type 'Dictionary<String, Int>?'}}
 
 var _: Dictionary<String, Int>? = ["foo" : 1.0]  // expected-error {{cannot convert value of type 'Double' to expected dictionary value type 'Int'}}
 
@@ -102,11 +102,11 @@
 func rdar32330004_1() -> [String: Any] {
   return ["a""one": 1, "two": 2, "three": 3] // expected-note {{did you mean to use a dictionary literal instead?}}
   // expected-error@-1 2 {{expected ',' separator}}
-  // expected-error@-2 {{contextual type '[String : Any]' cannot be used with array literal}}
+  // expected-error@-2 {{dictionary of type '[String : Any]' cannot be used with array literal}}
 }
 
 func rdar32330004_2() -> [String: Any] {
   return ["a", 0, "one", 1, "two", 2, "three", 3]
-  // expected-error@-1 {{contextual type '[String : Any]' cannot be used with array literal}}
+  // expected-error@-1 {{dictionary of type '[String : Any]' cannot be used with array literal}}
   // expected-note@-2 {{did you mean to use a dictionary literal instead?}} {{14-15=:}} {{24-25=:}} {{34-35=:}} {{46-47=:}}
 }
diff --git a/test/Constraints/iuo.swift b/test/Constraints/iuo.swift
index a2272ee..8cafd85 100644
--- a/test/Constraints/iuo.swift
+++ b/test/Constraints/iuo.swift
@@ -18,6 +18,22 @@
   var m: Int
 
   func fn() -> Int! { return i }
+
+  static func static_fn() -> Int! { return 0 }
+
+  init(i: Int!, j: Int!, k: Int, m: Int) {
+    self.i = i
+    self.j = j
+    self.k = k
+    self.m = m
+  }
+
+  init!() {
+    i = 0
+    j = 0
+    k = 0
+    m = 0
+  }
 }
 
 func takesStruct(s: S) {
@@ -37,6 +53,8 @@
 s.m = 7
 s.j = 3
 
+var s2: S = S()
+
 struct T {
   let i: Float!
   var j: Float!
@@ -93,6 +111,10 @@
   return s.fn()
 }
 
+func forceStaticMemberResult() -> Int {
+  return S.static_fn()
+}
+
 func overloadedForceMemberResult() -> Int {
   return overloaded().fn()
 }
@@ -114,3 +136,22 @@
 // expected-warning@-1 {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}
 let w1: Int = (x as? Int!)!! // expected-warning {{conditional cast from 'Int?' to 'Int!' always succeeds}}
 // expected-warning@-1 {{using '!' in this location is deprecated and will be removed in a future release; consider changing this to '?' instead}}
+
+func id<T>(_ t: T) -> T { return t }
+
+protocol P { }
+extension P {
+  func iuoResult(_ b: Bool) -> Self! { }
+  static func iuoResultStatic(_ b: Bool) -> Self! { }
+}
+
+func cast<T : P>(_ t: T) {
+  let _: (T) -> (Bool) -> T? = id(T.iuoResult as (T) -> (Bool) -> T?)
+  let _: (Bool) -> T? = id(T.iuoResult(t) as (Bool) -> T?)
+  let _: T! = id(T.iuoResult(t)(true))
+  let _: (Bool) -> T? = id(t.iuoResult as (Bool) -> T?)
+  let _: T! = id(t.iuoResult(true))
+  let _: T = id(t.iuoResult(true))
+  let _: (Bool) -> T? = id(T.iuoResultStatic as (Bool) -> T?)
+  let _: T! = id(T.iuoResultStatic(true))
+}
diff --git a/test/Constraints/lvalues.swift b/test/Constraints/lvalues.swift
index 53ef06a..1c2af46 100644
--- a/test/Constraints/lvalues.swift
+++ b/test/Constraints/lvalues.swift
@@ -167,7 +167,7 @@
 func takeArrayRef(_ x: inout Array<String>) { }
 
 // rdar://22308291
-takeArrayRef(["asdf", "1234"]) // expected-error{{contextual type 'inout Array<String>' cannot be used with array literal}}
+takeArrayRef(["asdf", "1234"]) // expected-error{{cannot pass immutable value of type '[String]' as inout argument}}
 
 // <rdar://problem/19835413> Reference to value from array changed
 func rdar19835413() {
diff --git a/test/Constraints/rdar35142121.swift b/test/Constraints/rdar35142121.swift
index ded3e9a..068f3b2 100644
--- a/test/Constraints/rdar35142121.swift
+++ b/test/Constraints/rdar35142121.swift
@@ -8,5 +8,5 @@
   return 42
 }
 
-// CHECK: function_ref @_T012rdar351421213fooS3icF : $@convention(thin) (@owned @noescape @callee_guaranteed (Int) -> Int) -> Int
+// CHECK: function_ref @_T012rdar351421213fooyS3icF : $@convention(thin) (@owned @noescape @callee_guaranteed (Int) -> Int) -> Int
 let _ = foo({ (a: Int) -> Int in a + 1 })
diff --git a/test/Constraints/tuple_arguments.swift b/test/Constraints/tuple_arguments.swift
index 48c5e10..bf6ce7c 100644
--- a/test/Constraints/tuple_arguments.swift
+++ b/test/Constraints/tuple_arguments.swift
@@ -1554,11 +1554,11 @@
 }
 
 func rdar33043106(_ records: [(Int)], _ other: [((Int))]) -> [Int] {
-  let x: [Int] = records.flatMap { _ in
+  let x: [Int] = records.map { _ in
     let i = 1
     return i
   }
-  let y: [Int] = other.flatMap { _ in
+  let y: [Int] = other.map { _ in
     let i = 1
     return i
   }
@@ -1571,9 +1571,9 @@
 }
 
 func rdar33159366(s: AnySequence<Int>) {
-  _ = s.flatMap(itsFalse)
+  _ = s.compactMap(itsFalse)
   let a = Array(s)
-  _ = a.flatMap(itsFalse)
+  _ = a.compactMap(itsFalse)
 }
 
 func sr5429<T>(t: T) {
diff --git a/test/DebugInfo/Constructors.swift b/test/DebugInfo/Constructors.swift
index d7c66b7..f51dbd3 100644
--- a/test/DebugInfo/Constructors.swift
+++ b/test/DebugInfo/Constructors.swift
@@ -1,7 +1,7 @@
 // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
 struct Foo {
   // Allocating constructor - should have no line table info.
-  // CHECK: !DISubprogram(name: "init", linkageName: "_T012Constructors3FooVACs5Int64V1x_tcfC",
+  // CHECK: !DISubprogram(name: "init", linkageName: "_T012Constructors3FooV1xACs5Int64V_tcfC",
   // CHECK-SAME:          line: [[@LINE+3]]
   // CHECK-NOT:           scopeLine: 0
   // CHECK-SAME:          isDefinition: true
diff --git a/test/DebugInfo/EagerTypeMetadata.swift b/test/DebugInfo/EagerTypeMetadata.swift
index 0a074ed..571b75b 100644
--- a/test/DebugInfo/EagerTypeMetadata.swift
+++ b/test/DebugInfo/EagerTypeMetadata.swift
@@ -5,7 +5,7 @@
   func c(_ i : T)
   {
     // Ensure that the type metadata for T is eagerly loaded at -Onone.
-    // CHECK: define {{.*}} @_T017EagerTypeMetadata1CC1cyxF
+    // CHECK: define {{.*}} @_T017EagerTypeMetadata1CC1cyyxF
     // CHECK: %T = load %swift.type*, %swift.type**
     // CHECK-SAME: !dbg ![[LOC:[0-9]+]], !invariant.load
     // CHECK: ![[LOC]] = !DILocation(line: 0,
diff --git a/test/DebugInfo/ErrorVar.swift b/test/DebugInfo/ErrorVar.swift
index 015d678..a394b7d 100644
--- a/test/DebugInfo/ErrorVar.swift
+++ b/test/DebugInfo/ErrorVar.swift
@@ -11,7 +11,7 @@
 // thrown error we create a shadow stack location holding the address of the
 // location that holds the pointer to the error instead.
 func simple(_ placeholder: Int64) throws -> () {
-  // CHECK: define {{.*}}void @_T08ErrorVar6simpleys5Int64VKF(i64, %swift.refcounted* swiftself, %swift.error**)
+  // CHECK: define {{.*}}void @_T08ErrorVar6simpleyys5Int64VKF(i64, %swift.refcounted* swiftself, %swift.error**)
   // CHECK: call void @llvm.dbg.declare
   // CHECK: call void @llvm.dbg.declare({{.*}}, metadata ![[ERROR:[0-9]+]], metadata !DIExpression(DW_OP_deref))
   // CHECK: ![[ERRTY:.*]] = !DICompositeType({{.*}}identifier: "_T0s5Error_pD"
diff --git a/test/DebugInfo/LinetableArtificialFn.swift b/test/DebugInfo/LinetableArtificialFn.swift
index 93705f9..9fc1a2d 100644
--- a/test/DebugInfo/LinetableArtificialFn.swift
+++ b/test/DebugInfo/LinetableArtificialFn.swift
@@ -3,7 +3,7 @@
 // Verify that a helper function that is generated on-the-fly does
 // not mess up the linetable of the calling function.
 // CHECK:  store i2048 10, i2048* [[STKLOC:%.*]], align
-// CHECK:  call swiftcc {{(i32|i64)}} @_T0S2iBi2048_22_builtinIntegerLiteral_tcfC(i2048* {{.*}} [[STKLOC]]
+// CHECK:  call swiftcc {{(i32|i64)}} @_T0Si22_builtinIntegerLiteralSiBi2048__tcfC(i2048* {{.*}} [[STKLOC]]
 // CHECK: store {{(i32|i64)}} {{.*}}getelementptr
 // CHECK: store {{(i32|i64)}} {{.*}}getelementptr{{.*}}, !dbg ![[DBG:[0-9]+]]
 // CHECK-NOT: ![[DBG]] = !{i32 0, i32 0,
diff --git a/test/DebugInfo/archetype.swift b/test/DebugInfo/archetype.swift
index 6b7e90a..65a3978 100644
--- a/test/DebugInfo/archetype.swift
+++ b/test/DebugInfo/archetype.swift
@@ -22,5 +22,5 @@
   return _overflowChecked((tmp.0, tmp.1))
 }
 // CHECK: ![[TT]] = !DICompositeType(tag: DW_TAG_structure_type,
-// CHECK-SAME:                       name: "_T09archetype16ExistentialTuple8Distance
+// CHECK-SAME:                       name: "_T09archetype16ExistentialTuple_1y8Distance
 
diff --git a/test/DebugInfo/atype.swift b/test/DebugInfo/atype.swift
index f6fc649..f64d4c8 100644
--- a/test/DebugInfo/atype.swift
+++ b/test/DebugInfo/atype.swift
@@ -3,7 +3,7 @@
 func markUsed<T>(_ t: T) {}
 
 class Class {
-// CHECK: tag: DW_TAG_structure_type, name: "_T05atype5ClassC8functionyxlFQq_D"
+// CHECK: tag: DW_TAG_structure_type, name: "_T05atype5ClassC8functionyyxlFQq_D"
   func function<T>(_ x: T) {
     markUsed("hello world")
   }
diff --git a/test/DebugInfo/autoclosure.swift b/test/DebugInfo/autoclosure.swift
index 3df5049..879f0f8 100644
--- a/test/DebugInfo/autoclosure.swift
+++ b/test/DebugInfo/autoclosure.swift
@@ -1,6 +1,6 @@
 // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
 
-// CHECK: define{{.*}}@_T011autoclosure7call_meys5Int64VF
+// CHECK: define{{.*}}@_T011autoclosure7call_meyys5Int64VF
 // CHECK-NOT: ret void
 // CHECK: call void @llvm.dbg.declare{{.*}}, !dbg
 // CHECK-NOT: ret void
@@ -21,7 +21,7 @@
 func call_me(_ input: Int64) -> Void {
 // rdar://problem/14627460
 // An autoclosure should have a line number in the debug info and a scope line of 0.
-// CHECK-DAG: !DISubprogram({{.*}}linkageName: "_T011autoclosure7call_meys5Int64VFSbyXKfu_",{{.*}} line: [[@LINE+3]],{{.*}} isLocal: true, isDefinition: true
+// CHECK-DAG: !DISubprogram({{.*}}linkageName: "_T011autoclosure7call_meyys5Int64VFSbyXKfu_",{{.*}} line: [[@LINE+3]],{{.*}} isLocal: true, isDefinition: true
 // But not in the line table.
 // CHECK-DAG: ![[DBG]] = !DILocation(line: [[@LINE+1]],
   if input != 0 &&&&& ( get_truth (input * 2 + 1) > 0 ) {
diff --git a/test/DebugInfo/basic.swift b/test/DebugInfo/basic.swift
index bbc2bc6..311e310 100644
--- a/test/DebugInfo/basic.swift
+++ b/test/DebugInfo/basic.swift
@@ -51,7 +51,7 @@
        // CHECK-DAG: smul{{.*}}, !dbg ![[MUL:[0-9]+]]
        // CHECK-DAG: [[MUL]] = !DILocation(line: [[@LINE+4]], column: 16,
        // Runtime call to multiply function:
-       // CHECK-NOSIL: @_T0s5Int64V1moiA2B_ABtFZ{{.*}}, !dbg ![[MUL:[0-9]+]]
+       // CHECK-NOSIL: @_T0s5Int64V1moiyA2B_ABtFZ{{.*}}, !dbg ![[MUL:[0-9]+]]
        // CHECK-NOSIL: [[MUL]] = !DILocation(line: [[@LINE+1]], column: 16,
        return a*b
      } else {
diff --git a/test/DebugInfo/conditional-assign.swift b/test/DebugInfo/conditional-assign.swift
index 104c18a..7374df0 100644
--- a/test/DebugInfo/conditional-assign.swift
+++ b/test/DebugInfo/conditional-assign.swift
@@ -16,7 +16,7 @@
   // Verify that definite initialization doesn't create a bogus description of
   // self pointing to the liveness bitvector.
   
-  // CHECK: sil @_T04main1MCAcA12WithDelegate_p4from_tKcfc
+  // CHECK: sil @_T04main1MC4fromAcA12WithDelegate_p_tKcfc
   // CHECK: bb0
   // CHECK-NEXT: %2 = alloc_stack $Builtin.Int2
   // CHECK-NOT: let
diff --git a/test/DebugInfo/debug_value_addr.swift b/test/DebugInfo/debug_value_addr.swift
index f2398c2..30d7ced 100644
--- a/test/DebugInfo/debug_value_addr.swift
+++ b/test/DebugInfo/debug_value_addr.swift
@@ -4,10 +4,10 @@
 // Verify that -Onone shadow copies are emitted for debug_value_addr
 // instructions.
 
-// CHECK-SIL: sil hidden @_T016debug_value_addr4testyxlF
+// CHECK-SIL: sil hidden @_T016debug_value_addr4testyyxlF
 // CHECK-SIL: debug_value_addr %0 : $*T, let, name "t"
 
-// CHECK: define {{.*}}_T016debug_value_addr4testyxlF
+// CHECK: define {{.*}}_T016debug_value_addr4testyyxlF
 // CHECK: entry:
 // CHECK-NEXT: %[[TADDR:.*]] = alloca
 // CHECK-NEXT: call void @llvm.dbg.declare({{.*}}%[[TADDR]]
diff --git a/test/DebugInfo/dynamic_layout.swift b/test/DebugInfo/dynamic_layout.swift
index ce96281..9a84a08 100644
--- a/test/DebugInfo/dynamic_layout.swift
+++ b/test/DebugInfo/dynamic_layout.swift
@@ -8,7 +8,7 @@
   init(_x : T) {x = _x}
 
   // Verify that the mangling of the decl context of the type U is correct.
-  // CHECK: !DICompositeType({{.*}}name: "{{[^"]*}}_T014dynamic_layout5ClassC3foox_qd__tqd__lFQq_{{[^"]*}}"
+  // CHECK: !DICompositeType({{.*}}name: "{{[^"]*}}_T014dynamic_layout5ClassC3fooyx_qd__tqd__lFQq_{{[^"]*}}"
   func foo <U> (_ y : U) -> (T,U) {
     var tuple = (x,y)
     return tuple
diff --git a/test/DebugInfo/enum.swift b/test/DebugInfo/enum.swift
index 5167d1c..a349bde 100644
--- a/test/DebugInfo/enum.swift
+++ b/test/DebugInfo/enum.swift
@@ -64,17 +64,17 @@
 // CHECK-SAME:             {{.*}}identifier: "_T04enum4RoseOyxG{{z?}}D")
 enum Rose<A> {
 	case MkRose(() -> A, () -> [Rose<A>])
-  // DWARF: !DICompositeType({{.*}}name: "Rose",{{.*}}identifier: "_T04enum4RoseOyAA3fooACyxGAElFQq_GD")
+  // DWARF: !DICompositeType({{.*}}name: "Rose",{{.*}}identifier: "_T04enum4RoseOyAA3fooyACyxGAElFQq_GD")
 	case IORose(() -> Rose<A>)
 }
 
 func foo<T>(_ x : Rose<T>) -> Rose<T> { return x }
 
-// CHECK: !DICompositeType({{.*}}name: "Tuple", {{.*}}elements: ![[ELTS:[0-9]+]], {{.*}}identifier: "_T04enum5TupleOyAA3barACyxGAElFQq_GD")
+// CHECK: !DICompositeType({{.*}}name: "Tuple", {{.*}}elements: ![[ELTS:[0-9]+]], {{.*}}identifier: "_T04enum5TupleOyAA3baryACyxGAElFQq_GD")
 // DWARF: !DICompositeType({{.*}}name: "Tuple", {{.*}}elements: ![[ELTS:[0-9]+]],
 // DWARF-SAME:             {{.*}}identifier: "_T04enum5TupleOyxG{{z?}}D")
 public enum Tuple<P> {
-  // DWARF: !DICompositeType({{.*}}name: "Tuple",{{.*}}identifier: "_T04enum5TupleOyAA3barACyxGAElFQq_GD")
+  // DWARF: !DICompositeType({{.*}}name: "Tuple",{{.*}}identifier: "_T04enum5TupleOyAA3baryACyxGAElFQq_GD")
 	case C(P, () -> Tuple)
 }
 
diff --git a/test/DebugInfo/generic_arg.swift b/test/DebugInfo/generic_arg.swift
index 3481a3c..156bcf6 100644
--- a/test/DebugInfo/generic_arg.swift
+++ b/test/DebugInfo/generic_arg.swift
@@ -1,7 +1,7 @@
 // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
 import StdlibUnittest
 func foo<T>(_ x: T) -> () {
-  // CHECK: define {{.*}} @_T011generic_arg3fooyxlF
+  // CHECK: define {{.*}} @_T011generic_arg3fooyyxlF
   // CHECK: %[[T:.*]] = alloca %swift.type*
   // CHECK: call void @llvm.dbg.declare(metadata %swift.type** %[[T]],
   // CHECK-SAME:               metadata ![[T1:.*]], metadata !DIExpression())
@@ -14,7 +14,7 @@
   // CHECK-SAME:                       flags: DIFlagArtificial)
   // CHECK: ![[X1]] = !DILocalVariable(name: "x", arg: 1,
   // CHECK-SAME:          line: 3, type: ![[TY:.*]])
-  // CHECK: ![[TY]] = !DICompositeType({{.*}}identifier: "_T011generic_arg3fooyxlFQq_D")
+  // CHECK: ![[TY]] = !DICompositeType({{.*}}identifier: "_T011generic_arg3fooyyxlFQq_D")
   _blackHole(x)
 }
 
diff --git a/test/DebugInfo/generic_arg3.swift b/test/DebugInfo/generic_arg3.swift
index c4349a8..de0e65f 100644
--- a/test/DebugInfo/generic_arg3.swift
+++ b/test/DebugInfo/generic_arg3.swift
@@ -4,12 +4,12 @@
 
 public func f<Type>(_ value : Type)
 {
-  // CHECK: define {{.*}}_T012generic_arg31fyxlFxxcfU_
+  // CHECK: define {{.*}}_T012generic_arg31fyyxlFxxcfU_
   // CHECK: call void @llvm.dbg.declare(metadata %swift.opaque** %[[ALLOCA:[^,]+]],
   // CHECK-SAME:       metadata ![[ARG:.*]], metadata !DIExpression())
   // CHECK: store %swift.opaque* %1, %swift.opaque** %[[ALLOCA]], align
   // No deref here: The argument is an Archetype and this implicitly indirect.
-  // CHECK: ![[TY:.*]] = !DICompositeType({{.*}}identifier: "_T012generic_arg31fyxlFQq_D"
+  // CHECK: ![[TY:.*]] = !DICompositeType({{.*}}identifier: "_T012generic_arg31fyyxlFQq_D"
   // CHECK: ![[ARG]] = !DILocalVariable(name: "arg", arg: 1,
   // CHECK-SAME:                        line: [[@LINE+1]], type: ![[TY]])
   apply(value) { arg in return arg }
diff --git a/test/DebugInfo/generic_arg4.swift b/test/DebugInfo/generic_arg4.swift
index 2d9e06c..936c244 100644
--- a/test/DebugInfo/generic_arg4.swift
+++ b/test/DebugInfo/generic_arg4.swift
@@ -3,7 +3,7 @@
 public struct Q<T> {
   let x: T
 }
-// CHECK: define {{.*}}_T012generic_arg43fooySayAA1QVyxGGlF
+// CHECK: define {{.*}}_T012generic_arg43fooyySayAA1QVyxGGlF
 // CHECK: call void @llvm.dbg.declare
 // CHECK: call void @llvm.dbg.declare(metadata %[[TY:.*]]** %[[ALLOCA:[^,]+]],
 // CHECK-SAME:       metadata ![[ARG:.*]], metadata !DIExpression())
@@ -11,6 +11,6 @@
 // No deref here: the array argument is passed by value.
 // CHECK: ![[ARG]] = !DILocalVariable(name: "arg", arg: 1,
 // CHECK-SAME:                        line: [[@LINE+2]], type: ![[TY:.*]])
-// CHECK: ![[TY]] = !DICompositeType({{.*}}identifier: "_T0Say12generic_arg41QVyAA3fooySayACyxGGlFQq_GGD")
+// CHECK: ![[TY]] = !DICompositeType({{.*}}identifier: "_T0Say12generic_arg41QVyAA3fooyySayACyxGGlFQq_GGD")
 public func foo<T>(_ arg: [Q<T>]) {
 }
diff --git a/test/DebugInfo/generic_arg5.swift b/test/DebugInfo/generic_arg5.swift
index c163805..f199186 100644
--- a/test/DebugInfo/generic_arg5.swift
+++ b/test/DebugInfo/generic_arg5.swift
@@ -6,7 +6,7 @@
 
 public func foo<Type>(_ values : [S<Type>])
 {
-  // CHECK: define {{.*}}_T012generic_arg53fooySayAA1SVyxGGlFAESgAEcfU_
+  // CHECK: define {{.*}}_T012generic_arg53fooyySayAA1SVyxGGlFAESgAEcfU_
   // CHECK: call void @llvm.dbg.declare
   // CHECK: call void @llvm.dbg.declare(metadata %[[TY:.*]]** %[[ALLOCA:[^,]+]],
   // CHECK-SAME:       metadata ![[ARG:[0-9]+]],
@@ -16,7 +16,7 @@
   // CHECK: ![[ARG]] = !DILocalVariable(name: "arg", arg: 1,
   // CHECK-SAME:                        line: [[@LINE+3]],
   // CHECK-SAME:     type: ![[TY:.*]])
-  // CHECK: ![[TY]] = !DICompositeType({{.*}}identifier: "_T012generic_arg51SVyAA3fooySayACyxGGlFQq_GD")
+  // CHECK: ![[TY]] = !DICompositeType({{.*}}identifier: "_T012generic_arg51SVyAA3fooyySayACyxGGlFQq_GD")
   let _ = values.flatMap { arg in
     return .some(arg)
   }
diff --git a/test/DebugInfo/generic_args.swift b/test/DebugInfo/generic_args.swift
index a08ab78..275972c 100644
--- a/test/DebugInfo/generic_args.swift
+++ b/test/DebugInfo/generic_args.swift
@@ -29,7 +29,7 @@
 struct Wrapper<T: AProtocol> {
 
   init<U>(from : Wrapper<U>) {
-  // CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "Wrapper",{{.*}} identifier: "_T012generic_args7WrapperVyA2CyxGACyqd__G4from_tcAA9AProtocolRd__lufcQq_GD")
+  // CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "Wrapper",{{.*}} identifier: "_T012generic_args7WrapperVyAC4fromACyxGACyqd__G_tcAA9AProtocolRd__lufcQq_GD")
     var wrapped = from
     wrapped = from
     _ = wrapped
@@ -45,7 +45,7 @@
   }
 }
 
-// CHECK-DAG: ![[FNTY:.*]] = !DICompositeType({{.*}}identifier: "_T012generic_args5applyq_x_q_xc1ftr0_lFQq_AaBq_x_q_xcACtr0_lFQq0_Igir_D"
+// CHECK-DAG: ![[FNTY:.*]] = !DICompositeType({{.*}}identifier: "_T012generic_args5apply_1fq_x_q_xctr0_lFQq_AaB_ACq_x_q_xctr0_lFQq0_Igir_D"
 // CHECK-DAG: !DILocalVariable(name: "f", {{.*}}, line: [[@LINE+1]], type: ![[FNTY]])
 func apply<T, U> (_ x: T, f: (T) -> (U)) -> U {
   return f(x)
diff --git a/test/DebugInfo/generic_enum_closure.swift b/test/DebugInfo/generic_enum_closure.swift
index 5bea3c9..b7bd4c3 100644
--- a/test/DebugInfo/generic_enum_closure.swift
+++ b/test/DebugInfo/generic_enum_closure.swift
@@ -5,7 +5,7 @@
  {
   var value : T?
   init(x : __CurrentErrno) {
-    // CHECK: define hidden {{.*}}void @_T020generic_enum_closure8CErrorOrVACyxGAA14__CurrentErrnoV1x_tcfC
+    // CHECK: define hidden {{.*}}void @_T020generic_enum_closure8CErrorOrV1xACyxGAA14__CurrentErrnoV_tcfC
     // CHECK-NOT: define
     // This is a SIL-level debug_value_addr instruction.
     // CHECK: call void @llvm.dbg.value({{.*}}, metadata ![[SELF:.*]], metadata !DIExpression())
diff --git a/test/DebugInfo/guard-let.swift b/test/DebugInfo/guard-let.swift
index b7d2c8c..d3cc0bd 100644
--- a/test/DebugInfo/guard-let.swift
+++ b/test/DebugInfo/guard-let.swift
@@ -7,7 +7,7 @@
 
 public func f(_ i : Int?)
 {
-  // CHECK: define {{.*}}@_T04main1fySiSgF
+  // CHECK: define {{.*}}@_T04main1fyySiSgF
   // The shadow copy store should not have a location.
   // Note that the store must be in the same scope or else it might defeat
   // livedebugvalues.
@@ -28,7 +28,7 @@
 
 public func g(_ s : String?)
 {
-  // CHECK2: define {{.*}}@_T04main1gySSSgF
+  // CHECK2: define {{.*}}@_T04main1gyySSSgF
   // The shadow copy store should not have a location.
   // CHECK2: getelementptr inbounds {{.*}} %s.debug, {{.*}}, !dbg ![[DBG0:.*]]
   // CHECK2: ![[G:.*]] = distinct !DISubprogram(name: "g"
diff --git a/test/DebugInfo/inlined-generics.swift b/test/DebugInfo/inlined-generics.swift
index 9ec8559..02df7d3 100644
--- a/test/DebugInfo/inlined-generics.swift
+++ b/test/DebugInfo/inlined-generics.swift
@@ -10,7 +10,7 @@
   return dttmp
 }
 
-// CHECK: define {{.*}}@_T04main4foo2yxAA1PRzlF
+// CHECK: define {{.*}}@_T04main4foo2yyxAA1PRzlF
 public func foo2<S:P>(_ s: S) {
   // CHECK: call void @llvm.dbg.value(metadata %swift.type* %S.DT1,
   // CHECK-SAME:                     metadata ![[META:[0-9]+]]
diff --git a/test/DebugInfo/inlinedAt.swift b/test/DebugInfo/inlinedAt.swift
index 40e47ef..8291ac4 100644
--- a/test/DebugInfo/inlinedAt.swift
+++ b/test/DebugInfo/inlinedAt.swift
@@ -24,14 +24,14 @@
   return g(i)                     // 302
 }
 
-// CHECK-SIL: sil {{.*}}@_T09inlinedAt1fS2iF :
+// CHECK-SIL: sil {{.*}}@_T09inlinedAt1fyS2iF :
 // CHECK-SIL-NOT: return
 // CHECK-SIL: debug_value %0 : $Int, let, name "k", argno 1
 // CHECK-SIL-SAME: line:101:10:in_prologue
 // CHECK-SIL-SAME: perf_inlined_at line:203:10
 // CHECK-SIL-SAME: perf_inlined_at line:302:10
 
-// CHECK: define {{.*}}@_T09inlinedAt1fS2iF({{.*}})
+// CHECK: define {{.*}}@_T09inlinedAt1fyS2iF({{.*}})
 // CHECK-NOT: ret
 // CHECK: @llvm.dbg.value
 // CHECK: @llvm.dbg.value
diff --git a/test/DebugInfo/inlinescopes.swift b/test/DebugInfo/inlinescopes.swift
index 515377f..3573d17 100644
--- a/test/DebugInfo/inlinescopes.swift
+++ b/test/DebugInfo/inlinescopes.swift
@@ -33,4 +33,4 @@
 use(y)
 
 // Check if the inlined and removed function still has the correct linkage name.
-// CHECK-DAG: !DISubprogram(name: "inlined", linkageName: "_T04main7inlineds5Int64VADF"
+// CHECK-DAG: !DISubprogram(name: "inlined", linkageName: "_T04main7inlinedys5Int64VADF"
diff --git a/test/DebugInfo/inout.swift b/test/DebugInfo/inout.swift
index 5692dbb..76813e8 100644
--- a/test/DebugInfo/inout.swift
+++ b/test/DebugInfo/inout.swift
@@ -14,7 +14,7 @@
 // CHECK-SAME:                        %[[ALLOCA]], metadata ![[A:[0-9]+]]
 
 // Closure with promoted capture.
-// PROMO-CHECK: define {{.*}}@_T05inout13modifyFooHeapys5Int64Vz_SftFADycfU_
+// PROMO-CHECK: define {{.*}}@_T05inout13modifyFooHeapyys5Int64Vz_SftFADycfU_
 // PROMO-CHECK: call void @llvm.dbg.declare(metadata %Ts5Int64V** %
 // PROMO-CHECK-SAME:   metadata ![[A1:[0-9]+]], metadata !DIExpression())
 
@@ -37,7 +37,7 @@
 }
 
 // Inout reference type.
-// FOO-CHECK: define {{.*}}@_T05inout9modifyFooys5Int64Vz_SftF
+// FOO-CHECK: define {{.*}}@_T05inout9modifyFooyys5Int64Vz_SftF
 // FOO-CHECK: call void @llvm.dbg.declare(metadata %Ts5Int64V** %
 // FOO-CHECK-SAME:          metadata ![[U:[0-9]+]], metadata !DIExpression())
 func modifyFoo(_ u: inout Int64,
diff --git a/test/DebugInfo/iuo_arg.swift b/test/DebugInfo/iuo_arg.swift
index bb59dc0..4bba265 100644
--- a/test/DebugInfo/iuo_arg.swift
+++ b/test/DebugInfo/iuo_arg.swift
@@ -13,7 +13,7 @@
 }
 
 class MyClass {
-  // CHECK: define hidden {{.*}} %T7iuo_arg7UIImageC* @_T07iuo_arg7MyClassC11filterImageAA7UIImageCSQyAFG_SbtF
+  // CHECK: define hidden {{.*}} %T7iuo_arg7UIImageC* @_T07iuo_arg7MyClassC11filterImageyAA7UIImageCSQyAFG_SbtF
   func filterImage(_ image: UIImage!, _ doSomething:Bool) -> UIImage
 	{
     // Test that image is in an alloca, but not an indirect location.
diff --git a/test/DebugInfo/linetable-assign.swift b/test/DebugInfo/linetable-assign.swift
index f679808..b41353c 100644
--- a/test/DebugInfo/linetable-assign.swift
+++ b/test/DebugInfo/linetable-assign.swift
@@ -3,7 +3,7 @@
 // RUN:   | %FileCheck %s
 public func g<T>(_ t: T) {}
 public func f(_ i: Int32) {
-  // CHECK: function_ref @_T04main1fys5Int32VFyycfU_
+  // CHECK: function_ref @_T04main1fyys5Int32VFyycfU_
   // CHECK-SAME: loc "{{.*}}":13:3,
   // CHECK: %[[CLOSURE:.*]] = partial_apply
   // CHECK-SAME: loc "{{.*}}":13:3,{{.*}}auto_gen
diff --git a/test/DebugInfo/linetable-cleanups.swift b/test/DebugInfo/linetable-cleanups.swift
index 278775f..318208e 100644
--- a/test/DebugInfo/linetable-cleanups.swift
+++ b/test/DebugInfo/linetable-cleanups.swift
@@ -17,11 +17,11 @@
         markUsed("element = \(element)")
     }
     markUsed("Done with the for loop")
-// CHECK: call {{.*}}void @_T04main8markUsedyxlF
+// CHECK: call {{.*}}void @_T04main8markUsedyyxlF
 // CHECK: br label
 // CHECK: <label>:
 // CHECK: call %Ts16IndexingIteratorVySaySiGG* @_T0s16IndexingIteratorVySaySiGGWh0_(%Ts16IndexingIteratorVySaySiGG* %{{.*}}), !dbg ![[LOOPHEADER_LOC:.*]]
-// CHECK: call {{.*}}void @_T04main8markUsedyxlF
+// CHECK: call {{.*}}void @_T04main8markUsedyyxlF
 // The cleanups should share the line number with the ret stmt.
 // CHECK:  call %TSa* @_T0SaySiGWh0_(%TSa* %{{.*}}), !dbg ![[CLEANUPS:.*]]
 // CHECK-NEXT:  !dbg ![[CLEANUPS]]
diff --git a/test/DebugInfo/linetable.swift b/test/DebugInfo/linetable.swift
index cac87e4..fa51685 100644
--- a/test/DebugInfo/linetable.swift
+++ b/test/DebugInfo/linetable.swift
@@ -29,7 +29,7 @@
 // ASM-CHECK: .loc [[FILEID:[0-9]]] [[@LINE+1]] 5
     call_me (
 // ASM-CHECK-NOT: .loc [[FILEID]] [[@LINE+1]] 5
-// CHECK-LABEL: define {{.*}} @_T09linetable4mainys5Int64VFyycfU_Tf2in_n({{.*}})
+// CHECK-LABEL: define {{.*}} @_T09linetable4mainyys5Int64VFyycfU_Tf2in_n({{.*}})
         {
             var result = my_class.do_something(x)
             markUsed(result)
@@ -49,7 +49,7 @@
 // ASM-CHECK: ret
 }
 
-// ASM-CHECK: {{^_?_T09linetable4mainys5Int64VFyycfU_Tf2in_n:}}
+// ASM-CHECK: {{^_?_T09linetable4mainyys5Int64VFyycfU_Tf2in_n:}}
 // ASM-CHECK-NOT: retq
 // The end-of-prologue should have a valid location (0 is ok, too).
 // ASM-CHECK: .loc [[FILEID]] {{0|34}} {{[0-9]+}} prologue_end
diff --git a/test/DebugInfo/patternvars.swift b/test/DebugInfo/patternvars.swift
index 1b5ccf4..7cff01a 100644
--- a/test/DebugInfo/patternvars.swift
+++ b/test/DebugInfo/patternvars.swift
@@ -33,7 +33,7 @@
 // which shares the storage with the expression in the switch statement. Make
 // sure we emit a dbg.value once per basic block.
 
-// CHECK: define {{.*}}@_T011patternvars6mangleSayAA13UnicodeScalarVGAE1s_tFA2DcfU_
+// CHECK: define {{.*}}@_T011patternvars6mangle1sSayAA13UnicodeScalarVGAF_tFA2EcfU_
 // CHECK: %[[VAL:[0-9]+]] = call swiftcc i32 @_T011patternvars13UnicodeScalarV5values6UInt32Vvg(i32 %0)
 // CHECK-NEXT:  call void @llvm.dbg.value(metadata i32 %[[VAL]]
 // CHECK:       ; <label>
diff --git a/test/DebugInfo/prologue.swift b/test/DebugInfo/prologue.swift
index 64745c3..aadae8d 100644
--- a/test/DebugInfo/prologue.swift
+++ b/test/DebugInfo/prologue.swift
@@ -6,7 +6,7 @@
 
 // CHECK: .file [[F:[0-9]+]] "{{.*}}prologue.swift"
 func bar<T, U>(_ x: T, y: U) { markUsed("bar") }
-// CHECK: _T08prologue3baryx_q_1ytr0_lF:
+// CHECK: _T08prologue3bar_1yyx_q_tr0_lF:
 // CHECK: .loc	[[F]] 0 0 prologue_end
 // Make sure there is no allocation happening between the end of
 // prologue and the beginning of the function body.
diff --git a/test/DebugInfo/protocolarg.swift b/test/DebugInfo/protocolarg.swift
index 248b5cf..a650dfd 100644
--- a/test/DebugInfo/protocolarg.swift
+++ b/test/DebugInfo/protocolarg.swift
@@ -7,7 +7,7 @@
   func callMe() -> Int64
 }
 
-// CHECK: define {{.*}}@_T011protocolarg16printSomeNumbersyAA12IGiveOutInts_pF
+// CHECK: define {{.*}}@_T011protocolarg16printSomeNumbersyyAA12IGiveOutInts_pF
 // CHECK: @llvm.dbg.declare(metadata %T11protocolarg12IGiveOutIntsP** %
 // CHECK-SAME:              metadata ![[ARG:[0-9]+]],
 // CHECK-SAME:              metadata !DIExpression(DW_OP_deref))
diff --git a/test/DebugInfo/return.swift b/test/DebugInfo/return.swift
index 5bff35e..c2d7486 100644
--- a/test/DebugInfo/return.swift
+++ b/test/DebugInfo/return.swift
@@ -10,7 +10,7 @@
   var x = X(i:0)
   // CHECK: [[ALLOCA:%.*]] = alloca %T6return1XC*
   // CHECK: [[META:%.*]] = call %swift.type* @_T06return1XCMa()
-  // CHECK: [[X:%.*]] = call {{.*}}%T6return1XC* @_T06return1XCACs5Int64V1i_tcfC(
+  // CHECK: [[X:%.*]] = call {{.*}}%T6return1XC* @_T06return1XC1iACs5Int64V_tcfC(
   // CHECK-SAME:                                  i64 0, %swift.type* swiftself [[META]])
   // CHECK:  store %T6return1XC* [[X]], %T6return1XC** [[ALLOCA]]
   // CHECK:  @swift_rt_swift_release to void (%T6return1XC*)*)(%T6return1XC* [[X]])
diff --git a/test/DebugInfo/shadow_copies.swift b/test/DebugInfo/shadow_copies.swift
index 044d8c8..af42117 100644
--- a/test/DebugInfo/shadow_copies.swift
+++ b/test/DebugInfo/shadow_copies.swift
@@ -16,7 +16,7 @@
 {
     override init (_ input : Int64)
     {
-    // CHECK: @_T0{{.*}}6ClassBCACs5Int64Vcfc
+    // CHECK: @_T0{{.*}}6ClassBCyACs5Int64Vcfc
     // CHECK:  alloca {{.*}}ClassBC*
     // CHECK:  alloca i64
     // CHECK-NOT: alloca
diff --git a/test/DebugInfo/specialization.swift b/test/DebugInfo/specialization.swift
index 8e11390..4c2d984 100644
--- a/test/DebugInfo/specialization.swift
+++ b/test/DebugInfo/specialization.swift
@@ -1,6 +1,6 @@
 // RUN: %target-swift-frontend -O %s -disable-llvm-optzns -emit-sil -g -o - | %FileCheck %s
 
-// CHECK: sil shared [noinline] @_T014specialization3sumxx_xtAA5ProtoRzlFAA7AddableV_Tg5
+// CHECK: sil shared [noinline] @_T014specialization3sumyxx_xtAA5ProtoRzlFAA7AddableV_Tg5
 // CHECK-SAME: $@convention(thin) (Addable, Addable) -> Addable {
 // CHECK: bb0(%0 : $Addable, %1 : $Addable):
 // CHECK:  debug_value %0 : $Addable, let, name "i", argno 1
diff --git a/test/DebugInfo/test-foundation.swift b/test/DebugInfo/test-foundation.swift
index d5d186f..6d99b70 100644
--- a/test/DebugInfo/test-foundation.swift
+++ b/test/DebugInfo/test-foundation.swift
@@ -53,10 +53,10 @@
 
 // LOC-CHECK: define {{.*}}4date
 public func date() {
-  // LOC-CHECK: call {{.*}} @_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC{{.*}}, !dbg ![[L1:.*]]
+  // LOC-CHECK: call {{.*}} @_T0SS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC{{.*}}, !dbg ![[L1:.*]]
   let d1 = DateFormatter()
   d1.dateFormat = "dd. mm. yyyy" // LOC-CHECK: call{{.*}}objc_msgSend{{.*}}, !dbg ![[L2:.*]]
-  // LOC-CHECK: call {{.*}} @_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC{{.*}}, !dbg ![[L3:.*]]
+  // LOC-CHECK: call {{.*}} @_T0SS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC{{.*}}, !dbg ![[L3:.*]]
   let d2 = DateFormatter()
   d2.dateFormat = "mm dd yyyy" // LOC-CHECK: call{{.*}}objc_msgSend{{.*}}, !dbg ![[L4:.*]]
 }
diff --git a/test/Demangle/Inputs/manglings.txt b/test/Demangle/Inputs/manglings.txt
index 6271e48..22607e4 100644
--- a/test/Demangle/Inputs/manglings.txt
+++ b/test/Demangle/Inputs/manglings.txt
@@ -80,14 +80,14 @@
 _TFC3foo3bar3basfT3zimCS_3zim_T_ ---> foo.bar.bas(zim: foo.zim) -> ()
 _TToFC3foo3bar3basfT3zimCS_3zim_T_ ---> {T:_TFC3foo3bar3basfT3zimCS_3zim_T_,C} @objc foo.bar.bas(zim: foo.zim) -> ()
 _TTOFSC3fooFTSdSd_Sd ---> {T:_TFSC3fooFTSdSd_Sd} @nonobjc __C.foo(Swift.Double, Swift.Double) -> Swift.Double
-_T03foo3barC3basyAA3zimCAE_tFTo ---> {T:_T03foo3barC3basyAA3zimCAE_tF,C} @objc foo.bar.bas(zim: foo.zim) -> ()
-_T0SC3fooS2d_SdtFTO ---> {T:_T0SC3fooS2d_SdtF} @nonobjc __C.foo(Swift.Double, Swift.Double) -> Swift.Double
-__$S3foo3barC3basyAA3zimCAE_tFTo ---> {T:_$S3foo3barC3basyAA3zimCAE_tF,C} @objc foo.bar.bas(zim: foo.zim) -> ()
-__$SSC3fooS2d_SdtFTO ---> {T:_$SSC3fooS2d_SdtF} @nonobjc __C.foo(Swift.Double, Swift.Double) -> Swift.Double
-_$S3foo3barC3basyAA3zimCAE_tFTo ---> {T:_$S3foo3barC3basyAA3zimCAE_tF,C} @objc foo.bar.bas(zim: foo.zim) -> ()
-_$SSC3fooS2d_SdtFTO ---> {T:_$SSC3fooS2d_SdtF} @nonobjc __C.foo(Swift.Double, Swift.Double) -> Swift.Double
-$S3foo3barC3basyAA3zimCAE_tFTo ---> {T:$S3foo3barC3basyAA3zimCAE_tF,C} @objc foo.bar.bas(zim: foo.zim) -> ()
-$SSC3fooS2d_SdtFTO ---> {T:$SSC3fooS2d_SdtF} @nonobjc __C.foo(Swift.Double, Swift.Double) -> Swift.Double
+_T03foo3barC3bas3zimyAaEC_tFTo ---> {T:_T03foo3barC3bas3zimyAaEC_tF,C} @objc foo.bar.bas(zim: foo.zim) -> ()
+_T0SC3fooyS2d_SdtFTO ---> {T:_T0SC3fooyS2d_SdtF} @nonobjc __C.foo(Swift.Double, Swift.Double) -> Swift.Double
+__$S3foo3barC3bas3zimyAaEC_tFTo ---> {T:_$S3foo3barC3bas3zimyAaEC_tF,C} @objc foo.bar.bas(zim: foo.zim) -> ()
+__$SSC3fooyS2d_SdtFTO ---> {T:_$SSC3fooyS2d_SdtF} @nonobjc __C.foo(Swift.Double, Swift.Double) -> Swift.Double
+_$S3foo3barC3bas3zimyAaEC_tFTo ---> {T:_$S3foo3barC3bas3zimyAaEC_tF,C} @objc foo.bar.bas(zim: foo.zim) -> ()
+_$SSC3fooyS2d_SdtFTO ---> {T:_$SSC3fooyS2d_SdtF} @nonobjc __C.foo(Swift.Double, Swift.Double) -> Swift.Double
+$S3foo3barC3bas3zimyAaEC_tFTo ---> {T:$S3foo3barC3bas3zimyAaEC_tF,C} @objc foo.bar.bas(zim: foo.zim) -> ()
+$SSC3fooyS2d_SdtFTO ---> {T:$SSC3fooyS2d_SdtF} @nonobjc __C.foo(Swift.Double, Swift.Double) -> Swift.Double
 _TTDFC3foo3bar3basfT3zimCS_3zim_T_ ---> dynamic foo.bar.bas(zim: foo.zim) -> ()
 _TFC3foo3bar3basfT3zimCS_3zim_T_ ---> foo.bar.bas(zim: foo.zim) -> ()
 _TF3foooi1pFTCS_3barVS_3bas_OS_3zim ---> foo.+ infix(foo.bar, foo.bas) -> foo.zim
@@ -246,36 +246,36 @@
 _TFVFE15nested_genericsSS3fooFT_T_L_6CheeseCfT8materialx_GS0_x_ ---> init(material: A) -> Cheese #1 in (extension in nested_generics):Swift.String.foo() -> ()<A> in Cheese #1 in (extension in nested_generics):Swift.String.foo() -> ()
 _TTWOE5imojiCSo5Imoji14ImojiMatchRankS_9RankValueS_FS2_g9rankValueqq_Ss16RawRepresentable8RawValue ---> _TTWOE5imojiCSo5Imoji14ImojiMatchRankS_9RankValueS_FS2_g9rankValueqq_Ss16RawRepresentable8RawValue
 _TtFzas4VoidGC16FusionXBaseUtils6FutureQq_ZFVS_7Futures6futureurFFzT_GS0_x_GS0_x__ ---> _TtFzas4VoidGC16FusionXBaseUtils6FutureQq_ZFVS_7Futures6futureurFFzT_GS0_x_GS0_x__
-_T0s17MutableCollectionP1asAARzs012RandomAccessB0RzsAA11SubSequences013BidirectionalB0PRpzsAdHRQlE06rotatecD05Indexs01_A9IndexablePQzAM15shiftingToStart_tFAJs01_J4BasePQzAQcfU_ ---> closure #1 (A.Index) -> A.Index in (extension in a):Swift.MutableCollection<A where A: Swift.MutableCollection, A: Swift.RandomAccessCollection, A.SubSequence: Swift.MutableCollection, A.SubSequence: Swift.RandomAccessCollection>.rotateRandomAccess(shiftingToStart: A.Index) -> A.Index
+_T0s17MutableCollectionP1asAARzs012RandomAccessB0RzsAA11SubSequences013BidirectionalB0PRpzsAdHRQlE06rotatecD015shiftingToStart5Indexs01_A9IndexablePQzAN_tFAKs01_M4BasePQzAQcfU_ ---> closure #1 (A.Index) -> A.Index in (extension in a):Swift.MutableCollection<A where A: Swift.MutableCollection, A: Swift.RandomAccessCollection, A.SubSequence: Swift.MutableCollection, A.SubSequence: Swift.RandomAccessCollection>.rotateRandomAccess(shiftingToStart: A.Index) -> A.Index
 _T03foo4_123ABTf3psbpsb_n ---> function signature specialization <Arg[0] = [Constant Propagated String : u8'123'], Arg[1] = [Constant Propagated String : u8'123']> of foo
-_T04main5innerys5Int32Vz_yADctF25closure_with_box_argumentxz_Bi32__lXXTf1nc_n ---> function signature specialization <Arg[1] = [Closure Propagated : closure_with_box_argument, Argument Types : [<A> { var A } <Builtin.Int32>]> of main.inner(inout Swift.Int32, (Swift.Int32) -> ()) -> ()
-_T03foo6testityyyc_yyctF1a1bTf3pfpf_n ---> function signature specialization <Arg[0] = [Constant Propagated Function : a], Arg[1] = [Constant Propagated Function : b]> of foo.testit(() -> (), () -> ()) -> ()
+_T04main5inneryys5Int32Vz_yADctF25closure_with_box_argumentxz_Bi32__lXXTf1nc_n ---> function signature specialization <Arg[1] = [Closure Propagated : closure_with_box_argument, Argument Types : [<A> { var A } <Builtin.Int32>]> of main.inner(inout Swift.Int32, (Swift.Int32) -> ()) -> ()
+_T03foo6testityyyyc_yyctF1a1bTf3pfpf_n ---> function signature specialization <Arg[0] = [Constant Propagated Function : a], Arg[1] = [Constant Propagated Function : b]> of foo.testit(() -> (), () -> ()) -> ()
 _SocketJoinOrLeaveMulticast ---> _SocketJoinOrLeaveMulticast
-_T0s10DictionaryV3t17E6Index2V1loiSbAEyxq__G_AGtFZ ---> static (extension in t17):Swift.Dictionary.Index2.< infix((extension in t17):[A : B].Index2, (extension in t17):[A : B].Index2) -> Swift.Bool
-_T08mangling14varargsVsArrayySi3arrd_SS1ntF ---> mangling.varargsVsArray(arr: Swift.Int..., n: Swift.String) -> ()
-_T08mangling14varargsVsArrayySaySiG3arr_SS1ntF ---> mangling.varargsVsArray(arr: [Swift.Int], n: Swift.String) -> ()
-_T08mangling14varargsVsArrayySaySiG3arrd_SS1ntF ---> mangling.varargsVsArray(arr: [Swift.Int]..., n: Swift.String) -> ()
-_T08mangling14varargsVsArrayySi3arrd_tF ---> mangling.varargsVsArray(arr: Swift.Int...) -> ()
-_T08mangling14varargsVsArrayySaySiG3arrd_tF ---> mangling.varargsVsArray(arr: [Swift.Int]...) -> ()
+_T0s10DictionaryV3t17E6Index2V1loiySbAEyxq__G_AGtFZ ---> static (extension in t17):Swift.Dictionary.Index2.< infix((extension in t17):[A : B].Index2, (extension in t17):[A : B].Index2) -> Swift.Bool
+_T08mangling14varargsVsArray3arr1nySid_SStF ---> mangling.varargsVsArray(arr: Swift.Int..., n: Swift.String) -> ()
+_T08mangling14varargsVsArray3arr1nySaySiG_SStF ---> mangling.varargsVsArray(arr: [Swift.Int], n: Swift.String) -> ()
+_T08mangling14varargsVsArray3arr1nySaySiGd_SStF ---> mangling.varargsVsArray(arr: [Swift.Int]..., n: Swift.String) -> ()
+_T08mangling14varargsVsArray3arrySid_tF ---> mangling.varargsVsArray(arr: Swift.Int...) -> ()
+_T08mangling14varargsVsArray3arrySaySiGd_tF ---> mangling.varargsVsArray(arr: [Swift.Int]...) -> ()
 _T0s13_UnicodeViewsVss22RandomAccessCollectionRzs0A8EncodingR_11SubSequence_5IndexQZAFRtzsAcERpzAE_AEQZAIRSs15UnsignedInteger8Iterator_7ElementRPzAE_AlMQZANRS13EncodedScalar_AlMQY_AORSr0_lE13CharacterViewVyxq__G ---> (extension in Swift):Swift._UnicodeViews<A, B><A, B where A: Swift.RandomAccessCollection, B: Swift.UnicodeEncoding, A.Index == A.SubSequence.Index, A.SubSequence: Swift.RandomAccessCollection, A.SubSequence == A.SubSequence.SubSequence, A.Iterator.Element: Swift.UnsignedInteger, A.Iterator.Element == A.SubSequence.Iterator.Element, A.SubSequence.Iterator.Element == B.EncodedScalar.Iterator.Element>.CharacterView
-_T010Foundation11MeasurementV12SimulatorKitSo9UnitAngleCRszlE11OrientationO2eeoiSbAcDEAGOyAF_G_AKtFZ ---> static (extension in SimulatorKit):Foundation.Measurement<A where A == __ObjC.UnitAngle>.Orientation.== infix((extension in SimulatorKit):Foundation.Measurement<__ObjC.UnitAngle>.Orientation, (extension in SimulatorKit):Foundation.Measurement<__ObjC.UnitAngle>.Orientation) -> Swift.Bool
+_T010Foundation11MeasurementV12SimulatorKitSo9UnitAngleCRszlE11OrientationO2eeoiySbAcDEAGOyAF_G_AKtFZ ---> static (extension in SimulatorKit):Foundation.Measurement<A where A == __ObjC.UnitAngle>.Orientation.== infix((extension in SimulatorKit):Foundation.Measurement<__ObjC.UnitAngle>.Orientation, (extension in SimulatorKit):Foundation.Measurement<__ObjC.UnitAngle>.Orientation) -> Swift.Bool
 _T04main1_yyF ---> main._() -> ()
-_T04test6testitSiyt_tF ---> test.testit(()) -> Swift.Int
+_T04test6testitySiyt_tF ---> test.testit(()) -> Swift.Int
 _T08_ElementQzSbs5Error_pIxxdzo_ABSbsAC_pIxidzo_s26RangeReplaceableCollectionRzABRLClTR ---> {T:} reabstraction thunk helper <A where A: Swift.RangeReplaceableCollection, A._Element: AnyObject> from @callee_owned (@owned A._Element) -> (@unowned Swift.Bool, @error @owned Swift.Error) to @callee_owned (@in A._Element) -> (@unowned Swift.Bool, @error @owned Swift.Error)
 _T0Ix_IyB_Tr ---> {T:} reabstraction thunk from @callee_owned () -> () to @callee_unowned @convention(block) () -> ()
 _T0Rml ---> _T0Rml
 _T0Tk ---> _T0Tk
 _T0A8 ---> _T0A8
 _T0s30ReversedRandomAccessCollectionVyxGTfq3nnpf_nTfq1cn_nTfq4x_n ---> _T0s30ReversedRandomAccessCollectionVyxGTfq3nnpf_nTfq1cn_nTfq4x_n
-_T03abc6testitySiFTm ---> merged abc.testit(Swift.Int) -> ()
-_T04main4TestCACSi1x_tc6_PRIV_Llfc ---> main.Test.(in _PRIV_).init(x: Swift.Int) -> main.Test
+_T03abc6testityySiFTm ---> merged abc.testit(Swift.Int) -> ()
+_T04main4TestC1xACSi_tc6_PRIV_Llfc ---> main.Test.(in _PRIV_).init(x: Swift.Int) -> main.Test
 _T0SqWy.17 ---> outlined copy of Swift.Optional with unmangled suffix ".17"
 _T03nix6testitSaySiGyFTv_ ---> outlined variable #0 of nix.testit() -> [Swift.Int]
 _T03nix6testitSaySiGyFTv0_ ---> outlined variable #1 of nix.testit() -> [Swift.Int]
 _T0So11UITextFieldC4textSSSgvgToTepb_ ---> outlined bridged method (pb) of @objc __ObjC.UITextField.text.getter : Swift.String?
 _T0So11UITextFieldC4textSSSgvgToTeab_ ---> outlined bridged method (ab) of @objc __ObjC.UITextField.text.getter : Swift.String?
-_T0So5GizmoC11doSomethingSQyypGSQySaySSGGFToTembnn_ ---> outlined bridged method (mbnn) of @objc __ObjC.Gizmo.doSomething([Swift.String]!) -> Any!
-_T0So5GizmoC12modifyStringSQySSGAD_Si10withNumberSQyypG0D6FoobartFToTembnnnb_ ---> outlined bridged method (mbnnnb) of @objc __ObjC.Gizmo.modifyString(Swift.String!, withNumber: Swift.Int, withFoobar: Any!) -> Swift.String!
+_T0So5GizmoC11doSomethingySQyypGSQySaySSGGFToTembnn_ ---> outlined bridged method (mbnn) of @objc __ObjC.Gizmo.doSomething([Swift.String]!) -> Any!
+_T0So5GizmoC12modifyString_10withNumber0D6FoobarSQySSGAF_SiSQyypGtFToTembnnnb_ ---> outlined bridged method (mbnnnb) of @objc __ObjC.Gizmo.modifyString(_: Swift.String!, withNumber: Swift.Int, withFoobar: Any!) -> Swift.String!
 _T04test1SVyxGAA1RA2A1ZRzAA1Y2ZZRpzl1A_AhaGPWT ---> {C} associated type witness table accessor for A.ZZ : test.Y in <A where A: test.Z, A.ZZ: test.Y> test.S<A> : test.R in test
 _T0s24_UnicodeScalarExceptions33_0E4228093681F6920F0AB2E48B4F1C69LLVACycfC ---> Swift.(_UnicodeScalarExceptions in _0E4228093681F6920F0AB2E48B4F1C69).init() -> Swift.(_UnicodeScalarExceptions in _0E4228093681F6920F0AB2E48B4F1C69)
 
diff --git a/test/Demangle/Inputs/simplified-manglings.txt b/test/Demangle/Inputs/simplified-manglings.txt
index bc3a520..38d11e3 100644
--- a/test/Demangle/Inputs/simplified-manglings.txt
+++ b/test/Demangle/Inputs/simplified-manglings.txt
@@ -203,5 +203,5 @@
 _TTRXFo_oCSo13SKPhysicsBodydVSC7CGPointdVSC8CGVectordGSpV10ObjectiveC8ObjCBool___XFdCb_dS_dS0_dS1_dGSpS3____ ---> thunk for @callee_owned (@owned SKPhysicsBody, @unowned CGPoint, @unowned CGVector, @unowned UnsafeMutablePointer<ObjCBool>) -> ()
 _T0So13SKPhysicsBodyCSC7CGPointVSC8CGVectorVSpy10ObjectiveC8ObjCBoolVGIxxyyy_AbdFSpyAIGIyByyyy_TR ---> thunk for @callee_owned (@owned SKPhysicsBody, @unowned CGPoint, @unowned CGVector, @unowned UnsafeMutablePointer<ObjCBool>) -> ()
 _T04main1_yyF ---> _()
-_T03abc6testitySiFTm ---> testit(_:)
-_T04main4TestCACSi1x_tc6_PRIV_Llfc ---> Test.init(x:)
+_T03abc6testityySiFTm ---> testit(_:)
+_T04main4TestC1xACSi_tc6_PRIV_Llfc ---> Test.init(x:)
diff --git a/test/Driver/options.swift b/test/Driver/options.swift
index ea1cbb5..e9807c4 100644
--- a/test/Driver/options.swift
+++ b/test/Driver/options.swift
@@ -4,9 +4,13 @@
 // NO_FILES: this mode requires at least one input file
 
 // RUN: not %target-swift-frontend -parse-sil -emit-sil 2>&1 | %FileCheck -check-prefix=SIL_FILES %s
-// RUN: not %target-swift-frontend -parse-sil -emit-sil %s %s 2>&1 | %FileCheck -check-prefix=SIL_FILES %s
 // SIL_FILES: this mode requires a single input file
 
+// RUN: not %target-swift-frontend -parse-sil -emit-sil %s %s 2>&1 | %FileCheck -check-prefix=DUPLICATE_FILES %s
+// RUN: not %target-swift-frontend -parse-sil -emit-sil %s %S/../Inputs/empty.swift 2>&1 | %FileCheck -check-prefix=SIL_FILES %s
+// DUPLICATE_FILES: duplicate input file 'SOURCE_DIR/test/Driver/options.swift'
+
+
 // RUN: not %target-swift-frontend -emit-silgen -parse-as-library %S/Inputs/invalid-module-name.swift 2>&1 | %FileCheck -check-prefix=INVALID_MODULE_NAME %s
 // INVALID_MODULE_NAME: error: module name "invalid-module-name" is not a valid identifier; use -module-name flag to specify an alternate name
 
diff --git a/test/Frontend/InternalChecks.swift b/test/Frontend/InternalChecks.swift
index f11284a..4cbb2c7 100644
--- a/test/Frontend/InternalChecks.swift
+++ b/test/Frontend/InternalChecks.swift
@@ -10,8 +10,8 @@
   return x + y
 }
 
-// CHECKS-LABEL: _T014InternalChecks27test_internal_checks_configS2i_SitF
+// CHECKS-LABEL: _T014InternalChecks27test_internal_checks_configyS2i_SitF
 // CHECKS: "internal check emitted"
 
-// NOCHECKS-LABEL: _T014InternalChecks27test_internal_checks_configS2i_SitF
+// NOCHECKS-LABEL: _T014InternalChecks27test_internal_checks_configyS2i_SitF
 // NOCHECKS-NOT: "internal check emitted"
diff --git a/test/Frontend/OptimizationOptions-with-stdlib-checks.swift b/test/Frontend/OptimizationOptions-with-stdlib-checks.swift
index 6b4298a..1ed2fe1 100644
--- a/test/Frontend/OptimizationOptions-with-stdlib-checks.swift
+++ b/test/Frontend/OptimizationOptions-with-stdlib-checks.swift
@@ -29,56 +29,56 @@
 }
 
 // In debug mode keep user asserts and runtime checks.
-// DEBUG-LABEL: sil hidden @_T019OptimizationOptions11test_assertS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// DEBUG-LABEL: sil hidden @_T019OptimizationOptions11test_assert1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // DEBUG-DAG: string_literal utf8 "x smaller than y"
 // DEBUG-DAG: string_literal utf8 "Assertion failed"
 // DEBUG-DAG: cond_fail
 // DEBUG: return
 
 // In playground mode keep user asserts and runtime checks.
-// PLAYGROUND-LABEL: sil hidden @_T019OptimizationOptions11test_assertS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// PLAYGROUND-LABEL: sil hidden @_T019OptimizationOptions11test_assert1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // PLAYGROUND-DAG: "Assertion failed"
 // PLAYGROUND-DAG: "x smaller than y"
 // PLAYGROUND-DAG: cond_fail
 // PLAYGROUND: return
 
 // In release mode remove user asserts and keep runtime checks.
-// RELEASE-LABEL: sil hidden @_T019OptimizationOptions11test_assertS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// RELEASE-LABEL: sil hidden @_T019OptimizationOptions11test_assert1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // RELEASE-NOT: "x smaller than y"
 // RELEASE-NOT: "Assertion failed"
 // RELEASE: cond_fail
 // RELEASE: return
 
 // In fast mode remove user asserts and runtime checks.
-// FAST-LABEL: sil hidden @_T019OptimizationOptions11test_assertS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// FAST-LABEL: sil hidden @_T019OptimizationOptions11test_assert1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // FAST-NOT: "x smaller than y"
 // FAST-NOT: "Assertion failed"
 // FAST-NOT: cond_fail
 
 
 // In debug mode keep verbose fatal errors.
-// DEBUG-LABEL: sil hidden @_T019OptimizationOptions10test_fatalS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// DEBUG-LABEL: sil hidden @_T019OptimizationOptions10test_fatal1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // DEBUG-DAG: "Human nature ..."
 // DEBUG-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC:.*fatalErrorMessage.*]] : $@convention(thin)
 // DEBUG: apply %[[FATAL_ERROR]]{{.*}}
 // DEBUG: unreachable
 
 // In playground mode keep verbose fatal errors.
-// PLAYGROUND-LABEL: sil hidden @_T019OptimizationOptions10test_fatalS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// PLAYGROUND-LABEL: sil hidden @_T019OptimizationOptions10test_fatal1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // PLAYGROUND-DAG: "Human nature ..."
 // PLAYGROUND-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC:.*fatalErrorMessage.*]] : $@convention(thin)
 // PLAYGROUND: apply %[[FATAL_ERROR]]{{.*}}
 // PLAYGROUND: unreachable
 
 // In release mode keep succinct fatal errors (trap).
-// RELEASE-LABEL: sil hidden @_T019OptimizationOptions10test_fatalS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// RELEASE-LABEL: sil hidden @_T019OptimizationOptions10test_fatal1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // RELEASE-NOT: "Human nature ..."
 // RELEASE-NOT: "Fatal error"
 // RELEASE: cond_fail
 // RELEASE: return
 
 // In fast mode remove fatal errors.
-// FAST-LABEL: sil hidden @_T019OptimizationOptions10test_fatalS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// FAST-LABEL: sil hidden @_T019OptimizationOptions10test_fatal1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // FAST-NOT: "Human nature ..."
 // FAST-NOT: "Fatal error"
 // FAST-NOT: int_trap
@@ -86,7 +86,7 @@
 // Precondition safety checks.
 
 // In debug mode keep verbose library precondition checks.
-// DEBUG-LABEL: sil hidden @_T019OptimizationOptions23test_precondition_checkS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// DEBUG-LABEL: sil hidden @_T019OptimizationOptions23test_precondition_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // DEBUG-DAG: "Fatal error"
 // DEBUG-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC]]
 // DEBUG: apply %[[FATAL_ERROR]]{{.*}}
@@ -94,7 +94,7 @@
 // DEBUG: return
 
 // In playground mode keep verbose library precondition checks.
-// PLAYGROUND-LABEL: sil hidden @_T019OptimizationOptions23test_precondition_checkS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// PLAYGROUND-LABEL: sil hidden @_T019OptimizationOptions23test_precondition_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // PLAYGROUND-DAG: "Fatal error"
 // PLAYGROUND-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC]]
 // PLAYGROUND: apply %[[FATAL_ERROR]]{{.*}}
@@ -102,14 +102,14 @@
 // PLAYGROUND: return
 
 // In release mode keep succinct library precondition checks (trap).
-// RELEASE-LABEL: sil hidden @_T019OptimizationOptions23test_precondition_checkS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// RELEASE-LABEL: sil hidden @_T019OptimizationOptions23test_precondition_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // RELEASE-NOT:  "Fatal error"
 // RELEASE:  %[[V2:.+]] = builtin "xor_Int1"(%{{.+}}, %{{.+}})
 // RELEASE:  cond_fail %[[V2]]
 // RELEASE:  return
 
 // In unchecked mode remove library precondition checks.
-// UNCHECKED-LABEL: sil hidden @_T019OptimizationOptions23test_precondition_checkS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// UNCHECKED-LABEL: sil hidden @_T019OptimizationOptions23test_precondition_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // UNCHECKED-NOT:  "Fatal error"
 // UNCHECKED-NOT:  builtin "int_trap"
 // UNCHECKED-NOT:  unreachable
@@ -118,28 +118,28 @@
 //  Partial safety checks.
 
 // In debug mode keep verbose partial safety checks.
-// DEBUG-LABEL: sil hidden @_T019OptimizationOptions25test_partial_safety_checkS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// DEBUG-LABEL: sil hidden @_T019OptimizationOptions25test_partial_safety_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // DEBUG-DAG: "Fatal error"
 // DEBUG-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC]]
 // DEBUG: apply %[[FATAL_ERROR]]{{.*}}
 // DEBUG: unreachable
 
 // In playground mode keep verbose partial safety checks.
-// PLAYGROUND-LABEL: sil hidden @_T019OptimizationOptions25test_partial_safety_checkS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// PLAYGROUND-LABEL: sil hidden @_T019OptimizationOptions25test_partial_safety_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // PLAYGROUND-DAG: "Fatal error"
 // PLAYGROUND-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC]]
 // PLAYGROUND: apply %[[FATAL_ERROR]]{{.*}}
 // PLAYGROUND: unreachable
 
 // In release mode remove partial safety checks.
-// RELEASE-LABEL: sil hidden @_T019OptimizationOptions25test_partial_safety_checkS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// RELEASE-LABEL: sil hidden @_T019OptimizationOptions25test_partial_safety_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // RELEASE-NOT:  "Fatal error"
 // RELEASE-NOT:  builtin "int_trap"
 // RELEASE-NOT:  unreachable
 // RELEASE: return
 
 // In fast mode remove partial safety checks.
-// FAST-LABEL: sil hidden @_T019OptimizationOptions25test_partial_safety_checkS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// FAST-LABEL: sil hidden @_T019OptimizationOptions25test_partial_safety_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // FAST-NOT:  "Fatal error"
 // FAST-NOT:  builtin "int_trap"
 // FAST-NOT:  unreachable
diff --git a/test/Frontend/OptimizationOptions-without-stdlib-checks.swift b/test/Frontend/OptimizationOptions-without-stdlib-checks.swift
index ef5a87a..3b7fddd 100644
--- a/test/Frontend/OptimizationOptions-without-stdlib-checks.swift
+++ b/test/Frontend/OptimizationOptions-without-stdlib-checks.swift
@@ -29,54 +29,54 @@
 }
 
 // In debug mode keep user asserts and runtime checks.
-// DEBUG-LABEL: sil hidden @_T019OptimizationOptions11test_assertS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// DEBUG-LABEL: sil hidden @_T019OptimizationOptions11test_assert1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // DEBUG: "x smaller than y"
 // DEBUG: "Assertion failed"
 // DEBUG: cond_fail
 // DEBUG: return
 
 // In playground mode keep user asserts and runtime checks.
-// PLAYGROUND-LABEL: sil hidden @_T019OptimizationOptions11test_assertS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// PLAYGROUND-LABEL: sil hidden @_T019OptimizationOptions11test_assert1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // PLAYGROUND: "x smaller than y"
 // PLAYGROUND: "Assertion failed"
 // PLAYGROUND: cond_fail
 
 // In release mode remove user asserts and keep runtime checks.
-// RELEASE-LABEL: sil hidden @_T019OptimizationOptions11test_assertS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// RELEASE-LABEL: sil hidden @_T019OptimizationOptions11test_assert1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // RELEASE-NOT: "x smaller than y"
 // RELEASE-NOT: "Assertion failed"
 // RELEASE: cond_fail
 
 // In fast mode remove user asserts and runtime checks.
-// FAST-LABEL: sil hidden @_T019OptimizationOptions11test_assertS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// FAST-LABEL: sil hidden @_T019OptimizationOptions11test_assert1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // FAST-NOT: "x smaller than y"
 // FAST-NOT: "Assertion failed"
 // FAST-NOT: cond_fail
 
 
 // In debug mode keep verbose fatal errors.
-// DEBUG-LABEL: sil hidden @_T019OptimizationOptions10test_fatalS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// DEBUG-LABEL: sil hidden @_T019OptimizationOptions10test_fatal1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // DEBUG-DAG: "Human nature ..."
 // DEBUG-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC:.*fatalErrorMessage.*]] : $@convention(thin)
 // DEBUG: apply %[[FATAL_ERROR]]({{.*}})
 // DEBUG: unreachable
 
 // In playground mode keep verbose fatal errors.
-// PLAYGROUND-LABEL: sil hidden @_T019OptimizationOptions10test_fatalS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// PLAYGROUND-LABEL: sil hidden @_T019OptimizationOptions10test_fatal1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // PLAYGROUND-DAG: "Human nature ..."
 // PLAYGROUND-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC:.*fatalErrorMessage.*]] : $@convention(thin)
 // PLAYGROUND: apply %[[FATAL_ERROR]]({{.*}})
 // PLAYGROUND: unreachable
 
 // In release mode keep succinct fatal errors (trap).
-// RELEASE-LABEL: sil hidden @_T019OptimizationOptions10test_fatalS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// RELEASE-LABEL: sil hidden @_T019OptimizationOptions10test_fatal1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // RELEASE-NOT: "Human nature ..."
 // RELEASE-NOT: "Fatal error"
 // RELEASE: cond_fail
 // RELEASE: return
 
 // In fast mode remove fatal errors.
-// FAST-LABEL: sil hidden @_T019OptimizationOptions10test_fatalS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// FAST-LABEL: sil hidden @_T019OptimizationOptions10test_fatal1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // FAST-NOT: "Human nature ..."
 // FAST-NOT: "Fatal error"
 // FAST-NOT: int_trap
@@ -84,7 +84,7 @@
 // Precondition safety checks.
 
 // In debug mode keep verbose library precondition checks.
-// DEBUG-LABEL: sil hidden @_T019OptimizationOptions23test_precondition_checkS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// DEBUG-LABEL: sil hidden @_T019OptimizationOptions23test_precondition_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // DEBUG-DAG: "Fatal error"
 // DEBUG-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC]]
 // DEBUG: apply %[[FATAL_ERROR]]({{.*}})
@@ -92,7 +92,7 @@
 // DEBUG: return
 
 // In playground mode keep verbose library precondition checks.
-// PLAYGROUND-LABEL: sil hidden @_T019OptimizationOptions23test_precondition_checkS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// PLAYGROUND-LABEL: sil hidden @_T019OptimizationOptions23test_precondition_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // PLAYGROUND-DAG: "Fatal error"
 // PLAYGROUND-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC]]
 // PLAYGROUND: apply %[[FATAL_ERROR]]({{.*}})
@@ -100,14 +100,14 @@
 // PLAYGROUND: return
 
 // In release mode keep succinct library precondition checks (trap).
-// RELEASE-LABEL: sil hidden @_T019OptimizationOptions23test_precondition_checkS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// RELEASE-LABEL: sil hidden @_T019OptimizationOptions23test_precondition_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // RELEASE-NOT:  "Fatal error"
 // RELEASE:  %[[V2:.+]] = builtin "xor_Int1"(%{{.+}}, %{{.+}})
 // RELEASE:  cond_fail %[[V2]]
 // RELEASE:  return
 
 // In unchecked mode remove library precondition checks.
-// UNCHECKED-LABEL: sil hidden @_T019OptimizationOptions23test_precondition_checkS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// UNCHECKED-LABEL: sil hidden @_T019OptimizationOptions23test_precondition_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // UNCHECKED-NOT:  "Fatal error"
 // UNCHECKED-NOT:  builtin "int_trap"
 // UNCHECKED-NOT:  unreachable
@@ -116,28 +116,28 @@
 //  Partial safety checks.
 
 // In debug mode keep verbose partial safety checks.
-// DEBUG-LABEL: sil hidden @_T019OptimizationOptions25test_partial_safety_checkS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// DEBUG-LABEL: sil hidden @_T019OptimizationOptions25test_partial_safety_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // DEBUG-DAG: "Fatal error"
 // DEBUG-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC]]
 // DEBUG: apply %[[FATAL_ERROR]]({{.*}})
 // DEBUG: unreachable
 
 // In playground mode keep verbose partial safety checks.
-// PLAYGROUND-LABEL: sil hidden @_T019OptimizationOptions25test_partial_safety_checkS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// PLAYGROUND-LABEL: sil hidden @_T019OptimizationOptions25test_partial_safety_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // PLAYGROUND-DAG: "Fatal error"
 // PLAYGROUND-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC]]
 // PLAYGROUND: apply %[[FATAL_ERROR]]({{.*}})
 // PLAYGROUND: unreachable
 
 // In release mode remove partial safety checks.
-// RELEASE-LABEL: sil hidden @_T019OptimizationOptions25test_partial_safety_checkS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// RELEASE-LABEL: sil hidden @_T019OptimizationOptions25test_partial_safety_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // RELEASE-NOT:  "Fatal error"
 // RELEASE-NOT:  builtin "int_trap"
 // RELEASE-NOT:  unreachable
 // RELEASE: return
 
 // In fast mode remove partial safety checks.
-// FAST-LABEL: sil hidden @_T019OptimizationOptions25test_partial_safety_checkS2i1x_Si1ytF : $@convention(thin) (Int, Int) -> Int {
+// FAST-LABEL: sil hidden @_T019OptimizationOptions25test_partial_safety_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int {
 // FAST-NOT:  "Fatal error"
 // FAST-NOT:  builtin "int_trap"
 // FAST-NOT:  unreachable
diff --git a/test/Frontend/input-errors.swift b/test/Frontend/input-errors.swift
new file mode 100644
index 0000000..7f2a294
--- /dev/null
+++ b/test/Frontend/input-errors.swift
@@ -0,0 +1,5 @@
+// RUN: not %target-swift-frontend %s -filelist nonexistent 2>&1 | %FileCheck -check-prefix=CHECK-BADFILEANDFILELIST %s
+// CHECK-BADFILEANDFILELIST: error: cannot have input files with file list
+
+// RUN: not %target-swift-frontend nonexistent.swift another-nonexistent.swift nonexistent.swift 2>&1 | %FileCheck -check-prefix=CHECK-APPEARSMORETHANONCE %s
+// CHECK-APPEARSMORETHANONCE: error: duplicate input file 'nonexistent.swift'
diff --git a/test/Frontend/primary-filelist.swift b/test/Frontend/primary-filelist.swift
new file mode 100644
index 0000000..7947b28
--- /dev/null
+++ b/test/Frontend/primary-filelist.swift
@@ -0,0 +1,33 @@
+// RUN: not %target-swift-frontend -primary-filelist 2>&1 | %FileCheck -check-prefix=CHECK-EXPECTEDARGUMENT %s
+// CHECK-EXPECTEDARGUMENT: error: missing argument value for '-primary-filelist', expected 1 argument(s)
+// RUN: not %target-swift-frontend -primary-filelist nonexistant 2>&1 | %FileCheck -check-prefix=CHECK-BADFILE %s
+// CHECK-BADFILE: error: cannot open file
+
+// RUN: %empty-directory(%t)
+// RUN: echo '%S/Inputs/filelist-other.swift' >> %t/input.txt
+// RUN: echo '%s' >> %t/input.txt
+// RUN: echo '%S/../Inputs/empty.swift' >> %t/input.txt
+// RUN: echo '%s' >> %t/primary.txt
+// RUN: not %target-swift-frontend -typecheck -filelist %t/input.txt -primary-filelist %t/primary.txt 2>&1 | %FileCheck %s
+// RUN: not %target-swift-frontend -typecheck '%S/Inputs/filelist-other.swift' '%s' -primary-filelist %t/primary.txt 2>&1 | %FileCheck %s
+
+// RUN: %empty-directory(%t)
+// RUN: echo '%S/Inputs/filelist-other.swift' >> %t/input.txt
+// RUN: echo '%s' >> %t/input.txt
+// RUN: echo '%S/../Inputs/empty.swift' >> %t/primary.txt
+// RUN: echo '%s' >> %t/primary.txt
+// RUN: not %target-swift-frontend -typecheck -filelist %t/input.txt -primary-filelist %t/primary.txt 2>&1 | %FileCheck -check-prefix=CHECK-PRIMARYNOTFOUND %s
+// CHECK-PRIMARYNOTFOUND: error: primary file '{{.*}}/../Inputs/empty.swift' was not found in file list '{{.*}}/input.txt'
+
+// RUN: not %target-swift-frontend -primary-file %s -primary-filelist nonexistent 2>&1 | %FileCheck -check-prefix=CHECK-BADFILEANDFILELIST %s
+// CHECK-BADFILEANDFILELIST: error: cannot have primary input files with primary file list
+
+
+func test() {
+  #if !WORKING
+    // Check with FileCheck because we want to see that this file is being
+    // compiled.
+    // CHECK: error: cannot convert value of type 'Bar' to specified type 'Foo'
+    let x: Foo = other()
+  #endif
+}
diff --git a/test/Generics/conditional_conformances.swift b/test/Generics/conditional_conformances.swift
index c71bd0f..8c11722 100644
--- a/test/Generics/conditional_conformances.swift
+++ b/test/Generics/conditional_conformances.swift
@@ -1,5 +1,5 @@
-// RUN: %target-typecheck-verify-swift -enable-experimental-conditional-conformances -typecheck %s -verify
-// RUN: %target-typecheck-verify-swift -enable-experimental-conditional-conformances -typecheck -debug-generic-signatures %s > %t.dump 2>&1
+// RUN: %target-typecheck-verify-swift -typecheck %s -verify
+// RUN: %target-typecheck-verify-swift -typecheck -debug-generic-signatures %s > %t.dump 2>&1
 // RUN: %FileCheck %s < %t.dump
 
 protocol P1 {}
diff --git a/test/Generics/conditional_conformances_execute_smoke.swift b/test/Generics/conditional_conformances_execute_smoke.swift
index d089a42..eb2ad6f 100644
--- a/test/Generics/conditional_conformances_execute_smoke.swift
+++ b/test/Generics/conditional_conformances_execute_smoke.swift
@@ -1,6 +1,4 @@
-// RUN: %empty-directory(%t)
-// RUN: %target-build-swift -enable-experimental-conditional-conformances %s -o %t/a.out
-// RUN: %target-run %t/a.out | %FileCheck %s
+// RUN: %target-run-simple-swift | %FileCheck %s
 
 // Smoke test to see that various conditional conformances correctly execute
 
diff --git a/test/Generics/conditional_conformances_operators.swift b/test/Generics/conditional_conformances_operators.swift
index acb5fa5..91b6a54 100644
--- a/test/Generics/conditional_conformances_operators.swift
+++ b/test/Generics/conditional_conformances_operators.swift
@@ -1,4 +1,4 @@
-// RUN: %target-typecheck-verify-swift -enable-experimental-conditional-conformances -typecheck %s -verify
+// RUN: %target-typecheck-verify-swift -typecheck %s -verify
 
 // rdar://problem/35480952
 
diff --git a/test/Generics/deduction.swift b/test/Generics/deduction.swift
index 4dc2647..355c684 100644
--- a/test/Generics/deduction.swift
+++ b/test/Generics/deduction.swift
@@ -321,7 +321,7 @@
 
 infix operator +&
 func +&<R, S>(lhs: inout R, rhs: S) where R : RangeReplaceableCollection, S : Sequence, R.Element == S.Element {}
-// expected-note@-1 {{candidate requires that the types 'String' and 'String.Element' (aka 'Character') be equivalent (requirement specified as 'R.Element' == 'S.Element' [with R = [String], S = String])}}
+// expected-note@-1 {{candidate requires that the types 'String' and 'Character' be equivalent (requirement specified as 'R.Element' == 'S.Element' [with R = [String], S = String])}}
 
 func rdar33477726_1() {
   var arr: [String] = []
@@ -330,13 +330,13 @@
 }
 
 func rdar33477726_2<R, S>(_: R, _: S) where R: Sequence, S == R.Element {}
-// expected-note@-1 {{candidate requires that the types 'Int' and 'String.Element' (aka 'Character') be equivalent (requirement specified as 'S' == 'R.Element' [with R = String, S = Int])}}
+// expected-note@-1 {{candidate requires that the types 'Int' and 'Character' be equivalent (requirement specified as 'S' == 'R.Element' [with R = String, S = Int])}}
 rdar33477726_2("answer", 42)
 // expected-error@-1 {{cannot invoke 'rdar33477726_2(_:_:)' with an argument list of type '(String, Int)'}}
 
 prefix operator +-
 prefix func +-<T>(_: T) where T: Sequence, T.Element == Int {}
-// expected-note@-1 {{candidate requires that the types 'String.Element' (aka 'Character') and 'Int' be equivalent (requirement specified as 'T.Element' == 'Int' [with T = String])}}
+// expected-note@-1 {{candidate requires that the types 'Character' and 'Int' be equivalent (requirement specified as 'T.Element' == 'Int' [with T = String])}}
 
 +-"hello"
 // expected-error@-1 {{unary operator '+-(_:)' cannot be applied to an operand of type 'String'}}
diff --git a/test/Generics/requirement_inference.swift b/test/Generics/requirement_inference.swift
index dbcc3c5..811bfce 100644
--- a/test/Generics/requirement_inference.swift
+++ b/test/Generics/requirement_inference.swift
@@ -1,5 +1,5 @@
-// RUN: %target-typecheck-verify-swift -enable-experimental-conditional-conformances -typecheck %s -verify
-// RUN: %target-typecheck-verify-swift -enable-experimental-conditional-conformances -typecheck -debug-generic-signatures %s > %t.dump 2>&1 
+// RUN: %target-typecheck-verify-swift -typecheck %s -verify
+// RUN: %target-typecheck-verify-swift -typecheck -debug-generic-signatures %s > %t.dump 2>&1 
 // RUN: %FileCheck %s < %t.dump
 
 protocol P1 { 
diff --git a/test/IDE/comment_extensions.swift b/test/IDE/comment_extensions.swift
index af37e83..bf63062 100644
--- a/test/IDE/comment_extensions.swift
+++ b/test/IDE/comment_extensions.swift
@@ -25,11 +25,11 @@
 
 // CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>note()</Name><USR>s:14swift_ide_test4noteyyF</USR><Declaration>func note()</Declaration><CommentParts><Discussion><Note><Para>This function is very hip and exciting.</Para></Note></Discussion></CommentParts></Function>]
 
-// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>postcondition(_:)</Name><USR>s:14swift_ide_test13postconditionySizF</USR><Declaration>func postcondition(_ x: inout Int)</Declaration><CommentParts><Discussion><Postcondition><Para>x is unchanged</Para></Postcondition></Discussion></CommentParts></Function>]
+// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>postcondition(_:)</Name><USR>s:14swift_ide_test13postconditionyySizF</USR><Declaration>func postcondition(_ x: inout Int)</Declaration><CommentParts><Discussion><Postcondition><Para>x is unchanged</Para></Postcondition></Discussion></CommentParts></Function>]
 
 // CHECK: {{.*}}DocCommentAsXML=none
 
-// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>precondition(_:)</Name><USR>s:14swift_ide_test12preconditionySiF</USR><Declaration>func precondition(_ x: Int)</Declaration><CommentParts><Discussion><Precondition><Para><codeVoice>x &lt; 100</codeVoice></Para></Precondition></Discussion></CommentParts></Function>]
+// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>precondition(_:)</Name><USR>s:14swift_ide_test12preconditionyySiF</USR><Declaration>func precondition(_ x: Int)</Declaration><CommentParts><Discussion><Precondition><Para><codeVoice>x &lt; 100</codeVoice></Para></Precondition></Discussion></CommentParts></Function>]
 // CHECK: {{.*}}DocCommentAsXML=none
 
 // CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>remark()</Name><USR>s:14swift_ide_test6remarkyyF</USR><Declaration>func remark()</Declaration><CommentParts><Discussion><Remark><Para>Always, no, never forget to check your references.</Para></Remark></Discussion></CommentParts></Function>]
diff --git a/test/IDE/complete_after_super.swift b/test/IDE/complete_after_super.swift
index 2970079..ea38e2d 100644
--- a/test/IDE/complete_after_super.swift
+++ b/test/IDE/complete_after_super.swift
@@ -9,6 +9,9 @@
 // RUN: %FileCheck %s -check-prefix=COMMON_BASE_A_DOT < %t.super.txt
 // RUN: %FileCheck %s -check-prefix=CONSTRUCTOR_SUPER_DOT_1 < %t.super.txt
 
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CONSTRUCTOR_SUPER_INIT_1 > %t.super.txt
+// RUN: %FileCheck %s -check-prefix=CONSTRUCTOR_SUPER_INIT_1 < %t.super.txt
+
 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CONSTRUCTOR_SUPER_INIT_PAREN_1 > %t.super.txt
 // RUN: %FileCheck %s -check-prefix=CONSTRUCTOR_SUPER_INIT_PAREN_1 < %t.super.txt
 
@@ -224,10 +227,14 @@
   }
 
   init (a: Float) {
+    super.init#^CONSTRUCTOR_SUPER_INIT_1^#
+// CONSTRUCTOR_SUPER_INIT_1: Begin completions
+// CONSTRUCTOR_SUPER_INIT_1-DAG: Pattern/CurrModule: ()[#SuperBaseA#];
+// CONSTRUCTOR_SUPER_INIT_1: End completions
+  }
+  init (b: Float) {
     super.init(#^CONSTRUCTOR_SUPER_INIT_PAREN_1^#
-// CONSTRUCTOR_SUPER_INIT_PAREN_1: Begin completions
-// CONSTRUCTOR_SUPER_INIT_PAREN_1-DAG: Pattern/ExprSpecific: ['('])[#SuperBaseA#]; name=)
-// CONSTRUCTOR_SUPER_INIT_PAREN_1: End completions
+// CONSTRUCTOR_SUPER_INIT_PAREN_1-NOT: Pattern/
   }
 
   deinit {
diff --git a/test/IDE/complete_at_eof_in_call_1.swift b/test/IDE/complete_at_eof_in_call_1.swift
index e8b5bd8..a26db97 100644
--- a/test/IDE/complete_at_eof_in_call_1.swift
+++ b/test/IDE/complete_at_eof_in_call_1.swift
@@ -4,7 +4,7 @@
 // Don't add any tests at the end of the file!
 //
 // A: Begin completions
-// A-DAG: Pattern/ExprSpecific:               ['(']{#(x): Int#})[#Void#]{{; name=.+$}}
+// A-DAG: Pattern/CurrModule:               ['(']{#(x): Int#}[')'][#Void#]{{; name=.+$}}
 // A: End completions
 func f(_ x: Int) {}
 f(#^A^#
diff --git a/test/IDE/complete_at_eof_in_call_no_newline_1.swift b/test/IDE/complete_at_eof_in_call_no_newline_1.swift
index 81e7347..7ba13b8 100644
--- a/test/IDE/complete_at_eof_in_call_no_newline_1.swift
+++ b/test/IDE/complete_at_eof_in_call_no_newline_1.swift
@@ -4,7 +4,7 @@
 // Don't add any tests at the end of the file!
 //
 // A: Begin completions
-// A-DAG: Pattern/ExprSpecific:               ['(']{#(x): Int#})[#Void#]{{; name=.+$}}
+// A-DAG: Pattern/CurrModule:               ['(']{#(x): Int#}[')'][#Void#]{{; name=.+$}}
 // A: End completions
 func f(_ x: Int) {}
 f(#^A^#
\ No newline at end of file
diff --git a/test/IDE/complete_call_arg.swift b/test/IDE/complete_call_arg.swift
index 2228b91..9d4e486 100644
--- a/test/IDE/complete_call_arg.swift
+++ b/test/IDE/complete_call_arg.swift
@@ -32,7 +32,8 @@
 
 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIRST_ARG_NAME_1 | %FileCheck %s -check-prefix=FIRST_ARG_NAME_PATTERN
 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIRST_ARG_NAME_2 | %FileCheck %s -check-prefix=FIRST_ARG_NAME_PATTERN
-// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIRST_ARG_NAME_3 | %FileCheck %s -check-prefix=FIRST_ARG_NAME_3
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIRST_ARG_NAME_3 -code-complete-call-pattern-heuristics | %FileCheck %s -check-prefix=FIRST_ARG_NAME_3
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIRST_ARG_NAME_3 | %FileCheck %s -check-prefix=FIRST_ARG_NAME_4
 
 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=BOUND_GENERIC_1_1 | %FileCheck %s -check-prefix=BOUND_GENERIC_1
 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=BOUND_GENERIC_1_2 | %FileCheck %s -check-prefix=BOUND_GENERIC_1
@@ -342,8 +343,7 @@
 func testArg1Name1() {
   firstArg(#^FIRST_ARG_NAME_1^#
 }
-// Skip the RParen, since it will be annotated in the second test.
-// FIRST_ARG_NAME_PATTERN: ['(']{#arg1: Int#}, {#arg2: Int#}
+// FIRST_ARG_NAME_PATTERN: ['(']{#arg1: Int#}, {#arg2: Int#}[')']
 func testArg2Name1() {
   firstArg(#^FIRST_ARG_NAME_2^#)
 }
@@ -352,6 +352,7 @@
   firstArg(#^FIRST_ARG_NAME_3^#,
 }
 // FIRST_ARG_NAME_3: Keyword/ExprSpecific: arg1: [#Argument name#]
+// FIRST_ARG_NAME_4: Pattern/CurrModule: ['(']{#arg1: Int#}, {#arg2: Int#}[')'][#Void#];
 
 func takeArray<T>(_ x: [T]) {}
 struct TestBoundGeneric1 {
diff --git a/test/IDE/complete_constructor.swift b/test/IDE/complete_constructor.swift
index 7d1190a..820c35f 100644
--- a/test/IDE/complete_constructor.swift
+++ b/test/IDE/complete_constructor.swift
@@ -24,7 +24,8 @@
 
 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=HAVE_RPAREN_1 | %FileCheck %s -check-prefix=HAVE_RPAREN_1
 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=HAVE_RPAREN_2 | %FileCheck %s -check-prefix=HAVE_RPAREN_2
-// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=HAVE_COMMA_1 | %FileCheck %s -check-prefix=HAVE_COMMA_1
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=HAVE_COMMA_1 -code-complete-call-pattern-heuristics | %FileCheck %s -check-prefix=HAVE_COMMA_1
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=HAVE_COMMA_1 | %FileCheck %s -check-prefix=EXPLICIT_CONSTRUCTORS_1P
 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=WITH_ALIAS_1 | %FileCheck %s -check-prefix=WITH_ALIAS_1
 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CLOSURE_IN_INIT_1 | %FileCheck %s -check-prefix=CLOSURE_IN_INIT_1
 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CLOSURE_IN_INIT_2 | %FileCheck %s -check-prefix=CLOSURE_IN_INIT_1
@@ -48,9 +49,7 @@
 }
 func testImplicitConstructors1P() {
   ImplicitConstructors1(#^IMPLICIT_CONSTRUCTORS_1P^#
-// IMPLICIT_CONSTRUCTORS_1P: Begin completions
-// IMPLICIT_CONSTRUCTORS_1P-NEXT: Decl[Constructor]/CurrNominal: ['('])[#ImplicitConstructors1#]{{; name=.+$}}
-// IMPLICIT_CONSTRUCTORS_1P-NEXT: End completions
+// IMPLICIT_CONSTRUCTORS_1P-NOT: Begin completions
 }
 
 struct ImplicitConstructors2 {
@@ -67,8 +66,7 @@
 func testImplicitConstructors2P() {
   ImplicitConstructors2(#^IMPLICIT_CONSTRUCTORS_2P^#
 // IMPLICIT_CONSTRUCTORS_2P: Begin completions
-// IMPLICIT_CONSTRUCTORS_2P-NEXT: Decl[Constructor]/CurrNominal: ['(']{#instanceVar: Int#})[#ImplicitConstructors2#]{{; name=.+$}}
-// IMPLICIT_CONSTRUCTORS_2P-NEXT: Decl[Constructor]/CurrNominal: ['('])[#ImplicitConstructors2#]{{; name=.+$}}
+// IMPLICIT_CONSTRUCTORS_2P-NEXT: Decl[Constructor]/CurrNominal: ['(']{#instanceVar: Int#}[')'][#ImplicitConstructors2#]{{; name=.+$}}
 // IMPLICIT_CONSTRUCTORS_2P-NEXT: End completions
 }
 
@@ -89,9 +87,8 @@
 func testExplicitConstructors1P() {
   ExplicitConstructors1(#^EXPLICIT_CONSTRUCTORS_1P^#
 // EXPLICIT_CONSTRUCTORS_1P: Begin completions
-// EXPLICIT_CONSTRUCTORS_1P-NEXT: Decl[Constructor]/CurrNominal: ['('])[#ExplicitConstructors1#]{{; name=.+$}}
-// EXPLICIT_CONSTRUCTORS_1P-NEXT: Decl[Constructor]/CurrNominal: ['(']{#a: Int#})[#ExplicitConstructors1#]{{; name=.+$}}
-// EXPLICIT_CONSTRUCTORS_1P-NEXT: Decl[Constructor]/CurrNominal: ['(']{#a: Int#}, {#b: Float#})[#ExplicitConstructors1#]{{; name=.+$}}
+// EXPLICIT_CONSTRUCTORS_1P-NEXT: Decl[Constructor]/CurrNominal: ['(']{#a: Int#}[')'][#ExplicitConstructors1#]{{; name=.+$}}
+// EXPLICIT_CONSTRUCTORS_1P-NEXT: Decl[Constructor]/CurrNominal: ['(']{#a: Int#}, {#b: Float#}[')'][#ExplicitConstructors1#]{{; name=.+$}}
 // EXPLICIT_CONSTRUCTORS_1P-NEXT: End completions
 }
 
@@ -106,9 +103,8 @@
 ExplicitConstructors1(#^EXPLICIT_CONSTRUCTORS_2P^#
 
 // EXPLICIT_CONSTRUCTORS_2P: Begin completions
-// EXPLICIT_CONSTRUCTORS_2P-DAG: Decl[Constructor]/CurrNominal: ['('])[#ExplicitConstructors1#]
-// EXPLICIT_CONSTRUCTORS_2P-DAG: Decl[Constructor]/CurrNominal: ['(']{#a: Int#})[#ExplicitConstructors1#]
-// EXPLICIT_CONSTRUCTORS_2P-DAG: Decl[Constructor]/CurrNominal: ['(']{#a: Int#}, {#b: Float#})[#ExplicitConstructors1#]
+// EXPLICIT_CONSTRUCTORS_2P-DAG: Decl[Constructor]/CurrNominal: ['(']{#a: Int#}[')'][#ExplicitConstructors1#]
+// EXPLICIT_CONSTRUCTORS_2P-DAG: Decl[Constructor]/CurrNominal: ['(']{#a: Int#}, {#b: Float#}[')'][#ExplicitConstructors1#]
 // EXPLICIT_CONSTRUCTORS_2P: End completions
 
 
@@ -121,9 +117,8 @@
 func testExplicitConstructors3P() {
   ExplicitConstructors3(#^EXPLICIT_CONSTRUCTORS_3P^#
 // EXPLICIT_CONSTRUCTORS_3P: Begin completions
-// EXPLICIT_CONSTRUCTORS_3P-DAG: Decl[Constructor]/CurrNominal: ['('])[#ExplicitConstructors3#]{{; name=.+$}}
-// EXPLICIT_CONSTRUCTORS_3P-DAG: Decl[Constructor]/CurrNominal: ['(']{#(a): Int#})[#ExplicitConstructors3#]{{; name=.+$}}
-// EXPLICIT_CONSTRUCTORS_3P-DAG: Decl[Constructor]/CurrNominal: ['(']{#a: Int#}, {#b: Float#})[#ExplicitConstructors3#]{{; name=.+$}}
+// EXPLICIT_CONSTRUCTORS_3P-DAG: Decl[Constructor]/CurrNominal: ['(']{#(a): Int#}[')'][#ExplicitConstructors3#]{{; name=.+$}}
+// EXPLICIT_CONSTRUCTORS_3P-DAG: Decl[Constructor]/CurrNominal: ['(']{#a: Int#}, {#b: Float#}[')'][#ExplicitConstructors3#]{{; name=.+$}}
 // EXPLICIT_CONSTRUCTORS_3P-DAG: Decl[FreeFunction]/CurrModule/NotRecommended/TypeRelation[Invalid]: freeFunc()[#Void#]{{; name=.+$}}
 // EXPLICIT_CONSTRUCTORS_3P: End completions
 }
@@ -254,11 +249,11 @@
 // WITH_ALIAS_1: Decl[Constructor]/CurrNominal:      ({#working: Int#})[#Alias1#];
 
 struct ClosureInInit1 {
-  struct S{}
+  struct S {init(_: Int) {}}
   var prop1: S = {
     return S(#^CLOSURE_IN_INIT_1^#
   }
-// CLOSURE_IN_INIT_1: Decl[Constructor]/CurrNominal:      ['('])[#ClosureInInit1.S#];
+// CLOSURE_IN_INIT_1: Decl[Constructor]/CurrNominal:      ['(']{#Int#}[')'][#ClosureInInit1.S#];
   var prop2: S = {
     return S(#^CLOSURE_IN_INIT_2^#
   }()
diff --git a/test/IDE/complete_crashes.swift b/test/IDE/complete_crashes.swift
index 7220893..e40372f 100644
--- a/test/IDE/complete_crashes.swift
+++ b/test/IDE/complete_crashes.swift
@@ -139,7 +139,7 @@
 func rdar22688199() {
   let f = flip(curried)(#^RDAR_22688199^#
 }
-// FLIP_CURRIED: Pattern/ExprSpecific: ['(']{#Int#}, {#Int#})[#(Int) -> ()#]
+// FLIP_CURRIED: Pattern/CurrModule: ['(']{#Int#}, {#Int#}[')'][#(Int) -> ()#]
 
 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RDAR_22836263
 func rdar22836263() {
diff --git a/test/IDE/complete_default_arguments.swift b/test/IDE/complete_default_arguments.swift
index 10a6b7b..2c2b4f9 100644
--- a/test/IDE/complete_default_arguments.swift
+++ b/test/IDE/complete_default_arguments.swift
@@ -67,16 +67,16 @@
   freeFuncWithDefaultArgs1#^DEFAULT_ARGS_2^#
 }
 // DEFAULT_ARGS_2: Begin completions
-// DEFAULT_ARGS_2-DAG: Pattern/ExprSpecific:      ({#(a): Int#})[#Void#]{{; name=.+$}}
-// DEFAULT_ARGS_2-DAG: Pattern/ExprSpecific:      ({#(a): Int#}, {#b: Int#})[#Void#]{{; name=.+$}}
+// DEFAULT_ARGS_2-DAG: Pattern/CurrModule:      ({#(a): Int#})[#Void#]{{; name=.+$}}
+// DEFAULT_ARGS_2-DAG: Pattern/CurrModule:      ({#(a): Int#}, {#b: Int#})[#Void#]{{; name=.+$}}
 // DEFAULT_ARGS_2: End completions
 
 func testDefaultArgs3() {
   freeFuncWithDefaultArgs3#^DEFAULT_ARGS_3^#
 }
 // DEFAULT_ARGS_3: Begin completions
-// DEFAULT_ARGS_3-DAG: Pattern/ExprSpecific:      ()[#Void#]{{; name=.+$}}
-// DEFAULT_ARGS_3-DAG: Pattern/ExprSpecific:      ({#a: Int#})[#Void#]{{; name=.+$}}
+// DEFAULT_ARGS_3-DAG: Pattern/CurrModule:      ()[#Void#]{{; name=.+$}}
+// DEFAULT_ARGS_3-DAG: Pattern/CurrModule:      ({#a: Int#})[#Void#]{{; name=.+$}}
 // DEFAULT_ARGS_3: End completions
 
 func testDefaultArgs4(_ x: A) {
@@ -91,8 +91,8 @@
   x.methodWithDefaultArgs1#^DEFAULT_ARGS_5^#
 }
 // DEFAULT_ARGS_5: Begin completions
-// DEFAULT_ARGS_5-DAG: Pattern/ExprSpecific:      ()[#Void#]{{; name=.+$}}
-// DEFAULT_ARGS_5-DAG: Pattern/ExprSpecific:      ({#a: Int#})[#Void#]{{; name=.+$}}
+// DEFAULT_ARGS_5-DAG: Pattern/CurrModule:      ()[#Void#]{{; name=.+$}}
+// DEFAULT_ARGS_5-DAG: Pattern/CurrModule:      ({#a: Int#})[#Void#]{{; name=.+$}}
 // DEFAULT_ARGS_5: End completions
 
 func testDefaultArgs6() {
diff --git a/test/IDE/complete_dynamic_lookup.swift b/test/IDE/complete_dynamic_lookup.swift
index 8d70083..068ada6 100644
--- a/test/IDE/complete_dynamic_lookup.swift
+++ b/test/IDE/complete_dynamic_lookup.swift
@@ -461,7 +461,7 @@
   dl.returnsObjcClass!(#^DL_FUNC_NAME_PAREN_1^#
 }
 // DL_FUNC_NAME_PAREN_1: Begin completions
-// DL_FUNC_NAME_PAREN_1-DAG: Pattern/ExprSpecific: ['(']{#Int#})[#TopLevelObjcClass#]{{; name=.+$}}
+// DL_FUNC_NAME_PAREN_1-DAG: Pattern/CurrModule: ['(']{#Int#}[')'][#TopLevelObjcClass#]{{; name=.+$}}
 // DL_FUNC_NAME_PAREN_1: End completions
 
 func testAnyObject12(_ dl: AnyObject) {
@@ -473,7 +473,7 @@
   dl.returnsObjcClass!#^DL_FUNC_NAME_BANG_1^#
 }
 // DL_FUNC_NAME_BANG_1: Begin completions
-// DL_FUNC_NAME_BANG_1-NEXT: Pattern/ExprSpecific: ({#Int#})[#TopLevelObjcClass#]
+// DL_FUNC_NAME_BANG_1-NEXT: Pattern/CurrModule: ({#Int#})[#TopLevelObjcClass#]
 // DL_FUNC_NAME_BANG_1-NEXT: End completions
 
 func testAnyObject14() {
diff --git a/test/IDE/complete_exception.swift b/test/IDE/complete_exception.swift
index 61cbaa2..f810cf1 100644
--- a/test/IDE/complete_exception.swift
+++ b/test/IDE/complete_exception.swift
@@ -123,7 +123,7 @@
 func test005() {
   do {} catch Error4.E2#^CATCH3^#
 // CATCH3: Begin completions
-// CATCH3: Pattern/ExprSpecific:               ({#Int32#})[#Error4#]{{; name=.+$}}
+// CATCH3: Pattern/CurrModule:               ({#Int32#})[#Error4#]{{; name=.+$}}
 // CATCH3: End completions
 }
 
diff --git a/test/IDE/complete_from_clang_framework.swift b/test/IDE/complete_from_clang_framework.swift
index 6cd1101..b6a93e2 100644
--- a/test/IDE/complete_from_clang_framework.swift
+++ b/test/IDE/complete_from_clang_framework.swift
@@ -226,14 +226,14 @@
 func testCompleteFunctionCall1() {
   fooFunc1#^FUNCTION_CALL_1^#
 // FUNCTION_CALL_1: Begin completions
-// FUNCTION_CALL_1-NEXT: Pattern/ExprSpecific: ({#(a): Int32#})[#Int32#]{{; name=.+$}}
+// FUNCTION_CALL_1-NEXT: Pattern/CurrModule: ({#(a): Int32#})[#Int32#]{{; name=.+$}}
 // FUNCTION_CALL_1-NEXT: End completions
 }
 
 func testCompleteFunctionCall2() {
   fooFunc1AnonymousParam#^FUNCTION_CALL_2^#
 // FUNCTION_CALL_2: Begin completions
-// FUNCTION_CALL_2-NEXT: Pattern/ExprSpecific: ({#Int32#})[#Int32#]{{; name=.+$}}
+// FUNCTION_CALL_2-NEXT: Pattern/CurrModule: ({#Int32#})[#Int32#]{{; name=.+$}}
 // FUNCTION_CALL_2-NEXT: End completions
 }
 
diff --git a/test/IDE/complete_init.swift b/test/IDE/complete_init.swift
index 41ac7c1..ad9d5aa 100644
--- a/test/IDE/complete_init.swift
+++ b/test/IDE/complete_init.swift
@@ -143,7 +143,5 @@
 
 var CAliasInstance = CAlias(#^ALIAS_CONSTRUCTOR_0^#
 // rdar://18586415
-// ALIAS_CONSTRUCTOR_0: Decl[Constructor]/CurrNominal:      ['('])[#CAlias#]; name=)
-// ALIAS_CONSTRUCTOR_0: Decl[Constructor]/CurrNominal:      ['(']{#x: A#})[#CAlias#]; name=x: A)
-// ALIAS_CONSTRUCTOR_0: Decl[Constructor]/CurrNominal:      ['('])[#CAlias#]; name=)
-// ALIAS_CONSTRUCTOR_0: Decl[Constructor]/CurrNominal:      ['(']{#y: A#})[#CAlias#]; name=y: A)
+// ALIAS_CONSTRUCTOR_0: Decl[Constructor]/CurrNominal:      ['(']{#x: A#}[')'][#CAlias#];
+// ALIAS_CONSTRUCTOR_0: Decl[Constructor]/CurrNominal:      ['(']{#y: A#}[')'][#CAlias#];
diff --git a/test/IDE/complete_operators.swift b/test/IDE/complete_operators.swift
index dc1e200..0aec8db 100644
--- a/test/IDE/complete_operators.swift
+++ b/test/IDE/complete_operators.swift
@@ -58,6 +58,11 @@
 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=ASSIGN_TUPLE_2| %FileCheck %s -check-prefix=ASSIGN_TUPLE_2
 // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=ASSIGN_TUPLE_3| %FileCheck %s -check-prefix=ASSIGN_TUPLE_1
 
+// RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_AUTOCLOSURE_1 | %FileCheck %s -check-prefix=INFIX_AUTOCLOSURE_1
+// RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_AUTOCLOSURE_2 | %FileCheck %s -check-prefix=INFIX_AUTOCLOSURE_1
+// RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_AUTOCLOSURE_3 | %FileCheck %s -check-prefix=INFIX_AUTOCLOSURE_1
+// RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=INFIX_AUTOCLOSURE_4 | %FileCheck %s -check-prefix=INFIX_AUTOCLOSURE_1
+
 struct S {}
 postfix operator ++ {}
 postfix func ++(x: inout S) -> S { return x }
@@ -278,7 +283,7 @@
 }
 
 // INFIX_16: Begin completions, 1 items
-// INFIX_16-NEXT: Pattern/ExprSpecific:               ({#(self): T#})[#() -> S2#]; name=(self: T)
+// INFIX_16-NEXT: Pattern/CurrModule:               ({#(self): T#})[#() -> S2#]; name=(self: T)
 // INFIX_16: End completions
 
 func testInfix17(x: Void) {
@@ -321,7 +326,7 @@
   E.B#^INFIX_22^#
 }
 // INFIX_22: Begin completions, 1 items
-// INFIX_22-NEXT: Pattern/ExprSpecific:               ({#S2#})[#E#]; name=(S2)
+// INFIX_22-NEXT: Pattern/CurrModule:               ({#S2#})[#E#]; name=(S2)
 // INFIX_22: End completions
 
 func testSpace(x: S2) {
@@ -397,3 +402,25 @@
   (x, y)#^ASSIGN_TUPLE_2^#
 }
 // ASSIGN_TUPLE_2: BuiltinOperator/None:                        = {#(S2, S2)#}[#Void#];
+
+
+infix operator ====: ComparisonPrecedence
+infix operator &&&& : LogicalConjunctionPrecedence
+infix operator |||| : LogicalDisjunctionPrecedence
+struct Boolish {}
+func ====(x: Boolish, y: Boolish) -> Boolish { return x }
+func &&&&(x: Boolish, y: @autoclosure ()->Boolish) -> Boolish { return x }
+func ||||(x: Boolish, y: @autoclosure ()->Boolish) -> Boolish { return x }
+
+func testAutoclosure(x: Boolish, y: Boolish) {
+  if x #^INFIX_AUTOCLOSURE_1^# {}
+  if x &&&& y #^INFIX_AUTOCLOSURE_2^# {}
+  if x |||| y #^INFIX_AUTOCLOSURE_3^# {}
+  if x &&&& x |||| y #^INFIX_AUTOCLOSURE_4^# {}
+}
+
+// INFIX_AUTOCLOSURE_1: Begin completions
+// INFIX_AUTOCLOSURE_1-DAG: Decl[InfixOperatorFunction]/CurrModule: [' ']&&&& {#Boolish#}[#Boolish#];
+// INFIX_AUTOCLOSURE_1-DAG: Decl[InfixOperatorFunction]/CurrModule: [' ']==== {#Boolish#}[#Boolish#];
+// INFIX_AUTOCLOSURE_1-DAG: Decl[InfixOperatorFunction]/CurrModule: [' ']|||| {#Boolish#}[#Boolish#];
+// INFIX_AUTOCLOSURE_1: End completions
\ No newline at end of file
diff --git a/test/IDE/complete_type_subscript.swift b/test/IDE/complete_type_subscript.swift
new file mode 100644
index 0000000..6a547f7
--- /dev/null
+++ b/test/IDE/complete_type_subscript.swift
@@ -0,0 +1,89 @@
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PARAM_0 | %FileCheck %s -check-prefix=TOP_LEVEL_0
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RETURN_0 | %FileCheck %s -check-prefix=TOP_LEVEL_0
+
+struct S0 {
+  subscript(x: #^PARAM_0^#) -> Int { return 0 }
+  subscript(x: Int) -> #^RETURN_0^# { }
+}
+// TOP_LEVEL_0: Keyword/None:                       Any[#Any#];
+// TOP_LEVEL_0: Decl[Struct]/CurrModule:            S0[#S0#];
+// TOP_LEVEL_0: Decl[Struct]/OtherModule[Swift]:    Int[#Int#];
+
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PARAM_1 | %FileCheck %s -check-prefix=MYSTRUCT_0
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RETURN_1 | %FileCheck %s -check-prefix=MYSTRUCT_0
+struct S1 {
+  struct MyStruct {}
+  subscript(x: MyStruct#^PARAM_1^#) -> Int { return 0 }
+  subscript(x: MyStruct) -> MyStruct#^RETURN_1^# { }
+}
+// MYSTRUCT_0: Keyword/None:                       .Type[#S1.MyStruct.Type#];
+// MYSTRUCT_0: Keyword/CurrNominal:                .self[#S1.MyStruct#];
+
+
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PARAM_2 | %FileCheck %s -check-prefix=MYSTRUCT_1
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RETURN_2 | %FileCheck %s -check-prefix=MYSTRUCT_1
+struct S2 {
+  struct MyStruct {}
+  subscript(x: MyStruct.#^PARAM_2^#) -> Int { return 0 }
+  subscript(x: MyStruct) -> MyStruct.#^RETURN_2^# { }
+}
+// MYSTRUCT_1: Keyword/None:                       Type[#S2.MyStruct.Type#];
+// MYSTRUCT_1: Keyword/CurrNominal:                self[#S2.MyStruct#];
+
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GEN_PARAM_0 | %FileCheck %s -check-prefix=GEN_TOP_LEVEL_0
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GEN_RETURN_0 | %FileCheck %s -check-prefix=GEN_TOP_LEVEL_0
+struct G0<T> {
+  subscript(x: #^GEN_PARAM_0^#) -> Int { return 0 }
+  subscript(x: T) -> #^GEN_RETURN_0^# { return 0 }
+}
+// GEN_TOP_LEVEL_0: Keyword/None:                       Any[#Any#];
+// GEN_TOP_LEVEL_0: Decl[GenericTypeParam]/Local:       T[#T#];
+// GEN_TOP_LEVEL_0: Decl[Struct]/CurrModule:            S0[#S0#];
+// GEN_TOP_LEVEL_0: Decl[Struct]/OtherModule[Swift]:    Int[#Int#];
+
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GEN_PARAM_1 | %FileCheck %s -check-prefix=GEN_PARAM_1
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GEN_RETURN_1 | %FileCheck %s -check-prefix=GEN_PARAM_1
+struct G1<T> {
+  subscript(x: T#^GEN_PARAM_1^#) -> Int { return 0 }
+  subscript(x: T) -> T#^GEN_RETURN_1^# { return 0 }
+}
+// GEN_PARAM_1: Keyword/None:                       .Type[#T.Type#];
+// GEN_PARAM_1: Keyword/CurrNominal:                .self[#T#];
+
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GEN_PARAM_2 | %FileCheck %s -check-prefix=GEN_PARAM_2
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GEN_RETURN_2 | %FileCheck %s -check-prefix=GEN_PARAM_2
+struct G2<T> {
+  subscript(x: T.#^GEN_PARAM_2^#) -> Int { return 0 }
+  subscript(x: T) -> T.#^GEN_RETURN_2^# { return 0 }
+}
+// GEN_PARAM_2: Keyword/None:                       Type[#T.Type#];
+// GEN_PARAM_2: Keyword/CurrNominal:                self[#T#];
+
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GEN_PARAM_3 | %FileCheck %s -check-prefix=GEN_TOP_LEVEL_1
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GEN_RETURN_3 | %FileCheck %s -check-prefix=GEN_TOP_LEVEL_1
+struct G3 {
+  subscript<T>(x: #^GEN_PARAM_3^#) -> Int { return 0 }
+  subscript<T>(x: T) -> #^GEN_RETURN_3^# { return 0 }
+}
+// GEN_TOP_LEVEL_1: Keyword/None:                       Any[#Any#];
+// GEN_TOP_LEVEL_1: Decl[GenericTypeParam]/Local:       T[#T#];
+// GEN_TOP_LEVEL_1: Decl[Struct]/CurrModule:            S0[#S0#];
+// GEN_TOP_LEVEL_1: Decl[Struct]/OtherModule[Swift]:    Int[#Int#];
+
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GEN_PARAM_4 | %FileCheck %s -check-prefix=GEN_PARAM_4
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GEN_RETURN_4 | %FileCheck %s -check-prefix=GEN_PARAM_4
+struct G4 {
+  subscript<T>(x: T#^GEN_PARAM_4^#) -> Int { return 0 }
+  subscript<T>(x: T) -> T#^GEN_RETURN_4^# { return 0 }
+}
+// GEN_PARAM_4: Keyword/None:                       .Type[#T.Type#];
+// GEN_PARAM_4: Keyword/CurrNominal:                .self[#T#];
+
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GEN_PARAM_5 | %FileCheck %s -check-prefix=GEN_PARAM_5
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GEN_RETURN_5 | %FileCheck %s -check-prefix=GEN_PARAM_5
+struct G5 {
+  subscript<T>(x: T.#^GEN_PARAM_5^#) -> Int { return 0 }
+  subscript<T>(x: T) -> T.#^GEN_RETURN_5^# { return 0 }
+}
+// GEN_PARAM_5: Keyword/None:                       Type[#T.Type#];
+// GEN_PARAM_5: Keyword/CurrNominal:                self[#T#];
\ No newline at end of file
diff --git a/test/IDE/complete_value_expr.swift b/test/IDE/complete_value_expr.swift
index 20b1409..983d837 100644
--- a/test/IDE/complete_value_expr.swift
+++ b/test/IDE/complete_value_expr.swift
@@ -49,8 +49,10 @@
 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_8 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_8
 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_9 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_9
 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_10 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_10
-// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_11 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_11
-// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_12 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_12
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_11 -code-complete-call-pattern-heuristics | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_11
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_11 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_4
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_12 -code-complete-call-pattern-heuristics | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_12
+// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_12 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_4
 
 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_VARARG_FUNCTION_CALL_1 | %FileCheck %s -check-prefix=INSIDE_VARARG_FUNCTION_CALL_1
 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_VARARG_FUNCTION_CALL_2 | %FileCheck %s -check-prefix=INSIDE_VARARG_FUNCTION_CALL_2
@@ -498,32 +500,32 @@
 func testImplicitlyCurriedFunc(_ fs: inout FooStruct) {
   FooStruct.instanceFunc0(&fs)#^IMPLICITLY_CURRIED_FUNC_0^#
 // IMPLICITLY_CURRIED_FUNC_0: Begin completions
-// IMPLICITLY_CURRIED_FUNC_0-NEXT: Pattern/ExprSpecific: ()[#Void#]{{; name=.+$}}
+// IMPLICITLY_CURRIED_FUNC_0-NEXT: Pattern/CurrModule: ()[#Void#]{{; name=.+$}}
 // IMPLICITLY_CURRIED_FUNC_0-NEXT: End completions
 
   FooStruct.instanceFunc1(&fs)#^IMPLICITLY_CURRIED_FUNC_1^#
 // IMPLICITLY_CURRIED_FUNC_1: Begin completions
-// IMPLICITLY_CURRIED_FUNC_1-NEXT: Pattern/ExprSpecific: ({#(a): Int#})[#Void#]{{; name=.+$}}
+// IMPLICITLY_CURRIED_FUNC_1-NEXT: Pattern/CurrModule: ({#(a): Int#})[#Void#]{{; name=.+$}}
 // IMPLICITLY_CURRIED_FUNC_1-NEXT: End completions
 
   FooStruct.instanceFunc2(&fs)#^IMPLICITLY_CURRIED_FUNC_2^#
 // IMPLICITLY_CURRIED_FUNC_2: Begin completions
-// IMPLICITLY_CURRIED_FUNC_2-NEXT: Pattern/ExprSpecific: ({#(a): Int#}, {#b: &Double#})[#Void#]{{; name=.+$}}
+// IMPLICITLY_CURRIED_FUNC_2-NEXT: Pattern/CurrModule: ({#(a): Int#}, {#b: &Double#})[#Void#]{{; name=.+$}}
 // IMPLICITLY_CURRIED_FUNC_2-NEXT: End completions
 
   FooStruct.varargInstanceFunc0(&fs)#^IMPLICITLY_CURRIED_VARARG_FUNC_0^#
 // IMPLICITLY_CURRIED_VARARG_FUNC_0: Begin completions
-// IMPLICITLY_CURRIED_VARARG_FUNC_0-NEXT: Pattern/ExprSpecific: ({#(v): Int...#})[#Void#]{{; name=.+$}}
+// IMPLICITLY_CURRIED_VARARG_FUNC_0-NEXT: Pattern/CurrModule: ({#(v): Int...#})[#Void#]{{; name=.+$}}
 // IMPLICITLY_CURRIED_VARARG_FUNC_0-NEXT: End completions
 
   FooStruct.varargInstanceFunc1(&fs)#^IMPLICITLY_CURRIED_VARARG_FUNC_1^#
 // IMPLICITLY_CURRIED_VARARG_FUNC_1: Begin completions
-// IMPLICITLY_CURRIED_VARARG_FUNC_1-NEXT: Pattern/ExprSpecific: ({#(a): Float#}, {#v: Int...#})[#Void#]{{; name=.+$}}
+// IMPLICITLY_CURRIED_VARARG_FUNC_1-NEXT: Pattern/CurrModule: ({#(a): Float#}, {#v: Int...#})[#Void#]{{; name=.+$}}
 // IMPLICITLY_CURRIED_VARARG_FUNC_1-NEXT: End completions
 
   FooStruct.varargInstanceFunc2(&fs)#^IMPLICITLY_CURRIED_VARARG_FUNC_2^#
 // IMPLICITLY_CURRIED_VARARG_FUNC_2: Begin completions
-// IMPLICITLY_CURRIED_VARARG_FUNC_2-NEXT: Pattern/ExprSpecific: ({#(a): Float#}, {#b: Double#}, {#v: Int...#})[#Void#]{{; name=.+$}}
+// IMPLICITLY_CURRIED_VARARG_FUNC_2-NEXT: Pattern/CurrModule: ({#(a): Float#}, {#b: Double#}, {#v: Int...#})[#Void#]{{; name=.+$}}
 // IMPLICITLY_CURRIED_VARARG_FUNC_2-NEXT: End completions
 
   // This call is ambiguous, and the expression is invalid.
@@ -660,11 +662,9 @@
 func testInsideFunctionCall1() {
   var a = FooStruct()
   a.instanceFunc0(#^INSIDE_FUNCTION_CALL_1^#
-// There should be no other results here because the function call
+// There should be no results here because the function call
 // unambiguously resolves to overload that takes 0 arguments.
-// INSIDE_FUNCTION_CALL_1: Begin completions
-// INSIDE_FUNCTION_CALL_1-NEXT: Pattern/ExprSpecific: ['('])[#Void#]{{; name=.+$}}
-// INSIDE_FUNCTION_CALL_1-NEXT: End completions
+// INSIDE_FUNCTION_CALL_1-NOT: Begin completions
 }
 
 func testInsideFunctionCall2() {
@@ -672,7 +672,7 @@
   a.instanceFunc1(#^INSIDE_FUNCTION_CALL_2^#
 // INSIDE_FUNCTION_CALL_2: Begin completions
 // FIXME: we should print the non-API param name rdar://20962472
-// INSIDE_FUNCTION_CALL_2-DAG: Pattern/ExprSpecific:       ['(']{#Int#})[#Void#]{{; name=.+$}}
+// INSIDE_FUNCTION_CALL_2-DAG: Pattern/CurrModule:       ['(']{#Int#}[')'][#Void#]{{; name=.+$}}
 // INSIDE_FUNCTION_CALL_2-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
 // INSIDE_FUNCTION_CALL_2: End completions
 }
@@ -691,7 +691,7 @@
   a.instanceFunc2(#^INSIDE_FUNCTION_CALL_4^#
 // INSIDE_FUNCTION_CALL_4: Begin completions
 // FIXME: we should print the non-API param name rdar://20962472
-// INSIDE_FUNCTION_CALL_4-DAG: Pattern/ExprSpecific:       ['(']{#Int#}, {#b: &Double#})[#Void#]{{; name=.+$}}
+// INSIDE_FUNCTION_CALL_4-DAG: Pattern/CurrModule:       ['(']{#Int#}, {#b: &Double#}[')'][#Void#]{{; name=.+$}}
 // INSIDE_FUNCTION_CALL_4-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
 // INSIDE_FUNCTION_CALL_4: End completions
 }
@@ -707,7 +707,7 @@
   var a = FooStruct()
   a.instanceFunc7(#^INSIDE_FUNCTION_CALL_6^#
 // INSIDE_FUNCTION_CALL_6: Begin completions
-// INSIDE_FUNCTION_CALL_6-NEXT: Pattern/ExprSpecific: ['(']{#a: Int#})[#Void#]{{; name=.+$}}
+// INSIDE_FUNCTION_CALL_6-NEXT: Pattern/CurrModule: ['(']{#a: Int#}[')'][#Void#]{{; name=.+$}}
 // INSIDE_FUNCTION_CALL_6-NEXT: End completions
 }
 
@@ -716,7 +716,7 @@
   a.instanceFunc8(#^INSIDE_FUNCTION_CALL_7^#
 // INSIDE_FUNCTION_CALL_7: Begin completions
 // FIXME: we should print the non-API param name rdar://20962472
-// INSIDE_FUNCTION_CALL_7: Pattern/ExprSpecific: ['(']{#(Int, Int)#})[#Void#]{{; name=.+$}}
+// INSIDE_FUNCTION_CALL_7: Pattern/CurrModule: ['(']{#(Int, Int)#}[')'][#Void#]{{; name=.+$}}
 // INSIDE_FUNCTION_CALL_7: End completions
 }
 
@@ -729,7 +729,7 @@
   x.instanceFunc1(#^INSIDE_FUNCTION_CALL_9^#)
 // Annotated ')'
 // INSIDE_FUNCTION_CALL_9: Begin completions
-// INSIDE_FUNCTION_CALL_9-DAG: Pattern/ExprSpecific: ['(']{#Int#}[')'][#Void#]{{; name=.+$}}
+// INSIDE_FUNCTION_CALL_9-DAG: Pattern/CurrModule: ['(']{#Int#}[')'][#Void#]{{; name=.+$}}
 // INSIDE_FUNCTION_CALL_9-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
 // INSIDE_FUNCTION_CALL_9: End completions
 }
@@ -737,13 +737,14 @@
   x.instanceFunc2(#^INSIDE_FUNCTION_CALL_10^#)
 // Annotated ')'
 // INSIDE_FUNCTION_CALL_10: Begin completions
-// INSIDE_FUNCTION_CALL_10-DAG: Pattern/ExprSpecific: ['(']{#Int#}, {#b: &Double#}[')'][#Void#]{{; name=.+$}}
+// INSIDE_FUNCTION_CALL_10-DAG: Pattern/CurrModule: ['(']{#Int#}, {#b: &Double#}[')'][#Void#]{{; name=.+$}}
 // INSIDE_FUNCTION_CALL_10-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
 // INSIDE_FUNCTION_CALL_10: End completions
 }
 func testInsideFunctionCall11(_ x: inout FooStruct) {
   x.instanceFunc2(#^INSIDE_FUNCTION_CALL_11^#,
 // INSIDE_FUNCTION_CALL_11-NOT: Pattern/{{.*}}:{{.*}}({{.*}}{#Int#}
+// INSIDE_FUNCTION_CALL_11B: Pattern/CurrModule: ['(']{#Int#}, {#b: &Double#}[')'][#Void#];
 }
 func testInsideFunctionCall12(_ x: inout FooStruct) {
   x.instanceFunc2(#^INSIDE_FUNCTION_CALL_12^#<#placeholder#>
@@ -755,7 +756,7 @@
   a.varargInstanceFunc0(#^INSIDE_VARARG_FUNCTION_CALL_1^#
 // INSIDE_VARARG_FUNCTION_CALL_1: Begin completions
 // FIXME: we should print the non-API param name rdar://20962472
-// INSIDE_VARARG_FUNCTION_CALL_1-DAG: Pattern/ExprSpecific:       ['(']{#Int...#})[#Void#]{{; name=.+$}}
+// INSIDE_VARARG_FUNCTION_CALL_1-DAG: Pattern/CurrModule:       ['(']{#Int...#}[')'][#Void#]{{; name=.+$}}
 // INSIDE_VARARG_FUNCTION_CALL_1-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
 // INSIDE_VARARG_FUNCTION_CALL_1: End completions
 }
@@ -787,7 +788,7 @@
   a.fooClassInstanceFunc1(#^INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1^#
 // INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1: Begin completions
 // FIXME: we should print the non-API param name rdar://20962472
-// INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1-DAG: Pattern/ExprSpecific:       ['(']{#Int#})[#Void#]{{; name=.+$}}
+// INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1-DAG: Pattern/CurrModule:       ['(']{#Int#}[')'][#Void#]{{; name=.+$}}
 // INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
 // INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1: End completions
 }
@@ -803,13 +804,13 @@
 func testFuncTypeVars() {
   funcTypeVarsObject.funcVar1#^VF1^#
 // VF1: Begin completions
-// VF1-NEXT: Pattern/ExprSpecific: ()[#Double#]{{; name=.+$}}
+// VF1-NEXT: Pattern/CurrModule: ()[#Double#]{{; name=.+$}}
 // VF1-NEXT: BuiltinOperator/None:         = {#() -> Double##() -> Double#}[#Void#]
 // VF1-NEXT: End completions
 
   funcTypeVarsObject.funcVar2#^VF2^#
 // VF2: Begin completions
-// VF2-NEXT: Pattern/ExprSpecific: ({#Int#})[#Double#]{{; name=.+$}}
+// VF2-NEXT: Pattern/CurrModule: ({#Int#})[#Double#]{{; name=.+$}}
 // VF2-NEXT: BuiltinOperator/None:         = {#(Int) -> Double##(Int) -> Double#}[#Void#]
 // VF2-NEXT: End completions
 }
@@ -1069,7 +1070,7 @@
 func testFuncParenPattern3(_ fpp: inout FuncParenPattern) {
   fpp.instanceFunc#^FUNC_PAREN_PATTERN_3^#
 // FUNC_PAREN_PATTERN_3: Begin completions
-// FUNC_PAREN_PATTERN_3-NEXT: Pattern/ExprSpecific: ({#Int#})[#Void#]{{; name=.+$}}
+// FUNC_PAREN_PATTERN_3-NEXT: Pattern/CurrModule: ({#Int#})[#Void#]{{; name=.+$}}
 // FUNC_PAREN_PATTERN_3-NEXT: End completions
 }
 
@@ -1572,8 +1573,7 @@
 }
 
 // PROTOCOL_EXT_INIT_1: Begin completions
-// PROTOCOL_EXT_INIT_1: Decl[Constructor]/Super:            ['('])[#Concrete1#]{{; name=.+$}}
-// PROTOCOL_EXT_INIT_1: Decl[Constructor]/Super:            ['(']{#x: Int#})[#Concrete1#]{{; name=.+$}}
+// PROTOCOL_EXT_INIT_1: Decl[Constructor]/Super:            ['(']{#x: Int#}[')'][#Concrete1#]{{; name=.+$}}
 // PROTOCOL_EXT_INIT_1: End completions
 
 func testProtExtInit2<S: P4 where S.T : P1>() {
@@ -1581,8 +1581,7 @@
 }
 
 // PROTOCOL_EXT_INIT_2: Begin completions
-// PROTOCOL_EXT_INIT_2: Decl[Constructor]/Super:            ['('])[#P4#]{{; name=.+$}}
-// PROTOCOL_EXT_INIT_2: Decl[Constructor]/Super:            ['(']{#x: Int#})[#P4#]{{; name=.+$}}
+// PROTOCOL_EXT_INIT_2: Decl[Constructor]/Super:            ['(']{#x: Int#}[')'][#P4#]{{; name=.+$}}
 // PROTOCOL_EXT_INIT_2: End completions
 
 extension P4 where Self.T == OnlyMe {
@@ -1690,14 +1689,14 @@
   globalFuncThrows#^THROWS1^#
 
 // THROWS1: Begin completions
-// THROWS1: Pattern/ExprSpecific:               ()[' throws'][#Void#]; name=() throws
+// THROWS1: Pattern/CurrModule:               ()[' throws'][#Void#]; name=() throws
 // THROWS1: End completions
 }
 func testThrows002() {
   globalFuncRethrows#^THROWS2^#
 
 // THROWS2: Begin completions
-// THROWS2: Pattern/ExprSpecific:               ({#(x): () throws -> ()##() throws -> ()#})[' rethrows'][#Void#]; name=(x: () throws -> ()) rethrows
+// THROWS2: Pattern/CurrModule:               ({#(x): () throws -> ()##() throws -> ()#})[' rethrows'][#Void#]; name=(x: () throws -> ()) rethrows
 // THROWS2: End completions
 }
 func testThrows003(_ x: HasThrowingMembers) {
@@ -1710,20 +1709,19 @@
 func testThrows004(_ x: HasThrowingMembers) {
   x.memberThrows#^MEMBER_THROWS2^#
 // MEMBER_THROWS2: Begin completions
-// MEMBER_THROWS2: Pattern/ExprSpecific:               ()[' throws'][#Void#]; name=() throws
+// MEMBER_THROWS2: Pattern/CurrModule:               ()[' throws'][#Void#]; name=() throws
 // MEMBER_THROWS2: End completions
 }
 func testThrows005(_ x: HasThrowingMembers) {
   x.memberRethrows#^MEMBER_THROWS3^#
 // MEMBER_THROWS3: Begin completions
-// MEMBER_THROWS3: Pattern/ExprSpecific: ({#(x): () throws -> ()##() throws -> ()#})[' rethrows'][#Void#]; name=(x: () throws -> ()) rethrows
+// MEMBER_THROWS3: Pattern/CurrModule: ({#(x): () throws -> ()##() throws -> ()#})[' rethrows'][#Void#]; name=(x: () throws -> ()) rethrows
 // MEMBER_THROWS3: End completions
 }
 func testThrows006() {
   HasThrowingMembers(#^INIT_THROWS1^#
 // INIT_THROWS1: Begin completions
-// INIT_THROWS1: Decl[Constructor]/CurrNominal:      ['('])[' throws'][#HasThrowingMembers#]
-// INIT_THROWS1: Decl[Constructor]/CurrNominal:      ['(']{#x: () throws -> ()##() throws -> ()#})[' rethrows'][#HasThrowingMembers#]
+// INIT_THROWS1: Decl[Constructor]/CurrNominal:      ['(']{#x: () throws -> ()##() throws -> ()#}[')'][' rethrows'][#HasThrowingMembers#]
 // INIT_THROWS1: End completions
 }
 
diff --git a/test/IDE/complete_vararg.swift b/test/IDE/complete_vararg.swift
index 7aabfa6..78a904d 100644
--- a/test/IDE/complete_vararg.swift
+++ b/test/IDE/complete_vararg.swift
@@ -54,17 +54,17 @@
   freeFunc2(#^FREE_FUNC_2^#
 }
 // FREE_FUNC_1: Begin completions, 1 items
-// FREE_FUNC_1: Pattern/ExprSpecific:               ['(']{#x: Int...#})[#Void#]{{; name=.+$}}
+// FREE_FUNC_1: Pattern/CurrModule:               ['(']{#x: Int...#}[')'][#Void#]{{; name=.+$}}
 // FREE_FUNC_1: End completions
 // FREE_FUNC_2: Begin completions, 1 items
-// FREE_FUNC_2: Pattern/ExprSpecific:               ['(']{#x: Int#}, {#y: Int...#})[#Void#]{{; name=.+$}}
+// FREE_FUNC_2: Pattern/CurrModule:               ['(']{#x: Int#}, {#y: Int...#}[')'][#Void#]{{; name=.+$}}
 // FREE_FUNC_2: End completions
 
 func testInit() {
   let c =C(#^INIT_1^#
 }
 // INIT_1: Begin completions, 1 items
-// INIT_1: Decl[Constructor]/CurrNominal:      ['(']{#x: Int...#})[#C#]{{; name=.+$}}
+// INIT_1: Decl[Constructor]/CurrNominal:      ['(']{#x: Int...#}[')'][#C#]{{; name=.+$}}
 // INIT_1: End completions
 
 func testMethod() {
@@ -72,10 +72,10 @@
   obj.method2(#^METHOD_2^#
 }
 // METHOD_1: Begin completions, 1 items
-// METHOD_1: Pattern/ExprSpecific:               ['(']{#x: Int...#})[#Void#]{{; name=.+$}}
+// METHOD_1: Pattern/CurrModule:               ['(']{#x: Int...#}[')'][#Void#]{{; name=.+$}}
 // METHOD_1: End completions
 // METHOD_2: Begin completions, 1 items
-// METHOD_2: Pattern/ExprSpecific:               ['(']{#x: Int#}, {#y: Int...#})[#Void#]{{; name=.+$}}
+// METHOD_2: Pattern/CurrModule:               ['(']{#x: Int#}, {#y: Int...#}[')'][#Void#]{{; name=.+$}}
 // METHOD_2: End completions
 
 func testSubscript() {
@@ -89,7 +89,7 @@
   genericFreeFunc1(#^GENERIC_FREE_FUNC_1^#
 }
 // GENERIC_FREE_FUNC_1: Begin completions, 1 items
-// GENERIC_FREE_FUNC_1: Pattern/ExprSpecific:               ['(']{#t: _...#})[#Void#]{{; name=.+$}}
+// GENERIC_FREE_FUNC_1: Pattern/CurrModule:               ['(']{#t: _...#}[')'][#Void#]{{; name=.+$}}
 // GENERIC_FREE_FUNC_1: End completions
 
 
@@ -97,5 +97,5 @@
   interestingType1(#^INTERESTING_TYPE_1^#
 }
 // INTERESTING_TYPE_1: Begin completions, 1 items
-// INTERESTING_TYPE_1: Pattern/ExprSpecific:               ['(']{#x: (Int, (Int, String))...#})[#Void#]{{; name=.+$}}
+// INTERESTING_TYPE_1: Pattern/CurrModule:               ['(']{#x: (Int, (Int, String))...#}[')'][#Void#]{{; name=.+$}}
 // INTERESTING_TYPE_1: End completions
diff --git a/test/IDE/local_types.swift b/test/IDE/local_types.swift
index f41c1d0..d4a53bf 100644
--- a/test/IDE/local_types.swift
+++ b/test/IDE/local_types.swift
@@ -47,34 +47,34 @@
 
 public func singleFuncWithDuplicates(_ fake: Bool) {
   if fake {
-    // CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD6StructL_V
+    // CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesyySbF06SingleD6StructL_V
     struct SingleFuncStruct {
       let sfsi: Int
     }
-    // CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD5ClassL_C
+    // CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesyySbF06SingleD5ClassL_C
     class SingleFuncClass {
       let sfcs: String
       init(s: String) {
         self.sfcs = s
       }
     }
-    // CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD4EnumL_O
+    // CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesyySbF06SingleD4EnumL_O
     enum SingleFuncEnum {
       case SFEI(Int)
     }
   } else {
-    // CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD6StructL0_V
+    // CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesyySbF06SingleD6StructL0_V
     struct SingleFuncStruct {
       let sfsi: Int
     }
-    // CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD5ClassL0_C
+    // CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesyySbF06SingleD5ClassL0_C
     class SingleFuncClass {
       let sfcs: String
       init(s: String) {
         self.sfcs = s
       }
     }
-    // CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesySbF06SingleD4EnumL0_O
+    // CHECK-DAG: 10LocalTypes24singleFuncWithDuplicatesyySbF06SingleD4EnumL0_O
     enum SingleFuncEnum {
       case SFEI(Int)
     }
@@ -119,18 +119,18 @@
 }
 
 public func singleDefaultArgument(i: Int = {
-  //CHECK-DAG: 10LocalTypes21singleDefaultArgumentySi1i_tFfA_SiycfU_06SingledE6StructL_V
+  //CHECK-DAG: 10LocalTypes21singleDefaultArgument1iySi_tFfA_SiycfU_06SingledE6StructL_V
   struct SingleDefaultArgumentStruct {
     let sdasi: Int
   }
-  // CHECK-DAG: 10LocalTypes21singleDefaultArgumentySi1i_tFfA_SiycfU_06SingledE5ClassL_C
+  // CHECK-DAG: 10LocalTypes21singleDefaultArgument1iySi_tFfA_SiycfU_06SingledE5ClassL_C
   class SingleDefaultArgumentClass {
     let sdacs: String
     init(s: String) {
       self.sdacs = s
     }
   }
-  // CHECK-DAG: 10LocalTypes21singleDefaultArgumentySi1i_tFfA_SiycfU_06SingledE4EnumL_O
+  // CHECK-DAG: 10LocalTypes21singleDefaultArgument1iySi_tFfA_SiycfU_06SingledE4EnumL_O
   enum SingleDefaultArgumentEnum {
     case SDAEI(Int)
   }
diff --git a/test/IDE/merge_local_types.swift b/test/IDE/merge_local_types.swift
index 18aa774..7cad7c3 100644
--- a/test/IDE/merge_local_types.swift
+++ b/test/IDE/merge_local_types.swift
@@ -29,18 +29,18 @@
 
 //CHECK-DAG: 16LocalTypesMerged7toMergeyyF14SingleFuncEnumL_O
 //CHECK-DAG: 16LocalTypesMerged10singleFuncyyF06SingleE4EnumL_O
-//CHECK-DAG: 16LocalTypesMerged21singleDefaultArgumentySi1i_tFfA_SiycfU_06SingleeF5ClassL_C
+//CHECK-DAG: 16LocalTypesMerged21singleDefaultArgument1iySi_tFfA_SiycfU_06SingleeF5ClassL_C
 //CHECK-DAG: 16LocalTypesMerged13singlePatternSivg06SingleE4EnumL_O
 //CHECK-DAG: 16LocalTypesMerged13singleClosureyycvpfiyycfU_06SingleE5ClassL_C
 //CHECK-DAG: 16LocalTypesMerged10doubleFuncyyF05innerE0L_yyF06DoubleE5ClassL_C
 //CHECK-DAG: 16LocalTypesMerged13singleClosureyycvpfiyycfU_06SingleE6StructL_V
-//CHECK-DAG: 16LocalTypesMerged21singleDefaultArgumentySi1i_tFfA_SiycfU_06SingleeF4EnumL_O
+//CHECK-DAG: 16LocalTypesMerged21singleDefaultArgument1iySi_tFfA_SiycfU_06SingleeF4EnumL_O
 //CHECK-DAG: 16LocalTypesMerged13singleClosureyycvpfiyycfU_06SingleE4EnumL_O
 //CHECK-DAG: 16LocalTypesMerged10singleFuncyyF06SingleE5ClassL_C
 //CHECK-DAG: 16LocalTypesMerged13singlePatternSivg06SingleE5ClassL_C
 //CHECK-DAG: 16LocalTypesMerged13doubleClosureyycvpfiyycfU_yycfU_06DoubleE5ClassL_C
 //CHECK-DAG: 16LocalTypesMerged13doubleClosureyycvpfiyycfU_yycfU_06DoubleE6StructL_V
-//CHECK-DAG: 16LocalTypesMerged21singleDefaultArgumentySi1i_tFfA_SiycfU_06SingleeF6StructL_V
+//CHECK-DAG: 16LocalTypesMerged21singleDefaultArgument1iySi_tFfA_SiycfU_06SingleeF6StructL_V
 //CHECK-DAG: 16LocalTypesMerged13doubleClosureyycvpfiyycfU_yycfU_06DoubleE4EnumL_O
 //CHECK-DAG: 16LocalTypesMerged10doubleFuncyyF05innerE0L_yyF06DoubleE6StructL_V
 //CHECK-DAG: 16LocalTypesMerged10doubleFuncyyF05innerE0L_yyF06DoubleE4EnumL_O
diff --git a/test/IDE/print_usrs.swift b/test/IDE/print_usrs.swift
index c6221a8..19c7703 100644
--- a/test/IDE/print_usrs.swift
+++ b/test/IDE/print_usrs.swift
@@ -18,28 +18,28 @@
   typealias TA = Int
   // CHECK: [[@LINE+1]]:7 s:14swift_ide_test5MyClsC3wwwSivp{{$}}
   var www : Int = 0
-  // CHECK: [[@LINE+1]]:8 s:14swift_ide_test5MyClsC3fooySiF{{$}}
+  // CHECK: [[@LINE+1]]:8 s:14swift_ide_test5MyClsC3fooyySiF{{$}}
   func foo(_ x : Int) {}
-  // CHECK: [[@LINE+1]]:3 s:14swift_ide_test5MyClsCSfSicip{{$}}
+  // CHECK: [[@LINE+1]]:3 s:14swift_ide_test5MyClsCySfSicip{{$}}
   subscript(i: Int) -> Float {
-    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test5MyClsCSfSicig{{$}}
+    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test5MyClsCySfSicig{{$}}
     get { return 0.0 }
-    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test5MyClsCSfSicis{{$}}
+    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test5MyClsCySfSicis{{$}}
     set {}
   }
-  // CHECK: [[@LINE+1]]:3 s:14swift_ide_test5MyClsCSfSi_Sitcip{{$}}
+  // CHECK: [[@LINE+1]]:3 s:14swift_ide_test5MyClsCySfSi_Sitcip{{$}}
   subscript(_: Int, _: Int) -> Float {
-    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test5MyClsCSfSi_Sitcig{{$}}
+    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test5MyClsCySfSi_Sitcig{{$}}
     get { return 0.0 }
-    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test5MyClsCSfSi_Sitcis{{$}}
+    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test5MyClsCySfSi_Sitcis{{$}}
     set {}
   }
 
-  // CHECK: [[@LINE+1]]:11 s:14swift_ide_test5MyClsCSfSi_S2itc33_32FE8F7EF2DE2FC69E75F86A8A3935D3Llip{{$}}
+  // CHECK: [[@LINE+1]]:11 s:14swift_ide_test5MyClsCySfSi_S2itc33_32FE8F7EF2DE2FC69E75F86A8A3935D3Llip{{$}}
   private subscript(_: Int, _: Int, _: Int) -> Float {
-    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test5MyClsCSfSi_S2itc33_32FE8F7EF2DE2FC69E75F86A8A3935D3Llig{{$}}
+    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test5MyClsCySfSi_S2itc33_32FE8F7EF2DE2FC69E75F86A8A3935D3Llig{{$}}
     get { return 0.0 }
-    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test5MyClsCSfSi_S2itc33_32FE8F7EF2DE2FC69E75F86A8A3935D3Llis{{$}}
+    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test5MyClsCySfSi_S2itc33_32FE8F7EF2DE2FC69E75F86A8A3935D3Llis{{$}}
     set {}
   }
 }
@@ -55,29 +55,29 @@
 
   // CHECK: [[@LINE+1]]:8 s:14swift_ide_test12GenericClassC12instanceFuncyyF{{$}}
   func instanceFunc() {
-    // CHECK: [[@LINE+2]]:18 s:14swift_ide_test12GenericClassC9classFuncyACFZ{{$}}
+    // CHECK: [[@LINE+2]]:18 s:14swift_ide_test12GenericClassC9classFuncyyACFZ{{$}}
     // CHECK: [[@LINE+1]]:28 s:14swift_ide_test12GenericClassC12instanceFuncyyF4selfL_ACvp{{$}}
     GenericClass.classFunc(self)
   }
 
-  // CHECK: [[@LINE+2]]:3 s:14swift_ide_test12GenericClassCSfSicip{{$}}
+  // CHECK: [[@LINE+2]]:3 s:14swift_ide_test12GenericClassCySfSicip{{$}}
   // CHECK: [[@LINE+1]]:13 s:14swift_ide_test12GenericClassC1iL_Sivp{{$}}
   subscript(i: Int) -> Float {
-    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test12GenericClassCSfSicig{{$}}
+    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test12GenericClassCySfSicig{{$}}
     get { return 0.0 }
-    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test12GenericClassCSfSicis{{$}}
+    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test12GenericClassCySfSicis{{$}}
     set {}
   }
 
   // CHECK: [[@LINE+1]]:3 s:14swift_ide_test12GenericClassCfd{{$}}
   deinit {
-    // CHECK: [[@LINE+2]]:18 s:14swift_ide_test12GenericClassC9classFuncyACFZ{{$}}
+    // CHECK: [[@LINE+2]]:18 s:14swift_ide_test12GenericClassC9classFuncyyACFZ{{$}}
     // CHECK: [[@LINE+1]]:28 s:14swift_ide_test12GenericClassCfd4selfL_ACvp{{$}}
     GenericClass.classFunc(self)
   }
 
-  // CHECK: [[@LINE+2]]:14 s:14swift_ide_test12GenericClassC9classFuncyACFZ{{$}}
-  // CHECK: [[@LINE+1]]:26 s:14swift_ide_test12GenericClassC9classFuncyACFZ1aL_ACvp{{$}}
+  // CHECK: [[@LINE+2]]:14 s:14swift_ide_test12GenericClassC9classFuncyyACFZ{{$}}
+  // CHECK: [[@LINE+1]]:26 s:14swift_ide_test12GenericClassC9classFuncyyACFZ1aL_ACvp{{$}}
   class func classFunc(_ a: GenericClass) {}
 }
 
@@ -85,7 +85,7 @@
 protocol Prot {
   // CHECK: [[@LINE+1]]:18 s:14swift_ide_test4ProtP5Blarg{{$}}
   associatedtype Blarg
-  // CHECK: [[@LINE+1]]:8 s:14swift_ide_test4ProtP8protMeth5BlargQzAFF{{$}}
+  // CHECK: [[@LINE+1]]:8 s:14swift_ide_test4ProtP8protMethy5BlargQzAFF{{$}}
   func protMeth(_ x: Blarg) -> Blarg
   // CHECK: [[@LINE+2]]:7 s:14swift_ide_test4ProtP17protocolProperty1Sivp{{$}}
   // CHECK: [[@LINE+1]]:32 s:14swift_ide_test4ProtP17protocolProperty1Sivg{{$}}
@@ -96,16 +96,16 @@
 class SubCls : MyCls, Prot {
   // CHECK: [[@LINE+1]]:13 s:14swift_ide_test6SubClsC5Blarga{{$}}
   typealias Blarg = Prot2
-  // CHECK: [[@LINE+1]]:8 s:14swift_ide_test6SubClsC8protMethAA5Prot2_pAaE_pF{{$}}
+  // CHECK: [[@LINE+1]]:8 s:14swift_ide_test6SubClsC8protMethyAA5Prot2_pAaE_pF{{$}}
   func protMeth(_ x: Blarg) -> Blarg {}
   // CHECK: [[@LINE+1]]:7 s:14swift_ide_test6SubClsC17protocolProperty1Sivp{{$}}
   var protocolProperty1 = 0
 }
 
-// CHECK: [[@LINE+1]]:6 s:14swift_ide_test5genFnSixAA4ProtRzAA5Prot25BlargRpzlF{{$}}
+// CHECK: [[@LINE+1]]:6 s:14swift_ide_test5genFnySixAA4ProtRzAA5Prot25BlargRpzlF{{$}}
 func genFn<T : Prot>(_ p : T) -> Int where T.Blarg : Prot2 {}
 
-// CHECK: [[@LINE+1]]:6 s:14swift_ide_test3barSi_SftSiF{{$}}
+// CHECK: [[@LINE+1]]:6 s:14swift_ide_test3barySi_SftSiF{{$}}
 func bar(_ x: Int) -> (Int, Float) {}
 
 // CHECK: [[@LINE+1]]:7 s:14swift_ide_test6GenClsC{{$}}
@@ -117,13 +117,13 @@
   // CHECK: [[@LINE+1]]:14 s:14swift_ide_test6GenClsC4cfooyyFZ{{$}}
   class func cfoo() {}
 
-  // CHECK: [[@LINE+1]]:3 s:14swift_ide_test6GenClsCS2i_Sitcip{{$}}
+  // CHECK: [[@LINE+1]]:3 s:14swift_ide_test6GenClsCyS2i_Sitcip{{$}}
   subscript (i : Int, j : Int) -> Int {
-    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test6GenClsCS2i_Sitcig{{$}}
+    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test6GenClsCyS2i_Sitcig{{$}}
     get {
       return i + j
     }
-    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test6GenClsCS2i_Sitcis{{$}}
+    // CHECK: [[@LINE+1]]:5 s:14swift_ide_test6GenClsCyS2i_Sitcis{{$}}
     set(v) {
       _ = v + i - j
     }
@@ -196,16 +196,16 @@
   // CHECK: [[@LINE+1]]:8 c:@M@swift_ide_test@objc(cs)ObjCClass1(im)instanceFunc1:{{$}}
   func instanceFunc1(_ a: Int) {
 
-    // CHECK: [[@LINE+1]]:16 s:14swift_ide_test10ObjCClass1C13instanceFunc1ySiF9LocalEnumL_O
+    // CHECK: [[@LINE+1]]:16 s:14swift_ide_test10ObjCClass1C13instanceFunc1yySiF9LocalEnumL_O
     @objc enum LocalEnum : Int {
-      // CHECK: [[@LINE+1]]:12 s:14swift_ide_test10ObjCClass1C13instanceFunc1ySiF9LocalEnumL_O8someCaseA2FmF
+      // CHECK: [[@LINE+1]]:12 s:14swift_ide_test10ObjCClass1C13instanceFunc1yySiF9LocalEnumL_O8someCaseyA2FmF
       case someCase
     }
   }
   // CHECK: [[@LINE+1]]:14 c:@M@swift_ide_test@objc(cs)ObjCClass1(cm)staticFunc1:{{$}}
   class func staticFunc1(_ a: Int) {}
 
-  // CHECK: [[@LINE+2]]:10 s:14swift_ide_test10ObjCClass1CS2icip{{$}}
+  // CHECK: [[@LINE+2]]:10 s:14swift_ide_test10ObjCClass1CyS2icip{{$}}
   // CHECK: [[@LINE+1]]:20 s:14swift_ide_test10ObjCClass1C1xL_Sivp{{$}}
   public subscript(x: Int) -> Int {
 
@@ -216,7 +216,7 @@
     set {}
   }
 
-  // CHECK: [[@LINE+2]]:10 s:14swift_ide_test10ObjCClass1CSiACcip{{$}}
+  // CHECK: [[@LINE+2]]:10 s:14swift_ide_test10ObjCClass1CySiACcip{{$}}
   // CHECK: [[@LINE+1]]:20 s:14swift_ide_test10ObjCClass1C1xL_ACvp{{$}}
   public subscript(x: ObjCClass1) -> Int {
 
@@ -253,9 +253,9 @@
 
 // CHECK: [[@LINE+1]]:6 s:14swift_ide_test5SuitsO{{$}}
 enum Suits {
-  // CHECK: [[@LINE+1]]:8 s:14swift_ide_test5SuitsO5ClubsA2CmF{{$}}
+  // CHECK: [[@LINE+1]]:8 s:14swift_ide_test5SuitsO5ClubsyA2CmF{{$}}
   case Clubs
-  // CHECK: [[@LINE+1]]:8 s:14swift_ide_test5SuitsO8DiamondsA2CmF{{$}}
+  // CHECK: [[@LINE+1]]:8 s:14swift_ide_test5SuitsO8DiamondsyA2CmF{{$}}
   case Diamonds
 
   // CHECK: [[@LINE+1]]:8 s:14swift_ide_test5SuitsO5enfooyyF{{$}}
diff --git a/test/IDE/reconstruct_type_from_mangled_name.swift b/test/IDE/reconstruct_type_from_mangled_name.swift
index 7951a55..21e87d5 100644
--- a/test/IDE/reconstruct_type_from_mangled_name.swift
+++ b/test/IDE/reconstruct_type_from_mangled_name.swift
@@ -64,7 +64,7 @@
 
     arr1.append(1)
 // FIXME: missing append()
-// CHECK: dref: FAILURE	for 'append' usr=s:Sa6appendyxF
+// CHECK: dref: FAILURE	for 'append' usr=s:Sa6appendyyxF
 // CHECK: type: (@lvalue Array<Int>) -> (Int) -> ()
 
     var arr2 : [Mystruct1]
@@ -204,7 +204,7 @@
 }
 
 func genericFunction<T : AnyObject>(t: T) {
-// CHECK: decl: FAILURE for 'T' usr=s:14swift_ide_test15genericFunctionyx1t_tRlzClF1TL_xmfp
+// CHECK: decl: FAILURE for 'T' usr=s:14swift_ide_test15genericFunction1tyx_tRlzClF1TL_xmfp
   genericFunction(t: t)
 }
 
diff --git a/test/IRGen/abitypes.swift b/test/IRGen/abitypes.swift
index 5bffd1b..e807695 100644
--- a/test/IRGen/abitypes.swift
+++ b/test/IRGen/abitypes.swift
@@ -203,8 +203,8 @@
   // x86_64-macosx:      call void @llvm.lifetime.start
   // x86_64-macosx:      store i32 {{.*}}
   // x86_64-macosx:      store i32 {{.*}}
-  // x86_64-macosx:      getelementptr inbounds { i64 }, { i64 }
-  // x86_64-macosx:      load i64, i64* %12, align 8
+  // x86_64-macosx:      [[T0:%.*]] = getelementptr inbounds { i64 }, { i64 }
+  // x86_64-macosx:      load i64, i64* [[T0]], align 8
   // x86_64-macosx:      bitcast
   // x86_64-macosx:      call void @llvm.lifetime.end
   // x86_64-macosx:      ret i64
@@ -253,14 +253,14 @@
   //
   // armv7-ios-fixme:     define hidden i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1, %T8abitypes3FooC*) {{.*}} {
   // armv7-ios-fixme:     define internal signext i8 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i8 signext) unnamed_addr {{.*}} {
-  // armv7-ios-fixme:     [[R1:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBoolSbAA0cD0V1x_tF
+  // armv7-ios-fixme:     [[R1:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBool1xSbAA0cD0V_tF
   // armv7-ios-fixme:     [[R2:%[0-9]+]] = call i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1 [[R1]]
   // armv7-ios-fixme:     [[R3:%[0-9]+]] = call i8 @_T010ObjectiveC22_convertBoolToObjCBoolAA0eF0VSb1x_tF(i1 [[R2]]
   // armv7-ios-fixme:     ret i8 [[R3]]
   //
   // armv7s-ios-fixme:     define hidden i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1, %T8abitypes3FooC*) {{.*}} {
   // armv7s-ios-fixme:     define internal signext i8 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i8 signext) unnamed_addr {{.*}} {
-  // armv7s-ios-fixme:     [[R1:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBoolSbAA0cD0V1x_tF
+  // armv7s-ios-fixme:     [[R1:%[0-9]+]] = call i1 @_T010ObjectiveC22_convertObjCBoolToBool1xSbAA0cD0V_tF
   // armv7s-ios-fixme:     [[R2:%[0-9]+]] = call i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1 [[R1]]
   // armv7s-ios-fixme:     [[R3:%[0-9]+]] = call i8 @_T010ObjectiveC22_convertBoolToObjCBoolAA0eF0VSb1x_tF(i1 [[R2]]
   // armv7s-ios-fixme:     ret i8 [[R3]]
@@ -291,9 +291,9 @@
 
   // i386-watchos:  define hidden swiftcc i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1, %T8abitypes3FooC* swiftself)
   // i386-watchos:  define hidden zeroext i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo
-  // i386-watchos:  [[R1:%[0-9]+]] = call swiftcc i1 @_T010ObjectiveC22_convertObjCBoolToBoolSbAA0cD0VF(i1 %2)
+  // i386-watchos:  [[R1:%[0-9]+]] = call swiftcc i1 @_T010ObjectiveC22_convertObjCBoolToBoolySbAA0cD0VF(i1 %2)
   // i386-watchos:  [[R2:%[0-9]+]] = call swiftcc i1 @_T08abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F(i1 [[R1]]
-  // i386-watchos:  [[R3:%[0-9]+]] = call swiftcc i1 @_T010ObjectiveC22_convertBoolToObjCBoolAA0eF0VSbF(i1 [[R2]])
+  // i386-watchos:  [[R3:%[0-9]+]] = call swiftcc i1 @_T010ObjectiveC22_convertBoolToObjCBoolyAA0eF0VSbF(i1 [[R2]])
   // i386-watchos:  ret i1 [[R3]]
 
   dynamic func negate(_ b: Bool) -> Bool {
@@ -417,19 +417,19 @@
     return g.negate(b)
   }
 
-  // x86_64-macosx: define hidden swiftcc i1 @_T08abitypes3FooC7negate3S2bF(i1, %T8abitypes3FooC* swiftself) {{.*}} {
+  // x86_64-macosx: define hidden swiftcc i1 @_T08abitypes3FooC7negate3yS2bF(i1, %T8abitypes3FooC* swiftself) {{.*}} {
   // x86_64-macosx: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(invert:)", align 8
   // x86_64-macosx: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1)*)(%1* [[RECEIVER:%[0-9]+]], i8* [[SEL]], i1 zeroext %0)
   // x86_64-macosx: ret i1 [[NEG]]
   // x86_64-macosx: }
 
-  // x86_64-ios: define hidden swiftcc i1 @_T08abitypes3FooC7negate3S2bF(i1, %T8abitypes3FooC* swiftself) {{.*}} {
+  // x86_64-ios: define hidden swiftcc i1 @_T08abitypes3FooC7negate3yS2bF(i1, %T8abitypes3FooC* swiftself) {{.*}} {
   // x86_64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(invert:)", align 8
   // x86_64-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1)*)(%1* [[RECEIVER:%[0-9]+]], i8* [[SEL]], i1 zeroext %0)
   // x86_64-ios: ret i1 [[NEG]]
   // x86_64-ios: }
 
-  // i386-ios: define hidden swiftcc i1 @_T08abitypes3FooC7negate3S2bF(i1, %T8abitypes3FooC* swiftself) {{.*}} {
+  // i386-ios: define hidden swiftcc i1 @_T08abitypes3FooC7negate3yS2bF(i1, %T8abitypes3FooC* swiftself) {{.*}} {
   // i386-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(invert:)", align 4
   // i386-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1)*)(%1* [[RECEIVER:%[0-9]+]], i8* [[SEL]], i1 zeroext %0)
   // i386-ios: ret i1 [[NEG]]
@@ -440,17 +440,17 @@
     return g.invert(b)
   }
 
-  // x86_64-macosx: define hidden swiftcc void @_T08abitypes3FooC10throwsTestySbKF(i1, %T8abitypes3FooC* swiftself, %swift.error** swifterror) {{.*}} {
+  // x86_64-macosx: define hidden swiftcc void @_T08abitypes3FooC10throwsTestyySbKF(i1, %T8abitypes3FooC* swiftself, %swift.error** swifterror) {{.*}} {
   // x86_64-macosx: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negateThrowing:error:)", align 8
   // x86_64-macosx: call signext i8 bitcast (void ()* @objc_msgSend to i8 (%1*, i8*, i8, %2**)*)(%1* {{%[0-9]+}}, i8* [[SEL]], i8 signext {{%[0-9]+}}, %2** {{%[0-9]+}})
   // x86_64-macosx: }
 
-  // x86_64-ios: define hidden swiftcc void @_T08abitypes3FooC10throwsTestySbKF(i1, %T8abitypes3FooC* swiftself, %swift.error** swifterror) {{.*}} {
+  // x86_64-ios: define hidden swiftcc void @_T08abitypes3FooC10throwsTestyySbKF(i1, %T8abitypes3FooC* swiftself, %swift.error** swifterror) {{.*}} {
   // x86_64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negateThrowing:error:)", align 8
   // x86_64-ios: call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1, %2**)*)(%1* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext {{%[0-9]+}}, %2** {{%[0-9]+}})
   // x86_64-ios: }
 
-  // i386-ios: define hidden swiftcc void @_T08abitypes3FooC10throwsTestySbKF(i1, %T8abitypes3FooC* swiftself, %swift.error**) {{.*}} {
+  // i386-ios: define hidden swiftcc void @_T08abitypes3FooC10throwsTestyySbKF(i1, %T8abitypes3FooC* swiftself, %swift.error**) {{.*}} {
   // i386-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negateThrowing:error:)", align 4
   // i386-ios: call signext i8 bitcast (void ()* @objc_msgSend to i8 (%1*, i8*, i8, %2**)*)(%1* {{%[0-9]+}}, i8* [[SEL]], i8 signext {{%[0-9]+}}, %2** {{%[0-9]+}})
   // i386-ios: }
@@ -529,7 +529,7 @@
 // armv7k-watchos: define internal %struct.One @makeOne(float %f, float %s)
 
 // rdar://17631440 - Expand direct arguments that are coerced to aggregates.
-// x86_64-macosx: define{{( protected)?}} swiftcc float @_T08abitypes13testInlineAggSfSC6MyRectVF(i64, i64) {{.*}} {
+// x86_64-macosx: define{{( protected)?}} swiftcc float @_T08abitypes13testInlineAggySfSC6MyRectVF(i64, i64) {{.*}} {
 // x86_64-macosx: [[COERCED:%.*]] = alloca %TSC6MyRectV, align 8
 // x86_64-macosx: store i64 %
 // x86_64-macosx: store i64 %
diff --git a/test/IRGen/associated_types.swift b/test/IRGen/associated_types.swift
index 64a07f4..e8d538b 100644
--- a/test/IRGen/associated_types.swift
+++ b/test/IRGen/associated_types.swift
@@ -71,7 +71,7 @@
   U.RuncerType.Runcee.accelerate()
 }
 
-// CHECK: define hidden swiftcc void @_T016associated_types16testFastRuncibleyx_q_1utAA0E0RzAA0dE0R_10RuncerTypeQy_AFRtzr0_lF(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U, i8** %T.Runcible, i8** %U.FastRuncible) #0 {
+// CHECK: define hidden swiftcc void @_T016associated_types16testFastRuncible_1uyx_q_tAA0E0RzAA0dE0R_10RuncerTypeQy_AFRtzr0_lF(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U, i8** %T.Runcible, i8** %U.FastRuncible) #0 {
 //   1. Get the type metadata for U.RuncerType.Runcee.
 //     1a. Get the type metadata for U.RuncerType.
 //         Note that we actually look things up in T, which is going to prove unfortunate.
diff --git a/test/IRGen/big_types_corner_cases.swift b/test/IRGen/big_types_corner_cases.swift
index 94b6989..5232825 100644
--- a/test/IRGen/big_types_corner_cases.swift
+++ b/test/IRGen/big_types_corner_cases.swift
@@ -43,7 +43,7 @@
   BigStruct()
 ]
 
-// CHECK-LABEL: define{{( protected)?}} internal swiftcc void @_T022big_types_corner_cases21OptionalInoutFuncTypeC7executeys5Error_pSgFyycfU_(%T22big_types_corner_cases9BigStructVSg* nocapture dereferenceable({{.*}}), %T22big_types_corner_cases21OptionalInoutFuncTypeC*, %T22big_types_corner_cases9BigStructVSgs5Error_pSgIegcx_Sg* nocapture dereferenceable({{.*}})
+// CHECK-LABEL: define{{( protected)?}} internal swiftcc void @_T022big_types_corner_cases21OptionalInoutFuncTypeC7executeyys5Error_pSgFyycfU_(%T22big_types_corner_cases9BigStructVSg* nocapture dereferenceable({{.*}}), %T22big_types_corner_cases21OptionalInoutFuncTypeC*, %T22big_types_corner_cases9BigStructVSgs5Error_pSgIegcx_Sg* nocapture dereferenceable({{.*}})
 // CHECK: call void @_T0SqWy
 // CHECK: call void @_T0SqWe
 // CHECK: ret void
@@ -93,7 +93,7 @@
   }
 }
 
-// CHECK-LABEL: define{{( protected)?}} hidden swiftcc void @_T022big_types_corner_cases8BigClassC03useE6StructyAA0eH0V0aH0_tF(%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}), %T22big_types_corner_cases8BigClassC* swiftself)
+// CHECK-LABEL: define{{( protected)?}} hidden swiftcc void @_T022big_types_corner_cases8BigClassC03useE6Struct0aH0yAA0eH0V_tF(%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}), %T22big_types_corner_cases8BigClassC* swiftself)
 // CHECK: getelementptr inbounds %T22big_types_corner_cases8BigClassC, %T22big_types_corner_cases8BigClassC*
 // CHECK: call void @_T0SqWy
 // CHECK: [[BITCAST:%.*]] = bitcast i8* {{.*}} to void (%T22big_types_corner_cases9BigStructV*, %swift.refcounted*)*
@@ -116,7 +116,7 @@
   func myMethod(_ callback: (MyStruct, Int) -> Void) -> Void { }
 }
 
-// CHECK-LABEL: define{{( protected)?}} linkonce_odr hidden swiftcc { i8*, %swift.refcounted* } @_T022big_types_corner_cases3FooC8myMethodyyAA8MyStructV_SitcFTc(%T22big_types_corner_cases3FooC*)
+// CHECK-LABEL: define{{( protected)?}} linkonce_odr hidden swiftcc { i8*, %swift.refcounted* } @_T022big_types_corner_cases3FooC8myMethodyyyAA8MyStructV_SitcFTc(%T22big_types_corner_cases3FooC*)
 // CHECK: getelementptr inbounds %T22big_types_corner_cases3FooC, %T22big_types_corner_cases3FooC*
 // CHECK: getelementptr inbounds void (i8*, %swift.refcounted*, %T22big_types_corner_cases3FooC*)*, void (i8*, %swift.refcounted*, %T22big_types_corner_cases3FooC*)**
 // CHECK: call noalias %swift.refcounted* @swift_rt_swift_allocObject(%swift.type* getelementptr inbounds (%swift.full_boxmetadata, %swift.full_boxmetadata*
@@ -144,7 +144,7 @@
 // CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO
 // CHECK-64: call void @llvm.memcpy.p0i8.p0i8.i64
 // CHECK-64: call void @llvm.memcpy.p0i8.p0i8.i64
-// CHECK-64: _T0s5printyypd_SS9separatorSS10terminatortF
+// CHECK-64: _T0s5print_9separator10terminatoryypd_S2StF
 // CHECK-64: ret void
 
 // CHECK-LABEL: define{{( protected)?}} internal swiftcc void @_T022big_types_corner_cases8SuperSubC1fyyFAA9BigStructVycfU_(%T22big_types_corner_cases9BigStructV* noalias nocapture sret, %T22big_types_corner_cases8SuperSubC*)
diff --git a/test/IRGen/builtins.swift b/test/IRGen/builtins.swift
index b9032ac..3f0c70d 100644
--- a/test/IRGen/builtins.swift
+++ b/test/IRGen/builtins.swift
@@ -221,7 +221,7 @@
 
 }
 
-// CHECK: define hidden {{.*}}void @_T08builtins27generic_sizeof_alignof_testyxlF(
+// CHECK: define hidden {{.*}}void @_T08builtins27generic_sizeof_alignof_testyyxlF
 func generic_sizeof_alignof_test<T>(_: T) {
   // CHECK:      [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 9
   // CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]]
@@ -237,7 +237,7 @@
   var a = Builtin.alignof(T.self)
 }
 
-// CHECK: define hidden {{.*}}void @_T08builtins21generic_strideof_testyxlF(
+// CHECK: define hidden {{.*}}void @_T08builtins21generic_strideof_testyyxlF
 func generic_strideof_test<T>(_: T) {
   // CHECK:      [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 11
   // CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]]
@@ -386,7 +386,7 @@
 // CHECK-objc:    [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1
 // CHECK-objc:    call void @llvm.assume(i1 [[IS_DONE]])
 
-func testOnce(_ p: Builtin.RawPointer, f: @escaping @convention(thin) () -> ()) {
+func testOnce(_ p: Builtin.RawPointer, f: @escaping @convention(c) () -> ()) {
   Builtin.once(p, f)
 }
 
@@ -402,7 +402,7 @@
 // CHECK-objc:    [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]]
 // CHECK-objc:    [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1
 // CHECK-objc:    call void @llvm.assume(i1 [[IS_DONE]])
-func testOnceWithContext(_ p: Builtin.RawPointer, f: @escaping @convention(thin) (Builtin.RawPointer) -> (), k: Builtin.RawPointer) {
+func testOnceWithContext(_ p: Builtin.RawPointer, f: @escaping @convention(c) (Builtin.RawPointer) -> (), k: Builtin.RawPointer) {
   Builtin.onceWithContext(p, f, k)
 }
 
@@ -451,7 +451,7 @@
   Builtin.destroyArray(C.self, array, count)
 }
 
-// CHECK-LABEL: define hidden {{.*}}void @_T08builtins15destroyGenArrayyBp_Bw5countxtlF(i8*, i64, %swift.opaque* noalias nocapture, %swift.type* %T)
+// CHECK-LABEL: define hidden {{.*}}void @_T08builtins15destroyGenArray_5count_yBp_BwxtlF(i8*, i64, %swift.opaque* noalias nocapture, %swift.type* %T)
 // CHECK-NOT:   loop:
 // CHECK:         call void @swift_arrayDestroy
 func destroyGenArray<T>(_ array: Builtin.RawPointer, count: Builtin.Word, _: T) {
@@ -561,7 +561,7 @@
 	var value : Builtin.Word
 }
 
-// CHECK-LABEL: define hidden {{.*}}@_T08builtins22assumeNonNegative_testBwAA3AbcVzF
+// CHECK-LABEL: define hidden {{.*}}@_T08builtins22assumeNonNegative_testyBwAA3AbcVzF
 func assumeNonNegative_test(_ x: inout Abc) -> Builtin.Word {
   // CHECK: load {{.*}}, !range ![[R:[0-9]+]]
   return Builtin.assumeNonNegative_Word(x.value)
@@ -572,7 +572,7 @@
 	return x
 }
 
-// CHECK-LABEL: define hidden {{.*}}@_T08builtins23assumeNonNegative_test2BwBwF
+// CHECK-LABEL: define hidden {{.*}}@_T08builtins23assumeNonNegative_test2yBwBwF
 func assumeNonNegative_test2(_ x: Builtin.Word) -> Builtin.Word {
   // CHECK: call {{.*}}, !range ![[R]]
   return Builtin.assumeNonNegative_Word(return_word(x))
@@ -625,11 +625,11 @@
 // isUnique variants
 // ----------------------------------------------------------------------------
 
-// CHECK: define hidden {{.*}}void @_T08builtins26acceptsBuiltinNativeObjectyBoSgzF([[BUILTIN_NATIVE_OBJECT_TY:%.*]]* nocapture dereferenceable({{.*}})) {{.*}} {
+// CHECK: define hidden {{.*}}void @_T08builtins26acceptsBuiltinNativeObjectyyBoSgzF([[BUILTIN_NATIVE_OBJECT_TY:%.*]]* nocapture dereferenceable({{.*}})) {{.*}} {
 func acceptsBuiltinNativeObject(_ ref: inout Builtin.NativeObject?) {}
 
 // native
-// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BoSgzF({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
+// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueyBi1_BoSgzF({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
 // CHECK-NEXT: entry:
 // CHECK-NEXT: bitcast [[BUILTIN_NATIVE_OBJECT_TY]]* %0 to %swift.refcounted**
 // CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
@@ -640,7 +640,7 @@
 }
 
 // native nonNull
-// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BozF(%swift.refcounted** nocapture dereferenceable({{.*}})) {{.*}} {
+// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueyBi1_BozF(%swift.refcounted** nocapture dereferenceable({{.*}})) {{.*}} {
 // CHECK-NEXT: entry:
 // CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %0
 // CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferenced_nonNull_native(%swift.refcounted* %1)
@@ -650,7 +650,7 @@
 }
 
 // native pinned
-// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedBi1_BoSgzF({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
+// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedyBi1_BoSgzF({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
 // CHECK-NEXT: entry:
 // CHECK-NEXT: bitcast [[BUILTIN_NATIVE_OBJECT_TY]]* %0 to %swift.refcounted**
 // CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
@@ -661,7 +661,7 @@
 }
 
 // native pinned nonNull
-// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedBi1_BozF(%swift.refcounted** nocapture dereferenceable({{.*}})) {{.*}} {
+// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedyBi1_BozF(%swift.refcounted** nocapture dereferenceable({{.*}})) {{.*}} {
 // CHECK-NEXT: entry:
 // CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %0
 // CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferencedOrPinned_nonNull_native(%swift.refcounted* %1)
@@ -670,11 +670,11 @@
   return Builtin.isUniqueOrPinned(&ref)
 }
 
-// CHECK: define hidden {{.*}}void @_T08builtins27acceptsBuiltinUnknownObjectyBOSgzF([[BUILTIN_UNKNOWN_OBJECT_TY:%.*]]* nocapture dereferenceable({{.*}})) {{.*}} {
+// CHECK: define hidden {{.*}}void @_T08builtins27acceptsBuiltinUnknownObjectyyBOSgzF([[BUILTIN_UNKNOWN_OBJECT_TY:%.*]]* nocapture dereferenceable({{.*}})) {{.*}} {
 func acceptsBuiltinUnknownObject(_ ref: inout Builtin.UnknownObject?) {}
 
 // ObjC
-// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BOSgzF({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
+// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueyBi1_BOSgzF({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
 // CHECK-NEXT: entry:
 // CHECK-NEXT: bitcast [[BUILTIN_UNKNOWN_OBJECT_TY]]* %0 to [[UNKNOWN_OBJECT:%objc_object|%swift\.refcounted]]**
 // CHECK-NEXT: load [[UNKNOWN_OBJECT]]*, [[UNKNOWN_OBJECT]]** %1
@@ -686,7 +686,7 @@
 }
 
 // ObjC nonNull
-// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BOzF
+// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueyBi1_BOzF
 // CHECK-SAME:    ([[UNKNOWN_OBJECT]]** nocapture dereferenceable({{.*}})) {{.*}} {
 // CHECK-NEXT: entry:
 // CHECK-NEXT: load [[UNKNOWN_OBJECT]]*, [[UNKNOWN_OBJECT]]** %0
@@ -698,7 +698,7 @@
 }
 
 // ObjC pinned nonNull
-// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedBi1_BOzF
+// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedyBi1_BOzF
 // CHECK-SAME:    ([[UNKNOWN_OBJECT]]** nocapture dereferenceable({{.*}})) {{.*}} {
 // CHECK-NEXT: entry:
 // CHECK-NEXT: load [[UNKNOWN_OBJECT]]*, [[UNKNOWN_OBJECT]]** %0
@@ -710,7 +710,7 @@
 }
 
 // BridgeObject nonNull
-// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
+// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueyBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
 // CHECK-NEXT: entry:
 // CHECK-NEXT: load %swift.bridge*, %swift.bridge** %0
 // CHECK-NEXT: call i1 @swift_isUniquelyReferencedNonObjC_nonNull_bridgeObject(%swift.bridge* %1)
@@ -720,7 +720,7 @@
 }
 
 // Bridge pinned nonNull
-// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
+// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedyBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
 // CHECK-NEXT: entry:
 // CHECK-NEXT: load %swift.bridge*, %swift.bridge** %0
 // CHECK-NEXT: call i1 @swift_isUniquelyReferencedOrPinnedNonObjC_nonNull_bridgeObject(%swift.bridge* %1)
@@ -730,7 +730,7 @@
 }
 
 // BridgeObject nonNull
-// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins15isUnique_nativeBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
+// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins15isUnique_nativeyBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
 // CHECK-NEXT: entry:
 // CHECK-NEXT: bitcast %swift.bridge** %0 to %swift.refcounted**
 // CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
@@ -741,7 +741,7 @@
 }
 
 // Bridge pinned nonNull
-// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins23isUniqueOrPinned_nativeBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
+// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins23isUniqueOrPinned_nativeyBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
 // CHECK-NEXT: entry:
 // CHECK-NEXT: bitcast %swift.bridge** %0 to %swift.refcounted**
 // CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
@@ -752,7 +752,7 @@
 }
 
 // ImplicitlyUnwrappedOptional argument to isUnique.
-// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins11isUniqueIUOBi1_BoSgzF(%{{.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
+// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins11isUniqueIUOyBi1_BoSgzF(%{{.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
 // CHECK-NEXT: entry:
 // CHECK: call i1 @swift_isUniquelyReferenced_native(%swift.refcounted*
 // CHECK: ret i1
diff --git a/test/IRGen/cf.sil b/test/IRGen/cf.sil
index 24e5e00..18af675 100644
--- a/test/IRGen/cf.sil
+++ b/test/IRGen/cf.sil
@@ -7,11 +7,18 @@
 // CHECK: [[REFRIGERATOR:%TSo14CCRefrigeratorC]] = type
 // CHECK: [[OBJC:%objc_object]] = type
 
-// CHECK: [[REFRIGERATOR_NAME:@.*]] = private unnamed_addr constant [20 x i8] c"So14CCRefrigeratorC\00"
+// CHECK: [[REFRIGERATOR_NAME:@.*]] = private constant [20 x i8] c"So14CCRefrigeratorC\00"
 
-// CHECK-32: @_T0So14CCRefrigeratorCN = linkonce_odr hidden global <{ {{.*}} }> <{ i8* getelementptr inbounds ([20 x i8], [20 x i8]* [[REFRIGERATOR_NAME]], i32 0, i32 0), [[TYPE]]* null, i32 0, i8** @_T0BOWV, i32 16, [[TYPE]]* null, i8* null, i8* null, i8* null }>
+// CHECK-32: @_T0So14CCRefrigeratorCN = linkonce_odr hidden global <{ {{.*}} }> <{
+// CHECK-32-SAME: [[REFRIGERATOR_NAME]] to i32
+// CHECK-32-SAME: i32 0,
+// CHECK-32-SAME: i8** @_T0BOWV, i32 16, [[TYPE]]* null, i8* null, i8* null, i8* null }>
 
-// CHECK-64: @_T0So14CCRefrigeratorCN = linkonce_odr hidden global <{ {{.*}} }> <{ i8* getelementptr inbounds ([20 x i8], [20 x i8]* [[REFRIGERATOR_NAME]], i64 0, i64 0), [[TYPE]]* null, i64 0, i8** @_T0BOWV, i64 16, [[TYPE]]* null, i8* null, i8* null, i8* null }>
+// CHECK-64: @_T0So14CCRefrigeratorCN = linkonce_odr hidden global <{ {{.*}} }> <{
+// CHECK-64-SAME: i32 0,
+// CHECK-64-SAME: i32 trunc {{.*}} [[REFRIGERATOR_NAME]] to i64
+// CHECK-64-SAME: i64 0,
+// CHECK-64-SAME: i8** @_T0BOWV, i64 16, [[TYPE]]* null, i8* null, i8* null, i8* null }>
 
 sil_stage canonical
 
@@ -35,5 +42,5 @@
 // CHECK-NEXT: ret void
 
 // CHECK:    define linkonce_odr hidden [[TYPE]]* @_T0So14CCRefrigeratorCMa()
-// CHECK-32:    call [[TYPE]]* @swift_getForeignTypeMetadata([[TYPE]]* bitcast (i8* getelementptr inbounds (i8, i8* bitcast ({{.*}}* @_T0So14CCRefrigeratorCN to i8*), i32 16) to [[TYPE]]*))
-// CHECK-64:    call [[TYPE]]* @swift_getForeignTypeMetadata([[TYPE]]* bitcast (i8* getelementptr inbounds (i8, i8* bitcast ({{.*}}* @_T0So14CCRefrigeratorCN to i8*), i64 32) to [[TYPE]]*))
+// CHECK-32:    call [[TYPE]]* @swift_getForeignTypeMetadata([[TYPE]]* bitcast (i8* getelementptr inbounds (i8, i8* bitcast ({{.*}}* @_T0So14CCRefrigeratorCN to i8*), i32 12) to [[TYPE]]*))
+// CHECK-64:    call [[TYPE]]* @swift_getForeignTypeMetadata([[TYPE]]* bitcast (i8* getelementptr inbounds (i8, i8* bitcast ({{.*}}* @_T0So14CCRefrigeratorCN to i8*), i64 24) to [[TYPE]]*))
diff --git a/test/IRGen/class_bounded_generics.swift b/test/IRGen/class_bounded_generics.swift
index 21ea905..efa4d54 100644
--- a/test/IRGen/class_bounded_generics.swift
+++ b/test/IRGen/class_bounded_generics.swift
@@ -274,17 +274,17 @@
   }
 }
 
-// CHECK-LABEL: define hidden swiftcc void @_T022class_bounded_generics14takes_metatypeyxmlF(%swift.type*, %swift.type* %T)
+// CHECK-LABEL: define hidden swiftcc void @_T022class_bounded_generics14takes_metatypeyyxmlF(%swift.type*, %swift.type* %T)
 func takes_metatype<T>(_: T.Type) {}
 
-// CHECK-LABEL: define hidden swiftcc void @_T022class_bounded_generics023archetype_with_generic_A11_constraintyx1t_tAA1ACyq_GRbzr0_lF(%T22class_bounded_generics1AC.2*, %swift.type* %T)
+// CHECK-LABEL: define hidden swiftcc void @_T022class_bounded_generics023archetype_with_generic_A11_constraint1tyx_tAA1ACyq_GRbzr0_lF(%T22class_bounded_generics1AC.2*, %swift.type* %T)
 // CHECK:      [[ISA_ADDR:%.*]] = bitcast %T22class_bounded_generics1AC.2* %0 to %swift.type**
 // CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]]
-// CHECK-NEXT: call swiftcc void @_T022class_bounded_generics14takes_metatypeyxmlF(%swift.type* %T, %swift.type* %T)
+// CHECK-NEXT: call swiftcc void @_T022class_bounded_generics14takes_metatypeyyxmlF(%swift.type* %T, %swift.type* %T)
 // CHECK-NEXT: [[ISA_PTR:%.*]] = bitcast %swift.type* [[ISA]] to %swift.type**
 // CHECK-NEXT: [[U_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[ISA_PTR]], i64 10
 // CHECK-NEXT: [[U:%.*]] = load %swift.type*, %swift.type** [[U_ADDR]]
-// CHECK-NEXT: call swiftcc void @_T022class_bounded_generics14takes_metatypeyxmlF(%swift.type* %U, %swift.type* %U)
+// CHECK-NEXT: call swiftcc void @_T022class_bounded_generics14takes_metatypeyyxmlF(%swift.type* %U, %swift.type* %U)
 // CHECK:      ret void
 
 func archetype_with_generic_class_constraint<T, U>(t: T) where T : A<U> {
@@ -292,7 +292,7 @@
   takes_metatype(U.self)
 }
 
-// CHECK-LABEL: define hidden swiftcc void @_T022class_bounded_generics029calls_archetype_with_generic_A11_constraintyAA1ACyxG1a_tlF(%T22class_bounded_generics1AC*) #0 {
+// CHECK-LABEL: define hidden swiftcc void @_T022class_bounded_generics029calls_archetype_with_generic_A11_constraint1ayAA1ACyxG_tlF(%T22class_bounded_generics1AC*) #0 {
 // CHECK:      [[ISA_ADDR:%.*]] = getelementptr inbounds %T22class_bounded_generics1AC, %T22class_bounded_generics1AC* %0, i32 0, i32 0, i32 0
 // CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]]
 // CHECK:      [[SELF:%.*]] = bitcast %T22class_bounded_generics1AC* %0 to %T22class_bounded_generics1AC.2*
@@ -300,7 +300,7 @@
 // CHECK-NEXT: [[T_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[ISA_PTR]], i64 10
 // CHECK-NEXT: [[T:%.*]] = load %swift.type*, %swift.type** [[T_ADDR]]
 // CHECK-NEXT: [[A_OF_T:%.*]] = call %swift.type* @_T022class_bounded_generics1ACMa(%swift.type* [[T]])
-// CHECK-NEXT: call swiftcc void @_T022class_bounded_generics023archetype_with_generic_A11_constraintyx1t_tAA1ACyq_GRbzr0_lF(%T22class_bounded_generics1AC.2* [[SELF]], %swift.type* [[A_OF_T]])
+// CHECK-NEXT: call swiftcc void @_T022class_bounded_generics023archetype_with_generic_A11_constraint1tyx_tAA1ACyq_GRbzr0_lF(%T22class_bounded_generics1AC.2* [[SELF]], %swift.type* [[A_OF_T]])
 // CHECK:      ret void
 
 func calls_archetype_with_generic_class_constraint<T>(a: A<T>) {
diff --git a/test/IRGen/class_isa_pointers.sil b/test/IRGen/class_isa_pointers.sil
index 869bdb1..169be0d 100644
--- a/test/IRGen/class_isa_pointers.sil
+++ b/test/IRGen/class_isa_pointers.sil
@@ -59,7 +59,7 @@
 entry(%0 : $Purebred):
   unreachable
 }
-sil private @_T018class_isa_pointers7MongrelCSQyACGSi7bellsOn_tcfcTo : $@convention(objc_method) (Int, Purebred) -> () {
+sil private @_T018class_isa_pointers7MongrelC7bellsOnSQyACGSi_tcfcTo : $@convention(objc_method) (Int, Purebred) -> () {
 entry(%0 : $Int, %1 : $Purebred):
   unreachable
 }
diff --git a/test/IRGen/class_resilience.swift b/test/IRGen/class_resilience.swift
index 1c8aa3b..236c5c3 100644
--- a/test/IRGen/class_resilience.swift
+++ b/test/IRGen/class_resilience.swift
@@ -16,12 +16,24 @@
 // CHECK: @_T016class_resilience14ResilientChildC5fields5Int32VvpWvd = {{(protected )?}}global [[INT]] {{8|16}}
 // CHECK: @_T016class_resilience21ResilientGenericChildC5fields5Int32VvpWvi = {{(protected )?}}global [[INT]] {{56|88}}
 
+// CHECK: @_T016class_resilience26ClassWithResilientPropertyCMo = {{(protected )?}}constant [[INT]] {{52|80}}
+
 // CHECK: @_T016class_resilience28ClassWithMyResilientPropertyC1rAA0eF6StructVvpWvd = {{(protected )?}}constant [[INT]] {{8|16}}
 // CHECK: @_T016class_resilience28ClassWithMyResilientPropertyC5colors5Int32VvpWvd = {{(protected )?}}constant [[INT]] {{12|20}}
 
 // CHECK: @_T016class_resilience30ClassWithIndirectResilientEnumC1s14resilient_enum10FunnyShapeOvpWvd = {{(protected )?}}constant [[INT]] {{8|16}}
 // CHECK: @_T016class_resilience30ClassWithIndirectResilientEnumC5colors5Int32VvpWvd = {{(protected )?}}constant [[INT]] {{12|24}}
 
+// CHECK: @_T016class_resilience14ResilientChildCMo = {{(protected )?}}global [[INT]] 0
+
+// CHECK: @_T016class_resilience16FixedLayoutChildCMo = {{(protected )?}}global [[INT]] 0
+
+// CHECK: @_T016class_resilience21ResilientGenericChildCMo = {{(protected )?}}global [[INT]] 0
+
+// CHECK: @_T016class_resilience17MyResilientParentCMo = {{(protected )?}}constant [[INT]] {{52|80}}
+
+// CHECK: @_T016class_resilience16MyResilientChildCMo = {{(protected )?}}constant [[INT]] {{60|96}}
+
 import resilient_class
 import resilient_struct
 import resilient_enum
@@ -93,6 +105,14 @@
   public let field: Int32 = 0
 }
 
+// Superclass is resilient, but the class is fixed-layout.
+// This simulates a user app subclassing a class in a resilient
+// framework. In this case, we still want to emit a base offset
+// global.
+
+@_fixed_layout public class FixedLayoutChild : ResilientOutsideParent {
+  public let field: Int32 = 0
+}
 
 // Superclass is resilient, so the number of fields and their
 // offsets is not known at compile time
@@ -240,7 +260,7 @@
 // ClassWithResilientProperty metadata initialization function
 
 
-// CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_ClassWithResilientProperty
+// CHECK-LABEL: define private void @initialize_metadata_ClassWithResilientProperty
 // CHECK:             [[METADATA:%.*]] = call %swift.type* @swift_relocateClassMetadata({{.*}}, [[INT]] {{60|96}}, [[INT]] 4)
 // CHECK:             [[SIZE_METADATA:%.*]] = call %swift.type* @_T016resilient_struct4SizeVMa()
 // CHECK:             call void @swift_initClassMetadata_UniversalStrategy(%swift.type* [[METADATA]], [[INT]] 3, {{.*}})
@@ -257,7 +277,7 @@
 
 // ClassWithResilientlySizedProperty metadata initialization function
 
-// CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_ClassWithResilientlySizedProperty
+// CHECK-LABEL: define private void @initialize_metadata_ClassWithResilientlySizedProperty
 // CHECK:             [[METADATA:%.*]] = call %swift.type* @swift_relocateClassMetadata({{.*}}, [[INT]] {{60|96}}, [[INT]] 3)
 // CHECK:             [[RECTANGLE_METADATA:%.*]] = call %swift.type* @_T016resilient_struct9RectangleVMa()
 // CHECK:             call void @swift_initClassMetadata_UniversalStrategy(%swift.type* [[METADATA]], [[INT]] 2, {{.*}})
@@ -271,3 +291,62 @@
 // CHECK:             store atomic %swift.type* [[METADATA]], %swift.type** @_T016class_resilience33ClassWithResilientlySizedPropertyCML release,
 // CHECK:             ret void
 
+
+// CHECK-LABEL: define private void @initialize_metadata_ResilientChild(i8*)
+
+// Get the superclass...
+
+// CHECK:              [[SUPER:%.*]] = call %swift.type* @_T015resilient_class22ResilientOutsideParentCMa()
+// CHECK:              [[SUPER_ADDR:%.*]] = bitcast %swift.type* [[SUPER]] to i8*
+// CHECK:              [[SIZE_TMP:%.*]] = getelementptr inbounds i8, i8* [[SUPER_ADDR]], i32 {{36|56}}
+// CHECK:              [[SIZE_ADDR:%.*]] = bitcast i8* [[SIZE_TMP]] to i32*
+// CHECK:              [[SIZE:%.*]] = load i32, i32* [[SIZE_ADDR]]
+
+// Initialize class metadata base offset...
+// CHECK:              store [[INT]] {{.*}}, [[INT]]* @_T016class_resilience14ResilientChildCMo
+
+// Initialize the superclass field...
+// CHECK:              store %swift.type* [[SUPER]], %swift.type** getelementptr inbounds ({{.*}})
+
+// Relocate metadata if necessary...
+// CHECK:              call %swift.type* @swift_relocateClassMetadata(%swift.type* {{.*}}, [[INT]] {{60|96}}, [[INT]] 1)
+
+// CHECK:              ret void
+
+// CHECK-LABEL: define private void @initialize_metadata_FixedLayoutChild(i8*)
+
+// Get the superclass...
+
+// CHECK:              [[SUPER:%.*]] = call %swift.type* @_T015resilient_class22ResilientOutsideParentCMa()
+// CHECK:              [[SUPER_ADDR:%.*]] = bitcast %swift.type* [[SUPER]] to i8*
+// CHECK:              [[SIZE_TMP:%.*]] = getelementptr inbounds i8, i8* [[SUPER_ADDR]], i32 {{36|56}}
+// CHECK:              [[SIZE_ADDR:%.*]] = bitcast i8* [[SIZE_TMP]] to i32*
+// CHECK:              [[SIZE:%.*]] = load i32, i32* [[SIZE_ADDR]]
+
+// Initialize class metadata base offset...
+// CHECK:              store [[INT]] {{.*}}, [[INT]]* @_T016class_resilience16FixedLayoutChildCMo
+
+// Initialize the superclass field...
+// CHECK:              store %swift.type* [[SUPER]], %swift.type** getelementptr inbounds ({{.*}})
+
+// Relocate metadata if necessary...
+// CHECK:              call %swift.type* @swift_relocateClassMetadata(%swift.type* {{.*}}, [[INT]] {{60|96}}, [[INT]] 1)
+
+// CHECK:              ret void
+
+// CHECK-LABEL: define private %swift.type* @create_generic_metadata_ResilientGenericChild(%swift.type_pattern*, i8**)
+
+// Get the superclass...
+
+// CHECK:              [[SUPER:%.*]] = call %swift.type* @_T015resilient_class29ResilientGenericOutsideParentCMa(%swift.type* %T)
+// CHECK:              [[SUPER_TMP:%.*]] = bitcast %swift.type* [[SUPER]] to %objc_class*
+// CHECK:              [[SUPER_ADDR:%.*]] = bitcast %objc_class* [[SUPER_TMP]] to i8*
+// CHECK:              [[SIZE_TMP:%.*]] = getelementptr inbounds i8, i8* [[SUPER_ADDR]], i32 {{36|56}}
+// CHECK:              [[SIZE_ADDR:%.*]] = bitcast i8* [[SIZE_TMP]] to i32*
+// CHECK:              [[SIZE:%.*]] = load i32, i32* [[SIZE_ADDR]]
+
+// Initialize class metadata base offset...
+// CHECK:              store [[INT]] {{.*}}, [[INT]]* @_T016class_resilience21ResilientGenericChildCMo
+
+// CHECK:              [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_pattern* %0, i8** %1, %objc_class* [[SUPER_TMP]], [[INT]] 2)
+// CHECK:              ret %swift.type* [[METADATA]]
diff --git a/test/IRGen/class_resilience_objc.swift b/test/IRGen/class_resilience_objc.swift
index 83f1619..e3ab94d 100644
--- a/test/IRGen/class_resilience_objc.swift
+++ b/test/IRGen/class_resilience_objc.swift
@@ -13,7 +13,7 @@
   public final var field: Int32 = 0
 };
 
-// CHECK-LABEL: define hidden swiftcc void @_T021class_resilience_objc29testConstantDirectFieldAccessyAA23FixedLayoutObjCSubclassCF(%T21class_resilience_objc23FixedLayoutObjCSubclassC*)
+// CHECK-LABEL: define hidden swiftcc void @_T021class_resilience_objc29testConstantDirectFieldAccessyyAA23FixedLayoutObjCSubclassCF(%T21class_resilience_objc23FixedLayoutObjCSubclassC*)
 // CHECK:      [[OFFSET:%.*]] = load [[INT]], [[INT]]* @_T021class_resilience_objc23FixedLayoutObjCSubclassC5fields5Int32VvpWvd
 // CHECK-NEXT: [[OBJECT:%.*]] = bitcast %T21class_resilience_objc23FixedLayoutObjCSubclassC* %0 to i8*
 // CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds i8, i8* [[OBJECT]], [[INT]] [[OFFSET]]
@@ -32,7 +32,7 @@
   public final var field: Int32 = 0
 }
 
-// CHECK-LABEL: define hidden swiftcc void @_T021class_resilience_objc32testNonConstantDirectFieldAccessyAA0E23FixedLayoutObjCSubclassCF(%T21class_resilience_objc26NonFixedLayoutObjCSubclassC*)
+// CHECK-LABEL: define hidden swiftcc void @_T021class_resilience_objc32testNonConstantDirectFieldAccessyyAA0E23FixedLayoutObjCSubclassCF(%T21class_resilience_objc26NonFixedLayoutObjCSubclassC*)
 // CHECK:      [[OFFSET:%.*]] = load [[INT]], [[INT]]* @_T021class_resilience_objc26NonFixedLayoutObjCSubclassC5fields5Int32VvpWvd
 // CHECK-NEXT: [[OBJECT:%.*]] = bitcast %T21class_resilience_objc26NonFixedLayoutObjCSubclassC* %0 to i8*
 // CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds i8, i8* [[OBJECT]], [[INT]] [[OFFSET]]
@@ -54,7 +54,7 @@
   }
 }
 
-// CHECK-LABEL: define hidden swiftcc void @_T021class_resilience_objc31testConstantIndirectFieldAccessyAA19GenericObjCSubclassCyxGlF(%T21class_resilience_objc19GenericObjCSubclassC*)
+// CHECK-LABEL: define hidden swiftcc void @_T021class_resilience_objc31testConstantIndirectFieldAccessyyAA19GenericObjCSubclassCyxGlF(%T21class_resilience_objc19GenericObjCSubclassC*)
 
 // FIXME: we could eliminate the unnecessary isa load by lazily emitting
 // metadata sources in EmitPolymorphicParameters
diff --git a/test/IRGen/closure.swift b/test/IRGen/closure.swift
index f5549ed..f44d980 100644
--- a/test/IRGen/closure.swift
+++ b/test/IRGen/closure.swift
@@ -11,7 +11,7 @@
 }
 
 // -- Closure entry point
-// CHECK: define internal swiftcc i64 @_T07closure1aS2icSi1i_tFS2icfU_(i64, i64)
+// CHECK: define internal swiftcc i64 @_T07closure1a1iS2icSi_tFS2icfU_(i64, i64)
 
 protocol Ordinable {
   func ord() -> Int
@@ -22,14 +22,14 @@
 }
 
 // -- partial_apply stub
-// CHECK: define internal swiftcc i64 @_T07closure1aS2icSi1i_tFS2icfU_TA(i64, %swift.refcounted* swiftself)
+// CHECK: define internal swiftcc i64 @_T07closure1a1iS2icSi_tFS2icfU_TA(i64, %swift.refcounted* swiftself)
 // CHECK: }
 
 // -- Closure entry point
-// CHECK: define internal swiftcc i64 @_T07closure1bS2icx3seq_tAA9OrdinableRzlFS2icfU_(i64, %swift.refcounted*, %swift.type* %T, i8** %T.Ordinable) {{.*}} {
+// CHECK: define internal swiftcc i64 @_T07closure1b3seqS2icx_tAA9OrdinableRzlFS2icfU_(i64, %swift.refcounted*, %swift.type* %T, i8** %T.Ordinable) {{.*}} {
 
 // -- partial_apply stub
-// CHECK: define internal swiftcc i64 @_T07closure1bS2icx3seq_tAA9OrdinableRzlFS2icfU_TA(i64, %swift.refcounted* swiftself) {{.*}} {
+// CHECK: define internal swiftcc i64 @_T07closure1b3seqS2icx_tAA9OrdinableRzlFS2icfU_TA(i64, %swift.refcounted* swiftself) {{.*}} {
 // CHECK: entry:
 // CHECK:   [[CONTEXT:%.*]] = bitcast %swift.refcounted* %1 to <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>*
 // CHECK:   [[BINDINGSADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 1
@@ -40,12 +40,12 @@
 // CHECK:   [[WITNESS:%.*]] = load i8**, i8*** [[WITNESSADDR]], align 8
 // CHECK:   [[BOXADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 2
 // CHECK:   [[BOX:%.*]] = load %swift.refcounted*, %swift.refcounted** [[BOXADDR]], align 8
-// CHECK:   [[RES:%.*]] = tail call swiftcc i64 @_T07closure1bS2icx3seq_tAA9OrdinableRzlFS2icfU_(i64 %0, %swift.refcounted* [[BOX]], %swift.type* [[TYPE]], i8** [[WITNESS]])
+// CHECK:   [[RES:%.*]] = tail call swiftcc i64 @_T07closure1b3seqS2icx_tAA9OrdinableRzlFS2icfU_(i64 %0, %swift.refcounted* [[BOX]], %swift.type* [[TYPE]], i8** [[WITNESS]])
 // CHECK:   ret i64 [[RES]]
 // CHECK: }
 
 // -- <rdar://problem/14443343> Boxing of tuples with generic elements
-// CHECK: define hidden swiftcc { i8*, %swift.refcounted* } @_T07closure14captures_tuplex_q_tycx_q_t1x_tr0_lF(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U)
+// CHECK: define hidden swiftcc { i8*, %swift.refcounted* } @_T07closure14captures_tuple1xx_q_tycx_q_t_tr0_lF(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U)
 func captures_tuple<T, U>(x x: (T, U)) -> () -> (T, U) {
   // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_getTupleTypeMetadata2(%swift.type* %T, %swift.type* %U, i8* null, i8** null)
   // CHECK-NOT: @swift_getTupleTypeMetadata2
diff --git a/test/IRGen/conditional_conformances.swift b/test/IRGen/conditional_conformances.swift
index 25eda5c..29a16aa 100644
--- a/test/IRGen/conditional_conformances.swift
+++ b/test/IRGen/conditional_conformances.swift
@@ -1,7 +1,7 @@
-// RUN: %target-swift-frontend -enable-experimental-conditional-conformances -emit-ir %S/../Inputs/conditional_conformance_basic_conformances.swift | %FileCheck %S/../Inputs/conditional_conformance_basic_conformances.swift
-// RUN: %target-swift-frontend -enable-experimental-conditional-conformances -emit-ir %S/../Inputs/conditional_conformance_with_assoc.swift | %FileCheck %S/../Inputs/conditional_conformance_with_assoc.swift
-// RUN: %target-swift-frontend -enable-experimental-conditional-conformances -emit-ir %S/../Inputs/conditional_conformance_subclass.swift | %FileCheck %S/../Inputs/conditional_conformance_subclass.swift
-// RUN: %target-swift-frontend -enable-experimental-conditional-conformances -emit-ir %S/../Inputs/conditional_conformance_recursive.swift | %FileCheck %S/../Inputs/conditional_conformance_recursive.swift
+// RUN: %target-swift-frontend -emit-ir %S/../Inputs/conditional_conformance_basic_conformances.swift | %FileCheck %S/../Inputs/conditional_conformance_basic_conformances.swift
+// RUN: %target-swift-frontend -emit-ir %S/../Inputs/conditional_conformance_with_assoc.swift | %FileCheck %S/../Inputs/conditional_conformance_with_assoc.swift
+// RUN: %target-swift-frontend -emit-ir %S/../Inputs/conditional_conformance_subclass.swift | %FileCheck %S/../Inputs/conditional_conformance_subclass.swift
+// RUN: %target-swift-frontend -emit-ir %S/../Inputs/conditional_conformance_recursive.swift | %FileCheck %S/../Inputs/conditional_conformance_recursive.swift
 
 // Too many pointer-sized integers in the IR
 // REQUIRES: PTRSIZE=64
diff --git a/test/IRGen/conformance_access_path.swift b/test/IRGen/conformance_access_path.swift
new file mode 100644
index 0000000..a33f467
--- /dev/null
+++ b/test/IRGen/conformance_access_path.swift
@@ -0,0 +1,34 @@
+// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir > %t.ll
+// RUN: %FileCheck %s < %t.ll
+
+
+// SR-6200: canonicalizing a conformance access path that was built
+// without the requirement signature.
+public struct Valid<V> {}
+
+extension Valid where V: ValidationSuite {}
+
+public protocol Validatable {}
+
+extension Validatable {
+    public func tested() {}
+
+    // CHECK-LABEL: define{{.*}}_T023conformance_access_path11ValidatablePAAE6tested2byyqd__m_t9InputTypeQyd__RszAA15ValidationSuiteRd__lF
+    public func tested<S: ValidationSuite>(by suite: S.Type) where S.InputType == Self {
+      // CHECK:   [[S_AS_VALIDATION_SUITE:%[0-9]+]] = load i8*, i8** %S.ValidationSuite
+      // CHECK-NEXT:   [[S_VALIDATOR_BASE:%.*]] = bitcast i8* [[S_AS_VALIDATION_SUITE]] to i8**
+      // CHECK-NEXT: [[S_VALIDATABLE_ADDR:%[0-9]+]] = getelementptr inbounds i8*, i8** [[S_VALIDATOR_BASE]], i32 1
+      // CHECK-NEXT: [[S_VALIDATABLE_FN_RAW:%[0-9]+]] = load i8*, i8** [[S_VALIDATABLE_ADDR]]
+      // CHECK-NEXT: [[S_VALIDATABLE_FN:%[0-9]+]] = bitcast i8* [[S_VALIDATABLE_FN_RAW]] to i8** (%swift.type*, %swift.type*, i8**)*
+      // CHECK-NEXT: call i8** [[S_VALIDATABLE_FN]](%swift.type* %Self, %swift.type* %S, i8** %S.Validator)
+      tested()
+    }
+}
+
+public protocol Validator {
+    associatedtype InputType: Validatable
+}
+
+public protocol ValidationSuite: Validator {
+    associatedtype InputType: Validatable
+}
diff --git a/test/IRGen/dependent_reabstraction.swift b/test/IRGen/dependent_reabstraction.swift
index 0dfe776..3b24595 100644
--- a/test/IRGen/dependent_reabstraction.swift
+++ b/test/IRGen/dependent_reabstraction.swift
@@ -8,7 +8,7 @@
 }
 
 struct X<Y> : A {
-  // CHECK-LABEL: define internal swiftcc void @_T023dependent_reabstraction1XVyxGAA1AA2aEP1by1BQzFTW(%swift.type** noalias nocapture dereferenceable({{.*}}), %T23dependent_reabstraction1XV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable)
+  // CHECK-LABEL: define internal swiftcc void @_T023dependent_reabstraction1XVyxGAA1AA2aEP1byy1BQzFTW(%swift.type** noalias nocapture dereferenceable({{.*}}), %T23dependent_reabstraction1XV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable)
   func b(_ b: X.Type) {
     let x: Any = b
     markUsed(b as X.Type)
diff --git a/test/IRGen/dynamic_lookup.sil b/test/IRGen/dynamic_lookup.sil
index 51c1e1c..5f6e356 100644
--- a/test/IRGen/dynamic_lookup.sil
+++ b/test/IRGen/dynamic_lookup.sil
@@ -30,21 +30,21 @@
   return %14 : $()
 }
 
-sil @_T014dynamic_lookup1XCS2icigTo : $@convention(objc_method) (Int, X) -> Int {
+sil @_T014dynamic_lookup1XCyS2icigTo : $@convention(objc_method) (Int, X) -> Int {
 bb0(%0 : $Int, %1 : $X):
-  %4 = function_ref @_T0Si33_convertFromBuiltinIntegerLiteralSiBi64_3val_tcSimF : $@convention(thin) (Builtin.Int64, @thin Int.Type) -> Int // user: %7
+  %4 = function_ref @_T0Si33_convertFromBuiltinIntegerLiteralySiBi64_3val_tcSimF : $@convention(thin) (Builtin.Int64, @thin Int.Type) -> Int // user: %7
   %5 = metatype $@thin Int.Type
   %6 = integer_literal $Builtin.Int64, 5
   %7 = apply %4(%6, %5) : $@convention(thin) (Builtin.Int64, @thin Int.Type) -> Int // user: %9
   return %7 : $Int
 }
 
-sil @_T0Si33_convertFromBuiltinIntegerLiteralSiBi64_3val_tcSimF : $@convention(thin) (Builtin.Int64, @thin Int.Type) -> Int
+sil @_T0Si33_convertFromBuiltinIntegerLiteralySiBi64_3val_tcSimF : $@convention(thin) (Builtin.Int64, @thin Int.Type) -> Int
 
 // [objc] dynamic_lookup.X.value.getter : Swift.Int
 sil @_T014dynamic_lookup1XC5valueSivgTo : $@convention(objc_method) (X) -> Int {
 bb0(%0 : $X):
-  %4 = function_ref @_T0Si33_convertFromBuiltinIntegerLiteralSiBi64_3val_tcSimF : $@convention(thin) (Builtin.Int64, @thin Int.Type) -> Int // user: %7
+  %4 = function_ref @_T0Si33_convertFromBuiltinIntegerLiteralySiBi64_3val_tcSimF : $@convention(thin) (Builtin.Int64, @thin Int.Type) -> Int // user: %7
   %5 = metatype $@thin Int.Type
   %6 = integer_literal $Builtin.Int64, 5
   %7 = apply %4(%6, %5) : $@convention(thin) (Builtin.Int64, @thin Int.Type) -> Int // user: %9
diff --git a/test/IRGen/dynamic_self_metadata.swift b/test/IRGen/dynamic_self_metadata.swift
index 67ad2bf..64bcd6d 100644
--- a/test/IRGen/dynamic_self_metadata.swift
+++ b/test/IRGen/dynamic_self_metadata.swift
@@ -10,7 +10,7 @@
 @inline(never) func id<T>(_ t: T) -> T {
   return t
 }
-// CHECK-LABEL: define hidden swiftcc void @_T021dynamic_self_metadata2idxxlF
+// CHECK-LABEL: define hidden swiftcc void @_T021dynamic_self_metadata2idyxxlF
 
 class C {
   class func fromMetatype() -> Self? { return nil }
@@ -38,5 +38,5 @@
   // CHECK: [[CAST1:%.+]] = bitcast %T21dynamic_self_metadata1CC* %0 to [[METATYPE:%.+]]
   // CHECK: [[TYPE1:%.+]] = call %swift.type* @swift_getObjectType([[METATYPE]] [[CAST1]])
   // CHECK: [[TYPE2:%.+]] = call %swift.type* @_T0SqMa(%swift.type* [[TYPE1]])
-  // CHECK: call swiftcc void @_T021dynamic_self_metadata2idxxlF({{.*}}, %swift.type* [[TYPE2]])
+  // CHECK: call swiftcc void @_T021dynamic_self_metadata2idyxxlF({{.*}}, %swift.type* [[TYPE2]])
 }
diff --git a/test/IRGen/enum.sil b/test/IRGen/enum.sil
index 142114c..ef5ddd7 100644
--- a/test/IRGen/enum.sil
+++ b/test/IRGen/enum.sil
@@ -105,6 +105,11 @@
 //    implementations which are used if the instance has extra inhabitants.
 //    FIXME: Strings should be unnamed_addr. rdar://problem/22674524
 // CHECK: [[DYNAMICSINGLETON_FIELD_NAMES:@.*]] = private constant [7 x i8] c"value\00\00"
+// CHECK: @_T04enum16DynamicSingletonOWV =
+// CHECK-SAME:   i8* null
+// CHECK-SAME:   i8* bitcast (void (%swift.opaque*, i32, %swift.type*)* @_T04enum16DynamicSingletonOwxs to i8*)
+// CHECK-SAME:   i8* bitcast (i32 (%swift.opaque*, %swift.type*)* @_T04enum16DynamicSingletonOwxg to i8*)
+
 // CHECK: [[DYNAMICSINGLETON_NAME:@.*]] = private constant [25 x i8] c"4enum16DynamicSingletonO\00"
 // CHECK: @_T04enum16DynamicSingletonOMn = hidden constant <{ {{.*}} i32 }> <{
 // CHECK-SAME:   [25 x i8]* [[DYNAMICSINGLETON_NAME]]
@@ -128,12 +133,10 @@
 // CHECK-SAME:   i32 1
 // CHECK-SAME: }>
 
-// CHECK: @_T04enum16DynamicSingletonOMP = internal global <{ {{.*}}, [18 x i8*] }> <{
+// CHECK: @_T04enum16DynamicSingletonOMP = internal global <{ {{.*}}, %swift.type* }> <{
 // CHECK-SAME:   %swift.type* (%swift.type_pattern*, i8**)* @create_generic_metadata_DynamicSingleton
+// CHECK-SAME:   [18 x i8*]* @_T04enum16DynamicSingletonOWV
 // CHECK-SAME:   @_T04enum16DynamicSingletonOMn
-// CHECK-SAME:   i8* null
-// CHECK-SAME:   i8* bitcast (void (%swift.opaque*, i32, %swift.type*)* @_T04enum16DynamicSingletonOwxs to i8*)
-// CHECK-SAME:   i8* bitcast (i32 (%swift.opaque*, %swift.type*)* @_T04enum16DynamicSingletonOwxg to i8*)
 
 // -- No-payload enums have extra inhabitants in
 //    their value witness table.
@@ -171,13 +174,15 @@
 // CHECK-SAME:   i8* bitcast (i32 (%swift.opaque*, %swift.type*)* @_T04enum19SinglePayloadNestedOwxg to i8*)
 // CHECK-SAME: ]
 
-
-// CHECK: @_T04enum20DynamicSinglePayloadOMP = internal global <{ {{.*}}, [18 x i8*] }> <{
-// CHECK-SAME:   %swift.type* (%swift.type_pattern*, i8**)* @create_generic_metadata_DynamicSinglePayload
+// CHECK: @_T04enum20DynamicSinglePayloadOWV = internal constant [18 x i8*] [
 // CHECK-SAME:   i8* null
 // CHECK-SAME:   i8* bitcast (void (%swift.opaque*, i32, %swift.type*)* @_T04enum20DynamicSinglePayloadOwxs to i8*)
 // CHECK-SAME:   i8* bitcast (i32 (%swift.opaque*, %swift.type*)* @_T04enum20DynamicSinglePayloadOwxg to i8*)
 
+// CHECK: @_T04enum20DynamicSinglePayloadOMP = internal global <{ {{.*}}, %swift.type* }> <{
+// CHECK-SAME:   %swift.type* (%swift.type_pattern*, i8**)* @create_generic_metadata_DynamicSinglePayload
+// CHECK-SAME:   [18 x i8*]* @_T04enum20DynamicSinglePayloadOWV
+
 // CHECK: @_T04enum18MultiPayloadNestedOWV = internal constant [18 x i8*] [
 // -- size
 // CHECK-32-SAME:   i8* inttoptr ([[WORD]] 5 to i8*),
@@ -2682,8 +2687,7 @@
  return %tuple : $()
 }
 
-// -- Fill function for dynamic singleton. The value witness table flags just
-//    get copied over from the element.
+// -- Fill function for dynamic singleton.
 // CHECK: define{{( protected)?}} private %swift.type* @create_generic_metadata_DynamicSingleton(%swift.type_pattern*, i8**) {{.*}} {
 // CHECK:   [[T0:%.*]] = bitcast i8** %1 to %swift.type**
 // CHECK:   [[T:%T]] = load %swift.type*, %swift.type** [[T0]],
@@ -2692,48 +2696,17 @@
 // CHECK:   [[T1:%.*]] = getelementptr inbounds i8*, i8** [[METADATA_ARRAY]], i32 2
 // CHECK:   [[T0:%.*]] = bitcast %swift.type* [[T]] to i8*
 // CHECK:   store i8* [[T0]], i8** [[T1]]
-// CHECK:   [[VWT:%.*]] = getelementptr inbounds i8*, i8** [[METADATA_ARRAY]], i32 3
-// CHECK:   [[T0:%.*]] = bitcast i8** [[VWT]] to i8*
-// CHECK:   [[T1:%.*]] = getelementptr inbounds i8*, i8** [[METADATA_ARRAY]], i32 -1
-// CHECK:   store i8* [[T0]], i8** [[T1]]
 // CHECK:   [[T_VWTS:%.*]] = bitcast %swift.type* [[T]] to i8***
 // CHECK:   [[T_VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[T_VWTS]], [[WORD]] -1
 // CHECK:   [[T_VWT:%.*]] = load i8**, i8*** [[T_VWT_ADDR]]
 // CHECK:   [[T_LAYOUT:%.*]] = getelementptr inbounds i8*, i8** [[T_VWT]], i32 9
-// CHECK:   [[SIZE_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 9
-// CHECK:   [[T_SIZE_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[T_LAYOUT]], i32 0
-// CHECK:   [[T_SIZE:%.*]] = load i8*, i8** [[T_SIZE_ADDR]]
-// CHECK:   store i8* [[T_SIZE]], i8** [[SIZE_ADDR]]
-// CHECK:   [[STRIDE_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 11
-// CHECK:   [[T_STRIDE_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[T_LAYOUT]], i32 2
-// CHECK:   [[T_STRIDE:%.*]] = load i8*, i8** [[T_STRIDE_ADDR]]
-// CHECK:   store i8* [[T_STRIDE]], i8** [[STRIDE_ADDR]]
-// CHECK:   [[FLAGS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 10
-// CHECK:   [[T_FLAGS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[T_LAYOUT]], i32 1
-// CHECK:   [[T_FLAGS:%.*]] = load i8*, i8** [[T_FLAGS_ADDR]]
-// CHECK:   [[T_FLAGS_INT:%.*]] = ptrtoint i8* [[T_FLAGS]] to [[WORD]]
-// CHECK:   [[T_FLAGS_INT_2:%.*]] = or [[WORD]] [[T_FLAGS_INT]], 2097152
-// CHECK:   [[T_FLAGS_2:%.*]] = inttoptr [[WORD]] [[T_FLAGS_INT_2]] to i8*
-// CHECK:   store i8* [[T_FLAGS_2]], i8** [[FLAGS_ADDR]]
-// -- Test the 'has extra inhabitants' bit and carry over the extra inhabitants
-//    flag if set.
-// CHECK:   [[T_FLAGS_VAL:%.*]] = ptrtoint i8* [[T_FLAGS]] to [[WORD]]
-// CHECK:   [[XI_FLAG:%.*]] = and [[WORD]] [[T_FLAGS_VAL]], 262144
-// CHECK:   [[XI_BIT:%.*]] = icmp ne [[WORD]] [[XI_FLAG]], 0
-// CHECK:   br i1 [[XI_BIT]], label %[[HAS_XI:[0-9]+]], label %[[HAS_NO_XI:[0-9]+]]
-// CHECK: ; <label>:[[HAS_XI]]
-// CHECK:   [[XI_FLAGS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 12
-// CHECK:   [[T_XI_FLAGS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[T_LAYOUT]], i32 3
-// CHECK:   [[T_XI_FLAGS:%.*]] = load i8*, i8** [[T_XI_FLAGS_ADDR]]
-// CHECK:   store i8* [[T_XI_FLAGS]], i8** [[XI_FLAGS_ADDR]]
-// CHECK:   br label %[[HAS_NO_XI]]
-// CHECK: ; <label>:[[HAS_NO_XI]]
+// CHECK:   call void @swift_initEnumMetadataSingleCase(%swift.type* [[METADATA]], [[WORD]] 0, i8** [[T_LAYOUT]])
 // CHECK:   ret %swift.type* [[METADATA]]
 
 // -- Fill function for dynamic single-payload. Call into the runtime to
 //    calculate the size.
 // CHECK-LABEL: define{{( protected)?}} private %swift.type* @create_generic_metadata_DynamicSinglePayload(%swift.type_pattern*, i8**) {{.*}} {
-// CHECK:   call void @swift_initEnumValueWitnessTableSinglePayload
+// CHECK:   call void @swift_initEnumMetadataSinglePayload(%swift.type* [[METADATA]], [[WORD]] 0, i8** [[T_LAYOUT]], i32 3)
 
 // CHECK-64-LABEL: define linkonce_odr hidden void @_T04enum17StructWithWeakVarVwxs(%swift.opaque* noalias %dest, i32 %index, %swift.type* %StructWithWeakVar)
 // -- TODO: some pointless masking here.
diff --git a/test/IRGen/enum_derived.swift b/test/IRGen/enum_derived.swift
index a607e65..5cc89e6 100644
--- a/test/IRGen/enum_derived.swift
+++ b/test/IRGen/enum_derived.swift
@@ -17,8 +17,8 @@
 
 // Check if the == comparison can be compiled to a simple icmp instruction.
 
-// CHECK-NORMAL-LABEL:define hidden swiftcc i1 @_T012enum_derived1EO02__b1_A7_equalsSbAC_ACtFZ(i8, i8)
-// CHECK-TESTABLE-LABEL:define{{( protected)?}} swiftcc i1 @_T012enum_derived1EO02__b1_A7_equalsSbAC_ACtFZ(i8, i8)
+// CHECK-NORMAL-LABEL:define hidden swiftcc i1 @_T012enum_derived1EO02__b1_A7_equalsySbAC_ACtFZ(i8, i8)
+// CHECK-TESTABLE-LABEL:define{{( protected)?}} swiftcc i1 @_T012enum_derived1EO02__b1_A7_equalsySbAC_ACtFZ(i8, i8)
 // CHECK: %2 = icmp eq i8 %0, %1
 // CHECK: ret i1 %2
 
diff --git a/test/IRGen/enum_dynamic_multi_payload.sil b/test/IRGen/enum_dynamic_multi_payload.sil
index 53f5215..fea6b26 100644
--- a/test/IRGen/enum_dynamic_multi_payload.sil
+++ b/test/IRGen/enum_dynamic_multi_payload.sil
@@ -437,4 +437,4 @@
 // CHECK-NEXT: [[LAYOUT:%.*]] = getelementptr inbounds i8*, i8** [[VALUE_WITNESSES]], i32 9
 // CHECK-NEXT: store i8** [[LAYOUT]], {{.*}} [[BUF1]]
 
-// CHECK:   call void @swift_initEnumMetadataMultiPayload(i8** {{%.*}}, %swift.type* [[METADATA]], {{i(32|64)}} 2, i8*** [[BUF0]])
+// CHECK:   call void @swift_initEnumMetadataMultiPayload(%swift.type* [[METADATA]], {{i(32|64)}} 0, {{i(32|64)}} 2, i8*** [[BUF0]])
diff --git a/test/IRGen/enum_resilience.swift b/test/IRGen/enum_resilience.swift
index a26a675..14eb805 100644
--- a/test/IRGen/enum_resilience.swift
+++ b/test/IRGen/enum_resilience.swift
@@ -62,7 +62,7 @@
   case Right(ReferenceFast)
 }
 
-// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience25functionWithResilientEnum010resilient_A06MediumOAEF(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture)
+// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience25functionWithResilientEnumy010resilient_A06MediumOAEF(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture)
 public func functionWithResilientEnum(_ m: Medium) -> Medium {
 
 // CHECK:      [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum6MediumOMa()
@@ -78,7 +78,7 @@
   return m
 }
 
-// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience33functionWithIndirectResilientEnum010resilient_A00E8ApproachOAEF(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture)
+// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience33functionWithIndirectResilientEnumy010resilient_A00E8ApproachOAEF(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture)
 public func functionWithIndirectResilientEnum(_ ia: IndirectApproach) -> IndirectApproach {
 
 // CHECK:      [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum16IndirectApproachOMa()
@@ -110,7 +110,7 @@
   return Medium.Paper
 }
 
-// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience29constructResilientEnumPayload010resilient_A06MediumO0G7_struct4SizeVF
+// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience29constructResilientEnumPayloady010resilient_A06MediumO0G7_struct4SizeVF
 public func constructResilientEnumPayload(_ s: Size) -> Medium {
 // CHECK:      [[METADATA:%.*]] = call %swift.type* @_T016resilient_struct4SizeVMa()
 // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
@@ -141,7 +141,7 @@
   return Medium.Postcard(s)
 }
 
-// CHECK-LABEL: define{{( protected)?}} swiftcc {{i32|i64}} @_T015enum_resilience19resilientSwitchTestSi0c1_A06MediumOF(%swift.opaque* noalias nocapture)
+// CHECK-LABEL: define{{( protected)?}} swiftcc {{i32|i64}} @_T015enum_resilience19resilientSwitchTestySi0c1_A06MediumOF(%swift.opaque* noalias nocapture)
 // CHECK: [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum6MediumOMa()
 // CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
 // CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1
@@ -201,11 +201,11 @@
 
 public func reabstraction<T>(_ f: (Medium) -> T) {}
 
-// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience25resilientEnumPartialApplyySi0c1_A06MediumOcF(i8*, %swift.refcounted*)
+// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience25resilientEnumPartialApplyyySi0c1_A06MediumOcF(i8*, %swift.refcounted*)
 public func resilientEnumPartialApply(_ f: (Medium) -> Int) {
 
 // CHECK:     [[CONTEXT:%.*]] = call noalias %swift.refcounted* @swift_rt_swift_allocObject
-// CHECK:     call swiftcc void @_T015enum_resilience13reabstractionyx010resilient_A06MediumOclF(i8* bitcast (void (%TSi*, %swift.opaque*, %swift.refcounted*)* @_T014resilient_enum6MediumOSiIgid_ACSiIgir_TRTA to i8*), %swift.refcounted* [[CONTEXT:%.*]], %swift.type* @_T0SiN)
+// CHECK:     call swiftcc void @_T015enum_resilience13reabstractionyyx010resilient_A06MediumOclF(i8* bitcast (void (%TSi*, %swift.opaque*, %swift.refcounted*)* @_T014resilient_enum6MediumOSiIgid_ACSiIgir_TRTA to i8*), %swift.refcounted* [[CONTEXT:%.*]], %swift.type* @_T0SiN)
   reabstraction(f)
 
 // CHECK:     ret void
@@ -262,3 +262,4 @@
 }
 
 // CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_EnumWithResilientPayload(i8*)
+// CHECK: call void @swift_initEnumMetadataMultiPayload(%swift.type* {{.*}}, [[INT]] 256, [[INT]] 2, i8*** {{.*}})
diff --git a/test/IRGen/foreign_types.sil b/test/IRGen/foreign_types.sil
index 64d9669..89ef81f 100644
--- a/test/IRGen/foreign_types.sil
+++ b/test/IRGen/foreign_types.sil
@@ -4,9 +4,8 @@
 import c_layout
 
 // CHECK-LABEL: @_T0SC14HasNestedUnionV18__Unnamed_struct_sVN = linkonce_odr hidden global
-// CHECK-SAME:  i8* getelementptr inbounds
-// CHECK-SAME:  %swift.type* null,
-// CHECK-SAME:  [[INT:i[0-9]+]] 0,
+// CHECK-SAME:  [[INT:i[0-9]+]] sub ([[INT]] ptrtoint
+// CHECK-SAME:  [[INT]] 0,
 // CHECK-SAME:  @_T0SC14HasNestedUnionV18__Unnamed_struct_sVWV
 // CHECK-SAME:  [[INT]] 1,
 // CHECK-SAME:  @_T0SC14HasNestedUnionV18__Unnamed_struct_sVMn
diff --git a/test/IRGen/generic_casts.swift b/test/IRGen/generic_casts.swift
index c3cc34a..80a70be 100644
--- a/test/IRGen/generic_casts.swift
+++ b/test/IRGen/generic_casts.swift
@@ -31,7 +31,7 @@
 // CHECK:   @_PROTOCOL__TtP13generic_casts10ObjCProto1_
 // CHECK: }
 
-// CHECK: define hidden swiftcc i64 @_T013generic_casts8allToIntSixlF(%swift.opaque* noalias nocapture, %swift.type* %T)
+// CHECK: define hidden swiftcc i64 @_T013generic_casts8allToIntySixlF(%swift.opaque* noalias nocapture, %swift.type* %T)
 func allToInt<T>(_ x: T) -> Int {
   return x as! Int
   // CHECK: [[INT_TEMP:%.*]] = alloca %TSi,
@@ -51,7 +51,7 @@
   // CHECK: ret i64 [[INT_RESULT]]
 }
 
-// CHECK: define hidden swiftcc void @_T013generic_casts8intToAllxSilF(%swift.opaque* noalias nocapture sret, i64, %swift.type* %T) {{.*}} {
+// CHECK: define hidden swiftcc void @_T013generic_casts8intToAllyxSilF(%swift.opaque* noalias nocapture sret, i64, %swift.type* %T) {{.*}} {
 func intToAll<T>(_ x: Int) -> T {
   // CHECK: [[INT_TEMP:%.*]] = alloca %TSi,
   // CHECK: [[T0:%.*]] = getelementptr inbounds %TSi, %TSi* [[INT_TEMP]], i32 0, i32 0
@@ -61,7 +61,7 @@
   return x as! T
 }
 
-// CHECK: define hidden swiftcc i64 @_T013generic_casts8anyToIntSiypF(%Any* noalias nocapture dereferenceable({{.*}})) {{.*}} {
+// CHECK: define hidden swiftcc i64 @_T013generic_casts8anyToIntySiypF(%Any* noalias nocapture dereferenceable({{.*}})) {{.*}} {
 func anyToInt(_ x: Any) -> Int {
   return x as! Int
 }
@@ -77,7 +77,7 @@
 
 @objc class ObjCClass {}
 
-// CHECK: define hidden swiftcc %objc_object* @_T013generic_casts9protoCastAA10ObjCProto1_So9NSRuncingpAA0E6CClassCF(%T13generic_casts9ObjCClassC*) {{.*}} {
+// CHECK: define hidden swiftcc %objc_object* @_T013generic_casts9protoCastyAA10ObjCProto1_So9NSRuncingpAA0E6CClassCF(%T13generic_casts9ObjCClassC*) {{.*}} {
 func protoCast(_ x: ObjCClass) -> ObjCProto1 & NSRuncing {
   // CHECK: load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP13generic_casts10ObjCProto1_"
   // CHECK: load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$_NSRuncing"
@@ -94,7 +94,7 @@
 
 // <rdar://problem/15313840>
 // Class existential to opaque archetype cast
-// CHECK: define hidden swiftcc void @_T013generic_casts33classExistentialToOpaqueArchetypexAA10ObjCProto1_plF(%swift.opaque* noalias nocapture sret, %objc_object*, %swift.type* %T)
+// CHECK: define hidden swiftcc void @_T013generic_casts33classExistentialToOpaqueArchetypeyxAA10ObjCProto1_plF(%swift.opaque* noalias nocapture sret, %objc_object*, %swift.type* %T)
 func classExistentialToOpaqueArchetype<T>(_ x: ObjCProto1) -> T {
   var x = x
   // CHECK: [[X:%.*]] = alloca %T13generic_casts10ObjCProto1P
@@ -108,7 +108,7 @@
 protocol P {}
 protocol Q {}
 
-// CHECK: define hidden swiftcc void @_T013generic_casts19compositionToMemberAA1P_pAaC_AA1QpF{{.*}}(%T13generic_casts1PP* noalias nocapture sret, %T13generic_casts1P_AA1Qp* noalias nocapture dereferenceable({{.*}})) {{.*}} {
+// CHECK: define hidden swiftcc void @_T013generic_casts19compositionToMemberyAA1P_pAaC_AA1QpF{{.*}}(%T13generic_casts1PP* noalias nocapture sret, %T13generic_casts1P_AA1Qp* noalias nocapture dereferenceable({{.*}})) {{.*}} {
 func compositionToMember(_ a: P & Q) -> P {
   return a
 }
diff --git a/test/IRGen/generic_class_anyobject.swift b/test/IRGen/generic_class_anyobject.swift
index 8193ef8..837defd 100644
--- a/test/IRGen/generic_class_anyobject.swift
+++ b/test/IRGen/generic_class_anyobject.swift
@@ -5,6 +5,6 @@
 
 func foo<T: AnyObject>(_ x: T) -> T { return x }
 
-// CHECK-LABEL: define hidden swiftcc %objc_object* @_T023generic_class_anyobject3baryXlyXlF(%objc_object*)
+// CHECK-LABEL: define hidden swiftcc %objc_object* @_T023generic_class_anyobject3baryyXlyXlF(%objc_object*)
 // CHECK:         call swiftcc %objc_object* @_T023generic_class_anyobject3foo{{[_0-9a-zA-Z]*}}F
 func bar(_ x: AnyObject) -> AnyObject { return foo(x) }
diff --git a/test/IRGen/generic_classes_objc.sil b/test/IRGen/generic_classes_objc.sil
index 341c75b..ba17d2e 100644
--- a/test/IRGen/generic_classes_objc.sil
+++ b/test/IRGen/generic_classes_objc.sil
@@ -32,7 +32,7 @@
   unreachable
 }
 
-sil @_T020generic_classes_objc19GenericInheritsObjCCSQyACyxGGSi7bellsOn_tcfcTo : $@convention(objc_method) <T> (Int, @owned GenericInheritsObjC<T>) -> @owned GenericInheritsObjC<T> {
+sil @_T020generic_classes_objc19GenericInheritsObjCC7bellsOnSQyACyxGGSi_tcfcTo : $@convention(objc_method) <T> (Int, @owned GenericInheritsObjC<T>) -> @owned GenericInheritsObjC<T> {
 bb0(%0 : $Int, %1 : $GenericInheritsObjC<T>):
   unreachable
 }
@@ -60,7 +60,7 @@
   unreachable
 }
 
-sil @_T020generic_classes_objc20GenericInheritsObjC2CSQyACyxGGSi7bellsOn_tcfcTo : $@convention(objc_method) <T> (Int, @owned GenericInheritsObjC<T>) -> @owned GenericInheritsObjC<T> {
+sil @_T020generic_classes_objc20GenericInheritsObjC2C7bellsOnSQyACyxGGSi_tcfcTo : $@convention(objc_method) <T> (Int, @owned GenericInheritsObjC<T>) -> @owned GenericInheritsObjC<T> {
 bb0(%0 : $Int, %1 : $GenericInheritsObjC<T>):
   unreachable
 }
diff --git a/test/IRGen/generic_metatypes.swift b/test/IRGen/generic_metatypes.swift
index 8a7e0f9..440dcd1 100644
--- a/test/IRGen/generic_metatypes.swift
+++ b/test/IRGen/generic_metatypes.swift
@@ -8,7 +8,7 @@
 
 // REQUIRES: CODEGENERATOR=X86
 
-// CHECK: define hidden swiftcc %swift.type* [[GENERIC_TYPEOF:@_T017generic_metatypes0A6TypeofxmxlF]](%swift.opaque* noalias nocapture, %swift.type* [[TYPE:%.*]])
+// CHECK: define hidden swiftcc %swift.type* [[GENERIC_TYPEOF:@_T017generic_metatypes0A6TypeofyxmxlF]](%swift.opaque* noalias nocapture, %swift.type* [[TYPE:%.*]])
 func genericTypeof<T>(_ x: T) -> T.Type {
   // CHECK: [[METATYPE:%.*]] = call %swift.type* @swift_getDynamicType(%swift.opaque* {{.*}}, %swift.type* [[TYPE]], i1 false)
   // CHECK: ret %swift.type* [[METATYPE]]
@@ -60,13 +60,13 @@
 struct Zim : Bas {}
 class Zang : Bas {}
 
-// CHECK-LABEL: define hidden swiftcc { %swift.type*, i8** } @_T017generic_metatypes15metatypeErasureAA3Bas_pXpAA3ZimVmF() #0
+// CHECK-LABEL: define hidden swiftcc { %swift.type*, i8** } @_T017generic_metatypes15metatypeErasureyAA3Bas_pXpAA3ZimVmF() #0
 func metatypeErasure(_ z: Zim.Type) -> Bas.Type {
   // CHECK: ret { %swift.type*, i8** } {{.*}} @_T017generic_metatypes3ZimVMf, {{.*}} @_T017generic_metatypes3ZimVAA3BasAAWP
   return z
 }
 
-// CHECK-LABEL: define hidden swiftcc { %swift.type*, i8** } @_T017generic_metatypes15metatypeErasureAA3Bas_pXpAA4ZangCmF(%swift.type*) #0
+// CHECK-LABEL: define hidden swiftcc { %swift.type*, i8** } @_T017generic_metatypes15metatypeErasureyAA3Bas_pXpAA4ZangCmF(%swift.type*) #0
 func metatypeErasure(_ z: Zang.Type) -> Bas.Type {
   // CHECK: [[RET:%.*]] = insertvalue { %swift.type*, i8** } undef, %swift.type* %0, 0
   // CHECK: [[RET2:%.*]] = insertvalue { %swift.type*, i8** } [[RET]], i8** getelementptr inbounds ([0 x i8*], [0 x i8*]* @_T017generic_metatypes4ZangCAA3BasAAWP, i32 0, i32 0), 1
diff --git a/test/IRGen/generic_metatypes_arm.swift b/test/IRGen/generic_metatypes_arm.swift
index 9308d05..4449809 100644
--- a/test/IRGen/generic_metatypes_arm.swift
+++ b/test/IRGen/generic_metatypes_arm.swift
@@ -6,7 +6,7 @@
 
 // REQUIRES: CODEGENERATOR=ARM
 
-// CHECK: define hidden swiftcc %swift.type* [[GENERIC_TYPEOF:@_T017generic_metatypes0A6TypeofxmxlF]](%swift.opaque* noalias nocapture, %swift.type* [[TYPE:%.*]])
+// CHECK: define hidden swiftcc %swift.type* [[GENERIC_TYPEOF:@_T017generic_metatypes0A6TypeofyxmxlF]](%swift.opaque* noalias nocapture, %swift.type* [[TYPE:%.*]])
 func genericTypeof<T>(_ x: T) -> T.Type {
   // CHECK: [[METATYPE:%.*]] = call %swift.type* @swift_getDynamicType(%swift.opaque* {{.*}}, %swift.type* [[TYPE]], i1 false)
   // CHECK: ret %swift.type* [[METATYPE]]
@@ -58,13 +58,13 @@
 struct Zim : Bas {}
 class Zang : Bas {}
 
-// CHECK-LABEL: define hidden swiftcc { %swift.type*, i8** } @_T017generic_metatypes15metatypeErasureAA3Bas_pXpAA3ZimVmF() #0
+// CHECK-LABEL: define hidden swiftcc { %swift.type*, i8** } @_T017generic_metatypes15metatypeErasureyAA3Bas_pXpAA3ZimVmF() #0
 func metatypeErasure(_ z: Zim.Type) -> Bas.Type {
   // CHECK: ret { %swift.type*, i8** } {{.*}} @_T017generic_metatypes3ZimVMf, {{.*}} @_T017generic_metatypes3ZimVAA3BasAAWP
   return z
 }
 
-// CHECK-LABEL: define hidden swiftcc { %swift.type*, i8** } @_T017generic_metatypes15metatypeErasureAA3Bas_pXpAA4ZangCmF(%swift.type*) #0
+// CHECK-LABEL: define hidden swiftcc { %swift.type*, i8** } @_T017generic_metatypes15metatypeErasureyAA3Bas_pXpAA4ZangCmF(%swift.type*) #0
 func metatypeErasure(_ z: Zang.Type) -> Bas.Type {
   // CHECK: [[RET:%.*]] = insertvalue { %swift.type*, i8** } undef, %swift.type* %0, 0
   // CHECK: [[RET2:%.*]] = insertvalue { %swift.type*, i8** } [[RET]], i8** getelementptr inbounds ([0 x i8*], [0 x i8*]* @_T017generic_metatypes4ZangCAA3BasAAWP, i32 0, i32 0), 1
diff --git a/test/IRGen/generic_structs.sil b/test/IRGen/generic_structs.sil
index 6234bd8..6006411 100644
--- a/test/IRGen/generic_structs.sil
+++ b/test/IRGen/generic_structs.sil
@@ -6,7 +6,16 @@
 
 // -- Generic structs with dynamic layout contain the vwtable pattern as part
 //    of the metadata pattern, and no independent vwtable symbol
-// CHECK-NOT: @_T015generic_structs13SingleDynamicVWV
+// CHECK: @_T015generic_structs13SingleDynamicVWV = internal constant
+// CHECK-SAME:   i8* bitcast (%swift.opaque* ([24 x i8]*, [24 x i8]*, %swift.type*)* @_T015generic_structs13SingleDynamicVwCP to i8*),
+// -- ...
+// -- placeholder for size, flags, stride
+// CHECK-SAME:   i8* null, i8* null, i8* null
+// -- extra inhabitants
+// CHECK-SAME:   i8* null,
+// CHECK-SAME:   i8* bitcast (void (%swift.opaque*, i32, %swift.type*)* @_T015generic_structs13SingleDynamicVwxs to i8*),
+// CHECK-SAME:   i8* bitcast (i32 (%swift.opaque*, %swift.type*)* @_T015generic_structs13SingleDynamicVwxg to i8*)]
+
 //    FIXME: Strings should be unnamed_addr. rdar://problem/22674524
 // CHECK: [[SINGLEDYNAMIC_NAME:@.*]] = private constant [34 x i8] c"15generic_structs13SingleDynamicV\00"
 // CHECK: [[SINGLEDYNAMIC_FIELDS:@.*]] = private constant [3 x i8] c"x\00\00"
@@ -35,23 +44,13 @@
 // CHECK: @_T015generic_structs13SingleDynamicVMP = internal global <{ {{.*}} }> <{
 // -- template header
 // CHECK-SAME:   %swift.type* (%swift.type_pattern*, i8**)* @create_generic_metadata_SingleDynamic,
-// CHECK-SAME:   i32 168, i16 1, i16 16, [{{[0-9]+}} x i8*] zeroinitializer,
-// -- placeholder for vwtable pointer
-// CHECK-SAME:   i8* null,
+// CHECK-SAME:   i32 48, i16 1, i16 16, [{{[0-9]+}} x i8*] zeroinitializer,
+// -- vwtable pointer
+// CHECK-SAME:   @_T015generic_structs13SingleDynamicVWV
 // -- address point
 // CHECK-SAME:   i64 1, {{.*}}* @_T015generic_structs13SingleDynamicVMn
 // -- field offset vector; generic parameter vector
-// CHECK-SAME:   i64 0, %swift.type* null,
-// -- tail-allocated vwtable pattern
-// CHECK-SAME:   i8* bitcast (%swift.opaque* ([24 x i8]*, [24 x i8]*, %swift.type*)* @_T015generic_structs13SingleDynamicVwCP to i8*),
-// -- ...
-// -- placeholder for size, flags, stride
-// CHECK-SAME:   i8* null, i8* null, i8* null
-// -- extra inhabitants
-// CHECK-SAME:   i8* null,
-// CHECK-SAME:   i8* bitcast (void (%swift.opaque*, i32, %swift.type*)* @_T015generic_structs13SingleDynamicVwxs to i8*),
-// CHECK-SAME:   i8* bitcast (i32 (%swift.opaque*, %swift.type*)* @_T015generic_structs13SingleDynamicVwxg to i8*)] }>
-// CHECK-NOT: @_T015generic_structs13SingleDynamicVWV
+// CHECK-SAME:   i64 0, %swift.type* null }>
 
 // -- Nominal type descriptor for generic struct with protocol requirements
 //    FIXME: Strings should be unnamed_addr. rdar://problem/22674524
@@ -82,8 +81,7 @@
 
 // CHECK: @_T015generic_structs23DynamicWithRequirementsVMP = internal global <{ {{.*}} }> <{
 // -- field offset vector; generic parameter vector
-// CHECK:   i64 0, i64 0, %swift.type* null, %swift.type* null, i8** null, i8** null,
-// CHECK: }>
+// CHECK:   i64 0, i64 0, %swift.type* null, %swift.type* null, i8** null, i8** null }>
 
 // -- Fixed-layout struct metadata contains fixed field offsets
 // CHECK: @_T015generic_structs6IntishVMf = internal constant <{ {{.*}} i64 }> <{
@@ -219,16 +217,11 @@
 // CHECK:   [[T1:%.*]] = getelementptr inbounds i8*, i8** [[SELF_ARRAY]], i32 3
 // CHECK:   [[T0:%.*]] = bitcast %swift.type* %T to i8*
 // CHECK:   store i8* [[T0]], i8** [[T1]], align 8
-//   Fill vwtable reference.
-// CHECK:   [[VWTABLE_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[SELF_ARRAY]], i32 4
-// CHECK:   [[VWTABLE_VAL:%.*]] = bitcast i8** [[VWTABLE_ADDR]] to i8*
-// CHECK:   [[VWTABLE_SLOT_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[SELF_ARRAY]], i32 -1
-// CHECK:   store i8* [[VWTABLE_VAL]], i8** [[VWTABLE_SLOT_ADDR]], align 8
 //   Lay out fields.
 // CHECK:   [[T0:%.*]] = bitcast %swift.type* [[METADATA]] to i64*
 // CHECK:   [[T1:%.*]] = getelementptr inbounds i64, i64* [[T0]], i64 2
 // CHECK:   [[T2:%.*]] = getelementptr inbounds i8**, i8*** [[TYPES:%.*]], i32 0
-// CHECK:   call void @swift_initStructMetadata_UniversalStrategy(i64 1, i8*** [[TYPES]], i64* [[T1]], i8** [[VWTABLE_ADDR]])
+// CHECK:   call void @swift_initStructMetadata(%swift.type* [[METADATA]], i64 0, i64 1, i8*** [[TYPES]], i64* [[T1]])
 // CHECK:   ret %swift.type* [[METADATA]]
 // CHECK: }
 
diff --git a/test/IRGen/generic_tuples.swift b/test/IRGen/generic_tuples.swift
index 0ac2adc..d4fcee9 100644
--- a/test/IRGen/generic_tuples.swift
+++ b/test/IRGen/generic_tuples.swift
@@ -11,7 +11,7 @@
 // CHECK: %swift.tuple_element_type = type { [[TYPE]]*, i64 }
 
 func dup<T>(_ x: T) -> (T, T) { var x = x; return (x,x) }
-// CHECK:    define hidden swiftcc void @_T014generic_tuples3dupx_xtxlF(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
+// CHECK:    define hidden swiftcc void @_T014generic_tuples3dupyx_xtxlF(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
 // CHECK:    entry:
 //   Allocate a local variable for 'x'.
 // CHECK: [[TYPE_ADDR:%.*]] = bitcast %swift.type* %T to i8***
@@ -38,15 +38,15 @@
 
 
 func callDup(_ s: S) { _ = dup(s) }
-// CHECK-LABEL: define hidden swiftcc void @_T014generic_tuples7callDupyAA1SVF()
+// CHECK-LABEL: define hidden swiftcc void @_T014generic_tuples7callDupyyAA1SVF()
 // CHECK-NEXT: entry:
-// CHECK-NEXT: call swiftcc void @_T014generic_tuples3dupx_xtxlF({{.*}} undef, {{.*}} undef, %swift.type* {{.*}} @_T014generic_tuples1SVMf, {{.*}})
+// CHECK-NEXT: call swiftcc void @_T014generic_tuples3dupyx_xtxlF({{.*}} undef, {{.*}} undef, %swift.type* {{.*}} @_T014generic_tuples1SVMf, {{.*}})
 // CHECK-NEXT: ret void
 
 class C {}
 
 func dupC<T : C>(_ x: T) -> (T, T) { return (x, x) }
-// CHECK-LABEL: define hidden swiftcc { %T14generic_tuples1CC*, %T14generic_tuples1CC* } @_T014generic_tuples4dupCx_xtxAA1CCRbzlF(%T14generic_tuples1CC*, %swift.type* %T)
+// CHECK-LABEL: define hidden swiftcc { %T14generic_tuples1CC*, %T14generic_tuples1CC* } @_T014generic_tuples4dupCyx_xtxAA1CCRbzlF(%T14generic_tuples1CC*, %swift.type* %T)
 // CHECK-NEXT: entry:
 // CHECK:      [[REF:%.*]] = bitcast %T14generic_tuples1CC* %0 to %swift.refcounted*
 // CHECK-NEXT: call %swift.refcounted* @swift_rt_swift_retain(%swift.refcounted* returned [[REF]])
@@ -55,12 +55,12 @@
 // CHECK-NEXT: ret { %T14generic_tuples1CC*, %T14generic_tuples1CC* } [[TUP2]]
 
 func callDupC(_ c: C) { _ = dupC(c) }
-// CHECK-LABEL: define hidden swiftcc void @_T014generic_tuples8callDupCyAA1CCF(%T14generic_tuples1CC*)
+// CHECK-LABEL: define hidden swiftcc void @_T014generic_tuples8callDupCyyAA1CCF(%T14generic_tuples1CC*)
 // CHECK-NEXT: entry:
 // CHECK-NEXT: [[REF:%.*]] = bitcast %T14generic_tuples1CC* %0 to %swift.refcounted*
 // CHECK-NEXT: call %swift.refcounted* @swift_rt_swift_retain(%swift.refcounted* returned [[REF]])
 // CHECK-NEXT: [[METATYPE:%.*]] = call %swift.type* @_T014generic_tuples1CCMa()
-// CHECK-NEXT: [[TUPLE:%.*]] = call swiftcc { %T14generic_tuples1CC*, %T14generic_tuples1CC* } @_T014generic_tuples4dupCx_xtxAA1CCRbzlF(%T14generic_tuples1CC* %0, %swift.type* [[METATYPE]])
+// CHECK-NEXT: [[TUPLE:%.*]] = call swiftcc { %T14generic_tuples1CC*, %T14generic_tuples1CC* } @_T014generic_tuples4dupCyx_xtxAA1CCRbzlF(%T14generic_tuples1CC* %0, %swift.type* [[METATYPE]])
 // CHECK-NEXT: [[LEFT:%.*]] = extractvalue { %T14generic_tuples1CC*, %T14generic_tuples1CC* } [[TUPLE]], 0
 // CHECK-NEXT: [[RIGHT:%.*]] = extractvalue { %T14generic_tuples1CC*, %T14generic_tuples1CC* } [[TUPLE]], 1
 // CHECK-NEXT: [[LEFT_CAST:%.*]] = bitcast %T14generic_tuples1CC* [[LEFT]] to %swift.refcounted*
@@ -74,22 +74,22 @@
 // CHECK-NEXT: call void bitcast (void (%swift.refcounted*)* @swift_rt_swift_release to void (%T14generic_tuples1CC*)*)(%T14generic_tuples1CC* %0)
 // CHECK-NEXT: ret void
 
-// CHECK: define hidden swiftcc i64 @_T014generic_tuples4lumpSi_xxtxlF(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
+// CHECK: define hidden swiftcc i64 @_T014generic_tuples4lumpySi_xxtxlF(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
 func lump<T>(_ x: T) -> (Int, T, T) { return (0,x,x) }
-// CHECK: define hidden swiftcc { i64, i64 } @_T014generic_tuples5lump2Si_SixtxlF(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
+// CHECK: define hidden swiftcc { i64, i64 } @_T014generic_tuples5lump2ySi_SixtxlF(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
 func lump2<T>(_ x: T) -> (Int, Int, T) { return (0,0,x) }
-// CHECK: define hidden swiftcc void @_T014generic_tuples5lump3x_xxtxlF(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
+// CHECK: define hidden swiftcc void @_T014generic_tuples5lump3yx_xxtxlF(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
 func lump3<T>(_ x: T) -> (T, T, T) { return (x,x,x) }
-// CHECK: define hidden swiftcc i64 @_T014generic_tuples5lump4x_SixtxlF(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
+// CHECK: define hidden swiftcc i64 @_T014generic_tuples5lump4yx_SixtxlF(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
 func lump4<T>(_ x: T) -> (T, Int, T) { return (x,0,x) }
 
-// CHECK: define hidden swiftcc i64 @_T014generic_tuples6unlumpS2i_xxt_tlF(i64, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
+// CHECK: define hidden swiftcc i64 @_T014generic_tuples6unlumpyS2i_xxt_tlF(i64, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
 func unlump<T>(_ x: (Int, T, T)) -> Int { return x.0 }
-// CHECK: define hidden swiftcc void @_T014generic_tuples7unlump1xSi_xxt_tlF(%swift.opaque* noalias nocapture sret, i64, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
+// CHECK: define hidden swiftcc void @_T014generic_tuples7unlump1yxSi_xxt_tlF(%swift.opaque* noalias nocapture sret, i64, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T)
 func unlump1<T>(_ x: (Int, T, T)) -> T { return x.1 }
-// CHECK: define hidden swiftcc void @_T014generic_tuples7unlump2xx_Sixt_tlF(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, i64, %swift.opaque* noalias nocapture, %swift.type* %T)
+// CHECK: define hidden swiftcc void @_T014generic_tuples7unlump2yxx_Sixt_tlF(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, i64, %swift.opaque* noalias nocapture, %swift.type* %T)
 func unlump2<T>(_ x: (T, Int, T)) -> T { return x.0 }
-// CHECK: define hidden swiftcc i64 @_T014generic_tuples7unlump3Six_Sixt_tlF(%swift.opaque* noalias nocapture, i64, %swift.opaque* noalias nocapture, %swift.type* %T)
+// CHECK: define hidden swiftcc i64 @_T014generic_tuples7unlump3ySix_Sixt_tlF(%swift.opaque* noalias nocapture, i64, %swift.opaque* noalias nocapture, %swift.type* %T)
 func unlump3<T>(_ x: (T, Int, T)) -> Int { return x.1 }
 
 
diff --git a/test/IRGen/indirect_return.swift b/test/IRGen/indirect_return.swift
index 1633bd5..147df3a 100644
--- a/test/IRGen/indirect_return.swift
+++ b/test/IRGen/indirect_return.swift
@@ -9,3 +9,18 @@
   // CHECK: call %swift.opaque* {{%.*}}(%swift.opaque* noalias %0, %swift.opaque* noalias [[T1]], %swift.type* %T)
   return p.pointee
 }
+
+
+protocol Number {}
+extension Int: Number {}
+
+// Make sure that the absence of the sret attribute matches.
+// CHECK: define hidden swiftcc void @_T015indirect_return3fooSS_S2SAA6Number_pAaC_ptyF(<{ %TSS, %TSS, %TSS }>* noalias nocapture
+func foo() -> (String, String, String, Number, Number) {
+    return ("1", "2", "3", 42, 7)
+}
+// CHECK-LABEL: define{{.*}}testCall
+func testCall() {
+// CHECK: call swiftcc void @_T015indirect_return3fooSS_S2SAA6Number_pAaC_ptyF(<{ %TSS, %TSS, %TSS }>* noalias nocapture %{{.*}}
+  print(foo())
+}
diff --git a/test/IRGen/local_types.swift b/test/IRGen/local_types.swift
index b54fbe6..04f5c07 100644
--- a/test/IRGen/local_types.swift
+++ b/test/IRGen/local_types.swift
@@ -33,7 +33,7 @@
 }
 
 public func singleDefaultArgument(i: Int = {
-  // CHECK-DAG: @_T011local_types21singleDefaultArgumentySi1i_tFfA_SiycfU_06SingledE6StructL_VWV = internal constant
+  // CHECK-DAG: @_T011local_types21singleDefaultArgument1iySi_tFfA_SiycfU_06SingledE6StructL_VWV = internal constant
   struct SingleDefaultArgumentStruct {
     let i: Int
   }
diff --git a/test/IRGen/meta_meta_type.swift b/test/IRGen/meta_meta_type.swift
index 4ba4345..232fab4 100644
--- a/test/IRGen/meta_meta_type.swift
+++ b/test/IRGen/meta_meta_type.swift
@@ -10,7 +10,7 @@
 struct Mystruct : Proto {
 }
 
-// CHECKIR-LABEL: define hidden {{.*}} @_T005meta_A5_type6testitAA5Proto_pXpXpAaC_pF
+// CHECKIR-LABEL: define hidden {{.*}} @_T005meta_A5_type6testityAA5Proto_pXpXpAaC_pF
 // CHECKIR: [[M1:%[0-9]+]] = call {{.*}} @swift_getDynamicType
 // CHECKIR: [[M2:%[0-9]+]] = call {{.*}} @swift_getMetatypeMetadata(%swift.type* [[M1]])
 // CHECKIR: [[R1:%[0-9]+]] = insertvalue {{.*}} [[M2]]
@@ -20,7 +20,7 @@
   return type(of: type(of: p))
 }
 
-// CHECKIR-LABEL: define hidden {{.*}} @_T005meta_A5_type7testit2AA5Proto_pXpXpXpAaC_pF
+// CHECKIR-LABEL: define hidden {{.*}} @_T005meta_A5_type7testit2yAA5Proto_pXpXpXpAaC_pF
 // CHECKIR: [[M1:%[0-9]+]] = call {{.*}} @swift_getDynamicType
 // CHECKIR: [[M2:%[0-9]+]] = call {{.*}} @swift_getMetatypeMetadata(%swift.type* [[M1]])
 // CHECKIR: [[M3:%[0-9]+]] = call {{.*}} @swift_getMetatypeMetadata(%swift.type* [[M2]])
diff --git a/test/IRGen/metadata_dominance.swift b/test/IRGen/metadata_dominance.swift
index 909a65c..ad7dbb3 100644
--- a/test/IRGen/metadata_dominance.swift
+++ b/test/IRGen/metadata_dominance.swift
@@ -13,21 +13,21 @@
 // CHECK: call swiftcc i1 @_T018metadata_dominance4condSbyF()
   if cond() {
 // CHECK: [[T0:%.*]] = call %swift.type* @_T0yycMa()
-// CHECK: call swiftcc void @_T018metadata_dominance04use_A0yxlF(%swift.opaque* {{.*}}, %swift.type* [[T0]])
+// CHECK: call swiftcc void @_T018metadata_dominance04use_A0yyxlF(%swift.opaque* {{.*}}, %swift.type* [[T0]])
     use_metadata(voidToVoid)
 // CHECK: call swiftcc i1 @_T018metadata_dominance4condSbyF()
 // CHECK-NOT: @_T0yycMa
-// CHECK: call swiftcc void @_T018metadata_dominance04use_A0yxlF(%swift.opaque* {{.*}}, %swift.type* [[T0]])
+// CHECK: call swiftcc void @_T018metadata_dominance04use_A0yyxlF(%swift.opaque* {{.*}}, %swift.type* [[T0]])
     if cond() {
       use_metadata(voidToVoid)
     } else {
 // CHECK-NOT: @_T0yycMa
-// CHECK: call swiftcc void @_T018metadata_dominance04use_A0yxlF(%swift.opaque* {{.*}}, %swift.type* [[T0]])
+// CHECK: call swiftcc void @_T018metadata_dominance04use_A0yyxlF(%swift.opaque* {{.*}}, %swift.type* [[T0]])
       use_metadata(voidToVoid)
     }
   }
 // CHECK: [[T1:%.*]] = call %swift.type* @_T0yycMa()
-// CHECK: call swiftcc void @_T018metadata_dominance04use_A0yxlF(%swift.opaque* {{.*}}, %swift.type* [[T1]])
+// CHECK: call swiftcc void @_T018metadata_dominance04use_A0yyxlF(%swift.opaque* {{.*}}, %swift.type* [[T1]])
   use_metadata(voidToVoid)
 }
 
@@ -37,17 +37,17 @@
   if cond() {
 // CHECK: call swiftcc i1 @_T018metadata_dominance4condSbyF()
 // CHECK: [[T0:%.*]] = call %swift.type* @_T0yycMa()
-// CHECK: call swiftcc void @_T018metadata_dominance04use_A0yxlF(%swift.opaque* {{.*}}, %swift.type* [[T0]])
+// CHECK: call swiftcc void @_T018metadata_dominance04use_A0yyxlF(%swift.opaque* {{.*}}, %swift.type* [[T0]])
     if cond() {
       use_metadata(voidToVoid)
     } else {
 // CHECK: [[T1:%.*]] = call %swift.type* @_T0yycMa()
-// CHECK: call swiftcc void @_T018metadata_dominance04use_A0yxlF(%swift.opaque* {{.*}}, %swift.type* [[T1]])
+// CHECK: call swiftcc void @_T018metadata_dominance04use_A0yyxlF(%swift.opaque* {{.*}}, %swift.type* [[T1]])
       use_metadata(voidToVoid)
     }
   }
 // CHECK: [[T2:%.*]] = call %swift.type* @_T0yycMa()
-// CHECK: call swiftcc void @_T018metadata_dominance04use_A0yxlF(%swift.opaque* {{.*}}, %swift.type* [[T2]])
+// CHECK: call swiftcc void @_T018metadata_dominance04use_A0yyxlF(%swift.opaque* {{.*}}, %swift.type* [[T2]])
   use_metadata(voidToVoid)
 }
 
diff --git a/test/IRGen/newtype.swift b/test/IRGen/newtype.swift
index ee50e60..90f0b00 100644
--- a/test/IRGen/newtype.swift
+++ b/test/IRGen/newtype.swift
@@ -24,7 +24,7 @@
   // CHECK: ret
 }
 
-// CHECK-LABEL: _T07newtype21getGlobalNotificationSSSiF
+// CHECK-LABEL: _T07newtype21getGlobalNotificationySSSiF
 public func getGlobalNotification(_ x: Int) -> String {
   switch x {
     case 1: return kNotification
@@ -39,7 +39,7 @@
 // CHECK: ret
 }
 
-// CHECK-LABEL: _T07newtype17getCFNewTypeValueSC0cD0VSb6useVar_tF
+// CHECK-LABEL: _T07newtype17getCFNewTypeValue6useVarSC0cD0VSb_tF
 public func getCFNewTypeValue(useVar: Bool) -> CFNewType {
   if (useVar) {
     return CFNewType.MyCFNewTypeValue
@@ -51,7 +51,7 @@
   // CHECK: ret
 }
 
-// CHECK-LABEL: _T07newtype21getUnmanagedCFNewTypes0C0VySo8CFStringCGSb6useVar_tF
+// CHECK-LABEL: _T07newtype21getUnmanagedCFNewType6useVars0C0VySo8CFStringCGSb_tF
 public func getUnmanagedCFNewType(useVar: Bool) -> Unmanaged<CFString> {
   if (useVar) {
     return CFNewType.MyCFNewTypeValueUnaudited
@@ -132,26 +132,26 @@
 }
 
 class ObjCTest {
-  // CHECK-LABEL: define hidden %0* @_T07newtype8ObjCTestC19optionalPassThroughSC11ErrorDomainVSgAGFTo
+  // CHECK-LABEL: define hidden %0* @_T07newtype8ObjCTestC19optionalPassThroughySC11ErrorDomainVSgAGFTo
   // CHECK: [[CASTED:%.+]] = ptrtoint %0* %2 to i{{32|64}}
-  // CHECK: [[RESULT:%.+]] = call swiftcc i{{32|64}} @_T07newtype8ObjCTestC19optionalPassThroughSC11ErrorDomainVSgAGF(i{{32|64}} [[CASTED]], %T7newtype8ObjCTestC* swiftself {{%.+}})
+  // CHECK: [[RESULT:%.+]] = call swiftcc i{{32|64}} @_T07newtype8ObjCTestC19optionalPassThroughySC11ErrorDomainVSgAGF(i{{32|64}} [[CASTED]], %T7newtype8ObjCTestC* swiftself {{%.+}})
   // CHECK: [[OPAQUE_RESULT:%.+]] = inttoptr i{{32|64}} [[RESULT]] to %0*
   // CHECK: ret %0* [[OPAQUE_RESULT]]
   // CHECK: {{^}$}}
 
-  // OPT-LABEL: define hidden %0* @_T07newtype8ObjCTestC19optionalPassThroughSC11ErrorDomainVSgAGFTo
+  // OPT-LABEL: define hidden %0* @_T07newtype8ObjCTestC19optionalPassThroughySC11ErrorDomainVSgAGFTo
   // OPT: ret %0* %2
   // OPT: {{^}$}}
   @objc func optionalPassThrough(_ ed: ErrorDomain?) -> ErrorDomain? {
     return ed
   }
 
-  // CHECK-LABEL: define hidden i32 @_T07newtype8ObjCTestC18integerPassThroughSC5MyIntVAFFTo
-  // CHECK: [[RESULT:%.+]] = call swiftcc i32 @_T07newtype8ObjCTestC18integerPassThroughSC5MyIntVAFF(i32 %2, %T7newtype8ObjCTestC* swiftself {{%.+}})
+  // CHECK-LABEL: define hidden i32 @_T07newtype8ObjCTestC18integerPassThroughySC5MyIntVAFFTo
+  // CHECK: [[RESULT:%.+]] = call swiftcc i32 @_T07newtype8ObjCTestC18integerPassThroughySC5MyIntVAFF(i32 %2, %T7newtype8ObjCTestC* swiftself {{%.+}})
   // CHECK: ret i32 [[RESULT]]
   // CHECK: {{^}$}}
 
-  // OPT-LABEL: define hidden i32 @_T07newtype8ObjCTestC18integerPassThroughSC5MyIntVAFFTo
+  // OPT-LABEL: define hidden i32 @_T07newtype8ObjCTestC18integerPassThroughySC5MyIntVAFFTo
   // OPT: ret i32 %2
   // OPT: {{^}$}}
   @objc func integerPassThrough(_ num: MyInt) -> MyInt {
diff --git a/test/IRGen/objc.swift b/test/IRGen/objc.swift
index bdca9a0..5e73969 100644
--- a/test/IRGen/objc.swift
+++ b/test/IRGen/objc.swift
@@ -124,7 +124,7 @@
 // Force the emission of the Rect metadata.
 func test11_helper<T>(_ t: T) {}
 // NSRect's metadata needs to be uniqued at runtime using getForeignTypeMetadata.
-// CHECK-LABEL: define hidden swiftcc void @_T04objc6test11ySC4RectVF
+// CHECK-LABEL: define hidden swiftcc void @_T04objc6test11yySC4RectVF
 // CHECK:         call %swift.type* @swift_getForeignTypeMetadata({{.*}} @_T0SC4RectVN
 func test11(_ r: Rect) { test11_helper(r) }
 
diff --git a/test/IRGen/objc_attr_NSManaged.sil b/test/IRGen/objc_attr_NSManaged.sil
index e49c573..98c08c2 100644
--- a/test/IRGen/objc_attr_NSManaged.sil
+++ b/test/IRGen/objc_attr_NSManaged.sil
@@ -27,7 +27,7 @@
 // The getter/setter should not show up in the Swift metadata.
 /* FIXME: sil_vtable parser picks the wrong 'init' overload. Both vtable entries
    ought to be nonnull here. rdar://problem/19572342 */
-// CHECK: @_T019objc_attr_NSManaged10SwiftGizmoCMf = internal global <{ {{.*}} }> <{ void (%T19objc_attr_NSManaged10SwiftGizmoC*)* @_T019objc_attr_NSManaged10SwiftGizmoCfD, i8** @_T0BOWV, i64 ptrtoint (%objc_class* @"OBJC_METACLASS_$__TtC19objc_attr_NSManaged10SwiftGizmo" to i64), %objc_class* @"OBJC_CLASS_$_Gizmo", %swift.opaque* @_objc_empty_cache, %swift.opaque* null, i64 add (i64 ptrtoint ({ i32, i32, i32, i32, i8*, i8*, { i32, i32, [2 x { i8*, i8*, i8* }] }*, i8*, i8*, i8*, { i32, i32, [1 x { i8*, i8* }] }* }* @_DATA__TtC19objc_attr_NSManaged10SwiftGizmo to i64), i64 1), i32 1, i32 0, i32 8, i16 7, i16 0, i32 112, i32 16, {{.*}}* @_T019objc_attr_NSManaged10SwiftGizmoCMn, i8* null, %T19objc_attr_NSManaged10SwiftGizmoC* (i64, %T19objc_attr_NSManaged10SwiftGizmoC*)* @_T019objc_attr_NSManaged10SwiftGizmoCACSi7bellsOn_tcfc, i8* bitcast (void ()* @swift_deletedMethodError to i8*) }>
+// CHECK: @_T019objc_attr_NSManaged10SwiftGizmoCMf = internal global <{ {{.*}} }> <{ void (%T19objc_attr_NSManaged10SwiftGizmoC*)* @_T019objc_attr_NSManaged10SwiftGizmoCfD, i8** @_T0BOWV, i64 ptrtoint (%objc_class* @"OBJC_METACLASS_$__TtC19objc_attr_NSManaged10SwiftGizmo" to i64), %objc_class* @"OBJC_CLASS_$_Gizmo", %swift.opaque* @_objc_empty_cache, %swift.opaque* null, i64 add (i64 ptrtoint ({ i32, i32, i32, i32, i8*, i8*, { i32, i32, [2 x { i8*, i8*, i8* }] }*, i8*, i8*, i8*, { i32, i32, [1 x { i8*, i8* }] }* }* @_DATA__TtC19objc_attr_NSManaged10SwiftGizmo to i64), i64 1), i32 1, i32 0, i32 8, i16 7, i16 0, i32 112, i32 16, {{.*}}* @_T019objc_attr_NSManaged10SwiftGizmoCMn, i8* null, %T19objc_attr_NSManaged10SwiftGizmoC* (i64, %T19objc_attr_NSManaged10SwiftGizmoC*)* @_T019objc_attr_NSManaged10SwiftGizmoC7bellsOnACSi_tcfc, i8* bitcast (void ()* @swift_deletedMethodError to i8*) }>
 
 @objc class SwiftGizmo : Gizmo {
   @objc @NSManaged var x: X
@@ -43,7 +43,7 @@
   return %0 : $SwiftGizmo
 }
 
-sil @_T019objc_attr_NSManaged10SwiftGizmoCSQyACGSi7bellsOn_tcfcTo : $@convention(objc_method) (Int, @owned SwiftGizmo) -> @owned SwiftGizmo? {
+sil @_T019objc_attr_NSManaged10SwiftGizmoC7bellsOnSQyACGSi_tcfcTo : $@convention(objc_method) (Int, @owned SwiftGizmo) -> @owned SwiftGizmo? {
 bb0(%0 : $Int, %1 : $SwiftGizmo):
   unreachable
 }
@@ -53,17 +53,17 @@
   return %0 : $SwiftGizmo
 }
 
-sil @_T019objc_attr_NSManaged10SwiftGizmoCACSi7bellsOn_tcfc : $@convention(method) (Int, @owned SwiftGizmo) -> @owned SwiftGizmo {
+sil @_T019objc_attr_NSManaged10SwiftGizmoC7bellsOnACSi_tcfc : $@convention(method) (Int, @owned SwiftGizmo) -> @owned SwiftGizmo {
 bb0(%0 : $Int, %1 : $SwiftGizmo):
   return %1 : $SwiftGizmo
 }
 
 sil @_T019objc_attr_NSManaged10SwiftGizmoCfD : $@convention(method) (@owned SwiftGizmo) -> ()
 
-sil @_T019objc_attr_NSManaged10SwiftGizmoCSQyACGSi7bellsOn_tcfc : $@convention(method) (Int, @owned SwiftGizmo) -> Int
+sil @_T019objc_attr_NSManaged10SwiftGizmoC7bellsOnSQyACGSi_tcfc : $@convention(method) (Int, @owned SwiftGizmo) -> Int
 
 /* FIXME: sil_vtable parser picks the wrong 'init' overload. rdar://problem/19572342 */
 sil_vtable SwiftGizmo {
   // #SwiftGizmo.init!initializer.1: _T019objc_attr_NSManaged10SwiftGizmoCACycfc
-  #SwiftGizmo.init!initializer.1: _T019objc_attr_NSManaged10SwiftGizmoCACSi7bellsOn_tcfc
+  #SwiftGizmo.init!initializer.1: _T019objc_attr_NSManaged10SwiftGizmoC7bellsOnACSi_tcfc
 }
diff --git a/test/IRGen/objc_bridge.swift b/test/IRGen/objc_bridge.swift
index f357d04..34cc43d 100644
--- a/test/IRGen/objc_bridge.swift
+++ b/test/IRGen/objc_bridge.swift
@@ -63,7 +63,7 @@
 // CHECK:     { i8*, i8*, i8* } {
 // CHECK:       i8* getelementptr inbounds ([{{[0-9]*}} x i8], [{{[0-9]*}} x i8]* @"\01L_selector_data(strArgWithS:)", i64 0, i64 0),
 // CHECK:       i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
-// CHECK:       i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_T011objc_bridge3BasC6strArgySS1s_tFTo to i8*)
+// CHECK:       i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_T011objc_bridge3BasC6strArg1sySS_tFTo to i8*)
 // CHECK:     },
 // CHECK:     { i8*, i8*, i8* } {
 // CHECK:       i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(nsstrResult)", i64 0, i64 0),
@@ -73,7 +73,7 @@
 // CHECK:     { i8*, i8*, i8* } {
 // CHECK:       i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* @"\01L_selector_data(nsstrArgWithS:)", i64 0, i64 0),
 // CHECK:       i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
-// CHECK:       i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_T011objc_bridge3BasC8nsstrArgySo8NSStringC1s_tFTo to i8*)
+// CHECK:       i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_T011objc_bridge3BasC8nsstrArg1sySo8NSStringC_tFTo to i8*)
 // CHECK:     },
 // CHECK:     { i8*, i8*, i8* } { 
 // CHECK:       i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0), 
@@ -88,7 +88,7 @@
 // CHECK:     { i8*, i8*, i8* } {
 // CHECK:       i8* getelementptr inbounds ([11 x i8], [11 x i8]* @"\01L_selector_data(acceptSet:)", i64 0, i64 0),
 // CHECK:       i8* getelementptr inbounds ([11 x i8], [11 x i8]* @{{[0-9]+}}, i64 0, i64 0),
-// CHECK:       i8* bitcast (void (%3*, i8*, %4*)* @_T011objc_bridge3BasC9acceptSetys0E0VyACGFTo to i8*)
+// CHECK:       i8* bitcast (void (%3*, i8*, %4*)* @_T011objc_bridge3BasC9acceptSetyys0E0VyACGFTo to i8*)
 // CHECK:     }
 // CHECK:     { i8*, i8*, i8* } { 
 // CHECK:       i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i64 0, i64 0), 
@@ -142,7 +142,7 @@
   // CHECK: define internal [[OPAQUE:.*]]* @_T0So8NSStringC11objc_bridgeE11nsstrResultAByFTo([[OPAQUE:.*]]*, i8*) unnamed_addr
   func nsstrResult() -> NSString { return NSS }
 
-  // CHECK: define internal void @_T0So8NSStringC11objc_bridgeE8nsstrArgyAB1s_tFTo([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr
+  // CHECK: define internal void @_T0So8NSStringC11objc_bridgeE8nsstrArg1syAB_tFTo([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr
   func nsstrArg(s s: NSString) { }
 }
 
@@ -175,12 +175,12 @@
 
   // CHECK: define internal [[OPAQUE:.*]]* @_T011objc_bridge3BasC9strResultSSyFTo([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} {
   func strResult() -> String { return "" }
-  // CHECK: define internal void @_T011objc_bridge3BasC6strArgySS1s_tFTo([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
+  // CHECK: define internal void @_T011objc_bridge3BasC6strArg1sySS_tFTo([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
   func strArg(s s: String) { }
 
   // CHECK: define internal [[OPAQUE:.*]]* @_T011objc_bridge3BasC11nsstrResultSo8NSStringCyFTo([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} {
   func nsstrResult() -> NSString { return NSS }
-  // CHECK: define internal void @_T011objc_bridge3BasC8nsstrArgySo8NSStringC1s_tFTo([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
+  // CHECK: define internal void @_T011objc_bridge3BasC8nsstrArg1sySo8NSStringC_tFTo([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
   func nsstrArg(s s: NSString) { }
 
   override init() { 
diff --git a/test/IRGen/objc_class_export.swift b/test/IRGen/objc_class_export.swift
index b502a83..c48c4e8 100644
--- a/test/IRGen/objc_class_export.swift
+++ b/test/IRGen/objc_class_export.swift
@@ -58,7 +58,7 @@
 // CHECK:   %swift.opaque* null,
 // CHECK:   i64 add (i64 ptrtoint ({{.*}}* @_DATA__TtC17objc_class_export3Foo to i64), i64 1),
 // CHECK:   [[FOO]]* (%swift.type*)* @_T017objc_class_export3FooC6createACyFZ,
-// CHECK:   void (double, double, double, double, [[FOO]]*)* @_T017objc_class_export3FooC10drawInRectySC6NSRectV5dirty_tF
+// CHECK:   void (double, double, double, double, [[FOO]]*)* @_T017objc_class_export3FooC10drawInRect5dirtyySC6NSRectV_tF
 // CHECK: }>, section "__DATA,__objc_data, regular"
 // -- TODO: The OBJC_CLASS symbol should reflect the qualified runtime name of
 //    Foo.
@@ -82,9 +82,9 @@
 
   @objc func drawInRect(dirty dirty: NSRect) {
   }
-  // CHECK: define internal void @_T017objc_class_export3FooC10drawInRectySC6NSRectV5dirty_tFTo([[OPAQUE:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} {
+  // CHECK: define internal void @_T017objc_class_export3FooC10drawInRect5dirtyySC6NSRectV_tFTo([[OPAQUE:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} {
   // CHECK:   [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE]]* %0 to [[FOO]]*
-  // CHECK:   call swiftcc void @_T017objc_class_export3FooC10drawInRectySC6NSRectV5dirty_tF(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]])
+  // CHECK:   call swiftcc void @_T017objc_class_export3FooC10drawInRect5dirtyySC6NSRectV_tF(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]])
   // CHECK: }
 
   @objc func bounds() -> NSRect {
@@ -98,19 +98,19 @@
   @objc func convertRectToBacking(r r: NSRect) -> NSRect {
     return r
   }
-  // CHECK: define internal void @_T017objc_class_export3FooC20convertRectToBackingSC6NSRectVAF1r_tFTo([[NSRECT]]* noalias nocapture sret, [[OPAQUE5:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} {
+  // CHECK: define internal void @_T017objc_class_export3FooC20convertRectToBacking1rSC6NSRectVAG_tFTo([[NSRECT]]* noalias nocapture sret, [[OPAQUE5:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} {
   // CHECK:   [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE5]]* %1 to [[FOO]]*
-  // CHECK:   call swiftcc { double, double, double, double } @_T017objc_class_export3FooC20convertRectToBackingSC6NSRectVAF1r_tF(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]])
+  // CHECK:   call swiftcc { double, double, double, double } @_T017objc_class_export3FooC20convertRectToBacking1rSC6NSRectVAG_tF(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]])
 
   func doStuffToSwiftSlice(f f: [Int]) {
   }
   // This function is not representable in Objective-C, so don't emit the objc entry point.
-  // CHECK-NOT: @_T017objc_class_export3FooC19doStuffToSwiftSliceySaySiG1f_tcAAFTo
+  // CHECK-NOT: @_T017objc_class_export3FooC19doStuffToSwiftSlice1fySaySiG_tcAAFTo
 
   func doStuffToBigSwiftStruct(f f: BigStructWithNativeObjects) {
   }
   // This function is not representable in Objective-C, so don't emit the objc entry point.
-  // CHECK-NOT: @_TToFC17objc_class_export3Foo23doStuffToBigSwiftStructfS_FT1fV17objc_class_export27BigStructWithNativeObjects_T_
+  // CHECK-NOT: @_TToFC17objc_class_export3Foo23doStuffToBigSwiftStruct1ffS_FTV17objc_class_export27BigStructWithNativeObjects_T_
 
   init() { }
 }
diff --git a/test/IRGen/objc_class_export.swift.tmp b/test/IRGen/objc_class_export.swift.tmp
new file mode 100644
index 0000000..21eea91
--- /dev/null
+++ b/test/IRGen/objc_class_export.swift.tmp
@@ -0,0 +1,107 @@
+// RUN: %empty-directory(%t)
+// RUN: %build-irgen-test-overlays
+// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -sdk %S/Inputs -I %t -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s
+
+// REQUIRES: CPU=x86_64
+// REQUIRES: objc_interop
+
+// CHECK: %swift.refcounted = type
+// CHECK: [[HOOZIT:%T17objc_class_export6HoozitC]] = type <{ [[REF:%swift.refcounted]] }>
+// CHECK: [[FOO:%T17objc_class_export3FooC]] = type <{ [[REF]], %TSi }>
+// CHECK: [[INT:%TSi]] = type <{ i64 }>
+// CHECK: [[DOUBLE:%TSd]] = type <{ double }>
+// CHECK: [[NSRECT:%TSC6NSRectV]] = type <{ %TSC7NSPointV, %TSC6NSSizeV }>
+// CHECK: [[NSPOINT:%TSC7NSPointV]] = type <{ %TSd, %TSd }>
+// CHECK: [[NSSIZE:%TSC6NSSizeV]] = type <{ %TSd, %TSd }>
+// CHECK: [[OBJC:%objc_object]] = type opaque
+
+// CHECK: @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" = hidden global %objc_class {
+// CHECK:   %objc_class* @"OBJC_METACLASS_$_SwiftObject",
+// CHECK:   %objc_class* @"OBJC_METACLASS_$_SwiftObject",
+// CHECK:   %swift.opaque* @_objc_empty_cache,
+// CHECK:   %swift.opaque* null,
+// CHECK:   i64 ptrtoint ({{.*}}* @_METACLASS_DATA__TtC17objc_class_export3Foo to i64)
+// CHECK: }
+// CHECK: [[FOO_NAME:@.*]] = private unnamed_addr constant [28 x i8] c"_TtC17objc_class_export3Foo\00"
+// CHECK: @_METACLASS_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } {
+// CHECK:   i32 129,
+// CHECK:   i32 40,
+// CHECK:   i32 40,
+// CHECK:   i32 0,
+// CHECK:   i8* null,
+// CHECK:   i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0),
+// CHECK:   @_CLASS_METHODS__TtC17objc_class_export3Foo,
+// CHECK:   i8* null,
+// CHECK:   i8* null,
+// CHECK:   i8* null,
+// CHECK:   i8* null
+// CHECK: }, section "__DATA, __objc_const", align 8
+// CHECK: @_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } {
+// CHECK:   i32 128,
+// CHECK:   i32 16,
+// CHECK:   i32 24,
+// CHECK:   i32 0,
+// CHECK:   i8* null,
+// CHECK:   i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0),
+// CHECK:   { i32, i32, [6 x { i8*, i8*, i8* }] }* @_INSTANCE_METHODS__TtC17objc_class_export3Foo,
+// CHECK:   i8* null,
+// CHECK:   @_IVARS__TtC17objc_class_export3Foo,
+// CHECK:   i8* null,
+// CHECK:   _PROPERTIES__TtC17objc_class_export3Foo
+// CHECK: }, section "__DATA, __objc_const", align 8
+// CHECK: @_T017objc_class_export3FooCMf = internal global <{{.*i64}} }> <{
+// CHECK:   void ([[FOO]]*)* @_T017objc_class_export3FooCfD,
+// CHECK:   i8** @_T0BOWV,
+// CHECK:   i64 ptrtoint (%objc_class* @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" to i64),
+// CHECK:   %objc_class* @"OBJC_CLASS_$_SwiftObject",
+// CHECK:   %swift.opaque* @_objc_empty_cache,
+// CHECK:   %swift.opaque* null,
+// CHECK:   i64 add (i64 ptrtoint ({{.*}}* @_DATA__TtC17objc_class_export3Foo to i64), i64 1),
+// CHECK:   [[FOO]]* (%swift.type*)* @_T017objc_class_export3FooC6createACyFZ,
+// CHECK:   void (double, double, double, double, [[FOO]]*)* @_T017objc_class_export3FooC10drawInRect5dirtyySC6NSRectV_tF
+// CHECK: }>, section "__DATA,__objc_data, regular"
+// -- TODO: The OBJC_CLASS symbol should reflect the qualified runtime name of
+//    Foo.
+// CHECK: @_T017objc_class_export3FooCN = hidden alias %swift.type, bitcast (i64* getelementptr inbounds ({{.*}} @_T017objc_class_export3FooCMf, i32 0, i32 2) to %swift.type*)
+// CHECK: @"OBJC_CLASS_$__TtC17objc_class_export3Foo" = hidden alias %swift.type, %swift.type* @_T017objc_class_export3FooCN
+
+import gizmo
+
+class Hoozit {}
+
+struct BigStructWithNativeObjects {
+  var x, y, w : Double
+  var h : Hoozit
+}
+
+@objc class Foo {
+  @objc var x = 0
+  @objc class func create() -> Foo {
+    return Foo()
+  }
+
+  @objc func drawInRect(dirty dirty: NSRect) {
+  }
+  // CHECK: define internal void @_T017objc_class_export3FooC10drawInRectySC6NSRectV5dirty_tFTo([[OPAQUE:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} {
+  // CHECK:   [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE]]* %0 to [[FOO]]*
+  // CHECK:   call swiftcc void @_T017objc_class_export3FooC10drawInRectySC6NSRectV5dirty_tF(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]])
+  // CHECK: }
+
+  @objc func bounds() -> NSRect {
+    return NSRect(origin: NSPoint(x: 0, y: 0),
+                  size: NSSize(width: 0, height: 0))
+  }
+  // CHECK: define internal void @_T017objc_class_export3FooC6boundsSC6NSRectVyFTo([[NSRECT]]* noalias nocapture sret, [[OPAQUE4:%.*]]*, i8*) unnamed_addr {{.*}} {
+  // CHECK:   [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE4]]* %1 to [[FOO]]*
+  // CHECK:   call swiftcc { double, double, double, double } @_T017objc_class_export3FooC6boundsSC6NSRectVyF([[FOO]]* swiftself [[CAST]])
+
+  @objc func convertRectToBacking(r r: NSRect) -> NSRect {
+    return r
+  }
+  // CHECK: define internal void @_T017objc_class_export3FooC20convertRectToBackingSC6NSRectVAF1r_tFTo([[NSRECT]]* noalias nocapture sret, [[OPAQUE5:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} {
+  // CHECK:   [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE5]]* %1 to [[FOO]]*
+  // CHECK:   call swiftcc { double, double, double, double } @_T017objc_class_export3FooC20convertRectToBackingSC6NSRectVAF1r_tF(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]])
+
+  func doStuffToSwiftSlice(f f: [Int]) {
+  }
+  // This function is not representable in Objective-C, so don't emit the objc entry point.
diff --git a/test/IRGen/objc_dealloc.sil b/test/IRGen/objc_dealloc.sil
index 0413004..8924536 100644
--- a/test/IRGen/objc_dealloc.sil
+++ b/test/IRGen/objc_dealloc.sil
@@ -129,7 +129,7 @@
   return %0 : $SwiftGizmo
 }
 
-sil @_T012objc_dealloc10SwiftGizmoCSQyACGSi7bellsOn_tcfcTo : $@convention(objc_method) (Int, @owned SwiftGizmo) -> @owned SwiftGizmo? {
+sil @_T012objc_dealloc10SwiftGizmoC7bellsOnSQyACGSi_tcfcTo : $@convention(objc_method) (Int, @owned SwiftGizmo) -> @owned SwiftGizmo? {
 bb0(%0 : @trivial $Int, %1 : @owned $SwiftGizmo):
   unreachable
 }
diff --git a/test/IRGen/objc_generic_class_metadata.sil b/test/IRGen/objc_generic_class_metadata.sil
index 4fa627c..d3564c0 100644
--- a/test/IRGen/objc_generic_class_metadata.sil
+++ b/test/IRGen/objc_generic_class_metadata.sil
@@ -56,12 +56,12 @@
   return undef : $()
 }
 
-sil @_T027objc_generic_class_metadata8SubclassCSQyACGSQySo8NSStringCG5thing_tcfcTo : $@convention(objc_method) (Optional<NSString>, @owned Subclass) -> @owned Optional<Subclass> {
+sil @_T027objc_generic_class_metadata8SubclassC5thingSQyACGSQySo8NSStringCG_tcfcTo : $@convention(objc_method) (Optional<NSString>, @owned Subclass) -> @owned Optional<Subclass> {
 entry(%0: $Optional<NSString>, %1: $Subclass):
   unreachable
 }
 
-sil @_T027objc_generic_class_metadata8SubclassCSQyACGSaySo8NSStringCG13arrayOfThings_tcfcTo : $@convention(objc_method) (NSArray, @owned Subclass) -> @owned Optional<Subclass> {
+sil @_T027objc_generic_class_metadata8SubclassC13arrayOfThingsSQyACGSaySo8NSStringCG_tcfcTo : $@convention(objc_method) (NSArray, @owned Subclass) -> @owned Optional<Subclass> {
 entry(%0: $NSArray, %1: $Subclass):
   unreachable
 }
@@ -71,7 +71,7 @@
   unreachable
 }
 
-sil @_T027objc_generic_class_metadata8SubclassCSQyACGs10DictionaryVySC13GenericOptionVypGSg7options_tcfcTo : $@convention(objc_method) (@owned Subclass, @owned NSDictionary) -> @owned Subclass {
+sil @_T027objc_generic_class_metadata8SubclassC7optionsSQyACGs10DictionaryVySC13GenericOptionVypGSg_tcfcTo : $@convention(objc_method) (@owned Subclass, @owned NSDictionary) -> @owned Subclass {
 entry(%0: $Subclass, %1: $NSDictionary):
   unreachable
 }
diff --git a/test/IRGen/objc_globals.swift b/test/IRGen/objc_globals.swift
index 3ab1ae8..37459dc 100644
--- a/test/IRGen/objc_globals.swift
+++ b/test/IRGen/objc_globals.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/abi %s -whole-module-optimization -emit-ir %s | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/abi %s -whole-module-optimization -emit-ir | %FileCheck %s
 // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/abi %s -emit-ir | %FileCheck %s
 //
 // REQUIRES: objc_interop
diff --git a/test/IRGen/objc_implicit_with.sil b/test/IRGen/objc_implicit_with.sil
index b1dbaf9..c2dbf0a 100644
--- a/test/IRGen/objc_implicit_with.sil
+++ b/test/IRGen/objc_implicit_with.sil
@@ -22,12 +22,12 @@
 }
 sil_vtable SwiftGizmo {}
 
-sil @_T018objc_implicit_with10SwiftGizmoCACSf3red_Sf5greenSf4bluetcfcTo : $@convention(objc_method) (Float, Float, Float, @owned SwiftGizmo) -> @owned SwiftGizmo {
+sil @_T018objc_implicit_with10SwiftGizmoC3red5green4blueACSf_S2ftcfcTo : $@convention(objc_method) (Float, Float, Float, @owned SwiftGizmo) -> @owned SwiftGizmo {
 bb0(%0 : $Float, %1 : $Float, %2 : $Float, %3 : $SwiftGizmo):
   return %3 : $SwiftGizmo
 }
 
-sil @_T018objc_implicit_with10SwiftGizmoCSQyACGSi7bellsOn_tcfcTo : $@convention(objc_method) (Int, @owned SwiftGizmo) -> @owned SwiftGizmo? {
+sil @_T018objc_implicit_with10SwiftGizmoC7bellsOnSQyACGSi_tcfcTo : $@convention(objc_method) (Int, @owned SwiftGizmo) -> @owned SwiftGizmo? {
 bb0(%0 : $Int, %1 : $SwiftGizmo):
   unreachable
 }
@@ -37,12 +37,12 @@
   return %0 : $SwiftGizmo
 }
 
-sil @_T018objc_implicit_with10SwiftGizmoC5colorySf3red_Sf5greenSf4bluetFTo : $@convention(objc_method) (Float, Float, Float, @owned SwiftGizmo) -> @owned SwiftGizmo {
+sil @_T018objc_implicit_with10SwiftGizmoC5color3red5green4blueySf_S2ftFTo : $@convention(objc_method) (Float, Float, Float, @owned SwiftGizmo) -> @owned SwiftGizmo {
 bb0(%0 : $Float, %1 : $Float, %2 : $Float, %3 : $SwiftGizmo):
   return %3 : $SwiftGizmo
 }
 
-sil @_T018objc_implicit_with10SwiftGizmoC13otherColorForySf3red_Sf5greenSf4bluetFTo : $@convention(objc_method) (Float, Float, Float, @owned SwiftGizmo) -> @owned SwiftGizmo {
+sil @_T018objc_implicit_with10SwiftGizmoC13otherColorFor3red5green4blueySf_S2ftFTo : $@convention(objc_method) (Float, Float, Float, @owned SwiftGizmo) -> @owned SwiftGizmo {
 bb0(%0 : $Float, %1 : $Float, %2 : $Float, %3 : $SwiftGizmo):
   return %3 : $SwiftGizmo
 }
diff --git a/test/IRGen/objc_int_encoding.sil b/test/IRGen/objc_int_encoding.sil
index 0f2cfdf..dfabfbb 100644
--- a/test/IRGen/objc_int_encoding.sil
+++ b/test/IRGen/objc_int_encoding.sil
@@ -6,7 +6,7 @@
 // CHECK-64: [[INT_UINT_METHOD_ENCODING:@.*]] = private unnamed_addr constant {{.*}} c"Q24@0:8q16\00"
 // CHECK-32: [[INT_UINT_METHOD_ENCODING:@.*]] = private unnamed_addr constant {{.*}} c"I12@0:4i8\00"
 
-// CHECK: @_INSTANCE_METHODS__TtC17objc_int_encoding3Foo = private constant {{.*}} [[SELECTOR]], {{.*}} [[INT_UINT_METHOD_ENCODING]], {{.*}} @_T017objc_int_encoding3FooC3fooSuSi1x_tFTo
+// CHECK: @_INSTANCE_METHODS__TtC17objc_int_encoding3Foo = private constant {{.*}} [[SELECTOR]], {{.*}} [[INT_UINT_METHOD_ENCODING]], {{.*}} @_T017objc_int_encoding3FooC3foo1xSuSi_tFTo
 
 sil_stage canonical
 
@@ -20,7 +20,7 @@
   @objc func foo(x: Int) -> UInt
 }
 
-sil hidden @_T017objc_int_encoding3FooC3fooSuSi1x_tFTo : $@convention(objc_method) (Int, @guaranteed Foo) -> UInt {
+sil hidden @_T017objc_int_encoding3FooC3foo1xSuSi_tFTo : $@convention(objc_method) (Int, @guaranteed Foo) -> UInt {
 entry(%0 : $Int, %1 : $Foo):
   unreachable
 }
diff --git a/test/IRGen/objc_methods.swift b/test/IRGen/objc_methods.swift
index 04bec8f..b7c1a31 100644
--- a/test/IRGen/objc_methods.swift
+++ b/test/IRGen/objc_methods.swift
@@ -50,15 +50,15 @@
 // CHECK:   }, {
 // CHECK:     i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(garply:)", i64 0, i64 0),
 // CHECK:     i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[GARPLY_SIGNATURE]], i64 0, i64 0),
-// CHECK:     i8* bitcast (void (i8*, i8*, i8*)* @_T012objc_methods3FooC6garplyyyXlSgFTo to i8*)
+// CHECK:     i8* bitcast (void (i8*, i8*, i8*)* @_T012objc_methods3FooC6garplyyyyXlSgFTo to i8*)
 // CHECK:   }, {
 // CHECK:     i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(block:)", i64 0, i64 0),
 // CHECK:     i8* getelementptr inbounds ([12 x i8], [12 x i8]* [[BLOCK_SIGNATURE_TRAD]], i64 0, i64 0),
-// CHECK:     i8* bitcast (void (i8*, i8*, i64 (i64)*)* @_T012objc_methods3FooC5blockyS2icFTo to i8*)
+// CHECK:     i8* bitcast (void (i8*, i8*, i64 (i64)*)* @_T012objc_methods3FooC5blockyyS2icFTo to i8*)
 // CHECK:   }, {
 // CHECK:     i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(block2:)", i64 0, i64 0),
 // CHECK:     i8* getelementptr inbounds ([12 x i8], [12 x i8]* [[BLOCK_SIGNATURE_TRAD]], i64 0, i64 0),
-// CHECK:     i8* bitcast (void (i8*, i8*, i64 (i64, i64)*)* @_T012objc_methods3FooC6block2yS2i_SitcFTo to i8*)
+// CHECK:     i8* bitcast (void (i8*, i8*, i64 (i64, i64)*)* @_T012objc_methods3FooC6block2yyS2i_SitcFTo to i8*)
 // CHECK:   }, {
 // CHECK:     i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(failAndReturnError:)", i64 0, i64 0),
 // CHECK:     i8* getelementptr inbounds ([12 x i8], [12 x i8]* [[FAIL_SIGNATURE]], i64 0, i64 0),
diff --git a/test/IRGen/objc_ns_enum.swift b/test/IRGen/objc_ns_enum.swift
index 43a76b6..3fd39fb 100644
--- a/test/IRGen/objc_ns_enum.swift
+++ b/test/IRGen/objc_ns_enum.swift
@@ -98,7 +98,7 @@
   return .Foo
 }
 
-// CHECK-LABEL: define hidden swiftcc i64 @_T012objc_ns_enum0a1_C7_switchSiAA14ExportedToObjCOF(i64)
+// CHECK-LABEL: define hidden swiftcc i64 @_T012objc_ns_enum0a1_C7_switchySiAA14ExportedToObjCOF(i64)
 // CHECK:         switch i64 %0, label {{%.*}} [
 // CHECK:           i64 -1, label {{%.*}}
 // CHECK:           i64  0, label {{%.*}}
@@ -115,7 +115,7 @@
 }
 
 @objc class ObjCEnumMethods : NSObject {
-  // CHECK: define internal void @_T012objc_ns_enum15ObjCEnumMethodsC0C2InyAA010ExportedToD1COFTo([[OBJC_ENUM_METHODS:.*]]*, i8*, i64)
+  // CHECK: define internal void @_T012objc_ns_enum15ObjCEnumMethodsC0C2InyyAA010ExportedToD1COFTo([[OBJC_ENUM_METHODS:.*]]*, i8*, i64)
   dynamic func enumIn(_ x: ExportedToObjC) {}
   // CHECK: define internal i64 @_T012objc_ns_enum15ObjCEnumMethodsC0C3OutAA010ExportedToD1COyFTo([[OBJC_ENUM_METHODS]]*, i8*)
   dynamic func enumOut() -> ExportedToObjC { return .Foo }
@@ -125,7 +125,7 @@
   dynamic var prop: ExportedToObjC = .Foo
 }
 
-// CHECK-LABEL: define hidden swiftcc void @_T012objc_ns_enum0a1_C13_method_callsyAA15ObjCEnumMethodsCF(%T12objc_ns_enum15ObjCEnumMethodsC*)
+// CHECK-LABEL: define hidden swiftcc void @_T012objc_ns_enum0a1_C13_method_callsyyAA15ObjCEnumMethodsCF(%T12objc_ns_enum15ObjCEnumMethodsC*)
 func objc_enum_method_calls(_ x: ObjCEnumMethods) {
   
   // CHECK: call i64 bitcast (void ()* @objc_msgSend to i64 ([[OBJC_ENUM_METHODS]]*, i8*)*)
diff --git a/test/IRGen/objc_partial_apply_forwarder.swift b/test/IRGen/objc_partial_apply_forwarder.swift
new file mode 100644
index 0000000..0c7291d
--- /dev/null
+++ b/test/IRGen/objc_partial_apply_forwarder.swift
@@ -0,0 +1,35 @@
+// RUN: %target-swift-frontend -emit-ir %s | %FileCheck %s
+
+public class Foo<T> {
+}
+
+public func use(_: Any) {}
+
+// Don't crash trying to generate IR.
+// CHECK:  define{{.*}}swiftcc void @_T028objc_partial_apply_forwarder13createClosure1a1tyAA3FooCyxGcyXl_xmtlF5localL_1xyAG_tlFTA
+public func createClosure<T>(a: AnyObject, t: T.Type) -> (Foo<T>) -> () {
+  func local(x: Foo<T>) {
+    use(a)
+    use(x)
+  }
+  return local
+}
+
+// Don't crash.
+public final class K<Error: Swift.Error> {
+  func act(error: Error) {}
+}
+
+public struct A<Error: Swift.Error>{
+  private let action: (K<Error>) -> Void
+
+  public init(_ action: @escaping (K<Error>) -> Void) {
+    self.action = action
+  }
+
+  public init(error: Error) {
+    self.init { actor in
+      actor.act(error: error)
+    }
+  }
+}
diff --git a/test/IRGen/objc_pointers.swift b/test/IRGen/objc_pointers.swift
index 58479b0..27ae7e6 100644
--- a/test/IRGen/objc_pointers.swift
+++ b/test/IRGen/objc_pointers.swift
@@ -8,13 +8,13 @@
 import Foundation
 
 @objc class Foo : NSObject {
-  // CHECK: define internal void @_T013objc_pointers3FooC16pointerArgumentsySpySiG_Sv1ySPySiG1zs33AutoreleasingUnsafeMutablePointerVyACSgG1wtFTo(%0*, i8*, i64*, i8*, i64*, %0**)
+  // CHECK: define internal void @_T013objc_pointers3FooC16pointerArguments_1y1z1wySpySiG_SvSPySiGs33AutoreleasingUnsafeMutablePointerVyACSgGtFTo(%0*, i8*, i64*, i8*, i64*, %0**)
   @objc func pointerArguments(_ x: UnsafeMutablePointer<Int>,
                               y: UnsafeMutableRawPointer,
                               z: UnsafePointer<Int>,
                               w: AutoreleasingUnsafeMutablePointer<Foo?>) {}
 
-  // CHECK: define internal void @_T013objc_pointers3FooC24pointerMetatypeArgumentsys33AutoreleasingUnsafeMutablePointerVyyXlXpG1x_AFyyXlXpSgG1ytFTo(%0*, i8*, i8**, i8**)
+  // CHECK: define internal void @_T013objc_pointers3FooC24pointerMetatypeArguments1x1yys33AutoreleasingUnsafeMutablePointerVyyXlXpG_AHyyXlXpSgGtFTo(%0*, i8*, i8**, i8**)
   @objc func pointerMetatypeArguments(x: AutoreleasingUnsafeMutablePointer<AnyClass>,
                                       y: AutoreleasingUnsafeMutablePointer<AnyClass?>) {}
 }
diff --git a/test/IRGen/objc_retainAutoreleasedReturnValue.swift b/test/IRGen/objc_retainAutoreleasedReturnValue.swift
index 98a9ed3..ea62dae 100644
--- a/test/IRGen/objc_retainAutoreleasedReturnValue.swift
+++ b/test/IRGen/objc_retainAutoreleasedReturnValue.swift
@@ -24,13 +24,13 @@
 // popq   %rbp  ;<== Blocks the handshake from objc_autoreleaseReturnValue
 // jmp    0x01ec20 ; symbol stub for: objc_retainAutoreleasedReturnValue
 
-// CHECK-LABEL: define {{.*}}swiftcc void @_T034objc_retainAutoreleasedReturnValue4testySo12NSDictionaryCFyADcfU_(%TSo12NSDictionaryC*)
+// CHECK-LABEL: define {{.*}}swiftcc void @_T034objc_retainAutoreleasedReturnValue4testyySo12NSDictionaryCFyADcfU_(%TSo12NSDictionaryC*)
 // CHECK: entry:
 // CHECK:   call {{.*}}@objc_msgSend
 // CHECK:   notail call i8* @objc_retainAutoreleasedReturnValue
 // CHECK:   ret void
 
-// OPT-LABEL: define {{.*}}swiftcc void @_T034objc_retainAutoreleasedReturnValue4testySo12NSDictionaryCFyADcfU_(%TSo12NSDictionaryC*)
+// OPT-LABEL: define {{.*}}swiftcc void @_T034objc_retainAutoreleasedReturnValue4testyySo12NSDictionaryCFyADcfU_(%TSo12NSDictionaryC*)
 // OPT: entry:
 // OPT:   call {{.*}}@objc_msgSend
 // OPT:   notail call i8* @objc_retainAutoreleasedReturnValue
diff --git a/test/IRGen/objc_structs.swift b/test/IRGen/objc_structs.swift
index efa2b5a..3c6928a 100644
--- a/test/IRGen/objc_structs.swift
+++ b/test/IRGen/objc_structs.swift
@@ -61,7 +61,7 @@
 }
 // CHECK: }
 
-// CHECK: define hidden swiftcc { {{.*}}*, {{.*}}*, {{.*}}*, {{.*}}* } @_T012objc_structs20useStructOfNSStringsSC0deF0VADF({{.*}}*, {{.*}}*, {{.*}}*, {{.*}}*)
+// CHECK: define hidden swiftcc { {{.*}}*, {{.*}}*, {{.*}}*, {{.*}}* } @_T012objc_structs20useStructOfNSStringsySC0deF0VADF({{.*}}*, {{.*}}*, {{.*}}*, {{.*}}*)
 // CHECK:   call void @useStructOfNSStringsInObjC(%struct.StructOfNSStrings* noalias nocapture sret {{%.*}}, %struct.StructOfNSStrings* byval align 8 {{%.*}})
 func useStructOfNSStrings(_ s: StructOfNSStrings) -> StructOfNSStrings {
   return useStructOfNSStringsInObjC(s)
diff --git a/test/IRGen/objc_subclass.swift b/test/IRGen/objc_subclass.swift
index 3377404..72c7e3e 100644
--- a/test/IRGen/objc_subclass.swift
+++ b/test/IRGen/objc_subclass.swift
@@ -82,7 +82,7 @@
 // CHECK-32:   }, { i8*, i8*, i8* } {
 // CHECK-32:     i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(initWithInt:string:)", i32 0, i32 0),
 // CHECK-32:     i8* getelementptr inbounds ([13 x i8], [13 x i8]* [[INIT_ENCODING]], i32 0, i32 0),
-// CHECK-32:     i8* bitcast (%0* (%0*, i8*, i32, %2*)* @_T013objc_subclass10SwiftGizmoCACSi3int_SS6stringtcfcTo to i8*)
+// CHECK-32:     i8* bitcast (%0* (%0*, i8*, i32, %2*)* @_T013objc_subclass10SwiftGizmoC3int6stringACSi_SStcfcTo to i8*)
 // CHECK-32:   }, { i8*, i8*, i8* } {
 // CHECK-32:     i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i32 0, i32 0),
 // CHECK-32:     i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[DEALLOC_ENCODING]], i32 0, i32 0),
@@ -98,7 +98,7 @@
 // CHECK-32:   }, { i8*, i8*, i8* } {
 // CHECK-32:     i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i32 0, i32 0),
 // CHECK-32:     i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0),
-// CHECK-32:     i8* bitcast (%0* (%0*, i8*, i32)* @_T013objc_subclass10SwiftGizmoCSQyACGSi7bellsOn_tcfcTo to i8*)
+// CHECK-32:     i8* bitcast (%0* (%0*, i8*, i32)* @_T013objc_subclass10SwiftGizmoC7bellsOnSQyACGSi_tcfcTo to i8*)
 // CHECK-32:   }, { i8*, i8*, i8* } {
 // CHECK-32:     i8* getelementptr inbounds ([15 x i8], [15 x i8]* @"\01L_selector_data(.cxx_construct)", i32 0, i32 0),
 // CHECK-32:     i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i32 0, i32 0),
@@ -132,7 +132,7 @@
 // CHECK-64:   }, {
 // CHECK-64:     i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(initWithInt:string:)", i64 0, i64 0),
 // CHECK-64:     i8* getelementptr inbounds ([14 x i8], [14 x i8]* [[INIT_ENCODING]], i64 0, i64 0),
-// CHECK-64:     i8* bitcast ([[OPAQUE7:%.*]]* ([[OPAQUE8:%.*]]*, i8*, i64, [[OPAQUEONE:.*]]*)* @_T013objc_subclass10SwiftGizmoCACSi3int_SS6stringtcfcTo to i8*)
+// CHECK-64:     i8* bitcast ([[OPAQUE7:%.*]]* ([[OPAQUE8:%.*]]*, i8*, i64, [[OPAQUEONE:.*]]*)* @_T013objc_subclass10SwiftGizmoC3int6stringACSi_SStcfcTo to i8*)
 // CHECK-64:   }, {
 // CHECK-64:     i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i64 0, i64 0),
 // CHECK-64:     i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[DEALLOC_ENCODING]], i64 0, i64 0),
@@ -148,7 +148,7 @@
 // CHECK-64:   }, {
 // CHECK-64:     i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i64 0, i64 0),
 // CHECK-64:     i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0),
-// CHECK-64:     i8* bitcast ([[OPAQUE11:%.*]]* ([[OPAQUE12:%.*]]*, i8*, i64)* @_T013objc_subclass10SwiftGizmoCSQyACGSi7bellsOn_tcfcTo to i8*)
+// CHECK-64:     i8* bitcast ([[OPAQUE11:%.*]]* ([[OPAQUE12:%.*]]*, i8*, i64)* @_T013objc_subclass10SwiftGizmoC7bellsOnSQyACGSi_tcfcTo to i8*)
 // CHECK-64:   }, {
 // CHECK-64:     i8* getelementptr inbounds ([15 x i8], [15 x i8]* @"\01L_selector_data(.cxx_construct)", i64 0, i64 0),
 // CHECK-64:     i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i64 0, i64 0),
@@ -234,7 +234,7 @@
 // CHECK-32:     }, {
 // CHECK-32:       i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i32 0, i32 0),
 // CHECK-32:       i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0),
-// CHECK-32:       i8* bitcast (%3* (%3*, i8*, i32)* @_T013objc_subclass11SwiftGizmo2CSQyACGSi7bellsOn_tcfcTo to i8*)
+// CHECK-32:       i8* bitcast (%3* (%3*, i8*, i32)* @_T013objc_subclass11SwiftGizmo2C7bellsOnSQyACGSi_tcfcTo to i8*)
 // CHECK-32:     }, {
 // CHECK-32:       i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i32 0, i32 0),
 // CHECK-32:       i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i32 0, i32 0),
@@ -262,7 +262,7 @@
 // CHECK-64:     }, {
 // CHECK-64:       i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i64 0, i64 0),
 // CHECK-64:       i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0),
-// CHECK-64:       i8* bitcast ([[OPAQUE21:%.*]]* ([[OPAQUE22:%.*]]*, i8*, i64)* @_T013objc_subclass11SwiftGizmo2CSQyACGSi7bellsOn_tcfcTo to i8*)
+// CHECK-64:       i8* bitcast ([[OPAQUE21:%.*]]* ([[OPAQUE22:%.*]]*, i8*, i64)* @_T013objc_subclass11SwiftGizmo2C7bellsOnSQyACGSi_tcfcTo to i8*)
 // CHECK-64:     }, {
 // CHECK-64:       i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i64 0, i64 0),
 // CHECK-64:       i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i64 0, i64 0)
diff --git a/test/IRGen/objc_subscripts.swift b/test/IRGen/objc_subscripts.swift
index 4e48a93..7c0620c 100644
--- a/test/IRGen/objc_subscripts.swift
+++ b/test/IRGen/objc_subscripts.swift
@@ -11,25 +11,25 @@
 // CHECK:         { 
 // CHECK:           i8* getelementptr inbounds ([26 x i8], [26 x i8]* @"\01L_selector_data(objectAtIndexedSubscript:)", i64 0, i64 0), 
 // CHECK:           i8* null, 
-// CHECK:           i8* bitcast ([[OPAQUE0:%.*]]* ([[OPAQUE1:%.*]]*, i8*, i64)* @_T015objc_subscripts10SomeObjectCACSicigTo to i8*)
+// CHECK:           i8* bitcast ([[OPAQUE0:%.*]]* ([[OPAQUE1:%.*]]*, i8*, i64)* @_T015objc_subscripts10SomeObjectCyACSicigTo to i8*)
 // CHECK:         }, 
 // CHECK:       { i8*, i8*, i8* } 
 // CHECK:         { 
 // CHECK:           i8* getelementptr inbounds ([30 x i8], [30 x i8]* @"\01L_selector_data(setObject:atIndexedSubscript:)", i64 0, i64 0), 
 // CHECK:           i8* null, 
-// CHECK:           i8* bitcast (void ([[OPAQUE2:%.*]]*, i8*, [[OPAQUE3:%.*]]*, i64)* @_T015objc_subscripts10SomeObjectCACSicisTo to i8*)
+// CHECK:           i8* bitcast (void ([[OPAQUE2:%.*]]*, i8*, [[OPAQUE3:%.*]]*, i64)* @_T015objc_subscripts10SomeObjectCyACSicisTo to i8*)
 // CHECK:         },
 // CHECK:       { i8*, i8*, i8* } 
 // CHECK:         { 
 // CHECK:           i8* getelementptr inbounds ([25 x i8], [25 x i8]* @"\01L_selector_data(objectForKeyedSubscript:)", i64 0, i64 0), 
 // CHECK:           i8* null, 
-// CHECK:           i8* bitcast (i64 ([[OPAQUE4:%.*]]*, i8*, [[OPAQUE5:%.*]]*)* @_T015objc_subscripts10SomeObjectCSiACcigTo to i8*)
+// CHECK:           i8* bitcast (i64 ([[OPAQUE4:%.*]]*, i8*, [[OPAQUE5:%.*]]*)* @_T015objc_subscripts10SomeObjectCySiACcigTo to i8*)
 // CHECK:         }, 
 // CHECK:       { i8*, i8*, i8* } 
 // CHECK:         { 
 // CHECK:           i8* getelementptr inbounds ([29 x i8], [29 x i8]* @"\01L_selector_data(setObject:forKeyedSubscript:)", i64 0, i64 0), 
 // CHECK:           i8* null, 
-// CHECK:           i8* bitcast (void ([[OPAQUE6:%.*]]*, i8*, i64, [[OPAQUE7:%.*]]*)* @_T015objc_subscripts10SomeObjectCSiACcisTo to i8*)
+// CHECK:           i8* bitcast (void ([[OPAQUE6:%.*]]*, i8*, i64, [[OPAQUE7:%.*]]*)* @_T015objc_subscripts10SomeObjectCySiACcisTo to i8*)
 // CHECK:         },
 // CHECK:       { i8*, i8*, i8* } 
 // CHECK:         { i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* @{{[0-9]+}}, i64 0, i64 0), i8* bitcast ([[OPAQUE8:%.*]]* ([[OPAQUE9:%.*]]*, i8*)* @_T015objc_subscripts10SomeObjectCACycfcTo to i8*) }
@@ -38,28 +38,28 @@
 
 @objc class SomeObject {
   subscript (i : Int) -> SomeObject {
-    // CHECK: define internal [[OPAQUE0:%.*]]* @_T015objc_subscripts10SomeObjectCACSicigTo([[OPAQUE1]]*, i8*, i64) unnamed_addr
+    // CHECK: define internal [[OPAQUE0:%.*]]* @_T015objc_subscripts10SomeObjectCyACSicigTo([[OPAQUE1]]*, i8*, i64) unnamed_addr
     get {
-      // CHECK: call swiftcc %T15objc_subscripts10SomeObjectC* @_T015objc_subscripts10SomeObjectCACSicig
+      // CHECK: call swiftcc %T15objc_subscripts10SomeObjectC* @_T015objc_subscripts10SomeObjectCyACSicig
       return self
     }
 
-    // CHECK-LABEL: define internal void @_T015objc_subscripts10SomeObjectCACSicisTo
+    // CHECK-LABEL: define internal void @_T015objc_subscripts10SomeObjectCyACSicisTo
     set {
-      // CHECK: swiftcc void @_T015objc_subscripts10SomeObjectCACSicis
+      // CHECK: swiftcc void @_T015objc_subscripts10SomeObjectCyACSicis
     }
   }
 
   subscript (s : SomeObject) -> Int {
-  // CHECK-LABEL: define internal i64 @_T015objc_subscripts10SomeObjectCSiACcigTo
+  // CHECK-LABEL: define internal i64 @_T015objc_subscripts10SomeObjectCySiACcigTo
     get {
-      // CHECK: call swiftcc i64 @_T015objc_subscripts10SomeObjectCSiACcig
+      // CHECK: call swiftcc i64 @_T015objc_subscripts10SomeObjectCySiACcig
       return 5
     }
 
-    // CHECK-LABEL: define internal void @_T015objc_subscripts10SomeObjectCSiACcisTo
+    // CHECK-LABEL: define internal void @_T015objc_subscripts10SomeObjectCySiACcisTo
     set {
-      // CHECK: call swiftcc void @_T015objc_subscripts10SomeObjectCSiACcis
+      // CHECK: call swiftcc void @_T015objc_subscripts10SomeObjectCySiACcis
     }
   }
 }
diff --git a/test/IRGen/objc_super.swift b/test/IRGen/objc_super.swift
index af050e2..46530a5 100644
--- a/test/IRGen/objc_super.swift
+++ b/test/IRGen/objc_super.swift
@@ -48,7 +48,7 @@
   }
   // CHECK: }
 
-  // CHECK: define hidden swiftcc [[HOOZIT]]* @_T010objc_super6HoozitCACSi1x_tcfc(i64, %T10objc_super6HoozitC* swiftself) {{.*}} {
+  // CHECK: define hidden swiftcc [[HOOZIT]]* @_T010objc_super6HoozitC1xACSi_tcfc(i64, %T10objc_super6HoozitC* swiftself) {{.*}} {
   init(x:Int) {
     // CHECK: load i8*, i8** @"\01L_selector(init)"
     // CHECK: call [[OPAQUE:.*]]* bitcast (void ()* @objc_msgSendSuper2 to [[OPAQUE:.*]]* (%objc_super*, i8*)*)([[SUPER]]* {{.*}}, i8* {{.*}})
@@ -58,7 +58,7 @@
   }
   // CHECK: }
 
-  // CHECK: define hidden swiftcc [[HOOZIT]]* @_T010objc_super6HoozitCACSi1y_tcfc(i64, %T10objc_super6HoozitC* swiftself) {{.*}} {
+  // CHECK: define hidden swiftcc [[HOOZIT]]* @_T010objc_super6HoozitC1yACSi_tcfc(i64, %T10objc_super6HoozitC* swiftself) {{.*}} {
   init(y:Int) {
     // CHECK: load i8*, i8** @"\01L_selector(initWithBellsOn:)"
     // CHECK: call [[OPAQUE:.*]]* bitcast (void ()* @objc_msgSendSuper2 to [[OPAQUE:.*]]* (%objc_super*, i8*, i64)*)([[SUPER]]* {{.*}}, i8* {{.*}}, i64 {{.*}})
@@ -74,7 +74,7 @@
 class PartialApply : Gizmo {
   // CHECK: define hidden swiftcc void @_T010objc_super12PartialApplyC4frobyyF([[PARTIAL_APPLY_CLASS]]* swiftself) {{.*}} {
   override func frob() {
-    // CHECK: call swiftcc void @_T010objc_super8acceptFnyyycF(i8* bitcast (void (%swift.refcounted*)* [[PARTIAL_FORWARDING_THUNK:@[A-Za-z0-9_]+]] to i8*), %swift.refcounted* %4)
+    // CHECK: call swiftcc void @_T010objc_super8acceptFnyyyycF(i8* bitcast (void (%swift.refcounted*)* [[PARTIAL_FORWARDING_THUNK:@[A-Za-z0-9_]+]] to i8*), %swift.refcounted* %4)
     acceptFn(super.frob)
   }
   // CHECK: }
diff --git a/test/IRGen/object_type.swift b/test/IRGen/object_type.swift
new file mode 100644
index 0000000..80faf60
--- /dev/null
+++ b/test/IRGen/object_type.swift
@@ -0,0 +1,39 @@
+// RUN: %empty-directory(%t)
+// RUN: %target-build-swift -O %s -o %t/a.out
+// RUN: %target-build-swift -O %s -emit-ir | %FileCheck --check-prefix=CHECK-IR %s
+// RUN: %target-run %t/a.out | %FileCheck %s
+// REQUIRES: executable_test
+
+// Check if the runtime function swift_getObjectType is not readnone and
+// therefore not re-scheduled with release-calls, which would lead to a crash
+// in this example.
+
+public protocol Proto: class {
+   static func printit()
+}
+
+public final class ConformingClass : Proto {
+   public static func printit() { print("okay") }
+}
+
+public final class Creator {
+   @inline(never)
+   public init() {}
+
+   @inline(never)
+   public func createIt() -> Proto {
+      return ConformingClass ()
+   }
+}
+
+func work() {
+  let myProtocolType: Proto.Type = type(of: Creator().createIt())
+  myProtocolType.printit()
+}
+
+// CHECK-IR: call {{.*}} @swift_getObjectType({{.*}}) #[[M:[0-9]]]
+// CHECK-IR: declare {{.*}} @swift_getObjectType{{.*}} #[[M]]
+// CHECK-IR: attributes #[[M]] = { nounwind readonly }
+
+// CHECK: okay
+work()
diff --git a/test/IRGen/partial_apply_generic.swift b/test/IRGen/partial_apply_generic.swift
index 39fca28..4194e2a 100644
--- a/test/IRGen/partial_apply_generic.swift
+++ b/test/IRGen/partial_apply_generic.swift
@@ -48,9 +48,9 @@
 
 let s = S()
 var y = s.hugeStructReturn
-// CHECK-LABEL: define internal swiftcc { i64, i64, i64, i64 } @_T021partial_apply_generic1SV16hugeStructReturnAA04HugeE0VAFFTA(i64, i64, i64, i64, %swift.refcounted* swiftself) #0 {
+// CHECK-LABEL: define internal swiftcc { i64, i64, i64, i64 } @_T021partial_apply_generic1SV16hugeStructReturnyAA04HugeE0VAFFTA(i64, i64, i64, i64, %swift.refcounted* swiftself) #0 {
 // CHECK: entry:
-// CHECK:   %5 = tail call swiftcc { i64, i64, i64, i64 } @_T021partial_apply_generic1SV16hugeStructReturnAA04HugeE0VAFF(i64 %0, i64 %1, i64 %2, i64 %3)
+// CHECK:   %5 = tail call swiftcc { i64, i64, i64, i64 } @_T021partial_apply_generic1SV16hugeStructReturnyAA04HugeE0VAFF(i64 %0, i64 %1, i64 %2, i64 %3)
 // CHECK:   ret { i64, i64, i64, i64 } %5
 // CHECK: }
 
diff --git a/test/IRGen/partial_apply_objc.sil b/test/IRGen/partial_apply_objc.sil
index d6c16ca..86b50e8 100644
--- a/test/IRGen/partial_apply_objc.sil
+++ b/test/IRGen/partial_apply_objc.sil
@@ -19,7 +19,7 @@
 sil_vtable ObjCClass {}
 sil @_T018partial_apply_objc9ObjCClassCfD : $@convention(method) (ObjCClass) -> ()
 
-sil @_T018partial_apply_objc9ObjCClassCACycACmcfc : $@convention(method) (ObjCClass) -> ObjCClass {
+sil @_T018partial_apply_objc9ObjCClassCyACycACmcfc : $@convention(method) (ObjCClass) -> ObjCClass {
 bb0(%0 : $ObjCClass):
   return %0 : $ObjCClass
 }
@@ -27,17 +27,17 @@
 sil @_T018partial_apply_objc9ObjCClassCACycfcTo : $@convention(objc_method) (ObjCClass) -> ObjCClass {
 bb0(%0 : $ObjCClass):
   // function_ref ObjectiveC.ObjCClass.constructor (ObjectiveC.ObjCClass.Type)() -> ObjectiveC.ObjCClass
-  %1 = function_ref @_T018partial_apply_objc9ObjCClassCACycACmcfc : $@convention(method) (ObjCClass) -> ObjCClass // user: %2
+  %1 = function_ref @_T018partial_apply_objc9ObjCClassCyACycACmcfc : $@convention(method) (ObjCClass) -> ObjCClass // user: %2
   %2 = apply %1(%0) : $@convention(method) (ObjCClass) -> ObjCClass // user: %3
   return %2 : $ObjCClass
 }
 
-sil @_T018partial_apply_objc9ObjCClassC6methodySi1x_tFTo : $@convention(objc_method) (Int, ObjCClass) -> () {
+sil @_T018partial_apply_objc9ObjCClassC6method1xySi_tFTo : $@convention(objc_method) (Int, ObjCClass) -> () {
 bb0(%0 : $Int, %1 : $ObjCClass):
   %v = tuple()
   return %v : $()
 }
-sil @_T018partial_apply_objc9ObjCClassC7method2ySC6NSRectV1r_tFTo : $@convention(objc_method) (NSRect, ObjCClass) -> () {
+sil @_T018partial_apply_objc9ObjCClassC7method21rySC6NSRectV_tFTo : $@convention(objc_method) (NSRect, ObjCClass) -> () {
 bb0(%0 : $NSRect, %1 : $ObjCClass):
   %v = tuple()
   return %v : $()
diff --git a/test/IRGen/protocol_conformance_records.swift b/test/IRGen/protocol_conformance_records.swift
index 2d4fec9..c8342ea 100644
--- a/test/IRGen/protocol_conformance_records.swift
+++ b/test/IRGen/protocol_conformance_records.swift
@@ -1,5 +1,5 @@
-// RUN: %target-swift-frontend -enable-experimental-conditional-conformances -primary-file %s -emit-ir -enable-resilience -enable-source-import -I %S/../Inputs | %FileCheck %s
-// RUN: %target-swift-frontend -enable-experimental-conditional-conformances %s -emit-ir -num-threads 8 -enable-resilience -enable-source-import -I %S/../Inputs | %FileCheck %s
+// RUN: %target-swift-frontend -primary-file %s -emit-ir -enable-resilience -enable-source-import -I %S/../Inputs | %FileCheck %s
+// RUN: %target-swift-frontend %s -emit-ir -num-threads 8 -enable-resilience -enable-source-import -I %S/../Inputs | %FileCheck %s
 
 import resilient_struct
 
diff --git a/test/IRGen/runtime_calling_conventions.swift b/test/IRGen/runtime_calling_conventions.swift
index b33c9cf..590d434 100644
--- a/test/IRGen/runtime_calling_conventions.swift
+++ b/test/IRGen/runtime_calling_conventions.swift
@@ -9,11 +9,11 @@
 public class C {
 }
 
-// CHECK-LABEL: define {{(protected )?}}swiftcc void @_T027runtime_calling_conventions3fooyAA1CCF(%T27runtime_calling_conventions1CC*)
+// CHECK-LABEL: define {{(protected )?}}swiftcc void @_T027runtime_calling_conventions3fooyyAA1CCF(%T27runtime_calling_conventions1CC*)
 // Check that runtime functions use a proper calling convention.
 // CHECK: call void {{.*}} @swift_rt_swift_release
 
-// OPT-CHECK-LABEL: define {{(protected )?}}swiftcc void @_T027runtime_calling_conventions3fooyAA1CCF(%T27runtime_calling_conventions1CC*)
+// OPT-CHECK-LABEL: define {{(protected )?}}swiftcc void @_T027runtime_calling_conventions3fooyyAA1CCF(%T27runtime_calling_conventions1CC*)
 // Check that runtime functions use a proper calling convention.
 // OPT-CHECK: tail call void @swift_rt_swift_release
 
diff --git a/test/IRGen/sil_witness_tables.swift b/test/IRGen/sil_witness_tables.swift
index 413712b..1c496b8 100644
--- a/test/IRGen/sil_witness_tables.swift
+++ b/test/IRGen/sil_witness_tables.swift
@@ -57,14 +57,14 @@
   func qMethod() {}
 }
 
-// CHECK-LABEL: define hidden swiftcc void @_T018sil_witness_tables7erasureAA2QQ_pAA9ConformerV1c_tF(%T18sil_witness_tables2QQP* noalias nocapture sret)
+// CHECK-LABEL: define hidden swiftcc void @_T018sil_witness_tables7erasure1cAA2QQ_pAA9ConformerV_tF(%T18sil_witness_tables2QQP* noalias nocapture sret)
 // CHECK:         [[WITNESS_TABLE_ADDR:%.*]] = getelementptr inbounds %T18sil_witness_tables2QQP, %T18sil_witness_tables2QQP* %0, i32 0, i32 2
 // CHECK-NEXT:    store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* [[CONFORMER_QQ_WITNESS_TABLE:@_T0.*WP]], i32 0, i32 0), i8*** [[WITNESS_TABLE_ADDR]], align 8
 func erasure(c c: Conformer) -> QQ {
   return c
 }
 
-// CHECK-LABEL: define hidden swiftcc void @_T018sil_witness_tables15externalErasure0a1_b1_c1_D12_conformance9ExternalP_pAC0G9ConformerV1c_tF(%T39sil_witness_tables_external_conformance9ExternalPP* noalias nocapture sret)
+// CHECK-LABEL: define hidden swiftcc void @_T018sil_witness_tables15externalErasure1c0a1_b1_c1_D12_conformance9ExternalP_pAD0G9ConformerV_tF(%T39sil_witness_tables_external_conformance9ExternalPP* noalias nocapture sret)
 // CHECK:         [[WITNESS_TABLE_ADDR:%.*]] = getelementptr inbounds %T39sil_witness_tables_external_conformance9ExternalPP, %T39sil_witness_tables_external_conformance9ExternalPP* %0, i32 0, i32 2
 // CHECK-NEXT:    store i8** [[EXTERNAL_CONFORMER_EXTERNAL_P_WITNESS_TABLE]], i8*** %2, align 8
 func externalErasure(c c: ExternalConformer) -> ExternalP {
diff --git a/test/IRGen/struct_resilience.swift b/test/IRGen/struct_resilience.swift
index 4299306..a06fbd6 100644
--- a/test/IRGen/struct_resilience.swift
+++ b/test/IRGen/struct_resilience.swift
@@ -14,7 +14,7 @@
 // Resilient structs from outside our resilience domain are manipulated via
 // value witnesses
 
-// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T017struct_resilience26functionWithResilientTypes010resilient_A04SizeVAE_A2Ec1ftF(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, i8*, %swift.refcounted*)
+// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T017struct_resilience26functionWithResilientTypes_1f010resilient_A04SizeVAF_A2FctF(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, i8*, %swift.refcounted*)
 
 public func functionWithResilientTypes(_ s: Size, f: (Size) -> Size) -> Size {
 
@@ -54,7 +54,7 @@
 // Make sure we use a type metadata accessor function, and load indirect
 // field offsets from it.
 
-// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T017struct_resilience26functionWithResilientTypesy010resilient_A09RectangleVF(%T16resilient_struct9RectangleV* noalias nocapture)
+// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T017struct_resilience26functionWithResilientTypesyy010resilient_A09RectangleVF(%T16resilient_struct9RectangleV* noalias nocapture)
 public func functionWithResilientTypes(_ r: Rectangle) {
 
 // CHECK: [[METADATA:%.*]] = call %swift.type* @_T016resilient_struct9RectangleVMa()
@@ -83,7 +83,7 @@
   public let h: Int
 }
 
-// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T017struct_resilience28functionWithMyResilientTypesAA0E4SizeVAD_A2Dc1ftF(%T17struct_resilience6MySizeV* {{.*}}, %T17struct_resilience6MySizeV* {{.*}}, i8*, %swift.refcounted*)
+// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T017struct_resilience28functionWithMyResilientTypes_1fAA0E4SizeVAE_A2EctF(%T17struct_resilience6MySizeV* {{.*}}, %T17struct_resilience6MySizeV* {{.*}}, i8*, %swift.refcounted*)
 public func functionWithMyResilientTypes(_ s: MySize, f: (MySize) -> MySize) -> MySize {
 
 // CHECK: [[TEMP:%.*]] = alloca %T17struct_resilience6MySizeV
@@ -150,14 +150,14 @@
 
 // Corner case -- type is address-only in SIL, but empty in IRGen
 
-// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T017struct_resilience29partialApplyOfResilientMethodyAA0f10StructWithG0V1r_tF(%T17struct_resilience25ResilientStructWithMethodV* noalias nocapture)
+// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T017struct_resilience29partialApplyOfResilientMethod1ryAA0f10StructWithG0V_tF(%T17struct_resilience25ResilientStructWithMethodV* noalias nocapture)
 public func partialApplyOfResilientMethod(r: ResilientStructWithMethod) {
   _ = r.method
 }
 
 // Type is address-only in SIL, and resilient in IRGen
 
-// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T017struct_resilience29partialApplyOfResilientMethody010resilient_A04SizeV1s_tF(%swift.opaque* noalias nocapture)
+// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T017struct_resilience29partialApplyOfResilientMethod1sy010resilient_A04SizeV_tF(%swift.opaque* noalias nocapture)
 public func partialApplyOfResilientMethod(s: Size) {
   _ = s.method
 }
@@ -170,7 +170,6 @@
 
 // CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_StructWithResilientStorage(i8*)
 // CHECK: [[FIELDS:%.*]] = alloca [4 x i8**]
-// CHECK: [[VWT:%.*]] = load i8**, i8*** getelementptr inbounds ({{.*}} @_T017struct_resilience26StructWithResilientStorageVMf{{.*}}, [[INT]] -1)
 
 // CHECK: [[FIELDS_ADDR:%.*]] = getelementptr inbounds [4 x i8**], [4 x i8**]* [[FIELDS]], i32 0, i32 0
 
@@ -195,6 +194,6 @@
 // CHECK: [[FIELD_4:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 3
 // CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_4]]
 
-// CHECK: call void @swift_initStructMetadata_UniversalStrategy([[INT]] 4, i8*** [[FIELDS_ADDR]], [[INT]]* {{.*}}, i8** [[VWT]])
+// CHECK: call void @swift_initStructMetadata(%swift.type* {{.*}}, [[INT]] 256, [[INT]] 4, i8*** [[FIELDS_ADDR]], [[INT]]* {{.*}})
 // CHECK: store atomic %swift.type* {{.*}} @_T017struct_resilience26StructWithResilientStorageVMf{{.*}}, %swift.type** @_T017struct_resilience26StructWithResilientStorageVML release,
 // CHECK: ret void
diff --git a/test/IRGen/subclass.swift b/test/IRGen/subclass.swift
index b658432..7e655fe9 100644
--- a/test/IRGen/subclass.swift
+++ b/test/IRGen/subclass.swift
@@ -57,7 +57,7 @@
 // Ensure that downcasts to generic types instantiate generic metadata instead
 // of trying to reference global metadata. <rdar://problem/14265663>
 
-// CHECK: define hidden swiftcc %T8subclass1GCySiG* @_T08subclass9a_to_gintAA1GCySiGAA1AC1a_tF(%T8subclass1AC*) {{.*}} {
+// CHECK: define hidden swiftcc %T8subclass1GCySiG* @_T08subclass9a_to_gint1aAA1GCySiGAA1AC_tF(%T8subclass1AC*) {{.*}} {
 func a_to_gint(a: A) -> G<Int> {
   // CHECK: call %swift.type* @_T08subclass1GCySiGMa()
   // CHECK: call i8* @swift_dynamicCastClassUnconditional
diff --git a/test/IRGen/unexploded-calls.swift b/test/IRGen/unexploded-calls.swift
index e9046f4..fb2ca0b 100644
--- a/test/IRGen/unexploded-calls.swift
+++ b/test/IRGen/unexploded-calls.swift
@@ -17,7 +17,7 @@
   return f(s)
 }
 
-// CHECK: define {{.*}}swiftcc void @_T0s1gySC1SVF(float, float) {{.*}}{
+// CHECK: define {{.*}}swiftcc void @_T0s1gyySC1SVF(float, float) {{.*}}{
 // CHECK: entry:
 // CHECK:   [[ALLOCA:%[-._0-9a-zA-Z]+]] = alloca %TSC1SV, align 4
 // CHECK:   %2 = bitcast %TSC1SV* [[ALLOCA]] to i8*
diff --git a/test/IRGen/witness_table_objc_associated_type.swift b/test/IRGen/witness_table_objc_associated_type.swift
index e9eba6d..05b72dd 100644
--- a/test/IRGen/witness_table_objc_associated_type.swift
+++ b/test/IRGen/witness_table_objc_associated_type.swift
@@ -35,7 +35,7 @@
 // CHECK:         i8* bitcast {{.*}} @_T034witness_table_objc_associated_type2SOVAA1CA2aDP3fooyyFTW
 // CHECK:       ]
 
-// CHECK-LABEL: define hidden swiftcc void @_T034witness_table_objc_associated_type0A25OffsetAfterAssociatedTypeyxAA1BRzlF(%swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.B)
+// CHECK-LABEL: define hidden swiftcc void @_T034witness_table_objc_associated_type0A25OffsetAfterAssociatedTypeyyxAA1BRzlF(%swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.B)
 func witnessOffsetAfterAssociatedType<T: B>(_ x: T) {
   // CHECK:         [[FOO_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.B, i32 2
   // CHECK:         [[FOO_OPAQUE:%.*]] = load {{.*}} [[FOO_ADDR]]
@@ -44,7 +44,7 @@
   x.foo()
 }
 
-// CHECK-LABEL: define hidden swiftcc void @_T034witness_table_objc_associated_type0A29OffsetAfterAssociatedTypeObjCyxAA1CRzlF(%swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.C) {{.*}} {
+// CHECK-LABEL: define hidden swiftcc void @_T034witness_table_objc_associated_type0A29OffsetAfterAssociatedTypeObjCyyxAA1CRzlF(%swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.C) {{.*}} {
 func witnessOffsetAfterAssociatedTypeObjC<T: C>(_ x: T) {
   // CHECK:         [[FOO_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.C, i32 1
   // CHECK:         [[FOO_OPAQUE:%.*]] = load {{.*}} [[FOO_ADDR]]
diff --git a/test/Index/Store/driver-index.swift b/test/Index/Store/driver-index.swift
index b8007d0..de0290b 100644
--- a/test/Index/Store/driver-index.swift
+++ b/test/Index/Store/driver-index.swift
@@ -1,2 +1,2 @@
 // RUN: %swiftc_driver -driver-print-jobs -index-file -index-file-path %s %S/Inputs/SwiftModuleA.swift %s -o %t.output_for_index -index-store-path %t.index_store -module-name driver_index 2>&1 | %FileCheck %s
-// CHECK: {{.*}}swift -frontend -typecheck {{.*}}-primary-file {{.*}}driver-index.swift {{.*}}SwiftModuleA.swift {{.*}}driver-index.swift {{.*}}-o {{.*}}.output_for_index {{.*}}-index-store-path {{.*}}.index_store -index-system-modules
+// CHECK: {{.*}}swift -frontend -typecheck {{.*}}-primary-file {{.*}}driver-index.swift {{.*}}SwiftModuleA.swift  {{.*}}-o {{.*}}.output_for_index {{.*}}-index-store-path {{.*}}.index_store -index-system-modules
diff --git a/test/Index/kinds.swift b/test/Index/kinds.swift
index 2f73e09..6bb6fba 100644
--- a/test/Index/kinds.swift
+++ b/test/Index/kinds.swift
@@ -6,7 +6,7 @@
 
   // EnumElement
   case Element
-  // CHECK: [[@LINE-1]]:8 | enumerator/Swift | Element | s:14swift_ide_test13AnEnumerationO7ElementA2CmF | Def,RelChild | rel: 1
+  // CHECK: [[@LINE-1]]:8 | enumerator/Swift | Element | s:14swift_ide_test13AnEnumerationO7ElementyA2CmF | Def,RelChild | rel: 1
   // CHECK-NEXT: RelChild | enum/Swift | AnEnumeration | s:14swift_ide_test13AnEnumerationO
 }
 
@@ -18,21 +18,21 @@
 
   // Subscript
   subscript(index: Int) -> Int {
-    // CHECK: [[@LINE-1]]:3 | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVS2icip | Def,RelChild | rel: 1
+    // CHECK: [[@LINE-1]]:3 | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVyS2icip | Def,RelChild | rel: 1
     // CHECK-NEXT: RelChild | struct/Swift | AStruct | s:14swift_ide_test7AStructV
 
     // Accessor + AccessorAddressor
     unsafeAddress {
-      // CHECK: [[@LINE-1]]:5 | instance-method/acc-addr/Swift |  | s:14swift_ide_test7AStructVS2icilu | Def,RelChild,RelAcc | rel: 1
-      // CHECK-NEXT: RelChild,RelAcc | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVS2icip
+      // CHECK: [[@LINE-1]]:5 | instance-method/acc-addr/Swift |  | s:14swift_ide_test7AStructVyS2icilu | Def,RelChild,RelAcc | rel: 1
+      // CHECK-NEXT: RelChild,RelAcc | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVyS2icip
 
       return UnsafePointer(base)
     }
 
     // Accessor + AccessorMutableAddressor
     unsafeMutableAddress {
-      // CHECK: [[@LINE-1]]:5 | instance-method/acc-mutaddr/Swift |  | s:14swift_ide_test7AStructVS2iciau | Def,RelChild,RelAcc | rel: 1
-      // CHECK-NEXT: RelChild,RelAcc | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVS2icip
+      // CHECK: [[@LINE-1]]:5 | instance-method/acc-mutaddr/Swift |  | s:14swift_ide_test7AStructVyS2iciau | Def,RelChild,RelAcc | rel: 1
+      // CHECK-NEXT: RelChild,RelAcc | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVyS2icip
 
       return base
     }
@@ -48,10 +48,10 @@
 
   // InstanceMethod + Parameters
   func instanceMethod(a: Int, b b: Int, _ c: Int, d _: Int, _: Int) {
-  // CHECK: [[@LINE-1]]:8 | instance-method/Swift | instanceMethod(a:b:_:d:_:) | s:14swift_ide_test6AClassC14instanceMethodySi1a_Si1bS2i1dSitF | Def,Dyn,RelChild | rel: 1
+  // CHECK: [[@LINE-1]]:8 | instance-method/Swift | instanceMethod(a:b:_:d:_:) | s:14swift_ide_test6AClassC14instanceMethod1a1b_1d_ySi_S4itF | Def,Dyn,RelChild | rel: 1
   // CHECK-NEXT: RelChild | class/Swift | AClass | s:14swift_ide_test6AClassC
-  // CHECK: [[@LINE-3]]:23 | param/Swift | a | s:14swift_ide_test6AClassC14instanceMethodySi1a_Si1bS2i1dSitFAEL_Sivp | Def,RelChild | rel: 1
-  // CHECK-NEXT: RelChild | instance-method/Swift | instanceMethod(a:b:_:d:_:) | s:14swift_ide_test6AClassC14instanceMethodySi1a_Si1bS2i1dSitF
+  // CHECK: [[@LINE-3]]:23 | param/Swift | a | s:14swift_ide_test6AClassC14instanceMethod1a1b_1d_ySi_S4itFAEL_Sivp | Def,RelChild | rel: 1
+  // CHECK-NEXT: RelChild | instance-method/Swift | instanceMethod(a:b:_:d:_:) | s:14swift_ide_test6AClassC14instanceMethod1a1b_1d_ySi_S4itF
   // CHECK: [[@LINE-5]]:33 | param(local)/Swift | b | s:{{.*}} | Def,RelChild | rel: 1
   // CHECK: [[@LINE-6]]:43 | param(local)/Swift | c | s:{{.*}} | Def,RelChild | rel: 1
   // CHECK: [[@LINE-7]]:53 | param(local)/Swift | _ | s:{{.*}} | Def,RelChild | rel: 1
@@ -182,15 +182,15 @@
 
 // PrefixOperator
 prefix func -(a: AStruct) -> AStruct { return a }
-// CHECK: [[@LINE-1]]:13 | function/prefix-operator/Swift | -(_:) | s:14swift_ide_test1sopAA7AStructVADF | Def | rel: 0
+// CHECK: [[@LINE-1]]:13 | function/prefix-operator/Swift | -(_:) | s:14swift_ide_test1sopyAA7AStructVADF | Def | rel: 0
 
 // PostfixOperator
 postfix func ++(a: AStruct) -> AStruct { return a }
-// CHECK: [[@LINE-1]]:14 | function/postfix-operator/Swift | ++(_:) | s:14swift_ide_test2ppoPAA7AStructVADF | Def | rel: 0
+// CHECK: [[@LINE-1]]:14 | function/postfix-operator/Swift | ++(_:) | s:14swift_ide_test2ppoPyAA7AStructVADF | Def | rel: 0
 
 // InfixOperator
 func +(a: AStruct, b: AStruct) -> AStruct { return a }
-// CHECK: [[@LINE-1]]:6 | function/infix-operator/Swift | +(_:_:) | s:14swift_ide_test1poiAA7AStructVAD_ADtF | Def | rel: 0
+// CHECK: [[@LINE-1]]:6 | function/infix-operator/Swift | +(_:_:) | s:14swift_ide_test1poiyAA7AStructVAD_ADtF | Def | rel: 0
 
 class XCTestCase {}
 class MyTestCase : XCTestCase {
diff --git a/test/Index/roles.swift b/test/Index/roles.swift
index 8c8acaf..886025b 100644
--- a/test/Index/roles.swift
+++ b/test/Index/roles.swift
@@ -17,18 +17,18 @@
 var y = x + 1
 // CHECK: [[@LINE-1]]:5 | variable/Swift | y | s:14swift_ide_test1ySivp | Def | rel: 0
 // CHECK: [[@LINE-2]]:9 | variable/Swift | x | s:14swift_ide_test1xSivp | Ref,Read | rel: 0
-// CHECK: [[@LINE-3]]:11 | static-method/infix-operator/Swift | +(_:_:) | s:Si1poiS2i_SitFZ | Ref | rel: 0
+// CHECK: [[@LINE-3]]:11 | static-method/infix-operator/Swift | +(_:_:) | s:Si1poiyS2i_SitFZ | Ref | rel: 0
 
 // Read of x + Write of y
 y = x + 1
 // CHECK: [[@LINE-1]]:1 | variable/Swift | y | s:14swift_ide_test1ySivp | Ref,Writ | rel: 0
 // CHECK: [[@LINE-2]]:5 | variable/Swift | x | s:14swift_ide_test1xSivp | Ref,Read | rel: 0
-// CHECK: [[@LINE-3]]:7 | static-method/infix-operator/Swift | +(_:_:) | s:Si1poiS2i_SitFZ | Ref | rel: 0
+// CHECK: [[@LINE-3]]:7 | static-method/infix-operator/Swift | +(_:_:) | s:Si1poiyS2i_SitFZ | Ref | rel: 0
 
 // Read of y + Write of y
 y += x
 // CHECK: [[@LINE-1]]:1 | variable/Swift | y | s:14swift_ide_test1ySivp | Ref,Read,Writ | rel: 0
-// CHECK: [[@LINE-2]]:3 | static-method/infix-operator/Swift | +=(_:_:) | s:Si2peoiySiz_SitFZ | Ref | rel: 0
+// CHECK: [[@LINE-2]]:3 | static-method/infix-operator/Swift | +=(_:_:) | s:Si2peoiyySiz_SitFZ | Ref | rel: 0
 // CHECK: [[@LINE-3]]:6 | variable/Swift | x | s:14swift_ide_test1xSivp | Ref,Read | rel: 0
 
 var z: Int {
@@ -57,23 +57,23 @@
 
 // Call
 func aCalledFunction(a: Int, b: inout Int) {
-// CHECK: [[@LINE-1]]:6 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunctionySi1a_Siz1btF | Def | rel: 0
+// CHECK: [[@LINE-1]]:6 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF | Def | rel: 0
 // CHECK: [[@LINE-2]]:22 | param/Swift | a | s:{{.*}} | Def,RelChild | rel: 1
-// CHECK-NEXT: RelChild | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunctionySi1a_Siz1btF
+// CHECK-NEXT: RelChild | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF
 // CHECK: [[@LINE-4]]:30 | param/Swift | b | s:{{.*}} | Def,RelChild | rel: 1
-// CHECK-NEXT: RelChild | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunctionySi1a_Siz1btF
+// CHECK-NEXT: RelChild | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF
 
   var _ = a + b
   // CHECK: [[@LINE-1]]:11 | param/Swift | a | s:{{.*}} | Ref,Read,RelCont | rel: 1
-  // CHECK-NEXT: RelCont | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunctionySi1a_Siz1btF
+  // CHECK-NEXT: RelCont | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF
   // CHECK: [[@LINE-3]]:15 | param/Swift | b | s:{{.*}} | Ref,Read,RelCont | rel: 1
-  // CHECK-NEXT: RelCont | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunctionySi1a_Siz1btF
+  // CHECK-NEXT: RelCont | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF
 
   b = a + 1
   // CHECK: [[@LINE-1]]:3 | param/Swift | b | s:{{.*}} | Ref,Writ,RelCont | rel: 1
-  // CHECK-NEXT: RelCont | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunctionySi1a_Siz1btF
+  // CHECK-NEXT: RelCont | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF
   // CHECK: [[@LINE-3]]:7 | param/Swift | a | s:{{.*}} | Ref,Read,RelCont | rel: 1
-  // CHECK-NEXT: RelCont | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunctionySi1a_Siz1btF
+  // CHECK-NEXT: RelCont | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF
 
   _ = { ignored in ignored + 1}
   // CHECK-NOT: [[@LINE-1]]:9 {{.*}} | ignored | {{.*}}
@@ -81,19 +81,19 @@
 }
 
 aCalledFunction(a: 1, b: &z)
-// CHECK: [[@LINE-1]]:1 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunctionySi1a_Siz1btF | Ref,Call | rel: 0
+// CHECK: [[@LINE-1]]:1 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF | Ref,Call | rel: 0
 // CHECK: [[@LINE-2]]:27 | variable/Swift | z | s:14swift_ide_test1zSivp | Ref,Read,Writ | rel: 0
 
 func aCaller() {
   // CHECK: [[@LINE-1]]:6 | function/Swift | aCaller() | s:14swift_ide_test7aCalleryyF | Def | rel: 0
 
   aCalledFunction(a: 1, b: &z)
-  // CHECK: [[@LINE-1]]:3 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunctionySi1a_Siz1btF | Ref,Call,RelCall,RelCont | rel: 1
+  // CHECK: [[@LINE-1]]:3 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF | Ref,Call,RelCall,RelCont | rel: 1
   // CHECK-NEXT: RelCall,RelCont | function/Swift | aCaller() | s:14swift_ide_test7aCalleryyF
 }
 
 let aRef = aCalledFunction
-// CHECK: [[@LINE-1]]:12 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunctionySi1a_Siz1btF | Ref | rel: 0
+// CHECK: [[@LINE-1]]:12 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF | Ref | rel: 0
 
 // RelationChildOf, Implicit
 struct AStruct {
@@ -119,24 +119,24 @@
     // CHECK: [[@LINE-6]]:5 | instance-method/acc-set/Swift | setter:x | s:14swift_ide_test7AStructV1xSivs | Ref,Call,Impl,RelRec,RelCall,RelCont | rel: 2
     // CHECK-NEXT: RelCall,RelCont | instance-method/Swift | aMethod() | s:14swift_ide_test7AStructV7aMethodyyF
     // CHECK-NEXT: RelRec | struct/Swift | AStruct | [[AStruct_USR]]
-    // CHECK: [[@LINE-9]]:7 | static-method/infix-operator/Swift | +=(_:_:) | s:Si2peoiySiz_SitFZ | Ref,RelCont | rel: 1
+    // CHECK: [[@LINE-9]]:7 | static-method/infix-operator/Swift | +=(_:_:) | s:Si2peoiyySiz_SitFZ | Ref,RelCont | rel: 1
     // CHECK-NEXT: RelCont | instance-method/Swift | aMethod() | s:14swift_ide_test7AStructV7aMethodyyF
   }
 
   // RelationChildOf, RelationAccessorOf
   subscript(index: Int) -> Int {
-    // CHECK: [[@LINE-1]]:3 | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVS2icip | Def,RelChild | rel: 1
+    // CHECK: [[@LINE-1]]:3 | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVyS2icip | Def,RelChild | rel: 1
     // CHECK-NEXT: RelChild | struct/Swift | AStruct | [[AStruct_USR]]
 
     get {
-      // CHECK: [[@LINE-1]]:5 | instance-method/acc-get/Swift | getter:subscript(_:) | s:14swift_ide_test7AStructVS2icig | Def,RelChild,RelAcc | rel: 1
-      // CHECK-NEXT: RelChild,RelAcc | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVS2icip
+      // CHECK: [[@LINE-1]]:5 | instance-method/acc-get/Swift | getter:subscript(_:) | s:14swift_ide_test7AStructVyS2icig | Def,RelChild,RelAcc | rel: 1
+      // CHECK-NEXT: RelChild,RelAcc | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVyS2icip
 
       return x
     }
     set {
-      // CHECK: [[@LINE-1]]:5 | instance-method/acc-set/Swift | setter:subscript(_:) | s:14swift_ide_test7AStructVS2icis | Def,RelChild,RelAcc | rel: 1
-      // CHECK-NEXT: RelChild,RelAcc | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVS2ici
+      // CHECK: [[@LINE-1]]:5 | instance-method/acc-set/Swift | setter:subscript(_:) | s:14swift_ide_test7AStructVyS2icis | Def,RelChild,RelAcc | rel: 1
+      // CHECK-NEXT: RelChild,RelAcc | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVyS2ici
 
       x = newValue
     }
@@ -321,7 +321,7 @@
 
 var anInstance = AClass(x: 1)
 // CHECK: [[@LINE-1]]:18 | class/Swift | AClass | s:14swift_ide_test6AClassC | Ref | rel: 0
-// CHECK: [[@LINE-2]]:18 | constructor/Swift | init(x:) | s:14swift_ide_test6AClassCACSi1x_tcfc | Ref,Call | rel: 0
+// CHECK: [[@LINE-2]]:18 | constructor/Swift | init(x:) | s:14swift_ide_test6AClassC1xACSi_tcfc | Ref,Call | rel: 0
 
 anInstance.y.x = anInstance.y.x
 // CHECK: [[@LINE-1]]:1 | variable/Swift | anInstance | s:14swift_ide_test10anInstanceAA6AClassCvp | Ref,Read | rel: 0
@@ -353,7 +353,7 @@
 
 let _ = otherInstance[0]
 // CHECK: [[@LINE-1]]:9 | variable/Swift | otherInstance | s:14swift_ide_test13otherInstanceAA7AStructVvp | Ref,Read | rel: 0
-// CHECK: [[@LINE-2]]:22 | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVS2icip | Ref,Read | rel: 0
+// CHECK: [[@LINE-2]]:22 | instance-property/subscript/Swift | subscript(_:) | s:14swift_ide_test7AStructVyS2icip | Ref,Read | rel: 0
 
 let _ = anInstance[0]
 // CHECK: [[@LINE-1]]:9 | variable/Swift | anInstance | s:14swift_ide_test10anInstanceAA6AClassCvp | Ref,Read | rel: 0
@@ -406,7 +406,7 @@
       // CHECK-NEXT: RelCont | function/Swift | containing() | s:14swift_ide_test10containingyyF
 
       aCalledFunction(a: 1, b: &z)
-      // CHECK: [[@LINE-1]]:7 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunctionySi1a_Siz1btF | Ref,Call,RelCall,RelCont | rel: 1
+      // CHECK: [[@LINE-1]]:7 | function/Swift | aCalledFunction(a:b:) | s:14swift_ide_test15aCalledFunction1a1bySi_SiztF | Ref,Call,RelCall,RelCont | rel: 1
       // CHECK-NEXT: RelCall,RelCont | function/Swift | containing() | s:14swift_ide_test10containingyyF
 
       return contained
@@ -445,16 +445,16 @@
   // CHECK-NEXT: RelOver | instance-method/Swift | bar1() | s:14swift_ide_test11ProtDerivedP4bar1yyF
 
   func foo3(a : Int) {}
-  // CHECK: [[@LINE-1]]:8 | instance-method/Swift | foo3(a:) | s:14swift_ide_test11ProtDerivedPAAE4foo3ySi1a_tF | Def,Dyn,RelChild,RelOver | rel: 2
-  // CHECK-NEXT: RelOver | instance-method/Swift | foo3(a:) | s:14swift_ide_test8ProtRootP4foo3ySi1a_tF
+  // CHECK: [[@LINE-1]]:8 | instance-method/Swift | foo3(a:) | s:14swift_ide_test11ProtDerivedPAAE4foo31aySi_tF | Def,Dyn,RelChild,RelOver | rel: 2
+  // CHECK-NEXT: RelOver | instance-method/Swift | foo3(a:) | s:14swift_ide_test8ProtRootP4foo31aySi_tF
 
   func foo3(a : String) {}
-  // CHECK: [[@LINE-1]]:8 | instance-method/Swift | foo3(a:) | s:14swift_ide_test11ProtDerivedPAAE4foo3ySS1a_tF | Def,Dyn,RelChild,RelOver | rel: 2
-  // CHECK-NEXT: RelOver | instance-method/Swift | foo3(a:) | s:14swift_ide_test8ProtRootP4foo3ySS1a_tF
+  // CHECK: [[@LINE-1]]:8 | instance-method/Swift | foo3(a:) | s:14swift_ide_test11ProtDerivedPAAE4foo31aySS_tF | Def,Dyn,RelChild,RelOver | rel: 2
+  // CHECK-NEXT: RelOver | instance-method/Swift | foo3(a:) | s:14swift_ide_test8ProtRootP4foo31aySS_tF
 
   func bar3(_ : Int) {}
-  // CHECK: [[@LINE-1]]:8 | instance-method/Swift | bar3(_:) | s:14swift_ide_test11ProtDerivedPAAE4bar3ySiF | Def,Dyn,RelChild,RelOver | rel: 2
-  // CHECK-NEXT: RelOver | instance-method/Swift | bar3(_:) | s:14swift_ide_test11ProtDerivedP4bar3ySiF
+  // CHECK: [[@LINE-1]]:8 | instance-method/Swift | bar3(_:) | s:14swift_ide_test11ProtDerivedPAAE4bar3yySiF | Def,Dyn,RelChild,RelOver | rel: 2
+  // CHECK-NEXT: RelOver | instance-method/Swift | bar3(_:) | s:14swift_ide_test11ProtDerivedP4bar3yySiF
 }
 
 enum MyEnum {
diff --git a/test/Inputs/comment_to_something_conversion.swift b/test/Inputs/comment_to_something_conversion.swift
index 480f77a..72c3700 100644
--- a/test/Inputs/comment_to_something_conversion.swift
+++ b/test/Inputs/comment_to_something_conversion.swift
@@ -15,7 +15,7 @@
 
 /// Aaa.  subscript(i: Int).
 @objc public subscript(i: Int) -> Int {
-// CHECK: {{.*}}DocCommentAsXML=[<Other file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>subscript(_:)</Name><USR>s:14comment_to_xml21A010_AttachToEntitiesCS2icip</USR><Declaration>@objc public subscript(i: Int) -&gt; Int { get set }</Declaration><CommentParts><Abstract><Para>Aaa.  subscript(i: Int).</Para></Abstract></CommentParts></Other>]
+// CHECK: {{.*}}DocCommentAsXML=[<Other file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>subscript(_:)</Name><USR>s:14comment_to_xml21A010_AttachToEntitiesCyS2icip</USR><Declaration>@objc public subscript(i: Int) -&gt; Int { get set }</Declaration><CommentParts><Abstract><Para>Aaa.  subscript(i: Int).</Para></Abstract></CommentParts></Other>]
     get {
 // CHECK: {{.*}}DocCommentAsXML=none
       return 0
diff --git a/test/Inputs/conditional_conformance_basic_conformances.swift b/test/Inputs/conditional_conformance_basic_conformances.swift
index 58f355e..981b315 100644
--- a/test/Inputs/conditional_conformance_basic_conformances.swift
+++ b/test/Inputs/conditional_conformance_basic_conformances.swift
@@ -32,7 +32,7 @@
 
 // witness method for Single.generic
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc void @_T042conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlAaEP7genericyqd__AA2P3Rd__lFTW(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T42conditional_conformance_basic_conformances6SingleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable) #0 {
+// CHECK-LABEL: define linkonce_odr hidden swiftcc void @_T042conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T42conditional_conformance_basic_conformances6SingleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable) #0 {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:    [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1
 // CHECK-NEXT:    [[A_P2_i8star:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8
@@ -40,14 +40,14 @@
 // CHECK-NEXT:    [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type**
 // CHECK-NEXT:    [[A_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2
 // CHECK-NEXT:    [[A:%.*]] = load %swift.type*, %swift.type** [[A_PTR]], align 8
-// CHECK-NEXT:    call swiftcc void @_T042conditional_conformance_basic_conformances6SingleVA2A2P2RzlE7genericyqd__AA2P3Rd__lF(%swift.opaque* noalias nocapture %0, %swift.type* [[A]], %swift.type* %"\CF\84_1_0", i8** [[A_P2]], i8** %"\CF\84_1_0.P3")
+// CHECK-NEXT:    call swiftcc void @_T042conditional_conformance_basic_conformances6SingleVA2A2P2RzlE7genericyyqd__AA2P3Rd__lF(%swift.opaque* noalias nocapture %0, %swift.type* [[A]], %swift.type* %"\CF\84_1_0", i8** [[A_P2]], i8** %"\CF\84_1_0.P3")
 // CHECK-NEXT:    ret void
 // CHECK-NEXT:  }
 
 public func single_generic<T: P2>(_: T.Type) {
   takes_p1(Single<T>.self)
 }
-// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T042conditional_conformance_basic_conformances14single_genericyxmAA2P2RzlF(%swift.type*, %swift.type* %T, i8** %T.P2) #0 {
+// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T042conditional_conformance_basic_conformances14single_genericyyxmAA2P2RzlF(%swift.type*, %swift.type* %T, i8** %T.P2) #0 {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:    %conditional.requirement.buffer = alloca [1 x i8**], align 8
 // CHECK-NEXT:    [[Single_TYPE:%.*]] = call %swift.type* @_T042conditional_conformance_basic_conformances6SingleVMa(%swift.type* %T)
@@ -55,7 +55,7 @@
 // CHECK-NEXT:    [[T_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
 // CHECK-NEXT:    store i8** %T.P2, i8*** [[T_P2_PTR]], align 8
 // CHECK-NEXT:    [[Single_P1:%.*]] = call i8** @_T042conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlWa(%swift.type* [[Single_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]], i64 1)
-// CHECK-NEXT:    call swiftcc void @_T042conditional_conformance_basic_conformances8takes_p1yxmAA2P1RzlF(%swift.type* [[Single_TYPE]], %swift.type* [[Single_TYPE]], i8** [[Single_P1]])
+// CHECK-NEXT:    call swiftcc void @_T042conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF(%swift.type* [[Single_TYPE]], %swift.type* [[Single_TYPE]], i8** [[Single_P1]])
 // CHECK-NEXT:    ret void
 // CHECK-NEXT:  }
 
@@ -81,7 +81,7 @@
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:    [[Single_TYPE:%.*]] = call %swift.type* @_T042conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMa()
 // CHECK-NEXT:    [[Single_P1:%.*]] = call i8** @_T042conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWl()
-// CHECK-NEXT:    call swiftcc void @_T042conditional_conformance_basic_conformances8takes_p1yxmAA2P1RzlF(%swift.type* [[Single_TYPE]], %swift.type* [[Single_TYPE]], i8** [[Single_P1]])
+// CHECK-NEXT:    call swiftcc void @_T042conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF(%swift.type* [[Single_TYPE]], %swift.type* [[Single_TYPE]], i8** [[Single_P1]])
 // CHECK-NEXT:    ret void
 // CHECK-NEXT:  }
 
@@ -144,7 +144,7 @@
 
 // witness method for Double.generic
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc void @_T042conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlAaEP7genericyqd__AaGRd__lFTW(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T42conditional_conformance_basic_conformances6DoubleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable) #0 {
+// CHECK-LABEL: define linkonce_odr hidden swiftcc void @_T042conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlAaEP7genericyyqd__AaGRd__lFTW(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T42conditional_conformance_basic_conformances6DoubleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable) #0 {
 // CHECK-NEXT:  entry:
 
 // CHECK-NEXT:    [[B_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1
@@ -163,7 +163,7 @@
 // CHECK-NEXT:    [[C_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY_2]], i64 3
 // CHECK-NEXT:    [[C:%.*]] = load %swift.type*, %swift.type** [[C_PTR]], align 8
 
-// CHECK-NEXT:    call swiftcc void @_T042conditional_conformance_basic_conformances6DoubleVA2A2P2RzAA2P3R_rlE7genericyqd__AaERd__lF(%swift.opaque* noalias nocapture %0, %swift.type* [[B]], %swift.type* [[C]], %swift.type* %"\CF\84_1_0", i8** [[B_P2]], i8** [[C_P3]], i8** %"\CF\84_1_0.P3")
+// CHECK-NEXT:    call swiftcc void @_T042conditional_conformance_basic_conformances6DoubleVA2A2P2RzAA2P3R_rlE7genericyyqd__AaERd__lF(%swift.opaque* noalias nocapture %0, %swift.type* [[B]], %swift.type* [[C]], %swift.type* %"\CF\84_1_0", i8** [[B_P2]], i8** [[C_P3]], i8** %"\CF\84_1_0.P3")
 // CHECK-NEXT:    ret void
 // CHECK-NEXT:  }
 
@@ -171,7 +171,7 @@
 public func double_generic_generic<U: P2, V: P3>(_: U.Type, _: V.Type) {
   takes_p1(Double<U, V>.self)
 }
-// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T042conditional_conformance_basic_conformances015double_generic_F0yxm_q_mtAA2P2RzAA2P3R_r0_lF(%swift.type*, %swift.type*, %swift.type* %U, %swift.type* %V, i8** %U.P2, i8** %V.P3) #0 {
+// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T042conditional_conformance_basic_conformances015double_generic_F0yyxm_q_mtAA2P2RzAA2P3R_r0_lF(%swift.type*, %swift.type*, %swift.type* %U, %swift.type* %V, i8** %U.P2, i8** %V.P3) #0 {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:    %conditional.requirement.buffer = alloca [2 x i8**], align 8
 // CHECK-NEXT:    [[Double_TYPE:%.*]] = call %swift.type* @_T042conditional_conformance_basic_conformances6DoubleVMa(%swift.type* %U, %swift.type* %V)
@@ -183,7 +183,7 @@
 // CHECK-NEXT:    store i8** %V.P3, i8*** [[C_P3_PTR]], align 8
 
 // CHECK-NEXT:    [[Double_P1:%.*]] = call i8** @_T042conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlWa(%swift.type* [[Double_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]], i64 2)
-// CHECK-NEXT:    call swiftcc void @_T042conditional_conformance_basic_conformances8takes_p1yxmAA2P1RzlF(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]])
+// CHECK-NEXT:    call swiftcc void @_T042conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]])
 // CHECK-NEXT:    ret void
 // CHECK-NEXT:  }
 
@@ -205,7 +205,7 @@
 public func double_generic_concrete<X: P2>(_: X.Type) {
   takes_p1(Double<X, IsP3>.self)
 }
-// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T042conditional_conformance_basic_conformances23double_generic_concreteyxmAA2P2RzlF(%swift.type*, %swift.type* %X, i8** %X.P2) #0 {
+// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T042conditional_conformance_basic_conformances23double_generic_concreteyyxmAA2P2RzlF(%swift.type*, %swift.type* %X, i8** %X.P2) #0 {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:    %conditional.requirement.buffer = alloca [2 x i8**], align 8
 // CHECK-NEXT:    [[Double_TYPE:%.*]] = call %swift.type* @_T042conditional_conformance_basic_conformances6DoubleVMa(%swift.type* %X, %swift.type* bitcast (i64* getelementptr inbounds (<{ i8**, i64, <{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i32 }>* }>, <{ i8**, i64, <{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i32 }>* }>* @_T042conditional_conformance_basic_conformances4IsP3VMf, i32 0, i32 1) to %swift.type*))
@@ -217,7 +217,7 @@
 // CHECK-NEXT:    store i8** getelementptr inbounds ([0 x i8*], [0 x i8*]* @_T042conditional_conformance_basic_conformances4IsP3VAA0F0AAWP, i32 0, i32 0), i8*** [[C_P3_PTR]], align 8
 
 // CHECK-NEXT:    [[Double_P1:%.*]] = call i8** @_T042conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlWa(%swift.type* %1, i8*** [[CONDITIONAL_REQUIREMENTS]], i64 2)
-// CHECK-NEXT:    call swiftcc void @_T042conditional_conformance_basic_conformances8takes_p1yxmAA2P1RzlF(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]])
+// CHECK-NEXT:    call swiftcc void @_T042conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]])
 // CHECK-NEXT:    ret void
 // CHECK-NEXT:  }
 
@@ -228,7 +228,7 @@
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:    [[Double_TYPE:%.*]] = call %swift.type* @_T042conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGMa()
 // CHECK-NEXT:    [[Double_P1:%.*]] = call i8** @_T042conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWl()
-// CHECK-NEXT:    call swiftcc void @_T042conditional_conformance_basic_conformances8takes_p1yxmAA2P1RzlF(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]])
+// CHECK-NEXT:    call swiftcc void @_T042conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]])
 // CHECK-NEXT:    ret void
 // CHECK-NEXT:  }
 
diff --git a/test/Inputs/conditional_conformance_subclass.swift b/test/Inputs/conditional_conformance_subclass.swift
index 76f27eb..1af6e96 100644
--- a/test/Inputs/conditional_conformance_subclass.swift
+++ b/test/Inputs/conditional_conformance_subclass.swift
@@ -28,13 +28,13 @@
 
 // witness method for Base.generic
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc void @_T032conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlAaEP7genericyqd__AA2P3Rd__lFTW(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T32conditional_conformance_subclass4BaseC.1** noalias nocapture swiftself dereferenceable(8), %swift.type* %Self, i8** %SelfWitnessTable) #0 {
+// CHECK-LABEL: define linkonce_odr hidden swiftcc void @_T032conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T32conditional_conformance_subclass4BaseC.1** noalias nocapture swiftself dereferenceable(8), %swift.type* %Self, i8** %SelfWitnessTable) #0 {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:    [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1
 // CHECK-NEXT:    [[A_P2:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8
 // CHECK-NEXT:    %"\CF\84_0_0.P2" = bitcast i8* [[A_P2]] to i8**
 // CHECK-NEXT:    [[SELF:%.]] = load %T32conditional_conformance_subclass4BaseC.1*, %T32conditional_conformance_subclass4BaseC.1** %1, align 8
-// CHECK-NEXT:    call swiftcc void @_T032conditional_conformance_subclass4BaseCA2A2P2RzlE7genericyqd__AA2P3Rd__lF(%swift.opaque* noalias nocapture %0, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_0_0.P2", i8** %"\CF\84_1_0.P3", %T32conditional_conformance_subclass4BaseC.1* swiftself [[SELF]])
+// CHECK-NEXT:    call swiftcc void @_T032conditional_conformance_subclass4BaseCA2A2P2RzlE7genericyyqd__AA2P3Rd__lF(%swift.opaque* noalias nocapture %0, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_0_0.P2", i8** %"\CF\84_1_0.P3", %T32conditional_conformance_subclass4BaseC.1* swiftself [[SELF]])
 // CHECK-NEXT:    ret void
 // CHECK-NEXT:  }
 
@@ -47,7 +47,7 @@
   takes_p1(SubclassGeneric<T>.self)
 }
 
-// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T032conditional_conformance_subclass23subclassgeneric_genericyxmAA2P2RzlF(%swift.type*, %swift.type* %T, i8** %T.P2) #0 {
+// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T032conditional_conformance_subclass23subclassgeneric_genericyyxmAA2P2RzlF(%swift.type*, %swift.type* %T, i8** %T.P2) #0 {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:    %conditional.requirement.buffer = alloca [1 x i8**], align 8
 // CHECK-NEXT:    [[SubclassGeneric_TYPE:%.*]] = call %swift.type* @_T032conditional_conformance_subclass15SubclassGenericCMa(%swift.type* %T)
@@ -55,7 +55,7 @@
 // CHECK-NEXT:    [[T_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
 // CHECK-NEXT:    store i8** %T.P2, i8*** [[T_P2_PTR]], align 8
 // CHECK-NEXT:    [[Base_P1:%.*]] = call i8** @_T032conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWa(%swift.type* [[SubclassGeneric_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]], i64 1)
-// CHECK-NEXT:    call swiftcc void @_T032conditional_conformance_subclass8takes_p1yxmAA2P1RzlF(%swift.type* [[SubclassGeneric_TYPE]], %swift.type* [[SubclassGeneric_TYPE]], i8** [[Base_P1]])
+// CHECK-NEXT:    call swiftcc void @_T032conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF(%swift.type* [[SubclassGeneric_TYPE]], %swift.type* [[SubclassGeneric_TYPE]], i8** [[Base_P1]])
 // CHECK-NEXT:    ret void
 // CHECK-NEXT:  }
 
@@ -81,7 +81,7 @@
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:    [[SubclassGeneric_TYPE:%.*]] = call %swift.type* @_T032conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMa()
 // CHECK-NEXT:    [[Base_P1:%.*]] = call i8** @_T032conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWl()
-// CHECK-NEXT:    call swiftcc void @_T032conditional_conformance_subclass8takes_p1yxmAA2P1RzlF(%swift.type* [[SubclassGeneric_TYPE]], %swift.type* [[SubclassGeneric_TYPE]], i8** [[Base_P1]])
+// CHECK-NEXT:    call swiftcc void @_T032conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF(%swift.type* [[SubclassGeneric_TYPE]], %swift.type* [[SubclassGeneric_TYPE]], i8** [[Base_P1]])
 // CHECK-NEXT:    ret void
 // CHECK-NEXT:  }
 
@@ -116,7 +116,7 @@
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:    [[SubclassConcrete_TYPE:%.*]] = call %swift.type* @_T032conditional_conformance_subclass16SubclassConcreteCMa()
 // CHECK-NEXT:    [[SubclassConcrete_P1:%.*]] = call i8** @_T032conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl()
-// CHECK-NEXT:    call swiftcc void @_T032conditional_conformance_subclass8takes_p1yxmAA2P1RzlF(%swift.type* [[SubclassConcrete_TYPE]], %swift.type* [[SubclassConcrete_TYPE]], i8** [[SubclassConcrete_P1]])
+// CHECK-NEXT:    call swiftcc void @_T032conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF(%swift.type* [[SubclassConcrete_TYPE]], %swift.type* [[SubclassConcrete_TYPE]], i8** [[SubclassConcrete_P1]])
 // CHECK-NEXT:    ret void
 // CHECK-NEXT:  }
 
@@ -149,7 +149,7 @@
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:    [[SubclassGenericConcrete_TYPE:%.*]] = call %swift.type* @_T032conditional_conformance_subclass23SubclassGenericConcreteCMa()
 // CHECK-NEXT:    [[SubclassGenericConcrete_P1:%.*]] = call i8** @_T032conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl()
-// CHECK-NEXT:    call swiftcc void @_T032conditional_conformance_subclass8takes_p1yxmAA2P1RzlF(%swift.type* [[SubclassGenericConcrete_TYPE]], %swift.type* [[SubclassGenericConcrete_TYPE]], i8** [[SubclassGenericConcrete_P1]])
+// CHECK-NEXT:    call swiftcc void @_T032conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF(%swift.type* [[SubclassGenericConcrete_TYPE]], %swift.type* [[SubclassGenericConcrete_TYPE]], i8** [[SubclassGenericConcrete_P1]])
 // CHECK-NEXT:    ret void
 // CHECK-NEXT:  }
 
diff --git a/test/Inputs/conditional_conformance_with_assoc.swift b/test/Inputs/conditional_conformance_with_assoc.swift
index 01336d6..1a01373 100644
--- a/test/Inputs/conditional_conformance_with_assoc.swift
+++ b/test/Inputs/conditional_conformance_with_assoc.swift
@@ -73,7 +73,7 @@
 
 // witness method for Double.generic
 
-// CHECK-LABEL: define linkonce_odr hidden swiftcc void @_T034conditional_conformance_with_assoc6DoubleVyxq_GAA2P1A2A2P3R_AA2P23AT2RpzAafH_AhaGP3AT3RPzrlAaEP7genericyqd__AaFRd__lFTW(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T34conditional_conformance_with_assoc6DoubleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable) #0 {
+// CHECK-LABEL: define linkonce_odr hidden swiftcc void @_T034conditional_conformance_with_assoc6DoubleVyxq_GAA2P1A2A2P3R_AA2P23AT2RpzAafH_AhaGP3AT3RPzrlAaEP7genericyyqd__AaFRd__lFTW(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T34conditional_conformance_with_assoc6DoubleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable) #0 {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:    [[C_P3_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1
 // CHECK-NEXT:    [[C_P3:%.*]] = load i8*, i8** [[C_P3_PTR]], align 8
@@ -99,7 +99,7 @@
 // CHECK-NEXT:    [[B_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[SELF_AS_WT_ARRAY]], i64 4
 // CHECK-NEXT:    %"\CF\84_0_0.P2" = load i8**, i8*** [[B_P2_PTR]], align 8
 
-// CHECK-NEXT:    call swiftcc void @_T034conditional_conformance_with_assoc6DoubleVA2A2P3R_AA2P23AT2RpzAadF_AfaEP3AT3RPzrlE7genericyqd__AaDRd__lF(%swift.opaque* noalias nocapture %0, %swift.type* %"\CF\84_0_0", %swift.type* %"\CF\84_0_1", %swift.type* %"\CF\84_1_0", i8** %"\CF\84_0_0.P2", i8** %"\CF\84_0_1.P3", i8** %"\CF\84_1_0.P3", i8** %"\CF\84_0_0.AT2.P2", i8** %"\CF\84_0_0.AT2.AT2.AT3.P3")
+// CHECK-NEXT:    call swiftcc void @_T034conditional_conformance_with_assoc6DoubleVA2A2P3R_AA2P23AT2RpzAadF_AfaEP3AT3RPzrlE7genericyyqd__AaDRd__lF(%swift.opaque* noalias nocapture %0, %swift.type* %"\CF\84_0_0", %swift.type* %"\CF\84_0_1", %swift.type* %"\CF\84_1_0", i8** %"\CF\84_0_0.P2", i8** %"\CF\84_0_1.P3", i8** %"\CF\84_1_0.P3", i8** %"\CF\84_0_0.AT2.P2", i8** %"\CF\84_0_0.AT2.AT2.AT3.P3")
 // CHECK-NEXT:    ret void
 // CHECK-NEXT:  }
 
@@ -109,7 +109,7 @@
 {
   takes_p1(Double<T, U>.self)
 }
-// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T034conditional_conformance_with_assoc08generic_E0yxm_q_mtAA2P2RzAA2P3R_AaC3AT2RpzAadE_AeaCP3AT3RPzr0_lF(%swift.type*, %swift.type*, %swift.type* %T, %swift.type* %U, i8** %T.P2, i8** %U.P3, i8** %T.AT2.P2, i8** %T.AT2.AT2.AT3.P3) #0 {
+// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T034conditional_conformance_with_assoc08generic_E0yyxm_q_mtAA2P2RzAA2P3R_AaC3AT2RpzAadE_AeaCP3AT3RPzr0_lF(%swift.type*, %swift.type*, %swift.type* %T, %swift.type* %U, i8** %T.P2, i8** %U.P3, i8** %T.AT2.P2, i8** %T.AT2.AT2.AT3.P3) #0 {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:    %conditional.requirement.buffer = alloca [3 x i8**], align 8
 // CHECK-NEXT:    [[Double_TYPE:%.*]] = call %swift.type* @_T034conditional_conformance_with_assoc6DoubleVMa(%swift.type* %T, %swift.type* %U, i8** %T.P2)
@@ -123,7 +123,7 @@
 // CHECK-NEXT:    store i8** %T.AT2.AT2.AT3.P3, i8*** [[B_AT2_AT2_AT3_P3_PTR]], align 8
 
 // CHECK-NEXT:    [[Double_P1:%.*]] = call i8** @_T034conditional_conformance_with_assoc6DoubleVyxq_GAA2P1A2A2P3R_AA2P23AT2RpzAafH_AhaGP3AT3RPzrlWa(%swift.type* [[Double_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]], i64 3)
-// CHECK-NEXT:    call swiftcc void @_T034conditional_conformance_with_assoc8takes_p1yxmAA2P1RzlF(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]])
+// CHECK-NEXT:    call swiftcc void @_T034conditional_conformance_with_assoc8takes_p1yyxmAA2P1RzlF(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]])
 // CHECK-NEXT:    ret void
 // CHECK-NEXT:  }
 
@@ -132,7 +132,7 @@
 {
   takes_p1(Double<T, IsP3>.self)
 }
-// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T034conditional_conformance_with_assoc16generic_concreteyxmAA2P2RzAaC3AT2RpzAA2P3AD_AdaCP3AT3RPzlF(%swift.type*, %swift.type* %T, i8** %T.P2, i8** %T.AT2.P2, i8** %T.AT2.AT2.AT3.P3) #0 {
+// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T034conditional_conformance_with_assoc16generic_concreteyyxmAA2P2RzAaC3AT2RpzAA2P3AD_AdaCP3AT3RPzlF(%swift.type*, %swift.type* %T, i8** %T.P2, i8** %T.AT2.P2, i8** %T.AT2.AT2.AT3.P3) #0 {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:    %conditional.requirement.buffer = alloca [3 x i8**], align 8
 // CHECK-NEXT:    [[Double_TYPE:%.*]] = call %swift.type* @_T034conditional_conformance_with_assoc6DoubleVMa(%swift.type* %T, %swift.type* bitcast (i64* getelementptr inbounds (<{ i8**, i64, <{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i32 }>* }>, <{ i8**, i64, <{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i32 }>* }>* @_T034conditional_conformance_with_assoc4IsP3VMf, i32 0, i32 1) to %swift.type*), i8** %T.P2)
@@ -146,7 +146,7 @@
 // CHECK-NEXT:    store i8** %T.AT2.AT2.AT3.P3, i8*** [[B_AT2_AT2_AT3_P3_PTR]], align 8
 
 // CHECK-NEXT:    [[Double_P1:%.*]] = call i8** @_T034conditional_conformance_with_assoc6DoubleVyxq_GAA2P1A2A2P3R_AA2P23AT2RpzAafH_AhaGP3AT3RPzrlWa(%swift.type* [[Double_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]], i64 3)
-// CHECK-NEXT:    call swiftcc void @_T034conditional_conformance_with_assoc8takes_p1yxmAA2P1RzlF(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]])
+// CHECK-NEXT:    call swiftcc void @_T034conditional_conformance_with_assoc8takes_p1yyxmAA2P1RzlF(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]])
 // CHECK-NEXT:    ret void
 // CHECK-NEXT:  }
 
@@ -157,7 +157,7 @@
   takes_p1(Double<IsAlsoP2, U>.self)
 }
 
-// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T034conditional_conformance_with_assoc16concrete_genericyxmAA2P3RzlF(%swift.type*, %swift.type* %U, i8** %U.P3) #0 {
+// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T034conditional_conformance_with_assoc16concrete_genericyyxmAA2P3RzlF(%swift.type*, %swift.type* %U, i8** %U.P3) #0 {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:  %conditional.requirement.buffer = alloca [3 x i8**], align 8
 // CHECK-NEXT:  [[Double_TYPE:%.*]] = call %swift.type* @_T034conditional_conformance_with_assoc6DoubleVMa(%swift.type* bitcast (i64* getelementptr inbounds (<{ i8**, i64, <{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i32 }>* }>, <{ i8**, i64, <{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i32 }>* }>* @_T034conditional_conformance_with_assoc8IsAlsoP2VMf, i32 0, i32 1) to %swift.type*), %swift.type* %U, i8** getelementptr inbounds ([2 x i8*], [2 x i8*]* @_T034conditional_conformance_with_assoc8IsAlsoP2VAA0G0AAWP, i32 0, i32 0))
@@ -169,7 +169,7 @@
 // CHECK-NEXT:  [[B_AT2_AT2_AT3_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 2
 // CHECK-NEXT:  store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @_T034conditional_conformance_with_assoc4IsP3VAA0F0AAWP, i32 0, i32 0), i8*** [[B_AT2_AT2_AT3_P3_PTR]], align 8
 // CHECK-NEXT:  [[Double_P1:%.*]] = call i8** @_T034conditional_conformance_with_assoc6DoubleVyxq_GAA2P1A2A2P3R_AA2P23AT2RpzAafH_AhaGP3AT3RPzrlWa(%swift.type* [[Double_TYPE]], i8*** [[CONDITIONAL_REQUIREMENTS]], i64 3)
-// CHECK-NEXT:  call swiftcc void @_T034conditional_conformance_with_assoc8takes_p1yxmAA2P1RzlF(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]])
+// CHECK-NEXT:  call swiftcc void @_T034conditional_conformance_with_assoc8takes_p1yyxmAA2P1RzlF(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]])
 // CHECK-NEXT:  ret void
 // CHECK-NEXT:}
 
@@ -182,7 +182,7 @@
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:    %0 = call %swift.type* @_T034conditional_conformance_with_assoc6DoubleVyAA8IsAlsoP2VAA0F2P3VGMa() #10
 // CHECK-NEXT:    %1 = call i8** @_T034conditional_conformance_with_assoc6DoubleVyAA8IsAlsoP2VAA0F2P3VGACyxq_GAA2P1A2A0I0R_AA0H03AT2RpzAakM_AmaLP3AT3RPzrlWl() #10
-// CHECK-NEXT:    call swiftcc void @_T034conditional_conformance_with_assoc8takes_p1yxmAA2P1RzlF(%swift.type* %0, %swift.type* %0, i8** %1)
+// CHECK-NEXT:    call swiftcc void @_T034conditional_conformance_with_assoc8takes_p1yyxmAA2P1RzlF(%swift.type* %0, %swift.type* %0, i8** %1)
 // CHECK-NEXT:    ret void
 // CHECK-NEXT: }
 
diff --git a/test/Interpreter/conditional_conformances.swift b/test/Interpreter/conditional_conformances.swift
index 0981767..ee035de 100644
--- a/test/Interpreter/conditional_conformances.swift
+++ b/test/Interpreter/conditional_conformances.swift
@@ -1,9 +1,9 @@
 // RUN: %empty-directory(%t)
 // The file that's `main` needs to be called that.
 // RUN: cp %s %t/main.swift
-// RUN: %target-build-swift -enable-experimental-conditional-conformances -D basic %t/main.swift %S/../Inputs/conditional_conformance_basic_conformances.swift -o %t/basic && %target-run %t/basic
-// RUN: %target-build-swift -enable-experimental-conditional-conformances -D with_assoc %t/main.swift %S/../Inputs/conditional_conformance_with_assoc.swift -o %t/with_assoc && %target-run %t/with_assoc
-// RUN: %target-build-swift -enable-experimental-conditional-conformances -D subclass %t/main.swift %S/../Inputs/conditional_conformance_subclass.swift -o %t/subclass && %target-run %t/subclass
+// RUN: %target-build-swift -D basic %t/main.swift %S/../Inputs/conditional_conformance_basic_conformances.swift -o %t/basic && %target-run %t/basic
+// RUN: %target-build-swift -D with_assoc %t/main.swift %S/../Inputs/conditional_conformance_with_assoc.swift -o %t/with_assoc && %target-run %t/with_assoc
+// RUN: %target-build-swift -D subclass %t/main.swift %S/../Inputs/conditional_conformance_subclass.swift -o %t/subclass && %target-run %t/subclass
 
 // REQUIRES: executable_test
 
diff --git a/test/Interpreter/conditional_conformances_modules.swift b/test/Interpreter/conditional_conformances_modules.swift
index 806c17a..9c0ab04 100644
--- a/test/Interpreter/conditional_conformances_modules.swift
+++ b/test/Interpreter/conditional_conformances_modules.swift
@@ -1,7 +1,7 @@
 // RUN: %empty-directory(%t)
-// RUN: %target-build-swift-dylib(%t/libBasic.%target-dylib-extension) -enable-experimental-conditional-conformances %S/../Inputs/conditional_conformance_basic_conformances.swift -module-name Basic -emit-module -emit-module-path %t/Basic.swiftmodule
-// RUN: %target-build-swift-dylib(%t/libWithAssoc.%target-dylib-extension) -enable-experimental-conditional-conformances %S/../Inputs/conditional_conformance_with_assoc.swift -module-name WithAssoc -emit-module -emit-module-path %t/WithAssoc.swiftmodule
-// RUN: %target-build-swift-dylib(%t/libSubclass.%target-dylib-extension) -enable-experimental-conditional-conformances %S/../Inputs/conditional_conformance_subclass.swift -module-name Subclass -emit-module -emit-module-path %t/Subclass.swiftmodule
+// RUN: %target-build-swift-dylib(%t/libBasic.%target-dylib-extension) %S/../Inputs/conditional_conformance_basic_conformances.swift -module-name Basic -emit-module -emit-module-path %t/Basic.swiftmodule
+// RUN: %target-build-swift-dylib(%t/libWithAssoc.%target-dylib-extension) %S/../Inputs/conditional_conformance_with_assoc.swift -module-name WithAssoc -emit-module -emit-module-path %t/WithAssoc.swiftmodule
+// RUN: %target-build-swift-dylib(%t/libSubclass.%target-dylib-extension) %S/../Inputs/conditional_conformance_subclass.swift -module-name Subclass -emit-module -emit-module-path %t/Subclass.swiftmodule
 // RUN: %target-build-swift -I%t -L%t -lBasic -lWithAssoc -lSubclass %s -o %t/conditional_conformances_modules -Xlinker -rpath -Xlinker %t
 // RUN: %target-run %t/conditional_conformances_modules %t/libBasic.%target-dylib-extension %t/libWithAssoc.%target-dylib-extension
 
diff --git a/test/Interpreter/conditional_conformances_smoke.swift b/test/Interpreter/conditional_conformances_smoke.swift
index 288f4b9c..aee921ec 100644
--- a/test/Interpreter/conditional_conformances_smoke.swift
+++ b/test/Interpreter/conditional_conformances_smoke.swift
@@ -1,6 +1,4 @@
-// RUN: %empty-directory(%t)
-// RUN: %target-build-swift -enable-experimental-conditional-conformances %s -o %t/a.out
-// RUN: %target-run %t/a.out | %FileCheck %s
+// RUN: %target-run-simple-swift | %FileCheck %s
 
 // REQUIRES: executable_test
 
diff --git a/test/Interpreter/conditional_conformances_warning.swift b/test/Interpreter/conditional_conformances_warning.swift
new file mode 100644
index 0000000..37a0d49
--- /dev/null
+++ b/test/Interpreter/conditional_conformances_warning.swift
@@ -0,0 +1,34 @@
+// RUN: rm -rf %t  &&  mkdir -p %t
+// RUN: %target-build-swift %s -o %t/a.out
+// RUN: %target-run %t/a.out 2>&1 | %FileCheck %s -check-prefix=CHECK_WARNINGS
+protocol P {
+  func foo()
+}
+
+struct X : P {
+  func foo() { print("X.P") }
+}
+
+struct Y<T> {
+  var wrapped: T
+}
+
+extension Y: P where T: P {
+  func foo() { wrapped.foo() }
+}
+
+func tryAsP(_ value: Any) {
+  if let p = value as? P {
+    p.foo()
+  }
+}
+
+extension Dictionary: P where Value == (Key) -> Bool {
+  func foo() { }
+}
+
+
+let yx = Y(wrapped: X())
+
+// CHECK_WARNINGS: warning: Swift runtime does not yet support dynamically querying conditional conformance ('a.Y<a.X>': 'a.P')
+tryAsP(yx)
diff --git a/test/Interpreter/functions.swift b/test/Interpreter/functions.swift
index 891948b..9238a20 100644
--- a/test/Interpreter/functions.swift
+++ b/test/Interpreter/functions.swift
@@ -42,3 +42,13 @@
 foo(D())
 // CHECK: Right
 bar(D())
+
+protocol Number {}
+extension Int: Number {}
+
+func foo() -> (String, String, String, Number, Number) {
+    return ("1", "2", "3", 42, 7)
+}
+
+// CHECK: ("1", "2", "3", 42, 7)
+print(foo())
diff --git a/test/Migrator/Inputs/API-function-hoist.json b/test/Migrator/Inputs/API-function-hoist.json
index c865962..574f46a 100644
--- a/test/Migrator/Inputs/API-function-hoist.json
+++ b/test/Migrator/Inputs/API-function-hoist.json
@@ -1,7 +1,7 @@
 [
   {
     "DiffItemKind": "TypeMemberDiffItem",
-    "Usr": "s:6Cities16setCityProperty1yA2AC_SitF",
+    "Usr": "s:6Cities16setCityProperty1yyA2AC_SitF",
     "OldPrintedName": "setCityProperty1(_:_:)",
     "NewPrintedName": "setProperty(Prop:)",
     "NewTypeName": "Cities",
@@ -16,7 +16,7 @@
   },
   {
     "DiffItemKind": "TypeMemberDiffItem",
-    "Usr": "s:6Cities16setCityProperty2yA2AC_S2itF",
+    "Usr": "s:6Cities16setCityProperty2yyA2AC_S2itF",
     "OldPrintedName": "setCityProperty2(_:_:_:)",
     "NewPrintedName": "setProperty2(with:using:)",
     "NewTypeName": "Cities",
@@ -24,7 +24,7 @@
   },
   {
     "DiffItemKind": "TypeMemberDiffItem",
-    "Usr": "s:6Cities15globalCityFunc2yA2ACF",
+    "Usr": "s:6Cities15globalCityFunc2yyA2ACF",
     "OldPrintedName": "globalCityFunc2(_:)",
     "NewPrintedName": "Property2",
     "NewTypeName": "Cities",
@@ -32,7 +32,7 @@
   },
   {
     "DiffItemKind": "TypeMemberDiffItem",
-    "Usr": "s:6Cities15globalCityFunc3SiA2AC_SitF",
+    "Usr": "s:6Cities15globalCityFunc3ySiA2AC_SitF",
     "OldPrintedName": "globalCityFunc3(_:_:)",
     "NewPrintedName": "memberFunc3()",
     "NewTypeName": "Cities",
@@ -41,7 +41,7 @@
   },
   {
     "DiffItemKind": "TypeMemberDiffItem",
-    "Usr": "s:6Cities15globalCityFunc4SiA2AC_S2itF",
+    "Usr": "s:6Cities15globalCityFunc4ySiA2AC_S2itF",
     "OldPrintedName": "globalCityFunc4(_:_:_:)",
     "NewPrintedName": "memberFunc4(remaining:)",
     "NewTypeName": "Cities",
@@ -57,7 +57,7 @@
   },
   {
     "DiffItemKind": "TypeMemberDiffItem",
-    "Usr": "s:6Cities22globalCityPointerTakerSiSPyA2ACG_S2itF",
+    "Usr": "s:6Cities22globalCityPointerTakerySiSPyA2ACG_S2itF",
     "OldPrintedName": "globalCityPointerTaker(_:_:_:)",
     "NewPrintedName": "takePointer(Pointer1:Pointer2:)",
     "NewTypeName": "Cities",
diff --git a/test/Migrator/Inputs/API.json b/test/Migrator/Inputs/API.json
index 822b318..954d6c5 100644
--- a/test/Migrator/Inputs/API.json
+++ b/test/Migrator/Inputs/API.json
@@ -143,7 +143,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "UnwrapOptional",
     "ChildIndex": "2",
-    "LeftUsr": "s:6CitiesAAC10mooloolabayAB1x_ABSg1ytF",
+    "LeftUsr": "s:6CitiesAAC10mooloolaba1x1yyAB_ABSgtF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -154,7 +154,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "WrapOptional",
     "ChildIndex": "1",
-    "LeftUsr": "s:6CitiesAAC10mooloolabayAB1x_ABSg1ytF",
+    "LeftUsr": "s:6CitiesAAC10mooloolaba1x1yyAB_ABSgtF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -165,7 +165,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "WrapOptional",
     "ChildIndex": "1:0",
-    "LeftUsr": "s:6CitiesAAC9toowoombaySayABG1x_ADSg1ytF",
+    "LeftUsr": "s:6CitiesAAC9toowoomba1x1yySayABG_AFSgtF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -176,7 +176,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "UnwrapOptional",
     "ChildIndex": "2",
-    "LeftUsr": "s:6CitiesAAC9toowoombaySayABG1x_ADSg1ytF",
+    "LeftUsr": "s:6CitiesAAC9toowoomba1x1yySayABG_AFSgtF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -187,7 +187,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "WrapOptional",
     "ChildIndex": "2:0:0",
-    "LeftUsr": "s:6CitiesAAC9toowoombaySayABG1x_ADSg1ytF",
+    "LeftUsr": "s:6CitiesAAC9toowoomba1x1yySayABG_AFSgtF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -198,7 +198,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "UnwrapOptional",
     "ChildIndex": "1:1",
-    "LeftUsr": "s:6CitiesAAC7mareebays10DictionaryVySSABSgG1x_AEySSABGSg1ytF",
+    "LeftUsr": "s:6CitiesAAC7mareeba1x1yys10DictionaryVySSABSgG_AGySSABGSgtF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -209,7 +209,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "WrapOptional",
     "ChildIndex": "1:0",
-    "LeftUsr": "s:6CitiesAAC7mareebays10DictionaryVySSABSgG1x_AEySSABGSg1ytF",
+    "LeftUsr": "s:6CitiesAAC7mareeba1x1yys10DictionaryVySSABSgG_AGySSABGSgtF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -220,7 +220,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "UnwrapOptional",
     "ChildIndex": "2",
-    "LeftUsr": "s:6CitiesAAC7mareebays10DictionaryVySSABSgG1x_AEySSABGSg1ytF",
+    "LeftUsr": "s:6CitiesAAC7mareeba1x1yys10DictionaryVySSABSgG_AGySSABGSgtF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -231,7 +231,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "TypeRewritten",
     "ChildIndex": "2:0:0",
-    "LeftUsr": "s:6CitiesAAC7mareebays10DictionaryVySSABSgG1x_AEySSABGSg1ytF",
+    "LeftUsr": "s:6CitiesAAC7mareeba1x1yys10DictionaryVySSABSgG_AGySSABGSgtF",
     "LeftComment": "String",
     "RightUsr": "",
     "RightComment": "Int",
@@ -242,7 +242,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "ImplicitOptionalToOptional",
     "ChildIndex": "1",
-    "LeftUsr": "s:6CitiesAAC7yandinaySQySays10DictionaryVySSABGGG1x_tF",
+    "LeftUsr": "s:6CitiesAAC7yandina1xySQySays10DictionaryVySSABGGG_tF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -253,7 +253,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "TypeRewritten",
     "ChildIndex": "1:0:0:0",
-    "LeftUsr": "s:6CitiesAAC7yandinaySQySays10DictionaryVySSABGGG1x_tF",
+    "LeftUsr": "s:6CitiesAAC7yandina1xySQySays10DictionaryVySSABGGG_tF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "Int",
@@ -297,7 +297,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "TypeRewritten",
     "ChildIndex": "1:1:1:0:0",
-    "LeftUsr": "s:6Cities05ExtraA0P6coolumys10DictionaryVySSAFySiSaySSSgGGG1x_tF",
+    "LeftUsr": "s:6Cities05ExtraA0P6coolum1xys10DictionaryVySSAGySiSaySSSgGGG_tF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "[String]",
@@ -308,7 +308,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "UnwrapOptional",
     "ChildIndex": "1:1:1:0",
-    "LeftUsr": "s:6Cities05ExtraA0P6coolumys10DictionaryVySSAFySiSaySSSgGGG1x_tF",
+    "LeftUsr": "s:6Cities05ExtraA0P6coolum1xys10DictionaryVySSAGySiSaySSSgGGG_tF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -319,7 +319,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "WrapOptional",
     "ChildIndex": "1",
-    "LeftUsr": "s:6Cities05ExtraA0P6blibliySQySSGSSSg_SStc1x_tF",
+    "LeftUsr": "s:6Cities05ExtraA0P6blibli1xySQySSGSSSg_SStc_tF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -330,7 +330,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "WrapOptional",
     "ChildIndex": "1",
-    "LeftUsr": "s:6Cities05ExtraA0P6blibliySQySSGSSSg_SStc1x_tF",
+    "LeftUsr": "s:6Cities05ExtraA0P6blibli1xySQySSGSSSg_SStc_tF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -341,7 +341,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "WrapOptional",
     "ChildIndex": "1",
-    "LeftUsr": "s:6Cities05ExtraA0P6blibliySQySSGSSSg_SStc1x_tF",
+    "LeftUsr": "s:6Cities05ExtraA0P6blibli1xySQySSGSSSg_SStc_tF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -352,7 +352,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "ImplicitOptionalToOptional",
     "ChildIndex": "1:0",
-    "LeftUsr": "s:6Cities05ExtraA0P6blibliySQySSGSSSg_SStc1x_tF",
+    "LeftUsr": "s:6Cities05ExtraA0P6blibli1xySQySSGSSSg_SStc_tF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -363,7 +363,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "UnwrapOptional",
     "ChildIndex": "1:1:0",
-    "LeftUsr": "s:6Cities05ExtraA0P6blibliySQySSGSSSg_SStc1x_tF",
+    "LeftUsr": "s:6Cities05ExtraA0P6blibli1xySQySSGSSSg_SStc_tF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -374,7 +374,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "ImplicitOptionalToOptional",
     "ChildIndex": "1",
-    "LeftUsr": "s:6Cities05ExtraA0P10currimundiySQySi_Si_SittG1x_tF",
+    "LeftUsr": "s:6Cities05ExtraA0P10currimundi1xySQySi_Si_SittG_tF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -385,7 +385,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "WrapOptional",
     "ChildIndex": "1:0:1:0",
-    "LeftUsr": "s:6Cities05ExtraA0P10currimundiySQySi_Si_SittG1x_tF",
+    "LeftUsr": "s:6Cities05ExtraA0P10currimundi1xySQySi_Si_SittG_tF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -396,7 +396,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "WrapOptional",
     "ChildIndex": "1",
-    "LeftUsr": "s:6CitiesAACABSi1x_tcfc",
+    "LeftUsr": "s:6CitiesAAC1xABSi_tcfc",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -407,7 +407,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "WrapOptional",
     "ChildIndex": "0",
-    "LeftUsr": "s:6CitiesAACABSi1x_tcfc",
+    "LeftUsr": "s:6CitiesAAC1xABSi_tcfc",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -418,7 +418,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "ImplicitOptionalToOptional",
     "ChildIndex": "0",
-    "LeftUsr": "s:6CitiesAACSQyABGSi1y_tcfc",
+    "LeftUsr": "s:6CitiesAAC1ySQyABGSi_tcfc",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -429,7 +429,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "Rename",
     "ChildIndex": "0",
-    "LeftUsr": "s:6CitiesAAC10mooloolabayAB1x_ABSg1ytF",
+    "LeftUsr": "s:6CitiesAAC10mooloolaba1x1yyAB_ABSgtF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "newMooloolaba(newX:newY:)",
@@ -440,7 +440,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "Rename",
     "ChildIndex": "0",
-    "LeftUsr": "s:6Cities04MoreA0P14setZooLocationySi1x_Si1ySi1ztF",
+    "LeftUsr": "s:6Cities04MoreA0P14setZooLocation1x1y1zySi_S2itF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "setZooLocationNew(newX:newY:newZ:)",
@@ -451,7 +451,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "Rename",
     "ChildIndex": "0",
-    "LeftUsr": "s:6Cities04MoreA0P8addZooAtySi_Si1ySi1ztF",
+    "LeftUsr": "s:6Cities04MoreA0P8addZooAt_1y1zySi_S2itF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "addNewZooAt(_:newY:newZ:)",
@@ -462,7 +462,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "TypeRewritten",
     "ChildIndex": "1:0",
-    "LeftUsr": "s:6CitiesAAC8maroochyySiSg1x_AD1ytF",
+    "LeftUsr": "s:6CitiesAAC8maroochy1x1yySiSg_AFtF",
     "LeftComment": "Int",
     "RightUsr": "",
     "RightComment": "(Int) -> Int",
@@ -473,7 +473,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "TypeRewritten",
     "ChildIndex": "2:0",
-    "LeftUsr": "s:6CitiesAAC8maroochyySiSg1x_AD1ytF",
+    "LeftUsr": "s:6CitiesAAC8maroochy1x1yySiSg_AFtF",
     "LeftComment": "Int",
     "RightUsr": "",
     "RightComment": "(Int) -> Int",
diff --git a/test/Migrator/Inputs/SpecialCaseAPI.json b/test/Migrator/Inputs/SpecialCaseAPI.json
index 5899beb..26c4a98 100644
--- a/test/Migrator/Inputs/SpecialCaseAPI.json
+++ b/test/Migrator/Inputs/SpecialCaseAPI.json
@@ -1,17 +1,17 @@
 [
   {
     "DiffItemKind": "SpecialCaseDiffItem",
-    "Usr": "s:8MyAppKit17NSOpenGLSetOptionyAA0D8GLOptionC_SitF",
+    "Usr": "s:8MyAppKit17NSOpenGLSetOptionyyAA0D8GLOptionC_SitF",
     "SpecialCaseId": "NSOpenGLSetOption"
   },
   {
     "DiffItemKind": "SpecialCaseDiffItem",
-    "Usr": "s:8MyAppKit17NSOpenGLGetOptionyAA0D8GLOptionC_SPySiGtF",
+    "Usr": "s:8MyAppKit17NSOpenGLGetOptionyyAA0D8GLOptionC_SPySiGtF",
     "SpecialCaseId": "NSOpenGLGetOption"
   },
   {
     "DiffItemKind": "SpecialCaseDiffItem",
-    "Usr": "s:7MySwift0A6DoubleV3absS2dFZ",
+    "Usr": "s:7MySwift0A6DoubleV3absyS2dFZ",
     "SpecialCaseId": "StaticAbsToSwiftAbs"
   }
 ]
diff --git a/test/Misc/misc_diagnostics.swift b/test/Misc/misc_diagnostics.swift
index b11f4d3..6d6880d 100644
--- a/test/Misc/misc_diagnostics.swift
+++ b/test/Misc/misc_diagnostics.swift
@@ -26,7 +26,7 @@
 if 1 {} // expected-error {{'Int' is not convertible to 'Bool'}}
 
 var a: [String] = [1] // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}}
-var b: Int = [1, 2, 3] // expected-error{{contextual type 'Int' cannot be used with array literal}}
+var b: Int = [1, 2, 3] // expected-error{{cannot convert value of type '[Int]' to specified type 'Int'}}
 
 var f1: Float = 2.0
 var f2: Float = 3.0
diff --git a/test/Misc/stats_dir_failure_count.swift b/test/Misc/stats_dir_failure_count.swift
index 4c89f74..a7ba9dc 100644
--- a/test/Misc/stats_dir_failure_count.swift
+++ b/test/Misc/stats_dir_failure_count.swift
@@ -1,4 +1,3 @@
-// REQUIRES: rdar35537905
 // Check that a failed process-tree emits nonzero failure counters
 // RUN: rm -rf %t && mkdir -p %t
 // RUN: echo zzz >%t/other.swift
@@ -8,14 +7,14 @@
 // FAILURE: {{"Driver.NumProcessFailures"	1$}}
 // FAILURE: {{"Frontend.NumProcessFailures"	2$}}
 
-// Check that a successful process-tree emits no failure counters
+// Check that a successful process-tree emits no nonzero failure counters
 // RUN: rm -rf %t && mkdir -p %t
 // RUN: echo 'let x : Int = 1' >%t/other.swift
 // RUN: %target-swiftc_driver -j 2 -typecheck -stats-output-dir %t %s %t/other.swift
 // RUN: %utils/process-stats-dir.py --set-csv-baseline %t/stats.csv %t
 // RUN: %FileCheck -input-file %t/stats.csv -check-prefix=SUCCESS %s
-// SUCCESS-NOT: {{"Driver.NumProcessFailures"}}
-// SUCCESS-NOT: {{"Frontend.NumProcessFailures"}}
+// SUCCESS-NOT: {{"Driver.NumProcessFailures"	[1-9]+}}
+// SUCCESS-NOT: {{"Frontend.NumProcessFailures"	[1-9]+}}
 
 func foo() {
 #if BROKEN
diff --git a/test/NameBinding/Inputs/NamedLazyMembers/NamedLazyMembers.h b/test/NameBinding/Inputs/NamedLazyMembers/NamedLazyMembers.h
index 69e119a..fded3c2 100644
--- a/test/NameBinding/Inputs/NamedLazyMembers/NamedLazyMembers.h
+++ b/test/NameBinding/Inputs/NamedLazyMembers/NamedLazyMembers.h
@@ -97,3 +97,9 @@
 
 @interface DerivedFromMirroringDoer : MirroringDoer
 @end
+
+@interface SimilarlyNamedThings
+- (void)doSomething:(double)x;
+- (void)doSomething:(double)x celsius:(double)y;
+- (void)doSomething:(double)x fahrenheit:(double)y using:(void (^)(void))block;
+@end
diff --git a/test/NameBinding/named_lazy_member_loading_anyobject.swift b/test/NameBinding/named_lazy_member_loading_anyobject.swift
new file mode 100644
index 0000000..dd43ee4
--- /dev/null
+++ b/test/NameBinding/named_lazy_member_loading_anyobject.swift
@@ -0,0 +1,15 @@
+// REQUIRES: objc_interop
+// REQUIRES: OS=macosx
+//
+// RUN: %target-swift-frontend -typecheck -I %S/Inputs/NamedLazyMembers %s -verify
+
+import NamedLazyMembers
+
+func callViaAnyObject(ao: AnyObject, d: Double) {
+  ao.doSomething(d, celsius: d)
+}
+
+func callDirect(snt: SimilarlyNamedThings, d: Double) {
+  snt.doSomething(d, fahrenheit: d) {
+  }
+}
diff --git a/test/NameBinding/named_lazy_member_loading_swift_struct.swift b/test/NameBinding/named_lazy_member_loading_swift_struct.swift
index d837a2f..8c8faad 100644
--- a/test/NameBinding/named_lazy_member_loading_swift_struct.swift
+++ b/test/NameBinding/named_lazy_member_loading_swift_struct.swift
@@ -6,9 +6,7 @@
 // Check that named-lazy-member-loading reduces the number of Decls deserialized
 // RUN: %target-swift-frontend -typecheck -I %t -disable-named-lazy-member-loading -typecheck -stats-output-dir %t/stats-pre %s
 // RUN: %target-swift-frontend -typecheck -I %t -stats-output-dir %t/stats-post %s
-// RUN: %utils/process-stats-dir.py --evaluate-delta 'NumDeclsDeserialized < -5' %t/stats-pre %t/stats-post
-
-// REQUIRES: rdar_35639403
+// RUN: %utils/process-stats-dir.py --evaluate-delta 'NumDeclsDeserialized < -4' %t/stats-pre %t/stats-post
 
 import NamedLazyMembers
 
diff --git a/test/NameBinding/reference-dependencies.swift b/test/NameBinding/reference-dependencies.swift
index 2fa1098..180303b 100644
--- a/test/NameBinding/reference-dependencies.swift
+++ b/test/NameBinding/reference-dependencies.swift
@@ -425,7 +425,7 @@
 // CHECK-DAG: - !private ["4main26OtherFileSecretTypeWrapperV0dE0V", "constant"]
 // CHECK-DAG: - !private ["4main25OtherFileProtoImplementorV", "deinit"]
 // CHECK-DAG: - !private ["4main26OtherFileProtoImplementor2V", "deinit"]
-// CHECK-DAG: - !private ["s13EmptyIteratorV", "init"]
+// CHECK-DAG: - !private ["s15EmptyCollectionV8IteratorV", "init"]
 // CHECK-DAG: - ["4main13OtherFileEnumO", "Value"]
 // CHECK-DAG: - !private ["4main20OtherFileEnumWrapperV", "Enum"]
 
@@ -451,7 +451,6 @@
 // CHECK: - "Sb"
 // CHECK: - "4main18ClassFromOtherFileC"
 // CHECK: - "s10ComparableP"
-// CHECK: - !private "s13EmptyIteratorV"
 // CHECK: - "s25ExpressibleByFloatLiteralP"
 // CHECK: - !private "s33ExpressibleByUnicodeScalarLiteralP"
 // CHECK: - !private "4main18OtherFileOuterTypeV05InnerE0V"
diff --git a/test/Parse/pointer_conversion.swift.gyb b/test/Parse/pointer_conversion.swift.gyb
index 0f17676..fdaa353 100644
--- a/test/Parse/pointer_conversion.swift.gyb
+++ b/test/Parse/pointer_conversion.swift.gyb
@@ -154,7 +154,7 @@
   takesConstPointer(ff) // expected-error{{cannot convert value of type '[Float]' to expected argument type 'UnsafePointer<Int>${suffix}'}}
   takesConstPointer([0, 1, 2])
   // <rdar://problem/22308330> QoI: CSDiags doesn't handle array -> pointer impl conversions well
-  takesConstPointer([0.0, 1.0, 2.0]) // expected-error{{cannot convert value of type 'Double' to expected element type 'Int'}}
+  takesConstPointer([0.0, 1.0, 2.0]) // expected-error{{cannot convert value of type '[Double]' to expected argument type 'UnsafePointer<Int>}}
 
   // We don't allow these conversions outside of function arguments.
   var x: UnsafePointer<Int> = &i // expected-error{{cannot pass immutable value as inout argument: 'i' is immutable}}
diff --git a/test/Parse/recovery.swift b/test/Parse/recovery.swift
index df24506..48c23d8 100644
--- a/test/Parse/recovery.swift
+++ b/test/Parse/recovery.swift
@@ -464,7 +464,7 @@
 
 struct ErrorInFunctionSignatureResultArrayType2 {
   func foo() -> Int[0 { // expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}}
-    return [0]  // expected-error {{contextual type 'Int' cannot be used with array literal}}
+    return [0]  // expected-error {{cannot convert return expression of type '[Int]' to return type 'Int'}}
   }
 }
 
diff --git a/test/Parse/subscripting.swift b/test/Parse/subscripting.swift
index 0351c5b..92c210e 100644
--- a/test/Parse/subscripting.swift
+++ b/test/Parse/subscripting.swift
@@ -1,6 +1,6 @@
 // RUN: %target-typecheck-verify-swift
 
-struct X { }
+struct X { } // expected-note {{did you mean}}
 
 // Simple examples
 struct X1 {
@@ -101,10 +101,10 @@
   subscript (i : Int) // expected-error{{expected '->' for subscript element type}}
      Int {
     get {
-      return stored
+      return stored // expected-error{{use of unresolved identifier}}
     }
     set {
-      stored = value
+      stored = newValue// expected-error{{use of unresolved identifier}}
     }
   }
 }
@@ -116,13 +116,14 @@
       return stored
     }
     set {
-      stored = value
+      stored = newValue // expected-error{{use of unresolved identifier}}
     }
   }
 }
 
 struct A3 {
   subscript(i : Int) // expected-error {{expected '->' for subscript element type}}
+                     // expected-error@-1 {{expected subscripting element type}}
   {
     get {
       return i
@@ -132,6 +133,7 @@
 
 struct A4 {
   subscript(i : Int) { // expected-error {{expected '->' for subscript element type}}
+                       // expected-error@-1 {{expected subscripting element type}}
     get {
       return i
     }
@@ -144,8 +146,10 @@
 
 struct A6 {
   subscript(i: Int)(j: Int) -> Int { // expected-error {{expected '->' for subscript element type}}
+                                     // expected-error@-1 {{function types cannot have argument labels}}
+                                     // expected-note@-2 {{did you mean}}
     get {
-      return i + j
+      return i + j // expected-error {{use of unresolved identifier}}
     }
   }
 }
diff --git a/validation-test/PrintAsObjC/Inputs/reintroduced-new.swift b/test/PrintAsObjC/Inputs/reintroduced-new.swift
similarity index 100%
rename from validation-test/PrintAsObjC/Inputs/reintroduced-new.swift
rename to test/PrintAsObjC/Inputs/reintroduced-new.swift
diff --git a/test/PrintAsObjC/availability.swift b/test/PrintAsObjC/availability.swift
index bf61fde..6c50df3 100644
--- a/test/PrintAsObjC/availability.swift
+++ b/test/PrintAsObjC/availability.swift
@@ -57,7 +57,7 @@
 
 // CHECK-LABEL: @interface AvailabilitySub
 // CHECK-NEXT: - (nonnull instancetype)init SWIFT_UNAVAILABLE;
-// CHECK-NEXT: + (nonnull instancetype)new SWIFT_UNAVAILABLE;
+// CHECK-NEXT: + (nonnull instancetype)new SWIFT_DEPRECATED_MSG("-init is unavailable");
 // CHECK-NEXT: - (nonnull instancetype)initWithX:(NSInteger)_ SWIFT_UNAVAILABLE;
 // CHECK-NEXT: @end
 
diff --git a/test/PrintAsObjC/classes.swift b/test/PrintAsObjC/classes.swift
index 663bd60..1b7acd4 100644
--- a/test/PrintAsObjC/classes.swift
+++ b/test/PrintAsObjC/classes.swift
@@ -178,7 +178,7 @@
 // CHECK-LABEL: @interface InheritedInitializersRequired
 // CHECK-NEXT: - (nonnull instancetype)initWithEvenMoreFun OBJC_DESIGNATED_INITIALIZER;
 // CHECK-NEXT: - (nonnull instancetype)init SWIFT_UNAVAILABLE;
-// CHECK-NEXT: + (nonnull instancetype)new SWIFT_UNAVAILABLE;
+// CHECK-NEXT: + (nonnull instancetype)new SWIFT_DEPRECATED_MSG("-init is unavailable");
 // CHECK-NEXT: @end
 @objc class InheritedInitializersRequired : InheritedInitializers {
   @objc required init(evenMoreFun: ()) { super.init() }
@@ -436,7 +436,7 @@
 // CHECK-LABEL: @interface NewBanned
 // CHECK-NEXT: - (nonnull instancetype)initWithArbitraryArgument:(NSInteger)arbitraryArgument OBJC_DESIGNATED_INITIALIZER;
 // CHECK-NEXT: - (nonnull instancetype)init SWIFT_UNAVAILABLE;
-// CHECK-NEXT: + (nonnull instancetype)new SWIFT_UNAVAILABLE;
+// CHECK-NEXT: + (nonnull instancetype)new SWIFT_DEPRECATED_MSG("-init is unavailable");
 // CHECK-NEXT: @end
 @objc class NewBanned : NSObject {
   init(arbitraryArgument: Int) { super.init() }
diff --git a/test/PrintAsObjC/protocols.swift b/test/PrintAsObjC/protocols.swift
index 60642f9..0542287 100644
--- a/test/PrintAsObjC/protocols.swift
+++ b/test/PrintAsObjC/protocols.swift
@@ -55,7 +55,7 @@
 // CHECK-LABEL: @interface MyObject : NSObject <NSCoding, Fungible>
 // CHECK-NEXT: initWithCoder
 // CHECK-NEXT: init SWIFT_UNAVAILABLE
-// CHECK-NEXT: new SWIFT_UNAVAILABLE
+// CHECK-NEXT: new SWIFT_DEPRECATED
 // CHECK-NEXT: @end
 // NEGATIVE-NOT: @protocol NSCoding
 class MyObject : NSObject, NSCoding, Fungible {
diff --git a/test/PrintAsObjC/reintroduced-new.m b/test/PrintAsObjC/reintroduced-new.m
new file mode 100644
index 0000000..d6a0342
--- /dev/null
+++ b/test/PrintAsObjC/reintroduced-new.m
@@ -0,0 +1,31 @@
+// REQUIRES: objc_interop
+
+// RUN: %empty-directory(%t)
+
+// FIXME: BEGIN -enable-source-import hackaround
+// RUN:  %target-swift-frontend(mock-sdk: -sdk %S/../../test/Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../../test/Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift
+// FIXME: END -enable-source-import hackaround
+
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../../test/Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/Inputs/reintroduced-new.swift -swift-version 4 -disable-objc-attr-requires-foundation-module -module-name main
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../../test/Inputs/clang-importer-sdk -I %t) -parse-as-library %t/main.swiftmodule -typecheck -emit-objc-header-path %t/generated.h -disable-objc-attr-requires-foundation-module -swift-version 4
+// RUN: not %clang -fsyntax-only -x objective-c %s -include %t/generated.h -fobjc-arc -fmodules -Werror -isysroot %S/../../test/Inputs/clang-importer-sdk 2>&1 | %FileCheck -check-prefix=CHECK -check-prefix=CHECK-4 %s
+
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../../test/Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/Inputs/reintroduced-new.swift -disable-objc-attr-requires-foundation-module -module-name main -swift-version 5
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../../test/Inputs/clang-importer-sdk -I %t) -parse-as-library %t/main.swiftmodule -typecheck -emit-objc-header-path %t/generated.h -disable-objc-attr-requires-foundation-module -swift-version 5
+// RUN: not %clang -fsyntax-only -x objective-c %s -include %t/generated.h -fobjc-arc -fmodules -Werror -isysroot %S/../../test/Inputs/clang-importer-sdk 2>&1 | %FileCheck  -check-prefix=CHECK -check-prefix=CHECK-5 %s
+
+// CHECK-NOT: error:
+
+void test() {
+  // CHECK: :[[@LINE+1]]:{{[0-9]+}}: error: 'init' is unavailable
+  (void)[[Base alloc] init];
+   // CHECK-NOT: error:
+  (void)[[Sub alloc] init];
+  // CHECK-4: :[[@LINE+2]]:{{[0-9]+}}: error: 'new' is deprecated: -init is unavailable
+  // CHECK-5: :[[@LINE+1]]:{{[0-9]+}}: error: 'new' is unavailable: -init is unavailable
+  (void)[Base new];
+   // CHECK-NOT: error:
+  (void)[Sub new];
+}
+
+// CHECK-NOT: error:
\ No newline at end of file
diff --git a/test/Prototypes/Algorithms.swift.gyb b/test/Prototypes/Algorithms.swift.gyb
index 4d5f099..7e4d9a7 100644
--- a/test/Prototypes/Algorithms.swift.gyb
+++ b/test/Prototypes/Algorithms.swift.gyb
@@ -11,7 +11,7 @@
 //===----------------------------------------------------------------------===//
 // RUN: %empty-directory(%t)
 // RUN: %gyb -DWORD_BITS=%target-ptrsize %s -o %t/out.swift
-// RUN: %line-directive %t/out.swift -- %target-build-swift -enable-experimental-conditional-conformances -parse-stdlib %t/out.swift -o %t/a.out -Onone -swift-version 4
+// RUN: %line-directive %t/out.swift -- %target-build-swift -parse-stdlib %t/out.swift -o %t/a.out -Onone -swift-version 4
 // RUN: %line-directive %t/out.swift -- %target-run %t/a.out
 
 // REQUIRES: executable_test
diff --git a/test/Prototypes/UnicodeDecoders.swift b/test/Prototypes/UnicodeDecoders.swift
index ee10bc1..748c44e 100644
--- a/test/Prototypes/UnicodeDecoders.swift
+++ b/test/Prototypes/UnicodeDecoders.swift
@@ -153,8 +153,7 @@
   public func index(before i: Index) -> Index {
     var parser = Encoding.ReverseParser()
     
-    var more = _ReverseIndexingIterator(
-      _elements: codeUnits, _position: i.codeUnitIndex)
+    var more = codeUnits[..<i.codeUnitIndex].reversed().makeIterator()
     
     switch parser.parseScalar(from: &more) {
     case .valid(let scalarContent):
diff --git a/test/SIL/Parser/generic_signature_with_depth.swift b/test/SIL/Parser/generic_signature_with_depth.swift
index 36d2901..0c5e26d 100644
--- a/test/SIL/Parser/generic_signature_with_depth.swift
+++ b/test/SIL/Parser/generic_signature_with_depth.swift
@@ -18,7 +18,7 @@
  > (_ seq: S)
 }
 
-// CHECK-LABEL:  @_T028generic_signature_with_depth4testxx_q_tAA5mmExtRzAaCR_9Generator_7ElementQY_AD_AERTzr0_lF : $@convention(thin) <EC1, EC2 where EC1 : mmExt, EC2 : mmExt, EC1.Generator.Element == EC2.Generator.Element> (@in EC1, @in EC2) -> @out EC1 {
+// CHECK-LABEL:  @_T028generic_signature_with_depth4testyxx_q_tAA5mmExtRzAaCR_9Generator_7ElementQY_AD_AERTzr0_lF : $@convention(thin) <EC1, EC2 where EC1 : mmExt, EC2 : mmExt, EC1.Generator.Element == EC2.Generator.Element> (@in EC1, @in EC2) -> @out EC1 {
 // CHECK: witness_method $EC1, #mmExt.extend!1 : {{.*}} : $@convention(witness_method: mmExt) <τ_0_0 where τ_0_0 : mmExt><τ_1_0 where τ_1_0 : mmSequenceType, τ_0_0.Generator.Element == τ_1_0.Generator.Element> (@in τ_1_0, @inout τ_0_0) -> ()
 // CHECK: apply {{%[0-9]+}}<EC1, EC2>({{%[0-9]+}}, {{%[0-9]+}}) : $@convention(witness_method: mmExt) <τ_0_0 where τ_0_0 : mmExt><τ_1_0 where τ_1_0 : mmSequenceType, τ_0_0.Generator.Element == τ_1_0.Generator.Element> (@in τ_1_0, @inout τ_0_0) -> ()
 
diff --git a/test/SIL/Parser/witness_tables.sil b/test/SIL/Parser/witness_tables.sil
index 27b62a5..c9b0ac0 100644
--- a/test/SIL/Parser/witness_tables.sil
+++ b/test/SIL/Parser/witness_tables.sil
@@ -1,4 +1,4 @@
-// RUN: %target-sil-opt -enable-experimental-conditional-conformances -assume-parsing-unqualified-ownership-sil %s -module-name=witness_tables | %target-sil-opt -enable-experimental-conditional-conformances -assume-parsing-unqualified-ownership-sil -module-name=witness_tables | %FileCheck %s
+// RUN: %target-sil-opt -assume-parsing-unqualified-ownership-sil %s -module-name=witness_tables | %target-sil-opt -assume-parsing-unqualified-ownership-sil -module-name=witness_tables | %FileCheck %s
 
 protocol AssocReqt {
   func requiredMethod()
diff --git a/test/SIL/Serialization/deserialize_generic.sil b/test/SIL/Serialization/deserialize_generic.sil
index 0951d98..4c306fc 100644
--- a/test/SIL/Serialization/deserialize_generic.sil
+++ b/test/SIL/Serialization/deserialize_generic.sil
@@ -12,14 +12,14 @@
 import Swift
 
 // CHECK-LABEL: sil @top_level_code
-// CHECK: function_ref @_T011def_generic1AC23convertFromArrayLiteralACyxGxd_tF
+// CHECK: function_ref @_T011def_generic1AC23convertFromArrayLiteralyACyxGxd_tF
 sil @top_level_code : $@convention(thin) () -> () {
 bb0:
-  %3 = function_ref @_T011def_generic1AC23convertFromArrayLiteralACyxGxd_tF : $@convention(method) <T> (@owned Array<T>, @guaranteed A<T>) -> @owned A<T>
+  %3 = function_ref @_T011def_generic1AC23convertFromArrayLiteralyACyxGxd_tF : $@convention(method) <T> (@owned Array<T>, @guaranteed A<T>) -> @owned A<T>
   %0 = tuple ()                                   // user: %1
   return %0 : $()                                 // id: %1
 }
 
 // Make sure the function body is deserialized.
-// CHECK-LABEL: @_T011def_generic1AC23convertFromArrayLiteralACyxGxd_tF : $@convention(method) <T> (@owned Array<T>, @guaranteed A<T>) -> @owned A<T> {
-sil @_T011def_generic1AC23convertFromArrayLiteralACyxGxd_tF : $@convention(method) <T> (@owned Array<T>, @guaranteed A<T>) -> @owned A<T>
+// CHECK-LABEL: @_T011def_generic1AC23convertFromArrayLiteralyACyxGxd_tF : $@convention(method) <T> (@owned Array<T>, @guaranteed A<T>) -> @owned A<T> {
+sil @_T011def_generic1AC23convertFromArrayLiteralyACyxGxd_tF : $@convention(method) <T> (@owned Array<T>, @guaranteed A<T>) -> @owned A<T>
diff --git a/test/SIL/Serialization/deserialize_generic_marker.sil b/test/SIL/Serialization/deserialize_generic_marker.sil
index 65bf8a2..373f4e2 100644
--- a/test/SIL/Serialization/deserialize_generic_marker.sil
+++ b/test/SIL/Serialization/deserialize_generic_marker.sil
@@ -10,14 +10,14 @@
 import Swift
 
 // CHECK-LABEL: sil @top_level_code
-// CHECK: function_ref @_T018def_generic_marker4testxx_q_tAA16mmCollectionTypeRzAaCR_9Generator_7ElementQY_AD_AERTzr0_lF : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : mmCollectionType, τ_0_1 : mmCollectionType, τ_0_0.Generator.Element == τ_0_1.Generator.Element> (@in τ_0_0, @in τ_0_1) -> @out τ_0_0
+// CHECK: function_ref @_T018def_generic_marker4testyxx_q_tAA16mmCollectionTypeRzAaCR_9Generator_7ElementQY_AD_AERTzr0_lF : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : mmCollectionType, τ_0_1 : mmCollectionType, τ_0_0.Generator.Element == τ_0_1.Generator.Element> (@in τ_0_0, @in τ_0_1) -> @out τ_0_0
 sil @top_level_code : $@convention(thin) () -> () {
 bb0:
-  %43 = function_ref @_T018def_generic_marker4testxx_q_tAA16mmCollectionTypeRzAaCR_9Generator_7ElementQY_AD_AERTzr0_lF : $@convention(thin) <EC1, EC2 where EC1 : mmCollectionType, EC2 : mmCollectionType, EC1.Generator.Element == EC2.Generator.Element> (@in EC1, @in EC2) -> @out EC1
+  %43 = function_ref @_T018def_generic_marker4testyxx_q_tAA16mmCollectionTypeRzAaCR_9Generator_7ElementQY_AD_AERTzr0_lF : $@convention(thin) <EC1, EC2 where EC1 : mmCollectionType, EC2 : mmCollectionType, EC1.Generator.Element == EC2.Generator.Element> (@in EC1, @in EC2) -> @out EC1
   %0 = tuple ()
   return %0 : $()
 }
 
 // Make sure the function body is deserialized.
-// CHECK-LABEL: @_T018def_generic_marker4testxx_q_tAA16mmCollectionTypeRzAaCR_9Generator_7ElementQY_AD_AERTzr0_lF : $@convention(thin) <EC1, EC2 where EC1 : mmCollectionType, EC2 : mmCollectionType, EC1.Generator.Element == EC2.Generator.Element> (@in EC1, @in EC2) -> @out EC1 {
-sil @_T018def_generic_marker4testxx_q_tAA16mmCollectionTypeRzAaCR_9Generator_7ElementQY_AD_AERTzr0_lF : $@convention(thin) <EC1, EC2 where EC1 : mmCollectionType, EC2 : mmCollectionType, EC1.Generator.Element == EC2.Generator.Element> (@in EC1, @in EC2) -> @out EC1
+// CHECK-LABEL: @_T018def_generic_marker4testyxx_q_tAA16mmCollectionTypeRzAaCR_9Generator_7ElementQY_AD_AERTzr0_lF : $@convention(thin) <EC1, EC2 where EC1 : mmCollectionType, EC2 : mmCollectionType, EC1.Generator.Element == EC2.Generator.Element> (@in EC1, @in EC2) -> @out EC1 {
+sil @_T018def_generic_marker4testyxx_q_tAA16mmCollectionTypeRzAaCR_9Generator_7ElementQY_AD_AERTzr0_lF : $@convention(thin) <EC1, EC2 where EC1 : mmCollectionType, EC2 : mmCollectionType, EC1.Generator.Element == EC2.Generator.Element> (@in EC1, @in EC2) -> @out EC1
diff --git a/test/SIL/Serialization/shared_function_serialization.sil b/test/SIL/Serialization/shared_function_serialization.sil
index 30d5c5a..0cfa7a1 100644
--- a/test/SIL/Serialization/shared_function_serialization.sil
+++ b/test/SIL/Serialization/shared_function_serialization.sil
@@ -4,8 +4,8 @@
 
 // CHECK: sil private @top_level_code
 // CHECK: sil public_external [serialized] @_T0s1XVABycfC{{.*}}
-// CHECK: sil public_external [serialized] @_T0s17the_thing_it_doesys1XV1x_tF{{.*}}
-// CHECK: sil shared_external [serializable] [noinline] @_T0s9the_thingyx1t_tlFs1XV_Tgq5{{.*}}
+// CHECK: sil public_external [serialized] @_T0s17the_thing_it_does1xys1XV_tF{{.*}}
+// CHECK: sil shared_external [serializable] [noinline] @_T0s9the_thing1tyx_tlFs1XV_Tgq5{{.*}}
 
 sil_stage canonical
 
@@ -24,7 +24,7 @@
   %3 = apply %1(%2) : $@convention(method) (@thin X.Type) -> X  // user: %4
   store %3 to %0 : $*X                            // id: %4
   // function_ref Swift.the_thing_it_does (x : Swift.X) -> ()
-  %5 = function_ref @_T0s17the_thing_it_doesys1XV1x_tF : $@convention(thin) (X) -> () // user: %7
+  %5 = function_ref @_T0s17the_thing_it_does1xys1XV_tF : $@convention(thin) (X) -> () // user: %7
   %6 = load %0 : $*X                              // user: %7
   %7 = apply %5(%6) : $@convention(thin) (X) -> ()
   %8 = tuple ()                                   // user: %9
@@ -35,6 +35,6 @@
 sil @_T0s1XVABycfC : $@convention(method) (@thin X.Type) -> X
 
 // Swift.the_thing_it_does (x : Swift.X) -> ()
-sil @_T0s17the_thing_it_doesys1XV1x_tF : $@convention(thin) (X) -> ()
+sil @_T0s17the_thing_it_does1xys1XV_tF : $@convention(thin) (X) -> ()
 
 
diff --git a/test/SIL/whole_module_optimization.swift b/test/SIL/whole_module_optimization.swift
index 16d24cb..7949f15 100644
--- a/test/SIL/whole_module_optimization.swift
+++ b/test/SIL/whole_module_optimization.swift
@@ -23,7 +23,7 @@
   // CHECK-SINGLE-FILE: %0 = function_ref @_T04main9privateFn33_4704C82F83811927370AA02DFDC75B5ALLs5Int32VyF
   // CHECK-SINGLE-FILE: %1 = thin_to_thick_function %0
   // CHECK-SINGLE-FILE: %2 = convert_function %1
-  // CHECK-SINGLE-FILE: %3 = function_ref @_T04main7computes5Int32VADycF
+  // CHECK-SINGLE-FILE: %3 = function_ref @_T04main7computeys5Int32VADycF
   // CHECK-SINGLE-FILE: %4 = apply %3(%2)
   // CHECK-SINGLE-FILE: return %4 : $Int
 
diff --git a/test/SILGen/SILDeclRef.swift b/test/SILGen/SILDeclRef.swift
index ae03280..cd9471f 100644
--- a/test/SILGen/SILDeclRef.swift
+++ b/test/SILGen/SILDeclRef.swift
@@ -38,7 +38,7 @@
   override public func foo(f: Float) -> Int32 { return 7 }
 }
 
-// CHECK-LABEL: sil @_T010SILDeclRef5testPs5Int32VAA1P_p1p_tF
+// CHECK-LABEL: sil @_T010SILDeclRef5testP1ps5Int32VAA1P_p_tF
 // Check that witness_method contains SILDeclRefs with a signature.
 // CHECK: witness_method $@opened({{.*}}) P, #P.foo!1 : <Self where Self : P> (Self) -> () -> Int32, %{{.*}} : $*@opened({{.*}}) P : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> Int32
 public func testP(p: P) -> Int32 {
@@ -46,7 +46,7 @@
 }
 
 // Check that class_method contains SILDeclRefs with a signature.
-// CHECK-LABEL:sil @_T010SILDeclRef8testBases5Int32VAA0D0C1b_tF
+// CHECK-LABEL:sil @_T010SILDeclRef8testBase1bs5Int32VAA0D0C_tF
 // CHECK: class_method %{{.*}} : $Base, #Base.foo!1 : (Base) -> (Float) -> Int32, $@convention(method) (Float, @guaranteed Base) -> Int32
 public func testBase(b: Base) -> Int32 {
   return b.foo(f: 10)
@@ -56,15 +56,15 @@
 
 // CHECK: sil_vtable [serialized] Base {
 // CHECK-NEXT:  #Base.foo!1: (Base) -> () -> Int32 : _T010SILDeclRef4BaseC3foos5Int32VyF	// Base.foo()
-// CHECK-NEXT:  #Base.foo!1: (Base) -> (Int32) -> () : _T010SILDeclRef4BaseC3fooys5Int32V1n_tF	// Base.foo(n:)
-// CHECK-NEXT:  #Base.foo!1: (Base) -> (Float) -> Int32 : _T010SILDeclRef4BaseC3foos5Int32VSf1f_tF	// Base.foo(f:)
+// CHECK-NEXT:  #Base.foo!1: (Base) -> (Int32) -> () : _T010SILDeclRef4BaseC3foo1nys5Int32V_tF	// Base.foo(n:)
+// CHECK-NEXT:  #Base.foo!1: (Base) -> (Float) -> Int32 : _T010SILDeclRef4BaseC3foo1fs5Int32VSf_tF	// Base.foo(f:)
 // CHECK-NEXT:  #Base.init!initializer.1: (Base.Type) -> () -> Base : _T010SILDeclRef4BaseCACycfc	// Base.init()
 // CHECK-NEXT:  #Base.deinit!deallocator: _T010SILDeclRef4BaseCfD	// Base.__deallocating_deinit
 // CHECK-NEXT: }
 
 // CHECK:sil_witness_table [serialized] Base: P module SILDeclRef {
 // CHECK-NEXT: method #P.foo!1: <Self where Self : P> (Self) -> () -> Int32 : @_T010SILDeclRef4BaseCAA1PA2aDP3foos5Int32VyFTW	// protocol witness for P.foo()
-// CHECK-NEXT: method #P.foo!1: <Self where Self : P> (Self) -> (Int32) -> () : @_T010SILDeclRef4BaseCAA1PA2aDP3fooys5Int32V1n_tFTW	// protocol witness for P.foo(n:) in conformance Base
+// CHECK-NEXT: method #P.foo!1: <Self where Self : P> (Self) -> (Int32) -> () : @_T010SILDeclRef4BaseCAA1PA2aDP3foo1nys5Int32V_tFTW	// protocol witness for P.foo(n:) in conformance Base
 // CHECK-NEXT: }
 
 
diff --git a/test/SILGen/access_marker_gen.swift b/test/SILGen/access_marker_gen.swift
index 03af5ba..ab93d03 100644
--- a/test/SILGen/access_marker_gen.swift
+++ b/test/SILGen/access_marker_gen.swift
@@ -7,7 +7,7 @@
   var o: AnyObject?
 }
 
-// CHECK-LABEL: sil hidden [noinline] @_T017access_marker_gen5initSAA1SVyXlSgF : $@convention(thin) (@owned Optional<AnyObject>) -> @owned S {
+// CHECK-LABEL: sil hidden [noinline] @_T017access_marker_gen5initSyAA1SVyXlSgF : $@convention(thin) (@owned Optional<AnyObject>) -> @owned S {
 // CHECK: bb0(%0 : @owned $Optional<AnyObject>):
 // CHECK: [[BOX:%.*]] = alloc_box ${ var S }, var, name "s"
 // CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [var] [[BOX]] : ${ var S }
@@ -26,7 +26,7 @@
 // CHECK: [[RET:%.*]] = load [copy] [[ACCESS3]] : $*S
 // CHECK: end_access [[ACCESS3]] : $*S
 // CHECK: return [[RET]] : $S
-// CHECK-LABEL: } // end sil function '_T017access_marker_gen5initSAA1SVyXlSgF'
+// CHECK-LABEL: } // end sil function '_T017access_marker_gen5initSyAA1SVyXlSgF'
 @inline(never)
 func initS(_ o: AnyObject?) -> S {
   var s: S
@@ -102,7 +102,7 @@
   let y = c.x
   c.x = y
 }
-// CHECK-LABEL: sil hidden @_T017access_marker_gen27testClassInstancePropertiesyAA1CC1c_tF :
+// CHECK-LABEL: sil hidden @_T017access_marker_gen27testClassInstanceProperties1cyAA1CC_tF :
 // CHECK:       [[C:%.*]] = begin_borrow %0 : $C
 // CHECK-NEXT:  [[CX:%.*]] = ref_element_addr [[C]] : $C, #C.x
 // CHECK-NEXT:  [[ACCESS:%.*]] = begin_access [read] [dynamic] [[CX]] : $*Int
@@ -129,7 +129,7 @@
 func testDispatchedClassInstanceProperty(d: D) {
   modify(&d.x)
 }
-// CHECK-LABEL: sil hidden @_T017access_marker_gen35testDispatchedClassInstancePropertyyAA1DC1d_tF
+// CHECK-LABEL: sil hidden @_T017access_marker_gen35testDispatchedClassInstanceProperty1dyAA1DC_tF
 // CHECK:       [[D:%.*]] = begin_borrow %0 : $D
 // CHECK:       [[METHOD:%.*]] = class_method [[D]] : $D, #D.x!materializeForSet.1
 // CHECK:       apply [[METHOD]]({{.*}}, [[D]])
diff --git a/test/SILGen/accessibility_vtables.swift b/test/SILGen/accessibility_vtables.swift
index ef64314..054af1a 100644
--- a/test/SILGen/accessibility_vtables.swift
+++ b/test/SILGen/accessibility_vtables.swift
@@ -14,7 +14,7 @@
 
 // CHECK-LABEL: sil hidden @_T021accessibility_vtables3SubCACycfc : $@convention(method) (@owned Sub) -> @owned Sub
 // CHECK:       bb0(%0 : $Sub):
-// CHECK:         function_ref @_T0s25_unimplementedInitializers5NeverOs12StaticStringV9className_AE04initG0AE4fileSu4lineSu6columntF
+// CHECK:         function_ref @_T0s25_unimplementedInitializer9className04initD04file4line6columns5NeverOs12StaticStringV_A2JS2utF
 
 // CHECK-LABEL: sil_vtable Sub {
 // CHECK-NEXT:  #Base.internalMethod!1: {{.*}} : _T028accessibility_vtables_helper4BaseC14internalMethodyyF [inherited]
diff --git a/test/SILGen/accessibility_warnings.swift b/test/SILGen/accessibility_warnings.swift
index f2584d7..58b1622 100644
--- a/test/SILGen/accessibility_warnings.swift
+++ b/test/SILGen/accessibility_warnings.swift
@@ -33,7 +33,7 @@
 
 
 extension PublicStruct {
-  // CHECK-DAG: sil @_T022accessibility_warnings12PublicStructVACSi1x_tcfC
+  // CHECK-DAG: sil @_T022accessibility_warnings12PublicStructV1xACSi_tcfC
   public init(x: Int) { self.init() }
 
   // CHECK-DAG: sil @_T022accessibility_warnings12PublicStructV18publicVarExtensionSivg
@@ -41,7 +41,7 @@
 }
 
 extension InternalStruct {
-  // CHECK-DAG: sil hidden @_T022accessibility_warnings14InternalStructVACSi1x_tcfC
+  // CHECK-DAG: sil hidden @_T022accessibility_warnings14InternalStructV1xACSi_tcfC
   public init(x: Int) { self.init() }
 
   // CHECK-DAG: sil hidden @_T022accessibility_warnings14InternalStructV18publicVarExtensionSivg
@@ -49,7 +49,7 @@
 }
 
 extension PrivateStruct {
-  // CHECK-DAG: sil private @_T022accessibility_warnings13PrivateStruct33_5D2F2E026754A901C0FF90C404896D02LLVADSi1x_tcfC
+  // CHECK-DAG: sil private @_T022accessibility_warnings13PrivateStruct33_5D2F2E026754A901C0FF90C404896D02LLV1xADSi_tcfC
   public init(x: Int) { self.init() }
 
   // CHECK-DAG: sil private @_T022accessibility_warnings13PrivateStruct33_5D2F2E026754A901C0FF90C404896D02LLV18publicVarExtensionSivg
@@ -104,8 +104,8 @@
 internal struct PrivateSettersForReadOnlyInternal : PublicReadOnlyOperations {
   // CHECK-DAG: sil hidden{{( \[.+\])*}} @_T022accessibility_warnings33PrivateSettersForReadOnlyInternalV4sizeSivg
   public private(set) var size = 0
-  // CHECK-DAG: sil hidden @_T022accessibility_warnings33PrivateSettersForReadOnlyInternalVS2icig
-  // CHECK-DAG: sil private @_T022accessibility_warnings33PrivateSettersForReadOnlyInternalVS2icis
+  // CHECK-DAG: sil hidden @_T022accessibility_warnings33PrivateSettersForReadOnlyInternalVyS2icig
+  // CHECK-DAG: sil private @_T022accessibility_warnings33PrivateSettersForReadOnlyInternalVyS2icis
   internal private(set) subscript (_: Int) -> Int { // no-warning
     get { return 42 }
     set {}
diff --git a/test/SILGen/accessors.swift b/test/SILGen/accessors.swift
index c81d367..d92021e 100644
--- a/test/SILGen/accessors.swift
+++ b/test/SILGen/accessors.swift
@@ -25,7 +25,7 @@
 func test0(_ ref: A) {
   ref.array[index0()] = ref.array[index1()]
 }
-// CHECK: sil hidden @_T09accessors5test0yAA1ACF : $@convention(thin) (@owned A) -> () {
+// CHECK: sil hidden @_T09accessors5test0yyAA1ACF : $@convention(thin) (@owned A) -> () {
 // CHECK: bb0([[ARG:%.*]] : @owned $A):
 // CHECK-NEXT: debug_value
 //   Formal evaluation of LHS.
@@ -45,7 +45,7 @@
 // CHECK-NEXT: store [[T1]] to [init] [[TEMP]]
 // CHECK-NEXT: [[T0:%.*]] = load_borrow [[TEMP]]
 // CHECK-NEXT: // function_ref accessors.OrdinarySub.subscript.getter : (Swift.Int) -> Swift.Int
-// CHECK-NEXT: [[T1:%.*]] = function_ref @_T09accessors11OrdinarySubVS2icig
+// CHECK-NEXT: [[T1:%.*]] = function_ref @_T09accessors11OrdinarySubVyS2icig
 // CHECK-NEXT: [[VALUE:%.*]] = apply [[T1]]([[INDEX1]], [[T0]])
 // CHECK-NEXT: end_borrow [[T0]] from [[TEMP]]
 // CHECK-NEXT: destroy_addr [[TEMP]]
@@ -60,7 +60,7 @@
 // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]]
 // CHECK-NEXT: [[ADDR:%.*]] = mark_dependence [[T4]] : $*OrdinarySub on [[BORROWED_ARG_LHS]] : $A
 // CHECK-NEXT: // function_ref accessors.OrdinarySub.subscript.setter : (Swift.Int) -> Swift.Int
-// CHECK-NEXT: [[SETTER:%.*]] = function_ref @_T09accessors11OrdinarySubVS2icis
+// CHECK-NEXT: [[SETTER:%.*]] = function_ref @_T09accessors11OrdinarySubVyS2icis
 // CHECK-NEXT: apply [[SETTER]]([[VALUE]], [[INDEX0]], [[ADDR]])
 // CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]]
 
@@ -99,7 +99,7 @@
 func test1(_ ref: B) {
   ref.array[index0()] = ref.array[index1()]
 }
-// CHECK-LABEL: sil hidden @_T09accessors5test1yAA1BCF : $@convention(thin) (@owned B) -> () {
+// CHECK-LABEL: sil hidden @_T09accessors5test1yyAA1BCF : $@convention(thin) (@owned B) -> () {
 // CHECK:    bb0([[ARG:%.*]] : @owned $B):
 // CHECK-NEXT: debug_value
 //   Formal evaluation of LHS.
@@ -123,7 +123,7 @@
 // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]]
 // CHECK-NEXT: [[ADDR:%.*]] = mark_dependence [[T4]] : $*MutatingSub on [[BORROWED_ARG_RHS]] : $B
 // CHECK-NEXT: // function_ref accessors.MutatingSub.subscript.getter : (Swift.Int) -> Swift.Int
-// CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors11MutatingSubVS2icig : $@convention(method) (Int, @inout MutatingSub) -> Int 
+// CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors11MutatingSubVyS2icig : $@convention(method) (Int, @inout MutatingSub) -> Int
 // CHECK-NEXT: [[VALUE:%.*]] = apply [[T0]]([[INDEX1]], [[ADDR]])
 // CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]]
 //
@@ -149,7 +149,7 @@
 // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]]
 // CHECK-NEXT: [[ADDR:%.*]] = mark_dependence [[T4]] : $*MutatingSub on [[BORROWED_ARG_LHS]] : $B
 // CHECK-NEXT: // function_ref accessors.MutatingSub.subscript.setter : (Swift.Int) -> Swift.Int
-// CHECK-NEXT: [[SETTER:%.*]] = function_ref @_T09accessors11MutatingSubVS2icis : $@convention(method) (Int, Int, @inout MutatingSub) -> () 
+// CHECK-NEXT: [[SETTER:%.*]] = function_ref @_T09accessors11MutatingSubVyS2icis : $@convention(method) (Int, Int, @inout MutatingSub) -> ()
 // CHECK-NEXT: apply [[SETTER]]([[VALUE]], [[INDEX0]], [[ADDR]])
 // CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]]
 //
@@ -190,7 +190,7 @@
   return outer.inner[0]
 }
 // This uses the immutable addressor.
-// CHECK: sil hidden @_T09accessors8test_recSiAA8RecOuterVzF : $@convention(thin) (@inout RecOuter) -> Int {
+// CHECK: sil hidden @_T09accessors8test_recySiAA8RecOuterVzF : $@convention(thin) (@inout RecOuter) -> Int {
 // CHECK:   function_ref @_T09accessors8RecOuterV5innerAA0B5InnerVvlu : $@convention(method) (RecOuter) -> UnsafePointer<RecInner>
 
 struct Rec2Inner {
@@ -208,23 +208,23 @@
   return outer.inner[0]
 }
 // This uses the mutable addressor.
-// CHECK: sil hidden @_T09accessors9test_rec2SiAA9Rec2OuterVzF : $@convention(thin) (@inout Rec2Outer) -> Int {
+// CHECK: sil hidden @_T09accessors9test_rec2ySiAA9Rec2OuterVzF : $@convention(thin) (@inout Rec2Outer) -> Int {
 // CHECK:   function_ref @_T09accessors9Rec2OuterV5innerAA0B5InnerVvau : $@convention(method) (@inout Rec2Outer) -> UnsafeMutablePointer<Rec2Inner>
 
 struct Foo {
   private subscript(privateSubscript x: Void) -> Void {
-    // CHECK-DAG: sil private @_T09accessors3FooVyyt16privateSubscript_tc33_D7F31B09EE737C687DC580B2014D759CLlig : $@convention(method) (Foo) -> () {
+    // CHECK-DAG: sil private @_T09accessors3FooV16privateSubscriptyyt_tc33_D7F31B09EE737C687DC580B2014D759CLlig : $@convention(method) (Foo) -> () {
     get {}
   }
   private(set) subscript(withPrivateSet x: Void) -> Void {
-    // CHECK-DAG: sil hidden @_T09accessors3FooVyyt14withPrivateSet_tcig : $@convention(method) (Foo) -> () {
+    // CHECK-DAG: sil hidden @_T09accessors3FooV14withPrivateSetyyt_tcig : $@convention(method) (Foo) -> () {
     get {}
-    // CHECK-DAG: sil private @_T09accessors3FooVyyt14withPrivateSet_tcis : $@convention(method) (@inout Foo) -> () {
+    // CHECK-DAG: sil private @_T09accessors3FooV14withPrivateSetyyt_tcis : $@convention(method) (@inout Foo) -> () {
     set {}
   }
   subscript(withNestedClass x: Void) -> Void {
     // Check for initializer of NestedClass
-    // CHECK-DAG: sil private @_T09accessors3FooVyyt15withNestedClass_tcig0dE0L_CAFycfc : $@convention(method) (@owned NestedClass) -> @owned NestedClass {
+    // CHECK-DAG: sil private @_T09accessors3FooV15withNestedClassyyt_tcig0dE0L_CAFycfc : $@convention(method) (@owned NestedClass) -> @owned NestedClass {
     class NestedClass {}
   }
 
diff --git a/test/SILGen/addressors.swift b/test/SILGen/addressors.swift
index 471d215..96bb7fe 100644
--- a/test/SILGen/addressors.swift
+++ b/test/SILGen/addressors.swift
@@ -31,14 +31,14 @@
   }
 }
 
-// CHECK-LABEL: sil hidden @_T010addressors1AVs5Int32VAEcilu : $@convention(method) (Int32, A) -> UnsafePointer<Int32>
+// CHECK-LABEL: sil hidden @_T010addressors1AVys5Int32VAEcilu : $@convention(method) (Int32, A) -> UnsafePointer<Int32>
 // CHECK: bb0([[INDEX:%.*]] : $Int32, [[SELF:%.*]] : $A):
 // CHECK:   [[BASE:%.*]] = struct_extract [[SELF]] : $A, #A.base
 // CHECK:   [[T0:%.*]] = struct_extract [[BASE]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue
 // CHECK:   [[T1:%.*]] = struct $UnsafePointer<Int32> ([[T0]] : $Builtin.RawPointer)
 // CHECK:   return [[T1]] : $UnsafePointer<Int32>
 
-// CHECK-LABEL: sil hidden @_T010addressors1AVs5Int32VAEciau : $@convention(method) (Int32, @inout A) -> UnsafeMutablePointer<Int32>
+// CHECK-LABEL: sil hidden @_T010addressors1AVys5Int32VAEciau : $@convention(method) (Int32, @inout A) -> UnsafeMutablePointer<Int32>
 // CHECK: bb0([[INDEX:%.*]] : $Int32, [[SELF:%.*]] : $*A):
 // CHECK:   [[READ:%.*]] = begin_access [read] [static] [[SELF]] : $*A
 // CHECK:   [[T0:%.*]] = struct_element_addr [[READ]] : $*A, #A.base
@@ -54,7 +54,7 @@
 // CHECK: store [[AVAL]] to [[A]]
   var a = A()
 
-// CHECK: [[T0:%.*]] = function_ref @_T010addressors1AVs5Int32VAEcilu :
+// CHECK: [[T0:%.*]] = function_ref @_T010addressors1AVys5Int32VAEcilu :
 // CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[AVAL]])
 // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafePointer<Int32>, #UnsafePointer._rawValue
 // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32
@@ -62,7 +62,7 @@
   let z = a[10]
 
 // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[A]] : $*A
-// CHECK: [[T0:%.*]] = function_ref @_T010addressors1AVs5Int32VAEciau :
+// CHECK: [[T0:%.*]] = function_ref @_T010addressors1AVys5Int32VAEciau :
 // CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[WRITE]])
 // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue
 // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32
@@ -72,7 +72,7 @@
   a[5] += z
 
 // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[A]] : $*A
-// CHECK: [[T0:%.*]] = function_ref @_T010addressors1AVs5Int32VAEciau :
+// CHECK: [[T0:%.*]] = function_ref @_T010addressors1AVys5Int32VAEciau :
 // CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[WRITE]])
 // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue
 // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32
@@ -85,7 +85,7 @@
 // CHECK: [[T0:%.*]] = metatype $@thin A.Type
 // CHECK: [[CTOR:%.*]] = function_ref @_T010addressors1AV{{[_0-9a-zA-Z]*}}fC
 // CHECK: [[A:%.*]] = apply [[CTOR]]([[T0]]) : $@convention(method) (@thin A.Type) -> A
-// CHECK: [[ACCESSOR:%.*]] = function_ref @_T010addressors1AVs5Int32VAEcilu : $@convention(method) (Int32, A) -> UnsafePointer<Int32>
+// CHECK: [[ACCESSOR:%.*]] = function_ref @_T010addressors1AVys5Int32VAEcilu : $@convention(method) (Int32, A) -> UnsafePointer<Int32>
 // CHECK: [[PTR:%.*]] = apply [[ACCESSOR]]({{%.*}}, [[A]]) : $@convention(method) (Int32, A) -> UnsafePointer<Int32>
 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] : $UnsafePointer<Int32>, #UnsafePointer._rawValue
 // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32
@@ -131,13 +131,13 @@
   }
 }
 
-// CHECK-LABEL: sil hidden @_T010addressors6test_ByAA1BVzF : $@convention(thin) (@inout B) -> () {
+// CHECK-LABEL: sil hidden @_T010addressors6test_ByyAA1BVzF : $@convention(thin) (@inout B) -> () {
 // CHECK: bb0([[B:%.*]] : $*B):
 // CHECK:   [[T0:%.*]] = integer_literal $Builtin.Int32, 0
 // CHECK:   [[INDEX:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32)
 // CHECK:   [[RHS:%.*]] = integer_literal $Builtin.Int32, 7
 // CHECK:   [[WRITE:%.*]] = begin_access [modify] [static] [[B]] : $*B
-// CHECK:   [[T0:%.*]] = function_ref @_T010addressors1BVs5Int32VAEciau
+// CHECK:   [[T0:%.*]] = function_ref @_T010addressors1BVys5Int32VAEciau
 // CHECK:   [[PTR:%.*]] = apply [[T0]]([[INDEX]], [[WRITE]])
 // CHECK:   [[T0:%.*]] = struct_extract [[PTR]] : $UnsafeMutablePointer<Int32>,
 // CHECK:   [[ADDR:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32
@@ -161,11 +161,11 @@
 
 func id_int(_ i: Int32) -> Int32 { return i }
 
-// CHECK-LABEL: sil hidden @_T010addressors11test_carrays5Int32VAA6CArrayVyA2DcGzF : $@convention(thin) (@inout CArray<(Int32) -> Int32>) -> Int32 {
+// CHECK-LABEL: sil hidden @_T010addressors11test_carrayys5Int32VAA6CArrayVyA2DcGzF : $@convention(thin) (@inout CArray<(Int32) -> Int32>) -> Int32 {
 // CHECK: bb0([[ARRAY:%.*]] : $*CArray<(Int32) -> Int32>):
 func test_carray(_ array: inout CArray<(Int32) -> Int32>) -> Int32 {
 // CHECK:   [[WRITE:%.*]] = begin_access [modify] [static] [[ARRAY]] : $*CArray<(Int32) -> Int32>
-// CHECK:   [[T0:%.*]] = function_ref @_T010addressors6CArrayVxSiciau :
+// CHECK:   [[T0:%.*]] = function_ref @_T010addressors6CArrayVyxSiciau :
 // CHECK:   [[T1:%.*]] = apply [[T0]]<(Int32) -> Int32>({{%.*}}, [[WRITE]])
 // CHECK:   [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<(Int32) -> Int32>, #UnsafeMutablePointer._rawValue
 // CHECK:   [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*@callee_guaranteed (@in Int32) -> @out Int32
@@ -174,7 +174,7 @@
 
 // CHECK:   [[READ:%.*]] = begin_access [read] [static] [[ARRAY]] : $*CArray<(Int32) -> Int32>
 // CHECK:   [[T0:%.*]] = load [[READ]]
-// CHECK:   [[T1:%.*]] = function_ref @_T010addressors6CArrayVxSicilu :
+// CHECK:   [[T1:%.*]] = function_ref @_T010addressors6CArrayVyxSicilu :
 // CHECK:   [[T2:%.*]] = apply [[T1]]<(Int32) -> Int32>({{%.*}}, [[T0]])
 // CHECK:   [[T3:%.*]] = struct_extract [[T2]] : $UnsafePointer<(Int32) -> Int32>, #UnsafePointer._rawValue
 // CHECK:   [[T4:%.*]] = pointer_to_address [[T3]] : $Builtin.RawPointer to [strict] $*@callee_guaranteed (@in Int32) -> @out Int32
@@ -190,22 +190,22 @@
   }
 }
 // Setter.
-// SILGEN-LABEL: sil hidden [transparent] @_T010addressors1DVs5Int32VAEcis
+// SILGEN-LABEL: sil hidden [transparent] @_T010addressors1DVys5Int32VAEcis
 // SILGEN: bb0([[VALUE:%.*]] : @trivial $Int32, [[I:%.*]] : @trivial $Int32, [[SELF:%.*]] : @trivial $*D):
 // SILGEN:   debug_value [[VALUE]] : $Int32
 // SILGEN:   debug_value [[I]] : $Int32
 // SILGEN:   debug_value_addr [[SELF]]
 // SILGEN:   [[ACCESS:%.*]] = begin_access [modify] [unknown] [[SELF]] : $*D   // users: %12, %8
-// SILGEN:   [[T0:%.*]] = function_ref @_T010addressors1DVs5Int32VAEciau{{.*}}
+// SILGEN:   [[T0:%.*]] = function_ref @_T010addressors1DVys5Int32VAEciau{{.*}}
 // SILGEN:   [[PTR:%.*]] = apply [[T0]]([[I]], [[ACCESS]])
 // SILGEN:   [[T0:%.*]] = struct_extract [[PTR]] : $UnsafeMutablePointer<Int32>,
 // SILGEN:   [[ADDR:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32
 // SILGEN:   assign [[VALUE]] to [[ADDR]] : $*Int32
 
 // materializeForSet.
-// SILGEN-LABEL: sil hidden [transparent] @_T010addressors1DVs5Int32VAEcim
+// SILGEN-LABEL: sil hidden [transparent] @_T010addressors1DVys5Int32VAEcim
 // SILGEN: bb0([[BUFFER:%.*]] : @trivial $Builtin.RawPointer, [[STORAGE:%.*]] : @trivial $*Builtin.UnsafeValueBuffer, [[I:%.*]] : @trivial $Int32, [[SELF:%.*]] : @trivial $*D):
-// SILGEN:   [[T0:%.*]] = function_ref @_T010addressors1DVs5Int32VAEciau
+// SILGEN:   [[T0:%.*]] = function_ref @_T010addressors1DVys5Int32VAEciau
 // SILGEN:   [[PTR:%.*]] = apply [[T0]]([[I]], [[SELF]])
 // SILGEN:   [[ADDR_TMP:%.*]] = struct_extract [[PTR]] : $UnsafeMutablePointer<Int32>,
 // SILGEN:   [[ADDR:%.*]] = pointer_to_address [[ADDR_TMP]]
@@ -217,13 +217,13 @@
 func make_int() -> Int32 { return 0 }
 func take_int_inout(_ value: inout Int32) {}
 
-// CHECK-LABEL: sil hidden @_T010addressors6test_ds5Int32VAA1DVzF : $@convention(thin) (@inout D) -> Int32
+// CHECK-LABEL: sil hidden @_T010addressors6test_dys5Int32VAA1DVzF : $@convention(thin) (@inout D) -> Int32
 // CHECK: bb0([[ARRAY:%.*]] : $*D):
 func test_d(_ array: inout D) -> Int32 {
 // CHECK:   [[T0:%.*]] = function_ref @_T010addressors8make_ints5Int32VyF
 // CHECK:   [[V:%.*]] = apply [[T0]]()
 // CHECK:   [[WRITE:%.*]] = begin_access [modify] [static] [[ARRAY]] : $*D
-// CHECK:   [[T0:%.*]] = function_ref @_T010addressors1DVs5Int32VAEciau
+// CHECK:   [[T0:%.*]] = function_ref @_T010addressors1DVys5Int32VAEciau
 // CHECK:   [[T1:%.*]] = apply [[T0]]({{%.*}}, [[WRITE]])
 // CHECK:   [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>,
 // CHECK:   [[ADDR:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32
@@ -231,17 +231,17 @@
   array[0] = make_int()
 
 // CHECK:   [[WRITE:%.*]] = begin_access [modify] [static] [[ARRAY]] : $*D
-// CHECK:   [[T0:%.*]] = function_ref @_T010addressors1DVs5Int32VAEciau
+// CHECK:   [[T0:%.*]] = function_ref @_T010addressors1DVys5Int32VAEciau
 // CHECK:   [[T1:%.*]] = apply [[T0]]({{%.*}}, [[WRITE]])
 // CHECK:   [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>,
 // CHECK:   [[ADDR:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32
-// CHECK:   [[FN:%.*]] = function_ref @_T010addressors14take_int_inoutys5Int32VzF
+// CHECK:   [[FN:%.*]] = function_ref @_T010addressors14take_int_inoutyys5Int32VzF
 // CHECK:   apply [[FN]]([[ADDR]])
   take_int_inout(&array[1])
 
 // CHECK:   [[READ:%.*]] = begin_access [read] [static] [[ARRAY]] : $*D
 // CHECK:   [[T0:%.*]] = load [[READ]]
-// CHECK:   [[T1:%.*]] = function_ref @_T010addressors1DVs5Int32VAEcig
+// CHECK:   [[T1:%.*]] = function_ref @_T010addressors1DVys5Int32VAEcig
 // CHECK:   [[T2:%.*]] = apply [[T1]]({{%.*}}, [[T0]])
 // CHECK:   return [[T2]]
   return array[2]
@@ -254,7 +254,7 @@
   }
 }
 
-// CHECK-LABEL: sil hidden @_T010addressors6test_eyAA1EVF
+// CHECK-LABEL: sil hidden @_T010addressors6test_eyyAA1EVF
 // CHECK: bb0([[E:%.*]] : $E):
 // CHECK:   [[T0:%.*]] = function_ref @_T010addressors1EV5values5Int32Vvau
 // CHECK:   [[T1:%.*]] = apply [[T0]]([[E]])
@@ -284,7 +284,7 @@
 func test_f0(_ f: F) -> Int32 {
   return f.value
 }
-// CHECK-LABEL: sil hidden @_T010addressors7test_f0s5Int32VAA1FCF : $@convention(thin) (@owned F) -> Int32 {
+// CHECK-LABEL: sil hidden @_T010addressors7test_f0ys5Int32VAA1FCF : $@convention(thin) (@owned F) -> Int32 {
 // CHECK: bb0([[SELF:%0]] : $F):
 // CHECK:   [[ADDRESSOR:%.*]] = function_ref @_T010addressors1FC5values5Int32Vvlo : $@convention(method) (@guaranteed F) -> (UnsafePointer<Int32>, @owned Builtin.NativeObject)
 // CHECK:   [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]])
@@ -301,7 +301,7 @@
 func test_f1(_ f: F) {
   f.value = 14
 }
-// CHECK-LABEL: sil hidden @_T010addressors7test_f1yAA1FCF : $@convention(thin) (@owned F) -> () {
+// CHECK-LABEL: sil hidden @_T010addressors7test_f1yyAA1FCF : $@convention(thin) (@owned F) -> () {
 // CHECK: bb0([[SELF:%0]] : $F):
 // CHECK:   [[T0:%.*]] = integer_literal $Builtin.Int32, 14
 // CHECK:   [[VALUE:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32)
@@ -404,7 +404,7 @@
 func test_h0(_ f: H) -> Int32 {
   return f.value
 }
-// CHECK-LABEL: sil hidden @_T010addressors7test_h0s5Int32VAA1HCF : $@convention(thin) (@owned H) -> Int32 {
+// CHECK-LABEL: sil hidden @_T010addressors7test_h0ys5Int32VAA1HCF : $@convention(thin) (@owned H) -> Int32 {
 // CHECK: bb0([[SELF:%0]] : $H):
 // CHECK:   [[ADDRESSOR:%.*]] = function_ref @_T010addressors1HC5values5Int32Vvlp : $@convention(method) (@guaranteed H) -> (UnsafePointer<Int32>, @owned Optional<Builtin.NativeObject>)
 
@@ -422,7 +422,7 @@
 func test_h1(_ f: H) {
   f.value = 14
 }
-// CHECK-LABEL: sil hidden @_T010addressors7test_h1yAA1HCF : $@convention(thin) (@owned H) -> () {
+// CHECK-LABEL: sil hidden @_T010addressors7test_h1yyAA1HCF : $@convention(thin) (@owned H) -> () {
 // CHECK: bb0([[SELF:%0]] : $H):
 // CHECK:   [[T0:%.*]] = integer_literal $Builtin.Int32, 14
 // CHECK:   [[VALUE:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32)
@@ -528,10 +528,10 @@
   return outer.middle.inner[0]
 }
 // This uses the mutable addressor.
-// CHECK-LABEL: sil hidden @_T010addressors8test_recs5Int32VAA8RecOuterCF : $@convention(thin) (@owned RecOuter) -> Int32 {
+// CHECK-LABEL: sil hidden @_T010addressors8test_recys5Int32VAA8RecOuterCF : $@convention(thin) (@owned RecOuter) -> Int32 {
 // CHECK:   function_ref @_T010addressors8RecOuterC6middleAA0B6MiddleVvaP
 // CHECK:   struct_element_addr {{.*}} : $*RecMiddle, #RecMiddle.inner
-// CHECK:   function_ref @_T010addressors8RecInnerVs5Int32VAEcig
+// CHECK:   function_ref @_T010addressors8RecInnerVys5Int32VAEcig
 
 class Base {
   var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.allocate(capacity: 100)
diff --git a/test/SILGen/argument_shuffle_swift3.swift b/test/SILGen/argument_shuffle_swift3.swift
index 7b036d0..9c80a76 100644
--- a/test/SILGen/argument_shuffle_swift3.swift
+++ b/test/SILGen/argument_shuffle_swift3.swift
@@ -6,12 +6,12 @@
   case any(_: Any)
 }
 
-// CHECK-LABEL: sil hidden @_T023argument_shuffle_swift31gyyp1x_tF : $@convention(thin) (@in Any) -> () {
+// CHECK-LABEL: sil hidden @_T023argument_shuffle_swift31g1xyyp_tF : $@convention(thin) (@in Any) -> () {
 func g(x: Any) {
-  // CHECK: [[FN:%.*]] = function_ref @_T023argument_shuffle_swift32fnyypF : $@convention(thin) (@in Any) -> ()
+  // CHECK: [[FN:%.*]] = function_ref @_T023argument_shuffle_swift32fnyyypF : $@convention(thin) (@in Any) -> ()
   // CHECK: apply [[FN:%.*]]({{.*}}) : $@convention(thin) (@in Any) -> ()
   fn(data: 123)
-  // CHECK: [[FN:%.*]] = function_ref @_T023argument_shuffle_swift32fnyypF : $@convention(thin) (@in Any) -> ()
+  // CHECK: [[FN:%.*]] = function_ref @_T023argument_shuffle_swift32fnyyypF : $@convention(thin) (@in Any) -> ()
   // CHECK: apply [[FN:%.*]]({{.*}}) : $@convention(thin) (@in Any) -> ()
   fn(data: x)
 
diff --git a/test/SILGen/arguments.swift b/test/SILGen/arguments.swift
index 1d6e958..b576363 100644
--- a/test/SILGen/arguments.swift
+++ b/test/SILGen/arguments.swift
@@ -19,13 +19,13 @@
 var i:Int, f:Float, c:UnicodeScalar
 
 func arg_tuple(x: Int, y: Float) {}
-// CHECK-LABEL: sil hidden @_T0s9arg_tupleySi1x_Sf1ytF
+// CHECK-LABEL: sil hidden @_T0s9arg_tuple1x1yySi_SftF
 // CHECK: bb0([[X:%[0-9]+]] : @trivial $Int, [[Y:%[0-9]+]] : @trivial $Float):
 
 arg_tuple(x: i, y: f)
 
 func arg_deep_tuples(x: Int, y: (Float, UnicodeScalar)) {}
-// CHECK-LABEL: sil hidden @_T0s15arg_deep_tuplesySi1x_Sf_Sct1ytF
+// CHECK-LABEL: sil hidden @_T0s15arg_deep_tuples1x1yySi_Sf_ScttF
 // CHECK: bb0([[X:%[0-9]+]] : @trivial $Int, [[Y_0:%[0-9]+]] : @trivial $Float, [[Y_1:%[0-9]+]] : @trivial $UnicodeScalar):
 
 arg_deep_tuples(x:i, y:(f, c))
@@ -37,7 +37,7 @@
 arg_deep_tuples(x:i, y: named_subtuple)
 
 func arg_deep_tuples_2(x: Int, _: (y: Float, z: UnicodeScalar)) {}
-// CHECK-LABEL: sil hidden @_T0s17arg_deep_tuples_2ySi1x_Sf1y_Sc1zttF
+// CHECK-LABEL: sil hidden @_T0s17arg_deep_tuples_21x_ySi_Sf1y_Sc1zttF
 // CHECK: bb0([[X:%[0-9]+]] : @trivial $Int, [[Y:%[0-9]+]] : @trivial $Float, [[Z:%[0-9]+]] : @trivial $UnicodeScalar):
 
 arg_deep_tuples_2(x: i, (f, c))
@@ -48,7 +48,7 @@
 //arg_deep_tuples_2(deep_named_tuple)
 
 func arg_default_tuple(x x: Int = i, y: Float = f) {}
-// CHECK-LABEL: sil hidden @_T0s17arg_default_tupleySi1x_Sf1ytF
+// CHECK-LABEL: sil hidden @_T0s17arg_default_tuple1x1yySi_SftF
 // CHECK: bb0([[X:%[0-9]+]] : @trivial $Int, [[Y:%[0-9]+]] : @trivial $Float):
 
 arg_default_tuple()
diff --git a/test/SILGen/arguments_as_tuple_overloads.swift b/test/SILGen/arguments_as_tuple_overloads.swift
index 1dd08c9..9250c13 100644
--- a/test/SILGen/arguments_as_tuple_overloads.swift
+++ b/test/SILGen/arguments_as_tuple_overloads.swift
@@ -4,54 +4,54 @@
 // subscripts correctly.
 
 public struct Pair {
-  // CHECK: sil @_T04test4PairVACSi_SitcfC :
+  // CHECK: sil @_T04test4PairVyACSi_SitcfC :
   public init(_ a: Int, _ b: Int) {
   }
 
-  // CHECK: sil @_T04test4PairVACSi_Sit_tcfC :
+  // CHECK: sil @_T04test4PairVyACSi_Sit_tcfC :
   public init(_ t: (Int, Int)) {
   }
 
-  // CHECK: sil @_T04test4PairVAAySi_SitF :
+  // CHECK: sil @_T04test4PairVAAyySi_SitF :
   public func test(_ a: Int, _ b: Int) {
   }
 
-  // CHECK: sil @_T04test4PairVAAySi_Sit_tF :
+  // CHECK: sil @_T04test4PairVAAyySi_Sit_tF :
   public func test(_ t: (Int, Int)) {
   }
 
-  // CHECK: sil @_T04test4PairVS2i_Sitcig :
+  // CHECK: sil @_T04test4PairVyS2i_Sitcig :
   public subscript(_:Int, _:Int) -> Int {
       get { return 0 }
   }
 
-  // CHECK: sil @_T04test4PairVS2i_Sit_tcig :
+  // CHECK: sil @_T04test4PairVyS2i_Sit_tcig :
   public subscript(_:(Int, Int)) -> Int {
       get { return 0 }
   }
 }
 
-// CHECK: sil @_T04testAAySi_SitF :
+// CHECK: sil @_T04testAAyySi_SitF :
 public func test(_ a: Int, _ b: Int) {
 }
 
-// CHECK: sil @_T04testAAySi_Sit_tF :
+// CHECK: sil @_T04testAAyySi_Sit_tF :
 public func test(_ t: (Int, Int)) {
 }
 
-// CHECK: sil @_T04test0A7NoLabelySi_Sit_tF :
+// CHECK: sil @_T04test0A7NoLabelyySi_Sit_tF :
 public func testNoLabel(_: (Int, Int)) {
 }
 
-// CHECK: sil @_T04test0A5FnArgyySi_SitcF :
+// CHECK: sil @_T04test0A5FnArgyyySi_SitcF :
 public func testFnArg(_: (Int, Int) -> Void) {
 }
 
-// CHECK: sil @_T04test0A5FnArgyySi_Sit_tcF :
+// CHECK: sil @_T04test0A5FnArgyyySi_Sit_tcF :
 public func testFnArg(_: ((Int, Int)) -> Void) {
 }
 
-// CHECK: sil @_T04test3fooyyt_tF :
+// CHECK: sil @_T04test3fooyyyt_tF :
 public func foo(_: ()) {
 }
 
diff --git a/test/SILGen/assignment.swift b/test/SILGen/assignment.swift
index 722c1bf..bebacd9 100644
--- a/test/SILGen/assignment.swift
+++ b/test/SILGen/assignment.swift
@@ -40,7 +40,7 @@
 
 // Verify that the access to the LHS does not begin until after the
 // RHS is formally evaluated.
-// CHECK-LABEL: sil hidden @_T010assignment15copyRightToLeftyAA1P_pz1p_tF : $@convention(thin) (@inout P) -> () {
+// CHECK-LABEL: sil hidden @_T010assignment15copyRightToLeft1pyAA1P_pz_tF : $@convention(thin) (@inout P) -> () {
 func copyRightToLeft(p: inout P) {
   // CHECK: bb0(%0 : @trivial $*P):
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] %0 : $*P
diff --git a/test/SILGen/auto_closures.swift b/test/SILGen/auto_closures.swift
index aaf4f47..8511f82 100644
--- a/test/SILGen/auto_closures.swift
+++ b/test/SILGen/auto_closures.swift
@@ -3,7 +3,7 @@
 struct Bool {}
 var false_ = Bool()
 
-// CHECK-LABEL: sil hidden @_T013auto_closures05call_A8_closureAA4BoolVADyXKF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> Bool) -> Bool
+// CHECK-LABEL: sil hidden @_T013auto_closures05call_A8_closureyAA4BoolVADyXKF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> Bool) -> Bool
 func call_auto_closure(_ x: @autoclosure () -> Bool) -> Bool {
   // CHECK: bb0([[CLOSURE:%.*]] : $@noescape @callee_guaranteed () -> Bool):
   // CHECK: [[BORROWED_CLOSURE:%.*]] = begin_borrow [[CLOSURE]]
@@ -49,7 +49,7 @@
   // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
   // CHECK: [[AUTOCLOSURE:%.*]] = partial_apply [callee_guaranteed] [[AUTOCLOSURE_FUNC]]([[SELF_COPY]])
   // CHECK: [[CVT:%.*]] = convert_function [[AUTOCLOSURE]]
-  // CHECK: [[AUTOCLOSURE_CONSUMER:%.*]] = function_ref @_T013auto_closures05call_A8_closureAA4BoolVADyXKF : $@convention(thin)
+  // CHECK: [[AUTOCLOSURE_CONSUMER:%.*]] = function_ref @_T013auto_closures05call_A8_closureyAA4BoolVADyXKF : $@convention(thin)
   // CHECK: [[RET:%.*]] = apply [[AUTOCLOSURE_CONSUMER]]([[CVT]])
   // CHECK: return [[RET]] : $Bool
   // CHECK: }
@@ -61,11 +61,11 @@
   override var x: Bool { return call_auto_closure(super.x) }
 }
 
-// CHECK-LABEL: sil hidden @_T013auto_closures20closureInAutoclosureAA4BoolVAD_ADtF : $@convention(thin) (Bool, Bool) -> Bool {
+// CHECK-LABEL: sil hidden @_T013auto_closures20closureInAutoclosureyAA4BoolVAD_ADtF : $@convention(thin) (Bool, Bool) -> Bool {
 // CHECK: }
-// CHECK-LABEL: sil private [transparent] @_T013auto_closures20closureInAutoclosureAA4BoolVAD_ADtFADyXKfu_ : $@convention(thin) (Bool, Bool) -> Bool {
+// CHECK-LABEL: sil private [transparent] @_T013auto_closures20closureInAutoclosureyAA4BoolVAD_ADtFADyXKfu_ : $@convention(thin) (Bool, Bool) -> Bool {
 // CHECK: }
-// CHECK-LABEL: sil private @_T013auto_closures20closureInAutoclosureAA4BoolVAD_ADtFADyXKfu_A2DcfU_ : $@convention(thin) (Bool, Bool) -> Bool {
+// CHECK-LABEL: sil private @_T013auto_closures20closureInAutoclosureyAA4BoolVAD_ADtFADyXKfu_A2DcfU_ : $@convention(thin) (Bool, Bool) -> Bool {
 // CHECK: }
 func compareBool(_ lhs: Bool, _ rhs: Bool) -> Bool { return false_ }
 func testBool(_ x: Bool, _ pred: (Bool) -> Bool) -> Bool {
diff --git a/test/SILGen/availability_query.swift b/test/SILGen/availability_query.swift
index 375d933..c44c9f0 100644
--- a/test/SILGen/availability_query.swift
+++ b/test/SILGen/availability_query.swift
@@ -8,7 +8,7 @@
 // CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
 // CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 53
 // CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 8
-// CHECK: [[FUNC:%.*]] = function_ref @_T0s26_stdlib_isOSVersionAtLeastBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
+// CHECK: [[FUNC:%.*]] = function_ref @_T0s26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
 // CHECK: [[QUERY_RESULT:%.*]] = apply [[FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
 if #available(OSX 10.53.8, iOS 7.1, *) {
 }
@@ -24,7 +24,7 @@
 // CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
 // CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52
 // CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
-// CHECK: [[QUERY_FUNC:%.*]] = function_ref @_T0s26_stdlib_isOSVersionAtLeastBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
+// CHECK: [[QUERY_FUNC:%.*]] = function_ref @_T0s26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
 // CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
 if #available(OSX 10.52, *) {
 }
@@ -32,7 +32,7 @@
 // CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
 // CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52
 // CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
-// CHECK: [[QUERY_FUNC:%.*]] = function_ref @_T0s26_stdlib_isOSVersionAtLeastBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
+// CHECK: [[QUERY_FUNC:%.*]] = function_ref @_T0s26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
 // CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
 if #available(macOS 10.52, *) {
 }
@@ -40,7 +40,7 @@
 // CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
 // CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 0
 // CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
-// CHECK: [[QUERY_FUNC:%.*]] = function_ref @_T0s26_stdlib_isOSVersionAtLeastBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
+// CHECK: [[QUERY_FUNC:%.*]] = function_ref @_T0s26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
 // CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
 if #available(OSX 10, *) {
 }
diff --git a/test/SILGen/boxed_existentials.swift b/test/SILGen/boxed_existentials.swift
index deca768..2db4524 100644
--- a/test/SILGen/boxed_existentials.swift
+++ b/test/SILGen/boxed_existentials.swift
@@ -2,7 +2,7 @@
 // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen %s | %FileCheck %s --check-prefix=GUARANTEED
 
 func test_type_lowering(_ x: Error) { }
-// CHECK-LABEL: sil hidden @_T018boxed_existentials18test_type_loweringys5Error_pF : $@convention(thin) (@owned Error) -> () {
+// CHECK-LABEL: sil hidden @_T018boxed_existentials18test_type_loweringyys5Error_pF : $@convention(thin) (@owned Error) -> () {
 // CHECK:         destroy_value %0 : $Error
 
 class Document {}
@@ -17,7 +17,7 @@
 func test_concrete_erasure(_ x: ClericalError) -> Error {
   return x
 }
-// CHECK-LABEL: sil hidden @_T018boxed_existentials21test_concrete_erasures5Error_pAA08ClericalF0OF
+// CHECK-LABEL: sil hidden @_T018boxed_existentials21test_concrete_erasureys5Error_pAA08ClericalF0OF
 // CHECK:       bb0([[ARG:%.*]] : @owned $ClericalError):
 // CHECK:         [[EXISTENTIAL:%.*]] = alloc_existential_box $Error, $ClericalError
 // CHECK:         [[ADDR:%.*]] = project_existential_box $ClericalError in [[EXISTENTIAL]] : $Error
@@ -33,7 +33,7 @@
 func test_composition_erasure(_ x: HairType & Error) -> Error {
   return x
 }
-// CHECK-LABEL: sil hidden @_T018boxed_existentials24test_composition_erasures5Error_psAC_AA8HairTypepF
+// CHECK-LABEL: sil hidden @_T018boxed_existentials24test_composition_erasureys5Error_psAC_AA8HairTypepF
 // CHECK:         [[VALUE_ADDR:%.*]] = open_existential_addr immutable_access [[OLD_EXISTENTIAL:%.*]] : $*Error & HairType to $*[[VALUE_TYPE:@opened\(.*\) Error & HairType]]
 // CHECK:         [[NEW_EXISTENTIAL:%.*]] = alloc_existential_box $Error, $[[VALUE_TYPE]]
 // CHECK:         [[ADDR:%.*]] = project_existential_box $[[VALUE_TYPE]] in [[NEW_EXISTENTIAL]] : $Error
@@ -46,7 +46,7 @@
 func test_class_composition_erasure(_ x: HairClass & Error) -> Error {
   return x
 }
-// CHECK-LABEL: sil hidden @_T018boxed_existentials30test_class_composition_erasures5Error_psAC_AA9HairClasspF
+// CHECK-LABEL: sil hidden @_T018boxed_existentials30test_class_composition_erasureys5Error_psAC_AA9HairClasspF
 // CHECK:         [[VALUE:%.*]] = open_existential_ref [[OLD_EXISTENTIAL:%.*]] : $Error & HairClass to $[[VALUE_TYPE:@opened\(.*\) Error & HairClass]]
 // CHECK:         [[NEW_EXISTENTIAL:%.*]] = alloc_existential_box $Error, $[[VALUE_TYPE]]
 // CHECK:         [[ADDR:%.*]] = project_existential_box $[[VALUE_TYPE]] in [[NEW_EXISTENTIAL]] : $Error
@@ -57,7 +57,7 @@
 func test_property(_ x: Error) -> String {
   return x._domain
 }
-// CHECK-LABEL: sil hidden @_T018boxed_existentials13test_propertySSs5Error_pF
+// CHECK-LABEL: sil hidden @_T018boxed_existentials13test_propertyySSs5Error_pF
 // CHECK: bb0([[ARG:%.*]] : @owned $Error):
 // CHECK:         [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:         [[VALUE:%.*]] = open_existential_box [[BORROWED_ARG]] : $Error to $*[[VALUE_TYPE:@opened\(.*\) Error]]
@@ -77,7 +77,7 @@
   return x._domain
 }
 
-// CHECK-LABEL: sil hidden @_T018boxed_existentials23test_property_of_lvalueSSs5Error_pF :
+// CHECK-LABEL: sil hidden @_T018boxed_existentials23test_property_of_lvalueySSs5Error_pF :
 // CHECK:       bb0([[ARG:%.*]] : @owned $Error):
 // CHECK:         [[VAR:%.*]] = alloc_box ${ var Error }
 // CHECK:         [[PVAR:%.*]] = project_box [[VAR]]
@@ -97,12 +97,12 @@
 // CHECK:         destroy_value [[VAR]]
 // CHECK:         destroy_value [[ARG]]
 // CHECK:         return [[RESULT]]
-// CHECK:      } // end sil function '_T018boxed_existentials23test_property_of_lvalueSSs5Error_pF'
+// CHECK:      } // end sil function '_T018boxed_existentials23test_property_of_lvalueySSs5Error_pF'
 extension Error {
   func extensionMethod() { }
 }
 
-// CHECK-LABEL: sil hidden @_T018boxed_existentials21test_extension_methodys5Error_pF
+// CHECK-LABEL: sil hidden @_T018boxed_existentials21test_extension_methodyys5Error_pF
 func test_extension_method(_ error: Error) {
   // CHECK: bb0([[ARG:%.*]] : @owned $Error):
   // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
@@ -120,8 +120,8 @@
 
 func plusOneError() -> Error { }
 
-// CHECK-LABEL: sil hidden @_T018boxed_existentials31test_open_existential_semanticsys5Error_p_sAC_ptF
-// GUARANTEED-LABEL: sil hidden @_T018boxed_existentials31test_open_existential_semanticsys5Error_p_sAC_ptF
+// CHECK-LABEL: sil hidden @_T018boxed_existentials31test_open_existential_semanticsyys5Error_p_sAC_ptF
+// GUARANTEED-LABEL: sil hidden @_T018boxed_existentials31test_open_existential_semanticsyys5Error_p_sAC_ptF
 // CHECK: bb0([[ARG0:%.*]]: @owned $Error,
 // GUARANTEED: bb0([[ARG0:%.*]]: @owned $Error,
 func test_open_existential_semantics(_ guaranteed: Error,
@@ -192,7 +192,7 @@
   plusOneError().extensionMethod()
 }
 
-// CHECK-LABEL: sil hidden @_T018boxed_existentials14erasure_to_anyyps5Error_p_sAC_ptF
+// CHECK-LABEL: sil hidden @_T018boxed_existentials14erasure_to_anyyyps5Error_p_sAC_ptF
 // CHECK:       bb0([[OUT:%.*]] : @trivial $*Any, [[GUAR:%.*]] : @owned $Error,
 func erasure_to_any(_ guaranteed: Error, _ immediate: Error) -> Any {
   var immediate = immediate
diff --git a/test/SILGen/builtins.swift b/test/SILGen/builtins.swift
index ba24418..92f09ca 100644
--- a/test/SILGen/builtins.swift
+++ b/test/SILGen/builtins.swift
@@ -365,7 +365,7 @@
   // CHECK:   return [[A2P]]
   return Builtin.projectTailElems(h, ty)
 }
-// CHECK: } // end sil function '_T08builtins16projectTailElemsBpAA6HeaderC1h_xm2tytlF'
+// CHECK: } // end sil function '_T08builtins16projectTailElems1h2tyBpAA6HeaderC_xmtlF'
 
 // CHECK-LABEL: sil hidden @_T08builtins11getTailAddr{{[_0-9a-zA-Z]*}}F
 func getTailAddr<T1, T2>(start: Builtin.RawPointer, i: Builtin.Word, ty1: T1.Type, ty2: T2.Type) -> Builtin.RawPointer {
@@ -446,7 +446,7 @@
   Builtin.canBeClass(TT.self)
 }
 
-// CHECK-LABEL: sil hidden @_T08builtins11fixLifetimeyAA1CCF : $@convention(thin) (@owned C) -> () {
+// CHECK-LABEL: sil hidden @_T08builtins11fixLifetimeyyAA1CCF : $@convention(thin) (@owned C) -> () {
 func fixLifetime(_ c: C) {
   // CHECK: bb0([[ARG:%.*]] : @owned $C):
   // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
@@ -457,7 +457,7 @@
   // CHECK:   destroy_value [[ARG]]
   Builtin.fixLifetime(c)
 }
-// CHECK: } // end sil function '_T08builtins11fixLifetimeyAA1CCF'
+// CHECK: } // end sil function '_T08builtins11fixLifetimeyyAA1CCF'
 
 // CHECK-LABEL: sil hidden @_T08builtins20assert_configuration{{[_0-9a-zA-Z]*}}F
 func assert_configuration() -> Builtin.Int32 {
@@ -466,14 +466,14 @@
   // CHECK: return [[APPLY]] : $Builtin.Int32
 }
 
-// CHECK-LABEL: sil hidden @_T08builtins17assumeNonNegativeBwBwF
+// CHECK-LABEL: sil hidden @_T08builtins17assumeNonNegativeyBwBwF
 func assumeNonNegative(_ x: Builtin.Word) -> Builtin.Word {
   return Builtin.assumeNonNegative_Word(x)
   // CHECK: [[APPLY:%.*]] = builtin "assumeNonNegative_Word"(%0 : $Builtin.Word) : $Builtin.Word
   // CHECK: return [[APPLY]] : $Builtin.Word
 }
 
-// CHECK-LABEL: sil hidden @_T08builtins11autoreleaseyAA1OCF : $@convention(thin) (@owned O) -> () {
+// CHECK-LABEL: sil hidden @_T08builtins11autoreleaseyyAA1OCF : $@convention(thin) (@owned O) -> () {
 // ==> SEMANTIC ARC TODO: This will be unbalanced... should we allow it?
 // CHECK: bb0([[ARG:%.*]] : @owned $O):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
@@ -482,7 +482,7 @@
 // CHECK:   destroy_value [[ARG_COPY]]
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK:   destroy_value [[ARG]]
-// CHECK: } // end sil function '_T08builtins11autoreleaseyAA1OCF'
+// CHECK: } // end sil function '_T08builtins11autoreleaseyyAA1OCF'
 func autorelease(_ o: O) {
   Builtin.autorelease(o)
 }
@@ -498,7 +498,7 @@
   Builtin.unreachable()
 }
 
-// CHECK-LABEL: sil hidden @_T08builtins15reinterpretCastBw_AA1DCAA1CCSgAFtAF_Bw1xtF : $@convention(thin) (@owned C, Builtin.Word) -> (Builtin.Word, @owned D, @owned Optional<C>, @owned C)
+// CHECK-LABEL: sil hidden @_T08builtins15reinterpretCast_1xBw_AA1DCAA1CCSgAGtAG_BwtF : $@convention(thin) (@owned C, Builtin.Word) -> (Builtin.Word, @owned D, @owned Optional<C>, @owned C)
 // CHECK:       bb0([[ARG1:%.*]] : @owned $C, [[ARG2:%.*]] : @trivial $Builtin.Word):
 // CHECK-NEXT:    debug_value
 // CHECK-NEXT:    debug_value
@@ -728,7 +728,7 @@
   return Builtin.castReference(o)
 }
 
-// CHECK-LABEL: sil hidden @_T08builtins17refcast_class_anyyXlAA1ACF :
+// CHECK-LABEL: sil hidden @_T08builtins17refcast_class_anyyyXlAA1ACF :
 // CHECK: bb0([[ARG:%.*]] : @owned $A):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
@@ -736,7 +736,7 @@
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK:   destroy_value [[ARG]]
 // CHECK:   return [[ARG_COPY_CASTED]]
-// CHECK: } // end sil function '_T08builtins17refcast_class_anyyXlAA1ACF'
+// CHECK: } // end sil function '_T08builtins17refcast_class_anyyyXlAA1ACF'
 func refcast_class_any(_ o: A) -> AnyObject {
   return Builtin.castReference(o)
 }
@@ -747,7 +747,7 @@
   return Builtin.castReference(o)
 }
 
-// CHECK-LABEL: sil hidden @_T08builtins18refcast_pclass_anyyXlAA6PClass_pF :
+// CHECK-LABEL: sil hidden @_T08builtins18refcast_pclass_anyyyXlAA6PClass_pF :
 // CHECK: bb0([[ARG:%.*]] : @owned $PClass):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
@@ -755,7 +755,7 @@
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK:   destroy_value [[ARG]]
 // CHECK:   return [[ARG_COPY_CAST]]
-// CHECK: } // end sil function '_T08builtins18refcast_pclass_anyyXlAA6PClass_pF'
+// CHECK: } // end sil function '_T08builtins18refcast_pclass_anyyyXlAA6PClass_pF'
 func refcast_pclass_any(_ o: PClass) -> AnyObject {
   return Builtin.castReference(o)
 }
@@ -909,3 +909,16 @@
 func release(ptr: Builtin.NativeObject) {
   Builtin.release(ptr)
 }
+
+//===----------------------------------------------------------------------===//
+// Other Operations
+//===----------------------------------------------------------------------===//
+
+func once_helper() {}
+
+// CHECK-LABEL: sil hidden @_T08builtins4once7controlyBp_tF
+// CHECK:      [[T0:%.*]] = function_ref @_T08builtins11once_helperyyFTo : $@convention(c) () -> ()
+// CHECK-NEXT: builtin "once"(%0 : $Builtin.RawPointer, [[T0]] : $@convention(c) () -> ())
+func once(control: Builtin.RawPointer) {
+  Builtin.once(control, once_helper)
+}
diff --git a/test/SILGen/c_function_pointers.swift b/test/SILGen/c_function_pointers.swift
index f8143e2..720f6a9 100644
--- a/test/SILGen/c_function_pointers.swift
+++ b/test/SILGen/c_function_pointers.swift
@@ -3,7 +3,7 @@
 func values(_ arg: @escaping @convention(c) (Int) -> Int) -> @convention(c) (Int) -> Int {
   return arg
 }
-// CHECK-LABEL: sil hidden @_T019c_function_pointers6valuesS2iXCS2iXCF
+// CHECK-LABEL: sil hidden @_T019c_function_pointers6valuesyS2iXCS2iXCF
 // CHECK:       bb0(%0 : @trivial $@convention(c) (Int) -> Int):
 // CHECK:         return %0 : $@convention(c) (Int) -> Int
 
@@ -11,7 +11,7 @@
 func calls(_ arg: @convention(c) (Int) -> Int, _ x: Int) -> Int {
   return arg(x)
 }
-// CHECK-LABEL: sil hidden @_T019c_function_pointers5callsS3iXC_SitF
+// CHECK-LABEL: sil hidden @_T019c_function_pointers5callsyS3iXC_SitF
 // CHECK:       bb0(%0 : @trivial $@convention(c) @noescape (Int) -> Int, %1 : @trivial $Int):
 // CHECK:         [[RESULT:%.*]] = apply %0(%1)
 // CHECK:         return [[RESULT]]
@@ -25,23 +25,23 @@
 
 func no_args() -> Int { return 42 }
 
-// CHECK-LABEL: sil hidden @_T019c_function_pointers0B19_to_swift_functionsySiF
+// CHECK-LABEL: sil hidden @_T019c_function_pointers0B19_to_swift_functionsyySiF
 func pointers_to_swift_functions(_ x: Int) {
 // CHECK: bb0([[X:%.*]] : @trivial $Int):
 
   func local(_ y: Int) -> Int { return y }
 
-  // CHECK:   [[GLOBAL_C:%.*]] = function_ref @_T019c_function_pointers6globalS2iFTo
+  // CHECK:   [[GLOBAL_C:%.*]] = function_ref @_T019c_function_pointers6globalyS2iFTo
   // CHECK:   [[CVT:%.*]] = convert_function [[GLOBAL_C]]
   // CHECK:   apply {{.*}}([[CVT]], [[X]])
   calls(global, x)
 
-  // CHECK:   [[LOCAL_C:%.*]] = function_ref @_T019c_function_pointers0B19_to_swift_functionsySiF5localL_S2iFTo
+  // CHECK:   [[LOCAL_C:%.*]] = function_ref @_T019c_function_pointers0B19_to_swift_functionsyySiF5localL_yS2iFTo
   // CHECK:   [[CVT:%.*]] = convert_function [[LOCAL_C]]
   // CHECK:   apply {{.*}}([[CVT]], [[X]])
   calls(local, x)
 
-  // CHECK:   [[CLOSURE_C:%.*]] = function_ref @_T019c_function_pointers0B19_to_swift_functionsySiFS2icfU_To
+  // CHECK:   [[CLOSURE_C:%.*]] = function_ref @_T019c_function_pointers0B19_to_swift_functionsyySiFS2icfU_To
   // CHECK:   [[CVT:%.*]] = convert_function [[CLOSURE_C]]
   // CHECK:   apply {{.*}}([[CVT]], [[X]])
   calls({ $0 + 1 }, x)
diff --git a/test/SILGen/capture_inout.swift b/test/SILGen/capture_inout.swift
index c6d591a..597528d 100644
--- a/test/SILGen/capture_inout.swift
+++ b/test/SILGen/capture_inout.swift
@@ -2,7 +2,7 @@
 
 typealias Int = Builtin.Int64
 
-// CHECK: sil hidden @_T013capture_inout8localFooyBi64_z1x_tF
+// CHECK: sil hidden @_T013capture_inout8localFoo1xyBi64_z_tF
 // CHECK: bb0([[X_INOUT:%.*]] : @trivial $*Builtin.Int64):
 // CHECK-NOT: alloc_box
 // CHECK:   [[FUNC:%.*]] = function_ref [[CLOSURE:@.*]] : $@convention(thin) (@inout_aliasable Builtin.Int64) -> Builtin.Int64
@@ -16,7 +16,7 @@
   bar()
 }
 
-// CHECK: sil hidden @_T013capture_inout7anonFooyBi64_z1x_tF
+// CHECK: sil hidden @_T013capture_inout7anonFoo1xyBi64_z_tF
 // CHECK: bb0([[X_INOUT:%.*]] : @trivial $*Builtin.Int64):
 // CHECK-NOT: alloc_box
 // CHECK:   [[FUNC:%.*]] = function_ref [[CLOSURE:@.*]] : $@convention(thin) (@inout_aliasable Builtin.Int64) -> Builtin.Int64
diff --git a/test/SILGen/capture_typed_boxes.swift b/test/SILGen/capture_typed_boxes.swift
index 4cdbbf4..8e74b50 100644
--- a/test/SILGen/capture_typed_boxes.swift
+++ b/test/SILGen/capture_typed_boxes.swift
@@ -4,7 +4,7 @@
   var x = x
   return { x }
 }
-// CHECK-LABEL: sil private @_T019capture_typed_boxes3fooSiycSiFSiycfU_ : $@convention(thin) (@guaranteed { var Int }) -> Int {
+// CHECK-LABEL: sil private @_T019capture_typed_boxes3fooySiycSiFSiycfU_ : $@convention(thin) (@guaranteed { var Int }) -> Int {
 // CHECK:       bb0(%0 : @guaranteed ${ var Int }):
 
 func closure(_ f: @escaping (Int) -> Int) -> Int {
@@ -15,7 +15,7 @@
 
   return bar(0)
 }
-// CHECK-LABEL: sil private @_T019capture_typed_boxes7closureS3icF3barL_S2iF : $@convention(thin) (Int, @guaranteed { var @callee_guaranteed (Int) -> Int }) -> Int {
+// CHECK-LABEL: sil private @_T019capture_typed_boxes7closureyS3icF3barL_yS2iF : $@convention(thin) (Int, @guaranteed { var @callee_guaranteed (Int) -> Int }) -> Int {
 // CHECK:       bb0(%0 : @trivial $Int, %1 : @guaranteed ${ var @callee_guaranteed (Int) -> Int }):
 
 func closure_generic<T>(_ f: @escaping (T) -> T, x: T) -> T {
diff --git a/test/SILGen/cf.swift b/test/SILGen/cf.swift
index bbd89bc..4e3af29 100644
--- a/test/SILGen/cf.swift
+++ b/test/SILGen/cf.swift
@@ -4,7 +4,7 @@
 
 import CoreCooling
 
-// CHECK: sil hidden @_T02cf8useEmAllySo16CCMagnetismModelCF :
+// CHECK: sil hidden @_T02cf8useEmAllyySo16CCMagnetismModelCF :
 // CHECK: bb0([[ARG:%.*]] : $CCMagnetismModel):
 func useEmAll(_ model: CCMagnetismModel) {
 // CHECK: function_ref @CCPowerSupplyGetDefault : $@convention(c) () -> @autoreleased Optional<CCPowerSupply>
diff --git a/test/SILGen/cf_members.swift b/test/SILGen/cf_members.swift
index b0cfdb9..52b4b79 100644
--- a/test/SILGen/cf_members.swift
+++ b/test/SILGen/cf_members.swift
@@ -39,7 +39,7 @@
   z = makeMetatype().init(value: x)
 
   // CHECK: [[SELF_META:%.*]] = metatype $@thin Struct1.Type
-  // CHECK: [[THUNK:%.*]] = function_ref @_T0SC7Struct1VABSd5value_tcfCTcTO
+  // CHECK: [[THUNK:%.*]] = function_ref @_T0SC7Struct1V5valueABSd_tcfCTcTO
   // CHECK: [[A:%.*]] = apply [[THUNK]]([[SELF_META]])
   // CHECK: [[BORROWED_A:%.*]] = begin_borrow [[A]]
   // CHECK: [[A_COPY:%.*]] = copy_value [[BORROWED_A]]
@@ -68,7 +68,7 @@
 
   // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
   // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
-  // CHECK: [[THUNK:%.*]] = function_ref [[THUNK_NAME:@_T0SC7Struct1V9translateABSd7radians_tFTcTO]]
+  // CHECK: [[THUNK:%.*]] = function_ref [[THUNK_NAME:@_T0SC7Struct1V9translate7radiansABSd_tFTcTO]]
   // CHECK: [[C:%.*]] = apply [[THUNK]]([[ZVAL]])
   // CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]]
   // CHECK: [[C_COPY:%.*]] = copy_value [[BORROWED_C]]
@@ -105,7 +105,7 @@
 
   // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
   // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]]
-  // CHECK: [[THUNK:%.*]] = function_ref @_T0SC7Struct1V5scaleABSdFTcTO
+  // CHECK: [[THUNK:%.*]] = function_ref @_T0SC7Struct1V5scaleyABSdFTcTO
   // CHECK: [[F:%.*]] = apply [[THUNK]]([[ZVAL]])
   // CHECK: [[BORROWED_F:%.*]] = begin_borrow [[F]]
   // CHECK: [[F_COPY:%.*]] = copy_value [[BORROWED_F]]
@@ -115,7 +115,7 @@
   // CHECK: destroy_value [[F_COPY]]
   // CHECK: end_borrow [[BORROWED_F]] from [[F]]
   z = f(x)
-  // CHECK: [[THUNK:%.*]] = function_ref @_T0SC7Struct1V5scaleABSdFTcTO
+  // CHECK: [[THUNK:%.*]] = function_ref @_T0SC7Struct1V5scaleyABSdFTcTO
   // CHECK: thin_to_thick_function [[THUNK]]
   let g = Struct1.scale
   // CHECK:  [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1
@@ -238,20 +238,20 @@
 }
 // CHECK: } // end sil function '_T010cf_members3foo{{[_0-9a-zA-Z]*}}F'
 
-// CHECK-LABEL: sil shared [serializable] [thunk] @_T0SC7Struct1VABSd5value_tcfCTO
+// CHECK-LABEL: sil shared [serializable] [thunk] @_T0SC7Struct1V5valueABSd_tcfCTO
 // CHECK:       bb0([[X:%.*]] : @trivial $Double, [[SELF:%.*]] : @trivial $@thin Struct1.Type):
 // CHECK:         [[CFUNC:%.*]] = function_ref @IAMStruct1CreateSimple
 // CHECK:         [[RET:%.*]] = apply [[CFUNC]]([[X]])
 // CHECK:         return [[RET]]
 
-// CHECK-LABEL: sil shared [serializable] [thunk] @_T0SC7Struct1V9translateABSd7radians_tFTO
+// CHECK-LABEL: sil shared [serializable] [thunk] @_T0SC7Struct1V9translate7radiansABSd_tFTO
 // CHECK:       bb0([[X:%.*]] : @trivial $Double, [[SELF:%.*]] : @trivial $Struct1):
 // CHECK:         store [[SELF]] to [trivial] [[TMP:%.*]] :
 // CHECK:         [[CFUNC:%.*]] = function_ref @IAMStruct1Rotate
 // CHECK:         [[RET:%.*]] = apply [[CFUNC]]([[TMP]], [[X]])
 // CHECK:         return [[RET]]
 
-// CHECK-LABEL: sil shared [serializable] [thunk] @_T0SC7Struct1V5scaleABSdFTO
+// CHECK-LABEL: sil shared [serializable] [thunk] @_T0SC7Struct1V5scaleyABSdFTO
 // CHECK:       bb0([[X:%.*]] : @trivial $Double, [[SELF:%.*]] : @trivial $Struct1):
 // CHECK:         [[CFUNC:%.*]] = function_ref @IAMStruct1Scale
 // CHECK:         [[RET:%.*]] = apply [[CFUNC]]([[SELF]], [[X]])
@@ -263,12 +263,12 @@
 // CHECK:         [[RET:%.*]] = apply [[CFUNC]]()
 // CHECK:         return [[RET]]
 
-// CHECK-LABEL: sil shared [serializable] [thunk] @_T0SC7Struct1V13selfComesLastySd1x_tFTO
+// CHECK-LABEL: sil shared [serializable] [thunk] @_T0SC7Struct1V13selfComesLast1xySd_tFTO
 // CHECK:       bb0([[X:%.*]] : @trivial $Double, [[SELF:%.*]] : @trivial $Struct1):
 // CHECK:         [[CFUNC:%.*]] = function_ref @IAMStruct1SelfComesLast
 // CHECK:         apply [[CFUNC]]([[X]], [[SELF]])
 
-// CHECK-LABEL: sil shared [serializable] [thunk] @_T0SC7Struct1V14selfComesThirdys5Int32V1a_Sf1bSd1xtFTO
+// CHECK-LABEL: sil shared [serializable] [thunk] @_T0SC7Struct1V14selfComesThird1a1b1xys5Int32V_SfSdtFTO
 // CHECK:       bb0([[X:%.*]] : @trivial $Int32, [[Y:%.*]] : @trivial $Float, [[Z:%.*]] : @trivial $Double, [[SELF:%.*]] : @trivial $Struct1):
 // CHECK:         [[CFUNC:%.*]] = function_ref @IAMStruct1SelfComesThird
 // CHECK:         apply [[CFUNC]]([[X]], [[Y]], [[SELF]], [[Z]])
diff --git a/test/SILGen/class_bound_protocols.swift b/test/SILGen/class_bound_protocols.swift
index 7048696..0b508b4 100644
--- a/test/SILGen/class_bound_protocols.swift
+++ b/test/SILGen/class_bound_protocols.swift
@@ -104,7 +104,7 @@
   // CHECK: return [[PROTO]]
 }
 
-// CHECK-LABEL: sil hidden @_T0s30class_bound_existential_upcasts10ClassBound_psAB_s0E6Bound2p1x_tF :
+// CHECK-LABEL: sil hidden @_T0s30class_bound_existential_upcast1xs10ClassBound_psAC_s0E6Bound2p_tF :
 func class_bound_existential_upcast(x: ClassBound & ClassBound2)
 -> ClassBound {
   return x
@@ -117,9 +117,9 @@
   // CHECK:   destroy_value [[ARG]]
   // CHECK:   return [[PROTO]]
 }
-// CHECK: } // end sil function '_T0s30class_bound_existential_upcasts10ClassBound_psAB_s0E6Bound2p1x_tF'
+// CHECK: } // end sil function '_T0s30class_bound_existential_upcast1xs10ClassBound_psAC_s0E6Bound2p_tF'
 
-// CHECK-LABEL: sil hidden @_T0s41class_bound_to_unbound_existential_upcasts13NotClassBound_ps0hI0_sABp1x_tF :
+// CHECK-LABEL: sil hidden @_T0s41class_bound_to_unbound_existential_upcast1xs13NotClassBound_ps0hI0_sACp_tF :
 // CHECK: bb0([[ARG0:%.*]] : $*NotClassBound, [[ARG1:%.*]] : $ClassBound & NotClassBound):
 // CHECK:   [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
 // CHECK:   [[X_OPENED:%.*]] = open_existential_ref [[BORROWED_ARG1]] : $ClassBound & NotClassBound to [[OPENED_TYPE:\$@opened(.*) ClassBound & NotClassBound]]
@@ -133,7 +133,7 @@
   return x
 }
 
-// CHECK-LABEL: sil hidden @_T0s18class_bound_methodys10ClassBound_p1x_tF :
+// CHECK-LABEL: sil hidden @_T0s18class_bound_method1xys10ClassBound_p_tF :
 // CHECK: bb0([[ARG:%.*]] : $ClassBound):
 func class_bound_method(x: ClassBound) {
   var x = x
@@ -153,7 +153,7 @@
   // CHECK: destroy_value [[XBOX]]
   // CHECK: destroy_value [[ARG]]
 }
-// CHECK: } // end sil function '_T0s18class_bound_methodys10ClassBound_p1x_tF'
+// CHECK: } // end sil function '_T0s18class_bound_method1xys10ClassBound_p_tF'
 
 // rdar://problem/31858378
 struct Value {}
@@ -168,7 +168,7 @@
 
 func takesInOut<T>(_: inout T) {}
 
-// CHECK-LABEL: sil hidden @_T0s27takesInheritsMutatingMethodys0bcD0_pz1x_s5ValueV1ytF : $@convention(thin) (@inout InheritsMutatingMethod, Value) -> () {
+// CHECK-LABEL: sil hidden @_T0s27takesInheritsMutatingMethod1x1yys0bcD0_pz_s5ValueVtF : $@convention(thin) (@inout InheritsMutatingMethod, Value) -> () {
 func takesInheritsMutatingMethod(x: inout InheritsMutatingMethod,
                                  y: Value) {
   // CHECK:      [[X_ADDR:%.*]] = begin_access [modify] [unknown] %0 : $*InheritsMutatingMethod
diff --git a/test/SILGen/class_resilience.swift b/test/SILGen/class_resilience.swift
index e75b0c6..fdf983f 100644
--- a/test/SILGen/class_resilience.swift
+++ b/test/SILGen/class_resilience.swift
@@ -8,7 +8,7 @@
 // Accessing final property of resilient class from different resilience domain
 // through accessor
 
-// CHECK-LABEL: sil @_T016class_resilience20finalPropertyOfOthery010resilient_A022ResilientOutsideParentCF
+// CHECK-LABEL: sil @_T016class_resilience20finalPropertyOfOtheryy010resilient_A022ResilientOutsideParentCF
 // CHECK: function_ref @_T015resilient_class22ResilientOutsideParentC13finalPropertySSvg
 
 public func finalPropertyOfOther(_ other: ResilientOutsideParent) {
@@ -23,7 +23,7 @@
   // CHECK:   return
   public func publicMethodFirst() -> Int? { return nil }
 
-  // CHECK-LABEL: sil [thunk] @_T016class_resilience16MyResilientClassC18publicMethodSecondyyXlFTj : $@convention(method) (@owned AnyObject, @guaranteed MyResilientClass) -> ()
+  // CHECK-LABEL: sil [thunk] @_T016class_resilience16MyResilientClassC18publicMethodSecondyyyXlFTj : $@convention(method) (@owned AnyObject, @guaranteed MyResilientClass) -> ()
   // CHECK:   class_method %1 : $MyResilientClass, #MyResilientClass.publicMethodSecond!1 : (MyResilientClass) -> (AnyObject) -> (), $@convention(method) (@owned AnyObject, @guaranteed MyResilientClass) -> ()
   // CHECK:   return
   public func publicMethodSecond(_ a: AnyObject) {}
@@ -42,7 +42,7 @@
 // Accessing final property of resilient class from my resilience domain
 // directly
 
-// CHECK-LABEL: sil @_T016class_resilience19finalPropertyOfMineyAA16MyResilientClassCF
+// CHECK-LABEL: sil @_T016class_resilience19finalPropertyOfMineyyAA16MyResilientClassCF
 // CHECK: bb0([[ARG:%.*]] : @owned $MyResilientClass):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   ref_element_addr [[BORROWED_ARG]] : $MyResilientClass, #MyResilientClass.finalProperty
@@ -58,7 +58,7 @@
   func newMethod() {}
 }
 
-// CHECK-LABEL: sil @_T016class_resilience19callResilientMethodyAA02MyD8SubclassCF : $@convention(thin) (@owned MyResilientSubclass) -> ()
+// CHECK-LABEL: sil @_T016class_resilience19callResilientMethodyyAA02MyD8SubclassCF : $@convention(thin) (@owned MyResilientSubclass) -> ()
 public func callResilientMethod(_ s: MyResilientSubclass) {
 // CHECK:   class_method {{.*}} : $MyResilientSubclass, #MyResilientSubclass.publicMethodFirst!1
   _ = s.publicMethodFirst()
@@ -67,18 +67,18 @@
 // CHECK:   return
 }
 
-// CHECK-LABEL: sil [serialized] @_T016class_resilience29callResilientMethodInlineableyAA02MyD8SubclassCF : $@convention(thin) (@owned MyResilientSubclass) -> ()
+// CHECK-LABEL: sil [serialized] @_T016class_resilience29callResilientMethodInlineableyyAA02MyD8SubclassCF : $@convention(thin) (@owned MyResilientSubclass) -> ()
 @_inlineable public func callResilientMethodInlineable(_ s: MyResilientSubclass) {
 // CHECK:   [[FN:%.*]] = function_ref @_T016class_resilience19MyResilientSubclassC17publicMethodFirstSiyFTj : $@convention(method) (@guaranteed MyResilientSubclass) -> Int
   _ = s.publicMethodFirst()
-  // CHECK:   [[FN:%.*]] = function_ref @_T016class_resilience16MyResilientClassC18publicMethodSecondyyXlFTj : $@convention(method) (@owned AnyObject, @guaranteed MyResilientClass) -> ()
+  // CHECK:   [[FN:%.*]] = function_ref @_T016class_resilience16MyResilientClassC18publicMethodSecondyyyXlFTj : $@convention(method) (@owned AnyObject, @guaranteed MyResilientClass) -> ()
   // CHECK:   [[CONVERTED:%.*]] = convert_function [[FN]] : $@convention(method) (@owned AnyObject, @guaranteed MyResilientClass) -> () to $@convention(method) (@owned Optional<AnyObject>, @guaranteed MyResilientSubclass) -> ()
   s.publicMethodSecond(nil)
 
   // CHECK:   function_ref @_T016class_resilience19MyResilientSubclassC17publicMethodFirstSiyFTc
   _ = s.publicMethodFirst
 
-  // CHECK:   function_ref @_T016class_resilience19MyResilientSubclassC18publicMethodSecondyyXlSgFTc
+  // CHECK:   function_ref @_T016class_resilience19MyResilientSubclassC18publicMethodSecondyyyXlSgFTc
   _ = s.publicMethodSecond
 // CHECK:   return
 }
@@ -87,8 +87,8 @@
 // CHECK:     function_ref @_T016class_resilience19MyResilientSubclassC17publicMethodFirstSiyFTj
 // CHECK:     return
 
-// CHECK-LABEL: sil shared [serializable] [thunk] @_T016class_resilience19MyResilientSubclassC18publicMethodSecondyyXlSgFTc : $@convention(thin) (@owned MyResilientSubclass) -> @owned @callee_guaranteed (@owned Optional<AnyObject>) -> ()
-// CHECK:     function_ref @_T016class_resilience16MyResilientClassC18publicMethodSecondyyXlFTj : $@convention(method) (@owned AnyObject, @guaranteed MyResilientClass) -> ()
+// CHECK-LABEL: sil shared [serializable] [thunk] @_T016class_resilience19MyResilientSubclassC18publicMethodSecondyyyXlSgFTc : $@convention(thin) (@owned MyResilientSubclass) -> @owned @callee_guaranteed (@owned Optional<AnyObject>) -> ()
+// CHECK:     function_ref @_T016class_resilience16MyResilientClassC18publicMethodSecondyyyXlFTj : $@convention(method) (@owned AnyObject, @guaranteed MyResilientClass) -> ()
 // CHECK:     return
 
 // Note: no entries for [inherited] methods
diff --git a/test/SILGen/closure_self_recursion.swift b/test/SILGen/closure_self_recursion.swift
index 981273e..e7e28ea 100644
--- a/test/SILGen/closure_self_recursion.swift
+++ b/test/SILGen/closure_self_recursion.swift
@@ -9,8 +9,8 @@
   return { recur() } // expected-warning {{attempting to access 'recur' within its own getter}}
 }
 
-// CHECK-LABEL: sil private @_T03foo12recur_harderyycyyccvgyycyyccfU_
+// CHECK-LABEL: sil private @_T03foo12recur_harderyyycyyccvgyycyyccfU_
 var recur_harder : (() -> ()) -> (() -> ()) {
-  // CHECK-LABEL: function_ref @_T03foo12recur_harderyycyyccvg
+  // CHECK-LABEL: function_ref @_T03foo12recur_harderyyycyyccvg
   return { f in recur_harder(f) } // expected-warning {{attempting to access 'recur_harder' within its own getter}}
 }
diff --git a/test/SILGen/closures.swift b/test/SILGen/closures.swift
index 1d67d6b..67d2f51 100644
--- a/test/SILGen/closures.swift
+++ b/test/SILGen/closures.swift
@@ -1,5 +1,5 @@
 // RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s
-// RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -parse-as-library -emit-silgen -enable-guaranteed-closure-contexts %s | %FileCheck %s --check-prefix=GUARANTEED
+// RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -parse-as-library -emit-silgen  %s | %FileCheck %s --check-prefix=GUARANTEED
 
 import Swift
 
@@ -25,7 +25,7 @@
   return f
 }
 
-// CHECK-LABEL: sil hidden @_T08closures17read_only_captureS2iF : $@convention(thin) (Int) -> Int {
+// CHECK-LABEL: sil hidden @_T08closures17read_only_captureyS2iF : $@convention(thin) (Int) -> Int {
 func read_only_capture(_ x: Int) -> Int {
   var x = x
   // CHECK: bb0([[X:%[0-9]+]] : @trivial $Int):
@@ -48,7 +48,7 @@
   // CHECK:   destroy_value [[XBOX]]
   // CHECK:   return [[RET]]
 }
-// CHECK:   } // end sil function '_T08closures17read_only_captureS2iF'
+// CHECK:   } // end sil function '_T08closures17read_only_captureyS2iF'
 
 // CHECK: sil private @[[CAP_NAME]]
 // CHECK: bb0([[XBOX:%[0-9]+]] : @guaranteed ${ var Int }):
@@ -59,7 +59,7 @@
 // } // end sil function '[[CAP_NAME]]'
 
 // SEMANTIC ARC TODO: This is a place where we have again project_box too early.
-// CHECK-LABEL: sil hidden @_T08closures16write_to_captureS2iF : $@convention(thin) (Int) -> Int {
+// CHECK-LABEL: sil hidden @_T08closures16write_to_captureyS2iF : $@convention(thin) (Int) -> Int {
 func write_to_capture(_ x: Int) -> Int {
   var x = x
   // CHECK: bb0([[X:%[0-9]+]] : @trivial $Int):
@@ -92,7 +92,7 @@
   // CHECK:   return [[RET]]
   return x2
 }
-// CHECK:  } // end sil function '_T08closures16write_to_captureS2iF'
+// CHECK:  } // end sil function '_T08closures16write_to_captureyS2iF'
 
 // CHECK: sil private @[[SCRIB_NAME]]
 // CHECK: bb0([[XBOX:%[0-9]+]] : @guaranteed ${ var Int }):
@@ -118,7 +118,7 @@
   // CHECK: return [[RET]]
 }
 
-// CHECK-LABEL: sil hidden @_T08closures18capture_local_funcSiycycSiF : $@convention(thin) (Int) -> @owned @callee_guaranteed () -> @owned @callee_guaranteed () -> Int {
+// CHECK-LABEL: sil hidden @_T08closures18capture_local_funcySiycycSiF : $@convention(thin) (Int) -> @owned @callee_guaranteed () -> @owned @callee_guaranteed () -> Int {
 func capture_local_func(_ x: Int) -> () -> () -> Int {
   // CHECK: bb0([[ARG:%.*]] : @trivial $Int):
   var x = x
@@ -129,7 +129,7 @@
   func aleph() -> Int { return x }
 
   func beth() -> () -> Int { return aleph }
-  // CHECK: [[BETH_REF:%.*]] = function_ref @[[BETH_NAME:_T08closures18capture_local_funcSiycycSiF4bethL_SiycyF]] : $@convention(thin) (@guaranteed { var Int }) -> @owned @callee_guaranteed () -> Int
+  // CHECK: [[BETH_REF:%.*]] = function_ref @[[BETH_NAME:_T08closures18capture_local_funcySiycycSiF4bethL_SiycyF]] : $@convention(thin) (@guaranteed { var Int }) -> @owned @callee_guaranteed () -> Int
   // CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]]
   // SEMANTIC ARC TODO: This is incorrect. This should be a project_box from XBOX_COPY.
   // CHECK: mark_function_escape [[XBOX_PB]]
@@ -139,9 +139,9 @@
   // CHECK: destroy_value [[XBOX]]
   // CHECK: return [[BETH_CLOSURE]]
 }
-// CHECK: } // end sil function '_T08closures18capture_local_funcSiycycSiF'
+// CHECK: } // end sil function '_T08closures18capture_local_funcySiycycSiF'
 
-// CHECK: sil private @[[ALEPH_NAME:_T08closures18capture_local_funcSiycycSiF5alephL_SiyF]] : $@convention(thin) (@guaranteed { var Int }) -> Int {
+// CHECK: sil private @[[ALEPH_NAME:_T08closures18capture_local_funcySiycycSiF5alephL_SiyF]] : $@convention(thin) (@guaranteed { var Int }) -> Int {
 // CHECK: bb0([[XBOX:%[0-9]+]] : @guaranteed ${ var Int }):
 
 // CHECK: sil private @[[BETH_NAME]] : $@convention(thin) (@guaranteed { var Int }) -> @owned @callee_guaranteed () -> Int {
@@ -291,13 +291,13 @@
   takesSomeClassGenerator({ x })
 }
 
-// CHECK-LABEL: sil private @_T08closures20generateWithConstantyAA17SomeSpecificClassCFAA0eG0CycfU_ : $@convention(thin) (@guaranteed SomeSpecificClass) -> @owned SomeClass {
+// CHECK-LABEL: sil private @_T08closures20generateWithConstantyyAA17SomeSpecificClassCFAA0eG0CycfU_ : $@convention(thin) (@guaranteed SomeSpecificClass) -> @owned SomeClass {
 // CHECK: bb0([[T0:%.*]] : @guaranteed $SomeSpecificClass):
 // CHECK:   debug_value [[T0]] : $SomeSpecificClass, let, name "x", argno 1
 // CHECK:   [[T0_COPY:%.*]] = copy_value [[T0]]
 // CHECK:   [[T0_COPY_CASTED:%.*]] = upcast [[T0_COPY]] : $SomeSpecificClass to $SomeClass
 // CHECK:   return [[T0_COPY_CASTED]]
-// CHECK: } // end sil function '_T08closures20generateWithConstantyAA17SomeSpecificClassCFAA0eG0CycfU_'
+// CHECK: } // end sil function '_T08closures20generateWithConstantyyAA17SomeSpecificClassCFAA0eG0CycfU_'
 
 
 // Check the annoying case of capturing 'self' in a derived class 'init'
@@ -616,7 +616,7 @@
     // CHECK:   [[CVT:%.*]] = convert_function [[PA]]
     // CHECK:   [[REABSTRACT_PA:%.*]] = partial_apply [callee_guaranteed] {{.*}}([[CVT]])
     // CHECK:   [[REABSTRACT_CVT:%.*]] = convert_function [[REABSTRACT_PA]]    
-    // CHECK:   [[TRY_APPLY_AUTOCLOSURE:%.*]] = function_ref @_T0s2qqoixxSg_xyKXKtKlF : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @owned @noescape @callee_guaranteed () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error)
+    // CHECK:   [[TRY_APPLY_AUTOCLOSURE:%.*]] = function_ref @_T0s2qqoiyxxSg_xyKXKtKlF : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @owned @noescape @callee_guaranteed () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error)
     // CHECK:   try_apply [[TRY_APPLY_AUTOCLOSURE]]<()>({{.*}}, {{.*}}, [[REABSTRACT_CVT]]) : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @owned @noescape @callee_guaranteed () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error), normal [[NORMAL_BB:bb1]], error [[ERROR_BB:bb2]]
     // CHECK: [[NORMAL_BB]]{{.*}}
     // CHECK: } // end sil function '[[INNER_FUNC_1]]'
@@ -648,7 +648,7 @@
     // CHECK:   [[CVT:%.*]] = convert_function [[PA]] : $@callee_guaranteed () -> @error Error to $@noescape @callee_guaranteed () -> @error Error
     // CHECK:   [[REABSTRACT_PA:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[CVT]]) : $@convention(thin) (@guaranteed @noescape @callee_guaranteed () -> @error Error) -> (@out (), @error Error)
     // CHECK:   [[REABSTRACT_CVT:%.*]] = convert_function [[REABSTRACT_PA]]
-    // CHECK:   [[TRY_APPLY_FUNC:%.*]] = function_ref @_T0s2qqoixxSg_xyKXKtKlF : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @owned @noescape @callee_guaranteed () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error)
+    // CHECK:   [[TRY_APPLY_FUNC:%.*]] = function_ref @_T0s2qqoiyxxSg_xyKXKtKlF : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @owned @noescape @callee_guaranteed () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error)
     // CHECK:   try_apply [[TRY_APPLY_FUNC]]<()>({{.*}}, {{.*}}, [[REABSTRACT_CVT]]) : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @owned @noescape @callee_guaranteed () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error), normal [[NORMAL_BB:bb1]], error [[ERROR_BB:bb2]]
     // CHECK: [[NORMAL_BB]]{{.*}}
     // CHECK: } // end sil function '[[INNER_FUNC_1]]'
@@ -790,4 +790,4 @@
 }
 
 //   DI will turn this into a direct capture of the specific stored property.
-// CHECK-LABEL: sil hidden @_T08closures16r29810997_helperS3icF : $@convention(thin) (@owned @noescape @callee_guaranteed (Int) -> Int) -> Int
+// CHECK-LABEL: sil hidden @_T08closures16r29810997_helperyS3icF : $@convention(thin) (@owned @noescape @callee_guaranteed (Int) -> Int) -> Int
diff --git a/test/SILGen/closures_callee_guaranteed.swift b/test/SILGen/closures_callee_guaranteed.swift
index bc716f9..d1389aa 100644
--- a/test/SILGen/closures_callee_guaranteed.swift
+++ b/test/SILGen/closures_callee_guaranteed.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -parse-as-library -enable-guaranteed-closure-contexts -emit-silgen %s | %FileCheck %s
+// RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -parse-as-library  -emit-silgen %s | %FileCheck %s
 import Swift
 
 // CHECK-LABEL: sil @{{.*}}apply{{.*}} : $@convention(thin) (@owned @noescape @callee_guaranteed () -> Int)
diff --git a/test/SILGen/collection_subtype_downcast.swift b/test/SILGen/collection_subtype_downcast.swift
index fead91f..1b8be20 100644
--- a/test/SILGen/collection_subtype_downcast.swift
+++ b/test/SILGen/collection_subtype_downcast.swift
@@ -2,13 +2,13 @@
 
 struct S { var x, y: Int }
 
-// CHECK-LABEL: sil hidden @_T027collection_subtype_downcast06array_C0SayAA1SVGSgSayypG0D0_tF :
+// CHECK-LABEL: sil hidden @_T027collection_subtype_downcast06array_C00D0SayAA1SVGSgSayypG_tF :
 // CHECK:    bb0([[ARG:%.*]] : @owned $Array<Any>):
 // CHECK-NEXT: debug_value [[ARG]]
 // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
 // CHECK-NEXT: // function_ref
-// CHECK-NEXT: [[FN:%.*]] = function_ref @_T0s21_arrayConditionalCastSayq_GSgSayxGr0_lF
+// CHECK-NEXT: [[FN:%.*]] = function_ref @_T0s21_arrayConditionalCastySayq_GSgSayxGr0_lF
 // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<Any, S>([[ARG_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1> (@owned Array<τ_0_0>) -> @owned Optional<Array<τ_0_1>>
 // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK-NEXT: destroy_value [[ARG]]
@@ -27,13 +27,13 @@
 }
 
 // FIXME: This entrypoint name should not be bridging-specific
-// CHECK-LABEL:      sil hidden @_T027collection_subtype_downcast05dict_C0s10DictionaryVyAA1SVSiGSgADyAFypG0D0_tF :
+// CHECK-LABEL:      sil hidden @_T027collection_subtype_downcast05dict_C00D0s10DictionaryVyAA1SVSiGSgAEyAGypG_tF :
 // CHECK:    bb0([[ARG:%.*]] : @owned $Dictionary<S, Any>):
 // CHECK-NEXT: debug_value [[ARG]]
 // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
 // CHECK-NEXT: // function_ref
-// CHECK-NEXT: [[FN:%.*]] = function_ref @_T0s30_dictionaryDownCastConditionals10DictionaryVyq0_q1_GSgACyxq_Gs8HashableRzsAGR0_r2_lF
+// CHECK-NEXT: [[FN:%.*]] = function_ref @_T0s30_dictionaryDownCastConditionalys10DictionaryVyq0_q1_GSgACyxq_Gs8HashableRzsAGR0_r2_lF
 // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<S, Any, S, Int>([[ARG_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@owned Dictionary<τ_0_0, τ_0_1>) -> @owned Optional<Dictionary<τ_0_2, τ_0_3>>
 // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK-NEXT: destroy_value [[ARG]]
diff --git a/test/SILGen/collection_subtype_upcast.swift b/test/SILGen/collection_subtype_upcast.swift
index a6fa9fe..549c70f 100644
--- a/test/SILGen/collection_subtype_upcast.swift
+++ b/test/SILGen/collection_subtype_upcast.swift
@@ -2,13 +2,13 @@
 
 struct S { var x, y: Int }
 
-// CHECK-LABEL: sil hidden @_T025collection_subtype_upcast06array_C0SayypGSayAA1SVG0D0_tF :
+// CHECK-LABEL: sil hidden @_T025collection_subtype_upcast06array_C00D0SayypGSayAA1SVG_tF :
 // CHECK:    bb0([[ARG:%.*]] : @owned $Array<S>):
 // CHECK-NEXT: debug_value [[ARG]]
 // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
 // CHECK-NEXT: // function_ref
-// CHECK-NEXT: [[FN:%.*]] = function_ref @_T0s15_arrayForceCastSayq_GSayxGr0_lF
+// CHECK-NEXT: [[FN:%.*]] = function_ref @_T0s15_arrayForceCastySayq_GSayxGr0_lF
 // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<S, Any>([[ARG_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1> (@owned Array<τ_0_0>) -> @owned Array<τ_0_1>
 // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK-NEXT: destroy_value [[ARG]]
@@ -27,13 +27,13 @@
 }
 
 // FIXME: This entrypoint name should not be bridging-specific
-// CHECK-LABEL:      sil hidden @_T025collection_subtype_upcast05dict_C0s10DictionaryVyAA1SVypGADyAFSiG0D0_tF :
+// CHECK-LABEL:      sil hidden @_T025collection_subtype_upcast05dict_C00D0s10DictionaryVyAA1SVypGAEyAGSiG_tF :
 // CHECK:    bb0([[ARG:%.*]] : @owned $Dictionary<S, Int>):
 // CHECK-NEXT: debug_value [[ARG]]
 // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
 // CHECK-NEXT: // function_ref
-// CHECK-NEXT: [[FN:%.*]] = function_ref @_T0s17_dictionaryUpCasts10DictionaryVyq0_q1_GACyxq_Gs8HashableRzsAFR0_r2_lF
+// CHECK-NEXT: [[FN:%.*]] = function_ref @_T0s17_dictionaryUpCastys10DictionaryVyq0_q1_GACyxq_Gs8HashableRzsAFR0_r2_lF
 // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<S, Int, S, Any>([[ARG_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@owned Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3>
 // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK-NEXT: destroy_value [[ARG]]
diff --git a/test/SILGen/conditional_conformance.swift b/test/SILGen/conditional_conformance.swift
index 2e6c912..29aafc9 100644
--- a/test/SILGen/conditional_conformance.swift
+++ b/test/SILGen/conditional_conformance.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -enable-experimental-conditional-conformances -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 protocol P1 {
   func normal()
@@ -18,7 +18,7 @@
 }
 // CHECK-LABEL: sil_witness_table hidden <A where A : P2> Conformance<A>: P1 module conditional_conformance {
 // CHECK-NEXT:    method #P1.normal!1: <Self where Self : P1> (Self) -> () -> () : @_T023conditional_conformance11ConformanceVyxGAA2P1A2A2P2RzlAaEP6normalyyFTW	// protocol witness for P1.normal() in conformance <A> Conformance<A>
-// CHECK-NEXT:    method #P1.generic!1: <Self where Self : P1><T where T : P3> (Self) -> (T) -> () : @_T023conditional_conformance11ConformanceVyxGAA2P1A2A2P2RzlAaEP7genericyqd__AA2P3Rd__lFTW	// protocol witness for P1.generic<A>(_:) in conformance <A> Conformance<A>
+// CHECK-NEXT:    method #P1.generic!1: <Self where Self : P1><T where T : P3> (Self) -> (T) -> () : @_T023conditional_conformance11ConformanceVyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW	// protocol witness for P1.generic<A>(_:) in conformance <A> Conformance<A>
 // CHECK-NEXT:    conditional_conformance (A: P2): dependent
 // CHECK-NEXT:  }
 
@@ -29,7 +29,7 @@
 }
 // CHECK-LABEL: sil_witness_table hidden <A where A : P4, A.AT : P2> ConformanceAssoc<A>: P1 module conditional_conformance {
 // CHECK-NEXT:    method #P1.normal!1: <Self where Self : P1> (Self) -> () -> () : @_T023conditional_conformance16ConformanceAssocVyxGAA2P1A2A2P4RzAA2P22ATRpzlAaEP6normalyyFTW // protocol witness for P1.normal() in conformance <A> ConformanceAssoc<A>
-// CHECK-NEXT:    method #P1.generic!1: <Self where Self : P1><T where T : P3> (Self) -> (T) -> () : @_T023conditional_conformance16ConformanceAssocVyxGAA2P1A2A2P4RzAA2P22ATRpzlAaEP7genericyqd__AA2P3Rd__lFTW // protocol witness for P1.generic<A>(_:) in conformance <A> ConformanceAssoc<A>
+// CHECK-NEXT:    method #P1.generic!1: <Self where Self : P1><T where T : P3> (Self) -> (T) -> () : @_T023conditional_conformance16ConformanceAssocVyxGAA2P1A2A2P4RzAA2P22ATRpzlAaEP7genericyyqd__AA2P3Rd__lFTW // protocol witness for P1.generic<A>(_:) in conformance <A> ConformanceAssoc<A>
 // CHECK-NEXT:    conditional_conformance (A: P4): dependent
 // CHECK-NEXT:    conditional_conformance (A.AT: P2): dependent
 // CHECK-NEXT:  }
@@ -71,7 +71,7 @@
 }
 // CHECK-LABEL: sil_witness_table hidden <A where A : P2> Base<A>: P1 module conditional_conformance {
 // CHECK-NEXT:  method #P1.normal!1: <Self where Self : P1> (Self) -> () -> () : @_T023conditional_conformance4BaseCyxGAA2P1A2A2P2RzlAaEP6normalyyFTW	// protocol witness for P1.normal() in conformance <A> Base<A>
-// CHECK-NEXT:    method #P1.generic!1: <Self where Self : P1><T where T : P3> (Self) -> (T) -> () : @_T023conditional_conformance4BaseCyxGAA2P1A2A2P2RzlAaEP7genericyqd__AA2P3Rd__lFTW	// protocol witness for P1.generic<A>(_:) in conformance <A> Base<A>
+// CHECK-NEXT:    method #P1.generic!1: <Self where Self : P1><T where T : P3> (Self) -> (T) -> () : @_T023conditional_conformance4BaseCyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW	// protocol witness for P1.generic<A>(_:) in conformance <A> Base<A>
 // CHECK-NEXT:    conditional_conformance (A: P2): dependent
 // CHECK-NEXT:  }
 
diff --git a/test/SILGen/constrained_extensions.swift b/test/SILGen/constrained_extensions.swift
index 31fdd9c..4086a5c 100644
--- a/test/SILGen/constrained_extensions.swift
+++ b/test/SILGen/constrained_extensions.swift
@@ -3,7 +3,7 @@
 // RUN: %target-swift-frontend -emit-ir -primary-file %s > /dev/null
 
 extension Array where Element == Int {
-  // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlESaySiGyt1x_tcfC : $@convention(method) (@thin Array<Int>.Type) -> @owned Array<Int>
+  // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE1xSaySiGyt_tcfC : $@convention(method) (@thin Array<Int>.Type) -> @owned Array<Int>
   public init(x: ()) {
     self.init()
   }
@@ -27,7 +27,7 @@
     return instanceProperty
   }
 
-  // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE14instanceMethodS2i1e_tF : $@convention(method) (Int, @guaranteed Array<Int>) -> Int
+  // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE14instanceMethod1eS2i_tF : $@convention(method) (Int, @guaranteed Array<Int>) -> Int
   public func instanceMethod(e: Element) -> Element {
     return e
   }
@@ -42,13 +42,13 @@
     return staticProperty
   }
 
-  // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE12staticMethodS2iSg1e_tFZfA_ : $@convention(thin) () -> Optional<Int>
-  // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE12staticMethodS2iSg1e_tFZ : $@convention(method) (Optional<Int>, @thin Array<Int>.Type) -> Int
+  // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE12staticMethod1eS2iSg_tFZfA_ : $@convention(thin) () -> Optional<Int>
+  // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE12staticMethod1eS2iSg_tFZ : $@convention(method) (Optional<Int>, @thin Array<Int>.Type) -> Int
   public static func staticMethod(e: Element? = nil) -> Element {
     return e!
   }
 
-  // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlESiyt_tcig : $@convention(method) (@guaranteed Array<Int>) -> Int
+  // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlEySiyt_tcig : $@convention(method) (@guaranteed Array<Int>) -> Int
   public subscript(i: ()) -> Element {
     return self[0]
   }
@@ -64,7 +64,7 @@
 }
 
 extension Dictionary where Key == Int {
-  // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszrlEABySiq_Gyt1x_tcfC : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @owned Dictionary<Int, Value> {
+  // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszrlE1xABySiq_Gyt_tcfC : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @owned Dictionary<Int, Value> {
   public init(x: ()) {
     self.init()
   }
@@ -87,7 +87,7 @@
     return instanceProperty
   }
 
-  // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszrlE14instanceMethodq_q_1v_tF : $@convention(method) <Key, Value where Key == Int> (@in Value, @guaranteed Dictionary<Int, Value>) -> @out Value
+  // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszrlE14instanceMethod1vq_q__tF : $@convention(method) <Key, Value where Key == Int> (@in Value, @guaranteed Dictionary<Int, Value>) -> @out Value
   public func instanceMethod(v: Value) -> Value {
     return v
   }
@@ -102,9 +102,9 @@
     return 0
   }
 
-  // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszrlE12staticMethodq_SiSg1k_q_Sg1vtFZfA_ : $@convention(thin) <Key, Value where Key == Int> () -> Optional<Int>
-  // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszrlE12staticMethodq_SiSg1k_q_Sg1vtFZfA0_ : $@convention(thin) <Key, Value where Key == Int> () -> @out Optional<Value>
-  // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszrlE12staticMethodq_SiSg1k_q_Sg1vtFZ : $@convention(method) <Key, Value where Key == Int> (Optional<Int>, @in Optional<Value>, @thin Dictionary<Int, Value>.Type) -> @out Value
+  // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszrlE12staticMethod1k1vq_SiSg_q_SgtFZfA_ : $@convention(thin) <Key, Value where Key == Int> () -> Optional<Int>
+  // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszrlE12staticMethod1k1vq_SiSg_q_SgtFZfA0_ : $@convention(thin) <Key, Value where Key == Int> () -> @out Optional<Value>
+  // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszrlE12staticMethod1k1vq_SiSg_q_SgtFZ : $@convention(method) <Key, Value where Key == Int> (Optional<Int>, @in Optional<Value>, @thin Dictionary<Int, Value>.Type) -> @out Value
   public static func staticMethod(k: Key? = nil, v: Value? = nil) -> Value {
     return v!
   }
@@ -119,7 +119,7 @@
     return Dictionary(x: ()).instanceMethod()
   }
 
-  // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszrlEq_yt_tcig : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value
+  // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszrlEyq_yt_tcig : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value
   public subscript(i: ()) -> Value {
     return self[0]!
   }
@@ -153,19 +153,19 @@
     set {}
   }
 
-  // CHECK-LABEL: sil @_T022constrained_extensions12GenericClassCAAytRs_rlExyt_tcig : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> @out X
-  // CHECK-LABEL: sil @_T022constrained_extensions12GenericClassCAAytRs_rlExyt_tcis : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> ()
-  // CHECK-LABEL: sil shared [transparent] [serialized] @_T022constrained_extensions12GenericClassCAAytRs_rlExyt_tcimytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> ()
-  // CHECK-LABEL: sil [transparent] [serialized] @_T022constrained_extensions12GenericClassCAAytRs_rlExyt_tcim : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed GenericClass<X, ()>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
+  // CHECK-LABEL: sil @_T022constrained_extensions12GenericClassCAAytRs_rlEyxyt_tcig : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> @out X
+  // CHECK-LABEL: sil @_T022constrained_extensions12GenericClassCAAytRs_rlEyxyt_tcis : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> ()
+  // CHECK-LABEL: sil shared [transparent] [serialized] @_T022constrained_extensions12GenericClassCAAytRs_rlEyxyt_tcimytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> ()
+  // CHECK-LABEL: sil [transparent] [serialized] @_T022constrained_extensions12GenericClassCAAytRs_rlEyxyt_tcim : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed GenericClass<X, ()>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
   public subscript(_: Y) -> X {
     get { while true {} }
     set {}
   }
 
-  // CHECK-LABEL: sil @_T022constrained_extensions12GenericClassCAAytRs_rlEyxcig : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> ()
-  // CHECK-LABEL: sil @_T022constrained_extensions12GenericClassCAAytRs_rlEyxcis : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> ()
-  // CHECK-LABEL: sil shared [transparent] [serialized] @_T022constrained_extensions12GenericClassCAAytRs_rlEyxcimytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> ()
-  // CHECK-LABEL: sil [transparent] [serialized] @_T022constrained_extensions12GenericClassCAAytRs_rlEyxcim : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in X, @guaranteed GenericClass<X, ()>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
+  // CHECK-LABEL: sil @_T022constrained_extensions12GenericClassCAAytRs_rlEyyxcig : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> ()
+  // CHECK-LABEL: sil @_T022constrained_extensions12GenericClassCAAytRs_rlEyyxcis : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> ()
+  // CHECK-LABEL: sil shared [transparent] [serialized] @_T022constrained_extensions12GenericClassCAAytRs_rlEyyxcimytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> ()
+  // CHECK-LABEL: sil [transparent] [serialized] @_T022constrained_extensions12GenericClassCAAytRs_rlEyyxcim : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in X, @guaranteed GenericClass<X, ()>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
   public subscript(_: X) -> Y {
     get { while true {} }
     set {}
@@ -180,7 +180,7 @@
 }
 
 extension AnythingGoes where T : VeryConstrained {
-  // CHECK-LABEL: sil hidden @_T022constrained_extensions12AnythingGoesVA2A15VeryConstrainedRzlEACyxGyt13fromExtension_tcfC : $@convention(method) <T where T : VeryConstrained> (@thin AnythingGoes<T>.Type) -> @out AnythingGoes<T> {
+  // CHECK-LABEL: sil hidden @_T022constrained_extensions12AnythingGoesVA2A15VeryConstrainedRzlE13fromExtensionACyxGyt_tcfC : $@convention(method) <T where T : VeryConstrained> (@thin AnythingGoes<T>.Type) -> @out AnythingGoes<T> {
 
   // CHECK: [[INIT:%.*]] = function_ref @_T022constrained_extensions12AnythingGoesV13meaningOfLifexSgvpfi : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0>
   // CHECK: [[RESULT:%.*]] = alloc_stack $Optional<T>
@@ -194,8 +194,8 @@
     // CHECK-LABEL: sil hidden [transparent] @_T0Sa22constrained_extensionsSiRszlE6NestedV1eSiSgvpfi : $@convention(thin) () -> Optional<Int>
     var e: Element? = nil
 
-    // CHECK-LABEL: sil hidden @_T0Sa22constrained_extensionsSiRszlE6NestedV10hasDefaultySiSg1e_tFfA_ : $@convention(thin) () -> Optional<Int>
-    // CHECK-LABEL: sil hidden @_T0Sa22constrained_extensionsSiRszlE6NestedV10hasDefaultySiSg1e_tF : $@convention(method) (Optional<Int>, @inout Array<Int>.Nested) -> ()
+    // CHECK-LABEL: sil hidden @_T0Sa22constrained_extensionsSiRszlE6NestedV10hasDefault1eySiSg_tFfA_ : $@convention(thin) () -> Optional<Int>
+    // CHECK-LABEL: sil hidden @_T0Sa22constrained_extensionsSiRszlE6NestedV10hasDefault1eySiSg_tF : $@convention(method) (Optional<Int>, @inout Array<Int>.Nested) -> ()
     mutating func hasDefault(e: Element? = nil) {
       self.e = e
     }
diff --git a/test/SILGen/default_arguments.swift b/test/SILGen/default_arguments.swift
index 8cf74c8..41e7f26 100644
--- a/test/SILGen/default_arguments.swift
+++ b/test/SILGen/default_arguments.swift
@@ -9,19 +9,19 @@
 // CHECK:         string_literal utf16 "default_arguments"
 
 // Default argument for first parameter.
-// CHECK-LABEL: sil hidden @_T017default_arguments7defarg1ySi1i_Sd1dSS1stFfA_ : $@convention(thin) () -> Int
+// CHECK-LABEL: sil hidden @_T017default_arguments7defarg11i1d1sySi_SdSStFfA_ : $@convention(thin) () -> Int
 // CHECK: [[INT:%[0-9]+]] = metatype $@thin Int.Type
 // CHECK: [[LIT:%[0-9]+]] = integer_literal $Builtin.Int2048, 17
-// CHECK: [[CVT:%[0-9]+]] = function_ref @_T0S2i{{[_0-9a-zA-Z]*}}fC
+// CHECK: [[CVT:%[0-9]+]] = function_ref @_T0Si22_builtinIntegerLiteralSiBi{{[_0-9]*}}__tcfC
 // CHECK: [[RESULT:%[0-9]+]] = apply [[CVT]]([[LIT]], [[INT]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int
 // CHECK: return [[RESULT]] : $Int
 
 // Default argument for third parameter.
-// CHECK-LABEL: sil hidden @_T017default_arguments7defarg1ySi1i_Sd1dSS1stFfA1_ : $@convention(thin) () -> @owned String
+// CHECK-LABEL: sil hidden @_T017default_arguments7defarg11i1d1sySi_SdSStFfA1_ : $@convention(thin) () -> @owned String
 // CHECK: [[LIT:%[0-9]+]] = string_literal utf8 "Hello"
 // CHECK: [[LEN:%[0-9]+]] = integer_literal $Builtin.Word, 5
 // CHECK: [[STRING:%[0-9]+]] = metatype $@thin String.Type
-// CHECK: [[CVT:%[0-9]+]] = function_ref @_T0S2S{{[_0-9a-zA-Z]*}}fC
+// CHECK: [[CVT:%[0-9]+]] = function_ref @_T0SS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC
 // CHECK: [[RESULT:%[0-9]+]] = apply [[CVT]]([[LIT]], [[LEN]], {{[^,]+}}, [[STRING]]) : $@convention(method)
 // CHECK: return [[RESULT]] : $String
 func defarg1(i: Int = 17, d: Double, s: String = "Hello") { }
@@ -30,7 +30,7 @@
 func testDefaultArg1() {
   // CHECK: [[FLOAT64:%[0-9]+]] = metatype $@thin Double.Type
   // CHECK: [[FLOATLIT:%[0-9]+]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0x4009000000000000|0x4000C800000000000000}}
-  // CHECK: [[LITFN:%[0-9]+]] = function_ref @_T0S2d{{[_0-9a-zA-Z]*}}fC
+  // CHECK: [[LITFN:%[0-9]+]] = function_ref @_T0Sd20_builtinFloatLiteralSdBf{{[_0-9]*}}__tcfC
   // CHECK: [[FLOATVAL:%[0-9]+]] = apply [[LITFN]]([[FLOATLIT]], [[FLOAT64]])
   // CHECK: [[DEF0FN:%[0-9]+]] = function_ref @_T017default_arguments7defarg1{{.*}}A_
   // CHECK: [[DEF0:%[0-9]+]] = apply [[DEF0FN]]()
@@ -47,7 +47,7 @@
 func testDefaultArg2() {
 // CHECK:  [[INT64:%[0-9]+]] = metatype $@thin Int.Type
 // CHECK:  [[INTLIT:%[0-9]+]] = integer_literal $Builtin.Int2048, 5
-// CHECK:  [[LITFN:%[0-9]+]] = function_ref @_T0S2i{{[_0-9a-zA-Z]*}}fC
+// CHECK:  [[LITFN:%[0-9]+]] = function_ref @_T0Si22_builtinIntegerLiteralSiBi{{[_0-9]*}}__tcfC
 // CHECK:  [[I:%[0-9]+]] = apply [[LITFN]]([[INTLIT]], [[INT64]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int
 // CHECK:  [[DFN:%[0-9]+]] = function_ref @_T017default_arguments7defarg2{{.*}}A0_ : $@convention(thin) () -> Double
 // CHECK:  [[D:%[0-9]+]] = apply [[DFN]]() : $@convention(thin) () -> Double
@@ -114,7 +114,7 @@
 
 class Foo {
 
-  // CHECK-LABEL: sil hidden @_T017default_arguments3FooCACSi3int_SS6stringtcfc : $@convention(method) (Int, @owned String, @owned Foo) -> @owned Foo
+  // CHECK-LABEL: sil hidden @_T017default_arguments3FooC3int6stringACSi_SStcfc : $@convention(method) (Int, @owned String, @owned Foo) -> @owned Foo
   // CHECK:         string_literal utf16 "init(int:string:)"
   init(int: Int, string: String = #function) {
     testMagicLiterals()
@@ -130,7 +130,7 @@
     autoclosure(testMagicLiterals())
   }
 
-  // CHECK-LABEL: sil hidden @_T017default_arguments3FooCS2icig
+  // CHECK-LABEL: sil hidden @_T017default_arguments3FooCyS2icig
   // CHECK:         string_literal utf16 "subscript"
   subscript(x: Int) -> Int {
     testMagicLiterals()
@@ -153,13 +153,13 @@
 // CHECK: string_literal utf16 "default_arguments"
 let y : String = #function 
 
-// CHECK-LABEL: sil hidden @_T017default_arguments16testSelectorCallySi_Si17withMagicLiteralstF
+// CHECK-LABEL: sil hidden @_T017default_arguments16testSelectorCall_17withMagicLiteralsySi_SitF
 // CHECK:         string_literal utf16 "testSelectorCall(_:withMagicLiterals:)"
 func testSelectorCall(_ x: Int, withMagicLiterals y: Int) {
   testMagicLiterals()
 }
 
-// CHECK-LABEL: sil hidden @_T017default_arguments32testSelectorCallWithUnnamedPieceySi_SitF
+// CHECK-LABEL: sil hidden @_T017default_arguments32testSelectorCallWithUnnamedPieceyySi_SitF
 // CHECK:         string_literal utf16 "testSelectorCallWithUnnamedPiece"
 func testSelectorCallWithUnnamedPiece(_ x: Int, _ y: Int) {
   testMagicLiterals()
@@ -170,15 +170,15 @@
   init(int i: Int = 10) { }
 }
 
-// CHECK: sil hidden @_T017default_arguments11SuperDefArgCACSi3int_tcfcfA_ : $@convention(thin) () -> Int
+// CHECK: sil hidden @_T017default_arguments11SuperDefArgC3intACSi_tcfcfA_ : $@convention(thin) () -> Int
 
-// CHECK-NOT: sil hidden @_T017default_arguments9SubDefArgCACSi3int_tcfcfA_ : $@convention(thin) () -> Int
+// CHECK-NOT: sil hidden @_T017default_arguments9SubDefArgCAC3intSi_tcfcfA_ : $@convention(thin) () -> Int
 
 class SubDefArg : SuperDefArg { }
 
 // CHECK: sil hidden @_T017default_arguments13testSubDefArgAA0deF0CyF : $@convention(thin) () -> @owned SubDefArg
 func testSubDefArg() -> SubDefArg {
-  // CHECK: function_ref @_T017default_arguments11SuperDefArgCACSi3int_tcfcfA_
+  // CHECK: function_ref @_T017default_arguments11SuperDefArgC3intACSi_tcfcfA_
   // CHECK: function_ref @_T017default_arguments9SubDefArgC{{[_0-9a-zA-Z]*}}fC
   // CHECK: return
   return SubDefArg()
@@ -192,7 +192,7 @@
 // CHECK-LABEL: sil hidden @_T017default_arguments25testTakeDefaultArgUnnamed{{[_0-9a-zA-Z]*}}F
 func testTakeDefaultArgUnnamed(_ i: Int) {
   // CHECK: bb0([[I:%[0-9]+]] : @trivial $Int):
-  // CHECK:   [[FN:%[0-9]+]] = function_ref @_T017default_arguments21takeDefaultArgUnnamedySiF : $@convention(thin) (Int) -> ()
+  // CHECK:   [[FN:%[0-9]+]] = function_ref @_T017default_arguments21takeDefaultArgUnnamedyySiF : $@convention(thin) (Int) -> ()
   // CHECK:   apply [[FN]]([[I]]) : $@convention(thin) (Int) -> ()
   takeDefaultArgUnnamed(i)
 }
@@ -237,8 +237,8 @@
 }
 
 // <rdar://problem/20494437> SILGen crash handling default arguments
-// CHECK-LABEL: sil hidden @_T017default_arguments18r20494437onSuccessyAA25r20494437ExecutionContext_pF
-// CHECK: function_ref @_T017default_arguments19r20494437onCompleteyAA25r20494437ExecutionContext_pF
+// CHECK-LABEL: sil hidden @_T017default_arguments18r20494437onSuccessyyAA25r20494437ExecutionContext_pF
+// CHECK: function_ref @_T017default_arguments19r20494437onCompleteyyAA25r20494437ExecutionContext_pF
 // <rdar://problem/20494437> SILGen crash handling default arguments
 protocol r20494437ExecutionContext {}
 let r20494437Default: r20494437ExecutionContext
@@ -250,13 +250,13 @@
 // <rdar://problem/18400194> Parenthesized function expression crashes the compiler
 func r18400194(_ a: Int, x: Int = 97) {}
 
-// CHECK-LABEL: sil hidden @_T017default_arguments9r18400194ySi_Si1xtFfA0_
+// CHECK-LABEL: sil hidden @_T017default_arguments9r18400194_1xySi_SitFfA0_
 // CHECK: integer_literal $Builtin.Int2048, 97
 
 // CHECK-LABEL: sil hidden @_T017default_arguments14test_r18400194yyF
 // CHECK: integer_literal $Builtin.Int2048, 1
-// CHECK:  function_ref @_T017default_arguments9r18400194ySi_Si1xtFfA0_ : $@convention(thin) () -> Int
-// CHECK: function_ref @_T017default_arguments9r18400194ySi_Si1xtF : $@convention(thin) (Int, Int) -> (){{.*}}
+// CHECK:  function_ref @_T017default_arguments9r18400194_1xySi_SitFfA0_ : $@convention(thin) () -> Int
+// CHECK: function_ref @_T017default_arguments9r18400194_1xySi_SitF : $@convention(thin) (Int, Int) -> (){{.*}}
 func test_r18400194() {
   (r18400194)(1)
 }
@@ -270,5 +270,5 @@
   }
   bar()
 }
-// CHECK-LABEL: sil private @_T017default_arguments27localFunctionWithDefaultArgyyF3barL_ySiSgFfA_
+// CHECK-LABEL: sil private @_T017default_arguments27localFunctionWithDefaultArgyyF3barL_yySiSgFfA_
 // CHECK-SAME: $@convention(thin) () -> Optional<Int>
diff --git a/test/SILGen/default_arguments_generic.swift b/test/SILGen/default_arguments_generic.swift
index a825808..2431199 100644
--- a/test/SILGen/default_arguments_generic.swift
+++ b/test/SILGen/default_arguments_generic.swift
@@ -42,24 +42,24 @@
 func testInitializable() {
   // The ".init" is required to trigger the crash that used to happen.
   _ = Generic<InitializableImpl>.init()
-  // CHECK: function_ref @_T025default_arguments_generic7GenericVACyxGxcfcfA_ : $@convention(thin) <τ_0_0 where τ_0_0 : Initializable> () -> @out τ_0_0
-  // CHECK: [[INIT:%.+]] = function_ref @_T025default_arguments_generic7GenericVACyxGxcfC
+  // CHECK: function_ref @_T025default_arguments_generic7GenericVyACyxGxcfcfA_ : $@convention(thin) <τ_0_0 where τ_0_0 : Initializable> () -> @out τ_0_0
+  // CHECK: [[INIT:%.+]] = function_ref @_T025default_arguments_generic7GenericVyACyxGxcfC
   // CHECK: apply [[INIT]]<InitializableImpl>({{%.+}}, {{%.+}}) : $@convention(method) <τ_0_0 where τ_0_0 : Initializable> (@in τ_0_0, @thin Generic<τ_0_0>.Type) -> Generic<τ_0_0>
 } // CHECK: end sil function '_T025default_arguments_generic17testInitializableyyF'
 
 // Local generic functions with default arguments
 
-// CHECK-LABEL: sil hidden @_T025default_arguments_generic5outeryx1t_tlF : $@convention(thin) <T> (@in T) -> ()
+// CHECK-LABEL: sil hidden @_T025default_arguments_generic5outer1tyx_tlF : $@convention(thin) <T> (@in T) -> ()
 func outer<T>(t: T) {
   func inner1(x: Int = 0) {}
 
-  // CHECK: [[ARG_GENERATOR:%.*]] = function_ref @_T025default_arguments_generic5outeryx1t_tlF6inner1L_ySi1x_tlFfA_ : $@convention(thin) () -> Int
+  // CHECK: [[ARG_GENERATOR:%.*]] = function_ref @_T025default_arguments_generic5outer1tyx_tlF6inner1L_1xySi_tlFfA_ : $@convention(thin) () -> Int
   // CHECK: [[ARG:%.*]] = apply [[ARG_GENERATOR]]() : $@convention(thin) () -> Int
   _ = inner1()
 
   func inner2(x: Int = 0) { _ = T.self }
 
-  // CHECK: [[ARG_GENERATOR:%.*]] = function_ref @_T025default_arguments_generic5outeryx1t_tlF6inner2L_ySi1x_tlFfA_ : $@convention(thin) <τ_0_0> () -> Int
+  // CHECK: [[ARG_GENERATOR:%.*]] = function_ref @_T025default_arguments_generic5outer1tyx_tlF6inner2L_1xySi_tlFfA_ : $@convention(thin) <τ_0_0> () -> Int
   // CHECK: [[ARG:%.*]] = apply [[ARG_GENERATOR]]<T>() : $@convention(thin) <τ_0_0> () -> Int
   _ = inner2()
 }
diff --git a/test/SILGen/default_arguments_imported.swift b/test/SILGen/default_arguments_imported.swift
index 95ad609..baf2197 100644
--- a/test/SILGen/default_arguments_imported.swift
+++ b/test/SILGen/default_arguments_imported.swift
@@ -8,23 +8,23 @@
 
 // CHECK-LABEL: sil hidden @_T026default_arguments_imported9testGizmo{{[_0-9a-zA-Z]*}}F
 func testGizmo(gizmo: Gizmo) {
-  // CHECK: function_ref @_T0SqxSgyt10nilLiteral_tcfC
+  // CHECK: function_ref @_T0Sq10nilLiteralxSgyt_tcfC
   // CHECK: objc_method [[SELF:%[0-9]+]] : $Gizmo, #Gizmo.enumerateSubGizmos!1.foreign
   gizmo.enumerateSubGizmos()
-} // CHECK: } // end sil function '_T026default_arguments_imported9testGizmoySo0E0C5gizmo_tF'
+} // CHECK: } // end sil function '_T026default_arguments_imported9testGizmo5gizmoySo0E0C_tF'
 
-// CHECK-LABEL: sil hidden @_T026default_arguments_imported21testNonnullDictionaryySo5GizmoC5gizmo_tF
+// CHECK-LABEL: sil hidden @_T026default_arguments_imported21testNonnullDictionary5gizmoySo5GizmoC_tF
 func testNonnullDictionary(gizmo: Gizmo) {
   // CHECK-NOT: nilLiteral
-  // CHECK: function_ref @_T0s10DictionaryVAByxq_Gx_q_t17dictionaryLiterald_tcfC
+  // CHECK: function_ref @_T0s10DictionaryV17dictionaryLiteralAByxq_Gx_q_td_tcfC
   // CHECK: objc_method [[SELF:%[0-9]+]] : $Gizmo, #Gizmo.doTheThing!1.foreign
   gizmo.doTheThing()
-} // CHECK: } // end sil function '_T026default_arguments_imported21testNonnullDictionaryySo5GizmoC5gizmo_tF'
+} // CHECK: } // end sil function '_T026default_arguments_imported21testNonnullDictionary5gizmoySo5GizmoC_tF'
 
-// CHECK-LABEL: sil hidden @_T026default_arguments_imported22testNullableDictionaryySo5GizmoC5gizmo_tF
+// CHECK-LABEL: sil hidden @_T026default_arguments_imported22testNullableDictionary5gizmoySo5GizmoC_tF
 func testNullableDictionary(gizmo: Gizmo) {
   // CHECK-NOT: dictionaryLiteral
-  // CHECK: function_ref @_T0SqxSgyt10nilLiteral_tcfC
+  // CHECK: function_ref @_T0Sq10nilLiteralxSgyt_tcfC
   // CHECK: objc_method [[SELF:%[0-9]+]] : $Gizmo, #Gizmo.doTheOtherThing!1.foreign
   gizmo.doTheOtherThing()
-} // CHECK: } // end sil function '_T026default_arguments_imported22testNullableDictionaryySo5GizmoC5gizmo_tF'
+} // CHECK: } // end sil function '_T026default_arguments_imported22testNullableDictionary5gizmoySo5GizmoC_tF'
diff --git a/test/SILGen/default_arguments_inherited.swift b/test/SILGen/default_arguments_inherited.swift
index c720202..4edd719 100644
--- a/test/SILGen/default_arguments_inherited.swift
+++ b/test/SILGen/default_arguments_inherited.swift
@@ -20,21 +20,21 @@
 
 // CHECK-LABEL: sil hidden @_T027default_arguments_inherited4doItyyF : $@convention(thin) () -> () {
 func doIt() {
-  // CHECK: [[ARG1:%.*]] = function_ref @_T027default_arguments_inherited5PuppyCACyxq_GxSg1t_q_Sg1utcfcfA_
+  // CHECK: [[ARG1:%.*]] = function_ref @_T027default_arguments_inherited5PuppyC1t1uACyxq_GxSg_q_SgtcfcfA_
   // CHECK: apply [[ARG1]]<Int, String>({{.*}})
-  // CHECK: [[ARG2:%.*]] = function_ref @_T027default_arguments_inherited5PuppyCACyxq_GxSg1t_q_Sg1utcfcfA0_
+  // CHECK: [[ARG2:%.*]] = function_ref @_T027default_arguments_inherited5PuppyC1t1uACyxq_GxSg_q_SgtcfcfA0_
   // CHECK: apply [[ARG2]]<Int, String>({{.*}})
   _ = Chipmunk()
 
-  // CHECK: [[ARG1:%.*]] = function_ref @_T027default_arguments_inherited5PuppyCACyxq_GxSg1t_q_Sg1utcfcfA_
+  // CHECK: [[ARG1:%.*]] = function_ref @_T027default_arguments_inherited5PuppyC1t1uACyxq_GxSg_q_SgtcfcfA_
   // CHECK: apply [[ARG1]]<Int, String>(%{{.*}})
-  // CHECK: [[ARG2:%.*]] = function_ref @_T027default_arguments_inherited5PuppyCACyxq_GxSg1t_q_Sg1utcfcfA0_
+  // CHECK: [[ARG2:%.*]] = function_ref @_T027default_arguments_inherited5PuppyC1t1uACyxq_GxSg_q_SgtcfcfA0_
   // CHECK: apply [[ARG2]]<Int, String>(%{{.*}})
   _ = Kitten<String>()
 
-  // CHECK: [[ARG1:%.*]] = function_ref @_T027default_arguments_inherited5PuppyCACyxq_GxSg1t_q_Sg1utcfcfA_
+  // CHECK: [[ARG1:%.*]] = function_ref @_T027default_arguments_inherited5PuppyC1t1uACyxq_GxSg_q_SgtcfcfA_
   // CHECK: apply [[ARG1]]<String, Int>(%{{.*}})
-  // CHECK: [[ARG2:%.*]] = function_ref @_T027default_arguments_inherited5PuppyCACyxq_GxSg1t_q_Sg1utcfcfA0_
+  // CHECK: [[ARG2:%.*]] = function_ref @_T027default_arguments_inherited5PuppyC1t1uACyxq_GxSg_q_SgtcfcfA0_
   // CHECK: apply [[ARG2]]<String, Int>(%{{.*}})
   _ = Goldfish<String>.Shark<Int>()
 }
diff --git a/test/SILGen/default_arguments_serialized.swift b/test/SILGen/default_arguments_serialized.swift
index d264736..aa268a8 100644
--- a/test/SILGen/default_arguments_serialized.swift
+++ b/test/SILGen/default_arguments_serialized.swift
@@ -14,18 +14,18 @@
 // CHECK-LABEL: sil @_T028default_arguments_serialized0A6StringSSyF : $@convention(thin) () -> @owned String
 public func defaultString() -> String { return "hi" }
 
-// SWIFT3-LABEL: sil @_T028default_arguments_serialized19hasDefaultArgumentsySi1x_SS1ytFfA_ : $@convention(thin) () -> Int
-// SWIFT4-LABEL: sil [serialized] @_T028default_arguments_serialized19hasDefaultArgumentsySi1x_SS1ytFfA_ : $@convention(thin) () -> Int
+// SWIFT3-LABEL: sil @_T028default_arguments_serialized19hasDefaultArguments1x1yySi_SStFfA_ : $@convention(thin) () -> Int
+// SWIFT4-LABEL: sil [serialized] @_T028default_arguments_serialized19hasDefaultArguments1x1yySi_SStFfA_ : $@convention(thin) () -> Int
 
-// SWIFT3-LABEL: sil @_T028default_arguments_serialized19hasDefaultArgumentsySi1x_SS1ytFfA0_ : $@convention(thin) () -> @owned String
-// SWIFT4-LABEL: sil [serialized] @_T028default_arguments_serialized19hasDefaultArgumentsySi1x_SS1ytFfA0_ : $@convention(thin) () -> @owned String
+// SWIFT3-LABEL: sil @_T028default_arguments_serialized19hasDefaultArguments1x1yySi_SStFfA0_ : $@convention(thin) () -> @owned String
+// SWIFT4-LABEL: sil [serialized] @_T028default_arguments_serialized19hasDefaultArguments1x1yySi_SStFfA0_ : $@convention(thin) () -> @owned String
 
 public func hasDefaultArguments(x: Int = 0, y: String = defaultString()) {}
 
 // CHECK-LABEL: sil @_T028default_arguments_serialized21callsDefaultArgumentsyyF : $@convention(thin) () -> ()
-// CHECK: function_ref @_T028default_arguments_serialized19hasDefaultArgumentsySi1x_SS1ytFfA_ : $@convention(thin) () -> Int
-// CHECK: function_ref @_T028default_arguments_serialized19hasDefaultArgumentsySi1x_SS1ytFfA0_ : $@convention(thin) () -> @owned String
-// CHECK: function_ref @_T028default_arguments_serialized19hasDefaultArgumentsySi1x_SS1ytF : $@convention(thin) (Int, @owned String) -> ()
+// CHECK: function_ref @_T028default_arguments_serialized19hasDefaultArguments1x1yySi_SStFfA_ : $@convention(thin) () -> Int
+// CHECK: function_ref @_T028default_arguments_serialized19hasDefaultArguments1x1yySi_SStFfA0_ : $@convention(thin) () -> @owned String
+// CHECK: function_ref @_T028default_arguments_serialized19hasDefaultArguments1x1yySi_SStF : $@convention(thin) (Int, @owned String) -> ()
 // CHECK: apply
 // CHECK: return
 public func callsDefaultArguments() {
@@ -37,8 +37,8 @@
 // even if *this* module is built in Swift 3 mode.
 
 // CHECK-LABEL: sil @_T028default_arguments_serialized26callsOtherDefaultArgumentsyyF : $@convention(thin) () -> ()
-// CHECK: function_ref @_T023default_arguments_other0C16DefaultArgumentsySi1x_tFfA_ : $@convention(thin) () -> Int
-// CHECK: function_ref @_T023default_arguments_other0C16DefaultArgumentsySi1x_tF : $@convention(thin) (Int) -> ()
+// CHECK: function_ref @_T023default_arguments_other0C16DefaultArguments1xySi_tFfA_ : $@convention(thin) () -> Int
+// CHECK: function_ref @_T023default_arguments_other0C16DefaultArguments1xySi_tF : $@convention(thin) (Int) -> ()
 // CHECK: apply
 // CHECK: return
 
@@ -48,14 +48,14 @@
 // OPT-LABEL: sil @_T028default_arguments_serialized26callsOtherDefaultArgumentsyyF : $@convention(thin) () -> ()
 // OPT: [[INT_VAL:%.*]] = integer_literal [[INT_TYPE:\$Builtin.Int(32|64)]], 0
 // OPT: [[INT:%.*]] = struct $Int ([[INT_VAL]] : [[INT_TYPE]]
-// OPT: [[FN:%.*]] = function_ref @_T023default_arguments_other0C16DefaultArgumentsySi1x_tF : $@convention(thin) (Int) -> ()
+// OPT: [[FN:%.*]] = function_ref @_T023default_arguments_other0C16DefaultArguments1xySi_tF : $@convention(thin) (Int) -> ()
 // OPT: apply [[FN]]([[INT]]) : $@convention(thin) (Int) -> ()
 // OPT: return
 public func callsOtherDefaultArguments() {
   otherDefaultArguments()
 }
 
-// CHECK-LABEL: sil [serialized] @_T023default_arguments_other0C16DefaultArgumentsySi1x_tFfA_ : $@convention(thin) () -> Int
+// CHECK-LABEL: sil [serialized] @_T023default_arguments_other0C16DefaultArguments1xySi_tFfA_ : $@convention(thin) () -> Int
 
-// CHECK-LABEL: sil @_T023default_arguments_other0C16DefaultArgumentsySi1x_tF : $@convention(thin) (Int) -> ()
+// CHECK-LABEL: sil @_T023default_arguments_other0C16DefaultArguments1xySi_tF : $@convention(thin) (Int) -> ()
 
diff --git a/test/SILGen/default_constructor.swift b/test/SILGen/default_constructor.swift
index 24f77ac..94e6804 100644
--- a/test/SILGen/default_constructor.swift
+++ b/test/SILGen/default_constructor.swift
@@ -17,11 +17,11 @@
 // CHECK-LABEL: sil hidden [transparent] @_T019default_constructor1DV1iSivpfi : $@convention(thin) () -> (Int, Double)
 // CHECK:      [[METATYPE:%.*]] = metatype $@thin Int.Type
 // CHECK-NEXT: [[VALUE:%.*]] = integer_literal $Builtin.Int2048, 2
-// CHECK:      [[FN:%.*]] = function_ref @_T0S2iBi2048_22_builtinIntegerLiteral_tcfC : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int
+// CHECK:      [[FN:%.*]] = function_ref @_T0Si22_builtinIntegerLiteralSiBi2048__tcfC : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int
 // CHECK-NEXT: [[LEFT:%.*]] = apply [[FN]]([[VALUE]], [[METATYPE]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int
 // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Double.Type
 // CHECK-NEXT: [[VALUE:%.*]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0x400C000000000000|0x4000E000000000000000}}
-// CHECK:      [[FN:%.*]] = function_ref @_T0S2dBf{{64|80}}_20_builtinFloatLiteral_tcfC : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Double.Type) -> Double
+// CHECK:      [[FN:%.*]] = function_ref @_T0Sd20_builtinFloatLiteralSdBf{{64|80}}__tcfC : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Double.Type) -> Double
 // CHECK-NEXT: [[RIGHT:%.*]] = apply [[FN]]([[VALUE]], [[METATYPE]]) : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Double.Type) -> Double
 // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[LEFT]] : $Int, [[RIGHT]] : $Double)
 // CHECK-NEXT: return [[RESULT]] : $(Int, Double)
@@ -102,7 +102,7 @@
 struct H<T> {
   var opt: T?
 
-  // CHECK-LABEL: sil hidden @_T019default_constructor1HVACyxGqd__clufC : $@convention(method) <T><U> (@in U, @thin H<T>.Type) -> @out H<T> {
+  // CHECK-LABEL: sil hidden @_T019default_constructor1HVyACyxGqd__clufC : $@convention(method) <T><U> (@in U, @thin H<T>.Type) -> @out H<T> {
   // CHECK: [[INIT_FN:%[0-9]+]] = function_ref @_T019default_constructor1HV3optxSgvpfi : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0>
   // CHECK-NEXT: [[OPT_T:%[0-9]+]] = alloc_stack $Optional<T>
   // CHECK-NEXT: apply [[INIT_FN]]<T>([[OPT_T]]) : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0>
@@ -114,7 +114,7 @@
 struct I {
   var x: Int = 0
 
-  // CHECK-LABEL: sil hidden @_T019default_constructor1IVACxclufC : $@convention(method) <T> (@in T, @thin I.Type) -> I {
+  // CHECK-LABEL: sil hidden @_T019default_constructor1IVyACxclufC : $@convention(method) <T> (@in T, @thin I.Type) -> I {
   // CHECK: [[INIT_FN:%[0-9]+]] = function_ref @_T019default_constructor1IV1xSivpfi : $@convention(thin) () -> Int
   // CHECK: [[RESULT:%[0-9]+]] = apply [[INIT_FN]]() : $@convention(thin) () -> Int
   // CHECK: [[X_ADDR:%[0-9]+]] = struct_element_addr {{.*}} : $*I, #I.x
diff --git a/test/SILGen/dependent_member_lowering.swift b/test/SILGen/dependent_member_lowering.swift
index 0f24071..85d04cf 100644
--- a/test/SILGen/dependent_member_lowering.swift
+++ b/test/SILGen/dependent_member_lowering.swift
@@ -9,13 +9,13 @@
   typealias A = T.Type
 
   func f(_ t: T.Type) {}
-  // CHECK-LABEL: sil private [transparent] [thunk] @_T025dependent_member_lowering3FooVyxGAA1PA2aEP1fy1AQzFTW : $@convention(witness_method: P) <τ_0_0> (@in @thick τ_0_0.Type, @in_guaranteed Foo<τ_0_0>) -> ()
+  // CHECK-LABEL: sil private [transparent] [thunk] @_T025dependent_member_lowering3FooVyxGAA1PA2aEP1fyy1AQzFTW : $@convention(witness_method: P) <τ_0_0> (@in @thick τ_0_0.Type, @in_guaranteed Foo<τ_0_0>) -> ()
   // CHECK:       bb0(%0 : @trivial $*@thick τ_0_0.Type, %1 : @trivial $*Foo<τ_0_0>):
 }
 struct Bar<T>: P {
   typealias A = (Int) -> T
 
   func f(_ t: @escaping (Int) -> T) {}
-  // CHECK-LABEL: sil private [transparent] [thunk] @_T025dependent_member_lowering3BarVyxGAA1PA2aEP1fy1AQzFTW : $@convention(witness_method: P) <τ_0_0> (@in @callee_guaranteed (@in Int) -> @out τ_0_0, @in_guaranteed Bar<τ_0_0>) -> ()
+  // CHECK-LABEL: sil private [transparent] [thunk] @_T025dependent_member_lowering3BarVyxGAA1PA2aEP1fyy1AQzFTW : $@convention(witness_method: P) <τ_0_0> (@in @callee_guaranteed (@in Int) -> @out τ_0_0, @in_guaranteed Bar<τ_0_0>) -> ()
   // CHECK:       bb0(%0 : @trivial $*@callee_guaranteed (@in Int) -> @out τ_0_0, %1 : @trivial $*Bar<τ_0_0>):
 }
diff --git a/test/SILGen/downcast_reabstraction.swift b/test/SILGen/downcast_reabstraction.swift
index f272178..a06befd 100644
--- a/test/SILGen/downcast_reabstraction.swift
+++ b/test/SILGen/downcast_reabstraction.swift
@@ -1,6 +1,6 @@
 // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
-// CHECK-LABEL: sil hidden @_T022downcast_reabstraction19condFunctionFromAnyyypF 
+// CHECK-LABEL: sil hidden @_T022downcast_reabstraction19condFunctionFromAnyyyypF
 // CHECK:         checked_cast_addr_br take_always Any in [[IN:%.*]] : $*Any to () -> () in [[OUT:%.*]] : $*@callee_guaranteed (@in ()) -> @out (), [[YES:bb[0-9]+]], [[NO:bb[0-9]+]]
 // CHECK:       [[YES]]:
 // CHECK:         [[ORIG_VAL:%.*]] = load [take] [[OUT]]
@@ -13,7 +13,7 @@
   }
 }
 
-// CHECK-LABEL: sil hidden @_T022downcast_reabstraction21uncondFunctionFromAnyyypF : $@convention(thin) (@in Any) -> () {
+// CHECK-LABEL: sil hidden @_T022downcast_reabstraction21uncondFunctionFromAnyyyypF : $@convention(thin) (@in Any) -> () {
 // CHECK:         unconditional_checked_cast_addr Any in [[IN:%.*]] : $*Any to () -> () in [[OUT:%.*]] : $*@callee_guaranteed (@in ()) -> @out ()
 // CHECK:         [[ORIG_VAL:%.*]] = load [take] [[OUT]]
 // CHECK:         [[REABSTRACT:%.*]] = function_ref @_T0ytytIegir_Ieg_TR
diff --git a/test/SILGen/downgrade_exhaustivity_swift3.swift b/test/SILGen/downgrade_exhaustivity_swift3.swift
index dba8bcc..8c2712c 100644
--- a/test/SILGen/downgrade_exhaustivity_swift3.swift
+++ b/test/SILGen/downgrade_exhaustivity_swift3.swift
@@ -7,7 +7,7 @@
   case fork
 }
 
-// CHECK-LABEL: sil hidden @_T029downgrade_exhaustivity_swift343testDowngradableOmittedPatternIsUnreachableyAA0E0OSg3pat_tF
+// CHECK-LABEL: sil hidden @_T029downgrade_exhaustivity_swift343testDowngradableOmittedPatternIsUnreachable3patyAA0E0OSg_tF
 func testDowngradableOmittedPatternIsUnreachable(pat : Downgradable?) {
   // CHECK: switch_enum {{%.*}} : $Downgradable, case #Downgradable.spoon!enumelt: [[CASE1:bb[0-9]+]], case #Downgradable.hat!enumelt: [[CASE2:bb[0-9]+]], default [[DEFAULT_CASE:bb[0-9]+]]
   switch pat! {
diff --git a/test/SILGen/dynamic.swift b/test/SILGen/dynamic.swift
index 5e8bfe7..839bf1c 100644
--- a/test/SILGen/dynamic.swift
+++ b/test/SILGen/dynamic.swift
@@ -70,8 +70,8 @@
 // CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooC10objcMethod{{[_0-9a-zA-Z]*}}FTo
 // CHECK-LABEL: sil hidden [transparent] [thunk] @_T07dynamic3FooC8objcPropSivgTo
 // CHECK-LABEL: sil hidden [transparent] [thunk] @_T07dynamic3FooC8objcPropSivsTo
-// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooCSiyXl4objc_tcigTo
-// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooCSiyXl4objc_tcisTo
+// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooC4objcSiyXl_tcigTo
+// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooC4objcSiyXl_tcisTo
 
 // TODO: dynamic initializing ctor must be objc dispatched
 // CHECK-LABEL: sil hidden @_T07dynamic3{{[_0-9a-zA-Z]*}}fC
@@ -83,8 +83,8 @@
 // CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooC0A6Method{{[_0-9a-zA-Z]*}}FTo
 // CHECK-LABEL: sil hidden [transparent] [thunk] @_T07dynamic3FooC0A4PropSivgTo
 // CHECK-LABEL: sil hidden [transparent] [thunk] @_T07dynamic3FooC0A4PropSivsTo
-// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooCS2iAA_tcigTo
-// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooCS2iAA_tcisTo
+// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooCAAS2i_tcigTo
+// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooCAAS2i_tcisTo
 
 // Protocol witnesses use best appropriate dispatch
 
@@ -95,9 +95,9 @@
 // CHECK:         class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 :
 // CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP10nativePropSivsTW
 // CHECK:         class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 :
-// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDPS2i6native_tcigTW
+// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP6nativeS2i_tcigTW
 // CHECK:         class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 :
-// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDPS2i6native_tcisTW
+// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP6nativeS2i_tcisTW
 // CHECK:         class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 :
 
 // @objc witnesses use vtable dispatch:
@@ -107,9 +107,9 @@
 // CHECK:         class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 :
 // CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP8objcPropSivsTW
 // CHECK:         class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 :
-// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDPSiyXl4objc_tcigTW
+// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP4objcSiyXl_tcigTW
 // CHECK:         class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 :
-// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDPSiyXl4objc_tcisTW
+// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP4objcSiyXl_tcisTW
 // CHECK:         class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 :
 
 // Dynamic witnesses use objc dispatch:
@@ -128,14 +128,14 @@
 // CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T07dynamic3FooC0A4PropSivsTD
 // CHECK:         objc_method {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign :
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDPS2iAA_tcigTW
-// CHECK:         function_ref @_T07dynamic3FooCS2iAA_tcigTD
-// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T07dynamic3FooCS2iAA_tcigTD
+// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDPAAS2i_tcigTW
+// CHECK:         function_ref @_T07dynamic3FooCAAS2i_tcigTD
+// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T07dynamic3FooCAAS2i_tcigTD
 // CHECK:         objc_method {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign :
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDPS2iAA_tcisTW
-// CHECK:         function_ref @_T07dynamic3FooCS2iAA_tcisTD
-// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T07dynamic3FooCS2iAA_tcisTD
+// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDPAAS2i_tcisTW
+// CHECK:         function_ref @_T07dynamic3FooCAAS2i_tcisTD
+// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T07dynamic3FooCAAS2i_tcisTD
 // CHECK:         objc_method {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign :
 
 // Superclass dispatch
@@ -164,18 +164,18 @@
 
   override subscript(native native: Int) -> Int {
     get { return super[native: native] }
-    // CHECK-LABEL: sil hidden @_T07dynamic8SubclassCS2i6native_tcig
-    // CHECK:         function_ref @_T07dynamic3FooCS2i6native_tcig : $@convention(method) (Int, @guaranteed Foo) -> Int
+    // CHECK-LABEL: sil hidden @_T07dynamic8SubclassC6nativeS2i_tcig
+    // CHECK:         function_ref @_T07dynamic3FooC6nativeS2i_tcig : $@convention(method) (Int, @guaranteed Foo) -> Int
     set { super[native: native] = newValue }
-    // CHECK-LABEL: sil hidden @_T07dynamic8SubclassCS2i6native_tcis
-    // CHECK:         function_ref @_T07dynamic3FooCS2i6native_tcis : $@convention(method) (Int, Int, @guaranteed Foo) -> ()
+    // CHECK-LABEL: sil hidden @_T07dynamic8SubclassC6nativeS2i_tcis
+    // CHECK:         function_ref @_T07dynamic3FooC6nativeS2i_tcis : $@convention(method) (Int, Int, @guaranteed Foo) -> ()
   }
 
   override init(objc: Int) {
     super.init(objc: objc)
   }
-  // CHECK-LABEL: sil hidden @_T07dynamic8SubclassCACSi4objc_tcfc
-  // CHECK:         function_ref @_T07dynamic3FooCACSi4objc_tcfc : $@convention(method) (Int, @owned Foo) -> @owned Foo
+  // CHECK-LABEL: sil hidden @_T07dynamic8SubclassC4objcACSi_tcfc
+  // CHECK:         function_ref @_T07dynamic3FooC4objcACSi_tcfc : $@convention(method) (Int, @owned Foo) -> @owned Foo
 
   override func objcMethod() {
     super.objcMethod()
@@ -194,11 +194,11 @@
 
   override subscript(objc objc: AnyObject) -> Int {
     get { return super[objc: objc] }
-    // CHECK-LABEL: sil hidden @_T07dynamic8SubclassCSiyXl4objc_tcig
-    // CHECK:         function_ref @_T07dynamic3FooCSiyXl4objc_tcig : $@convention(method) (@owned AnyObject, @guaranteed Foo) -> Int
+    // CHECK-LABEL: sil hidden @_T07dynamic8SubclassC4objcSiyXl_tcig
+    // CHECK:         function_ref @_T07dynamic3FooC4objcSiyXl_tcig : $@convention(method) (@owned AnyObject, @guaranteed Foo) -> Int
     set { super[objc: objc] = newValue }
-    // CHECK-LABEL: sil hidden @_T07dynamic8SubclassCSiyXl4objc_tcis
-    // CHECK:         function_ref @_T07dynamic3FooCSiyXl4objc_tcis : $@convention(method) (Int, @owned AnyObject, @guaranteed Foo) -> ()
+    // CHECK-LABEL: sil hidden @_T07dynamic8SubclassC4objcSiyXl_tcis
+    // CHECK:         function_ref @_T07dynamic3FooC4objcSiyXl_tcis : $@convention(method) (Int, @owned AnyObject, @guaranteed Foo) -> ()
   }
 
   // Dynamic methods are super-dispatched by objc_msgSend
@@ -225,10 +225,10 @@
 
   override subscript(dynamic dynamic: Int) -> Int {
     get { return super[dynamic: dynamic] }
-    // CHECK-LABEL: sil hidden @_T07dynamic8SubclassCS2iAA_tcig
+    // CHECK-LABEL: sil hidden @_T07dynamic8SubclassCAAS2i_tcig
     // CHECK:         objc_super_method {{%.*}} : $Subclass, #Foo.subscript!getter.1.foreign :
     set { super[dynamic: dynamic] = newValue }
-    // CHECK-LABEL: sil hidden @_T07dynamic8SubclassCS2iAA_tcis
+    // CHECK-LABEL: sil hidden @_T07dynamic8SubclassCAAS2i_tcis
     // CHECK:         objc_super_method {{%.*}} : $Subclass, #Foo.subscript!setter.1.foreign :
   }
 
@@ -300,7 +300,7 @@
   c[dynamic: 0] = y
 }
 
-// CHECK-LABEL: sil hidden @_T07dynamic15managedDispatchyAA3FooCF
+// CHECK-LABEL: sil hidden @_T07dynamic15managedDispatchyyAA3FooCF
 func managedDispatch(_ c: Foo) {
   // CHECK: objc_method {{%.*}} : $Foo, #Foo.managedProp!getter.1.foreign 
   let x = c.managedProp
@@ -349,7 +349,7 @@
   dynamic func foreignDynamicExtension() { }
 }
 
-// CHECK-LABEL: sil hidden @_T07dynamic24foreignExtensionDispatchySo5GizmoCF
+// CHECK-LABEL: sil hidden @_T07dynamic24foreignExtensionDispatchyySo5GizmoCF
 // CHECK: bb0([[ARG:%.*]] : $Gizmo):
 func foreignExtensionDispatch(_ g: Gizmo) {
   // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
@@ -409,7 +409,7 @@
   c[dynamic: 0] = y
 }
 
-// CHECK-LABEL: sil hidden @_T07dynamic28managedDispatchFromOtherFileyAA0deF0CF
+// CHECK-LABEL: sil hidden @_T07dynamic28managedDispatchFromOtherFileyyAA0deF0CF
 func managedDispatchFromOtherFile(_ c: FromOtherFile) {
   // CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!getter.1.foreign
   let x = c.managedProp
@@ -417,7 +417,7 @@
   c.managedProp = x
 }
 
-// CHECK-LABEL: sil hidden @_T07dynamic0A16ExtensionMethodsyAA13ObjCOtherFileCF
+// CHECK-LABEL: sil hidden @_T07dynamic0A16ExtensionMethodsyyAA13ObjCOtherFileCF
 func dynamicExtensionMethods(_ obj: ObjCOtherFile) {
   // CHECK: objc_method {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionMethod!1.foreign
   obj.extensionMethod()
@@ -491,30 +491,30 @@
 // so after re-abstracting the signature we must dispatch to the dynamic
 // thunk.
 
-// CHECK-LABEL: sil private @_T07dynamic15ConcreteDerivedC6methodySiFAA11GenericBaseCADyxFTV : $@convention(method) (@in Int, @guaranteed ConcreteDerived) -> ()
+// CHECK-LABEL: sil private @_T07dynamic15ConcreteDerivedC6methodyySiFAA11GenericBaseCADyyxFTV : $@convention(method) (@in Int, @guaranteed ConcreteDerived) -> ()
 // CHECK: bb0(%0 : $*Int, %1 : $ConcreteDerived):
 // CHECK-NEXT:  [[VALUE:%.*]] = load [trivial] %0 : $*Int
-// CHECK:       [[DYNAMIC_THUNK:%.*]] = function_ref @_T07dynamic15ConcreteDerivedC6methodySiFTD : $@convention(method) (Int, @guaranteed ConcreteDerived) -> ()
+// CHECK:       [[DYNAMIC_THUNK:%.*]] = function_ref @_T07dynamic15ConcreteDerivedC6methodyySiFTD : $@convention(method) (Int, @guaranteed ConcreteDerived) -> ()
 // CHECK-NEXT:  apply [[DYNAMIC_THUNK]]([[VALUE]], %1) : $@convention(method) (Int, @guaranteed ConcreteDerived) -> ()
 // CHECK:       return
 
 // Vtable contains entries for native and @objc methods, but not dynamic ones
 // CHECK-LABEL: sil_vtable Foo {
-// CHECK-NEXT:   #Foo.init!initializer.1: {{.*}} :   _T07dynamic3FooCACSi6native_tcfc
+// CHECK-NEXT:   #Foo.init!initializer.1: {{.*}} :   _T07dynamic3FooC6nativeACSi_tcfc
 // CHECK-NEXT:   #Foo.nativeMethod!1: {{.*}} :       _T07dynamic3FooC12nativeMethodyyF
 // CHECK-NEXT:   #Foo.nativeProp!getter.1: {{.*}} :  _T07dynamic3FooC10nativePropSivg     // dynamic.Foo.nativeProp.getter : Swift.Int
 // CHECK-NEXT:   #Foo.nativeProp!setter.1: {{.*}} :  _T07dynamic3FooC10nativePropSivs     // dynamic.Foo.nativeProp.setter : Swift.Int
 // CHECK-NEXT:   #Foo.nativeProp!materializeForSet.1
-// CHECK-NEXT:   #Foo.subscript!getter.1: {{.*}} :   _T07dynamic3FooCS2i6native_tcig    // dynamic.Foo.subscript.getter : (native: Swift.Int) -> Swift.Int
-// CHECK-NEXT:   #Foo.subscript!setter.1: {{.*}} :   _T07dynamic3FooCS2i6native_tcis    // dynamic.Foo.subscript.setter : (native: Swift.Int) -> Swift.Int
+// CHECK-NEXT:   #Foo.subscript!getter.1: {{.*}} :   _T07dynamic3FooC6nativeS2i_tcig    // dynamic.Foo.subscript.getter : (native: Swift.Int) -> Swift.Int
+// CHECK-NEXT:   #Foo.subscript!setter.1: {{.*}} :   _T07dynamic3FooC6nativeS2i_tcis    // dynamic.Foo.subscript.setter : (native: Swift.Int) -> Swift.Int
 // CHECK-NEXT:   #Foo.subscript!materializeForSet.1
-// CHECK-NEXT:   #Foo.init!initializer.1: {{.*}} :   _T07dynamic3FooCACSi4objc_tcfc
+// CHECK-NEXT:   #Foo.init!initializer.1: {{.*}} :   _T07dynamic3FooC4objcACSi_tcfc
 // CHECK-NEXT:   #Foo.objcMethod!1: {{.*}} :         _T07dynamic3FooC10objcMethodyyF
 // CHECK-NEXT:   #Foo.objcProp!getter.1: {{.*}} :    _T07dynamic3FooC8objcPropSivg  // dynamic.Foo.objcProp.getter : Swift.Int
 // CHECK-NEXT:   #Foo.objcProp!setter.1: {{.*}} :    _T07dynamic3FooC8objcPropSivs  // dynamic.Foo.objcProp.setter : Swift.Int
 // CHECK-NEXT:   #Foo.objcProp!materializeForSet.1
-// CHECK-NEXT:   #Foo.subscript!getter.1: {{.*}} : _T07dynamic3FooCSiyXl4objc_tcig // dynamic.Foo.subscript.getter : (objc: Swift.AnyObject) -> Swift.Int
-// CHECK-NEXT:   #Foo.subscript!setter.1: {{.*}} : _T07dynamic3FooCSiyXl4objc_tcis // dynamic.Foo.subscript.setter : (objc: Swift.AnyObject) -> Swift.Int
+// CHECK-NEXT:   #Foo.subscript!getter.1: {{.*}} : _T07dynamic3FooC4objcSiyXl_tcig // dynamic.Foo.subscript.getter : (objc: Swift.AnyObject) -> Swift.Int
+// CHECK-NEXT:   #Foo.subscript!setter.1: {{.*}} : _T07dynamic3FooC4objcSiyXl_tcis // dynamic.Foo.subscript.setter : (objc: Swift.AnyObject) -> Swift.Int
 // CHECK-NEXT:   #Foo.subscript!materializeForSet
 // CHECK-NEXT:   #Foo.overriddenByDynamic!1: {{.*}} : _T07dynamic3FooC19overriddenByDynamic{{[_0-9a-zA-Z]*}}
 // CHECK-NEXT:   #Foo.deinit!deallocator: {{.*}}
@@ -527,20 +527,20 @@
 
 // Check vtables for implicitly-inherited initializers
 // CHECK-LABEL: sil_vtable SubclassWithInheritedInits {
-// CHECK:   #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic26SubclassWithInheritedInitsCACSi6native_tcfc
-// CHECK:   #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic26SubclassWithInheritedInitsCACSi4objc_tcfc
+// CHECK:   #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic26SubclassWithInheritedInitsC6nativeACSi_tcfc
+// CHECK:   #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic26SubclassWithInheritedInitsC4objcACSi_tcfc
 // CHECK-NOT: .init!
 // CHECK: }
 
 // CHECK-LABEL: sil_vtable GrandchildWithInheritedInits {
-// CHECK:   #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic28GrandchildWithInheritedInitsCACSi6native_tcfc
-// CHECK:   #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic28GrandchildWithInheritedInitsCACSi4objc_tcfc
+// CHECK:   #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic28GrandchildWithInheritedInitsC6nativeACSi_tcfc
+// CHECK:   #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic28GrandchildWithInheritedInitsC4objcACSi_tcfc
 // CHECK-NOT: .init!
 // CHECK: }
 
 // CHECK-LABEL: sil_vtable GrandchildOfInheritedInits {
-// CHECK:   #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic26GrandchildOfInheritedInitsCACSi6native_tcfc
-// CHECK:   #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic26GrandchildOfInheritedInitsCACSi4objc_tcfc
+// CHECK:   #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic26GrandchildOfInheritedInitsC6nativeACSi_tcfc
+// CHECK:   #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic26GrandchildOfInheritedInitsC4objcACSi_tcfc
 // CHECK-NOT: .init!
 // CHECK: }
 
@@ -552,7 +552,7 @@
 
 // Dynamic thunk + vtable re-abstraction
 // CHECK-LABEL: sil_vtable [serialized] ConcreteDerived {
-// CHECK-NEXT: #GenericBase.method!1: <T> (GenericBase<T>) -> (T) -> () : public _T07dynamic15ConcreteDerivedC6methodySiFAA11GenericBaseCADyxFTV [override]     // vtable thunk for dynamic.GenericBase.method(A) -> () dispatching to dynamic.ConcreteDerived.method(Swift.Int) -> ()
+// CHECK-NEXT: #GenericBase.method!1: <T> (GenericBase<T>) -> (T) -> () : public _T07dynamic15ConcreteDerivedC6methodyySiFAA11GenericBaseCADyyxFTV [override]     // vtable thunk for dynamic.GenericBase.method(A) -> () dispatching to dynamic.ConcreteDerived.method(Swift.Int) -> ()
 // CHECK-NEXT: #GenericBase.init!initializer.1: <T> (GenericBase<T>.Type) -> () -> GenericBase<T> : _T07dynamic15ConcreteDerivedCACycfc [override]      // dynamic.ConcreteDerived.init() -> dynamic.ConcreteDerived
 // CHECK-NEXT: #ConcreteDerived.deinit!deallocator: _T07dynamic15ConcreteDerivedCfD  // dynamic.ConcreteDerived.__deallocating_deinit
 // CHECK-NEXT: }
diff --git a/test/SILGen/dynamic_lookup.swift b/test/SILGen/dynamic_lookup.swift
index 620fb88..9100cf0 100644
--- a/test/SILGen/dynamic_lookup.swift
+++ b/test/SILGen/dynamic_lookup.swift
@@ -1,5 +1,5 @@
 // RUN: %target-swift-frontend -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module %s | %FileCheck %s
-// RUN: %target-swift-frontend -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module -enable-guaranteed-closure-contexts %s | %FileCheck %s --check-prefix=GUARANTEED
+// RUN: %target-swift-frontend -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module  %s | %FileCheck %s --check-prefix=GUARANTEED
 
 // REQUIRES: objc_interop
 
@@ -345,7 +345,7 @@
   @objc optional var juice: Juice { get }
 }
 
-// CHECK-LABEL: sil hidden @_T014dynamic_lookup7consumeyAA5Fruit_pF
+// CHECK-LABEL: sil hidden @_T014dynamic_lookup7consumeyyAA5Fruit_pF
 // CHECK: bb0(%0 : $Fruit):
 // CHECK:        [[BOX:%.*]] = alloc_stack $Optional<Juice>
 // CHECK:        dynamic_method_br [[SELF:%.*]] : $@opened("{{.*}}") Fruit, #Fruit.juice!getter.1.foreign, bb1, bb2
diff --git a/test/SILGen/dynamic_lookup_throws.swift b/test/SILGen/dynamic_lookup_throws.swift
index 9d8624c..39ae4e8 100644
--- a/test/SILGen/dynamic_lookup_throws.swift
+++ b/test/SILGen/dynamic_lookup_throws.swift
@@ -11,7 +11,7 @@
    func blub() throws {}
 }
 
-// CHECK-LABEL: sil hidden @_T021dynamic_lookup_throws8testBlubyyXl1a_tKF : $@convention(thin) (@owned AnyObject) -> @error Error
+// CHECK-LABEL: sil hidden @_T021dynamic_lookup_throws8testBlub1ayyXl_tKF : $@convention(thin) (@owned AnyObject) -> @error Error
 // CHECK: bb0([[ARG:%.*]] : $AnyObject):
 func testBlub(a: AnyObject) throws {
   // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
@@ -24,7 +24,7 @@
   // CHECK:   return
 
   // CHECK: bb2
-  // CHECK:   function_ref @_T010Foundation22_convertNSErrorToErrors0E0_pSo0C0CSgF
+  // CHECK:   function_ref @_T010Foundation22_convertNSErrorToErrorys0E0_pSo0C0CSgF
   // CHECK:   throw {{%.*}} : $Error
   try a.blub()
 }
diff --git a/test/SILGen/dynamic_self.swift b/test/SILGen/dynamic_self.swift
index 3488e58..d103590 100644
--- a/test/SILGen/dynamic_self.swift
+++ b/test/SILGen/dynamic_self.swift
@@ -106,7 +106,7 @@
   @objc func method() -> Self { return self }
 }
 
-// CHECK-LABEL: sil hidden @_T012dynamic_self21testAnyObjectDispatchyyXl1o_tF : $@convention(thin) (@owned AnyObject) -> () {
+// CHECK-LABEL: sil hidden @_T012dynamic_self21testAnyObjectDispatch1oyyXl_tF : $@convention(thin) (@owned AnyObject) -> () {
 func testAnyObjectDispatch(o: AnyObject) {
   // CHECK: dynamic_method_br [[O_OBJ:%[0-9]+]] : $@opened({{.*}}) AnyObject, #ObjC.method!1.foreign, bb1, bb2
 
@@ -115,7 +115,7 @@
   // CHECK:   [[VAR_9:%[0-9]+]] = partial_apply [callee_guaranteed] [[METHOD]]([[O_OBJ_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @autoreleased AnyObject
   var _ = o.method
 }
-// CHECK: } // end sil function '_T012dynamic_self21testAnyObjectDispatchyyXl1o_tF'
+// CHECK: } // end sil function '_T012dynamic_self21testAnyObjectDispatch1oyyXl_tF'
 
 
 // <rdar://problem/16270889> Dispatch through ObjC metatypes.
@@ -155,7 +155,7 @@
   v.foo()?.bar()
 }
 
-// CHECK-LABEL: sil hidden @_T012dynamic_self18testOptionalResultyAA0dE9InheritorC1v_tF : $@convention(thin) (@owned OptionalResultInheritor) -> () {
+// CHECK-LABEL: sil hidden @_T012dynamic_self18testOptionalResult1vyAA0dE9InheritorC_tF : $@convention(thin) (@owned OptionalResultInheritor) -> () {
 // CHECK: bb0([[ARG:%.*]] : $OptionalResultInheritor):
 // CHECK:      [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:      [[CAST_BORROWED_ARG:%.*]] = upcast [[BORROWED_ARG]]
@@ -170,13 +170,13 @@
 
   required init() {}
 
-  // CHECK-LABEL: sil hidden @_T012dynamic_self1ZC23testDynamicSelfCapturesACXDSi1x_tF : $@convention(method) (Int, @guaranteed Z) -> @owned Z {
+  // CHECK-LABEL: sil hidden @_T012dynamic_self1ZC23testDynamicSelfCaptures1xACXDSi_tF : $@convention(method) (Int, @guaranteed Z) -> @owned Z {
   func testDynamicSelfCaptures(x: Int) -> Self {
     // CHECK: bb0({{.*}}, [[SELF:%.*]] : $Z):
 
     // Single capture of 'self' type
 
-    // CHECK:      [[FN:%.*]] = function_ref @_T012dynamic_self1ZC23testDynamicSelfCapturesACXDSi1x_tFyycfU_ : $@convention(thin) (@guaranteed Z) -> ()
+    // CHECK:      [[FN:%.*]] = function_ref @_T012dynamic_self1ZC23testDynamicSelfCaptures1xACXDSi_tFyycfU_ : $@convention(thin) (@guaranteed Z) -> ()
     // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Z
     // CHECK-NEXT: partial_apply [callee_guaranteed] [[FN]]([[SELF_COPY]])
     let fn1 = { _ = self }
@@ -185,7 +185,7 @@
     // Capturing 'self', but it's not the last capture. Make sure it ends
     // up at the end of the list anyway
 
-    // CHECK:      [[FN:%.*]] = function_ref @_T012dynamic_self1ZC23testDynamicSelfCapturesACXDSi1x_tFyycfU0_ : $@convention(thin) (Int, @guaranteed Z) -> ()
+    // CHECK:      [[FN:%.*]] = function_ref @_T012dynamic_self1ZC23testDynamicSelfCaptures1xACXDSi_tFyycfU0_ : $@convention(thin) (Int, @guaranteed Z) -> ()
     // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Z
     // CHECK-NEXT: partial_apply [callee_guaranteed] [[FN]]({{.*}}, [[SELF_COPY]])
     let fn2 = {
@@ -198,7 +198,7 @@
     // so that IRGen can recover metadata.
 
     // CHECK:      [[WEAK_SELF:%.*]] = alloc_box ${ var @sil_weak Optional<Z> }
-    // CHECK:      [[FN:%.*]] = function_ref @_T012dynamic_self1ZC23testDynamicSelfCapturesACXDSi1x_tFyycfU1_ : $@convention(thin) (@guaranteed { var @sil_weak Optional<Z> }, @thick @dynamic_self Z.Type) -> ()
+    // CHECK:      [[FN:%.*]] = function_ref @_T012dynamic_self1ZC23testDynamicSelfCaptures1xACXDSi_tFyycfU1_ : $@convention(thin) (@guaranteed { var @sil_weak Optional<Z> }, @thick @dynamic_self Z.Type) -> ()
     // CHECK:      [[WEAK_SELF_COPY:%.*]] = copy_value [[WEAK_SELF]] : ${ var @sil_weak Optional<Z> }
     // CHECK-NEXT: [[DYNAMIC_SELF:%.*]] = metatype $@thick @dynamic_self Z.Type
     // CHECK:      partial_apply [callee_guaranteed] [[FN]]([[WEAK_SELF_COPY]], [[DYNAMIC_SELF]]) : $@convention(thin) (@guaranteed { var @sil_weak Optional<Z> }, @thick @dynamic_self Z.Type) -> ()
@@ -210,7 +210,7 @@
 
     // Capturing a value with a complex type involving self
 
-    // CHECK:      [[FN:%.*]] = function_ref @_T012dynamic_self1ZC23testDynamicSelfCapturesACXDSi1x_tFyycfU2_ : $@convention(thin) (@guaranteed (Z, Z), @thick @dynamic_self Z.Type) -> ()
+    // CHECK:      [[FN:%.*]] = function_ref @_T012dynamic_self1ZC23testDynamicSelfCaptures1xACXDSi_tFyycfU2_ : $@convention(thin) (@guaranteed (Z, Z), @thick @dynamic_self Z.Type) -> ()
     let xx = (self, self)
     let fn4 = {
       _ = xx
@@ -259,7 +259,7 @@
   static func staticNewInstance() -> Self { return self.init() }
 }
 
-// CHECK-LABEL: sil hidden @_T012dynamic_self22partialApplySelfReturnyAA7FactoryC1c_ADm1ttF : $@convention(thin) (@owned Factory, @thick Factory.Type) -> ()
+// CHECK-LABEL: sil hidden @_T012dynamic_self22partialApplySelfReturn1c1tyAA7FactoryC_AFmtF : $@convention(thin) (@owned Factory, @thick Factory.Type) -> ()
 func partialApplySelfReturn(c: Factory, t: Factory.Type) {
   // CHECK: function_ref @_T012dynamic_self7FactoryC11newInstanceACXDyFTc : $@convention(thin) (@owned Factory) -> @owned @callee_guaranteed () -> @owned Factory
   _ = c.newInstance
diff --git a/test/SILGen/enum.swift b/test/SILGen/enum.swift
index 2ecc760..3a7d988 100644
--- a/test/SILGen/enum.swift
+++ b/test/SILGen/enum.swift
@@ -30,11 +30,11 @@
   case mere(Int)
 }
 
-// CHECK-LABEL: sil hidden @_T0s16Optionable_casesySiF
+// CHECK-LABEL: sil hidden @_T0s16Optionable_casesyySiF
 func Optionable_cases(_ x: Int) {
 
   // CHECK:       [[METATYPE:%.*]] = metatype $@thin Optionable.Type
-  // CHECK:       [[FN:%.*]] = function_ref @_T0s10OptionableO4mereABSicABmF
+  // CHECK:       [[FN:%.*]] = function_ref @_T0s10OptionableO4mereyABSicABmF
   // CHECK-NEXT:  [[CTOR:%.*]] = apply [[FN]]([[METATYPE]])
   // CHECK-NEXT:  destroy_value [[CTOR]]
   _ = Optionable.mere
@@ -44,13 +44,13 @@
   _ = Optionable.mere(x)
 }
 
-// CHECK-LABEL: sil shared [transparent] [thunk] @_T0s10OptionableO4mereABSicABmF
-// CHECK:        [[FN:%.*]] = function_ref @_T0s10OptionableO4mereABSicABmF
+// CHECK-LABEL: sil shared [transparent] [thunk] @_T0s10OptionableO4mereyABSicABmF
+// CHECK:        [[FN:%.*]] = function_ref @_T0s10OptionableO4mereyABSicABmF
 // CHECK-NEXT:   [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]](%0)
 // CHECK-NEXT:   return [[METHOD]]
 // CHECK-NEXT: }
 
-// CHECK-LABEL: sil shared [transparent] @_T0s10OptionableO4mereABSicABmF
+// CHECK-LABEL: sil shared [transparent] @_T0s10OptionableO4mereyABSicABmF
 // CHECK:        [[RES:%.*]] = enum $Optionable, #Optionable.mere!enumelt.1, %0 : $Int
 // CHECK-NEXT:   return [[RES]] : $Optionable
 // CHECK-NEXT: }
@@ -64,11 +64,11 @@
   case phantom(S)
 }
 
-// CHECK-LABEL: sil hidden @_T0s17AddressOnly_casesys1SVF
+// CHECK-LABEL: sil hidden @_T0s17AddressOnly_casesyys1SVF
 func AddressOnly_cases(_ s: S) {
 
   // CHECK:       [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type
-  // CHECK:       [[FN:%.*]] = function_ref @_T0s11AddressOnlyO4mereABs1P_pcABmF
+  // CHECK:       [[FN:%.*]] = function_ref @_T0s11AddressOnlyO4mereyABs1P_pcABmF
   // CHECK-NEXT:  [[CTOR:%.*]] = apply [[FN]]([[METATYPE]])
   // CHECK-NEXT:  destroy_value [[CTOR]]
   _ = AddressOnly.mere
@@ -104,13 +104,13 @@
   // CHECK:       return
 }
 
-// CHECK-LABEL: sil shared [transparent] [thunk] @_T0s11AddressOnlyO4mereABs1P_pcABmF
-// CHECK:       [[FN:%.*]] = function_ref @_T0s11AddressOnlyO4mereABs1P_pcABmF
+// CHECK-LABEL: sil shared [transparent] [thunk] @_T0s11AddressOnlyO4mereyABs1P_pcABmF
+// CHECK:       [[FN:%.*]] = function_ref @_T0s11AddressOnlyO4mereyABs1P_pcABmF
 // CHECK-NEXT:  [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]](%0)
 // CHECK-NEXT:  return [[METHOD]] : $@callee_guaranteed (@in P) -> @out AddressOnly
 // CHECK-NEXT: }
 
-// CHECK-LABEL: sil shared [transparent] @_T0s11AddressOnlyO4mereABs1P_pcABmF
+// CHECK-LABEL: sil shared [transparent] @_T0s11AddressOnlyO4mereyABs1P_pcABmF
 // CHECK:        [[RET_DATA:%.*]] = init_enum_data_addr %0 : $*AddressOnly, #AddressOnly.mere!enumelt.1
 // CHECK-NEXT:   copy_addr [take] %1 to [initialization] [[RET_DATA]] : $*P
 // CHECK-NEXT:   inject_enum_addr %0 : $*AddressOnly, #AddressOnly.mere!enumelt.1
@@ -122,7 +122,7 @@
   case mere(T)
 }
 
-// CHECK-LABEL: sil hidden @_T0s20PolyOptionable_casesyxlF
+// CHECK-LABEL: sil hidden @_T0s20PolyOptionable_casesyyxlF
 func PolyOptionable_cases<T>(_ t: T) {
 
 // CHECK:         [[METATYPE:%.*]] = metatype $@thin PolyOptionable<T>.Type
@@ -149,7 +149,7 @@
 
 // The substituted type is loadable and trivial here
 
-// CHECK-LABEL: sil hidden @_T0s32PolyOptionable_specialized_casesySiF
+// CHECK-LABEL: sil hidden @_T0s32PolyOptionable_specialized_casesyySiF
 func PolyOptionable_specialized_cases(_ t: Int) {
 
 // CHECK:         [[METATYPE:%.*]] = metatype $@thin PolyOptionable<Int>.Type
@@ -171,13 +171,13 @@
 
 enum Foo { case A(P, String) }
 
-// CHECK-LABEL: sil shared [transparent] [thunk] @_T0s3FooO1AABs1P_p_SStcABmF
-// CHECK:         [[FN:%.*]] = function_ref @_T0s3FooO1AABs1P_p_SStcABmF
+// CHECK-LABEL: sil shared [transparent] [thunk] @_T0s3FooO1AyABs1P_p_SStcABmF
+// CHECK:         [[FN:%.*]] = function_ref @_T0s3FooO1AyABs1P_p_SStcABmF
 // CHECK-NEXT:    [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]](%0)
 // CHECK-NEXT:    return [[METHOD]]
 // CHECK-NEXT:  }
 
-// CHECK-LABEL: sil shared [transparent] @_T0s3FooO1AABs1P_p_SStcABmF
+// CHECK-LABEL: sil shared [transparent] @_T0s3FooO1AyABs1P_p_SStcABmF
 // CHECK:         [[PAYLOAD:%.*]] = init_enum_data_addr %0 : $*Foo, #Foo.A!enumelt.1
 // CHECK-NEXT:    [[LEFT:%.*]] = tuple_element_addr [[PAYLOAD]] : $*(P, String), 0
 // CHECK-NEXT:    [[RIGHT:%.*]] = tuple_element_addr [[PAYLOAD]] : $*(P, String), 1
diff --git a/test/SILGen/enum_resilience.swift b/test/SILGen/enum_resilience.swift
index 41a265e..fa94ab1 100644
--- a/test/SILGen/enum_resilience.swift
+++ b/test/SILGen/enum_resilience.swift
@@ -8,7 +8,7 @@
 // Resilient enums are always address-only, and switches must include
 // a default case
 
-// CHECK-LABEL: sil hidden @_T015enum_resilience15resilientSwitchy0c1_A06MediumOF : $@convention(thin) (@in Medium) -> ()
+// CHECK-LABEL: sil hidden @_T015enum_resilience15resilientSwitchyy0c1_A06MediumOF : $@convention(thin) (@in Medium) -> ()
 // CHECK:         [[BOX:%.*]] = alloc_stack $Medium
 // CHECK-NEXT:    copy_addr %0 to [initialization] [[BOX]]
 // CHECK-NEXT:    switch_enum_addr [[BOX]] : $*Medium, case #Medium.Paper!enumelt: bb1, case #Medium.Canvas!enumelt: bb2, case #Medium.Pamphlet!enumelt.1: bb3, case #Medium.Postcard!enumelt.1: bb4, default bb5
@@ -50,7 +50,7 @@
 // as part of the value, so we cannot resiliently make assumptions about the
 // enum's size
 
-// CHECK-LABEL: sil hidden @_T015enum_resilience21indirectResilientEnumy010resilient_A016IndirectApproachOF : $@convention(thin) (@in IndirectApproach) -> ()
+// CHECK-LABEL: sil hidden @_T015enum_resilience21indirectResilientEnumyy010resilient_A016IndirectApproachOF : $@convention(thin) (@in IndirectApproach) -> ()
 func indirectResilientEnum(_ ia: IndirectApproach) {}
 
 public enum MyResilientEnum {
@@ -58,7 +58,7 @@
   case loki
 }
 
-// CHECK-LABEL: sil @_T015enum_resilience15resilientSwitchyAA15MyResilientEnumOF : $@convention(thin) (@in MyResilientEnum) -> ()
+// CHECK-LABEL: sil @_T015enum_resilience15resilientSwitchyyAA15MyResilientEnumOF : $@convention(thin) (@in MyResilientEnum) -> ()
 // CHECK:      switch_enum_addr %2 : $*MyResilientEnum, case #MyResilientEnum.kevin!enumelt: bb1, case #MyResilientEnum.loki!enumelt: bb2 //
 // CHECK:      return
 public func resilientSwitch(_ e: MyResilientEnum) {
@@ -70,7 +70,7 @@
 
 // Inlineable functions must lower the switch as if it came from outside the module
 
-// CHECK-LABEL: sil [serialized] @_T015enum_resilience16inlineableSwitchyAA15MyResilientEnumOF : $@convention(thin) (@in MyResilientEnum) -> ()
+// CHECK-LABEL: sil [serialized] @_T015enum_resilience16inlineableSwitchyyAA15MyResilientEnumOF : $@convention(thin) (@in MyResilientEnum) -> ()
 // CHECK:      switch_enum_addr %2 : $*MyResilientEnum, case #MyResilientEnum.kevin!enumelt: bb1, case #MyResilientEnum.loki!enumelt: bb2, default bb3
 // CHECK:      return
 @_inlineable public func inlineableSwitch(_ e: MyResilientEnum) {
diff --git a/test/SILGen/errors.swift b/test/SILGen/errors.swift
index e735a22..62418c6 100644
--- a/test/SILGen/errors.swift
+++ b/test/SILGen/errors.swift
@@ -47,7 +47,7 @@
   throw HomeworkError.TooMuch
 }
 
-// CHECK:    sil hidden @_T06errors16all_together_nowAA3CatCSbF : $@convention(thin) (Bool) -> @owned Cat {
+// CHECK:    sil hidden @_T06errors16all_together_nowyAA3CatCSbF : $@convention(thin) (Bool) -> @owned Cat {
 // CHECK:    bb0(%0 : @trivial $Bool):
 // CHECK:      [[RET_TEMP:%.*]] = alloc_stack $Cat
 
@@ -301,11 +301,11 @@
 func testForceTry(_ fn: () -> Int) {
   try! createInt(fn)
 }
-// CHECK-LABEL: sil hidden @_T06errors12testForceTryySiycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> Int) -> ()
+// CHECK-LABEL: sil hidden @_T06errors12testForceTryyySiycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> Int) -> ()
 // CHECK: bb0([[ARG:%.*]] : @owned $@noescape @callee_guaranteed () -> Int):
 // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
-// CHECK: [[FUNC:%.*]] = function_ref @_T06errors9createIntySiycKF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> Int) -> @error Error
+// CHECK: [[FUNC:%.*]] = function_ref @_T06errors9createIntyySiycKF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> Int) -> @error Error
 // CHECK: try_apply [[FUNC]]([[ARG_COPY]])
 // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK: destroy_value [[ARG]]
@@ -378,7 +378,7 @@
   }
 }
 // errors.getHungryCat throws (errors.CatFood) -> errors.Cat
-// CHECK-LABEL: sil hidden @_T06errors12getHungryCatAA0D0CAA0D4FoodOKF : $@convention(thin) (CatFood) -> (@owned Cat, @error Error)
+// CHECK-LABEL: sil hidden @_T06errors12getHungryCatyAA0D0CAA0D4FoodOKF : $@convention(thin) (CatFood) -> (@owned Cat, @error Error)
 // CHECK: bb0(%0 : @trivial $CatFood):
 // CHECK:   debug_value undef : $Error, var, name "$error", argno 2
 // CHECK:   switch_enum %0 : $CatFood, case #CatFood.Canned!enumelt: bb1, case #CatFood.Dry!enumelt: bb3
@@ -400,7 +400,7 @@
   try take_many_cats(make_a_cat(), cat, make_a_cat(), make_a_cat())
 }
 
-// CHECK-LABEL: sil hidden @_T06errors13test_variadicyAA3CatCKF : $@convention(thin) (@owned Cat) -> @error Error {
+// CHECK-LABEL: sil hidden @_T06errors13test_variadicyyAA3CatCKF : $@convention(thin) (@owned Cat) -> @error Error {
 // CHECK:       bb0([[ARG:%.*]] : @owned $Cat):
 // CHECK:         debug_value undef : $Error, var, name "$error", argno 2
 // CHECK:         [[N:%.*]] = integer_literal $Builtin.Word, 4
@@ -441,7 +441,7 @@
 // CHECK:       [[NORM_3]]([[CAT3:%.*]] : @owned $Cat):
 // CHECK-NEXT:    store [[CAT3]] to [init] [[ELT3]]
 //   Complete the call and return.
-// CHECK:         [[TAKE_FN:%.*]] = function_ref @_T06errors14take_many_catsyAA3CatCd_tKF : $@convention(thin) (@owned Array<Cat>) -> @error Error
+// CHECK:         [[TAKE_FN:%.*]] = function_ref @_T06errors14take_many_catsyyAA3CatCd_tKF : $@convention(thin) (@owned Array<Cat>) -> @error Error
 // CHECK-NEXT:    try_apply [[TAKE_FN]]([[ARRAY]]) : $@convention(thin) (@owned Array<Cat>) -> @error Error, normal [[NORM_CALL:bb[0-9]+]], error [[ERR_CALL:bb[0-9]+]]
 // CHECK:       [[NORM_CALL]]([[T0:%.*]] : @trivial $()):
 // CHECK-NEXT:    end_borrow [[BORROWED_ARG]] from [[ARG]]
@@ -482,7 +482,7 @@
 // CHECK:       [[RETHROW]]([[ERROR:%.*]] : @owned $Error):
 // CHECK-NEXT:    destroy_value [[ARG]] : $Cat
 // CHECK-NEXT:    throw [[ERROR]]
-// CHECK: } // end sil function '_T06errors13test_variadicyAA3CatCKF'
+// CHECK: } // end sil function '_T06errors13test_variadicyyAA3CatCKF'
 
 // rdar://20861374
 // Clear out the self box before delegating.
@@ -507,7 +507,7 @@
 //   Super delegation.
 // CHECK-NEXT: [[T0:%.*]] = load [take] [[PB]]
 // CHECK-NEXT: [[T2:%.*]] = upcast [[T0]] : $BaseThrowingInit to $HasThrowingInit
-// CHECK: [[T3:%[0-9]+]] = function_ref @_T06errors15HasThrowingInitCACSi5value_tKcfc : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error)
+// CHECK: [[T3:%[0-9]+]] = function_ref @_T06errors15HasThrowingInitC5valueACSi_tKcfc : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error)
 // CHECK-NEXT: apply [[T3]](%0, [[T2]])
 
 // Cleanups for writebacks.
@@ -603,7 +603,7 @@
 func supportStructure(_ b: inout Bridge, name: String) throws {
   try b[name].support()
 }
-// CHECK:    sil hidden @_T06errors16supportStructureyAA6BridgeVz_SS4nametKF : $@convention(thin) (@inout Bridge, @owned String) -> @error Error {
+// CHECK:    sil hidden @_T06errors16supportStructure_4nameyAA6BridgeVz_SStKF : $@convention(thin) (@inout Bridge, @owned String) -> @error Error {
 // CHECK:    bb0([[ARG1:%.*]] : @trivial $*Bridge, [[ARG2:%.*]] : @owned $String):
 // CHECK:      [[BORROWED_ARG2:%.*]] = begin_borrow [[ARG2]]
 // CHECK-NEXT: [[INDEX_COPY_1:%.*]] = copy_value [[BORROWED_ARG2]] : $String
@@ -612,7 +612,7 @@
 // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Pylon
 // CHECK-NEXT: [[BASE:%.*]] = load_borrow [[WRITE]] : $*Bridge
 // CHECK-NEXT: // function_ref
-// CHECK-NEXT: [[GETTER:%.*]] = function_ref @_T06errors6BridgeVAA5PylonVSScig :
+// CHECK-NEXT: [[GETTER:%.*]] = function_ref @_T06errors6BridgeVyAA5PylonVSScig :
 // CHECK-NEXT: [[T0:%.*]] = apply [[GETTER]]([[INDEX_COPY_1]], [[BASE]])
 // CHECK-NEXT: store [[T0]] to [init] [[TEMP]]
 // CHECK-NEXT: end_borrow [[BASE]] from [[WRITE]]
@@ -622,7 +622,7 @@
 // CHECK:    [[BB_NORMAL]]
 // CHECK-NEXT: [[T0:%.*]] = load [take] [[TEMP]]
 // CHECK-NEXT: // function_ref
-// CHECK-NEXT: [[SETTER:%.*]] = function_ref @_T06errors6BridgeVAA5PylonVSScis :
+// CHECK-NEXT: [[SETTER:%.*]] = function_ref @_T06errors6BridgeVyAA5PylonVSScis :
 // CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2]], [[WRITE]])
 // CHECK-NEXT: end_access [[WRITE]]
 // CHECK-NEXT: dealloc_stack [[TEMP]]
@@ -637,7 +637,7 @@
 // CHECK-NEXT: [[T0:%.*]] = load [copy] [[TEMP]]
 // CHECK-NEXT: [[INDEX_COPY_2_COPY:%.*]] = copy_value [[INDEX_COPY_2]]
 // CHECK-NEXT: // function_ref
-// CHECK-NEXT: [[SETTER:%.*]] = function_ref @_T06errors6BridgeVAA5PylonVSScis :
+// CHECK-NEXT: [[SETTER:%.*]] = function_ref @_T06errors6BridgeVyAA5PylonVSScis :
 // CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2_COPY]], [[WRITE]])
 // CHECK-NEXT: destroy_addr [[TEMP]]
 // CHECK-NEXT: dealloc_stack [[TEMP]]
@@ -647,7 +647,7 @@
 // CHECK-NEXT: end_borrow [[BORROWED_INDEX]] from [[INDEX]]
 // CHECK-NEXT: destroy_value [[INDEX]] : $String
 // CHECK-NEXT: throw [[ERROR]]
-// CHECK: } // end sil function '_T06errors16supportStructureyAA6BridgeVz_SS4nametKF'
+// CHECK: } // end sil function '_T06errors16supportStructure_4nameyAA6BridgeVz_SStKF'
 
 struct OwnedBridge {
   var owner : AnyObject
@@ -659,13 +659,13 @@
 func supportStructure(_ b: inout OwnedBridge, name: String) throws {
   try b[name].support()
 }
-// CHECK:    sil hidden @_T06errors16supportStructureyAA11OwnedBridgeVz_SS4nametKF :
+// CHECK:    sil hidden @_T06errors16supportStructure_4nameyAA11OwnedBridgeVz_SStKF :
 // CHECK:    bb0([[ARG1:%.*]] : @trivial $*OwnedBridge, [[ARG2:%.*]] : @owned $String):
 // CHECK:      [[BORROWED_ARG2:%.*]] = begin_borrow [[ARG2]]
 // CHECK:      [[ARG2_COPY:%.*]] = copy_value [[BORROWED_ARG2]] : $String
 // CHECK:      [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*OwnedBridge
 // CHECK-NEXT: // function_ref
-// CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @_T06errors11OwnedBridgeVAA5PylonVSSciaO :
+// CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @_T06errors11OwnedBridgeVyAA5PylonVSSciaO :
 // CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[ARG2_COPY]], [[WRITE]])
 // CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]]
 // CHECK-NEXT: [[T1:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 0
@@ -691,7 +691,7 @@
 // CHECK-NEXT: end_borrow [[BORROWED_ARG2]] from [[ARG2]]
 // CHECK-NEXT: destroy_value [[ARG2]] : $String
 // CHECK-NEXT: throw [[ERROR]]
-// CHECK: } // end sil function '_T06errors16supportStructureyAA11OwnedBridgeVz_SS4nametKF'
+// CHECK: } // end sil function '_T06errors16supportStructure_4nameyAA11OwnedBridgeVz_SStKF'
 
 struct PinnedBridge {
   var owner : Builtin.NativeObject
@@ -703,13 +703,13 @@
 func supportStructure(_ b: inout PinnedBridge, name: String) throws {
   try b[name].support()
 }
-// CHECK:      sil hidden @_T06errors16supportStructureyAA12PinnedBridgeVz_SS4nametKF :
+// CHECK:      sil hidden @_T06errors16supportStructure_4nameyAA12PinnedBridgeVz_SStKF :
 // CHECK:      bb0([[ARG1:%.*]] : @trivial $*PinnedBridge, [[ARG2:%.*]] : @owned $String):
 // CHECK:        [[BORROWED_ARG2:%.*]] = begin_borrow [[ARG2]]
 // CHECK:        [[ARG2_COPY:%.*]] = copy_value [[BORROWED_ARG2]] : $String
 // CHECK-NEXT:   [[WRITE:%.*]] = begin_access [modify] [unknown] [[ARG1]] : $*PinnedBridge
 // CHECK-NEXT:   // function_ref
-// CHECK-NEXT:   [[ADDRESSOR:%.*]] = function_ref @_T06errors12PinnedBridgeVAA5PylonVSSciaP :
+// CHECK-NEXT:   [[ADDRESSOR:%.*]] = function_ref @_T06errors12PinnedBridgeVyAA5PylonVSSciaP :
 // CHECK-NEXT:   [[T0:%.*]] = apply [[ADDRESSOR]]([[ARG2_COPY]], [[WRITE]])
 // CHECK-NEXT:   [[BORROWED_T0:%.*]] = begin_borrow [[T0]]
 // CHECK-NEXT:   [[T1:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 0
@@ -737,7 +737,7 @@
 // CHECK-NEXT:   end_borrow [[BORROWED_ARG2]] from [[ARG2]]
 // CHECK-NEXT:   destroy_value [[ARG2]] : $String
 // CHECK-NEXT:   throw [[ERROR]]
-// CHECK: } // end sil function '_T06errors16supportStructureyAA12PinnedBridgeVz_SS4nametKF'
+// CHECK: } // end sil function '_T06errors16supportStructure_4nameyAA12PinnedBridgeVz_SStKF'
 
 // ! peepholes its argument with getSemanticsProvidingExpr().
 // Test that that doesn't look through try!.
@@ -829,7 +829,7 @@
 // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : @owned $Error):
 // CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T
 // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
-// CHECK: } // end sil function '_T06errors26testOptionalTryAddressOnlyyxlF'
+// CHECK: } // end sil function '_T06errors26testOptionalTryAddressOnlyyyxlF'
 func testOptionalTryAddressOnly<T>(_ obj: T) {
   _ = try? dont_return(obj)
 }
@@ -859,7 +859,7 @@
 // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : @owned $Error):
 // CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T
 // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
-// CHECK: } // end sil function '_T06errors29testOptionalTryAddressOnlyVaryxlF'
+// CHECK: } // end sil function '_T06errors29testOptionalTryAddressOnlyVaryyxlF'
 func testOptionalTryAddressOnlyVar<T>(_ obj: T) {
   var copy = try? dont_return(obj) // expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}}
 }
@@ -929,7 +929,7 @@
 // CHECK-NEXT:   destroy_addr %0 : $*T
 // CHECK-NEXT:   [[VOID:%.+]] = tuple ()
 // CHECK-NEXT:   return [[VOID]] : $()
-// CHECK-NEXT: } // end sil function '_T06errors36testOptionalTryNeverFailsAddressOnlyyxlF'
+// CHECK-NEXT: } // end sil function '_T06errors36testOptionalTryNeverFailsAddressOnlyyyxlF'
 func testOptionalTryNeverFailsAddressOnly<T>(_ obj: T) {
   _ = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}}
 }
diff --git a/test/SILGen/existential_erasure.swift b/test/SILGen/existential_erasure.swift
index 3b2eebb..f21eaf3 100644
--- a/test/SILGen/existential_erasure.swift
+++ b/test/SILGen/existential_erasure.swift
@@ -38,7 +38,7 @@
 // Make sure uninitialized existentials are properly deallocated when we
 // have an early return.
 
-// CHECK-LABEL: sil hidden @_T019existential_erasure19openExistentialToP1yAA1P_pKF
+// CHECK-LABEL: sil hidden @_T019existential_erasure19openExistentialToP1yyAA1P_pKF
 func openExistentialToP1(_ p: P) throws {
 // CHECK: bb0(%0 : @trivial $*P):
 // CHECK:   [[OPEN:%.*]] = open_existential_addr immutable_access %0 : $*P to $*[[OPEN_TYPE:@opened\(.*\) P]]
@@ -63,7 +63,7 @@
   try useP(p.downgrade(throwingFunc()))
 }
 
-// CHECK-LABEL: sil hidden @_T019existential_erasure19openExistentialToP2yAA1P_pKF
+// CHECK-LABEL: sil hidden @_T019existential_erasure19openExistentialToP2yyAA1P_pKF
 func openExistentialToP2(_ p: P) throws {
 // CHECK: bb0(%0 : @trivial $*P):
 // CHECK:   [[OPEN:%.*]] = open_existential_addr immutable_access %0 : $*P to $*[[OPEN_TYPE:@opened\(.*\) P]]
@@ -94,7 +94,7 @@
   }
 }
 
-// CHECK-LABEL: sil hidden @_T019existential_erasure12errorHandlers5Error_psAC_pKF
+// CHECK-LABEL: sil hidden @_T019existential_erasure12errorHandlerys5Error_psAC_pKF
 func errorHandler(_ e: Error) throws -> Error {
 // CHECK: bb0([[ARG:%.*]] : @owned $Error):
 // CHECK:  debug_value [[ARG]] : $Error
diff --git a/test/SILGen/existential_metatypes.swift b/test/SILGen/existential_metatypes.swift
index 0da29eb..d158855 100644
--- a/test/SILGen/existential_metatypes.swift
+++ b/test/SILGen/existential_metatypes.swift
@@ -14,7 +14,7 @@
   static var value: Value { return Value() }
 }
 
-// CHECK-LABEL: sil hidden @_T021existential_metatypes0A8MetatypeyAA1P_pF
+// CHECK-LABEL: sil hidden @_T021existential_metatypes0A8MetatypeyyAA1P_pF
 // CHECK: bb0([[X:%.*]] : @trivial $*P):
 func existentialMetatype(_ x: P) {
   // CHECK: [[TYPE1:%.*]] = existential_metatype $@thick P.Type, [[X]]
@@ -40,7 +40,7 @@
 protocol PP: P {}
 protocol Q {}
 
-// CHECK-LABEL: sil hidden @_T021existential_metatypes0A15MetatypeUpcast1AA1P_pXpAA2PP_pXpF
+// CHECK-LABEL: sil hidden @_T021existential_metatypes0A15MetatypeUpcast1yAA1P_pXpAA2PP_pXpF
 // CHECK:         [[OPENED:%.*]] = open_existential_metatype %0
 // CHECK:         [[NEW:%.*]] = init_existential_metatype [[OPENED]]
 // CHECK:         return [[NEW]]
@@ -48,7 +48,7 @@
   return x
 }
 
-// CHECK-LABEL: sil hidden @_T021existential_metatypes0A15MetatypeUpcast2AA1P_pXpAaC_AA1QpXpF
+// CHECK-LABEL: sil hidden @_T021existential_metatypes0A15MetatypeUpcast2yAA1P_pXpAaC_AA1QpXpF
 // CHECK:         [[OPENED:%.*]] = open_existential_metatype %0
 // CHECK:         [[NEW:%.*]] = init_existential_metatype [[OPENED]]
 // CHECK:         return [[NEW]]
diff --git a/test/SILGen/expressions.swift b/test/SILGen/expressions.swift
index 89ca6d4..b230fa3 100644
--- a/test/SILGen/expressions.swift
+++ b/test/SILGen/expressions.swift
@@ -94,10 +94,10 @@
 // CHECK: string_literal utf8 "foo"
 // CHECK: [[CONST_STRING_LIT:%.*]] = const_string_literal utf8 "foobar"
 // CHECK: [[METATYPE:%.*]] = metatype $@thin SillyConstUTF16String.Type
-// CHECK: [[FUN:%.*]] = function_ref @_T011expressions21SillyConstUTF16StringVACBp08_builtincE7Literal_tcfC : $@convention(method) (Builtin.RawPointer, @thin SillyConstUTF16String.Type) -> SillyConstUTF16String
+// CHECK: [[FUN:%.*]] = function_ref @_T011expressions21SillyConstUTF16StringV08_builtincE7LiteralACBp_tcfC : $@convention(method) (Builtin.RawPointer, @thin SillyConstUTF16String.Type) -> SillyConstUTF16String
 // CHECK: apply [[FUN]]([[CONST_STRING_LIT]], [[METATYPE]]) : $@convention(method) (Builtin.RawPointer, @thin SillyConstUTF16String.Type) -> SillyConstUTF16String
 // CHECK: [[CONST_UTF16STRING_LIT:%.*]] = const_string_literal utf16 "foobarö"
-// CHECK: [[FUN:%.*]] = function_ref @_T011expressions21SillyConstUTF16StringVACBp08_builtincdE7Literal_tcfC : $@convention(method) (Builtin.RawPointer, @thin SillyConstUTF16String.Type) -> SillyConstUTF16String
+// CHECK: [[FUN:%.*]] = function_ref @_T011expressions21SillyConstUTF16StringV08_builtincdE7LiteralACBp_tcfC : $@convention(method) (Builtin.RawPointer, @thin SillyConstUTF16String.Type) -> SillyConstUTF16String
 // CHECK: apply [[FUN]]([[CONST_UTF16STRING_LIT]], {{.*}}) : $@convention(method) (Builtin.RawPointer, @thin SillyConstUTF16String.Type) -> SillyConstUTF16String
 
 func bar(_ x: Int) {}
@@ -583,7 +583,7 @@
 
 
 // <rdar://problem/18851497> Swiftc fails to compile nested destructuring tuple binding
-// CHECK-LABEL: sil hidden @_T011expressions21implodeRecursiveTupleySi_Sit_SitSgF
+// CHECK-LABEL: sil hidden @_T011expressions21implodeRecursiveTupleyySi_Sit_SitSgF
 // CHECK: bb0(%0 : @trivial $Optional<((Int, Int), Int)>):
 func implodeRecursiveTuple(_ expr: ((Int, Int), Int)?) {
 
diff --git a/test/SILGen/extensions.swift b/test/SILGen/extensions.swift
index aa1fe8f..37f8a69 100644
--- a/test/SILGen/extensions.swift
+++ b/test/SILGen/extensions.swift
@@ -23,7 +23,7 @@
   func zoom() {}
 }
 
-// CHECK-LABEL: sil hidden @_T010extensions19extensionReferencesyAA3FooCF
+// CHECK-LABEL: sil hidden @_T010extensions19extensionReferencesyyAA3FooCF
 func extensionReferences(_ x: Foo) {
   // Non-objc extension methods are statically dispatched.
   // CHECK: function_ref @_T010extensions3FooC4zang{{[_0-9a-zA-Z]*}}F
@@ -45,7 +45,7 @@
 // CHECK-LABEL: sil hidden [transparent] @_T010extensions3BoxV1txSgvpfi : $@convention(thin) <T> () -> @out Optional<T>
 // CHECK:      bb0(%0 : @trivial $*Optional<T>):
 // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Optional<T>.Type
-// CHECK:      [[FN:%.*]] = function_ref @_T0SqxSgyt10nilLiteral_tcfC : $@convention(method) <τ_0_0> (@thin Optional<τ_0_0>.Type) -> @out Optional<τ_0_0>
+// CHECK:      [[FN:%.*]] = function_ref @_T0Sq10nilLiteralxSgyt_tcfC : $@convention(method) <τ_0_0> (@thin Optional<τ_0_0>.Type) -> @out Optional<τ_0_0>
 // CHECK-NEXT: apply [[FN]]<T>(%0, [[METATYPE]]) : $@convention(method) <τ_0_0> (@thin Optional<τ_0_0>.Type) -> @out Optional<τ_0_0>
 // CHECK-NEXT: [[RESULT:%.*]] = tuple ()
 // CHECK-NEXT: return [[RESULT]] : $()
@@ -54,7 +54,7 @@
   let t: T? = nil
 }
 
-// CHECK-LABEL: sil hidden @_T010extensions3BoxVACyxGx1t_tcfC : $@convention(method) <T> (@in T, @thin Box<T>.Type) -> @out Box<T>
+// CHECK-LABEL: sil hidden @_T010extensions3BoxV1tACyxGx_tcfC : $@convention(method) <T> (@in T, @thin Box<T>.Type) -> @out Box<T>
 // CHECK:      [[SELF_BOX:%.*]] = alloc_box $<τ_0_0> { var Box<τ_0_0> } <T>
 // CHECK-NEXT: [[UNINIT_SELF_BOX:%.*]] = mark_uninitialized [rootself] [[SELF_BOX]]
 // CHECK-NEXT: [[SELF_ADDR:%.*]] = project_box [[UNINIT_SELF_BOX]] : $<τ_0_0> { var Box<τ_0_0> } <T>
diff --git a/test/SILGen/extensions_multifile.swift b/test/SILGen/extensions_multifile.swift
index 3c63079..3d997e5 100644
--- a/test/SILGen/extensions_multifile.swift
+++ b/test/SILGen/extensions_multifile.swift
@@ -1,6 +1,6 @@
 // RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/struct_with_initializer.swift -module-name extensions_multifile -enable-sil-ownership | %FileCheck %s
 
-// CHECK-LABEL: sil hidden @_T020extensions_multifile12HasInitValueVACSi1z_tcfC : $@convention(method) (Int, @thin HasInitValue.Type) -> @owned HasInitValue {
+// CHECK-LABEL: sil hidden @_T020extensions_multifile12HasInitValueV1zACSi_tcfC : $@convention(method) (Int, @thin HasInitValue.Type) -> @owned HasInitValue {
 // CHECK: function_ref @_T020extensions_multifile12HasInitValueV1xSivpfi : $@convention(thin) () -> Int
 
 // CHECK-LABEL: sil hidden_external [transparent] @_T020extensions_multifile12HasInitValueV1xSivpfi : $@convention(thin) () -> Int
diff --git a/test/SILGen/extensions_objc.swift b/test/SILGen/extensions_objc.swift
index 9336ca4..6ecf03d 100644
--- a/test/SILGen/extensions_objc.swift
+++ b/test/SILGen/extensions_objc.swift
@@ -11,7 +11,7 @@
   dynamic var cox: Int { return 0 }
 }
 
-// CHECK-LABEL: sil hidden @_T015extensions_objc19extensionReferencesyAA3FooCF
+// CHECK-LABEL: sil hidden @_T015extensions_objc19extensionReferencesyyAA3FooCF
 // CHECK: bb0([[ARG:%.*]] : @owned $Foo):
 func extensionReferences(_ x: Foo) {
   // dynamic extension methods are still dynamically dispatched.
diff --git a/test/SILGen/external_definitions.swift b/test/SILGen/external_definitions.swift
index fb679f1..9ea9776 100644
--- a/test/SILGen/external_definitions.swift
+++ b/test/SILGen/external_definitions.swift
@@ -19,7 +19,7 @@
 // CHECK:   [[NSANSE_RESULT:%.*]] = apply [[NSANSE]]([[ANSIBLE]])
 // CHECK:   destroy_value [[ANSIBLE]] : $Optional<Ansible>
 // -- Referencing unapplied C function goes through a thunk
-// CHECK:   [[NSANSE:%.*]] = function_ref @_T0SC6NSAnseSQySo7AnsibleCGADFTO : $@convention(thin) (@owned Optional<Ansible>) -> @owned Optional<Ansible>
+// CHECK:   [[NSANSE:%.*]] = function_ref @_T0SC6NSAnseySQySo7AnsibleCGADFTO : $@convention(thin) (@owned Optional<Ansible>) -> @owned Optional<Ansible>
 // -- Referencing unprototyped C function passes no parameters
 // CHECK:   [[NOPROTO:%.*]] = function_ref @hasNoPrototype : $@convention(c) () -> ()
 // CHECK:   apply [[NOPROTO]]()
@@ -31,7 +31,7 @@
 // CHECK-LABEL: sil shared [serializable] @_T0So7AnsibleC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@in Optional<Any>, @thick Ansible.Type) -> @owned Optional<Ansible>
 
 // -- Native Swift thunk for NSAnse
-// CHECK: sil shared [serialized] [thunk] @_T0SC6NSAnseSQySo7AnsibleCGADFTO : $@convention(thin) (@owned Optional<Ansible>) -> @owned Optional<Ansible> {
+// CHECK: sil shared [serialized] [thunk] @_T0SC6NSAnseySQySo7AnsibleCGADFTO : $@convention(thin) (@owned Optional<Ansible>) -> @owned Optional<Ansible> {
 // CHECK: bb0(%0 : @owned $Optional<Ansible>):
 // CHECK:   %1 = function_ref @NSAnse : $@convention(c) (Optional<Ansible>) -> @autoreleased Optional<Ansible>
 // CHECK:   %2 = apply %1(%0) : $@convention(c) (Optional<Ansible>) -> @autoreleased Optional<Ansible>
diff --git a/test/SILGen/force_cast_chained_optional.swift b/test/SILGen/force_cast_chained_optional.swift
index c5ae257..23af29e 100644
--- a/test/SILGen/force_cast_chained_optional.swift
+++ b/test/SILGen/force_cast_chained_optional.swift
@@ -11,7 +11,7 @@
 class C {}
 class D: C {}
 
-// CHECK-LABEL: sil hidden @_T027force_cast_chained_optional4testAA1DCAA3FooCF
+// CHECK-LABEL: sil hidden @_T027force_cast_chained_optional4testyAA1DCAA3FooCF
 // CHECK: bb0([[ARG:%.*]] : @owned $Foo):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   class_method [[BORROWED_ARG]] : $Foo, #Foo.bar!getter.1 : (Foo) -> () -> Bar!, $@convention(method) (@guaranteed Foo) ->
diff --git a/test/SILGen/foreach.swift b/test/SILGen/foreach.swift
index bcbdbc9..e5099ca 100644
--- a/test/SILGen/foreach.swift
+++ b/test/SILGen/foreach.swift
@@ -49,7 +49,7 @@
 // Trivial Struct
 //===----------------------------------------------------------------------===//
 
-// CHECK-LABEL: sil hidden @_T07foreach13trivialStructySaySiGF : $@convention(thin) (@owned Array<Int>) -> () {
+// CHECK-LABEL: sil hidden @_T07foreach13trivialStructyySaySiGF : $@convention(thin) (@owned Array<Int>) -> () {
 // CHECK: bb0([[ARRAY:%.*]] : @owned $Array<Int>):
 // CHECK:   [[ITERATOR_BOX:%.*]] = alloc_box ${ var IndexingIterator<Array<Int>> }, var, name "$x$generator"
 // CHECK:   [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]]
@@ -71,7 +71,7 @@
 // CHECK:   [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> ()
 // CHECK:   apply [[FUNC_END_FUNC]]()
 // CHECK:   destroy_value [[ARRAY]]
-// CHECK: } // end sil function '_T07foreach13trivialStructySaySiGF'
+// CHECK: } // end sil function '_T07foreach13trivialStructyySaySiGF'
 func trivialStruct(_ xx: [Int]) {
   for x in xx {
     loopBodyEnd()
@@ -105,7 +105,7 @@
   funcEnd()
 }
 
-// CHECK-LABEL: sil hidden @_T07foreach26trivialStructContinueBreakySaySiGF : $@convention(thin) (@owned Array<Int>) -> () {
+// CHECK-LABEL: sil hidden @_T07foreach26trivialStructContinueBreakyySaySiGF : $@convention(thin) (@owned Array<Int>) -> () {
 // CHECK: bb0([[ARRAY:%.*]] : @owned $Array<Int>):
 // CHECK:   [[ITERATOR_BOX:%.*]] = alloc_box ${ var IndexingIterator<Array<Int>> }, var, name "$x$generator"
 // CHECK:   [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]]
@@ -156,7 +156,7 @@
 // CHECK:   [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> ()
 // CHECK:   apply [[FUNC_END_FUNC]]()
 // CHECK:   destroy_value [[ARRAY]]
-// CHECK: } // end sil function '_T07foreach26trivialStructContinueBreakySaySiGF'
+// CHECK: } // end sil function '_T07foreach26trivialStructContinueBreakyySaySiGF'
 func trivialStructContinueBreak(_ xx: [Int]) {
   for x in xx {
     if (condition()) {
@@ -210,7 +210,7 @@
   funcEnd()
 }
 
-// CHECK-LABEL: sil hidden @_T07foreach24existentialContinueBreakySayAA1P_pGF : $@convention(thin) (@owned Array<P>) -> () {
+// CHECK-LABEL: sil hidden @_T07foreach24existentialContinueBreakyySayAA1P_pGF : $@convention(thin) (@owned Array<P>) -> () {
 // CHECK: bb0([[ARRAY:%.*]] : @owned $Array<P>):
 // CHECK:   [[ITERATOR_BOX:%.*]] = alloc_box ${ var IndexingIterator<Array<P>> }, var, name "$x$generator"
 // CHECK:   [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]]
@@ -270,7 +270,7 @@
 // CHECK:   [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> ()
 // CHECK:   apply [[FUNC_END_FUNC]]()
 // CHECK:   destroy_value [[ARRAY]]
-// CHECK: } // end sil function '_T07foreach24existentialContinueBreakySayAA1P_pGF'
+// CHECK: } // end sil function '_T07foreach24existentialContinueBreakyySayAA1P_pGF'
 func existentialContinueBreak(_ xx: [P]) {
   for x in xx {
     if (condition()) {
@@ -375,7 +375,7 @@
   funcEnd()
 }
 
-// CHECK-LABEL: sil hidden @_T07foreach26genericStructContinueBreakySayAA07GenericC0VyxGGlF : $@convention(thin) <T> (@owned Array<GenericStruct<T>>) -> () {
+// CHECK-LABEL: sil hidden @_T07foreach26genericStructContinueBreakyySayAA07GenericC0VyxGGlF : $@convention(thin) <T> (@owned Array<GenericStruct<T>>) -> () {
 // CHECK: bb0([[ARRAY:%.*]] : @owned $Array<GenericStruct<T>>):
 // CHECK:   [[ITERATOR_BOX:%.*]] = alloc_box $<τ_0_0> { var IndexingIterator<Array<GenericStruct<τ_0_0>>> } <T>, var, name "$x$generator"
 // CHECK:   [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]]
@@ -435,7 +435,7 @@
 // CHECK:   [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> ()
 // CHECK:   apply [[FUNC_END_FUNC]]()
 // CHECK:   destroy_value [[ARRAY]]
-// CHECK: } // end sil function '_T07foreach26genericStructContinueBreakySayAA07GenericC0VyxGGlF'
+// CHECK: } // end sil function '_T07foreach26genericStructContinueBreakyySayAA07GenericC0VyxGGlF'
 func genericStructContinueBreak<T>(_ xx: [GenericStruct<T>]) {
   for x in xx {
     if (condition()) {
@@ -488,7 +488,7 @@
   funcEnd()
 }
 
-// CHECK-LABEL: sil hidden @_T07foreach30genericCollectionContinueBreakyxs0C0RzlF : $@convention(thin) <T where T : Collection> (@in T) -> () {
+// CHECK-LABEL: sil hidden @_T07foreach30genericCollectionContinueBreakyyxs0C0RzlF : $@convention(thin) <T where T : Collection> (@in T) -> () {
 // CHECK: bb0([[COLLECTION:%.*]] : @trivial $*T):
 // CHECK:   [[ITERATOR_BOX:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : Collection> { var τ_0_0.Iterator } <T>, var, name "$x$generator"
 // CHECK:   [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]]
@@ -545,7 +545,7 @@
 // CHECK:   [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> ()
 // CHECK:   apply [[FUNC_END_FUNC]]()
 // CHECK:   destroy_addr [[COLLECTION]]
-// CHECK: } // end sil function '_T07foreach30genericCollectionContinueBreakyxs0C0RzlF'
+// CHECK: } // end sil function '_T07foreach30genericCollectionContinueBreakyyxs0C0RzlF'
 func genericCollectionContinueBreak<T : Collection>(_ xx: T) {
   for x in xx {
     if (condition()) {
@@ -567,7 +567,7 @@
 // Pattern Match Tests
 //===----------------------------------------------------------------------===//
 
-// CHECK-LABEL: sil hidden @_T07foreach13tupleElementsySayAA1CC_ADtGF
+// CHECK-LABEL: sil hidden @_T07foreach13tupleElementsyySayAA1CC_ADtGF
 func tupleElements(_ xx: [(C, C)]) {
   // CHECK: bb3([[PAYLOAD:%.*]] : @owned $(C, C)):
   // CHECK: [[BORROWED_PAYLOAD:%.*]] = begin_borrow [[PAYLOAD]]
@@ -629,7 +629,7 @@
 // Make sure that when we have an unused value, we properly iterate over the
 // loop rather than run through the loop once.
 //
-// CHECK-LABEL: sil hidden @_T07foreach16unusedArgPatternySaySiGF : $@convention(thin) (@owned Array<Int>) -> () {
+// CHECK-LABEL: sil hidden @_T07foreach16unusedArgPatternyySaySiGF : $@convention(thin) (@owned Array<Int>) -> () {
 // CHECK: bb0([[ARG:%.*]] : @owned $Array<Int>):
 // CHECK:   br [[LOOP_DEST:bb[0-9]+]]
 //
diff --git a/test/SILGen/foreign_errors.swift b/test/SILGen/foreign_errors.swift
index d5ae3f6..0f9ef26 100644
--- a/test/SILGen/foreign_errors.swift
+++ b/test/SILGen/foreign_errors.swift
@@ -48,7 +48,7 @@
   //   Error path: fall out and rethrow.
   // CHECK: [[ERROR_BB]]:
   // CHECK: [[T0:%.*]] = load [take] [[ERR_TEMP0]]
-  // CHECK: [[T1:%.*]] = function_ref @_T010Foundation22_convertNSErrorToErrors0E0_pSo0C0CSgF : $@convention(thin) (@owned Optional<NSError>) -> @owned Error
+  // CHECK: [[T1:%.*]] = function_ref @_T010Foundation22_convertNSErrorToErrorys0E0_pSo0C0CSgF : $@convention(thin) (@owned Optional<NSError>) -> @owned Error
   // CHECK: [[T2:%.*]] = apply [[T1]]([[T0]])
   // CHECK: throw [[T2]] : $Error
 }
@@ -68,7 +68,7 @@
 // CHECK: bb2([[ERR:%.*]] : $Error):
 // CHECK:   switch_enum %0 : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, case #Optional.some!enumelt.1: bb3, case #Optional.none!enumelt: bb4
 // CHECK: bb3([[UNWRAPPED_OUT:%.+]] : $AutoreleasingUnsafeMutablePointer<Optional<NSError>>):
-// CHECK:   [[T0:%.*]] = function_ref @_T010Foundation22_convertErrorToNSErrorSo0E0Cs0C0_pF : $@convention(thin) (@owned Error) -> @owned NSError
+// CHECK:   [[T0:%.*]] = function_ref @_T010Foundation22_convertErrorToNSErrorySo0E0Cs0C0_pF : $@convention(thin) (@owned Error) -> @owned NSError
 // CHECK:   [[T1:%.*]] = apply [[T0]]([[ERR]])
 // CHECK:   [[OBJCERR:%.*]] = enum $Optional<NSError>, #Optional.some!enumelt.1, [[T1]] : $NSError
 // CHECK:   [[TEMP:%.*]] = alloc_stack $Optional<NSError>
@@ -111,7 +111,7 @@
 // CHECK:   switch_enum [[UNOWNED_ARG0]] : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9][0-9]*]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9][0-9]*]]
 //
 // CHECK: [[SOME_BB]]([[UNWRAPPED_OUT:%.+]] : $AutoreleasingUnsafeMutablePointer<Optional<NSError>>):
-// CHECK:   [[T0:%.*]] = function_ref @_T010Foundation22_convertErrorToNSErrorSo0E0Cs0C0_pF : $@convention(thin) (@owned Error) -> @owned NSError
+// CHECK:   [[T0:%.*]] = function_ref @_T010Foundation22_convertErrorToNSErrorySo0E0Cs0C0_pF : $@convention(thin) (@owned Error) -> @owned NSError
 // CHECK:   [[T1:%.*]] = apply [[T0]]([[ERR]])
 // CHECK:   [[OBJCERR:%.*]] = enum $Optional<NSError>, #Optional.some!enumelt.1, [[T1]] : $NSError
 // CHECK:   [[TEMP:%.*]] = alloc_stack $Optional<NSError>
@@ -134,11 +134,11 @@
 // CHECK:   destroy_value [[ARG1]]
 // CHECK:   return [[T0]] : $Optional<NSString>
 
-// CHECK-LABEL: sil hidden [thunk] @_T0So8NSObjectC14foreign_errorsE7takeIntySiKFTo : $@convention(objc_method) (Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, NSObject) -> ObjCBool
+// CHECK-LABEL: sil hidden [thunk] @_T0So8NSObjectC14foreign_errorsE7takeIntyySiKFTo : $@convention(objc_method) (Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, NSObject) -> ObjCBool
 // CHECK: bb0([[I:%[0-9]+]] : $Int, [[ERROR:%[0-9]+]] : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, [[SELF:%[0-9]+]] : $NSObject)
   @objc func takeInt(_ i: Int) throws { }
 
-// CHECK-LABEL: sil hidden [thunk] @_T0So8NSObjectC14foreign_errorsE10takeDoubleySd_Si3intS2ic7closuretKFTo : $@convention(objc_method) (Double, Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @convention(block) @noescape (Int) -> Int, NSObject) -> ObjCBool
+// CHECK-LABEL: sil hidden [thunk] @_T0So8NSObjectC14foreign_errorsE10takeDouble_3int7closureySd_S3ictKFTo : $@convention(objc_method) (Double, Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @convention(block) @noescape (Int) -> Int, NSObject) -> ObjCBool
 // CHECK: bb0([[D:%[0-9]+]] : $Double, [[INT:%[0-9]+]] : $Int, [[ERROR:%[0-9]+]] : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, [[CLOSURE:%[0-9]+]] : $@convention(block) @noescape (Int) -> Int, [[SELF:%[0-9]+]] : $NSObject):
   @objc func takeDouble(_ d: Double, int: Int, closure: (Int) -> Int) throws {
     throw NSError(domain: "", code: 1, userInfo: [:])
@@ -188,7 +188,7 @@
 // on than is being tested here, we should consider adding FileCheck tests for
 // it.
 
-// CHECK-LABEL:    sil hidden @_T014foreign_errors14VeryErrorProneCACyXlSg7withTwo_tKcfc
+// CHECK-LABEL:    sil hidden @_T014foreign_errors14VeryErrorProneC7withTwoACyXlSg_tKcfc
 // CHECK:    bb0([[ARG1:%.*]] : $Optional<AnyObject>, [[ARG2:%.*]] : $VeryErrorProne):
 // CHECK:      [[BOX:%.*]] = alloc_box ${ var VeryErrorProne }
 // CHECK:      [[MARKED_BOX:%.*]] = mark_uninitialized [derivedself] [[BOX]]
@@ -207,7 +207,7 @@
 // CHECK:      apply [[T2]]([[ARG1_COPY]], {{%.*}}, [[T1]])
 
 // rdar://21051021
-// CHECK: sil hidden @_T014foreign_errors12testProtocolySo010ErrorProneD0_pKF : $@convention(thin) (@owned ErrorProneProtocol) -> @error Error
+// CHECK: sil hidden @_T014foreign_errors12testProtocolyySo010ErrorProneD0_pKF : $@convention(thin) (@owned ErrorProneProtocol) -> @error Error
 // CHECK: bb0([[ARG0:%.*]] : $ErrorProneProtocol):
 func testProtocol(_ p: ErrorProneProtocol) throws {
   // CHECK:   [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]]
@@ -227,8 +227,8 @@
 class ExtremelyErrorProne : ErrorProne {
   override func conflict3(_ obj: Any, error: ()) throws {}
 }
-// CHECK-LABEL: sil hidden @_T014foreign_errors19ExtremelyErrorProneC9conflict3yyp_yt5errortKF
-// CHECK-LABEL: sil hidden [thunk] @_T014foreign_errors19ExtremelyErrorProneC9conflict3yyp_yt5errortKFTo : $@convention(objc_method) (AnyObject, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, ExtremelyErrorProne) -> ObjCBool
+// CHECK-LABEL: sil hidden @_T014foreign_errors19ExtremelyErrorProneC9conflict3_5erroryyp_yttKF
+// CHECK-LABEL: sil hidden [thunk] @_T014foreign_errors19ExtremelyErrorProneC9conflict3_5erroryyp_yttKFTo : $@convention(objc_method) (AnyObject, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, ExtremelyErrorProne) -> ObjCBool
 
 // These conventions are usable because of swift_error. rdar://21715350
 func testNonNilError() throws -> Float {
diff --git a/test/SILGen/function_conversion.swift b/test/SILGen/function_conversion.swift
index bdc2502..5ea42b9 100644
--- a/test/SILGen/function_conversion.swift
+++ b/test/SILGen/function_conversion.swift
@@ -5,7 +5,7 @@
 
 // ==== Representation conversions
 
-// CHECK-LABEL: sil hidden @_T019function_conversion7cToFuncS2icS2iXCF : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @callee_guaranteed (Int) -> Int
+// CHECK-LABEL: sil hidden @_T019function_conversion7cToFuncyS2icS2iXCF : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @callee_guaranteed (Int) -> Int
 // CHECK:         [[THUNK:%.*]] = function_ref @_T0S2iIetCyd_S2iIegyd_TR
 // CHECK:         [[FUNC:%.*]] = partial_apply [callee_guaranteed] [[THUNK]](%0)
 // CHECK:         return [[FUNC]]
@@ -13,7 +13,7 @@
   return arg
 }
 
-// CHECK-LABEL: sil hidden @_T019function_conversion8cToBlockS2iXBS2iXCF : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @convention(block) (Int) -> Int
+// CHECK-LABEL: sil hidden @_T019function_conversion8cToBlockyS2iXBS2iXCF : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @convention(block) (Int) -> Int
 // CHECK:         [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage
 // CHECK:         [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]]
 // CHECK:         [[COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) (Int) -> Int
@@ -24,7 +24,7 @@
 
 // ==== Throws variance
 
-// CHECK-LABEL: sil hidden @_T019function_conversion12funcToThrowsyyKcyycF : $@convention(thin) (@owned @callee_guaranteed () -> ()) -> @owned @callee_guaranteed () -> @error Error
+// CHECK-LABEL: sil hidden @_T019function_conversion12funcToThrowsyyyKcyycF : $@convention(thin) (@owned @callee_guaranteed () -> ()) -> @owned @callee_guaranteed () -> @error Error
 // CHECK: bb0([[ARG:%.*]] : @owned $@callee_guaranteed () -> ()):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
@@ -32,12 +32,12 @@
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK:   destroy_value [[ARG]]
 // CHECK:   return [[FUNC]]
-// CHECK: } // end sil function '_T019function_conversion12funcToThrowsyyKcyycF'
+// CHECK: } // end sil function '_T019function_conversion12funcToThrowsyyyKcyycF'
 func funcToThrows(_ x: @escaping () -> ()) -> () throws -> () {
   return x
 }
 
-// CHECK-LABEL: sil hidden @_T019function_conversion12thinToThrowsyyKXfyyXfF : $@convention(thin) (@convention(thin) () -> ()) -> @convention(thin) () -> @error Error
+// CHECK-LABEL: sil hidden @_T019function_conversion12thinToThrowsyyyKXfyyXfF : $@convention(thin) (@convention(thin) () -> ()) -> @convention(thin) () -> @error Error
 // CHECK:         [[FUNC:%.*]] = convert_function %0 : $@convention(thin) () -> () to $@convention(thin) () -> @error Error
 // CHECK:         return [[FUNC]] : $@convention(thin) () -> @error Error
 func thinToThrows(_ x: @escaping @convention(thin) () -> ()) -> @convention(thin) () throws -> () {
@@ -58,7 +58,7 @@
 class Feral {}
 class Domesticated : Feral {}
 
-// CHECK-LABEL: sil hidden @_T019function_conversion12funcToUpcastAA5FeralCycAA12DomesticatedCycF : $@convention(thin) (@owned @callee_guaranteed () -> @owned Domesticated) -> @owned @callee_guaranteed () -> @owned Feral {
+// CHECK-LABEL: sil hidden @_T019function_conversion12funcToUpcastyAA5FeralCycAA12DomesticatedCycF : $@convention(thin) (@owned @callee_guaranteed () -> @owned Domesticated) -> @owned @callee_guaranteed () -> @owned Feral {
 // CHECK: bb0([[ARG:%.*]] : @owned $@callee_guaranteed () -> @owned Domesticated):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
@@ -66,12 +66,12 @@
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK:   destroy_value [[ARG]]
 // CHECK:   return [[FUNC]]
-// CHECK: } // end sil function '_T019function_conversion12funcToUpcastAA5FeralCycAA12DomesticatedCycF'
+// CHECK: } // end sil function '_T019function_conversion12funcToUpcastyAA5FeralCycAA12DomesticatedCycF'
 func funcToUpcast(_ x: @escaping () -> Domesticated) -> () -> Feral {
   return x
 }
 
-// CHECK-LABEL: sil hidden @_T019function_conversion12funcToUpcastyAA12DomesticatedCcyAA5FeralCcF : $@convention(thin) (@owned @callee_guaranteed (@owned Feral) -> ()) -> @owned @callee_guaranteed (@owned Domesticated) -> ()
+// CHECK-LABEL: sil hidden @_T019function_conversion12funcToUpcastyyAA12DomesticatedCcyAA5FeralCcF : $@convention(thin) (@owned @callee_guaranteed (@owned Feral) -> ()) -> @owned @callee_guaranteed (@owned Domesticated) -> ()
 // CHECK: bb0([[ARG:%.*]] :
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
@@ -121,7 +121,7 @@
   }
 }
 
-// CHECK-LABEL: sil hidden @_T019function_conversion19convOptionalTrivialyAA0E0VADSgcF
+// CHECK-LABEL: sil hidden @_T019function_conversion19convOptionalTrivialyyAA0E0VADSgcF
 func convOptionalTrivial(_ t1: @escaping (Trivial?) -> Trivial) {
 // CHECK:         function_ref @_T019function_conversion7TrivialVSgACIegyd_AcDIegyd_TR
 // CHECK:         partial_apply
@@ -143,7 +143,7 @@
 // CHECK-NEXT:    enum $Optional<Trivial>
 // CHECK-NEXT:    return
 
-// CHECK-LABEL: sil hidden @_T019function_conversion20convOptionalLoadableyAA0E0VADSgcF
+// CHECK-LABEL: sil hidden @_T019function_conversion20convOptionalLoadableyyAA0E0VADSgcF
 func convOptionalLoadable(_ l1: @escaping (Loadable?) -> Loadable) {
 // CHECK:         function_ref @_T019function_conversion8LoadableVSgACIegxo_AcDIegxo_TR
 // CHECK:         partial_apply
@@ -159,7 +159,7 @@
 // CHECK-NEXT:    enum $Optional<Loadable>
 // CHECK-NEXT:    return
 
-// CHECK-LABEL: sil hidden @_T019function_conversion20convOptionalAddrOnlyyAA0eF0VADSgcF
+// CHECK-LABEL: sil hidden @_T019function_conversion20convOptionalAddrOnlyyyAA0eF0VADSgcF
 func convOptionalAddrOnly(_ a1: @escaping (AddrOnly?) -> AddrOnly) {
 // CHECK:         function_ref @_T019function_conversion8AddrOnlyVSgACIegir_A2DIegir_TR
 // CHECK:         partial_apply
@@ -188,7 +188,7 @@
 extension Loadable : P {}
 extension AddrOnly : P {}
 
-// CHECK-LABEL: sil hidden @_T019function_conversion22convExistentialTrivialyAA0E0VAA1Q_pc_AdaE_pSgc2t3tF
+// CHECK-LABEL: sil hidden @_T019function_conversion22convExistentialTrivial_2t3yAA0E0VAA1Q_pc_AeaF_pSgctF
 func convExistentialTrivial(_ t2: @escaping (Q) -> Trivial, t3: @escaping (Q?) -> Trivial) {
 // CHECK:         function_ref @_T019function_conversion1Q_pAA7TrivialVIegid_AdA1P_pIegyr_TR
 // CHECK:         partial_apply
@@ -240,7 +240,7 @@
 
 // ==== Existential metatypes
 
-// CHECK-LABEL: sil hidden @_T019function_conversion23convExistentialMetatypeyAA7TrivialVmAA1Q_pXpSgcF
+// CHECK-LABEL: sil hidden @_T019function_conversion23convExistentialMetatypeyyAA7TrivialVmAA1Q_pXpSgcF
 func convExistentialMetatype(_ em: @escaping (Q.Type?) -> Trivial.Type) {
 // CHECK:         function_ref @_T019function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtAA1P_pXmTIegyd_TR
 // CHECK:         partial_apply
@@ -295,7 +295,7 @@
 // Note: we add a Trivial => Trivial? conversion here to force a thunk
 // to be generated
 
-// CHECK-LABEL: sil hidden @_T019function_conversion18convUpcastMetatypeyAA5ChildCmAA6ParentCm_AA7TrivialVSgtc_ADmAFmSg_AItc2c5tF
+// CHECK-LABEL: sil hidden @_T019function_conversion18convUpcastMetatype_2c5yAA5ChildCmAA6ParentCm_AA7TrivialVSgtc_AEmAGmSg_AJtctF
 func convUpcastMetatype(_ c4: @escaping (Parent.Type, Trivial?) -> Child.Type,
                         c5: @escaping (Parent.Type?, Trivial?) -> Child.Type) {
 // CHECK:         function_ref @_T019function_conversion6ParentCXMTAA7TrivialVSgAA5ChildCXMTIegyyd_AHXMTAeCXMTIegyyd_TR
@@ -333,7 +333,7 @@
 
 // ==== Function to existential -- make sure we maximally abstract it
 
-// CHECK-LABEL: sil hidden @_T019function_conversion19convFuncExistentialyS2icypcF : $@convention(thin) (@owned @callee_guaranteed (@in Any) -> @owned @callee_guaranteed (Int) -> Int) -> ()
+// CHECK-LABEL: sil hidden @_T019function_conversion19convFuncExistentialyyS2icypcF : $@convention(thin) (@owned @callee_guaranteed (@in Any) -> @owned @callee_guaranteed (Int) -> Int) -> ()
 // CHECK: bb0([[ARG:%.*]] :
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
@@ -342,7 +342,7 @@
 // CHECK:   destroy_value [[PA]]
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK:   destroy_value [[ARG]]
-// CHECK: } // end sil function '_T019function_conversion19convFuncExistentialyS2icypcF'
+// CHECK: } // end sil function '_T019function_conversion19convFuncExistentialyyS2icypcF'
 func convFuncExistential(_ f1: @escaping (Any) -> (Int) -> Int) {
   let _: ((Int) -> Int) -> Any = f1
 }
@@ -410,7 +410,7 @@
 
 // ==== Make sure we destructure one-element tuples
 
-// CHECK-LABEL: sil hidden @_T019function_conversion15convTupleScalaryyAA1Q_pc_yAaC_pc2f2ySi_SitSgc2f3tF
+// CHECK-LABEL: sil hidden @_T019function_conversion15convTupleScalar_2f22f3yyAA1Q_pc_yAaE_pcySi_SitSgctF
 // CHECK:         function_ref @_T019function_conversion1Q_pIegi_AA1P_pIegi_TR
 // CHECK:         function_ref @_T019function_conversion1Q_pIegi_AA1P_pIegi_TR
 // CHECK:         function_ref @_T0Si_SitSgIegy_S2iIegyy_TR
@@ -431,7 +431,7 @@
   return f
 }
 
-// CHECK-LABEL: sil hidden @_T019function_conversion25convTupleToOptionalDirectSi_SitSgSicSi_SitSicF : $@convention(thin) (@owned @callee_guaranteed (Int) -> (Int, Int)) -> @owned @callee_guaranteed (Int) -> Optional<(Int, Int)>
+// CHECK-LABEL: sil hidden @_T019function_conversion25convTupleToOptionalDirectySi_SitSgSicSi_SitSicF : $@convention(thin) (@owned @callee_guaranteed (Int) -> (Int, Int)) -> @owned @callee_guaranteed (Int) -> Optional<(Int, Int)>
 // CHECK:         bb0([[ARG:%.*]] : @owned $@callee_guaranteed (Int) -> (Int, Int)):
 // CHECK:           [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:           [[FN:%.*]] = copy_value [[BORROWED_ARG]]
@@ -454,7 +454,7 @@
   return f
 }
 
-// CHECK-LABEL: sil hidden @_T019function_conversion27convTupleToOptionalIndirectx_xtSgxcx_xtxclF : $@convention(thin) <T> (@owned @callee_guaranteed (@in T) -> (@out T, @out T)) -> @owned @callee_guaranteed (@in T) -> @out Optional<(T, T)>
+// CHECK-LABEL: sil hidden @_T019function_conversion27convTupleToOptionalIndirectyx_xtSgxcx_xtxclF : $@convention(thin) <T> (@owned @callee_guaranteed (@in T) -> (@out T, @out T)) -> @owned @callee_guaranteed (@in T) -> @out Optional<(T, T)>
 // CHECK:       bb0([[ARG:%.*]] : @owned $@callee_guaranteed (@in T) -> (@out T, @out T)):
 // CHECK:          [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:          [[FN:%.*]] = copy_value [[BORROWED_ARG]]
@@ -480,16 +480,16 @@
 
 // ==== Make sure we support AnyHashable erasure
 
-// CHECK-LABEL: sil hidden @_T019function_conversion15convAnyHashableyx1t_ts0E0RzlF
-// CHECK:         function_ref @_T019function_conversion15convAnyHashableyx1t_ts0E0RzlFSbs0dE0V_AFtcfU_
+// CHECK-LABEL: sil hidden @_T019function_conversion15convAnyHashable1tyx_ts0E0RzlF
+// CHECK:         function_ref @_T019function_conversion15convAnyHashable1tyx_ts0E0RzlFSbs0dE0V_AFtcfU_
 // CHECK:         function_ref @_T0s11AnyHashableVABSbIegiid_xxSbIegiid_s0B0RzlTR
 
 // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0s11AnyHashableVABSbIegiid_xxSbIegiid_s0B0RzlTR : $@convention(thin) <T where T : Hashable> (@in T, @in T, @guaranteed @callee_guaranteed (@in AnyHashable, @in AnyHashable) -> Bool) -> Bool
 // CHECK:         alloc_stack $AnyHashable
-// CHECK:         function_ref @_T0s21_convertToAnyHashables0cD0Vxs0D0RzlF
+// CHECK:         function_ref @_T0s21_convertToAnyHashableys0cD0Vxs0D0RzlF
 // CHECK:         apply {{.*}}<T>
 // CHECK:         alloc_stack $AnyHashable
-// CHECK:         function_ref @_T0s21_convertToAnyHashables0cD0Vxs0D0RzlF
+// CHECK:         function_ref @_T0s21_convertToAnyHashableys0cD0Vxs0D0RzlF
 // CHECK:         apply {{.*}}<T>
 // CHECK:         return
 
@@ -501,7 +501,7 @@
 
 // ==== Convert exploded tuples to Any or Optional<Any>
 
-// CHECK-LABEL: sil hidden @_T019function_conversion12convTupleAnyyyyc_Si_SitycyypcyypSgctF
+// CHECK-LABEL: sil hidden @_T019function_conversion12convTupleAnyyyyyc_Si_SitycyypcyypSgctF
 // CHECK:         function_ref @_T0Ieg_ypIegr_TR
 // CHECK:         partial_apply
 // CHECK:         function_ref @_T0Ieg_ypSgIegr_TR
@@ -611,11 +611,11 @@
   let fn_arr: ([Z]?) -> Void = { _ in }
   let fn_map: ([Int: Z]) -> Void = { _ in }
 
-  // CHECK: function_ref @_T0s15_arrayForceCastSayq_GSayxGr0_lF : $@convention(thin) <τ_0_0, τ_0_1> (@owned Array<τ_0_0>) -> @owned Array<τ_0_1>
+  // CHECK: function_ref @_T0s15_arrayForceCastySayq_GSayxGr0_lF : $@convention(thin) <τ_0_0, τ_0_1> (@owned Array<τ_0_0>) -> @owned Array<τ_0_1>
   // CHECK: apply %4<A, Z>(%3) : $@convention(thin) <τ_0_0, τ_0_1> (@owned Array<τ_0_0>) -> @owned Array<τ_0_1>
   foo_arr(type: A.self, fn_arr)
 
-  // CHECK: function_ref @_T0s17_dictionaryUpCasts10DictionaryVyq0_q1_GACyxq_Gs8HashableRzsAFR0_r2_lF : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@owned Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3>
+  // CHECK: function_ref @_T0s17_dictionaryUpCastys10DictionaryVyq0_q1_GACyxq_Gs8HashableRzsAFR0_r2_lF : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@owned Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3>
   // CHECK: apply %2<Int, A, Int, Z>(%0) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@owned Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3>
   // CHECK: apply %1(%3) : $@callee_guaranteed (@owned Dictionary<Int, Z>) -> ()
   foo_map(type: A.self, fn_map)
diff --git a/test/SILGen/function_conversion_objc.swift b/test/SILGen/function_conversion_objc.swift
index a539287..d05b8f0 100644
--- a/test/SILGen/function_conversion_objc.swift
+++ b/test/SILGen/function_conversion_objc.swift
@@ -6,7 +6,7 @@
 
 // ==== Metatype to object conversions
 
-// CHECK-LABEL: sil hidden @_T024function_conversion_objc20convMetatypeToObjectySo8NSObjectCmADcF
+// CHECK-LABEL: sil hidden @_T024function_conversion_objc20convMetatypeToObjectyySo8NSObjectCmADcF
 func convMetatypeToObject(_ f: @escaping (NSObject) -> NSObject.Type) {
 // CHECK:         function_ref @_T0So8NSObjectCABXMTIegxd_AByXlIegxo_TR
 // CHECK:         partial_apply
@@ -21,7 +21,7 @@
 
 @objc protocol NSBurrito {}
 
-// CHECK-LABEL: sil hidden @_T024function_conversion_objc31convExistentialMetatypeToObjectyAA9NSBurrito_pXpAaC_pcF
+// CHECK-LABEL: sil hidden @_T024function_conversion_objc31convExistentialMetatypeToObjectyyAA9NSBurrito_pXpAaC_pcF
 func convExistentialMetatypeToObject(_ f: @escaping (NSBurrito) -> NSBurrito.Type) {
 // CHECK:         function_ref @_T024function_conversion_objc9NSBurrito_pAaB_pXmTIegxd_AaB_pyXlIegxo_TR
 // CHECK:         partial_apply
@@ -34,7 +34,7 @@
 // CHECK:         objc_existential_metatype_to_object {{.*}} : $@objc_metatype NSBurrito.Type to $AnyObject
 // CHECK:         return
 
-// CHECK-LABEL: sil hidden @_T024function_conversion_objc28convProtocolMetatypeToObjectyAA9NSBurrito_pmycF
+// CHECK-LABEL: sil hidden @_T024function_conversion_objc28convProtocolMetatypeToObjectyyAA9NSBurrito_pmycF
 func convProtocolMetatypeToObject(_ f: @escaping () -> NSBurrito.Protocol) {
 // CHECK:         function_ref @_T024function_conversion_objc9NSBurrito_pXMtIegd_So8ProtocolCIego_TR
 // CHECK:         partial_apply
@@ -49,7 +49,7 @@
 
 // ==== Representation conversions
 
-// CHECK-LABEL: sil hidden @_T024function_conversion_objc11funcToBlockyyXByycF : $@convention(thin) (@owned @callee_guaranteed () -> ()) -> @owned @convention(block) () -> ()
+// CHECK-LABEL: sil hidden @_T024function_conversion_objc11funcToBlockyyyXByycF : $@convention(thin) (@owned @callee_guaranteed () -> ()) -> @owned @convention(block) () -> ()
 // CHECK:         [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage
 // CHECK:         [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]]
 // CHECK:         [[COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) () -> ()
@@ -58,7 +58,7 @@
   return x
 }
 
-// CHECK-LABEL: sil hidden @_T024function_conversion_objc11blockToFuncyycyyXBF : $@convention(thin) (@owned @convention(block) () -> ()) -> @owned @callee_guaranteed () -> ()
+// CHECK-LABEL: sil hidden @_T024function_conversion_objc11blockToFuncyyycyyXBF : $@convention(thin) (@owned @convention(block) () -> ()) -> @owned @callee_guaranteed () -> ()
 // CHECK: bb0([[ARG:%.*]] : @owned $@convention(block) () -> ()):
 // CHECK:   [[COPIED:%.*]] = copy_block [[ARG]]
 // CHECK:   [[BORROWED_COPIED:%.*]] = begin_borrow [[COPIED]]
@@ -75,7 +75,7 @@
 
 // ==== Representation change + function type conversion
 
-// CHECK-LABEL: sil hidden @_T024function_conversion_objc22blockToFuncExistentialypycSiyXBF : $@convention(thin) (@owned @convention(block) () -> Int) -> @owned @callee_guaranteed () -> @out Any
+// CHECK-LABEL: sil hidden @_T024function_conversion_objc22blockToFuncExistentialyypycSiyXBF : $@convention(thin) (@owned @convention(block) () -> Int) -> @owned @callee_guaranteed () -> @out Any
 // CHECK:         function_ref @_T0SiIeyBd_SiIegd_TR
 // CHECK:         partial_apply
 // CHECK:         function_ref @_T0SiIegd_ypIegr_TR
@@ -94,7 +94,7 @@
 class A : NSObject {}
 class B : A {}
 
-// CHECK-LABEL: sil hidden @_T024function_conversion_objc18cFuncPtrConversionyAA1BCXCyAA1ACXCF
+// CHECK-LABEL: sil hidden @_T024function_conversion_objc18cFuncPtrConversionyyAA1BCXCyAA1ACXCF
 func cFuncPtrConversion(_ x: @escaping @convention(c) (A) -> ()) -> @convention(c) (B) -> () {
 // CHECK:         convert_function %0 : $@convention(c) (A) -> () to $@convention(c) (B) -> ()
 // CHECK:         return
@@ -105,7 +105,7 @@
 
 // CHECK-LABEL: sil hidden @_T024function_conversion_objc19cFuncDeclConversionyAA1BCXCyF
 func cFuncDeclConversion() -> @convention(c) (B) -> () {
-// CHECK:         function_ref @_T024function_conversion_objc8cFuncPtryAA1ACFTo : $@convention(c) (A) -> ()
+// CHECK:         function_ref @_T024function_conversion_objc8cFuncPtryyAA1ACFTo : $@convention(c) (A) -> ()
 // CHECK:         convert_function %0 : $@convention(c) (A) -> () to $@convention(c) (B) -> ()
 // CHECK:         return
   return cFuncPtr
diff --git a/test/SILGen/functions.swift b/test/SILGen/functions.swift
index fcea36c..1eadcef 100644
--- a/test/SILGen/functions.swift
+++ b/test/SILGen/functions.swift
@@ -481,7 +481,7 @@
   @_optimize(speed)
   var x: Int { return getInt() }
 
-  // CHECK-LABEL: sil hidden [Ospeed] @_T09functions17OptmodeTestStructVBi64_Bi64_cig :
+  // CHECK-LABEL: sil hidden [Ospeed] @_T09functions17OptmodeTestStructVyBi64_Bi64_cig :
   @_optimize(speed)
   subscript(l: Int) -> Int { return getInt() }
 }
diff --git a/test/SILGen/generic_casts.swift b/test/SILGen/generic_casts.swift
index 0471c2e..ffaa4f3 100644
--- a/test/SILGen/generic_casts.swift
+++ b/test/SILGen/generic_casts.swift
@@ -30,7 +30,7 @@
   // CHECK: [[CONT]]([[I1:%.*]] : @trivial $Builtin.Int1):
   // -- apply the _getBool library fn
   // CHECK-NEXT:  function_ref Swift._getBool
-  // CHECK-NEXT:  [[GETBOOL:%.*]] = function_ref @_T0s8_getBoolSbBi1_F :
+  // CHECK-NEXT:  [[GETBOOL:%.*]] = function_ref @_T0s8_getBoolySbBi1_F :
   // CHECK-NEXT:  [[RES:%.*]] = apply [[GETBOOL]]([[I1]])
   // -- we don't consume the checked value
   // CHECK:   return [[RES]] : $Bool
@@ -216,7 +216,7 @@
   // CHECK: checked_cast_br {{%.*}} to $C
 }
 
-// CHECK-LABEL: sil hidden @_T013generic_casts27optional_anyobject_to_classAA1CCSgyXlSgF 
+// CHECK-LABEL: sil hidden @_T013generic_casts27optional_anyobject_to_classyAA1CCSgyXlSgF
 // CHECK:         checked_cast_br {{%.*}} : $AnyObject to $C
 func optional_anyobject_to_class(_ p: AnyObject?) -> C? {
   return p as? C
diff --git a/test/SILGen/generic_closures.swift b/test/SILGen/generic_closures.swift
index fb930dc..526d8c5 100644
--- a/test/SILGen/generic_closures.swift
+++ b/test/SILGen/generic_closures.swift
@@ -141,10 +141,10 @@
 // Ensure that nested closures capture the generic parameters of their nested
 // context.
 
-// CHECK: sil hidden @_T016generic_closures018nested_closure_in_A0xxlF : $@convention(thin) <T> (@in T) -> @out T
-// CHECK:   function_ref [[OUTER_CLOSURE:@_T016generic_closures018nested_closure_in_A0xxlFxycfU_]]
+// CHECK: sil hidden @_T016generic_closures018nested_closure_in_A0yxxlF : $@convention(thin) <T> (@in T) -> @out T
+// CHECK:   function_ref [[OUTER_CLOSURE:@_T016generic_closures018nested_closure_in_A0yxxlFxycfU_]]
 // CHECK: sil private [[OUTER_CLOSURE]] : $@convention(thin) <T> (@inout_aliasable T) -> @out T
-// CHECK:   function_ref [[INNER_CLOSURE:@_T016generic_closures018nested_closure_in_A0xxlFxycfU_xycfU_]]
+// CHECK:   function_ref [[INNER_CLOSURE:@_T016generic_closures018nested_closure_in_A0yxxlFxycfU_xycfU_]]
 // CHECK: sil private [[INNER_CLOSURE]] : $@convention(thin) <T> (@inout_aliasable T) -> @out T {
 func nested_closure_in_generic<T>(_ x:T) -> T {
   return { { x }() }()
@@ -205,9 +205,9 @@
 
 protocol HasClassAssoc { associatedtype Assoc : Class }
 
-// CHECK-LABEL: sil hidden @_T016generic_closures027captures_class_constrained_A0yx_5AssocQzADc1ftAA08HasClassF0RzlF
+// CHECK-LABEL: sil hidden @_T016generic_closures027captures_class_constrained_A0_1fyx_5AssocQzAEctAA08HasClassF0RzlF
 // CHECK: bb0([[ARG1:%.*]] : @trivial $*T, [[ARG2:%.*]] : @owned $@callee_guaranteed (@owned T.Assoc) -> @owned T.Assoc):
-// CHECK: [[GENERIC_FN:%.*]] = function_ref @_T016generic_closures027captures_class_constrained_A0yx_5AssocQzADc1ftAA08HasClassF0RzlFA2DcycfU_
+// CHECK: [[GENERIC_FN:%.*]] = function_ref @_T016generic_closures027captures_class_constrained_A0_1fyx_5AssocQzAEctAA08HasClassF0RzlFA2EcycfU_
 // CHECK: [[ARG2_COPY:%.*]] = copy_value [[ARG2]]
 // CHECK: [[CONCRETE_FN:%.*]] = partial_apply [callee_guaranteed] [[GENERIC_FN]]<T>([[ARG2_COPY]])
 
@@ -217,7 +217,7 @@
 
 // Make sure local generic functions can have captures
 
-// CHECK-LABEL: sil hidden @_T016generic_closures06outer_A0yx1t_Si1itlF : $@convention(thin) <T> (@in T, Int) -> ()
+// CHECK-LABEL: sil hidden @_T016generic_closures06outer_A01t1iyx_SitlF : $@convention(thin) <T> (@in T, Int) -> ()
 func outer_generic<T>(t: T, i: Int) {
   func inner_generic_nocapture<U>(u: U) -> U {
     return u
@@ -232,40 +232,40 @@
   }
 
   let _: () -> () = inner_generic_nocapture
-  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures06outer_A0yx1t_Si1itlF06inner_A10_nocaptureL_qd__qd__1u_tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0) -> @out τ_1_0
+  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures06outer_A01t1iyx_SitlF06inner_A10_nocaptureL_1uqd__qd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0) -> @out τ_1_0
   // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T, ()>() : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0) -> @out τ_1_0
   // CHECK: [[THUNK:%.*]] = function_ref @_T0ytytIegir_Ieg_TR
   // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]])
   // CHECK: destroy_value [[THUNK_CLOSURE]]
 
-  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures06outer_A0yx1t_Si1itlF06inner_A10_nocaptureL_qd__qd__1u_tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0) -> @out τ_1_0
+  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures06outer_A01t1iyx_SitlF06inner_A10_nocaptureL_1uqd__qd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0) -> @out τ_1_0
   // CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0) -> @out τ_1_0
   _ = inner_generic_nocapture(u: t)
 
-  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures06outer_A0yx1t_Si1itlF14inner_generic1L_Siqd__1u_tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, Int) -> Int
+  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures06outer_A01t1iyx_SitlF14inner_generic1L_1uSiqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, Int) -> Int
   // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T, ()>(%1) : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, Int) -> Int
   // CHECK: [[THUNK:%.*]] = function_ref @_T0ytSiIegid_SiIegd_TR
   // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]])
   // CHECK: destroy_value [[THUNK_CLOSURE]]
   let _: () -> Int = inner_generic1
 
-  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures06outer_A0yx1t_Si1itlF14inner_generic1L_Siqd__1u_tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, Int) -> Int
+  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures06outer_A01t1iyx_SitlF14inner_generic1L_1uSiqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, Int) -> Int
   // CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, Int) -> Int
   _ = inner_generic1(u: t)
 
-  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures06outer_A0yx1t_Si1itlF14inner_generic2L_xqd__1u_tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, @guaranteed <τ_0_0> { var τ_0_0 } <τ_0_0>) -> @out τ_0_0
+  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures06outer_A01t1iyx_SitlF14inner_generic2L_1uxqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, @guaranteed <τ_0_0> { var τ_0_0 } <τ_0_0>) -> @out τ_0_0
   // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T, ()>([[ARG:%.*]]) : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, @guaranteed <τ_0_0> { var τ_0_0 } <τ_0_0>) -> @out τ_0_0
   // CHECK: [[THUNK:%.*]] = function_ref @_T0ytxIegir_xIegr_lTR
   // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]<T>([[CLOSURE]])
   // CHECK: destroy_value [[THUNK_CLOSURE]]
   let _: () -> T = inner_generic2
 
-  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures06outer_A0yx1t_Si1itlF14inner_generic2L_xqd__1u_tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, @guaranteed <τ_0_0> { var τ_0_0 } <τ_0_0>) -> @out τ_0_0
+  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures06outer_A01t1iyx_SitlF14inner_generic2L_1uxqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, @guaranteed <τ_0_0> { var τ_0_0 } <τ_0_0>) -> @out τ_0_0
   // CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, @guaranteed <τ_0_0> { var τ_0_0 } <τ_0_0>) -> @out τ_0_0
   _ = inner_generic2(u: t)
 }
 
-// CHECK-LABEL: sil hidden @_T016generic_closures14outer_concreteySi1i_tF : $@convention(thin) (Int) -> ()
+// CHECK-LABEL: sil hidden @_T016generic_closures14outer_concrete1iySi_tF : $@convention(thin) (Int) -> ()
 func outer_concrete(i: Int) {
   func inner_generic_nocapture<U>(u: U) -> U {
     return u
@@ -275,30 +275,30 @@
     return i
   }
 
-  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures14outer_concreteySi1i_tF06inner_A10_nocaptureL_xx1u_tlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @out τ_0_0
+  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures14outer_concrete1iySi_tF06inner_A10_nocaptureL_1uxx_tlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @out τ_0_0
   // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<()>() : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @out τ_0_0
   // CHECK: [[THUNK:%.*]] = function_ref @_T0ytytIegir_Ieg_TR
   // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]])
   // CHECK: destroy_value [[THUNK_CLOSURE]]
   let _: () -> () = inner_generic_nocapture
 
-  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures14outer_concreteySi1i_tF06inner_A10_nocaptureL_xx1u_tlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @out τ_0_0
+  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures14outer_concrete1iySi_tF06inner_A10_nocaptureL_1uxx_tlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @out τ_0_0
   // CHECK: [[RESULT:%.*]] = apply [[FN]]<Int>({{.*}}) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @out τ_0_0
   _ = inner_generic_nocapture(u: i)
 
-  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures14outer_concreteySi1i_tF06inner_A0L_Six1u_tlF : $@convention(thin) <τ_0_0> (@in τ_0_0, Int) -> Int
+  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures14outer_concrete1iySi_tF06inner_A0L_1uSix_tlF : $@convention(thin) <τ_0_0> (@in τ_0_0, Int) -> Int
   // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<()>(%0) : $@convention(thin) <τ_0_0> (@in τ_0_0, Int) -> Int
   // CHECK: [[THUNK:%.*]] = function_ref @_T0ytSiIegid_SiIegd_TR
   // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]])
   // CHECK: destroy_value [[THUNK_CLOSURE]]
   let _: () -> Int = inner_generic
 
-  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures14outer_concreteySi1i_tF06inner_A0L_Six1u_tlF : $@convention(thin) <τ_0_0> (@in τ_0_0, Int) -> Int
+  // CHECK: [[FN:%.*]] = function_ref @_T016generic_closures14outer_concrete1iySi_tF06inner_A0L_1uSix_tlF : $@convention(thin) <τ_0_0> (@in τ_0_0, Int) -> Int
   // CHECK: [[RESULT:%.*]] = apply [[FN]]<Int>({{.*}}) : $@convention(thin) <τ_0_0> (@in τ_0_0, Int) -> Int
   _ = inner_generic(u: i)
 }
 
-// CHECK-LABEL: sil hidden @_T016generic_closures06mixed_A19_nongeneric_nestingyx1t_tlF : $@convention(thin) <T> (@in T) -> ()
+// CHECK-LABEL: sil hidden @_T016generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF : $@convention(thin) <T> (@in T) -> ()
 func mixed_generic_nongeneric_nesting<T>(t: T) {
   func outer() {
     func middle<U>(u: U) {
@@ -312,9 +312,9 @@
   outer()
 }
 
-// CHECK-LABEL: sil private @_T016generic_closures06mixed_A19_nongeneric_nestingyx1t_tlF5outerL_yylF : $@convention(thin) <T> () -> ()
-// CHECK-LABEL: sil private @_T016generic_closures06mixed_A19_nongeneric_nestingyx1t_tlF5outerL_yylF6middleL_yqd__1u_tr__lF : $@convention(thin) <T><U> (@in U) -> ()
-// CHECK-LABEL: sil private @_T016generic_closures06mixed_A19_nongeneric_nestingyx1t_tlF5outerL_yylF6middleL_yqd__1u_tr__lF5innerL_qd__yr__lF : $@convention(thin) <T><U> (@guaranteed <τ_0_0><τ_1_0> { var τ_1_0 } <T, U>) -> @out U
+// CHECK-LABEL: sil private @_T016generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF5outerL_yylF : $@convention(thin) <T> () -> ()
+// CHECK-LABEL: sil private @_T016generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF5outerL_yylF6middleL_1uyqd___tr__lF : $@convention(thin) <T><U> (@in U) -> ()
+// CHECK-LABEL: sil private @_T016generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF5outerL_yylF6middleL_1uyqd___tr__lF5innerL_qd__yr__lF : $@convention(thin) <T><U> (@guaranteed <τ_0_0><τ_1_0> { var τ_1_0 } <T, U>) -> @out U
 
 protocol Doge {
   associatedtype Nose : NoseProtocol
diff --git a/test/SILGen/generic_literals.swift b/test/SILGen/generic_literals.swift
index d0af2f4..7f2c51a 100644
--- a/test/SILGen/generic_literals.swift
+++ b/test/SILGen/generic_literals.swift
@@ -1,6 +1,6 @@
 // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
-// CHECK-LABEL: sil hidden @_T016generic_literals0A14IntegerLiteralyx1x_ts013ExpressibleBycD0RzlF
+// CHECK-LABEL: sil hidden @_T016generic_literals0A14IntegerLiteral1xyx_ts013ExpressibleBycD0RzlF
 func genericIntegerLiteral<T : ExpressibleByIntegerLiteral>(x: T) {
   var x = x
   // CHECK: [[ADDR:%.*]] = alloc_stack $T
diff --git a/test/SILGen/generic_local_property.swift b/test/SILGen/generic_local_property.swift
index cc55a83..8bc24b3 100644
--- a/test/SILGen/generic_local_property.swift
+++ b/test/SILGen/generic_local_property.swift
@@ -2,7 +2,7 @@
 
 func use<T>(_: T) {}
 
-// CHECK-LABEL: sil hidden @_T022generic_local_property3fooyx1x_Si1ytlF
+// CHECK-LABEL: sil hidden @_T022generic_local_property3foo1x1yyx_SitlF
 func foo<T>(x: T, y: Int) {
   var mutable: Int {
     get {
diff --git a/test/SILGen/generic_property_base_lifetime.swift b/test/SILGen/generic_property_base_lifetime.swift
index 21d2f48..031fc19 100644
--- a/test/SILGen/generic_property_base_lifetime.swift
+++ b/test/SILGen/generic_property_base_lifetime.swift
@@ -13,7 +13,7 @@
 }
 
 
-// CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolA_pF : $@convention(thin) (@owned ProtocolA) -> Int {
+// CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21getIntPropExistentialySiAA9ProtocolA_pF : $@convention(thin) (@owned ProtocolA) -> Int {
 // CHECK: bb0([[ARG:%.*]] : @owned $ProtocolA):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]]
@@ -26,12 +26,12 @@
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK:   destroy_value [[ARG]]
 // CHECK:   return [[RESULT]]
-// CHECK: } // end sil function '_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolA_pF'
+// CHECK: } // end sil function '_T030generic_property_base_lifetime21getIntPropExistentialySiAA9ProtocolA_pF'
 func getIntPropExistential(_ a: ProtocolA) -> Int {
   return a.intProp
 }
 
-// CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21setIntPropExistentialyAA9ProtocolA_pF : $@convention(thin) (@owned ProtocolA) -> () {
+// CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21setIntPropExistentialyyAA9ProtocolA_pF : $@convention(thin) (@owned ProtocolA) -> () {
 // CHECK: bb0([[ARG:%.*]] : @owned $ProtocolA):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]]
@@ -43,7 +43,7 @@
 // CHECK:   destroy_value [[PROJECTION_COPY]]
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK:   destroy_value [[ARG]]
-// CHECK: } // end sil function '_T030generic_property_base_lifetime21setIntPropExistentialyAA9ProtocolA_pF'
+// CHECK: } // end sil function '_T030generic_property_base_lifetime21setIntPropExistentialyyAA9ProtocolA_pF'
 func setIntPropExistential(_ a: ProtocolA) {
   a.intProp = 0
 }
@@ -68,7 +68,7 @@
   a.intProp = 0
 }
 
-// CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolB_pF
+// CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21getIntPropExistentialySiAA9ProtocolB_pF
 // CHECK:         [[PROJECTION:%.*]] = open_existential_addr immutable_access %0
 // CHECK:         [[STACK:%[0-9]+]] = alloc_stack $@opened({{".*"}}) ProtocolB
 // CHECK:         copy_addr [[PROJECTION]] to [initialization] [[STACK]]
@@ -91,7 +91,7 @@
   return a.intProp
 }
 
-// CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolO_pF : $@convention(thin) (@owned ProtocolO) -> Int {
+// CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21getIntPropExistentialySiAA9ProtocolO_pF : $@convention(thin) (@owned ProtocolO) -> Int {
 // CHECK: bb0([[ARG:%.*]] : @owned $ProtocolO):
 // CHECK:  [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:  [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]]
@@ -101,12 +101,12 @@
 // CHECK:  destroy_value [[PROJECTION_COPY]]
 // CHECK:  end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK:  destroy_value [[ARG]]
-// CHECK: } // end sil function '_T030generic_property_base_lifetime21getIntPropExistentialSiAA9ProtocolO_pF'
+// CHECK: } // end sil function '_T030generic_property_base_lifetime21getIntPropExistentialySiAA9ProtocolO_pF'
 func getIntPropExistential(_ a: ProtocolO) -> Int {
   return a.intProp
 }
 
-// CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21setIntPropExistentialyAA9ProtocolO_pF : $@convention(thin) (@owned ProtocolO) -> () {
+// CHECK-LABEL: sil hidden @_T030generic_property_base_lifetime21setIntPropExistentialyyAA9ProtocolO_pF : $@convention(thin) (@owned ProtocolO) -> () {
 // CHECK: bb0([[ARG:%.*]] : @owned $ProtocolO):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[PROJECTION:%.*]] = open_existential_ref [[BORROWED_ARG]]
@@ -116,7 +116,7 @@
 // CHECK:   destroy_value [[PROJECTION_COPY]]
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK:   destroy_value [[ARG]]
-// CHECK: } // end sil function '_T030generic_property_base_lifetime21setIntPropExistentialyAA9ProtocolO_pF'
+// CHECK: } // end sil function '_T030generic_property_base_lifetime21setIntPropExistentialyyAA9ProtocolO_pF'
 func setIntPropExistential(_ a: ProtocolO) {
   a.intProp = 0
 }
diff --git a/test/SILGen/generic_witness.swift b/test/SILGen/generic_witness.swift
index fee7e8a..88521c4 100644
--- a/test/SILGen/generic_witness.swift
+++ b/test/SILGen/generic_witness.swift
@@ -50,7 +50,7 @@
 
 extension Canvas : Medium {}
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T015generic_witness6CanvasVyxGAA6MediumA2aEP4drawy6StrokeQyd__5paint_qd__6penciltAA6PencilRd__7Texture_5PaintQZAIRSlFTW : $@convention(witness_method: Medium) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, @in_guaranteed Canvas<τ_0_0>) -> () {
-// CHECK: [[FN:%.*]] = function_ref @_T015generic_witness6CanvasV4drawy5PaintQz5paint_qd__6penciltAA6PencilRd__6StrokeQyd__AFRSlF : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, Canvas<τ_0_0>) -> ()
+// CHECK-LABEL: sil private [transparent] [thunk] @_T015generic_witness6CanvasVyxGAA6MediumA2aEP4draw5paint6pencily6StrokeQyd___qd__tAA6PencilRd__7Texture_5PaintQZAKRSlFTW : $@convention(witness_method: Medium) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, @in_guaranteed Canvas<τ_0_0>) -> () {
+// CHECK: [[FN:%.*]] = function_ref @_T015generic_witness6CanvasV4draw5paint6pencily5PaintQz_qd__tAA6PencilRd__6StrokeQyd__AHRSlF : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, Canvas<τ_0_0>) -> ()
 // CHECK: apply [[FN]]<τ_0_0, τ_1_0>({{.*}}) : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, Canvas<τ_0_0>) -> ()
 // CHECK: }
diff --git a/test/SILGen/guaranteed_closure_context.swift b/test/SILGen/guaranteed_closure_context.swift
index f5deee4..524df6e 100644
--- a/test/SILGen/guaranteed_closure_context.swift
+++ b/test/SILGen/guaranteed_closure_context.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -parse-as-library -emit-silgen -enable-sil-ownership -enable-guaranteed-closure-contexts %s | %FileCheck %s
+// RUN: %target-swift-frontend -parse-as-library -emit-silgen -enable-sil-ownership  %s | %FileCheck %s
 
 func use<T>(_: T) {}
 
diff --git a/test/SILGen/guaranteed_normal_args.swift b/test/SILGen/guaranteed_normal_args.swift
index 7f32459..f317303 100644
--- a/test/SILGen/guaranteed_normal_args.swift
+++ b/test/SILGen/guaranteed_normal_args.swift
@@ -42,11 +42,11 @@
   var buffer: Buffer
 
   // Make sure that the allocating init forwards into the initializing init at +1.
-  // CHECK-LABEL: sil hidden @_T0s15KlassWithBufferCABs0A0C3inK_tcfC : $@convention(method) (@owned Klass, @thick KlassWithBuffer.Type) -> @owned KlassWithBuffer {
+  // CHECK-LABEL: sil hidden @_T0s15KlassWithBufferC3inKABs0A0C_tcfC : $@convention(method) (@owned Klass, @thick KlassWithBuffer.Type) -> @owned KlassWithBuffer {
   // CHECK: bb0([[ARG:%.*]] : @owned $Klass,
-  // CHECK:   [[INITIALIZING_INIT:%.*]] = function_ref @_T0s15KlassWithBufferCABs0A0C3inK_tcfc : $@convention(method) (@owned Klass, @owned KlassWithBuffer) -> @owned KlassWithBuffer
+  // CHECK:   [[INITIALIZING_INIT:%.*]] = function_ref @_T0s15KlassWithBufferC3inKABs0A0C_tcfc : $@convention(method) (@owned Klass, @owned KlassWithBuffer) -> @owned KlassWithBuffer
   // CHECK:   apply [[INITIALIZING_INIT]]([[ARG]],
-  // CHECK: } // end sil function '_T0s15KlassWithBufferCABs0A0C3inK_tcfC'
+  // CHECK: } // end sil function '_T0s15KlassWithBufferC3inKABs0A0C_tcfC'
   init(inK: Klass = Klass()) {
     buffer = Buffer(inK: inK)
   }
@@ -80,13 +80,13 @@
 struct StructContainingBridgeObject {
   var rawValue: Builtin.BridgeObject
 
-  // CHECK-LABEL: sil hidden @_T0s28StructContainingBridgeObjectVAByXl8swiftObj_tcfC : $@convention(method) (@owned AnyObject, @thin StructContainingBridgeObject.Type) -> @owned StructContainingBridgeObject {
+  // CHECK-LABEL: sil hidden @_T0s28StructContainingBridgeObjectV8swiftObjAByXl_tcfC : $@convention(method) (@owned AnyObject, @thin StructContainingBridgeObject.Type) -> @owned StructContainingBridgeObject {
   // CHECK: bb0([[ARG:%.*]] : @owned $AnyObject,
   // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
   // CHECK:   [[CASTED_ARG:%.*]] = unchecked_ref_cast [[BORROWED_ARG]] : $AnyObject to $Builtin.BridgeObject
   // CHECK:   [[COPY_CASTED_ARG:%.*]] = copy_value [[CASTED_ARG]]
   // CHECK:   assign [[COPY_CASTED_ARG]] to
-  // CHECK: } // end sil function '_T0s28StructContainingBridgeObjectVAByXl8swiftObj_tcfC'
+  // CHECK: } // end sil function '_T0s28StructContainingBridgeObjectV8swiftObjAByXl_tcfC'
   init(swiftObj: AnyObject) {
     rawValue = Builtin.reinterpretCast(swiftObj)
   }
diff --git a/test/SILGen/guaranteed_self.swift b/test/SILGen/guaranteed_self.swift
index e5975f9..07a34cd 100644
--- a/test/SILGen/guaranteed_self.swift
+++ b/test/SILGen/guaranteed_self.swift
@@ -462,7 +462,7 @@
   // CHECK-NEXT: end_access [[READ]] : $*Kraken
   // CHECK:      [[BORROWED_KRAKEN:%.*]] = begin_borrow [[KRAKEN]]
   // CHECK-NEXT: [[KRAKEN_COPY:%.*]] = copy_value [[BORROWED_KRAKEN]]
-  // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> ()
+  // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> ()
   // CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]])
   // CHECK-NEXT: end_borrow [[BORROWED_KRAKEN]] from [[KRAKEN]]
   // CHECK-NEXT: [[KRAKEN_BOX:%.*]] = alloc_box ${ var Kraken }
@@ -475,7 +475,7 @@
   // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*Kraken
   // CHECK-NEXT: [[KRAKEN_COPY:%.*]] = load [copy] [[READ]]
   // CHECK-NEXT: end_access [[READ]] : $*Kraken
-  // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> ()
+  // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> ()
   // CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]])
   // CHECK-NEXT: destroy_value [[KRAKEN_BOX]]
   // CHECK-NEXT: destroy_value [[KRAKEN]]
@@ -502,7 +502,7 @@
   // CHECK-NEXT: [[KRAKEN:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]])
   // CHECK:      [[BORROWED_KRAKEN:%.*]] = begin_borrow [[KRAKEN]]
   // CHECK-NEXT: [[KRAKEN_COPY:%.*]] = copy_value [[BORROWED_KRAKEN]]
-  // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> ()
+  // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> ()
   // CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]])
   // CHECK-NEXT: end_borrow [[BORROWED_KRAKEN]] from [[KRAKEN]]
   // CHECK-NEXT: [[KRAKEN_BOX:%.*]] = alloc_box ${ var Kraken }
@@ -513,7 +513,7 @@
   // CHECK-NEXT: [[WRITE:%.*]] = begin_access [read] [unknown] [[PB]] : $*Kraken
   // CHECK-NEXT: [[KRAKEN_COPY:%.*]] = load [copy] [[WRITE]]
   // CHECK-NEXT: end_access [[WRITE]] : $*Kraken
-  // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> ()
+  // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> ()
   // CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]])
   // CHECK-NEXT: destroy_value [[KRAKEN_BOX]]
   // CHECK-NEXT: destroy_value [[KRAKEN]]
diff --git a/test/SILGen/if_expr.swift b/test/SILGen/if_expr.swift
index 79a3ee7..465c455 100644
--- a/test/SILGen/if_expr.swift
+++ b/test/SILGen/if_expr.swift
@@ -54,7 +54,7 @@
 // <rdar://problem/31595572> - crash when conditional expression is an
 // lvalue of IUO type
 
-// CHECK-LABEL: sil hidden @_T07if_expr18iuo_lvalue_ternarySiSQySbGz1x_tF : $@convention(thin) (@inout Optional<Bool>) -> Int
+// CHECK-LABEL: sil hidden @_T07if_expr18iuo_lvalue_ternary1xSiSQySbGz_tF : $@convention(thin) (@inout Optional<Bool>) -> Int
 // CHECK: [[IUO_BOOL_ADDR:%.*]] = begin_access [read] [unknown] %0 : $*Optional<Bool>
 // CHECK: [[IUO_BOOL:%.*]] = load [trivial] [[IUO_BOOL_ADDR]] : $*Optional<Bool>
 // CHECK: switch_enum [[IUO_BOOL]]
diff --git a/test/SILGen/if_while_binding.swift b/test/SILGen/if_while_binding.swift
index 2df545e..613c00d 100644
--- a/test/SILGen/if_while_binding.swift
+++ b/test/SILGen/if_while_binding.swift
@@ -279,7 +279,7 @@
 
 
 // <rdar://problem/19797158> Swift 1.2's "if" has 2 behaviors. They could be unified.
-// CHECK-LABEL: sil hidden @_T016if_while_binding0A16_leading_booleanySiF
+// CHECK-LABEL: sil hidden @_T016if_while_binding0A16_leading_booleanyySiF
 func if_leading_boolean(_ a : Int) {
   // Test the boolean condition.
   
@@ -318,7 +318,7 @@
 class BaseClass {}
 class DerivedClass : BaseClass {}
 
-// CHECK-LABEL: sil hidden @_T016if_while_binding20testAsPatternInIfLetyAA9BaseClassCSgF
+// CHECK-LABEL: sil hidden @_T016if_while_binding20testAsPatternInIfLetyyAA9BaseClassCSgF
 func testAsPatternInIfLet(_ a : BaseClass?) {
   // CHECK: bb0([[ARG:%.*]] : @owned $Optional<BaseClass>):
   // CHECK:   debug_value [[ARG]] : $Optional<BaseClass>, let, name "a"
@@ -362,7 +362,7 @@
 }
 
 // <rdar://problem/22312114> if case crashes swift - bools not supported in let/else yet
-// CHECK-LABEL: sil hidden @_T016if_while_binding12testCaseBoolySbSgF
+// CHECK-LABEL: sil hidden @_T016if_while_binding12testCaseBoolyySbSgF
 func testCaseBool(_ value : Bool?) {
   // CHECK: bb0([[ARG:%.*]] : @trivial $Optional<Bool>):
   // CHECK: switch_enum [[ARG]] : $Optional<Bool>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_TRAMPOLINE:bb[0-9]+]]
diff --git a/test/SILGen/implicitly_unwrapped_optional.swift b/test/SILGen/implicitly_unwrapped_optional.swift
index a80e99a..8e3ca70 100644
--- a/test/SILGen/implicitly_unwrapped_optional.swift
+++ b/test/SILGen/implicitly_unwrapped_optional.swift
@@ -46,7 +46,7 @@
   return wrap(x: x)!
 }
 
-// CHECK-LABEL: sil hidden @_T029implicitly_unwrapped_optional10tuple_bindSSSgSQySi_SStG1x_tF : $@convention(thin) (@owned Optional<(Int, String)>) -> @owned Optional<String> {
+// CHECK-LABEL: sil hidden @_T029implicitly_unwrapped_optional10tuple_bind1xSSSgSQySi_SStG_tF : $@convention(thin) (@owned Optional<(Int, String)>) -> @owned Optional<String> {
 func tuple_bind(x x: (Int, String)!) -> String? {
   return x?.1
   // CHECK:   cond_br {{%.*}}, [[NONNULL:bb[0-9]+]], [[NULL:bb[0-9]+]]
@@ -55,7 +55,7 @@
   // CHECK-NOT: destroy_value [[STRING]]
 }
 
-// CHECK-LABEL: sil hidden @_T029implicitly_unwrapped_optional011tuple_bind_a1_B0SSSQySi_SStG1x_tF
+// CHECK-LABEL: sil hidden @_T029implicitly_unwrapped_optional011tuple_bind_a1_B01xSSSQySi_SStG_tF
 func tuple_bind_implicitly_unwrapped(x x: (Int, String)!) -> String {
   return x.1
 }
diff --git a/test/SILGen/import_as_member.swift b/test/SILGen/import_as_member.swift
index 6d4154a..3619560 100644
--- a/test/SILGen/import_as_member.swift
+++ b/test/SILGen/import_as_member.swift
@@ -21,7 +21,7 @@
 // CHECK-LABEL: sil {{.*}}returnStringGlobalVar{{.*}} () -> @owned String {
 // CHECK:   %0 = global_addr @PKPandaCutenessFactor : $*NSString
 // CHECK:   [[VAL:%.*]] = load [copy] %0 : $*NSString
-// CHECK:   [[BRIDGE:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+// CHECK:   [[BRIDGE:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
 // CHECK:   [[RESULT:%.*]] = apply [[BRIDGE]](
 // CHECK:   return [[RESULT]] : $String
 // CHECK-NEXT: }
@@ -32,7 +32,7 @@
 // CHECK-LABEL: sil {{.*}}returnNullableStringGlobalVar{{.*}} () -> @owned Optional<String> {
 // CHECK:   %0 = global_addr @PKPandaCuddlynessFactor : $*NSString
 // CHECK:   [[VAL:%.*]] = load [copy] %0 : $*NSString
-// CHECK:   [[BRIDGE:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+// CHECK:   [[BRIDGE:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
 // CHECK:   [[RESULT:%.*]] = apply [[BRIDGE]](
 // CHECK:   [[SOME:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[RESULT]]
 // CHECK:   return [[SOME]] : $Optional<String>
@@ -54,7 +54,7 @@
 }
 
 extension SomeClass {
-  // CHECK-LABEL: sil hidden @_T0So9SomeClassC16import_as_memberEABSd6double_tcfc
+  // CHECK-LABEL: sil hidden @_T0So9SomeClassC16import_as_memberE6doubleABSd_tcfc
   // CHECK: bb0([[DOUBLE:%[0-9]+]] : $Double
   // CHECK-NOT: value_metatype
   // CHECK: [[FNREF:%[0-9]+]] = function_ref @MakeIAMSomeClass
diff --git a/test/SILGen/indirect_enum.swift b/test/SILGen/indirect_enum.swift
index be73d6c..9d781ce 100644
--- a/test/SILGen/indirect_enum.swift
+++ b/test/SILGen/indirect_enum.swift
@@ -6,7 +6,7 @@
   case Branch(left: TreeA<T>, right: TreeA<T>)
 }
 
-// CHECK-LABEL: sil hidden @_T013indirect_enum11TreeA_casesyx_AA0C1AOyxG1lAE1rtlF : $@convention(thin) <T> (@in T, @owned TreeA<T>, @owned TreeA<T>) -> () {
+// CHECK-LABEL: sil hidden @_T013indirect_enum11TreeA_cases_1l1ryx_AA0C1AOyxGAGtlF : $@convention(thin) <T> (@in T, @owned TreeA<T>, @owned TreeA<T>) -> () {
 func TreeA_cases<T>(_ t: T, l: TreeA<T>, r: TreeA<T>) {
 // CHECK: bb0([[ARG1:%.*]] : $*T, [[ARG2:%.*]] : $TreeA<T>, [[ARG3:%.*]] : $TreeA<T>):
 // CHECK:         [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type
@@ -43,10 +43,10 @@
   let _ = TreeA<T>.Branch(left: l, right: r)
 
 }
-// CHECK: // end sil function '_T013indirect_enum11TreeA_casesyx_AA0C1AOyxG1lAE1rtlF'
+// CHECK: // end sil function '_T013indirect_enum11TreeA_cases_1l1ryx_AA0C1AOyxGAGtlF'
 
 
-// CHECK-LABEL: sil hidden @_T013indirect_enum16TreeA_reabstractyS2icF : $@convention(thin) (@owned @callee_guaranteed (Int) -> Int) -> () {
+// CHECK-LABEL: sil hidden @_T013indirect_enum16TreeA_reabstractyyS2icF : $@convention(thin) (@owned @callee_guaranteed (Int) -> Int) -> () {
 func TreeA_reabstract(_ f: @escaping (Int) -> Int) {
 // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed (Int) -> Int):
 // CHECK:         [[METATYPE:%.*]] = metatype $@thin TreeA<(Int) -> Int>.Type
@@ -64,7 +64,7 @@
 // CHECK: return
   let _ = TreeA<(Int) -> Int>.Leaf(f)
 }
-// CHECK: } // end sil function '_T013indirect_enum16TreeA_reabstractyS2icF'
+// CHECK: } // end sil function '_T013indirect_enum16TreeA_reabstractyyS2icF'
 
 enum TreeB<T> {
   case Nil
@@ -72,7 +72,7 @@
   indirect case Branch(left: TreeB<T>, right: TreeB<T>)
 }
 
-// CHECK-LABEL: sil hidden @_T013indirect_enum11TreeB_casesyx_AA0C1BOyxG1lAE1rtlF
+// CHECK-LABEL: sil hidden @_T013indirect_enum11TreeB_cases_1l1ryx_AA0C1BOyxGAGtlF
 func TreeB_cases<T>(_ t: T, l: TreeB<T>, r: TreeB<T>) {
 
 // CHECK:         [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type
@@ -113,7 +113,7 @@
 
 }
 
-// CHECK-LABEL: sil hidden @_T013indirect_enum13TreeInt_casesySi_AA0cD0O1lAD1rtF : $@convention(thin) (Int, @owned TreeInt, @owned TreeInt) -> ()
+// CHECK-LABEL: sil hidden @_T013indirect_enum13TreeInt_cases_1l1rySi_AA0cD0OAFtF : $@convention(thin) (Int, @owned TreeInt, @owned TreeInt) -> ()
 func TreeInt_cases(_ t: Int, l: TreeInt, r: TreeInt) {
 // CHECK: bb0([[ARG1:%.*]] : $Int, [[ARG2:%.*]] : $TreeInt, [[ARG3:%.*]] : $TreeInt):
 // CHECK:         [[METATYPE:%.*]] = metatype $@thin TreeInt.Type
@@ -145,7 +145,7 @@
 // CHECK-NEXT:    destroy_value [[ARG2]]
   let _ = TreeInt.Branch(left: l, right: r)
 }
-// CHECK: } // end sil function '_T013indirect_enum13TreeInt_casesySi_AA0cD0O1lAD1rtF'
+// CHECK: } // end sil function '_T013indirect_enum13TreeInt_cases_1l1rySi_AA0cD0OAFtF'
 
 enum TreeInt {
   case Nil
@@ -164,7 +164,7 @@
 func c<T>(_ x: T, _ y: T) {}
 func d() {}
 
-// CHECK-LABEL: sil hidden @_T013indirect_enum11switchTreeAyAA0D1AOyxGlF : $@convention(thin) <T> (@owned TreeA<T>) -> () {
+// CHECK-LABEL: sil hidden @_T013indirect_enum11switchTreeAyyAA0D1AOyxGlF : $@convention(thin) <T> (@owned TreeA<T>) -> () {
 func switchTreeA<T>(_ x: TreeA<T>) {
   // CHECK: bb0([[ARG:%.*]] : $TreeA<T>):
   // --           x +2
@@ -239,7 +239,7 @@
   // --           x +0
   // CHECK:       destroy_value [[ARG]] : $TreeA<T>
 }
-// CHECK: } // end sil function '_T013indirect_enum11switchTreeAyAA0D1AOyxGlF'
+// CHECK: } // end sil function '_T013indirect_enum11switchTreeAyyAA0D1AOyxGlF'
 
 // CHECK-LABEL: sil hidden @_T013indirect_enum11switchTreeB{{[_0-9a-zA-Z]*}}F
 func switchTreeB<T>(_ x: TreeB<T>) {
@@ -533,7 +533,7 @@
 }
 
 // SEMANTIC ARC TODO: This test needs to be made far more comprehensive.
-// CHECK-LABEL: sil hidden @_T013indirect_enum35dontDisableCleanupOfIndirectPayloadyAA010TrivialButG0OF : $@convention(thin) (@owned TrivialButIndirect) -> () {
+// CHECK-LABEL: sil hidden @_T013indirect_enum35dontDisableCleanupOfIndirectPayloadyyAA010TrivialButG0OF : $@convention(thin) (@owned TrivialButIndirect) -> () {
 func dontDisableCleanupOfIndirectPayload(_ x: TrivialButIndirect) {
   // CHECK: bb0([[ARG:%.*]] : $TrivialButIndirect):
   // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
@@ -560,4 +560,4 @@
 
   guard case .Indirect(let bar) = x else { return }
 }
-// CHECK: } // end sil function '_T013indirect_enum35dontDisableCleanupOfIndirectPayloadyAA010TrivialButG0OF'
+// CHECK: } // end sil function '_T013indirect_enum35dontDisableCleanupOfIndirectPayloadyyAA010TrivialButG0OF'
diff --git a/test/SILGen/initializers.swift b/test/SILGen/initializers.swift
index 44a1999..dacde29 100644
--- a/test/SILGen/initializers.swift
+++ b/test/SILGen/initializers.swift
@@ -358,7 +358,7 @@
     return nil
   }
 
-  // CHECK-LABEL: sil hidden @_T021failable_initializers17FailableBaseClassCACSgyt19failAfterDelegation_tcfc : $@convention(method) (@owned FailableBaseClass) -> @owned Optional<FailableBaseClass> {
+  // CHECK-LABEL: sil hidden @_T021failable_initializers17FailableBaseClassC19failAfterDelegationACSgyt_tcfc : $@convention(method) (@owned FailableBaseClass) -> @owned Optional<FailableBaseClass> {
   // CHECK: bb0([[OLD_SELF:%.*]] : @owned $FailableBaseClass):
   // CHECK:   [[SELF_BOX:%.*]] = alloc_box ${ var FailableBaseClass }, let, name "self"
   // CHECK:   [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
@@ -371,7 +371,7 @@
   // CHECK:   br bb2([[RESULT]] : $Optional<FailableBaseClass>)
   // CHECK: bb2([[RESULT:%.*]] : @owned $Optional<FailableBaseClass>):
   // CHECK:   return [[RESULT]]
-  // CHECK: } // end sil function '_T021failable_initializers17FailableBaseClassCACSgyt19failAfterDelegation_tcfc
+  // CHECK: } // end sil function '_T021failable_initializers17FailableBaseClassC19failAfterDelegationACSgyt_tcfc
   convenience init?(failAfterDelegation: ()) {
     self.init(noFail: ())
     return nil
@@ -379,7 +379,7 @@
 
   // Optional to optional
   //
-  // CHECK-LABEL: sil hidden @_T021failable_initializers17FailableBaseClassCACSgyt20failDuringDelegation_tcfc : $@convention(method) (@owned FailableBaseClass) -> @owned Optional<FailableBaseClass> {
+  // CHECK-LABEL: sil hidden @_T021failable_initializers17FailableBaseClassC20failDuringDelegationACSgyt_tcfc : $@convention(method) (@owned FailableBaseClass) -> @owned Optional<FailableBaseClass> {
   // CHECK: bb0([[OLD_SELF:%.*]] : @owned $FailableBaseClass):
   // CHECK:   [[SELF_BOX:%.*]] = alloc_box ${ var FailableBaseClass }, let, name "self"
   // CHECK:   [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
@@ -414,7 +414,7 @@
 
   // IUO to optional
   //
-  // CHECK-LABEL: sil hidden @_T021failable_initializers17FailableBaseClassCSQyACGyt21failDuringDelegation2_tcfc : $@convention(method) (@owned FailableBaseClass) -> @owned Optional<FailableBaseClass> {
+  // CHECK-LABEL: sil hidden @_T021failable_initializers17FailableBaseClassC21failDuringDelegation2SQyACGyt_tcfc : $@convention(method) (@owned FailableBaseClass) -> @owned Optional<FailableBaseClass> {
   // CHECK: bb0([[OLD_SELF:%.*]] : @owned $FailableBaseClass):
   // CHECK:   [[SELF_BOX:%.*]] = alloc_box ${ var FailableBaseClass }, let, name "self"
   // CHECK:   [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
@@ -438,7 +438,7 @@
   //
   // CHECK: [[EPILOG_BB]]([[WRAPPED_RESULT:%.*]] : @owned $Optional<FailableBaseClass>):
   // CHECK:   return [[WRAPPED_RESULT]]
-  // CHECK: } // end sil function '_T021failable_initializers17FailableBaseClassCSQyACGyt21failDuringDelegation2_tcfc'
+  // CHECK: } // end sil function '_T021failable_initializers17FailableBaseClassC21failDuringDelegation2SQyACGyt_tcfc'
   convenience init!(failDuringDelegation2: ()) {
     self.init(failBeforeFullInitialization: ())! // unnecessary-but-correct '!'
   }
@@ -464,7 +464,7 @@
 class FailableDerivedClass : FailableBaseClass {
   var otherMember: Canary
 
-  // CHECK-LABEL: sil hidden @_T021failable_initializers20FailableDerivedClassCACSgyt27derivedFailBeforeDelegation_tcfc : $@convention(method) (@owned FailableDerivedClass) -> @owned Optional<FailableDerivedClass> {
+  // CHECK-LABEL: sil hidden @_T021failable_initializers20FailableDerivedClassC27derivedFailBeforeDelegationACSgyt_tcfc : $@convention(method) (@owned FailableDerivedClass) -> @owned Optional<FailableDerivedClass> {
   // CHECK: bb0([[OLD_SELF:%.*]] : @owned $FailableDerivedClass):
   // CHECK:   [[SELF_BOX:%.*]] = alloc_box ${ var FailableDerivedClass }, let, name "self"
   // CHECK:   [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]]
@@ -483,7 +483,7 @@
     return nil
   }
 
-  // CHECK-LABEL: sil hidden @_T021failable_initializers20FailableDerivedClassCACSgyt27derivedFailDuringDelegation_tcfc : $@convention(method) (@owned FailableDerivedClass) -> @owned Optional<FailableDerivedClass> {
+  // CHECK-LABEL: sil hidden @_T021failable_initializers20FailableDerivedClassC27derivedFailDuringDelegationACSgyt_tcfc : $@convention(method) (@owned FailableDerivedClass) -> @owned Optional<FailableDerivedClass> {
   // CHECK: bb0([[OLD_SELF:%.*]] : @owned $FailableDerivedClass):
   init?(derivedFailDuringDelegation: ()) {
     // First initialize the lvalue for self.
@@ -579,7 +579,7 @@
 
   // ---- Delegating to super
 
-  // CHECK-LABEL: sil hidden @_T021failable_initializers17ThrowDerivedClassCACSi30delegatingFailBeforeDelegation_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) {
+  // CHECK-LABEL: sil hidden @_T021failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegationACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) {
   // CHECK: bb0(
   // First initialize.
   // CHECK:   [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self"
@@ -598,13 +598,13 @@
   // CHECK:   end_borrow [[SELF]] from [[PROJ]]
   //
   // Now we perform the unwrap.
-  // CHECK:   [[UNWRAP_FN:%.*]] = function_ref @_T021failable_initializers6unwrapS2iKF : $@convention(thin)
+  // CHECK:   [[UNWRAP_FN:%.*]] = function_ref @_T021failable_initializers6unwrapyS2iKF : $@convention(thin)
   // CHECK:   try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]]
   //
   // CHECK: [[NORMAL_BB]](
   // CHECK:   [[SELF:%.*]] = load [take] [[PROJ]]
   // CHECK:   [[SELF_BASE:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass
-  // CHECK:   [[BASE_INIT_FN:%.*]] = function_ref @_T021failable_initializers14ThrowBaseClassCACyt6noFail_tcfc : $@convention(method)
+  // CHECK:   [[BASE_INIT_FN:%.*]] = function_ref @_T021failable_initializers14ThrowBaseClassC6noFailACyt_tcfc : $@convention(method)
   // CHECK:   [[SELF_INIT_BASE:%.*]] = apply [[BASE_INIT_FN]]([[SELF_BASE]])
   // CHECK:   [[SELF:%.*]] = unchecked_ref_cast [[SELF_INIT_BASE]] : $ThrowBaseClass to $ThrowDerivedClass
   // CHECK:   store [[SELF]] to [init] [[PROJ]]
@@ -617,13 +617,13 @@
   // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error):
   // CHECK:   destroy_value [[MARK_UNINIT]]
   // CHECK:   throw [[ERROR]]
-  // CHECK: } // end sil function '_T021failable_initializers17ThrowDerivedClassCACSi30delegatingFailBeforeDelegation_tKcfc'
+  // CHECK: } // end sil function '_T021failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegationACSi_tKcfc'
   init(delegatingFailBeforeDelegation : Int) throws {
     try unwrap(delegatingFailBeforeDelegation)
     super.init(noFail: ())
   }
 
-  // CHECK-LABEL: sil hidden @_T021failable_initializers17ThrowDerivedClassCACSi41delegatingFailDuringDelegationArgEmission_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) {
+  // CHECK-LABEL: sil hidden @_T021failable_initializers17ThrowDerivedClassC41delegatingFailDuringDelegationArgEmissionACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) {
   // CHECK: bb0(
   // First initialize.
   // CHECK:   [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self"
@@ -644,13 +644,13 @@
   // Now we begin argument emission where we perform the unwrap.
   // CHECK:   [[SELF:%.*]] = load [take] [[PROJ]]
   // CHECK:   [[BASE_SELF:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass
-  // CHECK:   [[UNWRAP_FN:%.*]] = function_ref @_T021failable_initializers6unwrapS2iKF : $@convention(thin)
+  // CHECK:   [[UNWRAP_FN:%.*]] = function_ref @_T021failable_initializers6unwrapyS2iKF : $@convention(thin)
   // CHECK:   try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]]
   //
   // Now we emit the call to the initializer. Notice how we return self back to
   // its memory locatio nbefore any other work is done.
   // CHECK: [[NORMAL_BB]](
-  // CHECK:   [[INIT_FN:%.*]] = function_ref @_T021failable_initializers14ThrowBaseClassCACSi6noFail_tcfc : $@convention(method)
+  // CHECK:   [[INIT_FN:%.*]] = function_ref @_T021failable_initializers14ThrowBaseClassC6noFailACSi_tcfc : $@convention(method)
   // CHECK:   [[BASE_SELF_INIT:%.*]] = apply [[INIT_FN]]({{%.*}}, [[BASE_SELF]])
   // CHECK:   [[SELF:%.*]] = unchecked_ref_cast [[BASE_SELF_INIT]] : $ThrowBaseClass to $ThrowDerivedClass
   // CHECK:   store [[SELF]] to [init] [[PROJ]]
@@ -669,12 +669,12 @@
   // CHECK:   store [[SELF]] to [init] [[PROJ]]
   // CHECK:   destroy_value [[MARK_UNINIT]]
   // CHECK:   throw [[ERROR]]
-  // CHECK: } // end sil function '_T021failable_initializers17ThrowDerivedClassCACSi41delegatingFailDuringDelegationArgEmission_tKcfc'
+  // CHECK: } // end sil function '_T021failable_initializers17ThrowDerivedClassC41delegatingFailDuringDelegationArgEmissionACSi_tKcfc'
   init(delegatingFailDuringDelegationArgEmission : Int) throws {
     super.init(noFail: try unwrap(delegatingFailDuringDelegationArgEmission))
   }
 
-  // CHECK-LABEL: sil hidden @_T021failable_initializers17ThrowDerivedClassCACSi34delegatingFailDuringDelegationCall_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) {
+  // CHECK-LABEL: sil hidden @_T021failable_initializers17ThrowDerivedClassC34delegatingFailDuringDelegationCallACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) {
   // CHECK: bb0(
   // First initialize.
   // CHECK:   [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self"
@@ -700,12 +700,12 @@
   // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error):
   // CHECK-NEXT:   destroy_value [[MARK_UNINIT]]
   // CHECK-NEXT:   throw [[ERROR]]
-  // CHECK: } // end sil function '_T021failable_initializers17ThrowDerivedClassCACSi34delegatingFailDuringDelegationCall_tKcfc'
+  // CHECK: } // end sil function '_T021failable_initializers17ThrowDerivedClassC34delegatingFailDuringDelegationCallACSi_tKcfc'
   init(delegatingFailDuringDelegationCall : Int) throws {
     try super.init()
   }
 
-  // CHECK-LABEL: sil hidden @_T021failable_initializers17ThrowDerivedClassCACSi29delegatingFailAfterDelegation_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) {
+  // CHECK-LABEL: sil hidden @_T021failable_initializers17ThrowDerivedClassC29delegatingFailAfterDelegationACSi_tKcfc : $@convention(method) (Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) {
   // CHECK: bb0(
   // First initialize.
   // CHECK:   [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self"
@@ -716,13 +716,13 @@
   // Call the initializer and then store the new self back into its memory slot.
   // CHECK:   [[SELF:%.*]] = load [take] [[PROJ]]
   // CHECK:   [[BASE_SELF:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass
-  // CHECK:   [[INIT_FN:%.*]] = function_ref @_T021failable_initializers14ThrowBaseClassCACyt6noFail_tcfc : $@convention(method)
+  // CHECK:   [[INIT_FN:%.*]] = function_ref @_T021failable_initializers14ThrowBaseClassC6noFailACyt_tcfc : $@convention(method)
   // CHECK:   [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) : $@convention(method) (@owned ThrowBaseClass) -> @owned ThrowBaseClass
   // CHECK:   [[NEW_SELF_CAST:%.*]] = unchecked_ref_cast [[NEW_SELF]] : $ThrowBaseClass to $ThrowDerivedClass
   // CHECK:   store [[NEW_SELF_CAST]] to [init] [[PROJ]]
   //
   // Finally perform the unwrap.
-  // CHECK:   [[UNWRAP_FN:%.*]] = function_ref @_T021failable_initializers6unwrapS2iKF : $@convention(thin) (Int) -> (Int, @error Error)
+  // CHECK:   [[UNWRAP_FN:%.*]] = function_ref @_T021failable_initializers6unwrapyS2iKF : $@convention(thin) (Int) -> (Int, @error Error)
   // CHECK:   try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]]
   //
   // Insert the return statement into the normal block...
@@ -735,32 +735,32 @@
   // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error):
   // CHECK-NEXT:   destroy_value [[MARK_UNINIT]]
   // CHECK-NEXT:   throw [[ERROR]]
-  // CHECK: } // end sil function '_T021failable_initializers17ThrowDerivedClassCACSi29delegatingFailAfterDelegation_tKcfc'
+  // CHECK: } // end sil function '_T021failable_initializers17ThrowDerivedClassC29delegatingFailAfterDelegationACSi_tKcfc'
   init(delegatingFailAfterDelegation : Int) throws {
     super.init(noFail: ())
     try unwrap(delegatingFailAfterDelegation)
   }
 
-  // CHECK-LABEL: sil hidden @_T021failable_initializers17ThrowDerivedClassCACSi30delegatingFailBeforeDelegation_Si0fg6DuringI11ArgEmissiontKcfc : $@convention(method) (Int, Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) {
+  // CHECK-LABEL: sil hidden @_T021failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegation0fg6DuringI11ArgEmissionACSi_SitKcfc : $@convention(method) (Int, Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) {
   // Create our box.
   // CHECK:   [[REF:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self"
   // CHECK:   [[MARK_UNINIT:%.*]] = mark_uninitialized [derivedself] [[REF]] : ${ var ThrowDerivedClass }
   // CHECK:   [[PROJ:%.*]] = project_box [[MARK_UNINIT]]
   //
   // Perform the unwrap.
-  // CHECK:   [[UNWRAP_FN:%.*]] = function_ref @_T021failable_initializers6unwrapS2iKF : $@convention(thin) (Int) -> (Int, @error Error)
+  // CHECK:   [[UNWRAP_FN:%.*]] = function_ref @_T021failable_initializers6unwrapyS2iKF : $@convention(thin) (Int) -> (Int, @error Error)
   // CHECK:   try_apply [[UNWRAP_FN]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[UNWRAP_NORMAL_BB:bb[0-9]+]], error [[UNWRAP_ERROR_BB:bb[0-9]+]]
   //
   // Now we begin argument emission where we perform another unwrap.
   // CHECK: [[UNWRAP_NORMAL_BB]](
   // CHECK:   [[SELF:%.*]] = load [take] [[PROJ]]
   // CHECK:   [[SELF_CAST:%.*]] = upcast [[SELF]] : $ThrowDerivedClass to $ThrowBaseClass
-  // CHECK:   [[UNWRAP_FN2:%.*]] = function_ref @_T021failable_initializers6unwrapS2iKF : $@convention(thin) (Int) -> (Int, @error Error)
+  // CHECK:   [[UNWRAP_FN2:%.*]] = function_ref @_T021failable_initializers6unwrapyS2iKF : $@convention(thin) (Int) -> (Int, @error Error)
   // CHECK:   try_apply [[UNWRAP_FN2]]({{%.*}}) : $@convention(thin) (Int) -> (Int, @error Error), normal [[UNWRAP_NORMAL_BB2:bb[0-9]+]], error [[UNWRAP_ERROR_BB2:bb[0-9]+]]
   //
   // Then since this example has a
   // CHECK: [[UNWRAP_NORMAL_BB2]]([[INT:%.*]] : @trivial $Int):
-  // CHECK:   [[INIT_FN2:%.*]] = function_ref @_T021failable_initializers14ThrowBaseClassCACSi6noFail_tcfc : $@convention(method) (Int, @owned ThrowBaseClass) -> @owned ThrowBaseClass
+  // CHECK:   [[INIT_FN2:%.*]] = function_ref @_T021failable_initializers14ThrowBaseClassC6noFailACSi_tcfc : $@convention(method) (Int, @owned ThrowBaseClass) -> @owned ThrowBaseClass
   // CHECK:   [[NEW_SELF_CAST:%.*]] = apply [[INIT_FN2]]([[INT]], [[SELF_CAST]]) : $@convention(method) (Int, @owned ThrowBaseClass) -> @owned ThrowBaseClass
   // CHECK:   [[NEW_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF_CAST]] : $ThrowBaseClass to $ThrowDerivedClass
   // CHECK:   store [[NEW_SELF]] to [init] [[PROJ]]
@@ -780,7 +780,7 @@
   // CHECK: [[ERROR_JOIN]]([[ERROR_PHI:%.*]] : @owned $Error):
   // CHECK:   destroy_value [[MARK_UNINIT]]
   // CHECK:   throw [[ERROR_PHI]]
-  // CHECK: } // end sil function '_T021failable_initializers17ThrowDerivedClassCACSi30delegatingFailBeforeDelegation_Si0fg6DuringI11ArgEmissiontKcfc'
+  // CHECK: } // end sil function '_T021failable_initializers17ThrowDerivedClassC30delegatingFailBeforeDelegation0fg6DuringI11ArgEmissionACSi_SitKcfc'
   init(delegatingFailBeforeDelegation : Int, delegatingFailDuringDelegationArgEmission : Int) throws {
     try unwrap(delegatingFailBeforeDelegation)
     super.init(noFail: try unwrap(delegatingFailDuringDelegationArgEmission))
@@ -875,7 +875,7 @@
     try unwrap(chainingFailAfterDelegation)
   }
 
-  // CHECK-LABEL: sil hidden @_T021failable_initializers17ThrowDerivedClassCACSi39chainingFailDuringDelegationArgEmission_Si0fghI4CalltKcfc : $@convention(method) (Int, Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) {
+  // CHECK-LABEL: sil hidden @_T021failable_initializers17ThrowDerivedClassC39chainingFailDuringDelegationArgEmission0fghI4CallACSi_SitKcfc : $@convention(method) (Int, Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) {
   // CHECK: bb0({{.*}}, [[OLD_SELF:%.*]] : @owned $ThrowDerivedClass):
   // CHECK:   [[SELF_BOX:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self"
   // CHECK:   [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
@@ -912,7 +912,7 @@
     try unwrap(chainingFailAfterDelegation)
   }
 
-  // CHECK-LABEL: sil hidden @_T021failable_initializers17ThrowDerivedClassCACSi32chainingFailDuringDelegationCall_Si0fg5AfterI0tKcfc : $@convention(method) (Int, Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) {
+  // CHECK-LABEL: sil hidden @_T021failable_initializers17ThrowDerivedClassC32chainingFailDuringDelegationCall0fg5AfterI0ACSi_SitKcfc : $@convention(method) (Int, Int, @owned ThrowDerivedClass) -> (@owned ThrowDerivedClass, @error Error) {
   // CHECK: bb0({{.*}}, [[OLD_SELF:%.*]] : @owned $ThrowDerivedClass):
   // CHECK:   [[SELF_BOX:%.*]] = alloc_box ${ var ThrowDerivedClass }, let, name "self"
   // CHECK:   [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
@@ -941,7 +941,7 @@
   // CHECK: [[THROWING_BB]]([[ERROR:%.*]] : @owned $Error):
   // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]]
   // CHECK-NEXT: throw [[ERROR]]
-  // CHECK: } // end sil function '_T021failable_initializers17ThrowDerivedClassCACSi28chainingFailBeforeDelegation_Si0fg6DuringI11ArgEmissionSi0fgjI4CalltKcfC'
+  // CHECK: } // end sil function '_T021failable_initializers17ThrowDerivedClassC28chainingFailBeforeDelegation0fg6DuringI11ArgEmission0fgjI4CallACSi_S2itKcfC'
   convenience init(chainingFailDuringDelegationCall : Int, chainingFailAfterDelegation : Int) throws {
     try self.init()
     try unwrap(chainingFailAfterDelegation)
diff --git a/test/SILGen/inlineable_attribute.swift b/test/SILGen/inlineable_attribute.swift
index f1aa8e1..1e32b2e 100644
--- a/test/SILGen/inlineable_attribute.swift
+++ b/test/SILGen/inlineable_attribute.swift
@@ -14,7 +14,7 @@
     return 5
   }
 
-  // CHECK-LABEL: sil [serialized] @_T020inlineable_attribute4MyStVS2icig : $@convention(method) (Int, MySt) -> Int
+  // CHECK-LABEL: sil [serialized] @_T020inlineable_attribute4MyStVyS2icig : $@convention(method) (Int, MySt) -> Int
   @_inlineable public subscript(x: Int) -> Int {
     return x
   }
@@ -26,12 +26,12 @@
 
   // Allocating entry point is [serialized]
 
-  // CHECK-LABEL: sil [serialized] @_T020inlineable_attribute5MyClsCACyt14designatedInit_tcfC : $@convention(method) (@thick MyCls.Type) -> @owned MyCls
+  // CHECK-LABEL: sil [serialized] @_T020inlineable_attribute5MyClsC14designatedInitACyt_tcfC : $@convention(method) (@thick MyCls.Type) -> @owned MyCls
   public init(designatedInit: ()) {}
 
   // Note -- convenience init is intentionally not [serialized]
 
-  // CHECK-LABEL: sil @_T020inlineable_attribute5MyClsCACyt15convenienceInit_tcfC : $@convention(method) (@thick MyCls.Type) -> @owned MyCls
+  // CHECK-LABEL: sil @_T020inlineable_attribute5MyClsC15convenienceInitACyt_tcfC : $@convention(method) (@thick MyCls.Type) -> @owned MyCls
   public convenience init(convenienceInit: ()) {
     self.init(designatedInit: ())
   }
@@ -43,7 +43,7 @@
   case c(MySt)
 }
 
-// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] @_T020inlineable_attribute6MyEnumO1cAcA0C2StVcACmFTc : $@convention(thin) (@thin MyEnum.Type) -> @owned @callee_guaranteed (MySt) -> MyEnum
+// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] @_T020inlineable_attribute6MyEnumO1cyAcA0C2StVcACmFTc : $@convention(thin) (@thin MyEnum.Type) -> @owned @callee_guaranteed (MySt) -> MyEnum
 
 @_inlineable public func referencesMyEnum() {
   _ = MyEnum.c
@@ -61,7 +61,7 @@
   public func gallop() {}
 }
 
-// CHECK-LABEL: sil [serialized] @_T020inlineable_attribute15talkAboutAHorseyAA5HorseC1h_tF : $@convention(thin) (@owned Horse) -> () {
+// CHECK-LABEL: sil [serialized] @_T020inlineable_attribute15talkAboutAHorse1hyAA5HorseC_tF : $@convention(thin) (@owned Horse) -> () {
 // CHECK: function_ref @_T020inlineable_attribute5HorseC6gallopyyFTc
 // CHECK: return
 // CHECK: }
@@ -86,7 +86,7 @@
 
 // Make sure the synthesized delegating initializer is inlineable also
 
-// CHECK-LABEL: sil [serialized] @_T020inlineable_attribute7DerivedCAcA5HorseC5horse_tcfc : $@convention(method) (@owned Horse, @owned Derived) -> @owned Derived
+// CHECK-LABEL: sil [serialized] @_T020inlineable_attribute7DerivedC5horseAcA5HorseC_tcfc : $@convention(method) (@owned Horse, @owned Derived) -> @owned Derived
 @_versioned class Derived : Base {
   // Allow @_inlineable deinits
   @_inlineable deinit {}
diff --git a/test/SILGen/inlineable_attribute_objc.swift b/test/SILGen/inlineable_attribute_objc.swift
index c66c9fa..c0857e9 100644
--- a/test/SILGen/inlineable_attribute_objc.swift
+++ b/test/SILGen/inlineable_attribute_objc.swift
@@ -14,7 +14,7 @@
 // Make sure we can reference dynamic thunks and curry thunks
 // from inlineable scopes
 
-// CHECK-LABEL: sil [serialized] @_T025inlineable_attribute_objc15talkAboutAHorseyAA5HorseC1h_tF : $@convention(thin) (@owned Horse) -> () {
+// CHECK-LABEL: sil [serialized] @_T025inlineable_attribute_objc15talkAboutAHorse1hyAA5HorseC_tF : $@convention(thin) (@owned Horse) -> () {
 // CHECK: function_ref @_T025inlineable_attribute_objc5HorseC6gallopyyFTc : $@convention(thin) (@owned Horse) -> @owned @callee_guaranteed () -> ()
 // CHECK: return
 // CHECK: }
diff --git a/test/SILGen/interface_type_mangling.swift b/test/SILGen/interface_type_mangling.swift
index 06e9108..8338884 100644
--- a/test/SILGen/interface_type_mangling.swift
+++ b/test/SILGen/interface_type_mangling.swift
@@ -30,7 +30,7 @@
 func f3<T where T: PQ, T: PP, T: P>(_ x: T) {}
 
 // CHECK-LABEL: interface_type_mangling.g1
-// CHECK:                                 [[G_SIGNATURE:<A, B where A: interface_type_mangling.PP, B: interface_type_mangling.PQ>\(B, y: A\) -> \(\)]]
+// CHECK:                                 [[G_SIGNATURE:<A, B where A: interface_type_mangling.PP, B: interface_type_mangling.PQ>\(_: B, y: A\) -> \(\)]]
 func g1<U, T where T: PQ, U: PP>(_ x: T, y: U) {}
 // CHECK:       interface_type_mangling.g2[[G_SIGNATURE]]
 func g2<U, T where T: PQ, T.Assoc1: A, U: PP>(_ x: T, y: U) {}
@@ -175,7 +175,7 @@
 struct X {}; struct Y {}
 
 // CHECK-LABEL: interface_type_mangling.m1
-// CHECK:                                 [[M_SIGNATURE:<A, B where A: interface_type_mangling.A, B: interface_type_mangling.A, A.Assoc == interface_type_mangling.X, B.Assoc == interface_type_mangling.Y>\(A, y: B\) -> \(\)]]
+// CHECK:                                 [[M_SIGNATURE:<A, B where A: interface_type_mangling.A, B: interface_type_mangling.A, A.Assoc == interface_type_mangling.X, B.Assoc == interface_type_mangling.Y>\(_: A, y: B\) -> \(\)]]
 func m1<T: A, U: A where T.Assoc == X, U.Assoc == Y>(_ x: T, y: U) {}
 // CHECK:       interface_type_mangling.m2[[M_SIGNATURE]]
 func m2<T: A, U: A where U.Assoc == Y, T.Assoc == X>(_ x: T, y: U) {}
@@ -194,7 +194,7 @@
   typealias Tee = T
 
   var a: T
-  // CHECK-LABEL: sil private @_T023interface_type_mangling18GenericTypeContextV09closureIndF0yqd__lF3fooL_yx_qd__tr__lF
+  // CHECK-LABEL: sil private @_T023interface_type_mangling18GenericTypeContextV09closureIndF0yyqd__lF3fooL_yyx_qd__tr__lF
   func closureInGenericContext<U>(_ b: U) {
     func foo(_ x: T, _ y: U) { }
 
@@ -209,16 +209,16 @@
   }
 
   // FIXME: Demangling for generic params at depth is wrong.
-  // CHECK-LABEL: twoParamsAtDepth<A, B>(A1, y: B1) -> ()
-  // CHECK-LABEL: sil hidden @_T023interface_type_mangling18GenericTypeContextV16twoParamsAtDepthyqd___qd_0_1ytr0_lF
+  // CHECK-LABEL: twoParamsAtDepth<A, B>(_: A1, y: B1) -> ()
+  // CHECK-LABEL: sil hidden @_T023interface_type_mangling18GenericTypeContextV16twoParamsAtDepth_1yyqd___qd_0_tr0_lF
   func twoParamsAtDepth<A, B>(_ x: A, y: B) {}
 }
 
 // CHECK-LABEL: protocol witness for interface_type_mangling.GenericWitnessTest.closureInGenericContext<A>(A1) -> () in conformance interface_type_mangling.GenericTypeContext<A> : interface_type_mangling.GenericWitnessTest in interface_type_mangling
-// CHECK-LABEL: @_T023interface_type_mangling18GenericTypeContextVyxGAA0D11WitnessTestA2aEP09closureIndF0yqd__lFTW
+// CHECK-LABEL: @_T023interface_type_mangling18GenericTypeContextVyxGAA0D11WitnessTestA2aEP09closureIndF0yyqd__lFTW
 
 // CHECK-LABEL: protocol witness for interface_type_mangling.GenericWitnessTest.closureInGenericPropertyContext.getter : A.Tee in conformance interface_type_mangling.GenericTypeContext<A> : interface_type_mangling.GenericWitnessTest in interface_type_mangling
 // CHECK-LABEL: @_T023interface_type_mangling18GenericTypeContextVyxGAA0D11WitnessTestA2aEP09closureInd8PropertyF03TeeQzvgTW
 
-// CHECK-LABEL: protocol witness for interface_type_mangling.GenericWitnessTest.twoParamsAtDepth<A, B>(A1, y: B1) -> () in conformance interface_type_mangling.GenericTypeContext<A> : interface_type_mangling.GenericWitnessTest in interface_type_mangling
-// CHECK-LABEL: @_T023interface_type_mangling18GenericTypeContextVyxGAA0D11WitnessTestA2aEP16twoParamsAtDepthyqd___qd_0_1ytr0_lFTW
+// CHECK-LABEL: protocol witness for interface_type_mangling.GenericWitnessTest.twoParamsAtDepth<A, B>(_: A1, y: B1) -> () in conformance interface_type_mangling.GenericTypeContext<A> : interface_type_mangling.GenericWitnessTest in interface_type_mangling
+// CHECK-LABEL: @_T023interface_type_mangling18GenericTypeContextVyxGAA0D11WitnessTestA2aEP16twoParamsAtDepth_1yyqd___qd_0_tr0_lFTW
diff --git a/test/SILGen/keypaths_objc.swift b/test/SILGen/keypaths_objc.swift
index 90b29fc..c6d027f 100644
--- a/test/SILGen/keypaths_objc.swift
+++ b/test/SILGen/keypaths_objc.swift
@@ -76,3 +76,15 @@
   _ = \NSObject.dynamic
 
 }
+
+@objc protocol ObjCProto {
+  var objcRequirement: Int { get set }
+}
+
+// CHECK-LABEL: sil hidden @{{.*}}ProtocolRequirement
+func objcProtocolRequirement<T: ObjCProto>(_: T) {
+  // CHECK: keypath {{.*}} id #ObjCProto.objcRequirement!getter.1.foreign
+  _ = \T.objcRequirement
+  // CHECK: keypath {{.*}} id #ObjCProto.objcRequirement!getter.1.foreign
+  _ = \ObjCProto.objcRequirement
+}
diff --git a/test/SILGen/lazy_properties.swift b/test/SILGen/lazy_properties.swift
index f6b362b..acf4642 100644
--- a/test/SILGen/lazy_properties.swift
+++ b/test/SILGen/lazy_properties.swift
@@ -8,7 +8,7 @@
 
 // CHECK-LABEL: sil hidden [transparent] @_T015lazy_properties19StructWithLazyFieldV4onceSivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout StructWithLazyField) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
 
-// CHECK-LABEL: sil hidden @_T015lazy_properties19StructWithLazyFieldVACSiSg4once_tcfC : $@convention(method) (Optional<Int>, @thin StructWithLazyField.Type) -> @owned StructWithLazyField
+// CHECK-LABEL: sil hidden @_T015lazy_properties19StructWithLazyFieldV4onceACSiSg_tcfC : $@convention(method) (Optional<Int>, @thin StructWithLazyField.Type) -> @owned StructWithLazyField
 
 struct StructWithLazyField {
   lazy var once : Int = 42
diff --git a/test/SILGen/lifetime.swift b/test/SILGen/lifetime.swift
index 8f13ad0..5a05513 100644
--- a/test/SILGen/lifetime.swift
+++ b/test/SILGen/lifetime.swift
@@ -129,7 +129,7 @@
     // CHECK: return [[RET]]
 }
 
-// CHECK-LABEL: sil hidden @_T08lifetime11reftype_argyAA3RefCF : $@convention(thin) (@owned Ref) -> () {
+// CHECK-LABEL: sil hidden @_T08lifetime11reftype_argyyAA3RefCF : $@convention(thin) (@owned Ref) -> () {
 // CHECK: bb0([[A:%[0-9]+]] : $Ref):
 // CHECK:   [[AADDR:%[0-9]+]] = alloc_box ${ var Ref }
 // CHECK:   [[PA:%[0-9]+]] = project_box [[AADDR]]
@@ -140,7 +140,7 @@
 // CHECK:   destroy_value [[AADDR]]
 // CHECK:   destroy_value [[A]]
 // CHECK:   return
-// CHECK: } // end sil function '_T08lifetime11reftype_argyAA3RefCF'
+// CHECK: } // end sil function '_T08lifetime11reftype_argyyAA3RefCF'
 func reftype_arg(_ a: Ref) {
     var a = a
 }
@@ -354,7 +354,7 @@
   var aleph_prop: Aleph { get {} set {} }
 }
 
-// CHECK-LABEL: sil hidden @_T08lifetime015logical_lvalue_A0yAA11RefWithPropC_SiAA3ValVtF : $@convention(thin) (@owned RefWithProp, Int, Val) -> () {
+// CHECK-LABEL: sil hidden @_T08lifetime015logical_lvalue_A0yyAA11RefWithPropC_SiAA3ValVtF : $@convention(thin) (@owned RefWithProp, Int, Val) -> () {
 func logical_lvalue_lifetime(_ r: RefWithProp, _ i: Int, _ v: Val) {
   var r = r
   var i = i
@@ -483,7 +483,7 @@
     // CHECK: return [[INIT_THIS]]
 
   // -- initializing entry point
-  // CHECK-LABEL: sil hidden @_T08lifetime3FooCACyxGSi3chi_tcfc : $@convention(method) <T> (Int, @owned Foo<T>) -> @owned Foo<T> {
+  // CHECK-LABEL: sil hidden @_T08lifetime3FooC3chiACyxGSi_tcfc : $@convention(method) <T> (Int, @owned Foo<T>) -> @owned Foo<T> {
     // CHECK: bb0([[CHI:%[0-9]+]] : $Int, [[THISIN:%[0-9]+]] : $Foo<T>):
     // CHECK:   [[THIS:%[0-9]+]] = mark_uninitialized [rootself] [[THISIN]]
 
@@ -526,7 +526,7 @@
     // CHECK: [[THIS_RETURN:%.*]] = copy_value [[THIS]]
     // CHECK: destroy_value [[THIS]]
     // CHECK: return [[THIS_RETURN]]
-  // CHECK: } // end sil function '_T08lifetime3FooCACyxGSi3chi_tcfc'
+  // CHECK: } // end sil function '_T08lifetime3FooC3chiACyxGSi_tcfc'
   }
 
   // -- allocating entry point
@@ -725,7 +725,7 @@
 
 class B { init(y:Int) {} }
 class D : B {
-  // CHECK-LABEL: sil hidden @_T08lifetime1DCACSi1x_Si1ytcfc
+  // CHECK-LABEL: sil hidden @_T08lifetime1DC1x1yACSi_Sitcfc
   // CHECK: bb0([[X:%[0-9]+]] : $Int, [[Y:%[0-9]+]] : $Int, [[SELF:%[0-9]+]] : $D):
   init(x: Int, y: Int) {
     var x = x
@@ -746,7 +746,7 @@
     // CHECK: [[THIS1_SUP:%[0-9]+]] = upcast [[THIS1]] : ${{.*}} to $B
     // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PY]]
     // CHECK: [[Y:%[0-9]+]] = load [trivial] [[READ]]
-    // CHECK: [[SUPER_CTOR:%[0-9]+]] = function_ref @_T08lifetime1BCACSi1y_tcfc : $@convention(method) (Int, @owned B) -> @owned B
+    // CHECK: [[SUPER_CTOR:%[0-9]+]] = function_ref @_T08lifetime1BC1yACSi_tcfc : $@convention(method) (Int, @owned B) -> @owned B
     // CHECK: [[THIS2_SUP:%[0-9]+]] = apply [[SUPER_CTOR]]([[Y]], [[THIS1_SUP]])
     // CHECK: [[THIS2:%[0-9]+]] = unchecked_ref_cast [[THIS2_SUP]] : $B to $D
     // CHECK: [[THIS1:%[0-9]+]] = load [copy] [[PB_BOX]]
diff --git a/test/SILGen/local_recursion.swift b/test/SILGen/local_recursion.swift
index de12c30..6b4d2c1 100644
--- a/test/SILGen/local_recursion.swift
+++ b/test/SILGen/local_recursion.swift
@@ -1,7 +1,7 @@
 // RUN: %target-swift-frontend  -parse-as-library -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 // RUN: %target-swift-frontend -enable-astscope-lookup  -parse-as-library -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
-// CHECK-LABEL: sil hidden @_T015local_recursionAAySi_Si1ytF : $@convention(thin) (Int, Int) -> () {
+// CHECK-LABEL: sil hidden @_T015local_recursionAA_1yySi_SitF : $@convention(thin) (Int, Int) -> () {
 // CHECK:       bb0([[X:%0]] : @trivial $Int, [[Y:%1]] : @trivial $Int):
 func local_recursion(_ x: Int, y: Int) {
   func self_recursive(_ a: Int) {
@@ -9,7 +9,7 @@
   }
 
   // Invoke local functions by passing all their captures.
-  // CHECK: [[SELF_RECURSIVE_REF:%.*]] = function_ref [[SELF_RECURSIVE:@_T015local_recursionAAySi_Si1ytF14self_recursiveL_ySiF]]
+  // CHECK: [[SELF_RECURSIVE_REF:%.*]] = function_ref [[SELF_RECURSIVE:@_T015local_recursionAA_1yySi_SitF14self_recursiveL_yySiF]]
   // CHECK: apply [[SELF_RECURSIVE_REF]]([[X]], [[X]])
   self_recursive(x)
 
@@ -32,7 +32,7 @@
     mutually_recursive_1(y + b)
   }
 
-  // CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1:@_T015local_recursionAAySi_Si1ytF20mutually_recursive_1L_ySiF]]
+  // CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1:@_T015local_recursionAA_1yySi_SitF20mutually_recursive_1L_yySiF]]
   // CHECK: apply [[MUTUALLY_RECURSIVE_REF]]([[X]], [[Y]], [[X]])
   mutually_recursive_1(x)
 
@@ -46,7 +46,7 @@
     return transitive_capture_1(y + b)
   }
 
-  // CHECK: [[TRANS_CAPTURE_REF:%.*]] = function_ref [[TRANS_CAPTURE:@_T015local_recursionAAySi_Si1ytF20transitive_capture_2L_S2iF]]
+  // CHECK: [[TRANS_CAPTURE_REF:%.*]] = function_ref [[TRANS_CAPTURE:@_T015local_recursionAA_1yySi_SitF20transitive_capture_2L_yS2iF]]
   // CHECK: apply [[TRANS_CAPTURE_REF]]([[X]], [[X]], [[Y]])
   transitive_capture_2(x)
 
@@ -62,14 +62,14 @@
   // CHECK: end_borrow [[BORROWED_CLOSURE]] from [[CLOSURE]]
   tc(x)
 
-  // CHECK: [[CLOSURE_REF:%.*]] = function_ref @_T015local_recursionAAySi_Si1ytFySicfU_
+  // CHECK: [[CLOSURE_REF:%.*]] = function_ref @_T015local_recursionAA_1yySi_SitFySicfU_
   // CHECK: apply [[CLOSURE_REF]]([[X]], [[X]], [[Y]])
   let _: Void = {
     self_recursive($0)
     transitive_capture_2($0)
   }(x)
 
-  // CHECK: [[CLOSURE_REF:%.*]] = function_ref @_T015local_recursionAAySi_Si1ytFySicfU0_
+  // CHECK: [[CLOSURE_REF:%.*]] = function_ref @_T015local_recursionAA_1yySi_SitFySicfU0_
   // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[CLOSURE_REF]]([[X]], [[Y]])
   // CHECK: [[BORROWED_CLOSURE:%.*]] = begin_borrow [[CLOSURE]]
   // CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_CLOSURE]]
@@ -92,7 +92,7 @@
 
 // CHECK: sil private [[MUTUALLY_RECURSIVE_1]]
 // CHECK: bb0([[A:%0]] : @trivial $Int, [[Y:%1]] : @trivial $Int, [[X:%2]] : @trivial $Int):
-// CHECK:   [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_2:@_T015local_recursionAAySi_Si1ytF20mutually_recursive_2L_ySiF]]
+// CHECK:   [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_2:@_T015local_recursionAA_1yySi_SitF20mutually_recursive_2L_yySiF]]
 // CHECK:   apply [[MUTUALLY_RECURSIVE_REF]]({{.*}}, [[X]], [[Y]])
 // CHECK: sil private [[MUTUALLY_RECURSIVE_2]]
 // CHECK: bb0([[B:%0]] : @trivial $Int, [[X:%1]] : @trivial $Int, [[Y:%2]] : @trivial $Int):
@@ -100,7 +100,7 @@
 // CHECK:   apply [[MUTUALLY_RECURSIVE_REF]]({{.*}}, [[Y]], [[X]])
 
 
-// CHECK: sil private [[TRANS_CAPTURE_1:@_T015local_recursionAAySi_Si1ytF20transitive_capture_1L_S2iF]]
+// CHECK: sil private [[TRANS_CAPTURE_1:@_T015local_recursionAA_1yySi_SitF20transitive_capture_1L_yS2iF]]
 // CHECK: bb0([[A:%0]] : @trivial $Int, [[X:%1]] : @trivial $Int):
 
 // CHECK: sil private [[TRANS_CAPTURE]]
diff --git a/test/SILGen/mangling.swift b/test/SILGen/mangling.swift
index e38fdc8..848050c 100644
--- a/test/SILGen/mangling.swift
+++ b/test/SILGen/mangling.swift
@@ -20,9 +20,9 @@
 // <rdar://problem/13757744> Variadic tuples need a different mangling from
 // non-variadic tuples.
 
-// CHECK-LABEL: sil hidden @_T08mangling9r13757744ySaySiG1x_tF
+// CHECK-LABEL: sil hidden @_T08mangling9r137577441xySaySiG_tF
 func r13757744(x: [Int]) {}
-// CHECK-LABEL: sil hidden @_T08mangling9r13757744ySi1xd_tF
+// CHECK-LABEL: sil hidden @_T08mangling9r137577441xySid_tF
 func r13757744(x: Int...) {}
 
 // <rdar://problem/13757750> Prefix, postfix, and infix operators need
@@ -32,65 +32,65 @@
 postfix operator +-
 infix operator +-
 
-// CHECK-LABEL: sil hidden @_T08mangling2psopyxlF
+// CHECK-LABEL: sil hidden @_T08mangling2psopyyxlF
 prefix func +- <T>(a: T) {}
-// CHECK-LABEL: sil hidden @_T08mangling2psoPyxlF
+// CHECK-LABEL: sil hidden @_T08mangling2psoPyyxlF
 postfix func +- <T>(a: T) {}
 
-// CHECK-LABEL: sil hidden @_T08mangling2psoiyx_xtlF
+// CHECK-LABEL: sil hidden @_T08mangling2psoiyyx_xtlF
 func +- <T>(a: T, b: T) {}
 
-// CHECK-LABEL: sil hidden @_T08mangling2psopyx1a_x1bt_tlF
+// CHECK-LABEL: sil hidden @_T08mangling2psopyyx1a_x1bt_tlF
 prefix func +- <T>(_: (a: T, b: T)) {}
-// CHECK-LABEL: sil hidden @_T08mangling2psoPyx1a_x1bt_tlF
+// CHECK-LABEL: sil hidden @_T08mangling2psoPyyx1a_x1bt_tlF
 postfix func +- <T>(_: (a: T, b: T)) {}
 
 infix operator «+» {}
 
-// CHECK-LABEL: sil hidden @_T08mangling007p_qcaDcoiS2i_SitF
+// CHECK-LABEL: sil hidden @_T08mangling007p_qcaDcoiyS2i_SitF
 func «+»(a: Int, b: Int) -> Int { return a + b }
 
 protocol Foo {}
 protocol Bar {}
 
 // Ensure protocol list manglings are '_' terminated regardless of length
-// CHECK-LABEL: sil hidden @_T08mangling12any_protocolyypF
+// CHECK-LABEL: sil hidden @_T08mangling12any_protocolyyypF
 func any_protocol(_: Any) {}
-// CHECK-LABEL: sil hidden @_T08mangling12one_protocolyAA3Foo_pF
+// CHECK-LABEL: sil hidden @_T08mangling12one_protocolyyAA3Foo_pF
 func one_protocol(_: Foo) {}
-// CHECK-LABEL: sil hidden @_T08mangling18one_protocol_twiceyAA3Foo_p_AaC_ptF
+// CHECK-LABEL: sil hidden @_T08mangling18one_protocol_twiceyyAA3Foo_p_AaC_ptF
 func one_protocol_twice(_: Foo, _: Foo) {}
-// CHECK-LABEL: sil hidden @_T08mangling12two_protocolyAA3Bar_AA3FoopF
+// CHECK-LABEL: sil hidden @_T08mangling12two_protocolyyAA3Bar_AA3FoopF
 func two_protocol(_: Foo & Bar) {}
 
 // Ensure archetype depths are mangled correctly.
 class Zim<T> {
-  // CHECK-LABEL: sil hidden @_T08mangling3ZimC4zangyx_qd__tlF
+  // CHECK-LABEL: sil hidden @_T08mangling3ZimC4zangyyx_qd__tlF
   func zang<U>(_: T, _: U) {}
-  // CHECK-LABEL: sil hidden @_T08mangling3ZimC4zungyqd___xtlF
+  // CHECK-LABEL: sil hidden @_T08mangling3ZimC4zungyyqd___xtlF
   func zung<U>(_: U, _: T) {}
 }
 
 // Don't crash mangling single-protocol "composition" types.
-// CHECK-LABEL: sil hidden @_T08mangling27single_protocol_compositionyAA3Foo_p1x_tF
+// CHECK-LABEL: sil hidden @_T08mangling27single_protocol_composition1xyAA3Foo_p_tF
 func single_protocol_composition(x: protocol<Foo>) {} // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}}
 
 // Clang-imported classes and protocols get mangled into a magic 'So' context
 // to make collisions into link errors. <rdar://problem/14221244>
-// CHECK-LABEL: sil hidden @_T08mangling28uses_objc_class_and_protocolySo8NSObjectC1o_So8NSAnsing_p1ptF
+// CHECK-LABEL: sil hidden @_T08mangling28uses_objc_class_and_protocol1o1pySo8NSObjectC_So8NSAnsing_ptF
 func uses_objc_class_and_protocol(o: NSObject, p: NSAnsing) {}
 
 // Clang-imported structs get mangled using their Clang module name.
 // FIXME: Temporarily mangles everything into the virtual module __C__
 // <rdar://problem/14221244>
-// CHECK-LABEL: sil hidden @_T08mangling17uses_clang_structySC6NSRectV1r_tF
+// CHECK-LABEL: sil hidden @_T08mangling17uses_clang_struct1rySC6NSRectV_tF
 func uses_clang_struct(r: NSRect) {}
 
-// CHECK-LABEL: sil hidden @_T08mangling14uses_optionalss7UnicodeO6ScalarVSgSiSg1x_tF
+// CHECK-LABEL: sil hidden @_T08mangling14uses_optionals1xs7UnicodeO6ScalarVSgSiSg_tF
 func uses_optionals(x: Int?) -> UnicodeScalar? { return nil }
 
 enum GenericUnion<T> {
-  // CHECK-LABEL: sil shared [transparent] @_T08mangling12GenericUnionO3FooACyxGSicAEmlF
+  // CHECK-LABEL: sil shared [transparent] @_T08mangling12GenericUnionO3FooyACyxGSicAEmlF
   case Foo(Int)
 }
 
@@ -107,16 +107,16 @@
 // auto_closures should not collide with the equivalent non-auto_closure
 // function type.
 
-// CHECK-LABEL: sil hidden @_T08mangling19autoClosureOverloadySiyXK1f_tF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> Int) -> () {
+// CHECK-LABEL: sil hidden @_T08mangling19autoClosureOverload1fySiyXK_tF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> Int) -> () {
 func autoClosureOverload(f: @autoclosure () -> Int) {}
-// CHECK-LABEL: sil hidden @_T08mangling19autoClosureOverloadySiyc1f_tF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> Int) -> () {
+// CHECK-LABEL: sil hidden @_T08mangling19autoClosureOverload1fySiyc_tF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> Int) -> () {
 func autoClosureOverload(f: () -> Int) {}
 
 // CHECK-LABEL: sil hidden @_T08mangling24autoClosureOverloadCallsyyF : $@convention(thin) () -> () {
 func autoClosureOverloadCalls() {
-  // CHECK: function_ref @_T08mangling19autoClosureOverloadySiyXK1f_tF
+  // CHECK: function_ref @_T08mangling19autoClosureOverload1fySiyXK_tF
   autoClosureOverload(f: 1)
-  // CHECK: function_ref @_T08mangling19autoClosureOverloadySiyc1f_tF
+  // CHECK: function_ref @_T08mangling19autoClosureOverload1fySiyc_tF
   autoClosureOverload {1}
 }
 
@@ -129,12 +129,12 @@
   associatedtype Assoc
 }
 
-// CHECK-LABEL: sil hidden @_T08mangling4fooAyxAA12HasAssocTypeRzlF : $@convention(thin) <T where T : HasAssocType> (@in T) -> ()
+// CHECK-LABEL: sil hidden @_T08mangling4fooAyyxAA12HasAssocTypeRzlF : $@convention(thin) <T where T : HasAssocType> (@in T) -> ()
 func fooA<T: HasAssocType>(_: T) {}
-// CHECK-LABEL: sil hidden @_T08mangling4fooByxAA12HasAssocTypeRzAA0D4Reqt0D0RpzlF : $@convention(thin) <T where T : HasAssocType, T.Assoc : AssocReqt> (@in T) -> ()
+// CHECK-LABEL: sil hidden @_T08mangling4fooByyxAA12HasAssocTypeRzAA0D4Reqt0D0RpzlF : $@convention(thin) <T where T : HasAssocType, T.Assoc : AssocReqt> (@in T) -> ()
 func fooB<T: HasAssocType>(_: T) where T.Assoc: AssocReqt {}
 
-// CHECK-LABEL: sil hidden @_T08mangling2qqoiySi_SitF
+// CHECK-LABEL: sil hidden @_T08mangling2qqoiyySi_SitF
 func ??(x: Int, y: Int) {}
 
 struct InstanceAndClassProperty {
@@ -180,11 +180,11 @@
   return curry1Throws
 }
 
-// CHECK-LABEL: sil hidden @_T08mangling14varargsVsArrayySi3arrd_SS1ntF : $@convention(thin) (@owned Array<Int>, @owned String) -> ()
+// CHECK-LABEL: sil hidden @_T08mangling14varargsVsArray3arr1nySid_SStF : $@convention(thin) (@owned Array<Int>, @owned String) -> ()
 func varargsVsArray(arr: Int..., n: String) { }
 
-// CHECK-LABEL: sil hidden @_T08mangling14varargsVsArrayySaySiG3arr_SS1ntF : $@convention(thin) (@owned Array<Int>, @owned String) -> ()
+// CHECK-LABEL: sil hidden @_T08mangling14varargsVsArray3arr1nySaySiG_SStF : $@convention(thin) (@owned Array<Int>, @owned String) -> ()
 func varargsVsArray(arr: [Int], n: String) { }
 
-// CHECK-LABEL: sil hidden @_T08mangling14varargsVsArrayySaySiG3arrd_SS1ntF : $@convention(thin) (@owned Array<Array<Int>>, @owned String) -> ()
+// CHECK-LABEL: sil hidden @_T08mangling14varargsVsArray3arr1nySaySiGd_SStF : $@convention(thin) (@owned Array<Array<Int>>, @owned String) -> ()
 func varargsVsArray(arr: [Int]..., n: String) { }
diff --git a/test/SILGen/mangling_generic_extensions.swift b/test/SILGen/mangling_generic_extensions.swift
index 5e6dcb9..c3ce757 100644
--- a/test/SILGen/mangling_generic_extensions.swift
+++ b/test/SILGen/mangling_generic_extensions.swift
@@ -18,9 +18,9 @@
 
   // NO-SELF-LABEL: sil hidden @_T027mangling_generic_extensions3FooV3zimyyF
   func zim() { }
-  // NO-SELF-LABEL: sil hidden @_T027mangling_generic_extensions3FooV4zangyqd__lF
+  // NO-SELF-LABEL: sil hidden @_T027mangling_generic_extensions3FooV4zangyyqd__lF
   func zang<U>(_: U) { }
-  // NO-SELF-LABEL: sil hidden @_T027mangling_generic_extensions3FooV4zungyqd__AA8RuncibleRd__3HatQyd__Rs_lF
+  // NO-SELF-LABEL: sil hidden @_T027mangling_generic_extensions3FooV4zungyyqd__AA8RuncibleRd__3HatQyd__Rs_lF
   func zung<U: Runcible>(_: U) where U.Hat == T { }
 }
 
@@ -61,9 +61,9 @@
 struct Bar<T: Runcible, U: Runcible> { }
 
 extension Bar {
-  // CHECK-LABEL: _T027mangling_generic_extensions3BarV4bar1yqd__AA8RuncibleRd__AaE5SpoonRpzAFQy_AGRSlF
+  // CHECK-LABEL: _T027mangling_generic_extensions3BarV4bar1yyqd__AA8RuncibleRd__AaE5SpoonRpzAFQy_AGRSlF
   func bar1<V: Runcible>(_: V) where U.Spoon: Runcible, T.Spoon == U.Spoon { }
 
-  // CHECK-LABEL: _T027mangling_generic_extensions3BarV4bar1yqd__AA8RuncibleRd__AaE5SpoonRp_lF
+  // CHECK-LABEL: _T027mangling_generic_extensions3BarV4bar1yyqd__AA8RuncibleRd__AaE5SpoonRp_lF
   func bar1<V: Runcible>(_: V) where U.Spoon: Runcible { }
 }
diff --git a/test/SILGen/mangling_private.swift b/test/SILGen/mangling_private.swift
index a8443eb..fc6a440 100644
--- a/test/SILGen/mangling_private.swift
+++ b/test/SILGen/mangling_private.swift
@@ -22,7 +22,7 @@
   // CHECK-LABEL: sil private @_T016mangling_private12PublicStructV0B6Method33_A3CCBB841DB59E79A4AD4EE458655068LLyyFZ
   private static func privateMethod() {}
 
-  // CHECK-LABEL: sil private @_T016mangling_private12PublicStructVACSi1x_tc33_A3CCBB841DB59E79A4AD4EE458655068LlfC
+  // CHECK-LABEL: sil private @_T016mangling_private12PublicStructV1xACSi_tc33_A3CCBB841DB59E79A4AD4EE458655068LlfC
   private init(x: Int) {}
 }
 
@@ -30,7 +30,7 @@
   // CHECK-LABEL: sil private @_T016mangling_private14InternalStructV0B6Method33_A3CCBB841DB59E79A4AD4EE458655068LLyyFZ
   private static func privateMethod() {}
 
-  // CHECK-LABEL: sil private @_T016mangling_private14InternalStructVACSi1x_tc33_A3CCBB841DB59E79A4AD4EE458655068LlfC
+  // CHECK-LABEL: sil private @_T016mangling_private14InternalStructV1xACSi_tc33_A3CCBB841DB59E79A4AD4EE458655068LlfC
   private init(x: Int) {}
 }
 
@@ -38,14 +38,14 @@
   // CHECK-LABEL: sil private @_T016mangling_private13PrivateStruct33_A3CCBB841DB59E79A4AD4EE458655068LLV0B6MethodyyFZ
   private static func privateMethod() {}
 
-  // CHECK-LABEL: sil private @_T016mangling_private13PrivateStruct33_A3CCBB841DB59E79A4AD4EE458655068LLVADSi1x_tcfC
+  // CHECK-LABEL: sil private @_T016mangling_private13PrivateStruct33_A3CCBB841DB59E79A4AD4EE458655068LLV1xADSi_tcfC
   private init(x: Int) {}
 
   struct Inner {
     // CHECK-LABEL: sil private @_T016mangling_private13PrivateStruct33_A3CCBB841DB59E79A4AD4EE458655068LLV5InnerV0B6MethodyyFZ
     private static func privateMethod() {}
 
-    // CHECK-LABEL: sil private @_T016mangling_private13PrivateStruct33_A3CCBB841DB59E79A4AD4EE458655068LLV5InnerVAFSi1x_tcfC
+    // CHECK-LABEL: sil private @_T016mangling_private13PrivateStruct33_A3CCBB841DB59E79A4AD4EE458655068LLV5InnerV1xAFSi_tcfC
     private init(x: Int) {}
   }
 }
@@ -60,14 +60,14 @@
   // CHECK-LABEL: sil private @_T016mangling_private12PublicStructV16extPrivateMethod33_A3CCBB841DB59E79A4AD4EE458655068LLyyF
   private func extPrivateMethod() {}
 
-  // CHECK-LABEL: sil private @_T016mangling_private12PublicStructVACSi3ext_tc33_A3CCBB841DB59E79A4AD4EE458655068LlfC
+  // CHECK-LABEL: sil private @_T016mangling_private12PublicStructV3extACSi_tc33_A3CCBB841DB59E79A4AD4EE458655068LlfC
   private init(ext: Int) {}
 }
 extension PrivateStruct {
   // CHECK-LABEL: sil private @_T016mangling_private13PrivateStruct33_A3CCBB841DB59E79A4AD4EE458655068LLV03extC6MethodyyF
   private func extPrivateMethod() {}
 
-  // CHECK-LABEL: sil private @_T016mangling_private13PrivateStruct33_A3CCBB841DB59E79A4AD4EE458655068LLVADSi3ext_tcfC
+  // CHECK-LABEL: sil private @_T016mangling_private13PrivateStruct33_A3CCBB841DB59E79A4AD4EE458655068LLV3extADSi_tcfC
   private init(ext: Int) {}
 }
 
diff --git a/test/SILGen/materializeForSet.swift b/test/SILGen/materializeForSet.swift
index 82584ad..ff3c3d6 100644
--- a/test/SILGen/materializeForSet.swift
+++ b/test/SILGen/materializeForSet.swift
@@ -363,7 +363,7 @@
 func improveWizard(_ wizard: inout Wizard) {
   improve(&wizard.hocus)
 }
-// CHECK-LABEL: sil hidden @_T017materializeForSet13improveWizardyAA0E0VzF
+// CHECK-LABEL: sil hidden @_T017materializeForSet13improveWizardyyAA0E0VzF
 // CHECK:       [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Wizard
 // CHECK-NEXT:  [[TEMP:%.*]] = alloc_stack $Int
 //   Call the getter and materialize the result in the temporary.
@@ -375,7 +375,7 @@
 // CHECK-NEXT:  dealloc_stack [[WTEMP]]
 // CHECK-NEXT:  store [[T0]] to [trivial] [[TEMP]]
 //   Call improve.
-// CHECK:       [[IMPROVE:%.*]] = function_ref @_T017materializeForSet7improveySizF :
+// CHECK:       [[IMPROVE:%.*]] = function_ref @_T017materializeForSet7improveyySizF :
 // CHECK-NEXT:  apply [[IMPROVE]]([[TEMP]])
 // CHECK-NEXT:  [[T0:%.*]] = load [trivial] [[TEMP]]
 // CHECK:       [[SETTER:%.*]] = function_ref @_T017materializeForSet5MagicPAAE5hocusSivs
@@ -433,26 +433,26 @@
   subscript<T>(_: T) -> T { get { } set { } }
 }
 
-// CHECK-LABEL: sil private [transparent] @_T017materializeForSet23GenericSubscriptWitnessVxxcluimytfU_ : $@convention(method) <T> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericSubscriptWitness, @thick GenericSubscriptWitness.Type) -> () {
+// CHECK-LABEL: sil private [transparent] @_T017materializeForSet23GenericSubscriptWitnessVyxxcluimytfU_ : $@convention(method) <T> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericSubscriptWitness, @thick GenericSubscriptWitness.Type) -> () {
 // CHECK:       bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*GenericSubscriptWitness, %3 : $@thick GenericSubscriptWitness.Type):
 // CHECK:         [[BUFFER:%.*]] = project_value_buffer $T in %1 : $*Builtin.UnsafeValueBuffer
 // CHECK-NEXT:    [[INDICES:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*T
-// CHECK:         [[SETTER:%.*]] = function_ref @_T017materializeForSet23GenericSubscriptWitnessVxxcluis : $@convention(method) <τ_0_0> (@in τ_0_0, @in τ_0_0, @inout GenericSubscriptWitness) -> ()
+// CHECK:         [[SETTER:%.*]] = function_ref @_T017materializeForSet23GenericSubscriptWitnessVyxxcluis : $@convention(method) <τ_0_0> (@in τ_0_0, @in τ_0_0, @inout GenericSubscriptWitness) -> ()
 // CHECK-NEXT:    apply [[SETTER]]<T>([[INDICES]], [[BUFFER]], %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @in τ_0_0, @inout GenericSubscriptWitness) -> ()
 // CHECK-NEXT:    dealloc_value_buffer $*T in %1 : $*Builtin.UnsafeValueBuffer
 // CHECK-NEXT:    [[RESULT:%.*]] = tuple ()
 // CHECK-NEXT:    return [[RESULT]] : $()
 
-// CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet23GenericSubscriptWitnessVxxcluim : $@convention(method) <T> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in T, @inout GenericSubscriptWitness) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
+// CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet23GenericSubscriptWitnessVyxxcluim : $@convention(method) <T> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in T, @inout GenericSubscriptWitness) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
 // CHECK:      bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*T, %3 : $*GenericSubscriptWitness):
 // CHECK-NEXT:   [[BUFFER:%.*]] = alloc_value_buffer $T in %1 : $*Builtin.UnsafeValueBuffer
 // CHECK-NEXT:   copy_addr %2 to [initialization] [[BUFFER]] : $*T
 // CHECK-NEXT:   [[VALUE:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*T
 // CHECK-NEXT:   [[SELF:%.*]] = load [trivial] %3 : $*GenericSubscriptWitness
-// CHECK:        [[GETTER:%.*]] = function_ref @_T017materializeForSet23GenericSubscriptWitnessVxxcluig : $@convention(method) <τ_0_0> (@in τ_0_0, GenericSubscriptWitness) -> @out τ_0_0
+// CHECK:        [[GETTER:%.*]] = function_ref @_T017materializeForSet23GenericSubscriptWitnessVyxxcluig : $@convention(method) <τ_0_0> (@in τ_0_0, GenericSubscriptWitness) -> @out τ_0_0
 // CHECK-NEXT:   apply [[GETTER]]<T>([[VALUE]], %2, [[SELF]]) : $@convention(method) <τ_0_0> (@in τ_0_0, GenericSubscriptWitness) -> @out τ_0_0
 // CHECK-NEXT:   [[VALUE_PTR:%.*]] = address_to_pointer [[VALUE]] : $*T to $Builtin.RawPointer
-// CHECK:        [[CALLBACK:%.*]] = function_ref @_T017materializeForSet23GenericSubscriptWitnessVxxcluimytfU_
+// CHECK:        [[CALLBACK:%.*]] = function_ref @_T017materializeForSet23GenericSubscriptWitnessVyxxcluimytfU_
 // CHECK-NEXT:   [[CALLBACK_PTR:%.*]] = thin_function_to_pointer [[CALLBACK]] : $@convention(method) <τ_0_0> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericSubscriptWitness, @thick GenericSubscriptWitness.Type) -> () to $Builtin.RawPointer
 // CHECK-NEXT:   [[CALLBACK_OPTIONAL:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_PTR]] : $Builtin.RawPointer
 // CHECK-NEXT:   [[RESULT:%.*]] = tuple ([[VALUE_PTR]] : $Builtin.RawPointer, [[CALLBACK_OPTIONAL]] : $Optional<Builtin.RawPointer>)
@@ -480,11 +480,11 @@
   }
 }
 
-// CHECK-LABEL: sil hidden @_T017materializeForSet30InferredRequirementOnSubscriptVAA015GenericTypeWithE0VyxGSicAA5MagicRzluig : $@convention(method) <T where T : Magic> (Int, InferredRequirementOnSubscript) -> GenericTypeWithRequirement<T>
+// CHECK-LABEL: sil hidden @_T017materializeForSet30InferredRequirementOnSubscriptVyAA015GenericTypeWithE0VyxGSicAA5MagicRzluig : $@convention(method) <T where T : Magic> (Int, InferredRequirementOnSubscript) -> GenericTypeWithRequirement<T>
 
-// CHECK-LABEL: sil hidden @_T017materializeForSet30InferredRequirementOnSubscriptVAA015GenericTypeWithE0VyxGSicAA5MagicRzluis : $@convention(method) <T where T : Magic> (GenericTypeWithRequirement<T>, Int, @inout InferredRequirementOnSubscript) -> ()
+// CHECK-LABEL: sil hidden @_T017materializeForSet30InferredRequirementOnSubscriptVyAA015GenericTypeWithE0VyxGSicAA5MagicRzluis : $@convention(method) <T where T : Magic> (GenericTypeWithRequirement<T>, Int, @inout InferredRequirementOnSubscript) -> ()
 
-// CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet30InferredRequirementOnSubscriptVAA015GenericTypeWithE0VyxGSicAA5MagicRzluim : $@convention(method) <T where T : Magic> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @inout InferredRequirementOnSubscript) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
+// CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet30InferredRequirementOnSubscriptVyAA015GenericTypeWithE0VyxGSicAA5MagicRzluim : $@convention(method) <T where T : Magic> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @inout InferredRequirementOnSubscript) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
 
 // Test for materializeForSet vs static properties of structs.
 
@@ -566,7 +566,7 @@
 
 struct TuxedoPanda : Panda { }
 
-// CHECK-LABEL: sil private [transparent] @_T017materializeForSet11TuxedoPandaVAA0E0A2aDP1xxxcvmytfU_TW : $@convention(witness_method: Panda) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout TuxedoPanda, @thick TuxedoPanda.Type) -> ()
+// CHECK-LABEL: sil private [transparent] @_T017materializeForSet11TuxedoPandaVAA0E0A2aDP1xyxxcvmytfU_TW : $@convention(witness_method: Panda) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout TuxedoPanda, @thick TuxedoPanda.Type) -> ()
 
   // FIXME: Useless re-abstractions
 
@@ -574,15 +574,15 @@
 
   // CHECK: function_ref @_T017materializeForSet11TuxedoPandaVACIegyd_A2CIegir_TR : $@convention(thin) (@in TuxedoPanda, @guaranteed @callee_guaranteed (TuxedoPanda) -> TuxedoPanda) -> @out TuxedoPanda
 
-  // CHECK: function_ref @_T017materializeForSet5PandaPAAE1xxxcvs : $@convention(method) <τ_0_0 where τ_0_0 : Panda> (@owned @callee_guaranteed (@in τ_0_0) -> @out τ_0_0, @inout τ_0_0) -> ()
+  // CHECK: function_ref @_T017materializeForSet5PandaPAAE1xyxxcvs : $@convention(method) <τ_0_0 where τ_0_0 : Panda> (@owned @callee_guaranteed (@in τ_0_0) -> @out τ_0_0, @inout τ_0_0) -> ()
 
 // CHECK: }
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T017materializeForSet11TuxedoPandaVAA0E0A2aDP1xxxcvmTW
+// CHECK-LABEL: sil private [transparent] [thunk] @_T017materializeForSet11TuxedoPandaVAA0E0A2aDP1xyxxcvmTW
 
 // Call the getter:
 
-  // CHECK: function_ref @_T017materializeForSet5PandaPAAE1xxxcvg : $@convention(method) <τ_0_0 where τ_0_0 : Panda> (@in_guaranteed τ_0_0) -> @owned @callee_guaranteed (@in τ_0_0) -> @out τ_0_0
+  // CHECK: function_ref @_T017materializeForSet5PandaPAAE1xyxxcvg : $@convention(method) <τ_0_0 where τ_0_0 : Panda> (@in_guaranteed τ_0_0) -> @owned @callee_guaranteed (@in τ_0_0) -> @out τ_0_0
 
 // Result of calling the getter is re-abstracted to the maximally substituted type
 // by SILGenFunction::emitApply():
@@ -597,7 +597,7 @@
 
 // The callback:
 
-  // CHECK: function_ref @_T017materializeForSet11TuxedoPandaVAA0E0A2aDP1xxxcvmytfU_TW : $@convention(witness_method: Panda) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout TuxedoPanda, @thick TuxedoPanda.Type) -> ()
+  // CHECK: function_ref @_T017materializeForSet11TuxedoPandaVAA0E0A2aDP1xyxxcvmytfU_TW : $@convention(witness_method: Panda) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout TuxedoPanda, @thick TuxedoPanda.Type) -> ()
 
 // CHECK: }
 
@@ -608,7 +608,7 @@
   lazy var cat: Int = 5
 }
 
-// CHECK-LABEL: sil hidden @_T017materializeForSet31inoutAccessOfLazyStructPropertyyAA0ghI0Vz1l_tF
+// CHECK-LABEL: sil hidden @_T017materializeForSet31inoutAccessOfLazyStructProperty1lyAA0ghI0Vz_tF
 // CHECK:   function_ref @_T017materializeForSet18LazyStructPropertyV3catSivg
 // CHECK:   function_ref @_T017materializeForSet18LazyStructPropertyV3catSivs
 func inoutAccessOfLazyStructProperty(l: inout LazyStructProperty) {
@@ -623,7 +623,7 @@
   lazy var cat: Int = 5
 }
 
-// CHECK-LABEL: sil hidden @_T017materializeForSet30inoutAccessOfLazyClassPropertyyAA0ghI0Cz1l_tF
+// CHECK-LABEL: sil hidden @_T017materializeForSet30inoutAccessOfLazyClassProperty1lyAA0ghI0Cz_tF
 // CHECK:    class_method {{.*}} : $LazyClassProperty, #LazyClassProperty.cat!materializeForSet.1
 func inoutAccessOfLazyClassProperty(l: inout LazyClassProperty) {
   increment(&l.cat)
@@ -635,7 +635,7 @@
   lazy var cat: Int = 5
 }
 
-// CHECK-LABEL: sil hidden @_T017materializeForSet35inoutAccessOfLazyFinalClassPropertyyAA0ghiJ0Cz1l_tF
+// CHECK-LABEL: sil hidden @_T017materializeForSet35inoutAccessOfLazyFinalClassProperty1lyAA0ghiJ0Cz_tF
 // CHECK:    function_ref @_T017materializeForSet22LazyFinalClassPropertyC3catSivg
 // CHECK:    function_ref @_T017materializeForSet22LazyFinalClassPropertyC3catSivs
 func inoutAccessOfLazyFinalClassProperty(l: inout LazyFinalClassProperty) {
diff --git a/test/SILGen/metatype_abstraction.swift b/test/SILGen/metatype_abstraction.swift
index f6f623b..dc18b13 100644
--- a/test/SILGen/metatype_abstraction.swift
+++ b/test/SILGen/metatype_abstraction.swift
@@ -51,7 +51,7 @@
   var x = x
   return x.value
 }
-// CHECK-LABEL: sil hidden @_T0s026dynamicMetatypeFromGenericB0s1CCms0dB0VyACGF
+// CHECK-LABEL: sil hidden @_T0s026dynamicMetatypeFromGenericB0ys1CCms0dB0VyACGF
 // CHECK:         [[XBOX:%[0-9]+]] = alloc_box ${ var GenericMetatype<C> }
 // CHECK:         [[PX:%[0-9]+]] = project_box [[XBOX]]
 // CHECK:         [[READ:%.*]] = begin_access [read] [unknown] [[PX]] : $*GenericMetatype<C>
@@ -88,7 +88,7 @@
   var x = x
   takeGeneric(x)
 }
-// CHECK-LABEL: sil hidden @_T0s024dynamicMetatypeToGenericB0ys1CCmF
+// CHECK-LABEL: sil hidden @_T0s024dynamicMetatypeToGenericB0yys1CCmF
 // CHECK:         [[XBOX:%[0-9]+]] = alloc_box ${ var @thick C.Type }
 // CHECK:         [[PX:%[0-9]+]] = project_box [[XBOX]]
 // CHECK:         [[READ:%.*]] = begin_access [read] [unknown] [[PX]] : $*@thick C.Type
@@ -109,13 +109,13 @@
   takeGenericMetatype(x)
 }
 
-// CHECK-LABEL: sil hidden @_T0s019static_metatype_of_B0s1SVmmACF
+// CHECK-LABEL: sil hidden @_T0s019static_metatype_of_B0ys1SVmmACF
 // CHECK:         metatype $@thin S.Type.Type
 func static_metatype_of_metatype(_ x: S) -> S.Type.Type {
   return type(of: type(of: x))
 }
 
-// CHECK-LABEL: sil hidden @_T0s018class_metatype_of_B0s1CCmmACF
+// CHECK-LABEL: sil hidden @_T0s018class_metatype_of_B0ys1CCmmACF
 // CHECK:         [[METATYPE:%.*]] = value_metatype $@thick C.Type
 // CHECK:         [[META_METATYPE:%.*]] = value_metatype $@thick C.Type.Type, [[METATYPE]]
 func class_metatype_of_metatype(_ x: C) -> C.Type.Type {
diff --git a/test/SILGen/metatype_object_conversion.swift b/test/SILGen/metatype_object_conversion.swift
index adb2b21..865464f 100644
--- a/test/SILGen/metatype_object_conversion.swift
+++ b/test/SILGen/metatype_object_conversion.swift
@@ -10,7 +10,7 @@
 
 @objc protocol OP {}
 
-// CHECK-LABEL: sil hidden @_T026metatype_object_conversion0A8ToObjectyXlAA1CCmF 
+// CHECK-LABEL: sil hidden @_T026metatype_object_conversion0A8ToObjectyyXlAA1CCmF
 func metatypeToObject(_ x: C.Type) -> AnyObject {
   // CHECK: bb0([[THICK:%.*]] : @trivial $@thick C.Type):
   // CHECK:   [[OBJC:%.*]] = thick_to_objc_metatype [[THICK]]
@@ -19,7 +19,7 @@
   return x
 }
 
-// CHECK-LABEL: sil hidden @_T026metatype_object_conversion27existentialMetatypeToObjectyXlAA2CP_pXpF
+// CHECK-LABEL: sil hidden @_T026metatype_object_conversion27existentialMetatypeToObjectyyXlAA2CP_pXpF
 func existentialMetatypeToObject(_ x: CP.Type) -> AnyObject {
   // CHECK: bb0([[THICK:%.*]] : @trivial $@thick CP.Type):
   // CHECK:   [[OBJC:%.*]] = thick_to_objc_metatype [[THICK]]
diff --git a/test/SILGen/multi_file.swift b/test/SILGen/multi_file.swift
index 70d7a5e..e606b90 100644
--- a/test/SILGen/multi_file.swift
+++ b/test/SILGen/multi_file.swift
@@ -24,7 +24,7 @@
   markUsed(container.lazyVar)
 }
 
-// CHECK-LABEL: sil hidden @_T010multi_file25finalVarsAreDevirtualizedyAA18FinalPropertyClassCF
+// CHECK-LABEL: sil hidden @_T010multi_file25finalVarsAreDevirtualizedyyAA18FinalPropertyClassCF
 func finalVarsAreDevirtualized(_ obj: FinalPropertyClass) {
   // CHECK: bb0([[ARG:%.*]] : @owned $FinalPropertyClass):
   // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
@@ -37,7 +37,7 @@
 }
 
 // rdar://18448869
-// CHECK-LABEL: sil hidden @_T010multi_file34finalVarsDontNeedMaterializeForSetyAA27ObservingPropertyFinalClassCF
+// CHECK-LABEL: sil hidden @_T010multi_file34finalVarsDontNeedMaterializeForSetyyAA27ObservingPropertyFinalClassCF
 func finalVarsDontNeedMaterializeForSet(_ obj: ObservingPropertyFinalClass) {
   obj.foo += 1
   // CHECK: function_ref @_T010multi_file27ObservingPropertyFinalClassC3fooSivg
diff --git a/test/SILGen/nested_generics.swift b/test/SILGen/nested_generics.swift
index 6524e88..f04ce15 100644
--- a/test/SILGen/nested_generics.swift
+++ b/test/SILGen/nested_generics.swift
@@ -41,13 +41,13 @@
 }
 
 // CHECK-LABEL: // nested_generics.Lunch.Dinner.coolCombination(t: A.Topping, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
-// CHECK-LABEL: sil hidden @_T015nested_generics5LunchV6DinnerV15coolCombinationy7ToppingQz1t_AA4DeliC7MustardOyAA6PepperV_G1utF : $@convention(method) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard> (@in T.Topping, Deli<Pepper>.Mustard, @in_guaranteed Lunch<T>.Dinner<U>) -> ()
+// CHECK-LABEL: sil hidden @_T015nested_generics5LunchV6DinnerV15coolCombination1t1uy7ToppingQz_AA4DeliC7MustardOyAA6PepperV_GtF : $@convention(method) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard> (@in T.Topping, Deli<Pepper>.Mustard, @in_guaranteed Lunch<T>.Dinner<U>) -> ()
 
 // CHECK-LABEL: // nestedGeneric #1 <A><A1><A2, B2 where A: nested_generics.Pizza, A1: nested_generics.HotDog, A.Topping: nested_generics.CuredMeat, A1.Condiment == nested_generics.Deli<nested_generics.Pepper>.Mustard>(x: A2, y: B2) -> (A2, B2) in nested_generics.Lunch.Dinner.coolCombination(t: A.Topping, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
-// CHECK-LABEL: sil private @_T015nested_generics5LunchV6DinnerV15coolCombinationy7ToppingQz1t_AA4DeliC7MustardOyAA6PepperV_G1utF0A7GenericL_qd0___qd0_0_tqd0__1x_qd0_0_1ytAA5PizzaRzAA6HotDogRd__AA9CuredMeatAHRQAP9CondimentRtd__r__0_lF : $@convention(thin) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard><X, Y> (@in X, @in Y) -> (@out X, @out Y)
+// CHECK-LABEL: sil private @_T015nested_generics5LunchV6DinnerV15coolCombination1t1uy7ToppingQz_AA4DeliC7MustardOyAA6PepperV_GtF0A7GenericL_1x1yqd0___qd0_0_tqd0___qd0_0_tAA5PizzaRzAA6HotDogRd__AA9CuredMeatAJRQAQ9CondimentRtd__r__0_lF : $@convention(thin) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard><X, Y> (@in X, @in Y) -> (@out X, @out Y)
 
 // CHECK-LABEL: // nested_generics.Lunch.Dinner.init(firstCourse: A, secondCourse: Swift.Optional<A1>, leftovers: A, transformation: (A) -> A1) -> nested_generics.Lunch<A>.Dinner<A1>
-// CHECK-LABEL: sil hidden @_T015nested_generics5LunchV6DinnerVAEyx_qd__Gx11firstCourse_qd__Sg06secondF0x9leftoversqd__xc14transformationtcfC : $@convention(method) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard> (@owned T, @in Optional<U>, @owned T, @owned @callee_guaranteed (@owned T) -> @out U, @thin Lunch<T>.Dinner<U>.Type) -> @out Lunch<T>.Dinner<U>
+// CHECK-LABEL: sil hidden @_T015nested_generics5LunchV6DinnerV11firstCourse06secondF09leftovers14transformationAEyx_qd__Gx_qd__Sgxqd__xctcfC : $@convention(method) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard> (@owned T, @in Optional<U>, @owned T, @owned @callee_guaranteed (@owned T) -> @out U, @thin Lunch<T>.Dinner<U>.Type) -> @out Lunch<T>.Dinner<U>
 
 // Non-generic nested inside generic
 
@@ -91,7 +91,7 @@
 extension String {
   func foo() {
     // CHECK-LABEL: // init(material: A) -> Cheese #1 in (extension in nested_generics):Swift.String.foo() -> ()<A> in Cheese #1 in (extension in nested_generics):Swift.String.foo() -> ()
-    // CHECK-LABEL: sil private @_T0SS15nested_genericsE3fooyyF6CheeseL_VADyxGx8material_tcfC
+    // CHECK-LABEL: sil private @_T0SS15nested_genericsE3fooyyF6CheeseL_V8materialADyxGx_tcfC
     struct Cheese<Milk> {
       let material: Milk
     }
@@ -103,7 +103,7 @@
 extension HotDogs {
   func applyRelish() {
     // CHECK-LABEL: // init(material: A) -> Relish #1 in nested_generics.HotDogs.applyRelish() -> ()<A> in Relish #1 in nested_generics.HotDogs.applyRelish() -> ()
-    // CHECK-LABEL: sil private @_T015nested_generics7HotDogsC11applyRelishyyF0F0L_VAFyxGx8material_tcfC
+    // CHECK-LABEL: sil private @_T015nested_generics7HotDogsC11applyRelishyyF0F0L_V8materialAFyxGx_tcfC
 
     struct Relish<Material> {
       let material: Material
@@ -116,7 +116,7 @@
 struct ChiliFlakes {}
 
 // CHECK-LABEL: // nested_generics.eatDinnerGeneric<A, B where A: nested_generics.Pizza, B: nested_generics.HotDog, A.Topping: nested_generics.CuredMeat, B.Condiment == nested_generics.Deli<nested_generics.Pepper>.Mustard>(d: inout nested_generics.Lunch<A>.Dinner<B>, t: A.Topping, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
-// CHECK-LABEL: sil hidden @_T015nested_generics16eatDinnerGenericyAA5LunchV0D0Vyx_q_Gz1d_7ToppingQz1tAA4DeliC7MustardOyAA6PepperV_G1utAA5PizzaRzAA6HotDogR_AA9CuredMeatAJRQAR9CondimentRt_r0_lF : $@convention(thin) <T, U where T : Pizza, U : HotDog, T.Topping : CuredMeat, U.Condiment == Deli<Pepper>.Mustard> (@inout Lunch<T>.Dinner<U>, @in T.Topping, Deli<Pepper>.Mustard) -> ()
+// CHECK-LABEL: sil hidden @_T015nested_generics16eatDinnerGeneric1d1t1uyAA5LunchV0D0Vyx_q_Gz_7ToppingQzAA4DeliC7MustardOyAA6PepperV_GtAA5PizzaRzAA6HotDogR_AA9CuredMeatALRQAS9CondimentRt_r0_lF : $@convention(thin) <T, U where T : Pizza, U : HotDog, T.Topping : CuredMeat, U.Condiment == Deli<Pepper>.Mustard> (@inout Lunch<T>.Dinner<U>, @in T.Topping, Deli<Pepper>.Mustard) -> ()
 
 func eatDinnerGeneric<T, U>(d: inout Lunch<T>.Dinner<U>, t: T.Topping, u: U.Condiment) {
   // Method call
@@ -135,7 +135,7 @@
 // Overloading concrete function with different bound generic arguments in parent type
 
 // CHECK-LABEL: // nested_generics.eatDinnerConcrete(d: inout nested_generics.Lunch<nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork>.Dinner<nested_generics.HotDogs.American>, t: nested_generics.Deli<nested_generics.ChiliFlakes>.Pepperoni, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
-// CHECK-LABEL: sil hidden @_T015nested_generics17eatDinnerConcreteyAA5LunchV0D0VyAA6PizzasV7NewYorkCyAA11ChiliFlakesV_G_AA7HotDogsC8AmericanVGz1d_AA4DeliC9PepperoniCyAL_G1tAU7MustardOyAA6PepperV_G1utF : $@convention(thin) (@inout Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDogs.American>, @owned Deli<ChiliFlakes>.Pepperoni, Deli<Pepper>.Mustard) -> ()
+// CHECK-LABEL: sil hidden @_T015nested_generics17eatDinnerConcrete1d1t1uyAA5LunchV0D0VyAA6PizzasV7NewYorkCyAA11ChiliFlakesV_G_AA7HotDogsC8AmericanVGz_AA4DeliC9PepperoniCyAO_GAW7MustardOyAA6PepperV_GtF : $@convention(thin) (@inout Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDogs.American>, @owned Deli<ChiliFlakes>.Pepperoni, Deli<Pepper>.Mustard) -> ()
 
 func eatDinnerConcrete(d: inout Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDogs.American>,
                        t: Deli<ChiliFlakes>.Pepperoni,
@@ -157,7 +157,7 @@
 // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T015nested_generics6PizzasV7NewYorkCyAA11ChiliFlakesV_GAA7HotDogsC8AmericanVIegxr_AhLIegxd_TR : $@convention(thin) (@owned Pizzas<ChiliFlakes>.NewYork, @guaranteed @callee_guaranteed (@owned Pizzas<ChiliFlakes>.NewYork) -> @out HotDogs.American) -> HotDogs.American
 
 // CHECK-LABEL: // nested_generics.eatDinnerConcrete(d: inout nested_generics.Lunch<nested_generics.Pizzas<nested_generics.Pepper>.NewYork>.Dinner<nested_generics.HotDogs.American>, t: nested_generics.Deli<nested_generics.Pepper>.Pepperoni, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
-// CHECK-LABEL: sil hidden @_T015nested_generics17eatDinnerConcreteyAA5LunchV0D0VyAA6PizzasV7NewYorkCyAA6PepperV_G_AA7HotDogsC8AmericanVGz1d_AA4DeliC9PepperoniCyAL_G1tAU7MustardOyAL_G1utF : $@convention(thin) (@inout Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>, @owned Deli<Pepper>.Pepperoni, Deli<Pepper>.Mustard) -> ()
+// CHECK-LABEL: sil hidden @_T015nested_generics17eatDinnerConcrete1d1t1uyAA5LunchV0D0VyAA6PizzasV7NewYorkCyAA6PepperV_G_AA7HotDogsC8AmericanVGz_AA4DeliC9PepperoniCyAO_GAW7MustardOyAO_GtF : $@convention(thin) (@inout Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>, @owned Deli<Pepper>.Pepperoni, Deli<Pepper>.Mustard) -> ()
 
 func eatDinnerConcrete(d: inout Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>,
                        t: Deli<Pepper>.Pepperoni,
@@ -225,7 +225,7 @@
 // CHECK-LABEL: // reabstraction thunk helper from @escaping @callee_guaranteed (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@unowned nested_generics.HotDogs.American) to @escaping @callee_guaranteed (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@out nested_generics.HotDogs.American)
 // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T015nested_generics6PizzasV7NewYorkCyAA6PepperV_GAA7HotDogsC8AmericanVIegxd_AhLIegxr_TR : $@convention(thin) (@owned Pizzas<Pepper>.NewYork, @guaranteed @callee_guaranteed (@owned Pizzas<Pepper>.NewYork) -> HotDogs.American) -> @out HotDogs.American
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T015nested_generics9OuterRingC05InnerD0Cyx_qd__GAA30ProtocolWithGenericRequirementA2aGP6method1TQz_1UQzqd__tAK1t_AM1uqd__1vtlFTW : $@convention(witness_method: ProtocolWithGenericRequirement) <τ_0_0><τ_1_0><τ_2_0> (@in τ_0_0, @in τ_1_0, @in τ_2_0, @in_guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0) {
+// CHECK-LABEL: sil private [transparent] [thunk] @_T015nested_generics9OuterRingC05InnerD0Cyx_qd__GAA30ProtocolWithGenericRequirementA2aGP6method1t1u1v1TQz_1UQzqd__tAN_APqd__tlFTW : $@convention(witness_method: ProtocolWithGenericRequirement) <τ_0_0><τ_1_0><τ_2_0> (@in τ_0_0, @in τ_1_0, @in τ_2_0, @in_guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0) {
 // CHECK: bb0([[T:%[0-9]+]] : @trivial $*τ_0_0, [[U:%[0-9]+]] : @trivial $*τ_1_0, [[V:%[0-9]+]] : @trivial $*τ_2_0, [[TOut:%[0-9]+]] : @trivial $*τ_0_0, [[UOut:%[0-9]+]] : @trivial $*τ_1_0, [[VOut:%[0-9]+]] : @trivial $*τ_2_0, [[SELF:%[0-9]+]] : @trivial $*OuterRing<τ_0_0>.InnerRing<τ_1_0>):
 // CHECK:   [[SELF_COPY_VAL:%[0-9]+]] = load_borrow [[SELF]] : $*OuterRing<τ_0_0>.InnerRing<τ_1_0>
 // CHECK:   [[METHOD:%[0-9]+]] = class_method [[SELF_COPY_VAL]] : $OuterRing<τ_0_0>.InnerRing<τ_1_0>, #OuterRing.InnerRing.method!1 : <T><U><V> (OuterRing<T>.InnerRing<U>) -> (T, U, V) -> (T, U, V), $@convention(method) <τ_0_0><τ_1_0><τ_2_0> (@in τ_0_0, @in τ_1_0, @in τ_2_0, @guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0)
diff --git a/test/SILGen/nested_types_referencing_nested_functions.swift b/test/SILGen/nested_types_referencing_nested_functions.swift
index 70a0514..2fdcb9f 100644
--- a/test/SILGen/nested_types_referencing_nested_functions.swift
+++ b/test/SILGen/nested_types_referencing_nested_functions.swift
@@ -13,7 +13,7 @@
     func zim() {
       foo()
     }
-    // CHECK-LABEL: sil private @_T0025nested_types_referencing_A10_functions3FooL_C4zangyxlF : $@convention(method) <T> (@in T, @guaranteed Foo) -> ()
+    // CHECK-LABEL: sil private @_T0025nested_types_referencing_A10_functions3FooL_C4zangyyxlF : $@convention(method) <T> (@in T, @guaranteed Foo) -> ()
     func zang<T>(_ x: T) {
       bar(x)
     }
diff --git a/test/SILGen/newtype.swift b/test/SILGen/newtype.swift
index 230f4f4..96a5fde 100644
--- a/test/SILGen/newtype.swift
+++ b/test/SILGen/newtype.swift
@@ -15,7 +15,7 @@
   return ErrorDomain(rawValue: str)
 }
 
-// CHECK-RAW-LABEL: sil shared [transparent] [serializable] @_T0SC11ErrorDomainVABSS8rawValue_tcfC
+// CHECK-RAW-LABEL: sil shared [transparent] [serializable] @_T0SC11ErrorDomainV8rawValueABSS_tcfC
 // CHECK-RAW: bb0([[STR:%[0-9]+]] : $String,
 // CHECK-RAW: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var ErrorDomain }, var, name "self"
 // CHECK-RAW: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [rootself] [[SELF_BOX]]
@@ -39,21 +39,21 @@
 // CHECK-RAW: bb0([[SELF:%[0-9]+]] : $ErrorDomain):
 // CHECK-RAW: [[STORED_VALUE:%[0-9]+]] = struct_extract [[SELF]] : $ErrorDomain, #ErrorDomain._rawValue
 // CHECK-RAW: [[STORED_VALUE_COPY:%.*]] = copy_value [[STORED_VALUE]]
-// CHECK-RAW: [[BRIDGE_FN:%[0-9]+]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+// CHECK-RAW: [[BRIDGE_FN:%[0-9]+]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
 // CHECK-RAW: [[OPT_STORED_VALUE_COPY:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[STORED_VALUE_COPY]]
 // CHECK-RAW: [[STRING_META:%[0-9]+]] = metatype $@thin String.Type
 // CHECK-RAW: [[STRING_RESULT:%[0-9]+]] = apply [[BRIDGE_FN]]([[OPT_STORED_VALUE_COPY]], [[STRING_META]])
 // CHECK-RAW: return [[STRING_RESULT]]
 
 class ObjCTest {
-  // CHECK-RAW-LABEL: sil hidden @_T07newtype8ObjCTestC19optionalPassThroughSC11ErrorDomainVSgAGF : $@convention(method) (@owned Optional<ErrorDomain>, @guaranteed ObjCTest) -> @owned Optional<ErrorDomain> {
-  // CHECK-RAW: sil hidden [thunk] @_T07newtype8ObjCTestC19optionalPassThroughSC11ErrorDomainVSgAGFTo : $@convention(objc_method) (Optional<ErrorDomain>, ObjCTest) -> Optional<ErrorDomain> {
+  // CHECK-RAW-LABEL: sil hidden @_T07newtype8ObjCTestC19optionalPassThroughySC11ErrorDomainVSgAGF : $@convention(method) (@owned Optional<ErrorDomain>, @guaranteed ObjCTest) -> @owned Optional<ErrorDomain> {
+  // CHECK-RAW: sil hidden [thunk] @_T07newtype8ObjCTestC19optionalPassThroughySC11ErrorDomainVSgAGFTo : $@convention(objc_method) (Optional<ErrorDomain>, ObjCTest) -> Optional<ErrorDomain> {
   @objc func optionalPassThrough(_ ed: ErrorDomain?) -> ErrorDomain? {
     return ed
   }  
 
-  // CHECK-RAW-LABEL: sil hidden @_T07newtype8ObjCTestC18integerPassThroughSC5MyIntVAFF : $@convention(method) (MyInt, @guaranteed ObjCTest) -> MyInt {
-  // CHECK-RAW: sil hidden [thunk] @_T07newtype8ObjCTestC18integerPassThroughSC5MyIntVAFFTo : $@convention(objc_method) (MyInt, ObjCTest) -> MyInt {
+  // CHECK-RAW-LABEL: sil hidden @_T07newtype8ObjCTestC18integerPassThroughySC5MyIntVAFF : $@convention(method) (MyInt, @guaranteed ObjCTest) -> MyInt {
+  // CHECK-RAW: sil hidden [thunk] @_T07newtype8ObjCTestC18integerPassThroughySC5MyIntVAFFTo : $@convention(objc_method) (MyInt, ObjCTest) -> MyInt {
   @objc func integerPassThrough(_ ed: MyInt) -> MyInt {
     return ed
   }  
@@ -66,18 +66,18 @@
 // CHECK-RAW: [[TO_NS:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
 // CHECK-RAW: [[BORROW:%.*]] = begin_borrow [[STRING]]
 // CHECK-RAW: [[NS:%.*]] = apply [[TO_NS]]([[BORROW]])
-// CHECK-RAW: [[TO_MY:%.*]] = function_ref @_T0s20_SwiftNewtypeWrapperPss21_ObjectiveCBridgeable8RawValueRpzrlE026_unconditionallyBridgeFromD1CxAD_01_D5CTypeQZSgFZ : $@convention(method) <τ_0_0 where τ_0_0 : _SwiftNewtypeWrapper, τ_0_0.RawValue : _ObjectiveCBridgeable> (@owned Optional<τ_0_0.RawValue._ObjectiveCType>, @thick τ_0_0.Type)
+// CHECK-RAW: [[TO_MY:%.*]] = function_ref @_T0s20_SwiftNewtypeWrapperPss21_ObjectiveCBridgeable8RawValueRpzrlE026_unconditionallyBridgeFromD1CyxAD_01_D5CTypeQZSgFZ : $@convention(method) <τ_0_0 where τ_0_0 : _SwiftNewtypeWrapper, τ_0_0.RawValue : _ObjectiveCBridgeable> (@owned Optional<τ_0_0.RawValue._ObjectiveCType>, @thick τ_0_0.Type)
 // CHECK-RAW: [[OPTNS:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NS]]
 // CHECK-RAW: [[META:%.*]] = metatype $@thick MyString.Type
 // CHECK-RAW: apply [[TO_MY]]<MyString, String>({{.*}}, [[OPTNS]], [[META]])
   return "foo" as NSString as MyString
 }
 
-// CHECK-RAW-LABEL: sil hidden @_T07newtype17bridgeFromNewtypeSSSC8MyStringV6string_tF
+// CHECK-RAW-LABEL: sil hidden @_T07newtype17bridgeFromNewtype6stringSSSC8MyStringV_tF
 func bridgeFromNewtype(string: MyString) -> String {
 // CHECK-RAW: [[FROM_MY:%.*]] = function_ref @_T0s20_SwiftNewtypeWrapperPss21_ObjectiveCBridgeable8RawValueRpzrlE09_bridgeToD1CAD_01_D5CTypeQZyF : $@convention(method) <τ_0_0 where τ_0_0 : _SwiftNewtypeWrapper, τ_0_0.RawValue : _ObjectiveCBridgeable> (@in_guaranteed τ_0_0) -> @owned τ_0_0.RawValue._ObjectiveCType
 // CHECK-RAW: [[NS:%.*]] = apply [[FROM_MY]]<MyString, String>(
-// CHECK-RAW: [[FROM_NS:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+// CHECK-RAW: [[FROM_NS:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
 // CHECK-RAW: [[OPTNS:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NS]]
 // CHECK-RAW: [[META:%.*]] = metatype $@thin String.Type
 // CHECK-RAW: apply [[FROM_NS]]([[OPTNS]], [[META]])
diff --git a/test/SILGen/noescape_reabstraction.swift b/test/SILGen/noescape_reabstraction.swift
index e7b26e5f..35ef3ed 100644
--- a/test/SILGen/noescape_reabstraction.swift
+++ b/test/SILGen/noescape_reabstraction.swift
@@ -9,7 +9,7 @@
 func noescape_generic<T>(_ x: (T) -> T) {
 }
 
-// CHECK-LABEL: sil hidden @_T022noescape_reabstraction0A9_concreteyAA1SVADcF
+// CHECK-LABEL: sil hidden @_T022noescape_reabstraction0A9_concreteyyAA1SVADcF
 // CHECK:         function_ref [[REABSTRACTION_THUNK:@_T022noescape_reabstraction1SVACIgyd_A2CIgir_TR]]
 
 func concrete(_ x: (S) -> S) {
@@ -19,5 +19,5 @@
 func generic<T>(_ x: (T) -> T) {
 }
 
-// CHECK-LABEL: sil hidden @_T022noescape_reabstraction8concreteyAA1SVADcF
+// CHECK-LABEL: sil hidden @_T022noescape_reabstraction8concreteyyAA1SVADcF
 // CHECK:         function_ref [[REABSTRACTION_THUNK]]
diff --git a/test/SILGen/objc_attr_NSManaged.swift b/test/SILGen/objc_attr_NSManaged.swift
index c264d2b..5c37327 100644
--- a/test/SILGen/objc_attr_NSManaged.swift
+++ b/test/SILGen/objc_attr_NSManaged.swift
@@ -68,7 +68,7 @@
   }
 }
 
-// CHECK-LABEL: sil hidden @_T019objc_attr_NSManaged9testFinalSSAA0E5GizmoCF : $@convention(thin) (@owned FinalGizmo) -> @owned String {
+// CHECK-LABEL: sil hidden @_T019objc_attr_NSManaged9testFinalySSAA0E5GizmoCF : $@convention(thin) (@owned FinalGizmo) -> @owned String {
 // CHECK: bb0([[ARG:%.*]] : @owned $FinalGizmo):
 // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK: objc_method [[BORROWED_ARG]] : $FinalGizmo, #FinalGizmo.kvc2!1.foreign : (FinalGizmo) -> () -> (), $@convention(objc_method) (FinalGizmo) -> ()
@@ -105,7 +105,7 @@
 // CHECK-NEXT:   #SwiftGizmo.modifyX!1: {{.*}} : _T019objc_attr_NSManaged10SwiftGizmoC7modifyXyyF
 // CHECK-NEXT:   #SwiftGizmo.testFunc!1: {{.*}} : _T019objc_attr_NSManaged10SwiftGizmoC8testFuncyyF
 // CHECK-NEXT:   #SwiftGizmo.init!initializer.1: {{.*}} : _T019objc_attr_NSManaged10SwiftGizmoCSQyACGycfc
-// CHECK-NEXT:   #SwiftGizmo.init!initializer.1: {{.*}} : _T019objc_attr_NSManaged10SwiftGizmoCSQyACGSi7bellsOn_tcfc
+// CHECK-NEXT:   #SwiftGizmo.init!initializer.1: {{.*}} : _T019objc_attr_NSManaged10SwiftGizmoC7bellsOnSQyACGSi_tcfc
 // CHECK-NEXT:   #SwiftGizmo.deinit!deallocator: _T019objc_attr_NSManaged10SwiftGizmoCfD
 // CHECK-NEXT: }
 
diff --git a/test/SILGen/objc_attr_NSManaged_multi.swift b/test/SILGen/objc_attr_NSManaged_multi.swift
index 6e8ea7a..a5d8244 100644
--- a/test/SILGen/objc_attr_NSManaged_multi.swift
+++ b/test/SILGen/objc_attr_NSManaged_multi.swift
@@ -4,7 +4,7 @@
 
 import Foundation
 
-// CHECK-LABEL: sil hidden @_T025objc_attr_NSManaged_multi9testMultiyXlAA10SwiftGizmoCF : $@convention(thin) (@owned SwiftGizmo) -> @owned AnyObject {
+// CHECK-LABEL: sil hidden @_T025objc_attr_NSManaged_multi9testMultiyyXlAA10SwiftGizmoCF : $@convention(thin) (@owned SwiftGizmo) -> @owned AnyObject {
 // CHECK: bb0([[ARG:%.*]] : @owned $SwiftGizmo):
 // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK: = objc_method [[BORROWED_ARG]] : $SwiftGizmo, #SwiftGizmo.kvc!1.foreign : (SwiftGizmo) -> () -> (), $@convention(objc_method) (SwiftGizmo) -> ()
@@ -21,7 +21,7 @@
   return obj.x
 }
 
-// CHECK-LABEL: sil hidden @_T025objc_attr_NSManaged_multi14testFinalMultiSSAA0F5GizmoCF : $@convention(thin) (@owned FinalGizmo) -> @owned String {
+// CHECK-LABEL: sil hidden @_T025objc_attr_NSManaged_multi14testFinalMultiySSAA0F5GizmoCF : $@convention(thin) (@owned FinalGizmo) -> @owned String {
 // CHECK: bb0([[ARG:%.*]] : @owned $FinalGizmo):
 // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK: objc_method [[BORROWED_ARG]] : $FinalGizmo, #FinalGizmo.kvc2!1.foreign : (FinalGizmo) -> () -> (), $@convention(objc_method) (FinalGizmo) -> ()
diff --git a/test/SILGen/objc_blocks_bridging.swift b/test/SILGen/objc_blocks_bridging.swift
index b263592..eab22f9 100644
--- a/test/SILGen/objc_blocks_bridging.swift
+++ b/test/SILGen/objc_blocks_bridging.swift
@@ -1,14 +1,14 @@
 // RUN: %empty-directory(%t)
 // RUN: %build-silgen-test-overlays
 // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -verify -emit-silgen -I %S/Inputs -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -verify -emit-silgen -I %S/Inputs -disable-objc-attr-requires-foundation-module -enable-sil-ownership -enable-guaranteed-closure-contexts %s | %FileCheck %s --check-prefix=GUARANTEED
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -verify -emit-silgen -I %S/Inputs -disable-objc-attr-requires-foundation-module -enable-sil-ownership  %s | %FileCheck %s --check-prefix=GUARANTEED
 
 // REQUIRES: objc_interop
 
 import Foundation
 
 @objc class Foo {
-// CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC3fooS3ic_Si1xtFTo :
+// CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC3foo_1xS3ic_SitFTo :
   // CHECK: bb0([[ARG1:%.*]] : @unowned $@convention(block) @noescape (Int) -> Int, {{.*}}, [[SELF:%.*]] : @unowned $Foo):
   // CHECK:         [[ARG1_COPY:%.*]] = copy_block [[ARG1]]
   // CHECK:         [[SELF_COPY:%.*]] = copy_value [[SELF]]
@@ -19,12 +19,12 @@
   // CHECK:         [[NATIVE:%.*]] = function_ref @_T020objc_blocks_bridging3FooC3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (@owned @noescape @callee_guaranteed (Int) -> Int, Int, @guaranteed Foo) -> Int
   // CHECK:         apply [[NATIVE]]([[CONVERT]], {{.*}}, [[BORROWED_SELF_COPY]])
   // CHECK:         end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
-  // CHECK: } // end sil function '_T020objc_blocks_bridging3FooC3fooS3ic_Si1xtFTo'
+  // CHECK: } // end sil function '_T020objc_blocks_bridging3FooC3foo_1xS3ic_SitFTo'
   dynamic func foo(_ f: (Int) -> Int, x: Int) -> Int {
     return f(x)
   }
 
-  // CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC3barS3Sc_SS1xtFTo : $@convention(objc_method) (@convention(block) @noescape (NSString) -> @autoreleased NSString, NSString, Foo) -> @autoreleased NSString {
+  // CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC3bar_1xS3Sc_SStFTo : $@convention(objc_method) (@convention(block) @noescape (NSString) -> @autoreleased NSString, NSString, Foo) -> @autoreleased NSString {
   // CHECK:       bb0([[BLOCK:%.*]] : @unowned $@convention(block) @noescape (NSString) -> @autoreleased NSString, [[NSSTRING:%.*]] : @unowned $NSString, [[SELF:%.*]] : @unowned $Foo):
   // CHECK:         [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
   // CHECK:         [[NSSTRING_COPY:%.*]] = copy_value [[NSSTRING]]
@@ -36,7 +36,7 @@
   // CHECK:         [[NATIVE:%.*]] = function_ref @_T020objc_blocks_bridging3FooC3bar{{[_0-9a-zA-Z]*}}F : $@convention(method) (@owned @noescape @callee_guaranteed (@owned String) -> @owned String, @owned String, @guaranteed Foo) -> @owned String
   // CHECK:         apply [[NATIVE]]([[CONVERT]], {{%.*}}, [[BORROWED_SELF_COPY]])
   // CHECK:         end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
-  // CHECK: } // end sil function '_T020objc_blocks_bridging3FooC3barS3Sc_SS1xtFTo'
+  // CHECK: } // end sil function '_T020objc_blocks_bridging3FooC3bar_1xS3Sc_SStFTo'
   dynamic func bar(_ f: (String) -> String, x: String) -> String {
     return f(x)
   }
@@ -49,7 +49,7 @@
   // GUARANTEED:   apply [[BLOCK]]([[NSSTR]]) : $@convention(block) @noescape (NSString) -> @autoreleased NSString
   // GUARANTEED: } // end sil function '_T0So8NSStringCABIyBya_S2SIgxo_TR'
 
-  // CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC3basSSSgA2Ec_AE1xtFTo : $@convention(objc_method) (@convention(block) @noescape (Optional<NSString>) -> @autoreleased Optional<NSString>, Optional<NSString>, Foo) -> @autoreleased Optional<NSString> {
+  // CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC3bas_1xSSSgA2Fc_AFtFTo : $@convention(objc_method) (@convention(block) @noescape (Optional<NSString>) -> @autoreleased Optional<NSString>, Optional<NSString>, Foo) -> @autoreleased Optional<NSString> {
   // CHECK:       bb0([[BLOCK:%.*]] : @unowned $@convention(block) @noescape (Optional<NSString>) -> @autoreleased Optional<NSString>, [[OPT_STRING:%.*]] : @unowned $Optional<NSString>, [[SELF:%.*]] : @unowned $Foo):
   // CHECK:         [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
   // CHECK:         [[OPT_STRING_COPY:%.*]] = copy_value [[OPT_STRING]]
diff --git a/test/SILGen/objc_bridged_results.swift b/test/SILGen/objc_bridged_results.swift
index d83c0c5..baa3e84 100644
--- a/test/SILGen/objc_bridged_results.swift
+++ b/test/SILGen/objc_bridged_results.swift
@@ -7,21 +7,21 @@
 
 import Foundation
 
-// CHECK-LABEL: sil hidden @_T020objc_bridged_results11testNonnullSayypGSo4TestCF
+// CHECK-LABEL: sil hidden @_T020objc_bridged_results11testNonnullySayypGSo4TestCF
 // CHECK: bb0([[ARG:%.*]] : @owned $Test):
 // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK: [[METHOD:%[0-9]+]] = objc_method [[BORROWED_ARG]] : $Test, #Test.nonnullArray!getter.1.foreign : (Test) -> () -> [Any], $@convention(objc_method) (Test) -> @autoreleased Optional<NSArray>
 // CHECK: [[COCOA_VAL:%[0-9]+]] = apply [[METHOD]]([[BORROWED_ARG]]) : $@convention(objc_method) (Test) -> @autoreleased Optional<NSArray>
-// CHECK: [[CONVERT:%[0-9]+]] = function_ref @_T0Sa10FoundationE36_unconditionallyBridgeFromObjectiveCSayxGSo7NSArrayCSgFZ
+// CHECK: [[CONVERT:%[0-9]+]] = function_ref @_T0Sa10FoundationE36_unconditionallyBridgeFromObjectiveCySayxGSo7NSArrayCSgFZ
 // CHECK: [[ARRAY_META:%[0-9]+]] = metatype $@thin Array<Any>.Type
 // CHECK: [[RESULT:%[0-9]+]] = apply [[CONVERT]]<Any>([[COCOA_VAL]], [[ARRAY_META]])
 // CHECK: destroy_value %0 : $Test
 // CHECK: return [[RESULT]] : $Array<Any>
 func testNonnull(_ obj: Test) -> [Any] {
   return obj.nonnullArray
-} // CHECK: } // end sil function '_T020objc_bridged_results11testNonnullSayypGSo4TestCF'
+} // CHECK: } // end sil function '_T020objc_bridged_results11testNonnullySayypGSo4TestCF'
 
-// CHECK-LABEL: sil hidden @_T020objc_bridged_results12testNullableSayypGSgSo4TestCF
+// CHECK-LABEL: sil hidden @_T020objc_bridged_results12testNullableySayypGSgSo4TestCF
 func testNullable(_ obj: Test) -> [Any]? {
   // CHECK: bb0([[ARG:%.*]] : @owned $Test):
   // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
@@ -31,7 +31,7 @@
   //
   // CHECK: [[CASE_NON_NIL]]([[COCOA_VAL_NON_NIL:%.*]] : @owned $NSArray):
   // CHECK-NOT: unchecked_enum_data
-  // CHECK: [[CONVERT:%[0-9]+]] = function_ref @_T0Sa10FoundationE36_unconditionallyBridgeFromObjectiveCSayxGSo7NSArrayCSgFZ
+  // CHECK: [[CONVERT:%[0-9]+]] = function_ref @_T0Sa10FoundationE36_unconditionallyBridgeFromObjectiveCySayxGSo7NSArrayCSgFZ
   // CHECK: [[COCOA_SOME_VAL:%[0-9]+]] = enum $Optional<NSArray>, #Optional.some!enumelt.1, [[COCOA_VAL_NON_NIL]]
   // CHECK: [[ARRAY_META:%[0-9]+]] = metatype $@thin Array<Any>.Type
   // CHECK: [[RESULT_VAL:%[0-9]+]] = apply [[CONVERT]]<Any>([[COCOA_SOME_VAL]], [[ARRAY_META]])
@@ -47,9 +47,9 @@
   // CHECK: destroy_value [[ARG]] : $Test
   // CHECK: return [[RESULT]] : $Optional<Array<Any>>
   return obj.nullableArray
-} // CHECK: } // end sil function '_T020objc_bridged_results12testNullableSayypGSgSo4TestCF'
+} // CHECK: } // end sil function '_T020objc_bridged_results12testNullableySayypGSgSo4TestCF'
 
-// CHECK-LABEL: sil hidden @_T020objc_bridged_results19testNullUnspecifiedSQySayypGGSo4TestCF
+// CHECK-LABEL: sil hidden @_T020objc_bridged_results19testNullUnspecifiedySQySayypGGSo4TestCF
 func testNullUnspecified(_ obj: Test) -> [Any]! {
   // CHECK: bb0([[ARG:%.*]] : @owned $Test):
   // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
@@ -59,7 +59,7 @@
 
   // CHECK: [[CASE_NON_NIL]]([[COCOA_VAL_NON_NIL:%.*]] : @owned $NSArray):
   // CHECK-NOT: unchecked_enum_data
-  // CHECK: [[CONVERT:%[0-9]+]] = function_ref @_T0Sa10FoundationE36_unconditionallyBridgeFromObjectiveCSayxGSo7NSArrayCSgFZ
+  // CHECK: [[CONVERT:%[0-9]+]] = function_ref @_T0Sa10FoundationE36_unconditionallyBridgeFromObjectiveCySayxGSo7NSArrayCSgFZ
   // CHECK: [[COCOA_SOME_VAL:%[0-9]+]] = enum $Optional<NSArray>, #Optional.some!enumelt.1, [[COCOA_VAL_NON_NIL]]
   // CHECK: [[ARRAY_META:%[0-9]+]] = metatype $@thin Array<Any>.Type
   // CHECK: [[RESULT_VAL:%[0-9]+]] = apply [[CONVERT]]<Any>([[COCOA_SOME_VAL]], [[ARRAY_META]])
@@ -75,60 +75,60 @@
   // CHECK: destroy_value [[ARG]] : $Test
   // CHECK: return [[RESULT]] : $Optional<Array<Any>>
   return obj.nullUnspecifiedArray
-} // CHECK: } // end sil function '_T020objc_bridged_results19testNullUnspecifiedSQySayypGGSo4TestCF'
+} // CHECK: } // end sil function '_T020objc_bridged_results19testNullUnspecifiedySQySayypGGSo4TestCF'
 
 
-// CHECK-LABEL: sil hidden @_T020objc_bridged_results21testNonnullDictionarys0F0Vys11AnyHashableVypGSo4TestCF
+// CHECK-LABEL: sil hidden @_T020objc_bridged_results21testNonnullDictionaryys0F0Vys11AnyHashableVypGSo4TestCF
 func testNonnullDictionary(_ obj: Test) -> [AnyHashable: Any] {
   // CHECK: bb0([[ARG:%.*]] : @owned $Test):
   // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
   // CHECK: [[METHOD:%[0-9]+]] = objc_method [[BORROWED_ARG]] : $Test, #Test.nonnullDictionary!getter.1.foreign : (Test) -> () -> [AnyHashable : Any], $@convention(objc_method) (Test) -> @autoreleased Optional<NSDictionary>
   // CHECK: [[COCOA_VAL:%[0-9]+]] = apply [[METHOD]]([[BORROWED_ARG]]) : $@convention(objc_method) (Test) -> @autoreleased Optional<NSDictionary>
-  // CHECK: [[CONVERT:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE36_unconditionallyBridgeFromObjectiveCAByxq_GSo12NSDictionaryCSgFZ
+  // CHECK: [[CONVERT:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE36_unconditionallyBridgeFromObjectiveCyAByxq_GSo12NSDictionaryCSgFZ
   // CHECK: [[DICT_META:%[0-9]+]] = metatype $@thin Dictionary<AnyHashable, Any>.Type
   // CHECK: [[RESULT:%[0-9]+]] = apply [[CONVERT]]<AnyHashable, Any>([[COCOA_VAL]], [[DICT_META]])
   // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
   // CHECK: destroy_value [[ARG]] : $Test
   // CHECK: return [[RESULT]] : $Dictionary<AnyHashable, Any>
   return obj.nonnullDictionary
-} // CHECK: } // end sil function '_T020objc_bridged_results21testNonnullDictionarys0F0Vys11AnyHashableVypGSo4TestCF'
+} // CHECK: } // end sil function '_T020objc_bridged_results21testNonnullDictionaryys0F0Vys11AnyHashableVypGSo4TestCF'
 
-// CHECK-LABEL: sil hidden @_T020objc_bridged_results14testNonnullSets0F0Vys11AnyHashableVGSo4TestCF
+// CHECK-LABEL: sil hidden @_T020objc_bridged_results14testNonnullSetys0F0Vys11AnyHashableVGSo4TestCF
 func testNonnullSet(_ obj: Test) -> Set<AnyHashable> {
   // CHECK: bb0([[ARG:%.*]] : @owned $Test):
   // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
   // CHECK: [[METHOD:%[0-9]+]] = objc_method [[BORROWED_ARG]] : $Test, #Test.nonnullSet!getter.1.foreign : (Test) -> () -> Set<AnyHashable>, $@convention(objc_method) (Test) -> @autoreleased Optional<NSSet>
   // CHECK: [[COCOA_VAL:%[0-9]+]] = apply [[METHOD]]([[BORROWED_ARG]]) : $@convention(objc_method) (Test) -> @autoreleased Optional<NSSet>
-  // CHECK: [[CONVERT:%[0-9]+]] = function_ref @_T0s3SetV10FoundationE36_unconditionallyBridgeFromObjectiveCAByxGSo5NSSetCSgFZ
+  // CHECK: [[CONVERT:%[0-9]+]] = function_ref @_T0s3SetV10FoundationE36_unconditionallyBridgeFromObjectiveCyAByxGSo5NSSetCSgFZ
   // CHECK: [[SET_META:%[0-9]+]] = metatype $@thin Set<AnyHashable>.Type
   // CHECK: [[RESULT:%[0-9]+]] = apply [[CONVERT]]<AnyHashable>([[COCOA_VAL]], [[SET_META]])
   // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
   // CHECK: destroy_value [[ARG]] : $Test
   // CHECK: return [[RESULT]] : $Set<AnyHashable>
   return obj.nonnullSet
-} // CHECK: } // end sil function '_T020objc_bridged_results14testNonnullSets0F0Vys11AnyHashableVGSo4TestCF'
+} // CHECK: } // end sil function '_T020objc_bridged_results14testNonnullSetys0F0Vys11AnyHashableVGSo4TestCF'
 
-// CHECK-LABEL: sil hidden @_T020objc_bridged_results17testNonnullStringSSSo4TestCF
+// CHECK-LABEL: sil hidden @_T020objc_bridged_results17testNonnullStringySSSo4TestCF
 func testNonnullString(_ obj: Test) -> String {
   // CHECK: bb0([[ARG:%.*]] : @owned $Test):
   // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
   // CHECK: [[METHOD:%[0-9]+]] = objc_method [[BORROWED_ARG]] : $Test, #Test.nonnullString!getter.1.foreign : (Test) -> () -> String, $@convention(objc_method) (Test) -> @autoreleased Optional<NSString>
   // CHECK: [[COCOA_VAL:%[0-9]+]] = apply [[METHOD]]([[BORROWED_ARG]]) : $@convention(objc_method) (Test) -> @autoreleased Optional<NSString>
-  // CHECK: [[CONVERT:%[0-9]+]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+  // CHECK: [[CONVERT:%[0-9]+]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
   // CHECK: [[STRING_META:%[0-9]+]] = metatype $@thin String.Type
   // CHECK: [[RESULT:%[0-9]+]] = apply [[CONVERT]]([[COCOA_VAL]], [[STRING_META]]) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
   // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
   // CHECK: destroy_value [[ARG]] : $Test
   // CHECK: return [[RESULT]] : $String
   return obj.nonnullString
-} // CHECK: } // end sil function '_T020objc_bridged_results17testNonnullStringSSSo4TestCF'
+} // CHECK: } // end sil function '_T020objc_bridged_results17testNonnullStringySSSo4TestCF'
 
 // CHECK-LABEL: sil hidden @_T020objc_bridged_results13testClassPropSSyF
 func testClassProp() -> String {
   // CHECK: [[CLASS:%.+]] = metatype $@objc_metatype Test.Type
   // CHECK: [[METHOD:%.+]] = objc_method [[CLASS]] : $@objc_metatype Test.Type, #Test.nonnullSharedString!getter.1.foreign : (Test.Type) -> () -> String, $@convention(objc_method) (@objc_metatype Test.Type) -> @autoreleased Optional<NSString>
   // CHECK: [[COCOA_VAL:%[0-9]+]] = apply [[METHOD]]([[CLASS]]) : $@convention(objc_method) (@objc_metatype Test.Type) -> @autoreleased Optional<NSString>
-  // CHECK: [[CONVERT:%[0-9]+]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+  // CHECK: [[CONVERT:%[0-9]+]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
   // CHECK: [[STRING_META:%[0-9]+]] = metatype $@thin String.Type
   // CHECK: [[RESULT:%[0-9]+]] = apply [[CONVERT]]([[COCOA_VAL]], [[STRING_META]]) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
   // CHECK: return [[RESULT]] : $String
@@ -139,23 +139,23 @@
 // Note: This doesn't really "work" in that it doesn't accept a nil value the
 // way the others do, because subscripts are thunked. But the main thing is
 // not to crash trying to generate the thunk.
-// CHECK-LABEL: sil hidden @_T020objc_bridged_results20testNonnullSubscriptSayypGSo4TestCF
+// CHECK-LABEL: sil hidden @_T020objc_bridged_results20testNonnullSubscriptySayypGSo4TestCF
 func testNonnullSubscript(_ obj: Test) -> [Any] {
   // CHECK: bb0([[ARG:%.*]] : @owned $Test):
   // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
   // CHECK: [[METHOD:%[0-9]+]] = objc_method [[BORROWED_ARG]] : $Test, #Test.subscript!getter.1.foreign : (Test) -> (Int) -> [Any], $@convention(objc_method) (Int, Test) -> @autoreleased Optional<NSArray>
   // CHECK: [[COCOA_VAL:%[0-9]+]] = apply [[METHOD]]({{%[0-9]+}}, [[BORROWED_ARG]]) : $@convention(objc_method) (Int, Test) -> @autoreleased Optional<NSArray>
-  // CHECK: [[CONVERT:%[0-9]+]] = function_ref @_T0Sa10FoundationE36_unconditionallyBridgeFromObjectiveCSayxGSo7NSArrayCSgFZ
+  // CHECK: [[CONVERT:%[0-9]+]] = function_ref @_T0Sa10FoundationE36_unconditionallyBridgeFromObjectiveCySayxGSo7NSArrayCSgFZ
   // CHECK: [[ARRAY_META:%[0-9]+]] = metatype $@thin Array<Any>.Type,
   // CHECK: [[RESULT:%[0-9]+]] = apply [[CONVERT]]<Any>([[COCOA_VAL]], [[ARRAY_META]])
   // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
   // CHECK: destroy_value [[ARG]] : $Test
   // CHECK: return [[RESULT]] : $Array<Any>
   return obj[0]
-} // CHECK: } // end sil function '_T020objc_bridged_results20testNonnullSubscriptSayypGSo4TestCF'
+} // CHECK: } // end sil function '_T020objc_bridged_results20testNonnullSubscriptySayypGSo4TestCF'
 
 
-// CHECK-LABEL: sil hidden @_T020objc_bridged_results19testPerformSelectorySo8NSObjectCF
+// CHECK-LABEL: sil hidden @_T020objc_bridged_results19testPerformSelectoryySo8NSObjectCF
 func testPerformSelector(_ obj: NSObject) {
   // CHECK: bb0([[ARG:%.*]] : @owned $NSObject):
   // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
@@ -165,4 +165,4 @@
   // CHECK-NOT: {{(retain|release).+}}[[RESULT]]
   // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
   // CHECK-NOT: {{(retain|release).+}}[[RESULT]]
-} // CHECK: } // end sil function '_T020objc_bridged_results19testPerformSelectorySo8NSObjectCF'
+} // CHECK: } // end sil function '_T020objc_bridged_results19testPerformSelectoryySo8NSObjectCF'
diff --git a/test/SILGen/objc_bridged_using_protocol_extension_impl.swift b/test/SILGen/objc_bridged_using_protocol_extension_impl.swift
index 088ff35..0968cc9 100644
--- a/test/SILGen/objc_bridged_using_protocol_extension_impl.swift
+++ b/test/SILGen/objc_bridged_using_protocol_extension_impl.swift
@@ -41,14 +41,14 @@
   dynamic func bar(_: Any) {}
 }
 
-// CHECK-LABEL: sil hidden @_T042objc_bridged_using_protocol_extension_impl7callBaryAA0H0C3bar_AA3FooV3footF
+// CHECK-LABEL: sil hidden @_T042objc_bridged_using_protocol_extension_impl7callBar3bar3fooyAA0H0C_AA3FooVtF
 func callBar(bar: Bar, foo: Foo) {
   // CHECK: [[BRIDGE:%.*]] = function_ref @_T042objc_bridged_using_protocol_extension_impl7FooablePAAs21_ObjectiveCBridgeableRzrlE09_bridgeToH1C01_H5CTypesADPQzyF
   // CHECK: apply [[BRIDGE]]<Foo>
   bar.bar(foo)
 }
 
-// CHECK-LABEL:sil hidden @_T042objc_bridged_using_protocol_extension_impl7callBaryAA0H0C3bar_AA3GenVySiSSG3gentF 
+// CHECK-LABEL:sil hidden @_T042objc_bridged_using_protocol_extension_impl7callBar3bar3genyAA0H0C_AA3GenVySiSSGtF
 func callBar(bar: Bar, gen: Gen<Int, String>) {
   // CHECK: [[BRIDGE:%.*]] = function_ref @_T042objc_bridged_using_protocol_extension_impl7FooablePAAs21_ObjectiveCBridgeableRzrlE09_bridgeToH1C01_H5CTypesADPQzyF
   // CHECK: apply [[BRIDGE]]<Gen<Int, String>>
diff --git a/test/SILGen/objc_bridging.swift b/test/SILGen/objc_bridging.swift
index d032540..657a880 100644
--- a/test/SILGen/objc_bridging.swift
+++ b/test/SILGen/objc_bridging.swift
@@ -21,7 +21,7 @@
 //
 // CHECK: [[SOME_BB]]([[BRIDGED:%.*]] : @owned $NSString):
 // CHECK-NOT:   unchecked_enum_data
-// CHECK:   [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+// CHECK:   [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
 // CHECK:   [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]]
 // CHECK:   [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]],
 // CHECK:   [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]]
@@ -49,7 +49,7 @@
 // CHECK-LABEL: sil hidden @_T013objc_bridging18getUppercaseString{{.*}}F
 // CHECK: bb0([[ARG:%.*]] : @owned $NSString):
 // -- The 'self' argument of NSString methods doesn't bridge.
-// CHECK-NOT: function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+// CHECK-NOT: function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
 // CHECK-NOT: function_ref @swift_StringToNSString
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[UPPERCASE_STRING:%.*]] = objc_method [[BORROWED_ARG]] : $NSString, #NSString.uppercase!1.foreign
@@ -59,7 +59,7 @@
 //
 // CHECK: [[SOME_BB]]([[BRIDGED:%.*]] :
 // CHECK-NOT:  unchecked_enum_data
-// CHECK:   [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+// CHECK:   [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
 // CHECK:   [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]]
 // CHECK:   [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]]
 // CHECK:   [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]]
@@ -210,7 +210,7 @@
 func getZang(_ f: Foo) -> Bool {
   return f.zang()
 }
-// CHECK-LABEL: sil hidden @_T013objc_bridging7getZangSbSo3FooCF
+// CHECK-LABEL: sil hidden @_T013objc_bridging7getZangySbSo3FooCF
 // CHECK: bb0([[ARG:%.*]] : @owned $Foo)
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[METHOD:%.*]] = objc_method [[BORROWED_ARG]] : $Foo, #Foo.zang!1.foreign
@@ -223,14 +223,14 @@
 func setZang(_ f: Foo, _ b: Bool) {
   f.setZang(b)
 }
-// CHECK-LABEL: sil hidden @_T013objc_bridging7setZangySo3FooC_SbtF
+// CHECK-LABEL: sil hidden @_T013objc_bridging7setZangyySo3FooC_SbtF
 // CHECK: bb0([[ARG0:%.*]] : @owned $Foo, [[ARG1:%.*]] : @trivial $Bool):
 // CHECK:   [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]]
 // CHECK:   [[METHOD:%.*]] = objc_method [[BORROWED_ARG0]] : $Foo, #Foo.setZang!1.foreign
 // CHECK:   apply [[METHOD]]([[ARG1]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Bool, Foo) -> ()
 // CHECK:   end_borrow [[BORROWED_ARG0]] from [[ARG0]]
 // CHECK:   destroy_value [[ARG0]]
-// CHECK: } // end sil function '_T013objc_bridging7setZangySo3FooC_SbtF' 
+// CHECK: } // end sil function '_T013objc_bridging7setZangyySo3FooC_SbtF'
 
 // NSString *bar(void);
 func callBar() -> String {
@@ -243,7 +243,7 @@
 // CHECK:   switch_enum [[OPT_BRIDGED]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
 
 // CHECK: [[SOME_BB]]([[BRIDGED:%.*]] : @owned $NSString):
-// CHECK:   [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+// CHECK:   [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
 // CHECK:   [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]]
 // CHECK:   [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]]
 // CHECK:   [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]]
@@ -279,23 +279,23 @@
   }
   // CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE13nsstrFakePropABvgTo
   // CHECK-NOT: swift_StringToNSString
-  // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+  // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
   // CHECK: }
   // CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE13nsstrFakePropABvsTo
   // CHECK-NOT: swift_StringToNSString
-  // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+  // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
   // CHECK: }
 
   func nsstrResult() -> NSString { return NSS }
   // CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE11nsstrResultAByFTo
   // CHECK-NOT: swift_StringToNSString
-  // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+  // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
   // CHECK: }
 
   func nsstrArg(_ s: NSString) { }
-  // CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE8nsstrArgyABFTo
+  // CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE8nsstrArgyyABFTo
   // CHECK-NOT: swift_StringToNSString
-  // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+  // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
   // CHECK: }
 
 }
@@ -331,7 +331,7 @@
   // CHECK: bb0([[VALUE:%.*]] : @unowned $NSString, [[THIS:%.*]] : @unowned $Bas):
   // CHECK:   [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
   // CHECK:   [[THIS_COPY:%.*]] = copy_value [[THIS]]
-  // CHECK:   [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+  // CHECK:   [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
   // CHECK:   [[VALUE_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[VALUE_COPY]]
   // CHECK:   [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[VALUE_BOX]]
 
@@ -374,7 +374,7 @@
   // CHECK: bb0([[NSSTR:%.*]] : @unowned $NSString, [[THIS:%.*]] : @unowned $Bas):
   // CHECK:   [[NSSTR_COPY:%.*]] = copy_value [[NSSTR]]
   // CHECK:   [[THIS_COPY:%.*]] = copy_value [[THIS]]
-  // CHECK:   [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+  // CHECK:   [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
   // CHECK:   [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR_COPY]]
   // CHECK:   [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[NSSTR_BOX]]
   // CHECK:   [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
@@ -392,12 +392,12 @@
   }
   // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC13nsstrRealPropSo8NSStringCvgTo : $@convention(objc_method) (Bas) -> @autoreleased NSString {
   // CHECK-NOT: swift_StringToNSString
-  // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+  // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
   // CHECK: }
 
   // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC13nsstrRealPropSo8NSStringCvsTo : $@convention(objc_method) (NSString, Bas) ->
   // CHECK-NOT: swift_StringToNSString
-  // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+  // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
   // CHECK: }
 
   // -- Bridging thunks for String methods convert between NSString
@@ -418,30 +418,30 @@
   // CHECK:   return [[NSSTR]]
   // CHECK: }
   func strArg(_ s: String) { }
-  // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC6strArgySSFTo
+  // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC6strArgyySSFTo
   // CHECK: bb0([[NSSTR:%.*]] : @unowned $NSString, [[THIS:%.*]] : @unowned $Bas):
   // CHECK:   [[NSSTR_COPY:%.*]] = copy_value [[NSSTR]]
   // CHECK:   [[THIS_COPY:%.*]] = copy_value [[THIS]]
-  // CHECK:   [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+  // CHECK:   [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
   // CHECK:   [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR_COPY]]
   // CHECK:   [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[NSSTR_BOX]]
   // CHECK:   [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
-  // CHECK:   [[METHOD:%.*]] = function_ref @_T013objc_bridging3BasC6strArgySSF
+  // CHECK:   [[METHOD:%.*]] = function_ref @_T013objc_bridging3BasC6strArgyySSF
   // CHECK:   apply [[METHOD]]([[STR]], [[BORROWED_THIS_COPY]])
   // CHECK:   end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
   // CHECK:   destroy_value [[THIS_COPY]]
-  // CHECK: } // end sil function '_T013objc_bridging3BasC6strArgySSFTo'
+  // CHECK: } // end sil function '_T013objc_bridging3BasC6strArgyySSFTo'
 
   // -- Bridging thunks for explicitly NSString properties don't convert
   func nsstrResult() -> NSString { return NSS }
   // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11nsstrResultSo8NSStringCyFTo
   // CHECK-NOT: swift_StringToNSString
-  // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+  // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
   // CHECK: }
   func nsstrArg(_ s: NSString) { }
-  // CHECK-LABEL: sil hidden @_T013objc_bridging3BasC8nsstrArgySo8NSStringCF
+  // CHECK-LABEL: sil hidden @_T013objc_bridging3BasC8nsstrArgyySo8NSStringCF
   // CHECK-NOT: swift_StringToNSString
-  // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+  // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
   // CHECK: }
 
   init(str: NSString) {
@@ -449,16 +449,16 @@
     super.init()
   }
 
-  // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC8arrayArgySayyXlGFTo : $@convention(objc_method) (NSArray, Bas) -> ()
+  // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC8arrayArgyySayyXlGFTo : $@convention(objc_method) (NSArray, Bas) -> ()
   // CHECK: bb0([[NSARRAY:%[0-9]+]] : @unowned $NSArray, [[SELF:%[0-9]+]] : @unowned $Bas):
   // CHECK:   [[NSARRAY_COPY:%.*]] = copy_value [[NSARRAY]] : $NSArray
   // CHECK:   [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Bas
-  // CHECK:   [[CONV_FN:%[0-9]+]] = function_ref @_T0Sa10FoundationE36_unconditionallyBridgeFromObjectiveCSayxGSo7NSArrayCSgFZ
+  // CHECK:   [[CONV_FN:%[0-9]+]] = function_ref @_T0Sa10FoundationE36_unconditionallyBridgeFromObjectiveCySayxGSo7NSArrayCSgFZ
   // CHECK:   [[OPT_NSARRAY:%[0-9]+]] = enum $Optional<NSArray>, #Optional.some!enumelt.1, [[NSARRAY_COPY]] : $NSArray
   // CHECK:   [[ARRAY_META:%[0-9]+]] = metatype $@thin Array<AnyObject>.Type
   // CHECK:   [[ARRAY:%[0-9]+]] = apply [[CONV_FN]]<AnyObject>([[OPT_NSARRAY]], [[ARRAY_META]])
   // CHECK:   [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
-  // CHECK:   [[SWIFT_FN:%[0-9]+]] = function_ref @_T013objc_bridging3BasC8arrayArgySayyXlGF : $@convention(method) (@owned Array<AnyObject>, @guaranteed Bas) -> ()
+  // CHECK:   [[SWIFT_FN:%[0-9]+]] = function_ref @_T013objc_bridging3BasC8arrayArgyySayyXlGF : $@convention(method) (@owned Array<AnyObject>, @guaranteed Bas) -> ()
   // CHECK:   [[RESULT:%[0-9]+]] = apply [[SWIFT_FN]]([[ARRAY]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Array<AnyObject>, @guaranteed Bas) -> ()
   // CHECK:   end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
   // CHECK:   destroy_value [[SELF_COPY]] : $Bas
@@ -486,7 +486,7 @@
   var arrayProp: [String] = []
 }
 
-// CHECK-LABEL: sil hidden @_T013objc_bridging16applyStringBlockS3SXB_SS1xtF
+// CHECK-LABEL: sil hidden @_T013objc_bridging16applyStringBlock_1xS3SXB_SStF
 func applyStringBlock(_ f: @convention(block) (String) -> String, x: String) -> String {
   // CHECK: bb0([[BLOCK:%.*]] : @owned $@convention(block) @noescape (NSString) -> @autoreleased NSString, [[STRING:%.*]] : @owned $String):
   // CHECK:   [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
@@ -501,7 +501,7 @@
   // CHECK:   destroy_value [[STRING_COPY]]
   // CHECK:   [[RESULT_NSSTR:%.*]] = apply [[BLOCK_COPY_COPY]]([[NSSTR]]) : $@convention(block) @noescape (NSString) -> @autoreleased NSString
   // CHECK:   destroy_value [[NSSTR]]
-  // CHECK:   [[FINAL_BRIDGE:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+  // CHECK:   [[FINAL_BRIDGE:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
   // CHECK:   [[OPTIONAL_NSSTR:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[RESULT_NSSTR]]
   // CHECK:   [[RESULT:%.*]] = apply [[FINAL_BRIDGE]]([[OPTIONAL_NSSTR]], {{.*}}) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
   // CHECK:   destroy_value [[BLOCK_COPY_COPY]]
@@ -511,11 +511,11 @@
   // CHECK:   return [[RESULT]] : $String
   return f(x)
 }
-// CHECK: } // end sil function '_T013objc_bridging16applyStringBlockS3SXB_SS1xtF'
+// CHECK: } // end sil function '_T013objc_bridging16applyStringBlock_1xS3SXB_SStF'
 
 // CHECK-LABEL: sil hidden @_T013objc_bridging15bridgeCFunction{{.*}}F
 func bridgeCFunction() -> (String?) -> (String?) {
-  // CHECK: [[THUNK:%.*]] = function_ref @_T0SC18NSStringFromStringSQySSGABFTO : $@convention(thin) (@owned Optional<String>) -> @owned Optional<String>
+  // CHECK: [[THUNK:%.*]] = function_ref @_T0SC18NSStringFromStringySQySSGABFTO : $@convention(thin) (@owned Optional<String>) -> @owned Optional<String>
   // CHECK: [[THICK:%.*]] = thin_to_thick_function [[THUNK]]
   // CHECK: return [[THICK]]
   return NSStringFromString
@@ -530,22 +530,22 @@
 // arguments lifetime-extends the bridged pointer for the right duration.
 // <rdar://problem/16738050>
 
-// CHECK-LABEL: sil shared [serializable] @_T0So7NSArrayCABSQySPyyXlSgGG7objects_s5Int32V5counttcfC
+// CHECK-LABEL: sil shared [serializable] @_T0So7NSArrayC7objects5countABSQySPyyXlSgGG_s5Int32VtcfC
 // CHECK:         [[SELF:%.*]] = alloc_ref_dynamic
-// CHECK:         [[METHOD:%.*]] = function_ref @_T0So7NSArrayCABSQySPyyXlSgGG7objects_s5Int32V5counttcfcTO
+// CHECK:         [[METHOD:%.*]] = function_ref @_T0So7NSArrayC7objects5countABSQySPyyXlSgGG_s5Int32VtcfcTO
 // CHECK:         [[RESULT:%.*]] = apply [[METHOD]]
 // CHECK:         return [[RESULT]]
 
 // Check that type lowering preserves the bool/BOOL distinction when bridging
 // imported C functions.
 
-// CHECK-ios-i386-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF
+// CHECK-ios-i386-LABEL: sil hidden @_T013objc_bridging5boolsySb_SbtSbF
 // CHECK-ios-i386:         function_ref @useBOOL : $@convention(c) (ObjCBool) -> ()
 // CHECK-ios-i386:         function_ref @useBool : $@convention(c) (Bool) -> ()
 // CHECK-ios-i386:         function_ref @getBOOL : $@convention(c) () -> ObjCBool
 // CHECK-ios-i386:         function_ref @getBool : $@convention(c) () -> Bool
 
-// CHECK-macosx-x86_64-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF
+// CHECK-macosx-x86_64-LABEL: sil hidden @_T013objc_bridging5boolsySb_SbtSbF
 // CHECK-macosx-x86_64:         function_ref @useBOOL : $@convention(c) (ObjCBool) -> ()
 // CHECK-macosx-x86_64:         function_ref @useBool : $@convention(c) (Bool) -> ()
 // CHECK-macosx-x86_64:         function_ref @getBOOL : $@convention(c) () -> ObjCBool
@@ -555,19 +555,19 @@
 // at the underlying Clang decl of the bridged decl to decide whether it needs
 // bridging.
 //
-// CHECK-watchos-i386-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF
+// CHECK-watchos-i386-LABEL: sil hidden @_T013objc_bridging5boolsySb_SbtSbF
 // CHECK-watchos-i386:         function_ref @useBOOL : $@convention(c) (Bool) -> ()
 // CHECK-watchos-i386:         function_ref @useBool : $@convention(c) (Bool) -> ()
 // CHECK-watchos-i386:         function_ref @getBOOL : $@convention(c) () -> Bool
 // CHECK-watchos-i386:         function_ref @getBool : $@convention(c) () -> Bool
 
-// CHECK-ios-x86_64-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF
+// CHECK-ios-x86_64-LABEL: sil hidden @_T013objc_bridging5boolsySb_SbtSbF
 // CHECK-ios-x86_64:         function_ref @useBOOL : $@convention(c) (Bool) -> ()
 // CHECK-ios-x86_64:         function_ref @useBool : $@convention(c) (Bool) -> ()
 // CHECK-ios-x86_64:         function_ref @getBOOL : $@convention(c) () -> Bool
 // CHECK-ios-x86_64:         function_ref @getBool : $@convention(c) () -> Bool
 
-// CHECK-arm64-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF
+// CHECK-arm64-LABEL: sil hidden @_T013objc_bridging5boolsySb_SbtSbF
 // CHECK-arm64:         function_ref @useBOOL : $@convention(c) (Bool) -> ()
 // CHECK-arm64:         function_ref @useBool : $@convention(c) (Bool) -> ()
 // CHECK-arm64:         function_ref @getBOOL : $@convention(c) () -> Bool
@@ -586,7 +586,7 @@
   // CHECK: [[BORROWED_HOME:%.*]] = begin_borrow [[HOME]]
   // CHECK: [[GETTER:%[0-9]+]] = objc_method [[BORROWED_HOME]] : $APPHouse, #APPHouse.fridge!getter.1.foreign
   // CHECK: [[OBJC_RESULT:%[0-9]+]] = apply [[GETTER]]([[BORROWED_HOME]])
-  // CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @_T010Appliances12RefrigeratorV36_unconditionallyBridgeFromObjectiveCACSo15APPRefrigeratorCSgFZ
+  // CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @_T010Appliances12RefrigeratorV36_unconditionallyBridgeFromObjectiveCyACSo15APPRefrigeratorCSgFZ
   // CHECK: [[REFRIGERATOR_META:%[0-9]+]] = metatype $@thin Refrigerator.Type
   // CHECK: [[RESULT:%[0-9]+]] = apply [[BRIDGE_FN]]([[OBJC_RESULT]], [[REFRIGERATOR_META]])
   // CHECK: end_borrow [[BORROWED_HOME]] from [[HOME]]
@@ -601,7 +601,7 @@
 // XCHECK: bb0([[HOME:%[0-9]+]] : $APPHouse, [[DELTA:%[0-9]+]] : $Double):
 func updateFridgeTemp(_ home: APPHouse, delta: Double) {
   // +=
-  // XCHECK: [[PLUS_EQ:%[0-9]+]] = function_ref @_T0s2peoiySdz_SdtF
+  // XCHECK: [[PLUS_EQ:%[0-9]+]] = function_ref @_T0s2peoiyySdz_SdtF
 
   // Borrowed home
   // CHECK: [[BORROWED_HOME:%.*]] = begin_borrow [[HOME]]
@@ -612,7 +612,7 @@
   // Get operation
   // CHECK: [[GETTER:%[0-9]+]] = objc_method [[BORROWED_HOME]] : $APPHouse, #APPHouse.fridge!getter.1.foreign
   // CHECK: [[OBJC_FRIDGE:%[0-9]+]] = apply [[GETTER]]([[BORROWED_HOME]])
-  // CHECK: [[BRIDGE_FROM_FN:%[0-9]+]] = function_ref @_T010Appliances12RefrigeratorV36_unconditionallyBridgeFromObjectiveCACSo15APPRefrigeratorCSgFZ
+  // CHECK: [[BRIDGE_FROM_FN:%[0-9]+]] = function_ref @_T010Appliances12RefrigeratorV36_unconditionallyBridgeFromObjectiveCyACSo15APPRefrigeratorCSgFZ
   // CHECK: [[REFRIGERATOR_META:%[0-9]+]] = metatype $@thin Refrigerator.Type
   // CHECK: [[FRIDGE:%[0-9]+]] = apply [[BRIDGE_FROM_FN]]([[OBJC_FRIDGE]], [[REFRIGERATOR_META]])
 
@@ -632,7 +632,7 @@
   home.fridge.temperature += delta
 }
 
-// CHECK-LABEL: sil hidden @_T013objc_bridging20callNonStandardBlockySi5value_tF
+// CHECK-LABEL: sil hidden @_T013objc_bridging20callNonStandardBlock5valueySi_tF
 func callNonStandardBlock(value: Int) {
   // CHECK: enum $Optional<@convention(block) () -> @owned Optional<AnyObject>>
   takesNonStandardBlock { return value }
@@ -640,9 +640,9 @@
 
 func takeTwoAnys(_ lhs: Any, _ rhs: Any) -> Any { return lhs }
 
-// CHECK-LABEL: sil hidden @_T013objc_bridging22defineNonStandardBlockyyp1x_tF
+// CHECK-LABEL: sil hidden @_T013objc_bridging22defineNonStandardBlock1xyyp_tF
 func defineNonStandardBlock(x: Any) {
-  // CHECK: function_ref @_T013objc_bridging22defineNonStandardBlockyyp1x_tFypypcfU_
+  // CHECK: function_ref @_T013objc_bridging22defineNonStandardBlock1xyyp_tFypypcfU_
   // CHECK: function_ref @_T0ypypIegir_yXlyXlIeyBya_TR : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed (@in Any) -> @out Any, AnyObject) -> @autoreleased AnyObject
 
   let fn : @convention(block) (Any) -> Any = { y in takeTwoAnys(x, y) }
@@ -658,13 +658,13 @@
 // CHECK:   [[RESULT:%.*]] = alloc_stack $Any
 // CHECK:   apply {{.*}}([[RESULT]], [[ARG]])
 
-// CHECK-LABEL: sil hidden @_T013objc_bridging15castToCFunctionySV3ptr_tF : $@convention(thin) (UnsafeRawPointer) -> () {
+// CHECK-LABEL: sil hidden @_T013objc_bridging15castToCFunction3ptrySV_tF : $@convention(thin) (UnsafeRawPointer) -> () {
 func castToCFunction(ptr: UnsafeRawPointer) {
   // CHECK: [[OUT:%.*]] = alloc_stack $@convention(c) (Optional<AnyObject>) -> ()
   // CHECK: [[IN:%.]] = alloc_stack $UnsafeRawPointer
   // CHECK: store %0 to [trivial] [[IN]] : $*UnsafeRawPointer
   // CHECK: [[META:%.*]] = metatype $@thick (@convention(c) (Optional<AnyObject>) -> ()).Type
-  // CHECK: [[CASTFN:%.*]] = function_ref @_T0s13unsafeBitCastq_x_q_m2totr0_lF
+  // CHECK: [[CASTFN:%.*]] = function_ref @_T0s13unsafeBitCast_2toq_x_q_mtr0_lF
   // CHECK: apply [[CASTFN]]<UnsafeRawPointer, @convention(c) (AnyObject?) -> ()>([[OUT]], [[IN]], [[META]]) : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0, @thick τ_0_1.Type) -> @out τ_0_1
   // CHECK: [[RESULT:%.*]] = load [trivial] [[OUT]] : $*@convention(c) (Optional<AnyObject>) -> ()
   typealias Fn = @convention(c) (AnyObject?) -> Void
diff --git a/test/SILGen/objc_bridging_any.swift b/test/SILGen/objc_bridging_any.swift
index 74486a1..01a215f 100644
--- a/test/SILGen/objc_bridging_any.swift
+++ b/test/SILGen/objc_bridging_any.swift
@@ -138,7 +138,7 @@
   // CHECK:   [[ERROR_BOX:%[0-9]+]] = open_existential_box [[ERROR_COPY]] : $Error to $*@opened([[ERROR_ARCHETYPE:"[^"]*"]]) Error
   // CHECK:   [[ERROR_STACK:%[0-9]+]] = alloc_stack $@opened([[ERROR_ARCHETYPE]]) Error
   // CHECK:   copy_addr [[ERROR_BOX]] to [initialization] [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error
-  // CHECK:   [[BRIDGE_FUNCTION:%[0-9]+]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF
+  // CHECK:   [[BRIDGE_FUNCTION:%[0-9]+]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyyXlxlF
   // CHECK:   [[BRIDGED_ERROR:%[0-9]+]] = apply [[BRIDGE_FUNCTION]]<@opened([[ERROR_ARCHETYPE]]) Error>([[ERROR_STACK]])
   // CHECK:   dealloc_stack [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error
   // CHECK:   destroy_value [[ERROR_COPY]] : $Error
@@ -225,7 +225,7 @@
 // _bridgeAnythingToObjectiveC call.  That's not true anymore.
 func zim() {}
 struct Zang {}
-// CHECK-LABEL: sil hidden @_T017objc_bridging_any27typesWithNontrivialLoweringySo9NSIdLoverC8receiver_tF
+// CHECK-LABEL: sil hidden @_T017objc_bridging_any27typesWithNontrivialLowering8receiverySo9NSIdLoverC_tF
 func typesWithNontrivialLowering(receiver: NSIdLover) {
   // CHECK: apply {{.*}}<() -> ()>
   receiver.takesId(zim)
@@ -385,7 +385,7 @@
   // CHECK-NEXT: [[ERROR_BOX:%[0-9]+]] = open_existential_box [[ERROR_COPY]] : $Error to $*@opened([[ERROR_ARCHETYPE:"[^"]*"]]) Error
   // CHECK-NEXT: [[ERROR_STACK:%[0-9]+]] = alloc_stack $@opened([[ERROR_ARCHETYPE]]) Error
   // CHECK-NEXT: copy_addr [[ERROR_BOX]] to [initialization] [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error
-  // CHECK: [[BRIDGE_FUNCTION:%[0-9]+]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF
+  // CHECK: [[BRIDGE_FUNCTION:%[0-9]+]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyyXlxlF
   // CHECK-NEXT: [[BRIDGED_ERROR:%[0-9]+]] = apply [[BRIDGE_FUNCTION]]<@opened([[ERROR_ARCHETYPE]]) Error>([[ERROR_STACK]])
   // CHECK-NEXT: [[BRIDGED_ERROR_OPT:%[0-9]+]] = enum $Optional<AnyObject>, #Optional.some!enumelt.1, [[BRIDGED_ERROR]] : $AnyObject
   // CHECK-NEXT: dealloc_stack [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error
@@ -518,7 +518,7 @@
   // CHECK:       function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F
 
   @objc func methodTakingAny(a: Any) {}
-  // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC15methodTakingAnyyyp1a_tFTo : $@convention(objc_method) (AnyObject, SwiftIdLover) -> ()
+  // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC15methodTakingAny1ayyp_tFTo : $@convention(objc_method) (AnyObject, SwiftIdLover) -> ()
   // CHECK:     bb0([[ARG:%.*]] : @unowned $AnyObject, [[SELF:%.*]] : @unowned $SwiftIdLover):
   // CHECK-NEXT:  [[ARG_COPY:%.*]] = copy_value [[ARG]]
   // CHECK-NEXT:  [[SELF_COPY:%.*]] = copy_value [[SELF]]
@@ -528,7 +528,7 @@
   // CHECK-NEXT:  store [[OPENED_SELF]] to [init] [[INIT]]
   // CHECK-NEXT:  [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
   // CHECK-NEXT:  // function_ref
-  // CHECK-NEXT:  [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC15methodTakingAnyyyp1a_tF
+  // CHECK-NEXT:  [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC15methodTakingAny1ayyp_tF
   // CHECK-NEXT:  apply [[METHOD]]([[RESULT]], [[BORROWED_SELF_COPY]])
   // CHECK-NEXT:  end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
   // CHECK-NEXT:  dealloc_stack [[RESULT]]
@@ -536,13 +536,13 @@
   // CHECK-NEXT:  return
 
   func methodTakingOptionalAny(a: Any?) {}
-  // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC23methodTakingOptionalAnyyypSg1a_tF
+  // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC23methodTakingOptionalAny1ayypSg_tF
 
-  // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC23methodTakingOptionalAnyyypSg1a_tFTo
+  // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC23methodTakingOptionalAny1ayypSg_tFTo
 
-  // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyypcF : $@convention(method) (@owned @noescape @callee_guaranteed (@in Any) -> (), @guaranteed SwiftIdLover) -> ()
+  // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyyypcF : $@convention(method) (@owned @noescape @callee_guaranteed (@in Any) -> (), @guaranteed SwiftIdLover) -> ()
 
-  // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyypcFTo : $@convention(objc_method) (@convention(block) @noescape (AnyObject) -> (), SwiftIdLover) -> ()
+  // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyyypcFTo : $@convention(objc_method) (@convention(block) @noescape (AnyObject) -> (), SwiftIdLover) -> ()
   // CHECK:    bb0([[BLOCK:%.*]] : @unowned $@convention(block) @noescape (AnyObject) -> (), [[SELF:%.*]] : @unowned $SwiftIdLover):
   // CHECK-NEXT:  [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
   // CHECK-NEXT:  [[SELF_COPY:%.*]] = copy_value [[SELF]]
@@ -551,7 +551,7 @@
   // CHECK-NEXT:  [[THUNK_CVT:%.*]] = convert_function [[THUNK]]
   // CHECK:       [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
   // CHECK-NEXT:  // function_ref
-  // CHECK-NEXT:  [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyypcF
+  // CHECK-NEXT:  [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyyypcF
   // CHECK-NEXT:  [[RESULT:%.*]] = apply [[METHOD]]([[THUNK_CVT]], [[BORROWED_SELF_COPY]])
   // CHECK-NEXT:  end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
   // CHECK-NEXT:  destroy_value [[SELF_COPY]]
@@ -616,9 +616,9 @@
 
   @objc func methodReturningBlockTakingAny() -> ((Any) -> ()) {}
 
-  // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyypycF : $@convention(method) (@owned @noescape @callee_guaranteed () -> @out Any, @guaranteed SwiftIdLover) -> () {
+  // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyyypycF : $@convention(method) (@owned @noescape @callee_guaranteed () -> @out Any, @guaranteed SwiftIdLover) -> () {
 
-  // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyypycFTo : $@convention(objc_method) (@convention(block) @noescape () -> @autoreleased AnyObject, SwiftIdLover) -> ()
+  // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyyypycFTo : $@convention(objc_method) (@convention(block) @noescape () -> @autoreleased AnyObject, SwiftIdLover) -> ()
   // CHECK:     bb0([[BLOCK:%.*]] : @unowned $@convention(block) @noescape () -> @autoreleased AnyObject, [[ANY:%.*]] : @unowned $SwiftIdLover):
   // CHECK-NEXT:  [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
   // CHECK-NEXT:  [[ANY_COPY:%.*]] = copy_value [[ANY]]
@@ -628,7 +628,7 @@
   // CHECK-NEXT:  [[THUNK_CVT:%.*]] = convert_function [[THUNK]]
   // CHECK-NEXT:  [[BORROWED_ANY_COPY:%.*]] = begin_borrow [[ANY_COPY]]
   // CHECK-NEXT:  // function_ref
-  // CHECK-NEXT:  [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyypycF
+  // CHECK-NEXT:  [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyyypycF
   // CHECK-NEXT:  [[RESULT:%.*]] = apply [[METHOD]]([[THUNK_CVT]], [[BORROWED_ANY_COPY]])
   // CHECK-NEXT:  end_borrow [[BORROWED_ANY_COPY]] from [[ANY_COPY]]
   // CHECK-NEXT:  destroy_value [[ANY_COPY]]
@@ -717,7 +717,7 @@
 }
 
 extension GenericClass {
-  // CHECK-LABEL: sil hidden @_T0So12GenericClassC17objc_bridging_anyE23pseudogenericAnyErasureypx1x_tF :
+  // CHECK-LABEL: sil hidden @_T0So12GenericClassC17objc_bridging_anyE23pseudogenericAnyErasure1xypx_tF :
   func pseudogenericAnyErasure(x: T) -> Any {
     // CHECK: bb0([[ANY_OUT:%.*]] : @trivial $*Any, [[ARG:%.*]] : @owned $T, [[SELF:%.*]] : @guaranteed $GenericClass<T>
     // CHECK:   [[ANY_BUF:%.*]] = init_existential_addr [[ANY_OUT]] : $*Any, $AnyObject
@@ -729,20 +729,20 @@
     // CHECK:   destroy_value [[ARG]]
     return x
   }
-  // CHECK: } // end sil function '_T0So12GenericClassC17objc_bridging_anyE23pseudogenericAnyErasureypx1x_tF'
+  // CHECK: } // end sil function '_T0So12GenericClassC17objc_bridging_anyE23pseudogenericAnyErasure1xypx_tF'
 }
 
 // Make sure AnyHashable erasure marks Hashable conformance as used
 class AnyHashableClass : NSObject {
   // CHECK-LABEL: sil hidden @_T017objc_bridging_any16AnyHashableClassC07returnsdE0s0dE0VyF
-  // CHECK: [[FN:%.*]] = function_ref @_T0s21_convertToAnyHashables0cD0Vxs0D0RzlF
+  // CHECK: [[FN:%.*]] = function_ref @_T0s21_convertToAnyHashableys0cD0Vxs0D0RzlF
   // CHECK: apply [[FN]]<GenericOption>({{.*}})
   func returnsAnyHashable() -> AnyHashable {
     return GenericOption.multithreaded
   }
 }
 
-// CHECK-LABEL: sil hidden @_T017objc_bridging_any33bridgeOptionalFunctionToAnyObjectyXlyycSg2fn_tF : $@convention(thin) (@owned Optional<@callee_guaranteed () -> ()>) -> @owned AnyObject
+// CHECK-LABEL: sil hidden @_T017objc_bridging_any33bridgeOptionalFunctionToAnyObject2fnyXlyycSg_tF : $@convention(thin) (@owned Optional<@callee_guaranteed () -> ()>) -> @owned AnyObject
 // CHECK: [[BRIDGE:%.*]] = function_ref @_T0Sq19_bridgeToObjectiveCyXlyF
 // CHECK: [[FN:%.*]] = function_ref @_T0Ieg_ytytIegir_TR
 // CHECK: partial_apply [callee_guaranteed] [[FN]]
diff --git a/test/SILGen/objc_bridging_peephole.swift b/test/SILGen/objc_bridging_peephole.swift
index 8644a41..0355ecb 100644
--- a/test/SILGen/objc_bridging_peephole.swift
+++ b/test/SILGen/objc_bridging_peephole.swift
@@ -15,13 +15,13 @@
 
 /*** Return values ***********************************************************/
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole16testMethodResultySo10DummyClassC5dummy_tF
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole16testMethodResult5dummyySo10DummyClassC_tF
 func testMethodResult(dummy: DummyClass) {
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK-NEXT: [[METHOD:%.*]] = objc_method
   // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]])
   // CHECK-NEXT: end_borrow [[SELF]] from %0
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole8useOptNSySo8NSStringCSgF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole8useOptNSyySo8NSStringCSgF
   // CHECK-NEXT: apply [[USE]]([[RESULT]])
   useOptNS(dummy.fetchNullableString() as NSString?)
 
@@ -29,7 +29,7 @@
   // CHECK-NEXT: [[METHOD:%.*]] = objc_method
   // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]])
   // CHECK-NEXT: end_borrow [[SELF]] from %0
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole8useOptNSySo8NSStringCSgF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole8useOptNSyySo8NSStringCSgF
   // CHECK-NEXT: apply [[USE]]([[RESULT]])
   useOptNS(dummy.fetchNullproneString() as NSString?)
 
@@ -37,7 +37,7 @@
   // CHECK-NEXT: [[METHOD:%.*]] = objc_method
   // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]])
   // CHECK-NEXT: end_borrow [[SELF]] from %0
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole8useOptNSySo8NSStringCSgF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole8useOptNSyySo8NSStringCSgF
   // CHECK-NEXT: apply [[USE]]([[RESULT]])
   useOptNS(dummy.fetchNonnullString() as NSString?)
 
@@ -46,7 +46,7 @@
   // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]])
   // CHECK-NEXT: end_borrow [[SELF]] from %0
   // CHECK-NEXT: [[ANYOBJECT:%.*]] = unchecked_ref_cast [[RESULT]] : $Optional<NSString> to $Optional<AnyObject>
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole15useOptAnyObjectyyXlSgF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole15useOptAnyObjectyyyXlSgF
   // CHECK-NEXT: apply [[USE]]([[ANYOBJECT]])
   useOptAnyObject(dummy.fetchNullableString() as AnyObject?)
 
@@ -55,7 +55,7 @@
   // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]])
   // CHECK-NEXT: end_borrow [[SELF]] from %0
   // CHECK-NEXT: [[ANYOBJECT:%.*]] = unchecked_ref_cast [[RESULT]] : $Optional<NSString> to $Optional<AnyObject>
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole15useOptAnyObjectyyXlSgF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole15useOptAnyObjectyyyXlSgF
   // CHECK-NEXT: apply [[USE]]([[ANYOBJECT]])
   useOptAnyObject(dummy.fetchNullproneString() as AnyObject?)
 
@@ -64,14 +64,14 @@
   // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]])
   // CHECK-NEXT: end_borrow [[SELF]] from %0
   // CHECK-NEXT: [[ANYOBJECT:%.*]] = unchecked_ref_cast [[RESULT]] : $Optional<NSString> to $Optional<AnyObject>
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole15useOptAnyObjectyyXlSgF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole15useOptAnyObjectyyyXlSgF
   // CHECK-NEXT: apply [[USE]]([[ANYOBJECT]])
   useOptAnyObject(dummy.fetchNonnullString() as AnyObject?)
 
   // CHECK:      return
 }
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole23testNonNullMethodResultySo10DummyClassC5dummy_tF
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole23testNonNullMethodResult5dummyySo10DummyClassC_tF
 func testNonNullMethodResult(dummy: DummyClass) {
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK-NEXT: [[METHOD:%.*]] = objc_method
@@ -79,9 +79,9 @@
   // CHECK-NEXT: end_borrow [[SELF]] from %0
   // CHECK-NEXT: switch_enum [[RESULT]]
   // CHECK:    bb1:
-  // CHECK:      function_ref @_T0s30_diagnoseUnexpectedNilOptionalyBp14_filenameStart_Bw01_E6LengthBi1_01_E7IsASCIIBw5_linetF
+  // CHECK:      function_ref @_T0s30_diagnoseUnexpectedNilOptional14_filenameStart01_E6Length01_E7IsASCII5_lineyBp_BwBi1_BwtF
   // CHECK:    bb2([[RESULT:%.*]] : @owned $NSString):
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole5useNSySo8NSStringCF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole5useNSyySo8NSStringCF
   // CHECK-NEXT: apply [[USE]]([[RESULT]])
   useNS(dummy.fetchNonnullString() as NSString)
 
@@ -91,17 +91,17 @@
   // CHECK-NEXT: end_borrow [[SELF]] from %0
   // CHECK-NEXT: switch_enum [[RESULT]]
   // CHECK:    bb3:
-  // CHECK:      function_ref @_T0s30_diagnoseUnexpectedNilOptionalyBp14_filenameStart_Bw01_E6LengthBi1_01_E7IsASCIIBw5_linetF
+  // CHECK:      function_ref @_T0s30_diagnoseUnexpectedNilOptional14_filenameStart01_E6Length01_E7IsASCII5_lineyBp_BwBi1_BwtF
   // CHECK:    bb4([[RESULT:%.*]] : @owned $NSString):
   // CHECK-NEXT: [[ANYOBJECT:%.*]] = init_existential_ref [[RESULT]] : $NSString : $NSString, $AnyObject
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole12useAnyObjectyyXlF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole12useAnyObjectyyyXlF
   // CHECK-NEXT: apply [[USE]]([[ANYOBJECT]])
   useAnyObject(dummy.fetchNonnullString() as AnyObject)
 
   // CHECK:      return
 }
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole22testForcedMethodResultySo10DummyClassC5dummy_tF
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole22testForcedMethodResult5dummyySo10DummyClassC_tF
 func testForcedMethodResult(dummy: DummyClass) {
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK-NEXT: [[METHOD:%.*]] = objc_method
@@ -109,9 +109,9 @@
   // CHECK-NEXT: end_borrow [[SELF]] from %0
   // CHECK-NEXT: switch_enum [[RESULT]]
   // CHECK:    bb1:
-  // CHECK:      function_ref @_T0s30_diagnoseUnexpectedNilOptionalyBp14_filenameStart_Bw01_E6LengthBi1_01_E7IsASCIIBw5_linetF
+  // CHECK:      function_ref @_T0s30_diagnoseUnexpectedNilOptional14_filenameStart01_E6Length01_E7IsASCII5_lineyBp_BwBi1_BwtF
   // CHECK:    bb2([[RESULT:%.*]] : @owned $NSString):
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole5useNSySo8NSStringCF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole5useNSyySo8NSStringCF
   // CHECK-NEXT: apply [[USE]]([[RESULT]])
   useNS(dummy.fetchNullproneString() as NSString)
 
@@ -123,7 +123,7 @@
   // CHECK-NEXT: end_borrow [[SELF]] from %0
   // CHECK-NEXT: switch_enum [[RESULT]]
   // CHECK:    bb3([[RESULT:%.*]] : @owned $NSString):
-  // CHECK:      function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+  // CHECK:      function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
   // CHECK:    bb4:
   // CHECK:      enum $Optional<String>, #Optional.none
   // CHECK:    bb5([[OPTSTRING:%.*]] : @owned $Optional<String>):
@@ -132,7 +132,7 @@
   // CHECK-NEXT: [[BORROW:%.*]] = begin_borrow [[OPTSTRING]]
   // CHECK-NEXT: store_borrow [[BORROW]] to [[TEMP]] : $*Optional<String>
   // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE]]<String>([[TEMP]])
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole12useAnyObjectyyXlF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole12useAnyObjectyyyXlF
   // CHECK-NEXT: apply [[USE]]([[ANYOBJECT]])
   // CHECK-NEXT: end_borrow [[BORROW]] from [[OPTSTRING]]
   // CHECK-NEXT: dealloc_stack [[TEMP]]
@@ -143,12 +143,12 @@
 
 /*** Property loads **********************************************************/
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole17testPropertyValueySo10DummyClassC5dummy_tF
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole17testPropertyValue5dummyySo10DummyClassC_tF
 func testPropertyValue(dummy: DummyClass) {
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK-NEXT: [[METHOD:%.*]] = objc_method
   // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]])
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole8useOptNSySo8NSStringCSgF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole8useOptNSyySo8NSStringCSgF
   // CHECK-NEXT: apply [[USE]]([[RESULT]])
   // CHECK-NEXT: end_borrow [[SELF]] from %0
   useOptNS(dummy.nullableStringProperty as NSString?)
@@ -156,7 +156,7 @@
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK-NEXT: [[METHOD:%.*]] = objc_method
   // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]])
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole8useOptNSySo8NSStringCSgF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole8useOptNSyySo8NSStringCSgF
   // CHECK-NEXT: apply [[USE]]([[RESULT]])
   // CHECK-NEXT: end_borrow [[SELF]] from %0
   useOptNS(dummy.nullproneStringProperty as NSString?)
@@ -164,7 +164,7 @@
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK-NEXT: [[METHOD:%.*]] = objc_method
   // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]])
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole8useOptNSySo8NSStringCSgF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole8useOptNSyySo8NSStringCSgF
   // CHECK-NEXT: apply [[USE]]([[RESULT]])
   // CHECK-NEXT: end_borrow [[SELF]] from %0
   useOptNS(dummy.nonnullStringProperty as NSString?)
@@ -173,7 +173,7 @@
   // CHECK-NEXT: [[METHOD:%.*]] = objc_method
   // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]])
   // CHECK-NEXT: [[ANYOBJECT:%.*]] = unchecked_ref_cast [[RESULT]] : $Optional<NSString> to $Optional<AnyObject>
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole15useOptAnyObjectyyXlSgF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole15useOptAnyObjectyyyXlSgF
   // CHECK-NEXT: apply [[USE]]([[ANYOBJECT]])
   // CHECK-NEXT: end_borrow [[SELF]] from %0
   useOptAnyObject(dummy.nullableStringProperty as AnyObject?)
@@ -182,7 +182,7 @@
   // CHECK-NEXT: [[METHOD:%.*]] = objc_method
   // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]])
   // CHECK-NEXT: [[ANYOBJECT:%.*]] = unchecked_ref_cast [[RESULT]] : $Optional<NSString> to $Optional<AnyObject>
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole15useOptAnyObjectyyXlSgF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole15useOptAnyObjectyyyXlSgF
   // CHECK-NEXT: apply [[USE]]([[ANYOBJECT]])
   // CHECK-NEXT: end_borrow [[SELF]] from %0
   useOptAnyObject(dummy.nullproneStringProperty as AnyObject?)
@@ -191,7 +191,7 @@
   // CHECK-NEXT: [[METHOD:%.*]] = objc_method
   // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]])
   // CHECK-NEXT: [[ANYOBJECT:%.*]] = unchecked_ref_cast [[RESULT]] : $Optional<NSString> to $Optional<AnyObject>
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole15useOptAnyObjectyyXlSgF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole15useOptAnyObjectyyyXlSgF
   // CHECK-NEXT: apply [[USE]]([[ANYOBJECT]])
   // CHECK-NEXT: end_borrow [[SELF]] from %0
   useOptAnyObject(dummy.nonnullStringProperty as AnyObject?)
@@ -199,16 +199,16 @@
   // CHECK:      return
 }
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole24testNonNullPropertyValueySo10DummyClassC5dummy_tF
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole24testNonNullPropertyValue5dummyySo10DummyClassC_tF
 func testNonNullPropertyValue(dummy: DummyClass) {
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK-NEXT: [[METHOD:%.*]] = objc_method
   // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]])
   // CHECK-NEXT: switch_enum [[RESULT]]
   // CHECK:    bb1:
-  // CHECK:      function_ref @_T0s30_diagnoseUnexpectedNilOptionalyBp14_filenameStart_Bw01_E6LengthBi1_01_E7IsASCIIBw5_linetF
+  // CHECK:      function_ref @_T0s30_diagnoseUnexpectedNilOptional14_filenameStart01_E6Length01_E7IsASCII5_lineyBp_BwBi1_BwtF
   // CHECK:    bb2([[RESULT:%.*]] : @owned $NSString):
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole5useNSySo8NSStringCF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole5useNSyySo8NSStringCF
   // CHECK-NEXT: apply [[USE]]([[RESULT]])
   // CHECK-NEXT: end_borrow [[SELF]] from %0
   useNS(dummy.nonnullStringProperty as NSString)
@@ -218,10 +218,10 @@
   // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]])
   // CHECK-NEXT: switch_enum [[RESULT]]
   // CHECK:    bb3:
-  // CHECK:      function_ref @_T0s30_diagnoseUnexpectedNilOptionalyBp14_filenameStart_Bw01_E6LengthBi1_01_E7IsASCIIBw5_linetF
+  // CHECK:      function_ref @_T0s30_diagnoseUnexpectedNilOptional14_filenameStart01_E6Length01_E7IsASCII5_lineyBp_BwBi1_BwtF
   // CHECK:    bb4([[RESULT:%.*]] : @owned $NSString):
   // CHECK-NEXT: [[ANYOBJECT:%.*]] = init_existential_ref [[RESULT]] : $NSString : $NSString, $AnyObject
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole12useAnyObjectyyXlF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole12useAnyObjectyyyXlF
   // CHECK-NEXT: apply [[USE]]([[ANYOBJECT]])
   // CHECK-NEXT: end_borrow [[SELF]] from %0
   useAnyObject(dummy.nonnullStringProperty as AnyObject)
@@ -229,16 +229,16 @@
   // CHECK:      return
 }
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole23testForcedPropertyValueySo10DummyClassC5dummy_tF
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole23testForcedPropertyValue5dummyySo10DummyClassC_tF
 func testForcedPropertyValue(dummy: DummyClass) {
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK-NEXT: [[METHOD:%.*]] = objc_method
   // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]])
   // CHECK-NEXT: switch_enum [[RESULT]]
   // CHECK:    bb1:
-  // CHECK:      function_ref @_T0s30_diagnoseUnexpectedNilOptionalyBp14_filenameStart_Bw01_E6LengthBi1_01_E7IsASCIIBw5_linetF
+  // CHECK:      function_ref @_T0s30_diagnoseUnexpectedNilOptional14_filenameStart01_E6Length01_E7IsASCII5_lineyBp_BwBi1_BwtF
   // CHECK:    bb2([[RESULT:%.*]] : @owned $NSString):
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole5useNSySo8NSStringCF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole5useNSyySo8NSStringCF
   // CHECK-NEXT: apply [[USE]]([[RESULT]])
   // CHECK-NEXT: end_borrow [[SELF]] from %0
   useNS(dummy.nullproneStringProperty as NSString)
@@ -250,7 +250,7 @@
   // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF]])
   // CHECK-NEXT: switch_enum [[RESULT]]
   // CHECK:    bb3([[RESULT:%.*]] : @owned $NSString):
-  // CHECK:      function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+  // CHECK:      function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
   // CHECK:    bb4:
   // CHECK:      enum $Optional<String>, #Optional.none
   // CHECK:    bb5([[OPTSTRING:%.*]] : @owned $Optional<String>):
@@ -259,7 +259,7 @@
   // CHECK-NEXT: [[BORROW:%.*]] = begin_borrow [[OPTSTRING]]
   // CHECK-NEXT: store_borrow [[BORROW]] to [[TEMP]] : $*Optional<String>
   // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE]]<String>([[TEMP]])
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole12useAnyObjectyyXlF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole12useAnyObjectyyyXlF
   // CHECK-NEXT: apply [[USE]]([[ANYOBJECT]])
   // CHECK-NEXT: end_borrow [[BORROW]] from [[OPTSTRING]]
   // CHECK-NEXT: dealloc_stack [[TEMP]]
@@ -274,29 +274,29 @@
 
 // FIXME: apply peepholes to indices, too!
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole23testNonnullSubscriptGetySo0eF0C6object_yXl5indextF
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole23testNonnullSubscriptGet6object5indexySo0eF0C_yXltF
 func testNonnullSubscriptGet(object: NonnullSubscript, index: AnyObject) {
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
-  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF
+  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyyXlxlF
   // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]]
   // CHECK:      [[METHOD:%.*]] = objc_method
   // CHECK:      [[RESULT:%.*]] = apply [[METHOD]]([[INDEX]], [[SELF]])
   // CHECK-NEXT: destroy_value [[INDEX]] : $AnyObject
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole8useOptNSySo8NSStringCSgF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole8useOptNSyySo8NSStringCSgF
   // CHECK-NEXT: apply [[USE]]([[RESULT]])
   // CHECK:      end_borrow [[SELF]] from %0
   useOptNS(object[index] as NSString?)
 
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
-  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF
+  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyyXlxlF
   // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]]
   // CHECK:      [[METHOD:%.*]] = objc_method
   // CHECK:      [[RESULT:%.*]] = apply [[METHOD]]([[INDEX]], [[SELF]])
   // CHECK-NEXT: destroy_value [[INDEX]] : $AnyObject
   // CHECK-NEXT: switch_enum [[RESULT]]
-  // CHECK:      function_ref @_T0s30_diagnoseUnexpectedNilOptionalyBp14_filenameStart
+  // CHECK:      function_ref @_T0s30_diagnoseUnexpectedNilOptional14_filenameStart01_E6Length01_E7IsASCII5_lineyBp_BwBi1_BwtF
   // CHECK:    bb{{[0-9]+}}([[RESULT:%.*]] : @owned $NSString):
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole5useNSySo8NSStringCF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole5useNSyySo8NSStringCF
   // CHECK-NEXT: apply [[USE]]([[RESULT]])
   // CHECK:      end_borrow [[SELF]] from %0
   useNS(object[index] as NSString)
@@ -304,15 +304,15 @@
   // CHECK:      return
 }
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole24testNullableSubscriptGetySo0eF0C6object_yXl5indextF
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole24testNullableSubscriptGet6object5indexySo0eF0C_yXltF
 func testNullableSubscriptGet(object: NullableSubscript, index: AnyObject) {
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
-  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF
+  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyyXlxlF
   // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]]
   // CHECK:      [[METHOD:%.*]] = objc_method
   // CHECK:      [[RESULT:%.*]] = apply [[METHOD]]([[INDEX]], [[SELF]])
   // CHECK-NEXT: destroy_value [[INDEX]] : $AnyObject
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole8useOptNSySo8NSStringCSgF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole8useOptNSyySo8NSStringCSgF
   // CHECK-NEXT: apply [[USE]]([[RESULT]])
   // CHECK:      end_borrow [[SELF]] from %0
   useOptNS(object[index] as NSString?)
@@ -320,29 +320,29 @@
   // CHECK:      return
 }
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole25testNullproneSubscriptGetySo0eF0C6object_yXl5indextF
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole25testNullproneSubscriptGet6object5indexySo0eF0C_yXltF
 func testNullproneSubscriptGet(object: NullproneSubscript, index: AnyObject) {
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
-  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF
+  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyyXlxlF
   // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]]
   // CHECK:      [[METHOD:%.*]] = objc_method
   // CHECK:      [[RESULT:%.*]] = apply [[METHOD]]([[INDEX]], [[SELF]])
   // CHECK-NEXT: destroy_value [[INDEX]] : $AnyObject
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole8useOptNSySo8NSStringCSgF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole8useOptNSyySo8NSStringCSgF
   // CHECK-NEXT: apply [[USE]]([[RESULT]])
   // CHECK:      end_borrow [[SELF]] from %0
   useOptNS(object[index] as NSString?)
 
   // CHECK-NEXT: [[SELF:%.*]] = begin_borrow %0
-  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF
+  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyyXlxlF
   // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]]
   // CHECK:      [[METHOD:%.*]] = objc_method
   // CHECK:      [[RESULT:%.*]] = apply [[METHOD]]([[INDEX]], [[SELF]])
   // CHECK-NEXT: destroy_value [[INDEX]] : $AnyObject
   // CHECK-NEXT: switch_enum [[RESULT]]
-  // CHECK:      function_ref @_T0s30_diagnoseUnexpectedNilOptionalyBp14_filenameStart
+  // CHECK:      function_ref @_T0s30_diagnoseUnexpectedNilOptional14_filenameStart01_E6Length01_E7IsASCII5_lineyBp_BwBi1_BwtF
   // CHECK:    bb{{[0-9]+}}([[RESULT:%.*]] : @owned $NSString):
-  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole5useNSySo8NSStringCF
+  // CHECK:      [[USE:%.*]] = function_ref @_T022objc_bridging_peephole5useNSyySo8NSStringCF
   // CHECK-NEXT: apply [[USE]]([[RESULT]])
   // CHECK:      end_borrow [[SELF]] from %0
   useNS(object[index] as NSString)
@@ -352,7 +352,7 @@
 
 /*** Call arguments **********************************************************/
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole18testMethodArgumentySo10DummyClassC5dummy_tF 
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole18testMethodArgument5dummyySo10DummyClassC_tF
 func testMethodArgument(dummy: DummyClass) {
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK-NEXT: // function_ref
@@ -389,7 +389,7 @@
   // CHECK:      return
 }
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole28testValueToOptMethodArgumentySo10DummyClassC5dummy_tF
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole28testValueToOptMethodArgument5dummyySo10DummyClassC_tF
 func testValueToOptMethodArgument(dummy: DummyClass) {
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK-NEXT: // function_ref
@@ -416,7 +416,7 @@
   // CHECK:      return
 }
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole09testOptToE14MethodArgumentySo10DummyClassC5dummy_tF
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole09testOptToE14MethodArgument5dummyySo10DummyClassC_tF
 func testOptToOptMethodArgument(dummy: DummyClass) {
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK-NEXT: // function_ref
@@ -443,7 +443,7 @@
 
 /*** Property assignments ****************************************************/
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole18testPropertySetterySo10DummyClassC5dummy_tF 
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole18testPropertySetter5dummyySo10DummyClassC_tF
 func testPropertySetter(dummy: DummyClass) {
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK-NEXT: // function_ref
@@ -480,7 +480,7 @@
   // CHECK:      return
 }
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole28testValueToOptPropertySetterySo10DummyClassC5dummy_tF
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole28testValueToOptPropertySetter5dummyySo10DummyClassC_tF
 func testValueToOptPropertySetter(dummy: DummyClass) {
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK-NEXT: // function_ref
@@ -507,7 +507,7 @@
   // CHECK:      return
 }
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole09testOptToE14PropertySetterySo10DummyClassC5dummy_tF
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole09testOptToE14PropertySetter5dummyySo10DummyClassC_tF
 func testOptToOptPropertySetter(dummy: DummyClass) {
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK-NEXT: // function_ref
@@ -536,12 +536,12 @@
 
 // FIXME: apply peepholes to indices, too!
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole23testNonnullSubscriptSetySo0eF0C6object_yXl5indextF
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole23testNonnullSubscriptSet6object5indexySo0eF0C_yXltF
 func testNonnullSubscriptSet(object: NonnullSubscript, index: AnyObject) {
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK:      [[MAKE:%.*]] = function_ref @_T022objc_bridging_peephole6makeNSSo8NSStringCyF
   // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]()
-  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF
+  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyyXlxlF
   // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]]
   // CHECK:      [[METHOD:%.*]] = objc_method
   // CHECK:      apply [[METHOD]]([[ARG]], [[INDEX]], [[SELF]])
@@ -553,13 +553,13 @@
   // CHECK:      return
 }
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole24testNullableSubscriptSetySo0eF0C6object_yXl5indextF
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole24testNullableSubscriptSet6object5indexySo0eF0C_yXltF
 func testNullableSubscriptSet(object: NullableSubscript, index: AnyObject) {
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK:      [[MAKE:%.*]] = function_ref @_T022objc_bridging_peephole6makeNSSo8NSStringCyF
   // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]()
   // CHECK-NEXT: [[OPTARG:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[ARG]]
-  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF
+  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyyXlxlF
   // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]]
   // CHECK:      [[METHOD:%.*]] = objc_method
   // CHECK:      apply [[METHOD]]([[OPTARG]], [[INDEX]], [[SELF]])
@@ -572,7 +572,7 @@
   // CHECK:      [[MAKE:%.*]] = function_ref @_T022objc_bridging_peephole6makeNSSo8NSStringCyF
   // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]()
   // CHECK-NEXT: [[OPTARG:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[ARG]]
-  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF
+  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyyXlxlF
   // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]]
   // CHECK:      [[METHOD:%.*]] = objc_method
   // CHECK:      apply [[METHOD]]([[OPTARG]], [[INDEX]], [[SELF]])
@@ -584,7 +584,7 @@
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK:      [[MAKE:%.*]] = function_ref @_T022objc_bridging_peephole9makeOptNSSo8NSStringCSgyF
   // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]()
-  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF
+  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyyXlxlF
   // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]]
   // CHECK:      [[METHOD:%.*]] = objc_method
   // CHECK:      apply [[METHOD]]([[ARG]], [[INDEX]], [[SELF]])
@@ -596,13 +596,13 @@
   // CHECK:      return
 }
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole25testNullproneSubscriptSetySo0eF0C6object_yXl5indextF 
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole25testNullproneSubscriptSet6object5indexySo0eF0C_yXltF
 func testNullproneSubscriptSet(object: NullproneSubscript, index: AnyObject) {
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK:      [[MAKE:%.*]] = function_ref @_T022objc_bridging_peephole6makeNSSo8NSStringCyF
   // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]()
   // CHECK-NEXT: [[OPTARG:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[ARG]]
-  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF
+  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyyXlxlF
   // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]]
   // CHECK:      [[METHOD:%.*]] = objc_method
   // CHECK:      apply [[METHOD]]([[OPTARG]], [[INDEX]], [[SELF]])
@@ -615,7 +615,7 @@
   // CHECK:      [[MAKE:%.*]] = function_ref @_T022objc_bridging_peephole6makeNSSo8NSStringCyF
   // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]()
   // CHECK-NEXT: [[OPTARG:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[ARG]]
-  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF
+  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyyXlxlF
   // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]]
   // CHECK:      [[METHOD:%.*]] = objc_method
   // CHECK:      apply [[METHOD]]([[OPTARG]], [[INDEX]], [[SELF]])
@@ -627,7 +627,7 @@
   // CHECK:      [[SELF:%.*]] = begin_borrow %0
   // CHECK:      [[MAKE:%.*]] = function_ref @_T022objc_bridging_peephole9makeOptNSSo8NSStringCSgyF
   // CHECK-NEXT: [[ARG:%.*]] = apply [[MAKE]]()
-  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF
+  // CHECK:      [[BRIDGE_TO_ID:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyyXlxlF
   // CHECK-NEXT: [[INDEX:%.*]] = apply [[BRIDGE_TO_ID]]
   // CHECK:      [[METHOD:%.*]] = objc_method
   // CHECK:      apply [[METHOD]]([[ARG]], [[INDEX]], [[SELF]])
@@ -654,13 +654,13 @@
 // CHECK-LABEL: sil hidden @_T022objc_bridging_peephole017testOptionalToNonE6BridgeyyF
 func testOptionalToNonOptionalBridge() {
   // CHECK: apply {{.*}}() : $@convention(c) () -> @autoreleased Optional<AnyObject>
-  // CHECK: function_ref @_T0s018_bridgeAnyObjectToB0ypyXlSgF :
+  // CHECK: function_ref @_T0s018_bridgeAnyObjectToB0yypyXlSgF :
   // CHECK: [[T0:%.*]] = function_ref @_T0Sq19_bridgeToObjectiveCyXlyF
   // CHECK: apply [[T0]]<Any>
   useAnyObject(returnNullableId() as AnyObject)
 } // CHECK: end sil function '_T022objc_bridging_peephole017testOptionalToNonE6BridgeyyF'
 
-// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole34testBlockToOptionalAnyObjectBridgeyyyXB5block_tF
+// CHECK-LABEL: sil hidden @_T022objc_bridging_peephole34testBlockToOptionalAnyObjectBridge5blockyyyXB_tF
 func testBlockToOptionalAnyObjectBridge(block: @escaping @convention(block) () -> ()) {
   // CHECK:      [[T0:%.*]] = begin_borrow {{%.*}} : $@convention(block) () -> ()
   // CHECK-NEXT: [[T1:%.*]] = copy_value [[T0]]
diff --git a/test/SILGen/objc_currying.swift b/test/SILGen/objc_currying.swift
index eeab932..b721fad 100644
--- a/test/SILGen/objc_currying.swift
+++ b/test/SILGen/objc_currying.swift
@@ -10,19 +10,19 @@
 func curry_pod(_ x: CurryTest) -> (Int) -> Int {
   return x.pod
 }
-// CHECK-LABEL: sil hidden @_T013objc_currying9curry_podS2icSo9CurryTestCF : $@convention(thin) (@owned CurryTest) -> @owned @callee_guaranteed (Int) -> Int
+// CHECK-LABEL: sil hidden @_T013objc_currying9curry_podyS2icSo9CurryTestCF : $@convention(thin) (@owned CurryTest) -> @owned @callee_guaranteed (Int) -> Int
 // CHECK:      bb0([[ARG1:%.*]] : @owned $CurryTest):
 // CHECK:         [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
 // CHECK:         [[COPIED_ARG1:%.*]] = copy_value [[BORROWED_ARG1]]
-// CHECK:         [[THUNK:%.*]] = function_ref @[[THUNK_FOO_1:_T0So9CurryTestC3podS2iFTcTO]] : $@convention(thin) (@owned CurryTest) -> @owned @callee_guaranteed (Int) -> Int
+// CHECK:         [[THUNK:%.*]] = function_ref @[[THUNK_FOO_1:_T0So9CurryTestC3podyS2iFTcTO]] : $@convention(thin) (@owned CurryTest) -> @owned @callee_guaranteed (Int) -> Int
 // CHECK:         [[FN:%.*]] = apply [[THUNK]]([[COPIED_ARG1]])
 // CHECK:         end_borrow [[BORROWED_ARG1]] from [[ARG1]]
 // CHECK:         destroy_value [[ARG1]]
 // CHECK:         return [[FN]]
-// CHECK: } // end sil function '_T013objc_currying9curry_podS2icSo9CurryTestCF'
+// CHECK: } // end sil function '_T013objc_currying9curry_podyS2icSo9CurryTestCF'
 
 // CHECK: sil shared [serializable] [thunk] @[[THUNK_FOO_1]] : $@convention(thin) (@owned CurryTest) -> @owned @callee_guaranteed (Int) -> Int
-// CHECK:   [[THUNK:%.*]] = function_ref @[[THUNK_FOO_2:_T0So9CurryTestC3podS2iFTO]]
+// CHECK:   [[THUNK:%.*]] = function_ref @[[THUNK_FOO_2:_T0So9CurryTestC3podyS2iFTO]]
 // CHECK:   [[FN:%.*]] = partial_apply [callee_guaranteed] [[THUNK]](%0)
 // CHECK:   return [[FN]]
 // CHECK: } // end sil function '[[THUNK_FOO_1]]'
@@ -39,20 +39,20 @@
 func curry_bridged(_ x: CurryTest) -> (String?) -> String? {
   return x.bridged
 }
-// CHECK-LABEL: sil hidden @_T013objc_currying13curry_bridgedSSSgACcSo9CurryTestCF : $@convention(thin) (@owned CurryTest) -> @owned @callee_guaranteed (@owned Optional<String>) -> @owned Optional<String>
+// CHECK-LABEL: sil hidden @_T013objc_currying13curry_bridgedySSSgACcSo9CurryTestCF : $@convention(thin) (@owned CurryTest) -> @owned @callee_guaranteed (@owned Optional<String>) -> @owned Optional<String>
 // CHECK: bb0([[ARG1:%.*]] : @owned $CurryTest):
 // CHECK:   [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
 // CHECK:   [[ARG1_COPY:%.*]] = copy_value [[BORROWED_ARG1]]
-// CHECK:   [[THUNK:%.*]] = function_ref @[[THUNK_BAR_1:_T0So9CurryTestC7bridgedSQySSGADFTcTO]]
+// CHECK:   [[THUNK:%.*]] = function_ref @[[THUNK_BAR_1:_T0So9CurryTestC7bridgedySQySSGADFTcTO]]
 // CHECK:   [[FN:%.*]] = apply [[THUNK]]([[ARG1_COPY]])
 // CHECK:   end_borrow [[BORROWED_ARG1]] from [[ARG1]]
 // CHECK:   destroy_value [[ARG1]]
 // CHECK:   return [[FN]]
-// CHECK: } // end sil function '_T013objc_currying13curry_bridgedSSSgACcSo9CurryTestCF'
+// CHECK: } // end sil function '_T013objc_currying13curry_bridgedySSSgACcSo9CurryTestCF'
 
 // CHECK: sil shared [serializable] [thunk] @[[THUNK_BAR_1]] : $@convention(thin) (@owned CurryTest) -> @owned @callee_guaranteed (@owned Optional<String>) -> @owned Optional<String>
 // CHECK: bb0([[ARG1:%.*]] : @owned $CurryTest):
-// CHECK:   [[THUNK:%.*]] = function_ref @[[THUNK_BAR_2:_T0So9CurryTestC7bridgedSQySSGADFTO]]
+// CHECK:   [[THUNK:%.*]] = function_ref @[[THUNK_BAR_2:_T0So9CurryTestC7bridgedySQySSGADFTO]]
 // CHECK:   [[FN:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[ARG1]])
 // CHECK:   return [[FN]]
 // CHECK: } // end sil function '[[THUNK_BAR_1]]'
@@ -81,7 +81,7 @@
 // CHECK:   switch_enum [[RESULT_OPT_NSSTRING]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]],
 
 // CHECK: [[SOME_BB]]([[RESULT_NSSTRING:%.*]] : @owned $NSString):
-// CHECK:   [[BRIDGE_FUNC:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
+// CHECK:   [[BRIDGE_FUNC:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
 // CHECK:   [[REWRAP_RESULT_NSSTRING:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[RESULT_NSSTRING]]
 // CHECK:   [[RESULT_STRING:%.*]] = apply [[BRIDGE_FUNC]]([[REWRAP_RESULT_NSSTRING]]
 // CHECK:   [[WRAPPED_RESULT_STRING:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[RESULT_STRING]]
@@ -100,7 +100,7 @@
 func curry_returnsInnerPointer(_ x: CurryTest) -> () -> UnsafeMutableRawPointer? {
   return x.returnsInnerPointer
 }
-// CHECK-LABEL: sil hidden @_T013objc_currying25curry_returnsInnerPointerSvSgycSo9CurryTestCF : $@convention(thin) (@owned CurryTest) -> @owned @callee_guaranteed () -> Optional<UnsafeMutableRawPointer> {
+// CHECK-LABEL: sil hidden @_T013objc_currying25curry_returnsInnerPointerySvSgycSo9CurryTestCF : $@convention(thin) (@owned CurryTest) -> @owned @callee_guaranteed () -> Optional<UnsafeMutableRawPointer> {
 // CHECK: bb0([[SELF:%.*]] : @owned $CurryTest):
 // CHECK:   [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
 // CHECK:   [[SELF_COPY:%.*]] = copy_value [[BORROWED_SELF]]
@@ -109,7 +109,7 @@
 // CHECK:   end_borrow [[BORROWED_SELF]] from [[SELF]]
 // CHECK:   destroy_value [[SELF]]
 // CHECK:   return [[FN]]
-// CHECK: } // end sil function '_T013objc_currying25curry_returnsInnerPointerSvSgycSo9CurryTestCF'
+// CHECK: } // end sil function '_T013objc_currying25curry_returnsInnerPointerySvSgycSo9CurryTestCF'
 
 // CHECK: sil shared [serializable] [thunk] @[[THUNK_RETURNSINNERPOINTER]] : $@convention(thin) (@owned CurryTest) -> @owned @callee_guaranteed () -> Optional<UnsafeMutableRawPointer>
 // CHECK:   [[THUNK:%.*]] = function_ref @[[THUNK_RETURNSINNERPOINTER_2:_T0So9CurryTestC19returnsInnerPointerSQySvGyFTO]]
@@ -126,7 +126,7 @@
 // CHECK:   return [[RES]]
 // CHECK: } // end sil function '[[THUNK_RETURNSINNERPOINTER_2]]'
 
-// CHECK-LABEL: sil hidden @_T013objc_currying19curry_pod_AnyObjectS2icyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_guaranteed (Int) -> Int
+// CHECK-LABEL: sil hidden @_T013objc_currying19curry_pod_AnyObjectyS2icyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_guaranteed (Int) -> Int
 // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject):
 // CHECK:   [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]]
 // CHECK:   [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]]
@@ -135,13 +135,13 @@
 // CHECK:   [[HAS_METHOD]]([[METHOD:%.*]] : @trivial $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int):
 // CHECK:   [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]]
 // CHECK:   partial_apply [callee_guaranteed] [[METHOD]]([[OPENED_ANY_COPY_2]])
-// CHECK: } // end sil function '_T013objc_currying19curry_pod_AnyObjectS2icyXlF'
+// CHECK: } // end sil function '_T013objc_currying19curry_pod_AnyObjectyS2icyXlF'
 func curry_pod_AnyObject(_ x: AnyObject) -> (Int) -> Int {
   return x.pod!
 }
 
 // normalOwnership requires a thunk to bring the method to Swift conventions
-// CHECK-LABEL: sil hidden @_T013objc_currying31curry_normalOwnership_AnyObjectSo9CurryTestCSgAEcyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_guaranteed (@owned Optional<CurryTest>) -> @owned Optional<CurryTest> {
+// CHECK-LABEL: sil hidden @_T013objc_currying31curry_normalOwnership_AnyObjectySo9CurryTestCSgAEcyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_guaranteed (@owned Optional<CurryTest>) -> @owned Optional<CurryTest> {
 // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject):
 // CHECK:   [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]]
 // CHECK:   [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]]
@@ -152,14 +152,14 @@
 // CHECK:   [[PA:%.*]] = partial_apply [callee_guaranteed] [[METHOD]]([[OPENED_ANY_COPY_2]])
 // CHECK:   [[THUNK:%.*]] = function_ref @_T0So9CurryTestCSgACIegyo_A2CIegxo_TR
 // CHECK:   partial_apply [callee_guaranteed] [[THUNK]]([[PA]])
-// CHECK: } // end sil function '_T013objc_currying31curry_normalOwnership_AnyObjectSo9CurryTestCSgAEcyXlF'
+// CHECK: } // end sil function '_T013objc_currying31curry_normalOwnership_AnyObjectySo9CurryTestCSgAEcyXlF'
 func curry_normalOwnership_AnyObject(_ x: AnyObject) -> (CurryTest?) -> CurryTest? {
   return x.normalOwnership!
 }
 
 // weirdOwnership is NS_RETURNS_RETAINED and NS_CONSUMES_SELF so already
 // follows Swift conventions
-// CHECK-LABEL: sil hidden @_T013objc_currying30curry_weirdOwnership_AnyObjectSo9CurryTestCSgAEcyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_guaranteed (@owned Optional<CurryTest>) -> @owned Optional<CurryTest>
+// CHECK-LABEL: sil hidden @_T013objc_currying30curry_weirdOwnership_AnyObjectySo9CurryTestCSgAEcyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_guaranteed (@owned Optional<CurryTest>) -> @owned Optional<CurryTest>
 // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject):
 // CHECK:   [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]]
 // CHECK:   [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]]
@@ -168,26 +168,26 @@
 // CHECK: bb1([[METHOD:%.*]] : @trivial $@convention(objc_method) (@owned Optional<CurryTest>, @owned @opened({{.*}}) AnyObject) -> @owned Optional<CurryTest>):
 // CHECK:   [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]]
 // CHECK:   partial_apply [callee_guaranteed] [[METHOD]]([[OPENED_ANY_COPY_2]])
-// CHECK: } // end sil function '_T013objc_currying30curry_weirdOwnership_AnyObjectSo9CurryTestCSgAEcyXlF'
+// CHECK: } // end sil function '_T013objc_currying30curry_weirdOwnership_AnyObjectySo9CurryTestCSgAEcyXlF'
 func curry_weirdOwnership_AnyObject(_ x: AnyObject) -> (CurryTest?) -> CurryTest? {
   return x.weirdOwnership!
 }
 
 // bridged requires a thunk to handle bridging conversions
-// CHECK-LABEL: sil hidden @_T013objc_currying23curry_bridged_AnyObjectSSSgACcyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_guaranteed (@owned Optional<String>) -> @owned Optional<String>
+// CHECK-LABEL: sil hidden @_T013objc_currying23curry_bridged_AnyObjectySSSgACcyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_guaranteed (@owned Optional<String>) -> @owned Optional<String>
 // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject):
 // CHECK:    [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]]
 // CHECK:   [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]]
 // CHECK:   [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
 // CHECK:   dynamic_method_br [[OPENED_ANY_COPY]] : $@opened({{.*}}) AnyObject, #CurryTest.bridged!1.foreign, [[HAS_METHOD:bb[0-9]+]]
-// CHECK: } // end sil function '_T013objc_currying23curry_bridged_AnyObjectSSSgACcyXlF'
+// CHECK: } // end sil function '_T013objc_currying23curry_bridged_AnyObjectySSSgACcyXlF'
 func curry_bridged_AnyObject(_ x: AnyObject) -> (String?) -> String? {
   return x.bridged!
 }
 
 // check that we substitute Self = AnyObject correctly for Self-returning
 // methods
-// CHECK-LABEL: sil hidden @_T013objc_currying27curry_returnsSelf_AnyObjectyXlSgycyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_guaranteed () -> @owned Optional<AnyObject> {
+// CHECK-LABEL: sil hidden @_T013objc_currying27curry_returnsSelf_AnyObjectyyXlSgycyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_guaranteed () -> @owned Optional<AnyObject> {
 // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject):
 // CHECK:   [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]]
 // CHECK:   [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]]
@@ -196,12 +196,12 @@
 // CHECK: [[HAS_METHOD]]([[METHOD:%.*]] : @trivial $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @autoreleased Optional<AnyObject>):
 // CHECK:   [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]]
 // CHECK:   [[PA:%.*]] = partial_apply [callee_guaranteed] [[METHOD]]([[OPENED_ANY_COPY_2]])
-// CHECK: } // end sil function '_T013objc_currying27curry_returnsSelf_AnyObjectyXlSgycyXlF'
+// CHECK: } // end sil function '_T013objc_currying27curry_returnsSelf_AnyObjectyyXlSgycyXlF'
 func curry_returnsSelf_AnyObject(_ x: AnyObject) -> () -> AnyObject? {
   return x.returnsSelf!
 }
 
-// CHECK-LABEL: sil hidden @_T013objc_currying35curry_returnsInnerPointer_AnyObjectSvSgycyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_guaranteed () -> Optional<UnsafeMutableRawPointer> {
+// CHECK-LABEL: sil hidden @_T013objc_currying35curry_returnsInnerPointer_AnyObjectySvSgycyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_guaranteed () -> Optional<UnsafeMutableRawPointer> {
 // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject):
 // CHECK:   [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]]
 // CHECK:   [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]]
@@ -210,7 +210,7 @@
 // CHECK: [[HAS_METHOD]]([[METHOD:%.*]] : @trivial $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @unowned_inner_pointer Optional<UnsafeMutableRawPointer>):
 // CHECK:   [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]]
 // CHECK:   [[PA:%.*]] = partial_apply [callee_guaranteed] [[METHOD]]([[OPENED_ANY_COPY_2]])
-// CHECK: } // end sil function '_T013objc_currying35curry_returnsInnerPointer_AnyObjectSvSgycyXlF'
+// CHECK: } // end sil function '_T013objc_currying35curry_returnsInnerPointer_AnyObjectySvSgycyXlF'
 
 func curry_returnsInnerPointer_AnyObject(_ x: AnyObject) -> () -> UnsafeMutableRawPointer? {
   return x.returnsInnerPointer!
diff --git a/test/SILGen/objc_deprecated_objc_thunks.swift b/test/SILGen/objc_deprecated_objc_thunks.swift
index 6ba5b47..dd57382 100644
--- a/test/SILGen/objc_deprecated_objc_thunks.swift
+++ b/test/SILGen/objc_deprecated_objc_thunks.swift
@@ -7,7 +7,7 @@
 import Foundation
 
 class ObjCSubclass : NSObject {
-  // CHECK-SWIFT4-LABEL: sil hidden [thunk] @_T0016objc_deprecated_A7_thunks12ObjCSubclassCACyt7nothing_tcfcTo : $@convention(objc_method) (@owned ObjCSubclass) -> @owned ObjCSubclass {
+  // CHECK-SWIFT4-LABEL: sil hidden [thunk] @_T0016objc_deprecated_A7_thunks12ObjCSubclassC7nothingACyt_tcfcTo : $@convention(objc_method) (@owned ObjCSubclass) -> @owned ObjCSubclass {
   // CHECK-SWIFT4: bb0(%0 : @owned $ObjCSubclass):
   // CHECK-SWIFT4-NEXT: [[FILENAME:%.*]] = [[FILENAME_LITERAL:string_literal.*"]]
   // CHECK-SWIFT4-NEXT: [[LENGTH:%.*]] = integer_literal
@@ -46,7 +46,7 @@
   // CHECK-SWIFT4-NEXT: builtin "swift3ImplicitObjCEntrypoint"([[FILENAME]] : $Builtin.RawPointer, [[LENGTH]] : $Builtin.Word, [[LINE]] : $Builtin.Word, [[COLUMN]] : $Builtin.Word) : $() 
   var bar: NSObject? = nil
 
-  // CHECK-SWIFT4-LABEL: sil hidden [thunk] @_T0016objc_deprecated_A7_thunks12ObjCSubclassCyXlSicigTo : $@convention(objc_method) (Int, ObjCSubclass) -> @autoreleased AnyObject
+  // CHECK-SWIFT4-LABEL: sil hidden [thunk] @_T0016objc_deprecated_A7_thunks12ObjCSubclassCyyXlSicigTo : $@convention(objc_method) (Int, ObjCSubclass) -> @autoreleased AnyObject
   // CHECK-SWIFT4: bb0(%0 : @trivial $Int, %1 : @unowned $ObjCSubclass):
   // CHECK-SWIFT4-NEXT: [[FILENAME:%.*]] = [[FILENAME_LITERAL]]
   // CHECK-SWIFT4-NEXT: [[LENGTH:%.*]] = integer_literal
@@ -55,7 +55,7 @@
   // CHECK-SWIFT4-NEXT: [[COLUMN:%.*]] = integer_literal $Builtin.Word, 3
   // CHECK-SWIFT4-NEXT: builtin "swift3ImplicitObjCEntrypoint"([[FILENAME]] : $Builtin.RawPointer, [[LENGTH]] : $Builtin.Word, [[LINE]] : $Builtin.Word, [[COLUMN]] : $Builtin.Word) : $() 
 
-  // CHECK-SWIFT4-LABEL: sil hidden [thunk] @_T0016objc_deprecated_A7_thunks12ObjCSubclassCyXlSicisTo : $@convention(objc_method) (AnyObject, Int, ObjCSubclass) ->
+  // CHECK-SWIFT4-LABEL: sil hidden [thunk] @_T0016objc_deprecated_A7_thunks12ObjCSubclassCyyXlSicisTo : $@convention(objc_method) (AnyObject, Int, ObjCSubclass) ->
   // CHECK-SWIFT4: bb0(%0 : @unowned $AnyObject, %1 : @trivial $Int, %2 : @unowned $ObjCSubclass):
   // CHECK-SWIFT4-NEXT: [[FILENAME:%.*]] = [[FILENAME_LITERAL]]
   // CHECK-SWIFT4-NEXT: [[LENGTH:%.*]] = integer_literal
diff --git a/test/SILGen/objc_dictionary_bridging.swift b/test/SILGen/objc_dictionary_bridging.swift
index 90bdcb9..0c6aea3 100644
--- a/test/SILGen/objc_dictionary_bridging.swift
+++ b/test/SILGen/objc_dictionary_bridging.swift
@@ -15,7 +15,7 @@
     // CHECK: bb0([[NSDICT:%[0-9]+]] : @unowned $NSDictionary, [[SELF:%[0-9]+]] : @unowned $Foo):
     // CHECK:   [[NSDICT_COPY:%.*]] = copy_value [[NSDICT]]
     // CHECK:   [[SELF_COPY:%.*]] = copy_value [[SELF]]
-    // CHECK:   [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE36_unconditionallyBridgeFromObjectiveCAByxq_GSo12NSDictionaryCSgFZ
+    // CHECK:   [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE36_unconditionallyBridgeFromObjectiveCyAByxq_GSo12NSDictionaryCSgFZ
     // CHECK:   [[OPT_NSDICT:%[0-9]+]] = enum $Optional<NSDictionary>, #Optional.some!enumelt.1, [[NSDICT_COPY]] : $NSDictionary
     // CHECK:   [[DICT_META:%[0-9]+]] = metatype $@thin Dictionary<Foo, Foo>.Type
     // CHECK:   [[DICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[OPT_NSDICT]], [[DICT_META]])
@@ -72,7 +72,7 @@
   // CHECK: bb0([[NSDICT:%[0-9]+]] : @unowned $NSDictionary, [[SELF:%[0-9]+]] : @unowned $Foo):
   // CHECK:   [[NSDICT_COPY:%.*]] = copy_value [[NSDICT]]
   // CHECK:   [[SELF_COPY:%.*]] = copy_value [[SELF]]
-  // CHECK:   [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE36_unconditionallyBridgeFromObjectiveCAByxq_GSo12NSDictionaryCSgFZ
+  // CHECK:   [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE36_unconditionallyBridgeFromObjectiveCyAByxq_GSo12NSDictionaryCSgFZ
   // CHECK:   [[OPT_NSDICT:%[0-9]+]] = enum $Optional<NSDictionary>, #Optional.some!enumelt.1, [[NSDICT_COPY]] : $NSDictionary
   // CHECK:   [[DICT_META:%[0-9]+]] = metatype $@thin Dictionary<Foo, Foo>.Type
   // CHECK:   [[DICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[OPT_NSDICT]], [[DICT_META]])
diff --git a/test/SILGen/objc_error.swift b/test/SILGen/objc_error.swift
index ca2b10b..00d903c 100644
--- a/test/SILGen/objc_error.swift
+++ b/test/SILGen/objc_error.swift
@@ -7,7 +7,7 @@
 
 import Foundation
 
-// CHECK-LABEL: sil hidden @_T010objc_error20NSErrorError_erasures0D0_pSo0C0CF : $@convention(thin) (@owned NSError) -> @owned Error {
+// CHECK-LABEL: sil hidden @_T010objc_error20NSErrorError_erasureys0D0_pSo0C0CF : $@convention(thin) (@owned NSError) -> @owned Error {
 // CHECK:         bb0([[ERROR:%.*]] : @owned $NSError):
 // CHECK:           [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]]
 // CHECK:           [[ERROR_COPY:%.*]] = copy_value [[BORROWED_ERROR]]
@@ -15,12 +15,12 @@
 // CHECK:           end_borrow [[BORROWED_ERROR]] from [[ERROR]]
 // CHECK:           destroy_value [[ERROR]]
 // CHECK:           return [[ERROR_TYPE]]
-// CHECK:       } // end sil function '_T010objc_error20NSErrorError_erasures0D0_pSo0C0CF'
+// CHECK:       } // end sil function '_T010objc_error20NSErrorError_erasureys0D0_pSo0C0CF'
 func NSErrorError_erasure(_ x: NSError) -> Error {
   return x
 }
 
-// CHECK-LABEL: sil hidden @_T010objc_error30NSErrorError_archetype_erasures0D0_pxSo0C0CRbzlF : $@convention(thin) <T where T : NSError> (@owned T) -> @owned Error {
+// CHECK-LABEL: sil hidden @_T010objc_error30NSErrorError_archetype_erasureys0D0_pxSo0C0CRbzlF : $@convention(thin) <T where T : NSError> (@owned T) -> @owned Error {
 // CHECK:         bb0([[ERROR:%.*]] : @owned $T):
 // CHECK:           [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]]
 // CHECK:           [[ERROR_COPY:%.*]] = copy_value [[BORROWED_ERROR]]
@@ -29,7 +29,7 @@
 // CHECK:           end_borrow [[BORROWED_ERROR]] from [[ERROR]]
 // CHECK:           destroy_value [[ERROR]]
 // CHECK:           return [[ERROR_TYPE]]
-// CHECK: } // end sil function '_T010objc_error30NSErrorError_archetype_erasures0D0_pxSo0C0CRbzlF'
+// CHECK: } // end sil function '_T010objc_error30NSErrorError_archetype_erasureys0D0_pxSo0C0CRbzlF'
 func NSErrorError_archetype_erasure<T : NSError>(_ t: T) -> Error {
   return t
 }
@@ -61,7 +61,7 @@
 func test_cast_to_nserror() {
   let e = ErrorClass()
 
-  // CHECK: function_ref @_T010Foundation22_convertErrorToNSErrorSo0E0Cs0C0_pF
+  // CHECK: function_ref @_T010Foundation22_convertErrorToNSErrorySo0E0Cs0C0_pF
   let nsCoerced = e as Error as NSError
 
   // CHECK: unconditional_checked_cast_addr AnyObject in {{%.*}} : $*AnyObject to NSError in {{%.*}} : $*NSError
@@ -87,7 +87,7 @@
 // CHECK-LABEL: sil hidden @_T010objc_error15testAcceptError{{[_0-9a-zA-Z]*}}F
 func testAcceptError(error: Error) {
   // CHECK-NOT: return
-  // CHECK: function_ref @_T010Foundation22_convertErrorToNSErrorSo0E0Cs0C0_pF
+  // CHECK: function_ref @_T010Foundation22_convertErrorToNSErrorySo0E0Cs0C0_pF
   acceptError(error)
 }
 
@@ -147,7 +147,7 @@
     // CHECK: copy_addr [[SELF]] to [initialization] [[COPY]]
     // CHECK: [[COPY2:%.*]] = alloc_stack $Self
     // CHECK: copy_addr [[COPY]] to [initialization] [[COPY2]]
-    // CHECK: [[GET_EMBEDDED_FN:%[0-9]+]] = function_ref @_T0s24_getErrorEmbeddedNSErroryXlSgxs0B0RzlF
+    // CHECK: [[GET_EMBEDDED_FN:%[0-9]+]] = function_ref @_T0s24_getErrorEmbeddedNSErroryyXlSgxs0B0RzlF
     // CHECK: [[EMBEDDED_RESULT_OPT:%[0-9]+]] = apply [[GET_EMBEDDED_FN]]<Self>([[COPY2]])
     // CHECK: switch_enum [[EMBEDDED_RESULT_OPT]] : $Optional<AnyObject>,
     // CHECK-SAME: case #Optional.some!enumelt.1: [[SUCCESS:bb[0-9]+]],
@@ -171,6 +171,6 @@
 }
 
 class Gizmoid : NSObject {
-  // CHECK-LABEL: sil hidden [thunk] @_T010objc_error7GizmoidCACyt3foo_tKcfcTo : $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @owned Gizmoid) -> @owned Optional<Gizmoid>
+  // CHECK-LABEL: sil hidden [thunk] @_T010objc_error7GizmoidC3fooACyt_tKcfcTo : $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @owned Gizmoid) -> @owned Optional<Gizmoid>
   @objc init(foo: ()) throws {}
 }
diff --git a/test/SILGen/objc_extensions.swift b/test/SILGen/objc_extensions.swift
index 1d5ddfc..cbddf70 100644
--- a/test/SILGen/objc_extensions.swift
+++ b/test/SILGen/objc_extensions.swift
@@ -106,13 +106,13 @@
   override func objCBaseMethod() {}
 }
 
-// CHECK-LABEL: sil hidden @_T015objc_extensions20testOverridePropertyyAA3SubCF
+// CHECK-LABEL: sil hidden @_T015objc_extensions20testOverridePropertyyyAA3SubCF
 func testOverrideProperty(_ obj: Sub) {
   // CHECK: bb0([[ARG:%.*]] : @owned $Sub):
   // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
   // CHECK: = objc_method [[BORROWED_ARG]] : $Sub, #Sub.prop!setter.1.foreign : (Sub) -> (String!) -> ()
   obj.prop = "abc"
-} // CHECK: } // end sil function '_T015objc_extensions20testOverridePropertyyAA3SubCF'
+} // CHECK: } // end sil function '_T015objc_extensions20testOverridePropertyyyAA3SubCF'
 
 testOverrideProperty(Sub())
 
diff --git a/test/SILGen/objc_factory_init.swift b/test/SILGen/objc_factory_init.swift
index 8825e70..cc5723f 100644
--- a/test/SILGen/objc_factory_init.swift
+++ b/test/SILGen/objc_factory_init.swift
@@ -5,7 +5,7 @@
 import Foundation
 import ImportAsMember.Class
 
-// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So4HiveCSQyABGSQySo3BeeCG5queen_tcfCTO : $@convention(method) (@owned Optional<Bee>, @thick Hive.Type) -> @owned Optional<Hive>
+// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So4HiveC5queenSQyABGSQySo3BeeCG_tcfCTO : $@convention(method) (@owned Optional<Bee>, @thick Hive.Type) -> @owned Optional<Hive>
 func testInstanceTypeFactoryMethod(queen: Bee) {
   // CHECK: bb0([[QUEEN:%[0-9]+]] : @owned $Optional<Bee>, [[HIVE_META:%[0-9]+]] : @trivial $@thick Hive.Type):
   // CHECK-NEXT:   [[HIVE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[HIVE_META]] : $@thick Hive.Type to $@objc_metatype Hive.Type
@@ -21,7 +21,7 @@
   // not a convenience initializer, which means it does not have an initializing
   // entry point at all.
 
-  // CHECK-LABEL: sil hidden @_T0So4HiveC17objc_factory_initEABSo3BeeC10otherQueen_tcfc : $@convention(method) (@owned Bee, @owned Hive) -> @owned Hive {
+  // CHECK-LABEL: sil hidden @_T0So4HiveC17objc_factory_initE10otherQueenABSo3BeeC_tcfc : $@convention(method) (@owned Bee, @owned Hive) -> @owned Hive {
   // CHECK: bb0([[QUEEN:%.*]] : @owned $Bee, [[OLD_HIVE:%.*]] : @owned $Hive):
   // CHECK:   [[SELF_BOX:%.*]] = alloc_box ${ var Hive }, let, name "self"
   // CHECK:   [[MU:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
@@ -42,12 +42,12 @@
   //
   // CHECK: [[SOME_BB]]([[NEW_HIVE:%.*]] : @owned $Hive):
   // CHECK:   assign [[NEW_HIVE]] to [[PB_BOX]]
-  // CHECK: } // end sil function '_T0So4HiveC17objc_factory_initEABSo3BeeC10otherQueen_tcfc'
+  // CHECK: } // end sil function '_T0So4HiveC17objc_factory_initE10otherQueenABSo3BeeC_tcfc'
   convenience init(otherQueen other: Bee) {
     self.init(queen: other)
   }
 
-  // CHECK-LABEL: sil hidden @_T0So4HiveC17objc_factory_initEABSo3BeeC15otherFlakyQueen_tKcfC : $@convention(method) (@owned Bee, @thick Hive.Type) -> (@owned Hive, @error Error) {
+  // CHECK-LABEL: sil hidden @_T0So4HiveC17objc_factory_initE15otherFlakyQueenABSo3BeeC_tKcfC : $@convention(method) (@owned Bee, @thick Hive.Type) -> (@owned Hive, @error Error) {
   // CHECK: bb0([[QUEEN:%.*]] : @owned $Bee, [[METATYPE:%.*]] : @trivial $@thick Hive.Type):
   // CHECK:   [[OBJC_METATYPE:%.*]] = thick_to_objc_metatype [[METATYPE]]
   // CHECK:   [[HIVE:%.*]] = alloc_ref_dynamic [objc] [[OBJC_METATYPE]]
@@ -59,26 +59,26 @@
   // CHECK: [[ERROR_BB]]([[ERROR:%.*]] : @owned $Error):
   // CHECK:   builtin "willThrow"([[ERROR]] : $Error)
   // CHECK:   throw [[ERROR]]
-  // CHECK: } // end sil function '_T0So4HiveC17objc_factory_initEABSo3BeeC15otherFlakyQueen_tKcfC'
+  // CHECK: } // end sil function '_T0So4HiveC17objc_factory_initE15otherFlakyQueenABSo3BeeC_tKcfC'
   convenience init(otherFlakyQueen other: Bee) throws {
     try self.init(flakyQueen: other)
   }
 }
 
 extension SomeClass {
-  // CHECK-LABEL: sil hidden @_T0So9SomeClassC17objc_factory_initEABSd6double_tcfc : $@convention(method) (Double, @owned SomeClass) -> @owned SomeClass {
+  // CHECK-LABEL: sil hidden @_T0So9SomeClassC17objc_factory_initE6doubleABSd_tcfc : $@convention(method) (Double, @owned SomeClass) -> @owned SomeClass {
   // CHECK: bb0([[DOUBLE:%.*]] : @trivial $Double,
   // CHECK-NOT: value_metatype
   // CHECK: [[FNREF:%[0-9]+]] = function_ref @MakeIAMSomeClass
   // CHECK: apply [[FNREF]]([[DOUBLE]])
-  // CHECK: } // end sil function '_T0So9SomeClassC17objc_factory_initEABSd6double_tcfc'
+  // CHECK: } // end sil function '_T0So9SomeClassC17objc_factory_initE6doubleABSd_tcfc'
   convenience init(double: Double) {
     self.init(value: double)
   }
 }
 
 class SubHive : Hive {
-  // CHECK-LABEL: sil hidden @_T017objc_factory_init7SubHiveCACyt20delegatesToInherited_tcfc : $@convention(method) (@owned SubHive) -> @owned SubHive {
+  // CHECK-LABEL: sil hidden @_T017objc_factory_init7SubHiveC20delegatesToInheritedACyt_tcfc : $@convention(method) (@owned SubHive) -> @owned SubHive {
   // CHECK: bb0([[SUBHIVE:%.*]] : @owned $SubHive):
   // CHECK:   [[SELF_BOX:%.*]] = alloc_box ${ var SubHive }, let, name "self"
   // CHECK:   [[MU:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] : ${ var SubHive }
@@ -93,7 +93,7 @@
   // CHECK:   [[HIVE_INIT_FN:%.*]] = objc_method [[OBJC_METATYPE]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign
   // CHECK:   apply [[HIVE_INIT_FN]]([[QUEEN]], [[OBJC_METATYPE]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
   // CHECK:   destroy_value [[QUEEN]]
-  // CHECK: } // end sil function '_T017objc_factory_init7SubHiveCACyt20delegatesToInherited_tcfc'
+  // CHECK: } // end sil function '_T017objc_factory_init7SubHiveC20delegatesToInheritedACyt_tcfc'
   convenience init(delegatesToInherited: ()) {
     self.init(queen: Bee())
   }
diff --git a/test/SILGen/objc_final.swift b/test/SILGen/objc_final.swift
index c283c55..ab5c267 100644
--- a/test/SILGen/objc_final.swift
+++ b/test/SILGen/objc_final.swift
@@ -13,7 +13,7 @@
   // CHECK-LABEL: sil hidden [transparent] [thunk] @_T010objc_final3FooC4propSivsTo
 }
 
-// CHECK-LABEL: sil hidden @_T010objc_final7callFooyAA0D0CF
+// CHECK-LABEL: sil hidden @_T010objc_final7callFooyyAA0D0CF
 func callFoo(_ x: Foo) {
   // Calls to the final @objc method statically reference the native entry
   // point.
diff --git a/test/SILGen/objc_implicitly_unwrapped_optional.swift b/test/SILGen/objc_implicitly_unwrapped_optional.swift
index f0806bc..4baf5eb 100644
--- a/test/SILGen/objc_implicitly_unwrapped_optional.swift
+++ b/test/SILGen/objc_implicitly_unwrapped_optional.swift
@@ -6,9 +6,9 @@
 
 class C : Hive {}
 
-// CHECK-LABEL: sil private @_T034objc_implicitly_unwrapped_optional1DCACSo7NSCoderC5coder_tcfcAA1CCSQyAHGSQyAEGAF_tcfcTV
+// CHECK-LABEL: sil private @_T034objc_implicitly_unwrapped_optional1DC5coderACSo7NSCoderC_tcfcAA1CCADSQyAHGSQyAFG_tcfcTV
 // CHECK: bb0(%0 : $Optional<NSCoder>, %1 : $D):
-// CHECK:   [[THUNK:%.*]] = function_ref @_T034objc_implicitly_unwrapped_optional1DCACSo7NSCoderC5coder_tcfc
+// CHECK:   [[THUNK:%.*]] = function_ref @_T034objc_implicitly_unwrapped_optional1DC5coderACSo7NSCoderC_tcfc
 // CHECK:   [[REF:%.*]] = apply [[THUNK]]
 // CHECK:   [[RESULT:%.*]] = enum $Optional<D>, #Optional.some!enumelt.1, [[REF]] : $D
 // CHECK:   return [[RESULT]] : $Optional<D>
diff --git a/test/SILGen/objc_imported_generic.swift b/test/SILGen/objc_imported_generic.swift
index 7542b09..f443b2f 100644
--- a/test/SILGen/objc_imported_generic.swift
+++ b/test/SILGen/objc_imported_generic.swift
@@ -10,7 +10,7 @@
   _ = GenericClass(thing: NSObject())
 }
 
-// CHECK-LABEL: sil shared [serializable] @_T0So12GenericClassCSQyAByxGGSQyxG5thing_tcfC
+// CHECK-LABEL: sil shared [serializable] @_T0So12GenericClassC5thingSQyAByxGGSQyxG_tcfC
 // CHECK:         thick_to_objc_metatype {{%.*}} : $@thick GenericClass<T>.Type to $@objc_metatype GenericClass<T>.Type
 
 public func genericMethodOnAnyObject(o: AnyObject, b: Bool) -> AnyObject {
@@ -24,39 +24,39 @@
   return o.thing?()
 }
 
-// CHECK-LABEL: sil @_T021objc_imported_generic0C24MethodOnAnyObjectChainedyXlSgyXl1o_Sb1btF
+// CHECK-LABEL: sil @_T021objc_imported_generic0C24MethodOnAnyObjectChained1o1byXlSgyXl_SbtF
 // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject, [[BOOL:%.*]] : @trivial $Bool):
 // CHECK:   [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]]
 // CHECK:   [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]]
 // CHECK:   [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
 // CHECK:   dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.thing!1.foreign, bb1
 // CHECK:   bb1({{%.*}} : @trivial $@convention(objc_method) @pseudogeneric (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>):
-// CHECK: } // end sil function '_T021objc_imported_generic0C24MethodOnAnyObjectChainedyXlSgyXl1o_Sb1btF'
+// CHECK: } // end sil function '_T021objc_imported_generic0C24MethodOnAnyObjectChained1o1byXlSgyXl_SbtF'
 
 public func genericSubscriptOnAnyObject(o: AnyObject, b: Bool) -> AnyObject? {
   return o[0 as UInt16]
 }
 
-// CHECK-LABEL: sil @_T021objc_imported_generic0C20SubscriptOnAnyObjectyXlSgyXl1o_Sb1btF
+// CHECK-LABEL: sil @_T021objc_imported_generic0C20SubscriptOnAnyObject1o1byXlSgyXl_SbtF
 // CHECK: bb0([[ANY:%.*]]
 // CHCEK:   [[OPENED_ANY:%.*]] = open_existential_ref [[ANY]]
 // CHECK:   [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
 // CHECK:   dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.subscript!getter.1.foreign, bb1
 // CHECK:   bb1({{%.*}} : @trivial $@convention(objc_method) @pseudogeneric (UInt16, @opened([[TAG]]) AnyObject) -> @autoreleased AnyObject):
-// CHECK: } // end sil function '_T021objc_imported_generic0C20SubscriptOnAnyObjectyXlSgyXl1o_Sb1btF'
+// CHECK: } // end sil function '_T021objc_imported_generic0C20SubscriptOnAnyObject1o1byXlSgyXl_SbtF'
 
 public func genericPropertyOnAnyObject(o: AnyObject, b: Bool) -> AnyObject?? {
   return o.propertyThing
 }
 
-// CHECK-LABEL: sil @_T021objc_imported_generic0C19PropertyOnAnyObjectyXlSgSgyXl1o_Sb1btF
+// CHECK-LABEL: sil @_T021objc_imported_generic0C19PropertyOnAnyObject1o1byXlSgSgyXl_SbtF
 // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject, [[BOOL:%.*]] : @trivial $Bool):
 // CHECK:   [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]]
 // CHECK:   [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]]
 // CHECK:   [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
 // CHECK:   dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.propertyThing!getter.1.foreign, bb1
 // CHECK:   bb1({{%.*}} : @trivial $@convention(objc_method) @pseudogeneric (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>):
-// CHECK: } // end sil function '_T021objc_imported_generic0C19PropertyOnAnyObjectyXlSgSgyXl1o_Sb1btF'
+// CHECK: } // end sil function '_T021objc_imported_generic0C19PropertyOnAnyObject1o1byXlSgSgyXl_SbtF'
 
 public protocol ThingHolder {
   associatedtype Thing
@@ -96,7 +96,7 @@
 
 // CHECK-LABEL: sil @_T021objc_imported_generic20arraysOfGenericParam{{[_0-9a-zA-Z]*}}F
 public func arraysOfGenericParam<T: AnyObject>(y: Array<T>) {
-  // CHECK:         function_ref {{@_T0So12GenericClassCSQyAByxGGSayxG13arrayOfThings.*}} : $@convention(method) <τ_0_0 where τ_0_0 : AnyObject> (@owned Array<τ_0_0>, @thick GenericClass<τ_0_0>.Type) -> @owned Optional<GenericClass<τ_0_0>>
+  // CHECK:         function_ref @_T0So12GenericClassC13arrayOfThingsSQyAByxGGSayxG_tcfC : $@convention(method) <τ_0_0 where τ_0_0 : AnyObject> (@owned Array<τ_0_0>, @thick GenericClass<τ_0_0>.Type) -> @owned Optional<GenericClass<τ_0_0>>
   let x = GenericClass<T>(arrayOfThings: y)!
   // CHECK:         objc_method {{%.*}} : $GenericClass<T>, #GenericClass.setArrayOfThings!1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, GenericClass<τ_0_0>) -> ()
   x.setArrayOfThings(y)
@@ -106,7 +106,7 @@
   x.propertyArrayOfThings = y
 }
 
-// CHECK-LABEL: sil private @_T021objc_imported_generic0C4FuncyxmRlzClFyycfU_ : $@convention(thin) <V where V : AnyObject> () -> () {
+// CHECK-LABEL: sil private @_T021objc_imported_generic0C4FuncyyxmRlzClFyycfU_ : $@convention(thin) <V where V : AnyObject> () -> () {
 // CHECK:  [[META:%.*]] = metatype $@thick GenericClass<V>.Type
 // CHECK:  [[INIT:%.*]] = function_ref @_T0So12GenericClassCAByxGycfC : $@convention(method) <τ_0_0 where τ_0_0 : AnyObject> (@thick GenericClass<τ_0_0>.Type) -> @owned GenericClass<τ_0_0>
 // CHECK:  apply [[INIT]]<V>([[META]])
@@ -118,26 +118,26 @@
 }
 
 // CHECK-LABEL: sil hidden @_T021objc_imported_generic23configureWithoutOptionsyyF : $@convention(thin) () -> ()
-// CHECK: [[NIL_FN:%.*]] = function_ref @_T0SqxSgyt10nilLiteral_tcfC : $@convention(method) <τ_0_0> (@thin Optional<τ_0_0>.Type) -> @out Optional<τ_0_0>
+// CHECK: [[NIL_FN:%.*]] = function_ref @_T0Sq10nilLiteralxSgyt_tcfC : $@convention(method) <τ_0_0> (@thin Optional<τ_0_0>.Type) -> @out Optional<τ_0_0>
 // CHECK: apply [[NIL_FN]]<[GenericOption : Any]>({{.*}})
 // CHECK: return
 func configureWithoutOptions() {
   _ = GenericClass<NSObject>(options: nil)
 }
 
+// This gets emitted down here for some reason
+
+// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So12GenericClassC13arrayOfThingsSQyAByxGGSayxG_tcfcTO
+// CHECK:         objc_method {{%.*}} : $GenericClass<T>, #GenericClass.init!initializer.1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, @owned GenericClass<τ_0_0>) -> @owned Optional<GenericClass<τ_0_0>>
+
 // foreign to native thunk for init(options:), uses GenericOption : Hashable
 // conformance
 
-// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So12GenericClassCSQyAByxGGs10DictionaryVySC0A6OptionVypGSg7options_tcfcTO : $@convention(method) <T where T : AnyObject> (@owned Optional<Dictionary<GenericOption, Any>>, @owned GenericClass<T>) -> @owned Optional<GenericClass<T>>
+// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So12GenericClassC7optionsSQyAByxGGs10DictionaryVySC0A6OptionVypGSg_tcfcTO : $@convention(method) <T where T : AnyObject> (@owned Optional<Dictionary<GenericOption, Any>>, @owned GenericClass<T>) -> @owned Optional<GenericClass<T>>
 // CHECK: [[FN:%.*]] = function_ref @_T0s10DictionaryV10FoundationE19_bridgeToObjectiveCSo12NSDictionaryCyF : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary
 // CHECK: apply [[FN]]<GenericOption, Any>({{.*}}) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary
 // CHECK: return
 
-// This gets emitted down here for some reason
-
-// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So12GenericClassCSQyAByxGGSayxG13arrayOfThings_tcfcTO
-// CHECK:         objc_method {{%.*}} : $GenericClass<T>, #GenericClass.init!initializer.1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, @owned GenericClass<τ_0_0>) -> @owned Optional<GenericClass<τ_0_0>>
-
 // Make sure we emitted the witness table for the above conformance
 
 // CHECK-LABEL: sil_witness_table shared [serialized] GenericOption: Hashable module objc_generics {
diff --git a/test/SILGen/objc_metatypes.swift b/test/SILGen/objc_metatypes.swift
index df81b8d..13c2609 100644
--- a/test/SILGen/objc_metatypes.swift
+++ b/test/SILGen/objc_metatypes.swift
@@ -9,7 +9,7 @@
 class A {
   // CHECK-LABEL: sil hidden @_T014objc_metatypes1AC3foo{{[_0-9a-zA-Z]*}}F
 
-  // CHECK-LABEL: sil hidden [thunk] @_T014objc_metatypes1AC3fooAA9ObjCClassCmAFmFTo
+  // CHECK-LABEL: sil hidden [thunk] @_T014objc_metatypes1AC3fooyAA9ObjCClassCmAFmFTo
   @objc dynamic func foo(_ m: ObjCClass.Type) -> ObjCClass.Type {
     // CHECK: bb0([[M:%[0-9]+]] : @trivial $@objc_metatype ObjCClass.Type, [[SELF:%[0-9]+]] : @unowned $A):
     // CHECK:   [[SELF_COPY:%.*]] = copy_value [[SELF]] : $A
@@ -21,7 +21,7 @@
     // CHECK:   destroy_value [[SELF_COPY]]
     // CHECK:   [[OBJC_RESULT:%[0-9]+]] = thick_to_objc_metatype [[NATIVE_RESULT]] : $@thick ObjCClass.Type to $@objc_metatype ObjCClass.Type
     // CHECK:   return [[OBJC_RESULT]] : $@objc_metatype ObjCClass.Type
-    // CHECK: } // end sil function '_T014objc_metatypes1AC3fooAA9ObjCClassCmAFmFTo'
+    // CHECK: } // end sil function '_T014objc_metatypes1AC3fooyAA9ObjCClassCmAFmFTo'
     return m
   }
 
diff --git a/test/SILGen/objc_ownership_conventions.swift b/test/SILGen/objc_ownership_conventions.swift
index d25a82f..5b428c7 100644
--- a/test/SILGen/objc_ownership_conventions.swift
+++ b/test/SILGen/objc_ownership_conventions.swift
@@ -206,7 +206,7 @@
 func useInnerPointer(_ p: UnsafeMutableRawPointer) {}
 
 // Handle inner-pointer methods by autoreleasing self after the call.
-// CHECK-LABEL: sil hidden @_T026objc_ownership_conventions18innerPointerMethodySo5GizmoCF : $@convention(thin) (@owned Gizmo) -> () {
+// CHECK-LABEL: sil hidden @_T026objc_ownership_conventions18innerPointerMethodyySo5GizmoCF : $@convention(thin) (@owned Gizmo) -> () {
 // CHECK: bb0([[ARG:%.*]] : @owned $Gizmo):
 // CHECK:         [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:         [[METHOD:%.*]] = objc_method [[BORROWED_ARG]] : $Gizmo, #Gizmo.getBytes!1.foreign : (Gizmo) -> () -> UnsafeMutableRawPointer, $@convention(objc_method) (Gizmo) -> @unowned_inner_pointer UnsafeMutableRawPointer
@@ -222,7 +222,7 @@
   useInnerPointer(g.getBytes())
 }
 
-// CHECK-LABEL: sil hidden @_T026objc_ownership_conventions20innerPointerPropertyySo5GizmoCF : $@convention(thin) (@owned Gizmo) -> () {
+// CHECK-LABEL: sil hidden @_T026objc_ownership_conventions20innerPointerPropertyyySo5GizmoCF : $@convention(thin) (@owned Gizmo) -> () {
 // CHECK:       bb0([[ARG:%.*]] : @owned $Gizmo):
 // CHECK:         [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:         [[METHOD:%.*]] = objc_method [[BORROWED_ARG]] : $Gizmo, #Gizmo.innerProperty!getter.1.foreign : (Gizmo) -> () -> UnsafeMutableRawPointer, $@convention(objc_method) (Gizmo) -> @unowned_inner_pointer UnsafeMutableRawPointer
@@ -233,7 +233,7 @@
 // CHECK:         [[USE:%.*]] = function_ref @_T026objc_ownership_conventions15useInnerPointer{{[_0-9a-zA-Z]*}}F
 // CHECK:         apply [[USE]]([[PTR]])
 // CHECK:         destroy_value [[ARG]]
-// CHECK: } // end sil function '_T026objc_ownership_conventions20innerPointerPropertyySo5GizmoCF'
+// CHECK: } // end sil function '_T026objc_ownership_conventions20innerPointerPropertyyySo5GizmoCF'
 func innerPointerProperty(_ g: Gizmo) {
   useInnerPointer(g.innerProperty)
 }
diff --git a/test/SILGen/objc_protocols.swift b/test/SILGen/objc_protocols.swift
index 11923be..1a684e7 100644
--- a/test/SILGen/objc_protocols.swift
+++ b/test/SILGen/objc_protocols.swift
@@ -44,7 +44,7 @@
   return (x.runce(), x.copyRuncing())
 }
 
-// CHECK-LABEL: sil hidden @_T014objc_protocols0A22_generic_partial_applyyxAA9NSRuncingRzlF : $@convention(thin) <T where T : NSRuncing> (@owned T) -> () {
+// CHECK-LABEL: sil hidden @_T014objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlF : $@convention(thin) <T where T : NSRuncing> (@owned T) -> () {
 func objc_generic_partial_apply<T : NSRuncing>(_ x: T) {
   // CHECK: bb0([[ARG:%.*]] : @owned $T):
   // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
@@ -67,7 +67,7 @@
   _ = T.mince
   // CHECK:   destroy_value [[ARG]]
 }
-// CHECK: } // end sil function '_T014objc_protocols0A22_generic_partial_applyyxAA9NSRuncingRzlF'
+// CHECK: } // end sil function '_T014objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlF'
 
 // CHECK: sil shared [serializable] [thunk] @[[THUNK1]] :
 // CHECK: bb0([[SELF:%.*]] : @owned $Self):
@@ -119,7 +119,7 @@
   return (x.runce(), x.copyRuncing())
 }
 
-// CHECK-LABEL: sil hidden @_T014objc_protocols0A23_protocol_partial_applyyAA9NSRuncing_pF : $@convention(thin) (@owned NSRuncing) -> () {
+// CHECK-LABEL: sil hidden @_T014objc_protocols0A23_protocol_partial_applyyyAA9NSRuncing_pF : $@convention(thin) (@owned NSRuncing) -> () {
 func objc_protocol_partial_apply(_ x: NSRuncing) {
   // CHECK: bb0([[ARG:%.*]] : @owned $NSRuncing):
   // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
@@ -135,7 +135,7 @@
   // FIXME: rdar://21289579
   // _ = NSRuncing.runce
 }
-// CHECK : } // end sil function '_T014objc_protocols0A23_protocol_partial_applyyAA9NSRuncing_pF'
+// CHECK : } // end sil function '_T014objc_protocols0A23_protocol_partial_applyyyAA9NSRuncing_pF'
 
 // CHECK-LABEL: sil hidden @_T014objc_protocols0A21_protocol_composition{{[_0-9a-zA-Z]*}}F
 func objc_protocol_composition(_ x: NSRuncing & NSFunging) {
@@ -258,7 +258,7 @@
   init(int: Int)
 }
 
-// CHECK-LABEL: sil hidden @_T014objc_protocols28testInitializableExistentialAA0D0_pAaC_pXp_Si1itF : $@convention(thin) (@thick Initializable.Type, Int) -> @owned Initializable {
+// CHECK-LABEL: sil hidden @_T014objc_protocols28testInitializableExistential_1iAA0D0_pAaD_pXp_SitF : $@convention(thin) (@thick Initializable.Type, Int) -> @owned Initializable {
 func testInitializableExistential(_ im: Initializable.Type, i: Int) -> Initializable {
   // CHECK: bb0([[META:%[0-9]+]] : @trivial $@thick Initializable.Type, [[I:%[0-9]+]] : @trivial $Int):
   // CHECK:   [[I2_BOX:%[0-9]+]] = alloc_box ${ var Initializable }
@@ -277,7 +277,7 @@
   var i2 = im.init(int: i)
   return i2
 }
-// CHECK: } // end sil function '_T014objc_protocols28testInitializableExistentialAA0D0_pAaC_pXp_Si1itF'
+// CHECK: } // end sil function '_T014objc_protocols28testInitializableExistential_1iAA0D0_pAaD_pXp_SitF'
 
 class InitializableConformer: Initializable {
   @objc required init(int: Int) {}
diff --git a/test/SILGen/objc_set_bridging.swift b/test/SILGen/objc_set_bridging.swift
index 585af2d..86c13c0 100644
--- a/test/SILGen/objc_set_bridging.swift
+++ b/test/SILGen/objc_set_bridging.swift
@@ -15,7 +15,7 @@
     // CHECK: bb0([[NSSET:%[0-9]+]] : @unowned $NSSet, [[SELF:%[0-9]+]] : @unowned $Foo):
     // CHECK:   [[NSSET_COPY:%.*]] = copy_value [[NSSET]] : $NSSet
     // CHECK:   [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Foo
-    // CHECK:   [[CONVERTER:%[0-9]+]] = function_ref @_T0s3SetV10FoundationE36_unconditionallyBridgeFromObjectiveCAByxGSo5NSSetCSgFZ
+    // CHECK:   [[CONVERTER:%[0-9]+]] = function_ref @_T0s3SetV10FoundationE36_unconditionallyBridgeFromObjectiveCyAByxGSo5NSSetCSgFZ
     // CHECK:   [[OPT_NSSET:%[0-9]+]] = enum $Optional<NSSet>, #Optional.some!enumelt.1, [[NSSET_COPY]] : $NSSet
     // CHECK:   [[SET_META:%[0-9]+]] = metatype $@thin Set<Foo>.Type
     // CHECK:   [[SET:%[0-9]+]] = apply [[CONVERTER]]<Foo>([[OPT_NSSET]], [[SET_META]])
@@ -71,7 +71,7 @@
   // CHECK: bb0([[NSSET:%[0-9]+]] : @unowned $NSSet, [[SELF:%[0-9]+]] : @unowned $Foo):
   // CHECK:   [[NSSET_COPY:%.*]] = copy_value [[NSSET]] : $NSSet
   // CHECK:   [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Foo
-  // CHECK:   [[CONVERTER:%[0-9]+]] = function_ref @_T0s3SetV10FoundationE36_unconditionallyBridgeFromObjectiveCAByxGSo5NSSetCSgFZ
+  // CHECK:   [[CONVERTER:%[0-9]+]] = function_ref @_T0s3SetV10FoundationE36_unconditionallyBridgeFromObjectiveCyAByxGSo5NSSetCSgFZ
   // CHECK:   [[OPT_NSSET:%[0-9]+]] = enum $Optional<NSSet>, #Optional.some!enumelt.1, [[NSSET_COPY]] : $NSSet
   // CHECK:   [[SET_META:%[0-9]+]] = metatype $@thin Set<Foo>.Type
   // CHECK:   [[SET:%[0-9]+]] = apply [[CONVERTER]]<Foo>([[OPT_NSSET]], [[SET_META]])
diff --git a/test/SILGen/objc_subscript.swift b/test/SILGen/objc_subscript.swift
index 2bb11c5..aa50bd1 100644
--- a/test/SILGen/objc_subscript.swift
+++ b/test/SILGen/objc_subscript.swift
@@ -28,12 +28,12 @@
 // 'super' subscript usage
 class B : A {
   @objc override subscript (i: Int) -> ObjCClass {
-    // CHECK-LABEL: sil hidden @_T014objc_subscript1BCAA9ObjCClassCSicig : $@convention(method) (Int, @guaranteed B) -> @owned ObjCClass
+    // CHECK-LABEL: sil hidden @_T014objc_subscript1BCyAA9ObjCClassCSicig : $@convention(method) (Int, @guaranteed B) -> @owned ObjCClass
     get {
       // CHECK: objc_super_method [[SELF:%[0-9]+]] : $B, #A.subscript!getter.1.foreign : (A) -> (Int) -> ObjCClass, $@convention(objc_method) (Int, A) -> @autoreleased ObjCClass
       return super[i]
     }
-    // CHECK-LABEL: sil hidden @_T014objc_subscript1BCAA9ObjCClassCSicis : $@convention(method) (@owned ObjCClass, Int, @guaranteed B) -> ()
+    // CHECK-LABEL: sil hidden @_T014objc_subscript1BCyAA9ObjCClassCSicis : $@convention(method) (@owned ObjCClass, Int, @guaranteed B) -> ()
     set(value) {
       // CHECK: objc_super_method [[SELF:%[0-9]+]] : $B, #A.subscript!setter.1.foreign : (A) -> (ObjCClass, Int) -> (), $@convention(objc_method) (ObjCClass, Int, A) -> ()
       super[i] = value
diff --git a/test/SILGen/objc_thunks.swift b/test/SILGen/objc_thunks.swift
index 7651ba2..acb1e5d 100644
--- a/test/SILGen/objc_thunks.swift
+++ b/test/SILGen/objc_thunks.swift
@@ -7,18 +7,18 @@
 
 class Hoozit : Gizmo {
   @objc func typical(_ x: Int, y: Gizmo) -> Gizmo { return y }
-  // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7typicalSo5GizmoCSi_AF1ytFTo : $@convention(objc_method) (Int, Gizmo, Hoozit) -> @autoreleased Gizmo {
+  // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7typical_1ySo5GizmoCSi_AGtFTo : $@convention(objc_method) (Int, Gizmo, Hoozit) -> @autoreleased Gizmo {
   // CHECK: bb0([[X:%.*]] : @trivial $Int, [[Y:%.*]] : @unowned $Gizmo, [[THIS:%.*]] : @unowned $Hoozit):
   // CHECK-NEXT:   [[Y_COPY:%.*]] = copy_value [[Y]]
   // CHECK-NEXT:   [[THIS_COPY:%.*]] = copy_value [[THIS]]
   // CHECK-NEXT:   [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
   // CHECK-NEXT:   // function_ref objc_thunks.Hoozit.typical
-  // CHECK-NEXT:   [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7typicalSo5GizmoCSi_AF1ytF : $@convention(method) (Int, @owned Gizmo, @guaranteed Hoozit) -> @owned Gizmo
+  // CHECK-NEXT:   [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7typical_1ySo5GizmoCSi_AGtF : $@convention(method) (Int, @owned Gizmo, @guaranteed Hoozit) -> @owned Gizmo
   // CHECK-NEXT:   [[RES:%.*]] = apply [[NATIVE]]([[X]], [[Y_COPY]], [[BORROWED_THIS_COPY]]) {{.*}} line:[[@LINE-8]]:14:auto_gen
   // CHECK-NEXT:   end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]]
   // CHECK-NEXT:   destroy_value [[THIS_COPY]] : $Hoozit
   // CHECK-NEXT:   return [[RES]] : $Gizmo{{.*}} line:[[@LINE-11]]:14:auto_gen
-  // CHECK-NEXT: } // end sil function '_T011objc_thunks6HoozitC7typicalSo5GizmoCSi_AF1ytFTo'
+  // CHECK-NEXT: } // end sil function '_T011objc_thunks6HoozitC7typical_1ySo5GizmoCSi_AGtFTo'
 
   // NS_CONSUMES_SELF by inheritance
   override func fork() { }
@@ -35,10 +35,10 @@
 
   // NS_CONSUMED 'gizmo' argument by inheritance
   override class func consume(_ gizmo: Gizmo?) { }
-   // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7consumeySo5GizmoCSgFZTo : $@convention(objc_method) (@owned Optional<Gizmo>, @objc_metatype Hoozit.Type) -> () {
+   // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC7consumeyySo5GizmoCSgFZTo : $@convention(objc_method) (@owned Optional<Gizmo>, @objc_metatype Hoozit.Type) -> () {
   // CHECK: bb0([[GIZMO:%.*]] : @owned $Optional<Gizmo>, [[THIS:%.*]] : @trivial $@objc_metatype Hoozit.Type):
   // CHECK-NEXT: [[THICK_THIS:%[0-9]+]] = objc_to_thick_metatype [[THIS]] : $@objc_metatype Hoozit.Type to $@thick Hoozit.Type
-  // CHECK:   [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7consumeySo5GizmoCSgFZ : $@convention(method) (@owned Optional<Gizmo>, @thick Hoozit.Type) -> ()
+  // CHECK:   [[NATIVE:%.*]] = function_ref @_T011objc_thunks6HoozitC7consumeyySo5GizmoCSgFZ : $@convention(method) (@owned Optional<Gizmo>, @thick Hoozit.Type) -> ()
   // CHECK-NEXT:   apply [[NATIVE]]([[GIZMO]], [[THICK_THIS]])
   // CHECK-NEXT:   return
   // CHECK-NEXT: }
@@ -307,7 +307,7 @@
   // CHECK-NOT: sil hidden [thunk] @_TToFC11objc_thunks6Hoozit7generic{{.*}}
 
   // Constructor.
-  // CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitCACSi7bellsOn_tcfc : $@convention(method) (Int, @owned Hoozit) -> @owned Hoozit {
+  // CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC7bellsOnACSi_tcfc : $@convention(method) (Int, @owned Hoozit) -> @owned Hoozit {
   // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Hoozit }
   // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [derivedself] [[SELF_BOX]]
   // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]]
@@ -328,12 +328,12 @@
   // Subscript
   @objc subscript (i: Int) -> Hoozit {
   // Getter
-  // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitCACSicigTo : $@convention(objc_method) (Int, Hoozit) -> @autoreleased Hoozit
+  // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitCyACSicigTo : $@convention(objc_method) (Int, Hoozit) -> @autoreleased Hoozit
   // CHECK: bb0([[I:%[0-9]+]] : @trivial $Int, [[SELF:%[0-9]+]] : @unowned $Hoozit):
   // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Hoozit
   // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
   // CHECK-NEXT: // function_ref
-  // CHECK-NEXT: [[NATIVE:%[0-9]+]] = function_ref @_T011objc_thunks6HoozitCACSicig : $@convention(method) (Int, @guaranteed Hoozit) -> @owned Hoozit
+  // CHECK-NEXT: [[NATIVE:%[0-9]+]] = function_ref @_T011objc_thunks6HoozitCyACSicig : $@convention(method) (Int, @guaranteed Hoozit) -> @owned Hoozit
   // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[NATIVE]]([[I]], [[BORROWED_SELF_COPY]]) : $@convention(method) (Int, @guaranteed Hoozit) -> @owned Hoozit
   // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
   // CHECK-NEXT: destroy_value [[SELF_COPY]]
@@ -343,17 +343,17 @@
   }
 
   // Setter
-  // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitCACSicisTo : $@convention(objc_method) (Hoozit, Int, Hoozit) -> ()
+  // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitCyACSicisTo : $@convention(objc_method) (Hoozit, Int, Hoozit) -> ()
   // CHECK: bb0([[VALUE:%[0-9]+]] : @unowned $Hoozit, [[I:%[0-9]+]] : @trivial $Int, [[SELF:%[0-9]+]] : @unowned $Hoozit):
   // CHECK:   [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $Hoozit
   // CHECK:   [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Hoozit
   // CHECK:   [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
-  // CHECK:   [[NATIVE:%[0-9]+]] = function_ref @_T011objc_thunks6HoozitCACSicis : $@convention(method) (@owned Hoozit, Int, @guaranteed Hoozit) -> ()
+  // CHECK:   [[NATIVE:%[0-9]+]] = function_ref @_T011objc_thunks6HoozitCyACSicis : $@convention(method) (@owned Hoozit, Int, @guaranteed Hoozit) -> ()
   // CHECK:   [[RESULT:%[0-9]+]] = apply [[NATIVE]]([[VALUE_COPY]], [[I]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Hoozit, Int, @guaranteed Hoozit) -> ()
   // CHECK:   end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
   // CHECK:   destroy_value [[SELF_COPY]]
   // CHECK:   return [[RESULT]] : $()
-  // CHECK: } // end sil function '_T011objc_thunks6HoozitCACSicisTo'
+  // CHECK: } // end sil function '_T011objc_thunks6HoozitCyACSicisTo'
   set {}
   }
 }
@@ -407,17 +407,17 @@
 
   // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitCSQyACyxGGycfcTo : $@convention(objc_method) <T> (@owned Wotsit<T>) -> @owned Optional<Wotsit<T>>
 
-  // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitCSQyACyxGGSi7bellsOn_tcfcTo : $@convention(objc_method) <T> (Int, @owned Wotsit<T>) -> @owned Optional<Wotsit<T>>
+  // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6WotsitC7bellsOnSQyACyxGGSi_tcfcTo : $@convention(objc_method) <T> (Int, @owned Wotsit<T>) -> @owned Optional<Wotsit<T>>
 }
 
 // CHECK-NOT: sil hidden [thunk] @_TToF{{.*}}Wotsit{{.*}}
 
 // Extension initializers, properties and methods need thunks too.
 extension Hoozit {
-  // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitCACSi3int_tcfcTo : $@convention(objc_method) (Int, @owned Hoozit) -> @owned Hoozit
+  // CHECK-LABEL: sil hidden [thunk] @_T011objc_thunks6HoozitC3intACSi_tcfcTo : $@convention(objc_method) (Int, @owned Hoozit) -> @owned Hoozit
   @objc dynamic convenience init(int i: Int) { self.init(bellsOn: i) }
 
-  // CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitCACSd6double_tcfc : $@convention(method) (Double, @owned Hoozit) -> @owned Hoozit
+  // CHECK-LABEL: sil hidden @_T011objc_thunks6HoozitC6doubleACSd_tcfc : $@convention(method) (Double, @owned Hoozit) -> @owned Hoozit
   convenience init(double d: Double) { 
     // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Hoozit }
     // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
@@ -441,7 +441,7 @@
 
 // Calling objc methods of subclass should go through native entry points
 func useHoozit(_ h: Hoozit) {
-// sil @_T011objc_thunks9useHoozityAA0D0C1h_tF
+// sil @_T011objc_thunks9useHoozit1hyAA0D0C_tF
   // In the class decl, overrides importd method, 'dynamic' was inferred
   h.fork()
   // CHECK: objc_method {{%.*}} : {{.*}}, #Hoozit.fork!1.foreign
@@ -452,7 +452,7 @@
 }
 
 func useWotsit(_ w: Wotsit<String>) {
-// sil @_T011objc_thunks9useWotsitySo0D0CySSG1w_tF
+// sil @_T011objc_thunks9useWotsit1wySo0D0CySSG_tF
   w.plain()
   // CHECK: class_method {{%.*}} : {{.*}}, #Wotsit.plain!1 :
   w.generic(2)
@@ -467,7 +467,7 @@
 
 class X { }
 
-// CHECK-LABEL: sil hidden @_T011objc_thunks8propertySiSo5GizmoCF
+// CHECK-LABEL: sil hidden @_T011objc_thunks8propertyySiSo5GizmoCF
 func property(_ g: Gizmo) -> Int {
   // CHECK: bb0([[ARG:%.*]] : @owned $Gizmo):
   // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
@@ -475,7 +475,7 @@
   return g.count
 }
 
-// CHECK-LABEL: sil hidden @_T011objc_thunks13blockPropertyySo5GizmoCF
+// CHECK-LABEL: sil hidden @_T011objc_thunks13blockPropertyyySo5GizmoCF
 func blockProperty(_ g: Gizmo) {
   // CHECK: bb0([[ARG:%.*]] : @owned $Gizmo):
   // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
@@ -491,11 +491,11 @@
 
   override init() { i = 5 }
 
-  // CHECK-LABEL: sil hidden @_T011objc_thunks15DesignatedStubsCSQyACGSi7bellsOn_tcfc
+  // CHECK-LABEL: sil hidden @_T011objc_thunks15DesignatedStubsC7bellsOnSQyACGSi_tcfc
   // CHECK: string_literal utf8 "objc_thunks.DesignatedStubs"
   // CHECK: string_literal utf8 "init(bellsOn:)"
   // CHECK: string_literal utf8 "{{.*}}objc_thunks.swift"
-  // CHECK: function_ref @_T0s25_unimplementedInitializers5NeverOs12StaticStringV9className_AE04initG0AE4fileSu4lineSu6columntF
+  // CHECK: function_ref @_T0s25_unimplementedInitializer9className04initD04file4line6columns5NeverOs12StaticStringV_A2JS2utF
   // CHECK: return
 
   // CHECK-NOT: sil hidden @_TFCSo15DesignatedStubsc{{.*}}
@@ -510,7 +510,7 @@
   // CHECK: objc_super_method [[SELF:%[0-9]+]] : $DesignatedOverrides, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> () -> Gizmo!, $@convention(objc_method) (@owned Gizmo) -> @owned Optional<Gizmo>
   // CHECK: return
 
-  // CHECK-LABEL: sil hidden @_T011objc_thunks19DesignatedOverridesCSQyACGSi7bellsOn_tcfc
+  // CHECK-LABEL: sil hidden @_T011objc_thunks19DesignatedOverridesC7bellsOnSQyACGSi_tcfc
   // CHECK: function_ref @_T011objc_thunks19DesignatedOverridesC1iSivpfi : $@convention(thin) () -> Int
   // CHECK: objc_super_method [[SELF:%[0-9]+]] : $DesignatedOverrides, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> (Int) -> Gizmo!, $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo>
   // CHECK: return
diff --git a/test/SILGen/objc_witnesses.swift b/test/SILGen/objc_witnesses.swift
index 130e294..30797a0 100644
--- a/test/SILGen/objc_witnesses.swift
+++ b/test/SILGen/objc_witnesses.swift
@@ -53,9 +53,9 @@
   subscript(x: Int) -> Any { get }
 }
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T0So7NSArrayC14objc_witnesses13SubscriptableA2cDPypSicigTW : $@convention(witness_method: Subscriptable) (Int, @in_guaranteed NSArray) -> @out Any {
-// CHECK:         function_ref @_T0So7NSArrayCypSicigTO : $@convention(method) (Int, @guaranteed NSArray) -> @out Any
-// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So7NSArrayCypSicigTO : $@convention(method) (Int, @guaranteed NSArray) -> @out Any {
+// CHECK-LABEL: sil private [transparent] [thunk] @_T0So7NSArrayC14objc_witnesses13SubscriptableA2cDPyypSicigTW : $@convention(witness_method: Subscriptable) (Int, @in_guaranteed NSArray) -> @out Any {
+// CHECK:         function_ref @_T0So7NSArrayCyypSicigTO : $@convention(method) (Int, @guaranteed NSArray) -> @out Any
+// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So7NSArrayCyypSicigTO : $@convention(method) (Int, @guaranteed NSArray) -> @out Any {
 // CHECK:         objc_method {{%.*}} : $NSArray, #NSArray.subscript!getter.1.foreign
 extension NSArray: Subscriptable {}
 
diff --git a/test/SILGen/opaque_ownership.swift b/test/SILGen/opaque_ownership.swift
index 4ff4926..0a6ea03 100644
--- a/test/SILGen/opaque_ownership.swift
+++ b/test/SILGen/opaque_ownership.swift
@@ -19,7 +19,7 @@
 
 // Test open_existential_value ownership
 // ---
-// CHECK-LABEL: sil @_T0s11takeDecoderBi1_s0B0_p4from_tKF : $@convention(thin) (@in Decoder) -> (Builtin.Int1, @error Error) {
+// CHECK-LABEL: sil @_T0s11takeDecoder4fromBi1_s0B0_p_tKF : $@convention(thin) (@in Decoder) -> (Builtin.Int1, @error Error) {
 // CHECK: bb0(%0 : @owned $Decoder):
 // CHECK:  [[BORROW1:%.*]] = begin_borrow %0 : $Decoder
 // CHECK:  [[OPENED:%.*]] = open_existential_value [[BORROW1]] : $Decoder to $@opened("{{.*}}") Decoder
@@ -36,7 +36,7 @@
 // CHECK:  destroy_value [[RET1]] : $UnkeyedDecodingContainer
 // CHECK:  destroy_value %0 : $Decoder
 // CHECK:  return [[RET2]] : $Builtin.Int1
-// CHECK-LABEL: } // end sil function '_T0s11takeDecoderBi1_s0B0_p4from_tKF'
+// CHECK-LABEL: } // end sil function '_T0s11takeDecoder4fromBi1_s0B0_p_tKF'
 public func takeDecoder(from decoder: Decoder) throws -> Builtin.Int1 {
   let container = try decoder.unkeyedContainer()
   return container.isAtEnd
@@ -44,7 +44,7 @@
 
 // Test unsafe_bitwise_cast nontrivial ownership.
 // ---
-// CHECK-LABEL: sil @_T0s13unsafeBitCastq_x_q_m2totr0_lF : $@convention(thin) <T, U> (@in T, @thick U.Type) -> @out U {
+// CHECK-LABEL: sil @_T0s13unsafeBitCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in T, @thick U.Type) -> @out U {
 // CHECK: bb0(%0 : @owned $T, %1 : @trivial $@thick U.Type):
 // CHECK:   %4 = begin_borrow %0 : $T
 // CHECK:   %5 = copy_value %4 : $T
@@ -54,7 +54,7 @@
 // CHECK:   end_borrow %4 from %0 : $T, $T
 // CHECK:   destroy_value %0 : $T
 // CHECK:   return %7 : $U
-// CHECK-LABEL: } // end sil function '_T0s13unsafeBitCastq_x_q_m2totr0_lF'
+// CHECK-LABEL: } // end sil function '_T0s13unsafeBitCast_2toq_x_q_mtr0_lF'
 public func unsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U {
   return Builtin.reinterpretCast(x)
 }
@@ -156,12 +156,12 @@
 
 // Test ownership of multi-case Enum values in the context of @trivial to @in thunks.
 // ---
-// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] @_T0s17FloatingPointSignOs9EquatablessACP2eeoiSbx_xtFZTW : $@convention(witness_method: Equatable) (@in FloatingPointSign, @in FloatingPointSign, @thick FloatingPointSign.Type) -> Bool {
+// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] @_T0s17FloatingPointSignOs9EquatablessACP2eeoiySbx_xtFZTW : $@convention(witness_method: Equatable) (@in FloatingPointSign, @in FloatingPointSign, @thick FloatingPointSign.Type) -> Bool {
 // CHECK: bb0(%0 : @trivial $FloatingPointSign, %1 : @trivial $FloatingPointSign, %2 : @trivial $@thick FloatingPointSign.Type):
-// CHECK:   %3 = function_ref @_T0s2eeoiSbx_xts16RawRepresentableRzs9Equatable0B5ValueRpzlF : $@convention(thin) <τ_0_0 where τ_0_0 : RawRepresentable, τ_0_0.RawValue : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool
+// CHECK:   %3 = function_ref @_T0s2eeoiySbx_xts16RawRepresentableRzs9Equatable0B5ValueRpzlF : $@convention(thin) <τ_0_0 where τ_0_0 : RawRepresentable, τ_0_0.RawValue : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool
 // CHECK:   %4 = apply %3<FloatingPointSign, Int64>(%0, %1) : $@convention(thin) <τ_0_0 where τ_0_0 : RawRepresentable, τ_0_0.RawValue : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool
 // CHECK:   return %4 : $Bool
-// CHECK-LABEL: } // end sil function '_T0s17FloatingPointSignOs9EquatablessACP2eeoiSbx_xtFZTW'
+// CHECK-LABEL: } // end sil function '_T0s17FloatingPointSignOs9EquatablessACP2eeoiySbx_xtFZTW'
 public enum FloatingPointSign: Int64 {
   /// The sign for a positive value.
   case plus
@@ -174,7 +174,7 @@
 // Test open_existential_value used in a conversion context.
 // (the actual bridging call is dropped because we don't import Swift).
 // ---
-// CHECK-OSX-LABEL: sil @_T0s26_unsafeDowncastToAnyObjectyXlyp04fromD0_tF : $@convention(thin) (@in Any) -> @owned AnyObject {
+// CHECK-OSX-LABEL: sil @_T0s26_unsafeDowncastToAnyObject04fromD0yXlyp_tF : $@convention(thin) (@in Any) -> @owned AnyObject {
 // CHECK-OSX: bb0(%0 : @owned $Any):
 // CHECK-OSX:   [[BORROW:%.*]] = begin_borrow %0 : $Any
 // CHECK-OSX:   [[COPY:%.*]] = copy_value [[BORROW]] : $Any
@@ -187,7 +187,7 @@
 // CHECK-OSX:   end_borrow [[BORROW]] from %0 : $Any, $Any
 // CHECK-OSX:   destroy_value %0 : $Any
 // CHECK-OSX:   return undef : $AnyObject
-// CHECK-OSX-LABEL: } // end sil function '_T0s26_unsafeDowncastToAnyObjectyXlyp04fromD0_tF'
+// CHECK-OSX-LABEL: } // end sil function '_T0s26_unsafeDowncastToAnyObject04fromD0yXlyp_tF'
 public func _unsafeDowncastToAnyObject(fromAny any: Any) -> AnyObject {
   return any as AnyObject
 }
@@ -198,13 +198,13 @@
 #if os(OSX)
 // Test open_existential_box_value in a conversion context.
 // ---
-// CHECK-OSX-LABEL: sil @_T0s3fooys5Error_pSg1e_tF : $@convention(thin) (@owned Optional<Error>) -> () {
+// CHECK-OSX-LABEL: sil @_T0s3foo1eys5Error_pSg_tF : $@convention(thin) (@owned Optional<Error>) -> () {
 // CHECK-OSX: [[BORROW:%.*]] = begin_borrow %{{.*}} : $Error
 // CHECK-OSX: [[VAL:%.*]] = open_existential_box_value [[BORROW]] : $Error to $@opened
 // CHECK-OSX: [[COPY:%.*]] = copy_value [[VAL]] : $@opened
 // CHECK-OSX: [[ANY:%.*]] = init_existential_value [[COPY]] : $@opened
 // CHECK-OSX: end_borrow [[BORROW]] from %{{.*}} : $Error, $Error
-// CHECK-OSX-LABEL: } // end sil function '_T0s3fooys5Error_pSg1e_tF'
+// CHECK-OSX-LABEL: } // end sil function '_T0s3foo1eys5Error_pSg_tF'
 public func foo(e: Error?) {
   if let u = e {
     let a: Any = u
@@ -250,7 +250,7 @@
 // CHECK:  [[ITER:%.*]] = apply [[WT]]<Base>([[BORROW]]) : $@convention(witness_method: Seq) <τ_0_0 where τ_0_0 : Seq> (@in_guaranteed τ_0_0) -> @out τ_0_0.Iterator
 // CHECK:  end_borrow [[BORROW]] from [[COPY]] : $Base, $Base
 // CHECK:  destroy_value [[COPY]] : $Base
-// CHECK: [[FN:%.*]] = function_ref @_T0s8EnumIterVAByxGx5_base_tcfC : $@convention(method) <τ_0_0 where τ_0_0 : IP> (@in τ_0_0, @thin EnumIter<τ_0_0>.Type) -> @out EnumIter<τ_0_0>
+// CHECK: [[FN:%.*]] = function_ref @_T0s8EnumIterV5_baseAByxGx_tcfC : $@convention(method) <τ_0_0 where τ_0_0 : IP> (@in τ_0_0, @thin EnumIter<τ_0_0>.Type) -> @out EnumIter<τ_0_0>
 // CHECK:  [[RET:%.*]] = apply [[FN]]<Base.Iterator>([[ITER]], [[MT]]) : $@convention(method) <τ_0_0 where τ_0_0 : IP> (@in τ_0_0, @thin EnumIter<τ_0_0>.Type) -> @out EnumIter<τ_0_0>
 // CHECK:  return [[RET]] : $EnumIter<Base.Iterator>
 // CHECK-LABEL: } // end sil function '_T0s7EnumSeqV12makeIterators0A4IterVy0D0QzGyF'
diff --git a/test/SILGen/opaque_values_silgen.swift b/test/SILGen/opaque_values_silgen.swift
index 995142c..feacd21 100644
--- a/test/SILGen/opaque_values_silgen.swift
+++ b/test/SILGen/opaque_values_silgen.swift
@@ -70,16 +70,16 @@
 func s010_hasVarArg(_ args: Any...) {}
 
 // Tests Address only enums's construction
-// CHECK-LABEL: sil shared [transparent] @_T020opaque_values_silgen15AddressOnlyEnumO4mereAcA6EmptyP_pcACmF : $@convention(method) (@in EmptyP, @thin AddressOnlyEnum.Type) -> @out AddressOnlyEnum {
+// CHECK-LABEL: sil shared [transparent] @_T020opaque_values_silgen15AddressOnlyEnumO4mereyAcA6EmptyP_pcACmF : $@convention(method) (@in EmptyP, @thin AddressOnlyEnum.Type) -> @out AddressOnlyEnum {
 // CHECK: bb0([[ARG0:%.*]] : $EmptyP, [[ARG1:%.*]] : $@thin AddressOnlyEnum.Type):
 // CHECK:   [[RETVAL:%.*]] = enum $AddressOnlyEnum, #AddressOnlyEnum.mere!enumelt.1, [[ARG0]] : $EmptyP
 // CHECK:   return [[RETVAL]] : $AddressOnlyEnum
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen15AddressOnlyEnumO4mereAcA6EmptyP_pcACmF'
-// CHECK-LABEL: sil shared [transparent] [thunk] @_T020opaque_values_silgen15AddressOnlyEnumO4mereAcA6EmptyP_pcACmFTc : $@convention(thin) (@thin AddressOnlyEnum.Type) -> @owned @callee_guaranteed (@in EmptyP) -> @out AddressOnlyEnum {
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen15AddressOnlyEnumO4mereyAcA6EmptyP_pcACmF'
+// CHECK-LABEL: sil shared [transparent] [thunk] @_T020opaque_values_silgen15AddressOnlyEnumO4mereyAcA6EmptyP_pcACmFTc : $@convention(thin) (@thin AddressOnlyEnum.Type) -> @owned @callee_guaranteed (@in EmptyP) -> @out AddressOnlyEnum {
 // CHECK: bb0([[ARG:%.*]] : $@thin AddressOnlyEnum.Type):
 // CHECK:   [[RETVAL:%.*]] = partial_apply {{.*}}([[ARG]]) : $@convention(method) (@in EmptyP, @thin AddressOnlyEnum.Type) -> @out AddressOnlyEnum
 // CHECK:   return [[RETVAL]] : $@callee_guaranteed (@in EmptyP) -> @out AddressOnlyEnum
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen15AddressOnlyEnumO4mereAcA6EmptyP_pcACmFTc'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen15AddressOnlyEnumO4mereyAcA6EmptyP_pcACmFTc'
 enum AddressOnlyEnum {
   case nought
   case mere(EmptyP)
@@ -88,7 +88,7 @@
 
 // Test vtables - OpaqueTupleClass
 // ---
-// CHECK-LABEL: sil private @_T020opaque_values_silgen16OpaqueTupleClassC8inAndOutx_xtx_xt1x_tFAA0dF0CADxxAE_tFTV : $@convention(method) <U> (@in (U, U), @guaranteed OpaqueTupleClass<U>) -> @out (U, U) {
+// CHECK-LABEL: sil private @_T020opaque_values_silgen16OpaqueTupleClassC8inAndOut1xx_xtx_xt_tFAA0dF0CAdExx_tFTV : $@convention(method) <U> (@in (U, U), @guaranteed OpaqueTupleClass<U>) -> @out (U, U) {
 // CHECK: bb0([[ARG0:%.*]] : $(U, U), [[ARG1:%.*]] : $OpaqueTupleClass<U>):
 // CHECK:   ([[TELEM0:%.*]], [[TELEM1:%.*]]) = destructure_tuple [[ARG0]] : $(U, U)
 // CHECK:   [[APPLY:%.*]] = apply {{.*}}<U>([[TELEM0]], [[TELEM1]], [[ARG1]]) : $@convention(method) <τ_0_0> (@in τ_0_0, @in τ_0_0, @guaranteed OpaqueTupleClass<τ_0_0>) -> (@out τ_0_0, @out τ_0_0)
@@ -100,11 +100,11 @@
 // CHECK:   end_borrow [[BORROWED_CALL]]
 // CHECK:   [[RETVAL:%.*]] = tuple ([[RETVAL0]] : $U, [[RETVAL1]] : $U)
 // CHECK:   return [[RETVAL]]
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen16OpaqueTupleClassC8inAndOutx_xtx_xt1x_tFAA0dF0CADxxAE_tFTV'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen16OpaqueTupleClassC8inAndOut1xx_xtx_xt_tFAA0dF0CAdExx_tFTV'
 
 // Test vtables - StillOpaqueClass
 // ---
-// CHECK-LABEL: sil private @_T020opaque_values_silgen16StillOpaqueClassC24variantOptionalityTuplesx_xm_xxcttx_xm_xxcttSg1x_tFAA0eF0CAdEx_xm_xxcttAF_tFTV : $@convention(method) <T> (@in T, @thick T.Type, @owned @callee_guaranteed (@in T) -> @out T, @guaranteed StillOpaqueClass<T>) -> @out Optional<(T, (@thick T.Type, @callee_guaranteed (@in T) -> @out T))> {
+// CHECK-LABEL: sil private @_T020opaque_values_silgen16StillOpaqueClassC24variantOptionalityTuples1xx_xm_xxcttx_xm_xxcttSg_tFAA0eF0CAdeFx_xm_xxctt_tFTV : $@convention(method) <T> (@in T, @thick T.Type, @owned @callee_guaranteed (@in T) -> @out T, @guaranteed StillOpaqueClass<T>) -> @out Optional<(T, (@thick T.Type, @callee_guaranteed (@in T) -> @out T))> {
 // CHECK: bb0([[ARG0:%.*]] : $T, [[ARG1:%.*]] : $@thick T.Type, [[ARG2:%.*]] : $@callee_guaranteed (@in T) -> @out T, [[ARG3:%.*]] : $StillOpaqueClass<T>):
 // CHECK:   [[TELEM0:%.*]] = tuple ([[ARG1]] : $@thick T.Type, [[ARG2]] : $@callee_guaranteed (@in T) -> @out T)
 // CHECK:   [[TELEM1:%.*]] = tuple ([[ARG0]] : $T, [[TELEM0]] : $(@thick T.Type, @callee_guaranteed (@in T) -> @out T))
@@ -121,7 +121,7 @@
 // CHECK:   [[RETTUPLE1:%.*]] = tuple ([[RETVAL0]] : $T, [[RETTUPLE0]] : $(@thick T.Type, @callee_guaranteed (@in T) -> @out T))
 // CHECK:   [[RETVAL:%.*]] = enum $Optional<(T, (@thick T.Type, @callee_guaranteed (@in T) -> @out T))>, #Optional.some!enumelt.1, [[RETTUPLE1]] : $(T, (@thick T.Type, @callee_guaranteed (@in T) -> @out T))
 // CHECK:   return [[RETVAL]]
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen16StillOpaqueClassC24variantOptionalityTuplesx_xm_xxcttx_xm_xxcttSg1x_tFAA0eF0CAdEx_xm_xxcttAF_tFTV'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen16StillOpaqueClassC24variantOptionalityTuples1xx_xm_xxcttx_xm_xxcttSg_tFAA0eF0CAdeFx_xm_xxctt_tFTV'
 
 
 // part of s280_convExistTrivial: conversion between existential types - reabstraction thunk
@@ -175,7 +175,7 @@
 
 // Test emitSemanticStore.
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s030______assigninoutyxz_xtlF : $@convention(thin) <T> (@inout T, @in T) -> () {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s030______assigninoutyyxz_xtlF : $@convention(thin) <T> (@inout T, @in T) -> () {
 // CHECK: bb0([[ARG0:%.*]] : $*T, [[ARG1:%.*]] : $T):
 // CHECK:   [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
 // CHECK:   [[CPY:%.*]] = copy_value [[BORROWED_ARG1]] : $T
@@ -184,14 +184,14 @@
 // CHECK:   end_borrow [[BORROWED_ARG1]] from [[ARG1]]
 // CHECK:   destroy_value [[ARG1]] : $T
 // CHECK:   return %{{.*}} : $()
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s030______assigninoutyxz_xtlF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s030______assigninoutyyxz_xtlF'
 func s030______assigninout<T>(_ a: inout T, _ b: T) {
   a = b
 }
 
 // Test that we no longer use copy_addr or tuple_element_addr when copy by value is possible
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s040___tupleReturnIntS2i_xt_tlF : $@convention(thin) <T> (Int, @in T) -> Int {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s040___tupleReturnIntyS2i_xt_tlF : $@convention(thin) <T> (Int, @in T) -> Int {
 // CHECK: bb0([[ARG0:%.*]] : $Int, [[ARG1:%.*]] : $T):
 // CHECK:   [[TPL:%.*]] = tuple ([[ARG0]] : $Int, [[ARG1]] : $T)
 // CHECK:   [[BORROWED_ARG1:%.*]] = begin_borrow [[TPL]] : $(Int, T)
@@ -206,7 +206,7 @@
 // CHECK:   end_borrow [[BORROWED_ARG1]] from [[TPL]] : $(Int, T), $(Int, T)
 // CHECK:   destroy_value [[TPL]] : $(Int, T)
 // CHECK:   return [[INT]]
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s040___tupleReturnIntS2i_xt_tlF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s040___tupleReturnIntyS2i_xt_tlF'
 func s040___tupleReturnInt<T>(_ x: (Int, T)) -> Int {
   let y = x.0
   return y
@@ -214,7 +214,7 @@
 
 // Test returning an opaque tuple of tuples.
 // ---
-// CHECK-LABEL: sil hidden [noinline] @_T020opaque_values_silgen21s050______multiResultx_x_xttxlF : $@convention(thin) <T> (@in T) -> (@out T, @out T, @out T) {
+// CHECK-LABEL: sil hidden [noinline] @_T020opaque_values_silgen21s050______multiResultyx_x_xttxlF : $@convention(thin) <T> (@in T) -> (@out T, @out T, @out T) {
 // CHECK: bb0(%0 : $T):
 // CHECK: %[[CP1:.*]] = copy_value %{{.*}} : $T
 // CHECK: %[[CP2:.*]] = copy_value %{{.*}} : $T
@@ -222,7 +222,7 @@
 // CHECK: destroy_value %0 : $T
 // CHECK: %[[TPL:.*]] = tuple (%[[CP1]] : $T, %[[CP2]] : $T, %[[CP3]] : $T)
 // CHECK: return %[[TPL]] : $(T, T, T)
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s050______multiResultx_x_xttxlF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s050______multiResultyx_x_xttxlF'
 @inline(never)
 func s050______multiResult<T>(_ t: T) -> (T, (T, T)) {
   return (t, (t, t))
@@ -230,16 +230,16 @@
 
 // Test returning an opaque tuple of tuples as a concrete tuple.
 // ---
-// CHECK-LABEL: sil @_T020opaque_values_silgen21s060__callMultiResultSi_Si_SittSi1i_tF : $@convention(thin) (Int) -> (Int, Int, Int) {
+// CHECK-LABEL: sil @_T020opaque_values_silgen21s060__callMultiResult1iSi_Si_SittSi_tF : $@convention(thin) (Int) -> (Int, Int, Int) {
 // CHECK: bb0(%0 : $Int):
-// CHECK: %[[FN:.*]] = function_ref @_T020opaque_values_silgen21s050______multiResultx_x_xttxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @out τ_0_0, @out τ_0_0)
+// CHECK: %[[FN:.*]] = function_ref @_T020opaque_values_silgen21s050______multiResultyx_x_xttxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @out τ_0_0, @out τ_0_0)
 // CHECK: %[[TPL:.*]] = apply %[[FN]]<Int>(%0) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @out τ_0_0, @out τ_0_0)
 // CHECK: %[[I1:.*]] = tuple_extract %[[TPL]] : $(Int, Int, Int), 0
 // CHECK: %[[I2:.*]] = tuple_extract %[[TPL]] : $(Int, Int, Int), 1
 // CHECK: %[[I3:.*]] = tuple_extract %[[TPL]] : $(Int, Int, Int), 2
 // CHECK: %[[R:.*]] = tuple (%[[I1]] : $Int, %[[I2]] : $Int, %[[I3]] : $Int)
 // CHECK: return %[[R]] : $(Int, Int, Int)
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s060__callMultiResultSi_Si_SittSi1i_tF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s060__callMultiResult1iSi_Si_SittSi_tF'
 public func s060__callMultiResult(i: Int) -> (Int, (Int, Int)) {
   return s050______multiResult(i)
 }
@@ -247,7 +247,7 @@
 // SILGen, prepareArchetypeCallee. Materialize a
 // non-class-constrainted self from a class-constrained archetype.
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s070__materializeSelfyx1t_tRlzCAA3FooRzlF : $@convention(thin) <T where T : AnyObject, T : Foo> (@owned T) -> () {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s070__materializeSelf1tyx_tRlzCAA3FooRzlF : $@convention(thin) <T where T : AnyObject, T : Foo> (@owned T) -> () {
 // CHECK: bb0([[ARG:%.*]] : $T):
 // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK: [[WITNESS_METHOD:%.*]] = witness_method $T, #Foo.foo!1 : <Self where Self : Foo> (Self) -> () -> () : $@convention(witness_method: Foo) <τ_0_0 where τ_0_0 : Foo> (@in_guaranteed τ_0_0) -> ()
@@ -255,14 +255,14 @@
 // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK: destroy_value [[ARG]] : $T
 // CHECK: return %{{[0-9]+}} : $()
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s070__materializeSelfyx1t_tRlzCAA3FooRzlF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s070__materializeSelf1tyx_tRlzCAA3FooRzlF'
 func s070__materializeSelf<T: Foo>(t: T) where T: AnyObject {
   t.foo()
 }
 
 // Test open existential with opaque values
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s080______________barSiAA1P_p1p_tF : $@convention(thin) (@in P) -> Int {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s080______________bar1pSiAA1P_p_tF : $@convention(thin) (@in P) -> Int {
 // CHECK: bb0([[ARG:%.*]] : $P):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[OPENED_ARG:%.*]] = open_existential_value [[BORROWED_ARG]] : $P to $@opened
@@ -277,7 +277,7 @@
 
 // Test OpaqueTypeLowering copyValue and destroyValue.
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s090___________callerxxlF : $@convention(thin) <T> (@in T) -> @out T {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s090___________calleryxxlF : $@convention(thin) <T> (@in T) -> @out T {
 // CHECK: bb0([[ARG:%.*]] : $T):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[COPY:%.*]] = copy_value [[BORROWED_ARG]] : $T
@@ -285,21 +285,21 @@
 // CHECK:   end_borrow [[BORROWED_ARG:%.*]] from [[ARG]]
 // CHECK:   destroy_value [[ARG]] : $T
 // CHECK:   return %{{.*}} : $T
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s090___________callerxxlF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s090___________calleryxxlF'
 func s090___________caller<T>(_ t: T) -> T {
   return s090___________caller(t)
 }
 
 // Test a simple opaque parameter and return value.
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s100_________identityxxlF : $@convention(thin) <T> (@in T) -> @out T {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s100_________identityyxxlF : $@convention(thin) <T> (@in T) -> @out T {
 // CHECK: bb0([[ARG:%.*]] : $T):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]] : $T
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK:   destroy_value [[ARG]] : $T
 // CHECK:   return [[COPY_ARG]] : $T
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s100_________identityxxlF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s100_________identityyxxlF'
 func s100_________identity<T>(_ t: T) -> T {
   return t
 }
@@ -318,7 +318,7 @@
 
 // Tests a corner case wherein we used to do a temporary and return a pointer to T instead of T
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s120______returnValuexxlF : $@convention(thin) <T> (@in T) -> @out T {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s120______returnValueyxxlF : $@convention(thin) <T> (@in T) -> @out T {
 // CHECK: bb0([[ARG:%.*]] : $T):
 // CHECK:   [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[COPY_ARG1:%.*]] = copy_value [[BORROWED_ARG1]] : $T
@@ -327,7 +327,7 @@
 // CHECK:   [[COPY_ARG2:%.*]] = copy_value [[BORROWED_ARG2]] : $T
 // CHECK:   end_borrow [[BORROWED_ARG2]] from [[COPY_ARG1]]
 // CHECK:   return [[COPY_ARG2]] : $T
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s120______returnValuexxlF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s120______returnValueyxxlF'
 func s120______returnValue<T>(_ x: T) -> T {
   let y = x
   return y
@@ -335,7 +335,7 @@
 
 // Tests Optional initialization by value
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s130_____________wrapxSgxlF : $@convention(thin) <T> (@in T) -> @out Optional<T> {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s130_____________wrapyxSgxlF : $@convention(thin) <T> (@in T) -> @out Optional<T> {
 // CHECK: bb0([[ARG:%.*]] : $T):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]] : $T
@@ -343,7 +343,7 @@
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK:   destroy_value [[ARG]] : $T
 // CHECK:   return [[OPTIONAL_ARG]] : $Optional<T>
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s130_____________wrapxSgxlF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s130_____________wrapyxSgxlF'
 func s130_____________wrap<T>(_ x: T) -> T? {
   return x
 }
@@ -464,7 +464,7 @@
 
 // Tests composition erasure of opaque existentials + copy into of opaques
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s210______compErasures5Error_psAC_AA3FoopF : $@convention(thin) (@in Error & Foo) -> @owned Error {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s210______compErasureys5Error_psAC_AA3FoopF : $@convention(thin) (@in Error & Foo) -> @owned Error {
 // CHECK: bb0([[ARG:%.*]] : $Error & Foo):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[OPAQUE_ARG:%.*]] = open_existential_value [[BORROWED_ARG]] : $Error & Foo to $@opened({{.*}}) Error & Foo
@@ -475,14 +475,14 @@
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK:   destroy_value [[ARG]] : $Error & Foo
 // CHECK:   return [[EXIST_BOX]] : $Error
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s210______compErasures5Error_psAC_AA3FoopF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s210______compErasureys5Error_psAC_AA3FoopF'
 func s210______compErasure(_ x: Foo & Error) -> Error {
   return x
 }
 
 // Tests that existential boxes can contain opaque types
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s220_____openExistBoxSSs5Error_pF : $@convention(thin) (@owned Error) -> @owned String {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s220_____openExistBoxySSs5Error_pF : $@convention(thin) (@owned Error) -> @owned String {
 // CHECK: bb0([[ARG:%.*]] : $Error):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[OPAQUE_ARG:%.*]] = open_existential_box_value [[BORROWED_ARG]] : $Error to $@opened({{.*}}) Error
@@ -492,14 +492,14 @@
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]]
 // CHECK:   destroy_value [[ARG]] : $Error
 // CHECK:   return {{.*}} : $String
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s220_____openExistBoxSSs5Error_pF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s220_____openExistBoxySSs5Error_pF'
 func s220_____openExistBox(_ x: Error) -> String {
   return x._domain
 }
 
 // Tests conditional value casts and correspondingly generated reabstraction thunk
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s230______condFromAnyyypF : $@convention(thin) (@in Any) -> () {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s230______condFromAnyyyypF : $@convention(thin) (@in Any) -> () {
 // CHECK: bb0([[ARG:%.*]] : $Any):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[COPY__ARG:%.*]] = copy_value [[BORROWED_ARG]]
@@ -509,7 +509,7 @@
 // CHECK:   partial_apply [callee_guaranteed] [[THUNK_REF]]([[THUNK_PARAM]])
 // CHECK: bb6:
 // CHECK:   return %{{.*}} : $()
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s230______condFromAnyyypF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s230______condFromAnyyyypF'
 func s230______condFromAny(_ x: Any) {
   if let f = x as? (Int, (Int, (Int, Int)), Int) -> (Int, (Int, (Int, Int)), Int) {
     _ = f(24, (4,(2, 42)), 42)
@@ -518,7 +518,7 @@
 
 // Tests LValue of error types / existential boxes
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s240_____propOfLValueSSs5Error_pF : $@convention(thin) (@owned Error) -> @owned String {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s240_____propOfLValueySSs5Error_pF : $@convention(thin) (@owned Error) -> @owned String {
 // CHECK: bb0([[ARG:%.*]] : $Error):
 // CHECK:   [[ALLOC_OF_BOX:%.*]] = alloc_box ${ var Error }
 // CHECK:   [[PROJ_BOX:%.*]] = project_box [[ALLOC_OF_BOX]]
@@ -534,7 +534,7 @@
 // CHECK:   store [[LOAD_OPAQUE]] to [init] [[ALLOC_OPEN]]
 // CHECK:   [[RET_VAL:%.*]] = apply {{.*}}<@opened({{.*}}) Error>([[ALLOC_OPEN]])
 // CHECK:   return [[RET_VAL]] : $String
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s240_____propOfLValueSSs5Error_pF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s240_____propOfLValueySSs5Error_pF'
 func s240_____propOfLValue(_ x: Error) -> String {
   var x = x
   return x._domain
@@ -557,7 +557,7 @@
 
 // Tests Address only enums
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s260_______AOnly_enumyAA17AddressOnlyStructVF : $@convention(thin) (AddressOnlyStruct) -> () {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s260_______AOnly_enumyyAA17AddressOnlyStructVF : $@convention(thin) (AddressOnlyStruct) -> () {
 // CHECK: bb0([[ARG:%.*]] : $AddressOnlyStruct):
 // CHECK:   [[MTYPE1:%.*]] = metatype $@thin AddressOnlyEnum.Type
 // CHECK:   [[APPLY1:%.*]] =  apply {{.*}}([[MTYPE1]]) : $@convention(thin) (@thin AddressOnlyEnum.Type) -> @owned @callee_guaranteed (@in EmptyP) -> @out AddressOnlyEnum
@@ -571,7 +571,7 @@
 // CHECK:   [[MTYPE4:%.*]] = metatype $@thin AddressOnlyEnum.Type
 // CHECK:   [[ENUM3:%.*]] = enum $AddressOnlyEnum, #AddressOnlyEnum.phantom!enumelt.1, [[ARG]] : $AddressOnlyStruct
 // CHECK:   return %{{.*}} : $()
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s260_______AOnly_enumyAA17AddressOnlyStructVF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s260_______AOnly_enumyyAA17AddressOnlyStructVF'
 func s260_______AOnly_enum(_ s: AddressOnlyStruct) {
   _ = AddressOnlyEnum.mere
 
@@ -584,7 +584,7 @@
 
 // Tests InjectOptional for opaque value types + conversion of opaque structs
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s270_convOptAnyStructyAA0gH0VADSgcF : $@convention(thin) (@owned @callee_guaranteed (@in Optional<AnyStruct>) -> @out AnyStruct) -> () {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s270_convOptAnyStructyyAA0gH0VADSgcF : $@convention(thin) (@owned @callee_guaranteed (@in Optional<AnyStruct>) -> @out AnyStruct) -> () {
 // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed (@in Optional<AnyStruct>) -> @out AnyStruct):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]]
@@ -593,14 +593,14 @@
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]] : $@callee_guaranteed (@in Optional<AnyStruct>) -> @out AnyStruct, $@callee_guaranteed (@in Optional<AnyStruct>) -> @out AnyStruct
 // CHECK:   destroy_value [[ARG]] : $@callee_guaranteed (@in Optional<AnyStruct>) -> @out AnyStruct
 // CHECK:   return %{{.*}} : $()
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s270_convOptAnyStructyAA0gH0VADSgcF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s270_convOptAnyStructyyAA0gH0VADSgcF'
 func s270_convOptAnyStruct(_ a1: @escaping (AnyStruct?) -> AnyStruct) {
   let _: (AnyStruct?) -> AnyStruct? = a1
 }
 
 // Tests conversion between existential types
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s280_convExistTrivialyAA0G6StructVAA1P_pcF : $@convention(thin) (@owned @callee_guaranteed (@in P) -> TrivialStruct) -> () {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s280_convExistTrivialyyAA0G6StructVAA1P_pcF : $@convention(thin) (@owned @callee_guaranteed (@in P) -> TrivialStruct) -> () {
 // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed (@in P) -> TrivialStruct):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]]
@@ -609,14 +609,14 @@
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]] : $@callee_guaranteed (@in P) -> TrivialStruct
 // CHECK:   destroy_value [[ARG]]
 // CHECK:   return %{{.*}} : $()
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s280_convExistTrivialyAA0G6StructVAA1P_pcF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s280_convExistTrivialyyAA0G6StructVAA1P_pcF'
 func s280_convExistTrivial(_ s: @escaping (P) -> TrivialStruct) {
   let _: (P2) -> P2 = s
 }
 
 // Tests conversion between existential types - optionals case
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s290_convOptExistTrivyAA13TrivialStructVAA1P_pSgcF : $@convention(thin) (@owned @callee_guaranteed (@in Optional<P>) -> TrivialStruct) -> () {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s290_convOptExistTrivyyAA13TrivialStructVAA1P_pSgcF : $@convention(thin) (@owned @callee_guaranteed (@in Optional<P>) -> TrivialStruct) -> () {
 // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed (@in Optional<P>) -> TrivialStruct):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]]
@@ -625,14 +625,14 @@
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]] : $@callee_guaranteed (@in Optional<P>) -> TrivialStruct, $@callee_guaranteed (@in Optional<P>) -> TrivialStruct
 // CHECK:   destroy_value [[ARG]]
 // CHECK:   return %{{.*}} : $()
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s290_convOptExistTrivyAA13TrivialStructVAA1P_pSgcF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s290_convOptExistTrivyyAA13TrivialStructVAA1P_pSgcF'
 func s290_convOptExistTriv(_ s: @escaping (P?) -> TrivialStruct) {
   let _: (TrivialStruct?) -> P2 = s
 }
 
 // Tests corner-case: reabstraction of an empty tuple to any
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s300__convETupleToAnyyyycF : $@convention(thin) (@owned @callee_guaranteed () -> ()) -> () {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s300__convETupleToAnyyyyycF : $@convention(thin) (@owned @callee_guaranteed () -> ()) -> () {
 // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed () -> ()):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]]
@@ -641,14 +641,14 @@
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]] : $@callee_guaranteed () -> (), $@callee_guaranteed () -> ()
 // CHECK:   destroy_value [[ARG]]
 // CHECK:   return %{{.*}} : $()
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s300__convETupleToAnyyyycF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s300__convETupleToAnyyyyycF'
 func s300__convETupleToAny(_ t: @escaping () -> ()) {
   let _: () -> Any = t
 }
 
 // Tests corner-case: reabstraction of a non-empty tuple to any
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s310__convIntTupleAnyySi_SitycF : $@convention(thin) (@owned @callee_guaranteed () -> (Int, Int)) -> () {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s310__convIntTupleAnyyySi_SitycF : $@convention(thin) (@owned @callee_guaranteed () -> (Int, Int)) -> () {
 // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed () -> (Int, Int)):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]]
@@ -657,14 +657,14 @@
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]] : $@callee_guaranteed () -> (Int, Int), $@callee_guaranteed () -> (Int, Int)
 // CHECK:   destroy_value [[ARG]]
 // CHECK:   return %{{.*}} : $()
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s310__convIntTupleAnyySi_SitycF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s310__convIntTupleAnyyySi_SitycF'
 func s310__convIntTupleAny(_ t: @escaping () -> (Int, Int)) {
   let _: () -> Any = t
 }
 
 // Tests translating and imploding into Any under opaque value mode
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s320__transImplodeAnyyyypcF : $@convention(thin) (@owned @callee_guaranteed (@in Any) -> ()) -> () {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s320__transImplodeAnyyyyypcF : $@convention(thin) (@owned @callee_guaranteed (@in Any) -> ()) -> () {
 // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed (@in Any) -> ()):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]]
@@ -673,18 +673,18 @@
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]] : $@callee_guaranteed (@in Any) -> (), $@callee_guaranteed (@in Any) -> ()
 // CHECK:   destroy_value [[ARG]]
 // CHECK:   return %{{.*}} : $()
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s320__transImplodeAnyyyypcF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s320__transImplodeAnyyyyypcF'
 func s320__transImplodeAny(_ t: @escaping (Any) -> ()) {
   let _: ((Int, Int)) -> () = t
 }
 
 // Tests support for address only let closures under opaque value mode - they are not by-address anymore
 // ---
-// CHECK-LABEL: sil private @_T020opaque_values_silgen21s330___addrLetClosurexxlFxycfU_xycfU_ : $@convention(thin) <T> (@in_guaranteed T) -> @out T {
+// CHECK-LABEL: sil private @_T020opaque_values_silgen21s330___addrLetClosureyxxlFxycfU_xycfU_ : $@convention(thin) <T> (@in_guaranteed T) -> @out T {
 // CHECK: bb0([[ARG:%.*]] : $T):
 // CHECK:   [[COPY_ARG:%.*]] = copy_value [[ARG]] : $T
 // CHECK:   return [[COPY_ARG]] : $T
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s330___addrLetClosurexxlFxycfU_xycfU_'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s330___addrLetClosureyxxlFxycfU_xycfU_'
 func s330___addrLetClosure<T>(_ x:T) -> T {
   return { { x }() }()
 }
@@ -715,7 +715,7 @@
 
 // Tests support for if statements for opaque value(s) under new mode
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s350_______addrOnlyIfAA6EmptyP_pSb1x_tF : $@convention(thin) (Bool) -> @out EmptyP {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s350_______addrOnlyIf1xAA6EmptyP_pSb_tF : $@convention(thin) (Bool) -> @out EmptyP {
 // CHECK: bb0([[ARG:%.*]] : $Bool):
 // CHECK:   [[ALLOC_OF_BOX:%.*]] = alloc_box ${ var EmptyP }, var
 // CHECK:   [[PROJ_BOX:%.*]] = project_box [[ALLOC_OF_BOX]]
@@ -735,7 +735,7 @@
 // CHECK: bb3([[RETVAL:%.*]] : $EmptyP):
 // CHECK:   destroy_value [[ALLOC_OF_BOX]]
 // CHECK:   return [[RETVAL]] : $EmptyP
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s350_______addrOnlyIfAA6EmptyP_pSb1x_tF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s350_______addrOnlyIf1xAA6EmptyP_pSb_tF'
 func s350_______addrOnlyIf(x: Bool) -> EmptyP {
   var a : EmptyP = AddressOnlyStruct()
 
@@ -744,7 +744,7 @@
 
 // Tests support for guards and indirect enums for opaque values
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s360________guardEnumyAA08IndirectF0OyxGlF : $@convention(thin) <T> (@owned IndirectEnum<T>) -> () {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s360________guardEnumyyAA08IndirectF0OyxGlF : $@convention(thin) <T> (@owned IndirectEnum<T>) -> () {
 // CHECK: bb0([[ARG:%.*]] : $IndirectEnum<T>):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[COPY__ARG:%.*]] = copy_value [[BORROWED_ARG]]
@@ -772,7 +772,7 @@
 // CHECK: [[EPILOG_BB]]:
 // CHECK:   destroy_value [[ARG]]
 // CHECK:   return %{{.*}} : $()
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s360________guardEnumyAA08IndirectF0OyxGlF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s360________guardEnumyyAA08IndirectF0OyxGlF'
 func s360________guardEnum<T>(_ e: IndirectEnum<T>) {
   do {
     guard case .Node(let x) = e else { return }
@@ -782,28 +782,28 @@
 
 // Tests contextual init() of opaque value types
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s370_____optToOptCastxSgSQyxGlF : $@convention(thin) <T> (@in Optional<T>) -> @out Optional<T> {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s370_____optToOptCastyxSgSQyxGlF : $@convention(thin) <T> (@in Optional<T>) -> @out Optional<T> {
 // CHECK: bb0([[ARG:%.*]] : $Optional<T>):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[COPY__ARG:%.*]] = copy_value [[BORROWED_ARG]]
 // CHECK:   end_borrow [[BORROWED_ARG]] from [[ARG]] : $Optional<T>, $Optional<T>
 // CHECK:   destroy_value [[ARG]]
 // CHECK:   return [[COPY__ARG]] : $Optional<T>
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s370_____optToOptCastxSgSQyxGlF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s370_____optToOptCastyxSgSQyxGlF'
 func s370_____optToOptCast<T>(_ x : T!) -> T? {
   return x
 }
 
 // Tests casting optional opaques to optional opaques
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s380___contextualInitySiSgF : $@convention(thin) (Optional<Int>) -> () {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s380___contextualInityySiSgF : $@convention(thin) (Optional<Int>) -> () {
 // CHECK: bb0([[ARG:%.*]] : $Optional<Int>):
 // CHECK:   [[ALLOC_OF_BOX:%.*]] = alloc_box ${ var Optional<Int> }, var
 // CHECK:   [[PROJ_BOX:%.*]] = project_box [[ALLOC_OF_BOX]]
 // CHECK:   store [[ARG]] to [trivial] [[PROJ_BOX]] : $*Optional<Int>
 // CHECK:   destroy_value [[ALLOC_OF_BOX]]
 // CHECK:   return %{{.*}} : $()
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s380___contextualInitySiSgF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s380___contextualInityySiSgF'
 func s380___contextualInit(_ a : Int?) {
   var x: Int! = a
   _ = x
@@ -811,7 +811,7 @@
 
 // Tests opaque call result types
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s390___addrCallResultyxycSglF : $@convention(thin) <T> (@owned Optional<@callee_guaranteed () -> @out T>) -> () {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s390___addrCallResultyyxycSglF : $@convention(thin) <T> (@owned Optional<@callee_guaranteed () -> @out T>) -> () {
 // CHECK: bb0([[ARG:%.*]] : $Optional<@callee_guaranteed () -> @out T>):
 // CHECK:   [[ALLOC_OF_BOX:%.*]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T>
 // CHECK:   [[PROJ_BOX:%.*]] = project_box [[ALLOC_OF_BOX]]
@@ -827,7 +827,7 @@
 // CHECK:   br bb4([[ONONE]] : $Optional<T>)
 // CHECK: bb4(%{{.*}} : $Optional<T>):
 // CHECK:   return %{{.*}} : $()
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s390___addrCallResultyxycSglF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s390___addrCallResultyyxycSglF'
 func s390___addrCallResult<T>(_ f: (() -> T)?) {
   var x = f?()
   _ = x
@@ -835,7 +835,7 @@
 
 // Tests reabstraction / partial apply of protocols under opaque value mode
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s400______maybeClonePyAA8Clonable_p1c_tF : $@convention(thin) (@in Clonable) -> () {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s400______maybeCloneP1cyAA8Clonable_p_tF : $@convention(thin) (@in Clonable) -> () {
 // CHECK: bb0([[ARG:%.*]] : $Clonable):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[OPEN_ARG:%.*]] = open_existential_value [[BORROWED_ARG]] : $Clonable
@@ -845,14 +845,14 @@
 // CHECK:   end_borrow [[BORROWED_ARG]]
 // CHECK:   destroy_value [[ARG]]
 // CHECK:   return %{{.*}} : $()
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s400______maybeClonePyAA8Clonable_p1c_tF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s400______maybeCloneP1cyAA8Clonable_p_tF'
 func s400______maybeCloneP(c: Clonable) {
   let _: () -> Clonable? = c.maybeClone
 }
 
 // Tests global opaque values / subscript rvalues
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s410__globalRvalueGetS2iF : $@convention(thin) (Int) -> Int {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s410__globalRvalueGetyS2iF : $@convention(thin) (Int) -> Int {
 // CHECK: bb0([[ARG:%.*]] : $Int):
 // CHECK:   [[GLOBAL_ADDR:%.*]] = global_addr @_T020opaque_values_silgen16subscriptableGetAA013SubscriptableE0_pvp : $*SubscriptableGet
 // CHECK:   [[READ:%.*]] = begin_access [read] [dynamic] [[GLOBAL_ADDR]] : $*SubscriptableGet
@@ -861,14 +861,14 @@
 // CHECK:   [[RETVAL:%.*]] = apply %{{.*}}<@opened({{.*}}) SubscriptableGet>([[ARG]], [[GET_OPAQUE]]) : $@convention(witness_method: SubscriptableGet) <τ_0_0 where τ_0_0 : SubscriptableGet> (Int, @in_guaranteed τ_0_0) -> Int
 // CHECK:   destroy_value [[GET_OPAQUE]]
 // CHECK:   return [[RETVAL]] : $Int
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s410__globalRvalueGetS2iF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s410__globalRvalueGetyS2iF'
 func s410__globalRvalueGet(_ i : Int) -> Int {
   return subscriptableGet[i]
 }
 
 // Tests global opaque values / subscript lvalues
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s420__globalLvalueGetS2iF : $@convention(thin) (Int) -> Int {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s420__globalLvalueGetyS2iF : $@convention(thin) (Int) -> Int {
 // CHECK: bb0([[ARG:%.*]] : $Int):
 // CHECK:   [[GLOBAL_ADDR:%.*]] = global_addr @_T020opaque_values_silgen19subscriptableGetSetAA013SubscriptableeF0_pvp : $*SubscriptableGetSet
 // CHECK:   [[READ:%.*]] = begin_access [read] [dynamic] [[GLOBAL_ADDR]] : $*SubscriptableGetSet
@@ -877,14 +877,14 @@
 // CHECK:   [[RETVAL:%.*]] = apply %{{.*}}<@opened({{.*}}) SubscriptableGetSet>([[ARG]], [[GET_OPAQUE]]) : $@convention(witness_method: SubscriptableGetSet) <τ_0_0 where τ_0_0 : SubscriptableGetSet> (Int, @in_guaranteed τ_0_0) -> Int
 // CHECK:   destroy_value [[GET_OPAQUE]]
 // CHECK:   return [[RETVAL]] : $Int
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s420__globalLvalueGetS2iF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s420__globalLvalueGetyS2iF'
 func s420__globalLvalueGet(_ i : Int) -> Int {
   return subscriptableGetSet[i]
 }
 
 // Tests tuple transformation
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s430_callUnreachableFyx1t_tlF : $@convention(thin) <T> (@in T) -> () {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s430_callUnreachableF1tyx_tlF : $@convention(thin) <T> (@in T) -> () {
 // CHECK: bb0([[ARG:%.*]] : $T):
 // CHECK:   [[APPLY_T:%.*]] = apply %{{.*}}<((T) -> (), T)>() : $@convention(thin) <τ_0_0> () -> @out Optional<(Int, τ_0_0)>
 // CHECK:   switch_enum [[APPLY_T]] : $Optional<(Int, (@callee_guaranteed (@in T) -> @out (), T))>, case #Optional.some!enumelt.1: bb2, case #Optional.none!enumelt: bb1
@@ -899,14 +899,14 @@
 // CHECK: bb3([[ENUMIN:%.*]] : $Optional<(Int, (@callee_guaranteed (@in T) -> (), T))>):
 // CHECK:   destroy_value [[ENUMIN]]
 // CHECK:   return %{{.*}} : $()
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s430_callUnreachableFyx1t_tlF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s430_callUnreachableF1tyx_tlF'
 func s430_callUnreachableF<T>(t: T) {
   let _: (Int, ((T) -> (), T))? = unreachableF()
 }
 
 // Further testing for conditional checked cast under opaque value mode - make sure we don't create a buffer for results
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s440__cleanupEmissionyxlF : $@convention(thin) <T> (@in T) -> () {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s440__cleanupEmissionyyxlF : $@convention(thin) <T> (@in T) -> () {
 // CHECK: bb0([[ARG:%.*]] : $T):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:   [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]]
@@ -937,7 +937,7 @@
 // CHECK: [[EPILOG_BB]]:
 // CHECK:   destroy_value [[ARG]]
 // CHECK:   return %{{.*}} : $()
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s440__cleanupEmissionyxlF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s440__cleanupEmissionyyxlF'
 func s440__cleanupEmission<T>(_ x: T) {
   guard let x2 = x as? EmptyP else { return }
   _ = x2
@@ -945,10 +945,10 @@
 
 // Test SILGenBuilder.loadCopy().
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s450__________lastValxxd_tlF : $@convention(thin) <T> (@owned Array<T>) -> @out T
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s450__________lastValyxxd_tlF : $@convention(thin) <T> (@owned Array<T>) -> @out T
 // CHECK: [[LOAD:%.*]] = load [copy] %{{.*}} : $*T
 // CHECK: return [[LOAD]] : $T
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s450__________lastValxxd_tlF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s450__________lastValyxxd_tlF'
 func s450__________lastVal<T>(_ rest: T...) -> T {
   var minValue: T
   for value in rest {
@@ -959,28 +959,28 @@
 
 // Test SILGenFunction::emitPointerToPointer.
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s460______________fooSRyxGSPyxG1p_tlF : $@convention(thin) <Element> (UnsafePointer<Element>) -> UnsafeBufferPointer<Element> {
-// CHECK: [[F:%.*]] = function_ref @_T0s017_convertPointerToB8Argumentq_xs01_B0RzsABR_r0_lF : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : _Pointer, τ_0_1 : _Pointer> (@in τ_0_0) -> @out τ_0_1
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s460______________foo1pSRyxGSPyxG_tlF : $@convention(thin) <Element> (UnsafePointer<Element>) -> UnsafeBufferPointer<Element> {
+// CHECK: [[F:%.*]] = function_ref @_T0s017_convertPointerToB8Argumentyq_xs01_B0RzsABR_r0_lF : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : _Pointer, τ_0_1 : _Pointer> (@in τ_0_0) -> @out τ_0_1
 // CHECK: apply [[F]]<UnsafePointer<Element>, UnsafePointer<Element>>(%0) : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : _Pointer, τ_0_1 : _Pointer> (@in τ_0_0) -> @out τ_0_1
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s460______________fooSRyxGSPyxG1p_tlF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s460______________foo1pSRyxGSPyxG_tlF'
 func s460______________foo<Element>(p: UnsafePointer<Element>) -> UnsafeBufferPointer<Element> {
   return UnsafeBufferPointer(start: p, count: 1)
 }
 
 // Test emitNativeToCBridgedNonoptionalValue.
 // ---
-// CHECK-objc-LABEL: sil hidden @_T020opaque_values_silgen21s470________nativeToCyXlyp7fromAny_tF : $@convention(thin) (@in Any) -> @owned AnyObject {
+// CHECK-objc-LABEL: sil hidden @_T020opaque_values_silgen21s470________nativeToC7fromAnyyXlyp_tF : $@convention(thin) (@in Any) -> @owned AnyObject {
 // CHECK-objc bb0(%0 : $Any):
 // CHECK-objc [[BORROW:%.*]] = begin_borrow %0 : $Any
 // CHECK-objc [[SRC:%.*]] = copy_value [[BORROW]] : $Any
 // CHECK-objc [[OPEN:%.*]] = open_existential_opaque [[SRC]] : $Any to $@opened
 // CHECK-objc [[COPY:%.*]] = copy_value [[OPEN]] : $@opened
-// CHECK-objc [[F:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @owned AnyObject
+// CHECK-objc [[F:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyyXlxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @owned AnyObject
 // CHECK-objc [[RET:%.*]] = apply [[F]]<@opened("{{.*}}") Any>([[COPY]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @owned AnyObject
 // CHECK-objc destroy_value [[SRC]] : $Any
 // CHECK-objc destroy_value %0 : $Any
 // CHECK-objc return [[RET]] : $AnyObject
-// CHECK-objc-LABEL: } // end sil function '_T020opaque_values_silgen21s470________nativeToCyXlyp7fromAny_tF'
+// CHECK-objc-LABEL: } // end sil function '_T020opaque_values_silgen21s470________nativeToC7fromAnyyXlyp_tF'
 #if _runtime(_ObjC)
 func s470________nativeToC(fromAny any: Any) -> AnyObject {
   return any as AnyObject
@@ -989,7 +989,7 @@
 
 // Test emitOpenExistential.
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s480_________getErroryps0F0_p04someF0_tF : $@convention(thin) (@owned Error) -> @out Any {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s480_________getError04someF0yps0F0_p_tF : $@convention(thin) (@owned Error) -> @out Any {
 // CHECK: bb0(%0 : $Error):
 // CHECK: [[BORROW:%.*]] = begin_borrow %0 : $Error
 // CHECK: [[VAL:%.*]] = open_existential_box_value [[BORROW]] : $Error to $@opened("{{.*}}") Error
@@ -997,14 +997,14 @@
 // CHECK: [[ANY:%.*]] = init_existential_value [[COPY]] : $@opened("{{.*}}") Error, $@opened("{{.*}}") Error, $Any
 // CHECK: destroy_value %0 : $Error
 // CHECK: return [[ANY]] : $Any
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s480_________getErroryps0F0_p04someF0_tF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s480_________getError04someF0yps0F0_p_tF'
 func s480_________getError(someError: Error) -> Any {
   return someError
 }
 
 // Test SILBuilder.createLoadBorrow.
 // ---
-// CHECK-LABEL: sil private @_T020opaque_values_silgen21s490_______loadBorrowyyF3FooL_V3foo7ElementQzSg5IndexQz3pos_tF : $@convention(method) <Elements where Elements : Collection> (@in Elements.Index, @inout Foo<Elements>) -> @out Optional<Elements.Element> {
+// CHECK-LABEL: sil private @_T020opaque_values_silgen21s490_______loadBorrowyyF3FooL_V3foo3pos7ElementQzSg5IndexQz_tF : $@convention(method) <Elements where Elements : Collection> (@in Elements.Index, @inout Foo<Elements>) -> @out Optional<Elements.Element> {
 // CHECK: bb0(%0 : $Elements.Index, %1 : $*Foo<Elements>):
 // CHECK: [[READ:%.*]] = begin_access [read] [unknown] %1 : $*Foo<Elements>
 // CHECK: [[LOAD:%.*]] = load [copy] [[READ]] : $*Foo<Elements>
@@ -1022,7 +1022,7 @@
 // CHECK: destroy_value [[LOAD]]
 // CHECK: destroy_value %0 : $Elements.Index
 // CHECK: return %15 : $Optional<Elements.Element>
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s490_______loadBorrowyyF3FooL_V3foo7ElementQzSg5IndexQz3pos_tF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s490_______loadBorrowyyF3FooL_V3foo3pos7ElementQzSg5IndexQz_tF'
 
 func s490_______loadBorrow() {
   struct Foo<Elements : Collection> {
@@ -1042,7 +1042,7 @@
 
 // Test visitBindOptionalExpr
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s500_______getAnyHashAA1P_pSgAA14ConvertibleToP_pSgF : $@convention(thin) (@in Optional<ConvertibleToP>) -> @out Optional<P> {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s500_______getAnyHashyAA1P_pSgAA14ConvertibleToP_pSgF : $@convention(thin) (@in Optional<ConvertibleToP>) -> @out Optional<P> {
 // CHECK: bb0(%0 : $Optional<ConvertibleToP>):
 // CHECK: [[BORROW_ARG:%.*]] = begin_borrow %0 : $Optional<ConvertibleToP>
 // CHECK: [[COPY:%.*]] = copy_value [[BORROW_ARG]] : $Optional<ConvertibleToP>
@@ -1055,7 +1055,7 @@
 // CHECK: destroy_value [[DATA]] : $ConvertibleToP
 // CHECK: end_borrow [[BORROW_ARG]] from %0 : $Optional<ConvertibleToP>, $Optional<ConvertibleToP>
 // CHECK: br bb{{.*}}([[ENUM]] : $Optional<P>)
-// CHECK: // end sil function '_T020opaque_values_silgen21s500_______getAnyHashAA1P_pSgAA14ConvertibleToP_pSgF'
+// CHECK: // end sil function '_T020opaque_values_silgen21s500_______getAnyHashyAA1P_pSgAA14ConvertibleToP_pSgF'
 func s500_______getAnyHash(_ value: ConvertibleToP?) -> P? {
   return value?.asP()
 }
@@ -1082,7 +1082,7 @@
 
 // Tests conditional value casts and correspondingly generated reabstraction thunk, with <T> types
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s999_____condTFromAnyyyp_xtlF : $@convention(thin) <T> (@in Any, @in T) -> () {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s999_____condTFromAnyyyyp_xtlF : $@convention(thin) <T> (@in Any, @in T) -> () {
 // CHECK: bb0([[ARG0:%.*]] : $Any, [[ARG1:%.*]] : $T):
 // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG0]]
 // CHECK:   [[COPY__ARG:%.*]] = copy_value [[BORROWED_ARG]]
@@ -1092,7 +1092,7 @@
 // CHECK:   partial_apply [callee_guaranteed] [[THUNK_REF]]<T>([[THUNK_PARAM]])
 // CHECK: bb6:
 // CHECK:   return %{{.*}} : $()
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s999_____condTFromAnyyyp_xtlF'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s999_____condTFromAnyyyyp_xtlF'
 func s999_____condTFromAny<T>(_ x: Any, _ y: T) {
   if let f = x as? (Int, T) -> (Int, T) {
     _ = f(42, y)
@@ -1125,11 +1125,11 @@
 
 // s250_________testBoxT continued Test Implicit Value Construction under Opaque value mode
 // ---
-// CHECK-LABEL: sil hidden @_T020opaque_values_silgen3BoxVACyxGx1t_tcfC : $@convention(method) <T> (@in T, @thin Box<T>.Type) -> @out Box<T> {
+// CHECK-LABEL: sil hidden @_T020opaque_values_silgen3BoxV1tACyxGx_tcfC : $@convention(method) <T> (@in T, @thin Box<T>.Type) -> @out Box<T> {
 // CHECK: bb0([[ARG0:%.*]] : $T, [[ARG1:%.*]] : $@thin Box<T>.Type):
 // CHECK:   [[RETVAL:%.*]] = struct $Box<T> ([[ARG0]] : $T)
 // CHECK:   return [[RETVAL]] : $Box<T>
-// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen3BoxVACyxGx1t_tcfC'
+// CHECK-LABEL: } // end sil function '_T020opaque_values_silgen3BoxV1tACyxGx_tcfC'
 
 // s270_convOptAnyStruct continued Test: reabstraction thunk helper
 // ---
@@ -1206,7 +1206,7 @@
 
 // Tests LogicalPathComponent's writeback for opaque value types
 // ---
-// CHECK-LABEL: sil @_T0s10DictionaryV20opaque_values_silgenE22inoutAccessOfSubscriptyq_3key_tF : $@convention(method) <Key, Value where Key : Hashable> (@in Value, @inout Dictionary<Key, Value>) -> () {
+// CHECK-LABEL: sil @_T0s10DictionaryV20opaque_values_silgenE22inoutAccessOfSubscript3keyyq__tF : $@convention(method) <Key, Value where Key : Hashable> (@in Value, @inout Dictionary<Key, Value>) -> () {
 // CHECK: bb0([[ARG0:%.*]] : $Value, [[ARG1:%.*]] : $*Dictionary<Key, Value>):
 // CHECK:   [[WRITE:%.*]] = begin_access [modify] [unknown] [[ARG1]] : $*Dictionary<Key, Value>
 // CHECK:   [[OPTIONAL_ALLOC:%.*]] = alloc_stack $Optional<Value>
@@ -1215,11 +1215,11 @@
 // CHECK:   [[OPTIONAL_LOAD:%.*]] = load [take] [[OPTIONAL_ALLOC]] : $*Optional<Value>
 // CHECK:   apply {{.*}}<Key, Value>([[OPTIONAL_LOAD]], {{.*}}, [[WRITE]]) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@in Optional<τ_0_1>, @in τ_0_1, @inout Dictionary<τ_0_0, τ_0_1>) -> ()
 // CHECK:   return %{{.*}} : $()
-// CHECK-LABEL: } // end sil function '_T0s10DictionaryV20opaque_values_silgenE22inoutAccessOfSubscriptyq_3key_tF'
+// CHECK-LABEL: } // end sil function '_T0s10DictionaryV20opaque_values_silgenE22inoutAccessOfSubscript3keyyq__tF'
 
 // Tests materializeForSet's createSetterCallback for opaque values
 // ---
-// CHECK-LABEL: sil shared [transparent] [serialized] @_T0s10DictionaryV20opaque_values_silgenEq_Sgq_cimytfU_ : $@convention(method) <Key, Value where Key : Hashable> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Dictionary<Key, Value>, @thick Dictionary<Key, Value>.Type) -> () {
+// CHECK-LABEL: sil shared [transparent] [serialized] @_T0s10DictionaryV20opaque_values_silgenEyq_Sgq_cimytfU_ : $@convention(method) <Key, Value where Key : Hashable> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Dictionary<Key, Value>, @thick Dictionary<Key, Value>.Type) -> () {
 // CHECK: bb0([[ARG0:%.*]] : $Builtin.RawPointer, [[ARG1:%.*]] : $*Builtin.UnsafeValueBuffer, [[ARG2:%.*]] : $*Dictionary<Key, Value>, [[ARG3:%.*]] : $@thick Dictionary<Key, Value>.Type):
 // CHECK:   [[PROJ_VAL1:%.*]] = project_value_buffer $Value in [[ARG1]] : $*Builtin.UnsafeValueBuffer
 // CHECK:   [[LOAD_VAL1:%.*]] = load [take] [[PROJ_VAL1]] : $*Value
@@ -1227,7 +1227,7 @@
 // CHECK:   [[LOAD_VAL0:%.*]] = load [take] [[ADDR_VAL0]] : $*Optional<Value>
 // CHECK:   apply {{.*}}<Key, Value>([[LOAD_VAL0]], [[LOAD_VAL1]], [[ARG2]]) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@in Optional<τ_0_1>, @in τ_0_1, @inout Dictionary<τ_0_0, τ_0_1>) -> ()
 // CHECK:   return %{{.*}} : $()
-// CHECK-LABEL: } // end sil function '_T0s10DictionaryV20opaque_values_silgenEq_Sgq_cimytfU_'
+// CHECK-LABEL: } // end sil function '_T0s10DictionaryV20opaque_values_silgenEyq_Sgq_cimytfU_'
 extension Dictionary {
   public subscript(key: Value) -> Value? {
     @inline(__always)
diff --git a/test/SILGen/opaque_values_silgen_lib.swift b/test/SILGen/opaque_values_silgen_lib.swift
index 0f8f99f..44a1587 100644
--- a/test/SILGen/opaque_values_silgen_lib.swift
+++ b/test/SILGen/opaque_values_silgen_lib.swift
@@ -27,21 +27,21 @@
 
 // Test emitBuiltinReinterpretCast.
 // ---
-// CHECK-LABEL: sil hidden @_T0s21s020__________bitCastq_x_q_m2totr0_lF : $@convention(thin) <T, U> (@in T, @thick U.Type) -> @out U {
+// CHECK-LABEL: sil hidden @_T0s21s020__________bitCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in T, @thick U.Type) -> @out U {
 // CHECK: [[BORROW:%.*]] = begin_borrow %0 : $T
 // CHECK: [[COPY:%.*]] = copy_value [[BORROW]] : $T
 // CHECK: [[CAST:%.*]] = unchecked_bitwise_cast [[COPY]] : $T to $U
 // CHECK: [[RET:%.*]] = copy_value [[CAST]] : $U
 // CHECK: destroy_value [[COPY]] : $T
 // CHECK: return [[RET]] : $U
-// CHECK-LABEL: } // end sil function '_T0s21s020__________bitCastq_x_q_m2totr0_lF'
+// CHECK-LABEL: } // end sil function '_T0s21s020__________bitCast_2toq_x_q_mtr0_lF'
 func s020__________bitCast<T, U>(_ x: T, to type: U.Type) -> U {
   return Builtin.reinterpretCast(x)
 }
 
 // Test emitBuiltinCastReference
 // ---
-// CHECK-LABEL: sil hidden @_T0s21s030__________refCastq_x_q_m2totr0_lF : $@convention(thin) <T, U> (@in T, @thick U.Type) -> @out U {
+// CHECK-LABEL: sil hidden @_T0s21s030__________refCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in T, @thick U.Type) -> @out U {
 // CHECK: bb0(%0 : @owned $T, %1 : @trivial $@thick U.Type):
 // CHECK: [[BORROW:%.*]] = begin_borrow %0 : $T
 // CHECK: [[COPY:%.*]] = copy_value [[BORROW]] : $T
@@ -54,23 +54,23 @@
 // CHECK: dealloc_stack [[SRC]] : $*T
 // CHECK: destroy_value %0 : $T
 // CHECK: return [[LOAD]] : $U
-// CHECK-LABEL: } // end sil function '_T0s21s030__________refCastq_x_q_m2totr0_lF'
+// CHECK-LABEL: } // end sil function '_T0s21s030__________refCast_2toq_x_q_mtr0_lF'
 func s030__________refCast<T, U>(_ x: T, to: U.Type) -> U {
   return Builtin.castReference(x)
 }
 
 // Init of Empty protocol + Builtin.NativeObject enum (including opaque tuples as a return value)
 // ---
-// CHECK-LABEL: sil shared [transparent] @_T0s9PAndSEnumO1AABs6EmptyP_p_SStcABmF : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum {
+// CHECK-LABEL: sil shared [transparent] @_T0s9PAndSEnumO1AyABs6EmptyP_p_SStcABmF : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum {
 // CHECK: bb0([[ARG0:%.*]] : @owned $EmptyP, [[ARG1:%.*]]  : @owned $String, [[ARG2:%.*]] : @trivial $@thin PAndSEnum.Type):
 // CHECK:   [[RTUPLE:%.*]] = tuple ([[ARG0]] : $EmptyP, [[ARG1]] : $String)
 // CHECK:   [[RETVAL:%.*]] = enum $PAndSEnum, #PAndSEnum.A!enumelt.1, [[RTUPLE]] : $(EmptyP, String)
 // CHECK:   return [[RETVAL]] : $PAndSEnum
-// CHECK-LABEL: } // end sil function '_T0s9PAndSEnumO1AABs6EmptyP_p_SStcABmF'
-// CHECK-LABEL: sil shared [transparent] [thunk] @_T0s9PAndSEnumO1AABs6EmptyP_p_SStcABmFTc : $@convention(thin) (@thin PAndSEnum.Type) -> @owned @callee_guaranteed (@in EmptyP, @owned String) -> @out PAndSEnum {
+// CHECK-LABEL: } // end sil function '_T0s9PAndSEnumO1AyABs6EmptyP_p_SStcABmF'
+// CHECK-LABEL: sil shared [transparent] [thunk] @_T0s9PAndSEnumO1AyABs6EmptyP_p_SStcABmFTc : $@convention(thin) (@thin PAndSEnum.Type) -> @owned @callee_guaranteed (@in EmptyP, @owned String) -> @out PAndSEnum {
 // CHECK: bb0([[ARG:%.*]] : @trivial $@thin PAndSEnum.Type):
 // CHECK:   [[RETVAL:%.*]] = partial_apply [callee_guaranteed] {{.*}}([[ARG]]) : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum
 // CHECK:   return [[RETVAL]] : $@callee_guaranteed (@in EmptyP, @owned String) -> @out PAndSEnum
-// CHECK-LABEL: } // end sil function '_T0s9PAndSEnumO1AABs6EmptyP_p_SStcABmFTc'
+// CHECK-LABEL: } // end sil function '_T0s9PAndSEnumO1AyABs6EmptyP_p_SStcABmFTc'
 enum PAndSEnum { case A(EmptyP, String) }
 
diff --git a/test/SILGen/optional-cast.swift b/test/SILGen/optional-cast.swift
index a5a6e32..fc0ba3a 100644
--- a/test/SILGen/optional-cast.swift
+++ b/test/SILGen/optional-cast.swift
@@ -3,7 +3,7 @@
 class A {}
 class B : A {}
 
-// CHECK-LABEL: sil hidden @_T04main3fooyAA1ACSgF : $@convention(thin) (@owned Optional<A>) -> () {
+// CHECK-LABEL: sil hidden @_T04main3fooyyAA1ACSgF : $@convention(thin) (@owned Optional<A>) -> () {
 // CHECK:    bb0([[ARG:%.*]] : @owned $Optional<A>):
 // CHECK:      [[X:%.*]] = alloc_box ${ var Optional<B> }, var, name "x"
 // CHECK-NEXT: [[PB:%.*]] = project_box [[X]]
@@ -55,7 +55,7 @@
   var x = (y as? B)
 }
 
-// CHECK-LABEL: sil hidden @_T04main3baryAA1ACSgSgSgSgF : $@convention(thin) (@owned Optional<Optional<Optional<Optional<A>>>>) -> () {
+// CHECK-LABEL: sil hidden @_T04main3baryyAA1ACSgSgSgSgF : $@convention(thin) (@owned Optional<Optional<Optional<Optional<A>>>>) -> () {
 // CHECK:    bb0([[ARG:%.*]] : @owned $Optional<Optional<Optional<Optional<A>>>>):
 // CHECK:      [[X:%.*]] = alloc_box ${ var Optional<Optional<Optional<B>>> }, var, name "x"
 // CHECK-NEXT: [[PB:%.*]] = project_box [[X]]
@@ -163,7 +163,7 @@
 }
 
 
-// CHECK-LABEL: sil hidden @_T04main3bazyyXlSgF : $@convention(thin) (@owned Optional<AnyObject>) -> () {
+// CHECK-LABEL: sil hidden @_T04main3bazyyyXlSgF : $@convention(thin) (@owned Optional<AnyObject>) -> () {
 // CHECK:       bb0([[ARG:%.*]] : @owned $Optional<AnyObject>):
 // CHECK:         [[X:%.*]] = alloc_box ${ var Optional<B> }, var, name "x"
 // CHECK-NEXT:    [[PB:%.*]] = project_box [[X]]
@@ -178,7 +178,7 @@
 // CHECK:         store [[CASTED_VALUE]] to [init] [[X_VALUE]]
 // CHECK:       [[NOT_B]]([[ORIGINAL_VALUE:%.*]] : @owned $AnyObject):
 // CHECK:         destroy_value [[ORIGINAL_VALUE]]
-// CHECK: } // end sil function '_T04main3bazyyXlSgF'
+// CHECK: } // end sil function '_T04main3bazyyyXlSgF'
 func baz(_ y : AnyObject?) {
   var x = (y as? B)
 }
@@ -186,7 +186,7 @@
 
 // <rdar://problem/17013042> T! <-> T? conversions should not produce a diamond
 
-// CHECK-LABEL: sil hidden @_T04main07opt_to_B8_trivialSQySiGSiSgF
+// CHECK-LABEL: sil hidden @_T04main07opt_to_B8_trivialySQySiGSiSgF
 // CHECK:       bb0(%0 : @trivial $Optional<Int>):
 // CHECK-NEXT:  debug_value %0 : $Optional<Int>, let, name "x"
 // CHECK-NEXT:  return %0 : $Optional<Int>
@@ -195,14 +195,14 @@
   return x
 }
 
-// CHECK-LABEL: sil hidden @_T04main07opt_to_B10_referenceAA1CCSgSQyADGF :
+// CHECK-LABEL: sil hidden @_T04main07opt_to_B10_referenceyAA1CCSgSQyADGF :
 // CHECK:  bb0([[ARG:%.*]] : @owned $Optional<C>):
 // CHECK:    debug_value [[ARG]] : $Optional<C>, let, name "x"
 // CHECK:    [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
 // CHECK:    [[RESULT:%.*]] = copy_value [[BORROWED_ARG]]
 // CHECK:    destroy_value [[ARG]]
 // CHECK:    return [[RESULT]] : $Optional<C>
-// CHECK: } // end sil function '_T04main07opt_to_B10_referenceAA1CCSgSQyADGF'
+// CHECK: } // end sil function '_T04main07opt_to_B10_referenceyAA1CCSgSQyADGF'
 func opt_to_opt_reference(_ x : C!) -> C? { return x }
 
 // CHECK-LABEL: sil hidden @_T04main07opt_to_B12_addressOnly{{[_0-9a-zA-Z]*}}F
@@ -227,7 +227,7 @@
   }
 }
 
-// CHECK-LABEL: sil hidden @_T04main35testContextualInitOfNonAddrOnlyTypeySiSgF
+// CHECK-LABEL: sil hidden @_T04main35testContextualInitOfNonAddrOnlyTypeyySiSgF
 // CHECK: bb0(%0 : @trivial $Optional<Int>):
 // CHECK-NEXT: debug_value %0 : $Optional<Int>, let, name "a"
 // CHECK-NEXT: [[X:%.*]] = alloc_box ${ var Optional<Int> }, var, name "x"
diff --git a/test/SILGen/optional.swift b/test/SILGen/optional.swift
index 589d202..8be5e8e 100644
--- a/test/SILGen/optional.swift
+++ b/test/SILGen/optional.swift
@@ -30,7 +30,7 @@
 // CHECK:    [[NOTHING_BLOCK_EXIT]]:
 // CHECK-NEXT: enum $Optional<()>, #Optional.none!enumelt
 // CHECK-NEXT: br [[EXIT]]
-// CHECK: } // end sil function '_T08optional8testCallyyycSgF'
+// CHECK: } // end sil function '_T08optional8testCallyyyycSgF'
 
 func testAddrOnlyCallResult<T>(_ f: (() -> T)?) {
   var f = f
@@ -102,7 +102,7 @@
 
 // rdar://21883752 - We were crashing on this function because the deallocation happened
 // out of scope.
-// CHECK-LABEL: sil hidden @_T08optional16crash_on_deallocys10DictionaryVySiSaySiGGFfA_
+// CHECK-LABEL: sil hidden @_T08optional16crash_on_deallocyys10DictionaryVySiSaySiGGFfA_
 func crash_on_dealloc(_ dict : [Int : [Int]] = [:]) {
   var dict = dict
   dict[1]?.append(2)
diff --git a/test/SILGen/optional_lvalue.swift b/test/SILGen/optional_lvalue.swift
index 57e81ea..cd61cf64 100644
--- a/test/SILGen/optional_lvalue.swift
+++ b/test/SILGen/optional_lvalue.swift
@@ -1,6 +1,6 @@
 // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
-// CHECK-LABEL: sil hidden @_T015optional_lvalue07assign_a1_B0ySiSgz_SitF
+// CHECK-LABEL: sil hidden @_T015optional_lvalue07assign_a1_B0yySiSgz_SitF
 // CHECK:         [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<Int>
 // CHECK:         [[PRECOND:%.*]] = function_ref @_T0s30_diagnoseUnexpectedNilOptional{{[_0-9a-zA-Z]*}}F
 // CHECK:         apply [[PRECOND]](
@@ -10,7 +10,7 @@
   x! = y
 }
 
-// CHECK-LABEL: sil hidden @_T015optional_lvalue011assign_iuo_B0ySQySiGz_SitF
+// CHECK-LABEL: sil hidden @_T015optional_lvalue011assign_iuo_B0yySQySiGz_SitF
 // CHECK:         [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<Int>
 // CHECK:         [[PRECOND:%.*]] = function_ref @_T0s30_diagnoseUnexpectedNilOptional{{[_0-9a-zA-Z]*}}F
 // CHECK:         apply [[PRECOND]](
@@ -29,7 +29,7 @@
   }
 }
 
-// CHECK-LABEL: sil hidden @_T015optional_lvalue011assign_iuo_B9_implicitySQyAA1SVGz_SitF
+// CHECK-LABEL: sil hidden @_T015optional_lvalue011assign_iuo_B9_implicityySQyAA1SVGz_SitF
 // CHECK:         [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<S>
 // CHECK:         [[SOME:%.*]] = unchecked_take_enum_data_addr [[WRITE]]
 // CHECK:         [[X:%.*]] = struct_element_addr [[SOME]]
@@ -41,7 +41,7 @@
   var value: T?
 }
 
-// CHECK-LABEL: sil hidden @_T015optional_lvalue07assign_a1_B13_reabstractedyAA6StructVyS2icGz_S2ictF
+// CHECK-LABEL: sil hidden @_T015optional_lvalue07assign_a1_B13_reabstractedyyAA6StructVyS2icGz_S2ictF
 // CHECK:         [[REABSTRACT:%.*]] = function_ref @_T0S2iIegyd_S2iIegir_TR
 // CHECK:         [[REABSTRACTED:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]
 // CHECK:         assign [[REABSTRACTED]] to {{%.*}} : $*@callee_guaranteed (@in Int) -> @out Int
@@ -50,7 +50,7 @@
   x.value! = y
 }
 
-// CHECK-LABEL: sil hidden @_T015optional_lvalue07assign_a1_B9_computedSiAA1SVSgz_SitF
+// CHECK-LABEL: sil hidden @_T015optional_lvalue07assign_a1_B9_computedySiAA1SVSgz_SitF
 // CHECK:         function_ref @_T015optional_lvalue1SV8computedSivs
 // CHECK:         function_ref @_T015optional_lvalue1SV8computedSivg
 func assign_optional_lvalue_computed(_ x: inout S?, _ y: Int) -> Int {
@@ -60,7 +60,7 @@
 
 func generate_int() -> Int { return 0 }
 
-// CHECK-LABEL: sil hidden @_T015optional_lvalue013assign_bound_a1_B0ySiSgzF
+// CHECK-LABEL: sil hidden @_T015optional_lvalue013assign_bound_a1_B0yySiSgzF
 // CHECK:         select_enum_addr
 // CHECK:         cond_br {{%.*}}, [[SOME:bb[0-9]+]], [[NONE:bb[0-9]+]]
 // CHECK:       [[SOME]]:
diff --git a/test/SILGen/partial_apply_generic.swift b/test/SILGen/partial_apply_generic.swift
index 1cae879..71a7914 100644
--- a/test/SILGen/partial_apply_generic.swift
+++ b/test/SILGen/partial_apply_generic.swift
@@ -67,16 +67,16 @@
 // CHECK-NEXT: return
 }
 
-// CHECK-LABEL: sil hidden @_T021partial_apply_generic23getNonCanonicalSelfFuncyq_cxcxm1t_t7CuddlesQy_RszAA5PandaR_r0_lF : $@convention(thin) <T, U where T == U.Cuddles, U : Panda> (@thick T.Type) -> @owned @callee_guaranteed (@in T) -> @owned @callee_guaranteed (@in U) -> () {
+// CHECK-LABEL: sil hidden @_T021partial_apply_generic23getNonCanonicalSelfFunc1tyq_cxcxm_t7CuddlesQy_RszAA5PandaR_r0_lF : $@convention(thin) <T, U where T == U.Cuddles, U : Panda> (@thick T.Type) -> @owned @callee_guaranteed (@in T) -> @owned @callee_guaranteed (@in U) -> () {
 func getNonCanonicalSelfFunc<T : Foo, U : Panda>(t: T.Type) -> (T) -> (U) -> () where U.Cuddles == T {
-// CHECK: [[REF:%.*]] = function_ref @_T021partial_apply_generic3FooP21makesSelfNonCanonicalyqd__7CuddlesQyd__RszAA5PandaRd__lFTc : $@convention(thin) <τ_0_0><τ_1_0 where τ_0_0 == τ_1_0.Cuddles, τ_1_0 : Panda> (@in τ_0_0) -> @owned @callee_guaranteed (@in τ_1_0) -> ()
+// CHECK: [[REF:%.*]] = function_ref @_T021partial_apply_generic3FooP21makesSelfNonCanonicalyyqd__7CuddlesQyd__RszAA5PandaRd__lFTc : $@convention(thin) <τ_0_0><τ_1_0 where τ_0_0 == τ_1_0.Cuddles, τ_1_0 : Panda> (@in τ_0_0) -> @owned @callee_guaranteed (@in τ_1_0) -> ()
 // CHECK-NEXT: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[REF]]<T, U>()
   return t.makesSelfNonCanonical
 // CHECK-NEXT: return [[CLOSURE]]
 }
 
 // curry thunk of Foo.makesSelfNonCanonical<A where ...> (A1) -> ()
-// CHECK-LABEL: sil shared [thunk] @_T021partial_apply_generic3FooP21makesSelfNonCanonicalyqd__7CuddlesQyd__RszAA5PandaRd__lFTc : $@convention(thin) <Self><T where Self == T.Cuddles, T : Panda> (@in Self) -> @owned @callee_guaranteed (@in T) -> () {
+// CHECK-LABEL: sil shared [thunk] @_T021partial_apply_generic3FooP21makesSelfNonCanonicalyyqd__7CuddlesQyd__RszAA5PandaRd__lFTc : $@convention(thin) <Self><T where Self == T.Cuddles, T : Panda> (@in Self) -> @owned @callee_guaranteed (@in T) -> () {
 // CHECK: [[REF:%.*]] = witness_method $Self, #Foo.makesSelfNonCanonical!1 : <Self><T where Self == T.Cuddles, T : Panda> (Self) -> (T) -> () : $@convention(witness_method: Foo) <τ_0_0><τ_1_0 where τ_0_0 == τ_1_0.Cuddles, τ_1_0 : Panda> (@in τ_1_0, @in_guaranteed τ_0_0) -> ()
 // CHECK-NEXT: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[REF]]<Self, T>(%0)
 // CHECK-NEXT: return [[CLOSURE]]
diff --git a/test/SILGen/partial_apply_protocol.swift b/test/SILGen/partial_apply_protocol.swift
index 2792fda..0dcd9a4 100644
--- a/test/SILGen/partial_apply_protocol.swift
+++ b/test/SILGen/partial_apply_protocol.swift
@@ -15,7 +15,7 @@
 // Partial apply of methods returning Self-derived types
 //===----------------------------------------------------------------------===//
 
-// CHECK-LABEL: sil hidden @_T022partial_apply_protocol12testClonableyAA0E0_p1c_tF : $@convention(thin) (@in Clonable) -> ()
+// CHECK-LABEL: sil hidden @_T022partial_apply_protocol12testClonable1cyAA0E0_p_tF : $@convention(thin) (@in Clonable) -> ()
 func testClonable(c: Clonable) {
   // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xIegr_22partial_apply_protocol8Clonable_pIegr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @out τ_0_0) -> @out Clonable
   // CHECK: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}})
@@ -97,7 +97,7 @@
 // Make sure the thunk only has the context generic parameters if needed!
 //===----------------------------------------------------------------------===//
 
-// CHECK-LABEL: sil hidden @_T022partial_apply_protocol28testClonableInGenericContextyAA0E0_p1c_x1ttlF : $@convention(thin) <T> (@in Clonable, @in T) -> ()
+// CHECK-LABEL: sil hidden @_T022partial_apply_protocol28testClonableInGenericContext1c1tyAA0E0_p_xtlF : $@convention(thin) <T> (@in Clonable, @in T) -> ()
 func testClonableInGenericContext<T>(c: Clonable, t: T) {
   // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xIegr_22partial_apply_protocol8Clonable_pIegr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @out τ_0_0) -> @out Clonable
   // CHECK: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}})
diff --git a/test/SILGen/partial_apply_protocol_class_refinement_method.swift b/test/SILGen/partial_apply_protocol_class_refinement_method.swift
index 28e4c5a..2602b6b 100644
--- a/test/SILGen/partial_apply_protocol_class_refinement_method.swift
+++ b/test/SILGen/partial_apply_protocol_class_refinement_method.swift
@@ -3,7 +3,7 @@
 protocol P { func foo() }
 protocol Q: class, P {}
 
-// CHECK-LABEL: sil hidden @_T046partial_apply_protocol_class_refinement_method0A5ApplyyycAA1Q_pF
+// CHECK-LABEL: sil hidden @_T046partial_apply_protocol_class_refinement_method0A5ApplyyyycAA1Q_pF
 func partialApply(_ q: Q) -> () -> () {
   // CHECK: [[OPENED:%.*]] = open_existential_ref
   // CHECK: [[COPY:%.*]] = copy_value [[OPENED]]
diff --git a/test/SILGen/partial_apply_super.swift b/test/SILGen/partial_apply_super.swift
index 671c7f3..735d402 100644
--- a/test/SILGen/partial_apply_super.swift
+++ b/test/SILGen/partial_apply_super.swift
@@ -36,7 +36,7 @@
   // CHECK:   [[SUPER_METHOD:%[0-9]+]] = function_ref @_T019partial_apply_super6ParentC6methodyyFTcTd : $@convention(thin) (@owned Parent) -> @owned @callee_guaranteed () -> ()
   // CHECK:   [[PARTIAL_APPLY:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(thin) (@owned Parent) -> @owned @callee_guaranteed () -> ()
   // CHECK:   [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
-  // CHECK:   [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
+  // CHECK:   [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK:   apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK: } // end sil function '_T019partial_apply_super5ChildC6methodyyF'
   override func method() {
@@ -48,7 +48,7 @@
   // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T019partial_apply_super6ParentC11classMethodyyFZTcTd : $@convention(thin) (@thick Parent.Type) -> @owned @callee_guaranteed () -> ()
   // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(thin) (@thick Parent.Type) -> @owned @callee_guaranteed () -> ()
   // CHECK:   [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
-  // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
+  // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   override class func classMethod() {
     doFoo(super.classMethod)
@@ -61,7 +61,7 @@
   // CHECK:     [[SUPER_METHOD:%[0-9]+]] = function_ref @_T019partial_apply_super6ParentC11finalMethodyyFTc : $@convention(thin) (@owned Parent) -> @owned @callee_guaranteed () -> ()
   // CHECK:     [[APPLIED_SELF:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(thin) (@owned Parent) -> @owned @callee_guaranteed () -> ()
   // CHECK:     [[CONVERT:%.*]] = convert_function [[APPLIED_SELF]]
-  // CHECK:     [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
+  // CHECK:     [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK:     apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK: } // end sil function '_T019partial_apply_super5ChildC20callFinalSuperMethodyyF'
   func callFinalSuperMethod() {
@@ -73,7 +73,7 @@
   // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T019partial_apply_super6ParentC16finalClassMethodyyFZTc : $@convention(thin) (@thick Parent.Type) -> @owned @callee_guaranteed () -> ()
   // CHECK: [[APPLIED_SELF:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(thin) (@thick Parent.Type) -> @owned @callee_guaranteed () -> ()
   // CHECK: [[CONVERT:%.*]] = convert_function [[APPLIED_SELF]]
-  // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
+  // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   class func callFinalSuperClassMethod() {
     doFoo(super.finalClassMethod)
@@ -91,7 +91,7 @@
   // CHECK:     [[SUPER_METHOD:%[0-9]+]] = function_ref @_T019partial_apply_super13GenericParentC6methodyyFTcTd : $@convention(thin) <τ_0_0> (@owned GenericParent<τ_0_0>) -> @owned @callee_guaranteed () -> ()
   // CHECK:     [[PARTIAL_APPLY:%[0-9]+]] = apply [[SUPER_METHOD]]<A>([[CASTED_SELF_COPY]]) : $@convention(thin) <τ_0_0> (@owned GenericParent<τ_0_0>) -> @owned @callee_guaranteed () -> ()
   // CHECK:     [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
-  // CHECK:     [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
+  // CHECK:     [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK:     apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK: } // end sil function '_T019partial_apply_super12GenericChildC6methodyyF'
   override func method() {
@@ -103,7 +103,7 @@
   // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T019partial_apply_super13GenericParentC11classMethodyyFZTcTd : $@convention(thin) <τ_0_0> (@thick GenericParent<τ_0_0>.Type) -> @owned @callee_guaranteed () -> ()
   // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = apply [[SUPER_METHOD]]<A>([[CASTED_SELF]]) : $@convention(thin) <τ_0_0> (@thick GenericParent<τ_0_0>.Type) -> @owned @callee_guaranteed () -> ()
   // CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
-  // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
+  // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   override class func classMethod() {
     doFoo(super.classMethod)
@@ -121,7 +121,7 @@
   // CHECK: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
   // CHECK:   [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(method) (@guaranteed OutsideParent) -> ()
   // CHECK:   [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
-  // CHECK:   [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
+  // CHECK:   [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK:   apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK: } // end sil function '_T019partial_apply_super25ChildToFixedOutsideParentC6methodyyF'
   override func method() {
@@ -133,7 +133,7 @@
   // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick ChildToFixedOutsideParent.Type, #OutsideParent.classMethod!1 : (OutsideParent.Type) -> () -> (), $@convention(method) (@thick OutsideParent.Type) -> (){{.*}}
   // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@thick OutsideParent.Type) -> ()
   // CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
-  // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
+  // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   override class func classMethod() {
     doFoo(super.classMethod)
@@ -151,7 +151,7 @@
   // CHECK:   end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
   // CHECK:   [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(method) (@guaranteed ResilientOutsideParent) -> ()
   // CHECK:   [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
-  // CHECK:   [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
+  // CHECK:   [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK:   apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK: } // end sil function '_T019partial_apply_super29ChildToResilientOutsideParentC6methodyyF'
   override func method() {
@@ -163,7 +163,7 @@
   // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick ChildToResilientOutsideParent.Type, #ResilientOutsideParent.classMethod!1 : (ResilientOutsideParent.Type) -> () -> (), $@convention(method) (@thick ResilientOutsideParent.Type) -> ()
   // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@thick ResilientOutsideParent.Type) -> ()
   // CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
-  // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
+  // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   override class func classMethod() {
     doFoo(super.classMethod)
@@ -181,7 +181,7 @@
   // CHECK:     end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
   // CHECK:     [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(method) (@guaranteed OutsideChild) -> ()
   // CHECK:     [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
-  // CHECK:     [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
+  // CHECK:     [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK:     apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK: } // end sil function '_T019partial_apply_super29GrandchildToFixedOutsideChildC6methodyyF'
   override func method() {
@@ -193,7 +193,7 @@
   // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GrandchildToFixedOutsideChild.Type, #OutsideChild.classMethod!1 : (OutsideChild.Type) -> () -> (), $@convention(method) (@thick OutsideChild.Type) -> ()
   // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@thick OutsideChild.Type) -> ()
   // CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
-  // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
+  // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   override class func classMethod() {
     doFoo(super.classMethod)
@@ -211,7 +211,7 @@
   // CHEC:      end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
   // CHECK:     [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(method) (@guaranteed ResilientOutsideChild) -> ()
   // CHECK:     [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
-  // CHECK:     [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
+  // CHECK:     [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK:     apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK: } // end sil function '_T019partial_apply_super33GrandchildToResilientOutsideChildC6methodyyF'
   override func method() {
@@ -223,7 +223,7 @@
   // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GrandchildToResilientOutsideChild.Type, #ResilientOutsideChild.classMethod!1 : (ResilientOutsideChild.Type) -> () -> (), $@convention(method) (@thick ResilientOutsideChild.Type) -> ()
   // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@thick ResilientOutsideChild.Type) -> ()
   // CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
-  // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
+  // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   override class func classMethod() {
     doFoo(super.classMethod)
@@ -241,7 +241,7 @@
   // CHECK:     end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
   // CHECK:     [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]<A>([[CASTED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed GenericOutsideParent<τ_0_0>) -> ()
   // CHECK:     [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
-  // CHECK:     [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
+  // CHECK:     [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK:     apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK: } // end sil function '_T019partial_apply_super019GenericChildToFixedD13OutsideParentC6methodyyF'
   override func method() {
@@ -253,7 +253,7 @@
   // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GenericChildToFixedGenericOutsideParent<A>.Type, #GenericOutsideParent.classMethod!1 : <A> (GenericOutsideParent<A>.Type) -> () -> (), $@convention(method) <τ_0_0> (@thick GenericOutsideParent<τ_0_0>.Type) -> ()
   // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]<A>([[CASTED_SELF]]) : $@convention(method) <τ_0_0> (@thick GenericOutsideParent<τ_0_0>.Type) -> ()
   // CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
-  // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
+  // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   override class func classMethod() {
     doFoo(super.classMethod)
@@ -271,7 +271,7 @@
   // CHECK:     end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
   // CHECK:     [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]<A>([[CASTED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed ResilientGenericOutsideParent<τ_0_0>) -> ()
   // CHECK:     [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
-  // CHECK:     [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
+  // CHECK:     [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK:     apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK: } // end sil function '_T019partial_apply_super023GenericChildToResilientD13OutsideParentC6methodyyF'
   override func method() {
@@ -283,7 +283,7 @@
   // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GenericChildToResilientGenericOutsideParent<A>.Type, #ResilientGenericOutsideParent.classMethod!1 : <A> (ResilientGenericOutsideParent<A>.Type) -> () -> (), $@convention(method) <τ_0_0> (@thick ResilientGenericOutsideParent<τ_0_0>.Type) -> ()
   // CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [callee_guaranteed] [[SUPER_METHOD]]<A>([[CASTED_SELF]]) : $@convention(method) <τ_0_0> (@thick ResilientGenericOutsideParent<τ_0_0>.Type) -> ()
   // CHECK: [[CONVERT:%.*]] = convert_function [[PARTIAL_APPLY]]
-  // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
+  // CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyyycF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   // CHECK: apply [[DOFOO]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> ()) -> ()
   override class func classMethod() {
     doFoo(super.classMethod)
diff --git a/test/SILGen/pgo_checked_cast.swift b/test/SILGen/pgo_checked_cast.swift
index 6ee7a21..32b76c9 100644
--- a/test/SILGen/pgo_checked_cast.swift
+++ b/test/SILGen/pgo_checked_cast.swift
@@ -13,7 +13,7 @@
 // REQUIRES: OS=macosx
 
 // SIL-LABEL: // pgo_checked_cast.check1<A>(Any, A) -> A
-// SIL-LABEL: sil @_T016pgo_checked_cast6check1xyp_xtlF : $@convention(thin) <T> (@in Any, @in T) -> @out T !function_entry_count(5001) {
+// SIL-LABEL: sil @_T016pgo_checked_cast6check1yxyp_xtlF : $@convention(thin) <T> (@in Any, @in T) -> @out T !function_entry_count(5001) {
 // IR-LABEL: define swiftcc i32 @_T06pgo_checked_cast6guess1s5Int32VAD1x_tF
 // IR-OPT-LABEL: define swiftcc i32 @_T06pgo_checked_cast6guess1s5Int32VAD1x_tF
 public func check1<T>(_ a : Any, _ t : T) -> T {
@@ -31,7 +31,7 @@
 public class D : C {}
 
 // SIL-LABEL: // pgo_checked_cast.check2(pgo_checked_cast.B) -> Swift.Int32
-// SIL-LABEL: sil @_T016pgo_checked_cast6check2s5Int32VAA1BCF : $@convention(thin) (@owned B) -> Int32 !function_entry_count(5003) {
+// SIL-LABEL: sil @_T016pgo_checked_cast6check2ys5Int32VAA1BCF : $@convention(thin) (@owned B) -> Int32 !function_entry_count(5003) {
 // IR-LABEL: define swiftcc i32 @_T06pgo_checked_cast6guess1s5Int32VAD1x_tF
 // IR-OPT-LABEL: define swiftcc i32 @_T06pgo_checked_cast6guess1s5Int32VAD1x_tF
 public func check2(_ a : B) -> Int32 {
diff --git a/test/SILGen/pgo_foreach.swift b/test/SILGen/pgo_foreach.swift
index 2ab281c..dd49f81 100644
--- a/test/SILGen/pgo_foreach.swift
+++ b/test/SILGen/pgo_foreach.swift
@@ -15,7 +15,7 @@
 // REQUIRES: OS=macosx
 
 // SIL-LABEL: // pgo_foreach.guessForEach1
-// SIL-LABEL: sil @_T011pgo_foreach13guessForEach1s5Int32VAD1x_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(42) {
+// SIL-LABEL: sil @_T011pgo_foreach13guessForEach11xs5Int32VAE_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(42) {
 // IR-LABEL: define swiftcc i32 @_T09pgo_foreach10guessWhiles5Int32VAD1x_tF
 // IR-OPT-LABEL: define swiftcc i32 @_T09pgo_foreach10guessWhiles5Int32VAD1x_tF
 
@@ -30,7 +30,7 @@
 }
 
 // SIL-LABEL: // pgo_foreach.guessForEach2
-// SIL-LABEL: sil @_T011pgo_foreach13guessForEach2s5Int32VAD1x_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(42) {
+// SIL-LABEL: sil @_T011pgo_foreach13guessForEach21xs5Int32VAE_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(42) {
 // IR-LABEL: define swiftcc i32 @_T09pgo_foreach10guessWhiles5Int32VAD1x_tF
 // IR-OPT-LABEL: define swiftcc i32 @_T09pgo_foreach10guessWhiles5Int32VAD1x_tF
 
diff --git a/test/SILGen/pgo_guard.swift b/test/SILGen/pgo_guard.swift
index 0b79a52..187e201 100644
--- a/test/SILGen/pgo_guard.swift
+++ b/test/SILGen/pgo_guard.swift
@@ -11,9 +11,9 @@
 // REQUIRES: OS=macosx
 
 // SIL-LABEL: // pgo_guard.guess1
-// SIL-LABEL: sil @_T09pgo_guard6guess1s5Int32VAD1x_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(5002) {
-// IR-LABEL: define swiftcc i32 @_T09pgo_guard6guess1s5Int32VAD1x_tF
-// IR-OPT-LABEL: define swiftcc i32 @_T09pgo_guard6guess1s5Int32VAD1x_tF
+// SIL-LABEL: sil @_T09pgo_guard6guess11xs5Int32VAE_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(5002) {
+// IR-LABEL: define swiftcc i32 @_T09pgo_guard6guess11xs5Int32VAE_tF
+// IR-OPT-LABEL: define swiftcc i32 @_T09pgo_guard6guess11xs5Int32VAE_tF
 
 public func guess1(x: Int32) -> Int32 {
   // SIL: cond_br {{.*}} !true_count(5000) !false_count(2)
diff --git a/test/SILGen/pgo_if.swift b/test/SILGen/pgo_if.swift
index 018dc62..a8d6165 100644
--- a/test/SILGen/pgo_if.swift
+++ b/test/SILGen/pgo_if.swift
@@ -11,9 +11,9 @@
 // REQUIRES: OS=macosx
 
 // SIL-LABEL: // pgo_if.guess1
-// SIL-LABEL: sil @_T06pgo_if6guess1s5Int32VAD1x_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(5001) {
-// IR-LABEL: define swiftcc i32 @_T06pgo_if6guess1s5Int32VAD1x_tF
-// IR-OPT-LABEL: define swiftcc i32 @_T06pgo_if6guess1s5Int32VAD1x_tF
+// SIL-LABEL: sil @_T06pgo_if6guess11xs5Int32VAE_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(5001) {
+// IR-LABEL: define swiftcc i32 @_T06pgo_if6guess11xs5Int32VAE_tF
+// IR-OPT-LABEL: define swiftcc i32 @_T06pgo_if6guess11xs5Int32VAE_tF
 public func guess1(x: Int32) -> Int32 {
   // SIL: cond_br {{.*}} !true_count(5000) !false_count(1)
   // SIL-OPT: cond_br {{.*}} !true_count(5000) !false_count(1)
@@ -27,9 +27,9 @@
 }
 
 // SIL-LABEL: // pgo_if.guess2
-// SIL-LABEL: sil @_T06pgo_if6guess2s5Int32VAD1x_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(5001) {
-// IR-LABEL: define swiftcc i32 @_T06pgo_if6guess2s5Int32VAD1x_tF
-// IR-OPT-LABEL: define swiftcc i32 @_T06pgo_if6guess2s5Int32VAD1x_tF
+// SIL-LABEL: sil @_T06pgo_if6guess21xs5Int32VAE_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(5001) {
+// IR-LABEL: define swiftcc i32 @_T06pgo_if6guess21xs5Int32VAE_tF
+// IR-OPT-LABEL: define swiftcc i32 @_T06pgo_if6guess21xs5Int32VAE_tF
 public func guess2(x: Int32) -> Int32 {
   // SIL: cond_br {{.*}} !true_count(5000) !false_count(1)
   // SIL-OPT: cond_br {{.*}} !true_count(5000) !false_count(1)
diff --git a/test/SILGen/pgo_repeatwhile.swift b/test/SILGen/pgo_repeatwhile.swift
index e55ddfa..66db06b 100644
--- a/test/SILGen/pgo_repeatwhile.swift
+++ b/test/SILGen/pgo_repeatwhile.swift
@@ -12,9 +12,9 @@
 // REQUIRES: OS=macosx
 
 // SIL-LABEL: // pgo_repeatwhile.guessWhile
-// SIL-LABEL: sil @_T015pgo_repeatwhile10guessWhiles5Int32VAD1x_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(42) {
-// IR-LABEL: define swiftcc i32 @_T015pgo_repeatwhile10guessWhiles5Int32VAD1x_tF
-// IR-OPT-LABEL: define swiftcc i32 @_T015pgo_repeatwhile10guessWhiles5Int32VAD1x_tF
+// SIL-LABEL: sil @_T015pgo_repeatwhile10guessWhile1xs5Int32VAE_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(42) {
+// IR-LABEL: define swiftcc i32 @_T015pgo_repeatwhile10guessWhile1xs5Int32VAE_tF
+// IR-OPT-LABEL: define swiftcc i32 @_T015pgo_repeatwhile10guessWhile1xs5Int32VAE_tF
 
 public func guessWhile(x: Int32) -> Int32 {
   // SIL: cond_br {{.*}} !true_count(176400) !false_count(420)
diff --git a/test/SILGen/pgo_switchenum.swift b/test/SILGen/pgo_switchenum.swift
index 079154b..4c754cc 100644
--- a/test/SILGen/pgo_switchenum.swift
+++ b/test/SILGen/pgo_switchenum.swift
@@ -22,7 +22,7 @@
 }
 
 // SIL-LABEL: // pgo_switchenum.guess1
-// SIL-LABEL: sil @_T014pgo_switchenum6guess1s5Int32VAA9MaybePairO1x_tF : $@convention(thin) (@owned MaybePair) -> Int32 !function_entry_count(5011) {
+// SIL-LABEL: sil @_T014pgo_switchenum6guess11xs5Int32VAA9MaybePairO_tF : $@convention(thin) (@owned MaybePair) -> Int32 !function_entry_count(5011) {
 // IR-LABEL: define swiftcc i32 @_T09pgo_switchenum6guess1s5Int32VAD1x_tF
 // IR-OPT-LABEL: define swiftcc i32 @_T09pgo_switchenum6guess1s5Int32VAD1x_tF
 
@@ -42,7 +42,7 @@
 }
 
 // SIL-LABEL: // pgo_switchenum.guess2
-// SIL-LABEL: sil @_T014pgo_switchenum6guess2s5Int32VAA9MaybePairO1x_tF : $@convention(thin) (@owned MaybePair) -> Int32 !function_entry_count(5011) {
+// SIL-LABEL: sil @_T014pgo_switchenum6guess21xs5Int32VAA9MaybePairO_tF : $@convention(thin) (@owned MaybePair) -> Int32 !function_entry_count(5011) {
 public func guess2(x: MaybePair) -> Int32 {
   // SIL: switch_enum {{.*}} : $MaybePair, case #MaybePair.Neither!enumelt: {{.*}} !case_count(2), case #MaybePair.Left!enumelt.1: {{.*}} !case_count(5001), default {{.*}} !default_count(8)
   // SIL-OPT: switch_enum {{.*}} : $MaybePair, case #MaybePair.Neither!enumelt: {{.*}} !case_count(2), case #MaybePair.Left!enumelt.1: {{.*}} !case_count(5001), default {{.*}} !default_count(8)
diff --git a/test/SILGen/pgo_while.swift b/test/SILGen/pgo_while.swift
index 20238d7..413ec5d 100644
--- a/test/SILGen/pgo_while.swift
+++ b/test/SILGen/pgo_while.swift
@@ -12,9 +12,9 @@
 // REQUIRES: OS=macosx
 
 // SIL-LABEL: // pgo_while.guessWhile
-// SIL-LABEL: sil @_T09pgo_while10guessWhiles5Int32VAD1x_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(42) {
-// IR-LABEL: define swiftcc i32 @_T09pgo_while10guessWhiles5Int32VAD1x_tF
-// IR-OPT-LABEL: define swiftcc i32 @_T09pgo_while10guessWhiles5Int32VAD1x_tF
+// SIL-LABEL: sil @_T09pgo_while10guessWhile1xs5Int32VAE_tF : $@convention(thin) (Int32) -> Int32 !function_entry_count(42) {
+// IR-LABEL: define swiftcc i32 @_T09pgo_while10guessWhile1xs5Int32VAE_tF
+// IR-OPT-LABEL: define swiftcc i32 @_T09pgo_while10guessWhile1xs5Int32VAE_tF
 
 public func guessWhile(x: Int32) -> Int32 {
   // SIL: cond_br {{.*}} !true_count(420) !false_count(42)
diff --git a/test/SILGen/pointer_conversion.swift b/test/SILGen/pointer_conversion.swift
index b60314e..7ed8716 100644
--- a/test/SILGen/pointer_conversion.swift
+++ b/test/SILGen/pointer_conversion.swift
@@ -20,7 +20,7 @@
 func takesOptConstRawPointer(_ x: UnsafeRawPointer?, and: Int) {}
 func takesOptOptConstRawPointer(_ x: UnsafeRawPointer??, and: Int) {}
 
-// CHECK-LABEL: sil hidden @_T018pointer_conversion0A9ToPointerySpySiG_SPySiGSvtF
+// CHECK-LABEL: sil hidden @_T018pointer_conversion0A9ToPointeryySpySiG_SPySiGSvtF
 // CHECK: bb0([[MP:%.*]] : $UnsafeMutablePointer<Int>, [[CP:%.*]] : $UnsafePointer<Int>, [[MRP:%.*]] : $UnsafeMutableRawPointer):
 func pointerToPointer(_ mp: UnsafeMutablePointer<Int>,
   _ cp: UnsafePointer<Int>, _ mrp: UnsafeMutableRawPointer) {
@@ -39,47 +39,47 @@
   takesMutableRawPointer(mp)
   // CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
   // CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeMutableRawPointer>
-  // CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion22takesMutableRawPointerySvF :
+  // CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion22takesMutableRawPointeryySvF :
   // CHECK: apply [[TAKES_MUTABLE_RAW_POINTER]]
 
   takesConstPointer(mp)
   // CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
   // CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafePointer<Int>>
-  // CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion17takesConstPointerySPySiGF
+  // CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion17takesConstPointeryySPySiGF
   // CHECK: apply [[TAKES_CONST_POINTER]]
 
   takesConstVoidPointer(mp)
   // CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
   // CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeRawPointer>
-  // CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_T018pointer_conversion21takesConstVoidPointerySVF
+  // CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_T018pointer_conversion21takesConstVoidPointeryySVF
   // CHECK: apply [[TAKES_CONST_VOID_POINTER]]
 
   takesConstRawPointer(mp)
   // CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
   // CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeRawPointer>
-  // CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySVF :
+  // CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointeryySVF :
   // CHECK: apply [[TAKES_CONST_RAW_POINTER]]
 
   takesConstPointer(cp)
-  // CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion17takesConstPointerySPySiGF
+  // CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion17takesConstPointeryySPySiGF
   // CHECK: apply [[TAKES_CONST_POINTER]]([[CP]])
 
   takesConstVoidPointer(cp)
   // CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
   // CHECK: apply [[CONVERT]]<UnsafePointer<Int>, UnsafeRawPointer>
-  // CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_T018pointer_conversion21takesConstVoidPointerySVF
+  // CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_T018pointer_conversion21takesConstVoidPointeryySVF
   // CHECK: apply [[TAKES_CONST_VOID_POINTER]]
 
   takesConstRawPointer(cp)
   // CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
   // CHECK: apply [[CONVERT]]<UnsafePointer<Int>, UnsafeRawPointer>
-  // CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySVF
+  // CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointeryySVF
   // CHECK: apply [[TAKES_CONST_RAW_POINTER]]
 
   takesConstRawPointer(mrp)
   // CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
   // CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer, UnsafeRawPointer>
-  // CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySVF
+  // CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointeryySVF
   // CHECK: apply [[TAKES_CONST_RAW_POINTER]]
 }
 
@@ -101,7 +101,7 @@
   // CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafePointer<Int>>([[POINTER_BUF:%[0-9]*]],
   // CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
   // CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafePointer<Int> on [[OWNER]]
-  // CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion17takesConstPointerySPySiGF
+  // CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion17takesConstPointeryySPySiGF
   // CHECK: apply [[TAKES_CONST_POINTER]]([[DEPENDENT]])
   // CHECK: destroy_value [[OWNER]]
 
@@ -110,7 +110,7 @@
   // CHECK: [[OWNER:%.*]] = apply [[CONVERT_MUTABLE]]<Int, UnsafeMutableRawPointer>([[POINTER_BUF:%[0-9]*]],
   // CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
   // CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeMutableRawPointer on [[OWNER]]
-  // CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion22takesMutableRawPointerySvF :
+  // CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion22takesMutableRawPointeryySvF :
   // CHECK: apply [[TAKES_MUTABLE_RAW_POINTER]]([[DEPENDENT]])
   // CHECK: destroy_value [[OWNER]]
 
@@ -119,7 +119,7 @@
   // CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
   // CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
   // CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
-  // CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySVF :
+  // CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointeryySVF :
   // CHECK: apply [[TAKES_CONST_RAW_POINTER]]([[DEPENDENT]])
   // CHECK: destroy_value [[OWNER]]
 
@@ -131,19 +131,19 @@
   // CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
   // CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafePointer<Int> on [[OWNER]]
   // CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt.1, [[DEPENDENT]]
-  // CHECK: [[TAKES_OPT_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesOptConstPointerySPySiGSg_Si3andtF :
+  // CHECK: [[TAKES_OPT_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesOptConstPointer_3andySPySiGSg_SitF :
   // CHECK: apply [[TAKES_OPT_CONST_POINTER]]([[OPTPTR]], [[RESULT1]])
   // CHECK: destroy_value [[OWNER]]
 }
 
-// CHECK-LABEL: sil hidden @_T018pointer_conversion15stringToPointerySSF 
+// CHECK-LABEL: sil hidden @_T018pointer_conversion15stringToPointeryySSF
 func stringToPointer(_ s: String) {
   takesConstVoidPointer(s)
   // CHECK: [[CONVERT_STRING:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
   // CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
   // CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
   // CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
-  // CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_T018pointer_conversion21takesConstVoidPointerySV{{[_0-9a-zA-Z]*}}F
+  // CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_T018pointer_conversion21takesConstVoidPointeryySV{{[_0-9a-zA-Z]*}}F
   // CHECK: apply [[TAKES_CONST_VOID_POINTER]]([[DEPENDENT]])
   // CHECK: destroy_value [[OWNER]]
 
@@ -152,7 +152,7 @@
   // CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
   // CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
   // CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
-  // CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySV{{[_0-9a-zA-Z]*}}F
+  // CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointeryySV{{[_0-9a-zA-Z]*}}F
   // CHECK: apply [[TAKES_CONST_RAW_POINTER]]([[DEPENDENT]])
   // CHECK: destroy_value [[OWNER]]
 
@@ -164,7 +164,7 @@
   // CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
   // CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
   // CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt.1, [[DEPENDENT]]
-  // CHECK: [[TAKES_OPT_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion23takesOptConstRawPointerySVSg_Si3andtF :
+  // CHECK: [[TAKES_OPT_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion23takesOptConstRawPointer_3andySVSg_SitF :
   // CHECK: apply [[TAKES_OPT_CONST_RAW_POINTER]]([[OPTPTR]], [[RESULT1]])
   // CHECK: destroy_value [[OWNER]]
 }
@@ -242,7 +242,7 @@
   // CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITEBACK]]
   // CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
   // CHECK: apply [[CONVERT]]<AutoreleasingUnsafeMutablePointer<C>>({{%.*}}, [[POINTER]])
-  // CHECK: [[TAKES_PLUS_ZERO:%.*]] = function_ref @_T018pointer_conversion20takesPlusZeroPointerys026AutoreleasingUnsafeMutableF0VyAA1CCGF
+  // CHECK: [[TAKES_PLUS_ZERO:%.*]] = function_ref @_T018pointer_conversion20takesPlusZeroPointeryys026AutoreleasingUnsafeMutableF0VyAA1CCGF
   // CHECK: apply [[TAKES_PLUS_ZERO]]
   // CHECK: [[UNOWNED_OUT:%.*]] = load [trivial] [[WRITEBACK]]
   // CHECK: [[OWNED_OUT:%.*]] = unmanaged_to_ref [[UNOWNED_OUT]]
@@ -285,7 +285,7 @@
   // CHECK: [[SIDE2:%.*]] = function_ref @_T018pointer_conversion11sideEffect2SiyF
   // CHECK: [[RESULT2:%.*]] = apply [[SIDE2]]()
   // CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[ARRAY]] : $*Array<Int>
-  // CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_T018pointer_conversion19takesMutablePointerySpySiG_Si3andtF
+  // CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_T018pointer_conversion19takesMutablePointer_3andySpySiG_SitF
   // CHECK: apply [[TAKES_MUTABLE]]({{.*}}, [[RESULT2]])
   // CHECK: strong_unpin
   // CHECK: end_access [[ACCESS]]
@@ -296,14 +296,14 @@
   // CHECK: [[SIDE2:%.*]] = function_ref @_T018pointer_conversion11sideEffect2SiyF
   // CHECK: [[RESULT2:%.*]] = apply [[SIDE2]]()
   // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[ARRAY]] : $*Array<Int>
-  // CHECK: [[TAKES_CONST:%.*]] = function_ref @_T018pointer_conversion17takesConstPointerySPySiG_Si3andtF
+  // CHECK: [[TAKES_CONST:%.*]] = function_ref @_T018pointer_conversion17takesConstPointer_3andySPySiG_SitF
   // CHECK: apply [[TAKES_CONST]]({{.*}}, [[RESULT2]])
   // CHECK: end_access [[ACCESS]]
   takesConstPointer(&array[sideEffect1()], and: sideEffect2())
 }
 
 // rdar://problem/31542269
-// CHECK-LABEL: sil hidden @_T018pointer_conversion20optArrayToOptPointerySaySiGSg5array_tF
+// CHECK-LABEL: sil hidden @_T018pointer_conversion20optArrayToOptPointer5arrayySaySiGSg_tF
 func optArrayToOptPointer(array: [Int]?) {
   // CHECK:   [[BORROW:%.*]] = begin_borrow %0
   // CHECK:   [[COPY:%.*]] = copy_value [[BORROW]]
@@ -313,7 +313,7 @@
   // CHECK:   cond_br [[T0]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]]
   // CHECK: [[SOME_BB]]:
   // CHECK:   [[SOME_VALUE:%.*]] = unchecked_enum_data [[COPY]]
-  // CHECK:   [[CONVERT:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgumentyXlSg_q_tSayxGs01_E0R_r0_lF
+  // CHECK:   [[CONVERT:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgumentyyXlSg_q_tSayxGs01_E0R_r0_lF
   // CHECK:   [[TEMP:%.*]] = alloc_stack $UnsafePointer<Int>
   // CHECK:   [[OWNER:%.*]] = apply [[CONVERT]]<Int, UnsafePointer<Int>>([[TEMP:%.*]], [[SOME_VALUE]])
   // CHECK:   [[PTR:%.*]] = load [trivial] [[TEMP]]
@@ -323,7 +323,7 @@
   // CHECK:   br [[CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafePointer<Int>>, [[OWNER]] : $Optional<AnyObject>)
   // CHECK: [[CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafePointer<Int>>, [[OWNER:%.*]] : $Optional<AnyObject>):
   // CHECK:   [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafePointer<Int>> on [[OWNER]]
-  // CHECK:   [[TAKES:%.*]] = function_ref @_T018pointer_conversion20takesOptConstPointerySPySiGSg_Si3andtF
+  // CHECK:   [[TAKES:%.*]] = function_ref @_T018pointer_conversion20takesOptConstPointer_3andySPySiGSg_SitF
   // CHECK:   apply [[TAKES]]([[OPTDEP]], [[RESULT1]])
   // CHECK:   destroy_value [[OWNER]]
   // CHECK:   end_borrow [[BORROW]]
@@ -335,7 +335,7 @@
   takesOptConstPointer(array, and: sideEffect1())
 }
 
-// CHECK-LABEL: sil hidden @_T018pointer_conversion013optOptArrayTodD7PointerySaySiGSgSg5array_tF
+// CHECK-LABEL: sil hidden @_T018pointer_conversion013optOptArrayTodD7Pointer5arrayySaySiGSgSg_tF
 func optOptArrayToOptOptPointer(array: [Int]??) {
   // CHECK:   [[BORROW:%.*]] = begin_borrow %0
   // CHECK:   [[COPY:%.*]] = copy_value [[BORROW]]
@@ -352,7 +352,7 @@
   // CHECK:   br [[SOME_NONE_BB2:bb[0-9]+]]
   // CHECK: [[SOME_SOME_BB]]:
   // CHECK:   [[SOME_SOME_VALUE:%.*]] = unchecked_enum_data [[SOME_VALUE]]
-  // CHECK:   [[CONVERT:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgumentyXlSg_q_tSayxGs01_E0R_r0_lF
+  // CHECK:   [[CONVERT:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgumentyyXlSg_q_tSayxGs01_E0R_r0_lF
   // CHECK:   [[TEMP:%.*]] = alloc_stack $UnsafePointer<Int>
   // CHECK:   [[OWNER:%.*]] = apply [[CONVERT]]<Int, UnsafePointer<Int>>([[TEMP:%.*]], [[SOME_SOME_VALUE]])
   // CHECK:   [[PTR:%.*]] = load [trivial] [[TEMP]]
@@ -366,7 +366,7 @@
   // CHECK:   br [[SOME_CONT_BB:bb[0-9]+]]([[OPTOPTPTR]] : $Optional<Optional<UnsafePointer<Int>>>, [[OWNER]] : $Optional<AnyObject>)
   // CHECK: [[SOME_CONT_BB]]([[OPTOPTPTR:%.*]] : $Optional<Optional<UnsafePointer<Int>>>, [[OWNER:%.*]] : $Optional<AnyObject>):
   // CHECK:   [[OPTOPTDEP:%.*]] = mark_dependence [[OPTOPTPTR]] : $Optional<Optional<UnsafePointer<Int>>> on [[OWNER]]
-  // CHECK:   [[TAKES:%.*]] = function_ref @_T018pointer_conversion08takesOptD12ConstPointerySPySiGSgSg_Si3andtF
+  // CHECK:   [[TAKES:%.*]] = function_ref @_T018pointer_conversion08takesOptD12ConstPointer_3andySPySiGSgSg_SitF
   // CHECK:   apply [[TAKES]]([[OPTOPTDEP]], [[RESULT1]])
   // CHECK:   destroy_value [[OWNER]]
   // CHECK:   end_borrow [[BORROW]]
@@ -382,7 +382,7 @@
   takesOptOptConstPointer(array, and: sideEffect1())
 }
 
-// CHECK-LABEL: sil hidden @_T018pointer_conversion21optStringToOptPointerySSSg6string_tF
+// CHECK-LABEL: sil hidden @_T018pointer_conversion21optStringToOptPointer6stringySSSg_tF
 func optStringToOptPointer(string: String?) {
   // CHECK:   [[BORROW:%.*]] = begin_borrow %0
   // CHECK:   [[COPY:%.*]] = copy_value [[BORROW]]
@@ -392,7 +392,7 @@
   // CHECK:   cond_br [[T0]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]]
   // CHECK: [[SOME_BB]]:
   // CHECK:   [[SOME_VALUE:%.*]] = unchecked_enum_data [[COPY]]
-  // CHECK:   [[CONVERT:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgumentyXlSg_xtSSs01_F0RzlF
+  // CHECK:   [[CONVERT:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgumentyyXlSg_xtSSs01_F0RzlF
   // CHECK:   [[TEMP:%.*]] = alloc_stack $UnsafeRawPointer
   // CHECK:   [[OWNER:%.*]] = apply [[CONVERT]]<UnsafeRawPointer>([[TEMP:%.*]], [[SOME_VALUE]])
   // CHECK:   [[PTR:%.*]] = load [trivial] [[TEMP]]
@@ -402,7 +402,7 @@
   // CHECK:   br [[CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafeRawPointer>, [[OWNER]] : $Optional<AnyObject>)
   // CHECK: [[CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafeRawPointer>, [[OWNER:%.*]] : $Optional<AnyObject>):
   // CHECK:   [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafeRawPointer> on [[OWNER]]
-  // CHECK:   [[TAKES:%.*]] = function_ref @_T018pointer_conversion23takesOptConstRawPointerySVSg_Si3andtF
+  // CHECK:   [[TAKES:%.*]] = function_ref @_T018pointer_conversion23takesOptConstRawPointer_3andySVSg_SitF
   // CHECK:   apply [[TAKES]]([[OPTDEP]], [[RESULT1]])
   // CHECK:   destroy_value [[OWNER]]
   // CHECK:   end_borrow [[BORROW]]
@@ -414,7 +414,7 @@
   takesOptConstRawPointer(string, and: sideEffect1())
 }
 
-// CHECK-LABEL: sil hidden @_T018pointer_conversion014optOptStringTodD7PointerySSSgSg6string_tF
+// CHECK-LABEL: sil hidden @_T018pointer_conversion014optOptStringTodD7Pointer6stringySSSgSg_tF
 func optOptStringToOptOptPointer(string: String??) {
   // CHECK:   [[BORROW:%.*]] = begin_borrow %0
   // CHECK:   [[COPY:%.*]] = copy_value [[BORROW]]
@@ -432,7 +432,7 @@
   // CHECK:   br [[SOME_NONE_BB2:bb[0-9]+]]
   // CHECK: [[SOME_SOME_BB]]:
   // CHECK:   [[SOME_SOME_VALUE:%.*]] = unchecked_enum_data [[SOME_VALUE]]
-  // CHECK:   [[CONVERT:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgumentyXlSg_xtSSs01_F0RzlF
+  // CHECK:   [[CONVERT:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgumentyyXlSg_xtSSs01_F0RzlF
   // CHECK:   [[TEMP:%.*]] = alloc_stack $UnsafeRawPointer
   // CHECK:   [[OWNER:%.*]] = apply [[CONVERT]]<UnsafeRawPointer>([[TEMP:%.*]], [[SOME_SOME_VALUE]])
   // CHECK:   [[PTR:%.*]] = load [trivial] [[TEMP]]
@@ -446,7 +446,7 @@
   // CHECK:   br [[SOME_CONT_BB:bb[0-9]+]]([[OPTOPTPTR]] : $Optional<Optional<UnsafeRawPointer>>, [[OWNER]] : $Optional<AnyObject>)
   // CHECK: [[SOME_CONT_BB]]([[OPTOPTPTR:%.*]] : $Optional<Optional<UnsafeRawPointer>>, [[OWNER:%.*]] : $Optional<AnyObject>):
   // CHECK:   [[OPTOPTDEP:%.*]] = mark_dependence [[OPTOPTPTR]] : $Optional<Optional<UnsafeRawPointer>> on [[OWNER]]
-  // CHECK:   [[TAKES:%.*]] = function_ref @_T018pointer_conversion08takesOptD15ConstRawPointerySVSgSg_Si3andtF
+  // CHECK:   [[TAKES:%.*]] = function_ref @_T018pointer_conversion08takesOptD15ConstRawPointer_3andySVSgSg_SitF
   // CHECK:   apply [[TAKES]]([[OPTOPTDEP]], [[RESULT1]])
   // CHECK:   destroy_value [[OWNER]]
   // CHECK:   end_borrow [[BORROW]]
diff --git a/test/SILGen/pointer_conversion_nonaccessing.swift b/test/SILGen/pointer_conversion_nonaccessing.swift
index 9f80c74..6562c55 100644
--- a/test/SILGen/pointer_conversion_nonaccessing.swift
+++ b/test/SILGen/pointer_conversion_nonaccessing.swift
@@ -7,56 +7,56 @@
 
 var global = 0
 
-// CHECK-LABEL: sil hidden @_T031pointer_conversion_nonaccessing6testEqSbSV3ptr_tF
+// CHECK-LABEL: sil hidden @_T031pointer_conversion_nonaccessing6testEq3ptrSbSV_tF
 func testEq(ptr: UnsafeRawPointer) -> Bool {
   // CHECK: [[T0:%.*]] = global_addr @_T031pointer_conversion_nonaccessing6globalSiv
   // CHECK: address_to_pointer [[T0]]
   return &global == ptr
 }
 
-// CHECK-LABEL: sil hidden @_T031pointer_conversion_nonaccessing7testNeqSbSV3ptr_tF
+// CHECK-LABEL: sil hidden @_T031pointer_conversion_nonaccessing7testNeq3ptrSbSV_tF
 func testNeq(ptr: UnsafeRawPointer) -> Bool {
   // CHECK: [[T0:%.*]] = global_addr @_T031pointer_conversion_nonaccessing6globalSiv
   // CHECK: address_to_pointer [[T0]]
   return &global != ptr
 }
 
-// CHECK-LABEL: sil hidden @_T031pointer_conversion_nonaccessing6testEqSbSv3ptr_tF 
+// CHECK-LABEL: sil hidden @_T031pointer_conversion_nonaccessing6testEq3ptrSbSv_tF
 func testEq(ptr: UnsafeMutableRawPointer) -> Bool {
   // CHECK: [[T0:%.*]] = global_addr @_T031pointer_conversion_nonaccessing6globalSiv
   // CHECK: address_to_pointer [[T0]]
   return &global == ptr
 }
 
-// CHECK-LABEL: sil hidden @_T031pointer_conversion_nonaccessing7testNeqSbSv3ptr_tF
+// CHECK-LABEL: sil hidden @_T031pointer_conversion_nonaccessing7testNeq3ptrSbSv_tF
 func testNeq(ptr: UnsafeMutableRawPointer) -> Bool {
   // CHECK: [[T0:%.*]] = global_addr @_T031pointer_conversion_nonaccessing6globalSiv
   // CHECK: address_to_pointer [[T0]]
   return &global != ptr
 }
 
-// CHECK-LABEL: sil hidden @_T031pointer_conversion_nonaccessing6testEqSbSPySiG3ptr_tF
+// CHECK-LABEL: sil hidden @_T031pointer_conversion_nonaccessing6testEq3ptrSbSPySiG_tF
 func testEq(ptr: UnsafePointer<Int>) -> Bool {
   // CHECK: [[T0:%.*]] = global_addr @_T031pointer_conversion_nonaccessing6globalSiv
   // CHECK: address_to_pointer [[T0]]
   return &global == ptr
 }
 
-// CHECK-LABEL: sil hidden @_T031pointer_conversion_nonaccessing7testNeqSbSPySiG3ptr_tF
+// CHECK-LABEL: sil hidden @_T031pointer_conversion_nonaccessing7testNeq3ptrSbSPySiG_tF
 func testNeq(ptr: UnsafePointer<Int>) -> Bool {
   // CHECK: [[T0:%.*]] = global_addr @_T031pointer_conversion_nonaccessing6globalSiv
   // CHECK: address_to_pointer [[T0]]
   return &global != ptr
 }
 
-// CHECK-LABEL: sil hidden @_T031pointer_conversion_nonaccessing6testEqSbSpySiG3ptr_tF
+// CHECK-LABEL: sil hidden @_T031pointer_conversion_nonaccessing6testEq3ptrSbSpySiG_tF
 func testEq(ptr: UnsafeMutablePointer<Int>) -> Bool {
   // CHECK: [[T0:%.*]] = global_addr @_T031pointer_conversion_nonaccessing6globalSiv
   // CHECK: address_to_pointer [[T0]]
   return &global == ptr
 }
 
-// CHECK-LABEL: sil hidden @_T031pointer_conversion_nonaccessing7testNeqSbSpySiG3ptr_tF
+// CHECK-LABEL: sil hidden @_T031pointer_conversion_nonaccessing7testNeq3ptrSbSpySiG_tF
 func testNeq(ptr: UnsafeMutablePointer<Int>) -> Bool {
   // CHECK: [[T0:%.*]] = global_addr @_T031pointer_conversion_nonaccessing6globalSiv
   // CHECK: address_to_pointer [[T0]]
diff --git a/test/SILGen/pointer_conversion_nonaccessing_objc.swift b/test/SILGen/pointer_conversion_nonaccessing_objc.swift
index fdb2a73..84ff3de 100644
--- a/test/SILGen/pointer_conversion_nonaccessing_objc.swift
+++ b/test/SILGen/pointer_conversion_nonaccessing_objc.swift
@@ -11,14 +11,14 @@
 
 var global = 0
 
-// CHECK-LABEL: sil hidden @_T036pointer_conversion_nonaccessing_objc15testAddObserverySo8NSObjectC6object_AD8observertF
+// CHECK-LABEL: sil hidden @_T036pointer_conversion_nonaccessing_objc15testAddObserver6object8observerySo8NSObjectC_AFtF
 func testAddObserver(object: NSObject, observer: NSObject) {
   // CHECK: [[T0:%.*]] = global_addr @_T036pointer_conversion_nonaccessing_objc6globalSiv
   // CHECK: address_to_pointer [[T0]] :
   object.addObserver(observer, forKeyPath: "", options: 0, context: &global)
 }
 
-// CHECK-LABEL: sil hidden @_T036pointer_conversion_nonaccessing_objc18testRemoveObserverySo8NSObjectC6object_AD8observertF
+// CHECK-LABEL: sil hidden @_T036pointer_conversion_nonaccessing_objc18testRemoveObserver6object8observerySo8NSObjectC_AFtF
 func testRemoveObserver(object: NSObject, observer: NSObject) {
   // CHECK: [[T0:%.*]] = global_addr @_T036pointer_conversion_nonaccessing_objc6globalSiv
   // CHECK: address_to_pointer [[T0]] :
@@ -28,28 +28,28 @@
 // rdar://33850465
 //   Make sure this applies to AnyObject dispatch, too.
 
-// CHECK-LABEL: sil hidden @_T036pointer_conversion_nonaccessing_objc28testDynamicForcedAddObserveryyXl6object_So8NSObjectC8observertF
+// CHECK-LABEL: sil hidden @_T036pointer_conversion_nonaccessing_objc28testDynamicForcedAddObserver6object8observeryyXl_So8NSObjectCtF
 func testDynamicForcedAddObserver(object: AnyObject, observer: NSObject) {
   // CHECK: [[T0:%.*]] = global_addr @_T036pointer_conversion_nonaccessing_objc6globalSiv
   // CHECK: address_to_pointer [[T0]] :
   object.addObserver!(observer, forKeyPath: "", options: 0, context: &global)
 }
 
-// CHECK-LABEL: sil hidden @_T036pointer_conversion_nonaccessing_objc31testDynamicForcedRemoveObserveryyXl6object_So8NSObjectC8observertF
+// CHECK-LABEL: sil hidden @_T036pointer_conversion_nonaccessing_objc31testDynamicForcedRemoveObserver6object8observeryyXl_So8NSObjectCtF
 func testDynamicForcedRemoveObserver(object: AnyObject, observer: NSObject) {
   // CHECK: [[T0:%.*]] = global_addr @_T036pointer_conversion_nonaccessing_objc6globalSiv
   // CHECK: address_to_pointer [[T0]] :
   object.removeObserver!(observer, forKeyPath: "", context: &global)
 }
 
-// CHECK-LABEL: sil hidden @_T036pointer_conversion_nonaccessing_objc30testDynamicOptionalAddObserveryyXl6object_So8NSObjectC8observertF
+// CHECK-LABEL: sil hidden @_T036pointer_conversion_nonaccessing_objc30testDynamicOptionalAddObserver6object8observeryyXl_So8NSObjectCtF
 func testDynamicOptionalAddObserver(object: AnyObject, observer: NSObject) {
   // CHECK: [[T0:%.*]] = global_addr @_T036pointer_conversion_nonaccessing_objc6globalSiv
   // CHECK: address_to_pointer [[T0]] :
   object.addObserver?(observer, forKeyPath: "", options: 0, context: &global)
 }
 
-// CHECK-LABEL: sil hidden @_T036pointer_conversion_nonaccessing_objc33testDynamicOptionalRemoveObserveryyXl6object_So8NSObjectC8observertF
+// CHECK-LABEL: sil hidden @_T036pointer_conversion_nonaccessing_objc33testDynamicOptionalRemoveObserver6object8observeryyXl_So8NSObjectCtF
 func testDynamicOptionalRemoveObserver(object: AnyObject, observer: NSObject) {
   // CHECK: [[T0:%.*]] = global_addr @_T036pointer_conversion_nonaccessing_objc6globalSiv
   // CHECK: address_to_pointer [[T0]] :
diff --git a/test/SILGen/properties.swift b/test/SILGen/properties.swift
index eae71a6..c00fb6f 100644
--- a/test/SILGen/properties.swift
+++ b/test/SILGen/properties.swift
@@ -317,7 +317,7 @@
       return x
     }
   }
-  // CHECK: [[GET_REF:%[0-9]+]] = function_ref [[PROP_GET_CLOSURE:@_T010properties17logical_local_getS2iF4propL_Sivg]]
+  // CHECK: [[GET_REF:%[0-9]+]] = function_ref [[PROP_GET_CLOSURE:@_T010properties17logical_local_getyS2iF4propL_Sivg]]
   // CHECK: apply [[GET_REF]](%0)
   return prop
 }
@@ -355,7 +355,7 @@
   }
 
   return get_prop()
-  // CHECK: [[FUNC_REF:%[0-9]+]] = function_ref @_T010properties26logical_local_captured_getS2iF0E5_propL_SiyF
+  // CHECK: [[FUNC_REF:%[0-9]+]] = function_ref @_T010properties26logical_local_captured_getyS2iF0E5_propL_SiyF
   // CHECK: apply [[FUNC_REF]](%0)
 }
 // CHECK: sil private @_T010properties26logical_local_captured_get{{.*}}vg
@@ -930,7 +930,7 @@
   init() { fatalError("scaffold") }
 }
 
-// CHECK-LABEL: sil hidden @_T010properties12genericPropsyAA12GenericClassCySSGF : $@convention(thin) (@owned GenericClass<String>) -> () {
+// CHECK-LABEL: sil hidden @_T010properties12genericPropsyyAA12GenericClassCySSGF : $@convention(thin) (@owned GenericClass<String>) -> () {
 func genericProps(_ x: GenericClass<String>) {
   // CHECK: bb0([[ARG:%.*]] : $GenericClass<String>):
   // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
@@ -1177,7 +1177,7 @@
   var x: Int { get nonmutating set }
 }
 
-// sil hidden @_T010properties19overlappingLoadExpryAA13ReferenceTypeCz1c_tF : $@convention(thin) (@inout ReferenceType) -> () {
+// sil hidden @_T010properties19overlappingLoadExpr1cyAA13ReferenceTypeCz_tF : $@convention(thin) (@inout ReferenceType) -> () {
 // CHECK:        [[RESULT:%.*]] = alloc_stack $Int
 // CHECK-NEXT:   [[UNINIT:%.*]] = mark_uninitialized [var] [[RESULT]] : $*Int
 // CHECK-NEXT:   [[C_INOUT:%.*]] = begin_access [read] [unknown] %0 : $*ReferenceType
diff --git a/test/SILGen/property_behavior_init.swift b/test/SILGen/property_behavior_init.swift
index b478742..99893b6 100644
--- a/test/SILGen/property_behavior_init.swift
+++ b/test/SILGen/property_behavior_init.swift
@@ -53,7 +53,7 @@
     // CHECK: [[GETTER:%.*]] = function_ref @_T022property_behavior_init3FooV1xSivg
     // CHECK: [[VALUE:%.*]] = apply [[GETTER]]([[SELF]])
     // CHECK: store [[VALUE]] to [trivial] [[INOUT]]
-    // CHECK: [[WHACK:%.*]] = function_ref @_T022property_behavior_init5whackyxzlF
+    // CHECK: [[WHACK:%.*]] = function_ref @_T022property_behavior_init5whackyyxzlF
     // CHECK: apply [[WHACK]]<Int>([[INOUT]])
     // CHECK: [[VALUE:%.*]] = load [trivial] [[INOUT]]
     // CHECK: [[SETTER:%.*]] = function_ref @_T022property_behavior_init3FooV1xSivs
diff --git a/test/SILGen/protocol_extensions.swift b/test/SILGen/protocol_extensions.swift
index 6920b92..40126cb 100644
--- a/test/SILGen/protocol_extensions.swift
+++ b/test/SILGen/protocol_extensions.swift
@@ -69,9 +69,9 @@
 }
 
 //   (materializeForSet test from above)
-// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_extensions1CCAA2P1A2aDPS2icimTW
+// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_extensions1CCAA2P1A2aDPyS2icimTW
 // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $Int, %3 : $*τ_0_0):
-// CHECK: function_ref @_T019protocol_extensions2P1PAAES2icig
+// CHECK: function_ref @_T019protocol_extensions2P1PAAEyS2icig
 // CHECK: return
 
 class D : C { }
@@ -95,7 +95,7 @@
 
 func inout_func(_ n: inout Int) {}
 
-// CHECK-LABEL: sil hidden @_T019protocol_extensions5testDyAA10MetaHolderV_AA1DCm2ddAF1dtF : $@convention(thin) (MetaHolder, @thick D.Type, @owned D) -> ()
+// CHECK-LABEL: sil hidden @_T019protocol_extensions5testD_2dd1dyAA10MetaHolderV_AA1DCmAHtF : $@convention(thin) (MetaHolder, @thick D.Type, @owned D) -> ()
 // CHECK: bb0([[M:%[0-9]+]] : $MetaHolder, [[DD:%[0-9]+]] : $@thick D.Type, [[D:%[0-9]+]] : $D):
 func testD(_ m: MetaHolder, dd: D.Type, d: D) {
   // CHECK: [[D2:%[0-9]+]] = alloc_box ${ var D }
@@ -143,7 +143,7 @@
   // CHECK: alloc_stack $Box
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
   // CHECK: store
-  // CHECK: function_ref @_T019protocol_extensions10inout_funcySizF
+  // CHECK: function_ref @_T019protocol_extensions10inout_funcyySizF
   // CHECK: load
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
   // CHECK: dealloc_stack
@@ -177,7 +177,7 @@
   // CHECK: alloc_stack $Box
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
   // CHECK: store
-  // CHECK: function_ref @_T019protocol_extensions10inout_funcySizF
+  // CHECK: function_ref @_T019protocol_extensions10inout_funcyySizF
   // CHECK: load
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
   // CHECK: dealloc_stack
@@ -211,7 +211,7 @@
   // CHECK: alloc_stack $Box
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
   // CHECK: store
-  // CHECK: function_ref @_T019protocol_extensions10inout_funcySizF
+  // CHECK: function_ref @_T019protocol_extensions10inout_funcyySizF
   // CHECK: load
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
   // CHECK: dealloc_stack
@@ -220,7 +220,7 @@
   // CHECK: return
 }
 
-// CHECK-LABEL: sil hidden @_T019protocol_extensions5testSyAA10MetaHolderV_AA1SVm2sstF
+// CHECK-LABEL: sil hidden @_T019protocol_extensions5testS_2ssyAA10MetaHolderV_AA1SVmtF
 func testS(_ m: MetaHolder, ss: S.Type) {
   // CHECK: metatype $@thick S.Type
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ
@@ -256,7 +256,7 @@
   // CHECK: metatype $@thick S.Type
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
   // CHECK: store
-  // CHECK: function_ref @_T019protocol_extensions10inout_funcySizF
+  // CHECK: function_ref @_T019protocol_extensions10inout_funcyySizF
   // CHECK: load
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
   // CHECK: dealloc_stack
@@ -296,7 +296,7 @@
   // CHECK: metatype $@thick S.Type
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
   // CHECK: store
-  // CHECK: function_ref @_T019protocol_extensions10inout_funcySizF
+  // CHECK: function_ref @_T019protocol_extensions10inout_funcyySizF
   // CHECK: load
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
   // CHECK: dealloc_stack
@@ -336,7 +336,7 @@
   // CHECK: metatype $@thick S.Type
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
   // CHECK: store
-  // CHECK: function_ref @_T019protocol_extensions10inout_funcySizF
+  // CHECK: function_ref @_T019protocol_extensions10inout_funcyySizF
   // CHECK: load
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
   // CHECK: dealloc_stack
@@ -381,7 +381,7 @@
   // CHECK: metatype $@thick G<T>.Type
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
   // CHECK: store
-  // CHECK: function_ref @_T019protocol_extensions10inout_funcySizF
+  // CHECK: function_ref @_T019protocol_extensions10inout_funcyySizF
   // CHECK: load
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
   // CHECK: dealloc_stack
@@ -421,7 +421,7 @@
   // CHECK: metatype $@thick G<T>.Type
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
   // CHECK: store
-  // CHECK: function_ref @_T019protocol_extensions10inout_funcySizF
+  // CHECK: function_ref @_T019protocol_extensions10inout_funcyySizF
   // CHECK: load
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
   // CHECK: dealloc_stack
@@ -461,7 +461,7 @@
   // CHECK: metatype $@thick G<T>.Type
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
   // CHECK: store
-  // CHECK: function_ref @_T019protocol_extensions10inout_funcySizF
+  // CHECK: function_ref @_T019protocol_extensions10inout_funcyySizF
   // CHECK: load
   // CHECK: function_ref @_T019protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
   // CHECK: dealloc_stack
@@ -507,7 +507,7 @@
 
   // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr immutable_access [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1
   // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] :
-  // CHECK: [[GETTER:%[0-9]+]] = function_ref @_T019protocol_extensions2P1PAAESbs5Int64Vcig
+  // CHECK: [[GETTER:%[0-9]+]] = function_ref @_T019protocol_extensions2P1PAAEySbs5Int64Vcig
   // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[I]], [[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Int64, @in_guaranteed τ_0_0) -> Bool
   // CHECK: destroy_addr [[POPENED_COPY]]
   // CHECK: store{{.*}} : $*Bool
@@ -546,7 +546,7 @@
 
   // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr immutable_access [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1
   // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] :
-  // CHECK: [[GETTER:%[0-9]+]] = function_ref @_T019protocol_extensions2P1PAAES2bcig
+  // CHECK: [[GETTER:%[0-9]+]] = function_ref @_T019protocol_extensions2P1PAAEyS2bcig
   // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[B]], [[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @in_guaranteed τ_0_0) -> Bool
   let b2: Bool = p1[b]
 }
@@ -567,7 +567,7 @@
 
   // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PBP]]
   // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr mutable_access [[WRITE]] : $*P1 to $*@opened([[UUID:".*"]]) P1
-  // CHECK: [[SUBSETTER:%[0-9]+]] = function_ref @_T019protocol_extensions2P1PAAES2bcis
+  // CHECK: [[SUBSETTER:%[0-9]+]] = function_ref @_T019protocol_extensions2P1PAAEyS2bcis
   // CHECK: apply [[SUBSETTER]]<@opened([[UUID]]) P1>([[B]], [[B]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, Bool, @inout τ_0_0) -> ()
   // CHECK-NOT: deinit_existential_addr [[PB]] : $*P1
   p1[b] = b
@@ -692,7 +692,7 @@
 }
 
 extension InitRequirement {
-  // CHECK-LABEL: sil hidden @_T019protocol_extensions15InitRequirementPAAExAA1DC1d_tcfC : $@convention(method) <Self where Self : InitRequirement> (@owned D, @thick Self.Type) -> @out Self
+  // CHECK-LABEL: sil hidden @_T019protocol_extensions15InitRequirementPAAE1dxAA1DC_tcfC : $@convention(method) <Self where Self : InitRequirement> (@owned D, @thick Self.Type) -> @out Self
   // CHECK:       bb0([[OUT:%.*]] : $*Self, [[ARG:%.*]] : $D, [[SELF_TYPE:%.*]] : $@thick Self.Type):
   init(d: D) {
     // CHECK:      [[SELF_BOX:%.*]] = alloc_box
@@ -714,7 +714,7 @@
     self.init(c: d)
   }
 
-  // CHECK-LABEL: sil hidden @_T019protocol_extensions15InitRequirementPAAExAA1DC2d2_tcfC : $@convention(method)
+  // CHECK-LABEL: sil hidden @_T019protocol_extensions15InitRequirementPAAE2d2xAA1DC_tcfC : $@convention(method)
   // CHECK:       bb0([[OUT:%.*]] : $*Self, [[ARG:%.*]] : $D, [[SELF_TYPE:%.*]] : $@thick Self.Type):
   init(d2: D) {
     // CHECK:      [[SELF_BOX:%.*]] = alloc_box
@@ -723,7 +723,7 @@
     // CHECK:      [[SELF_BOX:%.*]] = alloc_stack $Self
     // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
     // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
-    // CHECK:      [[DELEGATEE:%.*]] = function_ref @_T019protocol_extensions15InitRequirementPAAExAA1DC1d_tcfC
+    // CHECK:      [[DELEGATEE:%.*]] = function_ref @_T019protocol_extensions15InitRequirementPAAE1dxAA1DC_tcfC
     // CHECK-NEXT: apply [[DELEGATEE]]<Self>([[SELF_BOX]], [[ARG_COPY]], [[SELF_TYPE]])
     // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
     // CHECK-NEXT: copy_addr [take] [[SELF_BOX]] to [[SELF_BOX_ADDR]]
@@ -735,7 +735,7 @@
     self.init(d: d2)
   }
 
-  // CHECK-LABEL: sil hidden @_T019protocol_extensions15InitRequirementPAAExAA1CC2c2_tcfC  : $@convention(method)
+  // CHECK-LABEL: sil hidden @_T019protocol_extensions15InitRequirementPAAE2c2xAA1CC_tcfC  : $@convention(method)
   // CHECK:       bb0([[OUT:%.*]] : $*Self, [[ARG:%.*]] : $C, [[SELF_TYPE:%.*]] : $@thick Self.Type):
   init(c2: C) {
     // CHECK:      [[SELF_BOX:%.*]] = alloc_box
diff --git a/test/SILGen/protocol_optional.swift b/test/SILGen/protocol_optional.swift
index 7cea072..4f6d76d 100644
--- a/test/SILGen/protocol_optional.swift
+++ b/test/SILGen/protocol_optional.swift
@@ -8,7 +8,7 @@
   @objc optional subscript (i: Int) -> Int { get }
 }
 
-// CHECK-LABEL: sil hidden @_T017protocol_optional0B13MethodGenericyx1t_tAA2P1RzlF : $@convention(thin) <T where T : P1> (@owned T) -> ()
+// CHECK-LABEL: sil hidden @_T017protocol_optional0B13MethodGeneric1tyx_tAA2P1RzlF : $@convention(thin) <T where T : P1> (@owned T) -> ()
 func optionalMethodGeneric<T : P1>(t t : T) {
   var t = t
   // CHECK: bb0([[T:%[0-9]+]] : @owned $T):
@@ -26,7 +26,7 @@
   // CHECK:   dynamic_method_br [[T]] : $T, #P1.method!1.foreign
   var methodRef = t.method
 }
-// CHECK: } // end sil function '_T017protocol_optional0B13MethodGenericyx1t_tAA2P1RzlF'
+// CHECK: } // end sil function '_T017protocol_optional0B13MethodGeneric1tyx_tAA2P1RzlF'
 
 // CHECK-LABEL: sil hidden @_T017protocol_optional0B15PropertyGeneric{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : P1> (@owned T) -> ()
 func optionalPropertyGeneric<T : P1>(t t : T) {
@@ -64,7 +64,7 @@
   // CHECK:   [[T:%[0-9]+]] = load [copy] [[READ]] : $*T
   // CHECK:   [[INT64:%[0-9]+]] = metatype $@thin Int.Type
   // CHECK:   [[FIVELIT:%[0-9]+]] = integer_literal $Builtin.Int2048, 5
-  // CHECK:   [[INTCONV:%[0-9]+]] = function_ref @_T0S2i{{[_0-9a-zA-Z]*}}fC
+  // CHECK:   [[INTCONV:%[0-9]+]] = function_ref @_T0Si2{{[_0-9a-zA-Z]*}}fC
   // CHECK:   [[FIVE:%[0-9]+]] = apply [[INTCONV]]([[FIVELIT]], [[INT64]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int
   // CHECK:   alloc_stack $Optional<Int>
   // CHECK:   dynamic_method_br [[T]] : $T, #P1.subscript!getter.1.foreign
diff --git a/test/SILGen/protocol_resilience.swift b/test/SILGen/protocol_resilience.swift
index 8ece9cc..cca5c8e 100644
--- a/test/SILGen/protocol_resilience.swift
+++ b/test/SILGen/protocol_resilience.swift
@@ -34,24 +34,24 @@
 // CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE14defaultWitnessyyF
   public func defaultWitness() {}
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP21anotherDefaultWitnessxSiF
-// CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE21anotherDefaultWitnessxSiF
+// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP21anotherDefaultWitnessyxSiF
+// CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE21anotherDefaultWitnessyxSiF
   public func anotherDefaultWitness(_ x: Int) -> Self {}
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP32defaultWitnessWithAssociatedTypey05AssocI0QzF
-// CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE32defaultWitnessWithAssociatedTypey05AssocI0QzF
+// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP32defaultWitnessWithAssociatedTypeyy05AssocI0QzF
+// CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE32defaultWitnessWithAssociatedTypeyy05AssocI0QzF
   public func defaultWitnessWithAssociatedType(_ a: AssocType) {}
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP41defaultWitnessMoreAbstractThanRequirementy9AssocTypeQz_Si1btF
-// CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE41defaultWitnessMoreAbstractThanRequirementyqd___qd_0_1btr0_lF
+// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP41defaultWitnessMoreAbstractThanRequirement_1by9AssocTypeQz_SitF
+// CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE41defaultWitnessMoreAbstractThanRequirement_1byqd___qd_0_tr0_lF
   public func defaultWitnessMoreAbstractThanRequirement<A, T>(_ a: A, b: T) {}
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP48defaultWitnessMoreAbstractThanGenericRequirementy9AssocTypeQz_qd__1ttlF
-// CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE48defaultWitnessMoreAbstractThanGenericRequirementyqd___qd_0_1ttr0_lF
+// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP48defaultWitnessMoreAbstractThanGenericRequirement_1ty9AssocTypeQz_qd__tlF
+// CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE48defaultWitnessMoreAbstractThanGenericRequirement_1tyqd___qd_0_tr0_lF
   public func defaultWitnessMoreAbstractThanGenericRequirement<A, T>(_ a: A, t: T) {}
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP20staticDefaultWitnessxSiFZ
-// CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE20staticDefaultWitnessxSiFZ
+// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP20staticDefaultWitnessyxSiFZ
+// CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE20staticDefaultWitnessyxSiFZ
   public static func staticDefaultWitness(_ x: Int) -> Self {}
 
 // CHECK-LABEL: sil private @_T019protocol_resilience16ResilientMethodsPAAE25defaultWitnessIsNotPublic{{.*}}F
@@ -70,24 +70,24 @@
 
 extension ResilientConstructors {
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience21ResilientConstructorsPxyt7default_tcfC
-// CHECK-LABEL: sil @_T019protocol_resilience21ResilientConstructorsPAAExyt7default_tcfC
+// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience21ResilientConstructorsP7defaultxyt_tcfC
+// CHECK-LABEL: sil @_T019protocol_resilience21ResilientConstructorsPAAE7defaultxyt_tcfC
   public init(default: ()) {
     self.init(noDefault: ())
   }
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience21ResilientConstructorsPxSgyt17defaultIsOptional_tcfC
-// CHECK-LABEL: sil @_T019protocol_resilience21ResilientConstructorsPAAExSgyt17defaultIsOptional_tcfC
+// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience21ResilientConstructorsP17defaultIsOptionalxSgyt_tcfC
+// CHECK-LABEL: sil @_T019protocol_resilience21ResilientConstructorsPAAE17defaultIsOptionalxSgyt_tcfC
   public init?(defaultIsOptional: ()) {
     self.init(noDefault: ())
   }
 
-// CHECK-LABEL: sil @_T019protocol_resilience21ResilientConstructorsPAAExyt20defaultIsNotOptional_tcfC
+// CHECK-LABEL: sil @_T019protocol_resilience21ResilientConstructorsPAAE20defaultIsNotOptionalxyt_tcfC
   public init(defaultIsNotOptional: ()) {
     self.init(noDefault: ())
   }
 
-// CHECK-LABEL: sil @_T019protocol_resilience21ResilientConstructorsPAAExSgyt19optionalityMismatch_tcfC
+// CHECK-LABEL: sil @_T019protocol_resilience21ResilientConstructorsPAAE19optionalityMismatchxSgyt_tcfC
   public init?(optionalityMismatch: ()) {
     self.init(noDefault: ())
   }
@@ -145,12 +145,12 @@
     set { }
   }
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP1TQzAEcig
-// CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE1TQzAEcig
-// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP1TQzAEcis
-// CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE1TQzAEcis
-// CHECK-LABEL: sil private [transparent] @_T019protocol_resilience16ResilientStorageP1TQzAEcimytfU_
-// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP1TQzAEcim
+// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStoragePy1TQzAEcig
+// CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAEy1TQzAEcig
+// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStoragePy1TQzAEcis
+// CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAEy1TQzAEcis
+// CHECK-LABEL: sil private [transparent] @_T019protocol_resilience16ResilientStoragePy1TQzAEcimytfU_
+// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStoragePy1TQzAEcim
   public subscript(x: T) -> T {
     get {
       return x
@@ -182,23 +182,23 @@
   static func <===><T : ResilientOperators>(t: T, s: Self) -> T.AssocType
 }
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience18ResilientOperatorsP3tttopyxFZ
-// CHECK-LABEL: sil @_T019protocol_resilience3tttopyxlF
+// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience18ResilientOperatorsP3tttopyyxFZ
+// CHECK-LABEL: sil @_T019protocol_resilience3tttopyyxlF
 public prefix func ~~~<S>(s: S) {}
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience18ResilientOperatorsP3lmgoiyx_qd__tlFZ
-// CHECK-LABEL: sil @_T019protocol_resilience3lmgoiyq__xtr0_lF
+// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience18ResilientOperatorsP3lmgoiyyx_qd__tlFZ
+// CHECK-LABEL: sil @_T019protocol_resilience3lmgoiyyq__xtr0_lF
 public func <*><T, S>(s: S, t: T) {}
 
 // Swap the generic parameters to make sure we don't mix up our DeclContexts
 // when mapping interface types in and out
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience18ResilientOperatorsP4lmmgoi9AssocTypeQzqd___xtlFZ
-// CHECK-LABEL: sil @_T019protocol_resilience4lmmgoi9AssocTypeQzq__xtAA18ResilientOperatorsRzr0_lF
+// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience18ResilientOperatorsP4lmmgoiy9AssocTypeQzqd___xtlFZ
+// CHECK-LABEL: sil @_T019protocol_resilience4lmmgoiy9AssocTypeQzq__xtAA18ResilientOperatorsRzr0_lF
 public func <**><S : ResilientOperators, T>(t: T, s: S) -> S.AssocType {}
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience18ResilientOperatorsP5leeegoi9AssocTypeQyd__qd___xtAaBRd__lFZ
-// CHECK-LABEL: sil @_T019protocol_resilience5leeegoi9AssocTypeQzx_q_tAA18ResilientOperatorsRzAaER_r0_lF
+// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience18ResilientOperatorsP5leeegoiy9AssocTypeQyd__qd___xtAaBRd__lFZ
+// CHECK-LABEL: sil @_T019protocol_resilience5leeegoiy9AssocTypeQzx_q_tAA18ResilientOperatorsRzAaER_r0_lF
 public func <===><T : ResilientOperators, S : ResilientOperators>(t: T, s: S) -> T.AssocType {}
 
 
@@ -221,11 +221,11 @@
   }
 }
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience21ReabstractSelfRefinedP8callbackxxcvg : $@convention(witness_method: ReabstractSelfRefined) <τ_0_0 where τ_0_0 : ReabstractSelfRefined> (@guaranteed τ_0_0) -> @owned @callee_guaranteed (@owned τ_0_0) -> @owned τ_0_0
+// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience21ReabstractSelfRefinedP8callbackyxxcvg : $@convention(witness_method: ReabstractSelfRefined) <τ_0_0 where τ_0_0 : ReabstractSelfRefined> (@guaranteed τ_0_0) -> @owned @callee_guaranteed (@owned τ_0_0) -> @owned τ_0_0
 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $τ_0_0
 // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value %0 : $τ_0_0
 // CHECK-NEXT: store [[SELF_COPY]] to [init] [[SELF_BOX]] : $*τ_0_0
-// CHECK: [[WITNESS:%.*]] = function_ref @_T019protocol_resilience18ReabstractSelfBasePAAE8callbackxxcvg
+// CHECK: [[WITNESS:%.*]] = function_ref @_T019protocol_resilience18ReabstractSelfBasePAAE8callbackyxxcvg
 // CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS]]<τ_0_0>([[SELF_BOX]])
 // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xxIegir_xxIegxo_19protocol_resilience21ReabstractSelfRefinedRzlTR
 // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<τ_0_0>([[RESULT]])
@@ -237,7 +237,7 @@
 
 func inoutFunc(_ x: inout Int) {}
 
-// CHECK-LABEL: sil hidden @_T019protocol_resilience22inoutResilientProtocoly010resilient_A005OtherdE0_pzF
+// CHECK-LABEL: sil hidden @_T019protocol_resilience22inoutResilientProtocolyy010resilient_A005OtherdE0_pzF
 func inoutResilientProtocol(_ x: inout OtherResilientProtocol) {
   // CHECK: function_ref @_T018resilient_protocol22OtherResilientProtocolPAAE19propertyInExtensionSivm
   inoutFunc(&x.propertyInExtension)
@@ -245,7 +245,7 @@
 
 struct OtherConformingType : OtherResilientProtocol {}
 
-// CHECK-LABEL: sil hidden @_T019protocol_resilience22inoutResilientProtocolyAA19OtherConformingTypeVzF
+// CHECK-LABEL: sil hidden @_T019protocol_resilience22inoutResilientProtocolyyAA19OtherConformingTypeVzF
 func inoutResilientProtocol(_ x: inout OtherConformingType) {
   // CHECK: function_ref @_T018resilient_protocol22OtherResilientProtocolPAAE19propertyInExtensionSivm
   inoutFunc(&x.propertyInExtension)
@@ -254,19 +254,6 @@
   inoutFunc(&OtherConformingType.staticPropertyInExtension)
 }
 
-// Protocol is not public -- make sure default witnesses have the right linkage
-protocol InternalProtocol {
-  func noDefaultF()
-  func defaultG()
-}
-
-extension InternalProtocol {
-
-  // CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16InternalProtocolP8defaultGyyF
-  // CHECK: return
-  func defaultG() {}
-}
-
 // CHECK-LABEL: sil_default_witness_table P {
 // CHECK-NEXT: }
 
@@ -274,19 +261,19 @@
 // CHECK-NEXT:    no_default
 // CHECK-NEXT:    no_default
 // CHECK-NEXT:    method #ResilientMethods.defaultWitness!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP14defaultWitnessyyF
-// CHECK-NEXT:    method #ResilientMethods.anotherDefaultWitness!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP21anotherDefaultWitnessxSiF
-// CHECK-NEXT:    method #ResilientMethods.defaultWitnessWithAssociatedType!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP32defaultWitnessWithAssociatedTypey05AssocI0QzF
-// CHECK-NEXT:    method #ResilientMethods.defaultWitnessMoreAbstractThanRequirement!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP41defaultWitnessMoreAbstractThanRequirementy9AssocTypeQz_Si1btF
-// CHECK-NEXT:    method #ResilientMethods.defaultWitnessMoreAbstractThanGenericRequirement!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP48defaultWitnessMoreAbstractThanGenericRequirementy9AssocTypeQz_qd__1ttlF
+// CHECK-NEXT:    method #ResilientMethods.anotherDefaultWitness!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP21anotherDefaultWitnessyxSiF
+// CHECK-NEXT:    method #ResilientMethods.defaultWitnessWithAssociatedType!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP32defaultWitnessWithAssociatedTypeyy05AssocI0QzF
+// CHECK-NEXT:    method #ResilientMethods.defaultWitnessMoreAbstractThanRequirement!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP41defaultWitnessMoreAbstractThanRequirement_1by9AssocTypeQz_SitF
+// CHECK-NEXT:    method #ResilientMethods.defaultWitnessMoreAbstractThanGenericRequirement!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP48defaultWitnessMoreAbstractThanGenericRequirement_1ty9AssocTypeQz_qd__tlF
 // CHECK-NEXT:    no_default
 // CHECK-NEXT:    no_default
-// CHECK-NEXT:    method #ResilientMethods.staticDefaultWitness!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP20staticDefaultWitnessxSiFZ
+// CHECK-NEXT:    method #ResilientMethods.staticDefaultWitness!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP20staticDefaultWitnessyxSiFZ
 // CHECK-NEXT: }
 
 // CHECK-LABEL: sil_default_witness_table ResilientConstructors {
 // CHECK-NEXT:    no_default
-// CHECK-NEXT:    method #ResilientConstructors.init!allocator.1: {{.*}} : @_T019protocol_resilience21ResilientConstructorsPxyt7default_tcfC
-// CHECK-NEXT:    method #ResilientConstructors.init!allocator.1: {{.*}} : @_T019protocol_resilience21ResilientConstructorsPxSgyt17defaultIsOptional_tcfC
+// CHECK-NEXT:    method #ResilientConstructors.init!allocator.1: {{.*}} : @_T019protocol_resilience21ResilientConstructorsP7defaultxyt_tcfC
+// CHECK-NEXT:    method #ResilientConstructors.init!allocator.1: {{.*}} : @_T019protocol_resilience21ResilientConstructorsP17defaultIsOptionalxSgyt_tcfC
 // CHECK-NEXT:    no_default
 // CHECK-NEXT:    no_default
 // CHECK-NEXT: }
@@ -305,9 +292,9 @@
 // CHECK-NEXT:   method #ResilientStorage.mutableGenericPropertyWithDefault!getter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvg
 // CHECK-NEXT:   method #ResilientStorage.mutableGenericPropertyWithDefault!setter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvs
 // CHECK-NEXT:   method #ResilientStorage.mutableGenericPropertyWithDefault!materializeForSet.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvm
-// CHECK-NEXT:   method #ResilientStorage.subscript!getter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP1TQzAEcig
-// CHECK-NEXT:   method #ResilientStorage.subscript!setter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP1TQzAEcis
-// CHECK-NEXT:   method #ResilientStorage.subscript!materializeForSet.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP1TQzAEcim
+// CHECK-NEXT:   method #ResilientStorage.subscript!getter.1: {{.*}} : @_T019protocol_resilience16ResilientStoragePy1TQzAEcig
+// CHECK-NEXT:   method #ResilientStorage.subscript!setter.1: {{.*}} : @_T019protocol_resilience16ResilientStoragePy1TQzAEcis
+// CHECK-NEXT:   method #ResilientStorage.subscript!materializeForSet.1: {{.*}} : @_T019protocol_resilience16ResilientStoragePy1TQzAEcim
 // CHECK-NEXT:   method #ResilientStorage.mutatingGetterWithNonMutatingDefault!getter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivg
 // CHECK-NEXT:   method #ResilientStorage.mutatingGetterWithNonMutatingDefault!setter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivs
 // CHECK-NEXT:   method #ResilientStorage.mutatingGetterWithNonMutatingDefault!materializeForSet.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivm
@@ -316,20 +303,15 @@
 // CHECK-LABEL: sil_default_witness_table ResilientOperators {
 // CHECK-NEXT:    no_default
 // CHECK-NEXT:    no_default
-// CHECK-NEXT:    method #ResilientOperators."~~~"!1: {{.*}} : @_T019protocol_resilience18ResilientOperatorsP3tttopyxFZ
-// CHECK-NEXT:    method #ResilientOperators."<*>"!1: {{.*}} : @_T019protocol_resilience18ResilientOperatorsP3lmgoiyx_qd__tlFZ
-// CHECK-NEXT:    method #ResilientOperators."<**>"!1: {{.*}} : @_T019protocol_resilience18ResilientOperatorsP4lmmgoi9AssocTypeQzqd___xtlFZ
-// CHECK-NEXT:    method #ResilientOperators."<===>"!1: {{.*}} : @_T019protocol_resilience18ResilientOperatorsP5leeegoi9AssocTypeQyd__qd___xtAaBRd__lFZ
+// CHECK-NEXT:    method #ResilientOperators."~~~"!1: {{.*}} : @_T019protocol_resilience18ResilientOperatorsP3tttopyyxFZ
+// CHECK-NEXT:    method #ResilientOperators."<*>"!1: {{.*}} : @_T019protocol_resilience18ResilientOperatorsP3lmgoiyyx_qd__tlFZ
+// CHECK-NEXT:    method #ResilientOperators."<**>"!1: {{.*}} : @_T019protocol_resilience18ResilientOperatorsP4lmmgoiy9AssocTypeQzqd___xtlFZ
+// CHECK-NEXT:    method #ResilientOperators."<===>"!1: {{.*}} : @_T019protocol_resilience18ResilientOperatorsP5leeegoiy9AssocTypeQyd__qd___xtAaBRd__lFZ
 // CHECK-NEXT: }
 
 // CHECK-LABEL: sil_default_witness_table ReabstractSelfRefined {
 // CHECK-NEXT:   no_default
-// CHECK-NEXT:   method #ReabstractSelfRefined.callback!getter.1: {{.*}} : @_T019protocol_resilience21ReabstractSelfRefinedP8callbackxxcvg
-// CHECK-NEXT:   method #ReabstractSelfRefined.callback!setter.1: {{.*}} : @_T019protocol_resilience21ReabstractSelfRefinedP8callbackxxcvs
-// CHECK-NEXT:   method #ReabstractSelfRefined.callback!materializeForSet.1: {{.*}} : @_T019protocol_resilience21ReabstractSelfRefinedP8callbackxxcvm
-// CHECK-NEXT: }
-
-// CHECK-LABEL: sil_default_witness_table hidden InternalProtocol {
-// CHECK-NEXT:   no_default
-// CHECK-NEXT:   method #InternalProtocol.defaultG!1: {{.*}} : @_T019protocol_resilience16InternalProtocolP8defaultGyyF
+// CHECK-NEXT:   method #ReabstractSelfRefined.callback!getter.1: {{.*}} : @_T019protocol_resilience21ReabstractSelfRefinedP8callbackyxxcvg
+// CHECK-NEXT:   method #ReabstractSelfRefined.callback!setter.1: {{.*}} : @_T019protocol_resilience21ReabstractSelfRefinedP8callbackyxxcvs
+// CHECK-NEXT:   method #ReabstractSelfRefined.callback!materializeForSet.1: {{.*}} : @_T019protocol_resilience21ReabstractSelfRefinedP8callbackyxxcvm
 // CHECK-NEXT: }
diff --git a/test/SILGen/protocols.swift b/test/SILGen/protocols.swift
index 171acba..25abc8c 100644
--- a/test/SILGen/protocols.swift
+++ b/test/SILGen/protocols.swift
@@ -398,7 +398,7 @@
 func modifyProperty<T : PropertyWithGetterSetter>(_ x: inout T) {
   modify(&x.b)
 }
-// CHECK-LABEL: sil hidden @_T09protocols14modifyPropertyyxzAA0C16WithGetterSetterRzlF
+// CHECK-LABEL: sil hidden @_T09protocols14modifyPropertyyyxzAA0C16WithGetterSetterRzlF
 // CHECK:      [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T
 // CHECK:      [[WITNESS_FN:%.*]] = witness_method $T, #PropertyWithGetterSetter.b!materializeForSet.1
 // CHECK:      [[RESULT:%.*]] = apply [[WITNESS_FN]]<T>
@@ -406,7 +406,7 @@
 // CHECK:      [[CALLBACK:%.*]] = tuple_extract [[RESULT]]
 // CHECK:      [[TEMPORARY_ADDR_TMP:%.*]] = pointer_to_address [[TEMPORARY]] : $Builtin.RawPointer to [strict] $*Int
 // CHECK:      [[TEMPORARY_ADDR:%.*]] = mark_dependence [[TEMPORARY_ADDR_TMP]] : $*Int on [[WRITE]] : $*T
-// CHECK:      [[MODIFY_FN:%.*]] = function_ref @_T09protocols6modifyySizF
+// CHECK:      [[MODIFY_FN:%.*]] = function_ref @_T09protocols6modifyyySizF
 // CHECK:      apply [[MODIFY_FN]]([[TEMPORARY_ADDR]])
 // CHECK:      switch_enum [[CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: bb2
 // CHECK:    bb1([[CALLBACK_ADDR:%.*]] : @trivial $Builtin.RawPointer):
diff --git a/test/SILGen/reabstract-tuple.swift b/test/SILGen/reabstract-tuple.swift
index ef9287d..eda2e71 100644
--- a/test/SILGen/reabstract-tuple.swift
+++ b/test/SILGen/reabstract-tuple.swift
@@ -25,7 +25,7 @@
 // CHECK:   [[TUPLEB_1:%.*]] = tuple_extract [[BORROWB]] : $(Int, @callee_guaranteed (@in ()) -> @out ()), 1
 // CHECK:   [[COPYB_1:%.*]] = copy_value [[TUPLEB_1]] : $@callee_guaranteed (@in ()) -> @out ()
 // CHECK:   // function_ref Box.__allocating_init(_:)
-// CHECK:   [[INIT_F:%.*]] = function_ref @_T04main3BoxCACyxGxcfC : $@convention(method) <τ_0_0> (@in τ_0_0, @thick Box<τ_0_0>.Type) -> @owned Box<τ_0_0>
+// CHECK:   [[INIT_F:%.*]] = function_ref @_T04main3BoxCyACyxGxcfC : $@convention(method) <τ_0_0> (@in τ_0_0, @thick Box<τ_0_0>.Type) -> @owned Box<τ_0_0>
 // CHECK:   [[CALL:%.*]] = apply [[INIT_F]]<(Int, () -> ())>(%{{.*}}, %{{.*}}) : $@convention(method) <τ_0_0> (@in τ_0_0, @thick Box<τ_0_0>.Type) -> @owned Box<τ_0_0>
 // CHECK:   end_borrow [[BORROWB]] from %{{.*}} : $(Int, @callee_guaranteed (@in ()) -> @out ()), $(Int, @callee_guaranteed (@in ()) -> @out ())
 // CHECK:   destroy_value [[TUPLEB]] : $(Int, @callee_guaranteed (@in ()) -> @out ())
diff --git a/test/SILGen/reabstract.swift b/test/SILGen/reabstract.swift
index 3016671..cc95353 100644
--- a/test/SILGen/reabstract.swift
+++ b/test/SILGen/reabstract.swift
@@ -29,7 +29,7 @@
 // CHECK-NEXT: tuple ()
 // CHECK-NEXT: return
 
-// CHECK-LABEL: sil hidden @_T010reabstract10testThrowsyypF
+// CHECK-LABEL: sil hidden @_T010reabstract10testThrowsyyypF
 // CHECK:         function_ref @_T0ytytIegir_Ieg_TR
 // CHECK:         function_ref @_T0ytyts5Error_pIegirzo_sAA_pIegzo_TR
 func testThrows(_ x: Any) {
@@ -53,8 +53,8 @@
   box.t(&c, i)
 }
 
-// CHECK-LABEL: sil hidden @_T010reabstract15testInoutOpaqueyAA1CC_Si1itF
-// CHECK:         function_ref @_T010reabstract6notFunyAA1CCz_Si1itF
+// CHECK-LABEL: sil hidden @_T010reabstract15testInoutOpaque_1iyAA1CC_SitF
+// CHECK:         function_ref @_T010reabstract6notFun_1iyAA1CCz_SitF
 // CHECK:         thin_to_thick_function {{%[0-9]+}}
 // CHECK:         function_ref @_T010reabstract1CCSiIegly_ACSiytIeglir_TR
 // CHECK:         partial_apply
diff --git a/test/SILGen/reabstract_lvalue.swift b/test/SILGen/reabstract_lvalue.swift
index 868303c..9d94a9a 100644
--- a/test/SILGen/reabstract_lvalue.swift
+++ b/test/SILGen/reabstract_lvalue.swift
@@ -5,7 +5,7 @@
 // CHECK-LABEL: sil hidden @_T017reabstract_lvalue19consumeGenericInOut{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T> (@inout T) -> ()
 func consumeGenericInOut<T>(_ x: inout T) {}
 
-// CHECK-LABEL: sil hidden @_T017reabstract_lvalue9transformSdSiF : $@convention(thin) (Int) -> Double
+// CHECK-LABEL: sil hidden @_T017reabstract_lvalue9transformySdSiF : $@convention(thin) (Int) -> Double
 func transform(_ i: Int) -> Double {
   return Double(i)
 }
@@ -14,7 +14,7 @@
 func reabstractFunctionInOut() {
   // CHECK: [[BOX:%.*]] = alloc_box ${ var @callee_guaranteed (Int) -> Double }
   // CHECK: [[PB:%.*]] = project_box [[BOX]]
-  // CHECK: [[ARG:%.*]] = function_ref @_T017reabstract_lvalue9transformSdSiF
+  // CHECK: [[ARG:%.*]] = function_ref @_T017reabstract_lvalue9transformySdSiF
   // CHECK: [[THICK_ARG:%.*]] = thin_to_thick_function [[ARG]]
   // CHECK: store [[THICK_ARG:%.*]] to [init] [[PB]]
   // CHECK:  [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*@callee_guaranteed (Int) -> Double
diff --git a/test/SILGen/retaining_globals.swift b/test/SILGen/retaining_globals.swift
index daddfde..6909c86 100644
--- a/test/SILGen/retaining_globals.swift
+++ b/test/SILGen/retaining_globals.swift
@@ -52,7 +52,7 @@
   print(arr as Any)
   print(constArr as Any)
 
-  // CHECK: [[PRINT_FUN:%.*]] = function_ref @_T0s5printyypd_SS9separatorSS10terminatortF : $@convention(thin) (@owned Array<Any>, @owned String, @owned String) -> ()
+  // CHECK: [[PRINT_FUN:%.*]] = function_ref @_T0s5print_9separator10terminatoryypd_S2StF : $@convention(thin) (@owned Array<Any>, @owned String, @owned String) -> ()
   // CHECK: apply [[PRINT_FUN]]({{.*}})
   // CHECK: destroy_value [[load_4]]
   // CHECK: destroy_value [[load_3]]
diff --git a/test/SILGen/rethrows.swift b/test/SILGen/rethrows.swift
index 8d26cf2..22c8d6a 100644
--- a/test/SILGen/rethrows.swift
+++ b/test/SILGen/rethrows.swift
@@ -11,7 +11,7 @@
 // CHECK:       [[THROWER:%.*]] = function_ref @_T08rethrows7throwerSiyKF : $@convention(thin) () -> (Int, @error Error)
 // CHECK:       [[T0:%.*]] = thin_to_thick_function [[THROWER]]
 // CHECK:       [[CVT:%.*]] = convert_function [[T0]]
-// CHECK:       [[RETHROWER:%.*]] = function_ref @_T08rethrows9rethrowerS2iyKcKF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> (Int, @error Error)) -> (Int, @error Error)
+// CHECK:       [[RETHROWER:%.*]] = function_ref @_T08rethrows9rethroweryS2iyKcKF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> (Int, @error Error)) -> (Int, @error Error)
 // CHECK:       try_apply [[RETHROWER]]([[CVT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> (Int, @error Error)) -> (Int, @error Error), normal [[NORMAL:bb1]], error [[ERROR:bb2]]
 // CHECK:     [[NORMAL]]([[T0:%.*]] : $Int):
 // CHECK-NEXT:  [[T1:%.*]] = tuple ()
@@ -26,7 +26,7 @@
 // CHECK:       [[CLOSURE:%.*]] = function_ref @_T08rethrows5test1yyKFSiyKcfU_ : $@convention(thin) () -> (Int, @error Error)
 // CHECK:       [[CVT:%.*]] = convert_function [[CLOSURE]]
 // CHECK:       [[T0:%.*]] = thin_to_thick_function [[CVT]]
-// CHECK:       [[RETHROWER:%.*]] = function_ref @_T08rethrows9rethrowerS2iyKcKF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> (Int, @error Error)) -> (Int, @error Error)
+// CHECK:       [[RETHROWER:%.*]] = function_ref @_T08rethrows9rethroweryS2iyKcKF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> (Int, @error Error)) -> (Int, @error Error)
 // CHECK:       try_apply [[RETHROWER]]([[T0]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> (Int, @error Error)) -> (Int, @error Error), normal [[NORMAL:bb1]], error [[ERROR:bb2]]
 // CHECK:     [[NORMAL]]([[T0:%.*]] : $Int):
 // CHECK-NEXT:  [[T1:%.*]] = tuple ()
@@ -38,7 +38,7 @@
 // CHECK:       [[THROWER:%.*]] = function_ref @_T08rethrows7throwerSiyKF : $@convention(thin) () -> (Int, @error Error)
 // CHECK:       [[T0:%.*]] = thin_to_thick_function [[THROWER]]
 // CHECK:       [[CVT:%.*]] = convert_function [[T0]]
-// CHECK:       [[RETHROWER:%.*]] = function_ref @_T08rethrows9rethrowerS2iyKcKF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> (Int, @error Error)) -> (Int, @error Error)
+// CHECK:       [[RETHROWER:%.*]] = function_ref @_T08rethrows9rethroweryS2iyKcKF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> (Int, @error Error)) -> (Int, @error Error)
 // CHECK:       try_apply [[RETHROWER]]([[CVT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> (Int, @error Error)) -> (Int, @error Error), normal [[NORMAL:bb1]], error [[ERROR:bb2]]
 // CHECK:     [[NORMAL]]([[T0:%.*]] : $Int):
 // CHECK-NEXT:  return [[T0]]
@@ -52,7 +52,7 @@
 // CHECK:       [[NONTHROWER:%.*]] = function_ref @_T08rethrows10nonthrowerSiyF : $@convention(thin) () -> Int
 // CHECK:       [[T0:%.*]] = thin_to_thick_function [[NONTHROWER]]
 // CHECK:       [[T1:%.*]] = convert_function [[T0]] : $@callee_guaranteed () -> Int to $@noescape @callee_guaranteed () -> (Int, @error Error)
-// CHECK:       [[RETHROWER:%.*]] = function_ref @_T08rethrows9rethrowerS2iyKcKF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> (Int, @error Error)) -> (Int, @error Error)
+// CHECK:       [[RETHROWER:%.*]] = function_ref @_T08rethrows9rethroweryS2iyKcKF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> (Int, @error Error)) -> (Int, @error Error)
 // CHECK:       try_apply [[RETHROWER]]([[T1]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> (Int, @error Error)) -> (Int, @error Error), normal [[NORMAL:bb1]], error [[ERROR:bb2]]
 // CHECK:     [[NORMAL]]([[T0:%.*]] : $Int):
 // CHECK-NEXT:  [[T1:%.*]] = tuple ()
@@ -68,7 +68,7 @@
 // CHECK:       [[CVT:%.*]] = convert_function [[CLOSURE]] : $@convention(thin) () -> Int to $@convention(thin) @noescape () -> Int
 // CHECK:       [[T0:%.*]] = thin_to_thick_function [[CVT]]
 // CHECK:       [[T1:%.*]] = convert_function [[T0]] : $@noescape @callee_guaranteed () -> Int to $@noescape @callee_guaranteed () -> (Int, @error Error)
-// CHECK:       [[RETHROWER:%.*]] = function_ref @_T08rethrows9rethrowerS2iyKcKF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> (Int, @error Error)) -> (Int, @error Error)
+// CHECK:       [[RETHROWER:%.*]] = function_ref @_T08rethrows9rethroweryS2iyKcKF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> (Int, @error Error)) -> (Int, @error Error)
 // CHECK:       try_apply [[RETHROWER]]([[T1]]) : $@convention(thin) (@owned @noescape @callee_guaranteed () -> (Int, @error Error)) -> (Int, @error Error), normal [[NORMAL:bb1]], error [[ERROR:bb2]]
 // CHECK:     [[NORMAL]]([[T0:%.*]] : $Int):
 // CHECK-NEXT:  [[T1:%.*]] = tuple ()
diff --git a/test/SILGen/same_type_abstraction.swift b/test/SILGen/same_type_abstraction.swift
index 3ec7777..3353062 100644
--- a/test/SILGen/same_type_abstraction.swift
+++ b/test/SILGen/same_type_abstraction.swift
@@ -50,7 +50,7 @@
 }
 
 extension Refined {
-  // CHECK-LABEL: sil hidden @_T021same_type_abstraction7RefinedPAAEx5AssocQz12withElements_tcfC : $@convention(method) <Self where Self : Refined> (@in Self.Assoc, @thick Self.Type) -> @out Self
+  // CHECK-LABEL: sil hidden @_T021same_type_abstraction7RefinedPAAE12withElementsx5AssocQz_tcfC : $@convention(method) <Self where Self : Refined> (@in Self.Assoc, @thick Self.Type) -> @out Self
   init(withElements newElements: Key) {
     self.init()
   }
diff --git a/test/SILGen/scalar_to_tuple_args.swift b/test/SILGen/scalar_to_tuple_args.swift
index 14ef601..4dbe4be 100644
--- a/test/SILGen/scalar_to_tuple_args.swift
+++ b/test/SILGen/scalar_to_tuple_args.swift
@@ -16,14 +16,14 @@
 // CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
 // CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
 // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X_ADDR]] : $*Int
-// CHECK: [[INOUT_WITH_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args17inoutWithDefaultsySiz_Si1ySi1ztF
+// CHECK: [[INOUT_WITH_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args17inoutWithDefaults_1y1zySiz_S2itF
 // CHECK: apply [[INOUT_WITH_DEFAULTS]]([[WRITE]], [[DEFAULT_Y]], [[DEFAULT_Z]])
 inoutWithDefaults(&x)
 
 // CHECK: [[LINE_VAL:%.*]] = integer_literal
 // CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]]
 // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X_ADDR]] : $*Int
-// CHECK: [[INOUT_WITH_CALLER_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args27inoutWithCallerSideDefaultsySiz_Si1ytF
+// CHECK: [[INOUT_WITH_CALLER_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args27inoutWithCallerSideDefaults_1yySiz_SitF
 // CHECK: apply [[INOUT_WITH_CALLER_DEFAULTS]]([[WRITE]], [[LINE]])
 inoutWithCallerSideDefaults(&x)
 
@@ -31,14 +31,14 @@
 // CHECK: [[X:%.*]] = load [trivial] [[READ]]
 // CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
 // CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
-// CHECK: [[SCALAR_WITH_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args0A12WithDefaultsySi_Si1ySi1ztF
+// CHECK: [[SCALAR_WITH_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args0A12WithDefaults_1y1zySi_S2itF
 // CHECK: apply [[SCALAR_WITH_DEFAULTS]]([[X]], [[DEFAULT_Y]], [[DEFAULT_Z]])
 scalarWithDefaults(x)
 
 // CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]]
 // CHECK: [[LINE_VAL:%.*]] = integer_literal
 // CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]]
-// CHECK: [[SCALAR_WITH_CALLER_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args0A22WithCallerSideDefaultsySi_Si1ytF
+// CHECK: [[SCALAR_WITH_CALLER_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args0A22WithCallerSideDefaults_1yySi_SitF
 // CHECK: apply [[SCALAR_WITH_CALLER_DEFAULTS]]([[X]], [[LINE]])
 scalarWithCallerSideDefaults(x)
 
@@ -48,7 +48,7 @@
 // CHECK: [[X2:%.*]] = load [trivial] [[READ]]
 // CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
 // CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
-// CHECK: [[TUPLE_WITH_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args0C12WithDefaultsySi_Sit1x_Si1ySi1ztF
+// CHECK: [[TUPLE_WITH_DEFAULTS:%.*]] = function_ref @_T020scalar_to_tuple_args0C12WithDefaults1x1y1zySi_Sit_S2itF
 // CHECK: apply [[TUPLE_WITH_DEFAULTS]]([[X1]], [[X2]], [[DEFAULT_Y]], [[DEFAULT_Z]])
 tupleWithDefaults(x: (x,x))
 
@@ -63,7 +63,7 @@
 // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
 // CHECK: [[X:%.*]] = load [trivial] [[READ]]
 // CHECK: store [[X]] to [trivial] [[ADDR]]
-// CHECK: [[VARIADIC_FIRST:%.*]] = function_ref @_T020scalar_to_tuple_args13variadicFirstySid_tF
+// CHECK: [[VARIADIC_FIRST:%.*]] = function_ref @_T020scalar_to_tuple_args13variadicFirstyySid_tF
 // CHECK: apply [[VARIADIC_FIRST]]([[ARRAY]])
 variadicFirst(x)
 
@@ -74,6 +74,6 @@
 // CHECK: end_borrow [[BORROWED_ALLOC_ARRAY]] from [[ALLOC_ARRAY]]
 // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
 // CHECK: [[X:%.*]] = load [trivial] [[READ]]
-// CHECK: [[VARIADIC_SECOND:%.*]] = function_ref @_T020scalar_to_tuple_args14variadicSecondySi_SidtF
+// CHECK: [[VARIADIC_SECOND:%.*]] = function_ref @_T020scalar_to_tuple_args14variadicSecondyySi_SidtF
 // CHECK: apply [[VARIADIC_SECOND]]([[X]], [[ARRAY]])
 variadicSecond(x)
diff --git a/test/SILGen/shared.swift b/test/SILGen/shared.swift
index 56df23f..d08692a 100644
--- a/test/SILGen/shared.swift
+++ b/test/SILGen/shared.swift
@@ -4,81 +4,81 @@
 struct ValueAggregate { let x = RefAggregate() }
 
 
-// CHECK-LABEL: sil hidden @_T06shared0A10_argumentsySih7trivial_AA14ValueAggregateVh5valueAA03RefE0Ch3reftF : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()
+// CHECK-LABEL: sil hidden @_T06shared0A10_arguments7trivial5value3refySih_AA14ValueAggregateVhAA03RefG0ChtF : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()
 func shared_arguments(trivial : __shared Int, value : __shared ValueAggregate, ref : __shared RefAggregate) {
   // CHECK: bb0([[TRIVIAL_VAL:%[0-9]+]] : @trivial $Int, [[VALUE_VAL:%[0-9]+]] : @guaranteed $ValueAggregate, [[REF_VAL:%[0-9]+]] : @guaranteed $RefAggregate):
   // CHECK: [[COPY_VALUE_VAL:%[0-9]+]] = copy_value [[VALUE_VAL]] : $ValueAggregate
   // CHECK: [[COPY_REF_VAL:%[0-9]+]] = copy_value [[REF_VAL]] : $RefAggregate
-  // CHECK: [[OWNED_FUNC:%[0-9]+]] = function_ref @_T06shared15owned_argumentsySi7trivial_AA14ValueAggregateV5valueAA03RefF0C3reftF
+  // CHECK: [[OWNED_FUNC:%[0-9]+]] = function_ref @_T06shared15owned_arguments7trivial5value3refySi_AA14ValueAggregateVAA03RefH0CtF
   // CHECK: {{%.*}} = apply [[OWNED_FUNC]]([[TRIVIAL_VAL]], [[COPY_VALUE_VAL]], [[COPY_REF_VAL]]) : $@convention(thin) (Int, @owned ValueAggregate, @owned RefAggregate) -> ()
-  // CHECK: } // end sil function '_T06shared0A10_argumentsySih7trivial_AA14ValueAggregateVh5valueAA03RefE0Ch3reftF'
+  // CHECK: } // end sil function '_T06shared0A10_arguments7trivial5value3refySih_AA14ValueAggregateVhAA03RefG0ChtF'
   return owned_arguments(trivial: trivial, value: value, ref: ref)
 }
 
-// CHECK-LABEL: sil hidden @_T06shared15owned_argumentsySi7trivial_AA14ValueAggregateV5valueAA03RefF0C3reftF : $@convention(thin) (Int, @owned ValueAggregate, @owned RefAggregate) -> ()
+// CHECK-LABEL: sil hidden @_T06shared15owned_arguments7trivial5value3refySi_AA14ValueAggregateVAA03RefH0CtF : $@convention(thin) (Int, @owned ValueAggregate, @owned RefAggregate) -> ()
 func owned_arguments(trivial : Int, value : ValueAggregate, ref : RefAggregate) {
   // CHECK: bb0([[TRIVIAL_VAL:%[0-9]+]] : @trivial $Int, [[VALUE_VAL:%[0-9]+]] : @owned $ValueAggregate, [[REF_VAL:%[0-9]+]] : @owned $RefAggregate):
   // CHECK: [[BORROW_VALUE_VAL:%[0-9]+]] = begin_borrow [[VALUE_VAL]] : $ValueAggregate
   // CHECK: [[BORROW_REF_VAL:%[0-9]+]] = begin_borrow [[REF_VAL]] : $RefAggregate
-  // CHECK: [[SHARED_FUNC:%[0-9]+]] = function_ref @_T06shared0A10_argumentsySih7trivial_AA14ValueAggregateVh5valueAA03RefE0Ch3reftF
+  // CHECK: [[SHARED_FUNC:%[0-9]+]] = function_ref @_T06shared0A10_arguments7trivial5value3refySih_AA14ValueAggregateVhAA03RefG0ChtF
   // CHECK: {{%.*}} = apply [[SHARED_FUNC]]([[TRIVIAL_VAL]], [[BORROW_VALUE_VAL]], [[BORROW_REF_VAL]])
   // CHECK: end_borrow [[BORROW_REF_VAL]] from [[REF_VAL]] : $RefAggregate, $RefAggregate
   // CHECK: end_borrow [[BORROW_VALUE_VAL]] from [[VALUE_VAL]] : $ValueAggregate, $ValueAggregate
   // CHECK: destroy_value [[REF_VAL]] : $RefAggregate
   // CHECK: destroy_value [[VALUE_VAL]] : $ValueAggregate
-  // CHECK: } // end sil function '_T06shared15owned_argumentsySi7trivial_AA14ValueAggregateV5valueAA03RefF0C3reftF'
+  // CHECK: } // end sil function '_T06shared15owned_arguments7trivial5value3refySi_AA14ValueAggregateVAA03RefH0CtF'
   return shared_arguments(trivial: trivial, value: value, ref: ref)
 }
 
-// CHECK-LABEL: sil hidden @_T06shared0A17_argument_captureySih7trivial_AA14ValueAggregateVh5valueAA03RefF0Ch3reftF : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()
+// CHECK-LABEL: sil hidden @_T06shared0A17_argument_capture7trivial5value3refySih_AA14ValueAggregateVhAA03RefH0ChtF : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()
 func shared_argument_capture(trivial : __shared Int, value : __shared ValueAggregate, ref : __shared RefAggregate) {
   // CHECK: bb0([[TRIVIAL_VAL:%[0-9]+]] : @trivial $Int, [[VALUE_VAL:%[0-9]+]] : @guaranteed $ValueAggregate, [[REF_VAL:%[0-9]+]] : @guaranteed $RefAggregate):
-  // CHECK: [[CLO_1:%[0-9]+]] = function_ref @_T06shared0A17_argument_captureySih7trivial_AA14ValueAggregateVh5valueAA03RefF0Ch3reftFyycfU_
+  // CHECK: [[CLO_1:%[0-9]+]] = function_ref @_T06shared0A17_argument_capture7trivial5value3refySih_AA14ValueAggregateVhAA03RefH0ChtFyycfU_
   // CHECK: {{%.*}} = apply [[CLO_1]]([[TRIVIAL_VAL]], [[VALUE_VAL]], [[REF_VAL]]) : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()
   _ = {
     return shared_arguments(trivial: trivial, value: value, ref: ref)
   }()
   
-  // CHECK: [[CLO_2:%[0-9]+]] = function_ref @_T06shared0A17_argument_captureySih7trivial_AA14ValueAggregateVh5valueAA03RefF0Ch3reftFyycfU0_ : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()
+  // CHECK: [[CLO_2:%[0-9]+]] = function_ref @_T06shared0A17_argument_capture7trivial5value3refySih_AA14ValueAggregateVhAA03RefH0ChtFyycfU0_ : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()
   // CHECK: {{%.*}} = apply [[CLO_2]]([[TRIVIAL_VAL]], [[VALUE_VAL]], [[REF_VAL]]) : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()
   _ = {
     return owned_arguments(trivial: trivial, value: value, ref: ref)
   }()
   
-  // CHECK: } // end sil function '_T06shared0A17_argument_captureySih7trivial_AA14ValueAggregateVh5valueAA03RefF0Ch3reftF'
+  // CHECK: } // end sil function '_T06shared0A17_argument_capture7trivial5value3refySih_AA14ValueAggregateVhAA03RefH0ChtF'
   
   // ======== FIRST CLOSURE ==========
 
-  // CHECK-LABEL: sil private @_T06shared0A17_argument_captureySih7trivial_AA14ValueAggregateVh5valueAA03RefF0Ch3reftFyycfU_ : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()
+  // CHECK-LABEL: sil private @_T06shared0A17_argument_capture7trivial5value3refySih_AA14ValueAggregateVhAA03RefH0ChtFyycfU_ : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()
   // CHECK: bb0([[TRIVIAL_VAL:%[0-9]+]] : @trivial $Int, [[VALUE_VAL:%[0-9]+]] : @guaranteed $ValueAggregate, [[REF_VAL:%[0-9]+]] : @guaranteed $RefAggregate):
-  // CHECK: [[SHARED_CALL:%[0-9]+]] = function_ref @_T06shared0A10_argumentsySih7trivial_AA14ValueAggregateVh5valueAA03RefE0Ch3reftF : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()
+  // CHECK: [[SHARED_CALL:%[0-9]+]] = function_ref @_T06shared0A10_arguments7trivial5value3refySih_AA14ValueAggregateVhAA03RefG0ChtF : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()
   // CHECK: {{%.*}} = apply [[SHARED_CALL]]([[TRIVIAL_VAL]], [[VALUE_VAL]], [[REF_VAL]]) : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()
-  // CHECK: } // end sil function '_T06shared0A17_argument_captureySih7trivial_AA14ValueAggregateVh5valueAA03RefF0Ch3reftFyycfU_'
+  // CHECK: } // end sil function '_T06shared0A17_argument_capture7trivial5value3refySih_AA14ValueAggregateVhAA03RefH0ChtFyycfU_'
   
   // ======== SECOND CLOSURE ==========
   
-  // CHECK-LABEL:  sil private @_T06shared0A17_argument_captureySih7trivial_AA14ValueAggregateVh5valueAA03RefF0Ch3reftFyycfU0_ : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> () {
+  // CHECK-LABEL:  sil private @_T06shared0A17_argument_capture7trivial5value3refySih_AA14ValueAggregateVhAA03RefH0ChtFyycfU0_ : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> () {
   // CHECK: bb0([[TRIVIAL_VAL:%[0-9]+]] : @trivial $Int, [[VALUE_VAL:%[0-9]+]] : @guaranteed $ValueAggregate, [[REF_VAL:%[0-9]+]] : @guaranteed $RefAggregate):
   // CHECK: [[COPY_BORROW_VALUE_VAL:%[0-9]+]] = copy_value [[VALUE_VAL]] : $ValueAggregate
   // CHECK: [[COPY_BORROW_REF_VAL:%[0-9]+]] = copy_value [[REF_VAL]] : $RefAggregate
-  // CHECK: [[OWNED_CALL:%[0-9]+]] = function_ref @_T06shared15owned_argumentsySi7trivial_AA14ValueAggregateV5valueAA03RefF0C3reftF : $@convention(thin) (Int, @owned ValueAggregate, @owned RefAggregate) -> ()
+  // CHECK: [[OWNED_CALL:%[0-9]+]] = function_ref @_T06shared15owned_arguments7trivial5value3refySi_AA14ValueAggregateVAA03RefH0CtF : $@convention(thin) (Int, @owned ValueAggregate, @owned RefAggregate) -> ()
   // CHECK: {{%.*}} = apply [[OWNED_CALL]]([[TRIVIAL_VAL]], [[COPY_BORROW_VALUE_VAL]], [[COPY_BORROW_REF_VAL]]) : $@convention(thin) (Int, @owned ValueAggregate, @owned RefAggregate) -> ()
-  // CHECK: } // end sil function '_T06shared0A17_argument_captureySih7trivial_AA14ValueAggregateVh5valueAA03RefF0Ch3reftFyycfU0_'
+  // CHECK: } // end sil function '_T06shared0A17_argument_capture7trivial5value3refySih_AA14ValueAggregateVhAA03RefH0ChtFyycfU0_'
 }
 
-// CHECK-LABEL: sil hidden @_T06shared0A20_to_owned_conversionyySih_AA14ValueAggregateVhAA03RefF0ChtcF : $@convention(thin) (@owned @noescape @callee_guaranteed (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()) -> ()
+// CHECK-LABEL: sil hidden @_T06shared0A20_to_owned_conversionyyySih_AA14ValueAggregateVhAA03RefF0ChtcF : $@convention(thin) (@owned @noescape @callee_guaranteed (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()) -> ()
 func shared_to_owned_conversion(_ f : (__shared Int, __shared ValueAggregate, __shared RefAggregate) -> Void) {
   // CHECK: bb0([[UNUSED_FUNC:%[0-9]+]] : @owned $@noescape @callee_guaranteed (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()):
-  // CHECK: [[OWNED_THUNK:%[0-9]+]] = function_ref @_T06shared0A20_to_owned_conversionyySih_AA14ValueAggregateVhAA03RefF0ChtcFySi_AdFtcfU_ : $@convention(thin) (Int, @owned ValueAggregate, @owned RefAggregate) -> ()
+  // CHECK: [[OWNED_THUNK:%[0-9]+]] = function_ref @_T06shared0A20_to_owned_conversionyyySih_AA14ValueAggregateVhAA03RefF0ChtcFySi_AdFtcfU_ : $@convention(thin) (Int, @owned ValueAggregate, @owned RefAggregate) -> ()
   // CHECK: [[CONVERT:%.*]] = convert_function [[OWNED_THUNK]]
   // CHECK: [[THICK_OWNED_THUNK:%[0-9]+]] = thin_to_thick_function [[CONVERT]] : $@convention(thin) @noescape (Int, @owned ValueAggregate, @owned RefAggregate) -> () to $@noescape @callee_guaranteed (Int, @owned ValueAggregate, @owned RefAggregate) -> ()
   // CHECK: [[GUARANTEED_TO_OWNED_THUNK:%[0-9]+]] =  function_ref @_T0Si6shared14ValueAggregateVAA03RefC0CIgyxx_SiAcEIgygg_TR : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate, @guaranteed @noescape @callee_guaranteed (Int, @owned ValueAggregate, @owned RefAggregate) -> ()) -> ()
   // CHECK: [[APPLIED_THUNK:%[0-9]+]] = partial_apply [callee_guaranteed] [[GUARANTEED_TO_OWNED_THUNK]]([[THICK_OWNED_THUNK]]) : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate, @guaranteed @noescape @callee_guaranteed (Int, @owned ValueAggregate, @owned RefAggregate) -> ()) -> ()
   // CHECK: [[CONVERT:%.*]] = convert_function [[APPLIED_THUNK]]
-  // CHECK: [[RECUR_FN:%[0-9]+]] = function_ref @_T06shared0A20_to_owned_conversionyySih_AA14ValueAggregateVhAA03RefF0ChtcF : $@convention(thin) (@owned @noescape @callee_guaranteed (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()) -> ()
+  // CHECK: [[RECUR_FN:%[0-9]+]] = function_ref @_T06shared0A20_to_owned_conversionyyySih_AA14ValueAggregateVhAA03RefF0ChtcF : $@convention(thin) (@owned @noescape @callee_guaranteed (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()) -> ()
   // CHECK: {{%.*}} = apply [[RECUR_FN]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()) -> ()
   // CHECK: destroy_value [[UNUSED_FUNC]] : $@noescape @callee_guaranteed (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()
-  // CHECK: } // end sil function '_T06shared0A20_to_owned_conversionyySih_AA14ValueAggregateVhAA03RefF0ChtcF'
+  // CHECK: } // end sil function '_T06shared0A20_to_owned_conversionyyySih_AA14ValueAggregateVhAA03RefF0ChtcF'
   
   // ======== REABSTRACTION THUNK =========
   
@@ -92,19 +92,19 @@
   return shared_to_owned_conversion { (trivial : Int, val : ValueAggregate, ref : RefAggregate) in }
 }
 
-// CHECK-LABEL: sil hidden @_T06shared09owned_to_A11_conversionyySi_AA14ValueAggregateVAA03RefF0CtcF : $@convention(thin) (@owned @noescape @callee_guaranteed (Int, @owned ValueAggregate, @owned RefAggregate) -> ()) -> ()
+// CHECK-LABEL: sil hidden @_T06shared09owned_to_A11_conversionyyySi_AA14ValueAggregateVAA03RefF0CtcF : $@convention(thin) (@owned @noescape @callee_guaranteed (Int, @owned ValueAggregate, @owned RefAggregate) -> ()) -> ()
 func owned_to_shared_conversion(_ f : (Int, ValueAggregate, RefAggregate) -> Void) {
   // CHECK: bb0([[UNUSED_FUNC:%[0-9]+]] : @owned $@noescape @callee_guaranteed (Int, @owned ValueAggregate, @owned RefAggregate) -> ()):
-  // CHECK: [[SHARED_THUNK:%[0-9]+]] = function_ref @_T06shared09owned_to_A11_conversionyySi_AA14ValueAggregateVAA03RefF0CtcFySih_ADhAFhtcfU_ : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()
+  // CHECK: [[SHARED_THUNK:%[0-9]+]] = function_ref @_T06shared09owned_to_A11_conversionyyySi_AA14ValueAggregateVAA03RefF0CtcFySih_ADhAFhtcfU_ : $@convention(thin) (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()
   // CHECK: [[CONVERT:%.*]] = convert_function [[SHARED_THUNK]]
   // CHECK: [[THICK_SHARED_THUNK:%[0-9]+]] = thin_to_thick_function [[CONVERT]] : $@convention(thin) @noescape (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> () to $@noescape @callee_guaranteed (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()
   // CHECK: [[OWNED_TO_GUARANTEED_THUNK:%[0-9]+]] = function_ref @_T0Si6shared14ValueAggregateVAA03RefC0CIgygg_SiAcEIgyxx_TR : $@convention(thin) (Int, @owned ValueAggregate, @owned RefAggregate, @guaranteed @noescape @callee_guaranteed (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()) -> ()
   // CHECK: [[APPLIED_THUNK:%[0-9]+]] = partial_apply [callee_guaranteed] [[OWNED_TO_GUARANTEED_THUNK]]([[THICK_SHARED_THUNK]]) : $@convention(thin) (Int, @owned ValueAggregate, @owned RefAggregate, @guaranteed @noescape @callee_guaranteed (Int, @guaranteed ValueAggregate, @guaranteed RefAggregate) -> ()) -> ()
   // CHECK: [[CONVERT:%.*]] = convert_function [[APPLIED_THUNK]]
-  // CHECK: [[RECUR_FN:%[0-9]+]] = function_ref @_T06shared09owned_to_A11_conversionyySi_AA14ValueAggregateVAA03RefF0CtcF : $@convention(thin) (@owned @noescape @callee_guaranteed (Int, @owned ValueAggregate, @owned RefAggregate) -> ()) -> ()
+  // CHECK: [[RECUR_FN:%[0-9]+]] = function_ref @_T06shared09owned_to_A11_conversionyyySi_AA14ValueAggregateVAA03RefF0CtcF : $@convention(thin) (@owned @noescape @callee_guaranteed (Int, @owned ValueAggregate, @owned RefAggregate) -> ()) -> ()
   // CHECK: {{%.*}} = apply [[RECUR_FN]]([[CONVERT]]) : $@convention(thin) (@owned @noescape @callee_guaranteed (Int, @owned ValueAggregate, @owned RefAggregate) -> ()) -> ()
   // CHECK: destroy_value [[UNUSED_FUNC]] : $@noescape @callee_guaranteed (Int, @owned ValueAggregate, @owned RefAggregate) -> ()
-  // CHECK: } // end sil function '_T06shared09owned_to_A11_conversionyySi_AA14ValueAggregateVAA03RefF0CtcF'
+  // CHECK: } // end sil function '_T06shared09owned_to_A11_conversionyyySi_AA14ValueAggregateVAA03RefF0CtcF'
 
   // ======== REABSTRACTION THUNK =========
 
@@ -122,5 +122,5 @@
   return owned_to_shared_conversion { (trivial : __shared Int, val : __shared ValueAggregate, ref : __shared RefAggregate) in }
 }
 
-// CHECK-LABEL: sil hidden @_T06shared0A17_closure_loweringyySi_AA14ValueAggregateVAA03RefE0CtchF : $@convention(thin) (@guaranteed @callee_guaranteed (Int, @owned ValueAggregate, @owned RefAggregate) -> ()) -> ()
+// CHECK-LABEL: sil hidden @_T06shared0A17_closure_loweringyyySi_AA14ValueAggregateVAA03RefE0CtchF : $@convention(thin) (@guaranteed @callee_guaranteed (Int, @owned ValueAggregate, @owned RefAggregate) -> ()) -> ()
 func shared_closure_lowering(_ f : __shared (Int, ValueAggregate, RefAggregate) -> Void) {}
diff --git a/test/SILGen/sil_locations.swift b/test/SILGen/sil_locations.swift
index c66a978..44823be 100644
--- a/test/SILGen/sil_locations.swift
+++ b/test/SILGen/sil_locations.swift
@@ -65,8 +65,8 @@
 // --- Test function calls.
 func simpleDirectCallTest(_ i: Int) -> Int {
   return simpleDirectCallTest(i)
-  // CHECK-LABEL: sil hidden @_T013sil_locations20simpleDirectCallTestS2iF
-  // CHECK: function_ref @_T013sil_locations20simpleDirectCallTestS2iF : {{.*}}, loc "{{.*}}":[[@LINE-2]]:10
+  // CHECK-LABEL: sil hidden @_T013sil_locations20simpleDirectCallTestyS2iF
+  // CHECK: function_ref @_T013sil_locations20simpleDirectCallTestyS2iF : {{.*}}, loc "{{.*}}":[[@LINE-2]]:10
   // CHECK: {{%.*}} apply {{%.*}} line:[[@LINE-3]]:10
 }
 
@@ -76,7 +76,7 @@
 func useTemplateTest() -> Int {
   return templateTest(5);
   // CHECK-LABEL: sil hidden @_T013sil_locations15useTemplateTestSiyF
-  // CHECK: function_ref @_T0S2i{{[_0-9a-zA-Z]*}}fC :{{.*}}, loc "{{.*}}":77
+  // CHECK: function_ref @_T0Si2{{[_0-9a-zA-Z]*}}fC :{{.*}}, loc "{{.*}}":77
 }
 
 func foo(_ x: Int) -> Int {
diff --git a/test/SILGen/source_location.swift b/test/SILGen/source_location.swift
index df1405f..7725b13 100644
--- a/test/SILGen/source_location.swift
+++ b/test/SILGen/source_location.swift
@@ -8,7 +8,7 @@
 // CHECK: [[CALLER_FILE:%.*]] = apply {{.*}}([[CALLER_FILE_VAL]],
 // CHECK: [[CALLER_LINE_VAL:%.*]] = integer_literal $Builtin.Int{{[0-9]+}}, 10000,
 // CHECK: [[CALLER_LINE:%.*]] = apply {{.*}}([[CALLER_LINE_VAL]],
-// CHECK: [[PRINT_SOURCE_LOCATION:%.*]] = function_ref @_T015source_location19printSourceLocationySS4file_Si4linetF
+// CHECK: [[PRINT_SOURCE_LOCATION:%.*]] = function_ref @_T015source_location19printSourceLocation4file4lineySS_SitF
 // CHECK: apply [[PRINT_SOURCE_LOCATION]]([[CALLER_FILE]], [[CALLER_LINE]])
 
 #sourceLocation(file: "inplace.swift", line: 20000)
diff --git a/test/SILGen/specialize_attr.swift b/test/SILGen/specialize_attr.swift
index 69a76e9..836c849 100644
--- a/test/SILGen/specialize_attr.swift
+++ b/test/SILGen/specialize_attr.swift
@@ -32,9 +32,9 @@
   }
 }
 
-// CHECK-LABEL: sil hidden [_specialize exported: false, kind: full, where T == Int, U == Float] @_T015specialize_attr0A4Thisyx_q_1utr0_lF : $@convention(thin) <T, U> (@in T, @in U) -> () {
+// CHECK-LABEL: sil hidden [_specialize exported: false, kind: full, where T == Int, U == Float] @_T015specialize_attr0A4This_1uyx_q_tr0_lF : $@convention(thin) <T, U> (@in T, @in U) -> () {
 
-// CHECK-LABEL: sil [noinline] [_specialize exported: false, kind: full, where T == RR, U == SS] @_T015specialize_attr2CCC3fooqd___AA2GGVyxGtqd___AG1gtAA2QQRd__lF : $@convention(method) <T where T : PP><U where U : QQ> (@in U, GG<T>, @guaranteed CC<T>) -> (@out U, GG<T>) {
+// CHECK-LABEL: sil [noinline] [_specialize exported: false, kind: full, where T == RR, U == SS] @_T015specialize_attr2CCC3foo_1gqd___AA2GGVyxGtqd___AHtAA2QQRd__lF : $@convention(method) <T where T : PP><U where U : QQ> (@in U, GG<T>, @guaranteed CC<T>) -> (@out U, GG<T>) {
 
 // -----------------------------------------------------------------------------
 // Test user-specialized subscript accessors.
@@ -64,13 +64,13 @@
 }
 
 // ASubscriptable.subscript.getter with _specialize
-// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr14ASubscriptableCxSicig : $@convention(method) <Element> (Int, @guaranteed ASubscriptable<Element>) -> @out Element {
+// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr14ASubscriptableCyxSicig : $@convention(method) <Element> (Int, @guaranteed ASubscriptable<Element>) -> @out Element {
 
 // ASubscriptable.subscript.setter with _specialize
-// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr14ASubscriptableCxSicis : $@convention(method) <Element> (@in Element, Int, @guaranteed ASubscriptable<Element>) -> () {
+// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr14ASubscriptableCyxSicis : $@convention(method) <Element> (@in Element, Int, @guaranteed ASubscriptable<Element>) -> () {
 
 // ASubscriptable.subscript.materializeForSet with no attribute
-// CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr14ASubscriptableCxSicim : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed ASubscriptable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
+// CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr14ASubscriptableCyxSicim : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed ASubscriptable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
 
 public class Addressable<Element> : TestSubscriptable {
   var storage: UnsafeMutablePointer<Element>
@@ -92,17 +92,17 @@
 }
 
 // Addressable.subscript.getter with no attribute
-// CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr11AddressableCxSicig : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> @out Element {
+// CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr11AddressableCyxSicig : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> @out Element {
 
 // Addressable.subscript.unsafeAddressor with _specialize
-// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr11AddressableCxSicilu : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafePointer<Element> {
+// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr11AddressableCyxSicilu : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafePointer<Element> {
 
 // Addressable.subscript.setter with no attribute
-// CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr11AddressableCxSicis : $@convention(method) <Element> (@in Element, Int, @guaranteed Addressable<Element>) -> () {
+// CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr11AddressableCyxSicis : $@convention(method) <Element> (@in Element, Int, @guaranteed Addressable<Element>) -> () {
 
 // Addressable.subscript.unsafeMutableAddressor with _specialize
-// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr11AddressableCxSiciau : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafeMutablePointer<Element> {
+// CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] @_T015specialize_attr11AddressableCyxSiciau : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafeMutablePointer<Element> {
 
 // Addressable.subscript.materializeForSet with no attribute
-// CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr11AddressableCxSicim : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed Addressable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
+// CHECK-LABEL: sil [transparent] [serialized] @_T015specialize_attr11AddressableCyxSicim : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed Addressable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
 
diff --git a/test/SILGen/statements.swift b/test/SILGen/statements.swift
index 464bec8..49ec23e 100644
--- a/test/SILGen/statements.swift
+++ b/test/SILGen/statements.swift
@@ -240,7 +240,7 @@
 
 // <rdar://problem/19150249> Allow labeled "break" from an "if" statement
 
-// CHECK-LABEL: sil hidden @_T010statements13test_if_breakyAA1CCSgF : $@convention(thin) (@owned Optional<C>) -> () {
+// CHECK-LABEL: sil hidden @_T010statements13test_if_breakyyAA1CCSgF : $@convention(thin) (@owned Optional<C>) -> () {
 func test_if_break(_ c : C?) {
 // CHECK: bb0([[ARG:%.*]] : @owned $Optional<C>):
 label1:
@@ -263,7 +263,7 @@
   // CHECK: return
 }
 
-// CHECK-LABEL: sil hidden @_T010statements18test_if_else_breakyAA1CCSgF : $@convention(thin) (@owned Optional<C>) -> () {
+// CHECK-LABEL: sil hidden @_T010statements18test_if_else_breakyyAA1CCSgF : $@convention(thin) (@owned Optional<C>) -> () {
 func test_if_else_break(_ c : C?) {
 // CHECK: bb0([[ARG:%.*]] : @owned $Optional<C>):
 label2:
@@ -292,7 +292,7 @@
   // CHECK: return
 }
 
-// CHECK-LABEL: sil hidden @_T010statements23test_if_else_then_breakySb_AA1CCSgtF
+// CHECK-LABEL: sil hidden @_T010statements23test_if_else_then_breakyySb_AA1CCSgtF
 func test_if_else_then_break(_ a : Bool, _ c : C?) {
 label3:
   // CHECK: bb0({{.*}}, [[ARG2:%.*]] : @owned $Optional<C>):
@@ -331,7 +331,7 @@
 }
 
 
-// CHECK-LABEL: sil hidden @_T010statements13test_if_breakySbF
+// CHECK-LABEL: sil hidden @_T010statements13test_if_breakyySbF
 func test_if_break(_ a : Bool) {
   // CHECK: br [[LOOP:bb[0-9]+]]
   // CHECK: [[LOOP]]:
@@ -366,7 +366,7 @@
 // CHECK-LABEL: sil hidden @_T010statements7test_doyyF
 func test_do() {
   // CHECK: integer_literal $Builtin.Int2048, 0
-  // CHECK: [[BAR:%.*]] = function_ref @_T010statements3barySiF
+  // CHECK: [[BAR:%.*]] = function_ref @_T010statements3baryySiF
   // CHECK: apply [[BAR]](
   bar(0)
   // CHECK-NOT: br bb
@@ -377,7 +377,7 @@
     _ = obj
     
     // CHECK: integer_literal $Builtin.Int2048, 1
-    // CHECK: [[BAR:%.*]] = function_ref @_T010statements3barySiF
+    // CHECK: [[BAR:%.*]] = function_ref @_T010statements3baryySiF
     // CHECK: apply [[BAR]](
     bar(1)
 
@@ -387,7 +387,7 @@
   }
 
   // CHECK: integer_literal $Builtin.Int2048, 2
-  // CHECK: [[BAR:%.*]] = function_ref @_T010statements3barySiF
+  // CHECK: [[BAR:%.*]] = function_ref @_T010statements3baryySiF
   // CHECK: apply [[BAR]](
   bar(2)
 }
@@ -395,7 +395,7 @@
 // CHECK-LABEL: sil hidden @_T010statements15test_do_labeledyyF
 func test_do_labeled() {
   // CHECK: integer_literal $Builtin.Int2048, 0
-  // CHECK: [[BAR:%.*]] = function_ref @_T010statements3barySiF
+  // CHECK: [[BAR:%.*]] = function_ref @_T010statements3baryySiF
   // CHECK: apply [[BAR]](
   bar(0)
   // CHECK: br bb1
@@ -407,7 +407,7 @@
     _ = obj
 
     // CHECK: integer_literal $Builtin.Int2048, 1
-    // CHECK: [[BAR:%.*]] = function_ref @_T010statements3barySiF
+    // CHECK: [[BAR:%.*]] = function_ref @_T010statements3baryySiF
     // CHECK: apply [[BAR]](
     bar(1)
 
@@ -422,7 +422,7 @@
 
     // CHECK: bb3:
     // CHECK: integer_literal $Builtin.Int2048, 2
-    // CHECK: [[BAR:%.*]] = function_ref @_T010statements3barySiF
+    // CHECK: [[BAR:%.*]] = function_ref @_T010statements3baryySiF
     // CHECK: apply [[BAR]](
     bar(2)
 
@@ -437,7 +437,7 @@
 
     // CHECK: bb5:
     // CHECK: integer_literal $Builtin.Int2048, 3
-    // CHECK: [[BAR:%.*]] = function_ref @_T010statements3barySiF
+    // CHECK: [[BAR:%.*]] = function_ref @_T010statements3baryySiF
     // CHECK: apply [[BAR]](
     bar(3)
 
@@ -446,7 +446,7 @@
   }
 
   // CHECK: integer_literal $Builtin.Int2048, 4
-  // CHECK: [[BAR:%.*]] = function_ref @_T010statements3barySiF
+  // CHECK: [[BAR:%.*]] = function_ref @_T010statements3baryySiF
   // CHECK: apply [[BAR]](
   bar(4)
 }
@@ -475,7 +475,7 @@
 // CHECK: sil private @_T010statements11defer_test1yyF6
 // CHECK: function_ref @{{.*}}callee2yyF
 
-// CHECK-LABEL: sil hidden @_T010statements11defer_test2ySbF
+// CHECK-LABEL: sil hidden @_T010statements11defer_test2yySbF
 func defer_test2(_ cond : Bool) {
   // CHECK: [[C3:%.*]] = function_ref @{{.*}}callee3yyF
   // CHECK: apply [[C3]]
@@ -491,7 +491,7 @@
   // CHECK: [[C2:%.*]] = function_ref @{{.*}}callee2yyF
   // CHECK: apply [[C2]]
 
-  // CHECK: [[C1:%.*]] = function_ref @_T010statements11defer_test2ySbF6
+  // CHECK: [[C1:%.*]] = function_ref @_T010statements11defer_test2yySbF6
   // CHECK: apply [[C1]]
   // CHECK: br [[EXIT]]
     defer { callee1() }
@@ -514,31 +514,31 @@
 func defer_in_generic<T>(_ x: T) {
   // CHECK: [[C3:%.*]] = function_ref @_T010statements16generic_callee_3{{[_0-9a-zA-Z]*}}F
   // CHECK: apply [[C3]]<T>
-  // CHECK: [[C2:%.*]] = function_ref @_T010statements16defer_in_genericyxlF6
+  // CHECK: [[C2:%.*]] = function_ref @_T010statements16defer_in_genericyyxlF6
   // CHECK: apply [[C2]]<T>
-  // CHECK: [[C1:%.*]] = function_ref @_T010statements16defer_in_genericyxlF6
+  // CHECK: [[C1:%.*]] = function_ref @_T010statements16defer_in_genericyyxlF6
   // CHECK: apply [[C1]]<T>
   defer { generic_callee_1(x) }
   defer { generic_callee_2(x) }
   generic_callee_3(x)
 }
 
-// CHECK-LABEL: sil hidden @_T010statements017defer_in_closure_C8_genericyxlF : $@convention(thin) <T> (@in T) -> ()
+// CHECK-LABEL: sil hidden @_T010statements017defer_in_closure_C8_genericyyxlF : $@convention(thin) <T> (@in T) -> ()
 func defer_in_closure_in_generic<T>(_ x: T) {
-  // CHECK-LABEL: sil private @_T010statements017defer_in_closure_C8_genericyxlFyycfU_ : $@convention(thin) <T> () -> ()
+  // CHECK-LABEL: sil private @_T010statements017defer_in_closure_C8_genericyyxlFyycfU_ : $@convention(thin) <T> () -> ()
   _ = {
-    // CHECK-LABEL: sil private @_T010statements017defer_in_closure_C8_genericyxlFyycfU_6$deferL_yylF : $@convention(thin) <T> () -> ()
+    // CHECK-LABEL: sil private @_T010statements017defer_in_closure_C8_genericyyxlFyycfU_6$deferL_yylF : $@convention(thin) <T> () -> ()
     defer { generic_callee_1(T.self) }
   }
 }
 
-// CHECK-LABEL: sil hidden @_T010statements13defer_mutableySiF
+// CHECK-LABEL: sil hidden @_T010statements13defer_mutableyySiF
 func defer_mutable(_ x: Int) {
   var x = x
   // CHECK: [[BOX:%.*]] = alloc_box ${ var Int }
   // CHECK-NEXT: project_box [[BOX]]
   // CHECK-NOT: [[BOX]]
-  // CHECK: function_ref @_T010statements13defer_mutableySiF6$deferL_yyF : $@convention(thin) (@inout_aliasable Int) -> ()
+  // CHECK: function_ref @_T010statements13defer_mutableyySiF6$deferL_yyF : $@convention(thin) (@inout_aliasable Int) -> ()
   // CHECK-NOT: [[BOX]]
   // CHECK: destroy_value [[BOX]]
   defer { _ = x }
@@ -555,7 +555,7 @@
 
 
 
-// CHECK-LABEL: sil hidden @_T010statements22testRequireExprPatternySiF
+// CHECK-LABEL: sil hidden @_T010statements22testRequireExprPatternyySiF
 
 func testRequireExprPattern(_ a : Int) {
   marker_1()
@@ -585,7 +585,7 @@
 }
 
 
-// CHECK-LABEL: sil hidden @_T010statements20testRequireOptional1S2iSgF
+// CHECK-LABEL: sil hidden @_T010statements20testRequireOptional1yS2iSgF
 // CHECK: bb0([[ARG:%.*]] : @trivial $Optional<Int>):
 // CHECK-NEXT:   debug_value [[ARG]] : $Optional<Int>, let, name "a"
 // CHECK-NEXT:   switch_enum [[ARG]] : $Optional<Int>, case #Optional.some!enumelt.1: [[SOME:bb[0-9]+]], case #Optional.none!enumelt: [[NONE:bb[0-9]+]]
@@ -610,7 +610,7 @@
   return t
 }
 
-// CHECK-LABEL: sil hidden @_T010statements20testRequireOptional2S2SSgF
+// CHECK-LABEL: sil hidden @_T010statements20testRequireOptional2yS2SSgF
 // CHECK: bb0([[ARG:%.*]] : @owned $Optional<String>):
 // CHECK-NEXT:   debug_value [[ARG]] : $Optional<String>, let, name "a"
 // CHECK-NEXT:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
@@ -654,7 +654,7 @@
 }
 
 
-// CHECK-LABEL: sil hidden @_T010statements15test_is_patternyAA9BaseClassCF
+// CHECK-LABEL: sil hidden @_T010statements15test_is_patternyyAA9BaseClassCF
 func test_is_pattern(_ y : BaseClass) {
   // checked_cast_br %0 : $BaseClass to $DerivedClass
   guard case is DerivedClass = y else { marker_1(); return }
@@ -662,7 +662,7 @@
   marker_2()
 }
 
-// CHECK-LABEL: sil hidden @_T010statements15test_as_patternAA12DerivedClassCAA04BaseF0CF
+// CHECK-LABEL: sil hidden @_T010statements15test_as_patternyAA12DerivedClassCAA04BaseF0CF
 func test_as_pattern(_ y : BaseClass) -> DerivedClass {
   // CHECK: bb0([[ARG:%.*]] : @owned $BaseClass):
   // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
@@ -685,7 +685,7 @@
   // CHECK-NEXT: return [[RESULT]] : $DerivedClass
   return result
 }
-// CHECK-LABEL: sil hidden @_T010statements22let_else_tuple_bindingS2i_SitSgF
+// CHECK-LABEL: sil hidden @_T010statements22let_else_tuple_bindingyS2i_SitSgF
 func let_else_tuple_binding(_ a : (Int, Int)?) -> Int {
 
   // CHECK: bb0([[ARG:%.*]] : @trivial $Optional<(Int, Int)>):
diff --git a/test/SILGen/struct_resilience.swift b/test/SILGen/struct_resilience.swift
index 882d432..ef234d8 100644
--- a/test/SILGen/struct_resilience.swift
+++ b/test/SILGen/struct_resilience.swift
@@ -6,7 +6,7 @@
 
 // Resilient structs are always address-only
 
-// CHECK-LABEL: sil hidden @_T017struct_resilience26functionWithResilientTypes010resilient_A04SizeVAE_A2Ec1ftF : $@convention(thin) (@in Size, @owned @noescape @callee_guaranteed (@in Size) -> @out Size) -> @out Size
+// CHECK-LABEL: sil hidden @_T017struct_resilience26functionWithResilientTypes_1f010resilient_A04SizeVAF_A2FctF : $@convention(thin) (@in Size, @owned @noescape @callee_guaranteed (@in Size) -> @out Size) -> @out Size
 // CHECK:       bb0(%0 : @trivial $*Size, %1 : @trivial $*Size, %2 : @owned $@noescape @callee_guaranteed (@in Size) -> @out Size):
 func functionWithResilientTypes(_ s: Size, f: (Size) -> Size) -> Size {
 
@@ -43,12 +43,12 @@
 
 public func inoutFunc(_ x: inout Int) {}
 
-// CHECK-LABEL: sil hidden @_T017struct_resilience18resilientInOutTesty0c1_A04SizeVzF : $@convention(thin) (@inout Size) -> ()
+// CHECK-LABEL: sil hidden @_T017struct_resilience18resilientInOutTestyy0c1_A04SizeVzF : $@convention(thin) (@inout Size) -> ()
 
 func resilientInOutTest(_ s: inout Size) {
 
 // CHECK:         function_ref @_T016resilient_struct4SizeV1wSivm
-// CHECK:         function_ref @_T017struct_resilience9inoutFuncySizF
+// CHECK:         function_ref @_T017struct_resilience9inoutFuncyySizF
 
   inoutFunc(&s.w)
 
@@ -57,7 +57,7 @@
 
 // Fixed-layout structs may be trivial or loadable
 
-// CHECK-LABEL: sil hidden @_T017struct_resilience28functionWithFixedLayoutTypes010resilient_A05PointVAE_A2Ec1ftF : $@convention(thin) (Point, @owned @noescape @callee_guaranteed (Point) -> Point) -> Point
+// CHECK-LABEL: sil hidden @_T017struct_resilience28functionWithFixedLayoutTypes_1f010resilient_A05PointVAF_A2FctF : $@convention(thin) (Point, @owned @noescape @callee_guaranteed (Point) -> Point) -> Point
 // CHECK:       bb0(%0 : @trivial $Point, %1 : @owned $@noescape @callee_guaranteed (Point) -> Point):
 func functionWithFixedLayoutTypes(_ p: Point, f: (Point) -> Point) -> Point {
 
@@ -82,7 +82,7 @@
 
 // Fixed-layout struct with resilient stored properties is still address-only
 
-// CHECK-LABEL: sil hidden @_T017struct_resilience39functionWithFixedLayoutOfResilientTypes010resilient_A09RectangleVAE_A2Ec1ftF : $@convention(thin) (@in Rectangle, @owned @noescape @callee_guaranteed (@in Rectangle) -> @out Rectangle) -> @out Rectangle
+// CHECK-LABEL: sil hidden @_T017struct_resilience39functionWithFixedLayoutOfResilientTypes_1f010resilient_A09RectangleVAF_A2FctF : $@convention(thin) (@in Rectangle, @owned @noescape @callee_guaranteed (@in Rectangle) -> @out Rectangle) -> @out Rectangle
 // CHECK:        bb0(%0 : @trivial $*Rectangle, %1 : @trivial $*Rectangle, %2 : @owned $@noescape @callee_guaranteed (@in Rectangle) -> @out Rectangle):
 func functionWithFixedLayoutOfResilientTypes(_ r: Rectangle, f: (Rectangle) -> Rectangle) -> Rectangle {
   return f(r)
@@ -133,7 +133,7 @@
   public static var copyright: Int = 0
 }
 
-// CHECK-LABEL: sil @_T017struct_resilience28functionWithMyResilientTypesAA0E4SizeVAD_A2Dc1ftF : $@convention(thin) (@in MySize, @owned @noescape @callee_guaranteed (@in MySize) -> @out MySize) -> @out MySize
+// CHECK-LABEL: sil @_T017struct_resilience28functionWithMyResilientTypes_1fAA0E4SizeVAE_A2EctF : $@convention(thin) (@in MySize, @owned @noescape @callee_guaranteed (@in MySize) -> @out MySize) -> @out MySize
 public func functionWithMyResilientTypes(_ s: MySize, f: (MySize) -> MySize) -> MySize {
 
   // Stored properties of resilient structs from inside our resilience
@@ -163,7 +163,7 @@
   return f(s)
 }
 
-// CHECK-LABEL: sil [transparent] [serialized] @_T017struct_resilience25publicTransparentFunctionSiAA6MySizeVF : $@convention(thin) (@in MySize) -> Int
+// CHECK-LABEL: sil [transparent] [serialized] @_T017struct_resilience25publicTransparentFunctionySiAA6MySizeVF : $@convention(thin) (@in MySize) -> Int
 @_transparent public func publicTransparentFunction(_ s: MySize) -> Int {
 
   // Since the body of a public transparent function might be inlined into
@@ -181,10 +181,10 @@
   return s.w
 }
 
-// CHECK-LABEL: sil [transparent] [serialized] @_T017struct_resilience30publicTransparentLocalFunctionSiycAA6MySizeVF : $@convention(thin) (@in MySize) -> @owned @callee_guaranteed () -> Int
+// CHECK-LABEL: sil [transparent] [serialized] @_T017struct_resilience30publicTransparentLocalFunctionySiycAA6MySizeVF : $@convention(thin) (@in MySize) -> @owned @callee_guaranteed () -> Int
 @_transparent public func publicTransparentLocalFunction(_ s: MySize) -> () -> Int {
 
-// CHECK-LABEL: sil shared [serialized] @_T017struct_resilience30publicTransparentLocalFunctionSiycAA6MySizeVFSiycfU_ : $@convention(thin) (@guaranteed { var MySize }) -> Int
+// CHECK-LABEL: sil shared [serialized] @_T017struct_resilience30publicTransparentLocalFunctionySiycAA6MySizeVFSiycfU_ : $@convention(thin) (@guaranteed { var MySize }) -> Int
 // CHECK: function_ref @_T017struct_resilience6MySizeV1wSivg : $@convention(method) (@in_guaranteed MySize) -> Int
 // CHECK: return {{.*}} : $Int
 
@@ -192,7 +192,7 @@
 
 }
 
-// CHECK-LABEL: sil hidden [transparent] @_T017struct_resilience27internalTransparentFunctionSiAA6MySizeVF : $@convention(thin) (@in MySize) -> Int
+// CHECK-LABEL: sil hidden [transparent] @_T017struct_resilience27internalTransparentFunctionySiAA6MySizeVF : $@convention(thin) (@in MySize) -> Int
 // CHECK: bb0([[ARG:%.*]] : @trivial $*MySize):
 @_transparent func internalTransparentFunction(_ s: MySize) -> Int {
 
@@ -206,7 +206,7 @@
   return s.w
 }
 
-// CHECK-LABEL: sil [serialized] [always_inline] @_T017struct_resilience26publicInlineAlwaysFunctionSiAA6MySizeVF : $@convention(thin) (@in MySize) -> Int
+// CHECK-LABEL: sil [serialized] [always_inline] @_T017struct_resilience26publicInlineAlwaysFunctionySiAA6MySizeVF : $@convention(thin) (@in MySize) -> Int
 @inline(__always) public func publicInlineAlwaysFunction(_ s: MySize) -> Int {
 
   // Since the body of a public transparent function might be inlined into
@@ -238,7 +238,7 @@
 
   // Non-inlineable initializer, assigns to self -- treated as a root initializer
 
-  // CHECK-LABEL: sil @_T017struct_resilience24VersionedResilientStructVA2C5other_tcfC : $@convention(method) (@in VersionedResilientStruct, @thin VersionedResilientStruct.Type) -> @out VersionedResilientStruct
+  // CHECK-LABEL: sil @_T017struct_resilience24VersionedResilientStructV5otherA2C_tcfC : $@convention(method) (@in VersionedResilientStruct, @thin VersionedResilientStruct.Type) -> @out VersionedResilientStruct
   // CHECK:      [[SELF_BOX:%.*]] = alloc_box ${ var VersionedResilientStruct }
   // CHECK-NEXT: [[SELF_UNINIT:%.*]] = mark_uninitialized [rootself] [[SELF_BOX]]
   // CHECK:      return
@@ -248,7 +248,7 @@
 
   // Inlineable initializer, assigns to self -- treated as a delegating initializer
 
-  // CHECK-LABEL: sil [serialized] @_T017struct_resilience24VersionedResilientStructVA2C6other2_tcfC : $@convention(method) (@in VersionedResilientStruct, @thin VersionedResilientStruct.Type) -> @out VersionedResilientStruct
+  // CHECK-LABEL: sil [serialized] @_T017struct_resilience24VersionedResilientStructV6other2A2C_tcfC : $@convention(method) (@in VersionedResilientStruct, @thin VersionedResilientStruct.Type) -> @out VersionedResilientStruct
   // CHECK:      [[SELF_BOX:%.*]] = alloc_box ${ var VersionedResilientStruct }
   // CHECK-NEXT: [[SELF_UNINIT:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
   // CHECK:      return
@@ -257,20 +257,20 @@
   }
 }
 
-// CHECK-LABEL: sil [transparent] [serialized] @_T017struct_resilience27useVersionedResilientStructAA0deF0VADF : $@convention(thin) (@in VersionedResilientStruct) -> @out VersionedResilientStruct
+// CHECK-LABEL: sil [transparent] [serialized] @_T017struct_resilience27useVersionedResilientStructyAA0deF0VADF : $@convention(thin) (@in VersionedResilientStruct) -> @out VersionedResilientStruct
 @_versioned
 @_transparent func useVersionedResilientStruct(_ s: VersionedResilientStruct)
     -> VersionedResilientStruct {
   // CHECK:       function_ref @_T017struct_resilience24VersionedResilientStructV1ySivg
   // CHECK:       function_ref @_T017struct_resilience24VersionedResilientStructV1xSivg
-  // CHECK:       function_ref @_T017struct_resilience24VersionedResilientStructVACSi1x_Si1ytcfC
+  // CHECK:       function_ref @_T017struct_resilience24VersionedResilientStructV1x1yACSi_SitcfC
 
   return VersionedResilientStruct(x: s.y, y: s.x)
 
   // CHECK:       return
 }
 
-// CHECK-LABEL: sil [serialized] @_T017struct_resilience19inlineableInoutTestyAA6MySizeVzF : $@convention(thin) (@inout MySize) -> ()
+// CHECK-LABEL: sil [serialized] @_T017struct_resilience19inlineableInoutTestyyAA6MySizeVzF : $@convention(thin) (@inout MySize) -> ()
 @_inlineable public func inlineableInoutTest(_ s: inout MySize) {
   // Inlineable functions can be inlined in other resiliene domains.
   //
@@ -286,7 +286,7 @@
 // Initializers for resilient structs
 extension Size {
 
-  // CHECK-LABEL: sil hidden @_T016resilient_struct4SizeV0B11_resilienceEA2C5other_tcfC : $@convention(method) (@in Size, @thin Size.Type) -> @out Size
+  // CHECK-LABEL: sil hidden @_T016resilient_struct4SizeV0B11_resilienceE5otherA2C_tcfC : $@convention(method) (@in Size, @thin Size.Type) -> @out Size
   // CHECK:      [[SELF_BOX:%.*]] = alloc_box ${ var Size }
   // CHECK-NEXT: [[SELF_UNINIT:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] : ${ var Size }
   // CHECK:      return
diff --git a/test/SILGen/subclass_existentials.swift b/test/SILGen/subclass_existentials.swift
index efab8fd..ad26a8e 100644
--- a/test/SILGen/subclass_existentials.swift
+++ b/test/SILGen/subclass_existentials.swift
@@ -41,7 +41,8 @@
 
 protocol R {}
 
-// CHECK-LABEL: sil hidden @_T021subclass_existentials11conversionsyAA1P_AA4BaseCySiGXc8baseAndP_AA7DerivedC7derivedAA1R_AIXc0hF1RAaC_AFXcXp0eF5PTypeAIm0H4TypeAaK_AIXcXp0hF5RTypetF : $@convention(thin) (@owned Base<Int> & P, @owned Derived, @owned Derived & R, @thick (Base<Int> & P).Type, @thick Derived.Type, @thick (Derived & R).Type) -> () {
+// CHECK-LABEL: sil hidden @_T021subclass_existentials11conversions8baseAndP7derived0fE1R0dE5PType0F4Type0fE5RTypeyAA1P_AA4BaseCySiGXc_AA7DerivedCAA1R_ANXcAaI_ALXcXpANmAaO_ANXcXptF : $@convention(thin) (@owned Base<Int> & P, @owned Derived, @owned Derived & R, @thick (Base<Int> & P).Type, @thick Derived.Type, @thick (Derived & R).Type) -> () {
+
 
 func conversions(
   baseAndP: Base<Int> & P,
@@ -116,7 +117,7 @@
   // CHECK: return
 }
 
-// CHECK-LABEL: sil hidden @_T021subclass_existentials11methodCallsyAA1P_AA4BaseCySiGXc8baseAndP_AaC_AFXcXp0fG5PTypetF : $@convention(thin) (@owned Base<Int> & P, @thick (Base<Int> & P).Type) -> () {
+// CHECK-LABEL: sil hidden @_T021subclass_existentials11methodCalls8baseAndP0eF5PTypeyAA1P_AA4BaseCySiGXc_AaE_AHXcXptF : $@convention(thin) (@owned Base<Int> & P, @thick (Base<Int> & P).Type) -> () {
 
 func methodCalls(
   baseAndP: Base<Int> & P,
@@ -204,7 +205,7 @@
   }
 }
 
-// CHECK-LABEL: sil hidden @_T021subclass_existentials16propertyAccessesyAA9PropertyP_AA0E1CCXcF : $@convention(thin) (@owned PropertyC & PropertyP) -> () {
+// CHECK-LABEL: sil hidden @_T021subclass_existentials16propertyAccessesyyAA9PropertyP_AA0E1CCXcF : $@convention(thin) (@owned PropertyC & PropertyP) -> () {
 func propertyAccesses(_ x: PropertyP & PropertyC) {
   var xx = x
   xx.p.p = x
@@ -222,7 +223,7 @@
   xx[(1, 2)] += 1
 }
 
-// CHECK-LABEL: sil hidden @_T021subclass_existentials19functionConversionsyAA1P_AA4BaseCySiGXcyc07returnsE4AndP_AaC_AFXcXpyc0feG5PTypeAA7DerivedCyc0fI0AJmyc0fI4TypeAA1R_AJXcyc0fiG1RAaM_AJXcXpyc0fiG5RTypetF : $@convention(thin) (@owned @callee_guaranteed () -> @owned Base<Int> & P, @owned @callee_guaranteed () -> @thick (Base<Int> & P).Type, @owned @callee_guaranteed () -> @owned Derived, @owned @callee_guaranteed () -> @thick Derived.Type, @owned @callee_guaranteed () -> @owned Derived & R, @owned @callee_guaranteed () -> @thick (Derived & R).Type) -> () {
+// CHECK-LABEL: sil hidden @_T021subclass_existentials19functionConversions15returnsBaseAndP0efG5PType0E7Derived0eI4Type0eiG1R0eiG5RTypeyAA1P_AA0F0CySiGXcyc_AaI_ALXcXpycAA0I0CycANmycAA1R_ANXcycAaO_ANXcXpyctF : $@convention(thin) (@owned @callee_guaranteed () -> @owned Base<Int> & P, @owned @callee_guaranteed () -> @thick (Base<Int> & P).Type, @owned @callee_guaranteed () -> @owned Derived, @owned @callee_guaranteed () -> @thick Derived.Type, @owned @callee_guaranteed () -> @owned Derived & R, @owned @callee_guaranteed () -> @thick (Derived & R).Type) -> () {
 func functionConversions(
   returnsBaseAndP: @escaping () -> (Base<Int> & P),
   returnsBaseAndPType: @escaping () -> (Base<Int> & P).Type,
@@ -253,7 +254,7 @@
   // CHECK-NEXT: }
 }
 
-// CHECK-LABEL: sil hidden @_T021subclass_existentials9downcastsyAA1P_AA4BaseCySiGXc8baseAndP_AA7DerivedC7derivedAaC_AFXcXp0eF5PTypeAIm0H4TypetF : $@convention(thin) (@owned Base<Int> & P, @owned Derived, @thick (Base<Int> & P).Type, @thick Derived.Type) -> () {
+// CHECK-LABEL: sil hidden @_T021subclass_existentials9downcasts8baseAndP7derived0dE5PType0F4TypeyAA1P_AA4BaseCySiGXc_AA7DerivedCAaG_AJXcXpALmtF : $@convention(thin) (@owned Base<Int> & P, @owned Derived, @thick (Base<Int> & P).Type, @thick Derived.Type) -> () {
 func downcasts(
   baseAndP: Base<Int> & P,
   derived: Derived,
@@ -302,7 +303,7 @@
   // CHECK-NEXT: }
 }
 
-// CHECK-LABEL: sil hidden @_T021subclass_existentials16archetypeUpcastsyq_9baseTAndP_q0_0E7IntAndPq1_7derivedtAA4BaseCyxGRb_AA1PR_AGySiGRb0_AaIR0_AA7DerivedCRb1_r2_lF : $@convention(thin) <T, BaseTAndP, BaseIntAndP, DerivedT where BaseTAndP : Base<T>, BaseTAndP : P, BaseIntAndP : Base<Int>, BaseIntAndP : P, DerivedT : Derived> (@owned BaseTAndP, @owned BaseIntAndP, @owned DerivedT) -> () {
+// CHECK-LABEL: sil hidden @_T021subclass_existentials16archetypeUpcasts9baseTAndP0E7IntAndP7derivedyq__q0_q1_tAA4BaseCyxGRb_AA1PR_AGySiGRb0_AaIR0_AA7DerivedCRb1_r2_lF : $@convention(thin) <T, BaseTAndP, BaseIntAndP, DerivedT where BaseTAndP : Base<T>, BaseTAndP : P, BaseIntAndP : Base<Int>, BaseIntAndP : P, DerivedT : Derived> (@owned BaseTAndP, @owned BaseIntAndP, @owned DerivedT) -> () {
 func archetypeUpcasts<T,
                       BaseTAndP : Base<T> & P,
                       BaseIntAndP : Base<Int> & P,
@@ -330,7 +331,7 @@
   // CHECK-NEXT: }
 }
 
-// CHECK-LABEL: sil hidden @_T021subclass_existentials18archetypeDowncastsyx1s_q_1tq0_2ptq1_5baseTq2_0F3Intq3_0f6TAndP_C0q4_0fg5AndP_C0q5_08derived_C0AA1R_AA7DerivedCXc0ji2R_C0AA1P_AA4BaseCyq_GXc0fH10P_concreteAaO_AQySiGXc0fgi2P_M0tAaOR0_ARRb1_ATRb2_ARRb3_AaOR3_ATRb4_AaOR4_AMRb5_r6_lF : $@convention(thin) <S, T, PT, BaseT, BaseInt, BaseTAndP, BaseIntAndP, DerivedT where PT : P, BaseT : Base<T>, BaseInt : Base<Int>, BaseTAndP : Base<T>, BaseTAndP : P, BaseIntAndP : Base<Int>, BaseIntAndP : P, DerivedT : Derived> (@in S, @in T, @in PT, @owned BaseT, @owned BaseInt, @owned BaseTAndP, @owned BaseIntAndP, @owned DerivedT, @owned Derived & R, @owned Base<T> & P, @owned Base<Int> & P) -> () {
+// CHECK-LABEL: sil hidden @_T021subclass_existentials18archetypeDowncasts1s1t2pt5baseT0F3Int0f6TAndP_C00fg5AndP_C008derived_C00ji2R_C00fH10P_concrete0fgi2P_K0yx_q_q0_q1_q2_q3_q4_q5_AA1R_AA7DerivedCXcAA1P_AA4BaseCyq_GXcAaQ_ASySiGXctAaQR0_ATRb1_AURb2_ATRb3_AaQR3_AURb4_AaQR4_APRb5_r6_lF : $@convention(thin) <S, T, PT, BaseT, BaseInt, BaseTAndP, BaseIntAndP, DerivedT where PT : P, BaseT : Base<T>, BaseInt : Base<Int>, BaseTAndP : Base<T>, BaseTAndP : P, BaseIntAndP : Base<Int>, BaseIntAndP : P, DerivedT : Derived> (@in S, @in T, @in PT, @owned BaseT, @owned BaseInt, @owned BaseTAndP, @owned BaseIntAndP, @owned DerivedT, @owned Derived & R, @owned Base<T> & P, @owned Base<Int> & P) -> () {
 func archetypeDowncasts<S,
                         T,
                         PT : P,
diff --git a/test/SILGen/super-to-nonobjc-extension.swift b/test/SILGen/super-to-nonobjc-extension.swift
index e32919b..30634f8 100644
--- a/test/SILGen/super-to-nonobjc-extension.swift
+++ b/test/SILGen/super-to-nonobjc-extension.swift
@@ -6,7 +6,7 @@
 import Foundation
 
 class MyDictionary: NSDictionary {
-  // CHECK-LABEL: sil hidden @_T04main12MyDictionaryC31callSuperNonObjCExtensionMethodySiF
+  // CHECK-LABEL: sil hidden @_T04main12MyDictionaryC31callSuperNonObjCExtensionMethodyySiF
   func callSuperNonObjCExtensionMethod(_ x: Int) {
     // CHECK-NOT: super_method {{.*}} #NSDictionary.nonObjCExtensionMethod
     super.nonObjCExtensionMethod(x)
diff --git a/test/SILGen/super.swift b/test/SILGen/super.swift
index 4ff084c..f1ce2dd 100644
--- a/test/SILGen/super.swift
+++ b/test/SILGen/super.swift
@@ -189,13 +189,13 @@
     }
     localFunction()
 
-    // CHECK-LABEL: sil private @_T05super14GenericDerivedC6methodyyF15genericFunctionL_yqd__r__lF : $@convention(thin) <T><U> (@in U, @guaranteed GenericDerived<T>) -> ()
+    // CHECK-LABEL: sil private @_T05super14GenericDerivedC6methodyyF15genericFunctionL_yyqd__r__lF : $@convention(thin) <T><U> (@in U, @guaranteed GenericDerived<T>) -> ()
     // CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T>
     // CHECK: return
     func genericFunction<U>(_: U) {
       super.method()
     }
-    // CHECK: } // end sil function '_T05super14GenericDerivedC6methodyyF15genericFunctionL_yqd__r__lF'
+    // CHECK: } // end sil function '_T05super14GenericDerivedC6methodyyF15genericFunctionL_yyqd__r__lF'
     genericFunction(0)
   }
 }
diff --git a/test/SILGen/super_init_refcounting.swift b/test/SILGen/super_init_refcounting.swift
index 2809ebf..099ec3c 100644
--- a/test/SILGen/super_init_refcounting.swift
+++ b/test/SILGen/super_init_refcounting.swift
@@ -90,7 +90,7 @@
   // CHECK:         [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
   // CHECK:         [[X:%.*]] = load [trivial] [[READ]] : $*Int
   // CHECK:         end_borrow [[BORROWED_SUPER]] from [[SUPER_OBJ]]
-  // CHECK:         [[SUPER_INIT:%.*]] = function_ref @_T022super_init_refcounting3FooCACSicfc : $@convention(method) (Int, @owned Foo) -> @owned Foo
+  // CHECK:         [[SUPER_INIT:%.*]] = function_ref @_T022super_init_refcounting3FooCyACSicfc : $@convention(method) (Int, @owned Foo) -> @owned Foo
   // CHECK:         apply [[SUPER_INIT]]([[X]], [[SUPER_OBJ]])
   override init() {
     x = 10
diff --git a/test/SILGen/switch.swift b/test/SILGen/switch.swift
index df15227..ee4809f 100644
--- a/test/SILGen/switch.swift
+++ b/test/SILGen/switch.swift
@@ -313,7 +313,7 @@
 struct Y : P { func p() {} }
 struct Z : P { func p() {} }
 
-// CHECK-LABEL: sil hidden @_T06switch10test_isa_1yAA1P_p1p_tF
+// CHECK-LABEL: sil hidden @_T06switch10test_isa_11pyAA1P_p_tF
 func test_isa_1(p: P) {
   // CHECK: [[PTMPBUF:%[0-9]+]] = alloc_stack $P
   // CHECK-NEXT: copy_addr %0 to [initialization] [[PTMPBUF]] : $*P
@@ -360,7 +360,7 @@
   e()
 }
 
-// CHECK-LABEL: sil hidden @_T06switch10test_isa_2yAA1P_p1p_tF
+// CHECK-LABEL: sil hidden @_T06switch10test_isa_21pyAA1P_p_tF
 func test_isa_2(p: P) {
   switch (p, foo()) {
   // CHECK:   checked_cast_addr_br copy_on_success P in [[P:%.*]] : $*P to X in {{%.*}} : $*X, [[IS_X:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]]
@@ -430,7 +430,7 @@
 class D2 : D1 {}
 class E : C {}
 
-// CHECK-LABEL: sil hidden @_T06switch16test_isa_class_1yAA1BC1x_tF : $@convention(thin) (@owned B) -> () {
+// CHECK-LABEL: sil hidden @_T06switch16test_isa_class_11xyAA1BC_tF : $@convention(thin) (@owned B) -> () {
 func test_isa_class_1(x: B) {
   // CHECK: bb0([[X:%.*]] : $B):
   // CHECK:   [[BORROWED_X:%.*]] = begin_borrow [[X]]
@@ -522,9 +522,9 @@
   // CHECK:   destroy_value [[X]]
   f()
 }
-// CHECK: } // end sil function '_T06switch16test_isa_class_1yAA1BC1x_tF'
+// CHECK: } // end sil function '_T06switch16test_isa_class_11xyAA1BC_tF'
 
-// CHECK-LABEL: sil hidden @_T06switch16test_isa_class_2yXlAA1BC1x_tF : $@convention(thin)
+// CHECK-LABEL: sil hidden @_T06switch16test_isa_class_21xyXlAA1BC_tF : $@convention(thin)
 func test_isa_class_2(x: B) -> AnyObject {
   // CHECK: bb0([[X:%.*]] : $B):
   // CHECK:   [[BORROWED_X:%.*]] = begin_borrow [[X]]
@@ -639,7 +639,7 @@
   // CHECK:   destroy_value [[X]]
   // CHECK:   return [[T0]]
 }
-// CHECK: } // end sil function '_T06switch16test_isa_class_2yXlAA1BC1x_tF'
+// CHECK: } // end sil function '_T06switch16test_isa_class_21xyXlAA1BC_tF'
 
 enum MaybePair {
   case Neither
@@ -648,7 +648,7 @@
   case Both(Int, String)
 }
 
-// CHECK-LABEL: sil hidden @_T06switch12test_union_1yAA9MaybePairO1u_tF
+// CHECK-LABEL: sil hidden @_T06switch12test_union_11uyAA9MaybePairO_tF
 func test_union_1(u: MaybePair) {
   switch u {
   // CHECK: switch_enum [[SUBJECT:%.*]] : $MaybePair,
@@ -694,7 +694,7 @@
   e()
 }
 
-// CHECK-LABEL: sil hidden @_T06switch12test_union_3yAA9MaybePairO1u_tF : $@convention(thin) (@owned MaybePair) -> () {
+// CHECK-LABEL: sil hidden @_T06switch12test_union_31uyAA9MaybePairO_tF : $@convention(thin) (@owned MaybePair) -> () {
 func test_union_3(u: MaybePair) {
   // CHECK: bb0([[ARG:%.*]] : $MaybePair):
   // CHECK:   [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
@@ -741,7 +741,7 @@
   e()
 }
 
-// CHECK-LABEL: sil hidden @_T06switch12test_union_4yAA9MaybePairO1u_tF
+// CHECK-LABEL: sil hidden @_T06switch12test_union_41uyAA9MaybePairO_tF
 func test_union_4(u: MaybePair) {
   switch u {
   // CHECK: switch_enum {{%.*}} : $MaybePair,
@@ -780,7 +780,7 @@
   e()
 }
 
-// CHECK-LABEL: sil hidden @_T06switch12test_union_5yAA9MaybePairO1u_tF
+// CHECK-LABEL: sil hidden @_T06switch12test_union_51uyAA9MaybePairO_tF
 func test_union_5(u: MaybePair) {
   switch u {
   // CHECK: switch_enum {{%.*}} : $MaybePair,
@@ -826,7 +826,7 @@
   case Both(P, String)
 }
 
-// CHECK-LABEL: sil hidden @_T06switch22test_union_addr_only_1yAA20MaybeAddressOnlyPairO1u_tF
+// CHECK-LABEL: sil hidden @_T06switch22test_union_addr_only_11uyAA20MaybeAddressOnlyPairO_tF
 func test_union_addr_only_1(u: MaybeAddressOnlyPair) {
   switch u {
   // CHECK: switch_enum_addr [[ENUM_ADDR:%.*]] : $*MaybeAddressOnlyPair,
@@ -889,7 +889,7 @@
 
 enum Foo { case A, B }
 
-// CHECK-LABEL: sil hidden @_T06switch05test_A11_two_unionsyAA3FooO1x_AD1ytF
+// CHECK-LABEL: sil hidden @_T06switch05test_A11_two_unions1x1yyAA3FooO_AFtF
 func test_switch_two_unions(x: Foo, y: Foo) {
   // CHECK:   [[T0:%.*]] = tuple (%0 : $Foo, %1 : $Foo)
   // CHECK:   [[X:%.*]] = tuple_extract [[T0]] : $(Foo, Foo), 0
@@ -956,7 +956,7 @@
 // <rdar://problem/17272985>
 enum ABC { case A, B, C }
 
-// CHECK-LABEL: sil hidden @_T06switch18testTupleWildcardsyAA3ABCO_ADtF 
+// CHECK-LABEL: sil hidden @_T06switch18testTupleWildcardsyyAA3ABCO_ADtF
 // CHECK:         [[X:%.*]] = tuple_extract {{%.*}} : $(ABC, ABC), 0
 // CHECK:         [[Y:%.*]] = tuple_extract {{%.*}} : $(ABC, ABC), 1
 // CHECK:         switch_enum [[X]] : $ABC, case #ABC.A!enumelt: [[X_A:bb[0-9]+]], default [[X_NOT_A:bb[0-9]+]]
@@ -994,7 +994,7 @@
   case Payload(name: Int)
 }
 
-// CHECK-LABEL: sil hidden @_T06switch24testLabeledScalarPayloadypAA0cdE0OF
+// CHECK-LABEL: sil hidden @_T06switch24testLabeledScalarPayloadyypAA0cdE0OF
 func testLabeledScalarPayload(_ lsp: LabeledScalarPayload) -> Any {
   // CHECK: switch_enum {{%.*}}, case #LabeledScalarPayload.Payload!enumelt.1: bb1
   switch lsp {
@@ -1008,7 +1008,7 @@
 }
 
 // There should be no unreachable generated.
-// CHECK-LABEL: sil hidden @_T06switch19testOptionalPatternySiSgF
+// CHECK-LABEL: sil hidden @_T06switch19testOptionalPatternyySiSgF
 func testOptionalPattern(_ value : Int?) {
   // CHECK: switch_enum %0 : $Optional<Int>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: [[NILBB:bb[0-9]+]]
   switch value {
@@ -1022,7 +1022,7 @@
 
 // x? and .none should both be considered "similar" and thus handled in the same
 // switch on the enum kind.  There should be no unreachable generated.
-// CHECK-LABEL: sil hidden @_T06switch19testOptionalEnumMixS2iSgF
+// CHECK-LABEL: sil hidden @_T06switch19testOptionalEnumMixyS2iSgF
 func testOptionalEnumMix(_ a : Int?) -> Int {
   // CHECK: debug_value %0 : $Optional<Int>, let, name "a"
   // CHECK-NEXT: switch_enum %0 : $Optional<Int>, case #Optional.some!enumelt.1: [[SOMEBB:bb[0-9]+]], case #Optional.none!enumelt: [[NILBB:bb[0-9]+]]
@@ -1044,7 +1044,7 @@
 
 // x? and nil should both be considered "similar" and thus handled in the same
 // switch on the enum kind.  There should be no unreachable generated.
-// CHECK-LABEL: sil hidden @_T06switch26testOptionalEnumMixWithNilS2iSgF
+// CHECK-LABEL: sil hidden @_T06switch26testOptionalEnumMixWithNilyS2iSgF
 func testOptionalEnumMixWithNil(_ a : Int?) -> Int {
   // CHECK: debug_value %0 : $Optional<Int>, let, name "a"
   // CHECK-NEXT: switch_enum %0 : $Optional<Int>, case #Optional.some!enumelt.1: [[SOMEBB:bb[0-9]+]], case #Optional.none!enumelt: [[NILBB:bb[0-9]+]]
@@ -1065,7 +1065,7 @@
 }
 
 // SR-3518
-// CHECK-LABEL: sil hidden @_T06switch43testMultiPatternsWithOuterScopeSameNamedVarySiSg4base_AC6filtertF
+// CHECK-LABEL: sil hidden @_T06switch43testMultiPatternsWithOuterScopeSameNamedVar4base6filterySiSg_AEtF
 func testMultiPatternsWithOuterScopeSameNamedVar(base: Int?, filter: Int?) {
   switch(base, filter) {
     
@@ -1115,12 +1115,12 @@
   }
   func test3(x : Never) {
     // CHECK: unreachable
-    // CHECK-NEXT: } // end sil function '_T06switch30testUninhabitedSwitchScrutineeyyF5test3L_ys5NeverO1x_tF'
+    // CHECK-NEXT: } // end sil function '_T06switch30testUninhabitedSwitchScrutineeyyF5test3L_1xys5NeverO_tF'
     switch (x, 5, x) {}
   }
   func test4(x : Never) {
     // CHECK: unreachable
-    // CHECK-NEXT: } // end sil function '_T06switch30testUninhabitedSwitchScrutineeyyF5test4L_ys5NeverO1x_tF'
+    // CHECK-NEXT: } // end sil function '_T06switch30testUninhabitedSwitchScrutineeyyF5test4L_1xys5NeverO_tF'
     switch ((8, 6, 7), (5, 3, (0, x))) {}
   }
   func test5() {
diff --git a/test/SILGen/switch_abstraction.swift b/test/SILGen/switch_abstraction.swift
index 392cfc0..25d2afa 100644
--- a/test/SILGen/switch_abstraction.swift
+++ b/test/SILGen/switch_abstraction.swift
@@ -7,7 +7,7 @@
   case Nuttn
 }
 
-// CHECK-LABEL: sil hidden @_T018switch_abstraction18enum_reabstractionyAA10OptionableOyAA1AVAFcG1x_AF1atF : $@convention(thin) (@owned Optionable<(A) -> A>, A) -> ()
+// CHECK-LABEL: sil hidden @_T018switch_abstraction18enum_reabstraction1x1ayAA10OptionableOyAA1AVAHcG_AHtF : $@convention(thin) (@owned Optionable<(A) -> A>, A) -> ()
 // CHECK: switch_enum {{%.*}} : $Optionable<(A) -> A>, case #Optionable.Summn!enumelt.1: [[DEST:bb[0-9]+]]
 // CHECK: [[DEST]]([[ORIG:%.*]] : @owned $@callee_guaranteed (@in A) -> @out A):
 // CHECK:   [[REABSTRACT:%.*]] = function_ref @_T0{{.*}}TR :
diff --git a/test/SILGen/switch_isa.swift b/test/SILGen/switch_isa.swift
index f700db2..92e08e3 100644
--- a/test/SILGen/switch_isa.swift
+++ b/test/SILGen/switch_isa.swift
@@ -11,7 +11,7 @@
   }
 }
 
-// CHECK-LABEL: sil hidden @_T010switch_isa23testSwitchOnExistentialyypF :
+// CHECK-LABEL: sil hidden @_T010switch_isa23testSwitchOnExistentialyyypF :
 // CHECK:   [[ANY:%.*]] = alloc_stack $Any
 // CHECK:   copy_addr %0 to [initialization] [[ANY]]
 // CHECK:   [[BOOL:%.*]] = alloc_stack $Bool
@@ -38,7 +38,7 @@
   }
 }
 
-// CHECK-LABEL: sil hidden @_T010switch_isa27testSwitchEnumOnExistentialyypF : $@convention(thin) (@in Any) -> ()
+// CHECK-LABEL: sil hidden @_T010switch_isa27testSwitchEnumOnExistentialyyypF : $@convention(thin) (@in Any) -> ()
 // CHECK:   checked_cast_addr_br copy_on_success Any in {{%.*}} : $*Any to Foo
 // CHECK:   checked_cast_addr_br copy_on_success Any in {{%.*}} : $*Any to Bar<Int>
 // CHECK:   checked_cast_addr_br copy_on_success Any in {{%.*}} : $*Any to Bar<Foo>
@@ -49,12 +49,12 @@
 func guardFn(_ l: D, _ r: D) -> Bool { return true }
 
 // rdar://problem/21087371
-// CHECK-LABEL: sil hidden @_T010switch_isa32testSwitchTwoIsPatternsWithGuardyAA1BC_AD1rtF
+// CHECK-LABEL: sil hidden @_T010switch_isa32testSwitchTwoIsPatternsWithGuard_1ryAA1BC_AEtF
 // CHECK:         checked_cast_br {{%.*}} : $B to $D, [[R_CAST_YES:bb[0-9]+]], [[R_CAST_NO:bb[0-9]+]]
 // CHECK:       [[R_CAST_YES]]({{.*}}):
 // CHECK:         checked_cast_br {{%.*}} : $B to $D, [[L_CAST_YES:bb[0-9]+]], [[L_CAST_NO:bb[0-9]+]]
 // CHECK:       [[L_CAST_YES]]({{.*}}):
-// CHECK:         function_ref @_T010switch_isa7guardFnSbAA1DC_ADtF
+// CHECK:         function_ref @_T010switch_isa7guardFnySbAA1DC_ADtF
 // CHECK:         cond_br {{%.*}}, [[GUARD_YES:bb[0-9]+]], [[GUARD_NO:bb[0-9]+]]
 // CHECK:       [[GUARD_NO]]:
 // CHECK-NEXT:    destroy_value [[R2:%.*]] : $D
diff --git a/test/SILGen/switch_objc.swift b/test/SILGen/switch_objc.swift
index 8463ea6..5dbe1f2 100644
--- a/test/SILGen/switch_objc.swift
+++ b/test/SILGen/switch_objc.swift
@@ -4,26 +4,26 @@
 
 import Foundation
 
-// CHECK-LABEL: sil hidden @_T011switch_objc13matchesEitherSbSo4HiveC5input_AD1aAD1btF :
+// CHECK-LABEL: sil hidden @_T011switch_objc13matchesEither5input1a1bSbSo4HiveC_A2GtF :
 func matchesEither(input: Hive, a: Hive, b: Hive) -> Bool {
   switch input {
-  // CHECK:   function_ref @_T010ObjectiveC2teoiSbSo8NSObjectC_ADtF
+  // CHECK:   function_ref @_T010ObjectiveC2teoiySbSo8NSObjectC_ADtF
   // CHECK:   cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]]
   // CHECK: [[YES_CASE1]]:
   // CHECK:   br [[RET_TRUE:bb[0-9]+]]
   // CHECK: [[NOT_CASE1]]:
-  // CHECK:   function_ref @_T010ObjectiveC2teoiSbSo8NSObjectC_ADtF
+  // CHECK:   function_ref @_T010ObjectiveC2teoiySbSo8NSObjectC_ADtF
   // CHECK:   cond_br {{%.*}}, [[YES_CASE2:bb[0-9]+]], [[NOT_CASE2:bb[0-9]+]]
   // CHECK: [[YES_CASE2]]:
   case a, b:
-  // CHECK:   function_ref @_T0S2b{{[_0-9a-zA-Z]*}}fC
+  // CHECK:   function_ref @_T0Sb2{{[_0-9a-zA-Z]*}}fC
     return true
 
   // CHECK: [[NOT_CASE2]]:
   // CHECK:   br [[RET_FALSE:bb[0-9]+]]
   default:
   // CHECK: [[RET_FALSE]]:
-  // CHECK:   function_ref @_T0S2b{{[_0-9a-zA-Z]*}}fC
+  // CHECK:   function_ref @_T0Sb2{{[_0-9a-zA-Z]*}}fC
     return false
   }
 }
diff --git a/test/SILGen/switch_var.swift b/test/SILGen/switch_var.swift
index cff6657..bd7675a 100644
--- a/test/SILGen/switch_var.swift
+++ b/test/SILGen/switch_var.swift
@@ -52,7 +52,7 @@
   case var x:
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[X]]
   // CHECK:   load [trivial] [[READ]]
-  // CHECK:   function_ref @_T010switch_var1aySi1x_tF
+  // CHECK:   function_ref @_T010switch_var1a1xySi_tF
   // CHECK:   destroy_value [[XADDR]]
   // CHECK:   br [[CONT:bb[0-9]+]]
     a(x: x)
@@ -70,14 +70,14 @@
   // CHECK:   [[X:%.*]] = project_box [[XADDR]]
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[X]]
   // CHECK:   load [trivial] [[READ]]
-  // CHECK:   function_ref @_T010switch_var6runcedSbSi1x_tF
+  // CHECK:   function_ref @_T010switch_var6runced1xSbSi_tF
   // CHECK:   cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
   // -- TODO: Clean up these empty waypoint bbs.
   case var x where runced(x: x):
   // CHECK: [[CASE1]]:
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[X]]
   // CHECK:   load [trivial] [[READ]]
-  // CHECK:   function_ref @_T010switch_var1aySi1x_tF
+  // CHECK:   function_ref @_T010switch_var1a1xySi_tF
   // CHECK:   destroy_value [[XADDR]]
   // CHECK:   br [[CONT:bb[0-9]+]]
     a(x: x)
@@ -86,13 +86,13 @@
   // CHECK:   [[Y:%.*]] = project_box [[YADDR]]
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
   // CHECK:   load [trivial] [[READ]]
-  // CHECK:   function_ref @_T010switch_var6fungedSbSi1x_tF
+  // CHECK:   function_ref @_T010switch_var6funged1xSbSi_tF
   // CHECK:   cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
   case var y where funged(x: y):
   // CHECK: [[CASE2]]:
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
   // CHECK:   load [trivial] [[READ]]
-  // CHECK:   function_ref @_T010switch_var1bySi1x_tF
+  // CHECK:   function_ref @_T010switch_var1b1xySi_tF
   // CHECK:   destroy_value [[YADDR]]
   // CHECK:   br [[CONT]]
     b(x: y)
@@ -104,7 +104,7 @@
   // CHECK:   [[Z:%.*]] = project_box [[ZADDR]]
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
   // CHECK:   load [trivial] [[READ]]
-  // CHECK:   function_ref @_T010switch_var1cySi1x_tF
+  // CHECK:   function_ref @_T010switch_var1c1xySi_tF
   // CHECK:   destroy_value [[ZADDR]]
   // CHECK:   br [[CONT]]
     c(x: z)
@@ -123,13 +123,13 @@
   // CHECK:   [[X:%.*]] = project_box [[XADDR]]
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[X]]
   // CHECK:   tuple_element_addr [[READ]] : {{.*}}, 0
-  // CHECK:   function_ref @_T010switch_var6runcedSbSi1x_tF
+  // CHECK:   function_ref @_T010switch_var6runced1xSbSi_tF
   // CHECK:   cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
   case var x where runced(x: x.0):
   // CHECK: [[CASE1]]:
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[X]]
   // CHECK:   load [trivial] [[READ]]
-  // CHECK:   function_ref @_T010switch_var2aaySi_Sit1x_tF
+  // CHECK:   function_ref @_T010switch_var2aa1xySi_Sit_tF
   // CHECK:   destroy_value [[XADDR]]
   // CHECK:   br [[CONT:bb[0-9]+]]
     aa(x: x)
@@ -143,16 +143,16 @@
   // CHECK:   [[Z:%.*]] = project_box [[ZADDR]]
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
   // CHECK:   load [trivial] [[READ]]
-  // CHECK:   function_ref @_T010switch_var6fungedSbSi1x_tF
+  // CHECK:   function_ref @_T010switch_var6funged1xSbSi_tF
   // CHECK:   cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
   case (var y, var z) where funged(x: y):
   // CHECK: [[CASE2]]:
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
   // CHECK:   load [trivial] [[READ]]
-  // CHECK:   function_ref @_T010switch_var1aySi1x_tF
+  // CHECK:   function_ref @_T010switch_var1a1xySi_tF
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
   // CHECK:   load [trivial] [[READ]]
-  // CHECK:   function_ref @_T010switch_var1bySi1x_tF
+  // CHECK:   function_ref @_T010switch_var1b1xySi_tF
   // CHECK:   destroy_value [[ZADDR]]
   // CHECK:   destroy_value [[YADDR]]
   // CHECK:   br [[CONT]]
@@ -163,13 +163,13 @@
   // CHECK:   [[W:%.*]] = project_box [[WADDR]]
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[W]]
   // CHECK:   tuple_element_addr [[READ]] : {{.*}}, 0
-  // CHECK:   function_ref @_T010switch_var5ansedSbSi1x_tF
+  // CHECK:   function_ref @_T010switch_var5ansed1xSbSi_tF
   // CHECK:   cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
   case var w where ansed(x: w.0):
   // CHECK: [[CASE3]]:
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[W]]
   // CHECK:   load [trivial] [[READ]]
-  // CHECK:   function_ref @_T010switch_var2bbySi_Sit1x_tF
+  // CHECK:   function_ref @_T010switch_var2bb1xySi_Sit_tF
   // CHECK:   br [[CONT]]
     bb(x: w)
   // CHECK: [[NO_CASE3]]:
@@ -181,7 +181,7 @@
   // CHECK:   [[V:%.*]] = project_box [[VADDR]]
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[V]]
   // CHECK:   load [trivial] [[READ]]
-  // CHECK:   function_ref @_T010switch_var2ccySi_Sit1x_tF
+  // CHECK:   function_ref @_T010switch_var2cc1xySi_Sit_tF
   // CHECK:   destroy_value [[VADDR]]
   // CHECK:   br [[CONT]]
     cc(x: v)
@@ -197,7 +197,7 @@
 struct Y : P { func p() {} }
 struct Z : P { func p() {} }
 
-// CHECK-LABEL: sil hidden @_T010switch_var05test_B2_4yAA1P_p1p_tF
+// CHECK-LABEL: sil hidden @_T010switch_var05test_B2_41pyAA1P_p_tF
 func test_var_4(p p: P) {
   // CHECK:   function_ref @_T010switch_var3fooSiyF
   switch (p, foo()) {
@@ -216,11 +216,11 @@
   // CHECK:   store [[PAIR_1]] to [trivial] [[X]]
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[X]]
   // CHECK:   load [trivial] [[READ]]
-  // CHECK:   function_ref @_T010switch_var6runcedSbSi1x_tF
+  // CHECK:   function_ref @_T010switch_var6runced1xSbSi_tF
   // CHECK:   cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
   case (is X, var x) where runced(x: x):
   // CHECK: [[CASE1]]:
-  // CHECK:   function_ref @_T010switch_var1aySi1x_tF
+  // CHECK:   function_ref @_T010switch_var1a1xySi_tF
   // CHECK:   destroy_value [[XADDR]]
   // CHECK:   dealloc_stack [[TMP]]
   // CHECK:   destroy_addr [[PAIR_0]] : $*P
@@ -247,14 +247,14 @@
   // CHECK:   store [[PAIR_1]] to [trivial] [[Y]]
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
   // CHECK:   load [trivial] [[READ]]
-  // CHECK:   function_ref @_T010switch_var6fungedSbSi1x_tF
+  // CHECK:   function_ref @_T010switch_var6funged1xSbSi_tF
   // CHECK:   cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
 
   case (is Y, var y) where funged(x: y):
   // CHECK: [[CASE2]]:
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
   // CHECK:   load [trivial] [[READ]]
-  // CHECK:   function_ref @_T010switch_var1bySi1x_tF
+  // CHECK:   function_ref @_T010switch_var1b1xySi_tF
   // CHECK:   destroy_value [[YADDR]]
   // CHECK:   dealloc_stack [[TMP]]
   // CHECK:   destroy_addr [[PAIR_0]] : $*P
@@ -275,13 +275,13 @@
   // CHECK:   [[Z:%.*]] = project_box [[ZADDR]]
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
   // CHECK:   tuple_element_addr [[READ]] : {{.*}}, 1
-  // CHECK:   function_ref @_T010switch_var5ansedSbSi1x_tF
+  // CHECK:   function_ref @_T010switch_var5ansed1xSbSi_tF
   // CHECK:   cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[DFLT_NO_CASE3:bb[0-9]+]]
   case var z where ansed(x: z.1):
   // CHECK: [[CASE3]]:
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
   // CHECK:   tuple_element_addr [[READ]] : {{.*}}, 1
-  // CHECK:   function_ref @_T010switch_var1cySi1x_tF
+  // CHECK:   function_ref @_T010switch_var1c1xySi_tF
   // CHECK:   destroy_value [[ZADDR]]
   // CHECK-NEXT: dealloc_stack [[PAIR]]
   // CHECK:   br [[CONT]]
@@ -297,7 +297,7 @@
   // CHECK:   [[W:%.*]] = project_box [[WADDR]]
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[W]]
   // CHECK:   load [trivial] [[READ]]
-  // CHECK:   function_ref @_T010switch_var1dySi1x_tF
+  // CHECK:   function_ref @_T010switch_var1d1xySi_tF
   // CHECK:   destroy_value [[WADDR]]
   // CHECK:   destroy_addr [[PAIR_0]] : $*P
   // CHECK:   dealloc_stack [[PAIR]]
@@ -409,7 +409,7 @@
   // CHECK: [[CASE1]]:
   // CHECK:   [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
   // CHECK:   [[VAL_COPY_COPY:%.*]] = copy_value [[BORROWED_VAL_COPY]]
-  // CHECK:   [[A:%.*]] = function_ref @_T010switch_var1aySS1x_tF
+  // CHECK:   [[A:%.*]] = function_ref @_T010switch_var1a1xySS_tF
   // CHECK:   apply [[A]]([[VAL_COPY_COPY]])
   // CHECK:   end_borrow [[BORROWED_VAL_COPY]] from [[VAL_COPY]]
   // CHECK:   destroy_value [[VAL_COPY]]
@@ -427,7 +427,7 @@
   // CHECK: [[CASE2]]:
   // CHECK:   [[BORROWED_VAL_COPY_2:%.*]] = begin_borrow [[VAL_COPY_2]]
   // CHECK:   [[VAL_COPY_2_COPY:%.*]] = copy_value [[BORROWED_VAL_COPY_2]]
-  // CHECK:   [[B:%.*]] = function_ref @_T010switch_var1bySS1x_tF
+  // CHECK:   [[B:%.*]] = function_ref @_T010switch_var1b1xySS_tF
   // CHECK:   apply [[B]]([[VAL_COPY_2_COPY]])
   // CHECK:   end_borrow [[BORROWED_VAL_COPY_2]] from [[VAL_COPY_2]]
   // CHECK:   destroy_value [[VAL_COPY_2]]
@@ -488,7 +488,7 @@
   // CHECK: [[CASE1]]:
   // CHECK:   [[READ:%.*]] = begin_access [read] [unknown] [[PBOX]]
   // CHECK:   [[X:%.*]] = load [copy] [[READ]]
-  // CHECK:   [[A:%.*]] = function_ref @_T010switch_var1aySS1x_tF
+  // CHECK:   [[A:%.*]] = function_ref @_T010switch_var1a1xySS_tF
   // CHECK:   apply [[A]]([[X]])
   // CHECK:   destroy_value [[BOX]]
   // CHECK:   br [[CONT:bb[0-9]+]]
@@ -506,7 +506,7 @@
   // CHECK: [[CASE2]]:
   // CHECK:   [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
   // CHECK:   [[VAL_COPY_COPY:%.*]] = copy_value [[BORROWED_VAL_COPY]]
-  // CHECK:   [[B:%.*]] = function_ref @_T010switch_var1bySS1x_tF
+  // CHECK:   [[B:%.*]] = function_ref @_T010switch_var1b1xySS_tF
   // CHECK:   apply [[B]]([[VAL_COPY_COPY]])
   // CHECK:   end_borrow [[BORROWED_VAL_COPY]] from [[VAL_COPY]]
   // CHECK:   destroy_value [[VAL_COPY]]
@@ -568,7 +568,7 @@
     // CHECK:     debug_value [[SECOND_X:%.*]] :
     // CHECK:     br [[CASE_BODY]]([[SECOND_X]] : $Int)
     // CHECK:   [[CASE_BODY]]([[BODY_VAR:%.*]] : $Int):
-    // CHECK:     [[A:%.*]] = function_ref @_T010switch_var1aySi1x_tF
+    // CHECK:     [[A:%.*]] = function_ref @_T010switch_var1a1xySi_tF
     // CHECK:     apply [[A]]([[BODY_VAR]])
     a(x: x)
   default:
@@ -641,7 +641,7 @@
     // CHECK:     br [[CASE_BODY]]([[C_X]] : $Int, [[C_N]] : $Double)
 
     // CHECK:   [[CASE_BODY]]([[BODY_X:%.*]] : $Int, [[BODY_N:%.*]] : $Double):
-    // CHECK:     [[FUNC_A:%.*]] = function_ref @_T010switch_var1aySi1x_tF
+    // CHECK:     [[FUNC_A:%.*]] = function_ref @_T010switch_var1a1xySi_tF
     // CHECK:     apply [[FUNC_A]]([[BODY_X]])
     a(x: x)
   }
@@ -682,7 +682,7 @@
     // CHECK:     br [[CASE_BODY]]([[Z_X]] : $Int)
 
     // CHECK:   [[CASE_BODY]]([[BODY_X:%.*]] : $Int):
-    // CHECK:     [[FUNC_A:%.*]] = function_ref @_T010switch_var1aySi1x_tF
+    // CHECK:     [[FUNC_A:%.*]] = function_ref @_T010switch_var1a1xySi_tF
     // CHECK:     apply [[FUNC_A]]([[BODY_X]])
     a(x: x)
   }
@@ -722,7 +722,7 @@
     // CHECK:   [[CASE_BODY]]([[BODY_X:%.*]] : $Int):
     // CHECK:     store [[BODY_X]] to [trivial] [[BOX_X:%.*]] : $*Int
     // CHECK:     [[WRITE:%.*]] = begin_access [modify] [unknown] [[BOX_X]]
-    // CHECK:     [[FUNC_AAA:%.*]] = function_ref @_T010switch_var3aaaySiz1x_tF
+    // CHECK:     [[FUNC_AAA:%.*]] = function_ref @_T010switch_var3aaa1xySiz_tF
     // CHECK:     apply [[FUNC_AAA]]([[WRITE]])
     aaa(x: &x)
   }
diff --git a/test/SILGen/testable-multifile-other.swift b/test/SILGen/testable-multifile-other.swift
index 0ad365f..dd3b6fe 100644
--- a/test/SILGen/testable-multifile-other.swift
+++ b/test/SILGen/testable-multifile-other.swift
@@ -20,27 +20,27 @@
   publicFoo.foo()
 }
 
-// CHECK-LABEL: sil hidden @_T04main4testyAA7FooImplV08internalC0_AA06PubliccD0V06publicC0tF
-// CHECK: [[USE_1:%.+]] = function_ref @_T04main3useyxAA7FooableRzlF
+// CHECK-LABEL: sil hidden @_T04main4test11internalFoo06publicD0yAA0D4ImplV_AA06PublicdF0VtF
+// CHECK: [[USE_1:%.+]] = function_ref @_T04main3useyyxAA7FooableRzlF
 // CHECK: = apply [[USE_1]]<FooImpl>({{%.+}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Fooable> (@in τ_0_0) -> ()
-// CHECK: [[USE_2:%.+]] = function_ref @_T04main3useyxAA7FooableRzlF
+// CHECK: [[USE_2:%.+]] = function_ref @_T04main3useyyxAA7FooableRzlF
 // CHECK: = apply [[USE_2]]<PublicFooImpl>({{%.+}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Fooable> (@in τ_0_0) -> ()
 // CHECK: [[IMPL_1:%.+]] = function_ref @_T023TestableMultifileHelper13HasDefaultFooPAAE3fooyyF
 // CHECK: = apply [[IMPL_1]]<FooImpl>({{%.+}}) : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaultFoo> (@in_guaranteed τ_0_0) -> ()
 // CHECK: [[IMPL_2:%.+]] = function_ref @_T023TestableMultifileHelper13HasDefaultFooPAAE3fooyyF
 // CHECK: = apply [[IMPL_2]]<PublicFooImpl>({{%.+}}) : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaultFoo> (@in_guaranteed τ_0_0) -> ()
-// CHECK: } // end sil function '_T04main4testyAA7FooImplV08internalC0_AA06PubliccD0V06publicC0tF'
+// CHECK: } // end sil function '_T04main4test11internalFoo06publicD0yAA0D4ImplV_AA06PublicdF0VtF'
 
 func test(internalSub: Sub, publicSub: PublicSub) {
   internalSub.foo()
   publicSub.foo()
 }
 
-// CHECK-LABEL: sil hidden @_T04main4testyAA3SubC08internalC0_AA06PublicC0C06publicC0tF
+// CHECK-LABEL: sil hidden @_T04main4test11internalSub06publicD0yAA0D0C_AA06PublicD0CtF
 // CHECK: bb0([[ARG0:%.*]] : @owned $Sub, [[ARG1:%.*]] : @owned $PublicSub):
 // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]]
 // CHECK: = class_method [[BORROWED_ARG0]] : $Sub, #Sub.foo!1
 // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
 // CHECK: = class_method [[BORROWED_ARG1]] : $PublicSub, #PublicSub.foo!1
-// CHECK: } // end sil function '_T04main4testyAA3SubC08internalC0_AA06PublicC0C06publicC0tF'
+// CHECK: } // end sil function '_T04main4test11internalSub06publicD0yAA0D0C_AA06PublicD0CtF'
 
diff --git a/test/SILGen/toplevel.swift b/test/SILGen/toplevel.swift
index 3b021b0..673be55 100644
--- a/test/SILGen/toplevel.swift
+++ b/test/SILGen/toplevel.swift
@@ -78,7 +78,7 @@
 // CHECK: [[SOME_CASE]]([[VALUE:%.+]] : @owned $A):
 // CHECK: store [[VALUE]] to [init] [[BOX:%.+]] : $*A
 // CHECK-NOT: destroy_value
-// CHECK: [[SINK:%.+]] = function_ref @_T08toplevel8markUsedyxlF
+// CHECK: [[SINK:%.+]] = function_ref @_T08toplevel8markUsedyyxlF
 // CHECK-NOT: destroy_value
 // CHECK: apply [[SINK]]<A>({{%.+}})
 class A {}
diff --git a/test/SILGen/transparent_attribute.swift b/test/SILGen/transparent_attribute.swift
index f0a72fd..6228570 100644
--- a/test/SILGen/transparent_attribute.swift
+++ b/test/SILGen/transparent_attribute.swift
@@ -2,9 +2,9 @@
 
 // Test that the attribute gets set on default argument generators.
 
-// CHECK-LABEL: sil hidden [transparent] @_T021transparent_attribute0A23FuncWithDefaultArgumentS2i1x_tFfA_ : $@convention(thin) () -> Int {
+// CHECK-LABEL: sil hidden [transparent] @_T021transparent_attribute0A23FuncWithDefaultArgument1xS2i_tFfA_ : $@convention(thin) () -> Int {
 
-// CHECK-LABEL: sil hidden [transparent] @_T021transparent_attribute0A23FuncWithDefaultArgumentS2i1x_tF : $@convention(thin) (Int) -> Int {
+// CHECK-LABEL: sil hidden [transparent] @_T021transparent_attribute0A23FuncWithDefaultArgument1xS2i_tF : $@convention(thin) (Int) -> Int {
 
 @_transparent func transparentFuncWithDefaultArgument (x: Int = 1) -> Int {
   return x
diff --git a/test/SILGen/tsan_instrumentation.swift b/test/SILGen/tsan_instrumentation.swift
index 070cc9d..a4ca381 100644
--- a/test/SILGen/tsan_instrumentation.swift
+++ b/test/SILGen/tsan_instrumentation.swift
@@ -20,7 +20,7 @@
 // CHECK:  [[GLOBAL_ADDR:%.*]] = global_addr @_T020tsan_instrumentation7gStructAA02MyC0Vvp : $*MyStruct
 // CHECK:  [[WRITE:%.*]] = begin_access [modify] [dynamic] [[GLOBAL_ADDR]] : $*MyStruct
 // CHECK:  {{%.*}} = builtin "tsanInoutAccess"([[WRITE]] : $*MyStruct) : $()
-// CHECK:  [[TAKES_INOUT_FUNC:%.*]] = function_ref @_T020tsan_instrumentation10takesInoutyAA8MyStructVzF : $@convention(thin) (@inout MyStruct) -> ()
+// CHECK:  [[TAKES_INOUT_FUNC:%.*]] = function_ref @_T020tsan_instrumentation10takesInoutyyAA8MyStructVzF : $@convention(thin) (@inout MyStruct) -> ()
 // CHECK:  {{%.*}} = apply [[TAKES_INOUT_FUNC]]([[WRITE]]) : $@convention(thin) (@inout MyStruct) -> ()
 func inoutGlobalStruct() {
   takesInout(&gStruct)
@@ -33,7 +33,7 @@
 // CHECK:  {{%.*}} = builtin "tsanInoutAccess"([[WRITE]] : $*MyStruct) : $()
 // CHECK:  [[ELEMENT_ADDR:%.*]] = struct_element_addr [[WRITE]] : $*MyStruct, #MyStruct.storedProperty
 // CHECK:  {{%.*}} = builtin "tsanInoutAccess"([[ELEMENT_ADDR]] : $*Int) : $()
-// CHECK:  [[TAKES_INOUT_FUNC:%.*]] = function_ref @_T020tsan_instrumentation10takesInoutySizF : $@convention(thin) (@inout Int) -> ()
+// CHECK:  [[TAKES_INOUT_FUNC:%.*]] = function_ref @_T020tsan_instrumentation10takesInoutyySizF : $@convention(thin) (@inout Int) -> ()
 // CHECK:  {{%.*}} = apply [[TAKES_INOUT_FUNC]]([[ELEMENT_ADDR]]) : $@convention(thin) (@inout Int) -> ()
 func inoutGlobalStructStoredProperty() {
   // This should generate two TSan inout instrumentations; one for the address
@@ -58,7 +58,7 @@
 // CHECK:  [[BUFFER_ADDRESS_DEPENDENCE:%.*]] = mark_dependence [[BUFFER_ADDRESS]] : $*Int on [[LOADED_CLASS]] : $MyClass
 // CHECK:  end_borrow [[BORROWED_CLASS]] from [[LOADED_CLASS]] : $MyClass, $MyClass
 // CHECK:  {{%.*}} builtin "tsanInoutAccess"([[BUFFER_ADDRESS_DEPENDENCE]] : $*Int) : $()
-// CHECK:  [[TAKES_INOUT_FUNC:%.*]] = function_ref @_T020tsan_instrumentation10takesInoutySizF : $@convention(thin) (@inout Int) -> ()
+// CHECK:  [[TAKES_INOUT_FUNC:%.*]] = function_ref @_T020tsan_instrumentation10takesInoutyySizF : $@convention(thin) (@inout Int) -> ()
 // CHECK:  {{%.*}} apply [[TAKES_INOUT_FUNC]]([[BUFFER_ADDRESS_DEPENDENCE]]) : $@convention(thin) (@inout Int) -> ()
 func inoutGlobalClassStoredProperty() {
   // This generates two TSan inout instrumentations. One for the value
diff --git a/test/SILGen/tuples.swift b/test/SILGen/tuples.swift
index 8b87fa6..4db3d2d 100644
--- a/test/SILGen/tuples.swift
+++ b/test/SILGen/tuples.swift
@@ -6,7 +6,7 @@
 }
 
 // <rdar://problem/16020428>
-// CHECK-LABEL: sil hidden @_T06tuples8matchFooyAA0C0O1x_tF
+// CHECK-LABEL: sil hidden @_T06tuples8matchFoo1xyAA0C0O_tF
 func matchFoo(x x: Foo) {
   switch x {
   case .X(let x):
@@ -138,7 +138,7 @@
 // Make sure that we use a load_borrow instead of a load [take] when RValues are
 // formed with isGuaranteed set.
 extension P {
-  // CHECK-LABEL: sil hidden @_T06tuples1PPAAE12immutableUseyAA1CC5index_x5valuet5tuple_tFZ
+  // CHECK-LABEL: sil hidden @_T06tuples1PPAAE12immutableUse5tupleyAA1CC5index_x5valuet_tFZ
   // CHECK: bb0([[TUP0:%.*]] : @owned $C, [[TUP1:%.*]] : @trivial $*Self
   // Allocate space for the RValue.
   // CHECK:   [[RVALUE:%.*]] = alloc_stack $(index: C, value: Self), let, name "tuple"
diff --git a/test/SILGen/types.swift b/test/SILGen/types.swift
index 8b0dc6c..8a49777 100644
--- a/test/SILGen/types.swift
+++ b/test/SILGen/types.swift
@@ -4,7 +4,7 @@
   var member: Int = 0
 
   // Methods have method calling convention.
-  // CHECK-LABEL: sil hidden @_T05types1CC3fooySi1x_tF : $@convention(method) (Int, @guaranteed C) -> () {
+  // CHECK-LABEL: sil hidden @_T05types1CC3foo1xySi_tF : $@convention(method) (Int, @guaranteed C) -> () {
   func foo(x x: Int) {
     // CHECK: bb0([[X:%[0-9]+]] : @trivial $Int, [[THIS:%[0-9]+]] : @guaranteed $C):
     member = x
@@ -14,7 +14,7 @@
     // CHECK: apply [[FN]](%0, %1) : $@convention(method) (Int, @guaranteed C) -> ()
     // CHECK-NOT: destroy_value
   }
-  // CHECK: } // end sil function '_T05types1CC3fooySi1x_tF'
+  // CHECK: } // end sil function '_T05types1CC3foo1xySi_tF'
 }
 
 struct S {
@@ -69,7 +69,7 @@
   case g((ReferencedFromFunctionStruct) -> ())
 }
 
-// CHECK-LABEL: sil hidden @_T05types34referencedFromFunctionStructFieldsyAA010ReferencedcdE0Vc_yAA0gcD4EnumOctADF{{.*}} : $@convention(thin) (@owned ReferencedFromFunctionStruct) -> (@owned @callee_guaranteed (@owned ReferencedFromFunctionStruct) -> (), @owned @callee_guaranteed (@owned ReferencedFromFunctionEnum) -> ()) {
+// CHECK-LABEL: sil hidden @_T05types34referencedFromFunctionStructFieldsyyAA010ReferencedcdE0Vc_yAA0gcD4EnumOctADF{{.*}} : $@convention(thin) (@owned ReferencedFromFunctionStruct) -> (@owned @callee_guaranteed (@owned ReferencedFromFunctionStruct) -> (), @owned @callee_guaranteed (@owned ReferencedFromFunctionEnum) -> ()) {
 // CHECK: bb0([[X:%.*]] : @owned $ReferencedFromFunctionStruct):
 // CHECK:   [[BORROWED_X:%.*]] = begin_borrow [[X]]
 // CHECK:   [[F:%.*]] = struct_extract [[BORROWED_X]] : $ReferencedFromFunctionStruct, #ReferencedFromFunctionStruct.f
@@ -82,13 +82,13 @@
 // CHECK:   destroy_value [[X]]
 // CHECK:   [[RESULT:%.*]] = tuple ([[COPIED_F]] : {{.*}}, [[COPIED_G]] : {{.*}})
 // CHECK:   return [[RESULT]]
-// CHECK: } // end sil function '_T05types34referencedFromFunctionStructFieldsyAA010ReferencedcdE0Vc_yAA0gcD4EnumOctADF'
+// CHECK: } // end sil function '_T05types34referencedFromFunctionStructFieldsyyAA010ReferencedcdE0Vc_yAA0gcD4EnumOctADF'
 func referencedFromFunctionStructFields(_ x: ReferencedFromFunctionStruct)
     -> ((ReferencedFromFunctionStruct) -> (), (ReferencedFromFunctionEnum) -> ()) {
   return (x.f, x.g)
 }
 
-// CHECK-LABEL: sil hidden @_T05types32referencedFromFunctionEnumFieldsyAA010ReferencedcdE0OcSg_yAA0gcD6StructVcSgtADF
+// CHECK-LABEL: sil hidden @_T05types32referencedFromFunctionEnumFieldsyyAA010ReferencedcdE0OcSg_yAA0gcD6StructVcSgtADF
 // CHECK:       bb{{[0-9]+}}([[F:%.*]] : @owned $@callee_guaranteed (@owned ReferencedFromFunctionEnum) -> ()):
 // CHECK:       bb{{[0-9]+}}([[G:%.*]] : @owned $@callee_guaranteed (@owned ReferencedFromFunctionStruct) -> ()):
 func referencedFromFunctionEnumFields(_ x: ReferencedFromFunctionEnum)
@@ -105,5 +105,5 @@
 }
 
 // CHECK-LABEL: sil private @_T05types1fyyF2FCL_C3zimyyF
-// CHECK-LABEL: sil private @_T05types1gySb1b_tF2FCL_C3zimyyF
-// CHECK-LABEL: sil private @_T05types1gySb1b_tF2FCL0_C3zimyyF
+// CHECK-LABEL: sil private @_T05types1g1bySb_tF2FCL_C3zimyyF
+// CHECK-LABEL: sil private @_T05types1g1bySb_tF2FCL0_C3zimyyF
diff --git a/test/SILGen/unmanaged.swift b/test/SILGen/unmanaged.swift
index 52b1a01..d75df66 100644
--- a/test/SILGen/unmanaged.swift
+++ b/test/SILGen/unmanaged.swift
@@ -16,7 +16,7 @@
 func set(holder holder: inout Holder) {
   holder.value = C()
 }
-// CHECK-LABEL:sil hidden @_T09unmanaged3setyAA6HolderVz6holder_tF : $@convention(thin) (@inout Holder) -> ()
+// CHECK-LABEL:sil hidden @_T09unmanaged3set6holderyAA6HolderVz_tF : $@convention(thin) (@inout Holder) -> ()
 // CHECK: bb0([[ADDR:%.*]] : $*Holder):
 // CHECK:        [[T0:%.*]] = function_ref @_T09unmanaged1CC{{[_0-9a-zA-Z]*}}fC
 // CHECK:        [[C:%.*]] = apply [[T0]](
@@ -32,7 +32,7 @@
 func get(holder holder: inout Holder) -> C {
   return holder.value
 }
-// CHECK-LABEL:sil hidden @_T09unmanaged3getAA1CCAA6HolderVz6holder_tF : $@convention(thin) (@inout Holder) -> @owned C
+// CHECK-LABEL:sil hidden @_T09unmanaged3get6holderAA1CCAA6HolderVz_tF : $@convention(thin) (@inout Holder) -> @owned C
 // CHECK: bb0([[ADDR:%.*]] : $*Holder):
 // CHECK-NEXT:   debug_value_addr %0 : $*Holder, var, name "holder", argno 1 
 // CHECK-NEXT:   [[READ:%.*]] = begin_access [read] [static] [[ADDR]] : $*Holder
@@ -46,7 +46,7 @@
 func project(fn fn: () -> Holder) -> C {
   return fn().value
 }
-// CHECK-LABEL:sil hidden @_T09unmanaged7projectAA1CCAA6HolderVyc2fn_tF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> Holder) -> @owned C
+// CHECK-LABEL:sil hidden @_T09unmanaged7project2fnAA1CCAA6HolderVyc_tF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> Holder) -> @owned C
 // CHECK: bb0([[FN:%.*]] : $@noescape @callee_guaranteed () -> Holder):
 // CHECK:        strong_retain [[FN]]
 // CHECK-NEXT: [[T0:%.*]] = apply [[FN]]()
diff --git a/test/SILGen/unmanaged_ownership.swift b/test/SILGen/unmanaged_ownership.swift
index 5e47a73..67133c0 100644
--- a/test/SILGen/unmanaged_ownership.swift
+++ b/test/SILGen/unmanaged_ownership.swift
@@ -23,12 +23,12 @@
 // CHECK-NEXT:   destroy_value [[T0]] : $C
 // CHECK-NEXT:   [[T2:%.*]] = struct $Holder ([[T1]] : $@sil_unmanaged C)
 // CHECK-NEXT:   return [[T2]] : $Holder
-// CHECK-NEXT: } // end sil function '_T0s6HolderVABs1CC5value_tcfC'
+// CHECK-NEXT: } // end sil function '_T0s6HolderV5valueABs1CC_tcfC'
 func set(holder holder: inout Holder) {
   holder.value = C()
 }
 
-// CHECK-LABEL: sil hidden @_T0s3setys6HolderVz6holder_tF : $@convention(thin) (@inout Holder) -> () {
+// CHECK-LABEL: sil hidden @_T0s3set6holderys6HolderVz_tF : $@convention(thin) (@inout Holder) -> () {
 // CHECK: bb0([[ADDR:%.*]] : @trivial $*Holder):
 // CHECK:        [[T0:%.*]] = function_ref @_T0s1CC{{[_0-9a-zA-Z]*}}fC
 // CHECK:        [[C:%.*]] = apply [[T0]](
@@ -38,12 +38,12 @@
 // CHECK-NEXT:   assign [[T1]] to [[T0]]
 // CHECK-NEXT:   destroy_value [[C]]
 // CHECK-NEXT:   end_access [[WRITE]] : $*Holder
-// CHECK: } // end sil function '_T0s3setys6HolderVz6holder_tF'
+// CHECK: } // end sil function '_T0s3set6holderys6HolderVz_tF'
 
 func get(holder holder: inout Holder) -> C {
   return holder.value
 }
-// CHECK-LABEL: sil hidden @_T0s3gets1CCs6HolderVz6holder_tF : $@convention(thin) (@inout Holder) -> @owned C {
+// CHECK-LABEL: sil hidden @_T0s3get6holders1CCs6HolderVz_tF : $@convention(thin) (@inout Holder) -> @owned C {
 // CHECK: bb0([[ADDR:%.*]] : @trivial $*Holder):
 // CHECK-NEXT:   debug_value_addr %0 : $*Holder, var, name "holder", argno 1 
 // CHECK-NEXT:   [[READ:%.*]] = begin_access [read] [unknown] [[ADDR]] : $*Holder
@@ -57,7 +57,7 @@
 func project(fn fn: () -> Holder) -> C {
   return fn().value
 }
-// CHECK-LABEL: sil hidden @_T0s7projects1CCs6HolderVyc2fn_tF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> Holder) -> @owned C {
+// CHECK-LABEL: sil hidden @_T0s7project2fns1CCs6HolderVyc_tF : $@convention(thin) (@owned @noescape @callee_guaranteed () -> Holder) -> @owned C {
 // CHECK: bb0([[FN:%.*]] : @owned $@noescape @callee_guaranteed () -> Holder):
 // CHECK:      [[BORROWED_FN:%.*]] = begin_borrow [[FN]]
 // CHECK-NEXT: [[BORROWED_FN_COPY:%.*]] = copy_value [[BORROWED_FN]]
diff --git a/test/SILGen/unowned.swift b/test/SILGen/unowned.swift
index 6c77908..bc3c52b 100644
--- a/test/SILGen/unowned.swift
+++ b/test/SILGen/unowned.swift
@@ -36,7 +36,7 @@
 // CHECK:   destroy_value [[X]]
 // CHECK: }
 
-// CHECK-LABEL:    sil hidden @_T07unowned5test0yAA1CC1c_tF : $@convention(thin) (@owned C) -> () {
+// CHECK-LABEL:    sil hidden @_T07unowned5test01cyAA1CC_tF : $@convention(thin) (@owned C) -> () {
 func test0(c c: C) {
   // CHECK: bb0([[ARG:%.*]] : @owned $C):
 
@@ -82,7 +82,7 @@
   // CHECK:   destroy_value [[MARKED_A1]]
   // CHECK:   destroy_value [[ARG]]
 }
-// CHECK: } // end sil function '_T07unowned5test0yAA1CC1c_tF'
+// CHECK: } // end sil function '_T07unowned5test01cyAA1CC_tF'
 
 // CHECK-LABEL: sil hidden @{{.*}}testunowned_local
 func testunowned_local() -> C {
@@ -116,7 +116,7 @@
   takeClosure { bC.f() }
 }
 
-// CHECK-LABEL: sil private @_T07unowned05test_A12_let_captureyAA1CCFSiycfU_ : $@convention(thin) (@guaranteed @sil_unowned C) -> Int {
+// CHECK-LABEL: sil private @_T07unowned05test_A12_let_captureyyAA1CCFSiycfU_ : $@convention(thin) (@guaranteed @sil_unowned C) -> Int {
 // CHECK: bb0([[ARG:%.*]] : @guaranteed $@sil_unowned C):
 // CHECK-NEXT:   debug_value %0 : $@sil_unowned C, let, name "bC", argno 1
 // CHECK-NEXT:   [[UNOWNED_ARG:%.*]] = copy_unowned_value [[ARG]] : $@sil_unowned C
@@ -137,7 +137,7 @@
   }
 }
 
-// CHECK-LABEL: sil hidden @_T07unowned17TestUnownedMemberCAcA1CC5inval_tcfc :
+// CHECK-LABEL: sil hidden @_T07unowned17TestUnownedMemberC5invalAcA1CC_tcfc :
 // CHECK: bb0([[ARG1:%.*]] : @owned $C, [[SELF_PARAM:%.*]] : @owned $TestUnownedMember):
 // CHECK:   [[SELF:%.*]] = mark_uninitialized [rootself] [[SELF_PARAM]] : $TestUnownedMember
 // CHECK:   [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
@@ -155,7 +155,7 @@
 // CHECK:   destroy_value [[SELF]]
 // CHECK:   destroy_value [[ARG1]]
 // CHECK:   return [[RET_SELF]] : $TestUnownedMember
-// CHECK: } // end sil function '_T07unowned17TestUnownedMemberCAcA1CC5inval_tcfc'
+// CHECK: } // end sil function '_T07unowned17TestUnownedMemberC5invalAcA1CC_tcfc'
 
 // Just verify that lowering an unowned reference to a type parameter
 // doesn't explode.
@@ -163,4 +163,4 @@
   unowned var object: T
 }
 func takesUnownedStruct(_ z: Unowned<C>) {}
-// CHECK-LABEL: sil hidden @_T07unowned18takesUnownedStructyAA0C0VyAA1CCGF : $@convention(thin) (@owned Unowned<C>) -> ()
+// CHECK-LABEL: sil hidden @_T07unowned18takesUnownedStructyyAA0C0VyAA1CCGF : $@convention(thin) (@owned Unowned<C>) -> ()
diff --git a/test/SILGen/unreachable_code.swift b/test/SILGen/unreachable_code.swift
index 3048d71..7987976 100644
--- a/test/SILGen/unreachable_code.swift
+++ b/test/SILGen/unreachable_code.swift
@@ -106,7 +106,7 @@
   switch a {
   case _:
     break
-  default:  // expected-warning {{default will never be executed}}
+  default:  
     return
   }
 }
diff --git a/test/SILGen/unsafe_pointer_gen.swift b/test/SILGen/unsafe_pointer_gen.swift
index 496050a..d434291 100644
--- a/test/SILGen/unsafe_pointer_gen.swift
+++ b/test/SILGen/unsafe_pointer_gen.swift
@@ -1,7 +1,7 @@
 // RUN: %target-swift-frontend -O -emit-sil -parse-as-library %s | %FileCheck %s
 
 // Test the absence of a 'strict' flag.
-// CHECK-LABEL: _T018unsafe_pointer_gen13test_raw_loadSiSV2rp_tF
+// CHECK-LABEL: _T018unsafe_pointer_gen13test_raw_load2rpSiSV_tF
 // CHECK: pointer_to_address {{%.*}} : $Builtin.RawPointer to $*Int
 public func test_raw_load(rp: UnsafeRawPointer) -> Int {
   return rp.load(as: Int.self)
diff --git a/test/SILGen/vtable_thunks_reabstraction.swift b/test/SILGen/vtable_thunks_reabstraction.swift
index 4b368f1..0687cbd 100644
--- a/test/SILGen/vtable_thunks_reabstraction.swift
+++ b/test/SILGen/vtable_thunks_reabstraction.swift
@@ -163,17 +163,17 @@
 }
 
 // CHECK-LABEL: sil_vtable Opaque {
-// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC8inAndOutxx1x_tF	// Opaque.inAndOut(x:)
-// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF	// Opaque.inAndOutGeneric<A>(x:y:)
-// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF	// Opaque.inAndOutMetatypes(x:)
-// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF	// Opaque.inAndOutFunctions(x:)
-// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF	// Opaque.inAndOutTuples(x:)
-// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : _T027vtable_thunks_reabstraction6OpaqueC18variantOptionalityxSgx1x_tF	// Opaque.variantOptionality(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF	// Opaque.variantOptionalityMetatypes(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF	// Opaque.variantOptionalityFunctions(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF	// Opaque.variantOptionalityTuples(x:)
-// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction6OpaqueCACyxGycfc	// Opaque.init()
-// CHECK-NEXT:   #Opaque.deinit!deallocator: _T027vtable_thunks_reabstraction6OpaqueCfD	// Opaque.__deallocating_deinit
+// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC8inAndOut1xxx_tF    // Opaque.inAndOut(x:)
+// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGeneric1x1yqd__x_qd__tlF     // Opaque.inAndOutGeneric<A>(x:y:)
+// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypes1xxmxm_tF     // Opaque.inAndOutMetatypes(x:)
+// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctions1xxxcxxc_tF     // Opaque.inAndOutFunctions(x:)
+// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuples1xx_xm_xxcttx_xm_xxctt_tF // Opaque.inAndOutTuples(x:)
+// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : _T027vtable_thunks_reabstraction6OpaqueC18variantOptionality1xxSgx_tF    // Opaque.variantOptionality(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypes1xxmSgxm_tF      // Opaque.variantOptionalityMetatypes(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctions1xxxcSgxxc_tF    // Opaque.variantOptionalityFunctions(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuples1xx_xm_xxcttSgx_xm_xxctt_tF  // Opaque.variantOptionalityTuples(x:)
+// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction6OpaqueCACyxGycfc       // Opaque.init()
+// CHECK-NEXT:   #Opaque.deinit!deallocator: _T027vtable_thunks_reabstraction6OpaqueCfD        // Opaque.__deallocating_deinit
 // CHECK-NEXT: }
 
 class StillOpaque<T>: Opaque<T> {
@@ -181,22 +181,22 @@
 }
 
 // CHECK-LABEL: sil_vtable StillOpaque {
-// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC8inAndOutxx1x_tF	[inherited] // Opaque.inAndOut(x:)
-// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF [inherited]	// Opaque.inAndOutGeneric<A>(x:y:)
-// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF [inherited]	// Opaque.inAndOutMetatypes(x:)
-// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF [inherited]	// Opaque.inAndOutFunctions(x:)
-// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF [inherited]	// Opaque.inAndOutTuples(x:)
-// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : _T027vtable_thunks_reabstraction6OpaqueC18variantOptionalityxSgx1x_tF [inherited]	// Opaque.variantOptionality(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF [inherited]	// Opaque.variantOptionalityMetatypes(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF [inherited]	// Opaque.variantOptionalityFunctions(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : hidden _T027vtable_thunks_reabstraction11StillOpaqueC24variantOptionalityTuplesx_xm_xxcttx_xm_xxcttSg1x_tFAA0E0CAdEx_xm_xxcttAF_tFTV [override]	// vtable thunk for Opaque.variantOptionalityTuples(x:) dispatching to StillOpaque.variantOptionalityTuples(x:)
-// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction11StillOpaqueCACyxGycfc [override]	// StillOpaque.init()
+// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC8inAndOut1xxx_tF [inherited]        // Opaque.inAndOut(x:)
+// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGeneric1x1yqd__x_qd__tlF [inherited] // Opaque.inAndOutGeneric<A>(x:y:)
+// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypes1xxmxm_tF [inherited] // Opaque.inAndOutMetatypes(x:)
+// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctions1xxxcxxc_tF [inherited] // Opaque.inAndOutFunctions(x:)
+// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuples1xx_xm_xxcttx_xm_xxctt_tF [inherited]     // Opaque.inAndOutTuples(x:)
+// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : _T027vtable_thunks_reabstraction6OpaqueC18variantOptionality1xxSgx_tF [inherited]        // Opaque.variantOptionality(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypes1xxmSgxm_tF [inherited]  // Opaque.variantOptionalityMetatypes(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctions1xxxcSgxxc_tF [inherited]        // Opaque.variantOptionalityFunctions(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : hidden _T027vtable_thunks_reabstraction11StillOpaqueC24variantOptionalityTuples1xx_xm_xxcttx_xm_xxcttSg_tFAA0E0CAdeFx_xm_xxctt_tFTV [override] // vtable thunk for Opaque.variantOptionalityTuples(x:) dispatching to StillOpaque.variantOptionalityTuples(x:)
+// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction11StillOpaqueCACyxGycfc [override]      // StillOpaque.init()
 
 // Tuple becomes more optional -- needs new vtable entry
 
-// CHECK-NEXT:  #StillOpaque.variantOptionalityTuples!1: <T> (StillOpaque<T>) -> ((T, (T.Type, (T) -> T))?) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction11StillOpaqueC24variantOptionalityTuplesx_xm_xxcttx_xm_xxcttSg1x_tF	// StillOpaque.variantOptionalityTuples(x:)
+// CHECK-NEXT:   #StillOpaque.variantOptionalityTuples!1: <T> (StillOpaque<T>) -> ((T, (T.Type, (T) -> T))?) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction11StillOpaqueC24variantOptionalityTuples1xx_xm_xxcttx_xm_xxcttSg_tF  // StillOpaque.variantOptionalityTuples(x:)
 
-// CHECK-NEXT:   #StillOpaque.deinit!deallocator: _T027vtable_thunks_reabstraction11StillOpaqueCfD	// StillOpaque.__deallocating_deinit
+// CHECK-NEXT:   #StillOpaque.deinit!deallocator: _T027vtable_thunks_reabstraction11StillOpaqueCfD     // StillOpaque.__deallocating_deinit
 // CHECK-NEXT: }
 
 class ConcreteValue: Opaque<S> {
@@ -212,25 +212,25 @@
 }
 
 // CHECK-LABEL: sil_vtable ConcreteValue {
-// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction13ConcreteValueC8inAndOutAA1SVAF1x_tFAA6OpaqueCADxxAG_tFTV [override]	// vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteValue.inAndOut(x:)
-// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : hidden _T027vtable_thunks_reabstraction13ConcreteValueC15inAndOutGenericxAA1SV1x_x1ytlFAA6OpaqueCADqd__xAG_qd__AHtlFTV [override]	// vtable thunk for Opaque.inAndOutGeneric<A>(x:y:) dispatching to ConcreteValue.inAndOutGeneric<A>(x:y:)
-// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : hidden _T027vtable_thunks_reabstraction13ConcreteValueC17inAndOutMetatypesAA1SVmAFm1x_tFAA6OpaqueCADxmxmAG_tFTV [override]	// vtable thunk for Opaque.inAndOutMetatypes(x:) dispatching to ConcreteValue.inAndOutMetatypes(x:)
-// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : hidden _T027vtable_thunks_reabstraction13ConcreteValueC17inAndOutFunctionsAA1SVAFcA2Fc1x_tFAA6OpaqueCADxxcxxcAG_tFTV [override]	// vtable thunk for Opaque.inAndOutFunctions(x:) dispatching to ConcreteValue.inAndOutFunctions(x:)
-// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : hidden _T027vtable_thunks_reabstraction13ConcreteValueC14inAndOutTuplesAA1SV_AFm_A2FcttAF_AFm_A2Fctt1x_tFAA6OpaqueCADx_xm_xxcttx_xm_xxcttAG_tFTV [override]	// vtable thunk for Opaque.inAndOutTuples(x:) dispatching to ConcreteValue.inAndOutTuples(x:)
-// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction13ConcreteValueC18variantOptionalityAA1SVAFSg1x_tFAA6OpaqueCADxSgxAH_tFTV [override]	// vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteValue.variantOptionality(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : hidden _T027vtable_thunks_reabstraction13ConcreteValueC27variantOptionalityMetatypesAA1SVmAFmSg1x_tFAA6OpaqueCADxmSgxmAH_tFTV [override]	// vtable thunk for Opaque.variantOptionalityMetatypes(x:) dispatching to ConcreteValue.variantOptionalityMetatypes(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : hidden _T027vtable_thunks_reabstraction13ConcreteValueC27variantOptionalityFunctionsAA1SVAFcA2FcSg1x_tFAA6OpaqueCADxxcSgxxcAH_tFTV [override]	// vtable thunk for Opaque.variantOptionalityFunctions(x:) dispatching to ConcreteValue.variantOptionalityFunctions(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : hidden _T027vtable_thunks_reabstraction13ConcreteValueC24variantOptionalityTuplesAA1SV_AFm_A2FcttAF_AFm_A2FcttSg1x_tFAA6OpaqueCADx_xm_xxcttSgx_xm_xxcttAH_tFTV [override]	// vtable thunk for Opaque.variantOptionalityTuples(x:) dispatching to ConcreteValue.variantOptionalityTuples(x:)
-// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction13ConcreteValueCACycfc [override]	// ConcreteValue.init()
+// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction13ConcreteValueC8inAndOut1xAA1SVAG_tFAA6OpaqueCAdExx_tFTV [override] // vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteValue.inAndOut(x:)
+// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : hidden _T027vtable_thunks_reabstraction13ConcreteValueC15inAndOutGeneric1x1yxAA1SV_xtlFAA6OpaqueCAdeFqd__x_qd__tlFTV [override]        // vtable thunk for Opaque.inAndOutGeneric<A>(x:y:) dispatching to ConcreteValue.inAndOutGeneric<A>(x:y:)
+// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : hidden _T027vtable_thunks_reabstraction13ConcreteValueC17inAndOutMetatypes1xAA1SVmAGm_tFAA6OpaqueCAdExmxm_tFTV [override]        // vtable thunk for Opaque.inAndOutMetatypes(x:) dispatching to ConcreteValue.inAndOutMetatypes(x:)
+// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : hidden _T027vtable_thunks_reabstraction13ConcreteValueC17inAndOutFunctions1xAA1SVAGcA2Gc_tFAA6OpaqueCAdExxcxxc_tFTV [override]     // vtable thunk for Opaque.inAndOutFunctions(x:) dispatching to ConcreteValue.inAndOutFunctions(x:)
+// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : hidden _T027vtable_thunks_reabstraction13ConcreteValueC14inAndOutTuples1xAA1SV_AGm_A2GcttAG_AGm_A2Gctt_tFAA6OpaqueCAdEx_xm_xxcttx_xm_xxctt_tFTV [override]        // vtable thunk for Opaque.inAndOutTuples(x:) dispatching to ConcreteValue.inAndOutTuples(x:)
+// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction13ConcreteValueC18variantOptionality1xAA1SVAGSg_tFAA6OpaqueCAdExSgx_tFTV [override]       // vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteValue.variantOptionality(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : hidden _T027vtable_thunks_reabstraction13ConcreteValueC27variantOptionalityMetatypes1xAA1SVmAGmSg_tFAA6OpaqueCAdExmSgxm_tFTV [override]       // vtable thunk for Opaque.variantOptionalityMetatypes(x:) dispatching to ConcreteValue.variantOptionalityMetatypes(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : hidden _T027vtable_thunks_reabstraction13ConcreteValueC27variantOptionalityFunctions1xAA1SVAGcA2GcSg_tFAA6OpaqueCAdExxcSgxxc_tFTV [override]  // vtable thunk for Opaque.variantOptionalityFunctions(x:) dispatching to ConcreteValue.variantOptionalityFunctions(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : hidden _T027vtable_thunks_reabstraction13ConcreteValueC24variantOptionalityTuples1xAA1SV_AGm_A2GcttAG_AGm_A2GcttSg_tFAA6OpaqueCAdEx_xm_xxcttSgx_xm_xxctt_tFTV [override]       // vtable thunk for Opaque.variantOptionalityTuples(x:) dispatching to ConcreteValue.variantOptionalityTuples(x:)
+// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction13ConcreteValueCACycfc [override]       // ConcreteValue.init()
 
 // Value types becoming more optional -- needs new vtable entry
 
-// CHECK-NEXT:   #ConcreteValue.variantOptionality!1: (ConcreteValue) -> (S?) -> S : _T027vtable_thunks_reabstraction13ConcreteValueC18variantOptionalityAA1SVAFSg1x_tF // ConcreteValue.variantOptionality(x:)
-// CHECK-NEXT:   #ConcreteValue.variantOptionalityMetatypes!1: (ConcreteValue) -> (S.Type?) -> S.Type : _T027vtable_thunks_reabstraction13ConcreteValueC27variantOptionalityMetatypesAA1SVmAFmSg1x_tF // ConcreteValue.variantOptionalityMetatypes(x:)
-// CHECK-NEXT:   #ConcreteValue.variantOptionalityFunctions!1: (ConcreteValue) -> (((S) -> S)?) -> (S) -> S : _T027vtable_thunks_reabstraction13ConcreteValueC27variantOptionalityFunctionsAA1SVAFcA2FcSg1x_tF	// ConcreteValue.variantOptionalityFunctions(x:)
-// CHECK-NEXT:   #ConcreteValue.variantOptionalityTuples!1: (ConcreteValue) -> ((S, (S.Type, (S) -> S))?) -> (S, (S.Type, (S) -> S)) : _T027vtable_thunks_reabstraction13ConcreteValueC24variantOptionalityTuplesAA1SV_AFm_A2FcttAF_AFm_A2FcttSg1x_tF	// ConcreteValue.variantOptionalityTuples(x:)
+// CHECK-NEXT:   #ConcreteValue.variantOptionality!1: (ConcreteValue) -> (S?) -> S : _T027vtable_thunks_reabstraction13ConcreteValueC18variantOptionality1xAA1SVAGSg_tF        // ConcreteValue.variantOptionality(x:)
+// CHECK-NEXT:   #ConcreteValue.variantOptionalityMetatypes!1: (ConcreteValue) -> (S.Type?) -> S.Type : _T027vtable_thunks_reabstraction13ConcreteValueC27variantOptionalityMetatypes1xAA1SVmAGmSg_tF  // ConcreteValue.variantOptionalityMetatypes(x:)
+// CHECK-NEXT:   #ConcreteValue.variantOptionalityFunctions!1: (ConcreteValue) -> (((S) -> S)?) -> (S) -> S : _T027vtable_thunks_reabstraction13ConcreteValueC27variantOptionalityFunctions1xAA1SVAGcA2GcSg_tF // ConcreteValue.variantOptionalityFunctions(x:)
+// CHECK-NEXT:   #ConcreteValue.variantOptionalityTuples!1: (ConcreteValue) -> ((S, (S.Type, (S) -> S))?) -> (S, (S.Type, (S) -> S)) : _T027vtable_thunks_reabstraction13ConcreteValueC24variantOptionalityTuples1xAA1SV_AGm_A2GcttAG_AGm_A2GcttSg_tF  // ConcreteValue.variantOptionalityTuples(x:)
 
-// CHECK-NEXT:   #ConcreteValue.deinit!deallocator: _T027vtable_thunks_reabstraction13ConcreteValueCfD	// ConcreteValue.__deallocating_deinit
+// CHECK-NEXT:   #ConcreteValue.deinit!deallocator: _T027vtable_thunks_reabstraction13ConcreteValueCfD // ConcreteValue.__deallocating_deinit
 // CHECK-NEXT: }
 
 class ConcreteClass: Opaque<C> {
@@ -245,16 +245,16 @@
 }
 
 // CHECK-LABEL: sil_vtable ConcreteClass {
-// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction13ConcreteClassC8inAndOutAA1CCAF1x_tFAA6OpaqueCADxxAG_tFTV [override]	// vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteClass.inAndOut(x:)
-// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF [inherited]	// Opaque.inAndOutGeneric<A>(x:y:)
-// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction13ConcreteClassC17inAndOutMetatypesAA1CCmAFm1x_tF [override]	// ConcreteClass.inAndOutMetatypes(x:)
-// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : hidden _T027vtable_thunks_reabstraction13ConcreteClassC17inAndOutFunctionsAA1CCAFcA2Fc1x_tFAA6OpaqueCADxxcxxcAG_tFTV [override]	// vtable thunk for Opaque.inAndOutFunctions(x:) dispatching to ConcreteClass.inAndOutFunctions(x:)
-// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : hidden _T027vtable_thunks_reabstraction13ConcreteClassC14inAndOutTuplesAA1CC_AFm_A2FcttAF_AFm_A2Fctt1x_tFAA6OpaqueCADx_xm_xxcttx_xm_xxcttAG_tFTV [override]	// vtable thunk for Opaque.inAndOutTuples(x:) dispatching to ConcreteClass.inAndOutTuples(x:)
-// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction13ConcreteClassC18variantOptionalityAA1CCAFSg1x_tFAA6OpaqueCADxSgxAH_tFTV [override]	// vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteClass.variantOptionality(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction13ConcreteClassC27variantOptionalityMetatypesAA1CCmAFmSg1x_tF [override]	// ConcreteClass.variantOptionalityMetatypes(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : hidden _T027vtable_thunks_reabstraction13ConcreteClassC27variantOptionalityFunctionsAA1CCAFcA2FcSg1x_tFAA6OpaqueCADxxcSgxxcAH_tFTV [override]	// vtable thunk for Opaque.variantOptionalityFunctions(x:) dispatching to ConcreteClass.variantOptionalityFunctions(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : hidden _T027vtable_thunks_reabstraction13ConcreteClassC24variantOptionalityTuplesAA1CC_AFm_A2FcttAF_AFm_A2FcttSg1x_tFAA6OpaqueCADx_xm_xxcttSgx_xm_xxcttAH_tFTV [override]	// vtable thunk for Opaque.variantOptionalityTuples(x:) dispatching to ConcreteClass.variantOptionalityTuples(x:)
-// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction13ConcreteClassCACycfc [override]	// ConcreteClass.init()
+// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction13ConcreteClassC8inAndOut1xAA1CCAG_tFAA6OpaqueCAdExx_tFTV [override] // vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteClass.inAndOut(x:)
+// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGeneric1x1yqd__x_qd__tlF [inherited] // Opaque.inAndOutGeneric<A>(x:y:)
+// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction13ConcreteClassC17inAndOutMetatypes1xAA1CCmAGm_tF [override]     // ConcreteClass.inAndOutMetatypes(x:)
+// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : hidden _T027vtable_thunks_reabstraction13ConcreteClassC17inAndOutFunctions1xAA1CCAGcA2Gc_tFAA6OpaqueCAdExxcxxc_tFTV [override]     // vtable thunk for Opaque.inAndOutFunctions(x:) dispatching to ConcreteClass.inAndOutFunctions(x:)
+// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : hidden _T027vtable_thunks_reabstraction13ConcreteClassC14inAndOutTuples1xAA1CC_AGm_A2GcttAG_AGm_A2Gctt_tFAA6OpaqueCAdEx_xm_xxcttx_xm_xxctt_tFTV [override]        // vtable thunk for Opaque.inAndOutTuples(x:) dispatching to ConcreteClass.inAndOutTuples(x:)
+// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction13ConcreteClassC18variantOptionality1xAA1CCAGSg_tFAA6OpaqueCAdExSgx_tFTV [override]       // vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteClass.variantOptionality(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction13ConcreteClassC27variantOptionalityMetatypes1xAA1CCmAGmSg_tF [override]      // ConcreteClass.variantOptionalityMetatypes(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : hidden _T027vtable_thunks_reabstraction13ConcreteClassC27variantOptionalityFunctions1xAA1CCAGcA2GcSg_tFAA6OpaqueCAdExxcSgxxc_tFTV [override]  // vtable thunk for Opaque.variantOptionalityFunctions(x:) dispatching to ConcreteClass.variantOptionalityFunctions(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : hidden _T027vtable_thunks_reabstraction13ConcreteClassC24variantOptionalityTuples1xAA1CC_AGm_A2GcttAG_AGm_A2GcttSg_tFAA6OpaqueCAdEx_xm_xxcttSgx_xm_xxctt_tFTV [override]       // vtable thunk for Opaque.variantOptionalityTuples(x:) dispatching to ConcreteClass.variantOptionalityTuples(x:)
+// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction13ConcreteClassCACycfc [override]       // ConcreteClass.init()
 
 // Class references are ABI-compatible with optional class references, and
 // similarly for class metatypes.
@@ -262,10 +262,10 @@
 // Function and tuple optionality change still needs a new vtable entry
 // as above.
 
-// CHECK-NEXT:   #ConcreteClass.variantOptionalityFunctions!1: (ConcreteClass) -> (((C) -> C)?) -> (C) -> C : _T027vtable_thunks_reabstraction13ConcreteClassC27variantOptionalityFunctionsAA1CCAFcA2FcSg1x_tF	// ConcreteClass.variantOptionalityFunctions(x:)
-// CHECK-NEXT:   #ConcreteClass.variantOptionalityTuples!1: (ConcreteClass) -> ((C, (C.Type, (C) -> C))?) -> (C, (C.Type, (C) -> C)) : _T027vtable_thunks_reabstraction13ConcreteClassC24variantOptionalityTuplesAA1CC_AFm_A2FcttAF_AFm_A2FcttSg1x_tF	// ConcreteClass.variantOptionalityTuples(x:)
+// CHECK-NEXT:   #ConcreteClass.variantOptionalityFunctions!1: (ConcreteClass) -> (((C) -> C)?) -> (C) -> C : _T027vtable_thunks_reabstraction13ConcreteClassC27variantOptionalityFunctions1xAA1CCAGcA2GcSg_tF // ConcreteClass.variantOptionalityFunctions(x:)
+// CHECK-NEXT:   #ConcreteClass.variantOptionalityTuples!1: (ConcreteClass) -> ((C, (C.Type, (C) -> C))?) -> (C, (C.Type, (C) -> C)) : _T027vtable_thunks_reabstraction13ConcreteClassC24variantOptionalityTuples1xAA1CC_AGm_A2GcttAG_AGm_A2GcttSg_tF  // ConcreteClass.variantOptionalityTuples(x:)
 
-// CHECK-NEXT:   #ConcreteClass.deinit!deallocator: _T027vtable_thunks_reabstraction13ConcreteClassCfD	// ConcreteClass.__deallocating_deinit
+// CHECK-NEXT:   #ConcreteClass.deinit!deallocator: _T027vtable_thunks_reabstraction13ConcreteClassCfD // ConcreteClass.__deallocating_deinit
 // CHECK-NEXT: }
 
 class ConcreteClassVariance: Opaque<C> {
@@ -274,21 +274,21 @@
 }
 
 // CHECK-LABEL: sil_vtable ConcreteClassVariance {
-// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction21ConcreteClassVarianceC8inAndOutAA1DCAA1BC1x_tFAA6OpaqueCADxxAI_tFTV [override]	// vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteClassVariance.inAndOut(x:)
-// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF [inherited]	// Opaque.inAndOutGeneric<A>(x:y:)
-// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF [inherited]	// Opaque.inAndOutMetatypes(x:)
-// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF [inherited]	// Opaque.inAndOutFunctions(x:)
-// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF [inherited]	// Opaque.inAndOutTuples(x:)
-// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction21ConcreteClassVarianceC18variantOptionalityAA1DCAA1BCSg1x_tFAA6OpaqueCADxSgxAJ_tFTV [override]	// vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteClassVariance.variantOptionality(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF [inherited]	// Opaque.variantOptionalityMetatypes(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF [inherited]	// Opaque.variantOptionalityFunctions(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF [inherited]	// Opaque.variantOptionalityTuples(x:)
-// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction21ConcreteClassVarianceCACycfc [override]	// ConcreteClassVariance.init()
+// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction21ConcreteClassVarianceC8inAndOut1xAA1DCAA1BC_tFAA6OpaqueCAdExx_tFTV [override]      // vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteClassVariance.inAndOut(x:)
+// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGeneric1x1yqd__x_qd__tlF [inherited] // Opaque.inAndOutGeneric<A>(x:y:)
+// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypes1xxmxm_tF [inherited] // Opaque.inAndOutMetatypes(x:)
+// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctions1xxxcxxc_tF [inherited] // Opaque.inAndOutFunctions(x:)
+// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuples1xx_xm_xxcttx_xm_xxctt_tF [inherited]     // Opaque.inAndOutTuples(x:)
+// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction21ConcreteClassVarianceC18variantOptionality1xAA1DCAA1BCSg_tFAA6OpaqueCAdExSgx_tFTV [override]    // vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteClassVariance.variantOptionality(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypes1xxmSgxm_tF [inherited]  // Opaque.variantOptionalityMetatypes(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctions1xxxcSgxxc_tF [inherited]        // Opaque.variantOptionalityFunctions(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuples1xx_xm_xxcttSgx_xm_xxctt_tF [inherited]      // Opaque.variantOptionalityTuples(x:)
+// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction21ConcreteClassVarianceCACycfc [override]       // ConcreteClassVariance.init()
 
 // No new vtable entries -- class references are ABI compatible with
 // optional class references.
 
-// CHECK-NEXT:   #ConcreteClassVariance.deinit!deallocator: _T027vtable_thunks_reabstraction21ConcreteClassVarianceCfD	// ConcreteClassVariance.__deallocating_deinit
+// CHECK-NEXT:   #ConcreteClassVariance.deinit!deallocator: _T027vtable_thunks_reabstraction21ConcreteClassVarianceCfD // ConcreteClassVariance.__deallocating_deinit
 // CHECK-NEXT: }
 
 class OpaqueTuple<U>: Opaque<(U, U)> {
@@ -297,22 +297,22 @@
 }
 
 // CHECK-LABEL: sil_vtable OpaqueTuple {
-// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction11OpaqueTupleC8inAndOutx_xtx_xt1x_tFAA0D0CADxxAE_tFTV [override]	// vtable thunk for Opaque.inAndOut(x:) dispatching to OpaqueTuple.inAndOut(x:)
-// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF [inherited]	// Opaque.inAndOutGeneric<A>(x:y:)
-// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF [inherited]	// Opaque.inAndOutMetatypes(x:)
-// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF [inherited]	// Opaque.inAndOutFunctions(x:)
-// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF [inherited]	// Opaque.inAndOutTuples(x:)
-// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction11OpaqueTupleC18variantOptionalityx_xtx_xtSg1x_tFAA0D0CADxSgxAF_tFTV [override]	// vtable thunk for Opaque.variantOptionality(x:) dispatching to OpaqueTuple.variantOptionality(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF [inherited]	// Opaque.variantOptionalityMetatypes(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF [inherited]	// Opaque.variantOptionalityFunctions(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF [inherited]	// Opaque.variantOptionalityTuples(x:)
-// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction11OpaqueTupleCACyxGycfc [override]	// OpaqueTuple.init()
+// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction11OpaqueTupleC8inAndOut1xx_xtx_xt_tFAA0D0CAdExx_tFTV [override]      // vtable thunk for Opaque.inAndOut(x:) dispatching to OpaqueTuple.inAndOut(x:)
+// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGeneric1x1yqd__x_qd__tlF [inherited] // Opaque.inAndOutGeneric<A>(x:y:)
+// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypes1xxmxm_tF [inherited] // Opaque.inAndOutMetatypes(x:)
+// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctions1xxxcxxc_tF [inherited] // Opaque.inAndOutFunctions(x:)
+// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuples1xx_xm_xxcttx_xm_xxctt_tF [inherited]     // Opaque.inAndOutTuples(x:)
+// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction11OpaqueTupleC18variantOptionality1xx_xtx_xtSg_tFAA0D0CAdExSgx_tFTV [override]    // vtable thunk for Opaque.variantOptionality(x:) dispatching to OpaqueTuple.variantOptionality(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypes1xxmSgxm_tF [inherited]  // Opaque.variantOptionalityMetatypes(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctions1xxxcSgxxc_tF [inherited]        // Opaque.variantOptionalityFunctions(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuples1xx_xm_xxcttSgx_xm_xxctt_tF [inherited]      // Opaque.variantOptionalityTuples(x:)
+// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction11OpaqueTupleCACyxGycfc [override]      // OpaqueTuple.init()
 
 // Optionality change of tuple.
 
-// CHECK-NEXT:  #OpaqueTuple.variantOptionality!1: <U> (OpaqueTuple<U>) -> ((U, U)?) -> (U, U) : _T027vtable_thunks_reabstraction11OpaqueTupleC18variantOptionalityx_xtx_xtSg1x_tF	// OpaqueTuple.variantOptionality(x:)
+// CHECK-NEXT:   #OpaqueTuple.variantOptionality!1: <U> (OpaqueTuple<U>) -> ((U, U)?) -> (U, U) : _T027vtable_thunks_reabstraction11OpaqueTupleC18variantOptionality1xx_xtx_xtSg_tF    // OpaqueTuple.variantOptionality(x:)
 
-// CHECK-NEXT:   #OpaqueTuple.deinit!deallocator: _T027vtable_thunks_reabstraction11OpaqueTupleCfD	// OpaqueTuple.__deallocating_deinit
+// CHECK-NEXT:   #OpaqueTuple.deinit!deallocator: _T027vtable_thunks_reabstraction11OpaqueTupleCfD     // OpaqueTuple.__deallocating_deinit
 // CHECK-NEXT: }
 
 class ConcreteTuple: Opaque<(S, S)> {
@@ -321,22 +321,22 @@
 }
 
 // CHECK-LABEL: sil_vtable ConcreteTuple {
-// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction13ConcreteTupleC8inAndOutAA1SV_AFtAF_AFt1x_tFAA6OpaqueCADxxAG_tFTV [override]	// vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteTuple.inAndOut(x:)
-// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF [inherited]	// Opaque.inAndOutGeneric<A>(x:y:)
-// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF [inherited]	// Opaque.inAndOutMetatypes(x:)
-// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF [inherited]	// Opaque.inAndOutFunctions(x:)
-// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF [inherited]	// Opaque.inAndOutTuples(x:)
-// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction13ConcreteTupleC18variantOptionalityAA1SV_AFtAF_AFtSg1x_tFAA6OpaqueCADxSgxAH_tFTV [override]	// vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteTuple.variantOptionality(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF [inherited]	// Opaque.variantOptionalityMetatypes(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF [inherited]	// Opaque.variantOptionalityFunctions(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF [inherited]	// Opaque.variantOptionalityTuples(x:)
-// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction13ConcreteTupleCACycfc [override]	// ConcreteTuple.init()
+// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction13ConcreteTupleC8inAndOut1xAA1SV_AGtAG_AGt_tFAA6OpaqueCAdExx_tFTV [override] // vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteTuple.inAndOut(x:)
+// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGeneric1x1yqd__x_qd__tlF [inherited] // Opaque.inAndOutGeneric<A>(x:y:)
+// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypes1xxmxm_tF [inherited] // Opaque.inAndOutMetatypes(x:)
+// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctions1xxxcxxc_tF [inherited] // Opaque.inAndOutFunctions(x:)
+// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuples1xx_xm_xxcttx_xm_xxctt_tF [inherited]     // Opaque.inAndOutTuples(x:)
+// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction13ConcreteTupleC18variantOptionality1xAA1SV_AGtAG_AGtSg_tFAA6OpaqueCAdExSgx_tFTV [override]       // vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteTuple.variantOptionality(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypes1xxmSgxm_tF [inherited]  // Opaque.variantOptionalityMetatypes(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctions1xxxcSgxxc_tF [inherited]        // Opaque.variantOptionalityFunctions(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuples1xx_xm_xxcttSgx_xm_xxctt_tF [inherited]      // Opaque.variantOptionalityTuples(x:)
+// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction13ConcreteTupleCACycfc [override]       // ConcreteTuple.init()
 
 // Optionality change of tuple.
 
-// CHECK-NEXT:   #ConcreteTuple.variantOptionality!1: (ConcreteTuple) -> ((S, S)?) -> (S, S) : _T027vtable_thunks_reabstraction13ConcreteTupleC18variantOptionalityAA1SV_AFtAF_AFtSg1x_tF	// ConcreteTuple.variantOptionality(x:)
+// CHECK-NEXT:   #ConcreteTuple.variantOptionality!1: (ConcreteTuple) -> ((S, S)?) -> (S, S) : _T027vtable_thunks_reabstraction13ConcreteTupleC18variantOptionality1xAA1SV_AGtAG_AGtSg_tF      // ConcreteTuple.variantOptionality(x:)
 
-// CHECK-NEXT:   #ConcreteTuple.deinit!deallocator: _T027vtable_thunks_reabstraction13ConcreteTupleCfD	// ConcreteTuple.__deallocating_deinit
+// CHECK-NEXT:   #ConcreteTuple.deinit!deallocator: _T027vtable_thunks_reabstraction13ConcreteTupleCfD // ConcreteTuple.__deallocating_deinit
 // CHECK-NEXT: }
 
 class OpaqueFunction<U, V>: Opaque<(U) -> V> {
@@ -345,22 +345,22 @@
 }
 
 // CHECK-LABEL: sil_vtable OpaqueFunction {
-// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction14OpaqueFunctionC8inAndOutq_xcq_xc1x_tFAA0D0CADxxAE_tFTV [override]	// vtable thunk for Opaque.inAndOut(x:) dispatching to OpaqueFunction.inAndOut(x:)
-// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF [inherited]	// Opaque.inAndOutGeneric<A>(x:y:)
-// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF [inherited]	// Opaque.inAndOutMetatypes(x:)
-// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF [inherited]	// Opaque.inAndOutFunctions(x:)
-// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF [inherited]	// Opaque.inAndOutTuples(x:)
-// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction14OpaqueFunctionC18variantOptionalityq_xcq_xcSg1x_tFAA0D0CADxSgxAF_tFTV [override]	// vtable thunk for Opaque.variantOptionality(x:) dispatching to OpaqueFunction.variantOptionality(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF [inherited]	// Opaque.variantOptionalityMetatypes(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF [inherited]	// Opaque.variantOptionalityFunctions(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF [inherited]	// Opaque.variantOptionalityTuples(x:)
-// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction14OpaqueFunctionCACyxq_Gycfc [override]	// OpaqueFunction.init()
+// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction14OpaqueFunctionC8inAndOut1xq_xcq_xc_tFAA0D0CAdExx_tFTV [override]   // vtable thunk for Opaque.inAndOut(x:) dispatching to OpaqueFunction.inAndOut(x:)
+// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGeneric1x1yqd__x_qd__tlF [inherited] // Opaque.inAndOutGeneric<A>(x:y:)
+// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypes1xxmxm_tF [inherited] // Opaque.inAndOutMetatypes(x:)
+// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctions1xxxcxxc_tF [inherited] // Opaque.inAndOutFunctions(x:)
+// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuples1xx_xm_xxcttx_xm_xxctt_tF [inherited]     // Opaque.inAndOutTuples(x:)
+// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction14OpaqueFunctionC18variantOptionality1xq_xcq_xcSg_tFAA0D0CAdExSgx_tFTV [override] // vtable thunk for Opaque.variantOptionality(x:) dispatching to OpaqueFunction.variantOptionality(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypes1xxmSgxm_tF [inherited]  // Opaque.variantOptionalityMetatypes(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctions1xxxcSgxxc_tF [inherited]        // Opaque.variantOptionalityFunctions(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuples1xx_xm_xxcttSgx_xm_xxctt_tF [inherited]      // Opaque.variantOptionalityTuples(x:)
+// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction14OpaqueFunctionCACyxq_Gycfc [override] // OpaqueFunction.init()
 
 // Optionality change of function.
 
-// CHECK-NEXT:  #OpaqueFunction.variantOptionality!1: <U, V> (OpaqueFunction<U, V>) -> (((U) -> V)?) -> (U) -> V : _T027vtable_thunks_reabstraction14OpaqueFunctionC18variantOptionalityq_xcq_xcSg1x_tF	// OpaqueFunction.variantOptionality(x:)
+// CHECK-NEXT:   #OpaqueFunction.variantOptionality!1: <U, V> (OpaqueFunction<U, V>) -> (((U) -> V)?) -> (U) -> V : _T027vtable_thunks_reabstraction14OpaqueFunctionC18variantOptionality1xq_xcq_xcSg_tF       // OpaqueFunction.variantOptionality(x:)
 
-// CHECK-NEXT:   #OpaqueFunction.deinit!deallocator: _T027vtable_thunks_reabstraction14OpaqueFunctionCfD	// OpaqueFunction.__deallocating_deinit
+// CHECK-NEXT:   #OpaqueFunction.deinit!deallocator: _T027vtable_thunks_reabstraction14OpaqueFunctionCfD       // OpaqueFunction.__deallocating_deinit
 // CHECK-NEXT: }
 
 class ConcreteFunction: Opaque<(S) -> S> {
@@ -369,22 +369,22 @@
 }
 
 // CHECK-LABEL: sil_vtable ConcreteFunction {
-// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction16ConcreteFunctionC8inAndOutAA1SVAFcA2Fc1x_tFAA6OpaqueCADxxAG_tFTV [override]	// vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteFunction.inAndOut(x:)
-// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF [inherited]	// Opaque.inAndOutGeneric<A>(x:y:)
-// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF [inherited]	// Opaque.inAndOutMetatypes(x:)
-// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF [inherited]	// Opaque.inAndOutFunctions(x:)
-// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF [inherited]	// Opaque.inAndOutTuples(x:)
-// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction16ConcreteFunctionC18variantOptionalityAA1SVAFcA2FcSg1x_tFAA6OpaqueCADxSgxAH_tFTV [override]	// vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteFunction.variantOptionality(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF [inherited]	// Opaque.variantOptionalityMetatypes(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF [inherited]	// Opaque.variantOptionalityFunctions(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF [inherited]	// Opaque.variantOptionalityTuples(x:)
-// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction16ConcreteFunctionCACycfc [override]	// ConcreteFunction.init()
+// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction16ConcreteFunctionC8inAndOut1xAA1SVAGcA2Gc_tFAA6OpaqueCAdExx_tFTV [override] // vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteFunction.inAndOut(x:)
+// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGeneric1x1yqd__x_qd__tlF [inherited] // Opaque.inAndOutGeneric<A>(x:y:)
+// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypes1xxmxm_tF [inherited] // Opaque.inAndOutMetatypes(x:)
+// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctions1xxxcxxc_tF [inherited] // Opaque.inAndOutFunctions(x:)
+// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuples1xx_xm_xxcttx_xm_xxctt_tF [inherited]     // Opaque.inAndOutTuples(x:)
+// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction16ConcreteFunctionC18variantOptionality1xAA1SVAGcA2GcSg_tFAA6OpaqueCAdExSgx_tFTV [override]       // vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteFunction.variantOptionality(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypes1xxmSgxm_tF [inherited]  // Opaque.variantOptionalityMetatypes(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctions1xxxcSgxxc_tF [inherited]        // Opaque.variantOptionalityFunctions(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuples1xx_xm_xxcttSgx_xm_xxctt_tF [inherited]      // Opaque.variantOptionalityTuples(x:)
+// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction16ConcreteFunctionCACycfc [override]    // ConcreteFunction.init()
 
 // Optionality change of function.
 
-// CHECK-NEXT:   #ConcreteFunction.variantOptionality!1: (ConcreteFunction) -> (((S) -> S)?) -> (S) -> S : _T027vtable_thunks_reabstraction16ConcreteFunctionC18variantOptionalityAA1SVAFcA2FcSg1x_tF	// ConcreteFunction.variantOptionality(x:)
+// CHECK-NEXT:   #ConcreteFunction.variantOptionality!1: (ConcreteFunction) -> (((S) -> S)?) -> (S) -> S : _T027vtable_thunks_reabstraction16ConcreteFunctionC18variantOptionality1xAA1SVAGcA2GcSg_tF  // ConcreteFunction.variantOptionality(x:)
 
-// CHECK-NEXT:   #ConcreteFunction.deinit!deallocator: _T027vtable_thunks_reabstraction16ConcreteFunctionCfD	// ConcreteFunction.__deallocating_deinit
+// CHECK-NEXT:   #ConcreteFunction.deinit!deallocator: _T027vtable_thunks_reabstraction16ConcreteFunctionCfD   // ConcreteFunction.__deallocating_deinit
 // CHECK-NEXT: }
 
 class OpaqueMetatype<U>: Opaque<U.Type> {
@@ -393,22 +393,22 @@
 }
 
 // CHECK-LABEL: sil_vtable OpaqueMetatype {
-// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction14OpaqueMetatypeC8inAndOutxmxm1x_tFAA0D0CADxxAE_tFTV [override]	// vtable thunk for Opaque.inAndOut(x:) dispatching to OpaqueMetatype.inAndOut(x:)
-// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF [inherited]	// Opaque.inAndOutGeneric<A>(x:y:)
-// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF [inherited]	// Opaque.inAndOutMetatypes(x:)
-// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF [inherited]	// Opaque.inAndOutFunctions(x:)
-// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF [inherited]	// Opaque.inAndOutTuples(x:)
-// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction14OpaqueMetatypeC18variantOptionalityxmxmSg1x_tFAA0D0CADxSgxAF_tFTV [override]	// vtable thunk for Opaque.variantOptionality(x:) dispatching to OpaqueMetatype.variantOptionality(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF [inherited]	// Opaque.variantOptionalityMetatypes(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF [inherited]	// Opaque.variantOptionalityFunctions(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF [inherited]	// Opaque.variantOptionalityTuples(x:)
-// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction14OpaqueMetatypeCACyxGycfc [override]	// OpaqueMetatype.init()
+// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction14OpaqueMetatypeC8inAndOut1xxmxm_tFAA0D0CAdExx_tFTV [override]       // vtable thunk for Opaque.inAndOut(x:) dispatching to OpaqueMetatype.inAndOut(x:)
+// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGeneric1x1yqd__x_qd__tlF [inherited] // Opaque.inAndOutGeneric<A>(x:y:)
+// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypes1xxmxm_tF [inherited] // Opaque.inAndOutMetatypes(x:)
+// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctions1xxxcxxc_tF [inherited] // Opaque.inAndOutFunctions(x:)
+// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuples1xx_xm_xxcttx_xm_xxctt_tF [inherited]     // Opaque.inAndOutTuples(x:)
+// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction14OpaqueMetatypeC18variantOptionality1xxmxmSg_tFAA0D0CAdExSgx_tFTV [override]     // vtable thunk for Opaque.variantOptionality(x:) dispatching to OpaqueMetatype.variantOptionality(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypes1xxmSgxm_tF [inherited]  // Opaque.variantOptionalityMetatypes(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctions1xxxcSgxxc_tF [inherited]        // Opaque.variantOptionalityFunctions(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuples1xx_xm_xxcttSgx_xm_xxctt_tF [inherited]      // Opaque.variantOptionalityTuples(x:)
+// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction14OpaqueMetatypeCACyxGycfc [override]   // OpaqueMetatype.init()
 
 // Optionality change of metatype.
 
-// CHECK-NEXT:   #OpaqueMetatype.variantOptionality!1: <U> (OpaqueMetatype<U>) -> (U.Type?) -> U.Type : _T027vtable_thunks_reabstraction14OpaqueMetatypeC18variantOptionalityxmxmSg1x_tF	// OpaqueMetatype.variantOptionality(x:)
+// CHECK-NEXT:   #OpaqueMetatype.variantOptionality!1: <U> (OpaqueMetatype<U>) -> (U.Type?) -> U.Type : _T027vtable_thunks_reabstraction14OpaqueMetatypeC18variantOptionality1xxmxmSg_tF       // OpaqueMetatype.variantOptionality(x:)
 
-// CHECK-NEXT:   #OpaqueMetatype.deinit!deallocator: _T027vtable_thunks_reabstraction14OpaqueMetatypeCfD	// OpaqueMetatype.__deallocating_deinit
+// CHECK-NEXT:   #OpaqueMetatype.deinit!deallocator: _T027vtable_thunks_reabstraction14OpaqueMetatypeCfD       // OpaqueMetatype.__deallocating_deinit
 // CHECK-NEXT: }
 
 class ConcreteValueMetatype: Opaque<S.Type> {
@@ -417,22 +417,22 @@
 }
 
 // CHECK-LABEL: sil_vtable ConcreteValueMetatype {
-// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction21ConcreteValueMetatypeC8inAndOutAA1SVmAFm1x_tFAA6OpaqueCADxxAG_tFTV [override]	// vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteValueMetatype.inAndOut(x:)
-// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF [inherited]	// Opaque.inAndOutGeneric<A>(x:y:)
-// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF [inherited]	// Opaque.inAndOutMetatypes(x:)
-// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF [inherited]	// Opaque.inAndOutFunctions(x:)
-// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF [inherited]	// Opaque.inAndOutTuples(x:)
-// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction21ConcreteValueMetatypeC18variantOptionalityAA1SVmAFmSg1x_tFAA6OpaqueCADxSgxAH_tFTV [override]	// vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteValueMetatype.variantOptionality(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF [inherited]	// Opaque.variantOptionalityMetatypes(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF [inherited]	// Opaque.variantOptionalityFunctions(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF [inherited]	// Opaque.variantOptionalityTuples(x:)
-// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction21ConcreteValueMetatypeCACycfc [override]	// ConcreteValueMetatype.init()
+// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction21ConcreteValueMetatypeC8inAndOut1xAA1SVmAGm_tFAA6OpaqueCAdExx_tFTV [override]       // vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteValueMetatype.inAndOut(x:)
+// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGeneric1x1yqd__x_qd__tlF [inherited] // Opaque.inAndOutGeneric<A>(x:y:)
+// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypes1xxmxm_tF [inherited] // Opaque.inAndOutMetatypes(x:)
+// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctions1xxxcxxc_tF [inherited] // Opaque.inAndOutFunctions(x:)
+// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuples1xx_xm_xxcttx_xm_xxctt_tF [inherited]     // Opaque.inAndOutTuples(x:)
+// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction21ConcreteValueMetatypeC18variantOptionality1xAA1SVmAGmSg_tFAA6OpaqueCAdExSgx_tFTV [override]     // vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteValueMetatype.variantOptionality(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypes1xxmSgxm_tF [inherited]  // Opaque.variantOptionalityMetatypes(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctions1xxxcSgxxc_tF [inherited]        // Opaque.variantOptionalityFunctions(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuples1xx_xm_xxcttSgx_xm_xxctt_tF [inherited]      // Opaque.variantOptionalityTuples(x:)
+// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction21ConcreteValueMetatypeCACycfc [override]       // ConcreteValueMetatype.init()
 
 // Optionality change of metatype.
 
-// CHECK-NEXT:   #ConcreteValueMetatype.variantOptionality!1: (ConcreteValueMetatype) -> (S.Type?) -> S.Type : _T027vtable_thunks_reabstraction21ConcreteValueMetatypeC18variantOptionalityAA1SVmAFmSg1x_tF	// ConcreteValueMetatype.variantOptionality(x:)
+// CHECK-NEXT:   #ConcreteValueMetatype.variantOptionality!1: (ConcreteValueMetatype) -> (S.Type?) -> S.Type : _T027vtable_thunks_reabstraction21ConcreteValueMetatypeC18variantOptionality1xAA1SVmAGmSg_tF    // ConcreteValueMetatype.variantOptionality(x:)
 
-// CHECK-NEXT:   #ConcreteValueMetatype.deinit!deallocator: _T027vtable_thunks_reabstraction21ConcreteValueMetatypeCfD	// ConcreteValueMetatype.__deallocating_deinit
+// CHECK-NEXT:   #ConcreteValueMetatype.deinit!deallocator: _T027vtable_thunks_reabstraction21ConcreteValueMetatypeCfD // ConcreteValueMetatype.__deallocating_deinit
 // CHECK-NEXT: }
 
 class ConcreteClassMetatype: Opaque<C.Type> {
@@ -441,20 +441,20 @@
 }
 
 // CHECK-LABEL: sil_vtable ConcreteClassMetatype {
-// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction21ConcreteClassMetatypeC8inAndOutAA1CCmAFm1x_tFAA6OpaqueCADxxAG_tFTV [override]	// vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteClassMetatype.inAndOut(x:)
-// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF [inherited]	// Opaque.inAndOutGeneric<A>(x:y:)
-// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF [inherited]	// Opaque.inAndOutMetatypes(x:)
-// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF [inherited]	// Opaque.inAndOutFunctions(x:)
-// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF [inherited]	// Opaque.inAndOutTuples(x:)
-// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction21ConcreteClassMetatypeC18variantOptionalityAA1CCmAFmSg1x_tFAA6OpaqueCADxSgxAH_tFTV [override]	// vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteClassMetatype.variantOptionality(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF [inherited]	// Opaque.variantOptionalityMetatypes(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF [inherited]	// Opaque.variantOptionalityFunctions(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF [inherited]	// Opaque.variantOptionalityTuples(x:)
-// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction21ConcreteClassMetatypeCACycfc [override]	// ConcreteClassMetatype.init()
+// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction21ConcreteClassMetatypeC8inAndOut1xAA1CCmAGm_tFAA6OpaqueCAdExx_tFTV [override]       // vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteClassMetatype.inAndOut(x:)
+// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGeneric1x1yqd__x_qd__tlF [inherited] // Opaque.inAndOutGeneric<A>(x:y:)
+// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypes1xxmxm_tF [inherited] // Opaque.inAndOutMetatypes(x:)
+// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctions1xxxcxxc_tF [inherited] // Opaque.inAndOutFunctions(x:)
+// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuples1xx_xm_xxcttx_xm_xxctt_tF [inherited]     // Opaque.inAndOutTuples(x:)
+// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : hidden _T027vtable_thunks_reabstraction21ConcreteClassMetatypeC18variantOptionality1xAA1CCmAGmSg_tFAA6OpaqueCAdExSgx_tFTV [override]     // vtable thunk for Opaque.variantOptionality(x:) dispatching to ConcreteClassMetatype.variantOptionality(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypes1xxmSgxm_tF [inherited]  // Opaque.variantOptionalityMetatypes(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctions1xxxcSgxxc_tF [inherited]        // Opaque.variantOptionalityFunctions(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuples1xx_xm_xxcttSgx_xm_xxctt_tF [inherited]      // Opaque.variantOptionalityTuples(x:)
+// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction21ConcreteClassMetatypeCACycfc [override]       // ConcreteClassMetatype.init()
 
 // Class metatypes are ABI compatible with optional class metatypes.
 
-// CHECK-NEXT:   #ConcreteClassMetatype.deinit!deallocator: _T027vtable_thunks_reabstraction21ConcreteClassMetatypeCfD	// ConcreteClassMetatype.__deallocating_deinit
+// CHECK-NEXT:   #ConcreteClassMetatype.deinit!deallocator: _T027vtable_thunks_reabstraction21ConcreteClassMetatypeCfD // ConcreteClassMetatype.__deallocating_deinit
 // CHECK-NEXT: }
 
 class ConcreteOptional: Opaque<S?> {
@@ -465,17 +465,17 @@
 }
 
 // CHECK-LABEL: sil_vtable ConcreteOptional {
-// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction16ConcreteOptionalC8inAndOutAA1SVSgAG1x_tFAA6OpaqueCADxxAH_tFTV [override]	// vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteOptional.inAndOut(x:)
-// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGenericqd__x1x_qd__1ytlF [inherited]	// Opaque.inAndOutGeneric<A>(x:y:)
-// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypesxmxm1x_tF [inherited]	// Opaque.inAndOutMetatypes(x:)
-// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctionsxxcxxc1x_tF [inherited]	// Opaque.inAndOutFunctions(x:)
-// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuplesx_xm_xxcttx_xm_xxctt1x_tF [inherited]	// Opaque.inAndOutTuples(x:)
-// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : _T027vtable_thunks_reabstraction6OpaqueC18variantOptionalityxSgx1x_tF [inherited]	// Opaque.variantOptionality(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypesxmSgxm1x_tF [inherited]	// Opaque.variantOptionalityMetatypes(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctionsxxcSgxxc1x_tF [inherited]	// Opaque.variantOptionalityFunctions(x:)
-// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuplesx_xm_xxcttSgx_xm_xxctt1x_tF [inherited]	// Opaque.variantOptionalityTuples(x:)
-// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction16ConcreteOptionalCACycfc [override]	// ConcreteOptional.init()
-// CHECK-NEXT:   #ConcreteOptional.deinit!deallocator: _T027vtable_thunks_reabstraction16ConcreteOptionalCfD	// ConcreteOptional.__deallocating_deinit
+// CHECK-NEXT:   #Opaque.inAndOut!1: <T> (Opaque<T>) -> (T) -> T : hidden _T027vtable_thunks_reabstraction16ConcreteOptionalC8inAndOut1xAA1SVSgAH_tFAA6OpaqueCAdExx_tFTV [override]    // vtable thunk for Opaque.inAndOut(x:) dispatching to ConcreteOptional.inAndOut(x:)
+// CHECK-NEXT:   #Opaque.inAndOutGeneric!1: <T><U> (Opaque<T>) -> (T, U) -> U : _T027vtable_thunks_reabstraction6OpaqueC15inAndOutGeneric1x1yqd__x_qd__tlF [inherited] // Opaque.inAndOutGeneric<A>(x:y:)
+// CHECK-NEXT:   #Opaque.inAndOutMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutMetatypes1xxmxm_tF [inherited] // Opaque.inAndOutMetatypes(x:)
+// CHECK-NEXT:   #Opaque.inAndOutFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> (T) -> T : _T027vtable_thunks_reabstraction6OpaqueC17inAndOutFunctions1xxxcxxc_tF [inherited] // Opaque.inAndOutFunctions(x:)
+// CHECK-NEXT:   #Opaque.inAndOutTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T)) : _T027vtable_thunks_reabstraction6OpaqueC14inAndOutTuples1xx_xm_xxcttx_xm_xxctt_tF [inherited]     // Opaque.inAndOutTuples(x:)
+// CHECK-NEXT:   #Opaque.variantOptionality!1: <T> (Opaque<T>) -> (T) -> T? : _T027vtable_thunks_reabstraction6OpaqueC18variantOptionality1xxSgx_tF [inherited]        // Opaque.variantOptionality(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityMetatypes!1: <T> (Opaque<T>) -> (T.Type) -> T.Type? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityMetatypes1xxmSgxm_tF [inherited]  // Opaque.variantOptionalityMetatypes(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityFunctions!1: <T> (Opaque<T>) -> (@escaping (T) -> T) -> ((T) -> T)? : _T027vtable_thunks_reabstraction6OpaqueC27variantOptionalityFunctions1xxxcSgxxc_tF [inherited]        // Opaque.variantOptionalityFunctions(x:)
+// CHECK-NEXT:   #Opaque.variantOptionalityTuples!1: <T> (Opaque<T>) -> ((T, (T.Type, (T) -> T))) -> (T, (T.Type, (T) -> T))? : _T027vtable_thunks_reabstraction6OpaqueC24variantOptionalityTuples1xx_xm_xxcttSgx_xm_xxctt_tF [inherited]      // Opaque.variantOptionalityTuples(x:)
+// CHECK-NEXT:   #Opaque.init!initializer.1: <T> (Opaque<T>.Type) -> () -> Opaque<T> : _T027vtable_thunks_reabstraction16ConcreteOptionalCACycfc [override]    // ConcreteOptional.init()
+// CHECK-NEXT:   #ConcreteOptional.deinit!deallocator: _T027vtable_thunks_reabstraction16ConcreteOptionalCfD   // ConcreteOptional.__deallocating_deinit
 // CHECK-NEXT: }
 
 // Make sure we remap the method's innermost generic parameters
@@ -486,9 +486,9 @@
 }
 
 // CHECK-LABEL: sil_vtable GenericBase {
-// CHECK-NEXT:   #GenericBase.doStuff!1: <T><U> (GenericBase<T>) -> (T, U) -> () : _T027vtable_thunks_reabstraction11GenericBaseC7doStuffyx1t_qd__1utlF	// GenericBase.doStuff<A>(t:u:)
-// CHECK-NEXT:   #GenericBase.init!initializer.1: <T><U> (GenericBase<T>.Type) -> (T, U) -> GenericBase<T> : _T027vtable_thunks_reabstraction11GenericBaseCACyxGx1t_qd__1utclufc	// GenericBase.init<A>(t:u:)
-// CHECK-NEXT:   #GenericBase.deinit!deallocator: _T027vtable_thunks_reabstraction11GenericBaseCfD	// GenericBase.__deallocating_deinit
+// CHECK-NEXT:   #GenericBase.doStuff!1: <T><U> (GenericBase<T>) -> (T, U) -> () : _T027vtable_thunks_reabstraction11GenericBaseC7doStuff1t1uyx_qd__tlF        // GenericBase.doStuff<A>(t:u:)
+// CHECK-NEXT:   #GenericBase.init!initializer.1: <T><U> (GenericBase<T>.Type) -> (T, U) -> GenericBase<T> : _T027vtable_thunks_reabstraction11GenericBaseC1t1uACyxGx_qd__tclufc       // GenericBase.init<A>(t:u:)
+// CHECK-NEXT:   #GenericBase.deinit!deallocator: _T027vtable_thunks_reabstraction11GenericBaseCfD     // GenericBase.__deallocating_deinit
 // CHECK-NEXT: }
 
 class ConcreteSub : GenericBase<Int> {
@@ -501,9 +501,9 @@
 }
 
 // CHECK-LABEL: sil_vtable ConcreteSub {
-// CHECK-NEXT:   #GenericBase.doStuff!1: <T><U> (GenericBase<T>) -> (T, U) -> () : hidden _T027vtable_thunks_reabstraction11ConcreteSubC7doStuffySi1t_x1utlFAA11GenericBaseCADyxAE_qd__AFtlFTV [override]	// vtable thunk for GenericBase.doStuff<A>(t:u:) dispatching to ConcreteSub.doStuff<A>(t:u:)
-// CHECK-NEXT:   #GenericBase.init!initializer.1: <T><U> (GenericBase<T>.Type) -> (T, U) -> GenericBase<T> : hidden _T027vtable_thunks_reabstraction11ConcreteSubCACSi1t_x1utclufcAA11GenericBaseCAGyxGxAD_qd__AEtclufcTV [override]	// vtable thunk for GenericBase.init<A>(t:u:) dispatching to ConcreteSub.init<A>(t:u:)
-// CHECK-NEXT:   #ConcreteSub.deinit!deallocator: _T027vtable_thunks_reabstraction11ConcreteSubCfD	// ConcreteSub.__deallocating_deinit
+// CHECK-NEXT:   #GenericBase.doStuff!1: <T><U> (GenericBase<T>) -> (T, U) -> () : hidden _T027vtable_thunks_reabstraction11ConcreteSubC7doStuff1t1uySi_xtlFAA11GenericBaseCAdeFyx_qd__tlFTV [override]        // vtable thunk for GenericBase.doStuff<A>(t:u:) dispatching to ConcreteSub.doStuff<A>(t:u:)
+// CHECK-NEXT:   #GenericBase.init!initializer.1: <T><U> (GenericBase<T>.Type) -> (T, U) -> GenericBase<T> : hidden _T027vtable_thunks_reabstraction11ConcreteSubC1t1uACSi_xtclufcAA11GenericBaseCAdeGyxGx_qd__tclufcTV [override]     // vtable thunk for GenericBase.init<A>(t:u:) dispatching to ConcreteSub.init<A>(t:u:)
+// CHECK-NEXT:   #ConcreteSub.deinit!deallocator: _T027vtable_thunks_reabstraction11ConcreteSubCfD     // ConcreteSub.__deallocating_deinit
 // CHECK-NEXT: }
 
 class ConcreteBase {
@@ -512,9 +512,9 @@
 }
 
 // CHECK-LABEL: sil_vtable ConcreteBase {
-// CHECK-NEXT:   #ConcreteBase.init!initializer.1: <U> (ConcreteBase.Type) -> (Int, U) -> ConcreteBase : _T027vtable_thunks_reabstraction12ConcreteBaseCACSi1t_x1utclufc	// ConcreteBase.init<A>(t:u:)
-// CHECK-NEXT:   #ConcreteBase.doStuff!1: <U> (ConcreteBase) -> (Int, U) -> () : _T027vtable_thunks_reabstraction12ConcreteBaseC7doStuffySi1t_x1utlF	// ConcreteBase.doStuff<A>(t:u:)
-// CHECK-NEXT:   #ConcreteBase.deinit!deallocator: _T027vtable_thunks_reabstraction12ConcreteBaseCfD	// ConcreteBase.__deallocating_deinit
+// CHECK-NEXT:   #ConcreteBase.init!initializer.1: <U> (ConcreteBase.Type) -> (Int, U) -> ConcreteBase : _T027vtable_thunks_reabstraction12ConcreteBaseC1t1uACSi_xtclufc       // ConcreteBase.init<A>(t:u:)
+// CHECK-NEXT:   #ConcreteBase.doStuff!1: <U> (ConcreteBase) -> (Int, U) -> () : _T027vtable_thunks_reabstraction12ConcreteBaseC7doStuff1t1uySi_xtlF   // ConcreteBase.doStuff<A>(t:u:)
+// CHECK-NEXT:   #ConcreteBase.deinit!deallocator: _T027vtable_thunks_reabstraction12ConcreteBaseCfD   // ConcreteBase.__deallocating_deinit
 // CHECK-NEXT: }
 
 class GenericSub<T> : ConcreteBase {
@@ -527,9 +527,9 @@
 }
 
 // CHECK-LABEL: sil_vtable GenericSub {
-// CHECK-NEXT:   #ConcreteBase.init!initializer.1: <U> (ConcreteBase.Type) -> (Int, U) -> ConcreteBase : _T027vtable_thunks_reabstraction10GenericSubCACyxGSi1t_qd__1utclufc [override]	// GenericSub.init<A>(t:u:)
-// CHECK-NEXT:   #ConcreteBase.doStuff!1: <U> (ConcreteBase) -> (Int, U) -> () : _T027vtable_thunks_reabstraction10GenericSubC7doStuffySi1t_qd__1utlF [override]	// GenericSub.doStuff<A>(t:u:)
-// CHECK-NEXT:   #GenericSub.deinit!deallocator: _T027vtable_thunks_reabstraction10GenericSubCfD	// GenericSub.__deallocating_deinit
+// CHECK-NEXT:   #ConcreteBase.init!initializer.1: <U> (ConcreteBase.Type) -> (Int, U) -> ConcreteBase : _T027vtable_thunks_reabstraction10GenericSubC1t1uACyxGSi_qd__tclufc [override]        // GenericSub.init<A>(t:u:)
+// CHECK-NEXT:   #ConcreteBase.doStuff!1: <U> (ConcreteBase) -> (Int, U) -> () : _T027vtable_thunks_reabstraction10GenericSubC7doStuff1t1uySi_qd__tlF [override]       // GenericSub.doStuff<A>(t:u:)
+// CHECK-NEXT:   #GenericSub.deinit!deallocator: _T027vtable_thunks_reabstraction10GenericSubCfD       // GenericSub.__deallocating_deinit
 // CHECK-NEXT: }
 
 // Issue with generic parameter index
@@ -540,9 +540,9 @@
 }
 
 // CHECK-LABEL: sil_vtable MoreGenericSub1 {
-// CHECK-NEXT:   #GenericBase.doStuff!1: <T><U> (GenericBase<T>) -> (T, U) -> () : _T027vtable_thunks_reabstraction15MoreGenericSub1C7doStuffyx1t_qd__1utlF [override]	// MoreGenericSub1.doStuff<A>(t:u:)
-// CHECK-NEXT:   #GenericBase.init!initializer.1: <T><U> (GenericBase<T>.Type) -> (T, U) -> GenericBase<T> : _T027vtable_thunks_reabstraction11GenericBaseCACyxGx1t_qd__1utclufc [inherited]	// GenericBase.init<A>(t:u:)
-// CHECK-NEXT:   #MoreGenericSub1.deinit!deallocator: _T027vtable_thunks_reabstraction15MoreGenericSub1CfD	// MoreGenericSub1.__deallocating_deinit
+// CHECK-NEXT:   #GenericBase.doStuff!1: <T><U> (GenericBase<T>) -> (T, U) -> () : _T027vtable_thunks_reabstraction15MoreGenericSub1C7doStuff1t1uyx_qd__tlF [override] // MoreGenericSub1.doStuff<A>(t:u:)
+// CHECK-NEXT:   #GenericBase.init!initializer.1: <T><U> (GenericBase<T>.Type) -> (T, U) -> GenericBase<T> : _T027vtable_thunks_reabstraction11GenericBaseC1t1uACyxGx_qd__tclufc [inherited]   // GenericBase.init<A>(t:u:)
+// CHECK-NEXT:   #MoreGenericSub1.deinit!deallocator: _T027vtable_thunks_reabstraction15MoreGenericSub1CfD     // MoreGenericSub1.__deallocating_deinit
 // CHECK-NEXT: }
 
 class MoreGenericSub2<TT, T> : GenericBase<T> {
@@ -552,7 +552,7 @@
 }
 
 // CHECK-LABEL: sil_vtable MoreGenericSub2 {
-// CHECK-NEXT:   #GenericBase.doStuff!1: <T><U> (GenericBase<T>) -> (T, U) -> () : _T027vtable_thunks_reabstraction15MoreGenericSub2C7doStuffyq_1t_qd__1utlF [override]	// MoreGenericSub2.doStuff<A>(t:u:)
-// CHECK-NEXT:   #GenericBase.init!initializer.1: <T><U> (GenericBase<T>.Type) -> (T, U) -> GenericBase<T> : _T027vtable_thunks_reabstraction11GenericBaseCACyxGx1t_qd__1utclufc [inherited]	// GenericBase.init<A>(t:u:)
-// CHECK-NEXT:   #MoreGenericSub2.deinit!deallocator: _T027vtable_thunks_reabstraction15MoreGenericSub2CfD	// MoreGenericSub2.__deallocating_deinit
+// CHECK-NEXT:   #GenericBase.doStuff!1: <T><U> (GenericBase<T>) -> (T, U) -> () : _T027vtable_thunks_reabstraction15MoreGenericSub2C7doStuff1t1uyq__qd__tlF [override]        // MoreGenericSub2.doStuff<A>(t:u:)
+// CHECK-NEXT:   #GenericBase.init!initializer.1: <T><U> (GenericBase<T>.Type) -> (T, U) -> GenericBase<T> : _T027vtable_thunks_reabstraction11GenericBaseC1t1uACyxGx_qd__tclufc [inherited]   // GenericBase.init<A>(t:u:)
+// CHECK-NEXT:   #MoreGenericSub2.deinit!deallocator: _T027vtable_thunks_reabstraction15MoreGenericSub2CfD     // MoreGenericSub2.__deallocating_deinit
 // CHECK-NEXT: }
diff --git a/test/SILGen/vtable_thunks_reabstraction_final.swift b/test/SILGen/vtable_thunks_reabstraction_final.swift
index 5431bfd..0efe62c 100644
--- a/test/SILGen/vtable_thunks_reabstraction_final.swift
+++ b/test/SILGen/vtable_thunks_reabstraction_final.swift
@@ -30,7 +30,7 @@
   }
 }
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T033vtable_thunks_reabstraction_final10GenericSubCyxGAA8BarrableA2aEP3foo3BarQzSgAIFTW
+// CHECK-LABEL: sil private [transparent] [thunk] @_T033vtable_thunks_reabstraction_final10GenericSubCyxGAA8BarrableA2aEP3fooy3BarQzSgAIFTW
 // CHECK:         class_method {{%.*}} : $GenericSub<τ_0_0>, #GenericSub.foo!1 {{.*}}, $@convention(method) <τ_0_0 where τ_0_0 : AnyObject> (@in τ_0_0, @guaranteed GenericSub<τ_0_0>) -> @out Optional<τ_0_0>
 
 class C {}
diff --git a/test/SILGen/vtables_objc.swift b/test/SILGen/vtables_objc.swift
index b1dc2d4..bf04dcd 100644
--- a/test/SILGen/vtables_objc.swift
+++ b/test/SILGen/vtables_objc.swift
@@ -20,7 +20,7 @@
   func incorrige() {}
 }
 
-// CHECK-LABEL: sil hidden @_T012vtables_objc10callHoozityAA0D0CF : $@convention(thin) (@owned Hoozit) -> ()
+// CHECK-LABEL: sil hidden @_T012vtables_objc10callHoozityyAA0D0CF : $@convention(thin) (@owned Hoozit) -> ()
 func callHoozit(_ h: Hoozit) {
   // CHECK: objc_method {{.*}} : $Hoozit, #Hoozit.frob!1.foreign
   h.frob()
@@ -42,7 +42,7 @@
   final override func frob() {}
 }
 
-// CHECK-LABEL: sil hidden @_T012vtables_objc10callWotsityAA0D0CF : $@convention(thin) (@owned Wotsit) -> ()
+// CHECK-LABEL: sil hidden @_T012vtables_objc10callWotsityyAA0D0CF : $@convention(thin) (@owned Wotsit) -> ()
 func callWotsit(_ w: Wotsit) {
   // CHECK: objc_method {{.*}} : $Wotsit, #Wotsit.funge!1.foreign
   w.funge()
@@ -59,7 +59,7 @@
 // CHECK-NEXT:   #Hoozit.anse!1: {{.*}} : _T012vtables_objc6HoozitC4anse{{[_0-9a-zA-Z]*}}F
 // CHECK-NEXT:   #Hoozit.incorrige!1: {{.*}} : _T012vtables_objc6HoozitC9incorrige{{[_0-9a-zA-Z]*}}F
 // CHECK-NEXT:   #Hoozit.init!initializer.1: (Hoozit.Type) -> () -> Hoozit! : _T012vtables_objc6HoozitCSQyACGycfc
-// CHECK-NEXT:   #Hoozit.init!initializer.1: (Hoozit.Type) -> (Int) -> Hoozit! : _T012vtables_objc6HoozitCSQyACGSi7bellsOn_tcfc
+// CHECK-NEXT:   #Hoozit.init!initializer.1: (Hoozit.Type) -> (Int) -> Hoozit! : _T012vtables_objc6HoozitC7bellsOnSQyACGSi_tcfc
 // CHECK-NEXT:   #Hoozit.deinit!deallocator: _T012vtables_objc6HoozitCfD
 // CHECK-NEXT: }
 
@@ -67,7 +67,7 @@
 // CHECK-NEXT:   #Hoozit.anse!1: {{.*}} : _T012vtables_objc6HoozitC4anse{{[_0-9a-zA-Z]*}}F
 // CHECK-NEXT:   #Hoozit.incorrige!1: {{.*}} : _T012vtables_objc6WotsitC9incorrige{{[_0-9a-zA-Z]*}}F
 // CHECK-NEXT:   #Hoozit.init!initializer.1: (Hoozit.Type) -> () -> Hoozit! : _T012vtables_objc6WotsitCSQyACGycfc
-// CHECK-NEXT:   #Hoozit.init!initializer.1: (Hoozit.Type) -> (Int) -> Hoozit! : _T012vtables_objc6WotsitCSQyACGSi7bellsOn_tcfc
+// CHECK-NEXT:   #Hoozit.init!initializer.1: (Hoozit.Type) -> (Int) -> Hoozit! : _T012vtables_objc6WotsitC7bellsOnSQyACGSi_tcfc
 // CHECK-NEXT:   #Wotsit.deinit!deallocator: _T012vtables_objc6WotsitCfD
 // CHECK-NEXT: }
 
diff --git a/test/SILGen/weak.swift b/test/SILGen/weak.swift
index f6a243e..97d6c10 100644
--- a/test/SILGen/weak.swift
+++ b/test/SILGen/weak.swift
@@ -10,7 +10,7 @@
   weak var x: C?
 }
 
-// CHECK:    sil hidden @_T04weak5test0yAA1CC1c_tF : $@convention(thin) (@owned C) -> () {
+// CHECK:    sil hidden @_T04weak5test01cyAA1CC_tF : $@convention(thin) (@owned C) -> () {
 func test0(c c: C) {
   var c = c
 // CHECK:    bb0(%0 : @owned $C):
diff --git a/test/SILGen/weak_multiple_modules.swift b/test/SILGen/weak_multiple_modules.swift
index d95d334..64c2e5e 100644
--- a/test/SILGen/weak_multiple_modules.swift
+++ b/test/SILGen/weak_multiple_modules.swift
@@ -4,7 +4,7 @@
 
 import weak_other
 
-// CHECK-LABEL: sil hidden @_T021weak_multiple_modules11doSomethingSb0A6_other2UIC2ui_tF : $@convention(thin) (@owned UI) -> Bool
+// CHECK-LABEL: sil hidden @_T021weak_multiple_modules11doSomething2uiSb0A6_other2UIC_tF : $@convention(thin) (@owned UI) -> Bool
 func doSomething(ui: UI) -> Bool {
   // CHECK: ref_element_addr
   // CHECK-objc: load_unowned
diff --git a/test/SILGen/without_actually_escaping.swift b/test/SILGen/without_actually_escaping.swift
index 33cca12..a197586 100644
--- a/test/SILGen/without_actually_escaping.swift
+++ b/test/SILGen/without_actually_escaping.swift
@@ -2,7 +2,7 @@
 
 var escapeHatch: Any = 0
 
-// CHECK-LABEL: sil hidden @_T025without_actually_escaping9letEscapeyycyyc1f_tF
+// CHECK-LABEL: sil hidden @_T025without_actually_escaping9letEscape1fyycyyc_tF
 func letEscape(f: () -> ()) -> () -> () {
   // CHECK: bb0([[ARG:%.*]] : @owned $@noescape @callee_guaranteed () -> ()):
   // TODO: Use a canary wrapper instead of just copying the nonescaping value
diff --git a/test/SILGen/witness_accessibility.swift b/test/SILGen/witness_accessibility.swift
index 935522d..593c608 100644
--- a/test/SILGen/witness_accessibility.swift
+++ b/test/SILGen/witness_accessibility.swift
@@ -20,9 +20,9 @@
 
 public struct S : R {}
 
-// CHECK-LABEL: sil private @_T021witness_accessibility1R{{.*}}AE18privateRequirementyyF
 // CHECK-LABEL: sil private @_T021witness_accessibility1R{{.*}}E17publicRequirementyyF
 // CHECK-LABEL: sil private @_T021witness_accessibility1R{{.*}}E19internalRequirementyyF
+// CHECK-LABEL: sil private @_T021witness_accessibility1R{{.*}}AE18privateRequirementyyF
 
 // CHECK-LABEL: sil private [transparent] [thunk] @_T021witness_accessibility1SVAA1R{{.*}}dELLP18privateRequirementyyFTW
 // CHECK-LABEL: sil private [transparent] [thunk] @_T021witness_accessibility1SVAA1QA2aDP19internalRequirementyyFTW
diff --git a/test/SILGen/witness_same_type.swift b/test/SILGen/witness_same_type.swift
index 50d7c6b..6f52696 100644
--- a/test/SILGen/witness_same_type.swift
+++ b/test/SILGen/witness_same_type.swift
@@ -11,7 +11,7 @@
 
 // Ensure that the protocol witness for requirements with same-type constraints
 // is set correctly. <rdar://problem/16369105>
-// CHECK-LABEL: sil private [transparent] [thunk] @_T017witness_same_type3FooVAA7FooableA2aDP3foo3BarQzqd__1x_tAaDRd__AGQyd__AHRSlFTW : $@convention(witness_method: Fooable) <τ_0_0 where τ_0_0 : Fooable, τ_0_0.Bar == X> (@in τ_0_0, @in_guaranteed Foo) -> @out X
+// CHECK-LABEL: sil private [transparent] [thunk] @_T017witness_same_type3FooVAA7FooableA2aDP3foo1x3BarQzqd___tAaDRd__AHQyd__AIRSlFTW : $@convention(witness_method: Fooable) <τ_0_0 where τ_0_0 : Fooable, τ_0_0.Bar == X> (@in τ_0_0, @in_guaranteed Foo) -> @out X
 struct Foo: Fooable {
   typealias Bar = X
 
diff --git a/test/SILGen/witnesses.swift b/test/SILGen/witnesses.swift
index 18551e3..8697450 100644
--- a/test/SILGen/witnesses.swift
+++ b/test/SILGen/witnesses.swift
@@ -44,7 +44,7 @@
 func protocol_method(x: Existentiable) -> Loadable {
   return x.foo()
 }
-// CHECK-LABEL: sil hidden @_T09witnesses15protocol_methodAA8LoadableVAA13Existentiable_p1x_tF : $@convention(thin) (@in Existentiable) -> Loadable {
+// CHECK-LABEL: sil hidden @_T09witnesses15protocol_method1xAA8LoadableVAA13Existentiable_p_tF : $@convention(thin) (@in Existentiable) -> Loadable {
 // CHECK:         [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Existentiable]], #Existentiable.foo!1
 // CHECK:         apply [[METHOD]]<[[OPENED]]>({{%.*}})
 // CHECK:       }
@@ -52,7 +52,7 @@
 func protocol_generic_method(x: Existentiable) -> Loadable {
   return x.generic()
 }
-// CHECK-LABEL: sil hidden @_T09witnesses23protocol_generic_methodAA8LoadableVAA13Existentiable_p1x_tF : $@convention(thin) (@in Existentiable) -> Loadable {
+// CHECK-LABEL: sil hidden @_T09witnesses23protocol_generic_method1xAA8LoadableVAA13Existentiable_p_tF : $@convention(thin) (@in Existentiable) -> Loadable {
 // CHECK:         [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Existentiable]], #Existentiable.generic!1
 // CHECK:         apply [[METHOD]]<[[OPENED]], Loadable>({{%.*}}, {{%.*}})
 // CHECK:       }
@@ -61,7 +61,7 @@
   func foo()
 }
 
-// CHECK-LABEL: sil hidden @_T09witnesses20protocol_objc_methodyAA8ObjCAble_p1x_tF : $@convention(thin) (@owned ObjCAble) -> ()
+// CHECK-LABEL: sil hidden @_T09witnesses20protocol_objc_method1xyAA8ObjCAble_p_tF : $@convention(thin) (@owned ObjCAble) -> ()
 // CHECK:         objc_method {{%.*}} : $@opened({{.*}}) ObjCAble, #ObjCAble.foo!1.foreign
 func protocol_objc_method(x: ObjCAble) {
   x.foo()
@@ -156,7 +156,7 @@
 // CHECK-NEXT:    [[LOADED_ARG2:%.*]] = load [trivial] [[ARG2]] : $*ConformingStruct
 // CHECK-NEXT:    [[LOADED_ARG3:%.*]] = load [trivial] [[ARG3]] : $*ConformingStruct
 // CHECK-NEXT:    // function_ref
-// CHECK-NEXT:    [[FUNC:%.*]] = function_ref @_T09witnesses3ltgoiAA16ConformingStructVAD_ADtF : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct
+// CHECK-NEXT:    [[FUNC:%.*]] = function_ref @_T09witnesses3ltgoiyAA16ConformingStructVAD_ADtF : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct
 // CHECK-NEXT:    [[FUNC_RESULT:%.*]] = apply [[FUNC]]([[LOADED_ARG2]], [[LOADED_ARG3]]) : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct
 // CHECK-NEXT:    store [[FUNC_RESULT]] to [trivial] [[ARG1]] : $*ConformingStruct
 // CHECK-NEXT:    %9 = tuple ()
@@ -394,7 +394,7 @@
 final class IUOFailableClassModel: NonFailableClassRefinement, IUOFailableClassRequirement {
   // CHECK-LABEL: sil private [transparent] [thunk] @_T09witnesses21IUOFailableClassModelCAA011NonFailableC10Refinement{{[_0-9a-zA-Z]*}}fCTW
   // CHECK: bb0({{.*}}):
-  // CHECK:   [[FUNC:%.*]] = function_ref @_T09witnesses21IUOFailableClassModelCSQyACGSi3foo_tcfC : $@convention(method) (Int, @thick IUOFailableClassModel.Type) -> @owned Optional<IUOFailableClassModel>
+  // CHECK:   [[FUNC:%.*]] = function_ref @_T09witnesses21IUOFailableClassModelC3fooSQyACGSi_tcfC : $@convention(method) (Int, @thick IUOFailableClassModel.Type) -> @owned Optional<IUOFailableClassModel>
   // CHECK:   [[VALUE:%.*]] = apply [[FUNC]]({{.*}})
   // CHECK:   switch_enum [[VALUE]] : $Optional<IUOFailableClassModel>, case #Optional.some!enumelt.1: [[SOMEBB:bb[0-9]+]], case #Optional.none!enumelt: [[NONEBB:bb[0-9]+]]
   //
@@ -427,12 +427,12 @@
 struct GenericParameterNameCollision<T: HasAssoc> :
     GenericParameterNameCollisionProtocol {
 
-  // CHECK-LABEL: sil private [transparent] [thunk] @_T09witnesses29GenericParameterNameCollisionVyxGAA0bcdE8ProtocolA2aEP3fooyqd__lFTW : $@convention(witness_method: GenericParameterNameCollisionProtocol) <τ_0_0 where τ_0_0 : HasAssoc><τ_1_0> (@in τ_1_0, @in_guaranteed GenericParameterNameCollision<τ_0_0>) -> () {
+  // CHECK-LABEL: sil private [transparent] [thunk] @_T09witnesses29GenericParameterNameCollisionVyxGAA0bcdE8ProtocolA2aEP3fooyyqd__lFTW : $@convention(witness_method: GenericParameterNameCollisionProtocol) <τ_0_0 where τ_0_0 : HasAssoc><τ_1_0> (@in τ_1_0, @in_guaranteed GenericParameterNameCollision<τ_0_0>) -> () {
   // CHECK:       bb0(%0 : @trivial $*τ_1_0, %1 : @trivial $*GenericParameterNameCollision<τ_0_0>):
   // CHECK:         apply {{%.*}}<τ_0_0, τ_1_0>
   func foo<U>(_ x: U) {}
 
-  // CHECK-LABEL: sil private [transparent] [thunk] @_T09witnesses29GenericParameterNameCollisionVyxGAA0bcdE8ProtocolA2aEP3bary6Assoc2Qzqd__clFTW : $@convention(witness_method: GenericParameterNameCollisionProtocol) <τ_0_0 where τ_0_0 : HasAssoc><τ_1_0> (@owned @noescape @callee_guaranteed (@in τ_1_0) -> @out τ_0_0.Assoc, @in_guaranteed GenericParameterNameCollision<τ_0_0>) -> () {
+  // CHECK-LABEL: sil private [transparent] [thunk] @_T09witnesses29GenericParameterNameCollisionVyxGAA0bcdE8ProtocolA2aEP3baryy6Assoc2Qzqd__clFTW : $@convention(witness_method: GenericParameterNameCollisionProtocol) <τ_0_0 where τ_0_0 : HasAssoc><τ_1_0> (@owned @noescape @callee_guaranteed (@in τ_1_0) -> @out τ_0_0.Assoc, @in_guaranteed GenericParameterNameCollision<τ_0_0>) -> () {
   // CHECK:       bb0(%0 : @owned $@noescape @callee_guaranteed (@in τ_1_0) -> @out τ_0_0.Assoc, %1 : @trivial $*GenericParameterNameCollision<τ_0_0>):
   // CHECK:         apply {{%.*}}<τ_0_0, τ_1_0>
   func bar<V>(_ x: (V) -> T.Assoc) {}
diff --git a/test/SILGen/witnesses_class.swift b/test/SILGen/witnesses_class.swift
index c2b2dfc..f6c1a89 100644
--- a/test/SILGen/witnesses_class.swift
+++ b/test/SILGen/witnesses_class.swift
@@ -24,7 +24,7 @@
   // CHECK:         class_method
 }
 
-// CHECK-LABEL: sil hidden @_T015witnesses_class3genyxAA7FooableRzlF
+// CHECK-LABEL: sil hidden @_T015witnesses_class3genyyxAA7FooableRzlF
 // CHECK:         bb0([[SELF:%.*]] : @owned $T)
 // CHECK-NOT:     copy_value [[SELF]]
 // CHECK:         [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
@@ -39,7 +39,7 @@
   foo.foo()
 }
 
-// CHECK-LABEL: sil hidden @_T015witnesses_class2exyAA7Fooable_pF
+// CHECK-LABEL: sil hidden @_T015witnesses_class2exyyAA7Fooable_pF
 // CHECK: bb0([[SELF:%[0-0]+]] : @owned $Fooable):
 // CHECK:         [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
 // CHECK:         [[SELF_PROJ:%.*]] = open_existential_ref [[BORROWED_SELF]]
@@ -90,21 +90,21 @@
 
 // Invariant Self, since type signature contains an associated type:
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T015witnesses_class12UsesDefaultsCyxGAA03HasD0A2aEP16hasDefaultTakesTy1TQzFTW : $@convention(witness_method: HasDefaults) <τ_0_0 where τ_0_0 : Barable> (@in UsesDefaults<τ_0_0>, @in_guaranteed UsesDefaults<τ_0_0>) -> ()
-// CHECK: [[FN:%.*]] = function_ref @_T015witnesses_class11HasDefaultsPAAE16hasDefaultTakesTy1TQzF : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaults> (@in τ_0_0.T, @in_guaranteed τ_0_0) -> ()
+// CHECK-LABEL: sil private [transparent] [thunk] @_T015witnesses_class12UsesDefaultsCyxGAA03HasD0A2aEP16hasDefaultTakesTyy1TQzFTW : $@convention(witness_method: HasDefaults) <τ_0_0 where τ_0_0 : Barable> (@in UsesDefaults<τ_0_0>, @in_guaranteed UsesDefaults<τ_0_0>) -> ()
+// CHECK: [[FN:%.*]] = function_ref @_T015witnesses_class11HasDefaultsPAAE16hasDefaultTakesTyy1TQzF : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaults> (@in τ_0_0.T, @in_guaranteed τ_0_0) -> ()
 // CHECK: apply [[FN]]<UsesDefaults<τ_0_0>>(
 // CHECK: return
 
 // Covariant Self:
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T015witnesses_class12UsesDefaultsCyxGAA03HasD0A2aEP17hasDefaultGenericyqd__AA7FooableRd__lFTW : $@convention(witness_method: HasDefaults) <τ_0_0><τ_1_0 where τ_0_0 : UsesDefaults<τ_1_0>, τ_1_0 : Barable><τ_2_0 where τ_2_0 : Fooable> (@owned τ_2_0, @in_guaranteed τ_0_0) -> ()
-// CHECK: [[FN:%.*]] = function_ref @_T015witnesses_class11HasDefaultsPAAE17hasDefaultGenericyqd__AA7FooableRd__lF : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaults><τ_1_0 where τ_1_0 : Fooable> (@owned τ_1_0, @in_guaranteed τ_0_0) -> ()
+// CHECK-LABEL: sil private [transparent] [thunk] @_T015witnesses_class12UsesDefaultsCyxGAA03HasD0A2aEP17hasDefaultGenericyyqd__AA7FooableRd__lFTW : $@convention(witness_method: HasDefaults) <τ_0_0><τ_1_0 where τ_0_0 : UsesDefaults<τ_1_0>, τ_1_0 : Barable><τ_2_0 where τ_2_0 : Fooable> (@owned τ_2_0, @in_guaranteed τ_0_0) -> ()
+// CHECK: [[FN:%.*]] = function_ref @_T015witnesses_class11HasDefaultsPAAE17hasDefaultGenericyyqd__AA7FooableRd__lF : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaults><τ_1_0 where τ_1_0 : Fooable> (@owned τ_1_0, @in_guaranteed τ_0_0) -> ()
 // CHECK: apply [[FN]]<τ_0_0, τ_2_0>(
 // CHECK: return
 
 // Invariant Self, since type signature contains an associated type:
 
-// CHECK-LABEL: sil private [transparent] [thunk] @_T015witnesses_class12UsesDefaultsCyxGAA03HasD0A2aEP23hasDefaultGenericTakesTy1TQz_qd__tAA7FooableRd__lFTW : $@convention(witness_method: HasDefaults) <τ_0_0 where τ_0_0 : Barable><τ_1_0 where τ_1_0 : Fooable> (@in UsesDefaults<τ_0_0>, @owned τ_1_0, @in_guaranteed UsesDefaults<τ_0_0>) -> ()
-// CHECK: [[FN:%.*]] = function_ref @_T015witnesses_class11HasDefaultsPAAE23hasDefaultGenericTakesTy1TQz_qd__tAA7FooableRd__lF : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaults><τ_1_0 where τ_1_0 : Fooable> (@in τ_0_0.T, @owned τ_1_0, @in_guaranteed τ_0_0) -> ()
+// CHECK-LABEL: sil private [transparent] [thunk] @_T015witnesses_class12UsesDefaultsCyxGAA03HasD0A2aEP23hasDefaultGenericTakesTyy1TQz_qd__tAA7FooableRd__lFTW : $@convention(witness_method: HasDefaults) <τ_0_0 where τ_0_0 : Barable><τ_1_0 where τ_1_0 : Fooable> (@in UsesDefaults<τ_0_0>, @owned τ_1_0, @in_guaranteed UsesDefaults<τ_0_0>) -> ()
+// CHECK: [[FN:%.*]] = function_ref @_T015witnesses_class11HasDefaultsPAAE23hasDefaultGenericTakesTyy1TQz_qd__tAA7FooableRd__lF : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaults><τ_1_0 where τ_1_0 : Fooable> (@in τ_0_0.T, @owned τ_1_0, @in_guaranteed τ_0_0) -> ()
 // CHECK: apply [[FN]]<UsesDefaults<τ_0_0>, τ_1_0>(
 // CHECK: return
diff --git a/test/SILGen/writeback.swift b/test/SILGen/writeback.swift
index de739d8..7100459 100644
--- a/test/SILGen/writeback.swift
+++ b/test/SILGen/writeback.swift
@@ -60,7 +60,7 @@
 // CHECK: [[GET_X:%.*]] = function_ref @_T09writeback1xAA3FooVvg : $@convention(thin) () -> Foo
 // CHECK: [[X:%.*]] = apply [[GET_X]]() : $@convention(thin) () -> Foo
 // CHECK: store [[X]] to [trivial] [[X_TEMP]] : $*Foo
-// CHECK: [[BAR:%.*]] = function_ref @_T09writeback3baryAA3FooVz1x_tF : $@convention(thin) (@inout Foo) -> ()
+// CHECK: [[BAR:%.*]] = function_ref @_T09writeback3bar1xyAA3FooVz_tF : $@convention(thin) (@inout Foo) -> ()
 // CHECK: apply [[BAR]]([[X_TEMP]]) : $@convention(thin) (@inout Foo) -> ()
 // CHECK: [[X1:%.*]] = load [trivial] [[X_TEMP]] : $*Foo
 // CHECK: [[SET_X:%.*]] = function_ref @_T09writeback1xAA3FooVvs : $@convention(thin) (Foo) -> ()
@@ -71,10 +71,10 @@
 
 // No writeback for pass-by-value argument
 zang(x: x)
-// CHECK:  function_ref @_T09writeback4zangyAA3FooV1x_tF : $@convention(thin) (Foo) -> ()
+// CHECK:  function_ref @_T09writeback4zang1xyAA3FooV_tF : $@convention(thin) (Foo) -> ()
 // CHECK-NOT: @_T09writeback1xAA3FooVvs
 zang(x: readonly)
-// CHECK:  function_ref @_T09writeback4zangyAA3FooV1x_tF : $@convention(thin) (Foo) -> ()
+// CHECK:  function_ref @_T09writeback4zang1xyAA3FooV_tF : $@convention(thin) (Foo) -> ()
 // CHECK-NOT: @_T09writeback8readonlyAA3FooVvs
 
 func zung() -> Int { return 0 }
@@ -86,7 +86,7 @@
 // CHECK: [[GET_X:%.*]] = function_ref @_T09writeback1xAA3FooVvg : $@convention(thin) () -> Foo
 // CHECK: [[GET_SUBSCRIPT:%.*]] = function_ref @_T09writeback3FooV{{[_0-9a-zA-Z]*}}ig : $@convention(method) (Int, Foo) -> Foo
 // CHECK: apply [[GET_SUBSCRIPT]]([[INDEX]], {{%.*}}) : $@convention(method) (Int, Foo) -> Foo
-// CHECK: [[BAR:%.*]] = function_ref @_T09writeback3baryAA3FooVz1x_tF : $@convention(thin) (@inout Foo) -> ()
+// CHECK: [[BAR:%.*]] = function_ref @_T09writeback3bar1xyAA3FooVz_tF : $@convention(thin) (@inout Foo) -> ()
 // CHECK: apply [[BAR]]({{%.*}}) : $@convention(thin) (@inout Foo) -> ()
 // CHECK: [[SET_SUBSCRIPT:%.*]] = function_ref @_T09writeback3FooV{{[_0-9a-zA-Z]*}}is : $@convention(method) (Foo, Int, @inout Foo) -> ()
 // CHECK: apply [[SET_SUBSCRIPT]]({{%.*}}, [[INDEX]], {{%.*}}) : $@convention(method) (Foo, Int, @inout Foo) -> ()
@@ -108,7 +108,7 @@
 // CHECK: [[TEMP:%.*]] = alloc_stack $Fungible
 // CHECK: [[GET:%.*]] = function_ref @_T09writeback11addressOnlyAA8Fungible_pvg : $@convention(thin) () -> @out Fungible
 // CHECK: apply [[GET]]([[TEMP]]) : $@convention(thin) () -> @out Fungible
-// CHECK: [[FUNGE:%.*]] = function_ref @_T09writeback5fungeyAA8Fungible_pz1x_tF : $@convention(thin) (@inout Fungible) -> ()
+// CHECK: [[FUNGE:%.*]] = function_ref @_T09writeback5funge1xyAA8Fungible_pz_tF : $@convention(thin) (@inout Fungible) -> ()
 // CHECK: apply [[FUNGE]]([[TEMP]]) : $@convention(thin) (@inout Fungible) -> ()
 // CHECK: [[SET:%.*]] = function_ref @_T09writeback11addressOnlyAA8Fungible_pvs : $@convention(thin) (@in Fungible) -> ()
 // CHECK: apply [[SET]]([[TEMP]]) : $@convention(thin) (@in Fungible) -> ()
diff --git a/test/SILOptimizer/access_enforcement_noescape.swift b/test/SILOptimizer/access_enforcement_noescape.swift
index b9f58b7..4ae7088 100644
--- a/test/SILOptimizer/access_enforcement_noescape.swift
+++ b/test/SILOptimizer/access_enforcement_noescape.swift
@@ -38,16 +38,16 @@
 func nestedNoEscape(f: inout Frob) {
   doOne { f.outerMut() }
 }
-// CHECK-LABEL: sil hidden @_T027access_enforcement_noescape14nestedNoEscapeyAA4FrobVz1f_tF : $@convention(thin) (@inout Frob) -> () {
+// CHECK-LABEL: sil hidden @_T027access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tF : $@convention(thin) (@inout Frob) -> () {
 // CHECK-NOT: begin_access
-// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14nestedNoEscapeyAA4FrobVz1f_tF'
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tF'
 
 // closure #1 in nestedNoEscape(f:)
-// CHECK-LABEL: sil private @_T027access_enforcement_noescape14nestedNoEscapeyAA4FrobVz1f_tFyycfU_ : $@convention(thin) (@inout_aliasable Frob) -> () {
+// CHECK-LABEL: sil private @_T027access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tFyycfU_ : $@convention(thin) (@inout_aliasable Frob) -> () {
 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Frob
 // CHECK: %{{.*}} = apply %{{.*}}([[ACCESS]]) : $@convention(method) (@inout Frob) -> ()
 // CHECK: end_access [[ACCESS]] : $*Frob
-// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14nestedNoEscapeyAA4FrobVz1f_tFyycfU_'
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tFyycfU_'
 
 // Allow aliased noescape reads.
 func readRead() {
@@ -81,28 +81,28 @@
   // Inside each closure: [read] [static]
   doTwo({ _ = x }, { _ = x })
 }
-// CHECK-LABEL: sil hidden @_T027access_enforcement_noescape09inoutReadE0ySiz1x_tF : $@convention(thin) (@inout Int) -> () {
+// CHECK-LABEL: sil hidden @_T027access_enforcement_noescape09inoutReadE01xySiz_tF : $@convention(thin) (@inout Int) -> () {
 // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
 // CHECK: [[CVT1:%.*]] = convert_function [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
 // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
 // CHECK: [[CVT2:%.*]] = convert_function [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
 // CHECK-NOT: begin_access
 // CHECK: apply %{{.*}}([[CVT1]], [[CVT2]])
-// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape09inoutReadE0ySiz1x_tF'
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape09inoutReadE01xySiz_tF'
 
 // closure #1 in inoutReadRead(x:)
-// CHECK-LABEL: sil private @_T027access_enforcement_noescape09inoutReadE0ySiz1x_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
+// CHECK-LABEL: sil private @_T027access_enforcement_noescape09inoutReadE01xySiz_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
 // CHECK-NOT: begin_access [read] [dynamic]
 // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int
 // CHECK: end_access [[ACCESS]] 
-// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape09inoutReadE0ySiz1x_tFyycfU_'
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape09inoutReadE01xySiz_tFyycfU_'
 
 // closure #2 in inoutReadRead(x:)
-// CHECK-LABEL: sil private @_T027access_enforcement_noescape09inoutReadE0ySiz1x_tFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
+// CHECK-LABEL: sil private @_T027access_enforcement_noescape09inoutReadE01xySiz_tFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
 // CHECK-NOT: begin_access [read] [dynamic]
 // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int
 // CHECK: end_access [[ACCESS]] 
-// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape09inoutReadE0ySiz1x_tFyycfU0_'
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape09inoutReadE01xySiz_tFyycfU0_'
 
 // Allow aliased noescape read + boxed read.
 func readBoxRead() {
@@ -179,25 +179,25 @@
   doTwo({ _ = x }, { x = 3 })
 }
 
-// CHECK-LABEL: sil hidden @_T027access_enforcement_noescape14inoutReadWriteySiz1x_tF : $@convention(thin) (@inout Int) -> () {
+// CHECK-LABEL: sil hidden @_T027access_enforcement_noescape14inoutReadWrite1xySiz_tF : $@convention(thin) (@inout Int) -> () {
 // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
 // CHECK: [[CVT1:%.*]] = convert_function [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
 // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
 // CHECK: [[CVT2:%.*]] = convert_function [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
 // CHECK: apply %{{.*}}([[CVT1]], [[CVT2]])
-// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14inoutReadWriteySiz1x_tF'
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14inoutReadWrite1xySiz_tF'
 
 // closure #1 in inoutReadWrite(x:)
-// CHECK-LABEL: sil private @_T027access_enforcement_noescape14inoutReadWriteySiz1x_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
+// CHECK-LABEL: sil private @_T027access_enforcement_noescape14inoutReadWrite1xySiz_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
 // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int
 // CHECK: end_access [[ACCESS]] 
-// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14inoutReadWriteySiz1x_tFyycfU_'
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14inoutReadWrite1xySiz_tFyycfU_'
 
 // closure #2 in inoutReadWrite(x:)
-// CHECK-LABEL: sil private @_T027access_enforcement_noescape14inoutReadWriteySiz1x_tFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
+// CHECK-LABEL: sil private @_T027access_enforcement_noescape14inoutReadWrite1xySiz_tFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int
 // CHECK: end_access [[ACCESS]] 
-// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14inoutReadWriteySiz1x_tFyycfU0_'
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14inoutReadWrite1xySiz_tFyycfU0_'
 
 
 func readBoxWrite() {
@@ -304,19 +304,19 @@
   doOneInout({ _ = x }, &x)
 }
 
-// CHECK-LABEL: sil hidden @_T027access_enforcement_noescape19inoutReadWriteInoutySiz1x_tF : $@convention(thin) (@inout Int) -> () {
+// CHECK-LABEL: sil hidden @_T027access_enforcement_noescape19inoutReadWriteInout1xySiz_tF : $@convention(thin) (@inout Int) -> () {
 // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
 // CHECK: [[CVT:%.*]] = convert_function [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
 // CHECK: [[ACCESS2:%.*]] = begin_access [modify] [static] %0 : $*Int
 // CHECK: apply %{{.*}}([[CVT]], [[ACCESS2]])
 // CHECK: end_access [[ACCESS2]]
-// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape19inoutReadWriteInoutySiz1x_tF'
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape19inoutReadWriteInout1xySiz_tF'
 
 // closure #1 in inoutReadWriteInout(x:)
-// CHECK-LABEL: sil private @_T027access_enforcement_noescape19inoutReadWriteInoutySiz1x_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
+// CHECK-LABEL: sil private @_T027access_enforcement_noescape19inoutReadWriteInout1xySiz_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
 // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int
 // CHECK: end_access [[ACCESS]] 
-// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape19inoutReadWriteInoutySiz1x_tFyycfU_'
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape19inoutReadWriteInout1xySiz_tFyycfU_'
 
 // Traps on boxed read + write inout.
 // Covered by Interpreter/enforce_exclusive_access.swift.
@@ -388,26 +388,26 @@
   doTwo({ x = 42}, { x = 87 })
 }
 
-// CHECK-LABEL: sil hidden @_T027access_enforcement_noescape010inoutWriteE0ySiz1x_tF : $@convention(thin) (@inout Int) -> () {
+// CHECK-LABEL: sil hidden @_T027access_enforcement_noescape010inoutWriteE01xySiz_tF : $@convention(thin) (@inout Int) -> () {
 // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
 // CHECK: [[CVT1:%.*]] = convert_function [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
 // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed]
 // CHECK: [[CVT2:%.*]] = convert_function [[PA2]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
 // CHECK-NOT: begin_access
 // CHECK: apply %{{.*}}([[CVT1]], [[CVT2]])
-// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape010inoutWriteE0ySiz1x_tF'
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape010inoutWriteE01xySiz_tF'
 
 // closure #1 in inoutWriteWrite(x:)
-// CHECK-LABEL: sil private @_T027access_enforcement_noescape010inoutWriteE0ySiz1x_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
+// CHECK-LABEL: sil private @_T027access_enforcement_noescape010inoutWriteE01xySiz_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int
 // CHECK: end_access [[ACCESS]] 
-// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape010inoutWriteE0ySiz1x_tFyycfU_'
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape010inoutWriteE01xySiz_tFyycfU_'
 
 // closure #2 in inoutWriteWrite(x:)
-// CHECK-LABEL: sil private @_T027access_enforcement_noescape010inoutWriteE0ySiz1x_tFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
+// CHECK-LABEL: sil private @_T027access_enforcement_noescape010inoutWriteE01xySiz_tFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () {
 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int
 // CHECK: end_access [[ACCESS]] 
-// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape010inoutWriteE0ySiz1x_tFyycfU0_'
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape010inoutWriteE01xySiz_tFyycfU0_'
 
 // Traps on aliased boxed write + noescape write.
 // Covered by Interpreter/enforce_exclusive_access.swift.
@@ -482,19 +482,19 @@
 }
 
 // inoutWriteWriteInout(x:)
-// CHECK-LABEL: sil hidden @_T027access_enforcement_noescape010inoutWriteE5InoutySiz1x_tF : $@convention(thin) (@inout Int) -> () {
+// CHECK-LABEL: sil hidden @_T027access_enforcement_noescape010inoutWriteE5Inout1xySiz_tF : $@convention(thin) (@inout Int) -> () {
 // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed]
 // CHECK: [[CVT:%.*]] = convert_function [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
 // CHECK: [[ACCESS2:%.*]] = begin_access [modify] [static] %0 : $*Int
 // CHECK: apply %{{.*}}([[CVT]], [[ACCESS2]])
 // CHECK: end_access [[ACCESS2]]
-// CHECK-LABEL: // end sil function '_T027access_enforcement_noescape010inoutWriteE5InoutySiz1x_tF'
+// CHECK-LABEL: // end sil function '_T027access_enforcement_noescape010inoutWriteE5Inout1xySiz_tF'
 
 // closure #1 in inoutWriteWriteInout(x:)
-// CHECK-LABEL: sil private @_T027access_enforcement_noescape010inoutWriteE5InoutySiz1x_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
+// CHECK-LABEL: sil private @_T027access_enforcement_noescape010inoutWriteE5Inout1xySiz_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int
 // CHECK: end_access [[ACCESS]] 
-// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape010inoutWriteE5InoutySiz1x_tFyycfU_'
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape010inoutWriteE5Inout1xySiz_tFyycfU_'
 
 // Traps on boxed write + write inout.
 // Covered by Interpreter/enforce_exclusive_access.swift.
@@ -534,7 +534,9 @@
 func readBlockWriteInout() {
   var x = 3
   // Around the call: [modify] [static]
-  // Inside closure: [modify] [static]
+  // Inside closure: [read] [static]
+  // expected-warning@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}}
+  // expected-note@+1{{conflicting access is here}}
   doBlockInout({ _ = x }, &x)
 }
 
@@ -558,6 +560,8 @@
 func noEscapeBlock() {
   var x = 3
   doOne {
+    // expected-warning@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}}
+    // expected-note@+1{{conflicting access is here}}
     doBlockInout({ _ = x }, &x)
   }
 }
diff --git a/test/SILOptimizer/access_enforcement_selection.swift b/test/SILOptimizer/access_enforcement_selection.swift
index f28ba38..ec0e169 100644
--- a/test/SILOptimizer/access_enforcement_selection.swift
+++ b/test/SILOptimizer/access_enforcement_selection.swift
@@ -6,7 +6,7 @@
 public func takesInout(_ i: inout Int) {
   i = 42
 }
-// CHECK-LABEL: Access Enforcement Selection in _T028access_enforcement_selection10takesInoutySizF
+// CHECK-LABEL: Access Enforcement Selection in _T028access_enforcement_selection10takesInoutyySizF
 // CHECK: Static Access: %{{.*}} = begin_access [modify] [static] %{{.*}} : $*Int
 
 // Helper taking a basic, no-escape closure.
diff --git a/test/SILOptimizer/access_marker_mandatory.swift b/test/SILOptimizer/access_marker_mandatory.swift
index 20c0c59..f670c7a 100644
--- a/test/SILOptimizer/access_marker_mandatory.swift
+++ b/test/SILOptimizer/access_marker_mandatory.swift
@@ -5,7 +5,7 @@
   var o: AnyObject
 }
 
-// CHECK-LABEL: sil [noinline] @_T023access_marker_mandatory5initSAA1SVSi_yXltF : $@convention(thin) (Int, @owned AnyObject) -> @owned S {
+// CHECK-LABEL: sil [noinline] @_T023access_marker_mandatory5initSyAA1SVSi_yXltF : $@convention(thin) (Int, @owned AnyObject) -> @owned S {
 // CHECK: bb0(%0 : $Int, %1 : $AnyObject):
 // CHECK: [[STK:%.*]] = alloc_stack $S, var, name "s"
 // CHECK: cond_br %{{.*}}, bb1, bb2
@@ -24,7 +24,7 @@
 // CHECK: destroy_addr [[STK]]
 // CHECK: dealloc_stack [[STK]]
 // CHECK: return [[RET]] : $S
-// CHECK-LABEL: } // end sil function '_T023access_marker_mandatory5initSAA1SVSi_yXltF'
+// CHECK-LABEL: } // end sil function '_T023access_marker_mandatory5initSyAA1SVSi_yXltF'
 @inline(never)
 public func initS(_ x: Int, _ o: AnyObject) -> S {
   var s: S
@@ -39,10 +39,10 @@
 @inline(never)
 func takeS(_ s: S) {}
 
-// CHECK-LABEL: sil @_T023access_marker_mandatory14modifyAndReadSyyXl1o_tF : $@convention(thin) (@owned AnyObject) -> () {
+// CHECK-LABEL: sil @_T023access_marker_mandatory14modifyAndReadS1oyyXl_tF : $@convention(thin) (@owned AnyObject) -> () {
 // CHECK: bb0(%0 : $AnyObject):
 // CHECK: [[STK:%.*]] = alloc_stack $S, var, name "s"
-// CHECK: [[FINIT:%.*]] = function_ref @_T023access_marker_mandatory5initSAA1SVSi_yXltF : $@convention(thin) (Int, @owned AnyObject) -> @owned S
+// CHECK: [[FINIT:%.*]] = function_ref @_T023access_marker_mandatory5initSyAA1SVSi_yXltF : $@convention(thin) (Int, @owned AnyObject) -> @owned S
 // CHECK: [[INITS:%.*]] = apply [[FINIT]](%{{.*}}, %0) : $@convention(thin) (Int, @owned AnyObject) -> @owned S
 // CHECK: store [[INITS]] to [[STK]] : $*S
 // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[STK]] : $*S
@@ -51,9 +51,9 @@
 // CHECK: end_access [[WRITE]]
 // CHECK: [[READ:%.*]] = begin_access [read] [static] [[STK]] : $*S
 // CHECK: end_access [[READ]]
-// CHECK: [[FTAKE:%.*]] = function_ref @_T023access_marker_mandatory5takeSyAA1SVF : $@convention(thin) (@owned S) -> ()
+// CHECK: [[FTAKE:%.*]] = function_ref @_T023access_marker_mandatory5takeSyyAA1SVF : $@convention(thin) (@owned S) -> ()
 // CHECK: apply [[FTAKE]](%{{.*}}) : $@convention(thin) (@owned S) -> ()
-// CHECK-LABEL: } // end sil function '_T023access_marker_mandatory14modifyAndReadSyyXl1o_tF'
+// CHECK-LABEL: } // end sil function '_T023access_marker_mandatory14modifyAndReadS1oyyXl_tF'
 public func modifyAndReadS(o: AnyObject) {
   var s = initS(3, o)
   s.i = 42
diff --git a/test/SILOptimizer/alive_method_with_thunk.swift b/test/SILOptimizer/alive_method_with_thunk.swift
index 1c38a2f..78b48e1 100644
--- a/test/SILOptimizer/alive_method_with_thunk.swift
+++ b/test/SILOptimizer/alive_method_with_thunk.swift
@@ -15,10 +15,10 @@
 }
 
 // CHECK: sil_vtable [serialized] BaseClass {
-// CHECK:  #BaseClass.doSomething!1: <T> (BaseClass<T>) -> (T) -> Int : _T023alive_method_with_thunk9BaseClassC11doSomethingSixF // BaseClass.doSomething(_:)
+// CHECK:  #BaseClass.doSomething!1: <T> (BaseClass<T>) -> (T) -> Int : _T023alive_method_with_thunk9BaseClassC11doSomethingySixF // BaseClass.doSomething(_:)
 // CHECK: }
 
 // CHECK: sil_vtable [serialized] DerivedClass {
-// CHECK:  #BaseClass.doSomething!1: <T> (BaseClass<T>) -> (T) -> Int : public _T023alive_method_with_thunk12DerivedClassC11doSomethingSiSdFAA04BaseF0CADSixFTV [override]  // vtable thunk for BaseClass.doSomething(_:) dispatching to DerivedClass.doSomething(_:)
+// CHECK:  #BaseClass.doSomething!1: <T> (BaseClass<T>) -> (T) -> Int : public _T023alive_method_with_thunk12DerivedClassC11doSomethingySiSdFAA04BaseF0CADySixFTV [override]  // vtable thunk for BaseClass.doSomething(_:) dispatching to DerivedClass.doSomething(_:)
 // CHECK: }
 
diff --git a/test/SILOptimizer/allocbox_to_stack.sil b/test/SILOptimizer/allocbox_to_stack.sil
index 96fc487..d52af51 100644
--- a/test/SILOptimizer/allocbox_to_stack.sil
+++ b/test/SILOptimizer/allocbox_to_stack.sil
@@ -353,9 +353,9 @@
   br bb2
 }
 
-// CHECK-LABEL: sil @_T06struct5applySiSiyc1f_tF
+// CHECK-LABEL: sil @_T06struct5apply1fS2iyc_tF
 // struct.apply (f : () -> Swift.Int) -> Swift.Int
-sil @_T06struct5applySiSiyc1f_tF : $@convention(thin) (@owned @callee_owned () -> Int) -> Int {
+sil @_T06struct5apply1fS2iyc_tF : $@convention(thin) (@owned @callee_owned () -> Int) -> Int {
 bb0(%0 : $@callee_owned () -> Int):
   debug_value %0 : $@callee_owned () -> Int, let, name "f" // id: %1
   strong_retain %0 : $@callee_owned () -> Int     // id: %2
@@ -364,17 +364,17 @@
   return %3 : $Int                                // id: %5
 }
 
-// CHECK-LABEL: sil @_T06struct6escapeSiycSiyc1f_tF
+// CHECK-LABEL: sil @_T06struct6escape1fSiycSiyc_tF
 // struct.escape (f : () -> Swift.Int) -> () -> Swift.Int
-sil @_T06struct6escapeSiycSiyc1f_tF : $@convention(thin) (@owned @callee_owned () -> Int) -> @owned @callee_owned () -> Int {
+sil @_T06struct6escape1fSiycSiyc_tF : $@convention(thin) (@owned @callee_owned () -> Int) -> @owned @callee_owned () -> Int {
 bb0(%0 : $@callee_owned () -> Int):
   debug_value %0 : $@callee_owned () -> Int, let, name "f" // id: %1
   return %0 : $@callee_owned () -> Int            // id: %2
 }
 
-// CHECK-LABEL: sil @_T06struct8useStackySi1t_tF
+// CHECK-LABEL: sil @_T06struct8useStack1tySi_tF
 // struct.useStack (t : Swift.Int) -> ()
-sil @_T06struct8useStackySi1t_tF : $@convention(thin) (Int) -> () {
+sil @_T06struct8useStack1tySi_tF : $@convention(thin) (Int) -> () {
 bb0(%0 : $Int):
   debug_value %0 : $Int, let, name "t" // id: %1
   // CHECK: alloc_stack
@@ -382,10 +382,10 @@
   %2a = project_box %2 : $<τ_0_0> { var τ_0_0 } <Int>, 0
   store %0 to %2a : $*Int                        // id: %3
   // function_ref struct.apply (f : () -> Swift.Int) -> Swift.Int
-  %4 = function_ref @_T06struct5applySiSiyc1f_tF : $@convention(thin) (@owned @callee_owned () -> Int) -> Int // user: %8
-  // CHECK: [[FUNC:%[a-zA-Z0-9]+]] = function_ref @_T06struct8useStackySi1t_tFSiycfU_Tf0s_n
+  %4 = function_ref @_T06struct5apply1fS2iyc_tF : $@convention(thin) (@owned @callee_owned () -> Int) -> Int // user: %8
+  // CHECK: [[FUNC:%[a-zA-Z0-9]+]] = function_ref @_T06struct8useStack1tySi_tFSiycfU_Tf0s_n
   // function_ref struct.(useStack (t : Swift.Int) -> ()).(closure #1)
-  %5 = function_ref @_T06struct8useStackySi1t_tFSiycfU_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int // user: %7
+  %5 = function_ref @_T06struct8useStack1tySi_tFSiycfU_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int // user: %7
   strong_retain %2 : $<τ_0_0> { var τ_0_0 } <Int>     // id: %6
   // CHECK: [[PA:%[a-zA-Z0-9]+]] = partial_apply [[FUNC]]
   %7 = partial_apply %5(%2) : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int // user: %8
@@ -395,10 +395,10 @@
   return %10 : $()                                // id: %11
 }
 
-// CHECK-LABEL: sil shared @_T06struct8useStackySi1t_tFSiycfU_Tf0s_n
-// CHECK-LABEL: sil private @_T06struct8useStackySi1t_tFSiycfU_
+// CHECK-LABEL: sil shared @_T06struct8useStack1tySi_tFSiycfU_Tf0s_n
+// CHECK-LABEL: sil private @_T06struct8useStack1tySi_tFSiycfU_
 // struct.(useStack (t : Swift.Int) -> ()).(closure #1)
-sil private @_T06struct8useStackySi1t_tFSiycfU_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int {
+sil private @_T06struct8useStack1tySi_tFSiycfU_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int {
 bb0(%0 : $<τ_0_0> { var τ_0_0 } <Int>):
   %1 = project_box %0 : $<τ_0_0> { var τ_0_0 } <Int>, 0
   // function_ref Swift.++ @postfix <A : Swift._Incrementable>(x : @inout A) -> A
@@ -414,9 +414,9 @@
 // Swift.++ @postfix <A : Swift._Incrementable>(x : @inout A) -> A
 sil [transparent] @_TFsoP2ppUs14_Incrementable__FT1xRQ__Q_ : $@convention(thin) <τ_0_0 where τ_0_0 : My_Incrementable> (@inout τ_0_0) -> @out τ_0_0
 
-// CHECK-LABEL: sil @_T06struct6useBoxySi1t_tF
+// CHECK-LABEL: sil @_T06struct6useBox1tySi_tF
 // struct.useBox (t : Swift.Int) -> ()
-sil @_T06struct6useBoxySi1t_tF : $@convention(thin) (Int) -> () {
+sil @_T06struct6useBox1tySi_tF : $@convention(thin) (Int) -> () {
 bb0(%0 : $Int):
   debug_value %0 : $Int, let, name "t" // id: %1
   // CHECK: alloc_box
@@ -424,9 +424,9 @@
   %2a = project_box %2 : $<τ_0_0> { var τ_0_0 } <Int>, 0
   store %0 to %2a : $*Int                        // id: %3
   // function_ref struct.escape (f : () -> Swift.Int) -> () -> Swift.Int
-  %4 = function_ref @_T06struct6escapeSiycSiyc1f_tF : $@convention(thin) (@owned @callee_owned () -> Int) -> @owned @callee_owned () -> Int // user: %8
+  %4 = function_ref @_T06struct6escape1fSiycSiyc_tF : $@convention(thin) (@owned @callee_owned () -> Int) -> @owned @callee_owned () -> Int // user: %8
   // function_ref struct.(useBox (t : Swift.Int) -> ()).(closure #1)
-  %5 = function_ref @_T06struct6useBoxySi1t_tFSiycfU_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int // user: %7
+  %5 = function_ref @_T06struct6useBox1tySi_tFSiycfU_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int // user: %7
   strong_retain %2 : $<τ_0_0> { var τ_0_0 } <Int>     // id: %6
   %7 = partial_apply %5(%2) : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int // user: %8
   %8 = apply %4(%7) : $@convention(thin) (@owned @callee_owned () -> Int) -> @owned @callee_owned () -> Int // user: %9
@@ -436,9 +436,9 @@
   return %11 : $()                                // id: %12
 }
 
-// CHECK-LABEL: sil private @_T06struct6useBoxySi1t_tFSiycfU_
+// CHECK-LABEL: sil private @_T06struct6useBox1tySi_tFSiycfU_
 // struct.(useBox (t : Swift.Int) -> ()).(closure #1)
-sil private @_T06struct6useBoxySi1t_tFSiycfU_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int {
+sil private @_T06struct6useBox1tySi_tFSiycfU_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int {
 bb0(%0 : $<τ_0_0> { var τ_0_0 } <Int>):
   %1 = project_box %0 : $<τ_0_0> { var τ_0_0 } <Int>, 0
   // function_ref Swift.++ @postfix <A : Swift._Incrementable>(x : @inout A) -> A
diff --git a/test/SILOptimizer/allocbox_to_stack_ownership.sil b/test/SILOptimizer/allocbox_to_stack_ownership.sil
index 5b2f8a8..fce2d45 100644
--- a/test/SILOptimizer/allocbox_to_stack_ownership.sil
+++ b/test/SILOptimizer/allocbox_to_stack_ownership.sil
@@ -348,9 +348,9 @@
   br bb2
 }
 
-// CHECK-LABEL: sil @_T06struct5applySiSiyc1f_tF
+// CHECK-LABEL: sil @_T06struct5apply1fS2iyc_tF
 // struct.apply (f : () -> Swift.Int) -> Swift.Int
-sil @_T06struct5applySiSiyc1f_tF : $@convention(thin) (@owned @callee_owned () -> Int) -> Int {
+sil @_T06struct5apply1fS2iyc_tF : $@convention(thin) (@owned @callee_owned () -> Int) -> Int {
 bb0(%0 : @owned $@callee_owned () -> Int):
   debug_value %0 : $@callee_owned () -> Int, let, name "f" // id: %1
   %1 = copy_value %0 : $@callee_owned () -> Int     // id: %2
@@ -359,17 +359,17 @@
   return %3 : $Int                                // id: %5
 }
 
-// CHECK-LABEL: sil @_T06struct6escapeSiycSiyc1f_tF
+// CHECK-LABEL: sil @_T06struct6escape1fSiycSiyc_tF
 // struct.escape (f : () -> Swift.Int) -> () -> Swift.Int
-sil @_T06struct6escapeSiycSiyc1f_tF : $@convention(thin) (@owned @callee_owned () -> Int) -> @owned @callee_owned () -> Int {
+sil @_T06struct6escape1fSiycSiyc_tF : $@convention(thin) (@owned @callee_owned () -> Int) -> @owned @callee_owned () -> Int {
 bb0(%0 : @owned $@callee_owned () -> Int):
   debug_value %0 : $@callee_owned () -> Int, let, name "f" // id: %1
   return %0 : $@callee_owned () -> Int            // id: %2
 }
 
-// CHECK-LABEL: sil @_T06struct8useStackySi1t_tF
+// CHECK-LABEL: sil @_T06struct8useStack1tySi_tF
 // struct.useStack (t : Swift.Int) -> ()
-sil @_T06struct8useStackySi1t_tF : $@convention(thin) (Int) -> () {
+sil @_T06struct8useStack1tySi_tF : $@convention(thin) (Int) -> () {
 bb0(%0 : @trivial $Int):
   debug_value %0 : $Int, let, name "t" // id: %1
   // CHECK: alloc_stack
@@ -377,10 +377,10 @@
   %2a = project_box %2 : $<τ_0_0> { var τ_0_0 } <Int>, 0
   store %0 to [trivial] %2a : $*Int                        // id: %3
   // function_ref struct.apply (f : () -> Swift.Int) -> Swift.Int
-  %4 = function_ref @_T06struct5applySiSiyc1f_tF : $@convention(thin) (@owned @callee_owned () -> Int) -> Int // user: %8
-  // CHECK: [[FUNC:%[a-zA-Z0-9]+]] = function_ref @_T06struct8useStackySi1t_tFSiycfU_Tf0s_n
+  %4 = function_ref @_T06struct5apply1fS2iyc_tF : $@convention(thin) (@owned @callee_owned () -> Int) -> Int // user: %8
+  // CHECK: [[FUNC:%[a-zA-Z0-9]+]] = function_ref @_T06struct8useStack1tySi_tFSiycfU_Tf0s_n
   // function_ref struct.(useStack (t : Swift.Int) -> ()).(closure #1)
-  %5 = function_ref @_T06struct8useStackySi1t_tFSiycfU_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int // user: %7
+  %5 = function_ref @_T06struct8useStack1tySi_tFSiycfU_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int // user: %7
   %6 = copy_value %2 : $<τ_0_0> { var τ_0_0 } <Int>     // id: %6
   // CHECK: [[PA:%[a-zA-Z0-9]+]] = partial_apply [[FUNC]]
   %7 = partial_apply %5(%6) : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int // user: %8
@@ -390,10 +390,10 @@
   return %10 : $()                                // id: %11
 }
 
-// CHECK-LABEL: sil shared @_T06struct8useStackySi1t_tFSiycfU_Tf0s_n
-// CHECK-LABEL: sil private @_T06struct8useStackySi1t_tFSiycfU_
+// CHECK-LABEL: sil shared @_T06struct8useStack1tySi_tFSiycfU_Tf0s_n
+// CHECK-LABEL: sil private @_T06struct8useStack1tySi_tFSiycfU_
 // struct.(useStack (t : Swift.Int) -> ()).(closure #1)
-sil private @_T06struct8useStackySi1t_tFSiycfU_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int {
+sil private @_T06struct8useStack1tySi_tFSiycfU_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int {
 bb0(%0 : @owned $<τ_0_0> { var τ_0_0 } <Int>):
   %1 = project_box %0 : $<τ_0_0> { var τ_0_0 } <Int>, 0
   // function_ref Swift.++ @postfix <A : Swift._Incrementable>(x : @inout A) -> A
@@ -409,9 +409,9 @@
 // Swift.++ @postfix <A : Swift._Incrementable>(x : @inout A) -> A
 sil [transparent] @_TFsoP2ppUs14_Incrementable__FT1xRQ__Q_ : $@convention(thin) <τ_0_0 where τ_0_0 : My_Incrementable> (@inout τ_0_0) -> @out τ_0_0
 
-// CHECK-LABEL: sil @_T06struct6useBoxySi1t_tF
+// CHECK-LABEL: sil @_T06struct6useBox1tySi_tF
 // struct.useBox (t : Swift.Int) -> ()
-sil @_T06struct6useBoxySi1t_tF : $@convention(thin) (Int) -> () {
+sil @_T06struct6useBox1tySi_tF : $@convention(thin) (Int) -> () {
 bb0(%0 : @trivial $Int):
   debug_value %0 : $Int, let, name "t" // id: %1
   // CHECK: alloc_box
@@ -419,9 +419,9 @@
   %2a = project_box %2 : $<τ_0_0> { var τ_0_0 } <Int>, 0
   store %0 to [trivial] %2a : $*Int                        // id: %3
   // function_ref struct.escape (f : () -> Swift.Int) -> () -> Swift.Int
-  %4 = function_ref @_T06struct6escapeSiycSiyc1f_tF : $@convention(thin) (@owned @callee_owned () -> Int) -> @owned @callee_owned () -> Int // user: %8
+  %4 = function_ref @_T06struct6escape1fSiycSiyc_tF : $@convention(thin) (@owned @callee_owned () -> Int) -> @owned @callee_owned () -> Int // user: %8
   // function_ref struct.(useBox (t : Swift.Int) -> ()).(closure #1)
-  %5 = function_ref @_T06struct6useBoxySi1t_tFSiycfU_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int // user: %7
+  %5 = function_ref @_T06struct6useBox1tySi_tFSiycfU_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int // user: %7
   %6 = copy_value %2 : $<τ_0_0> { var τ_0_0 } <Int>     // id: %6
   %7 = partial_apply %5(%6) : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int // user: %8
   %8 = apply %4(%7) : $@convention(thin) (@owned @callee_owned () -> Int) -> @owned @callee_owned () -> Int // user: %9
@@ -431,9 +431,9 @@
   return %11 : $()                                // id: %12
 }
 
-// CHECK-LABEL: sil private @_T06struct6useBoxySi1t_tFSiycfU_
+// CHECK-LABEL: sil private @_T06struct6useBox1tySi_tFSiycfU_
 // struct.(useBox (t : Swift.Int) -> ()).(closure #1)
-sil private @_T06struct6useBoxySi1t_tFSiycfU_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int {
+sil private @_T06struct6useBox1tySi_tFSiycfU_ : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Int>) -> Int {
 bb0(%0 : @owned $<τ_0_0> { var τ_0_0 } <Int>):
   %1 = project_box %0 : $<τ_0_0> { var τ_0_0 } <Int>, 0
   // function_ref Swift.++ @postfix <A : Swift._Incrementable>(x : @inout A) -> A
diff --git a/test/SILOptimizer/array_contentof_opt.swift b/test/SILOptimizer/array_contentof_opt.swift
index 60dc959..64c3bac 100644
--- a/test/SILOptimizer/array_contentof_opt.swift
+++ b/test/SILOptimizer/array_contentof_opt.swift
@@ -5,7 +5,7 @@
 
 // CHECK-LABEL: sil @{{.*}}testInt
 // CHECK-NOT: apply
-// CHECK:        [[F:%[0-9]+]] = function_ref @_T0Sa6appendyxFSi_Tg
+// CHECK:        [[F:%[0-9]+]] = function_ref @_T0Sa6appendyyxFSi_Tg5
 // CHECK-NOT: apply
 // CHECK:        apply [[F]]
 // CHECK-NEXT:   tuple
@@ -16,10 +16,10 @@
 
 // CHECK-LABEL: sil @{{.*}}testThreeInt
 // CHECK-NOT: apply
-// CHECK:        [[FR:%[0-9]+]] = function_ref @_T0Sa15reserveCapacityySiFSi_Tg5
+// CHECK:        [[FR:%[0-9]+]] = function_ref @_T0Sa15reserveCapacityyySiFSi_Tg5
 // CHECK-NEXT:   apply [[FR]]
 // CHECK-NOT: apply
-// CHECK:        [[F:%[0-9]+]] = function_ref @_T0Sa6appendyxFSi_Tg
+// CHECK:        [[F:%[0-9]+]] = function_ref @_T0Sa6appendyyxFSi_Tg5
 // CHECK-NOT: apply
 // CHECK:        apply [[F]]
 // CHECK-NEXT:   apply [[F]]
@@ -32,7 +32,7 @@
 
 // CHECK-LABEL: sil @{{.*}}testTooManyInts
 // CHECK-NOT: apply
-// CHECK:        [[F:%[0-9]+]] = function_ref  @_T0Sa6appendyqd__10contentsOf_t7ElementQyd__Rszs8SequenceRd__lFSi_SaySiGTg5
+// CHECK:        [[F:%[0-9]+]] = function_ref  @_T0Sa6append10contentsOfyqd___t7ElementQyd__Rszs8SequenceRd__lFSi_SaySiGTg5Tf4gn_n
 // CHECK-NOT: apply
 // CHECK:        apply [[F]]
 // CHECK-NOT: apply
@@ -43,7 +43,7 @@
 
 // CHECK-LABEL: sil @{{.*}}testString
 // CHECK-NOT: apply
-// CHECK:        [[F:%[0-9]+]] = function_ref @_T0Sa6appendyxFSS_Tg
+// CHECK:        [[F:%[0-9]+]] = function_ref @_T0Sa6appendyyxFSS_Tg5
 // CHECK-NOT: apply
 // CHECK:        apply [[F]]
 // CHECK-NOT: apply
diff --git a/test/SILOptimizer/array_element_propagation.sil b/test/SILOptimizer/array_element_propagation.sil
index 29e8221..a181575 100644
--- a/test/SILOptimizer/array_element_propagation.sil
+++ b/test/SILOptimizer/array_element_propagation.sil
@@ -309,7 +309,7 @@
 // CHECK-NEXT: [[ARR:%.*]] = apply [[ASFUN]]
 // CHECK-NEXT: [[OWNER:%.*]] = tuple_extract [[ARR]]{{.*}}, 0
 // CHECK-NOT:    apply [[ACFUN]]
-// CHECK:      [[AEFUN:%.*]] = function_ref @_T0Sa6appendyxF
+// CHECK:      [[AEFUN:%.*]] = function_ref @_T0Sa6appendyyxF
 // CHECK-NEXT: [[STACK:%.*]] = alloc_stack $MyInt
 // CHECK-NEXT: store %{{[0-9]+}} to [[STACK]]
 // CHECK-NEXT: apply [[AEFUN]]<MyInt>([[STACK]]
@@ -356,7 +356,7 @@
 // CHECK:      strong_retain %1 : $Hello
 // CHECK-NEXT: store %1 to %{{[0-9]+}} : $*Hello
 // CHECK-NOT:     apply
-// CHECK:      [[AEFUN:%.*]] = function_ref @_T0Sa6appendyxF
+// CHECK:      [[AEFUN:%.*]] = function_ref @_T0Sa6appendyyxF
 // CHECK-NEXT: strong_retain %1 : $Hello
 // CHECK-NEXT: [[STACK:%.*]] = alloc_stack $Hello
 // CHECK-NEXT: store %1 to [[STACK]]
diff --git a/test/SILOptimizer/bridged_casts_folding.swift b/test/SILOptimizer/bridged_casts_folding.swift
index 473fb6a..c12746c 100644
--- a/test/SILOptimizer/bridged_casts_folding.swift
+++ b/test/SILOptimizer/bridged_casts_folding.swift
@@ -28,7 +28,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding29testForcedCastNStoSwiftStringSSyF
 // CHECK-NOT: unconditional_checked
-// CHECK: function_ref @_T0SS10FoundationE26_forceBridgeFromObjectiveCySo8NSStringC_SSSgz6resulttFZ : $@convention(method) (@owned NSString, @inout Optional<String>, @thin String.Type) -> ()
+// CHECK: function_ref @_T0SS10FoundationE26_forceBridgeFromObjectiveC_6resultySo8NSStringC_SSSgztFZ : $@convention(method) (@owned NSString, @inout Optional<String>, @thin String.Type) -> ()
 // CHECK: return
 @inline(never)
 public func testForcedCastNStoSwiftString() -> String {
@@ -38,7 +38,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding27testCondCastNStoSwiftStringSSSgyF
 // CHECK-NOT: checked_cast
-// CHECK: function_ref @_T0SS10FoundationE34_conditionallyBridgeFromObjectiveCSbSo8NSStringC_SSSgz6resulttFZ : $@convention(method) (@owned NSString, @inout Optional<String>, @thin String.Type) -> Bool
+// CHECK: function_ref @_T0SS10FoundationE34_conditionallyBridgeFromObjectiveC_6resultSbSo8NSStringC_SSSgztFZ : $@convention(method) (@owned NSString, @inout Optional<String>, @thin String.Type) -> Bool
 // CHECK: return
 @inline(never)
 public func testCondCastNStoSwiftString() -> String? {
@@ -53,7 +53,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding32testForcedCastNSNumberToSwiftIntSiyF
 // CHECK-NOT: unconditional_checked
-// CHECK: function_ref @_T0Si10FoundationE26_forceBridgeFromObjectiveCySo8NSNumberC_SiSgz6resulttFZ : $@convention(method) (@owned NSNumber, @inout Optional<Int>, @thin Int.Type) -> ()
+// CHECK: function_ref @_T0Si10FoundationE26_forceBridgeFromObjectiveC_6resultySo8NSNumberC_SiSgztFZ : $@convention(method) (@owned NSNumber, @inout Optional<Int>, @thin Int.Type) -> ()
 // CHECK: return
 @inline(never)
 public func testForcedCastNSNumberToSwiftInt() -> Int {
@@ -63,7 +63,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding30testCondCastNSNumberToSwiftIntSiSgyF
 // CHECK-NOT: checked_cast
-// CHECK: function_ref @_T0Si10FoundationE34_conditionallyBridgeFromObjectiveCSbSo8NSNumberC_SiSgz6resulttFZ : $@convention(method) (@owned NSNumber, @inout Optional<Int>, @thin Int.Type) -> Bool
+// CHECK: function_ref @_T0Si10FoundationE34_conditionallyBridgeFromObjectiveC_6resultSbSo8NSNumberC_SiSgztFZ : $@convention(method) (@owned NSNumber, @inout Optional<Int>, @thin Int.Type) -> Bool
 // CHECK: return
 @inline(never)
 public func testCondCastNSNumberToSwiftInt() -> Int? {
@@ -77,7 +77,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding35testForcedCastNSNumberToSwiftDoubleSdyF
 // CHECK-NOT: unconditional_checked
-// CHECK: function_ref @_T0Sd10FoundationE26_forceBridgeFromObjectiveCySo8NSNumberC_SdSgz6resulttFZ : $@convention(method) (@owned NSNumber, @inout Optional<Double>, @thin Double.Type) -> ()
+// CHECK: function_ref @_T0Sd10FoundationE26_forceBridgeFromObjectiveC_6resultySo8NSNumberC_SdSgztFZ : $@convention(method) (@owned NSNumber, @inout Optional<Double>, @thin Double.Type) -> ()
 // CHECK: return
 @inline(never)
 public func testForcedCastNSNumberToSwiftDouble() -> Double {
@@ -87,7 +87,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding33testCondCastNSNumberToSwiftDoubleSdSgyF
 // CHECK-NOT: checked_cast
-// CHECK: function_ref @_T0Sd10FoundationE34_conditionallyBridgeFromObjectiveCSbSo8NSNumberC_SdSgz6resulttFZ : $@convention(method) (@owned NSNumber, @inout Optional<Double>, @thin Double.Type) -> Bool
+// CHECK: function_ref @_T0Sd10FoundationE34_conditionallyBridgeFromObjectiveC_6resultSbSo8NSNumberC_SdSgztFZ : $@convention(method) (@owned NSNumber, @inout Optional<Double>, @thin Double.Type) -> Bool
 // CHECK: return
 @inline(never)
 public func testCondCastNSNumberToSwiftDouble() -> Double? {
@@ -97,7 +97,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding38testForcedCastNSIntNumberToSwiftDoubleSdyF
 // CHECK-NOT: unconditional_checked
-// CHECK: function_ref @_T0Sd10FoundationE26_forceBridgeFromObjectiveCySo8NSNumberC_SdSgz6resulttFZ : $@convention(method) (@owned NSNumber, @inout Optional<Double>, @thin Double.Type) -> ()
+// CHECK: function_ref @_T0Sd10FoundationE26_forceBridgeFromObjectiveC_6resultySo8NSNumberC_SdSgztFZ : $@convention(method) (@owned NSNumber, @inout Optional<Double>, @thin Double.Type) -> ()
 // CHECK: return
 @inline(never)
 public func testForcedCastNSIntNumberToSwiftDouble() -> Double {
@@ -107,7 +107,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding36testCondCastNSIntNumberToSwiftDoubleSdSgyF
 // CHECK-NOT: checked_cast
-// CHECK: function_ref @_T0Sd10FoundationE34_conditionallyBridgeFromObjectiveCSbSo8NSNumberC_SdSgz6resulttFZ : $@convention(method) (@owned NSNumber, @inout Optional<Double>, @thin Double.Type) -> Bool
+// CHECK: function_ref @_T0Sd10FoundationE34_conditionallyBridgeFromObjectiveC_6resultSbSo8NSNumberC_SdSgztFZ : $@convention(method) (@owned NSNumber, @inout Optional<Double>, @thin Double.Type) -> Bool
 // CHECK: return
 @inline(never)
 public func testCondCastNSIntNumberToSwiftDouble() -> Double? {
@@ -125,7 +125,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding31testForcedCastNStoSwiftArrayIntSaySiGyF
 // CHECK-NOT: unconditional_checked
-// CHECK: function_ref @_T0Sa10FoundationE26_forceBridgeFromObjectiveCySo7NSArrayC_SayxGSgz6resulttFZ : $@convention(method) <τ_0_0> (@owned NSArray, @inout Optional<Array<τ_0_0>>, @thin Array<τ_0_0>.Type) -> ()
+// CHECK: function_ref @_T0Sa10FoundationE26_forceBridgeFromObjectiveC_6resultySo7NSArrayC_SayxGSgztFZ : $@convention(method) <τ_0_0> (@owned NSArray, @inout Optional<Array<τ_0_0>>, @thin Array<τ_0_0>.Type) -> ()
 // CHECK: return
 @inline(never)
 public func testForcedCastNStoSwiftArrayInt() -> [Int] {
@@ -135,7 +135,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding29testCondCastNStoSwiftArrayIntSaySiGSgyF
 // CHECK-NOT: checked_cast
-// CHECK: function_ref @_T0Sa10FoundationE34_conditionallyBridgeFromObjectiveCSbSo7NSArrayC_SayxGSgz6resulttFZ : $@convention(method) <τ_0_0> (@owned NSArray, @inout Optional<Array<τ_0_0>>, @thin Array<τ_0_0>.Type) -> Bool
+// CHECK: function_ref @_T0Sa10FoundationE34_conditionallyBridgeFromObjectiveC_6resultSbSo7NSArrayC_SayxGSgztFZ : $@convention(method) <τ_0_0> (@owned NSArray, @inout Optional<Array<τ_0_0>>, @thin Array<τ_0_0>.Type) -> Bool
 // CHECK: return
 @inline(never)
 public func testCondCastNStoSwiftArrayInt() -> [Int]? {
@@ -145,7 +145,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding34testForcedCastNStoSwiftArrayDoubleSaySdGyF
 // CHECK-NOT: unconditional_checked
-// CHECK: function_ref @_T0Sa10FoundationE26_forceBridgeFromObjectiveCySo7NSArrayC_SayxGSgz6resulttFZ : $@convention(method) <τ_0_0> (@owned NSArray, @inout Optional<Array<τ_0_0>>, @thin Array<τ_0_0>.Type) -> ()
+// CHECK: function_ref @_T0Sa10FoundationE26_forceBridgeFromObjectiveC_6resultySo7NSArrayC_SayxGSgztFZ : $@convention(method) <τ_0_0> (@owned NSArray, @inout Optional<Array<τ_0_0>>, @thin Array<τ_0_0>.Type) -> ()
 // CHECK: return
 @inline(never)
 public func testForcedCastNStoSwiftArrayDouble() -> [Double] {
@@ -155,7 +155,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding32testCondCastNStoSwiftArrayDoubleSaySdGSgyF
 // CHECK-NOT: checked_cast
-// CHECK: function_ref @_T0Sa10FoundationE34_conditionallyBridgeFromObjectiveCSbSo7NSArrayC_SayxGSgz6resulttFZ : $@convention(method) <τ_0_0> (@owned NSArray, @inout Optional<Array<τ_0_0>>, @thin Array<τ_0_0>.Type) -> Bool
+// CHECK: function_ref @_T0Sa10FoundationE34_conditionallyBridgeFromObjectiveC_6resultSbSo7NSArrayC_SayxGSgztFZ : $@convention(method) <τ_0_0> (@owned NSArray, @inout Optional<Array<τ_0_0>>, @thin Array<τ_0_0>.Type) -> Bool
 // CHECK: return
 @inline(never)
 public func testCondCastNStoSwiftArrayDouble() -> [Double]? {
@@ -166,7 +166,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding34testForcedCastNStoSwiftArrayStringSaySSGyF
 // CHECK-NOT: unconditional_checked
-// CHECK: function_ref @_T0Sa10FoundationE26_forceBridgeFromObjectiveCySo7NSArrayC_SayxGSgz6resulttFZ : $@convention(method) <τ_0_0> (@owned NSArray, @inout Optional<Array<τ_0_0>>, @thin Array<τ_0_0>.Type) -> ()
+// CHECK: function_ref @_T0Sa10FoundationE26_forceBridgeFromObjectiveC_6resultySo7NSArrayC_SayxGSgztFZ : $@convention(method) <τ_0_0> (@owned NSArray, @inout Optional<Array<τ_0_0>>, @thin Array<τ_0_0>.Type) -> ()
 // CHECK: return
 @inline(never)
 public func testForcedCastNStoSwiftArrayString() -> [String] {
@@ -176,7 +176,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding32testCondCastNStoSwiftArrayStringSaySSGSgyF
 // CHECK-NOT: checked_cast
-// CHECK: function_ref @_T0Sa10FoundationE34_conditionallyBridgeFromObjectiveCSbSo7NSArrayC_SayxGSgz6resulttFZ : $@convention(method) <τ_0_0> (@owned NSArray, @inout Optional<Array<τ_0_0>>, @thin Array<τ_0_0>.Type) -> Bool
+// CHECK: function_ref @_T0Sa10FoundationE34_conditionallyBridgeFromObjectiveC_6resultSbSo7NSArrayC_SayxGSgztFZ : $@convention(method) <τ_0_0> (@owned NSArray, @inout Optional<Array<τ_0_0>>, @thin Array<τ_0_0>.Type) -> Bool
 // CHECK: return
 @inline(never)
 public func testCondCastNStoSwiftArrayString() -> [String]? {
@@ -194,7 +194,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding30testForcedCastNStoSwiftDictInts10DictionaryVyS2iGyF
 // CHECK-NOT: unconditional_checked
-// CHECK: function_ref @_T0s10DictionaryV10FoundationE26_forceBridgeFromObjectiveCySo12NSDictionaryC_AByxq_GSgz6resulttFZ : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@owned NSDictionary, @inout Optional<Dictionary<τ_0_0, τ_0_1>>, @thin Dictionary<τ_0_0, τ_0_1>.Type) -> ()
+// CHECK: function_ref @_T0s10DictionaryV10FoundationE26_forceBridgeFromObjectiveC_6resultySo12NSDictionaryC_AByxq_GSgztFZ : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@owned NSDictionary, @inout Optional<Dictionary<τ_0_0, τ_0_1>>, @thin Dictionary<τ_0_0, τ_0_1>.Type) -> ()
 // CHECK: return
 @inline(never)
 public func testForcedCastNStoSwiftDictInt() -> [Int: Int] {
@@ -204,7 +204,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding28testCondCastNStoSwiftDictInts10DictionaryVyS2iGSgyF
 // CHECK-NOT: checked_cast
-// CHECK: function_ref @_T0s10DictionaryV10FoundationE34_conditionallyBridgeFromObjectiveCSbSo12NSDictionaryC_AByxq_GSgz6resulttFZ : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@owned NSDictionary, @inout Optional<Dictionary<τ_0_0, τ_0_1>>, @thin Dictionary<τ_0_0, τ_0_1>.Type) -> Bool
+// CHECK: function_ref @_T0s10DictionaryV10FoundationE34_conditionallyBridgeFromObjectiveC_6resultSbSo12NSDictionaryC_AByxq_GSgztFZ : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@owned NSDictionary, @inout Optional<Dictionary<τ_0_0, τ_0_1>>, @thin Dictionary<τ_0_0, τ_0_1>.Type) -> Bool
 // CHECK: return
 @inline(never)
 public func testCondCastNStoSwiftDictInt() -> [Int: Int]? {
@@ -214,7 +214,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding33testForcedCastNStoSwiftDictDoubles10DictionaryVyS2dGyF
 // CHECK-NOT: unconditional_checked
-// CHECK: function_ref @_T0s10DictionaryV10FoundationE26_forceBridgeFromObjectiveCySo12NSDictionaryC_AByxq_GSgz6resulttFZ : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@owned NSDictionary, @inout Optional<Dictionary<τ_0_0, τ_0_1>>, @thin Dictionary<τ_0_0, τ_0_1>.Type) -> ()
+// CHECK: function_ref @_T0s10DictionaryV10FoundationE26_forceBridgeFromObjectiveC_6resultySo12NSDictionaryC_AByxq_GSgztFZ : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@owned NSDictionary, @inout Optional<Dictionary<τ_0_0, τ_0_1>>, @thin Dictionary<τ_0_0, τ_0_1>.Type) -> ()
 // CHECK: return
 @inline(never)
 public func testForcedCastNStoSwiftDictDouble() -> [Double: Double] {
@@ -224,7 +224,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding31testCondCastNStoSwiftDictDoubles10DictionaryVyS2dGSgyF
 // CHECK-NOT: checked_cast
-// CHECK: function_ref @_T0s10DictionaryV10FoundationE34_conditionallyBridgeFromObjectiveCSbSo12NSDictionaryC_AByxq_GSgz6resulttFZ : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@owned NSDictionary, @inout Optional<Dictionary<τ_0_0, τ_0_1>>, @thin Dictionary<τ_0_0, τ_0_1>.Type) -> Bool
+// CHECK: function_ref @_T0s10DictionaryV10FoundationE34_conditionallyBridgeFromObjectiveC_6resultSbSo12NSDictionaryC_AByxq_GSgztFZ : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@owned NSDictionary, @inout Optional<Dictionary<τ_0_0, τ_0_1>>, @thin Dictionary<τ_0_0, τ_0_1>.Type) -> Bool
 // CHECK: return
 @inline(never)
 public func testCondCastNStoSwiftDictDouble() -> [Double: Double]? {
@@ -235,7 +235,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding33testForcedCastNStoSwiftDictStrings10DictionaryVyS2SGyF
 // CHECK-NOT: unconditional_checked
-// CHECK: function_ref @_T0s10DictionaryV10FoundationE26_forceBridgeFromObjectiveCySo12NSDictionaryC_AByxq_GSgz6resulttFZ : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@owned NSDictionary, @inout Optional<Dictionary<τ_0_0, τ_0_1>>, @thin Dictionary<τ_0_0, τ_0_1>.Type) -> ()
+// CHECK: function_ref @_T0s10DictionaryV10FoundationE26_forceBridgeFromObjectiveC_6resultySo12NSDictionaryC_AByxq_GSgztFZ : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@owned NSDictionary, @inout Optional<Dictionary<τ_0_0, τ_0_1>>, @thin Dictionary<τ_0_0, τ_0_1>.Type) -> ()
 // CHECK: return
 @inline(never)
 public func testForcedCastNStoSwiftDictString() -> [String: String] {
@@ -245,7 +245,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding31testCondCastNStoSwiftDictStrings10DictionaryVyS2SGSgyF
 // CHECK-NOT: checked_cast
-// CHECK: function_ref @_T0s10DictionaryV10FoundationE34_conditionallyBridgeFromObjectiveCSbSo12NSDictionaryC_AByxq_GSgz6resulttFZ : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@owned NSDictionary, @inout Optional<Dictionary<τ_0_0, τ_0_1>>, @thin Dictionary<τ_0_0, τ_0_1>.Type) -> Bool
+// CHECK: function_ref @_T0s10DictionaryV10FoundationE34_conditionallyBridgeFromObjectiveC_6resultSbSo12NSDictionaryC_AByxq_GSgztFZ : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@owned NSDictionary, @inout Optional<Dictionary<τ_0_0, τ_0_1>>, @thin Dictionary<τ_0_0, τ_0_1>.Type) -> Bool
 // CHECK: return
 @inline(never)
 public func testCondCastNStoSwiftDictString() -> [String: String]? {
@@ -255,7 +255,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding40testForcedCastNSDictStringtoSwiftDictInts10DictionaryVyS2iGyF
 // CHECK-NOT: unconditional_checked
-// CHECK: function_ref @_T0s10DictionaryV10FoundationE26_forceBridgeFromObjectiveCySo12NSDictionaryC_AByxq_GSgz6resulttFZ : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@owned NSDictionary, @inout Optional<Dictionary<τ_0_0, τ_0_1>>, @thin Dictionary<τ_0_0, τ_0_1>.Type) -> ()
+// CHECK: function_ref @_T0s10DictionaryV10FoundationE26_forceBridgeFromObjectiveC_6resultySo12NSDictionaryC_AByxq_GSgztFZ : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@owned NSDictionary, @inout Optional<Dictionary<τ_0_0, τ_0_1>>, @thin Dictionary<τ_0_0, τ_0_1>.Type) -> ()
 // CHECK: return
 @inline(never)
 public func testForcedCastNSDictStringtoSwiftDictInt() -> [Int: Int] {
@@ -266,7 +266,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding38testCondCastNSDictStringtoSwiftDictInts10DictionaryVyS2iGSgyF
 // CHECK-NOT: checked_cast
-// CHECK: function_ref @_T0s10DictionaryV10FoundationE34_conditionallyBridgeFromObjectiveCSbSo12NSDictionaryC_AByxq_GSgz6resulttFZ : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@owned NSDictionary, @inout Optional<Dictionary<τ_0_0, τ_0_1>>, @thin Dictionary<τ_0_0, τ_0_1>.Type) -> Bool
+// CHECK: function_ref @_T0s10DictionaryV10FoundationE34_conditionallyBridgeFromObjectiveC_6resultSbSo12NSDictionaryC_AByxq_GSgztFZ : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@owned NSDictionary, @inout Optional<Dictionary<τ_0_0, τ_0_1>>, @thin Dictionary<τ_0_0, τ_0_1>.Type) -> Bool
 // CHECK: return
 @inline(never)
 public func testCondCastNSDictStringtoSwiftDictInt() -> [Int: Int]? {
@@ -283,7 +283,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding29testForcedCastNStoSwiftSetInts0I0VySiGyF
 // CHECK-NOT: unconditional_checked
-// CHECK: function_ref @_T0s3SetV10FoundationE26_forceBridgeFromObjectiveCySo5NSSetC_AByxGSgz6resulttFZ : $@convention(method) <τ_0_0 where τ_0_0 : Hashable> (@owned NSSet, @inout Optional<Set<τ_0_0>>, @thin Set<τ_0_0>.Type) -> ()
+// CHECK: function_ref @_T0s3SetV10FoundationE26_forceBridgeFromObjectiveC_6resultySo5NSSetC_AByxGSgztFZ : $@convention(method) <τ_0_0 where τ_0_0 : Hashable> (@owned NSSet, @inout Optional<Set<τ_0_0>>, @thin Set<τ_0_0>.Type) -> ()
 // CHECK: return
 @inline(never)
 public func testForcedCastNStoSwiftSetInt() -> Set<Int> {
@@ -293,7 +293,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding27testCondCastNStoSwiftSetInts0I0VySiGSgyF
 // CHECK-NOT: checked_cast
-// CHECK: function_ref @_T0s3SetV10FoundationE34_conditionallyBridgeFromObjectiveCSbSo5NSSetC_AByxGSgz6resulttFZ : $@convention(method) <τ_0_0 where τ_0_0 : Hashable> (@owned NSSet, @inout Optional<Set<τ_0_0>>, @thin Set<τ_0_0>.Type) -> Bool
+// CHECK: function_ref @_T0s3SetV10FoundationE34_conditionallyBridgeFromObjectiveC_6resultSbSo5NSSetC_AByxGSgztFZ : $@convention(method) <τ_0_0 where τ_0_0 : Hashable> (@owned NSSet, @inout Optional<Set<τ_0_0>>, @thin Set<τ_0_0>.Type) -> Bool
 // CHECK: return
 @inline(never)
 public func testCondCastNStoSwiftSetInt() -> Set<Int>? {
@@ -303,7 +303,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding32testForcedCastNStoSwiftSetDoubles0I0VySdGyF
 // CHECK-NOT: unconditional_checked
-// CHECK: function_ref @_T0s3SetV10FoundationE26_forceBridgeFromObjectiveCySo5NSSetC_AByxGSgz6resulttFZ : $@convention(method) <τ_0_0 where τ_0_0 : Hashable> (@owned NSSet, @inout Optional<Set<τ_0_0>>, @thin Set<τ_0_0>.Type) -> ()
+// CHECK: function_ref @_T0s3SetV10FoundationE26_forceBridgeFromObjectiveC_6resultySo5NSSetC_AByxGSgztFZ : $@convention(method) <τ_0_0 where τ_0_0 : Hashable> (@owned NSSet, @inout Optional<Set<τ_0_0>>, @thin Set<τ_0_0>.Type) -> ()
 // CHECK: return
 @inline(never)
 public func testForcedCastNStoSwiftSetDouble() -> Set<Double> {
@@ -313,7 +313,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding30testCondCastNStoSwiftSetDoubles0I0VySdGSgyF
 // CHECK-NOT: checked_cast
-// CHECK: function_ref @_T0s3SetV10FoundationE34_conditionallyBridgeFromObjectiveCSbSo5NSSetC_AByxGSgz6resulttFZ : $@convention(method) <τ_0_0 where τ_0_0 : Hashable> (@owned NSSet, @inout Optional<Set<τ_0_0>>, @thin Set<τ_0_0>.Type) -> Bool
+// CHECK: function_ref @_T0s3SetV10FoundationE34_conditionallyBridgeFromObjectiveC_6resultSbSo5NSSetC_AByxGSgztFZ : $@convention(method) <τ_0_0 where τ_0_0 : Hashable> (@owned NSSet, @inout Optional<Set<τ_0_0>>, @thin Set<τ_0_0>.Type) -> Bool
 // CHECK: return
 @inline(never)
 public func testCondCastNStoSwiftSetDouble() -> Set<Double>? {
@@ -324,7 +324,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding32testForcedCastNStoSwiftSetStrings0I0VySSGyF
 // CHECK-NOT: unconditional_checked
-// CHECK: function_ref @_T0s3SetV10FoundationE26_forceBridgeFromObjectiveCySo5NSSetC_AByxGSgz6resulttFZ : $@convention(method) <τ_0_0 where τ_0_0 : Hashable> (@owned NSSet, @inout Optional<Set<τ_0_0>>, @thin Set<τ_0_0>.Type) -> ()
+// CHECK: function_ref @_T0s3SetV10FoundationE26_forceBridgeFromObjectiveC_6resultySo5NSSetC_AByxGSgztFZ : $@convention(method) <τ_0_0 where τ_0_0 : Hashable> (@owned NSSet, @inout Optional<Set<τ_0_0>>, @thin Set<τ_0_0>.Type) -> ()
 // CHECK: return
 @inline(never)
 public func testForcedCastNStoSwiftSetString() -> Set<String> {
@@ -334,7 +334,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T021bridged_casts_folding30testCondCastNStoSwiftSetStrings0I0VySSGSgyF
 // CHECK-NOT: checked_cast
-// CHECK: function_ref @_T0s3SetV10FoundationE34_conditionallyBridgeFromObjectiveCSbSo5NSSetC_AByxGSgz6resulttFZ : $@convention(method) <τ_0_0 where τ_0_0 : Hashable> (@owned NSSet, @inout Optional<Set<τ_0_0>>, @thin Set<τ_0_0>.Type) -> Bool
+// CHECK: function_ref @_T0s3SetV10FoundationE34_conditionallyBridgeFromObjectiveC_6resultSbSo5NSSetC_AByxGSgztFZ : $@convention(method) <τ_0_0 where τ_0_0 : Hashable> (@owned NSSet, @inout Optional<Set<τ_0_0>>, @thin Set<τ_0_0>.Type) -> Bool
 // CHECK: return
 @inline(never)
 public func testCondCastNStoSwiftSetString() -> Set<String>? {
@@ -911,3 +911,36 @@
 public func testUncondCastSwiftToSubclass() -> NSObjectSubclass {
   return anyHashable as! NSObjectSubclass
 }
+
+class MyThing: Hashable {
+    let name: String
+    
+    init(name: String) {
+        self.name = name
+    }
+    
+    deinit {
+        Swift.print("Deinit \(name)")
+    }
+    
+    var hashValue: Int {
+        return 0
+    }
+    
+    static func ==(lhs: MyThing, rhs: MyThing) -> Bool {
+        return false
+    }
+}
+
+// CHECK-LABEL: sil hidden [noinline] @_T021bridged_casts_folding26doSomethingWithAnyHashableyys0gH0VF : $@convention(thin) (@in AnyHashable) -> ()
+// CHECK: checked_cast_addr_br take_always AnyHashable in %0 : $*AnyHashable to MyThing
+@inline(never)
+func doSomethingWithAnyHashable(_ item: AnyHashable) {
+  _ = item as? MyThing
+}
+
+@inline(never)
+public func testMyThing() {
+  let x = MyThing(name: "B")
+  doSomethingWithAnyHashable(x)
+}
diff --git a/test/SILOptimizer/capture_promotion.sil b/test/SILOptimizer/capture_promotion.sil
index 027bcfb..1aec79e 100644
--- a/test/SILOptimizer/capture_promotion.sil
+++ b/test/SILOptimizer/capture_promotion.sil
@@ -267,7 +267,7 @@
 bb0(%0 : $<τ_0_0> { var τ_0_0 } <Int>, %2 : $<τ_0_0> { var τ_0_0 } <Int>):
   %1 = project_box %0 : $<τ_0_0> { var τ_0_0 } <Int>, 0
   %3 = project_box %2 : $<τ_0_0> { var τ_0_0 } <Int>, 0
-  %4 = function_ref @_T0s1poiSiSi_SitF : $@convention(thin) (Int, Int) -> Int
+  %4 = function_ref @_T0s1poiyS2i_SitF : $@convention(thin) (Int, Int) -> Int
   %5 = load %3 : $*Int
   %6 = load %3 : $*Int
   %7 = apply %4(%5, %6) : $@convention(thin) (Int, Int) -> Int
@@ -278,7 +278,7 @@
   return %11 : $()
 }
 
-sil [transparent] [serialized] @_T0s1poiSiSi_SitF : $@convention(thin) (Int, Int) -> Int
+sil [transparent] [serialized] @_T0s1poiyS2i_SitF : $@convention(thin) (Int, Int) -> Int
 
 
 sil private @closure_indirect_result : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Foo>, @owned <τ_0_0> { var τ_0_0 } <Baz>, @owned <τ_0_0> { var τ_0_0 } <Int>) -> @out Int {
diff --git a/test/SILOptimizer/capture_promotion_ownership.sil b/test/SILOptimizer/capture_promotion_ownership.sil
index 601a0e4..e2e8dc6 100644
--- a/test/SILOptimizer/capture_promotion_ownership.sil
+++ b/test/SILOptimizer/capture_promotion_ownership.sil
@@ -296,7 +296,7 @@
 bb0(%0 : @owned $<τ_0_0> { var τ_0_0 } <Int>, %2 : @owned $<τ_0_0> { var τ_0_0 } <Int>):
   %1 = project_box %0 : $<τ_0_0> { var τ_0_0 } <Int>, 0
   %3 = project_box %2 : $<τ_0_0> { var τ_0_0 } <Int>, 0
-  %4 = function_ref @_T0s1poiSiSi_SitF : $@convention(thin) (Int, Int) -> Int
+  %4 = function_ref @_T0s1poiyS2i_SitF : $@convention(thin) (Int, Int) -> Int
   %5 = load [trivial] %3 : $*Int
   %6 = load [trivial] %3 : $*Int
   %7 = apply %4(%5, %6) : $@convention(thin) (Int, Int) -> Int
@@ -307,7 +307,7 @@
   return %11 : $()
 }
 
-sil [transparent] [serialized] @_T0s1poiSiSi_SitF : $@convention(thin) (Int, Int) -> Int
+sil [transparent] [serialized] @_T0s1poiyS2i_SitF : $@convention(thin) (Int, Int) -> Int
 
 sil private @closure_indirect_result : $@convention(thin) (@owned <τ_0_0> { var τ_0_0 } <Foo>, @owned <τ_0_0> { var τ_0_0 } <Baz>, @owned <τ_0_0> { var τ_0_0 } <Int>) -> @out Int {
 bb0(%0: @trivial $*Int, %1 : @owned $<τ_0_0> { var τ_0_0 } <Foo>, %2 : @owned $<τ_0_0> { var τ_0_0 } <Baz>, %4 : @owned $<τ_0_0> { var τ_0_0 } <Int>):
diff --git a/test/SILOptimizer/cast_folding.swift b/test/SILOptimizer/cast_folding.swift
index 4305260..fb1cb43 100644
--- a/test/SILOptimizer/cast_folding.swift
+++ b/test/SILOptimizer/cast_folding.swift
@@ -738,7 +738,7 @@
 // Check that the body of the function
 // contains a trap followed by unreachable
 // and no code afterwards.
-// CHECK-LABEL: sil @_T012cast_folding7getAsDDAA0E0CAA2CCCF
+// CHECK-LABEL: sil @_T012cast_folding7getAsDDyAA0E0CAA2CCCF
 // CHECK: builtin "int_trap"
 // CHECK-NEXT: unreachable
 // CHECK-NEXT: }
@@ -749,7 +749,7 @@
 // Check that the body of the function
 // contains a trap followed by unreachable
 // and no code afterwards.
-// CHECK-LABEL: sil @_T012cast_folding7callFooSiAA2CCCF
+// CHECK-LABEL: sil @_T012cast_folding7callFooySiAA2CCCF
 // CHECK: builtin "int_trap"
 // CHECK-NEXT: unreachable
 // CHECK-NEXT: }
@@ -765,7 +765,7 @@
 
 // Check that the inlined version of callFooGeneric contains only a trap
 // followed by unreachable and no code afterwards
-// CHECK-LABEL: sil [noinline] @_T012cast_folding16callForGenericCCyAA0F0CF
+// CHECK-LABEL: sil [noinline] @_T012cast_folding16callForGenericCCyyAA0F0CF
 // CHECK: builtin "int_trap"
 // CHECK-NEXT: unreachable
 // CHECK-NEXT: }
diff --git a/test/SILOptimizer/cast_folding_no_bridging.sil b/test/SILOptimizer/cast_folding_no_bridging.sil
index 88c00cf..35a01a8 100644
--- a/test/SILOptimizer/cast_folding_no_bridging.sil
+++ b/test/SILOptimizer/cast_folding_no_bridging.sil
@@ -85,7 +85,7 @@
 // CHECK: bb0(
 // CHECK-NEXT: [[T0:%.*]] = load %1 : $*CFString
 // CHECK-NEXT: [[T1:%.*]] = unchecked_ref_cast [[T0]] : $CFString to $NSString
-// CHECK:      [[FN:%.*]] = function_ref @_T0SS10FoundationE34_conditionallyBridgeFromObjectiveCSbSo8NSStringC_SSSgz6resulttFZ : $@convention(method) (@owned NSString, @inout Optional<String>, @thin String.Type) -> Bool
+// CHECK:      [[FN:%.*]] = function_ref @_T0SS10FoundationE34_conditionallyBridgeFromObjectiveC_6resultSbSo8NSStringC_SSSgztFZ : $@convention(method) (@owned NSString, @inout Optional<String>, @thin String.Type) -> Bool
 // CHECK: apply [[FN]]([[T1]], {{.*}}, {{.*}})
 sil @testCFToSwift : $@convention(thin) (@in CFString) -> @out String {
 bb0(%0 : $*String, %1 : $*CFString):
diff --git a/test/SILOptimizer/cast_folding_objc.swift b/test/SILOptimizer/cast_folding_objc.swift
index 8f98198..16d16aa 100644
--- a/test/SILOptimizer/cast_folding_objc.swift
+++ b/test/SILOptimizer/cast_folding_objc.swift
@@ -52,7 +52,7 @@
 // the compiler does not statically know if this object
 // is NSNumber can be converted into Int.
 
-// CHECK-LABEL: sil [noinline] @_T017cast_folding_objc35testMayBeBridgedCastFromObjCtoSwiftSiyXlF
+// CHECK-LABEL: sil [noinline] @_T017cast_folding_objc35testMayBeBridgedCastFromObjCtoSwiftySiyXlF
 // CHECK: unconditional_checked_cast_addr
 // CHECK: return
 @inline(never)
@@ -64,7 +64,7 @@
 // the compiler does not statically know if this object
 // is NSString can be converted into String.
 
-// CHECK-LABEL: sil [noinline] @_T017cast_folding_objc41testConditionalBridgedCastFromObjCtoSwiftSSSgyXlF
+// CHECK-LABEL: sil [noinline] @_T017cast_folding_objc41testConditionalBridgedCastFromObjCtoSwiftySSSgyXlF
 // CHECK: unconditional_checked_cast_addr
 // CHECK: return
 @inline(never)
@@ -77,7 +77,7 @@
 }
 
 // Check that compiler understands that this cast always fails
-// CHECK-LABEL: sil [noinline] @_T017cast_folding_objc37testFailingBridgedCastFromObjCtoSwiftSiSo8NSStringCF
+// CHECK-LABEL: sil [noinline] @_T017cast_folding_objc37testFailingBridgedCastFromObjCtoSwiftySiSo8NSStringCF
 // CHECK: builtin "int_trap"
 // CHECK-NEXT: unreachable
 // CHECK-NEXT: }
@@ -87,7 +87,7 @@
 }
 
 // Check that compiler understands that this cast always fails
-// CHECK-LABEL: sil [noinline] @_T017cast_folding_objc37testFailingBridgedCastFromSwiftToObjCSiSSF
+// CHECK-LABEL: sil [noinline] @_T017cast_folding_objc37testFailingBridgedCastFromSwiftToObjCySiSSF
 // CHECK: builtin "int_trap"
 // CHECK-NEXT: unreachable
 // CHECK-NEXT: }
@@ -297,7 +297,7 @@
 
 // Check that compiler understands that this cast always succeeds
 
-// CHECK-LABEL: sil [noinline] @_T017cast_folding_objc30testBridgedCastFromSwiftToObjCSo8NSStringCSSF
+// CHECK-LABEL: sil [noinline] @_T017cast_folding_objc30testBridgedCastFromSwiftToObjCySo8NSStringCSSF
 // CHECK-NOT: {{ cast}}
 // CHECK: function_ref @_T0SS10FoundationE19_bridgeToObjectiveC{{[_0-9a-zA-Z]*}}F
 // CHECK: apply
diff --git a/test/SILOptimizer/cast_folding_objc_no_foundation.swift b/test/SILOptimizer/cast_folding_objc_no_foundation.swift
index b05ed57..a59bed0 100644
--- a/test/SILOptimizer/cast_folding_objc_no_foundation.swift
+++ b/test/SILOptimizer/cast_folding_objc_no_foundation.swift
@@ -7,7 +7,7 @@
 
 struct PlainStruct {}
 
-// CHECK-LABEL: sil shared [noinline] @_T031cast_folding_objc_no_foundation23testAnyObjectToArrayIntSbyXlFTf4g_n
+// CHECK-LABEL: sil shared [noinline] @_T031cast_folding_objc_no_foundation23testAnyObjectToArrayIntySbyXlFTf4g_n
 // CHECK: bb0(%0 : $AnyObject):
 // CHECK: [[SOURCE:%.*]] = alloc_stack $AnyObject
 // CHECK: [[TARGET:%.*]] = alloc_stack $Array<Int>
@@ -17,7 +17,7 @@
   return a is [Int]
 }
 
-// CHECK-LABEL: sil shared [noinline] @_T031cast_folding_objc_no_foundation26testAnyObjectToArrayStringSbyXlFTf4g_n
+// CHECK-LABEL: sil shared [noinline] @_T031cast_folding_objc_no_foundation26testAnyObjectToArrayStringySbyXlFTf4g_n
 // CHECK: bb0(%0 : $AnyObject):
 // CHECK: [[SOURCE:%.*]] = alloc_stack $AnyObject
 // CHECK: [[TARGET:%.*]] = alloc_stack $Array<String>
@@ -37,7 +37,7 @@
   return a is [PlainStruct]
 }
 
-// CHECK-LABEL: sil shared [noinline] @_T031cast_folding_objc_no_foundation25testAnyObjectToDictionarySbyXlFTf4g_n
+// CHECK-LABEL: sil shared [noinline] @_T031cast_folding_objc_no_foundation25testAnyObjectToDictionaryySbyXlFTf4g_n
 // CHECK: bb0(%0 : $AnyObject):
 // CHECK: [[SOURCE:%.*]] = alloc_stack $AnyObject
 // CHECK: [[TARGET:%.*]] = alloc_stack $Dictionary<Int, String>
@@ -47,7 +47,7 @@
   return a is [Int: String]
 }
 
-// CHECK-LABEL: sil shared [noinline] @_T031cast_folding_objc_no_foundation21testAnyObjectToStringSbyXlFTf4g_n
+// CHECK-LABEL: sil shared [noinline] @_T031cast_folding_objc_no_foundation21testAnyObjectToStringySbyXlFTf4g_n
 // CHECK: bb0(%0 : $AnyObject):
 // CHECK: [[SOURCE:%.*]] = alloc_stack $AnyObject
 // CHECK: [[TARGET:%.*]] = alloc_stack $String
diff --git a/test/SILOptimizer/cast_foldings.sil b/test/SILOptimizer/cast_foldings.sil
index 0a9bde5..b34b4d4 100644
--- a/test/SILOptimizer/cast_foldings.sil
+++ b/test/SILOptimizer/cast_foldings.sil
@@ -139,3 +139,13 @@
   return %r : $()
 }
 
+// CHECK-LABEL: sil @testIOU
+// CHECK: bb0(%0 : $*Optional<AnyObject>, %1 : $*Optional<AnyObject>):
+// CHECK:  [[TMP:%.*]] = load %1 : $*Optional<AnyObject>
+// CHECK:  store [[TMP]] to %0 : $*Optional<AnyObject>
+sil @testIOU : $@convention(thin) (@in Optional<AnyObject>) -> (@out Optional<AnyObject>) {
+bb0(%0 : $*Optional<AnyObject>, %1: $*Optional<AnyObject>):
+  unconditional_checked_cast_addr ImplicitlyUnwrappedOptional<AnyObject> in %1 : $*Optional<AnyObject> to Optional<AnyObject> in %0 : $*Optional<AnyObject>
+  %2 = tuple ()
+  return %2 : $()
+}
diff --git a/test/SILOptimizer/closure_spec_and_inline.swift b/test/SILOptimizer/closure_spec_and_inline.swift
index 57c1afb..5e0d06f 100644
--- a/test/SILOptimizer/closure_spec_and_inline.swift
+++ b/test/SILOptimizer/closure_spec_and_inline.swift
@@ -7,7 +7,7 @@
 // Check that closure() is inlined into call_closure after call_closure is
 // specialized for it.
 
-// CHECK-LABEL: sil shared [noinline] @_T04test12call_closureSbSi_SiSbSi_SitctF27_T04test7closureSbSi_Si1btFTf1nnc_n
+// CHECK-LABEL: sil shared [noinline] @_T04test12call_closureySbSi_SiSbSi_SitctF28_T04test7closure_1bSbSi_SitFTf1nnc_n
 // CHECK-NOT: apply
 // CHECK: builtin "cmp_slt_Int
 // CHECK-NOT: apply
diff --git a/test/SILOptimizer/closure_specialize.sil b/test/SILOptimizer/closure_specialize.sil
index 244dd3c..bd20bce 100644
--- a/test/SILOptimizer/closure_specialize.sil
+++ b/test/SILOptimizer/closure_specialize.sil
@@ -3,18 +3,19 @@
 import Builtin
 import Swift
 
-// CHECK-LABEL: sil shared [noinline] @_T07specgen12take_closureyySi_SitcF023_T07specgen6callerySiFyE8_SitcfU_SiTf1c_n : $@convention(thin) (Int) -> () {
+// CHECK-LABEL: sil shared [noinline] @_T07specgen12take_closureyyySi_SitcF024_T07specgen6calleryySiFyE8_SitcfU_SiTf1c_n : $@convention(thin) (Int) -> () {
+
 // CHECK: bb0(%0 : $Int)
-// CHECK: function_ref @_T07specgen6callerySiFySi_SitcfU_
+// CHECK: function_ref @_T07specgen6calleryySiFySi_SitcfU_
 // CHECK: partial_apply
 
-// CHECK-LABEL: sil shared [noinline] @_T07specgen12take_closureyySi_SitcF26_T07specgen6calleeySi_SitFTf1c_n : $@convention(thin) () -> () {
+// CHECK-LABEL: sil shared [noinline] @_T07specgen12take_closureyyySi_SitcF27_T07specgen6calleeyySi_SitFTf1c_n : $@convention(thin) () -> () {
 // CHECK-NEXT: bb0:
-// CHECK: [[FUN:%.*]] = function_ref @_T07specgen6calleeySi_SitF : $@convention(thin) (Int, Int) -> ()
+// CHECK: [[FUN:%.*]] = function_ref @_T07specgen6calleeyySi_SitF : $@convention(thin) (Int, Int) -> ()
 // CHECK: thin_to_thick_function [[FUN]] : $@convention(thin) (Int, Int) -> () to $@callee_owned (Int, Int) -> ()
 
-// CHECK-LABEL: sil [noinline] @_T07specgen12take_closureyySi_SitcF : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> () {
-sil [noinline] @_T07specgen12take_closureyySi_SitcF : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> () {
+// CHECK-LABEL: sil [noinline] @_T07specgen12take_closureyyySi_SitcF : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> () {
+sil [noinline] @_T07specgen12take_closureyyySi_SitcF : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> () {
 bb0(%0 : $@callee_owned (Int, Int) -> ()):
   %1 = alloc_stack $Int
   %2 = load %1 : $*Int
@@ -24,18 +25,18 @@
   return %9999 : $()
 }
 
-// CHECK-LABEL: sil shared [noinline] @_T07specgen13take_closure2yySi_SitcF023_T07specgen6callerySiFyE8_SitcfU_SiTf1c_n : $@convention(thin) (Int) -> () {
+// CHECK-LABEL: sil shared [noinline] @_T07specgen13take_closure2yyySi_SitcF024_T07specgen6calleryySiFyE8_SitcfU_SiTf1c_n : $@convention(thin) (Int) -> () {
 // CHECK: bb0(%0 : $Int)
-// CHECK: [[FUN:%.*]] = function_ref @_T07specgen6callerySiFySi_SitcfU_
+// CHECK: [[FUN:%.*]] = function_ref @_T07specgen6calleryySiFySi_SitcfU_
 // CHECK: partial_apply [[FUN]](
 
-// CHECK-LABEL: sil shared [noinline] @_T07specgen13take_closure2yySi_SitcF26_T07specgen6calleeySi_SitFTf1c_n : $@convention(thin) () -> () {
+// CHECK-LABEL: sil shared [noinline] @_T07specgen13take_closure2yyySi_SitcF27_T07specgen6calleeyySi_SitFTf1c_n : $@convention(thin) () -> () {
 // CHECK-NEXT: bb0:
-// CHECK: [[FUN:%.*]] = function_ref @_T07specgen6calleeySi_SitF : $@convention(thin) (Int, Int) -> ()
+// CHECK: [[FUN:%.*]] = function_ref @_T07specgen6calleeyySi_SitF : $@convention(thin) (Int, Int) -> ()
 // CHECK: thin_to_thick_function [[FUN]] : $@convention(thin) (Int, Int) -> () to $@callee_owned (Int, Int) -> ()
 
-// CHECK-LABEL: sil [noinline] @_T07specgen13take_closure2yySi_SitcF : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> () {
-sil [noinline] @_T07specgen13take_closure2yySi_SitcF : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> () {
+// CHECK-LABEL: sil [noinline] @_T07specgen13take_closure2yyySi_SitcF : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> () {
+sil [noinline] @_T07specgen13take_closure2yyySi_SitcF : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> () {
 bb0(%0 : $@callee_owned (Int, Int) -> ()):
   %1 = alloc_stack $Int
   %2 = load %1 : $*Int
@@ -45,29 +46,29 @@
   return %9999 : $()
 }
 
-// CHECK-LABEL: sil [noinline] @_T07specgen6calleeySi_S2itF : $@convention(thin) (Int, Int, Int) -> () {
+// CHECK-LABEL: sil [noinline] @_T07specgen6calleeyySi_S2itF : $@convention(thin) (Int, Int, Int) -> () {
 // specgen.callee (Swift.Int, Swift.Int, Swift.Int) -> ()
-sil [noinline] @_T07specgen6calleeySi_S2itF : $@convention(thin) (Int, Int, Int) -> () {
+sil [noinline] @_T07specgen6calleeyySi_S2itF : $@convention(thin) (Int, Int, Int) -> () {
 bb0(%0 : $Int, %1 : $Int, %2 : $Int):
   %6 = tuple ()                                   // user: %7
   return %6 : $()                                 // id: %7
 }
 
-// CHECK-LABEL: sil @_T07specgen6callerySiF : $@convention(thin) (Int) -> () {
-// CHECK: [[ID1:%[0-9]+]] = function_ref @_T07specgen13take_closure2yySi_SitcF023_T07specgen6callerySiFyE8_SitcfU_SiTf1c_n : $@convention(thin) (Int) -> ()
-// CHECK: [[ID2:%[0-9]+]] = function_ref @_T07specgen12take_closureyySi_SitcF023_T07specgen6callerySiFyE8_SitcfU_SiTf1c_n : $@convention(thin) (Int) -> ()
+// CHECK-LABEL: sil @_T07specgen6calleryySiF : $@convention(thin) (Int) -> () {
+// CHECK: [[ID1:%[0-9]+]] = function_ref @_T07specgen13take_closure2yyySi_SitcF024_T07specgen6calleryySiFyE8_SitcfU_SiTf1c_n : $@convention(thin) (Int) -> ()
+// CHECK: [[ID2:%[0-9]+]] = function_ref @_T07specgen12take_closureyyySi_SitcF024_T07specgen6calleryySiFyE8_SitcfU_SiTf1c_n : $@convention(thin) (Int) -> ()
 // CHECK: apply [[ID2]](%0) : $@convention(thin) (Int) -> ()
 // CHECK: apply [[ID1]](%0) : $@convention(thin) (Int) -> ()
-sil @_T07specgen6callerySiF : $@convention(thin) (Int) -> () {
+sil @_T07specgen6calleryySiF : $@convention(thin) (Int) -> () {
 bb0(%0 : $Int):
   // function_ref specgen.take_closure ((Swift.Int, Swift.Int) -> ()) -> ()
-  %2 = function_ref @_T07specgen12take_closureyySi_SitcF : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> () // user: %5
+  %2 = function_ref @_T07specgen12take_closureyyySi_SitcF : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> () // user: %5
   // function_ref specgen.(caller (Swift.Int) -> ()).(closure #1)
-  %3 = function_ref @_T07specgen6callerySiFySi_SitcfU_ : $@convention(thin) (Int, Int, Int) -> () // user: %4
+  %3 = function_ref @_T07specgen6calleryySiFySi_SitcfU_ : $@convention(thin) (Int, Int, Int) -> () // user: %4
   %4 = partial_apply %3(%0) : $@convention(thin) (Int, Int, Int) -> () // user: %5
   strong_retain %4 : $@callee_owned (Int, Int) -> ()
   %5 = apply %2(%4) : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> ()
-  %6 = function_ref @_T07specgen13take_closure2yySi_SitcF : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> () // user: %5
+  %6 = function_ref @_T07specgen13take_closure2yyySi_SitcF : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> () // user: %5
   strong_retain %4 : $@callee_owned (Int, Int) -> ()
   %7 = apply %6(%4) : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> ()
   strong_release %4 : $@callee_owned (Int, Int) -> ()
@@ -75,8 +76,8 @@
   return %9999 : $()
 }
 
-// CHECK-LABEL: sil shared @_T07specgen6callerySiFySi_SitcfU_ : $@convention(thin) (Int, Int, Int) -> () {
-sil shared @_T07specgen6callerySiFySi_SitcfU_ : $@convention(thin) (Int, Int, Int) -> () {
+// CHECK-LABEL: sil shared @_T07specgen6calleryySiFySi_SitcfU_ : $@convention(thin) (Int, Int, Int) -> () {
+sil shared @_T07specgen6calleryySiFySi_SitcfU_ : $@convention(thin) (Int, Int, Int) -> () {
 bb0(%0 : $Int, %1 : $Int, %2 : $Int):
   %5 = alloc_box $<τ_0_0> { var τ_0_0 } <Int>, var, name "p"                   // users: %6, %10, %14
   %5a = project_box %5 : $<τ_0_0> { var τ_0_0 } <Int>, 0
@@ -85,7 +86,7 @@
   %7a = project_box %7 : $<τ_0_0> { var τ_0_0 } <Int>, 0
   store %1 to %7a : $*Int                        // id: %8
   // function_ref specgen.callee (Swift.Int, Swift.Int, Swift.Int) -> ()
-  %9 = function_ref @_T07specgen6calleeySi_S2itF : $@convention(thin) (Int, Int, Int) -> () // user: %12
+  %9 = function_ref @_T07specgen6calleeyySi_S2itF : $@convention(thin) (Int, Int, Int) -> () // user: %12
   %10 = load %5a : $*Int                         // user: %12
   %11 = load %7a : $*Int                         // user: %12
   %12 = apply %9(%10, %11, %2) : $@convention(thin) (Int, Int, Int) -> ()
@@ -99,28 +100,28 @@
 // Thin To Thick Function Tests //
 //////////////////////////////////
 
-// CHECK-LABEL: sil [noinline] @_T07specgen6calleeySi_SitF : $@convention(thin) (Int, Int) -> () {
+// CHECK-LABEL: sil [noinline] @_T07specgen6calleeyySi_SitF : $@convention(thin) (Int, Int) -> () {
 // specgen.callee (Swift.Int, Swift.Int) -> ()
-sil [noinline] @_T07specgen6calleeySi_SitF : $@convention(thin) (Int, Int) -> () {
+sil [noinline] @_T07specgen6calleeyySi_SitF : $@convention(thin) (Int, Int) -> () {
 bb0(%0 : $Int, %1 : $Int):
   %6 = tuple ()                                   // user: %7
   return %6 : $()                                 // id: %7
 }
 
-// CHECK-LABEL: sil @_T07specgen11tttficallerySiF : $@convention(thin) (Int) -> () {
-// CHECK: [[ID1:%[0-9]+]] = function_ref @_T07specgen13take_closure2yySi_SitcF26_T07specgen6calleeySi_SitFTf1c_n : $@convention(thin) () -> ()
-// CHECK: [[ID2:%[0-9]+]] = function_ref @_T07specgen12take_closureyySi_SitcF26_T07specgen6calleeySi_SitFTf1c_n : $@convention(thin) () -> ()
+// CHECK-LABEL: sil @_T07specgen11tttficalleryySiF : $@convention(thin) (Int) -> () {
+// CHECK: [[ID1:%[0-9]+]] = function_ref @_T07specgen13take_closure2yyySi_SitcF27_T07specgen6calleeyySi_SitFTf1c_n : $@convention(thin) () -> ()
+// CHECK: [[ID2:%[0-9]+]] = function_ref @_T07specgen12take_closureyyySi_SitcF27_T07specgen6calleeyySi_SitFTf1c_n : $@convention(thin) () -> ()
 // CHECK: apply [[ID2]]() : $@convention(thin) () -> ()
 // CHECK: apply [[ID1]]() : $@convention(thin) () -> ()
-sil @_T07specgen11tttficallerySiF : $@convention(thin) (Int) -> () {
+sil @_T07specgen11tttficalleryySiF : $@convention(thin) (Int) -> () {
 bb0(%0 : $Int):
   // function_ref specgen.take_closure ((Swift.Int, Swift.Int) -> ()) -> ()
-  %2 = function_ref @_T07specgen12take_closureyySi_SitcF : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> () // user: %5
+  %2 = function_ref @_T07specgen12take_closureyyySi_SitcF : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> () // user: %5
   // function_ref specgen.(caller (Swift.Int) -> ()).(closure #1)
-  %3 = function_ref @_T07specgen6calleeySi_SitF : $@convention(thin) (Int, Int) -> () // user: %4
+  %3 = function_ref @_T07specgen6calleeyySi_SitF : $@convention(thin) (Int, Int) -> () // user: %4
   %4 = thin_to_thick_function %3 : $@convention(thin) (Int, Int) -> () to $@callee_owned (Int, Int) -> () // user: %5
   %5 = apply %2(%4) : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> ()
-  %6 = function_ref @_T07specgen13take_closure2yySi_SitcF : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> ()
+  %6 = function_ref @_T07specgen13take_closure2yyySi_SitcF : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> ()
   %7 = apply %6(%4) : $@convention(thin) (@owned @callee_owned (Int, Int) -> ()) -> ()
   %9999 = tuple ()                                   // user: %7
   return %9999 : $()                                 // id: %7
@@ -426,15 +427,15 @@
 
 // Ensure that we can specialize and properly mangle functions that take closures with <τ_0_0> { var τ_0_0 } <arguments>.
 
-// CHECK-LABEL: sil shared [noinline] @_T04main5innerys5Int32Vz_yADctF25closure_with_box_argumentxz_Bi32__lXXTf1nc_n : $@convention(thin) (@inout Builtin.Int32, @owned <τ_0_0> { var τ_0_0 } <Builtin.Int32>) -> ()
+// CHECK-LABEL: sil shared [noinline] @_T04main5inneryys5Int32Vz_yADctF25closure_with_box_argumentxz_Bi32__lXXTf1nc_n : $@convention(thin) (@inout Builtin.Int32, @owned <τ_0_0> { var τ_0_0 } <Builtin.Int32>) -> ()
 // CHECK: bb0
 // CHECK: [[FN:%.*]] = function_ref @closure_with_box_argument
 // CHECK: [[PARTIAL:%.*]] = partial_apply [[FN]](%1)
 // CHECK: [[ARG:%.*]] = load %0
 // CHECK: apply [[PARTIAL]]([[ARG]])
 
-// CHECK-LABEL: {{.*}} @_T04main5innerys5Int32Vz_yADctF
-sil hidden [noinline] @_T04main5innerys5Int32Vz_yADctF : $@convention(thin) (@inout Builtin.Int32, @owned @callee_owned (Builtin.Int32) -> ()) -> () {
+// CHECK-LABEL: {{.*}} @_T04main5inneryys5Int32Vz_yADctF
+sil hidden [noinline] @_T04main5inneryys5Int32Vz_yADctF : $@convention(thin) (@inout Builtin.Int32, @owned @callee_owned (Builtin.Int32) -> ()) -> () {
 bb0(%0 : $*Builtin.Int32, %1 : $@callee_owned (Builtin.Int32) -> ()):
   strong_retain %1 : $@callee_owned (Builtin.Int32) -> ()
   %5 = load %0 : $*Builtin.Int32
@@ -456,7 +457,7 @@
   %7 = alloc_stack $Builtin.Int32
   %9 = integer_literal $Builtin.Int32, 1
   store %9 to %7 : $*Builtin.Int32
-  %12 = function_ref @_T04main5innerys5Int32Vz_yADctF: $@convention(thin) (@inout Builtin.Int32, @owned @callee_owned (Builtin.Int32) -> ()) -> ()
+  %12 = function_ref @_T04main5inneryys5Int32Vz_yADctF: $@convention(thin) (@inout Builtin.Int32, @owned @callee_owned (Builtin.Int32) -> ()) -> ()
   strong_retain %6 : $@callee_owned (Builtin.Int32) -> ()
   %14 = apply %12(%7, %6) : $@convention(thin) (@inout Builtin.Int32, @owned @callee_owned (Builtin.Int32) -> ()) -> ()
   strong_release %6 : $@callee_owned (Builtin.Int32) -> ()
@@ -489,8 +490,8 @@
   init()
 }
 
-// CHECK-LABEL: sil shared @_T04test1SVAA1PA2aDP3fooS2iycFZTW8closure2SiTf1cn_n : $@convention(thin) (@thick S.Type, Int) -> Int
-sil @_T04test1SVAA1PA2aDP3fooS2iycFZTW : $@convention(witness_method: P) (@owned @callee_owned () -> Int, @thick S.Type) -> Int {
+// CHECK-LABEL: sil shared @_T04test1SVAA1PA2aDP3fooyS2iycFZTW8closure2SiTf1cn_n : $@convention(thin) (@thick S.Type, Int) -> Int
+sil @_T04test1SVAA1PA2aDP3fooyS2iycFZTW : $@convention(witness_method: P) (@owned @callee_owned () -> Int, @thick S.Type) -> Int {
 bb0(%0 : $@callee_owned () -> Int, %1 : $@thick S.Type):
   %3 = apply %0() : $@callee_owned () -> Int
   return %3 : $Int
@@ -506,13 +507,13 @@
   %3 = function_ref @closure2 : $@convention(thin) (Int) -> Int
   %4 = partial_apply %3(%0) : $@convention(thin) (Int) -> Int
   %5 = metatype $@thick S.Type
-  %6 = function_ref @_T04test1SVAA1PA2aDP3fooS2iycFZTW : $@convention(witness_method: P) (@owned @callee_owned () -> Int, @thick S.Type) -> Int
+  %6 = function_ref @_T04test1SVAA1PA2aDP3fooyS2iycFZTW : $@convention(witness_method: P) (@owned @callee_owned () -> Int, @thick S.Type) -> Int
   %7 = apply %6(%4, %5) : $@convention(witness_method: P) (@owned @callee_owned () -> Int, @thick S.Type) -> Int
   return %7 : $Int
 }
 
 sil_witness_table S: P module test {
-  method #P.foo!1: @_T04test1SVAA1PA2aDP3fooS2iycFZTW
+  method #P.foo!1: @_T04test1SVAA1PA2aDP3fooyS2iycFZTW
 }
 
 // Test partial_apply -> convert_function -> convert_function -> try_apply.
diff --git a/test/SILOptimizer/copyforward.sil b/test/SILOptimizer/copyforward.sil
index 572dbe5..667e06f 100644
--- a/test/SILOptimizer/copyforward.sil
+++ b/test/SILOptimizer/copyforward.sil
@@ -685,3 +685,91 @@
   %7 = tuple ()
   return %7 : $()
 }
+
+struct ObjWrapper {
+  var obj: AnyObject
+}
+
+// Test that backward copy propagation does not interfere with the previous
+// value of the copy's destination. The `load` is a use of the `alloc` value,
+// but not a direct use. Since it occurs between the initialization of `temp`
+// and the copy from temp into `alloc`, the copy into `alloc` cannot be backward
+// propagated.
+// <rdar://35646292> Swift CI: resilience bot seg faults in stdlib/RangeReplaceable.swift.gyb.
+//
+// CHECK-LABEL: sil @testLoadDestroy : $@convention(thin) (@in ObjWrapper, @in ObjWrapper) -> () {
+// CHECK: bb0(%0 : $*ObjWrapper, %1 : $*ObjWrapper):
+// CHECK:   [[ALLOC:%.*]] = alloc_stack $ObjWrapper, var, name "o"
+// CHECK:   [[ELT_ADDR:%.*]] = struct_element_addr [[ALLOC]] : $*ObjWrapper, #ObjWrapper.obj
+// CHECK:   copy_addr %0 to [initialization] [[ALLOC]] : $*ObjWrapper
+// CHECK:   [[TEMP:%.*]] = alloc_stack $ObjWrapper
+// CHECK:   copy_addr %1 to [initialization] [[TEMP]] : $*ObjWrapper
+// CHECK:   [[LD:%.*]] = load [[ELT_ADDR]] : $*AnyObject
+// CHECK:   strong_release [[LD]] : $AnyObject
+// CHECK:   copy_addr [take] [[TEMP]] to [initialization] [[ALLOC]] : $*ObjWrapper
+// CHECK:   dealloc_stack [[TEMP]] : $*ObjWrapper
+// CHECK:   dealloc_stack [[ALLOC]] : $*ObjWrapper
+// CHECK:   %{{.*}} = tuple ()
+// CHECK:   return %{{.*}} : $()
+// CHECK-LABEL: } // end sil function 'testLoadDestroy'
+sil @testLoadDestroy : $@convention(thin) (@in ObjWrapper, @in ObjWrapper) -> () {
+bb(%0 : $*ObjWrapper, %1 : $*ObjWrapper):
+  // Fully initialize a new stack var to arg0.
+  %alloc = alloc_stack $ObjWrapper, var, name "o"
+  %objadr = struct_element_addr %alloc : $*ObjWrapper, #ObjWrapper.obj
+  copy_addr %0 to [initialization] %alloc : $*ObjWrapper
+
+  // Fully initialize a temporary to arg1.
+  // Rewriting this to %alloc would alias with the subsequent load.
+  %temp = alloc_stack $ObjWrapper
+  copy_addr %1 to [initialization] %temp : $*ObjWrapper
+
+  // Load and release an reference from arg0 inside the stack var.
+  %obj = load %objadr : $*AnyObject
+  strong_release %obj : $AnyObject
+
+  // Move `temp` copy of arg1 into the stack var.
+  copy_addr [take] %temp to [initialization] %alloc : $*ObjWrapper
+
+  dealloc_stack %temp : $*ObjWrapper
+  dealloc_stack %alloc : $*ObjWrapper
+  %74 = tuple ()
+  return %74 : $()
+}
+
+// Helper for multipleUse
+sil @multipleArg : $@convention(thin) <T> (@in_guaranteed T, @in_guaranteed T) -> () {
+bb0(%0 : $*T, %1 : $*T):
+  %r1 = tuple ()
+  return %r1 : $()
+}
+
+// Test a corner case of forward copy propagation in which simple substitution
+// does not work (the source is reinitialized) and need to propagate to an
+// instruction with multiple uses of the source.
+// CHECK-LABEL: sil hidden @multipleUse : $@convention(thin) <T> (@in T, @in T) -> () {
+// CHECK: bb0(%0 : $*T, %1 : $*T):
+// CHECK:   [[A:%.*]] = alloc_stack $T
+// CHECK:   copy_addr [take] %0 to [initialization] [[A]] : $*T
+// CHECK:   [[F:%.*]] = function_ref @multipleArg : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> ()
+// CHECK:   [[C:%.*]] = apply [[F]]<T>([[A]], [[A]]) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> ()
+// CHECK:   destroy_addr [[A]] : $*T
+// CHECK:   dealloc_stack [[A]] : $*T
+// CHECK:   copy_addr [take] %1 to [initialization] %0 : $*T
+// CHECK:   %{{.*}} = tuple ()
+// CHECK:   return %{{.*}} : $()
+// CHECK: } // end sil function 'multipleUse'
+sil hidden @multipleUse : $@convention(thin) <T> (@in T, @in T) -> () {
+bb0(%0 : $*T, %1 : $*T):
+  %l1 = alloc_stack $T
+  copy_addr [take] %0 to [initialization] %l1 : $*T
+  %f1 = function_ref @multipleArg : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> ()
+  %c1 = apply %f1<T>(%l1, %l1) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> ()
+  destroy_addr %l1 : $*T
+  dealloc_stack %l1 : $*T
+  destroy_addr %0 : $*T
+  // Reinitialize copy's source to avoid a fast isSourceDeadAtCopy check.
+  copy_addr [take] %1 to [initialization] %0 : $*T
+  %r1 = tuple ()
+  return %r1 : $()
+}
diff --git a/test/SILOptimizer/dead_function_elimination.swift b/test/SILOptimizer/dead_function_elimination.swift
index 8a867da..8344eac 100644
--- a/test/SILOptimizer/dead_function_elimination.swift
+++ b/test/SILOptimizer/dead_function_elimination.swift
@@ -216,15 +216,3 @@
 
 // CHECK-TESTING-LABEL: sil_witness_table [serialized] Adopt: Prot
 // CHECK-TESTING: DeadWitness{{.*}}: @{{.*}}DeadWitness
-
-// CHECK-LABEL: sil_default_witness_table hidden Prot
-// CHECK:  no_default
-// CHECK:  no_default
-// CHECK:  method #Prot.aliveDefaultWitness!1: {{.*}} : @{{.*}}aliveDefaultWitness
-// CHECK:  no_default
-
-// CHECK-TESTING-LABEL: sil_default_witness_table Prot
-// CHECK-TESTING:  no_default
-// CHECK-TESTING:  no_default
-// CHECK-TESTING:  method #Prot.aliveDefaultWitness!1: {{.*}} : @{{.*}}aliveDefaultWitness
-// CHECK-TESTING:  method #Prot.DeadDefaultWitness!1: {{.*}} : @{{.*}}DeadDefaultWitness
diff --git a/test/SILOptimizer/dead_partial_apply_arg.swift b/test/SILOptimizer/dead_partial_apply_arg.swift
index fd80dbd..d52b89f 100644
--- a/test/SILOptimizer/dead_partial_apply_arg.swift
+++ b/test/SILOptimizer/dead_partial_apply_arg.swift
@@ -8,14 +8,14 @@
 
 // This function has an unused metatype argument.
 
-// CHECK-LABEL: sil [thunk] [always_inline] @_T0s5Int32V4testE8lessthanSbAB3lhs_AB3rhstFZ : $@convention(method) (Int32, Int32, @thin Int32.Type) -> Bool
+// CHECK-LABEL: sil [thunk] [always_inline] @_T0s5Int32V4testE8lessthan3lhs3rhsSbAB_ABtFZ : $@convention(method) (Int32, Int32, @thin Int32.Type) -> Bool
   public static func lessthan (lhs: Int32, rhs: Int32) -> Bool {
     return lhs < rhs
   }
 }
 
 // CHECK-LABEL: sil hidden @_T04test6callitSbs5Int32V_ADtcyF : $@convention(thin) () -> @owned @callee_guaranteed (Int32, Int32) -> Bool
-// CHECK: [[F:%[0-9]+]] = function_ref @_T0s5Int32V4testE8lessthanSbAB3lhs_AB3rhstFZTf4nnd_n
+// CHECK: [[F:%[0-9]+]] = function_ref @_T0s5Int32V4testE8lessthan3lhs3rhsSbAB_ABtFZTf4nnd_n
 // CHECK: [[R:%[0-9]+]] = thin_to_thick_function [[F]]
 // CHECK: return [[R]]
 func callit()  -> (Int32, Int32) -> Bool {
diff --git a/test/SILOptimizer/definite_init_failable_initializers.swift b/test/SILOptimizer/definite_init_failable_initializers.swift
index 1d3cc4b..f7b557e 100644
--- a/test/SILOptimizer/definite_init_failable_initializers.swift
+++ b/test/SILOptimizer/definite_init_failable_initializers.swift
@@ -35,7 +35,7 @@
     y = Canary()
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructVACSgyt24failBeforeInitialization_tcfC
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructV24failBeforeInitializationACSgyt_tcfC
 // CHECK:       bb0(%0 : $@thin FailableStruct.Type):
 // CHECK:         [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
 // CHECK:         br bb1
@@ -49,7 +49,7 @@
     return nil
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructVACSgyt30failAfterPartialInitialization_tcfC
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructV30failAfterPartialInitializationACSgyt_tcfC
 // CHECK:       bb0(%0 : $@thin FailableStruct.Type):
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
 // CHECK:         [[CANARY:%.*]] = apply
@@ -71,7 +71,7 @@
     return nil
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructVACSgyt27failAfterFullInitialization_tcfC
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructV27failAfterFullInitializationACSgyt_tcfC
 // CHECK:       bb0
 // CHECK:         [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
 // CHECK:         [[CANARY1:%.*]] = apply
@@ -98,7 +98,7 @@
     return nil
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructVACSgyt46failAfterWholeObjectInitializationByAssignment_tcfC
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructV46failAfterWholeObjectInitializationByAssignmentACSgyt_tcfC
 // CHECK:       bb0
 // CHECK:         [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
 // CHECK:         [[CANARY]] = apply
@@ -118,10 +118,10 @@
     return nil
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructVACSgyt46failAfterWholeObjectInitializationByDelegation_tcfC
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructV46failAfterWholeObjectInitializationByDelegationACSgyt_tcfC
 // CHECK:       bb0
 // CHECK:         [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14FailableStructVACyt6noFail_tcfC
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14FailableStructV6noFailACyt_tcfC
 // CHECK-NEXT:    [[NEW_SELF:%.*]] = apply [[INIT_FN]](%0)
 // CHECK-NEXT:    store [[NEW_SELF]] to [[SELF_BOX]]
 // CHECK-NEXT:    br bb1
@@ -137,10 +137,10 @@
     return nil
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructVACSgyt20failDuringDelegation_tcfC
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructV20failDuringDelegationACSgyt_tcfC
 // CHECK:       bb0
 // CHECK:         [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14FailableStructVACSgyt24failBeforeInitialization_tcfC
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14FailableStructV24failBeforeInitializationACSgyt_tcfC
 // CHECK-NEXT:    [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]](%0)
 // CHECK:         [[COND:%.*]] = select_enum [[SELF_OPTIONAL]]
 // CHECK-NEXT:    cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]]
@@ -338,13 +338,13 @@
 
   init(noFail: ()) { x = Canary() }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi20failBeforeDelegation_tKcfC
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructV20failBeforeDelegationACSi_tKcfC
 // CHECK:       bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
 // CHECK:         [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb1([[RESULT:%.*]] : $Int):
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt6noFail_tcfC
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC
 // CHECK-NEXT:    [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
 // CHECK-NEXT:    store [[NEW_SELF]] to [[SELF_BOX]]
 // CHECK-NEXT:    retain_value [[NEW_SELF]]
@@ -359,13 +359,13 @@
     self.init(noFail: ())
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi28failBeforeOrDuringDelegation_tKcfC
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructV28failBeforeOrDuringDelegationACSi_tKcfC
 // CHECK:       bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
 // CHECK:         [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb1([[RESULT:%.*]] : $Int):
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt4fail_tKcfC
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC
 // CHECK-NEXT:    try_apply [[INIT_FN]](%1)
 // CHECK:       bb2([[NEW_SELF:%.*]] : $ThrowStruct):
 // CHECK-NEXT:    store [[NEW_SELF]] to [[SELF_BOX]]
@@ -385,13 +385,13 @@
     try self.init(fail: ())
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi29failBeforeOrDuringDelegation2_tKcfC
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructV29failBeforeOrDuringDelegation2ACSi_tKcfC
 // CHECK:       bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
 // CHECK:         [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb1([[RESULT:%.*]] : $Int):
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACSi20failBeforeDelegation_tKcfC
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructV20failBeforeDelegationACSi_tKcfC
 // CHECK-NEXT:    try_apply [[INIT_FN]]([[RESULT]], %1)
 // CHECK:       bb2([[NEW_SELF:%.*]] : $ThrowStruct):
 // CHECK-NEXT:    store [[NEW_SELF]] to [[SELF_BOX]]
@@ -408,10 +408,10 @@
     try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2))
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi20failDuringDelegation_tKcfC
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructV20failDuringDelegationACSi_tKcfC
 // CHECK:       bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
 // CHECK:         [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt4fail_tKcfC
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC
 // CHECK-NEXT:    try_apply [[INIT_FN]](%1)
 // CHECK:       bb1([[NEW_SELF:%.*]] : $ThrowStruct):
 // CHECK-NEXT:    store [[NEW_SELF]] to [[SELF_BOX]]
@@ -426,13 +426,13 @@
     try self.init(fail: ())
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi19failAfterDelegation_tKcfC
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructV19failAfterDelegationACSi_tKcfC
 // CHECK:       bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
 // CHECK:         [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt6noFail_tcfC
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC
 // CHECK-NEXT:    [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
 // CHECK-NEXT:    store [[NEW_SELF]] to [[SELF_BOX]]
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb1([[RESULT:%.*]] : $Int):
 // CHECK-NEXT:    retain_value [[NEW_SELF]]
@@ -448,19 +448,19 @@
     try unwrap(failAfterDelegation)
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi27failDuringOrAfterDelegation_tKcfC
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructV27failDuringOrAfterDelegationACSi_tKcfC
 // CHECK:       bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
 // CHECK-NEXT:    [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
 // CHECK-NEXT:    [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
 // CHECK-NEXT:    store [[ZERO]] to [[BITMAP_BOX]]
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt4fail_tKcfC
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC
 // CHECK-NEXT:    try_apply [[INIT_FN]](%1)
 // CHECK:       bb1([[NEW_SELF:.*]] : $ThrowStruct):
 // CHECK-NEXT:    [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
 // CHECK-NEXT:    store [[BIT]] to [[BITMAP_BOX]]
 // CHECK-NEXT:    store [[NEW_SELF]] to [[SELF_BOX]]
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb2([[RESULT:%.*]] : $Int):
 // CHECK-NEXT:    retain_value [[NEW_SELF]]
@@ -487,21 +487,21 @@
     try unwrap(failDuringOrAfterDelegation)
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi27failBeforeOrAfterDelegation_tKcfC
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructV27failBeforeOrAfterDelegationACSi_tKcfC
 // CHECK:       bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
 // CHECK-NEXT:    [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
 // CHECK-NEXT:    [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
 // CHECK-NEXT:    store [[ZERO]] to [[BITMAP_BOX]]
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb1([[RESULT:%.*]] : $Int):
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt6noFail_tcfC
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC
 // CHECK-NEXT:    [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
 // CHECK-NEXT:    [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
 // CHECK-NEXT:    store [[BIT]] to [[BITMAP_BOX]]
 // CHECK-NEXT:    store [[NEW_SELF]] to [[SELF_BOX]]
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb2([[RESULT:%.*]] : $Int):
 // CHECK-NEXT:    retain_value [[NEW_SELF]]
@@ -529,10 +529,10 @@
     try unwrap(failBeforeOrAfterDelegation)
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSgSi16throwsToOptional_tcfC
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructV16throwsToOptionalACSgSi_tcfC
 // CHECK:       bb0([[ARG1:%.*]] : $Int, [[ARG2:%.*]] : $@thin ThrowStruct.Type):
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACSi20failDuringDelegation_tKcfC
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructV20failDuringDelegationACSi_tKcfC
 // CHECK-NEXT:    try_apply [[INIT_FN]]([[ARG1]], [[ARG2]]) : $@convention(method) (Int, @thin ThrowStruct.Type) -> (@owned ThrowStruct, @error Error), normal [[TRY_APPLY_SUCC_BB:bb[0-9]+]], error [[TRY_APPLY_FAIL_BB:bb[0-9]+]]
 //
 // CHECK:       [[TRY_APPLY_SUCC_BB]]([[NEW_SELF:%.*]] : $ThrowStruct):
@@ -596,11 +596,11 @@
     self = ThrowStruct(noFail: ())
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi25failDuringSelfReplacement_tKcfC
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructV25failDuringSelfReplacementACSi_tKcfC
 // CHECK:       bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
 // CHECK:         [[SELF_TYPE:%.*]] = metatype $@thin ThrowStruct.Type
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt4fail_tKcfC
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC
 // CHECK-NEXT:    try_apply [[INIT_FN]]([[SELF_TYPE]])
 // CHECK:       bb1([[NEW_SELF:%.*]] : $ThrowStruct):
 // CHECK-NEXT:    [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*ThrowStruct
@@ -617,16 +617,16 @@
     try self = ThrowStruct(fail: ())
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi24failAfterSelfReplacement_tKcfC
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructV24failAfterSelfReplacementACSi_tKcfC
 // CHECK:       bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
 // CHECK:         [[SELF_TYPE:%.*]] = metatype $@thin ThrowStruct.Type
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt6noFail_tcfC
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC
 // CHECK-NEXT:    [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[SELF_TYPE]])
 // CHECK-NEXT:    [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*ThrowStruct
 // CHECK-NEXT:    store [[NEW_SELF]] to [[WRITE]]
 // CHECK-NEXT:    end_access [[WRITE]] : $*ThrowStruct
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb1([[RESULT:%.*]] : $Int):
 // CHECK-NEXT:    retain_value [[NEW_SELF]]
@@ -746,7 +746,7 @@
     member = Canary()
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassCACSgyt28failBeforeFullInitialization_tcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassC28failBeforeFullInitializationACSgyt_tcfc
 // CHECK:       bb0(%0 : $FailableBaseClass):
 // CHECK:         [[METATYPE:%.*]] = metatype $@thick FailableBaseClass.Type
 // CHECK:         dealloc_partial_ref %0 : $FailableBaseClass, [[METATYPE]]
@@ -756,7 +756,7 @@
     return nil
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassCACSgyt27failAfterFullInitialization_tcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassC27failAfterFullInitializationACSgyt_tcfc
 // CHECK:       bb0(%0 : $FailableBaseClass):
 // CHECK:         [[CANARY:%.*]] = apply
 // CHECK-NEXT:    [[MEMBER_ADDR:%.*]] = ref_element_addr %0
@@ -775,7 +775,7 @@
     return nil
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassCACSgyt20failBeforeDelegation_tcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassC20failBeforeDelegationACSgyt_tcfc
 // CHECK:       bb0(%0 : $FailableBaseClass):
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass
 // CHECK:         store %0 to [[SELF_BOX]]
@@ -792,7 +792,7 @@
     return nil
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassCACSgyt19failAfterDelegation_tcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassC19failAfterDelegationACSgyt_tcfc
 // CHECK:       bb0(%0 : $FailableBaseClass):
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass
 // CHECK:         store %0 to [[SELF_BOX]]
@@ -812,7 +812,7 @@
     return nil
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassCACSgyt20failDuringDelegation_tcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassC20failDuringDelegationACSgyt_tcfc
 // CHECK:       bb0(%0 : $FailableBaseClass):
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass
 // CHECK:         store %0 to [[SELF_BOX]]
@@ -872,7 +872,7 @@
 class FailableDerivedClass : FailableBaseClass {
   var otherMember: Canary
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers20FailableDerivedClassCACSgyt27derivedFailBeforeDelegation_tcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers20FailableDerivedClassC27derivedFailBeforeDelegationACSgyt_tcfc
 // CHECK:       bb0(%0 : $FailableDerivedClass):
 // CHECK:         [[SELF_BOX:%.*]] = alloc_stack $FailableDerivedClass
 // CHECK:         store %0 to [[SELF_BOX]]
@@ -889,7 +889,7 @@
     return nil
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers20FailableDerivedClassCACSgyt27derivedFailDuringDelegation_tcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers20FailableDerivedClassC27derivedFailDuringDelegationACSgyt_tcfc
 // CHECK:       bb0(%0 : $FailableDerivedClass):
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $FailableDerivedClass
 // CHECK:         store %0 to [[SELF_BOX]]
@@ -899,7 +899,7 @@
 // CHECK-NEXT:    store [[CANARY]] to [[WRITE]]
 // CHECK-NEXT:    end_access [[WRITE]] : $*Canary
 // CHECK-NEXT:    [[BASE_SELF:%.*]] = upcast %0
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17FailableBaseClassCACSgyt28failBeforeFullInitialization_tcfc
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17FailableBaseClassC28failBeforeFullInitializationACSgyt_tcfc
 // CHECK-NEXT:    [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
 // CHECK:         [[COND:%.*]] = select_enum [[SELF_OPTIONAL]]
 // CHECK-NEXT:    cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]]
@@ -990,15 +990,15 @@
     try! super.init()
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi28failBeforeFullInitialization_tKcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitializationACSi_tKcfc
 // CHECK:       bb0(%0 : $Int, %1 : $ThrowDerivedClass):
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
 // CHECK:         store %1 to [[SELF_BOX]]
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb1([[RESULT:%.*]] : $Int):
 // CHECK-NEXT:    [[BASE_SELF:%.*]] = upcast %1
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassCACyt6noFail_tcfc
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassC6noFailACyt_tcfc
 // CHECK-NEXT:    [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
 // CHECK-NEXT:    [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
 // CHECK-NEXT:    store [[DERIVED_SELF]] to [[SELF_BOX]]
@@ -1016,14 +1016,14 @@
     super.init(noFail: ())
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi28failBeforeFullInitialization_Si0h6DuringjK0tKcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitialization0h6DuringjK0ACSi_SitKcfc
 // CHECK:       bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass):
 // CHECK-NEXT:    [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
 // CHECK-NEXT:    [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
 // CHECK-NEXT:    store [[ZERO]] to [[BITMAP_BOX]]
 // CHECK:         store %2 to [[SELF_BOX]] : $*ThrowDerivedClass
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb1([[RESULT:%.*]] : $Int)
 // CHECK-NEXT:    [[BASE_SELF:%.*]] = upcast %2
@@ -1061,16 +1061,16 @@
     try super.init()
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi27failAfterFullInitialization_tKcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassC27failAfterFullInitializationACSi_tKcfc
 // CHECK:       bb0(%0 : $Int, %1 : $ThrowDerivedClass):
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
 // CHECK:         store %1 to [[SELF_BOX]]
 // CHECK-NEXT:    [[BASE_SELF:%.*]] = upcast %1
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassCACyt6noFail_tcfc
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassC6noFailACyt_tcfc
 // CHECK-NEXT:    [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
 // CHECK-NEXT:    [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
 // CHECK-NEXT:    store [[DERIVED_SELF]] to [[SELF_BOX]]
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb1([[RESULT:%.*]] : $Int):
 // CHECK-NEXT:    strong_retain [[DERIVED_SELF]]
@@ -1086,7 +1086,7 @@
     try unwrap(failAfterFullInitialization)
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi27failAfterFullInitialization_Si0h6DuringjK0tKcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassC27failAfterFullInitialization0h6DuringjK0ACSi_SitKcfc
 // CHECK:       bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass):
 // CHECK-NEXT:    [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
@@ -1101,7 +1101,7 @@
 // CHECK-NEXT:    store [[BIT]] to [[BITMAP_BOX]]
 // CHECK-NEXT:    [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
 // CHECK-NEXT:    store [[DERIVED_SELF]] to [[SELF_BOX]]
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb2([[RESULT:%.*]] : $Int):
 // CHECK-NEXT:    strong_retain [[DERIVED_SELF]]
@@ -1133,26 +1133,26 @@
     try unwrap(failAfterFullInitialization)
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi28failBeforeFullInitialization_Si0h5AfterjK0tKcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitialization0h5AfterjK0ACSi_SitKcfc
 // CHECK:       bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass):
 // CHECK-NEXT:    [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
 // CHECK-NEXT:    [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
 // CHECK-NEXT:    store [[ZERO]] to [[BITMAP_BOX]]
 // CHECK:         store %2 to [[SELF_BOX]]
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb1([[RESULT:%.*]] : $Int):
 // CHECK-NEXT:    [[TWO:%.*]] = integer_literal $Builtin.Int2, -2
 // CHECK-NEXT:    store [[TWO]] to [[BITMAP_BOX]]
 // CHECK-NEXT:    [[BASE_SELF:%.*]] = upcast %2
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassCACyt6noFail_tcfc
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassC6noFailACyt_tcfc
 // CHECK-NEXT:    [[ONE:%.*]] = integer_literal $Builtin.Int2, -1
 // CHECK-NEXT:    store [[ONE]] to [[BITMAP_BOX]]
 // CHECK:         [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
 // CHECK-NEXT:    [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
 // CHECK-NEXT:    store [[DERIVED_SELF]] to [[SELF_BOX]]
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%1)
 // CHECK:       bb2([[RESULT:%.*]] : $Int):
 // CHECK-NEXT:    strong_retain [[DERIVED_SELF]]
@@ -1196,14 +1196,14 @@
     try unwrap(failAfterFullInitialization)
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi28failBeforeFullInitialization_Si0h6DuringjK0Si0h5AfterjK0tKcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitialization0h6DuringjK00h5AfterjK0ACSi_S2itKcfc
 // CHECK:       bb0(%0 : $Int, %1 : $Int, %2 : $Int, %3 : $ThrowDerivedClass):
 // CHECK-NEXT:    [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
 // CHECK-NEXT:    [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
 // CHECK-NEXT:    store [[ZERO]] to [[BITMAP_BOX]]
 // CHECK:         store %3 to [[SELF_BOX]]
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb1([[RESULT:%.*]] : $Int):
 // CHECK-NEXT:    [[BASE_SELF:%.*]] = upcast %3
@@ -1216,7 +1216,7 @@
 // CHECK-NEXT:    store [[NEG_ONE]] to [[BITMAP_BOX]]
 // CHECK-NEXT:    [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
 // CHECK-NEXT:    store [[DERIVED_SELF]] to [[SELF_BOX]]
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%2)
 // CHECK:       bb3([[RESULT:%.*]] : $Int):
 // CHECK-NEXT:    strong_retain [[DERIVED_SELF]]
@@ -1266,14 +1266,14 @@
     try! self.init()
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi20failBeforeDelegation_tKcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassC20failBeforeDelegationACSi_tKcfc
 // CHECK:       bb0(%0 : $Int, %1 : $ThrowDerivedClass):
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
 // CHECK:         store %1 to [[SELF_BOX]]
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb1([[ARG:%.*]] : $Int):
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassCACyt6noFail_tcfc
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassC6noFailACyt_tcfc
 // CHECK-NEXT:    [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
 // CHECK-NEXT:    store [[NEW_SELF]] to [[SELF_BOX]]
 // CHECK-NEXT:    strong_retain [[NEW_SELF]]
@@ -1290,7 +1290,7 @@
     self.init(noFail: ())
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi20failDuringDelegation_tKcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassC20failDuringDelegationACSi_tKcfc
 // CHECK:       bb0(%0 : $Int, %1 : $ThrowDerivedClass):
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
 // CHECK:         store %1 to [[SELF_BOX]]
@@ -1309,14 +1309,14 @@
     try self.init()
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi28failBeforeOrDuringDelegation_tKcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassC28failBeforeOrDuringDelegationACSi_tKcfc
 // CHECK:       bb0(%0 : $Int, %1 : $ThrowDerivedClass):
 // CHECK-NEXT:    [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
 // CHECK:         [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
 // CHECK-NEXT:    store [[ZERO]] to [[BITMAP_BOX]] : $*Builtin.Int1
 // CHECK:         store %1 to [[SELF_BOX]]
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb1([[ARG:%.*]] : $Int):
 // CHECK-NEXT:    [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
@@ -1352,19 +1352,19 @@
     try self.init()
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi29failBeforeOrDuringDelegation2_tKcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassC29failBeforeOrDuringDelegation2ACSi_tKcfc
 // CHECK:         bb0(%0 : $Int, %1 : $ThrowDerivedClass):
 // CHECK-NEXT:    [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
 // CHECK:         [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
 // CHECK-NEXT:    store [[ZERO]] to [[BITMAP_BOX]] : $*Builtin.Int1
 // CHECK:         store %1 to [[SELF_BOX]]
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb1([[ARG:%.*]] : $Int):
 // CHECK-NEXT:    [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
 // CHECK-NEXT:    store [[BIT]] to [[BITMAP_BOX]]
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi20failBeforeDelegation_tKcfc
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassC20failBeforeDelegationACSi_tKcfc
 // CHECK-NEXT:    try_apply [[INIT_FN]]([[ARG]], %1)
 // CHECK:       bb2([[NEW_SELF:%.*]] : $ThrowDerivedClass):
 // CHECK-NEXT:    store [[NEW_SELF]] to [[SELF_BOX]]
@@ -1396,14 +1396,14 @@
     try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2))
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi19failAfterDelegation_tKcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassC19failAfterDelegationACSi_tKcfc
 // CHECK:       bb0(%0 : $Int, %1 : $ThrowDerivedClass):
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
 // CHECK:         store %1 to [[SELF_BOX]]
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassCACyt6noFail_tcfc
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassC6noFailACyt_tcfc
 // CHECK-NEXT:    [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
 // CHECK-NEXT:    store [[NEW_SELF]] to [[SELF_BOX]]
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb1([[RESULT:%.*]] : $Int):
 // CHECK-NEXT:    strong_retain [[NEW_SELF]]
@@ -1419,7 +1419,7 @@
     try unwrap(failAfterDelegation)
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi27failDuringOrAfterDelegation_tKcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassC27failDuringOrAfterDelegationACSi_tKcfc
 // CHECK:       bb0(%0 : $Int, %1 : $ThrowDerivedClass):
 // CHECK-NEXT:    [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
 // CHECK:         [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
@@ -1434,7 +1434,7 @@
 // CHECK-NEXT:    [[BIT:%.*]] = integer_literal $Builtin.Int2, -1
 // CHECK-NEXT:    store [[BIT]] to [[BITMAP_BOX]]
 // CHECK-NEXT:    store [[NEW_SELF]] to [[SELF_BOX]]
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb2([[RESULT:%.*]] : $Int):
 // CHECK-NEXT:    strong_retain [[NEW_SELF]]
@@ -1466,24 +1466,24 @@
     try unwrap(failDuringOrAfterDelegation)
   }
 
-// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi27failBeforeOrAfterDelegation_tKcfc
+// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassC27failBeforeOrAfterDelegationACSi_tKcfc
 // CHECK:       bb0(%0 : $Int, %1 : $ThrowDerivedClass):
 // CHECK-NEXT:    [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
 // CHECK-NEXT:    [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
 // CHECK-NEXT:    [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
 // CHECK-NEXT:    store [[ZERO]] to [[BITMAP_BOX]]
 // CHECK:         store %1 to [[SELF_BOX]]
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb1([[RESULT:%.*]] : $Int):
 // CHECK-NEXT:    [[BIT:%.*]] = integer_literal $Builtin.Int2, -2
 // CHECK-NEXT:    store [[BIT]] to [[BITMAP_BOX]]
 // CHECK-NEXT:    [[BIT:%.*]] = integer_literal $Builtin.Int2, -1
 // CHECK-NEXT:    store [[BIT]] to [[BITMAP_BOX]]
-// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassCACyt6noFail_tcfc
+// CHECK:         [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassC6noFailACyt_tcfc
 // CHECK-NEXT:    [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
 // CHECK-NEXT:    store [[NEW_SELF]] to [[SELF_BOX]]
-// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
+// CHECK:         [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapyS2iKF
 // CHECK-NEXT:    try_apply [[UNWRAP_FN]](%0)
 // CHECK:       bb2([[RESULT:%.*]] : $Int):
 // CHECK-NEXT:    strong_retain [[NEW_SELF]]
diff --git a/test/SILOptimizer/definite_init_failable_initializers_objc.swift b/test/SILOptimizer/definite_init_failable_initializers_objc.swift
index 9a5810c..7b52282 100644
--- a/test/SILOptimizer/definite_init_failable_initializers_objc.swift
+++ b/test/SILOptimizer/definite_init_failable_initializers_objc.swift
@@ -7,12 +7,12 @@
 }
 
 extension P3 {
-  // CHECK-LABEL: sil hidden @_T040definite_init_failable_initializers_objc2P3PAAESQyxGs5Int64V3p3a_tcfC : $@convention(method) <Self where Self : P3> (Int64, @thick Self.Type) -> @owned Optional<Self>
+  // CHECK-LABEL: sil hidden @_T040definite_init_failable_initializers_objc2P3PAAE3p3aSQyxGs5Int64V_tcfC : $@convention(method) <Self where Self : P3> (Int64, @thick Self.Type) -> @owned Optional<Self>
   init!(p3a: Int64) {
     self.init(p3: p3a)! // unnecessary-but-correct '!'
   }
 
-  // CHECK-LABEL: sil hidden @_T040definite_init_failable_initializers_objc2P3PAAExs5Int64V3p3b_tcfC : $@convention(method) <Self where Self : P3> (Int64, @thick Self.Type) -> @owned Self
+  // CHECK-LABEL: sil hidden @_T040definite_init_failable_initializers_objc2P3PAAE3p3bxs5Int64V_tcfC : $@convention(method) <Self where Self : P3> (Int64, @thick Self.Type) -> @owned Self
   init(p3b: Int64) {
     self.init(p3: p3b)! // necessary '!'
   }
@@ -29,7 +29,7 @@
 class Cat : FakeNSObject {
   let x: LifetimeTracked
 
-  // CHECK-LABEL: sil hidden @_T040definite_init_failable_initializers_objc3CatCACSgSi1n_Sb5aftertcfc : $@convention(method) (Int, Bool, @owned Cat) -> @owned Optional<Cat>
+  // CHECK-LABEL: sil hidden @_T040definite_init_failable_initializers_objc3CatC1n5afterACSgSi_Sbtcfc : $@convention(method) (Int, Bool, @owned Cat) -> @owned Optional<Cat>
   // CHECK: bb0(%0 : $Int, %1 : $Bool, %2 : $Cat):
     // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $Cat
     // CHECK:      store %2 to [[SELF_BOX]] : $*Cat
diff --git a/test/SILOptimizer/definite_init_objc_factory_init.swift b/test/SILOptimizer/definite_init_objc_factory_init.swift
index 1002361..72f2640 100644
--- a/test/SILOptimizer/definite_init_objc_factory_init.swift
+++ b/test/SILOptimizer/definite_init_objc_factory_init.swift
@@ -5,7 +5,7 @@
 import Foundation
 import ImportAsMember.Class
 
-// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So4HiveCSQyABGSQySo3BeeCG5queen_tcfCTO : $@convention(method) (@owned Optional<Bee>, @thick Hive.Type) -> @owned Optional<Hive>
+// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So4HiveC5queenSQyABGSQySo3BeeCG_tcfCTO : $@convention(method) (@owned Optional<Bee>, @thick Hive.Type) -> @owned Optional<Hive>
 func testInstanceTypeFactoryMethod(queen: Bee) {
   // CHECK: bb0([[QUEEN:%[0-9]+]] : $Optional<Bee>, [[HIVE_META:%[0-9]+]] : $@thick Hive.Type):
   // CHECK-NEXT:   [[HIVE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[HIVE_META]] : $@thick Hive.Type to $@objc_metatype Hive.Type
@@ -21,7 +21,7 @@
   // initializer, not a convenience initializer, which means it does
   // not have an initializing entry point at all.
 
-  // CHECK-LABEL: sil hidden @_T0So4HiveC027definite_init_objc_factory_C0EABSo3BeeC10otherQueen_tcfc : $@convention(method) (@owned Bee, @owned Hive) -> @owned Hive
+  // CHECK-LABEL: sil hidden @_T0So4HiveC027definite_init_objc_factory_C0E10otherQueenABSo3BeeC_tcfc : $@convention(method) (@owned Bee, @owned Hive) -> @owned Hive
   convenience init(otherQueen other: Bee) {
     // CHECK: [[SELF_ADDR:%[0-9]+]] = alloc_stack $Hive
     // CHECK: store [[OLD_SELF:%[0-9]+]] to [[SELF_ADDR]]
@@ -54,7 +54,7 @@
 }
 
 class SubHive : Hive {
-  // CHECK-LABEL: sil hidden @_T0027definite_init_objc_factory_B07SubHiveCACyt20delegatesToInherited_tcfc : $@convention(method) (@owned SubHive) -> @owned SubHive
+  // CHECK-LABEL: sil hidden @_T0027definite_init_objc_factory_B07SubHiveC20delegatesToInheritedACyt_tcfc : $@convention(method) (@owned SubHive) -> @owned SubHive
   convenience init(delegatesToInherited: ()) {
     // CHECK: [[UPCAST:%.*]] = upcast %0 : $SubHive to $Hive
     // CHECK: [[METATYPE:%.*]] = value_metatype $@thick Hive.Type, [[UPCAST]] : $Hive
diff --git a/test/SILOptimizer/definite_init_protocol_init.swift b/test/SILOptimizer/definite_init_protocol_init.swift
index ff72ad8..ac1037e 100644
--- a/test/SILOptimizer/definite_init_protocol_init.swift
+++ b/test/SILOptimizer/definite_init_protocol_init.swift
@@ -25,7 +25,7 @@
 class TrivialClass : TriviallyConstructible {
   required init(lower: Int) {}
 
-  // CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B012TrivialClassCACSi5upper_tcfc
+  // CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B012TrivialClassC5upperACSi_tcfc
   // CHECK:     bb0(%0 : $Int, [[OLD_SELF:%.*]] : $TrivialClass):
   // CHECK-NEXT:  [[SELF_BOX:%.*]] = alloc_stack $TrivialClass
   // CHECK-NEXT:  debug_value
@@ -33,7 +33,7 @@
   // CHECK-NEXT:  [[METATYPE:%.*]] = value_metatype $@thick @dynamic_self TrivialClass.Type, %1
   // CHECK-NEXT:  [[RESULT:%.*]] = alloc_stack $TrivialClass
   // CHECK-NEXT:  // function_ref
-  // CHECK-NEXT:  [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAExSi6middle_tcfC
+  // CHECK-NEXT:  [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAE6middlexSi_tcfC
   // CHECK-NEXT:  apply [[FN]]<@dynamic_self TrivialClass>([[RESULT]], %0, [[METATYPE]])
   // CHECK-NEXT:  [[NEW_SELF:%.*]] = load [[RESULT]]
   // CHECK-NEXT:  store [[NEW_SELF]] to [[SELF_BOX]]
@@ -63,12 +63,12 @@
 
   init(lower: Int) { self.x = lower }
 
-// CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B013TrivialStructVACSi5upper_tcfC
+// CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B013TrivialStructV5upperACSi_tcfC
 // CHECK:     bb0(%0 : $Int, %1 : $@thin TrivialStruct.Type):
 // CHECK-NEXT: [[SELF:%.*]] = alloc_stack $TrivialStruct
 // CHECK:      [[SELF_BOX:%.*]] = alloc_stack $TrivialStruct
 // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick TrivialStruct.Type
-// CHECK:      [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAExSi6middle_tcfC
+// CHECK:      [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAE6middlexSi_tcfC
 // CHECK-NEXT: apply [[FN]]<TrivialStruct>([[SELF_BOX]], %0, [[METATYPE]])
 // CHECK-NEXT: [[NEW_SELF:%.*]] = load [[SELF_BOX]]
 // CHECK-NEXT: store [[NEW_SELF]] to [[SELF]]
@@ -93,12 +93,12 @@
 
   init(lower: Int) { self.x = lower }
 
-// CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B017AddressOnlyStructVACSi5upper_tcfC
+// CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B017AddressOnlyStructV5upperACSi_tcfC
 // CHECK:     bb0(%0 : $*AddressOnlyStruct, %1 : $Int, %2 : $@thin AddressOnlyStruct.Type):
 // CHECK-NEXT: [[SELF:%.*]] = alloc_stack $AddressOnlyStruct
 // CHECK:      [[SELF_BOX:%.*]] = alloc_stack $AddressOnlyStruct
 // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick AddressOnlyStruct.Type
-// CHECK:      [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAExSi6middle_tcfC
+// CHECK:      [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAE6middlexSi_tcfC
 // CHECK-NEXT: apply [[FN]]<AddressOnlyStruct>([[SELF_BOX]], %1, [[METATYPE]])
 // CHECK-NEXT: copy_addr [take] [[SELF_BOX]] to [initialization] [[SELF]]
 // CHECK-NEXT: dealloc_stack [[SELF_BOX]]
@@ -126,12 +126,12 @@
     self = .NotSoTrivial
   }
 
-// CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B011TrivialEnumOACSi5upper_tcfC
+// CHECK-LABEL: sil hidden @_T0023definite_init_protocol_B011TrivialEnumO5upperACSi_tcfC
 // CHECK:     bb0(%0 : $Int, %1 : $@thin TrivialEnum.Type):
 // CHECK-NEXT: [[SELF:%.*]] = alloc_stack $TrivialEnum
 // CHECK:      [[SELF_BOX:%.*]] = alloc_stack $TrivialEnum
 // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick TrivialEnum.Type
-// CHECK:      [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAExSi6middle_tcfC
+// CHECK:      [[FN:%.*]] = function_ref @_T0023definite_init_protocol_B022TriviallyConstructiblePAAE6middlexSi_tcfC
 // CHECK-NEXT: apply [[FN]]<TrivialEnum>([[SELF_BOX]], %0, [[METATYPE]])
 // CHECK-NEXT: [[NEW_SELF:%.*]] = load [[SELF_BOX]]
 // CHECK-NEXT: store [[NEW_SELF]] to [[SELF]]
diff --git a/test/SILOptimizer/devirt_class_witness_method.sil b/test/SILOptimizer/devirt_class_witness_method.sil
index 6632c0f..1c973f6 100644
--- a/test/SILOptimizer/devirt_class_witness_method.sil
+++ b/test/SILOptimizer/devirt_class_witness_method.sil
@@ -1,5 +1,6 @@
-// RUN: %target-sil-opt -assume-parsing-unqualified-ownership-sil -enable-sil-verify-all %s -devirtualizer -sil-combine -enable-resilience | %FileCheck %s
+// RUN: %target-sil-opt -assume-parsing-unqualified-ownership-sil -enable-sil-verify-all %s -devirtualizer -sil-combine -enable-resilience -save-optimization-record-path=%t.opt.yaml | %FileCheck %s
 sil_stage canonical
+// RUN: %FileCheck -check-prefix=YAML -input-file=%t.opt.yaml %s
 
 import Builtin
 
@@ -19,6 +20,24 @@
 // CHECK: [[FN:%.*]] = function_ref @witness_thunk
 // CHECK: apply [[FN]]<C<T, U>, T, U>(
 // CHECK: return
+
+// YAML:      --- !Passed
+// YAML-NEXT: Pass:            sil-devirtualizer
+// YAML-NEXT: Name:            sil.WitnessMethodDevirtualized
+// YAML-NEXT: DebugLoc:
+// YAML-NEXT:   File:            {{.*}}/devirt_class_witness_method.sil
+// YAML-NEXT:   Line:            47
+// YAML-NEXT:   Column:          8
+// YAML-NEXT: Function:        caller
+// YAML-NEXT: Args:
+// YAML-NEXT:   - String:          'Devirtualized call to '
+// YAML-NEXT:   - Method:          '"witness_thunk"'
+// YAML-NEXT:     DebugLoc:
+// YAML-NEXT:       File:            {{.*}}/devirt_class_witness_method.sil
+// YAML-NEXT:       Line:            17
+// YAML-NEXT:       Column:          44
+// YAML-NEXT: ...
+
 sil hidden @caller : $@convention(thin) <T, U> (@owned C<T, U>) -> () {
 bb0(%0 : $C<T, U>):
   strong_retain %0 : $C<T, U>
diff --git a/test/SILOptimizer/devirt_conditional_conformance.swift b/test/SILOptimizer/devirt_conditional_conformance.swift
index 4beb6dc..a992775 100644
--- a/test/SILOptimizer/devirt_conditional_conformance.swift
+++ b/test/SILOptimizer/devirt_conditional_conformance.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-frontend -enable-experimental-conditional-conformances -O -Xllvm -sil-inline-generics=false -Xllvm -sil-disable-pass=GlobalOpt %s -emit-sil -sil-verify-all | %FileCheck %s
+// RUN: %target-swift-frontend -O -Xllvm -sil-inline-generics=false -Xllvm -sil-disable-pass=GlobalOpt %s -emit-sil -sil-verify-all | %FileCheck %s
 
 
 public protocol Foo {
diff --git a/test/SILOptimizer/devirt_covariant_return.swift b/test/SILOptimizer/devirt_covariant_return.swift
index ac5f307..68961a3 100644
--- a/test/SILOptimizer/devirt_covariant_return.swift
+++ b/test/SILOptimizer/devirt_covariant_return.swift
@@ -177,7 +177,7 @@
 // Check that the Optional return value from doSomething
 // gets properly unwrapped into a Payload object and then further
 // devirtualized.
-// CHECK-LABEL: sil shared [noinline] @_T023devirt_covariant_return7driver1s5Int32VAA2C1CFTf4d_n
+// CHECK-LABEL: sil shared [noinline] @_T023devirt_covariant_return7driver1ys5Int32VAA2C1CFTf4d_n
 // CHECK: integer_literal $Builtin.Int32, 2
 // CHECK: struct $Int32 (%{{.*}} : $Builtin.Int32)
 // CHECK-NOT: class_method
@@ -191,7 +191,7 @@
 // Check that the Optional return value from doSomething
 // gets properly unwrapped into a Payload object and then further
 // devirtualized.
-// CHECK-LABEL: sil shared [noinline] @_T023devirt_covariant_return7driver3s5Int32VAA1CCFTf4g_n
+// CHECK-LABEL: sil shared [noinline] @_T023devirt_covariant_return7driver3ys5Int32VAA1CCFTf4g_n
 // CHECK: bb{{[0-9]+}}(%{{[0-9]+}} : $C2):
 // CHECK-NOT: bb{{.*}}:
 // check that for C2, we convert the non-optional result into an optional and then cast.
@@ -232,7 +232,7 @@
 
 // Check that the boo call gets properly devirtualized and that
 // that D2.foo() is inlined thanks to this.
-// CHECK-LABEL: sil shared [noinline] @_T023devirt_covariant_return7driver2s5Int32VAA2D2CFTf4g_n
+// CHECK-LABEL: sil shared [noinline] @_T023devirt_covariant_return7driver2ys5Int32VAA2D2CFTf4g_n
 // CHECK-NOT: class_method
 // CHECK: checked_cast_br [exact] %{{.*}} : $D1 to $D2
 // CHECK: bb2
@@ -277,7 +277,7 @@
 
 // Check that c.foo() is devirtualized, because the optimizer can handle the casting the return type
 // correctly, i.e. it can cast (BBB, BBB) into (AAA, AAA)
-// CHECK-LABEL: sil shared [noinline] @_T023devirt_covariant_return37testDevirtOfMethodReturningTupleTypesAA2AAC_ADtAA3CCCC_AA2BBC1btFTf4gg_n
+// CHECK-LABEL: sil shared [noinline] @_T023devirt_covariant_return37testDevirtOfMethodReturningTupleTypes_1bAA2AAC_AEtAA3CCCC_AA2BBCtFTf4gg_n
 // CHECK: checked_cast_br [exact] %{{.*}} : $CCC to $CCC
 // CHECK: checked_cast_br [exact] %{{.*}} : $CCC to $DDD
 // CHECK: checked_cast_br [exact] %{{.*}} : $CCC to $EEE
diff --git a/test/SILOptimizer/devirt_default_case.swift b/test/SILOptimizer/devirt_default_case.swift
index c3120b9..0df1f56 100644
--- a/test/SILOptimizer/devirt_default_case.swift
+++ b/test/SILOptimizer/devirt_default_case.swift
@@ -40,7 +40,7 @@
 
 // Check that call to Base2.middle can be devirtualized
 //
-// CHECK-LABEL: sil @_T019devirt_default_case9callOuterS2iF
+// CHECK-LABEL: sil @_T019devirt_default_case9callOuteryS2iF
 // CHECK: function_ref @_T019devirt_default_case5Base233_{{.*}}5inner
 // CHECK: function_ref @_T019devirt_default_case8Derived233_{{.*}}6middle
 // CHECK-NOT: class_method
@@ -97,7 +97,7 @@
 class D3: C3 {}
 class E3 :C3 {}
 
-// CHECK-TESTABLE: sil{{( hidden)?}} [thunk] [always_inline] @_T019devirt_default_case3fooSiAA2A3CF
+// CHECK-TESTABLE: sil{{( hidden)?}} [thunk] [always_inline] @_T019devirt_default_case3fooySiAA2A3CF
 
 public func testfoo1() -> Int {
   return foo(E2())
@@ -132,7 +132,7 @@
 func foo(_ a: A3) -> Int {
 // Check that call to A3.f() can be devirtualized.
 //
-// CHECK-NORMAL: sil{{( shared)?}} [noinline] @_T019devirt_default_case3fooSiAA2A3CFTf4g_n
+// CHECK-NORMAL: sil{{( shared)?}} [noinline] @_T019devirt_default_case3fooySiAA2A3CFTf4g_n
 // CHECK-NORMAL: function_ref @_T019devirt_default_case2B3C1fSiyFTf4d_n
 // CHECK-NORMAL: function_ref @_T019devirt_default_case2A3C1fSiyFTf4d_n
 // CHECK-NORMAL-NOT: class_method
@@ -168,7 +168,7 @@
 func check_static_class_devirt(_ c: C6) -> Int { 
 // Check that C.bar() and D.bar() are devirtualized.
 //
-// CHECK-LABEL: sil shared [noinline] @_T019devirt_default_case019check_static_class_A0SiAA2C6CFTf4g_n
+// CHECK-LABEL: sil shared [noinline] @_T019devirt_default_case019check_static_class_A0ySiAA2C6CFTf4g_n
 // CHECK: checked_cast_br [exact] %0 : $C6 to $C6
 // CHECK: checked_cast_br [exact] %0 : $C6 to $D6
 // CHECK: class_method
diff --git a/test/SILOptimizer/devirt_nested_class.swift b/test/SILOptimizer/devirt_nested_class.swift
index 65199ff..ef4cf3e 100644
--- a/test/SILOptimizer/devirt_nested_class.swift
+++ b/test/SILOptimizer/devirt_nested_class.swift
@@ -26,5 +26,5 @@
 foo(d: Outer<Int>.Inner<Int>(), v: 0)
 
 // CHECK-LABEL: sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32
-// CHECK: function_ref @_T019devirt_nested_class5Outer{{.*}}LC5InnerC6methodyqd0__1v_tlF : $@convention(method) <τ_0_0><τ_1_0><τ_2_0> (@in τ_2_0, @guaranteed Outer<τ_0_0>.Inner<τ_1_0>) -> ()
+// CHECK: function_ref @_T019devirt_nested_class5Outer{{.*}}LC5InnerC6method1vyqd0___tlF : $@convention(method) <τ_0_0><τ_1_0><τ_2_0> (@in τ_2_0, @guaranteed Outer<τ_0_0>.Inner<τ_1_0>) -> ()
 // CHECK: return
diff --git a/test/SILOptimizer/devirt_protocol_method_invocations.swift b/test/SILOptimizer/devirt_protocol_method_invocations.swift
index dbc1820..2bf5062 100644
--- a/test/SILOptimizer/devirt_protocol_method_invocations.swift
+++ b/test/SILOptimizer/devirt_protocol_method_invocations.swift
@@ -81,7 +81,7 @@
 }
 
 // Check that methods returning Self are not devirtualized and do not crash the compiler.
-// CHECK-LABEL: sil [noinline] @_T034devirt_protocol_method_invocations05test_a1_b11_extension_C33_invocation_with_self_return_typeAA3Foo_pAA1CCF
+// CHECK-LABEL: sil [noinline] @_T034devirt_protocol_method_invocations05test_a1_b11_extension_C33_invocation_with_self_return_typeyAA3Foo_pAA1CCF
 // CHECK: init_existential_addr
 // CHECK: open_existential_addr
 // CHECK: return
@@ -107,7 +107,7 @@
 // be propagated from init_existential_addr into witness_method and 
 // apply instructions.
 
-// CHECK-LABEL: sil shared [noinline] @_T034devirt_protocol_method_invocations05test_a1_b1_C11_invocationSiAA1CCFTf4g_n
+// CHECK-LABEL: sil shared [noinline] @_T034devirt_protocol_method_invocations05test_a1_b1_C11_invocationySiAA1CCFTf4g_n
 // CHECK-NOT: witness_method
 // CHECK: checked_cast
 // CHECK-NOT: checked_cast
@@ -138,7 +138,7 @@
 // In fact, the call is expected to be inlined and then constant-folded
 // into a single integer constant.
 
-// CHECK-LABEL: sil shared [noinline] @_T034devirt_protocol_method_invocations05test_a1_b11_extension_C11_invocations5Int32VAA1CCFTf4d_n
+// CHECK-LABEL: sil shared [noinline] @_T034devirt_protocol_method_invocations05test_a1_b11_extension_C11_invocationys5Int32VAA1CCFTf4d_n
 // CHECK-NOT: checked_cast
 // CHECK-NOT: open_existential
 // CHECK-NOT: witness_method
@@ -249,7 +249,7 @@
 }
 
 // Check that all witness_method invocations are devirtualized.
-// CHECK-LABEL: sil shared [noinline] @_T034devirt_protocol_method_invocations44testPropagationOfConcreteTypeIntoExistentialyAA1VC1v_s5Int32V1xtFTf4gd_n
+// CHECK-LABEL: sil shared [noinline] @_T034devirt_protocol_method_invocations44testPropagationOfConcreteTypeIntoExistential1v1xyAA1VC_s5Int32VtFTf4gd_n
 // CHECK-NOT: witness_method
 // CHECK-NOT: class_method
 // CHECK: return
diff --git a/test/SILOptimizer/devirt_speculate.swift b/test/SILOptimizer/devirt_speculate.swift
index ff2c9f4..5988d07 100644
--- a/test/SILOptimizer/devirt_speculate.swift
+++ b/test/SILOptimizer/devirt_speculate.swift
@@ -1,4 +1,5 @@
-// RUN: %target-swift-frontend %s -parse-as-library -O -emit-sil | %FileCheck %s
+// RUN: %target-swift-frontend %s -parse-as-library -O -emit-sil -save-optimization-record-path %t.opt.yaml | %FileCheck %s
+// RUN: %FileCheck -check-prefix=YAML -input-file=%t.opt.yaml %s
 // RUN: %target-swift-frontend %s -parse-as-library -Osize -emit-sil | %FileCheck %s --check-prefix=OSIZE
 //
 // Test speculative devirtualization.
@@ -30,7 +31,7 @@
 class Sub7 : Base {
   override func foo() {}
 }
-// CHECK: @_T016devirt_speculate28testMaxNumSpeculativeTargetsyAA4BaseCF
+// CHECK: @_T016devirt_speculate28testMaxNumSpeculativeTargetsyyAA4BaseCF
 // CHECK: checked_cast_br [exact] %0 : $Base to $Base
 // CHECK: checked_cast_br [exact] %0 : $Base to $Sub1
 // CHECK: checked_cast_br [exact] %0 : $Base to $Sub2
@@ -42,7 +43,23 @@
 // CHECK: %[[CM:[0-9]+]] = class_method %0 : $Base, #Base.foo!1 : (Base) -> () -> (), $@convention(method) (@guaranteed Base) -> ()
 // CHECK: apply %[[CM]](%0) : $@convention(method) (@guaranteed Base) -> ()
 
-// OSIZE: @_T016devirt_speculate28testMaxNumSpeculativeTargetsyAA4BaseCF
+// YAML:      Pass:            sil-speculative-devirtualizer
+// YAML-NEXT: Name:            sil.PartialSpecDevirt
+// YAML-NEXT: DebugLoc:
+// YAML-NEXT:   File:            {{.*}}/devirt_speculate.swift
+// YAML-NEXT:   Line:            66
+// YAML-NEXT:   Column:          5
+// YAML-NEXT: Function:        'testMaxNumSpeculativeTargets(_:)'
+// YAML-NEXT: Args:
+// YAML-NEXT:   - String:          'Partially devirtualized call with run-time checks for '
+// YAML-NEXT:   - NumSubTypesChecked: '6'
+// YAML-NEXT:   - String:          ' subclasses of '
+// YAML-NEXT:   - ClassType:       '$Base'
+// YAML-NEXT:   - String:          ', number of subclasses not devirtualized: '
+// YAML-NEXT:   - NotHandledSubsNum: '1'
+// YAML-NEXT: ...
+
+// OSIZE: @_T016devirt_speculate28testMaxNumSpeculativeTargetsyyAA4BaseCF
 // OSIZE-NOT: checked_cast_br [exact] %0 : $Base to $Base
 // OSIZE-NOT: checked_cast_br [exact] %0 : $Base to $Sub
 public func testMaxNumSpeculativeTargets(_ b: Base) {
diff --git a/test/SILOptimizer/devirt_speculative_nested.swift b/test/SILOptimizer/devirt_speculative_nested.swift
index dbfd46f..9914a11 100644
--- a/test/SILOptimizer/devirt_speculative_nested.swift
+++ b/test/SILOptimizer/devirt_speculative_nested.swift
@@ -20,7 +20,7 @@
 //
 // But at least, we shouldn't crash.
 
-// CHECK-LABEL: sil [thunk] [always_inline] @_T025devirt_speculative_nested3fooyAA4BaseC1x_tF : $@convention(thin) (@owned Base) -> ()
+// CHECK-LABEL: sil [thunk] [always_inline] @_T025devirt_speculative_nested3foo1xyAA4BaseC_tF : $@convention(thin) (@owned Base) -> ()
 // CHECK: checked_cast_br [exact] %0 : $Base to $Base
 // CHECK: function_ref @_T025devirt_speculative_nested4BaseC6updateyyF
 // CHECK: class_method %0 : $Base, #Base.update!1
diff --git a/test/SILOptimizer/devirt_unbound_generic.swift b/test/SILOptimizer/devirt_unbound_generic.swift
index e56133e..86c997c 100644
--- a/test/SILOptimizer/devirt_unbound_generic.swift
+++ b/test/SILOptimizer/devirt_unbound_generic.swift
@@ -55,12 +55,12 @@
 
 // Check that the instance method Derived<T>.foo can be devirtualized, because Derived.foo is an internal function,
 // Derived has no subclasses and it is a WMO compilation.
-// CHECK-LABEL: sil shared [noinline] @_T022devirt_unbound_generic5test2yAA7DerivedCyxGlF{{.*}}
+// CHECK-LABEL: sil shared [noinline] @_T022devirt_unbound_generic5test2yyAA7DerivedCyxGlFTf4d_n
 // CHECK-NOT: class_method
 // CHECK-NOT: witness_method
 // CHECK-NOT: apply
 // CHECK: return
-// CHECK: end sil function '_T022devirt_unbound_generic5test2yAA7DerivedCyxGlF{{.*}}'
+// CHECK: end sil function '_T022devirt_unbound_generic5test2yyAA7DerivedCyxGlFTf4d_n'
 @inline(never)
 func test2<T>(_ d: Derived<T>) {
    d.foo()
@@ -72,12 +72,12 @@
 
 // Check that the class method Derived<T>.boo can be devirtualized, because Derived.boo is an internal function,
 // Derived has no subclasses and it is a WMO compilation.
-// CHECK: sil shared [noinline] @_T022devirt_unbound_generic5test3yAA7DerivedCyxGlF{{.*}}
+// CHECK: sil shared [noinline] @_T022devirt_unbound_generic5test3yyAA7DerivedCyxGlFTf4d_n
 // CHECK-NOT: class_method
 // CHECK-NOT: witness_method
 // CHECK-NOT: apply
 // CHECK: return
-// CHECK: end sil function '_T022devirt_unbound_generic5test3yAA7DerivedCyxGlF{{.*}}'
+// CHECK: end sil function '_T022devirt_unbound_generic5test3yyAA7DerivedCyxGlFTf4d_n'
 @inline(never)
 func test3<T>(_ d: Derived<T>) {
    type(of: d).boo()
diff --git a/test/SILOptimizer/devirt_value_metatypes.swift b/test/SILOptimizer/devirt_value_metatypes.swift
index 9e7df3e..0c8a8e5 100644
--- a/test/SILOptimizer/devirt_value_metatypes.swift
+++ b/test/SILOptimizer/devirt_value_metatypes.swift
@@ -12,7 +12,7 @@
   override class func foo() {}
 }
 
-// CHECK-LABEL: sil [thunk] [always_inline] @_T022devirt_value_metatypes17testValueMetatypeyAA1ACF 
+// CHECK-LABEL: sil [thunk] [always_inline] @_T022devirt_value_metatypes17testValueMetatypeyyAA1ACF
 // CHECK: value_metatype $@thick A.Type
 // CHECK: checked_cast_br
 // CHECK: checked_cast_br
@@ -32,7 +32,7 @@
   override class func foo() -> Int { return 1 }
 }
 
-// CHECK-LABEL: sil [thunk] [always_inline] @_T022devirt_value_metatypes5testDSiAA1DCF
+// CHECK-LABEL: sil [thunk] [always_inline] @_T022devirt_value_metatypes5testDySiAA1DCF
 // CHECK-NOT: value_metatype %
 // D.foo is an internal method, D has no subclasses and it is a wmo compilation,
 // therefore D.foo method invocation can be devirtualized.
@@ -51,7 +51,7 @@
   override class func foo() -> Int { return 1 }
 }
 
-// CHECK-LABEL: sil [thunk] [always_inline] @_T022devirt_value_metatypes5testESiAA1ECF
+// CHECK-LABEL: sil [thunk] [always_inline] @_T022devirt_value_metatypes5testEySiAA1ECF
 // CHECK-NOT: value_metatype $@thick E.Type
 // CHECK_NOT: checked_cast_br
 // CHECK: function_ref
diff --git a/test/SILOptimizer/devirt_witness_method_conformance.swift b/test/SILOptimizer/devirt_witness_method_conformance.swift
index e515739..7618d13 100644
--- a/test/SILOptimizer/devirt_witness_method_conformance.swift
+++ b/test/SILOptimizer/devirt_witness_method_conformance.swift
@@ -7,7 +7,7 @@
 public func a(y: Sub) {
   callFoo(y)
   // specialization of callFoo for Sub:
-// CHECK-LABEL: define linkonce_odr hidden swiftcc void @_T033devirt_witness_method_conformance7callFooyxAA1XRzlFAA3SubC_Tg5Tf4d_n() local_unnamed_addr
+// CHECK-LABEL: define linkonce_odr hidden swiftcc void @_T033devirt_witness_method_conformance7callFooyyxAA1XRzlFAA3SubC_Tg5Tf4d_n() local_unnamed_addr
 }
 protocol X {
   func foo()
diff --git a/test/SILOptimizer/devirtualize.sil b/test/SILOptimizer/devirtualize.sil
index 13414d4..87c0aa9 100644
--- a/test/SILOptimizer/devirtualize.sil
+++ b/test/SILOptimizer/devirtualize.sil
@@ -1,4 +1,5 @@
-// RUN: %target-sil-opt -assume-parsing-unqualified-ownership-sil -enable-sil-verify-all %s -devirtualizer -dce | %FileCheck %s
+// RUN: %target-sil-opt -assume-parsing-unqualified-ownership-sil -enable-sil-verify-all %s -devirtualizer -dce -save-optimization-record-path=%t.yaml | %FileCheck %s
+// RUN: %FileCheck -check-prefix=YAML -input-file=%t.yaml %s
 
 sil_stage canonical
 
@@ -18,6 +19,24 @@
 //CHECK-NEXT: apply
 //CHECK-NOT: class_method
 //CHECK: return
+
+// YAML:      --- !Passed
+// YAML-NEXT: Pass:            sil-devirtualizer
+// YAML-NEXT: Name:            sil.ClassMethodDevirtualized
+// YAML-NEXT: DebugLoc:
+// YAML-NEXT:   File:            {{.*}}/devirtualize.sil
+// YAML-NEXT:   Line:            47
+// YAML-NEXT:   Column:          8
+// YAML-NEXT: Function:        function_with_cm
+// YAML-NEXT: Args:
+// YAML-NEXT:   - String:          'Devirtualized call to class method '
+// YAML-NEXT:   - Method:          '"main.Bar.foo(_:)"'
+// YAML-NEXT:     DebugLoc:
+// YAML-NEXT:       File:            {{.*}}/devirtualize.sil
+// YAML-NEXT:       Line:            53
+// YAML-NEXT:       Column:          6
+// YAML-NEXT: ...
+
 sil @function_with_cm : $@convention(thin) () -> () {
 bb0:
   %0 = global_addr @x : $*Bar                     // users: %2, %3
@@ -59,6 +78,24 @@
   return %4 : $Int
 }
 
+// YAML-NEXT: --- !Passed
+// YAML-NEXT: Pass:            sil-devirtualizer
+// YAML-NEXT: Name:            sil.ClassMethodDevirtualized
+// YAML-NEXT: DebugLoc:
+// YAML-NEXT:   File:            {{.*}}/devirtualize.sil
+// YAML-NEXT:   Line:            74
+// YAML-NEXT:   Column:          8
+// YAML-NEXT: Function:        class_method_apply
+// YAML-NEXT: Args:
+// YAML-NEXT:   - String:          'Devirtualized call to class method '
+// YAML-NEXT:   - Method:          '"transparent_target"'
+// YAML-NEXT:     DebugLoc:
+// YAML-NEXT:       File:            {{.*}}/devirtualize.sil
+// YAML-NEXT:       Line:            100
+// YAML-NEXT:       Column:          39
+// YAML-NEXT: ...
+
+
 // CHECK-LABEL: sil private [transparent] [noinline] @transparent_target
 sil private [transparent] [noinline] @transparent_target : $@convention(method) (@guaranteed Node) -> Int {
 bb0(%0 : $Node):
@@ -93,6 +130,23 @@
   return %5 : $()
 }
 
+// YAML-NEXT: --- !Passed
+// YAML-NEXT: Pass:            sil-devirtualizer
+// YAML-NEXT: Name:            sil.ClassMethodDevirtualized
+// YAML-NEXT: DebugLoc:
+// YAML-NEXT:   File:            {{.*}}/devirtualize.sil
+// YAML-NEXT:   Line:            127
+// YAML-NEXT:   Column:          8
+// YAML-NEXT: Function:        'caller(_:)'
+// YAML-NEXT: Args:
+// YAML-NEXT:   - String:          'Devirtualized call to class method '
+// YAML-NEXT:   - Method:          '"static meta.B.foo(_:)"'
+// YAML-NEXT:     DebugLoc:
+// YAML-NEXT:       File:            {{.*}}/devirtualize.sil
+// YAML-NEXT:       Line:            118
+// YAML-NEXT:       Column:          6
+// YAML-NEXT: ...
+
 sil_vtable B {
   #B.foo!1: _TZFC4metaP33_7026FC13D35FB9700BACF693F51A99011B3foofMS0_FT_Si
 }
diff --git a/test/SILOptimizer/eager_specialize.sil b/test/SILOptimizer/eager_specialize.sil
index 1e2f807..34bc488 100644
--- a/test/SILOptimizer/eager_specialize.sil
+++ b/test/SILOptimizer/eager_specialize.sil
@@ -72,7 +72,7 @@
 // Helper
 //
 // G.getContainer(A.Elt) -> A
-sil @_T016eager_specialize1GV12getContainerx3EltQzF : $@convention(method) <Container where Container : HasElt> (@in Container.Elt, G<Container>) -> @out Container {
+sil @_T016eager_specialize1GV12getContaineryx3EltQzF : $@convention(method) <Container where Container : HasElt> (@in Container.Elt, G<Container>) -> @out Container {
 bb0(%0 : $*Container, %1 : $*Container.Elt, %2 : $G<Container>):
   %4 = witness_method $Container, #HasElt.init!allocator.1 : $@convention(witness_method: HasElt) <τ_0_0 where τ_0_0 : HasElt> (@in τ_0_0.Elt, @thick τ_0_0.Type) -> @out τ_0_0
   %5 = metatype $@thick Container.Type
@@ -82,10 +82,10 @@
 }
 
 // getGenericContainer<A where ...> (G<A>, e : A.Elt) -> A
-sil [_specialize where T == S] @_T016eager_specialize19getGenericContainerxAA1GVyxG_3EltQz1etAA03HasF0RzAA02AnF0AGRQlF : $@convention(thin) <T where T : HasElt, T.Elt : AnElt> (G<T>, @in T.Elt) -> @out T {
+sil [_specialize where T == S] @_T016eager_specialize19getGenericContainer_1exAA1GVyxG_3EltQztAA03HasF0RzAA02AnF0AHRQlF : $@convention(thin) <T where T : HasElt, T.Elt : AnElt> (G<T>, @in T.Elt) -> @out T {
 bb0(%0 : $*T, %1 : $G<T>, %2 : $*T.Elt):
   // function_ref G.getContainer(A.Elt) -> A
-  %5 = function_ref @_T016eager_specialize1GV12getContainerx3EltQzF : $@convention(method) <τ_0_0 where τ_0_0 : HasElt> (@in τ_0_0.Elt, G<τ_0_0>) -> @out τ_0_0
+  %5 = function_ref @_T016eager_specialize1GV12getContaineryx3EltQzF : $@convention(method) <τ_0_0 where τ_0_0 : HasElt> (@in τ_0_0.Elt, G<τ_0_0>) -> @out τ_0_0
   %6 = apply %5<T>(%0, %2, %1) : $@convention(method) <τ_0_0 where τ_0_0 : HasElt> (@in τ_0_0.Elt, G<τ_0_0>) -> @out τ_0_0
   %7 = tuple ()
   return %7 : $()
@@ -93,13 +93,13 @@
 
 // Specialization getGenericContainer<S, X>
 //
-// CHECK-LABEL: sil shared @_T016eager_specialize19getGenericContainerxAA1GVyxG_3EltQz1etAA03HasF0RzAA02AnF0AGRQlF4main1SV_Tg5 : $@convention(thin) (G<S>, X) -> S {
+// CHECK-LABEL: sil shared @_T016eager_specialize19getGenericContainer_1exAA1GVyxG_3EltQztAA03HasF0RzAA02AnF0AHRQlF4main1SV_Tg5 : $@convention(thin) (G<S>, X) -> S {
 // CHECK: bb0(%0 : $G<S>, %1 : $X):
 // CHECK:   return %{{.*}} : $S
 
 // Generic with specialized dispatch. No more [specialize] attribute.
 //
-// CHECK-LABEL: sil @_T016eager_specialize19getGenericContainerxAA1GVyxG_3EltQz1etAA03HasF0RzAA02AnF0AGRQlF : $@convention(thin) <T where T : HasElt, T.Elt : AnElt> (G<T>, @in T.Elt) -> @out T {
+// CHECK-LABEL: sil @_T016eager_specialize19getGenericContainer_1exAA1GVyxG_3EltQztAA03HasF0RzAA02AnF0AHRQlF : $@convention(thin) <T where T : HasElt, T.Elt : AnElt> (G<T>, @in T.Elt) -> @out T {
 // CHECK: bb0(%0 : $*T, %1 : $G<T>, %2 : $*T.Elt):
 // CHECK:   %3 = metatype $@thick T.Type
 // CHECK:   %4 = metatype $@thick S.Type
@@ -109,7 +109,7 @@
 // CHECK:   cond_br %7, bb3, bb1
 
 // CHECK: bb1:
-// CHECK:   %9 = function_ref @_T016eager_specialize1GV12getContainerx3EltQzF : $@convention(method) <τ_0_0 where τ_0_0 : HasElt> (@in τ_0_0.Elt, G<τ_0_0>) -> @out τ_0_0
+// CHECK:   %9 = function_ref @_T016eager_specialize1GV12getContaineryx3EltQzF : $@convention(method) <τ_0_0 where τ_0_0 : HasElt> (@in τ_0_0.Elt, G<τ_0_0>) -> @out τ_0_0
 // CHECK:   %10 = apply %9<T>(%0, %2, %1) : $@convention(method) <τ_0_0 where τ_0_0 : HasElt> (@in τ_0_0.Elt, G<τ_0_0>) -> @out τ_0_0
 // CHECK:   br bb2
 
@@ -123,7 +123,7 @@
 // CHECK:   %16 = unchecked_addr_cast %2 : $*T.Elt to $*X
 // CHECK:   %17 = load %16 : $*X
   // function_ref specialized getGenericContainer<A where ...> (G<A>, e : A.Elt) -> A
-// CHECK:   %18 = function_ref @_T016eager_specialize19getGenericContainerxAA1GVyxG_3EltQz1etAA03HasF0RzAA02AnF0AGRQlF4main1SV_Tg5 : $@convention(thin) (G<S>, X) -> S
+// CHECK:   %18 = function_ref @_T016eager_specialize19getGenericContainer_1exAA1GVyxG_3EltQztAA03HasF0RzAA02AnF0AHRQlF4main1SV_Tg5 : $@convention(thin) (G<S>, X) -> S
 // CHECK:   %19 = apply %18(%15, %17) : $@convention(thin) (G<S>, X) -> S
 // CHECK:   store %19 to %14 : $*S
 // CHECK:   %21 = tuple ()
@@ -135,7 +135,7 @@
 // Helper
 //
 // static != infix<A where ...> (A, A) -> Bool
-sil public_external [serialized] @_T0s2neoiSbx_xts9EquatableRzlFZ : $@convention(thin) <T where T : Equatable> (@in T, @in T) -> Bool {
+sil public_external [serialized] @_T0s2neoiySbx_xts9EquatableRzlFZ : $@convention(thin) <T where T : Equatable> (@in T, @in T) -> Bool {
 bb0(%0 : $*T, %1 : $*T):
   %4 = witness_method $T, #Equatable."=="!1 : $@convention(witness_method: Equatable) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0, @thick τ_0_0.Type) -> Bool
   %5 = metatype $@thick T.Type
@@ -148,10 +148,10 @@
 }
 
 // divideNum<A where ...> (A, den : A) throws -> A
-sil [_specialize where T == Int] @_T016eager_specialize9divideNumxx_x3dentKs13SignedIntegerRzlF : $@convention(thin) <T where T : SignedInteger, T : _ExpressibleByBuiltinIntegerLiteral> (@in T, @in T) -> (@out T, @error Error) {
+sil [_specialize where T == Int] @_T016eager_specialize9divideNum_3denxx_xtKs13SignedIntegerRzlF : $@convention(thin) <T where T : SignedInteger, T : _ExpressibleByBuiltinIntegerLiteral> (@in T, @in T) -> (@out T, @error Error) {
 bb0(%0 : $*T, %1 : $*T, %2 : $*T):
   // function_ref static != infix<A where ...> (A, A) -> Bool
-  %5 = function_ref @_T0s2neoiSbx_xts9EquatableRzlFZ : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool
+  %5 = function_ref @_T0s2neoiySbx_xts9EquatableRzlFZ : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in τ_0_0, @in τ_0_0) -> Bool
   %6 = alloc_stack $T
   copy_addr %2 to [initialization] %6 : $*T
   %8 = witness_method $T, #_ExpressibleByBuiltinIntegerLiteral.init!allocator.1 : $@convention(witness_method: _ExpressibleByBuiltinIntegerLiteral) <τ_0_0 where τ_0_0 : _ExpressibleByBuiltinIntegerLiteral> (Builtin.Int2048, @thick τ_0_0.Type) -> @out τ_0_0
@@ -182,14 +182,14 @@
 }
 
 // specialized divideNum<A where ...> (A, den : A) throws -> A
-// CHECK-LABEL: sil shared @_T016eager_specialize9divideNumxx_x3dentKs13SignedIntegerRzlFSi_Tg5 : $@convention(thin) (Int, Int) -> (Int, @error Error) {
+// CHECK-LABEL: sil shared @_T016eager_specialize9divideNum_3denxx_xtKs13SignedIntegerRzlFSi_Tg5 : $@convention(thin) (Int, Int) -> (Int, @error Error) {
 // CHECK: bb0(%0 : $Int, %1 : $Int):
 // CHECK: return %{{.*}}
 // CHECK: throw %{{.*}}
 
 // Generic with specialized dispatch. No more [specialize] attribute.
 //
-// CHECK-LABEL: sil @_T016eager_specialize9divideNumxx_x3dentKs13SignedIntegerRzlF : $@convention(thin) <T where T : SignedInteger, T : _ExpressibleByBuiltinIntegerLiteral> (@in T, @in T) -> (@out T, @error Error) {
+// CHECK-LABEL: sil @_T016eager_specialize9divideNum_3denxx_xtKs13SignedIntegerRzlF : $@convention(thin) <T where T : SignedInteger, T : _ExpressibleByBuiltinIntegerLiteral> (@in T, @in T) -> (@out T, @error Error) {
 // CHECK: bb0(%0 : $*T, %1 : $*T, %2 : $*T):
 // CHECK:   %3 = metatype $@thick T.Type
 // CHECK:   %4 = metatype $@thick Int.Type
@@ -224,7 +224,7 @@
 // CHECK:   %{{.*}} = unchecked_addr_cast %2 : $*T to $*Int
 // CHECK:   %{{.*}} = load %{{.*}} : $*Int
 // CHECK:   // function_ref specialized divideNum<A>(_:den:)
-// CHECK:   %{{.*}} = function_ref @_T016eager_specialize9divideNumxx_x3dentKs13SignedIntegerRzlFSi_Tg5 : $@convention(thin) (Int, Int) -> (Int, @error Error)
+// CHECK:   %{{.*}} = function_ref @_T016eager_specialize9divideNum_3denxx_xtKs13SignedIntegerRzlFSi_Tg5 : $@convention(thin) (Int, Int) -> (Int, @error Error)
 // CHECK:   try_apply %{{.*}}(%{{.*}}, %{{.*}}) : $@convention(thin) (Int, Int) -> (Int, @error Error), normal bb8, error bb7
 
 // CHECK: bb7(%{{.*}} : $Error):
@@ -240,7 +240,7 @@
 // --- test: multiple void and non-void return values
 
 // foo<A> (A) -> Int64
-sil hidden [noinline] [Onone] @_T016eager_specialize3foos5Int64VxlF : $@convention(thin) <T> (@in T) -> Int64 {
+sil hidden [noinline] [Onone] @_T016eager_specialize3fooys5Int64VxlF : $@convention(thin) <T> (@in T) -> Int64 {
 // %0                                             // users: %1, %4
 bb0(%0 : $*T):
   %2 = integer_literal $Builtin.Int64, 3
@@ -250,30 +250,30 @@
 }
 
 // voidReturn<A> (A) -> ()
-sil [_specialize where T == Float] [_specialize where T == Int64] @_T016eager_specialize10voidReturnyxlF : $@convention(thin) <T> (@in T) -> () {
+sil [_specialize where T == Float] [_specialize where T == Int64] @_T016eager_specialize10voidReturnyyxlF : $@convention(thin) <T> (@in T) -> () {
 bb0(%0 : $*T):
   // function_ref foo<A> (A) -> Int64
-  %2 = function_ref @_T016eager_specialize3foos5Int64VxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Int64
+  %2 = function_ref @_T016eager_specialize3fooys5Int64VxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Int64
   %3 = apply %2<T>(%0) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Int64
   %4 = tuple ()
   return %4 : $()
 }
 
 // CHECK-LABEL: // specialized voidReturn<A>(_:)
-// CHECK: sil shared @_T016eager_specialize10voidReturnyxlFSf_Tg5 : $@convention(thin) (Float) -> () {
+// CHECK: sil shared @_T016eager_specialize10voidReturnyyxlFSf_Tg5 : $@convention(thin) (Float) -> () {
 // %0                                             // user: %2
 // CHECK: bb0(%0 : $Float):
 // CHECK:   return %5 : $()
 
 // CHECK-LABEL: // specialized voidReturn<A>(_:)
-// CHECK: sil shared @_T016eager_specialize10voidReturnyxlFs5Int64V_Tg5 : $@convention(thin) (Int64) -> () {
+// CHECK: sil shared @_T016eager_specialize10voidReturnyyxlFs5Int64V_Tg5 : $@convention(thin) (Int64) -> () {
 // CHECK: bb0(%0 : $Int64):
 // CHECK:   return %5 : $()
 
 // Generic with specialized dispatch. No more [specialize] attribute.
 //
 // CHECK-LABEL: // voidReturn<A>(_:)
-// CHECK: sil @_T016eager_specialize10voidReturnyxlF : $@convention(thin) <T> (@in T) -> () {
+// CHECK: sil @_T016eager_specialize10voidReturnyyxlF : $@convention(thin) <T> (@in T) -> () {
 // CHECK: bb0(%0 : $*T):
 // CHECK:  builtin "cmp_eq_Word"
 // CHECK:   cond_br %5, bb5, bb1
@@ -283,7 +283,7 @@
 // CHECK:   cond_br %11, bb4, bb2
 
 // CHECK: bb2:
-// CHECK:   function_ref @_T016eager_specialize3foos5Int64VxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Int64
+// CHECK:   function_ref @_T016eager_specialize3fooys5Int64VxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Int64
 // CHECK:   apply %13<T>(%0) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Int64
 // CHECK:   br bb3
 
@@ -292,34 +292,34 @@
 // CHECK:   return
 
 // CHECK: bb4:
-// CHECK:   function_ref @_T016eager_specialize10voidReturnyxlFSf_Tg5 : $@convention(thin) (Float) -> ()
+// CHECK:   function_ref @_T016eager_specialize10voidReturnyyxlFSf_Tg5 : $@convention(thin) (Float) -> ()
 // CHECK:   br bb3
 
 // CHECK: bb5:
 // CHECK:   br bb3
 
 // nonvoidReturn<A>(A) -> Int64
-sil [_specialize where T == Float] [_specialize where T == Int64] @_T016eager_specialize13nonvoidReturns5Int64VxlF : $@convention(thin) <T> (@in T) -> Int64 {
+sil [_specialize where T == Float] [_specialize where T == Int64] @_T016eager_specialize13nonvoidReturnys5Int64VxlF : $@convention(thin) <T> (@in T) -> Int64 {
 // %0                                             // users: %1, %3
 bb0(%0 : $*T):
   // function_ref foo<A>(A) -> Int64
-  %2 = function_ref @_T016eager_specialize3foos5Int64VxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Int64
+  %2 = function_ref @_T016eager_specialize3fooys5Int64VxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Int64
   %3 = apply %2<T>(%0) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Int64
   return %3 : $Int64
 }
 
 // CHECK-LABEL: // specialized nonvoidReturn<A>(_:)
-// CHECK: sil shared @_T016eager_specialize13nonvoidReturns5Int64VxlFSf_Tg5 : $@convention(thin) (Float) -> Int64 {
+// CHECK: sil shared @_T016eager_specialize13nonvoidReturnys5Int64VxlFSf_Tg5 : $@convention(thin) (Float) -> Int64 {
 // CHECK: bb0(%0 : $Float):
 // CHECK:   return %4 : $Int64
 
 // CHECK-LABEL: // specialized nonvoidReturn<A>(_:)
-// CHECK: sil shared @_T016eager_specialize13nonvoidReturns5Int64VxlFAD_Tg5 : $@convention(thin) (Int64) -> Int64 {
+// CHECK: sil shared @_T016eager_specialize13nonvoidReturnys5Int64VxlFAD_Tg5 : $@convention(thin) (Int64) -> Int64 {
 // CHECK: bb0(%0 : $Int64):
 // CHECK:   return %4 : $Int64
 
 // CHECK-LABEL: // nonvoidReturn<A>(_:)
-// CHECK: sil @_T016eager_specialize13nonvoidReturns5Int64VxlF : $@convention(thin) <T> (@in T) -> Int64 {
+// CHECK: sil @_T016eager_specialize13nonvoidReturnys5Int64VxlF : $@convention(thin) <T> (@in T) -> Int64 {
 // CHECK: bb0(%0 : $*T):
 // CHECK:   builtin "cmp_eq_Word"
 // CHECK:   cond_br %{{.*}}, bb5, bb1
@@ -330,7 +330,7 @@
 
 // CHECK: bb2:
 // CHECK:   // function_ref foo<A>(_:)
-// CHECK:   function_ref @_T016eager_specialize3foos5Int64VxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Int64
+// CHECK:   function_ref @_T016eager_specialize3fooys5Int64VxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Int64
 // CHECK:   apply %13<T>
 // CHECK:   br bb3(%{{.*}} : $Int64)
 
@@ -348,38 +348,38 @@
 ////////////////////////////////////////////////////////////////////
 
 // copyValueAndReturn<A> (A, s : inout A) -> A
-sil [noinline] [_specialize where S : _Trivial(32)] [_specialize where S : _Trivial(64)] @_T016eager_specialize18copyValueAndReturnxx_xz1stlF : $@convention(thin) <S> (@in S, @inout S) -> @out S {
+sil [noinline] [_specialize where S : _Trivial(32)] [_specialize where S : _Trivial(64)] @_T016eager_specialize18copyValueAndReturn_1sxx_xztlF : $@convention(thin) <S> (@in S, @inout S) -> @out S {
 bb0(%0 : $*S, %1 : $*S, %2 : $*S):
   copy_addr %2 to [initialization] %0 : $*S
   destroy_addr %1 : $*S
   %7 = tuple ()
   return %7 : $()
-} // end sil function '_T016eager_specialize18copyValueAndReturnxx_xz1stlF'
+} // end sil function '_T016eager_specialize18copyValueAndReturn_1sxx_xztlF'
 
 
 // Check specialized for 32 bits
 // specialized copyValueAndReturn<A>(A, s : inout A) -> A
-// CHECK-LABEL: sil shared [noinline] @_T016eager_specialize18copyValueAndReturnxx_xz1stlFxxxRlze31_lIetilr_Tp5 : $@convention(thin) <τ_0_0 where τ_0_0 : _Trivial(32)> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
+// CHECK-LABEL: sil shared [noinline] @_T016eager_specialize18copyValueAndReturn_1sxx_xztlFxxxRlze31_lIetilr_Tp5 : $@convention(thin) <τ_0_0 where τ_0_0 : _Trivial(32)> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
 // CHECK: bb0(%0 : $*τ_0_0, %1 : $*τ_0_0, %2 : $*τ_0_0):
 // CHECK:  copy_addr %2 to [initialization] %0 : $*τ_0_0
 // CHECK:  destroy_addr %1 : $*τ_0_0
 // CHECK:  %5 = tuple ()
 // CHECK:  return %5 : $()
-// CHECK: } // end sil function '_T016eager_specialize18copyValueAndReturnxx_xz1stlFxxxRlze31_lIetilr_Tp5'
+// CHECK: } // end sil function '_T016eager_specialize18copyValueAndReturn_1sxx_xztlFxxxRlze31_lIetilr_Tp5'
 
 // Check specialized for 64 bits
 // specialized copyValueAndReturn<A>(A, s : inout A) -> A
-// CHECK-LABEL: sil shared [noinline] @_T016eager_specialize18copyValueAndReturnxx_xz1stlFxxxRlze63_lIetilr_Tp5 : $@convention(thin) <τ_0_0 where τ_0_0 : _Trivial(64)> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
+// CHECK-LABEL: sil shared [noinline] @_T016eager_specialize18copyValueAndReturn_1sxx_xztlFxxxRlze63_lIetilr_Tp5 : $@convention(thin) <τ_0_0 where τ_0_0 : _Trivial(64)> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
 // CHECK: bb0(%0 : $*τ_0_0, %1 : $*τ_0_0, %2 : $*τ_0_0):
 // CHECK:  copy_addr %2 to [initialization] %0 : $*τ_0_0
 // CHECK:  destroy_addr %1 : $*τ_0_0
 // CHECK:  %5 = tuple ()
 // CHECK:  return %5 : $()
-// CHECK: } // end sil function '_T016eager_specialize18copyValueAndReturnxx_xz1stlFxxxRlze63_lIetilr_Tp5'
+// CHECK: } // end sil function '_T016eager_specialize18copyValueAndReturn_1sxx_xztlFxxxRlze63_lIetilr_Tp5'
 
 // Generic with specialized dispatch. No more [specialize] attribute.
 //
-// CHECK-LABEL: sil [noinline] @_T016eager_specialize18copyValueAndReturnxx_xz1stlF : $@convention(thin) <S> (@in S, @inout S) -> @out S 
+// CHECK-LABEL: sil [noinline] @_T016eager_specialize18copyValueAndReturn_1sxx_xztlF : $@convention(thin) <S> (@in S, @inout S) -> @out S
 // Check if size == 8 bytes, i.e. 64  444its
 // CHECK:  %3 = metatype $@thick S.Type
 // CHECK:  %4 = builtin "sizeof"<S>(%3 : $@thick S.Type) : $Builtin.Word
@@ -416,7 +416,7 @@
 // CHECK:  %21 = unchecked_addr_cast %1 : $*S to $*S
 // CHECK:  %22 = unchecked_addr_cast %2 : $*S to $*S
 // function_ref specialized copyValueAndReturn<A> (A, s : inout A) -> A
-// CHECK:  %23 = function_ref @_T016eager_specialize18copyValueAndReturnxx_xz1stlFxxxRlze31_lIetilr_Tp5 : $@convention(thin) <τ_0_0 where τ_0_0 : _Trivial(32)> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
+// CHECK:  %23 = function_ref @_T016eager_specialize18copyValueAndReturn_1sxx_xztlFxxxRlze31_lIetilr_Tp5 : $@convention(thin) <τ_0_0 where τ_0_0 : _Trivial(32)> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
 // CHECK:  %24 = apply %23<S>(%20, %21, %22) : $@convention(thin) <τ_0_0 where τ_0_0 : _Trivial(32)> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
 // CHECK:  %25 = tuple ()
 // CHECK:  %26 = unchecked_trivial_bit_cast %25 : $() to $()
@@ -433,39 +433,39 @@
 // CHECK:  %31 = unchecked_addr_cast %1 : $*S to $*S
 // CHECK:  %32 = unchecked_addr_cast %2 : $*S to $*S
 // function_ref specialized copyValueAndReturn<A> (A, s : inout A) -> A
-// CHECK:  %33 = function_ref @_T016eager_specialize18copyValueAndReturnxx_xz1stlFxxxRlze63_lIetilr_Tp5 : $@convention(thin) <τ_0_0 where τ_0_0 : _Trivial(64)> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
+// CHECK:  %33 = function_ref @_T016eager_specialize18copyValueAndReturn_1sxx_xztlFxxxRlze63_lIetilr_Tp5 : $@convention(thin) <τ_0_0 where τ_0_0 : _Trivial(64)> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
 // CHECK:  %34 = apply %33<S>(%30, %31, %32) : $@convention(thin) <τ_0_0 where τ_0_0 : _Trivial(64)> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
 // CHECK:  %35 = tuple ()
 // CHECK:  %36 = unchecked_trivial_bit_cast %35 : $() to $()
 // CHECK:  br bb3
-// CHECK:  } // end sil function '_T016eager_specialize18copyValueAndReturnxx_xz1stlF'
+// CHECK:  } // end sil function '_T016eager_specialize18copyValueAndReturn_1sxx_xztlF'
 
 ////////////////////////////////////////////////////////////////////
 // Check the ability to specialize for _Trivial 
 ////////////////////////////////////////////////////////////////////
 
 // copyValueAndReturn2<A> (A, s : inout A) -> A
-sil [noinline] [_specialize where S : _Trivial] @_T016eager_specialize19copyValueAndReturn2xx_xz1stlF : $@convention(thin) <S> (@in S, @inout S) -> @out S {
+sil [noinline] [_specialize where S : _Trivial] @_T016eager_specialize19copyValueAndReturn2_1sxx_xztlF : $@convention(thin) <S> (@in S, @inout S) -> @out S {
 bb0(%0 : $*S, %1 : $*S, %2 : $*S):
   copy_addr %2 to [initialization] %0 : $*S
   destroy_addr %1 : $*S
   %7 = tuple ()
   return %7 : $()
-} // end sil function '_T016eager_specialize19copyValueAndReturn2xx_xz1stlF'
+} // end sil function '_T016eager_specialize19copyValueAndReturn2_1sxx_xztlF'
 
 // Check the specialization for _Trivial
 // specialized copyValueAndReturn2<A> (A, s : inout A) -> A
-// CHECK-LABEL: sil shared [noinline] @_T016eager_specialize19copyValueAndReturn2xx_xz1stlFxxxRlzTlIetilr_Tp5 : $@convention(thin) <τ_0_0 where τ_0_0 : _Trivial> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
+// CHECK-LABEL: sil shared [noinline] @_T016eager_specialize19copyValueAndReturn2_1sxx_xztlFxxxRlzTlIetilr_Tp5 : $@convention(thin) <τ_0_0 where τ_0_0 : _Trivial> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
 // CHECK: bb0(%0 : $*τ_0_0, %1 : $*τ_0_0, %2 : $*τ_0_0):
 // CHECK:  copy_addr %2 to [initialization] %0 : $*τ_0_0
 // CHECK:  destroy_addr %1 : $*τ_0_0
 // CHECK:  %5 = tuple ()
 // CHECK:  return %5 : $()
-// CHECK: } // end sil function '_T016eager_specialize19copyValueAndReturn2xx_xz1stlFxxxRlzTlIetilr_Tp5'
+// CHECK: } // end sil function '_T016eager_specialize19copyValueAndReturn2_1sxx_xztlFxxxRlzTlIetilr_Tp5'
 
 // Generic with specialized dispatch. No more [specialize] attribute.
 // copyValueAndReturn2<A> (A, s : inout A) -> A
-// CHECK-LABEL: sil [noinline] @_T016eager_specialize19copyValueAndReturn2xx_xz1stlF : $@convention(thin) <S> (@in S, @inout S) -> @out S
+// CHECK-LABEL: sil [noinline] @_T016eager_specialize19copyValueAndReturn2_1sxx_xztlF : $@convention(thin) <S> (@in S, @inout S) -> @out S
 // CHECK: bb0(%0 : $*S, %1 : $*S, %2 : $*S):
 // CHECK:  %3 = metatype $@thick S.Type
 // CHECK:  %4 = builtin "ispod"<S>(%3 : $@thick S.Type) : $Builtin.Int1
@@ -487,41 +487,41 @@
 // CHECK:   %12 = unchecked_addr_cast %1 : $*S to $*S
 // CHECK:   %13 = unchecked_addr_cast %2 : $*S to $*S
   // function_ref specialized copyValueAndReturn2<A> (A, s : inout A) -> A
-// CHECK:   %14 = function_ref @_T016eager_specialize19copyValueAndReturn2xx_xz1stlFxxxRlzTlIetilr_Tp5 : $@convention(thin) <τ_0_0 where τ_0_0 : _Trivial> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
+// CHECK:   %14 = function_ref @_T016eager_specialize19copyValueAndReturn2_1sxx_xztlFxxxRlzTlIetilr_Tp5 : $@convention(thin) <τ_0_0 where τ_0_0 : _Trivial> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
 // CHECK:   %15 = apply %14<S>(%11, %12, %13) : $@convention(thin) <τ_0_0 where τ_0_0 : _Trivial> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
 // CHECK:   %16 = tuple ()
 // CHECK:   %17 = unchecked_trivial_bit_cast %16 : $() to $()
 // CHECK:   br bb2
-// CHECK: } // end sil function '_T016eager_specialize19copyValueAndReturn2xx_xz1stlF'
+// CHECK: } // end sil function '_T016eager_specialize19copyValueAndReturn2_1sxx_xztlF'
 
 ////////////////////////////////////////////////////////////////////
 // Check the ability to specialize for _RefCountedObject 
 ////////////////////////////////////////////////////////////////////
 
 // copyValueAndReturn3<A> (A, s : inout A) -> A
-sil [noinline] [_specialize where S : _RefCountedObject] @_T016eager_specialize19copyValueAndReturn3xx_xz1stlF : $@convention(thin) <S> (@in S, @inout S) -> @out S {
+sil [noinline] [_specialize where S : _RefCountedObject] @_T016eager_specialize19copyValueAndReturn3_1sxx_xztlF : $@convention(thin) <S> (@in S, @inout S) -> @out S {
 bb0(%0 : $*S, %1 : $*S, %2 : $*S):
   copy_addr %2 to [initialization] %0 : $*S
   destroy_addr %1 : $*S
   %7 = tuple ()
   return %7 : $()
-} // end sil function '_T016eager_specialize19copyValueAndReturn3xx_xz1stlF'
+} // end sil function '_T016eager_specialize19copyValueAndReturn3_1sxx_xztlF'
 
 
 // Check for specialized function for _RefCountedObject
 // specialized copyValueAndReturn3<A> (A, s : inout A) -> A
-// CHECK-LABEL: sil shared [noinline] @_T016eager_specialize19copyValueAndReturn3xx_xz1stlFxxxRlzRlIetilr_Tp5 : $@convention(thin) <τ_0_0 where τ_0_0 : _RefCountedObject> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
+// CHECK-LABEL: sil shared [noinline] @_T016eager_specialize19copyValueAndReturn3_1sxx_xztlFxxxRlzRlIetilr_Tp5 : $@convention(thin) <τ_0_0 where τ_0_0 : _RefCountedObject> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
 // CHECK: bb0(%0 : $*τ_0_0, %1 : $*τ_0_0, %2 : $*τ_0_0):
 // CHECK:   copy_addr %2 to [initialization] %0 : $*τ_0_0
 // CHECK:   destroy_addr %1 : $*τ_0_0
 // CHECK:   %5 = tuple ()
 // CHECK:   return %5 : $()
-// CHECK: } // end sil function '_T016eager_specialize19copyValueAndReturn3xx_xz1stlFxxxRlzRlIetilr_Tp5'
+// CHECK: } // end sil function '_T016eager_specialize19copyValueAndReturn3_1sxx_xztlFxxxRlzRlIetilr_Tp5'
 
 
 // Generic with specialized dispatch. No more [specialize] attribute.
 // copyValueAndReturn3<A> (A, s : inout A) -> A
-// CHECK-LABEL: sil [noinline] @_T016eager_specialize19copyValueAndReturn3xx_xz1stlF : $@convention(thin) <S> (@in S, @inout S) -> @out S {
+// CHECK-LABEL: sil [noinline] @_T016eager_specialize19copyValueAndReturn3_1sxx_xztlF : $@convention(thin) <S> (@in S, @inout S) -> @out S {
 // Check if can be a class
 // CHECK: bb0(%0 : $*S, %1 : $*S, %2 : $*S):
 // CHECK:   %3 = metatype $@thick S.Type
@@ -546,7 +546,7 @@
 // CHECK:   %14 = unchecked_addr_cast %1 : $*S to $*S
 // CHECK:   %15 = unchecked_addr_cast %2 : $*S to $*S
   // function_ref specialized copyValueAndReturn3<A> (A, s : inout A) -> A
-// CHECK:   %16 = function_ref @_T016eager_specialize19copyValueAndReturn3xx_xz1stlFxxxRlzRlIetilr_Tp5 : $@convention(thin) <τ_0_0 where τ_0_0 : _RefCountedObject> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
+// CHECK:   %16 = function_ref @_T016eager_specialize19copyValueAndReturn3_1sxx_xztlFxxxRlzRlIetilr_Tp5 : $@convention(thin) <τ_0_0 where τ_0_0 : _RefCountedObject> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
 // CHECK:   %17 = apply %16<S>(%13, %14, %15) : $@convention(thin) <τ_0_0 where τ_0_0 : _RefCountedObject> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
 // CHECK:   %18 = tuple ()
 // CHECK:   %19 = unchecked_trivial_bit_cast %18 : $() to $()
@@ -564,7 +564,7 @@
 // CHECK:   %25 = apply %24<S>(%3) : $@convention(thin) <τ_0_0> (@thick τ_0_0.Type) -> Bool
 // CHECK:   %26 = struct_extract %25 : $Bool, #Bool._value
 // CHECK:   cond_br %26, bb3, bb1
-// CHECK: } // end sil function '_T016eager_specialize19copyValueAndReturn3xx_xz1stlF'
+// CHECK: } // end sil function '_T016eager_specialize19copyValueAndReturn3_1sxx_xztlF'
 
 ////////////////////////////////////////////////////////////////////
 // Check the ability to produce exported specializations, which can
@@ -572,34 +572,34 @@
 ////////////////////////////////////////////////////////////////////
 
 // exportSpecializations<A> (A) -> ()
-sil [_specialize exported: true, where T == Int64] @_T016eager_specialize21exportSpecializationsyxlF : $@convention(thin) <T> (@in T) -> () {
+sil [_specialize exported: true, where T == Int64] @_T016eager_specialize21exportSpecializationsyyxlF : $@convention(thin) <T> (@in T) -> () {
 bb0(%0 : $*T):
   destroy_addr %0 : $*T
   %3 = tuple ()
   return %3 : $()
-} // end sil function '_T016eager_specialize21exportSpecializationsyxlF'
+} // end sil function '_T016eager_specialize21exportSpecializationsyyxlF'
 
 // Check that a public specialization for Int64 was produced.
 // specialized exportSpecializations<A> (A) -> ()
-// CHECK-DEADFUNCELIM-LABEL: sil @_T016eager_specialize21exportSpecializationsyxlFs5Int64V_Tg5 : $@convention(thin) (Int64) -> ()
+// CHECK-DEADFUNCELIM-LABEL: sil @_T016eager_specialize21exportSpecializationsyyxlFs5Int64V_Tg5 : $@convention(thin) (Int64) -> ()
 
 ////////////////////////////////////////////////////////////////////
 // Check the ability to produce explicit partial specializations.
 ////////////////////////////////////////////////////////////////////
 
 // checkExplicitPartialSpecialization<A, B> (A, B) -> ()
-sil [_specialize kind: partial, where T == Int64] @_T016eager_specialize34checkExplicitPartialSpecializationyx_q_tr0_lF : $@convention(thin) <T, S> (@in T, @in S) -> () {
+sil [_specialize kind: partial, where T == Int64] @_T016eager_specialize34checkExplicitPartialSpecializationyyx_q_tr0_lF : $@convention(thin) <T, S> (@in T, @in S) -> () {
 bb0(%0 : $*T, %1 : $*S):
   destroy_addr %1 : $*S
   destroy_addr %0 : $*T
   %6 = tuple ()
   return %6 : $()
-} // end sil function '_T016eager_specialize34checkExplicitPartialSpecializationyx_q_tr0_lF'
+} // end sil function '_T016eager_specialize34checkExplicitPartialSpecializationyyx_q_tr0_lF'
 
 
 // Check for specialized function for τ_0_0 == Int64
 // specialized checkExplicitPartialSpecialization<A, B> (A, B) -> ()
-// CHECK-LABEL: sil shared @_T016eager_specialize34checkExplicitPartialSpecializationyx_q_tr0_lFs5Int64Vq_ADRszr0_lIetyi_Tp5 : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 == Int64> (Int64, @in τ_0_1) -> ()
+// CHECK-LABEL: sil shared @_T016eager_specialize34checkExplicitPartialSpecializationyyx_q_tr0_lFs5Int64Vq_ADRszr0_lIetyi_Tp5 : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 == Int64> (Int64, @in τ_0_1) -> ()
 // CHECK: bb0(%0 : $Int64, %1 : $*τ_0_1):
 // CHECK:   %2 = alloc_stack $Int64
 // CHECK:   store %0 to %2 : $*Int64
@@ -608,11 +608,11 @@
 // CHECK:   %6 = tuple ()
 // CHECK:   dealloc_stack %2 : $*Int64
 // CHECK:   return %6 : $()
-// CHECK: } // end sil function '_T016eager_specialize34checkExplicitPartialSpecializationyx_q_tr0_lFs5Int64Vq_ADRszr0_lIetyi_Tp5'
+// CHECK: } // end sil function '_T016eager_specialize34checkExplicitPartialSpecializationyyx_q_tr0_lFs5Int64Vq_ADRszr0_lIetyi_Tp5'
 
 // Generic with specialized dispatch. No more [specialize] attribute.
 // checkExplicitPartialSpecialization<A, B> (A, B) -> ()
-// CHECK-LABEL: sil @_T016eager_specialize34checkExplicitPartialSpecializationyx_q_tr0_lF : $@convention(thin) <T, S> (@in T, @in S) -> ()
+// CHECK-LABEL: sil @_T016eager_specialize34checkExplicitPartialSpecializationyyx_q_tr0_lF : $@convention(thin) <T, S> (@in T, @in S) -> ()
 // CHECK: bb0(%0 : $*T, %1 : $*S):
 // CHECK:   %2 = metatype $@thick T.Type
 // CHECK:   %3 = metatype $@thick Int64.Type
@@ -637,12 +637,12 @@
 // CHECK:   %14 = load %13 : $*Int64
 // CHECK:   %15 = unchecked_addr_cast %1 : $*S to $*S
 // function_ref specialized checkExplicitPartialSpecialization<A, B> (A, B) -> ()
-// CHECK:   %16 = function_ref @_T016eager_specialize34checkExplicitPartialSpecializationyx_q_tr0_lFs5Int64Vq_ADRszr0_lIetyi_Tp5 : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 == Int64> (Int64, @in τ_0_1) -> ()
+// CHECK:   %16 = function_ref @_T016eager_specialize34checkExplicitPartialSpecializationyyx_q_tr0_lFs5Int64Vq_ADRszr0_lIetyi_Tp5 : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 == Int64> (Int64, @in τ_0_1) -> ()
 // CHECK:   %17 = apply %16<S>(%14, %15) : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 == Int64> (Int64, @in τ_0_1) -> ()
 // CHECK:   %18 = tuple ()
 // CHECK:   %19 = unchecked_trivial_bit_cast %18 : $() to $()
 // CHECK:   br bb2
-// CHECK: } // end sil function '_T016eager_specialize34checkExplicitPartialSpecializationyx_q_tr0_lF'
+// CHECK: } // end sil function '_T016eager_specialize34checkExplicitPartialSpecializationyyx_q_tr0_lF'
 
 /////////////////////////////////////////////////////////////////////////
 // Check that functions with unreachable instructions can be specialized.
@@ -661,7 +661,7 @@
 
 sil @error : $@convention(thin) () -> Never
 
-// CHECK-LABEL: sil @_T016eager_specialize1PPAAE1fxxFZ : $@convention(method) <Self where Self : P> (@in Self, @thick Self.Type) -> @out Self
+// CHECK-LABEL: sil @_T016eager_specialize1PPAAE1fyxxFZ : $@convention(method) <Self where Self : P> (@in Self, @thick Self.Type) -> @out Self
 // CHECK: %3 = metatype $@thick Self.Type
 // CHECK:  %4 = metatype $@thick T.Type
 // CHECK:  %5 = unchecked_bitwise_cast %3 : $@thick Self.Type to $Builtin.Word
@@ -679,20 +679,20 @@
 // CHECK:  %13 = unchecked_addr_cast %1 : $*Self to $*T
 // CHECK:  %14 = load %13 : $*T
 // CHECK:  %15 = unchecked_trivial_bit_cast %2 : $@thick Self.Type to $@thick T.Type
-// CHECK:  %16 = function_ref @_T016eager_specialize1PPAAE1fxxFZ4main1TV_Tg5 : $@convention(method) (T, @thick T.Type) -> T
+// CHECK:  %16 = function_ref @_T016eager_specialize1PPAAE1fyxxFZ4main1TV_Tg5 : $@convention(method) (T, @thick T.Type) -> T
 // CHECK:  %17 = apply %16(%14, %15) : $@convention(method) (T, @thick T.Type) -> T
 // CHECK:  store %17 to %12 : $*T
 // CHECK:  %19 = tuple ()
 // CHECK:  unreachable 
-// CHECK: } // end sil function '_T016eager_specialize1PPAAE1fxxFZ'
+// CHECK: } // end sil function '_T016eager_specialize1PPAAE1fyxxFZ'
 
-sil [_specialize exported: false, kind: full, where Self == T] @_T016eager_specialize1PPAAE1fxxFZ : $@convention(method) <Self where Self : P> (@in Self, @thick Self.Type) -> @out Self {
+sil [_specialize exported: false, kind: full, where Self == T] @_T016eager_specialize1PPAAE1fyxxFZ : $@convention(method) <Self where Self : P> (@in Self, @thick Self.Type) -> @out Self {
 bb0(%0 : $*Self, %1 : $*Self, %2 : $@thick Self.Type):
   // function_ref error
   %5 = function_ref @error : $@convention(thin) () -> Never
   %6 = apply %5() : $@convention(thin) () -> Never
   unreachable 
-} // end sil function '_T016eager_specialize1PPAAE1fxxFZ'
+} // end sil function '_T016eager_specialize1PPAAE1fyxxFZ'
 
 
 ////////////////////////////////////////////////////////////////////
@@ -702,7 +702,7 @@
 
 // Check that a specialization for _Trivial(32) uses direct loads and stores
 // instead of value witness functions to load and store the value of a generic type.
-// CHECK-IRGEN-LABEL: define linkonce_odr hidden swiftcc void @_T016eager_specialize18copyValueAndReturnxx_xz1stlFxxxRlze31_lIetilr_Tp5(i32* noalias nocapture sret, i32* noalias nocapture dereferenceable(4), i32* nocapture dereferenceable(4), %swift.type* %"\CF\84_0_0")
+// CHECK-IRGEN-LABEL: define linkonce_odr hidden swiftcc void @_T016eager_specialize18copyValueAndReturn_1sxx_xztlFxxxRlze31_lIetilr_Tp5(i32* noalias nocapture sret, i32* noalias nocapture dereferenceable(4), i32* nocapture dereferenceable(4), %swift.type* %"\CF\84_0_0")
 // CHECK-IRGEN: entry:
 // CHECK-IRGEN-NEXT:  %3 = load i32, i32* %2
 // CHECK-IRGEN-NEXT:  store i32 %3, i32* %0
@@ -711,7 +711,7 @@
 
 // Check that a specialization for _Trivial(64) uses direct loads and stores
 // instead of value witness functions to load and store the value of a generic type.
-// CHECK-IRGEN-LABEL: define linkonce_odr hidden swiftcc void @_T016eager_specialize18copyValueAndReturnxx_xz1stlFxxxRlze63_lIetilr_Tp5(i64* noalias nocapture sret, i64* noalias nocapture dereferenceable(8), i64* nocapture dereferenceable(8), %swift.type* %"\CF\84_0_0")
+// CHECK-IRGEN-LABEL: define linkonce_odr hidden swiftcc void @_T016eager_specialize18copyValueAndReturn_1sxx_xztlFxxxRlze63_lIetilr_Tp5(i64* noalias nocapture sret, i64* noalias nocapture dereferenceable(8), i64* nocapture dereferenceable(8), %swift.type* %"\CF\84_0_0")
 // CHECK-IRGEN: entry:
 // CHECK-IRGEN-NEXT:   %3 = load i64, i64* %2
 // CHECK-IRGEN-NEXT:   store i64 %3, i64* %0
@@ -720,7 +720,7 @@
 
 // Check that a specialization for _Trivial does not call the 'destroy' value witness,
 // because it is known that the object is Trivial, i.e. contains no references.
-// CHECK-IRGEN-LABEL: define linkonce_odr hidden swiftcc void @_T016eager_specialize19copyValueAndReturn2xx_xz1stlFxxxRlzTlIetilr_Tp5(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.opaque* nocapture, %swift.type* %"\CF\84_0_0")
+// CHECK-IRGEN-LABEL: define linkonce_odr hidden swiftcc void @_T016eager_specialize19copyValueAndReturn2_1sxx_xztlFxxxRlzTlIetilr_Tp5(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.opaque* nocapture, %swift.type* %"\CF\84_0_0")
 // CHECK-IRGEN-NEXT: entry:
 // CHECK-IRGEN-NEXT:   %3 = bitcast %swift.type* %"\CF\84_0_0" to i8***
 // CHECK-IRGEN-NEXT:   %4 = getelementptr inbounds i8**, i8*** %3, i{{.*}} -1
@@ -735,7 +735,7 @@
 // Check that a specialization for _RefCountedObject just copies the fixed-size reference,
 // and call retain/release directly, instead of calling the value witness functions.
 // The matching patterns in this test are rather non-precise to cover both objc and non-objc platforms.
-// CHECK-IRGEN-LABEL: define{{.*}}@_T016eager_specialize19copyValueAndReturn3xx_xz1stlFxxxRlzRlIetilr_Tp5
+// CHECK-IRGEN-LABEL: define{{.*}}@_T016eager_specialize19copyValueAndReturn3_1sxx_xztlFxxxRlzRlIetilr_Tp5
 // CHECK-IRGEN: entry:
 // CHECK-IRGEN-NOT: ret void
 // CHECK-IRGEN:   call {{.*}}etain
@@ -786,12 +786,12 @@
 // It should dispatch to its specialized version, but use apply [nothrow] to invoke
 // the specialized version.
 
-// CHECK-LABEL: sil @_T034eager_specialize_throwing_function19ClassUsingThrowingPC1fACXDxKAA0G1PRzlFZ : $@convention(method) <T where T : ThrowingP> (@in T, @thick ClassUsingThrowingP.Type) -> (@owned ClassUsingThrowingP, @error Error)
-// CHECK: [[SPECIALIZED:%.*]] = function_ref @_T034eager_specialize_throwing_function19ClassUsingThrowingPC1fACXDxKAA0G1PRzlFZs5Int64V_Tg5 : $@convention(method) (Int64, @thick ClassUsingThrowingP.Type) -> (@owned ClassUsingThrowingP, @error Error)
+// CHECK-LABEL: sil @_T034eager_specialize_throwing_function19ClassUsingThrowingPC1fyACXDxKAA0G1PRzlFZ : $@convention(method) <T where T : ThrowingP> (@in T, @thick ClassUsingThrowingP.Type) -> (@owned ClassUsingThrowingP, @error Error)
+// CHECK: [[SPECIALIZED:%.*]] = function_ref @_T034eager_specialize_throwing_function19ClassUsingThrowingPC1fyACXDxKAA0G1PRzlFZs5Int64V_Tg5 : $@convention(method) (Int64, @thick ClassUsingThrowingP.Type) -> (@owned ClassUsingThrowingP, @error Error)
 // CHECK: apply [nothrow] [[SPECIALIZED]]
-// CHECK: // end sil function '_T034eager_specialize_throwing_function19ClassUsingThrowingPC1fACXDxKAA0G1PRzlFZ'
+// CHECK: // end sil function '_T034eager_specialize_throwing_function19ClassUsingThrowingPC1fyACXDxKAA0G1PRzlFZ'
 // static ClassUsingThrowingP.f<A>(_:)
-sil [_specialize exported: false, kind: full, where T == Int64] @_T034eager_specialize_throwing_function19ClassUsingThrowingPC1fACXDxKAA0G1PRzlFZ : $@convention(method) <T where T : ThrowingP> (@in T, @thick ClassUsingThrowingP.Type) -> (@owned ClassUsingThrowingP, @error Error) {
+sil [_specialize exported: false, kind: full, where T == Int64] @_T034eager_specialize_throwing_function19ClassUsingThrowingPC1fyACXDxKAA0G1PRzlFZ : $@convention(method) <T where T : ThrowingP> (@in T, @thick ClassUsingThrowingP.Type) -> (@owned ClassUsingThrowingP, @error Error) {
 bb0(%0 : $*T, %1 : $@thick ClassUsingThrowingP.Type):
   destroy_addr %0 : $*T
   %4 = unchecked_trivial_bit_cast %1 : $@thick ClassUsingThrowingP.Type to $@thick @dynamic_self ClassUsingThrowingP.Type
@@ -801,7 +801,7 @@
   %9 = apply %7(%8) : $@convention(method) (@thick ClassUsingThrowingP.Type) -> @owned ClassUsingThrowingP
   %10 = unchecked_ref_cast %9 : $ClassUsingThrowingP to $ClassUsingThrowingP
   return %10 : $ClassUsingThrowingP
-} // end sil function '_T034eager_specialize_throwing_function19ClassUsingThrowingPC1fACXDxKAA0G1PRzlFZ'
+} // end sil function '_T034eager_specialize_throwing_function19ClassUsingThrowingPC1fyACXDxKAA0G1PRzlFZ'
 
 // g is a function that may throw according to its type and has a try_apply inisde
 // its body.
@@ -809,13 +809,13 @@
 // It should dispatch to its specialized version and use try_apply to invoke
 // the specialized version.
 
-// CHECK-LABEL: sil @_T034eager_specialize_throwing_function19ClassUsingThrowingPC1gs5Int64VxKAA0G1PRzlFZ : $@convention(method) <T where T : ThrowingP> (@in T, @thick ClassUsingThrowingP.Type) -> (Int64, @error Error)
-// CHECK: [[SPECIALIZED:%.*]] = function_ref @_T034eager_specialize_throwing_function19ClassUsingThrowingPC1gs5Int64VxKAA0G1PRzlFZAF_Tg5 : $@convention(method) (Int64, @thick ClassUsingThrowingP.Type) -> (Int64, @error Error)
+// CHECK-LABEL: sil @_T034eager_specialize_throwing_function19ClassUsingThrowingPC1gys5Int64VxKAA0G1PRzlFZ : $@convention(method) <T where T : ThrowingP> (@in T, @thick ClassUsingThrowingP.Type) -> (Int64, @error Error)
+// CHECK: [[SPECIALIZED:%.*]] = function_ref @_T034eager_specialize_throwing_function19ClassUsingThrowingPC1gys5Int64VxKAA0G1PRzlFZAF_Tg5 : $@convention(method) (Int64, @thick ClassUsingThrowingP.Type) -> (Int64, @error Error)
 // CHECK: try_apply [[SPECIALIZED]]
-// CHECK: // end sil function '_T034eager_specialize_throwing_function19ClassUsingThrowingPC1gs5Int64VxKAA0G1PRzlFZ'
+// CHECK: // end sil function '_T034eager_specialize_throwing_function19ClassUsingThrowingPC1gys5Int64VxKAA0G1PRzlFZ'
 
 // static ClassUsingThrowingP.g<A>(_:)
-sil [_specialize exported: false, kind: full, where T == Int64] @_T034eager_specialize_throwing_function19ClassUsingThrowingPC1gs5Int64VxKAA0G1PRzlFZ : $@convention(method) <T where T : ThrowingP> (@in T, @thick ClassUsingThrowingP.Type) -> (Int64, @error Error) {
+sil [_specialize exported: false, kind: full, where T == Int64] @_T034eager_specialize_throwing_function19ClassUsingThrowingPC1gys5Int64VxKAA0G1PRzlFZ : $@convention(method) <T where T : ThrowingP> (@in T, @thick ClassUsingThrowingP.Type) -> (Int64, @error Error) {
 bb0(%0 : $*T, %1 : $@thick ClassUsingThrowingP.Type):
   %5 = witness_method $T, #ThrowingP.action!1 : <Self where Self : ThrowingP> (Self) -> () throws -> Int64 : $@convention(witness_method: ThrowingP) <τ_0_0 where τ_0_0 : ThrowingP> (@in_guaranteed τ_0_0) -> (Int64, @error Error)
   try_apply %5<T>(%0) : $@convention(witness_method: ThrowingP) <τ_0_0 where τ_0_0 : ThrowingP> (@in_guaranteed τ_0_0) -> (Int64, @error Error), normal bb1, error bb2
@@ -827,7 +827,7 @@
 bb2(%10 : $Error):                                // Preds: bb0
   destroy_addr %0 : $*T
   throw %10 : $Error
-} // end sil function '_T034eager_specialize_throwing_function19ClassUsingThrowingPC1gs5Int64VxKAA0G1PRzlFZ'
+} // end sil function '_T034eager_specialize_throwing_function19ClassUsingThrowingPC1gys5Int64VxKAA0G1PRzlFZ'
 
 // Check that a specialization was produced and it is not inlined.
 // CHECK-EAGER-SPECIALIZE-AND-GENERICS-INLINE-LABEL: sil{{.*}}@{{.*}}testSimpleGeneric{{.*}}where τ_0_0 : _Trivial(64, 64)
diff --git a/test/SILOptimizer/earlycodemotion.sil b/test/SILOptimizer/earlycodemotion.sil
index 2db1ec9..23bd649 100644
--- a/test/SILOptimizer/earlycodemotion.sil
+++ b/test/SILOptimizer/earlycodemotion.sil
@@ -68,6 +68,8 @@
   case some(T)
 }
 
+class Klass {}
+
 sil @user : $@convention(thin) (Builtin.NativeObject) -> ()
 sil @user_int : $@convention(thin) (Int) -> ()
 sil @optional_user : $@convention(thin) (Optional<Builtin.Int32>) -> ()
@@ -1593,3 +1595,41 @@
   return %23 : $()                                // id: %25
 }
 
+// Make sure that we properly perform global blotting of values and do not crash
+// on this code. This will only fail reliably in ASAN builds of swift in such a
+// case.
+sil @test_global_blotting : $@convention(thin) () -> () {
+bbBegin:
+  %0a = enum $Optional<Klass>, #Optional.none!enumelt
+  cond_br undef, bb1, bb2
+
+bb1:
+  br bb8(%0a : $Optional<Klass>)
+
+bb2:
+  %0 = enum $Optional<Klass>, #Optional.none!enumelt
+  cond_br undef, bb7, bb3
+
+bb3:
+  cond_br undef, bb4, bb5
+
+bb4:
+  br bb6
+
+bb5:
+  br bb6
+
+bb6:
+  br bb9
+
+bb7:
+  br bb8(%0 : $Optional<Klass>)
+
+bb8(%result : $Optional<Klass>):
+  release_value %result : $Optional<Klass>
+  br bb9
+
+bb9:
+  %9999 = tuple()
+  return %9999 : $()
+}
diff --git a/test/SILOptimizer/exclusivity_static_diagnostics.sil b/test/SILOptimizer/exclusivity_static_diagnostics.sil
index 4723351..2c1faa2 100644
--- a/test/SILOptimizer/exclusivity_static_diagnostics.sil
+++ b/test/SILOptimizer/exclusivity_static_diagnostics.sil
@@ -12,6 +12,7 @@
 sil @takesInoutAndNoEscapeClosure : $@convention(thin) (@inout Int, @noescape @owned @callee_owned () -> ()) -> ()
 sil @takesInoutAndNoEscapeClosureTakingArgument : $@convention(thin) (@inout Int, @noescape @owned @callee_owned (Int) -> ()) -> ()
 sil @takesInoutAndNoEscapeClosureWithGenericReturn : $@convention(thin) <T> (@inout Int, @owned @noescape @callee_owned (Int) -> @out T) -> ()
+sil @takesInoutAndNoEscapeBlockClosure : $@convention(thin) (@inout Int, @owned @convention(block) @noescape () -> ()) -> ()
 
 // CHECK-LABEL: sil hidden @twoLocalInoutsDisaliased
 sil hidden @twoLocalInoutsDisaliased : $@convention(thin) (Int) -> () {
@@ -553,7 +554,7 @@
 
 sil hidden @closureThatModifiesCapture_1: $@convention(thin) (@inout_aliasable Int) -> () {
 bb0(%0 : $*Int):
-  %1 = begin_access [modify] [unknown] %0 : $*Int // expected-note {{conflicting access is here}}
+  %1 = begin_access [modify] [unknown] %0 : $*Int // expected-note 2{{conflicting access is here}}
   end_access %1 : $*Int
   %2 = tuple ()
   return %2 : $()
@@ -657,6 +658,35 @@
   return %13 : $()
 }
 
+sil [reabstraction_thunk] @thunkForCalleeGuaranteed : $@convention(c) (@inout_aliasable @block_storage @noescape @callee_guaranteed () -> ()) -> ()
+
+// CHECK-LABEL: sil hidden @inProgressConflictWithNoEscapeClosureWithBlockStorage
+sil hidden @inProgressConflictWithNoEscapeClosureWithBlockStorage : $@convention(thin) (Int) -> () {
+bb0(%0 : $Int):
+  %2 = alloc_box ${ var Int }
+  %3 = project_box %2 : ${ var Int }, 0
+  store %0 to [trivial] %3 : $*Int
+  %4 = function_ref @takesInoutAndNoEscapeBlockClosure : $@convention(thin) (@inout Int, @owned @convention(block) @noescape () -> ()) -> ()
+  %5 = function_ref @closureThatModifiesCapture_1 : $@convention(thin) (@inout_aliasable Int) -> ()
+  %6 = partial_apply [callee_guaranteed] %5(%3) : $@convention(thin) (@inout_aliasable Int) -> ()
+  %conv = convert_function %6 : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
+  %7 = alloc_stack $@block_storage @noescape @callee_guaranteed () -> ()
+  %8 = project_block_storage %7 : $*@block_storage @noescape @callee_guaranteed () -> ()
+  store %conv to [init] %8 : $*@noescape  @callee_guaranteed () -> ()
+  %10 = function_ref @thunkForCalleeGuaranteed : $@convention(c) (@inout_aliasable @block_storage @noescape @callee_guaranteed () -> ()) -> ()
+  %11 = init_block_storage_header %7 : $*@block_storage @noescape @callee_guaranteed () -> (), invoke %10 : $@convention(c) (@inout_aliasable @block_storage @noescape @callee_guaranteed () -> ()) -> (), type $@convention(block) @noescape () -> ()
+  %12 = copy_block %11 : $@convention(block) @noescape () -> ()
+  %13 = begin_access [modify] [unknown] %3 : $*Int // expected-warning {{overlapping accesses, but modification requires exclusive access; consider copying to a local variable}}
+  %14 = apply %4(%13, %12) : $@convention(thin) (@inout Int, @owned @convention(block) @noescape () -> ()) -> ()
+  end_access %13 : $*Int
+  destroy_addr %8 : $*@callee_guaranteed @noescape () -> ()
+  dealloc_stack %7 : $*@block_storage @callee_guaranteed @noescape () -> ()
+  destroy_value %2 : ${ var Int }
+  %ret = tuple ()
+  return %ret : $()
+}
+
+
 // Stored property relaxation.
 
 struct NestedStructWithStoredProps {
diff --git a/test/SILOptimizer/exclusivity_static_diagnostics.swift b/test/SILOptimizer/exclusivity_static_diagnostics.swift
index f24d2e8..6c0a94c 100644
--- a/test/SILOptimizer/exclusivity_static_diagnostics.swift
+++ b/test/SILOptimizer/exclusivity_static_diagnostics.swift
@@ -312,6 +312,44 @@
   }
 }
 
+
+func takesNoEscapeBlockClosure
+(
+  _ p: inout Int, _ c: @convention(block) () -> ()
+) { }
+
+func takesEscapingBlockClosure
+(
+  _ p: inout Int, _ c: @escaping @convention(block) () -> ()
+) { }
+
+func testCallNoEscapeBlockClosure() {
+  var i = 7
+  takesNoEscapeBlockClosure(&i) {
+    // expected-warning@-1 {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
+    i = 7
+    // expected-note@-1 {{conflicting access is here}}
+  }
+}
+
+func testCallEscapingBlockClosure() {
+  var i = 7
+  takesEscapingBlockClosure(&i) { // no-warning
+    i = 7
+  }
+}
+
+
+
+func testCallNonEscapingWithEscapedBlock() {
+  var i = 7
+  let someBlock : @convention(block) () -> () = {
+    i = 8
+  }
+
+  takesNoEscapeBlockClosure(&i, someBlock) // no-warning
+}
+
 func takesInoutAndClosureWithGenericArg<T>(_ p: inout Int, _ c: (T) -> Int) { }
 
 func callsTakesInoutAndClosureWithGenericArg() {
diff --git a/test/SILOptimizer/exclusivity_static_diagnostics_objc.swift b/test/SILOptimizer/exclusivity_static_diagnostics_objc.swift
new file mode 100644
index 0000000..0066103
--- /dev/null
+++ b/test/SILOptimizer/exclusivity_static_diagnostics_objc.swift
@@ -0,0 +1,11 @@
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enforce-exclusivity=checked -swift-version 4 -emit-sil -primary-file %s -o /dev/null -verify
+// REQUIRES: objc_interop
+
+import Foundation
+
+class SomeClass {
+  @objc
+  func testCallNoEscapeBlockDirectly(_ c: @convention(block) () -> ()) {
+    c()
+  }
+}
diff --git a/test/SILOptimizer/generic_inline_self.swift b/test/SILOptimizer/generic_inline_self.swift
index 367e809..875d432 100644
--- a/test/SILOptimizer/generic_inline_self.swift
+++ b/test/SILOptimizer/generic_inline_self.swift
@@ -28,7 +28,7 @@
 // CHECK-LABEL: sil hidden @_T019generic_inline_self1CC18returnsNewInstanceACXDyF : $@convention(method) (@guaranteed C) -> @owned C
 // CHECK:       bb0(%0 : $C):
 // CHECK:         [[METATYPE:%.*]] = value_metatype $@thick @dynamic_self C.Type, %0 : $C
-// CHECK:         [[FN:%.*]] = function_ref @_T019generic_inline_self12makeInstancexxmAA1CCRbzlF : $@convention(thin) <τ_0_0 where τ_0_0 : C> (@thick τ_0_0.Type) -> @owned τ_0_0
+// CHECK:         [[FN:%.*]] = function_ref @_T019generic_inline_self12makeInstanceyxxmAA1CCRbzlF : $@convention(thin) <τ_0_0 where τ_0_0 : C> (@thick τ_0_0.Type) -> @owned τ_0_0
 // CHECK-NEXT:    [[RESULT:%.*]] = apply [[FN]]<@dynamic_self C>([[METATYPE]]) : $@convention(thin) <τ_0_0 where τ_0_0 : C> (@thick τ_0_0.Type) -> @owned τ_0_0
 // CHECK-NEXT:    return [[RESULT]] : $C
   func returnsNewInstance() -> Self {
diff --git a/test/SILOptimizer/generic_specialization_loops_detection_with_loops.swift b/test/SILOptimizer/generic_specialization_loops_detection_with_loops.swift
index 9f1ef80..8e29fb1 100644
--- a/test/SILOptimizer/generic_specialization_loops_detection_with_loops.swift
+++ b/test/SILOptimizer/generic_specialization_loops_detection_with_loops.swift
@@ -14,20 +14,20 @@
 // CHECK-LABEL: sil_stage canonical
 
 // Check that a specialization information for a specialized function was produced.
-// CHECK-LABEL: // Generic specialization information for function _T0044generic_specialization_loops_detection_with_C04foo4yx_q_tr0_lFSi_SdTg5
+// CHECK-LABEL: // Generic specialization information for function _T0044generic_specialization_loops_detection_with_C04foo4yyx_q_tr0_lFSi_SdTg5
 // CHECK-NEXT:  // Caller: _T0044generic_specialization_loops_detection_with_C011testFooBar4yyF
-// CHECK-NEXT:  // Parent: _T0044generic_specialization_loops_detection_with_C04foo4yx_q_tr0_lF
+// CHECK-NEXT:  // Parent: _T0044generic_specialization_loops_detection_with_C04foo4yyx_q_tr0_lF
 // CHECK-NEXT:  // Substitutions: <Int, Double>
 
 // Check that the compiler has produced a specialization information for a call-site that
 // was inlined from a specialized generic function.
-// CHECK-LABEL: // Generic specialization information for call-site _T0044generic_specialization_loops_detection_with_C04foo4yx_q_tr0_lF <Array<Int>, Array<Double>>
-// CHECK-NEXT:  // Caller: _T0044generic_specialization_loops_detection_with_C04foo4yx_q_tr0_lFSi_SdTg5
-// CHECK-NEXT:  // Parent: _T0044generic_specialization_loops_detection_with_C04bar4yx_q_tr0_lF
+// CHECK-LABEL: // Generic specialization information for call-site _T0044generic_specialization_loops_detection_with_C04foo4yyx_q_tr0_lF <Array<Int>, Array<Double>>
+// CHECK-NEXT:  // Caller: _T0044generic_specialization_loops_detection_with_C04foo4yyx_q_tr0_lFSi_SdTg5
+// CHECK-NEXT:  // Parent: _T0044generic_specialization_loops_detection_with_C04bar4yyx_q_tr0_lF
 // CHECK-NEXT:  // Substitutions: <Int, Double>
 // CHECK-NEXT:  //
 // CHECK-NEXT:  // Caller: _T0044generic_specialization_loops_detection_with_C011testFooBar4yyF
-// CHECK-NEXT:  // Parent: _T0044generic_specialization_loops_detection_with_C04foo4yx_q_tr0_lF
+// CHECK-NEXT:  // Parent: _T0044generic_specialization_loops_detection_with_C04foo4yyx_q_tr0_lF
 // CHECK-NEXT:  // Substitutions: <Int, Double>
 // CHECK-NEXT:  //
 // CHECK-NEXT: apply %{{[0-9]+}}<Array<Int>, Array<Double>>
diff --git a/test/SILOptimizer/inline_recursive.swift b/test/SILOptimizer/inline_recursive.swift
index 2f0dfd8..f2d54d9 100644
--- a/test/SILOptimizer/inline_recursive.swift
+++ b/test/SILOptimizer/inline_recursive.swift
@@ -11,7 +11,7 @@
 // CHECK: bb0:
 // CHECK: [[INTLIT:%.*]] = integer_literal $Builtin.Int32, 3
 // CHECK: [[STRUCT:%.*]] = struct $Int32 ([[INTLIT]] : $Builtin.Int32)
-// CHECK: [[REF:%.*]] = function_ref @_T016inline_recursive7recFunc33_38E63D320CFF538A1F98BBC31453B1EBLLs5Int32VAEF
+// CHECK: [[REF:%.*]] = function_ref @_T016inline_recursive7recFunc33_38E63D320CFF538A1F98BBC31453B1EBLLys5Int32VAEF
 // CHECK: [[APPLY:%.*]] = apply [[REF]]([[STRUCT]])
 // CHECK: return [[APPLY]]
 
diff --git a/test/SILOptimizer/let_properties_opts.swift b/test/SILOptimizer/let_properties_opts.swift
index 4795a24..b9ccc86 100644
--- a/test/SILOptimizer/let_properties_opts.swift
+++ b/test/SILOptimizer/let_properties_opts.swift
@@ -167,7 +167,7 @@
 // Check that Foo1.Prop1 is not constant-folded, because its value is unknown, since it is initialized differently
 // by Foo1 initializers.
 
-// CHECK-LABEL: sil [thunk] [always_inline] @_T019let_properties_opts13testClassLet1s5Int32VAA4Foo1CF : $@convention(thin) (@owned Foo1) -> Int32
+// CHECK-LABEL: sil [thunk] [always_inline] @_T019let_properties_opts13testClassLet1ys5Int32VAA4Foo1CF : $@convention(thin) (@owned Foo1) -> Int32
 // bb0
 // CHECK: ref_element_addr %{{[0-9]+}} : $Foo1, #Foo1.Prop1 
 // CHECK-NOT: ref_element_addr %{{[0-9]+}} : $Foo1, #Foo1.Prop2
@@ -180,7 +180,7 @@
 // Check that Foo1.Prop1 is not constant-folded, because its value is unknown, since it is initialized differently
 // by Foo1 initializers.
 
-// CHECK-LABEL: sil @_T019let_properties_opts13testClassLet1s5Int32VAA4Foo1CzF : $@convention(thin) (@inout Foo1) -> Int32 
+// CHECK-LABEL: sil @_T019let_properties_opts13testClassLet1ys5Int32VAA4Foo1CzF : $@convention(thin) (@inout Foo1) -> Int32
 // bb0
 // CHECK: ref_element_addr %{{[0-9]+}} : $Foo1, #Foo1.Prop1 
 // CHECK-NOT: ref_element_addr %{{[0-9]+}} : $Foo1, #Foo1.Prop2
@@ -193,7 +193,7 @@
 // Check that return expressions in all subsequent functions can be constant folded, because the values of let properties
 // are known to be constants of simple types.
 
-// CHECK: sil [thunk] [always_inline] @_T019let_properties_opts12testClassLets5Int32VAA3FooCF : $@convention(thin) (@owned Foo) -> Int32
+// CHECK: sil [thunk] [always_inline] @_T019let_properties_opts12testClassLetys5Int32VAA3FooCF : $@convention(thin) (@owned Foo) -> Int32
 // CHECK: bb0
 // CHECK-NEXT: strong_release
 // CHECK: integer_literal $Builtin.Int32, 75
@@ -203,7 +203,7 @@
   return f.Prop1 + f.Prop1 + f.Prop2 + f.Prop3
 }
 
-// CHECK-LABEL: sil @_T019let_properties_opts12testClassLets5Int32VAA3FooCzF : $@convention(thin) (@inout Foo) -> Int32
+// CHECK-LABEL: sil @_T019let_properties_opts12testClassLetys5Int32VAA3FooCzF : $@convention(thin) (@inout Foo) -> Int32
 // CHECK: bb0
 // CHECK: integer_literal $Builtin.Int32, 75
 // CHECK-NEXT: struct $Int32
@@ -212,7 +212,7 @@
   return f.Prop1 + f.Prop1 + f.Prop2 + f.Prop3
 }
 
-// CHECK-LABEL: sil [thunk] [always_inline] @_T019let_properties_opts18testClassPublicLets5Int32VAA3FooCF : $@convention(thin) (@owned Foo) -> Int32
+// CHECK-LABEL: sil [thunk] [always_inline] @_T019let_properties_opts18testClassPublicLetys5Int32VAA3FooCF : $@convention(thin) (@owned Foo) -> Int32
 // CHECK: bb0
 // CHECK-NEXT: strong_release
 // CHECK: integer_literal $Builtin.Int32, 1
@@ -222,7 +222,7 @@
   return f.Prop0
 }
 
-// CHECK-LABEL: sil @_T019let_properties_opts13testStructLets5Int32VAA3BooVF : $@convention(thin) (Boo) -> Int32
+// CHECK-LABEL: sil @_T019let_properties_opts13testStructLetys5Int32VAA3BooVF : $@convention(thin) (Boo) -> Int32
 // CHECK: bb0
 // CHECK: integer_literal $Builtin.Int32, 75
 // CHECK-NEXT: struct $Int32
@@ -231,7 +231,7 @@
   return b.Prop1 + b.Prop1 + b.Prop2 + b.Prop3
 }
 
-// CHECK-LABEL: sil @_T019let_properties_opts13testStructLets5Int32VAA3BooVzF : $@convention(thin) (@inout Boo) -> Int32
+// CHECK-LABEL: sil @_T019let_properties_opts13testStructLetys5Int32VAA3BooVzF : $@convention(thin) (@inout Boo) -> Int32
 // CHECK: bb0
 // CHECK: integer_literal $Builtin.Int32, 75
 // CHECK-NEXT: struct $Int32
@@ -240,7 +240,7 @@
   return b.Prop1 + b.Prop1 + b.Prop2 + b.Prop3
 }
 
-// CHECK-LABEL: sil @_T019let_properties_opts19testStructPublicLets5Int32VAA3BooVF : $@convention(thin) (Boo) -> Int32
+// CHECK-LABEL: sil @_T019let_properties_opts19testStructPublicLetys5Int32VAA3BooVF : $@convention(thin) (Boo) -> Int32
 // CHECK: bb0
 // CHECK: integer_literal $Builtin.Int32, 1
 // CHECK-NEXT: struct $Int32
@@ -251,7 +251,7 @@
 
 // Check that f.x is not constant folded, because the initializer of Foo2 has multiple
 // assignments to the property x with different values.
-// CHECK-LABEL: sil [thunk] [always_inline] @_T019let_properties_opts13testClassLet2s5Int32VAA4Foo2CF : $@convention(thin) (@owned Foo2) -> Int32
+// CHECK-LABEL: sil [thunk] [always_inline] @_T019let_properties_opts13testClassLet2ys5Int32VAA4Foo2CF : $@convention(thin) (@owned Foo2) -> Int32
 // bb0
 // CHECK: ref_element_addr %{{[0-9]+}} : $Foo2, #Foo2.x
 // CHECK-NOT: ref_element_addr %{{[0-9]+}} : $Foo2, #Foo2.x
@@ -262,7 +262,7 @@
 }
 
 // Check that the sum of properties is not folded into a constant.
-// CHECK-WMO-LABEL: sil hidden [noinline] @_T019let_properties_opts27testStructWithMultipleInitss5Int32VAA4Boo3V_AFtF : $@convention(thin) (Boo3, Boo3) -> Int32
+// CHECK-WMO-LABEL: sil hidden [noinline] @_T019let_properties_opts27testStructWithMultipleInitsys5Int32VAA4Boo3V_AFtF : $@convention(thin) (Boo3, Boo3) -> Int32
 // CHECK-WMO: bb0
 // No constant folding should have been performed.
 // CHECK-WMO-NOT: integer_literal $Builtin.Int32, 92
@@ -297,11 +297,11 @@
 // different module.
 // Their values are not known and cannot be propagated.
 
-// CHECK-LABEL: sil @_T019let_properties_opts31testStructPropertyAccessibilitys5Int32VAA0E27WithOnlyPublicLetPropertiesVF 
+// CHECK-LABEL: sil @_T019let_properties_opts31testStructPropertyAccessibilityys5Int32VAA0E27WithOnlyPublicLetPropertiesVF
 // CHECK: struct_extract %0 : $StructWithOnlyPublicLetProperties, #StructWithOnlyPublicLetProperties.Prop0
 // CHECK: return
 
-// CHECK-WMO-LABEL: sil @_T019let_properties_opts31testStructPropertyAccessibilitys5Int32VAA0E27WithOnlyPublicLetPropertiesVF
+// CHECK-WMO-LABEL: sil @_T019let_properties_opts31testStructPropertyAccessibilityys5Int32VAA0E27WithOnlyPublicLetPropertiesVF
 // CHECK-WMO: struct_extract %0 : $StructWithOnlyPublicLetProperties, #StructWithOnlyPublicLetProperties.Prop0
 // CHECK-WMO: return
 public func testStructPropertyAccessibility(_ b: StructWithOnlyPublicLetProperties) -> Int32 {
@@ -312,12 +312,12 @@
 // Their values are not known and cannot be propagated,
 // unless it is a WMO compilation.
 
-// CHECK-LABEL: sil @_T019let_properties_opts31testStructPropertyAccessibilitys5Int32VAA0E34WithPublicAndInternalLetPropertiesVF
+// CHECK-LABEL: sil @_T019let_properties_opts31testStructPropertyAccessibilityys5Int32VAA0E34WithPublicAndInternalLetPropertiesVF
 // CHECK: struct_extract %0 : $StructWithPublicAndInternalLetProperties, #StructWithPublicAndInternalLetProperties.Prop0
 // CHECK-NOT: integer_literal $Builtin.Int32, 21
 // CHECK: return
 
-// CHECK-WMO-LABEL: sil @_T019let_properties_opts31testStructPropertyAccessibilitys5Int32VAA0E34WithPublicAndInternalLetPropertiesVF
+// CHECK-WMO-LABEL: sil @_T019let_properties_opts31testStructPropertyAccessibilityys5Int32VAA0E34WithPublicAndInternalLetPropertiesVF
 // CHECK-WMO: integer_literal $Builtin.Int32, 21
 // CHECK-WMO-NEXT: struct $Int32
 // CHECK-WMO-NEXT: return
@@ -329,12 +329,12 @@
 // properties is fileprivate.
 // Therefore their values are known and can be propagated.
 
-// CHECK: sil @_T019let_properties_opts31testStructPropertyAccessibilitys5Int32VAA0e21WithPublicAndInternalK20PrivateLetPropertiesVF
+// CHECK: sil @_T019let_properties_opts31testStructPropertyAccessibilityys5Int32VAA0e21WithPublicAndInternalK20PrivateLetPropertiesVF
 // CHECK: integer_literal $Builtin.Int32, 33
 // CHECK-NEXT: struct $Int32
 // CHECK-NEXT: return
 
-// CHECK-WMO-LABEL: sil @_T019let_properties_opts31testStructPropertyAccessibilitys5Int32VAA0e21WithPublicAndInternalK20PrivateLetPropertiesVF
+// CHECK-WMO-LABEL: sil @_T019let_properties_opts31testStructPropertyAccessibilityys5Int32VAA0e21WithPublicAndInternalK20PrivateLetPropertiesVF
 // CHECK-WMO: integer_literal $Builtin.Int32, 33
 // CHECK-WMO-NEXT: struct $Int32
 // CHECK-WMO-NEXT: return
diff --git a/test/SILOptimizer/linker.swift b/test/SILOptimizer/linker.swift
index 8a17b90..a4d6905 100644
--- a/test/SILOptimizer/linker.swift
+++ b/test/SILOptimizer/linker.swift
@@ -15,7 +15,7 @@
 
 // CHECK: sil @_T0s1AVABycfC
 
-// CHECK: sil [noinline] @_T0s12doSomething3yxlF
+// CHECK: sil [noinline] @_T0s12doSomething3yyxlF
 // CHECK-NOT: return
 
 callDoSomething3()
diff --git a/test/SILOptimizer/mandatory_inlining.swift b/test/SILOptimizer/mandatory_inlining.swift
index e1839bf..c1e3e96 100644
--- a/test/SILOptimizer/mandatory_inlining.swift
+++ b/test/SILOptimizer/mandatory_inlining.swift
@@ -152,7 +152,7 @@
   return T.self
 }
 
-// CHECK-LABEL: sil hidden @_T018mandatory_inlining6invokeyAA1CCF : $@convention(thin) (@owned C) -> () {
+// CHECK-LABEL: sil hidden @_T018mandatory_inlining6invokeyyAA1CCF : $@convention(thin) (@owned C) -> () {
 func invoke(_ c: C) {
   // CHECK-NOT: function_ref @_T018mandatory_inlining25class_constrained_generic{{[_0-9a-zA-Z]*}}F
   // CHECK-NOT: apply
diff --git a/test/SILOptimizer/mandatory_inlining_devirt.swift b/test/SILOptimizer/mandatory_inlining_devirt.swift
index f4f2af6..1bd787f 100644
--- a/test/SILOptimizer/mandatory_inlining_devirt.swift
+++ b/test/SILOptimizer/mandatory_inlining_devirt.swift
@@ -5,7 +5,7 @@
 // the constructor itself is not "open".
 
 open class OpenClass {
-  // CHECK-LABEL: sil @_T04test9OpenClassCACSi1x_tcfc : $@convention(method) (Int, @owned OpenClass) -> @owned OpenClass
+  // CHECK-LABEL: sil @_T04test9OpenClassC1xACSi_tcfc : $@convention(method) (Int, @owned OpenClass) -> @owned OpenClass
   // CHECK: [[M:%[0-9]+]] = class_method %1 : $OpenClass, #OpenClass.init!initializer.1 : (OpenClass.Type) -> (Int, Int) -> OpenClass
   // CHECK: apply [[M]]
   // CHECK: return
@@ -19,8 +19,8 @@
 // Static dispatch for not-open class (we are compiling with -wmo).
 
 public class PublicClass {
-  // CHECK-LABEL: sil @_T04test11PublicClassCACSi1x_tcfc : $@convention(method) (Int, @owned PublicClass) -> @owned PublicClass
-  // CHECK: [[M:%[0-9]+]] = function_ref @_T04test11PublicClassCACSi1x_Si1ytcfc : $@convention(method) (Int, Int, @owned PublicClass) -> @owned PublicClass
+  // CHECK-LABEL: sil @_T04test11PublicClassC1xACSi_tcfc : $@convention(method) (Int, @owned PublicClass) -> @owned PublicClass
+  // CHECK: [[M:%[0-9]+]] = function_ref @_T04test11PublicClassC1x1yACSi_Sitcfc : $@convention(method) (Int, Int, @owned PublicClass) -> @owned PublicClass
   // CHECK: apply [[M]]
   // CHECK: return
   public convenience init(x: Int) {
diff --git a/test/SILOptimizer/optimize_never.sil b/test/SILOptimizer/optimize_never.sil
index 7144327..cb6a38a 100644
--- a/test/SILOptimizer/optimize_never.sil
+++ b/test/SILOptimizer/optimize_never.sil
@@ -90,7 +90,7 @@
 }
 
 
-sil [transparent] [serialized] @_T0s5Int32VABBi2048_22_builtinIntegerLiteral_tcfC : $@convention(thin) (Builtin.Int2048, @thin Int32.Type) -> Int32
+sil [transparent] [serialized] @_T0s5Int32V22_builtinIntegerLiteralABBi2048__tcfC : $@convention(thin) (Builtin.Int2048, @thin Int32.Type) -> Int32
 
 
 sil @_T014optimize_never1CCfD : $@convention(method) (@owned C) -> () {
@@ -160,7 +160,7 @@
 }
 
 
-sil @_T014optimize_never10transform1s5Int32VxlF : $@convention(thin) <T> (@in T) -> Int32 {
+sil @_T014optimize_never10transform1ys5Int32VxlF : $@convention(thin) <T> (@in T) -> Int32 {
 bb0(%0 : $*T):
   %2 = integer_literal $Builtin.Int32, 2
   %3 = struct $Int32 (%2 : $Builtin.Int32)
@@ -171,17 +171,17 @@
 
 
 // Check that both calls are not inlined or devirtualized.
-// CHECK-LABEL: sil [Onone] @_T014optimize_never4foo1s5Int32Vx_AA1CCtlF
+// CHECK-LABEL: sil [Onone] @_T014optimize_never4foo1ys5Int32Vx_AA1CCtlF
 // CHECK-NOT: checked_cast_br
-// CHECK: function_ref @_T014optimize_never10transform1s5Int32VxlF
+// CHECK: function_ref @_T014optimize_never10transform1ys5Int32VxlF
 // CHECK: apply
 // CHECK-NOT: checked_cast_br
 // CHECK: class_method {{%.*}} : $C, #C.foo!1 : (C) -> () -> Int32, $@convention(method) (@guaranteed C) -> Int32
 // CHECK: apply
 // CHECK: return
-sil [Onone] @_T014optimize_never4foo1s5Int32Vx_AA1CCtlF : $@convention(thin) <T> (@in T, @owned C) -> Int32 {
+sil [Onone] @_T014optimize_never4foo1ys5Int32Vx_AA1CCtlF : $@convention(thin) <T> (@in T, @owned C) -> Int32 {
 bb0(%0 : $*T, %1 : $C):
-  %4 = function_ref @_T014optimize_never10transform1s5Int32VxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Int32
+  %4 = function_ref @_T014optimize_never10transform1ys5Int32VxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Int32
   %5 = alloc_stack $T
   copy_addr %0 to [initialization] %5 : $*T
   %7 = apply %4<T>(%5) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Int32
@@ -202,18 +202,18 @@
 }
 
 
-sil [transparent] [serialized] @_T0s1pois5Int32VAC_ACtFZ : $@convention(thin) (Int32, Int32) -> Int32
+sil [transparent] [serialized] @_T0s1poiys5Int32VAC_ACtFZ : $@convention(thin) (Int32, Int32) -> Int32
 
 
-// CHECK-LABEL: sil @_T014optimize_never4boo1s5Int32VAA1CCF
+// CHECK-LABEL: sil @_T014optimize_never4boo1ys5Int32VAA1CCF
 // CHECK-NOT: return
 // This call should not be inlined, because the callee is annotated with @_optimize(none)
-// CHECK: function_ref @_T014optimize_never4foo1s5Int32Vx_AA1CCtlF
+// CHECK: function_ref @_T014optimize_never4foo1ys5Int32Vx_AA1CCtlF
 // CHECK: apply
 // CHECK: return
-sil @_T014optimize_never4boo1s5Int32VAA1CCF : $@convention(thin) (@owned C) -> Int32 {
+sil @_T014optimize_never4boo1ys5Int32VAA1CCF : $@convention(thin) (@owned C) -> Int32 {
 bb0(%0 : $C):
-  %2 = function_ref @_T014optimize_never4foo1s5Int32Vx_AA1CCtlF : $@convention(thin) <τ_0_0> (@in τ_0_0, @owned C) -> Int32
+  %2 = function_ref @_T014optimize_never4foo1ys5Int32Vx_AA1CCtlF : $@convention(thin) <τ_0_0> (@in τ_0_0, @owned C) -> Int32
   %3 = integer_literal $Builtin.Int32, 1
   %4 = struct $Int32 (%3 : $Builtin.Int32)
   %5 = alloc_stack $Int32
@@ -226,27 +226,27 @@
 }
 
 
-sil [transparent] [serialized] @_T0S2iBi2048_22_builtinIntegerLiteral_tcfC : $@convention(thin) (Builtin.Int2048, @thin Int.Type) -> Int
+sil [transparent] [serialized] @_T0Si22_builtinIntegerLiteralSiBi2048__tcfC : $@convention(thin) (Builtin.Int2048, @thin Int.Type) -> Int
 
 
-sil @_T014optimize_never10transform2s5Int32VADF : $@convention(thin) (Int32) -> Int32 {
+sil @_T014optimize_never10transform2ys5Int32VADF : $@convention(thin) (Int32) -> Int32 {
 bb0(%0 : $Int32):
   return %0 : $Int32
 }
 
 
 // Check that both calls are not inlined or devirtualized.
-// CHECK-LABEL: sil [Onone] @_T014optimize_never4foo2s5Int32VAD_AA1CCtF
+// CHECK-LABEL: sil [Onone] @_T014optimize_never4foo2ys5Int32VAD_AA1CCtF
 // CHECK-NOT: checked_cast_br
-// CHECK: function_ref @_T014optimize_never10transform2s5Int32VADF
+// CHECK: function_ref @_T014optimize_never10transform2ys5Int32VADF
 // CHECK: apply
 // CHECK-NOT: checked_cast_br
 // CHECK: class_method {{%.*}} : $C, #C.foo!1 : (C) -> () -> Int32, $@convention(method) (@guaranteed C) -> Int32
 // CHECK: apply
 // CHECK: return
-sil [Onone] @_T014optimize_never4foo2s5Int32VAD_AA1CCtF : $@convention(thin) (Int32, @owned C) -> Int32 {
+sil [Onone] @_T014optimize_never4foo2ys5Int32VAD_AA1CCtF : $@convention(thin) (Int32, @owned C) -> Int32 {
 bb0(%0 : $Int32, %1 : $C):
-  %4 = function_ref @_T014optimize_never10transform2s5Int32VADF : $@convention(thin) (Int32) -> Int32
+  %4 = function_ref @_T014optimize_never10transform2ys5Int32VADF : $@convention(thin) (Int32) -> Int32
   %5 = apply %4(%0) : $@convention(thin) (Int32) -> Int32
   %6 = class_method %1 : $C, #C.foo!1 : (C) -> () -> Int32, $@convention(method) (@guaranteed C) -> Int32
   %7 = apply %6(%1) : $@convention(method) (@guaranteed C) -> Int32
@@ -263,15 +263,15 @@
 }
 
 
-// CHECK-LABEL: sil @_T014optimize_never4boo2s5Int32VAA1CCF
+// CHECK-LABEL: sil @_T014optimize_never4boo2ys5Int32VAA1CCF
 // CHECK-NOT: return
 // This call should not be inlined, because the callee is annotated with @_optimize(none)
-// CHECK: function_ref @_T014optimize_never4foo2s5Int32VAD_AA1CCtF
+// CHECK: function_ref @_T014optimize_never4foo2ys5Int32VAD_AA1CCtF
 // CHECK: apply
 // CHECK: return
-sil @_T014optimize_never4boo2s5Int32VAA1CCF : $@convention(thin) (@owned C) -> Int32 {
+sil @_T014optimize_never4boo2ys5Int32VAA1CCF : $@convention(thin) (@owned C) -> Int32 {
 bb0(%0 : $C):
-  %2 = function_ref @_T014optimize_never4foo2s5Int32VAD_AA1CCtF : $@convention(thin) (Int32, @owned C) -> Int32
+  %2 = function_ref @_T014optimize_never4foo2ys5Int32VAD_AA1CCtF : $@convention(thin) (Int32, @owned C) -> Int32
   %3 = integer_literal $Builtin.Int32, 1
   %4 = struct $Int32 (%3 : $Builtin.Int32)
   strong_retain %0 : $C
@@ -286,7 +286,7 @@
 // CHECK: generic specialization <Swift.Int32> of {{.*}}.foo3
 
 
-sil @_T014optimize_never10transform3s5Int32VxlF : $@convention(thin) <T> (@in T) -> Int32 {
+sil @_T014optimize_never10transform3ys5Int32VxlF : $@convention(thin) <T> (@in T) -> Int32 {
 bb0(%0 : $*T):
   %2 = integer_literal $Builtin.Int32, 2
   %3 = struct $Int32 (%2 : $Builtin.Int32)
@@ -295,9 +295,9 @@
 }
 
 
-sil @_T014optimize_never4foo3s5Int32Vx_AA1CCtlF : $@convention(thin) <T> (@in T, @owned C) -> Int32 {
+sil @_T014optimize_never4foo3ys5Int32Vx_AA1CCtlF : $@convention(thin) <T> (@in T, @owned C) -> Int32 {
 bb0(%0 : $*T, %1 : $C):
-  %4 = function_ref @_T014optimize_never10transform3s5Int32VxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Int32
+  %4 = function_ref @_T014optimize_never10transform3ys5Int32VxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Int32
   %5 = alloc_stack $T
   copy_addr %0 to [initialization] %5 : $*T
   %7 = apply %4<T>(%5) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> Int32
@@ -321,16 +321,16 @@
 // Everything in this function should get devirtualized, inlined and folded together,
 // because neither this function nor any of its callees are annotated to be
 // excluded from the optimization.
-// CHECK-LABEL: sil @_T014optimize_never4boo3s5Int32VAA1CCF
+// CHECK-LABEL: sil @_T014optimize_never4boo3ys5Int32VAA1CCF
 // CHECK: bb0
-// CHECK-NOT: function_ref @_T014optimize_never4foo3s5Int32Vx_AA1CCtlF
+// CHECK-NOT: function_ref @_T014optimize_never4foo3ys5Int32Vx_AA1CCtlF
 // Presence of checked_cast_br indicates that the speculative devirtualization
 // was performed. And this is only possible, if the original call is inlined.
 // CHECK: checked_cast_br [exact] {{%.*}} : $C to $C, bb2, bb3
 // CHECK: return
-sil @_T014optimize_never4boo3s5Int32VAA1CCF : $@convention(thin) (@owned C) -> Int32 {
+sil @_T014optimize_never4boo3ys5Int32VAA1CCF : $@convention(thin) (@owned C) -> Int32 {
 bb0(%0 : $C):
-  %2 = function_ref @_T014optimize_never4foo3s5Int32Vx_AA1CCtlF : $@convention(thin) <τ_0_0> (@in τ_0_0, @owned C) -> Int32
+  %2 = function_ref @_T014optimize_never4foo3ys5Int32Vx_AA1CCtlF : $@convention(thin) <τ_0_0> (@in τ_0_0, @owned C) -> Int32
   %3 = integer_literal $Builtin.Int32, 1
   %4 = struct $Int32 (%3 : $Builtin.Int32)
   %5 = alloc_stack $Int32
@@ -343,15 +343,15 @@
 }
 
 
-sil @_T014optimize_never10transform4s5Int32VADF : $@convention(thin) (Int32) -> Int32 {
+sil @_T014optimize_never10transform4ys5Int32VADF : $@convention(thin) (Int32) -> Int32 {
 bb0(%0 : $Int32):
   return %0 : $Int32
 }
 
 
-sil @_T014optimize_never4foo4s5Int32VAD_AA1CCtF : $@convention(thin) (Int32, @owned C) -> Int32 {
+sil @_T014optimize_never4foo4ys5Int32VAD_AA1CCtF : $@convention(thin) (Int32, @owned C) -> Int32 {
 bb0(%0 : $Int32, %1 : $C):
-  %4 = function_ref @_T014optimize_never10transform4s5Int32VADF : $@convention(thin) (Int32) -> Int32
+  %4 = function_ref @_T014optimize_never10transform4ys5Int32VADF : $@convention(thin) (Int32) -> Int32
   %5 = apply %4(%0) : $@convention(thin) (Int32) -> Int32
   %6 = class_method %1 : $C, #C.foo!1 : (C) -> () -> Int32, $@convention(method) (@guaranteed C) -> Int32
   %7 = apply %6(%1) : $@convention(method) (@guaranteed C) -> Int32
@@ -371,16 +371,16 @@
 // Everything in this function should get devirtualized and inlined,
 // because neither this function nor any of its callees are annotated to be
 // excluded from the optimization.
-// CHECK-LABEL: sil @_T014optimize_never4boo4s5Int32VAA1CCF
+// CHECK-LABEL: sil @_T014optimize_never4boo4ys5Int32VAA1CCF
 // CHECK: bb0
-// CHECK-NOT: function_ref @_T014optimize_never4foo4s5Int32VAD_AA1CCtF
+// CHECK-NOT: function_ref @_T014optimize_never4foo4ys5Int32VAD_AA1CCtF
 // Presence of checked_cast_br indicates that the speculative devirtualization
 // was performed. And this is only possible, if the original call is inlined.
 // CHECK: checked_cast_br [exact] {{%.*}} : $C to $C, bb2, bb3
 // CHECK: return
-sil @_T014optimize_never4boo4s5Int32VAA1CCF : $@convention(thin) (@owned C) -> Int32 {
+sil @_T014optimize_never4boo4ys5Int32VAA1CCF : $@convention(thin) (@owned C) -> Int32 {
 bb0(%0 : $C):
-  %2 = function_ref @_T014optimize_never4foo4s5Int32VAD_AA1CCtF : $@convention(thin) (Int32, @owned C) -> Int32
+  %2 = function_ref @_T014optimize_never4foo4ys5Int32VAD_AA1CCtF : $@convention(thin) (Int32, @owned C) -> Int32
   %3 = integer_literal $Builtin.Int32, 1
   %4 = struct $Int32 (%3 : $Builtin.Int32)
   strong_retain %0 : $C
@@ -434,13 +434,13 @@
 // method foo in the class Base, which mentioned in the class_method
 // instruction is marked with @_optimize(none).
 //
-// CHECK-LABEL: sil @_T014optimize_never19testDoNotDevirtBases5Int32VAA0G0C1o_tF
+// CHECK-LABEL: sil @_T014optimize_never19testDoNotDevirtBase1os5Int32VAA0G0C_tF
 // CHECK: bb0
 // CHECK-NOT: checked_cast_br
 // CHECK: class_method {{%[0-9]+}} : $Base, #Base.foo!1 : (Base) -> () -> Int32
 // CHECK-NOT: checked_cast_br
 // CHECK: return
-sil @_T014optimize_never19testDoNotDevirtBases5Int32VAA0G0C1o_tF : $@convention(thin) (@owned Base) -> Int32 {
+sil @_T014optimize_never19testDoNotDevirtBase1os5Int32VAA0G0C_tF : $@convention(thin) (@owned Base) -> Int32 {
 bb0(%0 : $Base):
   %2 = class_method %0 : $Base, #Base.foo!1 : (Base) -> () -> Int32, $@convention(method) (@guaranteed Base) -> Int32
   %3 = apply %2(%0) : $@convention(method) (@guaranteed Base) -> Int32
@@ -452,14 +452,14 @@
 // is marked with @_optimize(none) and thus should not
 // participate in speculative devirtualization.
 //
-// CHECK-LABEL: sil @_T014optimize_never23testDoNotDevirtDerived1s5Int32VAA4BaseC1o_tF
+// CHECK-LABEL: sil @_T014optimize_never23testDoNotDevirtDerived11os5Int32VAA4BaseC_tF
 // CHECK: bb0
 // CHECK: class_method {{%[0-9]+}} : $Base, #Base.boo!1 : (Base) -> () -> Int32
 // CHECK: checked_cast_br [exact] {{%[0-9]+}} : $Base to $Base
 // CHECK: checked_cast_br [exact] {{%[0-9]+}} : $Base to $Derived2
 // CHECK-NOT: class_method
 // CHECK: }
-sil @_T014optimize_never23testDoNotDevirtDerived1s5Int32VAA4BaseC1o_tF : $@convention(thin) (@owned Base) -> Int32 {
+sil @_T014optimize_never23testDoNotDevirtDerived11os5Int32VAA4BaseC_tF : $@convention(thin) (@owned Base) -> Int32 {
 bb0(%0 : $Base):
   %2 = class_method %0 : $Base, #Base.boo!1 : (Base) -> () -> Int32, $@convention(method) (@guaranteed Base) -> Int32
   %3 = apply %2(%0) : $@convention(method) (@guaranteed Base) -> Int32
diff --git a/test/SILOptimizer/outliner.swift b/test/SILOptimizer/outliner.swift
index cabc9e5..f7641af 100644
--- a/test/SILOptimizer/outliner.swift
+++ b/test/SILOptimizer/outliner.swift
@@ -31,10 +31,10 @@
 // CHECK:  [[FUN:%.*]] = function_ref @_T0So5GizmoC14stringPropertySQySSGvsToTembnn_
 // CHECK:  apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Gizmo) -> ()
 // CHECK:  apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Gizmo) -> ()
-// CHECK:  [[FUN:%.*]] = function_ref @_T0So5GizmoC12modifyStringSQySSGAD_Si10withNumberSQyypG0D6FoobartFToTembnnnb_
+// CHECK:  [[FUN:%.*]] = function_ref @_T0So5GizmoC12modifyString_10withNumber0D6FoobarSQySSGAF_SiSQyypGtFToTembnnnb_
 // CHECK:  apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String>
 // CHECK:  apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String>
-// CHECK:  [[FUN:%.*]] = function_ref @_T0So5GizmoC11doSomethingSQyypGSQySaySSGGFToTembnn_
+// CHECK:  [[FUN:%.*]] = function_ref @_T0So5GizmoC11doSomethingySQyypGSQySaySSGGFToTembnn_
 // CHECK:  apply [[FUN]]({{.*}}) : $@convention(thin) (@owned Array<String>, Gizmo) -> @owned Optional<AnyObject>
 // CHECK:  apply [[FUN]]({{.*}}) : $@convention(thin) (@owned Array<String>, Gizmo) -> @owned Optional<AnyObject>
 // CHECK: return
@@ -60,7 +60,7 @@
 // CHECK:   %3 = apply %2(%1) : $@convention(objc_method) (Gizmo) -> @autoreleased Optional<NSString>
 // CHECK:   switch_enum %3 : $Optional<NSString>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: bb2
 // CHECK: bb1(%5 : $NSString):
-// CHECK:   %6 = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
+// CHECK:   %6 = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
 // CHECK:   %7 = metatype $@thin String.Type
 // CHECK:   %8 = apply %6(%3, %7) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
 // CHECK:   %9 = enum $Optional<String>, #Optional.some!enumelt.1, %8 : $String
@@ -77,7 +77,7 @@
 // CHECK:  %2 = apply %1(%0) : $@convention(objc_method) (Gizmo) -> @autoreleased Optional<NSString>
 // CHECK:  switch_enum %2 : $Optional<NSString>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: bb2
 // CHECK:bb1(%4 : $NSString):
-// CHECK:  %5 = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
+// CHECK:  %5 = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
 // CHECK:  %6 = metatype $@thin String.Type
 // CHECK:  %7 = apply %5(%2, %6) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
 // CHECK:  %8 = enum $Optional<String>, #Optional.some!enumelt.1, %7 : $String
@@ -99,7 +99,7 @@
 // CHECK:   strong_release %4 : $NSString
 // CHECK:   return %7 : $()
 
-// CHECK-LABEL: sil shared [noinline] @_T0So5GizmoC12modifyStringSQySSGAD_Si10withNumberSQyypG0D6FoobartFToTembnnnb_ : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String> {
+// CHECK-LABEL: sil shared [noinline] @_T0So5GizmoC12modifyString_10withNumber0D6FoobarSQySSGAF_SiSQyypGtFToTembnnnb_ : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String> {
 // CHECK: bb0(%0 : $String, %1 : $Int, %2 : $Optional<AnyObject>, %3 : $Gizmo):
 // CHECK:   %4 = objc_method %3 : $Gizmo, #Gizmo.modifyString!1.foreign : (Gizmo) -> (String!, Int, Any!) -> String!
 // CHECK:   %5 = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : $@convention(method) (@guaranteed String) -> @owned NSString
@@ -115,7 +115,7 @@
 // CHECK:   br bb3(%12 : $Optional<String>)
 //
 // CHECK: bb2(%14 : $NSString):
-// CHECK:   %15 = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
+// CHECK:   %15 = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
 // CHECK:   %16 = metatype $@thin String.Type
 // CHECK:   %17 = apply %15(%9, %16) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
 // CHECK:   %18 = enum $Optional<String>, #Optional.some!enumelt.1, %17 : $String
@@ -124,7 +124,7 @@
 // CHECK: bb3(%20 : $Optional<String>):
 // CHECK:   return %20 : $Optional<String>
 
-// CHECK-LABEL: sil shared [noinline] @_T0So5GizmoC11doSomethingSQyypGSQySaySSGGFToTembnn_ : $@convention(thin) (@owned Array<String>, Gizmo) -> @owned Optional<AnyObject> {
+// CHECK-LABEL: sil shared [noinline] @_T0So5GizmoC11doSomethingySQyypGSQySaySSGGFToTembnn_ : $@convention(thin) (@owned Array<String>, Gizmo) -> @owned Optional<AnyObject> {
 // CHECK: bb0(%0 : $Array<String>, %1 : $Gizmo):
 // CHECK:   %2 = objc_method %1 : $Gizmo, #Gizmo.doSomething!1.foreign : (Gizmo) -> ([String]!) -> Any!
 // CHECK:   %3 = function_ref @_T0Sa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF : $@convention(method) <{{.*}}> (@guaranteed Array<{{.*}}>) -> @owned NSArray
diff --git a/test/SILOptimizer/partial_specialization.sil b/test/SILOptimizer/partial_specialization.sil
index 9fd0aa9..854f460 100644
--- a/test/SILOptimizer/partial_specialization.sil
+++ b/test/SILOptimizer/partial_specialization.sil
@@ -29,7 +29,7 @@
 sil @use : $@convention(thin) <τ_0_0> (@in τ_0_0) -> ()
 
 // S.init(_:)
-sil [noinline] @_T022partial_specialization1SVACyxGxcfC : $@convention(method) <T> (@in T, @thin S<T>.Type) -> S<T>
+sil [noinline] @_T022partial_specialization1SVyACyxGxcfC : $@convention(method) <T> (@in T, @thin S<T>.Type) -> S<T>
 
 // simple_generic_callee<A, B>(_:_:)
 sil [noinline] @simple_generic_callee : $@convention(thin) <U, V> (@in U, @in V) -> () {
@@ -77,7 +77,7 @@
   // function_ref simple_generic_callee<A, B>(_:_:)
   %2 = function_ref @simple_generic_callee : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0, @in τ_0_1) -> ()
   // function_ref S.init(_:)
-  %3 = function_ref @_T022partial_specialization1SVACyxGxcfC : $@convention(method) <τ_0_0> (@in τ_0_0, @thin S<τ_0_0>.Type) -> S<τ_0_0>
+  %3 = function_ref @_T022partial_specialization1SVyACyxGxcfC : $@convention(method) <τ_0_0> (@in τ_0_0, @thin S<τ_0_0>.Type) -> S<τ_0_0>
   %4 = metatype $@thin S<U>.Type
   %5 = alloc_stack $U
   copy_addr %0 to [initialization] %5 : $*U
diff --git a/test/SILOptimizer/performance_inliner.sil b/test/SILOptimizer/performance_inliner.sil
index 2daa26c..dde27c5 100644
--- a/test/SILOptimizer/performance_inliner.sil
+++ b/test/SILOptimizer/performance_inliner.sil
@@ -301,7 +301,7 @@
 sil @trivial_witness_method_caller : $@convention(thin) () -> () {
   %0 = alloc_box ${ var Int64 }, var, name "x"
   %1 = project_box %0 : ${ var Int64 }, 0
-  %2 = function_ref @_T0s5Int64VABBi2048_22_builtinIntegerLiteral_tcfC : $@convention(method) (Builtin.Int2048, @thin Int64.Type) -> Int64 // user: %5
+  %2 = function_ref @_T0s5Int64V22_builtinIntegerLiteralABBi2048__tcfC : $@convention(method) (Builtin.Int2048, @thin Int64.Type) -> Int64 // user: %5
   %3 = metatype $@thin Int64.Type
   %4 = integer_literal $Builtin.Int2048, 0
   %5 = apply %2(%4, %3) : $@convention(method) (Builtin.Int2048, @thin Int64.Type) -> Int64
@@ -313,7 +313,7 @@
 }
 
 // Int64.init(_builtinIntegerLiteral:)
-sil [transparent] [serialized] @_T0s5Int64VABBi2048_22_builtinIntegerLiteral_tcfC : $@convention(method) (Builtin.Int2048, @thin Int64.Type) -> Int64
+sil [transparent] [serialized] @_T0s5Int64V22_builtinIntegerLiteralABBi2048__tcfC : $@convention(method) (Builtin.Int2048, @thin Int64.Type) -> Int64
 
 
 // We can inline function_refs with c calling convention.
diff --git a/test/SILOptimizer/pgo_si_inlinelarge.swift b/test/SILOptimizer/pgo_si_inlinelarge.swift
index 1efb9cd..0236886 100644
--- a/test/SILOptimizer/pgo_si_inlinelarge.swift
+++ b/test/SILOptimizer/pgo_si_inlinelarge.swift
@@ -102,15 +102,15 @@
   return ret
 }
 
-// SIL-LABEL: sil @_T018pgo_si_inlinelarge3fooys5Int64VF : $@convention(thin) (Int64) -> () !function_entry_count(1) {
-// SIL-OPT-LABEL: sil @_T018pgo_si_inlinelarge3fooys5Int64VF : $@convention(thin) (Int64) -> () !function_entry_count(1) {
+// SIL-LABEL: sil @_T018pgo_si_inlinelarge3fooyys5Int64VF : $@convention(thin) (Int64) -> () !function_entry_count(1) {
+// SIL-OPT-LABEL: sil @_T018pgo_si_inlinelarge3fooyys5Int64VF : $@convention(thin) (Int64) -> () !function_entry_count(1) {
 public func foo(_ x: Int64) {
   // SIL: switch_enum {{.*}} : $Optional<Int64>, case #Optional.some!enumelt.1: {{.*}} !case_count(100), case #Optional.none!enumelt: {{.*}} !case_count(1)
   // SIL: cond_br {{.*}}, {{.*}}, {{.*}} !true_count(50)
   // SIL: cond_br {{.*}}, {{.*}}, {{.*}} !true_count(1)
   // SIL-OPT: integer_literal $Builtin.Int64, 93
   // SIL-OPT: integer_literal $Builtin.Int64, 42
-  // SIL-OPT: function_ref @_T018pgo_si_inlinelarge3bars5Int64VADF : $@convention(thin) (Int64) -> Int64
+  // SIL-OPT: function_ref @_T018pgo_si_inlinelarge3barys5Int64VADF : $@convention(thin) (Int64) -> Int64
 
   var sum : Int64 = 0
   for index in 1...x {
@@ -124,7 +124,7 @@
   }
   print(sum)
 }
-// SIL-LABEL: } // end sil function '_T018pgo_si_inlinelarge3fooys5Int64VF'
-// SIL-OPT-LABEL: } // end sil function '_T018pgo_si_inlinelarge3fooys5Int64VF'
+// SIL-LABEL: } // end sil function '_T018pgo_si_inlinelarge3fooyys5Int64VF'
+// SIL-OPT-LABEL: } // end sil function '_T018pgo_si_inlinelarge3fooyys5Int64VF'
 
 foo(100)
diff --git a/test/SILOptimizer/pgo_si_reduce.swift b/test/SILOptimizer/pgo_si_reduce.swift
index 0982ad0..2fab15d 100644
--- a/test/SILOptimizer/pgo_si_reduce.swift
+++ b/test/SILOptimizer/pgo_si_reduce.swift
@@ -28,15 +28,15 @@
   return ret
 }
 
-// SIL-LABEL: sil @_T013pgo_si_reduce3fooys5Int32VF : $@convention(thin) (Int32) -> () !function_entry_count(1) {
-// SIL-OPT-LABEL: sil @_T013pgo_si_reduce3fooys5Int32VF : $@convention(thin) (Int32) -> () !function_entry_count(1) {
+// SIL-LABEL: sil @_T013pgo_si_reduce3fooyys5Int32VF : $@convention(thin) (Int32) -> () !function_entry_count(1) {
+// SIL-OPT-LABEL: sil @_T013pgo_si_reduce3fooyys5Int32VF : $@convention(thin) (Int32) -> () !function_entry_count(1) {
 public func foo(_ x: Int32) {
   // SIL: switch_enum {{.*}} : $Optional<Int32>, case #Optional.some!enumelt.1: {{.*}} !case_count(100), case #Optional.none!enumelt: {{.*}} !case_count(1)
   // SIL: cond_br {{.*}}, {{.*}}, {{.*}} !true_count(50)
   // SIL: cond_br {{.*}}, {{.*}}, {{.*}} !true_count(1)
   // SIL-OPT: integer_literal $Builtin.Int32, 4242
   // SIL-OPT: integer_literal $Builtin.Int32, 42
-  // SIL-OPT: function_ref @_T013pgo_si_reduce3bars5Int32VADF : $@convention(thin) (Int32) -> Int32
+  // SIL-OPT: function_ref @_T013pgo_si_reduce3barys5Int32VADF : $@convention(thin) (Int32) -> Int32
   
   var sum : Int32 = 0
   for index in 1...x {
@@ -50,7 +50,7 @@
   }
   print(sum)
 }
-// SIL-LABEL: } // end sil function '_T013pgo_si_reduce3fooys5Int32VF'
-// SIL-OPT-LABEL: } // end sil function '_T013pgo_si_reduce3fooys5Int32VF'
+// SIL-LABEL: } // end sil function '_T013pgo_si_reduce3fooyys5Int32VF'
+// SIL-OPT-LABEL: } // end sil function '_T013pgo_si_reduce3fooyys5Int32VF'
 
 foo(100)
diff --git a/test/SILOptimizer/predictable_memopt_unreferenceable_storage.swift b/test/SILOptimizer/predictable_memopt_unreferenceable_storage.swift
index 0d6e20c..f939b8d 100644
--- a/test/SILOptimizer/predictable_memopt_unreferenceable_storage.swift
+++ b/test/SILOptimizer/predictable_memopt_unreferenceable_storage.swift
@@ -14,7 +14,7 @@
         self.s = s
     }
 }
-// CHECK-LABEL: sil hidden @_T042predictable_memopt_unreferenceable_storage1TVACSC19StructWithBitfieldsV1v_AA1SV1stcfC
+// CHECK-LABEL: sil hidden @_T042predictable_memopt_unreferenceable_storage1TV1v1sACSC19StructWithBitfieldsV_AA1SVtcfC
 // CHECK:       bb0(%0 : $StructWithBitfields, %1 : $S, %2 : $@thin T.Type):
 // CHECK:         [[RESULT:%.*]] = struct $T (%0 : $StructWithBitfields, %1 : $S)
 // CHECK:         return [[RESULT]]
diff --git a/test/SILOptimizer/prespecialize.swift b/test/SILOptimizer/prespecialize.swift
index bddb2b9..28d97be 100644
--- a/test/SILOptimizer/prespecialize.swift
+++ b/test/SILOptimizer/prespecialize.swift
@@ -5,7 +5,7 @@
 // Check that pre-specialization works at -Onone.
 // This test requires the standard library to be compiled with pre-specializations!
 
-// CHECK-LABEL: sil [noinline] @_T013prespecialize4testySaySiGz_Si4sizetF 
+// CHECK-LABEL: sil [noinline] @_T013prespecialize4test_4sizeySaySiGz_SitF
 //
 // function_ref specialized Collection<A where ...>.makeIterator() -> IndexingIterator<A>
 // CHECK: function_ref @_T0s10CollectionPss16IndexingIteratorVyxG0C0RtzrlE04makeC0AEyFs14CountableRangeVySiG_Tg5
@@ -14,7 +14,7 @@
 // CHECK: function_ref @_T0s16IndexingIteratorV4next7ElementQzSgyFs14CountableRangeVySiG_Tg5
 //
 // Look for generic specialization <Swift.Int> of Swift.Array.subscript.getter : (Swift.Int) -> A
-// CHECK: function_ref {{@_T0SaxSicigSi_Tg5|@_TTSg5Si___TFSaap9subscriptFSix}}
+// CHECK: function_ref @_T0s14CountableRangeV15uncheckedBoundsAByxGx5lower_x5uppert_tcfCSi_Tg5
 // CHECK: return
 @inline(never)
 public func test(_ a: inout [Int], size: Int) {
@@ -27,7 +27,7 @@
 
 // CHECK-LABEL: sil [noinline] @_T013prespecialize3runyyF
 // Look for generic specialization <Swift.Int> of Swift.Array.init (repeating : A, count : Swift.Int) -> Swift.Array<A>
-// CHECK: function_ref @_T0S2ayxGx9repeating_Si5counttcfCSi_Tg5
+// CHECK: function_ref @_T0Sa9repeating5countSayxGx_SitcfCSi_Tg5
 // CHECK: return
 @inline(never)
 public func run() {
diff --git a/test/SILOptimizer/sil_concat_string_literals.sil b/test/SILOptimizer/sil_concat_string_literals.sil
index 2bea5fd..6d2c0ef 100644
--- a/test/SILOptimizer/sil_concat_string_literals.sil
+++ b/test/SILOptimizer/sil_concat_string_literals.sil
@@ -16,9 +16,9 @@
 bb0:
   %0 = alloc_stack $String, var, name "s"              // users: %15, %16
   // function_ref static String.+ infix(String, String) -> String
-  %1 = function_ref @_T0SS1poiS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
+  %1 = function_ref @_T0SS1poiyS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
   // function_ref String.init(_builtinStringLiteral : Builtin.RawPointer, utf8CodeUnitCount : Builtin.Word, isASCII : Builtin.Int1) -> String
-  %2 = function_ref @_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
+  %2 = function_ref @_T0SS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
   %3 = metatype $@thin String.Type                // user: %7
   %4 = string_literal utf8 "1"                    // user: %7
   %5 = integer_literal $Builtin.Word, 1           // user: %7
@@ -44,16 +44,16 @@
 bb0:
   %0 = alloc_stack $String, var, name "s"              // users: %15, %16
   // function_ref static String.+ infix(String, String) -> String
-  %1 = function_ref @_T0SS1poiS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
+  %1 = function_ref @_T0SS1poiyS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
   // function_ref String.init(_builtinStringLiteral : Builtin.RawPointer, utf8CodeUnitCount : Builtin.Word, isASCII : Builtin.Int1) -> String
-  %2 = function_ref @_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
+  %2 = function_ref @_T0SS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
   %3 = metatype $@thin String.Type                // user: %7
   %4 = string_literal utf8 "1"                    // user: %7
   %5 = integer_literal $Builtin.Word, 1           // user: %7
   %6 = integer_literal $Builtin.Int1, -1          // user: %7
   %7 = apply %2(%4, %5, %6, %3) : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String // user: %14
   // function_ref String.init(_builtinUTF16StringLiteral : Builtin.RawPointer, utf16CodeUnitCount : Builtin.Word) -> String
-  %8 = function_ref @_T0S2SBp26_builtinUTF16StringLiteral_Bw18utf16CodeUnitCounttcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> @owned String
+  %8 = function_ref @_T0SS26_builtinUTF16StringLiteral18utf16CodeUnitCountSSBp_BwtcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> @owned String
   %9 = metatype $@thin String.Type                // user: %13
   %10 = string_literal utf16 "á"                // user: %13
   %11 = integer_literal $Builtin.Word, 2          // user: %13
@@ -66,15 +66,15 @@
 }
 
 // static String.+ infix(String, String) -> String
-sil [readonly] [_semantics "string.concat"] @_T0SS1poiS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
+sil [readonly] [_semantics "string.concat"] @_T0SS1poiyS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
 
 
 // String.init(_builtinStringLiteral : Builtin.RawPointer, utf8CodeUnitCount : Builtin.Word, isASCII : Builtin.Int1) -> String
-sil [serialized] [readonly] [_semantics "string.makeUTF8"] @_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
+sil [serialized] [readonly] [_semantics "string.makeUTF8"] @_T0SS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
 
 
 // String.init(_builtinUTF16StringLiteral : Builtin.RawPointer, utf16CodeUnitCount : Builtin.Word) -> String
-sil [serialized] [readonly] [_semantics "string.makeUTF16"] @_T0S2SBp26_builtinUTF16StringLiteral_Bw18utf16CodeUnitCounttcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> @owned String
+sil [serialized] [readonly] [_semantics "string.makeUTF16"] @_T0SS26_builtinUTF16StringLiteral18utf16CodeUnitCountSSBp_BwtcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> @owned String
 
 //CHECK-LABEL: sil @_TF12StringConcat51testStringConcat_UnicodeScalarLiteral_StringLiteralFT_SS : $@convention(thin) () -> @owned String
 //CHECK-NOT: string_literal utf8 "1"
@@ -85,9 +85,9 @@
 bb0:
   %0 = alloc_stack $String, var, name "s"              // users: %15, %16
   // function_ref static String.+ infix(String, String) -> String
-  %1 = function_ref @_T0SS1poiS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
+  %1 = function_ref @_T0SS1poiyS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
   // function_ref String.init(_builtinStringLiteral : Builtin.RawPointer, utf8CodeUnitCount : Builtin.Word, isASCII : Builtin.Int1) -> String
-  %2 = function_ref @_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
+  %2 = function_ref @_T0SS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
   %3 = metatype $@thin String.Type                // user: %7
   %4 = string_literal utf8 "1"                    // user: %7
   %5 = integer_literal $Builtin.Word, 1           // user: %7
@@ -113,16 +113,16 @@
 bb0:
   %0 = alloc_stack $String, var, name "s"              // users: %15, %16
   // function_ref static String.+ infix(String, String) -> String
-  %1 = function_ref @_T0SS1poiS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
+  %1 = function_ref @_T0SS1poiyS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
   // function_ref String.init(_builtinUTF16StringLiteral : Builtin.RawPointer, utf16CodeUnitCount : Builtin.Word) -> String
-  %2 = function_ref @_T0S2SBp26_builtinUTF16StringLiteral_Bw18utf16CodeUnitCounttcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> @owned String
+  %2 = function_ref @_T0SS26_builtinUTF16StringLiteral18utf16CodeUnitCountSSBp_BwtcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> @owned String
   %3 = metatype $@thin String.Type                // user: %7
   %4 = string_literal utf16 "á"                 // user: %7
   %5 = integer_literal $Builtin.Word, 2           // user: %7
   %6 = integer_literal $Builtin.Int1, 0
   %7 = apply %2(%4, %5, %3) : $@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> @owned String // user: %14
   // function_ref String.init(_builtinStringLiteral : Builtin.RawPointer, utf8CodeUnitCount : Builtin.Word, isASCII : Builtin.Int1) -> String
-  %8 = function_ref @_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
+  %8 = function_ref @_T0SS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
   %9 = metatype $@thin String.Type                // user: %13
   %10 = string_literal utf8 "z"                   // user: %13
   %11 = integer_literal $Builtin.Word, 1          // user: %13
@@ -143,9 +143,9 @@
 bb0:
   %0 = alloc_stack $String, var, name "s"              // users: %15, %16
   // function_ref static String.+ infix(String, String) -> String
-  %1 = function_ref @_T0SS1poiS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
+  %1 = function_ref @_T0SS1poiyS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
   // function_ref String.init(_builtinUTF16StringLiteral : Builtin.RawPointer, utf16CodeUnitCount : Builtin.Word) -> String
-  %2 = function_ref @_T0S2SBp26_builtinUTF16StringLiteral_Bw18utf16CodeUnitCounttcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> @owned String
+  %2 = function_ref @_T0SS26_builtinUTF16StringLiteral18utf16CodeUnitCountSSBp_BwtcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> @owned String
   %3 = metatype $@thin String.Type                // user: %7
   %4 = string_literal utf16 "á"                 // user: %7
   %5 = integer_literal $Builtin.Word, 2           // user: %7
@@ -171,16 +171,16 @@
 bb0:
   %0 = alloc_stack $String, var, name "s"              // users: %15, %16
   // function_ref static String.+ infix(String, String) -> String
-  %1 = function_ref @_T0SS1poiS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
+  %1 = function_ref @_T0SS1poiyS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
   // function_ref String.init(_builtinUTF16StringLiteral : Builtin.RawPointer, utf16CodeUnitCount : Builtin.Word) -> String
-  %2 = function_ref @_T0S2SBp26_builtinUTF16StringLiteral_Bw18utf16CodeUnitCounttcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> @owned String
+  %2 = function_ref @_T0SS26_builtinUTF16StringLiteral18utf16CodeUnitCountSSBp_BwtcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> @owned String
   %3 = metatype $@thin String.Type                // user: %7
   %4 = string_literal utf16 "á"                 // user: %7
   %5 = integer_literal $Builtin.Word, 2           // user: %7
   %6 = integer_literal $Builtin.Int1, 0
   %7 = apply %2(%4, %5, %3) : $@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> @owned String // user: %14
   // function_ref String.init(_builtinStringLiteral : Builtin.RawPointer, utf8CodeUnitCount : Builtin.Word, isASCII : Builtin.Int1) -> String
-  %8 = function_ref @_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
+  %8 = function_ref @_T0SS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
   %9 = metatype $@thin String.Type                // user: %13
   %10 = string_literal utf8 "xyz"                 // user: %13
   %11 = integer_literal $Builtin.Word, 3          // user: %13
@@ -201,9 +201,9 @@
 bb0:
   %0 = alloc_stack $String, var, name "s"              // users: %15, %16
   // function_ref static String.+ infix(String, String) -> String
-  %1 = function_ref @_T0SS1poiS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
+  %1 = function_ref @_T0SS1poiyS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
   // function_ref String.init(_builtinStringLiteral : Builtin.RawPointer, utf8CodeUnitCount : Builtin.Word, isASCII : Builtin.Int1) -> String
-  %2 = function_ref @_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
+  %2 = function_ref @_T0SS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
   %3 = metatype $@thin String.Type                // user: %7
   %4 = string_literal utf8 "xyz"                  // user: %7
   %5 = integer_literal $Builtin.Word, 3           // user: %7
@@ -229,16 +229,16 @@
 bb0:
   %0 = alloc_stack $String, var, name "s"              // users: %15, %16
   // function_ref static String.+ infix(String, String) -> String
-  %1 = function_ref @_T0SS1poiS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
+  %1 = function_ref @_T0SS1poiyS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
   // function_ref String.init(_builtinStringLiteral : Builtin.RawPointer, utf8CodeUnitCount : Builtin.Word, isASCII : Builtin.Int1) -> String
-  %2 = function_ref @_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
+  %2 = function_ref @_T0SS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
   %3 = metatype $@thin String.Type                // user: %7
   %4 = string_literal utf8 "xyz"                  // user: %7
   %5 = integer_literal $Builtin.Word, 3           // user: %7
   %6 = integer_literal $Builtin.Int1, -1          // user: %7
   %7 = apply %2(%4, %5, %6, %3) : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String // user: %14
   // function_ref String.init(_builtinUTF16StringLiteral : Builtin.RawPointer, utf16CodeUnitCount : Builtin.Word) -> String
-  %8 = function_ref @_T0S2SBp26_builtinUTF16StringLiteral_Bw18utf16CodeUnitCounttcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> @owned String
+  %8 = function_ref @_T0SS26_builtinUTF16StringLiteral18utf16CodeUnitCountSSBp_BwtcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> @owned String
   %9 = metatype $@thin String.Type                // user: %13
   %10 = string_literal utf16 "á"                // user: %13
   %11 = integer_literal $Builtin.Word, 2          // user: %13
@@ -259,9 +259,9 @@
 bb0:
   %0 = alloc_stack $String, var, name "s"              // users: %15, %16
   // function_ref static String.+ infix(String, String) -> String
-  %1 = function_ref @_T0SS1poiS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
+  %1 = function_ref @_T0SS1poiyS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
   // function_ref String.init(_builtinStringLiteral : Builtin.RawPointer, utf8CodeUnitCount : Builtin.Word, isASCII : Builtin.Int1) -> String
-  %2 = function_ref @_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
+  %2 = function_ref @_T0SS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
   %3 = metatype $@thin String.Type                // user: %7
   %4 = string_literal utf8 "xyz"                  // user: %7
   %5 = integer_literal $Builtin.Word, 3           // user: %7
@@ -289,9 +289,9 @@
 bb0:
   %0 = alloc_stack $String, var, name "s"              // users: %31, %32
   // function_ref static String.+ infix(String, String) -> String
-  %1 = function_ref @_T0SS1poiS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
+  %1 = function_ref @_T0SS1poiyS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
   // function_ref String.init(_builtinStringLiteral : Builtin.RawPointer, utf8CodeUnitCount : Builtin.Word, isASCII : Builtin.Int1) -> String
-  %2 = function_ref @_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
+  %2 = function_ref @_T0SS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
   %5 = metatype $@thin String.Type                // user: %9
   %6 = string_literal utf8 "ab"                   // user: %9
   %7 = integer_literal $Builtin.Word, 2           // user: %9
@@ -330,16 +330,16 @@
 bb0:
   %0 = alloc_stack $String, var, name "s"              // users: %23, %24
   // function_ref static String.+ infix(String, String) -> String
-  %1 = function_ref @_T0SS1poiS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
+  %1 = function_ref @_T0SS1poiyS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
   // function_ref String.init(_builtinStringLiteral : Builtin.RawPointer, utf8CodeUnitCount : Builtin.Word, isASCII : Builtin.Int1) -> String
-  %3 = function_ref @_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
+  %3 = function_ref @_T0SS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String
   %4 = metatype $@thin String.Type                // user: %8
   %5 = string_literal utf8 "ab"                   // user: %8
   %6 = integer_literal $Builtin.Word, 2           // user: %8
   %7 = integer_literal $Builtin.Int1, -1          // user: %8
   %8 = apply %3(%5, %6, %7, %4) : $@convention(method) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> @owned String // user: %15
   // function_ref String.init(_builtinUTF16StringLiteral : Builtin.RawPointer, utf16CodeUnitCount : Builtin.Word) -> String
-  %9 = function_ref @_T0S2SBp26_builtinUTF16StringLiteral_Bw18utf16CodeUnitCounttcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> @owned String
+  %9 = function_ref @_T0SS26_builtinUTF16StringLiteral18utf16CodeUnitCountSSBp_BwtcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> @owned String
   %10 = metatype $@thin String.Type               // user: %14
   %11 = string_literal utf8 "c"                   // user: %14
   %12 = integer_literal $Builtin.Word, 1          // user: %14
@@ -368,9 +368,9 @@
 bb0:
   %0 = alloc_stack $String, var, name "s"              // users: %23, %24
   // function_ref static String.+ infix(String, String) -> String
-  %1 = function_ref @_T0SS1poiS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
+  %1 = function_ref @_T0SS1poiyS2S_SStFZ : $@convention(method) (@owned String, @owned String, @thin String.Type) -> @owned String
   // function_ref String.init(_builtinUTF16StringLiteral : Builtin.RawPointer, utf16CodeUnitCount : Builtin.Word) -> String
-  %2 = function_ref @_T0S2SBp26_builtinUTF16StringLiteral_Bw18utf16CodeUnitCounttcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> @owned String
+  %2 = function_ref @_T0SS26_builtinUTF16StringLiteral18utf16CodeUnitCountSSBp_BwtcfC : $@convention(method) (Builtin.RawPointer, Builtin.Word, @thin String.Type) -> @owned String
   %4 = metatype $@thin String.Type                // user: %8
   %5 = string_literal utf16 "aaaá"              // user: %8
   %6 = integer_literal $Builtin.Word, 5           // user: %8
diff --git a/test/SILOptimizer/sil_locations.swift b/test/SILOptimizer/sil_locations.swift
index 721262c..4d43760 100644
--- a/test/SILOptimizer/sil_locations.swift
+++ b/test/SILOptimizer/sil_locations.swift
@@ -21,7 +21,7 @@
 func testMandatoryInlining(_ x: Float, b: Bool) -> Float {
   return bar(x, b)
 // CHECK-LABEL: _T013sil_locations21testMandatoryInlining{{[_0-9a-zA-Z]*}}F
-// CHECK: function_ref @_T013sil_locations11searchForMeS2fF : {{.*}} line:22:10:minlined
+// CHECK: function_ref @_T013sil_locations11searchForMeyS2fF : {{.*}} line:22:10:minlined
 // CHECK: apply                                                  {{.*}} line:22:10:minlined
 // CHECK: br                                                     {{.*}} line:22:10:minlined
 // CHECK: br                                                     {{.*}} line:22:10:minlined
diff --git a/test/SILOptimizer/spec_conf1.swift b/test/SILOptimizer/spec_conf1.swift
index 12716cf..3ba8b3e 100644
--- a/test/SILOptimizer/spec_conf1.swift
+++ b/test/SILOptimizer/spec_conf1.swift
@@ -19,8 +19,8 @@
 @inline(never)
 func outer_function<T : P>(In In : T) { inner_function(In: In) }
 
-//CHECK: sil shared [noinline] @_T010spec_conf114outer_functionyx2In_tAA1PRzlFAA3FooC_Tg5
-//CHECK: _T010spec_conf114inner_functionyx2In_tAA1PRzlFAA3FooC_Tg5
+//CHECK: sil shared [noinline] @_T010spec_conf114outer_function2Inyx_tAA1PRzlFAA3FooC_Tg5
+//CHECK: _T010spec_conf114inner_function2Inyx_tAA1PRzlFAA3FooC_Tg5
 //CHECK-NEXT: apply
 //CHECK: return
 
diff --git a/test/SILOptimizer/spec_conf2.swift b/test/SILOptimizer/spec_conf2.swift
index 4e584bd..bb15792 100644
--- a/test/SILOptimizer/spec_conf2.swift
+++ b/test/SILOptimizer/spec_conf2.swift
@@ -18,8 +18,8 @@
 @inline(never)
 func outer_function<T : P & Q>(In In : T) { inner_function(In: In) }
 
-//CHECK: sil shared [noinline] @_T010spec_conf214outer_functionyx2In_tAA1PRzAA1QRzlFAA3FooC_Tg5
-//CHECK: function_ref @_T010spec_conf214inner_functionyx2In_tAA1PRzAA1QRzlFAA3FooC_Tg5
+//CHECK: sil shared [noinline] @_T010spec_conf214outer_function2Inyx_tAA1PRzAA1QRzlFAA3FooC_Tg5
+//CHECK: function_ref @_T010spec_conf214inner_function2Inyx_tAA1PRzAA1QRzlFAA3FooC_Tg5
 //CHECK-NEXT: apply
 //CHECK: return
 
diff --git a/test/SILOptimizer/specialize.sil b/test/SILOptimizer/specialize.sil
index 54df0a6..0218ab1 100644
--- a/test/SILOptimizer/specialize.sil
+++ b/test/SILOptimizer/specialize.sil
@@ -102,7 +102,7 @@
 }
 
 // Swift.Int32._convertFromBuiltinIntegerLiteral (Swift.Int32.Type)(Builtin.Int2048) -> Swift.Int32
-sil public_external [transparent] @_T0Si33_convertFromBuiltinIntegerLiteralSiBi2048_cSimF : $@convention(thin) (Builtin.Int2048, @thin Int32.Type) -> Int32 {
+sil public_external [transparent] @_T0Si33_convertFromBuiltinIntegerLiteralySiBi2048_cSimF : $@convention(thin) (Builtin.Int2048, @thin Int32.Type) -> Int32 {
 bb0(%0 : $Builtin.Int2048, %1 : $@thin Int32.Type):
   %3 = builtin "s_to_s_checked_trunc_Int2048_Int32"(%0 : $Builtin.Int2048) : $(Builtin.Int32, Builtin.Int1)
   %4 = tuple_extract %3 : $(Builtin.Int32, Builtin.Int1), 0 // user: %5
@@ -367,7 +367,7 @@
 }
 
 // static Swift.+ infix (Swift.Int32, Swift.Int32) -> Swift.Int32
-sil public_external [transparent] [serialized] @_T0s1pois5Int32VAC_ACtFZ : $@convention(thin) (Int32, Int32) -> Int32 {
+sil public_external [transparent] [serialized] @_T0s1poiys5Int32VAC_ACtFZ : $@convention(thin) (Int32, Int32) -> Int32 {
 bb0(%0 : $Int32, %1 : $Int32):
   %2 = struct_extract %0 : $Int32, #Int32._value   // user: %5
   %3 = struct_extract %1 : $Int32, #Int32._value   // user: %5
diff --git a/test/SILOptimizer/specialize_anyobject.swift b/test/SILOptimizer/specialize_anyobject.swift
index e7d48a2..8df2285 100644
--- a/test/SILOptimizer/specialize_anyobject.swift
+++ b/test/SILOptimizer/specialize_anyobject.swift
@@ -17,6 +17,6 @@
 
 // CHECK-LABEL: sil hidden @_T020specialize_anyobject6callit{{[_0-9a-zA-Z]*}}F
 func callit(s: S<CB>) {
-  // CHECK: function_ref @_T0s3eeeoiSbyXlSg_ABtF : $@convention(thin) (@owned Optional<AnyObject>, @owned Optional<AnyObject>) -> Bool
+  // CHECK: function_ref @_T0s3eeeoiySbyXlSg_ABtF : $@convention(thin) (@owned Optional<AnyObject>, @owned Optional<AnyObject>) -> Bool
   s.crash()
 }
diff --git a/test/SILOptimizer/specialize_apply_conf.swift b/test/SILOptimizer/specialize_apply_conf.swift
index 8219564..dccca52 100644
--- a/test/SILOptimizer/specialize_apply_conf.swift
+++ b/test/SILOptimizer/specialize_apply_conf.swift
@@ -19,7 +19,7 @@
 }
 
 //CHECK: sil hidden @_T021specialize_apply_conf11interestingyyF
-//CHECK-DAG: [[F:%[0-9]+]] = function_ref @_T021specialize_apply_conf9main_funcyx2In_tlFSi_Tg5{{.*}}{{.*}}scope
+//CHECK-DAG: [[F:%[0-9]+]] = function_ref @_T021specialize_apply_conf9main_func2Inyx_tlFSi_Tg5{{.*}}{{.*}}scope
 //CHECK-DAG: [[A:%[0-9]+]] = struct $Int
 //CHECK-DAG: apply [[F]]([[A]])
 //CHECK: return
diff --git a/test/SILOptimizer/specialize_checked_cast_branch.swift b/test/SILOptimizer/specialize_checked_cast_branch.swift
index bf9f9f3..fa056e3 100644
--- a/test/SILOptimizer/specialize_checked_cast_branch.swift
+++ b/test/SILOptimizer/specialize_checked_cast_branch.swift
@@ -24,21 +24,21 @@
   _preconditionFailure("??? Profit?")
 }
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch28ArchetypeToConcreteCastUInt8AA03NotI0Vx1t_tlFAD_Tg5 : $@convention(thin) (NotUInt8) -> NotUInt8 {
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch28ArchetypeToConcreteCastUInt81tAA03NotI0Vx_tlFAE_Tg5 : $@convention(thin) (NotUInt8) -> NotUInt8 {
 // CHECK: bb0
 // CHECK: return %0 : $NotUInt8
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ArchetypeToConcreteCastCAA1CCx1t_tlFAD_Tg5 : $@convention(thin) (@owned C) -> @owned C {
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ArchetypeToConcreteCastC1tAA1CCx_tlFAE_Tg5 : $@convention(thin) (@owned C) -> @owned C {
 // CHECK: bb0
 // CHECK: return %0 : $C
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ArchetypeToConcreteCastCAA1CCx1t_tlFAA1DC_Tg5 : $@convention(thin) (@owned D) -> @owned C {
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ArchetypeToConcreteCastC1tAA1CCx_tlFAA1DC_Tg5 : $@convention(thin) (@owned D) -> @owned C {
 // CHECK: bb0
 // CHECK:  [[CAST:%.*]] = upcast %0 : $D to $C
 // CHECK: return [[CAST]]
 
 // x -> y where x is a super class of y.
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ArchetypeToConcreteCastDAA1DCx1t_tlFAA1CC_Tg5 : $@convention(thin) (@owned C) -> @owned D {
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ArchetypeToConcreteCastD1tAA1DCx_tlFAA1CC_Tg5 : $@convention(thin) (@owned C) -> @owned D {
 // CHECK: checked_cast_br %0 : $C to $D,
 // CHECK: bb1([[T0:%.*]] : $D):
 // CHECK: return [[T0]] : $D
@@ -47,7 +47,7 @@
 // CHECK: cond_fail
 // CHECK: unreachable
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Castq_x2t1_q_2t2tr0_lFAA1CC_AA1DCTg5Tf4nd_n : $@convention(thin) (@owned C) -> @owned D
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA1CC_AA1DCTg5Tf4nd_n : $@convention(thin) (@owned C) -> @owned D
 // CHECK: bb0
 // CHECK:  checked_cast_br %0 : $C to $D, bb1, bb2
 // CHECK: bb1(
@@ -58,19 +58,19 @@
 // CHECK:   unreachable
 
 // x -> x where x is a class.
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Castq_x2t1_q_2t2tr0_lFAA1CC_AFTg5Tf4nd_n : $@convention(thin) (@owned C) -> @owned C {
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA1CC_AFTg5Tf4nd_n : $@convention(thin) (@owned C) -> @owned C {
 // CHECK: bb0
 // CHECK-NOT: bb1
 // CHECK: return %0 : $C
 
 // x -> x where x is not a class.
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Castq_x2t1_q_2t2tr0_lFAA8NotUInt8V_AFTg5Tf4nd_n : $@convention(thin) (NotUInt8) -> NotUInt8 {
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA8NotUInt8V_AFTg5Tf4nd_n : $@convention(thin) (NotUInt8) -> NotUInt8 {
 // CHECK: bb0
 // CHECK-NOT: bb1
 // CHECK: return %0 : $NotUInt8
 
 // x -> y where x,y are not classes and x is a different type from y.
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Castq_x2t1_q_2t2tr0_lFAA8NotUInt8V_AA0J6UInt64VTg5Tf4dd_n : $@convention(thin) () -> NotUInt64 {
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA8NotUInt8V_AA0J6UInt64VTg5Tf4dd_n : $@convention(thin) () -> NotUInt64 {
 // CHECK: bb0
 // CHECK-NOT: bb1
 // CHECK: %0 = integer_literal $Builtin.Int1, -1
@@ -78,7 +78,7 @@
 // CHECK: unreachable
 
 // x -> y where x is not a class but y is.
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Castq_x2t1_q_2t2tr0_lFAA8NotUInt8V_AA1CCTg5Tf4dd_n : $@convention(thin) () -> @owned C {
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA8NotUInt8V_AA1CCTg5Tf4dd_n : $@convention(thin) () -> @owned C {
 // CHECK: bb0
 // CHECK-NOT: bb1
 // CHECK: %0 = integer_literal $Builtin.Int1, -1
@@ -86,7 +86,7 @@
 // CHECK: unreachable
 
 // y -> x where x is a class but y is not.
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Castq_x2t1_q_2t2tr0_lFAA1CC_AA8NotUInt8VTg5Tf4dd_n : $@convention(thin) () -> NotUInt8 {
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA1CC_AA8NotUInt8VTg5Tf4dd_n : $@convention(thin) () -> NotUInt8 {
 // CHECK: bb0
 // CHECK-NOT: bb1
 // CHECK: %0 = integer_literal $Builtin.Int1, -1
@@ -94,12 +94,12 @@
 // CHECK: unreachable
 
 // y -> x where x is a super class of y.
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Castq_x2t1_q_2t2tr0_lFAA1DC_AA1CCTg5Tf4nd_n : $@convention(thin) (@owned D) -> @owned C {
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA1DC_AA1CCTg5Tf4nd_n : $@convention(thin) (@owned D) -> @owned C {
 // CHECK: [[T1:%.*]] = upcast %0 : $D to $C
 // CHECK: return [[T1]] : $C
 
 // x -> y where x and y are unrelated.
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Castq_x2t1_q_2t2tr0_lFAA1CC_AA1ECTg5Tf4dd_n : $@convention(thin) () -> @owned E {
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Cast2t12t2q_x_q_tr0_lFAA1CC_AA1ECTg5Tf4dd_n : $@convention(thin) () -> @owned E {
 // CHECK: bb0
 // CHECK-NOT: bb1
 // CHECK: %0 = integer_literal $Builtin.Int1, -1
@@ -150,34 +150,34 @@
 
 _ = ArchetypeToConcreteCastUInt8(t: b)
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch28ArchetypeToConcreteCastUInt8AA03NotI0Vx1t_tlFAA1CC_Tg5Tf4d_n : $@convention(thin) () -> NotUInt8 {
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch28ArchetypeToConcreteCastUInt81tAA03NotI0Vx_tlFAA1CC_Tg5Tf4d_n : $@convention(thin) () -> NotUInt8 {
 // CHECK: bb0
 // CHECK-NOT: checked_cast_br
 // CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
 // CHECK: cond_fail [[TRUE]]
 // CHECK: unreachable
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch28ArchetypeToConcreteCastUInt8AA03NotI0Vx1t_tlFAA0J6UInt64V_Tg5Tf4d_n : $@convention(thin) () -> NotUInt8 {
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch28ArchetypeToConcreteCastUInt81tAA03NotI0Vx_tlFAA0J6UInt64V_Tg5Tf4d_n : $@convention(thin) () -> NotUInt8 {
 // CHECK-NEXT: bb0
 // CHECK-NOT: checked_cast_br archetype_to_concrete
 // CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
 // CHECK: cond_fail [[TRUE]]
 // CHECK: unreachable
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ArchetypeToConcreteCastCAA1CCx1t_tlFAA8NotUInt8V_Tg5Tf4d_n : $@convention(thin) () -> @owned C {
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ArchetypeToConcreteCastC1tAA1CCx_tlFAA8NotUInt8V_Tg5Tf4d_n : $@convention(thin) () -> @owned C {
 // CHECK: bb0
 // CHECK-NOT: checked_cast_br
 // CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
 // CHECK: cond_fail [[TRUE]]
 // CHECK: unreachable
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ArchetypeToConcreteCastCAA1CCx1t_tlFAA1EC_Tg5Tf4d_n : $@convention(thin) () -> @owned C {
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ArchetypeToConcreteCastC1tAA1CCx_tlFAA1EC_Tg5Tf4d_n : $@convention(thin) () -> @owned C {
 // CHECK: bb0
 // CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
 // CHECK: cond_fail [[TRUE]]
 // CHECK: unreachable
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ArchetypeToConcreteCastEAA1ECx1t_tlFAA1CC_Tg5Tf4d_n : $@convention(thin) () -> @owned E {
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ArchetypeToConcreteCastE1tAA1ECx_tlFAA1CC_Tg5Tf4d_n : $@convention(thin) () -> @owned E {
 // CHECK: bb0
 // CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
 // CHECK: cond_fail [[TRUE]]
@@ -215,44 +215,44 @@
   _preconditionFailure("??? Profit?")
 }
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch28ConcreteToArchetypeCastUInt8xAA03NotI0V1t_x2t2tlFAD_Tg5Tf4nd_n : $@convention(thin) (NotUInt8) -> NotUInt8
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch28ConcreteToArchetypeCastUInt81t2t2xAA03NotI0V_xtlFAF_Tg5Tf4nd_n : $@convention(thin) (NotUInt8) -> NotUInt8
 // CHECK: bb0
 // CHECK: return %0
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch28ConcreteToArchetypeCastUInt8xAA03NotI0V1t_x2t2tlFAA1CC_Tg5Tf4dd_n : $@convention(thin) () -> @owned C
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch28ConcreteToArchetypeCastUInt81t2t2xAA03NotI0V_xtlFAA1CC_Tg5Tf4dd_n : $@convention(thin) () -> @owned C
 // CHECK: bb0
 // CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
 // CHECK: cond_fail [[TRUE]]
 // CHECK: unreachable
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch28ConcreteToArchetypeCastUInt8xAA03NotI0V1t_x2t2tlFAA0J6UInt64V_Tg5Tf4dd_n : $@convention(thin) () -> NotUInt64
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch28ConcreteToArchetypeCastUInt81t2t2xAA03NotI0V_xtlFAA0K6UInt64V_Tg5Tf4dd_n : $@convention(thin) () -> NotUInt64
 // CHECK: bb0
 // CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
 // CHECK: cond_fail [[TRUE]]
 // CHECK: unreachable
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ConcreteToArchetypeCastCxAA1CC1t_x2t2tlFAD_Tg5Tf4nd_n : $@convention(thin) (@owned C) -> @owned C
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ConcreteToArchetypeCastC1t2t2xAA1CC_xtlFAF_Tg5Tf4nd_n : $@convention(thin) (@owned C) -> @owned C
 // CHECK: bb0
 // CHECK: return %0
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ConcreteToArchetypeCastCxAA1CC1t_x2t2tlFAA8NotUInt8V_Tg5Tf4dd_n : $@convention(thin) () -> NotUInt8
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ConcreteToArchetypeCastC1t2t2xAA1CC_xtlFAA8NotUInt8V_Tg5Tf4dd_n : $@convention(thin) () -> NotUInt8
 // CHECK: bb0
 // CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
 // CHECK: cond_fail [[TRUE]]
 // CHECK: unreachable
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ConcreteToArchetypeCastCxAA1CC1t_x2t2tlFAA1DC_Tg5Tf4nd_n : $@convention(thin) (@owned C) -> @owned D
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ConcreteToArchetypeCastC1t2t2xAA1CC_xtlFAA1DC_Tg5Tf4nd_n : $@convention(thin) (@owned C) -> @owned D
 // CHECK: bb0
 // CHECK:  checked_cast_br %0 : $C to $D
 // CHECK: bb1
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ConcreteToArchetypeCastCxAA1CC1t_x2t2tlFAA1EC_Tg5Tf4dd_n : $@convention(thin) () -> @owned E
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ConcreteToArchetypeCastC1t2t2xAA1CC_xtlFAA1EC_Tg5Tf4dd_n : $@convention(thin) () -> @owned E
 // CHECK: bb0
 // CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
 // CHECK: cond_fail [[TRUE]]
 // CHECK: unreachable
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ConcreteToArchetypeCastDxAA1DC1t_x2t2tlFAA1CC_Tg5Tf4nd_n : $@convention(thin) (@owned D) -> @owned C
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ConcreteToArchetypeCastD1t2t2xAA1DC_xtlFAA1CC_Tg5Tf4nd_n : $@convention(thin) (@owned D) -> @owned C
 // CHECK: bb0
 // CHECK:  [[T0:%.*]] = upcast %0 : $D to $C
 // CHECK:  return [[T0]]
@@ -284,27 +284,27 @@
   _preconditionFailure("??? Profit?")
 }
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch21SuperToArchetypeCastCxAA1CC1c_x1ttlFAD_Tg5Tf4nd_n : $@convention(thin) (@owned C) -> @owned C
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch21SuperToArchetypeCastC1c1txAA1CC_xtlFAF_Tg5Tf4nd_n : $@convention(thin) (@owned C) -> @owned C
 // CHECK: bb0
 // CHECK: return %0 : $C
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch21SuperToArchetypeCastCxAA1CC1c_x1ttlFAA1DC_Tg5Tf4nd_n : $@convention(thin) (@owned C) -> @owned D
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch21SuperToArchetypeCastC1c1txAA1CC_xtlFAA1DC_Tg5Tf4nd_n : $@convention(thin) (@owned C) -> @owned D
 // CHECK: bb0
 // CHECK:  checked_cast_br %0 : $C to $D
 // CHECK: bb1
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch21SuperToArchetypeCastCxAA1CC1c_x1ttlFAA8NotUInt8V_Tg5Tf4dd_n : $@convention(thin) () -> NotUInt8
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch21SuperToArchetypeCastC1c1txAA1CC_xtlFAA8NotUInt8V_Tg5Tf4dd_n : $@convention(thin) () -> NotUInt8
 // CHECK: bb0
 // CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
 // CHECK: cond_fail [[TRUE]]
 // CHECK: unreachable
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch21SuperToArchetypeCastDxAA1DC1d_x1ttlFAA1CC_Tg5Tf4nd_n : $@convention(thin) (@owned D) -> @owned C
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch21SuperToArchetypeCastD1d1txAA1DC_xtlFAA1CC_Tg5Tf4nd_n : $@convention(thin) (@owned D) -> @owned C
 // CHECK: bb0
 // CHECK:  [[T0:%.*]] = upcast %0 : $D to $C
 // CHECK:  return [[T0]]
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch21SuperToArchetypeCastDxAA1DC1d_x1ttlFAD_Tg5Tf4nd_n : $@convention(thin) (@owned D) -> @owned D
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch21SuperToArchetypeCastD1d1txAA1DC_xtlFAF_Tg5Tf4nd_n : $@convention(thin) (@owned D) -> @owned D
 // CHECK: bb0
 // CHECK: return %0 : $D
 
@@ -325,17 +325,17 @@
   _preconditionFailure("??? Profit?")
 }
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch26ExistentialToArchetypeCastxyXl1o_x1ttlFAA1CC_Tg5Tf4nd_n : $@convention(thin) (@owned AnyObject) -> @owned C
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch26ExistentialToArchetypeCast1o1txyXl_xtlFAA1CC_Tg5Tf4nd_n : $@convention(thin) (@owned AnyObject) -> @owned C
 // CHECK: bb0
 // CHECK:  checked_cast_br %0 : $AnyObject to $C
 // CHECK: bb1
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch26ExistentialToArchetypeCastxyXl1o_x1ttlFAA8NotUInt8V_Tg5Tf4gd_n : $@convention(thin) (@guaranteed AnyObject) -> NotUInt8
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch26ExistentialToArchetypeCast1o1txyXl_xtlFAA8NotUInt8V_Tg5Tf4gd_n : $@convention(thin) (@guaranteed AnyObject) -> NotUInt8
 // CHECK: bb0
 // CHECK:  checked_cast_addr_br take_always AnyObject in {{%.*}} : $*AnyObject to NotUInt8 in {{%.*}} : $*NotUInt8,
 // CHECK: bb1
 
-// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch26ExistentialToArchetypeCastxyXl1o_x1ttlFyXl_Tg5Tf4nd_n : $@convention(thin) (@owned AnyObject) -> @owned AnyObject
+// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch26ExistentialToArchetypeCast1o1txyXl_xtlFyXl_Tg5Tf4nd_n : $@convention(thin) (@owned AnyObject) -> @owned AnyObject
 // CHECK: bb0
 // CHECK-NOT: checked_cast_br %
 // CHECK: return %0 : $AnyObject
diff --git a/test/SILOptimizer/specialize_class_inherits_base_inherits_protocol.swift b/test/SILOptimizer/specialize_class_inherits_base_inherits_protocol.swift
index c5b2375..646c291 100644
--- a/test/SILOptimizer/specialize_class_inherits_base_inherits_protocol.swift
+++ b/test/SILOptimizer/specialize_class_inherits_base_inherits_protocol.swift
@@ -12,7 +12,7 @@
 
 // CHECK-LABEL: sil @_T0031specialize_class_inherits_base_C9_protocol3fooyyF
 public func foo() {
-  // CHECK: function_ref @_T0031specialize_class_inherits_base_C9_protocol4sinkyxlFypXp_Tg5Tf4d_n
+  // CHECK: function_ref @_T0031specialize_class_inherits_base_C9_protocol4sinkyyxlFypXp_Tg5Tf4d_n
   p(Bar<Int>())
 }
 
diff --git a/test/SILOptimizer/specialize_dynamic_self.swift b/test/SILOptimizer/specialize_dynamic_self.swift
index 71aef3e..37269f5 100644
--- a/test/SILOptimizer/specialize_dynamic_self.swift
+++ b/test/SILOptimizer/specialize_dynamic_self.swift
@@ -21,7 +21,7 @@
   }
 }
 
-// CHECK-LABEL: sil hidden [thunk] [always_inline] @_T023specialize_dynamic_self8usesCIntyAA1CCySiG1c_tF : $@convention(thin) (@owned C<Int>) -> () {
+// CHECK-LABEL: sil hidden [thunk] [always_inline] @_T023specialize_dynamic_self8usesCInt1cyAA1CCySiG_tF : $@convention(thin) (@owned C<Int>) -> () {
 // CHECK: function_ref @_T023specialize_dynamic_self1CC11returnsSelfACyxGXDyFSi_Tg5 : $@convention(method) (@guaranteed C<Int>) -> @owned C<Int>
 // CHECK: return
 func usesCInt(c: C<Int>) {
diff --git a/test/SILOptimizer/specialize_inherited_multifile.swift b/test/SILOptimizer/specialize_inherited_multifile.swift
index feac0f7..470a6c1 100644
--- a/test/SILOptimizer/specialize_inherited_multifile.swift
+++ b/test/SILOptimizer/specialize_inherited_multifile.swift
@@ -8,8 +8,8 @@
 
 // Make sure the ConcreteDerived : Base conformance is available here.
 
-// CHECK-LABEL: sil shared [noinline] @_T030specialize_inherited_multifile17takesHasAssocTypeyx1t_tAA0efG0RzlFAA08ConcreteefG0C_Tg5 : $@convention(thin) (@owned ConcreteHasAssocType) -> ()
-// CHECK: [[FN:%.*]] = function_ref @_T030specialize_inherited_multifile9takesBaseyx1t_tAA0E0RzlF
+// CHECK-LABEL: sil shared [noinline] @_T030specialize_inherited_multifile17takesHasAssocType1tyx_tAA0efG0RzlFAA08ConcreteefG0C_Tg5 : $@convention(thin) (@owned ConcreteHasAssocType) -> ()
+// CHECK: [[FN:%.*]] = function_ref @_T030specialize_inherited_multifile9takesBase1tyx_tAA0E0RzlF
 // CHECK: apply [[FN]]<ConcreteDerived>({{%.*}})
 // CHECK: return
 
diff --git a/test/SILOptimizer/specialize_partial_apply.swift b/test/SILOptimizer/specialize_partial_apply.swift
index cf447e0..e14975d 100644
--- a/test/SILOptimizer/specialize_partial_apply.swift
+++ b/test/SILOptimizer/specialize_partial_apply.swift
@@ -17,8 +17,8 @@
 // We need a reabstraction thunk to convert from direct args/result to indirect
 // args/result, which is expected in the returned closure.
 
-// CHECK-LABEL: sil shared [noinline] @_T04test16generic_get_funcxxcx_SbtlFSi_Tg5 : $@convention(thin) (Int, Bool) -> @owned @callee_guaranteed (@in Int) -> @out Int {
-// CHECK: [[F:%[0-9]+]] = function_ref @_T04test16generic_get_funcxxcx_SbtlF0B0L_xxlFSi_TG5 : $@convention(thin) (@in Int, Bool, @guaranteed <τ_0_0> { var τ_0_0 } <Int>) -> @out Int
+// CHECK-LABEL: sil shared [noinline] @_T04test16generic_get_funcyxxcx_SbtlFSi_Tg5 : $@convention(thin) (Int, Bool) -> @owned @callee_guaranteed (@in Int) -> @out Int {
+// CHECK: [[F:%[0-9]+]] = function_ref @_T04test16generic_get_funcyxxcx_SbtlF0B0L_yxxlFSi_TG5 : $@convention(thin) (@in Int, Bool, @guaranteed <τ_0_0> { var τ_0_0 } <Int>) -> @out Int
 // CHECK: [[PA:%[0-9]+]] = partial_apply [callee_guaranteed] [[F]](%1, %{{[0-9]+}}) : $@convention(thin) (@in Int, Bool, @guaranteed <τ_0_0> { var τ_0_0 } <Int>) -> @out Int
 // CHECK: return [[PA]] : $@callee_guaranteed (@in Int) -> @out Int
 @inline(never)
@@ -32,8 +32,8 @@
 	return generic
 }
 
-// CHECK-LABEL: sil hidden [noinline] @_T04test7testit1S2icSbF : $@convention(thin) (Bool) -> @owned @callee_guaranteed (Int) -> Int {
-// CHECK: [[F:%[0-9]+]] = function_ref @_T04test16generic_get_funcxxcx_SbtlFSi_Tg5 : $@convention(thin) (Int, Bool) -> @owned @callee_guaranteed (@in Int) -> @out Int
+// CHECK-LABEL: sil hidden [noinline] @_T04test7testit1yS2icSbF : $@convention(thin) (Bool) -> @owned @callee_guaranteed (Int) -> Int {
+// CHECK: [[F:%[0-9]+]] = function_ref @_T04test16generic_get_funcyxxcx_SbtlFSi_Tg5 : $@convention(thin) (Int, Bool) -> @owned @callee_guaranteed (@in Int) -> @out Int
 // CHECK: [[CL:%[0-9]+]] = apply [[F]](%{{[0-9]+}}, %0) : $@convention(thin) (Int, Bool) -> @owned @callee_guaranteed (@in Int) -> @out Int
 // CHECK: [[TH:%[0-9]+]] = function_ref @_T0S2iIegir_S2iIegyd_TR : $@convention(thin) (Int, @guaranteed @callee_guaranteed (@in Int) -> @out Int) -> Int
 // CHECK: [[RET:%[0-9]+]] = partial_apply [callee_guaranteed] [[TH]]([[CL]])
@@ -53,7 +53,7 @@
 // args/result anyway.
 
 // CHECK-LABEL: sil hidden [noinline] @_T04test17concrete_get_funcS2i_SiSbtcyF : $@convention(thin) () -> @owned @callee_guaranteed (Int, Int, Bool) -> Int {
-// CHECK: [[F:%[0-9]+]] = function_ref @_T04test8generic2xx_x2t2Sb1btlFSi_Tg5 : $@convention(thin) (Int, Int, Bool) -> Int
+// CHECK: [[F:%[0-9]+]] = function_ref @_T04test8generic2_2t21bxx_xSbtlFSi_Tg5 : $@convention(thin) (Int, Int, Bool) -> Int
 // CHECK: [[RET:%[0-9]+]] = thin_to_thick_function [[F]] : $@convention(thin) (Int, Int, Bool) -> Int to $@callee_guaranteed (Int, Int, Bool) -> Int
 // CHECK: return [[RET]] : $@callee_guaranteed (Int, Int, Bool) -> Int
 @inline(never)
@@ -74,8 +74,8 @@
 
 // No reabstraction thunk is needed because we directly apply the returned closure.
 
-// CHECK-LABEL: sil hidden [noinline] @_T04test7testit3SiSbF : $@convention(thin) (Bool) -> Int {
-// CHECK: [[F:%[0-9]+]] = function_ref @_T04test8generic3xx_xSbtlFSi_Tg5 : $@convention(thin) (Int, Int, Bool) -> Int
+// CHECK-LABEL: sil hidden [noinline] @_T04test7testit3ySiSbF : $@convention(thin) (Bool) -> Int {
+// CHECK: [[F:%[0-9]+]] = function_ref @_T04test8generic3yxx_xSbtlFSi_Tg5 : $@convention(thin) (Int, Int, Bool) -> Int
 // CHECK: [[RET:%[0-9]+]] = apply [[F]]({{.*}}) : $@convention(thin) (Int, Int, Bool) -> Int
 // CHECK: return [[RET]] : $Int
 @inline(never)
@@ -88,8 +88,8 @@
 // We need a reabstraction thunk to convert from direct args/result to indirect
 // args/result, which is expected in the returned closure.
 
-// CHECK-LABEL: sil shared [noinline] @_T04test25generic_get_func_throwingxxKcSblFSi_Tg5 : $@convention(thin) (Bool) -> @owned @callee_guaranteed (@in Int) -> (@out Int, @error Error) {
-// CHECK: [[F:%[0-9]+]] = function_ref @_T04test25generic_get_func_throwingxxKcSblF0B0L_xxKlFSi_TG5 : $@convention(thin) (@in Int, Bool) -> (@out Int, @error Error)
+// CHECK-LABEL: sil shared [noinline] @_T04test25generic_get_func_throwingyxxKcSblFSi_Tg5 : $@convention(thin) (Bool) -> @owned @callee_guaranteed (@in Int) -> (@out Int, @error Error) {
+// CHECK: [[F:%[0-9]+]] = function_ref @_T04test25generic_get_func_throwingyxxKcSblF0B0L_yxxKlFSi_TG5 : $@convention(thin) (@in Int, Bool) -> (@out Int, @error Error)
 // CHECK: [[PA:%[0-9]+]] = partial_apply [callee_guaranteed] [[F]](%0) : $@convention(thin) (@in Int, Bool) -> (@out Int, @error Error)
 // CHECK: return [[PA]] : $@callee_guaranteed (@in Int) -> (@out Int, @error Error)
 @inline(never)
@@ -106,8 +106,8 @@
 	return generic
 }
 
-// CHECK-LABEL: sil hidden [noinline] @_T04test16testit1_throwingS2iKcSbF : $@convention(thin) (Bool) -> @owned @callee_guaranteed (Int) -> (Int, @error Error) {
-// CHECK: [[F:%[0-9]+]] = function_ref @_T04test25generic_get_func_throwingxxKcSblFSi_Tg5 : $@convention(thin) (Bool) -> @owned @callee_guaranteed (@in Int) -> (@out Int, @error Error)
+// CHECK-LABEL: sil hidden [noinline] @_T04test16testit1_throwingyS2iKcSbF : $@convention(thin) (Bool) -> @owned @callee_guaranteed (Int) -> (Int, @error Error) {
+// CHECK: [[F:%[0-9]+]] = function_ref @_T04test25generic_get_func_throwingyxxKcSblFSi_Tg5 : $@convention(thin) (Bool) -> @owned @callee_guaranteed (@in Int) -> (@out Int, @error Error)
 // CHECK: [[CL:%[0-9]+]] = apply [[F]](%0) : $@convention(thin) (Bool) -> @owned @callee_guaranteed (@in Int) -> (@out Int, @error Error)
 // CHECK: [[TH:%[0-9]+]] = function_ref @_T0S2is5Error_pIegirzo_S2isAA_pIegydzo_TR : $@convention(thin) (Int, @guaranteed @callee_guaranteed (@in Int) -> (@out Int, @error Error)) -> (Int, @error Error)
 // CHECK: [[RET:%[0-9]+]] = partial_apply [callee_guaranteed] [[TH]]([[CL]])
@@ -130,7 +130,7 @@
 // args/result anyway.
 
 // CHECK-LABEL: sil hidden [noinline] @_T04test26concrete_get_func_throwingS2i_SbtKcyF : $@convention(thin) () -> @owned @callee_guaranteed (Int, Bool) -> (Int, @error Error) {
-// CHECK: [[F:%[0-9]+]] = function_ref @_T04test17generic2_throwingxx_Sb1btKlFSi_Tg5 : $@convention(thin) (Int, Bool) -> (Int, @error Error)
+// CHECK: [[F:%[0-9]+]] = function_ref @_T04test17generic2_throwing_1bxx_SbtKlFSi_Tg5 : $@convention(thin) (Int, Bool) -> (Int, @error Error)
 // CHECK: [[RET:%[0-9]+]] = thin_to_thick_function [[F]] : $@convention(thin) (Int, Bool) -> (Int, @error Error) to $@callee_guaranteed (Int, Bool) -> (Int, @error Error)
 // CHECK: return [[RET]] : $@callee_guaranteed (Int, Bool) -> (Int, @error Error)
 @inline(never)
@@ -155,8 +155,8 @@
 
 // No reabstraction thunk is needed because we directly apply the returned closure.
 
-// CHECK-LABEL: sil hidden [noinline] @_T04test16testit3_throwingSiSbF : $@convention(thin) (Bool) -> Int {
-// CHECK: [[F:%[0-9]+]] = function_ref @_T04test17generic3_throwingxx_SbtKlFSi_Tg5 : $@convention(thin) (Int, Bool) -> (Int, @error Error)
+// CHECK-LABEL: sil hidden [noinline] @_T04test16testit3_throwingySiSbF : $@convention(thin) (Bool) -> Int {
+// CHECK: [[F:%[0-9]+]] = function_ref @_T04test17generic3_throwingyxx_SbtKlFSi_Tg5 : $@convention(thin) (Int, Bool) -> (Int, @error Error)
 // CHECK: try_apply [[F]](%{{[0-9]+}}, %0) : $@convention(thin) (Int, Bool) -> (Int, @error Error), normal bb{{[0-9]+}}, error bb{{[0-9]+}}
 // CHECK: }
 @inline(never)
@@ -168,18 +168,18 @@
 	}
 }
 
-// CHECK-LABEL: sil shared [transparent] [thunk] @_T04test16generic_get_funcxxcx_SbtlF0B0L_xxlFSi_TG5 : $@convention(thin) (@in Int, Bool, @guaranteed <τ_0_0> { var τ_0_0 } <Int>) -> @out Int {
+// CHECK-LABEL: sil shared [transparent] [thunk] @_T04test16generic_get_funcyxxcx_SbtlF0B0L_yxxlFSi_TG5 : $@convention(thin) (@in Int, Bool, @guaranteed <τ_0_0> { var τ_0_0 } <Int>) -> @out Int {
 // CHECK: bb0(%0 : $*Int, %1 : $*Int, %2 : $Bool, %3 : $<τ_0_0> { var τ_0_0 } <Int>):
 // CHECK: [[LD:%[0-9]+]] = load %1 : $*Int
-// CHECK: [[F:%[0-9]+]] = function_ref @_T04test16generic_get_funcxxcx_SbtlF0B0L_xxlFSi_Tg5 : $@convention(thin) (Int, Bool, @guaranteed <τ_0_0> { var τ_0_0 } <Int>) -> Int
+// CHECK: [[F:%[0-9]+]] = function_ref @_T04test16generic_get_funcyxxcx_SbtlF0B0L_yxxlFSi_Tg5 : $@convention(thin) (Int, Bool, @guaranteed <τ_0_0> { var τ_0_0 } <Int>) -> Int
 // CHECK: [[RET:%[0-9]+]] = apply [[F]]([[LD]], %2, %3)
 // CHECK: store [[RET]] to %0 : $*Int
 // CHECK: return %{{[0-9]*}} : $()
 
-// CHECK-LABEL: sil shared [transparent] [thunk] @_T04test25generic_get_func_throwingxxKcSblF0B0L_xxKlFSi_TG5 : $@convention(thin) (@in Int, Bool) -> (@out Int, @error Error) {
+// CHECK-LABEL: sil shared [transparent] [thunk] @_T04test25generic_get_func_throwingyxxKcSblF0B0L_yxxKlFSi_TG5 : $@convention(thin) (@in Int, Bool) -> (@out Int, @error Error) {
 // CHECK: bb0(%0 : $*Int, %1 : $*Int, %2 : $Bool):
 // CHECK: [[LD:%[0-9]+]] = load %1 : $*Int
-// CHECK: [[F:%[0-9]+]] = function_ref @_T04test25generic_get_func_throwingxxKcSblF0B0L_xxKlFSi_Tg5 : $@convention(thin) (Int, Bool) -> (Int, @error Error)
+// CHECK: [[F:%[0-9]+]] = function_ref @_T04test25generic_get_func_throwingyxxKcSblF0B0L_yxxKlFSi_Tg5 : $@convention(thin) (Int, Bool) -> (Int, @error Error)
 // CHECK: try_apply [[F]]([[LD]], %2) : $@convention(thin) (Int, Bool) -> (Int, @error Error), normal bb1, error bb2
 // CHECK: bb1([[NORMAL:%[0-9]+]] : $Int):
 // CHECK: store [[NORMAL]] to %0 : $*Int
diff --git a/test/SILOptimizer/specialize_refined_adds_constraints.swift b/test/SILOptimizer/specialize_refined_adds_constraints.swift
index 89aa3e2..691dd16 100644
--- a/test/SILOptimizer/specialize_refined_adds_constraints.swift
+++ b/test/SILOptimizer/specialize_refined_adds_constraints.swift
@@ -22,7 +22,7 @@
   func assoc() -> Assoc { return Assoc() }
 }
 
-// CHECK-LABEL: sil shared @_T035specialize_refined_adds_constraints1gyxAA1RRzlFAA1XV_Tg5 :
+// CHECK-LABEL: sil shared @_T035specialize_refined_adds_constraints1gyyxAA1RRzlFAA1XV_Tg5 :
 func test(x: X) {
   g(x)
 }
diff --git a/test/SILOptimizer/specialize_same_type_constraint.swift b/test/SILOptimizer/specialize_same_type_constraint.swift
index 7b6152e..c286a22 100644
--- a/test/SILOptimizer/specialize_same_type_constraint.swift
+++ b/test/SILOptimizer/specialize_same_type_constraint.swift
@@ -45,9 +45,9 @@
 doStuff(f: ConcreteFirstParent<ConcreteChild>(),
         s: ConcreteSecondParent<ConcreteChild>())
 
-// CHECK-LABEL: sil shared [noinline] @_T031specialize_same_type_constraint7doStuffyx1f_q_1stAA11FirstParentRzAA06SecondH0R_5ChildQy_AGRtzr0_lFAA08ConcretegH0VyAA0kJ0VG_AA0kiH0VyAMGTg5Tf4dd_n : $@convention(thin) () -> () {
-// CHECK: [[FIRST:%.*]] = function_ref @_T031specialize_same_type_constraint15takesFirstChildyx1t_tAA0fG0RzlF
+// CHECK-LABEL: sil shared [noinline] @_T031specialize_same_type_constraint7doStuff1f1syx_q_tAA11FirstParentRzAA06SecondH0R_5ChildQy_AGRtzr0_lFAA08ConcretegH0VyAA0kJ0VG_AA0kiH0VyAMGTg5Tf4dd_n : $@convention(thin) () -> () {
+// CHECK: [[FIRST:%.*]] = function_ref @_T031specialize_same_type_constraint15takesFirstChild1tyx_tAA0fG0RzlF
 // CHECK: apply [[FIRST]]<ConcreteChild>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : FirstChild> (@in τ_0_0) -> ()
-// CHECK: [[SECOND:%.*]] = function_ref @_T031specialize_same_type_constraint16takesSecondChildyx1t_tAA0fG0RzlF
+// CHECK: [[SECOND:%.*]] = function_ref @_T031specialize_same_type_constraint16takesSecondChild1tyx_tAA0fG0RzlF
 // CHECK: apply [[SECOND]]<ConcreteChild>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : SecondChild> (@in τ_0_0) -> ()
 // CHECK: return
diff --git a/test/SILOptimizer/specialize_self_conforming.swift b/test/SILOptimizer/specialize_self_conforming.swift
index 1a0fbd4..6e25837 100644
--- a/test/SILOptimizer/specialize_self_conforming.swift
+++ b/test/SILOptimizer/specialize_self_conforming.swift
@@ -14,8 +14,8 @@
   takesP(t)
 }
 
-// CHECK-LABEL: sil hidden @_T026specialize_self_conforming16callsTakesPWithPyAA1P_pF : $@convention(thin) (@owned P) -> () {
-// CHECK: [[FN:%.*]] = function_ref @_T026specialize_self_conforming6takesPyxAA1PRzlF : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@owned τ_0_0) -> ()
+// CHECK-LABEL: sil hidden @_T026specialize_self_conforming16callsTakesPWithPyyAA1P_pF : $@convention(thin) (@owned P) -> () {
+// CHECK: [[FN:%.*]] = function_ref @_T026specialize_self_conforming6takesPyyxAA1PRzlF : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@owned τ_0_0) -> ()
 // CHECK: apply [[FN]]<P>(%0) : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@owned τ_0_0) -> ()
 // CHECK: return
 
diff --git a/test/SILOptimizer/specialize_unconditional_checked_cast.swift b/test/SILOptimizer/specialize_unconditional_checked_cast.swift
index 067805f..80c8342 100644
--- a/test/SILOptimizer/specialize_unconditional_checked_cast.swift
+++ b/test/SILOptimizer/specialize_unconditional_checked_cast.swift
@@ -366,7 +366,7 @@
 // value cast. We could do the promotion, but the optimizer would need
 // to insert the Optional unwrapping logic before the cast.
 //
-// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast15genericDownCastq_x_q_mtr0_lFAA1CCSg_AA1DCTg5 : $@convention(thin) (@owned Optional<C>, @thick D.Type) -> @owned D {
+// CHECK-LABEL: sil shared [noinline] @_T037specialize_unconditional_checked_cast15genericDownCastyq_x_q_mtr0_lFAA1CCSg_AA1DCTg5 : $@convention(thin) (@owned Optional<C>, @thick D.Type) -> @owned D {
 // CHECK: bb0(%0 : $Optional<C>, %1 : $@thick D.Type):
 // CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D
 // CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $Optional<C>
diff --git a/test/SILOptimizer/specialized_anyobject_conformance.swift b/test/SILOptimizer/specialized_anyobject_conformance.swift
index 287cb56..d7af486 100644
--- a/test/SILOptimizer/specialized_anyobject_conformance.swift
+++ b/test/SILOptimizer/specialized_anyobject_conformance.swift
@@ -16,7 +16,7 @@
   p.use(t!)
 }
 
-// CHECK-LABEL: sil @_T033specialized_anyobject_conformance7caller1yAA1P_p1p_tF : $@convention(thin) (@in P) -> ()
+// CHECK-LABEL: sil @_T033specialized_anyobject_conformance7caller11pyAA1P_p_tF : $@convention(thin) (@in P) -> ()
 public func caller1(p: P) {
   callee(C<Int32>(), p)
 }
diff --git a/test/SILOptimizer/super_init.swift b/test/SILOptimizer/super_init.swift
index ff1fa12..949092e 100644
--- a/test/SILOptimizer/super_init.swift
+++ b/test/SILOptimizer/super_init.swift
@@ -1,9 +1,9 @@
 // RUN: %target-swift-frontend -emit-sil %s | %FileCheck %s
 
-// CHECK-LABEL: sil hidden [noinline] @_T010super_init3FooCACSicfC : $@convention(method) (Int, @thick Foo.Type) -> @owned Foo
+// CHECK-LABEL: sil hidden [noinline] @_T010super_init3FooCyACSicfC : $@convention(method) (Int, @thick Foo.Type) -> @owned Foo
 // CHECK-NOT:     class_method
 // CHECK-NOT:     super_method
-// CHECK:         [[SUPER_INIT:%.*]] = function_ref @_T010super_init3FooCACSicfc
+// CHECK:         [[SUPER_INIT:%.*]] = function_ref @_T010super_init3FooCyACSicfc
 // CHECK:         [[NEW_SELF:%.*]] = apply [[SUPER_INIT]]
 
 // CHECK-LABEL: sil hidden [noinline] @_T010super_init3BarC{{[_0-9a-zA-Z]*}}fc
@@ -60,7 +60,7 @@
 
   // CHECK-LABEL: sil hidden [noinline] @_T010super_init4GoodCACycfc
   // CHECK-NOT:     super_method {{%[0-9]+}} : $Good, #Foo.init!initializer.1
-  // CHECK:         [[SUPER_INIT:%.*]] = function_ref @_T010super_init3FooCACSicfc
+  // CHECK:         [[SUPER_INIT:%.*]] = function_ref @_T010super_init3FooCyACSicfc
   // CHECK:         apply [[SUPER_INIT]]
   @inline(never)
   override init() {
diff --git a/test/SILOptimizer/super_method.swift b/test/SILOptimizer/super_method.swift
index 6390053..4722e5c 100644
--- a/test/SILOptimizer/super_method.swift
+++ b/test/SILOptimizer/super_method.swift
@@ -71,10 +71,10 @@
 }
 
 class ConcreteChild : GenericParent<String> {
-  // CHECK-LABEL: sil hidden @_T012super_method13ConcreteChildCACSS1a_tcfc : $@convention(method) (@owned String, @owned ConcreteChild) -> @owned ConcreteChild
+  // CHECK-LABEL: sil hidden @_T012super_method13ConcreteChildC1aACSS_tcfc : $@convention(method) (@owned String, @owned ConcreteChild) -> @owned ConcreteChild
   override init(a: String) {
     // CHECK-NOT: super_method {{%[0-9]+}} : $ConcreteChild, #GenericParent.init!initializer.1
-    // CHECK: [[INIT_FN_REF:%[0-9]+]] = function_ref @_T012super_method13GenericParentCACyxGx1a_tcfc : $@convention(method) <τ_0_0> (@in τ_0_0, @owned GenericParent<τ_0_0>) -> @owned GenericParent<τ_0_0>{{.*}} // user: %10
+    // CHECK: [[INIT_FN_REF:%[0-9]+]] = function_ref @_T012super_method13GenericParentC1aACyxGx_tcfc : $@convention(method) <τ_0_0> (@in τ_0_0, @owned GenericParent<τ_0_0>) -> @owned GenericParent<τ_0_0>{{.*}} // user: %10
     // CHECK: apply [[INIT_FN_REF]]
     super.init(a: a)
   }
diff --git a/test/SILOptimizer/swap_refcnt.swift b/test/SILOptimizer/swap_refcnt.swift
index 06cb59c..1251c5f 100644
--- a/test/SILOptimizer/swap_refcnt.swift
+++ b/test/SILOptimizer/swap_refcnt.swift
@@ -2,10 +2,10 @@
 
 // Make sure we can swap two values in an array without retaining anything along non-fatalerror paths.
 
-// CHECK-LABEL: sil @_T011swap_refcnt0A7ByIndexySays4Int8VGz1A_Si1xSi1ytF : $@convention(thin) (@inout Array<Int8>, Int, Int) -> () {
+// CHECK-LABEL: sil @_T011swap_refcnt0A7ByIndex1A1x1yySays4Int8VGz_S2itF : $@convention(thin) (@inout Array<Int8>, Int, Int) -> () {
 // CHECK-NOT: strong_retain
 // CHECK-NOT: strong_release
-// CHECK: } // end sil function '_T011swap_refcnt0A7ByIndexySays4Int8VGz1A_Si1xSi1ytF'
+// CHECK: } // end sil function '_T011swap_refcnt0A7ByIndex1A1x1yySays4Int8VGz_S2itF'
 public func swapByIndex(A: inout [Int8], x : Int, y : Int) {
   swap(&A[x],&A[y])
 }
diff --git a/test/SILOptimizer/unreachable_code.swift b/test/SILOptimizer/unreachable_code.swift
index 9104645..98372de 100644
--- a/test/SILOptimizer/unreachable_code.swift
+++ b/test/SILOptimizer/unreachable_code.swift
@@ -208,7 +208,7 @@
       str = "A"
     case .B:
       str = "B"
-    default:    // expected-warning {{default will never be executed}}
+    default: 
       str = "unknown"  // Should not be rejected.
     }
     return str
diff --git a/test/Sema/enum_equatable_conditional.swift b/test/Sema/enum_equatable_conditional.swift
index eab8d00..d862dd5 100644
--- a/test/Sema/enum_equatable_conditional.swift
+++ b/test/Sema/enum_equatable_conditional.swift
@@ -1,4 +1,4 @@
-// RUN: %target-typecheck-verify-swift -enable-experimental-conditional-conformances
+// RUN: %target-typecheck-verify-swift
 
 struct NotEquatable { }
 
diff --git a/test/Sema/exhaustive_switch.swift b/test/Sema/exhaustive_switch.swift
index 83bc8c8..c336342 100644
--- a/test/Sema/exhaustive_switch.swift
+++ b/test/Sema/exhaustive_switch.swift
@@ -444,7 +444,7 @@
 }
 
 func quiteBigEnough() -> Bool {
-  switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{switch must be exhaustive}}
+  switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{analysis of uncovered switch statement is too complex to perform in a reasonable amount of time}}
   // expected-note@-1 {{do you want to add a default clause?}}
   case (.case0, .case0): return true
   case (.case1, .case1): return true
@@ -460,8 +460,7 @@
   case (.case11, .case11): return true
   }
 
-  // No diagnostic
-  switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{switch must be exhaustive}}
+  switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{analysis of uncovered switch statement is too complex to perform in a reasonable amount of time}}
   // expected-note@-1 {{do you want to add a default clause?}}
   case (.case0, _): return true
   case (.case1, _): return true
@@ -477,8 +476,9 @@
   }
 
 
-  // No diagnostic
+  // expected-error@+1 {{analysis of uncovered switch statement is too complex to perform in a reasonable amount of time}}
   switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
+  // expected-note@-1 {{do you want to add a default clause?}}
   case (.case0, _): return true
   case (.case1, _): return true
   case (.case2, _): return true
@@ -493,8 +493,9 @@
   case (.case11, _): return true
   }
 
-  // No diagnostic
+  // expected-error@+1 {{analysis of uncovered switch statement is too complex to perform in a reasonable amount of time}}
   switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
+  // expected-note@-1 {{do you want to add a default clause?}}
   case (_, .case0): return true
   case (_, .case1): return true
   case (_, .case2): return true
@@ -509,13 +510,14 @@
   case (_, .case11): return true
   }
 
-  // No diagnostic
+  // No diagnostic 
   switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
   case (_, _): return true
   }
 
-  // No diagnostic
+  // expected-error@+1 {{analysis of uncovered switch statement is too complex to perform in a reasonable amount of time}} 
   switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
+  // expected-note@-1 {{do you want to add a default clause?}}
   case (.case0, .case0): return true
   case (.case1, .case1): return true
   case (.case2, .case2): return true
@@ -523,7 +525,7 @@
   case _: return true
   }
   
-  // No diagnostic
+  // No diagnostic 
   switch ContainsOverlyLargeEnum.one(.case0) {
   case .one: return true
   case .two: return true
@@ -559,6 +561,28 @@
   }
 }
 
+// SR-6316: Size heuristic is insufficient to catch space covering when the
+// covered space size is greater than or equal to the master space size.
+func largeSpaceMatch(_ x: Bool) {
+  switch (x, (x, x, x, x), (x, x, x, x)) { // expected-error {{analysis of uncovered switch statement is too complex to perform in a reasonable amount of time}}
+  // expected-note@-1 {{do you want to add a default clause?}}
+  case (true, (_, _, _, _), (_, true, true, _)):
+    break
+  case (true, (_, _, _, _), (_, _, false, _)):
+    break
+  case (_, (_, true, true, _), (_, _, false, _)):
+    break
+  case (_, (_, _, false, _), (_, true, true, _)):
+    break
+  case (_, (_, true, true, _), (_, true, true, _)):
+    break
+  case (_, (_, _, false, _), (_, _, false, _)):
+    break
+  case (_, (false, false, false, false), (_, _, _, _)):
+    break
+  }
+}
+
 func diagnoseDuplicateLiterals() {
   let str = "def"
   let int = 2
diff --git a/test/Sema/fixed_ambiguities/rdar27033993.swift b/test/Sema/fixed_ambiguities/rdar27033993.swift
index f922cff..22a21ef 100644
--- a/test/Sema/fixed_ambiguities/rdar27033993.swift
+++ b/test/Sema/fixed_ambiguities/rdar27033993.swift
@@ -4,7 +4,7 @@
 let arr: [(S, Int)] = []
 let _: [S] = arr.sorted {
     $0.1 < $1.1
-// CHECK: function_ref @_T0s10CollectionPsE6prefix11SubSequenceQzSiF : $@convention(method) <τ_0_0 where τ_0_0 : Collection> (Int, @in_guaranteed τ_0_0) -> @out τ_0_0.SubSequence
+// CHECK: function_ref @_T0s10CollectionPsE6prefixy11SubSequenceQzSiF : $@convention(method) <τ_0_0 where τ_0_0 : Collection> (Int, @in_guaranteed τ_0_0) -> @out τ_0_0.SubSequence
 }.prefix(1).map {
     return $0.0
 }
diff --git a/test/Sema/fixed_ambiguities/rdar27198177.swift b/test/Sema/fixed_ambiguities/rdar27198177.swift
index 6a9c77e..e5050b5 100644
--- a/test/Sema/fixed_ambiguities/rdar27198177.swift
+++ b/test/Sema/fixed_ambiguities/rdar27198177.swift
@@ -2,5 +2,5 @@
 
 let arr = ["A", "B", "C"]
 let lazy: LazyMapCollection = arr.lazy.map { $0 }
-// CHECK: function_ref @_T0s22LazyCollectionProtocolPsE6filters0a6FilterB0Vy8ElementsQzGSb7ElementQzcF : $@convention(method) <τ_0_0 where τ_0_0 : LazyCollectionProtocol> (@owned @callee_guaranteed (@in τ_0_0.Element) -> Bool, @in_guaranteed τ_0_0) -> @out LazyFilterCollection<τ_0_0.Elements>
+// CHECK: function_ref @_T0s22LazyCollectionProtocolPsE6filterys0a6FilterB0Vy8ElementsQzGSb7ElementQzcF : $@convention(method) <τ_0_0 where τ_0_0 : LazyCollectionProtocol> (@owned @callee_guaranteed (@in τ_0_0.Element) -> Bool, @in_guaranteed τ_0_0) -> @out LazyFilterCollection<τ_0_0.Elements>
 _ = lazy.filter { $0 > "A" }.count
diff --git a/test/Sema/fixed_ambiguities/rdar33142386.swift b/test/Sema/fixed_ambiguities/rdar33142386.swift
index 5153f89..d711218 100644
--- a/test/Sema/fixed_ambiguities/rdar33142386.swift
+++ b/test/Sema/fixed_ambiguities/rdar33142386.swift
@@ -1,5 +1,5 @@
 // RUN: %target-swift-frontend -emit-sil -verify %s -swift-version 4 | %FileCheck %s
 
 let x: String = "ultimate question"
-// CHECK: function_ref @_T0s26RangeReplaceableCollectionPsE6filterxSb7ElementQzKcKF : $@convention(method) <τ_0_0 where τ_0_0 : RangeReplaceableCollection> (@owned @noescape @callee_guaranteed (@in τ_0_0.Element) -> (Bool, @error Error), @in_guaranteed τ_0_0) -> (@out τ_0_0, @error Error)
+// CHECK: function_ref @_T0s26RangeReplaceableCollectionPsE6filteryxSb7ElementQzKcKF : $@convention(method) <τ_0_0 where τ_0_0 : RangeReplaceableCollection> (@owned @noescape @callee_guaranteed (@in τ_0_0.Element) -> (Bool, @error Error), @in_guaranteed τ_0_0) -> (@out τ_0_0, @error Error)
 _ = x.filter({ $0 == " " }).count < 3
diff --git a/test/Sema/fixed_ambiguities/rdar35623181.swift b/test/Sema/fixed_ambiguities/rdar35623181.swift
index 615aae2..e0acf03 100644
--- a/test/Sema/fixed_ambiguities/rdar35623181.swift
+++ b/test/Sema/fixed_ambiguities/rdar35623181.swift
@@ -2,7 +2,7 @@
 
 extension Sequence where Element == String {
   func record() -> String {
-    // CHECK: function_ref @_T0s20LazySequenceProtocolPsE3maps0a3MapB0Vy8ElementsQzqd__Gqd__7ElementQzclF : $@convention(method) <τ_0_0 where τ_0_0 : LazySequenceProtocol><τ_1_0> (@owned @callee_guaranteed (@in τ_0_0.Element) -> @out τ_1_0, @in_guaranteed τ_0_0) -> @out LazyMapSequence<τ_0_0.Elements, τ_1_0
+    // CHECK: function_ref @_T0s20LazySequenceProtocolPsE3mapys0a3MapB0Vy8ElementsQzqd__Gqd__7ElementQzclF : $@convention(method) <τ_0_0 where τ_0_0 : LazySequenceProtocol><τ_1_0> (@owned @callee_guaranteed (@in τ_0_0.Element) -> @out τ_1_0, @in_guaranteed τ_0_0) -> @out LazyMapSequence<τ_0_0.Elements, τ_1_0
     return lazy.map({ $0 }).joined(separator: ",")
   }
 }
diff --git a/test/Sema/fixed_ambiguities/rdar35625339.swift b/test/Sema/fixed_ambiguities/rdar35625339.swift
index 9cd2bee..94e781f 100644
--- a/test/Sema/fixed_ambiguities/rdar35625339.swift
+++ b/test/Sema/fixed_ambiguities/rdar35625339.swift
@@ -1,4 +1,4 @@
 // RUN: %target-swift-frontend -emit-sil -verify %s | %FileCheck %s
 let arr = Array(10...20)
-// CHECK: function_ref @_T0s10CollectionPsE6prefix11SubSequenceQzSiF : $@convention(method) <τ_0_0 where τ_0_0 : Collection> (Int, @in_guaranteed τ_0_0) -> @out τ_0_0.SubSequence
+// CHECK: function_ref @_T0s10CollectionPsE6prefixy11SubSequenceQzSiF : $@convention(method) <τ_0_0 where τ_0_0 : Collection> (Int, @in_guaranteed τ_0_0) -> @out τ_0_0.SubSequence
 arr.prefix(3).forEach { (v: Int) in }
diff --git a/test/Sema/fixed_ambiguities/rdar35625473.swift b/test/Sema/fixed_ambiguities/rdar35625473.swift
index d921e19..46051ad 100644
--- a/test/Sema/fixed_ambiguities/rdar35625473.swift
+++ b/test/Sema/fixed_ambiguities/rdar35625473.swift
@@ -1,4 +1,4 @@
 // RUN: %target-swift-frontend -emit-sil -verify %s | %FileCheck %s
 
-// CHECK: function_ref @_T0s10CollectionPsE9dropFirst11SubSequenceQzSiF : $@convention(method) <τ_0_0 where τ_0_0 : Collection> (Int, @in_guaranteed τ_0_0) -> @out τ_0_0.SubSequence
+// CHECK: function_ref @_T0s10CollectionPsE9dropFirsty11SubSequenceQzSiF : $@convention(method) <τ_0_0 where τ_0_0 : Collection> (Int, @in_guaranteed τ_0_0) -> @out τ_0_0.SubSequence
 _ = [1, 2, 3].dropFirst(1).dropFirst(1)
diff --git a/test/Serialization/Inputs/def_basic.sil b/test/Serialization/Inputs/def_basic.sil
index 51c898c..ebf60d1 100644
--- a/test/Serialization/Inputs/def_basic.sil
+++ b/test/Serialization/Inputs/def_basic.sil
@@ -17,8 +17,8 @@
 sil [serialized] @globalinit_func0 : $@convention(thin) () -> ()
 
 // We should not serialize this.
-// CHECK-NOT: sil public_external @_T018lazy_global_access4TypeV10staticProp3IntsFa : $@convention(thin) () -> Builtin.RawPointer {
-sil @_T018lazy_global_access4TypeV10staticProp3IntsFa : $@convention(thin) () -> Builtin.RawPointer {
+// CHECK-NOT: sil public_external @_TV18lazy_global_access4Type10staticPropySia : $@convention(thin) () -> Builtin.RawPointer {
+sil @_TV18lazy_global_access4Type10staticPropySia : $@convention(thin) () -> Builtin.RawPointer {
 bb0:
   %1 = global_addr @globalinit_token0 : $*Builtin.Word
   %2 = address_to_pointer %1 : $*Builtin.Word to $Builtin.RawPointer
@@ -30,8 +30,8 @@
 }
 
 // This references a public global so we *SHOULD* deserialize this.
-// CHECK-LABEL: sil public_external [serialized] @_T018lazy_global_access4TypeV10staticProp3IntsFa_public : $@convention(thin) () -> Builtin.RawPointer {
-sil [serialized] @_T018lazy_global_access4TypeV10staticProp3IntsFa_public : $@convention(thin) () -> Builtin.RawPointer {
+// CHECK-LABEL: sil public_external [serialized] @_TV18lazy_global_access4Type10staticPropySia_public : $@convention(thin) () -> Builtin.RawPointer {
+sil [serialized] @_TV18lazy_global_access4Type10staticPropySia_public : $@convention(thin) () -> Builtin.RawPointer {
 bb0:
   // CHECK: alloc_global @public_global
   alloc_global @public_global
@@ -134,8 +134,8 @@
 
 sil [serialized] @return_constant : $@convention(thin) () -> Int {  // CHECK-LABEL: @return_constant
 bb0:                                         // CHECK: bb0:
-  // CHECK: function_ref @_T0Si25convertFromIntegerLiteralSiBi64_3val_tcSimF : $@convention(thin) (Builtin.Word, @thin Int.Type) -> Int
-  %1 = function_ref @_T0Si25convertFromIntegerLiteralSiBi64_3val_tcSimF : $@convention(thin) (Builtin.Word, @thin Int.Type) -> Int
+  // CHECK: function_ref @_T0Si25convertFromIntegerLiteralySiBi64_3val_tcSimF : $@convention(thin) (Builtin.Word, @thin Int.Type) -> Int
+  %1 = function_ref @_T0Si25convertFromIntegerLiteralySiBi64_3val_tcSimF : $@convention(thin) (Builtin.Word, @thin Int.Type) -> Int
 
   // CHECK: metatype $@thin Int.Type
   %2 = metatype $@thin Int.Type
@@ -149,12 +149,12 @@
   return %4 : $Int
 }
 
-sil [serialized] @_T0Si25convertFromIntegerLiteralSiBi64_3val_tcSimF : $@convention(thin) (Builtin.Word, @thin Int.Type) -> Int
+sil [serialized] @_T0Si25convertFromIntegerLiteralySiBi64_3val_tcSimF : $@convention(thin) (Builtin.Word, @thin Int.Type) -> Int
 
 // Parse SIL generated from the following swift program:
 // func x(_ a : Bool) -> Int { if a { return 4 } else {return 5} }
-sil [serialized] @_T0Sb13getLogicValueBi1_ycSbzF : $@convention(method) (@inout Bool) -> Builtin.Int1
-sil [serialized] @_T0Si33_convertFromBuiltinIntegerLiteralSiBi128_3val_tcSimF : $@convention(thin) (Builtin.Int128, @thin Int.Type) -> Int
+sil [serialized] @_T0Sb13getLogicValueyBi1_ycSbzF : $@convention(method) (@inout Bool) -> Builtin.Int1
+sil [serialized] @_T0Si33_convertFromBuiltinIntegerLiteralySiBi128_3val_tcSimF : $@convention(thin) (Builtin.Int128, @thin Int.Type) -> Int
 
 
 protocol P {
@@ -251,7 +251,7 @@
 protocol Bendable { }
 
 // CHECK-LABEL: $@convention(thin) (@in Bendable & Runcible) -> @out Runcible
-sil [serialized] @_T04todo18erasure_from_protoAA8Runcible_pAaC_AA8Bendablep1x_tF : $@convention(thin) (@in Bendable & Runcible) -> (@out Runcible) {
+sil [serialized] @_T04todo18erasure_from_proto1xAA8Runcible_pAaD_AA8Bendablep_tF : $@convention(thin) (@in Bendable & Runcible) -> (@out Runcible) {
 bb0(%0 : $*Runcible, %1 : $*Bendable & Runcible):
   // CHECK: alloc_box
   %2 = alloc_box $<τ_0_0> { var τ_0_0 } <(Bendable & Runcible)>
@@ -276,8 +276,8 @@
   func classBoundMethod()
 }
 
-// CHECK-LABEL: @_T04todo18class_bound_methodyAA10ClassBound_p1x_tF : $@convention(thin) (@owned ClassBound) -> ()
-sil [serialized] @_T04todo18class_bound_methodyAA10ClassBound_p1x_tF : $@convention(thin) (@owned ClassBound) -> () {
+// CHECK-LABEL: @_T04todo18class_bound_method1xyAA10ClassBound_p_tF : $@convention(thin) (@owned ClassBound) -> ()
+sil [serialized] @_T04todo18class_bound_method1xyAA10ClassBound_p_tF : $@convention(thin) (@owned ClassBound) -> () {
 bb0(%0 : $ClassBound):
   %1 = alloc_box $<τ_0_0> { var τ_0_0 } <ClassBound>
   %1a = project_box %1 : $<τ_0_0> { var τ_0_0 } <ClassBound>, 0
@@ -297,7 +297,7 @@
 struct Val {
 }
 
-//sil @_T04todo3ValVACycACmcfC : $@convention(thin) (@thin Val.Type) -> Val {
+//sil @_T04todo3ValVyACycACmcfC : $@convention(thin) (@thin Val.Type) -> Val {
 //bb0(%0 : $@thin Val.Type):
   //%1 = alloc_stack $Val
   //%3 = load %1#1 : $*Val
@@ -311,16 +311,16 @@
   var b:Val
 }
 
-// CHECK-LABEL: @_T06struct5AlephVAcA3RefC1a_AA3ValV1btcACmcfC : $@convention(thin) (Ref, Val, @thin Aleph.Type) -> Aleph
-sil [serialized] @_T06struct5AlephVAcA3RefC1a_AA3ValV1btcACmcfC : $@convention(thin) (Ref, Val, @thin Aleph.Type) -> Aleph {
+// CHECK-LABEL: @_T06struct5AlephVyAcA3RefC1a_AA3ValV1btcACmcfC : $@convention(thin) (Ref, Val, @thin Aleph.Type) -> Aleph
+sil [serialized] @_T06struct5AlephVyAcA3RefC1a_AA3ValV1btcACmcfC : $@convention(thin) (Ref, Val, @thin Aleph.Type) -> Aleph {
 bb0(%0 : $Ref, %1 : $Val, %2 : $@thin Aleph.Type):
   // CHECK: struct $Aleph ({{%.*}} : $Ref, {{%.*}} : $Val)
   %3 = struct $Aleph (%0 : $Ref, %1 : $Val)
   return %3 : $Aleph  // CHECK: return
 }
 
-// CHECK-LABEL: @_T06struct5AlephVACycACmcfC : $@convention(thin) (@thin Aleph.Type) -> Aleph
-sil [serialized] @_T06struct5AlephVACycACmcfC : $@convention(thin) (@thin Aleph.Type) -> Aleph {
+// CHECK-LABEL: @_T06struct5AlephVyACycACmcfC : $@convention(thin) (@thin Aleph.Type) -> Aleph
+sil [serialized] @_T06struct5AlephVyACycACmcfC : $@convention(thin) (@thin Aleph.Type) -> Aleph {
 bb0(%0 : $@thin Aleph.Type):
   %1 = tuple ()
   %2 = alloc_box $<τ_0_0> { var τ_0_0 } <Aleph>       // CHECK: alloc_box
@@ -385,11 +385,11 @@
   return %t : $()
 }
 
-sil [serialized] @_T05tuple5floatySf1x_tF : $@convention(thin) (Float32) -> ()
+sil [serialized] @_T05tuple5float1xySf_tF : $@convention(thin) (Float32) -> ()
 sil [serialized] @_T05tupleAASi_SftyF : $@convention(thin) () -> (Int, Float32)
 
-// CHECK-LABEL: @_T05tuple0A8_elementySi_Sft1x_tF : $@convention(thin) (Int, Float) -> ()
-sil [serialized] @_T05tuple0A8_elementySi_Sft1x_tF : $@convention(thin) (Int, Float) -> () {
+// CHECK-LABEL: @_T05tuple0A8_element1xySi_Sft_tF : $@convention(thin) (Int, Float) -> ()
+sil [serialized] @_T05tuple0A8_element1xySi_Sft_tF : $@convention(thin) (Int, Float) -> () {
 bb0(%0 : $Int, %1 : $Float32):
   %2 = alloc_box $<τ_0_0> { var τ_0_0 } <(Int, Float32)>
   %2a = project_box %2 : $<τ_0_0> { var τ_0_0 } <(Int, Float32)>, 0
@@ -406,7 +406,7 @@
   // CHECK: apply
   %15 = apply %14() : $@convention(thin) () -> (Int, Float32)
   // CHECK: function_ref
-  %19 = function_ref @_T05tuple5floatySf1x_tF : $@convention(thin) (Float32) -> ()
+  %19 = function_ref @_T05tuple5float1xySf_tF : $@convention(thin) (Float32) -> ()
   // CHECK: tuple_extract {{%.*}} : $(Int, Float), 1
   %17 = tuple_extract %15 : $(Int, Float), 1
   // CHECK: apply
@@ -421,8 +421,8 @@
   init()
 }
 
-// CHECK-LABEL: @_T03ref1CC3fooySi1x_tcACF : $@convention(method) (Int, @guaranteed M) -> ()
-sil [serialized] @_T03ref1CC3fooySi1x_tcACF : $@convention(method) (Int, @guaranteed M) -> () {
+// CHECK-LABEL: @_T03ref1CC3fooyySi1x_tcACF : $@convention(method) (Int, @guaranteed M) -> ()
+sil [serialized] @_T03ref1CC3fooyySi1x_tcACF : $@convention(method) (Int, @guaranteed M) -> () {
 bb0(%0 : $Int, %1 : $M):
   %2 = alloc_box $<τ_0_0> { var τ_0_0 } <Int>
   %2a = project_box %2 : $<τ_0_0> { var τ_0_0 } <Int>, 0
@@ -446,8 +446,8 @@
 class B { }
 class E : B { }
 
-// CHECK-LABEL: @_T04null3isaSbAA1BC1b_tF : $@convention(thin) (B) -> Builtin.Int1
-sil [serialized] @_T04null3isaSbAA1BC1b_tF : $@convention(thin) (B) -> Builtin.Int1 {
+// CHECK-LABEL: @_T04null3isa1bSbAA1BC_tF : $@convention(thin) (B) -> Builtin.Int1
+sil [serialized] @_T04null3isa1bSbAA1BC_tF : $@convention(thin) (B) -> Builtin.Int1 {
 bb0(%0 : $B):
   %1 = alloc_box $<τ_0_0> { var τ_0_0 } <B>
   %1a = project_box %1 : $<τ_0_0> { var τ_0_0 } <B>, 0
@@ -469,11 +469,11 @@
 
 sil [serialized] @_T07literal8literalsyyF : $@convention(thin) () -> ()
 
-sil [serialized] @_T0Sd31_convertFromBuiltinFloatLiteralSdBf64_5value_tcSdmF : $@convention(thin) (Builtin.FPIEEE64, @thin Float64.Type) -> Float64
-sil [serialized] @_T0SS32_convertFromBuiltinStringLiteralSSBp5value_Bi64_17utf8CodeUnitCountBi1_7isASCIItcSSmF : $@convention(thin) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> String
+sil [serialized] @_T0Sd31_convertFromBuiltinFloatLiteralySdBf64_5value_tcSdmF : $@convention(thin) (Builtin.FPIEEE64, @thin Float64.Type) -> Float64
+sil [serialized] @_T0SS32_convertFromBuiltinStringLiteralySSBp5value_Bi64_17utf8CodeUnitCountBi1_7isASCIItcSSmF : $@convention(thin) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> String
 
-// CHECK-LABEL: @_T05index5gep64BpBp1p_Bi64_1itF : $@convention(thin) (Builtin.RawPointer, Builtin.Word) -> Builtin.RawPointer {
-sil [serialized] @_T05index5gep64BpBp1p_Bi64_1itF : $@convention(thin) (Builtin.RawPointer, Builtin.Word) -> Builtin.RawPointer {
+// CHECK-LABEL: @_T05index5gep641p1iBpBp_Bi64_tF : $@convention(thin) (Builtin.RawPointer, Builtin.Word) -> Builtin.RawPointer {
+sil [serialized] @_T05index5gep641p1iBpBp_Bi64_tF : $@convention(thin) (Builtin.RawPointer, Builtin.Word) -> Builtin.RawPointer {
 bb0(%0 : $Builtin.RawPointer, %1 : $Builtin.Word):
   %2 = alloc_box $<τ_0_0> { var τ_0_0 } <Builtin.RawPointer>
   %2a = project_box %2 : $<τ_0_0> { var τ_0_0 } <Builtin.RawPointer>, 0
@@ -896,7 +896,7 @@
 // CHECK-LABEL: [noinline] @noinline_callee
 sil [serialized] [noinline] @noinline_callee : $@convention(thin) () -> Int {
 bb0:
-  %0 = function_ref @_T0Si33_convertFromBuiltinIntegerLiteralSiBi2048_cSimF : $@convention(thin) (Builtin.Int2048, @thin Int.Type) -> Int
+  %0 = function_ref @_T0Si33_convertFromBuiltinIntegerLiteralySiBi2048_cSimF : $@convention(thin) (Builtin.Int2048, @thin Int.Type) -> Int
   %1 = metatype $@thin Int.Type
   %2 = integer_literal $Builtin.Int2048, 0
   %3 = apply %0(%2, %1) : $@convention(thin) (Builtin.Int2048, @thin Int.Type) -> Int
@@ -905,13 +905,13 @@
 // CHECK-LABEL: [always_inline] @always_inline_callee
 sil [serialized] [always_inline] @always_inline_callee : $@convention(thin) () -> Int {
 bb0:
-  %0 = function_ref @_T0Si33_convertFromBuiltinIntegerLiteralSiBi2048_cSimF : $@convention(thin) (Builtin.Int2048, @thin Int.Type) -> Int
+  %0 = function_ref @_T0Si33_convertFromBuiltinIntegerLiteralySiBi2048_cSimF : $@convention(thin) (Builtin.Int2048, @thin Int.Type) -> Int
   %1 = metatype $@thin Int.Type
   %2 = integer_literal $Builtin.Int2048, 0
   %3 = apply %0(%2, %1) : $@convention(thin) (Builtin.Int2048, @thin Int.Type) -> Int
   return %3 : $Int
 }
-sil [serialized] [transparent] @_T0Si33_convertFromBuiltinIntegerLiteralSiBi2048_cSimF : $@convention(thin) (Builtin.Int2048, @thin Int.Type) -> Int
+sil [serialized] [transparent] @_T0Si33_convertFromBuiltinIntegerLiteralySiBi2048_cSimF : $@convention(thin) (Builtin.Int2048, @thin Int.Type) -> Int
 
 // CHECK-LABEL: [_semantics "foo"] @test_semantics : $@convention(thin) () -> ()
 sil [serialized] [_semantics "foo"] @test_semantics : $@convention(thin) () -> () {
@@ -1253,6 +1253,31 @@
   return %1 : $()
 }
 
+public class WeakUnownedTest {
+  @sil_stored public unowned var unownedVal: @sil_unowned AnyObject { get set }
+  @sil_stored public weak var weakVal: @sil_weak AnyObject? { get set }
+  public init(protoVal: AnyObject)
+  deinit
+}
+
+// CHECK-LABEL: sil public_external [serialized] @weak_unowned : $@convention(thin) (@owned WeakUnownedTest, @owned AnyObject) -> ()
+sil [serialized] @weak_unowned : $@convention(thin) (@owned WeakUnownedTest, @owned AnyObject) -> () {
+bb0(%0 : $WeakUnownedTest, %1 : $AnyObject):
+  %2 = ref_element_addr %0 : $WeakUnownedTest, #WeakUnownedTest.unownedVal
+  // CHECK: store_unowned
+  store_unowned %1 to %2 : $*@sil_unowned AnyObject
+
+  %3 = enum $Optional<AnyObject>, #Optional.some!enumelt.1, %1 : $AnyObject
+  %4 = ref_element_addr %0 : $WeakUnownedTest, #WeakUnownedTest.weakVal
+  // CHECK: store_weak
+  store_weak %3 to %4 : $*@sil_weak AnyObject?
+
+  %r = tuple ()
+
+  // CHECK: return
+  return %r : $()
+}
+
 public class Foo {
   subscript (x: Int, y: Int) -> Int32 { get set }
   var x: Int
@@ -1324,7 +1349,7 @@
   func requiredMethod()
 }
 
-sil [serialized] @_T014witness_tables15ConformingAssocV14requiredMethodyycACF : $@convention(method) (@guaranteed ConformingAssoc) -> () {
+sil [serialized] @_T014witness_tables15ConformingAssocV14requiredMethodyyycACF : $@convention(method) (@guaranteed ConformingAssoc) -> () {
 bb0(%0 : $ConformingAssoc):
   debug_value %0 : $ConformingAssoc
   %2 = tuple ()
@@ -1334,7 +1359,7 @@
 sil [serialized] @_TTWV14witness_tables15ConformingAssocS_9AssocReqtS_FS1_14requiredMethodU_fRQPS1_FT_T_ : $@convention(witness_method: AssocReqt) (@inout ConformingAssoc) -> () {
 bb0(%0 : $*ConformingAssoc):
   %1 = load %0 : $*ConformingAssoc
-  %2 = function_ref @_T014witness_tables15ConformingAssocV14requiredMethodyycACF : $@convention(method) (@guaranteed ConformingAssoc) -> ()
+  %2 = function_ref @_T014witness_tables15ConformingAssocV14requiredMethodyyycACF : $@convention(method) (@guaranteed ConformingAssoc) -> ()
   %3 = apply %2(%1) : $@convention(method) (@guaranteed ConformingAssoc) -> ()
   return %3 : $()
 }
@@ -1384,8 +1409,8 @@
 
 sil [serialized] [transparent] @_T09def_basic13serialize_allyyF : $@convention(thin) () -> () {
 bb0:
-  %0 = function_ref @_T018lazy_global_access4TypeV10staticProp3IntsFa_public : $@convention(thin) () -> Builtin.RawPointer
-  %1 = function_ref @_T018lazy_global_access4TypeV10staticProp3IntsFa : $@convention(thin) () -> Builtin.RawPointer
+  %0 = function_ref @_TV18lazy_global_access4Type10staticPropySia_public : $@convention(thin) () -> Builtin.RawPointer
+  %1 = function_ref @_TV18lazy_global_access4Type10staticPropySia : $@convention(thin) () -> Builtin.RawPointer
   %2 = function_ref @test1 : $@convention(thin) () -> ()
   %4 = function_ref @test2 : $@convention(thin) (Int) -> ()
   %6 = function_ref @named_tuple : $@convention(thin) () -> (Builtin.Word, Builtin.Word)
@@ -1394,23 +1419,23 @@
   %13 = function_ref @return_constant : $@convention(thin) () -> Int
   %23 = function_ref @existentials : $@convention(thin) (@in P) -> ()
   %25 = function_ref @classes : $@convention(thin) () -> ()
-  %27 = function_ref @_T04todo18erasure_from_protoAA8Runcible_pAaC_AA8Bendablep1x_tF : $@convention(thin) (@in Bendable & Runcible) -> @out Runcible
-  %29 = function_ref @_T04todo18class_bound_methodyAA10ClassBound_p1x_tF : $@convention(thin) (@owned ClassBound) -> ()
-  %31 = function_ref @_T06struct5AlephVAcA3RefC1a_AA3ValV1btcACmcfC : $@convention(thin) (Ref, Val, @thin Aleph.Type) -> Aleph
-  %33 = function_ref @_T06struct5AlephVACycACmcfC : $@convention(thin) (@thin Aleph.Type) -> Aleph
+  %27 = function_ref @_T04todo18erasure_from_proto1xAA8Runcible_pAaD_AA8Bendablep_tF : $@convention(thin) (@in Bendable & Runcible) -> @out Runcible
+  %29 = function_ref @_T04todo18class_bound_method1xyAA10ClassBound_p_tF : $@convention(thin) (@owned ClassBound) -> ()
+  %31 = function_ref @_T06struct5AlephVyAcA3RefC1a_AA3ValV1btcACmcfC : $@convention(thin) (Ref, Val, @thin Aleph.Type) -> Aleph
+  %33 = function_ref @_T06struct5AlephVyACycACmcfC : $@convention(thin) (@thin Aleph.Type) -> Aleph
   %35 = function_ref @test_union_empty_case : $@convention(thin) () -> Beth
   %37 = function_ref @test_union_data_case : $@convention(thin) Int -> Beth
   %39 = function_ref @test_union_addr_empty_case : $@convention(thin) () -> @out Gimel
   %41 = function_ref @test_union_addr_data_case : $@convention(thin) (@in Q) -> @out Gimel
-  %43 = function_ref @_T05tuple5floatySf1x_tF : $@convention(thin) (Float32) -> ()
+  %43 = function_ref @_T05tuple5float1xySf_tF : $@convention(thin) (Float32) -> ()
   %45 = function_ref @_T05tupleAASi_SftyF : $@convention(thin) () -> (Int, Float32)
-  %47 = function_ref @_T05tuple0A8_elementySi_Sft1x_tF : $@convention(thin) (Int, Float32) -> ()
-  %49 = function_ref @_T03ref1CC3fooySi1x_tcACF : $@convention(method) (Int, @guaranteed M) -> ()
-  %51 = function_ref @_T04null3isaSbAA1BC1b_tF : $@convention(thin) (B) -> Builtin.Int1
-  %53 = function_ref @_T0Sd31_convertFromBuiltinFloatLiteralSdBf64_5value_tcSdmF : $@convention(thin) (Builtin.FPIEEE64, @thin Float64.Type) -> Float64
-  %55 = function_ref @_T0SS32_convertFromBuiltinStringLiteralSSBp5value_Bi64_17utf8CodeUnitCountBi1_7isASCIItcSSmF : $@convention(thin) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> String
+  %47 = function_ref @_T05tuple0A8_element1xySi_Sft_tF : $@convention(thin) (Int, Float32) -> ()
+  %49 = function_ref @_T03ref1CC3fooyySi1x_tcACF : $@convention(method) (Int, @guaranteed M) -> ()
+  %51 = function_ref @_T04null3isa1bSbAA1BC_tF : $@convention(thin) (B) -> Builtin.Int1
+  %53 = function_ref @_T0Sd31_convertFromBuiltinFloatLiteralySdBf64_5value_tcSdmF : $@convention(thin) (Builtin.FPIEEE64, @thin Float64.Type) -> Float64
+  %55 = function_ref @_T0SS32_convertFromBuiltinStringLiteralySSBp5value_Bi64_17utf8CodeUnitCountBi1_7isASCIItcSSmF : $@convention(thin) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thin String.Type) -> String
   %57 = function_ref @_T07literal8literalsyyF : $@convention(thin) () -> ()
-  %59 = function_ref @_T05index5gep64BpBp1p_Bi64_1itF : $@convention(thin) (Builtin.RawPointer, Builtin.Word) -> Builtin.RawPointer
+  %59 = function_ref @_T05index5gep641p1iBpBp_Bi64_tF : $@convention(thin) (Builtin.RawPointer, Builtin.Word) -> Builtin.RawPointer
   %60 = function_ref @global_code : $@convention(thin) () -> ()
   %61 = function_ref @global_object : $@convention(thin) () -> GlobalObject
   %63 = function_ref @test_class_metatype : $@convention(thin) (SomeClass, SomeSubclass) -> (@thick SomeClass.Type, @thick SomeClass.Type)
@@ -1467,6 +1492,7 @@
   %150 = function_ref @bridge_object : $@convention(thin) (@owned Class1, Builtin.Word) -> ()
   %151 = function_ref @a_reabstraction_thunk: $@convention(thin) () -> ()
   %152 = function_ref @a_regular_thunk: $@convention(thin) () -> ()
+  %153 = function_ref @weak_unowned: $@convention(thin) (@owned WeakUnownedTest, @owned AnyObject) -> ()
 
   %r = tuple ()
   return %r : $()
diff --git a/test/Serialization/Recovery/typedefs.swift b/test/Serialization/Recovery/typedefs.swift
index 1c2a942..3d53f60 100644
--- a/test/Serialization/Recovery/typedefs.swift
+++ b/test/Serialization/Recovery/typedefs.swift
@@ -27,7 +27,7 @@
   _ = Lib.usesAssoc
 } // CHECK-SIL: end sil function '_T08typedefs11testSymbolsyyF'
 
-// CHECK-IR-LABEL: define{{.*}} void @_T08typedefs18testVTableBuildingy3Lib4UserC4user_tF
+// CHECK-IR-LABEL: define{{.*}} void @_T08typedefs18testVTableBuilding4usery3Lib4UserC_tF
 public func testVTableBuilding(user: User) {
   // The important thing in this CHECK line is the "i64 30", which is the offset
   // for the vtable slot for 'lastMethod()'. If the layout here
diff --git a/test/Serialization/always_inline.swift b/test/Serialization/always_inline.swift
index e2813a6..bb2587b 100644
--- a/test/Serialization/always_inline.swift
+++ b/test/Serialization/always_inline.swift
@@ -9,17 +9,17 @@
 
 // SIL-LABEL: sil @main
 // SIL: [[RAW:%.+]] = global_addr @_T013always_inline3rawSbvp : $*Bool
-// SIL: [[FUNC:%.+]] = function_ref @_T017def_always_inline16testAlwaysInlineS2b1x_tF : $@convention(thin) (Bool) -> Bool
+// SIL: [[FUNC:%.+]] = function_ref @_T017def_always_inline16testAlwaysInline1xS2b_tF : $@convention(thin) (Bool) -> Bool
 // SIL: [[RESULT:%.+]] = apply [[FUNC]]({{%.+}}) : $@convention(thin) (Bool) -> Bool
 // SIL: store [[RESULT]] to [trivial] [[RAW]] : $*Bool
 var raw = testAlwaysInline(x: false)
 
-// SIL: [[FUNC2:%.+]] = function_ref @_T017def_always_inline22AlwaysInlineInitStructVACSb1x_tcfC : $@convention(method) (Bool, @thin AlwaysInlineInitStruct.Type) -> AlwaysInlineInitStruct
+// SIL: [[FUNC2:%.+]] = function_ref @_T017def_always_inline22AlwaysInlineInitStructV1xACSb_tcfC : $@convention(method) (Bool, @thin AlwaysInlineInitStruct.Type) -> AlwaysInlineInitStruct
 // SIL: apply [[FUNC2]]({{%.+}}, {{%.+}}) : $@convention(method) (Bool, @thin AlwaysInlineInitStruct.Type) -> AlwaysInlineInitStruct
 
 var a = AlwaysInlineInitStruct(x: false)
 
-// SIL-LABEL: [always_inline] @_T017def_always_inline16testAlwaysInlineS2b1x_tF : $@convention(thin) (Bool) -> Bool
+// SIL-LABEL: [always_inline] @_T017def_always_inline16testAlwaysInline1xS2b_tF : $@convention(thin) (Bool) -> Bool
 
-// SIL-LABEL: sil public_external [serialized] [always_inline] @_T017def_always_inline22AlwaysInlineInitStructVACSb1x_tcfC : $@convention(method) (Bool, @thin AlwaysInlineInitStruct.Type) -> AlwaysInlineInitStruct {
+// SIL-LABEL: sil public_external [serialized] [always_inline] @_T017def_always_inline22AlwaysInlineInitStructV1xACSb_tcfC : $@convention(method) (Bool, @thin AlwaysInlineInitStruct.Type) -> AlwaysInlineInitStruct {
 
diff --git a/test/Serialization/class-roundtrip-module.swift b/test/Serialization/class-roundtrip-module.swift
index e6e4f20..81f8ea7 100644
--- a/test/Serialization/class-roundtrip-module.swift
+++ b/test/Serialization/class-roundtrip-module.swift
@@ -3,4 +3,4 @@
 // RUN: %target-swift-frontend -emit-module -parse-as-library -o %t/def_class.swiftmodule %t/stage1.swiftmodule
 // RUN: %target-swift-frontend -emit-sil -Xllvm -sil-disable-pass="External Definition To Declaration" -sil-debug-serialization -I %t %S/class.swift | %FileCheck %s -check-prefix=SIL
 
-// SIL-LABEL: sil public_external [transparent] [serialized] @_T0Si1poiS2i_SitFZ : $@convention(method) (Int, Int, @thin Int.Type) -> Int
+// SIL-LABEL: sil public_external [transparent] [serialized] @_T0Si1poiyS2i_SitFZ : $@convention(method) (Int, Int, @thin Int.Type) -> Int
diff --git a/test/Serialization/class.swift b/test/Serialization/class.swift
index 03b8627..403935d 100644
--- a/test/Serialization/class.swift
+++ b/test/Serialization/class.swift
@@ -76,7 +76,7 @@
 
 getReqPairLike()
 
-// SIL-LABEL: sil public_external [transparent] [serialized] @_T0Si1poiS2i_SitFZ : $@convention(method) (Int, Int, @thin Int.Type) -> Int
+// SIL-LABEL: sil public_external [transparent] [serialized] @_T0Si1poiyS2i_SitFZ : $@convention(method) (Int, Int, @thin Int.Type) -> Int
 
 func test(_ sharer: ResourceSharer) {}
 
diff --git a/test/Serialization/early-serialization.swift b/test/Serialization/early-serialization.swift
index 5c55bad..970ad98 100644
--- a/test/Serialization/early-serialization.swift
+++ b/test/Serialization/early-serialization.swift
@@ -11,14 +11,23 @@
   public init() {}
 }
 
+// Check that a call of a @_semantics function was not inlined if early-serialization is enabled.
+// CHECK: sil [serialized] @_T0s28userOfSemanticsAnnotatedFuncySiSaySiGF
+// CHECK: function_ref
+// CHECK: apply
+@_inlineable
+public func userOfSemanticsAnnotatedFunc(_ a: Array<Int>) -> Int {
+  return a._getCapacity()
+}
+
 public struct Array<T> {
   @_inlineable
   public init() {}
 
-  // Check that the generic version of a @_semantics function is preserved.
-  // CHECK: sil [serialized] [_semantics "array.get_capacity"] @_T0Sa12_getCapacitySiyF : $@convention(method) <T> (Array<T>) -> Int
   // Check that a specialized version of a function is produced
   // CHECK: sil shared [serializable] [_semantics "array.get_capacity"] @_T0Sa12_getCapacitySiyFSi_Tgq5 : $@convention(method) (Array<Int>) -> Int
+  // Check that the generic version of a @_semantics function is preserved.
+  // CHECK: sil [serialized] [_semantics "array.get_capacity"] @_T0Sa12_getCapacitySiyF : $@convention(method) <T> (Array<T>) -> Int
   @_inlineable
   @_versioned
   @_semantics("array.get_capacity")
@@ -26,12 +35,3 @@
     return Int()
   }
 }
-
-// Check that a call of a @_semantics function was not inlined if early-serialization is enabled.
-// CHECK: sil [serialized] @_T0s28userOfSemanticsAnnotatedFuncSiSaySiGF
-// CHECK: function_ref
-// CHECK: apply
-@_inlineable
-public func userOfSemanticsAnnotatedFunc(_ a: Array<Int>) -> Int {
-  return a._getCapacity()
-}
diff --git a/test/Serialization/function.swift b/test/Serialization/function.swift
index 9a12e9a..07cfcdf 100644
--- a/test/Serialization/function.swift
+++ b/test/Serialization/function.swift
@@ -23,30 +23,30 @@
 var cooked : Int = raw
 
 
-// SIL:   [[GET_INPUT:%.+]] = function_ref @_T08def_func8getInputS2i1x_tF : $@convention(thin) (Int) -> Int
+// SIL:   [[GET_INPUT:%.+]] = function_ref @_T08def_func8getInput1xS2i_tF : $@convention(thin) (Int) -> Int
 // SIL:   {{%.+}} = apply [[GET_INPUT]]({{%.+}}) : $@convention(thin) (Int) -> Int
 var raw2 = getInput(x: raw)
 
-// SIL:   [[GET_SECOND:%.+]] = function_ref @_T08def_func9getSecondS2i_Si1ytF : $@convention(thin) (Int, Int) -> Int
+// SIL:   [[GET_SECOND:%.+]] = function_ref @_T08def_func9getSecond_1yS2i_SitF : $@convention(thin) (Int, Int) -> Int
 // SIL:   {{%.+}} = apply [[GET_SECOND]]({{%.+}}, {{%.+}}) : $@convention(thin) (Int, Int) -> Int
 var raw3 = getSecond(raw, y: raw2)
 
-// SIL:   [[USE_NESTED:%.+]] = function_ref @_T08def_func9useNestedySi1x_Si1yt_Si1ntF : $@convention(thin) (Int, Int, Int) -> ()
+// SIL:   [[USE_NESTED:%.+]] = function_ref @_T08def_func9useNested_1nySi1x_Si1yt_SitF : $@convention(thin) (Int, Int, Int) -> ()
 // SIL:   {{%.+}} = apply [[USE_NESTED]]({{%.+}}, {{%.+}}, {{%.+}}) : $@convention(thin) (Int, Int, Int) -> ()
 useNested((raw, raw2), n: raw3)
 
 // SIL:   [[VA_SIZE:%.+]] = integer_literal $Builtin.Word, 2
 // SIL:   {{%.+}} = apply {{%.*}}<Int>([[VA_SIZE]])
-// SIL:   [[VARIADIC:%.+]] = function_ref @_T08def_func8variadicySd1x_SidtF : $@convention(thin) (Double, @owned Array<Int>) -> ()
+// SIL:   [[VARIADIC:%.+]] = function_ref @_T08def_func8variadic1x_ySd_SidtF : $@convention(thin) (Double, @owned Array<Int>) -> ()
 // SIL:   {{%.+}} = apply [[VARIADIC]]({{%.+}}, {{%.+}}) : $@convention(thin) (Double, @owned Array<Int>) -> ()
 variadic(x: 2.5, 4, 5)
 
-// SIL:   [[VARIADIC:%.+]] = function_ref @_T08def_func9variadic2ySid_Sd1xtF : $@convention(thin) (@owned Array<Int>, Double) -> ()
+// SIL:   [[VARIADIC:%.+]] = function_ref @_T08def_func9variadic2_1xySid_SdtF : $@convention(thin) (@owned Array<Int>, Double) -> ()
 variadic2(1, 2, 3, x: 5.0)
 
 // SIL:   [[SLICE_SIZE:%.+]] = integer_literal $Builtin.Word, 3
 // SIL:   {{%.+}} = apply {{%.*}}<Int>([[SLICE_SIZE]])
-// SIL:   [[SLICE:%.+]] = function_ref @_T08def_func5sliceySaySiG1x_tF : $@convention(thin) (@owned Array<Int>) -> ()
+// SIL:   [[SLICE:%.+]] = function_ref @_T08def_func5slice1xySaySiG_tF : $@convention(thin) (@owned Array<Int>) -> ()
 // SIL:   {{%.+}} = apply [[SLICE]]({{%.+}}) : $@convention(thin) (@owned Array<Int>) -> ()
 slice(x: [2, 4, 5])
 
@@ -80,14 +80,14 @@
   func getValue() -> Int { return 2 }
 }
 
-// SIL:   [[DIFFERENT_WRAPPED:%.+]] = function_ref @_T08def_func16differentWrappedSbx1a_q_1btAA0D0RzAaER_5ValueQy_AFRtzr0_lF : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Wrapped, τ_0_1 : Wrapped, τ_0_0.Value == τ_0_1.Value> (@in τ_0_0, @in τ_0_1) -> Bool
+// SIL:   [[DIFFERENT_WRAPPED:%.+]] = function_ref @_T08def_func16differentWrapped1a1bSbx_q_tAA0D0RzAaER_5ValueQy_AFRtzr0_lF : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Wrapped, τ_0_1 : Wrapped, τ_0_0.Value == τ_0_1.Value> (@in τ_0_0, @in τ_0_1) -> Bool
 
 
 _ = differentWrapped(a: IntWrapper1(), b: IntWrapper2())
 
 
-// SIL:   {{%.+}} = function_ref @_T08def_func10overloadedySi1x_tF : $@convention(thin) (Int) -> ()
-// SIL:   {{%.+}} = function_ref @_T08def_func10overloadedySb1x_tF : $@convention(thin) (Bool) -> ()
+// SIL:   {{%.+}} = function_ref @_T08def_func10overloaded1xySi_tF : $@convention(thin) (Int) -> ()
+// SIL:   {{%.+}} = function_ref @_T08def_func10overloaded1xySb_tF : $@convention(thin) (Bool) -> ()
 
 overloaded(x: 1)
 overloaded(x: false)
diff --git a/test/Serialization/inherited-initializer.swift b/test/Serialization/inherited-initializer.swift
index b2936f3..4c1b686 100644
--- a/test/Serialization/inherited-initializer.swift
+++ b/test/Serialization/inherited-initializer.swift
@@ -8,15 +8,15 @@
 
 // CHECK-LABEL: sil hidden @_T04main10testSimpleyyF
 func testSimple() {
-  // CHECK: [[DEFAULT:%.+]] = function_ref @_T024InheritedInitializerBase0C0CACSicfcfA_
+  // CHECK: [[DEFAULT:%.+]] = function_ref @_T024InheritedInitializerBase0C0CyACSicfcfA_
   // CHECK: [[ARG:%.+]] = apply [[DEFAULT]]()
-  // CHECK: [[INIT:%.+]] = function_ref @_T04main12InheritsInitCACSicfC
+  // CHECK: [[INIT:%.+]] = function_ref @_T04main12InheritsInitCyACSicfC
   // CHECK: apply [[INIT]]([[ARG]], {{%.+}})
   _ = InheritsInit()
 
   // CHECK: [[VALUE:%.+]] = integer_literal $Builtin.Int2048, 5
   // CHECK: [[ARG:%.+]] = apply {{%.+}}([[VALUE]], {{%.+}}) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int
-  // CHECK: [[INIT:%.+]] = function_ref @_T04main12InheritsInitCACSicfC
+  // CHECK: [[INIT:%.+]] = function_ref @_T04main12InheritsInitCyACSicfC
   // CHECK: apply [[INIT]]([[ARG]], {{%.+}})
   _ = InheritsInit(5)
 } // CHECK: end sil function '_T04main10testSimpleyyF'
@@ -32,23 +32,23 @@
 // CHECK-LABEL: sil hidden @_T04main11testGenericyyF
 func testGeneric() {
   // CHECK: [[TYPE:%.+]] = metatype $@thick GenericSub<Reinitializable<Int8>>.Type
-  // CHECK: [[DEFAULT:%.+]] = function_ref @_T024InheritedInitializerBase07GenericC0CACyxGxcfcfA_
+  // CHECK: [[DEFAULT:%.+]] = function_ref @_T024InheritedInitializerBase07GenericC0CyACyxGxcfcfA_
   // CHECK: apply [[DEFAULT]]<Reinitializable<Int8>>({{%.+}})
-  // CHECK: [[INIT:%.+]] = function_ref @_T04main10GenericSubCACyxGxcfC
+  // CHECK: [[INIT:%.+]] = function_ref @_T04main10GenericSubCyACyxGxcfC
   // CHECK: apply [[INIT]]<Reinitializable<Int8>>({{%.+}}, [[TYPE]])
   _ = GenericSub<Reinitializable<Int8>>.init() // works around SR-3806
 
   // CHECK: [[TYPE:%.+]] = metatype $@thick ModifiedGenericSub<Int16>.Type
-  // CHECK: [[DEFAULT:%.+]] = function_ref @_T024InheritedInitializerBase07GenericC0CACyxGxcfcfA_
+  // CHECK: [[DEFAULT:%.+]] = function_ref @_T024InheritedInitializerBase07GenericC0CyACyxGxcfcfA_
   // CHECK: apply [[DEFAULT]]<Reinitializable<Int16>>({{%.+}})
-  // CHECK: [[INIT:%.+]] = function_ref @_T04main18ModifiedGenericSubCACyxGAA15ReinitializableVyxGcfC
+  // CHECK: [[INIT:%.+]] = function_ref @_T04main18ModifiedGenericSubCyACyxGAA15ReinitializableVyxGcfC
   // CHECK: apply [[INIT]]<Int16>({{%.+}}, [[TYPE]])
   _ = ModifiedGenericSub<Int16>()
 
   // CHECK: [[TYPE:%.+]] = metatype $@thick NonGenericSub.Type
-  // CHECK: [[DEFAULT:%.+]] = function_ref @_T024InheritedInitializerBase07GenericC0CACyxGxcfcfA_
+  // CHECK: [[DEFAULT:%.+]] = function_ref @_T024InheritedInitializerBase07GenericC0CyACyxGxcfcfA_
   // CHECK: apply [[DEFAULT]]<Reinitializable<Int>>({{%.+}})
-  // CHECK: [[INIT:%.+]] = function_ref @_T04main13NonGenericSubCAcA15ReinitializableVySiGcfC
+  // CHECK: [[INIT:%.+]] = function_ref @_T04main13NonGenericSubCyAcA15ReinitializableVySiGcfC
   // CHECK: apply [[INIT]]({{%.+}}, [[TYPE]])
   _ = NonGenericSub()
 } // CHECK: end sil function '_T04main11testGenericyyF'
diff --git a/test/Serialization/noinline.swift b/test/Serialization/noinline.swift
index 6dd1560..80465b9 100644
--- a/test/Serialization/noinline.swift
+++ b/test/Serialization/noinline.swift
@@ -9,16 +9,16 @@
 
 // SIL-LABEL: sil @main
 // SIL: [[RAW:%.+]] = global_addr @_T08noinline3rawSbvp : $*Bool
-// SIL: [[FUNC:%.+]] = function_ref @_T012def_noinline12testNoinlineS2b1x_tF : $@convention(thin) (Bool) -> Bool
+// SIL: [[FUNC:%.+]] = function_ref @_T012def_noinline12testNoinline1xS2b_tF : $@convention(thin) (Bool) -> Bool
 // SIL: [[RESULT:%.+]] = apply [[FUNC]]({{%.+}}) : $@convention(thin) (Bool) -> Bool
 // SIL: store [[RESULT]] to [trivial] [[RAW]] : $*Bool
 var raw = testNoinline(x: false)
 
-// SIL: [[FUNC2:%.+]] = function_ref @_T012def_noinline18NoInlineInitStructVACSb1x_tcfC : $@convention(method) (Bool, @thin NoInlineInitStruct.Type) -> NoInlineInitStruct
+// SIL: [[FUNC2:%.+]] = function_ref @_T012def_noinline18NoInlineInitStructV1xACSb_tcfC : $@convention(method) (Bool, @thin NoInlineInitStruct.Type) -> NoInlineInitStruct
 // SIL: apply [[FUNC2]]({{%.+}}, {{%.+}}) : $@convention(method) (Bool, @thin NoInlineInitStruct.Type) -> NoInlineInitStruct
 
 var a = NoInlineInitStruct(x: false)
 
-// SIL-LABEL: [serialized] [noinline] @_T012def_noinline12testNoinlineS2b1x_tF : $@convention(thin) (Bool) -> Bool
+// SIL-LABEL: [serialized] [noinline] @_T012def_noinline12testNoinline1xS2b_tF : $@convention(thin) (Bool) -> Bool
 
-// SIL-LABEL: sil public_external [serialized] [noinline] @_T012def_noinline18NoInlineInitStructVACSb1x_tcfC : $@convention(method) (Bool, @thin NoInlineInitStruct.Type) -> NoInlineInitStruct {
+// SIL-LABEL: sil public_external [serialized] [noinline] @_T012def_noinline18NoInlineInitStructV1xACSb_tcfC : $@convention(method) (Bool, @thin NoInlineInitStruct.Type) -> NoInlineInitStruct {
diff --git a/test/Serialization/objc.swift b/test/Serialization/objc.swift
index d7d4a04..9048bb2 100644
--- a/test/Serialization/objc.swift
+++ b/test/Serialization/objc.swift
@@ -7,13 +7,13 @@
 
 import def_objc
 
-// SIL: sil hidden @_T04objc9testProtoy04def_A09ObjCProto_p3obj_tF : $@convention(thin) (@owned ObjCProto) -> () {
+// SIL: sil hidden @_T04objc9testProto3objy04def_A09ObjCProto_p_tF : $@convention(thin) (@owned ObjCProto) -> () {
 func testProto(obj obj: ObjCProto) {
   // SIL: = objc_method {{%.*}} : $@opened({{.*}}) ObjCProto, #ObjCProto.doSomething!1.foreign
   obj.doSomething()
 }
 
-// SIL: sil hidden @_T04objc9testClassy04def_A09ObjCClassC3obj_tF : $@convention(thin) (@owned ObjCClass) -> () {
+// SIL: sil hidden @_T04objc9testClass3objy04def_A09ObjCClassC_tF : $@convention(thin) (@owned ObjCClass) -> () {
 func testClass(obj obj: ObjCClass) {
   // SIL: = objc_method %{{.+}} : $ObjCClass, #ObjCClass.implicitlyObjC!1.foreign
   obj.implicitlyObjC()
@@ -22,7 +22,7 @@
   ObjCClass.classMethod()
 }
 
-// SIL: sil hidden @_T04objc15testNativeClassy04def_A012NonObjCClassC3obj_tF : $@convention(thin) (@owned NonObjCClass) -> () {
+// SIL: sil hidden @_T04objc15testNativeClass3objy04def_A012NonObjCClassC_tF : $@convention(thin) (@owned NonObjCClass) -> () {
 func testNativeClass(obj obj: NonObjCClass) {
   // SIL: = objc_method %{{.+}} : $NonObjCClass, #NonObjCClass.doSomething!1.foreign
   // SIL: = objc_method %{{.+}} : $NonObjCClass, #NonObjCClass.objcMethod!1.foreign
diff --git a/test/Serialization/serialize_attr.swift b/test/Serialization/serialize_attr.swift
index 0fc5004..aa21ab1 100644
--- a/test/Serialization/serialize_attr.swift
+++ b/test/Serialization/serialize_attr.swift
@@ -78,6 +78,6 @@
   }
 }
 
-// CHECK-DAG: sil [serialized] [_specialize exported: false, kind: full, where T == Int, U == Float] @_T014serialize_attr14specializeThisyx_q_1utr0_lF : $@convention(thin) <T, U> (@in T, @in U) -> () {
+// CHECK-DAG: sil [serialized] [_specialize exported: false, kind: full, where T == Int, U == Float] @_T014serialize_attr14specializeThis_1uyx_q_tr0_lF : $@convention(thin) <T, U> (@in T, @in U) -> () {
 
-// CHECK-DAG: sil [serialized] [noinline] [_specialize exported: false, kind: full, where T == RR, U == SS] @_T014serialize_attr2CCC3fooqd___AA2GGVyxGtqd___AG1gtAA2QQRd__lF : $@convention(method) <T where T : PP><U where U : QQ> (@in U, GG<T>, @guaranteed CC<T>) -> (@out U, GG<T>) {
+// CHECK-DAG: sil [serialized] [noinline] [_specialize exported: false, kind: full, where T == RR, U == SS] @_T014serialize_attr2CCC3foo_1gqd___AA2GGVyxGtqd___AHtAA2QQRd__lF : $@convention(method) <T where T : PP><U where U : QQ> (@in U, GG<T>, @guaranteed CC<T>) -> (@out U, GG<T>) {
diff --git a/test/Serialization/sil-imported-enums.swift b/test/Serialization/sil-imported-enums.swift
index 38e1f47..01d4668 100644
--- a/test/Serialization/sil-imported-enums.swift
+++ b/test/Serialization/sil-imported-enums.swift
@@ -14,9 +14,9 @@
 import Foundation
 import UsesImportedEnums
 
-// CHECK-LABEL: sil hidden @_T04main4testSbSC13NSRuncingModeO1e_tF
+// CHECK-LABEL: sil hidden @_T04main4test1eSbSC13NSRuncingModeO_tF
 func test(e: NSRuncingMode) -> Bool {
   // CHECK-NOT: return
-  // CHECK: _T0s2eeoiSbx_xts16RawRepresentableRzs9Equatable0B5ValueRpzlF
+  // CHECK: _T0s2eeoiySbx_xts16RawRepresentableRzs9Equatable0B5ValueRpzlF
   return compareImportedEnumToSelf(e)
 }
diff --git a/test/Serialization/transparent-std.swift b/test/Serialization/transparent-std.swift
index 894e4bd..9299851 100644
--- a/test/Serialization/transparent-std.swift
+++ b/test/Serialization/transparent-std.swift
@@ -7,14 +7,14 @@
 
 import def_transparent_std
 
-// SIL-LABEL: sil public_external [transparent] [serialized] @_T019def_transparent_std3fooBi1_Bi1_1x_Bi1_1ytF : $@convention(thin) (Builtin.Int1, Builtin.Int1) -> Builtin.Int1 {
+// SIL-LABEL: sil public_external [transparent] [serialized] @_T019def_transparent_std3foo1x1yBi1_Bi1__Bi1_tF : $@convention(thin) (Builtin.Int1, Builtin.Int1) -> Builtin.Int1 {
 // SIL: = builtin "cmp_eq_Int1"(%0 : $Builtin.Int1, %1 : $Builtin.Int1) : $Builtin.Int1
 func test_foo(x: Builtin.Int1, y: Builtin.Int1) -> Builtin.Int1 {
   var a = foo(x: x, y: y)
   return a
 }
 
-// SIL-LABEL: sil public_external [transparent] [serialized] @_T019def_transparent_std12assign_tupleyBi64__Bot1x_Bp1ytF : $@convention(thin) (Builtin.Int64, @owned Builtin.NativeObject, Builtin.RawPointer) -> () {
+// SIL-LABEL: sil public_external [transparent] [serialized] @_T019def_transparent_std12assign_tuple1x1yyBi64__Bot_BptF : $@convention(thin) (Builtin.Int64, @owned Builtin.NativeObject, Builtin.RawPointer) -> () {
 // SIL: = tuple (%0 : $Builtin.Int64, %1 : $Builtin.NativeObject)
 // SIL: retain_value
 // SIL: = tuple_extract
@@ -28,29 +28,29 @@
 }
 
 func test_conversion(c: C, t32: Builtin.Int32) {
-// SIL-LABEL: sil public_external [transparent] [serialized] @_T019def_transparent_std22class_to_native_objectBoAA1CC1c_tF : $@convention(thin) (@owned C) -> @owned Builtin.NativeObject {
+// SIL-LABEL: sil public_external [transparent] [serialized] @_T019def_transparent_std22class_to_native_object1cBoAA1CC_tF : $@convention(thin) (@owned C) -> @owned Builtin.NativeObject {
 // SIL: bb0(%0 : $C):
 // SIL: unchecked_ref_cast %0 : $C to $Builtin.NativeObject
 // SIL-NEXT: return
   var b = class_to_native_object(c: c)
 
-// SIL-LABEL: sil public_external [transparent] [serialized] @_T019def_transparent_std24class_from_native_objectAA1CCBo1p_tF : $@convention(thin) (@owned Builtin.NativeObject) -> @owned C {
+// SIL-LABEL: sil public_external [transparent] [serialized] @_T019def_transparent_std24class_from_native_object1pAA1CCBo_tF : $@convention(thin) (@owned Builtin.NativeObject) -> @owned C {
 // SIL: unchecked_ref_cast %0 : $Builtin.NativeObject to $C
   var c = class_from_native_object(p: b)
 
-// SIL-LABEL: sil public_external [transparent] [serialized] @_T019def_transparent_std20class_to_raw_pointerBpAA1CC1c_tF : $@convention(thin) (@owned C) -> Builtin.RawPointer {
+// SIL-LABEL: sil public_external [transparent] [serialized] @_T019def_transparent_std20class_to_raw_pointer1cBpAA1CC_tF : $@convention(thin) (@owned C) -> Builtin.RawPointer {
 // SIL: ref_to_raw_pointer %0 : $C to $Builtin.RawPointer
   var d = class_to_raw_pointer(c: c)
 
-// SIL-LABEL: sil public_external [transparent] [serialized] @_T019def_transparent_std22class_from_raw_pointerAA1CCBp1p_tF : $@convention(thin) (Builtin.RawPointer) -> @owned C {
+// SIL-LABEL: sil public_external [transparent] [serialized] @_T019def_transparent_std22class_from_raw_pointer1pAA1CCBp_tF : $@convention(thin) (Builtin.RawPointer) -> @owned C {
 // SIL: raw_pointer_to_ref %0 : $Builtin.RawPointer to $C
   var e = class_from_raw_pointer(p: d)
 
-// SIL-LABEL: sil public_external [transparent] [serialized] @_T019def_transparent_std5gep32BpBp1p_Bi32_1itF : $@convention(thin) (Builtin.RawPointer, Builtin.Int32) -> Builtin.RawPointer {
+// SIL-LABEL: sil public_external [transparent] [serialized] @_T019def_transparent_std5gep321p1iBpBp_Bi32_tF : $@convention(thin) (Builtin.RawPointer, Builtin.Int32) -> Builtin.RawPointer {
 // SIL: index_raw_pointer %0 : $Builtin.RawPointer, %1 : $Builtin.Int32
   var f = gep32(p: d, i: t32)
 
-// SIL-LABEL: sil public_external [transparent] [serialized] @_T019def_transparent_std11destroy_objyBp1x_tF : $@convention(thin) (Builtin.RawPointer) -> () {
+// SIL-LABEL: sil public_external [transparent] [serialized] @_T019def_transparent_std11destroy_obj1xyBp_tF : $@convention(thin) (Builtin.RawPointer) -> () {
 // SIL: pointer_to_address %0 : $Builtin.RawPointer to [strict] $*Builtin.NativeObject
   destroy_obj(x: d)
 }
diff --git a/test/Serialization/transparent.swift b/test/Serialization/transparent.swift
index fcfd81e..e8a2bb5 100644
--- a/test/Serialization/transparent.swift
+++ b/test/Serialization/transparent.swift
@@ -9,7 +9,7 @@
 
 // SIL-LABEL: sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 {
 // SIL: [[RAW:%.+]] = global_addr @_T011transparent3rawSbvp : $*Bool
-// SIL: [[FUNC:%.+]] = function_ref @_T015def_transparent15testTransparentS2b1x_tF : $@convention(thin) (Bool) -> Bool
+// SIL: [[FUNC:%.+]] = function_ref @_T015def_transparent15testTransparent1xS2b_tF : $@convention(thin) (Bool) -> Bool
 // SIL: [[RESULT:%.+]] = apply [[FUNC]]({{%.+}}) : $@convention(thin) (Bool) -> Bool
 // SIL: store [[RESULT]] to [trivial] [[RAW]] : $*Bool
 var raw = testTransparent(x: false)
@@ -20,7 +20,7 @@
 // SIL: store [[RESULT2]] to [trivial] [[TMP]] : $*Int32
 var tmp = testBuiltin()
 
-// SIL-LABEL: sil public_external [transparent] [serialized] @_T015def_transparent15testTransparentS2b1x_tF : $@convention(thin) (Bool) -> Bool {
+// SIL-LABEL: sil public_external [transparent] [serialized] @_T015def_transparent15testTransparent1xS2b_tF : $@convention(thin) (Bool) -> Bool {
 // SIL: bb0(%0 : $Bool):
 // SIL: return %0 : $Bool
 
@@ -39,7 +39,7 @@
   test_br()
 }
 
-// SIL-LABEL: sil public_external [serialized] @_T015def_transparent9do_switchyAA9MaybePairO1u_tF : $@convention(thin) (@owned MaybePair) -> () {
+// SIL-LABEL: sil public_external [serialized] @_T015def_transparent9do_switch1uyAA9MaybePairO_tF : $@convention(thin) (@owned MaybePair) -> () {
 // SIL: bb0(%0 : $MaybePair):
 // SIL: retain_value %0 : $MaybePair
 // SIL: switch_enum %0 : $MaybePair, case #MaybePair.Neither!enumelt: bb[[CASE1:[0-9]+]], case #MaybePair.Left!enumelt.1: bb[[CASE2:[0-9]+]], case #MaybePair.Right!enumelt.1: bb[[CASE3:[0-9]+]], case #MaybePair.Both!enumelt.1: bb[[CASE4:[0-9]+]]
@@ -51,7 +51,7 @@
   do_switch(u: u)
 }
 
-// SIL-LABEL: sil public_external [transparent] [serialized] @_T015def_transparent7WrapperVACs5Int32V3Val_tcfC : $@convention(method) (Int32, @thin Wrapper.Type) -> Wrapper {
+// SIL-LABEL: sil public_external [transparent] [serialized] @_T015def_transparent7WrapperV3ValACs5Int32V_tcfC : $@convention(method) (Int32, @thin Wrapper.Type) -> Wrapper {
 // SIL-LABEL: sil public_external [transparent] [serialized] @_T015def_transparent7WrapperV8getValue{{[_0-9a-zA-Z]*}}F : $@convention(method) (Wrapper) -> Int32 {
 // SIL-LABEL: sil public_external [transparent] [serialized] @_T015def_transparent7WrapperV10valueAgains5Int32Vvg : $@convention(method) (Wrapper) -> Int32 {
 // SIL-LABEL: sil public_external [transparent] [serialized] @_T015def_transparent7WrapperV13getValueAgain{{[_0-9a-zA-Z]*}}F : $@convention(method) (Wrapper) -> Int32 {
@@ -64,7 +64,7 @@
   print(w.getValueAgain(), terminator: "")
 }
 
-// SIL-LABEL: sil public_external [transparent] [serialized] @_T015def_transparent17open_existentialsyAA1P_p1p_AA2CP_p2cptF
+// SIL-LABEL: sil public_external [transparent] [serialized] @_T015def_transparent17open_existentials1p2cpyAA1P_p_AA2CP_ptF
 func test_open_existentials(p: P, cp: CP) {
   // SIL: open_existential_addr immutable_access [[EXIST:%[0-9]+]] : $*P to $*@opened([[N:".*"]]) P
   // SIL: open_existential_ref [[EXIST:%[0-9]+]] : $CP to $@opened([[M:".*"]]) CP
diff --git a/test/SourceKit/CodeComplete/complete_call_pattern.swift b/test/SourceKit/CodeComplete/complete_call_pattern.swift
new file mode 100644
index 0000000..85ab6b6
--- /dev/null
+++ b/test/SourceKit/CodeComplete/complete_call_pattern.swift
@@ -0,0 +1,20 @@
+struct S {
+  init(foo: Int) {}
+}
+func takeS(_: S, other: Int) {}
+
+func test() {
+  takeS(S(, other: 2)
+}
+
+// RUN: %sourcekitd-test -req=complete -pos=7:11 %s -- %s | %FileCheck %s -check-prefix=CALL_PATTERN
+// CALL_PATTERN: key.kind: source.lang.swift.decl.function.constructor
+
+// RUN: %sourcekitd-test -req=complete.open -pos=7:11 %s -- %s | %FileCheck %s -check-prefix=NO_PATTERN
+// NO_PATTERN-NOT: key.kind: source.lang.swift.decl.function.constructor
+
+// RUN: %sourcekitd-test -req=complete.open -req-opts=callpatternheuristics=1 -pos=7:11 %s -- %s | %FileCheck %s -check-prefix=NO_PATTERN
+// NO_PATTERN-NOT: key.kind: source.lang.swift.decl.function.constructor
+
+// RUN: %sourcekitd-test -req=complete.open -req-opts=callpatternheuristics=0 -pos=7:11 %s -- %s | %FileCheck %s -check-prefix=CALL_PATTERN
+// NO_PATTERN-NOT: key.kind: source.lang.swift.decl.function.constructor
diff --git a/test/SourceKit/CodeComplete/complete_constructor.swift.response b/test/SourceKit/CodeComplete/complete_constructor.swift.response
index e4e9208..b025292 100644
--- a/test/SourceKit/CodeComplete/complete_constructor.swift.response
+++ b/test/SourceKit/CodeComplete/complete_constructor.swift.response
@@ -2,13 +2,13 @@
   key.results: [
     {
       key.kind: source.lang.swift.decl.function.constructor,
-      key.name: "arg1:arg2:)",
-      key.sourcetext: "arg1: <#T##Int#>, arg2: <#T##Int#>)",
+      key.name: "arg1:arg2:",
+      key.sourcetext: "arg1: <#T##Int#>, arg2: <#T##Int#>",
       key.description: "(arg1: Int, arg2: Int)",
       key.typename: "Foo",
       key.context: source.codecompletion.context.thisclass,
       key.num_bytes_to_erase: 0,
-      key.associated_usrs: "s:20complete_constructor3FooCACSi4arg1_Si4arg2tcfc",
+      key.associated_usrs: "s:20complete_constructor3FooC4arg14arg2ACSi_Sitcfc",
       key.modulename: "complete_constructor"
     }
   ]
diff --git a/test/SourceKit/CodeComplete/complete_member.swift b/test/SourceKit/CodeComplete/complete_member.swift
index 0fdae65..1851dae 100644
--- a/test/SourceKit/CodeComplete/complete_member.swift
+++ b/test/SourceKit/CodeComplete/complete_member.swift
@@ -52,7 +52,7 @@
 // CHECK-OPTIONAL-NEXT:       key.typename: "Double",
 // CHECK-OPTIONAL-NEXT:       key.context: source.codecompletion.context.thisclass,
 // CHECK-OPTIONAL-NEXT:       key.num_bytes_to_erase: 1,
-// CHECK-OPTIONAL-NEXT:       key.associated_usrs: "s:15complete_member11FooProtocolP16fooInstanceFunc1SdSiF",
+// CHECK-OPTIONAL-NEXT:       key.associated_usrs: "s:15complete_member11FooProtocolP16fooInstanceFunc1ySdSiF",
 // CHECK-OPTIONAL-NEXT:       key.modulename: "complete_member"
 // CHECK-OPTIONAL-NEXT:     },
 
diff --git a/test/SourceKit/CodeComplete/complete_member.swift.response b/test/SourceKit/CodeComplete/complete_member.swift.response
index 46ccf07..b4977f8 100644
--- a/test/SourceKit/CodeComplete/complete_member.swift.response
+++ b/test/SourceKit/CodeComplete/complete_member.swift.response
@@ -19,7 +19,7 @@
       key.typename: "Double",
       key.context: source.codecompletion.context.thisclass,
       key.num_bytes_to_erase: 0,
-      key.associated_usrs: "s:15complete_member11FooProtocolP16fooInstanceFunc1SdSiF",
+      key.associated_usrs: "s:15complete_member11FooProtocolP16fooInstanceFunc1ySdSiF",
       key.modulename: "complete_member"
     },
     {
diff --git a/test/SourceKit/CodeComplete/complete_name.swift b/test/SourceKit/CodeComplete/complete_name.swift
index 40927a9..752c48d 100644
--- a/test/SourceKit/CodeComplete/complete_name.swift
+++ b/test/SourceKit/CodeComplete/complete_name.swift
@@ -12,7 +12,7 @@
 func test01() {
   S(#^INIT_NAME^#)
 }
-// INIT_NAME: key.name: "a:b::)"
+// INIT_NAME: key.name: "a:b::"
 
 func test02(_ x: S) {
   x.#^METHOD_NAME^#
diff --git a/test/SourceKit/CodeComplete/complete_override.swift.response b/test/SourceKit/CodeComplete/complete_override.swift.response
index 87fb5e9..4bbdb18 100644
--- a/test/SourceKit/CodeComplete/complete_override.swift.response
+++ b/test/SourceKit/CodeComplete/complete_override.swift.response
@@ -71,7 +71,7 @@
       key.typename: "",
       key.context: source.codecompletion.context.superclass,
       key.num_bytes_to_erase: 0,
-      key.associated_usrs: "s:17complete_override4BaseC1fySi5getMe_Sd1btF",
+      key.associated_usrs: "s:17complete_override4BaseC1f5getMe1bySi_SdtF",
       key.modulename: "complete_override"
     },
     {
diff --git a/test/SourceKit/CodeComplete/complete_structure.swift b/test/SourceKit/CodeComplete/complete_structure.swift
index 42a2268..e1c2d50 100644
--- a/test/SourceKit/CodeComplete/complete_structure.swift
+++ b/test/SourceKit/CodeComplete/complete_structure.swift
@@ -64,7 +64,6 @@
 func test5() {
   S1(#^S1_PAREN_INIT^#
 }
-// S1_INIT: ()
 // S1_INIT: ({params:{t:Int}, {t:Int}})
 // S1_INIT: ({params:{n:a:}{t: Int}, {n:b:}{t: Int}})
 // S1_INIT: ({params:{n:c:}{t: Int}})
diff --git a/test/SourceKit/CursorInfo/cursor_generics.swift b/test/SourceKit/CursorInfo/cursor_generics.swift
index e0a898f..a64d901 100644
--- a/test/SourceKit/CursorInfo/cursor_generics.swift
+++ b/test/SourceKit/CursorInfo/cursor_generics.swift
@@ -10,7 +10,7 @@
 }
 
 // RUN: %sourcekitd-test -req=cursor -pos=1:10 %s -- %s | %FileCheck -check-prefix=CHECK1 %s
-// CHECK1: <Declaration>func testGenerics&lt;T&gt;(x: <Type usr="s:15cursor_generics12testGenericsyx1x_tlF1TL_xmfp">T</Type>)</Declaration>
+// CHECK1: <Declaration>func testGenerics&lt;T&gt;(x: <Type usr="s:15cursor_generics12testGenerics1xyx_tlF1TL_xmfp">T</Type>)</Declaration>
 
 // RUN: %sourcekitd-test -req=cursor -pos=5:10 %s -- %s | %FileCheck -check-prefix=CHECK2 %s
 // CHECK2: <Function
diff --git a/test/SourceKit/CursorInfo/cursor_info.swift b/test/SourceKit/CursorInfo/cursor_info.swift
index 507278d..ba574f9 100644
--- a/test/SourceKit/CursorInfo/cursor_info.swift
+++ b/test/SourceKit/CursorInfo/cursor_info.swift
@@ -227,7 +227,7 @@
 // XUN: %sourcekitd-test -req=cursor -pos=9:13 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK2 %s
 // XCHECK2:      source.lang.swift.ref.function.operator.infix ()
 // XCHECK2-NEXT: +
-// XCHECK2-NEXT: s:s1poiS2i_SitF
+// XCHECK2-NEXT: s:s1poiyS2i_SitF
 // XCHECK2-NEXT: (Int, Int) -> Int{{$}}
 // XCHECK2-NEXT: _T0S2i_SitcD
 // XCHECK2-NEXT: Swift{{$}}
@@ -239,7 +239,7 @@
 // RUN: %sourcekitd-test -req=cursor -pos=9:12 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK3 %s
 // CHECK3:      source.lang.swift.ref.var.local (8:12-8:13)
 // CHECK3-NEXT: x{{$}}
-// CHECK3-NEXT: s:11cursor_info3gooySiF1xL_Sivp{{$}}
+// CHECK3-NEXT: s:11cursor_info3gooyySiF1xL_Sivp{{$}}
 // CHECK3-NEXT: Int{{$}}
 // CHECK3-NEXT: _T0SiD
 // CHECK3-NEXT: <Declaration>let x: <Type usr="s:Si">Int</Type></Declaration>
@@ -259,7 +259,7 @@
 // RUN: %sourcekitd-test -req=cursor -pos=8:7 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK5 %s
 // CHECK5:      source.lang.swift.decl.function.free (8:6-8:19)
 // CHECK5-NEXT: goo(_:){{$}}
-// CHECK5-NEXT: s:11cursor_info3gooySiF{{$}}
+// CHECK5-NEXT: s:11cursor_info3gooyySiF{{$}}
 // CHECK5-NEXT: (Int) -> (){{$}}
 
 // RUN: %sourcekitd-test -req=cursor -pos=9:32 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK6 %s
@@ -286,9 +286,9 @@
 // RUN: %sourcekitd-test -req=cursor -pos=19:12 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK8 %s
 // CHECK8:      source.lang.swift.ref.function.constructor (18:3-18:15)
 // CHECK8-NEXT: init
-// CHECK8-NEXT: s:11cursor_info2CCCACSi1x_tcfc
+// CHECK8-NEXT: s:11cursor_info2CCC1xACSi_tcfc
 // CHECK8-NEXT: (CC.Type) -> (Int) -> CC
-// CHECK8-NEXT: _T011cursor_info2CCCSi1x_tcD
+// CHECK8-NEXT: _T01x11cursor_info2CCCSi_tcD
 // CHECK8-NEXT: <Container>_T011cursor_info2CCCD</Container>
 // CHECK8-NEXT: <Declaration>convenience init(x: <Type usr="s:Si">Int</Type>)</Declaration>
 // CHECK8-NEXT: <decl.function.constructor><syntaxtype.keyword>convenience</syntaxtype.keyword> <syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>x</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr="s:Si">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>
@@ -330,7 +330,7 @@
 // CHECK15: <Declaration>func myFunc(arg1: <Type usr="s:SS">String</Type>, options: <Type usr="s:Si">Int</Type>)</Declaration>
 // CHECK15: <decl.function.free><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>myFunc</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>arg1</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr="s:SS">String</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>options</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr="s:Si">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.free>
 // CHECK15: RELATED BEGIN
-// CHECK15-NEXT: <RelatedName usr="s:11cursor_info6myFuncySS4arg1_tF">myFunc(arg1:)</RelatedName>
+// CHECK15-NEXT: <RelatedName usr="s:11cursor_info6myFunc4arg1ySS_tF">myFunc(arg1:)</RelatedName>
 // CHECK15-NEXT: RELATED END
 
 // RUN: %sourcekitd-test -req=cursor -pos=41:26 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck -check-prefix=CHECK16 %s
@@ -401,27 +401,27 @@
 // RUN: %sourcekitd-test -req=cursor -pos=75:3 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck %s -check-prefix=CHECK30
 // CHECK30: source.lang.swift.decl.function.constructor (75:3-75:16)
 // CHECK30-NEXT: init(x:)
-// CHECK30-NEXT: s:11cursor_info2C3CSQyACGSi1x_tcfc
+// CHECK30-NEXT: s:11cursor_info2C3C1xSQyACGSi_tcfc
 // CHECK30-NEXT: (C3.Type) -> (Int) -> C3!
-// CHECK30-NEXT: _T0SQy11cursor_info2C3CGSi1x_tcD
+// CHECK30-NEXT: _T01xSQy11cursor_info2C3CGSi_tcD
 // CHECK30-NEXT: <Declaration>init!(x: <Type usr="s:Si">Int</Type>)</Declaration>
 // CHECK30-NEXT: <decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>!(<decl.var.parameter><decl.var.parameter.argument_label>x</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr="s:Si">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>
 
 // RUN: %sourcekitd-test -req=cursor -pos=76:3 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck %s -check-prefix=CHECK31
 // CHECK31: source.lang.swift.decl.function.constructor (76:3-76:16)
 // CHECK31-NEXT: init(y:)
-// CHECK31-NEXT: s:11cursor_info2C3CACSgSi1y_tcfc
+// CHECK31-NEXT: s:11cursor_info2C3C1yACSgSi_tcfc
 // CHECK31-NEXT: (C3.Type) -> (Int) -> C3?
-// CHECK31-NEXT: _T011cursor_info2C3CSgSi1y_tcD
+// CHECK31-NEXT: _T01y11cursor_info2C3CSgSi_tcD
 // CHECK31-NEXT: <Declaration>init?(y: <Type usr="s:Si">Int</Type>)</Declaration>
 // CHECK31-NEXT: <decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>?(<decl.var.parameter><decl.var.parameter.argument_label>y</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr="s:Si">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>
 
 // RUN: %sourcekitd-test -req=cursor -pos=77:3 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck %s -check-prefix=CHECK32
 // CHECK32: source.lang.swift.decl.function.constructor (77:3-77:15)
 // CHECK32-NEXT: init(z:)
-// CHECK32-NEXT: s:11cursor_info2C3CACSi1z_tKcfc
+// CHECK32-NEXT: s:11cursor_info2C3C1zACSi_tKcfc
 // CHECK32-NEXT: (C3.Type) -> (Int) throws -> C3
-// CHECK32-NEXT: _T011cursor_info2C3CSi1z_tKcD
+// CHECK32-NEXT: _T01z11cursor_info2C3CSi_tKcD
 // CHECK32-NEXT: <Declaration>init(z: <Type usr="s:Si">Int</Type>) throws</Declaration>
 // CHECK32-NEXT: <decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>z</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr="s:Si">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>) <syntaxtype.keyword>throws</syntaxtype.keyword></decl.function.constructor>
 
@@ -436,10 +436,10 @@
 // RUN: %sourcekitd-test -req=cursor -pos=81:8 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck %s -check-prefix=CHECK34
 // CHECK34: source.lang.swift.decl.function.method.instance (81:8-81:62)
 // CHECK34-NEXT: foo(_:_:_:)
-// CHECK34-NEXT: s:11cursor_info2S2V3fooyycqd___qd__yyctqd_0_Rsd__r0_lF
+// CHECK34-NEXT: s:11cursor_info2S2V3fooyyycqd___qd__yyctqd_0_Rsd__r0_lF
 // CHECK34-NEXT: <T, U, V, W where T == U, V == W> (S2<T, U>) -> (V, W, () -> ()) -> () -> ()
-// CHECK34: <Declaration>func foo&lt;V, W&gt;(_: <Type usr="s:11cursor_info2S2V3fooyycqd___qd__yyctqd_0_Rsd__r0_lF1VL_qd__mfp">V</Type>, _: <Type usr="s:11cursor_info2S2V3fooyycqd___qd__yyctqd_0_Rsd__r0_lF1WL_qd_0_mfp">W</Type>, _ closure: () -&gt; ()) -&gt; () -&gt; () where V == W</Declaration>
-// CHECK34: <decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo</decl.name>&lt;<decl.generic_type_param usr="s:11cursor_info2S2V3fooyycqd___qd__yyctqd_0_Rsd__r0_lF1VL_qd__mfp"><decl.generic_type_param.name>V</decl.generic_type_param.name></decl.generic_type_param>, <decl.generic_type_param usr="s:11cursor_info2S2V3fooyycqd___qd__yyctqd_0_Rsd__r0_lF1WL_qd_0_mfp"><decl.generic_type_param.name>W</decl.generic_type_param.name></decl.generic_type_param>&gt;(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.generic_type_param usr="s:11cursor_info2S2V3fooyycqd___qd__yyctqd_0_Rsd__r0_lF1VL_qd__mfp">V</ref.generic_type_param></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.generic_type_param usr="s:11cursor_info2S2V3fooyycqd___qd__yyctqd_0_Rsd__r0_lF1WL_qd_0_mfp">W</ref.generic_type_param></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>closure</decl.var.parameter.name>: <decl.var.parameter.type>() -&gt; <decl.function.returntype><tuple>()</tuple></decl.function.returntype></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype>() -&gt; <decl.function.returntype><tuple>()</tuple></decl.function.returntype></decl.function.returntype> <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement>V == W</decl.generic_type_requirement></decl.function.method.instance>
+// CHECK34: <Declaration>func foo&lt;V, W&gt;(_: <Type usr="s:11cursor_info2S2V3fooyyycqd___qd__yyctqd_0_Rsd__r0_lF1VL_qd__mfp">V</Type>, _: <Type usr="s:11cursor_info2S2V3fooyyycqd___qd__yyctqd_0_Rsd__r0_lF1WL_qd_0_mfp">W</Type>, _ closure: () -&gt; ()) -&gt; () -&gt; () where V == W</Declaration>
+// CHECK34: <decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo</decl.name>&lt;<decl.generic_type_param usr="s:11cursor_info2S2V3fooyyycqd___qd__yyctqd_0_Rsd__r0_lF1VL_qd__mfp"><decl.generic_type_param.name>V</decl.generic_type_param.name></decl.generic_type_param>, <decl.generic_type_param usr="s:11cursor_info2S2V3fooyyycqd___qd__yyctqd_0_Rsd__r0_lF1WL_qd_0_mfp"><decl.generic_type_param.name>W</decl.generic_type_param.name></decl.generic_type_param>&gt;(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.generic_type_param usr="s:11cursor_info2S2V3fooyyycqd___qd__yyctqd_0_Rsd__r0_lF1VL_qd__mfp">V</ref.generic_type_param></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.generic_type_param usr="s:11cursor_info2S2V3fooyyycqd___qd__yyctqd_0_Rsd__r0_lF1WL_qd_0_mfp">W</ref.generic_type_param></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>closure</decl.var.parameter.name>: <decl.var.parameter.type>() -&gt; <decl.function.returntype><tuple>()</tuple></decl.function.returntype></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype>() -&gt; <decl.function.returntype><tuple>()</tuple></decl.function.returntype></decl.function.returntype> <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement>V == W</decl.generic_type_requirement></decl.function.method.instance>
 
 // RUN: %sourcekitd-test -req=cursor -pos=83:7 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck %s -check-prefix=CHECK35
 // CHECK35: source.lang.swift.decl.class (83:7-83:9)
@@ -460,7 +460,7 @@
 // RUN: %sourcekitd-test -req=cursor -pos=86:6 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck %s -check-prefix=CHECK37
 // CHECK37: source.lang.swift.decl.function.free (86:6-86:111)
 // CHECK37-NEXT: nonDefaultArgNames(external1:_:external3:external4:_:)
-// CHECK37-NEXT: s:11cursor_info18nonDefaultArgNamesySi9external1_S2i9external3Si9external4SitF
+// CHECK37-NEXT: s:11cursor_info18nonDefaultArgNames9external1_9external39external4_ySi_S4itF
 // CHECK37-NEXT: (Int, Int, Int, Int, Int) -> ()
 // CHECK37: <Declaration>func nonDefaultArgNames(external1 local1: <Type usr="s:Si">Int</Type>, _ local2: <Type usr="s:Si">Int</Type>, external3 local3: <Type usr="s:Si">Int</Type>, external4 _: <Type usr="s:Si">Int</Type>, _: <Type usr="s:Si">Int</Type>)</Declaration>
 // CHECK37-NEXT: <decl.function.free><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>nonDefaultArgNames</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>external1</decl.var.parameter.argument_label> <decl.var.parameter.name>local1</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr="s:Si">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>local2</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr="s:Si">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>external3</decl.var.parameter.argument_label> <decl.var.parameter.name>local3</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr="s:Si">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>external4</decl.var.parameter.argument_label> <decl.var.parameter.name>_</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr="s:Si">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr="s:Si">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.free>
@@ -471,7 +471,7 @@
 // RUN: %sourcekitd-test -req=cursor -pos=91:8 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck %s -check-prefix=CHECK39
 // CHECK39: source.lang.swift.decl.enumelement (91:8-91:10)
 // CHECK39-NEXT: C1
-// CHECK39-NEXT: s:11cursor_info2E2O2C1A2CmF
+// CHECK39-NEXT: s:11cursor_info2E2O2C1yA2CmF
 // CHECK39-NEXT: (E2.Type) -> E2
 // CHECK39: <Declaration>case C1</Declaration>
 // CHECK39-NEXT: <decl.enumelement><syntaxtype.keyword>case</syntaxtype.keyword> <decl.name>C1</decl.name></decl.enumelement>
@@ -479,7 +479,7 @@
 // RUN: %sourcekitd-test -req=cursor -pos=92:8 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck %s -check-prefix=CHECK40
 // CHECK40: source.lang.swift.decl.enumelement (92:8-92:10)
 // CHECK40-NEXT: C2
-// CHECK40-NEXT: s:11cursor_info2E2O2C2ACSi1x_SS1ytcACmF
+// CHECK40-NEXT: s:11cursor_info2E2O2C2yACSi_SStcACmF
 // CHECK40-NEXT: (E2.Type) -> (Int, String) -> E2
 // CHECK40: <Declaration>case C2(x: <Type usr="s:Si">Int</Type>, y: <Type usr="s:SS">String</Type>)</Declaration>
 // CHECK40-NEXT: <decl.enumelement><syntaxtype.keyword>case</syntaxtype.keyword> <decl.name>C2</decl.name><tuple>(<tuple.element><tuple.element.argument_label>x</tuple.element.argument_label>: <tuple.element.type><ref.struct usr="s:Si">Int</ref.struct></tuple.element.type></tuple.element>, <tuple.element><tuple.element.argument_label>y</tuple.element.argument_label>: <tuple.element.type><ref.struct usr="s:SS">String</ref.struct></tuple.element.type></tuple.element>)</tuple></decl.enumelement>
@@ -487,7 +487,7 @@
 // RUN: %sourcekitd-test -req=cursor -pos=92:31 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck %s -check-prefix=CHECK41
 // CHECK41: source.lang.swift.decl.enumelement (92:31-92:33)
 // CHECK41-NEXT: C3
-// CHECK41-NEXT: s:11cursor_info2E2O2C3ACSicACmF
+// CHECK41-NEXT: s:11cursor_info2E2O2C3yACSicACmF
 // CHECK41-NEXT: (E2.Type) -> (Int) -> E2
 // CHECK41: <Declaration>case C3(<Type usr="s:Si">Int</Type>)</Declaration>
 // CHECK41-NEXT: <decl.enumelement><syntaxtype.keyword>case</syntaxtype.keyword> <decl.name>C3</decl.name>(<ref.struct usr="s:Si">Int</ref.struct>)</decl.enumelement>
@@ -496,7 +496,7 @@
 // RUN: %sourcekitd-test -req=cursor -pos=96:8 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck %s -check-prefix=CHECK42
 // CHECK42: source.lang.swift.decl.enumelement (96:8-96:9)
 // CHECK42-NEXT: C
-// CHECK42-NEXT: s:11cursor_info2E3O1CA2CmF
+// CHECK42-NEXT: s:11cursor_info2E3O1CyA2CmF
 // CHECK42-NEXT: (E3.Type) -> E3
 // CHECK42: <Declaration>case C = &quot;a&quot;</Declaration>
 // CHECK42-NEXT: <decl.enumelement><syntaxtype.keyword>case</syntaxtype.keyword> <decl.name>C</decl.name> = <syntaxtype.string>&quot;a&quot;</syntaxtype.string></decl.enumelement>
@@ -552,7 +552,7 @@
 // RUN: %sourcekitd-test -req=cursor -pos=117:6 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck %s -check-prefix=CHECK52
 // CHECK52: source.lang.swift.decl.function.free (117:6-117:36)
 // CHECK52: <U, V where U == V.T, V : P1> (U, v: V) -> ()
-// CHECK52: <decl.function.free><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>genReq</decl.name>&lt;<decl.generic_type_param usr="s:11cursor_info6genReqyx_q_1vt1TQy_RszAA2P1R_r0_lF1UL_xmfp"><decl.generic_type_param.name>U</decl.generic_type_param.name></decl.generic_type_param>, <decl.generic_type_param usr="s:11cursor_info6genReqyx_q_1vt1TQy_RszAA2P1R_r0_lF1VL_q_mfp"><decl.generic_type_param.name>V</decl.generic_type_param.name></decl.generic_type_param>&gt;(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>u</decl.var.parameter.name>: <decl.var.parameter.type><ref.generic_type_param usr="s:11cursor_info6genReqyx_q_1vt1TQy_RszAA2P1R_r0_lF1UL_xmfp">U</ref.generic_type_param></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>v</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.generic_type_param usr="s:11cursor_info6genReqyx_q_1vt1TQy_RszAA2P1R_r0_lF1VL_q_mfp">V</ref.generic_type_param></decl.var.parameter.type></decl.var.parameter>) <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement>U == V.T</decl.generic_type_requirement>, <decl.generic_type_requirement>V : <ref.protocol usr="s:11cursor_info2P1P">P1</ref.protocol></decl.generic_type_requirement></decl.function.free>
+// CHECK52: <decl.function.free><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>genReq</decl.name>&lt;<decl.generic_type_param usr="s:11cursor_info6genReq_1vyx_q_t1TQy_RszAA2P1R_r0_lF1UL_xmfp"><decl.generic_type_param.name>U</decl.generic_type_param.name></decl.generic_type_param>, <decl.generic_type_param usr="s:11cursor_info6genReq_1vyx_q_t1TQy_RszAA2P1R_r0_lF1VL_q_mfp"><decl.generic_type_param.name>V</decl.generic_type_param.name></decl.generic_type_param>&gt;(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>u</decl.var.parameter.name>: <decl.var.parameter.type><ref.generic_type_param usr="s:11cursor_info6genReq_1vyx_q_t1TQy_RszAA2P1R_r0_lF1UL_xmfp">U</ref.generic_type_param></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>v</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.generic_type_param usr="s:11cursor_info6genReq_1vyx_q_t1TQy_RszAA2P1R_r0_lF1VL_q_mfp">V</ref.generic_type_param></decl.var.parameter.type></decl.var.parameter>) <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement>U == V.T</decl.generic_type_requirement>, <decl.generic_type_requirement>V : <ref.protocol usr="s:11cursor_info2P1P">P1</ref.protocol></decl.generic_type_requirement></decl.function.free>
 
 // RUN: %sourcekitd-test -req=cursor -pos=117:16 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | %FileCheck %s -check-prefix=CHECK53
 // CHECK53: source.lang.swift.decl.generic_type_param (117:16-117:17)
diff --git a/test/SourceKit/CursorInfo/cursor_usr.swift b/test/SourceKit/CursorInfo/cursor_usr.swift
index b707065..72d5004 100644
--- a/test/SourceKit/CursorInfo/cursor_usr.swift
+++ b/test/SourceKit/CursorInfo/cursor_usr.swift
@@ -51,7 +51,7 @@
 // CHECK2: FooSwiftModule
 // CHECK2: <decl.function.free><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>fooSwiftFunc</decl.name>() -&gt; <decl.function.returntype><ref.struct usr="s:Si">Int</ref.struct></decl.function.returntype></decl.function.free>
 
-// RUN: %sourcekitd-test -req=cursor -usr "s:10cursor_usr3fooAA2S1VSC10FooStruct1VF" %s -- -I %t -F %S/../Inputs/libIDE-mock-sdk %mcp_opt %s | %FileCheck %s -check-prefix=CHECK3
+// RUN: %sourcekitd-test -req=cursor -usr "s:10cursor_usr3fooyAA2S1VSC10FooStruct1VF" %s -- -I %t -F %S/../Inputs/libIDE-mock-sdk %mcp_opt %s | %FileCheck %s -check-prefix=CHECK3
 // CHECK3: source.lang.swift.decl.function.free (9:6-9:24)
 // CHECK3: foo(x:)
 // CHECK3: (FooStruct1) -> S1
diff --git a/test/SourceKit/DocSupport/doc_clang_module.swift.response b/test/SourceKit/DocSupport/doc_clang_module.swift.response
index 80b05ae..5e23a94 100644
--- a/test/SourceKit/DocSupport/doc_clang_module.swift.response
+++ b/test/SourceKit/DocSupport/doc_clang_module.swift.response
@@ -4554,7 +4554,7 @@
       {
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init(_:)",
-        key.usr: "s:SC8FooEnum1VABs6UInt32Vcfc",
+        key.usr: "s:SC8FooEnum1VyABs6UInt32Vcfc",
         key.offset: 89,
         key.length: 24,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>rawValue</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:s6UInt32V\">UInt32</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>",
@@ -4571,7 +4571,7 @@
       {
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init(rawValue:)",
-        key.usr: "s:SC8FooEnum1VABs6UInt32V8rawValue_tcfc",
+        key.usr: "s:SC8FooEnum1V8rawValueABs6UInt32V_tcfc",
         key.offset: 119,
         key.length: 31,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>rawValue</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:s6UInt32V\">UInt32</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>",
@@ -4579,7 +4579,7 @@
           {
             key.kind: source.lang.swift.ref.function.constructor,
             key.name: "init(rawValue:)",
-            key.usr: "s:s16RawRepresentablePxSg0A5ValueQz03rawC0_tcfc"
+            key.usr: "s:s16RawRepresentableP8rawValuexSg0aD0Qz_tcfc"
           }
         ],
         key.entities: [
@@ -4610,9 +4610,9 @@
       {
         key.kind: source.lang.swift.decl.function.operator.infix,
         key.name: "!=(_:_:)",
-        key.usr: "s:s9EquatablePsE2neoiSbx_xtFZ::SYNTHESIZED::c:@E@FooEnum1",
-        key.original_usr: "s:s9EquatablePsE2neoiSbx_xtFZ",
-        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiSbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
+        key.usr: "s:s9EquatablePsE2neoiySbx_xtFZ::SYNTHESIZED::c:@E@FooEnum1",
+        key.original_usr: "s:s9EquatablePsE2neoiySbx_xtFZ",
+        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiySbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
         key.offset: 182,
         key.length: 57,
         key.fully_annotated_decl: "<decl.function.operator.infix><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>static</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>!= </decl.name>(<decl.var.parameter><decl.var.parameter.name>lhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooEnum1\">FooEnum1</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.name>rhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooEnum1\">FooEnum1</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.operator.infix>",
@@ -4655,7 +4655,7 @@
       {
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init(_:)",
-        key.usr: "s:SC8FooEnum2VABs6UInt32Vcfc",
+        key.usr: "s:SC8FooEnum2VyABs6UInt32Vcfc",
         key.offset: 327,
         key.length: 24,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>rawValue</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:s6UInt32V\">UInt32</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>",
@@ -4672,7 +4672,7 @@
       {
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init(rawValue:)",
-        key.usr: "s:SC8FooEnum2VABs6UInt32V8rawValue_tcfc",
+        key.usr: "s:SC8FooEnum2V8rawValueABs6UInt32V_tcfc",
         key.offset: 357,
         key.length: 31,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>rawValue</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:s6UInt32V\">UInt32</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>",
@@ -4680,7 +4680,7 @@
           {
             key.kind: source.lang.swift.ref.function.constructor,
             key.name: "init(rawValue:)",
-            key.usr: "s:s16RawRepresentablePxSg0A5ValueQz03rawC0_tcfc"
+            key.usr: "s:s16RawRepresentableP8rawValuexSg0aD0Qz_tcfc"
           }
         ],
         key.entities: [
@@ -4711,9 +4711,9 @@
       {
         key.kind: source.lang.swift.decl.function.operator.infix,
         key.name: "!=(_:_:)",
-        key.usr: "s:s9EquatablePsE2neoiSbx_xtFZ::SYNTHESIZED::c:@E@FooEnum2",
-        key.original_usr: "s:s9EquatablePsE2neoiSbx_xtFZ",
-        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiSbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
+        key.usr: "s:s9EquatablePsE2neoiySbx_xtFZ::SYNTHESIZED::c:@E@FooEnum2",
+        key.original_usr: "s:s9EquatablePsE2neoiySbx_xtFZ",
+        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiySbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
         key.offset: 420,
         key.length: 57,
         key.fully_annotated_decl: "<decl.function.operator.infix><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>static</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>!= </decl.name>(<decl.var.parameter><decl.var.parameter.name>lhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooEnum2\">FooEnum2</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.name>rhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooEnum2\">FooEnum2</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.operator.infix>",
@@ -4763,7 +4763,7 @@
       {
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init(_:)",
-        key.usr: "s:SC8FooEnum3VABs6UInt32Vcfc",
+        key.usr: "s:SC8FooEnum3VyABs6UInt32Vcfc",
         key.offset: 597,
         key.length: 24,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>rawValue</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:s6UInt32V\">UInt32</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>",
@@ -4780,7 +4780,7 @@
       {
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init(rawValue:)",
-        key.usr: "s:SC8FooEnum3VABs6UInt32V8rawValue_tcfc",
+        key.usr: "s:SC8FooEnum3V8rawValueABs6UInt32V_tcfc",
         key.offset: 627,
         key.length: 31,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>rawValue</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:s6UInt32V\">UInt32</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>",
@@ -4788,7 +4788,7 @@
           {
             key.kind: source.lang.swift.ref.function.constructor,
             key.name: "init(rawValue:)",
-            key.usr: "s:s16RawRepresentablePxSg0A5ValueQz03rawC0_tcfc"
+            key.usr: "s:s16RawRepresentableP8rawValuexSg0aD0Qz_tcfc"
           }
         ],
         key.entities: [
@@ -4819,9 +4819,9 @@
       {
         key.kind: source.lang.swift.decl.function.operator.infix,
         key.name: "!=(_:_:)",
-        key.usr: "s:s9EquatablePsE2neoiSbx_xtFZ::SYNTHESIZED::c:@E@FooEnum3",
-        key.original_usr: "s:s9EquatablePsE2neoiSbx_xtFZ",
-        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiSbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
+        key.usr: "s:s9EquatablePsE2neoiySbx_xtFZ::SYNTHESIZED::c:@E@FooEnum3",
+        key.original_usr: "s:s9EquatablePsE2neoiySbx_xtFZ",
+        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiySbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
         key.offset: 690,
         key.length: 57,
         key.fully_annotated_decl: "<decl.function.operator.infix><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>static</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>!= </decl.name>(<decl.var.parameter><decl.var.parameter.name>lhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooEnum3\">FooEnum3</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.name>rhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooEnum3\">FooEnum3</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.operator.infix>",
@@ -4903,9 +4903,9 @@
       {
         key.kind: source.lang.swift.decl.function.operator.infix,
         key.name: "!=(_:_:)",
-        key.usr: "s:s9EquatablePsE2neoiSbx_xtFZ::SYNTHESIZED::c:@E@FooComparisonResult",
-        key.original_usr: "s:s9EquatablePsE2neoiSbx_xtFZ",
-        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiSbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
+        key.usr: "s:s9EquatablePsE2neoiySbx_xtFZ::SYNTHESIZED::c:@E@FooComparisonResult",
+        key.original_usr: "s:s9EquatablePsE2neoiySbx_xtFZ",
+        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiySbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
         key.offset: 929,
         key.length: 79,
         key.fully_annotated_decl: "<decl.function.operator.infix><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>static</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>!= </decl.name>(<decl.var.parameter><decl.var.parameter.name>lhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.enum usr=\"c:@E@FooComparisonResult\">FooComparisonResult</ref.enum></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.name>rhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.enum usr=\"c:@E@FooComparisonResult\">FooComparisonResult</ref.enum></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.operator.infix>",
@@ -4940,7 +4940,7 @@
       {
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init(rawValue:)",
-        key.usr: "s:SC17FooRuncingOptionsVABSi8rawValue_tcfc",
+        key.usr: "s:SC17FooRuncingOptionsV8rawValueABSi_tcfc",
         key.offset: 1055,
         key.length: 28,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>rawValue</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>",
@@ -4948,12 +4948,12 @@
           {
             key.kind: source.lang.swift.ref.function.constructor,
             key.name: "init(rawValue:)",
-            key.usr: "s:s9OptionSetPx8RawValueQz03rawD0_tcfc"
+            key.usr: "s:s9OptionSetP8rawValuex03RawD0Qz_tcfc"
           },
           {
             key.kind: source.lang.swift.ref.function.constructor,
             key.name: "init(rawValue:)",
-            key.usr: "s:s16RawRepresentablePxSg0A5ValueQz03rawC0_tcfc"
+            key.usr: "s:s16RawRepresentableP8rawValuexSg0aD0Qz_tcfc"
           }
         ],
         key.entities: [
@@ -4985,9 +4985,9 @@
       {
         key.kind: source.lang.swift.decl.function.operator.infix,
         key.name: "!=(_:_:)",
-        key.usr: "s:s9EquatablePsE2neoiSbx_xtFZ::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s9EquatablePsE2neoiSbx_xtFZ",
-        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiSbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
+        key.usr: "s:s9EquatablePsE2neoiySbx_xtFZ::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s9EquatablePsE2neoiySbx_xtFZ",
+        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiySbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
         key.offset: 1200,
         key.length: 75,
         key.fully_annotated_decl: "<decl.function.operator.infix><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>static</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>!= </decl.name>(<decl.var.parameter><decl.var.parameter.name>lhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.name>rhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.operator.infix>",
@@ -5011,9 +5011,9 @@
       {
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init(arrayLiteral:)",
-        key.usr: "s:s10SetAlgebraPs7ElementQz012ArrayLiteralC0RtzrlExAF05arrayE0d_tcfc::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s10SetAlgebraPs7ElementQz012ArrayLiteralC0RtzrlExAF05arrayE0d_tcfc",
-        key.doc.full_as_xml: "<Function><Name>init(arrayLiteral:)</Name><USR>s:s10SetAlgebraPs7ElementQz012ArrayLiteralC0RtzrlExAF05arrayE0d_tcfc</USR><Declaration>convenience init(arrayLiteral: Self.Element...)</Declaration><CommentParts><Abstract><Para>Creates a set containing the elements of the given array literal.</Para></Abstract><Parameters><Parameter><Name>arrayLiteral</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A list of elements of the new set.</Para></Discussion></Parameter></Parameters><Discussion><Para>Do not call this initializer directly. It is used by the compiler when you use an array literal. Instead, create a new set using an array literal as its value by enclosing a comma-separated list of values in square brackets. You can use an array literal anywhere a set is expected by the type context.</Para><Para>Here, a set of strings is created from an array literal holding only strings:</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let ingredients: Set = [\"cocoa beans\", \"sugar\", \"cocoa butter\", \"salt\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[if ingredients.isSuperset(of: [\"sugar\", \"salt\"]) {]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[    print(\"Whatever it is, it's bound to be delicious!\")]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[}]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"Whatever it is, it's bound to be delicious!\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
+        key.usr: "s:s10SetAlgebraPs7ElementQz012ArrayLiteralC0RtzrlE05arrayE0xAFd_tcfc::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s10SetAlgebraPs7ElementQz012ArrayLiteralC0RtzrlE05arrayE0xAFd_tcfc",
+        key.doc.full_as_xml: "<Function><Name>init(arrayLiteral:)</Name><USR>s:s10SetAlgebraPs7ElementQz012ArrayLiteralC0RtzrlE05arrayE0xAFd_tcfc</USR><Declaration>convenience init(arrayLiteral: Self.Element...)</Declaration><CommentParts><Abstract><Para>Creates a set containing the elements of the given array literal.</Para></Abstract><Parameters><Parameter><Name>arrayLiteral</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A list of elements of the new set.</Para></Discussion></Parameter></Parameters><Discussion><Para>Do not call this initializer directly. It is used by the compiler when you use an array literal. Instead, create a new set using an array literal as its value by enclosing a comma-separated list of values in square brackets. You can use an array literal anywhere a set is expected by the type context.</Para><Para>Here, a set of strings is created from an array literal holding only strings:</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let ingredients: Set = [\"cocoa beans\", \"sugar\", \"cocoa butter\", \"salt\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[if ingredients.isSuperset(of: [\"sugar\", \"salt\"]) {]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[    print(\"Whatever it is, it's bound to be delicious!\")]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[}]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"Whatever it is, it's bound to be delicious!\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
         key.offset: 1281,
         key.length: 65,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>convenience</syntaxtype.keyword> <syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>arrayLiteral</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type>...</decl.var.parameter>)</decl.function.constructor>",
@@ -5043,8 +5043,8 @@
       {
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init(_:)",
-        key.usr: "s:s10SetAlgebraPsExqd__cs8SequenceRd__7ElementQyd__ADRtzlufc::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s10SetAlgebraPsExqd__cs8SequenceRd__7ElementQyd__ADRtzlufc",
+        key.usr: "s:s10SetAlgebraPsEyxqd__cs8SequenceRd__7ElementQyd__ADRtzlufc::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s10SetAlgebraPsEyxqd__cs8SequenceRd__7ElementQyd__ADRtzlufc",
         key.generic_params: [
           {
             key.name: "S"
@@ -5058,7 +5058,7 @@
             key.description: "Self.Element == S.Element"
           }
         ],
-        key.doc.full_as_xml: "<Function><Name>init(_:)</Name><USR>s:s10SetAlgebraPsExqd__cs8SequenceRd__7ElementQyd__ADRtzlufc</USR><Declaration>convenience init&lt;S&gt;(_ sequence: S) where S : Sequence, Self.Element == S.Element</Declaration><CommentParts><Abstract><Para>Creates a new set from a finite sequence of items.</Para></Abstract><Parameters><Parameter><Name>sequence</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>The elements to use as members of the new set.</Para></Discussion></Parameter></Parameters><Discussion><Para>Use this initializer to create a new set from an existing sequence, like an array or a range:</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let validIndices = Set(0..<7).subtracting([2, 4, 5])]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(validIndices)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"[6, 0, 1, 3]\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
+        key.doc.full_as_xml: "<Function><Name>init(_:)</Name><USR>s:s10SetAlgebraPsEyxqd__cs8SequenceRd__7ElementQyd__ADRtzlufc</USR><Declaration>convenience init&lt;S&gt;(_ sequence: S) where S : Sequence, Self.Element == S.Element</Declaration><CommentParts><Abstract><Para>Creates a new set from a finite sequence of items.</Para></Abstract><Parameters><Parameter><Name>sequence</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>The elements to use as members of the new set.</Para></Discussion></Parameter></Parameters><Discussion><Para>Use this initializer to create a new set from an existing sequence, like an array or a range:</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let validIndices = Set(0..<7).subtracting([2, 4, 5])]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(validIndices)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"[6, 0, 1, 3]\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
         key.offset: 1385,
         key.length: 93,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>convenience</syntaxtype.keyword> <syntaxtype.keyword>init</syntaxtype.keyword>&lt;S&gt;(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>sequence</decl.var.parameter.name>: <decl.var.parameter.type>S</decl.var.parameter.type></decl.var.parameter>) <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement>S : <ref.protocol usr=\"s:s8SequenceP\">Sequence</ref.protocol></decl.generic_type_requirement>, <decl.generic_type_requirement><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct>.<ref.typealias usr=\"s:SC17FooRuncingOptionsV7Elementa\">Element</ref.typealias> == S.Element</decl.generic_type_requirement></decl.function.constructor>",
@@ -5075,9 +5075,9 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "subtract(_:)",
-        key.usr: "s:s10SetAlgebraPsE8subtractyxF::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s10SetAlgebraPsE8subtractyxF",
-        key.doc.full_as_xml: "<Function><Name>subtract(_:)</Name><USR>s:s10SetAlgebraPsE8subtractyxF</USR><Declaration>mutating func subtract(_ other: Self)</Declaration><CommentParts><Abstract><Para>Removes the elements of the given set from this set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A set of the same type as the current set.</Para></Discussion></Parameter></Parameters><Discussion><Para>In the following example, the elements of the <codeVoice>employees</codeVoice> set that are also members of the <codeVoice>neighbors</codeVoice> set are removed. In particular, the names <codeVoice>&quot;Bethany&quot;</codeVoice> and <codeVoice>&quot;Eric&quot;</codeVoice> are removed from <codeVoice>employees</codeVoice>.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[var employees: Set = [\"Alicia\", \"Bethany\", \"Chris\", \"Diana\", \"Eric\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let neighbors: Set = [\"Bethany\", \"Eric\", \"Forlani\", \"Greta\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[employees.subtract(neighbors)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(employees)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"[\"Diana\", \"Chris\", \"Alicia\"]\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
+        key.usr: "s:s10SetAlgebraPsE8subtractyyxF::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s10SetAlgebraPsE8subtractyyxF",
+        key.doc.full_as_xml: "<Function><Name>subtract(_:)</Name><USR>s:s10SetAlgebraPsE8subtractyyxF</USR><Declaration>mutating func subtract(_ other: Self)</Declaration><CommentParts><Abstract><Para>Removes the elements of the given set from this set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A set of the same type as the current set.</Para></Discussion></Parameter></Parameters><Discussion><Para>In the following example, the elements of the <codeVoice>employees</codeVoice> set that are also members of the <codeVoice>neighbors</codeVoice> set are removed. In particular, the names <codeVoice>&quot;Bethany&quot;</codeVoice> and <codeVoice>&quot;Eric&quot;</codeVoice> are removed from <codeVoice>employees</codeVoice>.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[var employees: Set = [\"Alicia\", \"Bethany\", \"Chris\", \"Diana\", \"Eric\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let neighbors: Set = [\"Bethany\", \"Eric\", \"Forlani\", \"Greta\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[employees.subtract(neighbors)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(employees)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"[\"Diana\", \"Chris\", \"Alicia\"]\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
         key.offset: 1484,
         key.length: 50,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>mutating</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>subtract</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>other</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
@@ -5094,9 +5094,9 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "isSubset(of:)",
-        key.usr: "s:s10SetAlgebraPsE8isSubsetSbx2of_tF::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s10SetAlgebraPsE8isSubsetSbx2of_tF",
-        key.doc.full_as_xml: "<Function><Name>isSubset(of:)</Name><USR>s:s10SetAlgebraPsE8isSubsetSbx2of_tF</USR><Declaration>func isSubset(of other: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value that indicates whether the set is a subset of another set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A set of the same type as the current set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para><codeVoice>true</codeVoice> if the set is a subset of <codeVoice>other</codeVoice>; otherwise, <codeVoice>false</codeVoice>.</Para></ResultDiscussion><Discussion><Para>Set <emphasis>A</emphasis> is a subset of another set <emphasis>B</emphasis> if every member of <emphasis>A</emphasis> is also a member of <emphasis>B</emphasis>.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let employees: Set = [\"Alicia\", \"Bethany\", \"Chris\", \"Diana\", \"Eric\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let attendees: Set = [\"Alicia\", \"Bethany\", \"Diana\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(attendees.isSubset(of: employees))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
+        key.usr: "s:s10SetAlgebraPsE8isSubset2ofSbx_tF::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s10SetAlgebraPsE8isSubset2ofSbx_tF",
+        key.doc.full_as_xml: "<Function><Name>isSubset(of:)</Name><USR>s:s10SetAlgebraPsE8isSubset2ofSbx_tF</USR><Declaration>func isSubset(of other: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value that indicates whether the set is a subset of another set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A set of the same type as the current set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para><codeVoice>true</codeVoice> if the set is a subset of <codeVoice>other</codeVoice>; otherwise, <codeVoice>false</codeVoice>.</Para></ResultDiscussion><Discussion><Para>Set <emphasis>A</emphasis> is a subset of another set <emphasis>B</emphasis> if every member of <emphasis>A</emphasis> is also a member of <emphasis>B</emphasis>.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let employees: Set = [\"Alicia\", \"Bethany\", \"Chris\", \"Diana\", \"Eric\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let attendees: Set = [\"Alicia\", \"Bethany\", \"Diana\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(attendees.isSubset(of: employees))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
         key.offset: 1540,
         key.length: 50,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>isSubset</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>of</decl.var.parameter.argument_label> <decl.var.parameter.name>other</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.method.instance>",
@@ -5113,9 +5113,9 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "isSuperset(of:)",
-        key.usr: "s:s10SetAlgebraPsE10isSupersetSbx2of_tF::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s10SetAlgebraPsE10isSupersetSbx2of_tF",
-        key.doc.full_as_xml: "<Function><Name>isSuperset(of:)</Name><USR>s:s10SetAlgebraPsE10isSupersetSbx2of_tF</USR><Declaration>func isSuperset(of other: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value that indicates whether the set is a superset of the given set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A set of the same type as the current set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para><codeVoice>true</codeVoice> if the set is a superset of <codeVoice>other</codeVoice>; otherwise, <codeVoice>false</codeVoice>.</Para></ResultDiscussion><Discussion><Para>Set <emphasis>A</emphasis> is a superset of another set <emphasis>B</emphasis> if every member of <emphasis>B</emphasis> is also a member of <emphasis>A</emphasis>.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let employees: Set = [\"Alicia\", \"Bethany\", \"Chris\", \"Diana\", \"Eric\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let attendees: Set = [\"Alicia\", \"Bethany\", \"Diana\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(employees.isSuperset(of: attendees))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
+        key.usr: "s:s10SetAlgebraPsE10isSuperset2ofSbx_tF::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s10SetAlgebraPsE10isSuperset2ofSbx_tF",
+        key.doc.full_as_xml: "<Function><Name>isSuperset(of:)</Name><USR>s:s10SetAlgebraPsE10isSuperset2ofSbx_tF</USR><Declaration>func isSuperset(of other: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value that indicates whether the set is a superset of the given set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A set of the same type as the current set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para><codeVoice>true</codeVoice> if the set is a superset of <codeVoice>other</codeVoice>; otherwise, <codeVoice>false</codeVoice>.</Para></ResultDiscussion><Discussion><Para>Set <emphasis>A</emphasis> is a superset of another set <emphasis>B</emphasis> if every member of <emphasis>B</emphasis> is also a member of <emphasis>A</emphasis>.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let employees: Set = [\"Alicia\", \"Bethany\", \"Chris\", \"Diana\", \"Eric\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let attendees: Set = [\"Alicia\", \"Bethany\", \"Diana\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(employees.isSuperset(of: attendees))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
         key.offset: 1596,
         key.length: 52,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>isSuperset</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>of</decl.var.parameter.argument_label> <decl.var.parameter.name>other</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.method.instance>",
@@ -5132,9 +5132,9 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "isDisjoint(with:)",
-        key.usr: "s:s10SetAlgebraPsE10isDisjointSbx4with_tF::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s10SetAlgebraPsE10isDisjointSbx4with_tF",
-        key.doc.full_as_xml: "<Function><Name>isDisjoint(with:)</Name><USR>s:s10SetAlgebraPsE10isDisjointSbx4with_tF</USR><Declaration>func isDisjoint(with other: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value that indicates whether the set has no members in common with the given set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A set of the same type as the current set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para><codeVoice>true</codeVoice> if the set has no elements in common with <codeVoice>other</codeVoice>; otherwise, <codeVoice>false</codeVoice>.</Para></ResultDiscussion><Discussion><Para>In the following example, the <codeVoice>employees</codeVoice> set is disjoint with the <codeVoice>visitors</codeVoice> set because no name appears in both sets.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let employees: Set = [\"Alicia\", \"Bethany\", \"Chris\", \"Diana\", \"Eric\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let visitors: Set = [\"Marcia\", \"Nathaniel\", \"Olivia\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(employees.isDisjoint(with: visitors))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
+        key.usr: "s:s10SetAlgebraPsE10isDisjoint4withSbx_tF::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s10SetAlgebraPsE10isDisjoint4withSbx_tF",
+        key.doc.full_as_xml: "<Function><Name>isDisjoint(with:)</Name><USR>s:s10SetAlgebraPsE10isDisjoint4withSbx_tF</USR><Declaration>func isDisjoint(with other: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value that indicates whether the set has no members in common with the given set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A set of the same type as the current set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para><codeVoice>true</codeVoice> if the set has no elements in common with <codeVoice>other</codeVoice>; otherwise, <codeVoice>false</codeVoice>.</Para></ResultDiscussion><Discussion><Para>In the following example, the <codeVoice>employees</codeVoice> set is disjoint with the <codeVoice>visitors</codeVoice> set because no name appears in both sets.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let employees: Set = [\"Alicia\", \"Bethany\", \"Chris\", \"Diana\", \"Eric\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let visitors: Set = [\"Marcia\", \"Nathaniel\", \"Olivia\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(employees.isDisjoint(with: visitors))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
         key.offset: 1654,
         key.length: 54,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>isDisjoint</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>with</decl.var.parameter.argument_label> <decl.var.parameter.name>other</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.method.instance>",
@@ -5151,9 +5151,9 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "subtracting(_:)",
-        key.usr: "s:s10SetAlgebraPsE11subtractingxxF::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s10SetAlgebraPsE11subtractingxxF",
-        key.doc.full_as_xml: "<Function><Name>subtracting(_:)</Name><USR>s:s10SetAlgebraPsE11subtractingxxF</USR><Declaration>func subtracting(_ other: Self) -&gt; Self</Declaration><CommentParts><Abstract><Para>Returns a new set containing the elements of this set that do not occur in the given set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A set of the same type as the current set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para>A new set.</Para></ResultDiscussion><Discussion><Para>In the following example, the <codeVoice>nonNeighbors</codeVoice> set is made up of the elements of the <codeVoice>employees</codeVoice> set that are not elements of <codeVoice>neighbors</codeVoice>:</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let employees: Set = [\"Alicia\", \"Bethany\", \"Chris\", \"Diana\", \"Eric\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let neighbors: Set = [\"Bethany\", \"Eric\", \"Forlani\", \"Greta\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let nonNeighbors = employees.subtract(neighbors)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(nonNeighbors)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"[\"Diana\", \"Chris\", \"Alicia\"]\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
+        key.usr: "s:s10SetAlgebraPsE11subtractingyxxF::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s10SetAlgebraPsE11subtractingyxxF",
+        key.doc.full_as_xml: "<Function><Name>subtracting(_:)</Name><USR>s:s10SetAlgebraPsE11subtractingyxxF</USR><Declaration>func subtracting(_ other: Self) -&gt; Self</Declaration><CommentParts><Abstract><Para>Returns a new set containing the elements of this set that do not occur in the given set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A set of the same type as the current set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para>A new set.</Para></ResultDiscussion><Discussion><Para>In the following example, the <codeVoice>nonNeighbors</codeVoice> set is made up of the elements of the <codeVoice>employees</codeVoice> set that are not elements of <codeVoice>neighbors</codeVoice>:</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let employees: Set = [\"Alicia\", \"Bethany\", \"Chris\", \"Diana\", \"Eric\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let neighbors: Set = [\"Bethany\", \"Eric\", \"Forlani\", \"Greta\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let nonNeighbors = employees.subtract(neighbors)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(nonNeighbors)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"[\"Diana\", \"Chris\", \"Alicia\"]\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
         key.offset: 1714,
         key.length: 65,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>subtracting</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>other</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.function.returntype></decl.function.method.instance>",
@@ -5180,9 +5180,9 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "isStrictSuperset(of:)",
-        key.usr: "s:s10SetAlgebraPsE16isStrictSupersetSbx2of_tF::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s10SetAlgebraPsE16isStrictSupersetSbx2of_tF",
-        key.doc.full_as_xml: "<Function><Name>isStrictSuperset(of:)</Name><USR>s:s10SetAlgebraPsE16isStrictSupersetSbx2of_tF</USR><Declaration>func isStrictSuperset(of other: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value that indicates whether this set is a strict superset of the given set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A set of the same type as the current set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para><codeVoice>true</codeVoice> if the set is a strict superset of <codeVoice>other</codeVoice>; otherwise, <codeVoice>false</codeVoice>.</Para></ResultDiscussion><Discussion><Para>Set <emphasis>A</emphasis> is a strict superset of another set <emphasis>B</emphasis> if every member of <emphasis>B</emphasis> is also a member of <emphasis>A</emphasis> and <emphasis>A</emphasis> contains at least one element that is <emphasis>not</emphasis> a member of <emphasis>B</emphasis>.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let employees: Set = [\"Alicia\", \"Bethany\", \"Chris\", \"Diana\", \"Eric\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let attendees: Set = [\"Alicia\", \"Bethany\", \"Diana\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(employees.isStrictSuperset(of: attendees))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// A set is never a strict superset of itself:]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(employees.isStrictSuperset(of: employees))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"false\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
+        key.usr: "s:s10SetAlgebraPsE16isStrictSuperset2ofSbx_tF::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s10SetAlgebraPsE16isStrictSuperset2ofSbx_tF",
+        key.doc.full_as_xml: "<Function><Name>isStrictSuperset(of:)</Name><USR>s:s10SetAlgebraPsE16isStrictSuperset2ofSbx_tF</USR><Declaration>func isStrictSuperset(of other: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value that indicates whether this set is a strict superset of the given set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A set of the same type as the current set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para><codeVoice>true</codeVoice> if the set is a strict superset of <codeVoice>other</codeVoice>; otherwise, <codeVoice>false</codeVoice>.</Para></ResultDiscussion><Discussion><Para>Set <emphasis>A</emphasis> is a strict superset of another set <emphasis>B</emphasis> if every member of <emphasis>B</emphasis> is also a member of <emphasis>A</emphasis> and <emphasis>A</emphasis> contains at least one element that is <emphasis>not</emphasis> a member of <emphasis>B</emphasis>.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let employees: Set = [\"Alicia\", \"Bethany\", \"Chris\", \"Diana\", \"Eric\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let attendees: Set = [\"Alicia\", \"Bethany\", \"Diana\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(employees.isStrictSuperset(of: attendees))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// A set is never a strict superset of itself:]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(employees.isStrictSuperset(of: employees))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"false\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
         key.offset: 1816,
         key.length: 58,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>isStrictSuperset</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>of</decl.var.parameter.argument_label> <decl.var.parameter.name>other</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.method.instance>",
@@ -5199,9 +5199,9 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "isStrictSubset(of:)",
-        key.usr: "s:s10SetAlgebraPsE14isStrictSubsetSbx2of_tF::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s10SetAlgebraPsE14isStrictSubsetSbx2of_tF",
-        key.doc.full_as_xml: "<Function><Name>isStrictSubset(of:)</Name><USR>s:s10SetAlgebraPsE14isStrictSubsetSbx2of_tF</USR><Declaration>func isStrictSubset(of other: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value that indicates whether this set is a strict subset of the given set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A set of the same type as the current set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para><codeVoice>true</codeVoice> if the set is a strict subset of <codeVoice>other</codeVoice>; otherwise, <codeVoice>false</codeVoice>.</Para></ResultDiscussion><Discussion><Para>Set <emphasis>A</emphasis> is a strict subset of another set <emphasis>B</emphasis> if every member of <emphasis>A</emphasis> is also a member of <emphasis>B</emphasis> and <emphasis>B</emphasis> contains at least one element that is not a member of <emphasis>A</emphasis>.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let employees: Set = [\"Alicia\", \"Bethany\", \"Chris\", \"Diana\", \"Eric\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let attendees: Set = [\"Alicia\", \"Bethany\", \"Diana\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(attendees.isStrictSubset(of: employees))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// A set is never a strict subset of itself:]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(attendees.isStrictSubset(of: attendees))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"false\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
+        key.usr: "s:s10SetAlgebraPsE14isStrictSubset2ofSbx_tF::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s10SetAlgebraPsE14isStrictSubset2ofSbx_tF",
+        key.doc.full_as_xml: "<Function><Name>isStrictSubset(of:)</Name><USR>s:s10SetAlgebraPsE14isStrictSubset2ofSbx_tF</USR><Declaration>func isStrictSubset(of other: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value that indicates whether this set is a strict subset of the given set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A set of the same type as the current set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para><codeVoice>true</codeVoice> if the set is a strict subset of <codeVoice>other</codeVoice>; otherwise, <codeVoice>false</codeVoice>.</Para></ResultDiscussion><Discussion><Para>Set <emphasis>A</emphasis> is a strict subset of another set <emphasis>B</emphasis> if every member of <emphasis>A</emphasis> is also a member of <emphasis>B</emphasis> and <emphasis>B</emphasis> contains at least one element that is not a member of <emphasis>A</emphasis>.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let employees: Set = [\"Alicia\", \"Bethany\", \"Chris\", \"Diana\", \"Eric\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let attendees: Set = [\"Alicia\", \"Bethany\", \"Diana\"]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(attendees.isStrictSubset(of: employees))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// A set is never a strict subset of itself:]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(attendees.isStrictSubset(of: attendees))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"false\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
         key.offset: 1880,
         key.length: 56,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>isStrictSubset</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>of</decl.var.parameter.argument_label> <decl.var.parameter.name>other</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.method.instance>",
@@ -5231,9 +5231,9 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "union(_:)",
-        key.usr: "s:s9OptionSetPsE5unionxxF::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s9OptionSetPsE5unionxxF",
-        key.doc.full_as_xml: "<Function><Name>union(_:)</Name><USR>s:s9OptionSetPsE5unionxxF</USR><Declaration>func union(_ other: Self) -&gt; Self</Declaration><CommentParts><Abstract><Para>Returns a new option set of the elements contained in this set, in the given set, or in both.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>An option set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para>A new option set made up of the elements contained in this set, in <codeVoice>other</codeVoice>, or in both.</Para></ResultDiscussion><Discussion><Para>This example uses the <codeVoice>union(_:)</codeVoice> method to add two more shipping options to the default set.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let defaultShipping = ShippingOptions.standard]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let memberShipping = defaultShipping.union([.secondDay, .priority])]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(memberShipping.contains(.priority))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
+        key.usr: "s:s9OptionSetPsE5unionyxxF::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s9OptionSetPsE5unionyxxF",
+        key.doc.full_as_xml: "<Function><Name>union(_:)</Name><USR>s:s9OptionSetPsE5unionyxxF</USR><Declaration>func union(_ other: Self) -&gt; Self</Declaration><CommentParts><Abstract><Para>Returns a new option set of the elements contained in this set, in the given set, or in both.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>An option set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para>A new option set made up of the elements contained in this set, in <codeVoice>other</codeVoice>, or in both.</Para></ResultDiscussion><Discussion><Para>This example uses the <codeVoice>union(_:)</codeVoice> method to add two more shipping options to the default set.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let defaultShipping = ShippingOptions.standard]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let memberShipping = defaultShipping.union([.secondDay, .priority])]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(memberShipping.contains(.priority))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
         key.offset: 1975,
         key.length: 59,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>union</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>other</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.function.returntype></decl.function.method.instance>",
@@ -5250,9 +5250,9 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "intersection(_:)",
-        key.usr: "s:s9OptionSetPsE12intersectionxxF::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s9OptionSetPsE12intersectionxxF",
-        key.doc.full_as_xml: "<Function><Name>intersection(_:)</Name><USR>s:s9OptionSetPsE12intersectionxxF</USR><Declaration>func intersection(_ other: Self) -&gt; Self</Declaration><CommentParts><Abstract><Para>Returns a new option set with only the elements contained in both this set and the given set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>An option set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para>A new option set with only the elements contained in both this set and <codeVoice>other</codeVoice>.</Para></ResultDiscussion><Discussion><Para>This example uses the <codeVoice>intersection(_:)</codeVoice> method to limit the available shipping options to what can be used with a PO Box destination.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[// Can only ship standard or priority to PO Boxes]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let poboxShipping: ShippingOptions = [.standard, .priority]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let memberShipping: ShippingOptions =]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[        [.standard, .priority, .secondDay]]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let availableOptions = memberShipping.intersection(poboxShipping)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(availableOptions.contains(.priority))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(availableOptions.contains(.secondDay))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"false\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
+        key.usr: "s:s9OptionSetPsE12intersectionyxxF::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s9OptionSetPsE12intersectionyxxF",
+        key.doc.full_as_xml: "<Function><Name>intersection(_:)</Name><USR>s:s9OptionSetPsE12intersectionyxxF</USR><Declaration>func intersection(_ other: Self) -&gt; Self</Declaration><CommentParts><Abstract><Para>Returns a new option set with only the elements contained in both this set and the given set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>An option set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para>A new option set with only the elements contained in both this set and <codeVoice>other</codeVoice>.</Para></ResultDiscussion><Discussion><Para>This example uses the <codeVoice>intersection(_:)</codeVoice> method to limit the available shipping options to what can be used with a PO Box destination.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[// Can only ship standard or priority to PO Boxes]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let poboxShipping: ShippingOptions = [.standard, .priority]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let memberShipping: ShippingOptions =]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[        [.standard, .priority, .secondDay]]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let availableOptions = memberShipping.intersection(poboxShipping)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(availableOptions.contains(.priority))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(availableOptions.contains(.secondDay))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"false\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
         key.offset: 2040,
         key.length: 66,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>intersection</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>other</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.function.returntype></decl.function.method.instance>",
@@ -5269,9 +5269,9 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "symmetricDifference(_:)",
-        key.usr: "s:s9OptionSetPsE19symmetricDifferencexxF::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s9OptionSetPsE19symmetricDifferencexxF",
-        key.doc.full_as_xml: "<Function><Name>symmetricDifference(_:)</Name><USR>s:s9OptionSetPsE19symmetricDifferencexxF</USR><Declaration>func symmetricDifference(_ other: Self) -&gt; Self</Declaration><CommentParts><Abstract><Para>Returns a new option set with the elements contained in this set or in the given set, but not in both.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>An option set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para>A new option set with only the elements contained in either this set or <codeVoice>other</codeVoice>, but not in both.</Para></ResultDiscussion></CommentParts></Function>",
+        key.usr: "s:s9OptionSetPsE19symmetricDifferenceyxxF::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s9OptionSetPsE19symmetricDifferenceyxxF",
+        key.doc.full_as_xml: "<Function><Name>symmetricDifference(_:)</Name><USR>s:s9OptionSetPsE19symmetricDifferenceyxxF</USR><Declaration>func symmetricDifference(_ other: Self) -&gt; Self</Declaration><CommentParts><Abstract><Para>Returns a new option set with the elements contained in this set or in the given set, but not in both.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>An option set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para>A new option set with only the elements contained in either this set or <codeVoice>other</codeVoice>, but not in both.</Para></ResultDiscussion></CommentParts></Function>",
         key.offset: 2112,
         key.length: 73,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>symmetricDifference</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>other</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.function.returntype></decl.function.method.instance>",
@@ -5306,9 +5306,9 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "contains(_:)",
-        key.usr: "s:s9OptionSetPs7ElementQzRszrlE8containsSbxF::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s9OptionSetPs7ElementQzRszrlE8containsSbxF",
-        key.doc.full_as_xml: "<Function><Name>contains(_:)</Name><USR>s:s9OptionSetPs7ElementQzRszrlE8containsSbxF</USR><Declaration>func contains(_ member: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value that indicates whether a given element is a member of the option set.</Para></Abstract><Parameters><Parameter><Name>member</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>The element to look for in the option set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para><codeVoice>true</codeVoice> if the option set contains <codeVoice>member</codeVoice>; otherwise, <codeVoice>false</codeVoice>.</Para></ResultDiscussion><Discussion><Para>This example uses the <codeVoice>contains(_:)</codeVoice> method to check whether next-day shipping is in the <codeVoice>availableOptions</codeVoice> instance.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let availableOptions = ShippingOptions.express]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[if availableOptions.contains(.nextDay) {]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[    print(\"Next day shipping available\")]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[}]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"Next day shipping available\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
+        key.usr: "s:s9OptionSetPs7ElementQzRszrlE8containsySbxF::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s9OptionSetPs7ElementQzRszrlE8containsySbxF",
+        key.doc.full_as_xml: "<Function><Name>contains(_:)</Name><USR>s:s9OptionSetPs7ElementQzRszrlE8containsySbxF</USR><Declaration>func contains(_ member: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value that indicates whether a given element is a member of the option set.</Para></Abstract><Parameters><Parameter><Name>member</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>The element to look for in the option set.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para><codeVoice>true</codeVoice> if the option set contains <codeVoice>member</codeVoice>; otherwise, <codeVoice>false</codeVoice>.</Para></ResultDiscussion><Discussion><Para>This example uses the <codeVoice>contains(_:)</codeVoice> method to check whether next-day shipping is in the <codeVoice>availableOptions</codeVoice> instance.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let availableOptions = ShippingOptions.express]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[if availableOptions.contains(.nextDay) {]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[    print(\"Next day shipping available\")]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[}]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"Next day shipping available\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
         key.offset: 2224,
         key.length: 50,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>contains</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>member</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.method.instance>",
@@ -5325,9 +5325,9 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "insert(_:)",
-        key.usr: "s:s9OptionSetPs7ElementQzRszrlE6insertSb8inserted_x17memberAfterInserttxF::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s9OptionSetPs7ElementQzRszrlE6insertSb8inserted_x17memberAfterInserttxF",
-        key.doc.full_as_xml: "<Function><Name>insert(_:)</Name><USR>s:s9OptionSetPs7ElementQzRszrlE6insertSb8inserted_x17memberAfterInserttxF</USR><Declaration>mutating func insert(_ newMember: Self.Element) -&gt; (inserted: Bool, memberAfterInsert: Self.Element)</Declaration><CommentParts><Abstract><Para>Adds the given element to the option set if it is not already a member.</Para></Abstract><Parameters><Parameter><Name>newMember</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>The element to insert.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para><codeVoice>(true, newMember)</codeVoice> if <codeVoice>newMember</codeVoice> was not contained in <codeVoice>self</codeVoice>. Otherwise, returns <codeVoice>(false, oldMember)</codeVoice>, where <codeVoice>oldMember</codeVoice> is the member of the set equal to <codeVoice>newMember</codeVoice>.</Para></ResultDiscussion><Discussion><Para>In the following example, the <codeVoice>.secondDay</codeVoice> shipping option is added to the <codeVoice>freeOptions</codeVoice> option set if <codeVoice>purchasePrice</codeVoice> is greater than 50.0. For the <codeVoice>ShippingOptions</codeVoice> declaration, see the <codeVoice>OptionSet</codeVoice> protocol discussion.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let purchasePrice = 87.55]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered><zCodeLineNumbered><![CDATA[var freeOptions: ShippingOptions = [.standard, .priority]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[if purchasePrice > 50 {]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[    freeOptions.insert(.secondDay)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[}]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(freeOptions.contains(.secondDay))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
+        key.usr: "s:s9OptionSetPs7ElementQzRszrlE6insertySb8inserted_x17memberAfterInserttxF::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s9OptionSetPs7ElementQzRszrlE6insertySb8inserted_x17memberAfterInserttxF",
+        key.doc.full_as_xml: "<Function><Name>insert(_:)</Name><USR>s:s9OptionSetPs7ElementQzRszrlE6insertySb8inserted_x17memberAfterInserttxF</USR><Declaration>mutating func insert(_ newMember: Self.Element) -&gt; (inserted: Bool, memberAfterInsert: Self.Element)</Declaration><CommentParts><Abstract><Para>Adds the given element to the option set if it is not already a member.</Para></Abstract><Parameters><Parameter><Name>newMember</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>The element to insert.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para><codeVoice>(true, newMember)</codeVoice> if <codeVoice>newMember</codeVoice> was not contained in <codeVoice>self</codeVoice>. Otherwise, returns <codeVoice>(false, oldMember)</codeVoice>, where <codeVoice>oldMember</codeVoice> is the member of the set equal to <codeVoice>newMember</codeVoice>.</Para></ResultDiscussion><Discussion><Para>In the following example, the <codeVoice>.secondDay</codeVoice> shipping option is added to the <codeVoice>freeOptions</codeVoice> option set if <codeVoice>purchasePrice</codeVoice> is greater than 50.0. For the <codeVoice>ShippingOptions</codeVoice> declaration, see the <codeVoice>OptionSet</codeVoice> protocol discussion.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let purchasePrice = 87.55]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered><zCodeLineNumbered><![CDATA[var freeOptions: ShippingOptions = [.standard, .priority]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[if purchasePrice > 50 {]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[    freeOptions.insert(.secondDay)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[}]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(freeOptions.contains(.secondDay))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
         key.offset: 2280,
         key.length: 110,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@discardableResult</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>mutating</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>insert</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>newMember</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><tuple>(<tuple.element><tuple.element.argument_label>inserted</tuple.element.argument_label>: <tuple.element.type><ref.struct usr=\"s:Sb\">Bool</ref.struct></tuple.element.type></tuple.element>, <tuple.element><tuple.element.argument_label>memberAfterInsert</tuple.element.argument_label>: <tuple.element.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></tuple.element.type></tuple.element>)</tuple></decl.function.returntype></decl.function.method.instance>",
@@ -5344,9 +5344,9 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "remove(_:)",
-        key.usr: "s:s9OptionSetPs7ElementQzRszrlE6removexSgxF::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s9OptionSetPs7ElementQzRszrlE6removexSgxF",
-        key.doc.full_as_xml: "<Function><Name>remove(_:)</Name><USR>s:s9OptionSetPs7ElementQzRszrlE6removexSgxF</USR><Declaration>mutating func remove(_ member: Self.Element) -&gt; Self.Element?</Declaration><CommentParts><Abstract><Para>Removes the given element and all elements subsumed by it.</Para></Abstract><Parameters><Parameter><Name>member</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>The element of the set to remove.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para>The intersection of <codeVoice>[member]</codeVoice> and the set, if the intersection was nonempty; otherwise, <codeVoice>nil</codeVoice>.</Para></ResultDiscussion><Discussion><Para>In the following example, the <codeVoice>.priority</codeVoice> shipping option is removed from the <codeVoice>options</codeVoice> option set. Attempting to remove the same shipping option a second time results in <codeVoice>nil</codeVoice>, because <codeVoice>options</codeVoice> no longer contains <codeVoice>.priority</codeVoice> as a member.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[var options: ShippingOptions = [.secondDay, .priority]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let priorityOption = options.remove(.priority)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(priorityOption == .priority)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(options.remove(.priority))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"nil\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing><Para>In the next example, the <codeVoice>.express</codeVoice> element is passed to <codeVoice>remove(_:)</codeVoice>. Although <codeVoice>.express</codeVoice> is not a member of <codeVoice>options</codeVoice>, <codeVoice>.express</codeVoice> subsumes the remaining <codeVoice>.secondDay</codeVoice> element of the option set. Therefore, <codeVoice>options</codeVoice> is emptied and the intersection between <codeVoice>.express</codeVoice> and <codeVoice>options</codeVoice> is returned.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let expressOption = options.remove(.express)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(expressOption == .express)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"false\"]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(expressOption == .secondDay)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
+        key.usr: "s:s9OptionSetPs7ElementQzRszrlE6removeyxSgxF::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s9OptionSetPs7ElementQzRszrlE6removeyxSgxF",
+        key.doc.full_as_xml: "<Function><Name>remove(_:)</Name><USR>s:s9OptionSetPs7ElementQzRszrlE6removeyxSgxF</USR><Declaration>mutating func remove(_ member: Self.Element) -&gt; Self.Element?</Declaration><CommentParts><Abstract><Para>Removes the given element and all elements subsumed by it.</Para></Abstract><Parameters><Parameter><Name>member</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>The element of the set to remove.</Para></Discussion></Parameter></Parameters><ResultDiscussion><Para>The intersection of <codeVoice>[member]</codeVoice> and the set, if the intersection was nonempty; otherwise, <codeVoice>nil</codeVoice>.</Para></ResultDiscussion><Discussion><Para>In the following example, the <codeVoice>.priority</codeVoice> shipping option is removed from the <codeVoice>options</codeVoice> option set. Attempting to remove the same shipping option a second time results in <codeVoice>nil</codeVoice>, because <codeVoice>options</codeVoice> no longer contains <codeVoice>.priority</codeVoice> as a member.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[var options: ShippingOptions = [.secondDay, .priority]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let priorityOption = options.remove(.priority)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(priorityOption == .priority)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(options.remove(.priority))]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"nil\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing><Para>In the next example, the <codeVoice>.express</codeVoice> element is passed to <codeVoice>remove(_:)</codeVoice>. Although <codeVoice>.express</codeVoice> is not a member of <codeVoice>options</codeVoice>, <codeVoice>.express</codeVoice> subsumes the remaining <codeVoice>.secondDay</codeVoice> element of the option set. Therefore, <codeVoice>options</codeVoice> is emptied and the intersection between <codeVoice>.express</codeVoice> and <codeVoice>options</codeVoice> is returned.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[let expressOption = options.remove(.express)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(expressOption == .express)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"false\"]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(expressOption == .secondDay)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
         key.offset: 2396,
         key.length: 71,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@discardableResult</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>mutating</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>remove</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>member</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct>?</decl.function.returntype></decl.function.method.instance>",
@@ -5363,9 +5363,9 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "update(with:)",
-        key.usr: "s:s9OptionSetPs7ElementQzRszrlE6updatexSgx4with_tF::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s9OptionSetPs7ElementQzRszrlE6updatexSgx4with_tF",
-        key.doc.full_as_xml: "<Function><Name>update(with:)</Name><USR>s:s9OptionSetPs7ElementQzRszrlE6updatexSgx4with_tF</USR><Declaration>mutating func update(with newMember: Self.Element) -&gt; Self.Element?</Declaration><CommentParts><Abstract><Para>Inserts the given element into the set.</Para></Abstract><ResultDiscussion><Para>The intersection of <codeVoice>[newMember]</codeVoice> and the set if the intersection was nonempty; otherwise, <codeVoice>nil</codeVoice>.</Para></ResultDiscussion><Discussion><Para>If <codeVoice>newMember</codeVoice> is not contained in the set but subsumes current members of the set, the subsumed members are returned.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[var options: ShippingOptions = [.secondDay, .priority]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let replaced = options.update(with: .express)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(replaced == .secondDay)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
+        key.usr: "s:s9OptionSetPs7ElementQzRszrlE6update4withxSgx_tF::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s9OptionSetPs7ElementQzRszrlE6update4withxSgx_tF",
+        key.doc.full_as_xml: "<Function><Name>update(with:)</Name><USR>s:s9OptionSetPs7ElementQzRszrlE6update4withxSgx_tF</USR><Declaration>mutating func update(with newMember: Self.Element) -&gt; Self.Element?</Declaration><CommentParts><Abstract><Para>Inserts the given element into the set.</Para></Abstract><ResultDiscussion><Para>The intersection of <codeVoice>[newMember]</codeVoice> and the set if the intersection was nonempty; otherwise, <codeVoice>nil</codeVoice>.</Para></ResultDiscussion><Discussion><Para>If <codeVoice>newMember</codeVoice> is not contained in the set but subsumes current members of the set, the subsumed members are returned.</Para><CodeListing language=\"swift\"><zCodeLineNumbered><![CDATA[var options: ShippingOptions = [.secondDay, .priority]]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[let replaced = options.update(with: .express)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[print(replaced == .secondDay)]]></zCodeLineNumbered><zCodeLineNumbered><![CDATA[// Prints \"true\"]]></zCodeLineNumbered><zCodeLineNumbered></zCodeLineNumbered></CodeListing></Discussion></CommentParts></Function>",
         key.offset: 2473,
         key.length: 77,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@discardableResult</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>mutating</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>update</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>with</decl.var.parameter.argument_label> <decl.var.parameter.name>newMember</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct>?</decl.function.returntype></decl.function.method.instance>",
@@ -5410,9 +5410,9 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "formUnion(_:)",
-        key.usr: "s:s9OptionSetPss17FixedWidthInteger8RawValueRpzrlE9formUnionyxF::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s9OptionSetPss17FixedWidthInteger8RawValueRpzrlE9formUnionyxF",
-        key.doc.full_as_xml: "<Function><Name>formUnion(_:)</Name><USR>s:s9OptionSetPss17FixedWidthInteger8RawValueRpzrlE9formUnionyxF</USR><Declaration>mutating func formUnion(_ other: Self)</Declaration><CommentParts><Abstract><Para>Inserts the elements of another set into this option set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>An option set.</Para></Discussion></Parameter></Parameters><Discussion><Para>This method is implemented as a <codeVoice>|</codeVoice> (bitwise OR) operation on the two sets’ raw values.</Para></Discussion></CommentParts></Function>",
+        key.usr: "s:s9OptionSetPss17FixedWidthInteger8RawValueRpzrlE9formUnionyyxF::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s9OptionSetPss17FixedWidthInteger8RawValueRpzrlE9formUnionyyxF",
+        key.doc.full_as_xml: "<Function><Name>formUnion(_:)</Name><USR>s:s9OptionSetPss17FixedWidthInteger8RawValueRpzrlE9formUnionyyxF</USR><Declaration>mutating func formUnion(_ other: Self)</Declaration><CommentParts><Abstract><Para>Inserts the elements of another set into this option set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>An option set.</Para></Discussion></Parameter></Parameters><Discussion><Para>This method is implemented as a <codeVoice>|</codeVoice> (bitwise OR) operation on the two sets’ raw values.</Para></Discussion></CommentParts></Function>",
         key.offset: 2613,
         key.length: 51,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>mutating</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>formUnion</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>other</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
@@ -5429,9 +5429,9 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "formIntersection(_:)",
-        key.usr: "s:s9OptionSetPss17FixedWidthInteger8RawValueRpzrlE16formIntersectionyxF::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s9OptionSetPss17FixedWidthInteger8RawValueRpzrlE16formIntersectionyxF",
-        key.doc.full_as_xml: "<Function><Name>formIntersection(_:)</Name><USR>s:s9OptionSetPss17FixedWidthInteger8RawValueRpzrlE16formIntersectionyxF</USR><Declaration>mutating func formIntersection(_ other: Self)</Declaration><CommentParts><Abstract><Para>Removes all elements of this option set that are not also present in the given set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>An option set.</Para></Discussion></Parameter></Parameters><Discussion><Para>This method is implemented as a <codeVoice>&amp;</codeVoice> (bitwise AND) operation on the two sets’ raw values.</Para></Discussion></CommentParts></Function>",
+        key.usr: "s:s9OptionSetPss17FixedWidthInteger8RawValueRpzrlE16formIntersectionyyxF::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s9OptionSetPss17FixedWidthInteger8RawValueRpzrlE16formIntersectionyyxF",
+        key.doc.full_as_xml: "<Function><Name>formIntersection(_:)</Name><USR>s:s9OptionSetPss17FixedWidthInteger8RawValueRpzrlE16formIntersectionyyxF</USR><Declaration>mutating func formIntersection(_ other: Self)</Declaration><CommentParts><Abstract><Para>Removes all elements of this option set that are not also present in the given set.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>An option set.</Para></Discussion></Parameter></Parameters><Discussion><Para>This method is implemented as a <codeVoice>&amp;</codeVoice> (bitwise AND) operation on the two sets’ raw values.</Para></Discussion></CommentParts></Function>",
         key.offset: 2670,
         key.length: 58,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>mutating</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>formIntersection</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>other</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
@@ -5448,9 +5448,9 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "formSymmetricDifference(_:)",
-        key.usr: "s:s9OptionSetPss17FixedWidthInteger8RawValueRpzrlE23formSymmetricDifferenceyxF::SYNTHESIZED::c:@E@FooRuncingOptions",
-        key.original_usr: "s:s9OptionSetPss17FixedWidthInteger8RawValueRpzrlE23formSymmetricDifferenceyxF",
-        key.doc.full_as_xml: "<Function><Name>formSymmetricDifference(_:)</Name><USR>s:s9OptionSetPss17FixedWidthInteger8RawValueRpzrlE23formSymmetricDifferenceyxF</USR><Declaration>mutating func formSymmetricDifference(_ other: Self)</Declaration><CommentParts><Abstract><Para>Replaces this set with a new set containing all elements contained in either this set or the given set, but not in both.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>An option set.</Para></Discussion></Parameter></Parameters><Discussion><Para>This method is implemented as a <codeVoice>^</codeVoice> (bitwise XOR) operation on the two sets’ raw values.</Para></Discussion></CommentParts></Function>",
+        key.usr: "s:s9OptionSetPss17FixedWidthInteger8RawValueRpzrlE23formSymmetricDifferenceyyxF::SYNTHESIZED::c:@E@FooRuncingOptions",
+        key.original_usr: "s:s9OptionSetPss17FixedWidthInteger8RawValueRpzrlE23formSymmetricDifferenceyyxF",
+        key.doc.full_as_xml: "<Function><Name>formSymmetricDifference(_:)</Name><USR>s:s9OptionSetPss17FixedWidthInteger8RawValueRpzrlE23formSymmetricDifferenceyyxF</USR><Declaration>mutating func formSymmetricDifference(_ other: Self)</Declaration><CommentParts><Abstract><Para>Replaces this set with a new set containing all elements contained in either this set or the given set, but not in both.</Para></Abstract><Parameters><Parameter><Name>other</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>An option set.</Para></Discussion></Parameter></Parameters><Discussion><Para>This method is implemented as a <codeVoice>^</codeVoice> (bitwise XOR) operation on the two sets’ raw values.</Para></Discussion></CommentParts></Function>",
         key.offset: 2734,
         key.length: 65,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>mutating</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>formSymmetricDifference</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>other</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooRuncingOptions\">FooRuncingOptions</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
@@ -5501,7 +5501,7 @@
       {
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init(x:y:)",
-        key.usr: "s:SC10FooStruct1VABs5Int32V1x_Sd1ytcfc",
+        key.usr: "s:SC10FooStruct1V1x1yABs5Int32V_Sdtcfc",
         key.offset: 2876,
         key.length: 29,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>x</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:s5Int32V\">Int32</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>y</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:Sd\">Double</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>",
@@ -5574,7 +5574,7 @@
       {
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init(x:y:)",
-        key.usr: "s:SC10FooStruct2VABs5Int32V1x_Sd1ytcfc",
+        key.usr: "s:SC10FooStruct2V1x1yABs5Int32V_Sdtcfc",
         key.offset: 3045,
         key.length: 29,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>x</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:s5Int32V\">Int32</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>y</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:Sd\">Double</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>",
@@ -5640,7 +5640,7 @@
       {
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init(x:y:)",
-        key.usr: "s:SC17FooStructTypedef2VABs5Int32V1x_Sd1ytcfc",
+        key.usr: "s:SC17FooStructTypedef2V1x1yABs5Int32V_Sdtcfc",
         key.offset: 3199,
         key.length: 29,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>x</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:s5Int32V\">Int32</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>y</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:Sd\">Double</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>",
@@ -6437,7 +6437,7 @@
       {
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init(x:)",
-        key.usr: "s:SC15_InternalStructVABs5Int32V1x_tcfc",
+        key.usr: "s:SC15_InternalStructV1xABs5Int32V_tcfc",
         key.offset: 5789,
         key.length: 16,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>x</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:s5Int32V\">Int32</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>",
@@ -7001,9 +7001,9 @@
       {
         key.kind: source.lang.swift.decl.function.operator.infix,
         key.name: "!=(_:_:)",
-        key.usr: "s:s9EquatablePsE2neoiSbx_xtFZ::SYNTHESIZED::c:@E@ABAuthorizationStatus",
-        key.original_usr: "s:s9EquatablePsE2neoiSbx_xtFZ",
-        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiSbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
+        key.usr: "s:s9EquatablePsE2neoiySbx_xtFZ::SYNTHESIZED::c:@E@ABAuthorizationStatus",
+        key.original_usr: "s:s9EquatablePsE2neoiySbx_xtFZ",
+        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiySbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
         key.offset: 7284,
         key.length: 83,
         key.fully_annotated_decl: "<decl.function.operator.infix><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>static</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>!= </decl.name>(<decl.var.parameter><decl.var.parameter.name>lhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.enum usr=\"c:@E@ABAuthorizationStatus\">ABAuthorizationStatus</ref.enum></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.name>rhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.enum usr=\"c:@E@ABAuthorizationStatus\">ABAuthorizationStatus</ref.enum></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.operator.infix>",
@@ -7063,7 +7063,7 @@
       {
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init(_:)",
-        key.usr: "s:SC11FooSubEnum1VABs6UInt32Vcfc",
+        key.usr: "s:SC11FooSubEnum1VyABs6UInt32Vcfc",
         key.offset: 7464,
         key.length: 24,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>rawValue</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:s6UInt32V\">UInt32</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>",
@@ -7080,7 +7080,7 @@
       {
         key.kind: source.lang.swift.decl.function.constructor,
         key.name: "init(rawValue:)",
-        key.usr: "s:SC11FooSubEnum1VABs6UInt32V8rawValue_tcfc",
+        key.usr: "s:SC11FooSubEnum1V8rawValueABs6UInt32V_tcfc",
         key.offset: 7494,
         key.length: 31,
         key.fully_annotated_decl: "<decl.function.constructor><syntaxtype.keyword>init</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>rawValue</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:s6UInt32V\">UInt32</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.constructor>",
@@ -7088,7 +7088,7 @@
           {
             key.kind: source.lang.swift.ref.function.constructor,
             key.name: "init(rawValue:)",
-            key.usr: "s:s16RawRepresentablePxSg0A5ValueQz03rawC0_tcfc"
+            key.usr: "s:s16RawRepresentableP8rawValuexSg0aD0Qz_tcfc"
           }
         ],
         key.entities: [
@@ -7119,9 +7119,9 @@
       {
         key.kind: source.lang.swift.decl.function.operator.infix,
         key.name: "!=(_:_:)",
-        key.usr: "s:s9EquatablePsE2neoiSbx_xtFZ::SYNTHESIZED::c:@E@FooSubEnum1",
-        key.original_usr: "s:s9EquatablePsE2neoiSbx_xtFZ",
-        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiSbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
+        key.usr: "s:s9EquatablePsE2neoiySbx_xtFZ::SYNTHESIZED::c:@E@FooSubEnum1",
+        key.original_usr: "s:s9EquatablePsE2neoiySbx_xtFZ",
+        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiySbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
         key.offset: 7557,
         key.length: 63,
         key.fully_annotated_decl: "<decl.function.operator.infix><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>static</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>!= </decl.name>(<decl.var.parameter><decl.var.parameter.name>lhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooSubEnum1\">FooSubEnum1</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.name>rhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"c:@E@FooSubEnum1\">FooSubEnum1</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.operator.infix>",
diff --git a/test/SourceKit/DocSupport/doc_source_file.swift.response b/test/SourceKit/DocSupport/doc_source_file.swift.response
index 73c9946..90bf9ef 100644
--- a/test/SourceKit/DocSupport/doc_source_file.swift.response
+++ b/test/SourceKit/DocSupport/doc_source_file.swift.response
@@ -467,7 +467,7 @@
   {
     key.kind: source.lang.swift.ref.function.operator.infix,
     key.name: "+(_:_:)",
-    key.usr: "s:8__main__1poiAA2CCCAD_AA3CC0CtF",
+    key.usr: "s:8__main__1poiyAA2CCCAD_AA3CC0CtF",
     key.offset: 526,
     key.length: 1
   },
@@ -527,7 +527,7 @@
   {
     key.kind: source.lang.swift.ref.enumelement,
     key.name: "EElem",
-    key.usr: "s:8__main__1EO5EElemA2CmF",
+    key.usr: "s:8__main__1EO5EElemyA2CmF",
     key.offset: 568,
     key.length: 5
   },
@@ -571,7 +571,7 @@
   {
     key.kind: source.lang.swift.ref.class,
     key.name: "LocalCC",
-    key.usr: "s:8__main__3fooyAA2CCC_AA1EO1btF05LocalC0L_C",
+    key.usr: "s:8__main__3foo_1byAA2CCC_AA1EOtF05LocalC0L_C",
     key.offset: 614,
     key.length: 7
   },
@@ -993,7 +993,7 @@
   {
     key.kind: source.lang.swift.ref.function.operator.infix,
     key.name: "+(_:_:)",
-    key.usr: "s:Si1poiS2i_SitFZ",
+    key.usr: "s:Si1poiyS2i_SitFZ",
     key.offset: 1217,
     key.length: 1
   },
@@ -1118,7 +1118,7 @@
   {
     key.kind: source.lang.swift.ref.function.operator.infix,
     key.name: "+=(_:_:)",
-    key.usr: "s:Si2peoiySiz_SitFZ",
+    key.usr: "s:Si2peoiyySiz_SitFZ",
     key.offset: 1343,
     key.length: 2
   },
@@ -1142,7 +1142,7 @@
   {
     key.kind: source.lang.swift.ref.function.subscript,
     key.name: "subscript(_:)",
-    key.usr: "s:8__main__3CC2CS2icip",
+    key.usr: "s:8__main__3CC2CyS2icip",
     key.offset: 1357,
     key.length: 1
   },
@@ -1154,7 +1154,7 @@
   {
     key.kind: source.lang.swift.ref.function.subscript,
     key.name: "subscript(_:)",
-    key.usr: "s:8__main__3CC2CS2icip",
+    key.usr: "s:8__main__3CC2CyS2icip",
     key.offset: 1359,
     key.length: 1
   },
@@ -1167,7 +1167,7 @@
   {
     key.kind: source.lang.swift.ref.function.subscript,
     key.name: "subscript(_:)",
-    key.usr: "s:8__main__3CC2CS2icip",
+    key.usr: "s:8__main__3CC2CyS2icip",
     key.offset: 1366,
     key.length: 1
   },
@@ -1179,7 +1179,7 @@
   {
     key.kind: source.lang.swift.ref.function.subscript,
     key.name: "subscript(_:)",
-    key.usr: "s:8__main__3CC2CS2icip",
+    key.usr: "s:8__main__3CC2CyS2icip",
     key.offset: 1368,
     key.length: 1
   },
@@ -1198,7 +1198,7 @@
   {
     key.kind: source.lang.swift.ref.function.subscript,
     key.name: "subscript(_:)",
-    key.usr: "s:8__main__3CC2CS2icip",
+    key.usr: "s:8__main__3CC2CyS2icip",
     key.offset: 1379,
     key.length: 1
   },
@@ -1210,14 +1210,14 @@
   {
     key.kind: source.lang.swift.ref.function.subscript,
     key.name: "subscript(_:)",
-    key.usr: "s:8__main__3CC2CS2icip",
+    key.usr: "s:8__main__3CC2CyS2icip",
     key.offset: 1381,
     key.length: 1
   },
   {
     key.kind: source.lang.swift.ref.function.operator.infix,
     key.name: "+=(_:_:)",
-    key.usr: "s:Si2peoiySiz_SitFZ",
+    key.usr: "s:Si2peoiyySiz_SitFZ",
     key.offset: 1383,
     key.length: 2
   },
@@ -1645,7 +1645,7 @@
   {
     key.kind: source.lang.swift.ref.generic_type_param,
     key.name: "T",
-    key.usr: "s:8__main__6genfooyxAA5Prot2RzSi7ElementRtzlF1TL_xmfp",
+    key.usr: "s:8__main__6genfooyyxAA5Prot2RzSi7ElementRtzlF1TL_xmfp",
     key.offset: 1924,
     key.length: 1
   },
@@ -1657,7 +1657,7 @@
   {
     key.kind: source.lang.swift.ref.generic_type_param,
     key.name: "T",
-    key.usr: "s:8__main__6genfooyxAA5Prot2RzSi7ElementRtzlF1TL_xmfp",
+    key.usr: "s:8__main__6genfooyyxAA5Prot2RzSi7ElementRtzlF1TL_xmfp",
     key.offset: 1933,
     key.length: 1
   },
@@ -1768,7 +1768,7 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "instanceFunc0(_:b:)",
-        key.usr: "s:8__main__2CCC13instanceFunc0S2i_Sf1btF",
+        key.usr: "s:8__main__2CCC13instanceFunc0_1bS2i_SftF",
         key.offset: 94,
         key.length: 63,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>instanceFunc0</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>a</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>b</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:Sf\">Float</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Si\">Int</ref.struct></decl.function.returntype></decl.function.method.instance>",
@@ -1792,7 +1792,7 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "instanceFunc1(a:b:)",
-        key.usr: "s:8__main__2CCC13instanceFunc1S2i1a_Sf1btF",
+        key.usr: "s:8__main__2CCC13instanceFunc11a1bS2i_SftF",
         key.offset: 161,
         key.length: 65,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>instanceFunc1</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>a</decl.var.parameter.argument_label> <decl.var.parameter.name>x</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>b</decl.var.parameter.argument_label> <decl.var.parameter.name>y</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:Sf\">Float</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Si\">Int</ref.struct></decl.function.returntype></decl.function.method.instance>",
@@ -1834,7 +1834,7 @@
   {
     key.kind: source.lang.swift.decl.function.operator.infix,
     key.name: "+(_:_:)",
-    key.usr: "s:8__main__1poiAA2CCCAD_AA3CC0CtF",
+    key.usr: "s:8__main__1poiyAA2CCCAD_AA3CC0CtF",
     key.offset: 288,
     key.length: 42,
     key.fully_annotated_decl: "<decl.function.operator.infix><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>+ </decl.name>(<decl.var.parameter><decl.var.parameter.name>a</decl.var.parameter.name>: <decl.var.parameter.type><ref.class usr=\"s:8__main__2CCC\">CC</ref.class></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.name>b</decl.var.parameter.name>: <decl.var.parameter.type><ref.class usr=\"s:8__main__3CC0C\">CC0</ref.class></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.class usr=\"s:8__main__2CCC\">CC</ref.class></decl.function.returntype></decl.function.operator.infix>",
@@ -1892,7 +1892,7 @@
       {
         key.kind: source.lang.swift.decl.enumelement,
         key.name: "EElem",
-        key.usr: "s:8__main__1EO5EElemA2CmF",
+        key.usr: "s:8__main__1EO5EElemyA2CmF",
         key.fully_annotated_decl: "<decl.enumelement><syntaxtype.keyword>case</syntaxtype.keyword> <decl.name>EElem</decl.name></decl.enumelement>"
       }
     ]
@@ -1908,7 +1908,7 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "protMeth(_:)",
-        key.usr: "s:8__main__4ProtP8protMethyAaB_pF",
+        key.usr: "s:8__main__4ProtP8protMethyyAaB_pF",
         key.offset: 432,
         key.length: 23,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>protMeth</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>a</decl.var.parameter.name>: <decl.var.parameter.type><ref.protocol usr=\"s:8__main__4ProtP\">Prot</ref.protocol></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
@@ -1927,7 +1927,7 @@
   {
     key.kind: source.lang.swift.decl.function.free,
     key.name: "foo(_:b:)",
-    key.usr: "s:8__main__3fooyAA2CCC_AA1EO1btF",
+    key.usr: "s:8__main__3foo_1byAA2CCC_AA1EOtF",
     key.offset: 460,
     key.length: 162,
     key.fully_annotated_decl: "<decl.function.free><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>a</decl.var.parameter.name>: <decl.var.parameter.type><ref.class usr=\"s:8__main__2CCC\">CC</ref.class></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>b</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.enum usr=\"s:8__main__1EO\">E</ref.enum></decl.var.parameter.type></decl.var.parameter>)</decl.function.free>",
@@ -1976,7 +1976,7 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "meth2(_:)",
-        key.usr: "s:8__main__2CCC5meth2yACF",
+        key.usr: "s:8__main__2CCC5meth2yyACF",
         key.offset: 673,
         key.length: 26,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>meth2</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>x</decl.var.parameter.name>: <decl.var.parameter.type><ref.typealias usr=\"s:8__main__7CCAliasa\">CCAlias</ref.typealias></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
@@ -1993,7 +1993,7 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "protMeth(_:)",
-        key.usr: "s:8__main__2CCC8protMethyAA4Prot_pF",
+        key.usr: "s:8__main__2CCC8protMethyyAA4Prot_pF",
         key.offset: 703,
         key.length: 26,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>protMeth</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>a</decl.var.parameter.name>: <decl.var.parameter.type><ref.protocol usr=\"s:8__main__4ProtP\">Prot</ref.protocol></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
@@ -2001,7 +2001,7 @@
           {
             key.kind: source.lang.swift.ref.function.method.instance,
             key.name: "protMeth(_:)",
-            key.usr: "s:8__main__4ProtP8protMethyAaB_pF"
+            key.usr: "s:8__main__4ProtP8protMethyyAaB_pF"
           }
         ],
         key.entities: [
@@ -2104,7 +2104,7 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "protMeth(_:)",
-        key.usr: "s:8__main__3BC2C8protMethyAA4Prot_pF",
+        key.usr: "s:8__main__3BC2C8protMethyyAA4Prot_pF",
         key.offset: 1017,
         key.length: 26,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>protMeth</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>a</decl.var.parameter.name>: <decl.var.parameter.type><ref.protocol usr=\"s:8__main__4ProtP\">Prot</ref.protocol></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
@@ -2145,7 +2145,7 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "protMeth(_:)",
-        key.usr: "s:8__main__5SubC2C8protMethyAA4Prot_pF",
+        key.usr: "s:8__main__5SubC2C8protMethyyAA4Prot_pF",
         key.offset: 1084,
         key.length: 26,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>override</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>protMeth</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>a</decl.var.parameter.name>: <decl.var.parameter.type><ref.protocol usr=\"s:8__main__4ProtP\">Prot</ref.protocol></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
@@ -2153,14 +2153,14 @@
           {
             key.kind: source.lang.swift.ref.function.method.instance,
             key.name: "protMeth(_:)",
-            key.usr: "s:8__main__3BC2C8protMethyAA4Prot_pF"
+            key.usr: "s:8__main__3BC2C8protMethyyAA4Prot_pF"
           }
         ],
         key.conforms: [
           {
             key.kind: source.lang.swift.ref.function.method.instance,
             key.name: "protMeth(_:)",
-            key.usr: "s:8__main__4ProtP8protMethyAaB_pF"
+            key.usr: "s:8__main__4ProtP8protMethyyAaB_pF"
           }
         ],
         key.entities: [
@@ -2186,7 +2186,7 @@
       {
         key.kind: source.lang.swift.decl.function.subscript,
         key.name: "subscript(_:)",
-        key.usr: "s:8__main__3CC2CS2icip",
+        key.usr: "s:8__main__3CC2CyS2icip",
         key.offset: 1129,
         key.length: 99,
         key.fully_annotated_decl: "<decl.function.subscript><syntaxtype.keyword>subscript</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.name>i</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Si\">Int</ref.struct></decl.function.returntype> { <syntaxtype.keyword>get</syntaxtype.keyword> <syntaxtype.keyword>set</syntaxtype.keyword> }</decl.function.subscript>",
@@ -2202,14 +2202,14 @@
       },
       {
         key.kind: source.lang.swift.decl.function.accessor.getter,
-        key.usr: "s:8__main__3CC2CS2icig",
+        key.usr: "s:8__main__3CC2CyS2icig",
         key.offset: 1162,
         key.length: 25,
         key.fully_annotated_decl: "<decl.function.accessor.getter><decl.name>get</decl.name> {}</decl.function.accessor.getter>"
       },
       {
         key.kind: source.lang.swift.decl.function.accessor.setter,
-        key.usr: "s:8__main__3CC2CS2icis",
+        key.usr: "s:8__main__3CC2CyS2icis",
         key.offset: 1193,
         key.length: 31,
         key.fully_annotated_decl: "<decl.function.accessor.setter><decl.name>set(vvv)</decl.name> {}</decl.function.accessor.setter>"
@@ -2219,7 +2219,7 @@
   {
     key.kind: source.lang.swift.decl.function.free,
     key.name: "test1(_:sub:)",
-    key.usr: "s:8__main__5test1yAA16ComputedPropertyC_AA3CC2C3subtF",
+    key.usr: "s:8__main__5test1_3subyAA16ComputedPropertyC_AA3CC2CtF",
     key.offset: 1233,
     key.length: 155,
     key.fully_annotated_decl: "<decl.function.free><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>test1</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>cp</decl.var.parameter.name>: <decl.var.parameter.type><ref.class usr=\"s:8__main__16ComputedPropertyC\">ComputedProperty</ref.class></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>sub</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.class usr=\"s:8__main__3CC2C\">CC2</ref.class></decl.var.parameter.type></decl.var.parameter>)</decl.function.free>",
@@ -2332,7 +2332,7 @@
   {
     key.kind: source.lang.swift.decl.function.free,
     key.name: "test3(_:s:)",
-    key.usr: "s:8__main__5test3yAA3SB1C_AA2S2V1stF",
+    key.usr: "s:8__main__5test3_1syAA3SB1C_AA2S2VtF",
     key.offset: 1638,
     key.length: 61,
     key.fully_annotated_decl: "<decl.function.free><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>test3</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>c</decl.var.parameter.name>: <decl.var.parameter.type><ref.class usr=\"s:8__main__3SB1C\">SB1</ref.class></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>s</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:8__main__2S2V\">S2</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.free>",
@@ -2356,7 +2356,7 @@
   {
     key.kind: source.lang.swift.decl.function.free,
     key.name: "test4(_:)",
-    key.usr: "s:8__main__5test4ySizF",
+    key.usr: "s:8__main__5test4yySizF",
     key.offset: 1702,
     key.length: 28,
     key.fully_annotated_decl: "<decl.function.free><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>test4</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>a</decl.var.parameter.name>: <decl.var.parameter.type><syntaxtype.keyword>inout</syntaxtype.keyword> <ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.free>",
@@ -2480,7 +2480,7 @@
   {
     key.kind: source.lang.swift.decl.function.free,
     key.name: "genfoo(_:)",
-    key.usr: "s:8__main__6genfooyxAA5Prot2RzSi7ElementRtzlF",
+    key.usr: "s:8__main__6genfooyyxAA5Prot2RzSi7ElementRtzlF",
     key.generic_params: [
       {
         key.name: "T"
@@ -2496,7 +2496,7 @@
     ],
     key.offset: 1896,
     key.length: 55,
-    key.fully_annotated_decl: "<decl.function.free><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>genfoo</decl.name>&lt;<decl.generic_type_param usr=\"s:8__main__6genfooyxAA5Prot2RzSi7ElementRtzlF1TL_xmfp\"><decl.generic_type_param.name>T</decl.generic_type_param.name></decl.generic_type_param>&gt;(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>x</decl.var.parameter.name>: <decl.var.parameter.type><ref.generic_type_param usr=\"s:8__main__6genfooyxAA5Prot2RzSi7ElementRtzlF1TL_xmfp\">T</ref.generic_type_param></decl.var.parameter.type></decl.var.parameter>) <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement>T : <ref.protocol usr=\"s:8__main__5Prot2P\">Prot2</ref.protocol></decl.generic_type_requirement>, <decl.generic_type_requirement>T.Element == <ref.struct usr=\"s:Si\">Int</ref.struct></decl.generic_type_requirement></decl.function.free>",
+    key.fully_annotated_decl: "<decl.function.free><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>genfoo</decl.name>&lt;<decl.generic_type_param usr=\"s:8__main__6genfooyyxAA5Prot2RzSi7ElementRtzlF1TL_xmfp\"><decl.generic_type_param.name>T</decl.generic_type_param.name></decl.generic_type_param>&gt;(<decl.var.parameter><decl.var.parameter.argument_label>_</decl.var.parameter.argument_label> <decl.var.parameter.name>x</decl.var.parameter.name>: <decl.var.parameter.type><ref.generic_type_param usr=\"s:8__main__6genfooyyxAA5Prot2RzSi7ElementRtzlF1TL_xmfp\">T</ref.generic_type_param></decl.var.parameter.type></decl.var.parameter>) <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement>T : <ref.protocol usr=\"s:8__main__5Prot2P\">Prot2</ref.protocol></decl.generic_type_requirement>, <decl.generic_type_requirement>T.Element == <ref.struct usr=\"s:Si\">Int</ref.struct></decl.generic_type_requirement></decl.function.free>",
     key.entities: [
       {
         key.kind: source.lang.swift.decl.var.local,
@@ -2518,7 +2518,7 @@
       {
         key.kind: source.lang.swift.decl.function.operator.infix,
         key.name: "+(_:_:)",
-        key.usr: "s:8__main__5Prot3P1poiyx_xtFZ",
+        key.usr: "s:8__main__5Prot3P1poiyyx_xtFZ",
         key.offset: 1973,
         key.length: 30,
         key.fully_annotated_decl: "<decl.function.operator.infix><syntaxtype.keyword>static</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>+ </decl.name>(<decl.var.parameter><decl.var.parameter.name>x</decl.var.parameter.name>: <decl.var.parameter.type><ref.generic_type_param usr=\"s:8__main__5Prot3P4Selfxmfp\">Self</ref.generic_type_param></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.name>y</decl.var.parameter.name>: <decl.var.parameter.type><ref.generic_type_param usr=\"s:8__main__5Prot3P4Selfxmfp\">Self</ref.generic_type_param></decl.var.parameter.type></decl.var.parameter>)</decl.function.operator.infix>",
diff --git a/test/SourceKit/DocSupport/doc_swift_module.swift.response b/test/SourceKit/DocSupport/doc_swift_module.swift.response
index 252e7ea..e402b2e 100644
--- a/test/SourceKit/DocSupport/doc_swift_module.swift.response
+++ b/test/SourceKit/DocSupport/doc_swift_module.swift.response
@@ -1381,7 +1381,7 @@
       {
         key.kind: source.lang.swift.decl.function.subscript,
         key.name: "subscript(_:)",
-        key.usr: "s:4cake2C1CS2icip",
+        key.usr: "s:4cake2C1CyS2icip",
         key.offset: 110,
         key.length: 38,
         key.fully_annotated_decl: "<decl.function.subscript><syntaxtype.keyword>subscript</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.name>index</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Si\">Int</ref.struct></decl.function.returntype> { <syntaxtype.keyword>get</syntaxtype.keyword> }</decl.function.subscript>",
@@ -1398,7 +1398,7 @@
       {
         key.kind: source.lang.swift.decl.function.subscript,
         key.name: "subscript(index:)",
-        key.usr: "s:4cake2C1CSiSf5index_tcip",
+        key.usr: "s:4cake2C1C5indexSiSf_tcip",
         key.offset: 154,
         key.length: 40,
         key.fully_annotated_decl: "<decl.function.subscript><syntaxtype.keyword>subscript</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.argument_label>index</decl.var.parameter.argument_label> <decl.var.parameter.name>i</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:Sf\">Float</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Si\">Int</ref.struct></decl.function.returntype> { <syntaxtype.keyword>get</syntaxtype.keyword> }</decl.function.subscript>",
@@ -1430,7 +1430,7 @@
           {
             key.kind: source.lang.swift.decl.enumelement,
             key.name: "case1",
-            key.usr: "s:4cake2C1C0B5CasesO5case1A2EmF",
+            key.usr: "s:4cake2C1C0B5CasesO5case1yA2EmF",
             key.offset: 230,
             key.length: 10,
             key.fully_annotated_decl: "<decl.enumelement><syntaxtype.keyword>case</syntaxtype.keyword> <decl.name>case1</decl.name></decl.enumelement>"
@@ -1458,8 +1458,8 @@
       {
         key.kind: source.lang.swift.decl.function.subscript,
         key.name: "subscript(_:)",
-        key.usr: "s:4cake4ProtPAAES2icip::SYNTHESIZED::s:4cake2C1C",
-        key.original_usr: "s:4cake4ProtPAAES2icip",
+        key.usr: "s:4cake4ProtPAAEyS2icip::SYNTHESIZED::s:4cake2C1C",
+        key.original_usr: "s:4cake4ProtPAAEyS2icip",
         key.offset: 288,
         key.length: 38,
         key.fully_annotated_decl: "<decl.function.subscript><syntaxtype.keyword>subscript</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.name>index</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Si\">Int</ref.struct></decl.function.returntype> { <syntaxtype.keyword>get</syntaxtype.keyword> }</decl.function.subscript>",
@@ -1511,7 +1511,7 @@
           {
             key.kind: source.lang.swift.decl.function.method.instance,
             key.name: "C1S1foo(a:)",
-            key.usr: "s:4cake2C1C0B2S1V0B5S1fooyAA2P4_p1a_tF",
+            key.usr: "s:4cake2C1C0B2S1V0B5S1foo1ayAA2P4_p_tF",
             key.offset: 396,
             key.length: 21,
             key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>C1S1foo</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>a</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.protocol usr=\"s:4cake2P4P\">P4</ref.protocol></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
@@ -1542,9 +1542,9 @@
       {
         key.kind: source.lang.swift.decl.function.operator.infix,
         key.name: "!=(_:_:)",
-        key.usr: "s:s9EquatablePsE2neoiSbx_xtFZ::SYNTHESIZED::s:4cake2C1C0B5CasesO",
-        key.original_usr: "s:s9EquatablePsE2neoiSbx_xtFZ",
-        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiSbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
+        key.usr: "s:s9EquatablePsE2neoiySbx_xtFZ::SYNTHESIZED::s:4cake2C1C0B5CasesO",
+        key.original_usr: "s:s9EquatablePsE2neoiySbx_xtFZ",
+        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiySbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
         key.offset: 452,
         key.length: 61,
         key.fully_annotated_decl: "<decl.function.operator.infix><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>static</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>!= </decl.name>(<decl.var.parameter><decl.var.parameter.name>lhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.class usr=\"s:4cake2C1C\">C1</ref.class>.<ref.enum usr=\"s:4cake2C1C0B5CasesO\">C1Cases</ref.enum></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.name>rhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.class usr=\"s:4cake2C1C\">C1</ref.class>.<ref.enum usr=\"s:4cake2C1C0B5CasesO\">C1Cases</ref.enum></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.operator.infix>",
@@ -1609,7 +1609,7 @@
           {
             key.kind: source.lang.swift.decl.enumelement,
             key.name: "case1",
-            key.usr: "s:4cake2C1C0B5CasesO5case1A2EmF",
+            key.usr: "s:4cake2C1C0B5CasesO5case1yA2EmF",
             key.offset: 591,
             key.length: 10,
             key.fully_annotated_decl: "<decl.enumelement><syntaxtype.keyword>case</syntaxtype.keyword> <decl.name>case1</decl.name></decl.enumelement>"
@@ -1637,8 +1637,8 @@
       {
         key.kind: source.lang.swift.decl.function.subscript,
         key.name: "subscript(_:)",
-        key.usr: "s:4cake4ProtPAAES2icip::SYNTHESIZED::s:4cake2C2C",
-        key.original_usr: "s:4cake4ProtPAAES2icip",
+        key.usr: "s:4cake4ProtPAAEyS2icip::SYNTHESIZED::s:4cake2C2C",
+        key.original_usr: "s:4cake4ProtPAAEyS2icip",
         key.offset: 649,
         key.length: 38,
         key.fully_annotated_decl: "<decl.function.subscript><syntaxtype.keyword>subscript</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.name>index</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Si\">Int</ref.struct></decl.function.returntype> { <syntaxtype.keyword>get</syntaxtype.keyword> }</decl.function.subscript>",
@@ -1692,7 +1692,7 @@
           {
             key.kind: source.lang.swift.decl.function.method.instance,
             key.name: "C1S1foo(a:)",
-            key.usr: "s:4cake2C1C0B2S1V0B5S1fooyAA2P4_p1a_tF",
+            key.usr: "s:4cake2C1C0B2S1V0B5S1foo1ayAA2P4_p_tF",
             key.offset: 757,
             key.length: 21,
             key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>C1S1foo</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>a</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.protocol usr=\"s:4cake2P4P\">P4</ref.protocol></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
@@ -1728,7 +1728,7 @@
       {
         key.kind: source.lang.swift.decl.enumelement,
         key.name: "Blah",
-        key.usr: "s:4cake6MyEnumO4BlahA2CmF",
+        key.usr: "s:4cake6MyEnumO4BlahyA2CmF",
         key.offset: 813,
         key.length: 9,
         key.fully_annotated_decl: "<decl.enumelement><syntaxtype.keyword>case</syntaxtype.keyword> <decl.name>Blah</decl.name></decl.enumelement>"
@@ -1736,9 +1736,9 @@
       {
         key.kind: source.lang.swift.decl.function.operator.infix,
         key.name: "!=(_:_:)",
-        key.usr: "s:s9EquatablePsE2neoiSbx_xtFZ::SYNTHESIZED::s:4cake6MyEnumO",
-        key.original_usr: "s:s9EquatablePsE2neoiSbx_xtFZ",
-        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiSbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
+        key.usr: "s:s9EquatablePsE2neoiySbx_xtFZ::SYNTHESIZED::s:4cake6MyEnumO",
+        key.original_usr: "s:s9EquatablePsE2neoiySbx_xtFZ",
+        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiySbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
         key.offset: 828,
         key.length: 53,
         key.fully_annotated_decl: "<decl.function.operator.infix><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>static</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>!= </decl.name>(<decl.var.parameter><decl.var.parameter.name>lhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.enum usr=\"s:4cake6MyEnumO\">MyEnum</ref.enum></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.name>rhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.enum usr=\"s:4cake6MyEnumO\">MyEnum</ref.enum></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.operator.infix>",
@@ -1870,7 +1870,7 @@
       {
         key.kind: source.lang.swift.decl.function.subscript,
         key.name: "subscript(_:)",
-        key.usr: "s:4cake4ProtPAAES2icip",
+        key.usr: "s:4cake4ProtPAAEyS2icip",
         key.offset: 1139,
         key.length: 38,
         key.fully_annotated_decl: "<decl.function.subscript><syntaxtype.keyword>subscript</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.name>index</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Si\">Int</ref.struct></decl.function.returntype> { <syntaxtype.keyword>get</syntaxtype.keyword> }</decl.function.subscript>",
@@ -1930,7 +1930,7 @@
           {
             key.kind: source.lang.swift.decl.enumelement,
             key.name: "a",
-            key.usr: "s:4cake2S1V2SEO1aA2EmF",
+            key.usr: "s:4cake2S1V2SEO1ayA2EmF",
             key.offset: 1282,
             key.length: 6,
             key.fully_annotated_decl: "<decl.enumelement><syntaxtype.keyword>case</syntaxtype.keyword> <decl.name>a</decl.name></decl.enumelement>"
@@ -1938,7 +1938,7 @@
           {
             key.kind: source.lang.swift.decl.enumelement,
             key.name: "b",
-            key.usr: "s:4cake2S1V2SEO1bA2EmF",
+            key.usr: "s:4cake2S1V2SEO1byA2EmF",
             key.offset: 1298,
             key.length: 6,
             key.fully_annotated_decl: "<decl.enumelement><syntaxtype.keyword>case</syntaxtype.keyword> <decl.name>b</decl.name></decl.enumelement>"
@@ -1946,7 +1946,7 @@
           {
             key.kind: source.lang.swift.decl.enumelement,
             key.name: "c",
-            key.usr: "s:4cake2S1V2SEO1cA2EmF",
+            key.usr: "s:4cake2S1V2SEO1cyA2EmF",
             key.offset: 1314,
             key.length: 6,
             key.fully_annotated_decl: "<decl.enumelement><syntaxtype.keyword>case</syntaxtype.keyword> <decl.name>c</decl.name></decl.enumelement>"
@@ -1994,9 +1994,9 @@
       {
         key.kind: source.lang.swift.decl.function.operator.infix,
         key.name: "!=(_:_:)",
-        key.usr: "s:s9EquatablePsE2neoiSbx_xtFZ::SYNTHESIZED::s:4cake2S1V2SEO",
-        key.original_usr: "s:s9EquatablePsE2neoiSbx_xtFZ",
-        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiSbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
+        key.usr: "s:s9EquatablePsE2neoiySbx_xtFZ::SYNTHESIZED::s:4cake2S1V2SEO",
+        key.original_usr: "s:s9EquatablePsE2neoiySbx_xtFZ",
+        key.doc.full_as_xml: "<Function><Name>!=(_:_:)</Name><USR>s:s9EquatablePsE2neoiySbx_xtFZ</USR><Declaration>static func != (lhs: Self, rhs: Self) -&gt; Bool</Declaration><CommentParts><Abstract><Para>Returns a Boolean value indicating whether two values are not equal.</Para></Abstract><Parameters><Parameter><Name>lhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>A value to compare.</Para></Discussion></Parameter><Parameter><Name>rhs</Name><Direction isExplicit=\"0\">in</Direction><Discussion><Para>Another value to compare.</Para></Discussion></Parameter></Parameters><Discussion><Para>Inequality is the inverse of equality. For any values <codeVoice>a</codeVoice> and <codeVoice>b</codeVoice>, <codeVoice>a != b</codeVoice> implies that <codeVoice>a == b</codeVoice> is <codeVoice>false</codeVoice>.</Para><Para>This is the default implementation of the not-equal-to operator (<codeVoice>!=</codeVoice>) for any type that conforms to <codeVoice>Equatable</codeVoice>.</Para></Discussion></CommentParts></Function>",
         key.offset: 1410,
         key.length: 51,
         key.fully_annotated_decl: "<decl.function.operator.infix><syntaxtype.attribute.builtin><syntaxtype.attribute.name>@_inlineable</syntaxtype.attribute.name></syntaxtype.attribute.builtin> <syntaxtype.keyword>static</syntaxtype.keyword> <syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>!= </decl.name>(<decl.var.parameter><decl.var.parameter.name>lhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:4cake2S1V\">S1</ref.struct>.<ref.enum usr=\"s:4cake2S1V2SEO\">SE</ref.enum></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.name>rhs</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:4cake2S1V\">S1</ref.struct>.<ref.enum usr=\"s:4cake2S1V2SEO\">SE</ref.enum></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Sb\">Bool</ref.struct></decl.function.returntype></decl.function.operator.infix>",
@@ -2054,7 +2054,7 @@
   {
     key.kind: source.lang.swift.decl.function.free,
     key.name: "genfoo(x:y:)",
-    key.usr: "s:4cake6genfooyx1x_q_1ytAA4ProtRzAA2C1CRb_Si7ElementRtzr0_lF",
+    key.usr: "s:4cake6genfoo1x1yyx_q_tAA4ProtRzAA2C1CRb_Si7ElementRtzr0_lF",
     key.generic_params: [
       {
         key.name: "T1"
@@ -2076,7 +2076,7 @@
     ],
     key.offset: 1512,
     key.length: 100,
-    key.fully_annotated_decl: "<decl.function.free><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>genfoo</decl.name>&lt;<decl.generic_type_param usr=\"s:4cake6genfooyx1x_q_1ytAA4ProtRzAA2C1CRb_Si7ElementRtzr0_lF2T1L_xmfp\"><decl.generic_type_param.name>T1</decl.generic_type_param.name></decl.generic_type_param>, <decl.generic_type_param usr=\"s:4cake6genfooyx1x_q_1ytAA4ProtRzAA2C1CRb_Si7ElementRtzr0_lF2T2L_q_mfp\"><decl.generic_type_param.name>T2</decl.generic_type_param.name></decl.generic_type_param>&gt;(<decl.var.parameter><decl.var.parameter.argument_label>x</decl.var.parameter.argument_label> <decl.var.parameter.name>ix</decl.var.parameter.name>: <decl.var.parameter.type>T1</decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>y</decl.var.parameter.argument_label> <decl.var.parameter.name>iy</decl.var.parameter.name>: <decl.var.parameter.type>T2</decl.var.parameter.type></decl.var.parameter>) <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement>T1 : <ref.protocol usr=\"s:4cake4ProtP\">Prot</ref.protocol></decl.generic_type_requirement>, <decl.generic_type_requirement>T2 : <ref.class usr=\"s:4cake2C1C\">C1</ref.class></decl.generic_type_requirement>, <decl.generic_type_requirement>T1.Element == <ref.class usr=\"s:4cake2C1C\">C1</ref.class>.<ref.typealias usr=\"s:4cake2C1C7Elementa\">Element</ref.typealias></decl.generic_type_requirement></decl.function.free>",
+    key.fully_annotated_decl: "<decl.function.free><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>genfoo</decl.name>&lt;<decl.generic_type_param usr=\"s:4cake6genfoo1x1yyx_q_tAA4ProtRzAA2C1CRb_Si7ElementRtzr0_lF2T1L_xmfp\"><decl.generic_type_param.name>T1</decl.generic_type_param.name></decl.generic_type_param>, <decl.generic_type_param usr=\"s:4cake6genfoo1x1yyx_q_tAA4ProtRzAA2C1CRb_Si7ElementRtzr0_lF2T2L_q_mfp\"><decl.generic_type_param.name>T2</decl.generic_type_param.name></decl.generic_type_param>&gt;(<decl.var.parameter><decl.var.parameter.argument_label>x</decl.var.parameter.argument_label> <decl.var.parameter.name>ix</decl.var.parameter.name>: <decl.var.parameter.type>T1</decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>y</decl.var.parameter.argument_label> <decl.var.parameter.name>iy</decl.var.parameter.name>: <decl.var.parameter.type>T2</decl.var.parameter.type></decl.var.parameter>) <syntaxtype.keyword>where</syntaxtype.keyword> <decl.generic_type_requirement>T1 : <ref.protocol usr=\"s:4cake4ProtP\">Prot</ref.protocol></decl.generic_type_requirement>, <decl.generic_type_requirement>T2 : <ref.class usr=\"s:4cake2C1C\">C1</ref.class></decl.generic_type_requirement>, <decl.generic_type_requirement>T1.Element == <ref.class usr=\"s:4cake2C1C\">C1</ref.class>.<ref.typealias usr=\"s:4cake2C1C7Elementa\">Element</ref.typealias></decl.generic_type_requirement></decl.function.free>",
     key.entities: [
       {
         key.kind: source.lang.swift.decl.var.local,
diff --git a/test/SourceKit/DocSupport/doc_swift_module1.swift.response b/test/SourceKit/DocSupport/doc_swift_module1.swift.response
index e878974..193fea0 100644
--- a/test/SourceKit/DocSupport/doc_swift_module1.swift.response
+++ b/test/SourceKit/DocSupport/doc_swift_module1.swift.response
@@ -413,7 +413,7 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "foo2(a:b:)",
-        key.usr: "s:5cake12P1P4foo2ySi1a_Si1btF",
+        key.usr: "s:5cake12P1P4foo21a1bySi_SitF",
         key.offset: 92,
         key.length: 29,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo2</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>a</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>b</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
@@ -437,7 +437,7 @@
       {
         key.kind: source.lang.swift.decl.function.subscript,
         key.name: "subscript(_:)",
-        key.usr: "s:5cake12P1PS2icip",
+        key.usr: "s:5cake12P1PyS2icip",
         key.offset: 127,
         key.length: 38,
         key.fully_annotated_decl: "<decl.function.subscript><syntaxtype.keyword>subscript</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.name>a</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Si\">Int</ref.struct></decl.function.returntype> { <syntaxtype.keyword>get</syntaxtype.keyword> <syntaxtype.keyword>set</syntaxtype.keyword> }</decl.function.subscript>",
@@ -525,8 +525,8 @@
       {
         key.kind: source.lang.swift.decl.function.method.instance,
         key.name: "foo2(a:b:)",
-        key.usr: "s:5cake12P2PAAE4foo2ySi1a_Si1btF",
-        key.default_implementation_of: "s:5cake12P1P4foo2ySi1a_Si1btF",
+        key.usr: "s:5cake12P2PAAE4foo21a1bySi_SitF",
+        key.default_implementation_of: "s:5cake12P1P4foo21a1bySi_SitF",
         key.offset: 306,
         key.length: 29,
         key.fully_annotated_decl: "<decl.function.method.instance><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>foo2</decl.name>(<decl.var.parameter><decl.var.parameter.argument_label>a</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.argument_label>b</decl.var.parameter.argument_label>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>)</decl.function.method.instance>",
@@ -550,8 +550,8 @@
       {
         key.kind: source.lang.swift.decl.function.subscript,
         key.name: "subscript(_:)",
-        key.usr: "s:5cake12P2PAAES2icip",
-        key.default_implementation_of: "s:5cake12P1PS2icip",
+        key.usr: "s:5cake12P2PAAEyS2icip",
+        key.default_implementation_of: "s:5cake12P1PyS2icip",
         key.offset: 341,
         key.length: 26,
         key.fully_annotated_decl: "<decl.function.subscript><syntaxtype.keyword>subscript</syntaxtype.keyword>(<decl.var.parameter><decl.var.parameter.name>a</decl.var.parameter.name>: <decl.var.parameter.type><ref.struct usr=\"s:Si\">Int</ref.struct></decl.var.parameter.type></decl.var.parameter>) -&gt; <decl.function.returntype><ref.struct usr=\"s:Si\">Int</ref.struct></decl.function.returntype> { <syntaxtype.keyword>get</syntaxtype.keyword> <syntaxtype.keyword>set</syntaxtype.keyword> }</decl.function.subscript>",
diff --git a/test/SourceKit/Indexing/Inputs/test_module.index.response b/test/SourceKit/Indexing/Inputs/test_module.index.response
index b48864b..93768e3 100644
--- a/test/SourceKit/Indexing/Inputs/test_module.index.response
+++ b/test/SourceKit/Indexing/Inputs/test_module.index.response
@@ -125,7 +125,7 @@
         {
           key.kind: source.lang.swift.decl.function.constructor,
           key.name: "init(a:b:)",
-          key.usr: "s:11test_module7TwoIntsCACSi1a_Si1btcfc"
+          key.usr: "s:11test_module7TwoIntsC1a1bACSi_Sitcfc"
         }
       ]
     },
diff --git a/test/SourceKit/Indexing/index_enum_case.swift.response b/test/SourceKit/Indexing/index_enum_case.swift.response
index 46be33f..f3b46a1 100644
--- a/test/SourceKit/Indexing/index_enum_case.swift.response
+++ b/test/SourceKit/Indexing/index_enum_case.swift.response
@@ -20,14 +20,14 @@
         {
           key.kind: source.lang.swift.decl.enumelement,
           key.name: "one",
-          key.usr: "s:15index_enum_case1EO3oneA2CmF",
+          key.usr: "s:15index_enum_case1EO3oneyA2CmF",
           key.line: 6,
           key.column: 10
         },
         {
           key.kind: source.lang.swift.decl.enumelement,
           key.name: "two",
-          key.usr: "s:15index_enum_case1EO3twoACSS1a_tcACmF",
+          key.usr: "s:15index_enum_case1EO3twoyACSS_tcACmF",
           key.line: 6,
           key.column: 15,
           key.entities: [
@@ -43,7 +43,7 @@
         {
           key.kind: source.lang.swift.decl.enumelement,
           key.name: "three",
-          key.usr: "s:15index_enum_case1EO5threeA2CmF",
+          key.usr: "s:15index_enum_case1EO5threeyA2CmF",
           key.line: 6,
           key.column: 31
         },
@@ -64,21 +64,21 @@
                 {
                   key.kind: source.lang.swift.ref.enumelement,
                   key.name: "one",
-                  key.usr: "s:15index_enum_case1EO3oneA2CmF",
+                  key.usr: "s:15index_enum_case1EO3oneyA2CmF",
                   key.line: 10,
                   key.column: 15
                 },
                 {
                   key.kind: source.lang.swift.ref.enumelement,
                   key.name: "two",
-                  key.usr: "s:15index_enum_case1EO3twoACSS1a_tcACmF",
+                  key.usr: "s:15index_enum_case1EO3twoyACSS_tcACmF",
                   key.line: 12,
                   key.column: 15
                 },
                 {
                   key.kind: source.lang.swift.ref.enumelement,
                   key.name: "three",
-                  key.usr: "s:15index_enum_case1EO5threeA2CmF",
+                  key.usr: "s:15index_enum_case1EO5threeyA2CmF",
                   key.line: 14,
                   key.column: 15
                 }
@@ -131,7 +131,7 @@
     {
       key.kind: source.lang.swift.ref.enumelement,
       key.name: "two",
-      key.usr: "s:15index_enum_case1EO3twoACSS1a_tcACmF",
+      key.usr: "s:15index_enum_case1EO3twoyACSS_tcACmF",
       key.line: 21,
       key.column: 13
     },
@@ -152,7 +152,7 @@
         {
           key.kind: source.lang.swift.ref.enumelement,
           key.name: "one",
-          key.usr: "s:15index_enum_case1EO3oneA2CmF",
+          key.usr: "s:15index_enum_case1EO3oneyA2CmF",
           key.line: 28,
           key.column: 12
         }
diff --git a/test/SourceKit/Indexing/index_is_test_candidate.swift.response b/test/SourceKit/Indexing/index_is_test_candidate.swift.response
index 0691811..247556f 100644
--- a/test/SourceKit/Indexing/index_is_test_candidate.swift.response
+++ b/test/SourceKit/Indexing/index_is_test_candidate.swift.response
@@ -145,7 +145,7 @@
         {
           key.kind: source.lang.swift.decl.function.method.instance,
           key.name: "test_startsWithTest_butTakesAParam(param:)",
-          key.usr: "s:23index_is_test_candidate7MyClassC0C30_startsWithTest_butTakesAParamySi5param_tF",
+          key.usr: "s:23index_is_test_candidate7MyClassC0C30_startsWithTest_butTakesAParam5paramySi_tF",
           key.line: 22,
           key.column: 8,
           key.is_dynamic: 1,
diff --git a/test/SourceKit/Indexing/index_is_test_candidate_objc.swift.response b/test/SourceKit/Indexing/index_is_test_candidate_objc.swift.response
index 6fcdd26..bd04a95 100644
--- a/test/SourceKit/Indexing/index_is_test_candidate_objc.swift.response
+++ b/test/SourceKit/Indexing/index_is_test_candidate_objc.swift.response
@@ -146,7 +146,7 @@
         {
           key.kind: source.lang.swift.decl.function.method.instance,
           key.name: "test_startsWithTest_butTakesAParam(param:)",
-          key.usr: "s:28index_is_test_candidate_objc7MyClassC0C30_startsWithTest_butTakesAParamySi5param_tF",
+          key.usr: "s:28index_is_test_candidate_objc7MyClassC0C30_startsWithTest_butTakesAParam5paramySi_tF",
           key.line: 21,
           key.column: 8,
           key.is_dynamic: 1,
diff --git a/test/SourceKit/Refactoring/semantic-refactoring/local-rename-lazy.swift.expected b/test/SourceKit/Refactoring/semantic-refactoring/local-rename-lazy.swift.expected
new file mode 100644
index 0000000..4f121c9
--- /dev/null
+++ b/test/SourceKit/Refactoring/semantic-refactoring/local-rename-lazy.swift.expected
@@ -0,0 +1,4 @@
+source.edit.kind.active:
+  7:11-7:16 source.refactoring.range.kind.basename
+source.edit.kind.active:
+  8:14-8:19 source.refactoring.range.kind.basename
diff --git a/test/SourceKit/Refactoring/semantic-refactoring/local-rename.swift b/test/SourceKit/Refactoring/semantic-refactoring/local-rename.swift
index f9f7737..32d5f42 100644
--- a/test/SourceKit/Refactoring/semantic-refactoring/local-rename.swift
+++ b/test/SourceKit/Refactoring/semantic-refactoring/local-rename.swift
@@ -2,6 +2,12 @@
   var aa = 3
   aa = aa + 1
   _ = "before \(aa) after"
+  struct S {
+    lazy var lazyVal: Int = {
+      let myVal = 0
+      return myVal
+     }()
+  }
   return 1
 }
 
@@ -10,5 +16,7 @@
 // RUN: diff -u %S/local-rename.swift.expected %t.result/local-rename.swift.expected
 // RUN: %sourcekitd-test -req=find-local-rename-ranges -pos=2:8 %s -- %s > %t.result/local-rename-ranges.swift.expected
 // RUN: diff -u %S/local-rename-ranges.swift.expected %t.result/local-rename-ranges.swift.expected
+// RUN: %sourcekitd-test -req=find-local-rename-ranges -pos=7:11 %s -- %s > %t.result/local-rename-lazy.swift.expected
+// RUN: diff -u %S/local-rename-lazy.swift.expected %t.result/local-rename-lazy.swift.expected
 
 // REQUIRES-ANY: OS=macosx, OS=linux-gnu
\ No newline at end of file
diff --git a/test/SwiftSyntax/DiagnosticTest.swift b/test/SwiftSyntax/DiagnosticTest.swift
new file mode 100644
index 0000000..929fa03
--- /dev/null
+++ b/test/SwiftSyntax/DiagnosticTest.swift
@@ -0,0 +1,59 @@
+// RUN: %target-run-simple-swift
+// REQUIRES: executable_test
+// REQUIRES: OS=macosx
+// REQUIRES: objc_interop
+
+import Foundation
+import StdlibUnittest
+import SwiftSyntax
+
+func loc(_ file: String = #file, line: Int = #line,
+         column: Int = #line) -> SourceLocation {
+  return SourceLocation(line: line, column: column, offset: 0, file: file)
+}
+
+/// Adds static constants to Diagnostic.Message.
+extension Diagnostic.Message {
+  /// Error thrown when a conversion between two types is impossible.
+  static func cannotConvert(fromType: String,
+                            toType: String) -> Diagnostic.Message {
+    return .init(.error,
+      "cannot convert value of type '\(fromType)' to '\(toType)'")
+  }
+
+  /// Suggestion for the user to explicitly check a value does not equal zero.
+  static let checkEqualToZero =
+    Diagnostic.Message(.note, "check for explicit equality to '0'")
+}
+
+var Diagnostics = TestSuite("Diagnostics")
+
+Diagnostics.test("DiagnosticEmission") {
+  let startLoc = loc()
+  let fixLoc = loc()
+
+  let engine = DiagnosticEngine()
+
+  engine.diagnose(.cannotConvert(fromType: "Int", toType: "Bool"),
+                  location: startLoc) {
+    $0.note(.checkEqualToZero, location: fixLoc,
+            fixIts: [.insert(fixLoc, " != 0")])
+  }
+
+  expectEqual(engine.diagnostics.count, 1)
+  guard let diag = engine.diagnostics.first else { return }
+  expectEqual(diag.message.text, 
+              "cannot convert value of type 'Int' to 'Bool'")
+  expectEqual(diag.message.severity, .error)
+  expectEqual(diag.notes.count, 1)
+
+  guard let note = diag.notes.first else { return }
+  expectEqual(note.message.text, "check for explicit equality to '0'")
+  expectEqual(note.message.severity, .note)
+  expectEqual(note.fixIts.count, 1)
+
+  guard let fixIt = note.fixIts.first else { return }
+  expectEqual(fixIt.text, " != 0")
+}
+
+runAllTests()
diff --git a/test/SwiftSyntax/LazyCaching.swift b/test/SwiftSyntax/LazyCaching.swift
index 753fca4..32386b8 100644
--- a/test/SwiftSyntax/LazyCaching.swift
+++ b/test/SwiftSyntax/LazyCaching.swift
@@ -1,7 +1,7 @@
 // RUN: %target-run-simple-swift
 // REQUIRES: executable_test
 // REQUIRES: OS=macosx
-// REQUIRES: sdk_overlay
+// REQUIRES: objc_interop
 
 import StdlibUnittest
 import Foundation
diff --git a/test/SwiftSyntax/ParseFile.swift b/test/SwiftSyntax/ParseFile.swift
index 4cd1ed1..34970a8 100644
--- a/test/SwiftSyntax/ParseFile.swift
+++ b/test/SwiftSyntax/ParseFile.swift
@@ -1,7 +1,7 @@
 // RUN: %target-run-simple-swift
 // REQUIRES: executable_test
 // REQUIRES: OS=macosx
-// REQUIRES: sdk_overlay
+// REQUIRES: objc_interop
 
 import Foundation
 import StdlibUnittest
diff --git a/test/SwiftSyntax/SyntaxChildren.swift b/test/SwiftSyntax/SyntaxChildren.swift
index a9af258..5b6522f 100644
--- a/test/SwiftSyntax/SyntaxChildren.swift
+++ b/test/SwiftSyntax/SyntaxChildren.swift
@@ -1,7 +1,7 @@
 // RUN: %target-run-simple-swift
 // REQUIRES: executable_test
 // REQUIRES: OS=macosx
-// REQUIRES: sdk_overlay
+// REQUIRES: objc_interop
 
 import Foundation
 import StdlibUnittest
diff --git a/test/SwiftSyntax/SyntaxFactory.swift b/test/SwiftSyntax/SyntaxFactory.swift
index f94d86a..624d418 100644
--- a/test/SwiftSyntax/SyntaxFactory.swift
+++ b/test/SwiftSyntax/SyntaxFactory.swift
@@ -1,21 +1,24 @@
 // RUN: %target-run-simple-swift
 // REQUIRES: executable_test
 // REQUIRES: OS=macosx
-// REQUIRES: sdk_overlay
+// REQUIRES: objc_interop
 
 import Foundation
 import StdlibUnittest
 import SwiftSyntax
 
 func cannedStructDecl() -> StructDeclSyntax {
-  let fooID = SyntaxFactory.makeIdentifier("Foo", trailingTrivia: .spaces(1))
   let structKW = SyntaxFactory.makeStructKeyword(trailingTrivia: .spaces(1))
+  let fooID = SyntaxFactory.makeIdentifier("Foo", trailingTrivia: .spaces(1))
   let rBrace = SyntaxFactory.makeRightBraceToken(leadingTrivia: .newlines(1))
+  let members = MemberDeclBlockSyntax {
+    $0.useLeftBrace(SyntaxFactory.makeLeftBraceToken())
+    $0.useRightBrace(rBrace)
+  }
   return StructDeclSyntax {
     $0.useStructKeyword(structKW)
     $0.useIdentifier(fooID)
-    $0.useLeftBrace(SyntaxFactory.makeLeftBraceToken())
-    $0.useRightBrace(rBrace)
+    $0.useMembers(members)
   }
 }
 
@@ -39,7 +42,8 @@
   let newBrace = SyntaxFactory.makeRightBraceToken(leadingTrivia: .newlines(2))
 
   let renamed = structDecl.withIdentifier(forType)
-                          .withRightBrace(newBrace)
+                          .withMembers(structDecl.members
+                                                 .withRightBrace(newBrace))
 
   expectEqual("\(renamed)",
               """
@@ -48,17 +52,17 @@
               }
               """)
 
-  expectNotEqual(structDecl.leftBrace, renamed.leftBrace)
+  expectNotEqual(structDecl.members, renamed.members)
   expectEqual(structDecl, structDecl.root)
   expectNil(structDecl.parent)
-  expectNotNil(structDecl.leftBrace.parent)
-  expectEqual(structDecl.leftBrace.parent, structDecl)
+  expectNotNil(structDecl.members.parent)
+  expectEqual(structDecl.members.parent, structDecl)
 
   // Ensure that accessing children via named identifiers is exactly the
   // same as accessing them as their underlying data.
-  expectEqual(structDecl.leftBrace, structDecl.child(at: 7))
+  expectEqual(structDecl.members, structDecl.child(at: 7))
   
-  expectEqual("\(structDecl.rightBrace)",
+  expectEqual("\(structDecl.members.rightBrace)",
               """
 
               }
diff --git a/test/Syntax/Inputs/serialize_struct_decl.json b/test/Syntax/Inputs/serialize_struct_decl.json
index d43cfb0..67ecd98 100644
--- a/test/Syntax/Inputs/serialize_struct_decl.json
+++ b/test/Syntax/Inputs/serialize_struct_decl.json
@@ -116,9 +116,23 @@
                               "kind": "DeclList",
                               "layout": [
                                 {
-                                  "kind": "UnknownDecl",
+                                  "kind": "VariableDecl",
                                   "layout": [
                                     {
+                                      "kind": "AttributeList",
+                                      "layout": [
+
+                                      ],
+                                      "presence": "Missing"
+                                    },
+                                    {
+                                      "kind": "ModifierList",
+                                      "layout": [
+
+                                      ],
+                                      "presence": "Missing"
+                                    },
+                                    {
                                       "tokenKind": {
                                         "kind": "kw_let"
                                       },
@@ -141,58 +155,108 @@
                                       "presence": "Present"
                                     },
                                     {
-                                      "tokenKind": {
-                                        "kind": "identifier",
-                                        "text": "bar"
-                                      },
-                                      "leadingTrivia": [
-
-                                      ],
-                                      "trailingTrivia": [
-                                        {
-                                          "kind": "Space",
-                                          "value": 1
-                                        }
-                                      ],
-                                      "presence": "Present"
-                                    },
-                                    {
-                                      "tokenKind": {
-                                        "kind": "colon"
-                                      },
-                                      "leadingTrivia": [
-
-                                      ],
-                                      "trailingTrivia": [
-                                        {
-                                          "kind": "Space",
-                                          "value": 1
-                                        }
-                                      ],
-                                      "presence": "Present"
-                                    },
-                                    {
-                                      "kind": "SimpleTypeIdentifier",
+                                      "kind": "PatternBindingList",
                                       "layout": [
                                         {
-                                          "tokenKind": {
-                                            "kind": "identifier",
-                                            "text": "Int"
-                                          },
-                                          "leadingTrivia": [
+                                          "kind": "PatternBinding",
+                                          "layout": [
+                                            {
+                                              "kind": "IdentifierPattern",
+                                              "layout": [
+                                                {
+                                                  "tokenKind": {
+                                                    "kind": "identifier",
+                                                    "text": "bar"
+                                                  },
+                                                  "leadingTrivia": [
 
-                                          ],
-                                          "trailingTrivia": [
+                                                  ],
+                                                  "trailingTrivia": [
+                                                    {
+                                                      "kind": "Space",
+                                                      "value": 1
+                                                    }
+                                                  ],
+                                                  "presence": "Present"
+                                                }
+                                              ],
+                                              "presence": "Present"
+                                            },
+                                            {
+                                              "kind": "TypeAnnotation",
+                                              "layout": [
+                                                {
+                                                  "tokenKind": {
+                                                    "kind": "colon"
+                                                  },
+                                                  "leadingTrivia": [
 
+                                                  ],
+                                                  "trailingTrivia": [
+                                                    {
+                                                      "kind": "Space",
+                                                      "value": 1
+                                                    }
+                                                  ],
+                                                  "presence": "Present"
+                                                },
+                                                {
+                                                  "kind": "SimpleTypeIdentifier",
+                                                  "layout": [
+                                                    {
+                                                      "tokenKind": {
+                                                        "kind": "identifier",
+                                                        "text": "Int"
+                                                      },
+                                                      "leadingTrivia": [
+
+                                                      ],
+                                                      "trailingTrivia": [
+
+                                                      ],
+                                                      "presence": "Present"
+                                                    },
+                                                    {
+                                                      "kind": "GenericArgumentClause",
+                                                      "layout": [
+
+                                                      ],
+                                                      "presence": "Missing"
+                                                    }
+                                                  ],
+                                                  "presence": "Present"
+                                                }
+                                              ],
+                                              "presence": "Present"
+                                            },
+                                            {
+                                              "kind": "InitializerClause",
+                                              "layout": [
+
+                                              ],
+                                              "presence": "Missing"
+                                            },
+                                            {
+                                              "kind": "AccessorBlock",
+                                              "layout": [
+
+                                              ],
+                                              "presence": "Missing"
+                                            },
+                                            {
+                                              "tokenKind": {
+                                                "kind": "comma"
+                                              },
+                                              "leadingTrivia": [
+
+                                              ],
+                                              "trailingTrivia": [
+
+                                              ],
+                                              "presence": "Missing"
+                                            }
                                           ],
                                           "presence": "Present"
-                                        },
-                                        {
-                                          "kind": "GenericArgumentClause",
-                                          "layout": [
-
-                                          ],
-                                          "presence": "Missing"
                                         }
                                       ],
                                       "presence": "Present"
@@ -201,9 +265,23 @@
                                   "presence": "Present"
                                 },
                                 {
-                                  "kind": "UnknownDecl",
+                                  "kind": "VariableDecl",
                                   "layout": [
                                     {
+                                      "kind": "AttributeList",
+                                      "layout": [
+
+                                      ],
+                                      "presence": "Missing"
+                                    },
+                                    {
+                                      "kind": "ModifierList",
+                                      "layout": [
+
+                                      ],
+                                      "presence": "Missing"
+                                    },
+                                    {
                                       "tokenKind": {
                                         "kind": "kw_let"
                                       },
@@ -226,86 +304,76 @@
                                       "presence": "Present"
                                     },
                                     {
-                                      "tokenKind": {
-                                        "kind": "identifier",
-                                        "text": "baz"
-                                      },
-                                      "leadingTrivia": [
-
-                                      ],
-                                      "trailingTrivia": [
-                                        {
-                                          "kind": "Space",
-                                          "value": 1
-                                        }
-                                      ],
-                                      "presence": "Present"
-                                    },
-                                    {
-                                      "tokenKind": {
-                                        "kind": "colon"
-                                      },
-                                      "leadingTrivia": [
-
-                                      ],
-                                      "trailingTrivia": [
-                                        {
-                                          "kind": "Space",
-                                          "value": 1
-                                        }
-                                      ],
-                                      "presence": "Present"
-                                    },
-                                    {
-                                      "kind": "SimpleTypeIdentifier",
+                                      "kind": "PatternBindingList",
                                       "layout": [
                                         {
-                                          "tokenKind": {
-                                            "kind": "identifier",
-                                            "text": "Array"
-                                          },
-                                          "leadingTrivia": [
-
-                                          ],
-                                          "trailingTrivia": [
-                                            {
-                                              "kind": "Space",
-                                              "value": 1
-                                            }
-                                          ],
-                                          "presence": "Present"
-                                        },
-                                        {
-                                          "kind": "GenericArgumentClause",
+                                          "kind": "PatternBinding",
                                           "layout": [
                                             {
-                                              "tokenKind": {
-                                                "kind": "l_angle"
-                                              },
-                                              "leadingTrivia": [
-
-                                              ],
-                                              "trailingTrivia": [
+                                              "kind": "IdentifierPattern",
+                                              "layout": [
                                                 {
-                                                  "kind": "Space",
-                                                  "value": 1
+                                                  "tokenKind": {
+                                                    "kind": "identifier",
+                                                    "text": "baz"
+                                                  },
+                                                  "leadingTrivia": [
+
+                                                  ],
+                                                  "trailingTrivia": [
+                                                    {
+                                                      "kind": "Space",
+                                                      "value": 1
+                                                    }
+                                                  ],
+                                                  "presence": "Present"
                                                 }
                                               ],
                                               "presence": "Present"
                                             },
                                             {
-                                              "kind": "GenericArgumentList",
+                                              "kind": "TypeAnnotation",
                                               "layout": [
                                                 {
-                                                  "kind": "GenericArgument",
+                                                  "tokenKind": {
+                                                    "kind": "colon"
+                                                  },
+                                                  "leadingTrivia": [
+
+                                                  ],
+                                                  "trailingTrivia": [
+                                                    {
+                                                      "kind": "Space",
+                                                      "value": 1
+                                                    }
+                                                  ],
+                                                  "presence": "Present"
+                                                },
+                                                {
+                                                  "kind": "SimpleTypeIdentifier",
                                                   "layout": [
                                                     {
-                                                      "kind": "SimpleTypeIdentifier",
+                                                      "tokenKind": {
+                                                        "kind": "identifier",
+                                                        "text": "Array"
+                                                      },
+                                                      "leadingTrivia": [
+
+                                                      ],
+                                                      "trailingTrivia": [
+                                                        {
+                                                          "kind": "Space",
+                                                          "value": 1
+                                                        }
+                                                      ],
+                                                      "presence": "Present"
+                                                    },
+                                                    {
+                                                      "kind": "GenericArgumentClause",
                                                       "layout": [
                                                         {
                                                           "tokenKind": {
-                                                            "kind": "identifier",
-                                                            "text": "Int"
+                                                            "kind": "l_angle"
                                                           },
                                                           "leadingTrivia": [
 
@@ -319,26 +387,72 @@
                                                           "presence": "Present"
                                                         },
                                                         {
-                                                          "kind": "GenericArgumentClause",
+                                                          "kind": "GenericArgumentList",
                                                           "layout": [
+                                                            {
+                                                              "kind": "GenericArgument",
+                                                              "layout": [
+                                                                {
+                                                                  "kind": "SimpleTypeIdentifier",
+                                                                  "layout": [
+                                                                    {
+                                                                      "tokenKind": {
+                                                                        "kind": "identifier",
+                                                                        "text": "Int"
+                                                                      },
+                                                                      "leadingTrivia": [
+
+                                                                      ],
+                                                                      "trailingTrivia": [
+                                                                        {
+                                                                          "kind": "Space",
+                                                                          "value": 1
+                                                                        }
+                                                                      ],
+                                                                      "presence": "Present"
+                                                                    },
+                                                                    {
+                                                                      "kind": "GenericArgumentClause",
+                                                                      "layout": [
+
+                                                                      ],
+                                                                      "presence": "Missing"
+                                                                    }
+                                                                  ],
+                                                                  "presence": "Present"
+                                                                },
+                                                                {
+                                                                  "tokenKind": {
+                                                                    "kind": "comma"
+                                                                  },
+                                                                  "leadingTrivia": [
+
+                                                                  ],
+                                                                  "trailingTrivia": [
+
+                                                                  ],
+                                                                  "presence": "Missing"
+                                                                }
+                                                              ],
+                                                              "presence": "Present"
+                                                            }
+                                                          ],
+                                                          "presence": "Present"
+                                                        },
+                                                        {
+                                                          "tokenKind": {
+                                                            "kind": "r_angle"
+                                                          },
+                                                          "leadingTrivia": [
 
                                                           ],
-                                                          "presence": "Missing"
+                                                          "trailingTrivia": [
+
+                                                          ],
+                                                          "presence": "Present"
                                                         }
                                                       ],
                                                       "presence": "Present"
-                                                    },
-                                                    {
-                                                      "tokenKind": {
-                                                        "kind": "comma"
-                                                      },
-                                                      "leadingTrivia": [
-
-                                                      ],
-                                                      "trailingTrivia": [
-
-                                                      ],
-                                                      "presence": "Missing"
                                                     }
                                                   ],
                                                   "presence": "Present"
@@ -347,8 +461,22 @@
                                               "presence": "Present"
                                             },
                                             {
+                                              "kind": "InitializerClause",
+                                              "layout": [
+
+                                              ],
+                                              "presence": "Missing"
+                                            },
+                                            {
+                                              "kind": "AccessorBlock",
+                                              "layout": [
+
+                                              ],
+                                              "presence": "Missing"
+                                            },
+                                            {
                                               "tokenKind": {
-                                                "kind": "r_angle"
+                                                "kind": "comma"
                                               },
                                               "leadingTrivia": [
 
@@ -356,7 +484,7 @@
                                               "trailingTrivia": [
 
                                               ],
-                                              "presence": "Present"
+                                              "presence": "Missing"
                                             }
                                           ],
                                           "presence": "Present"
diff --git a/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds b/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds
index b3790df..92b145f 100644
--- a/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds
+++ b/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds
@@ -1,42 +1,50 @@
-// RUN: %swift-syntax-test -input-source-filename %s -parse-gen > %t
+<ImportDecl>// RUN: %swift-syntax-test -input-source-filename %s -parse-gen > %t
 // RUN: diff -u %s %t
 // RUN: %swift-syntax-test -input-source-filename %s -parse-gen -print-node-kind > %t.withkinds
 // RUN: diff -u %S/Outputs/round_trip_parse_gen.swift.withkinds %t.withkinds
 
-class C {<FunctionDecl>
-  func bar<FunctionSignature>(<FunctionParameter>_ a: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></FunctionParameter>) </FunctionSignature><CodeBlock>{}</CodeBlock></FunctionDecl><FunctionDecl>
-  func bar1<FunctionSignature>(<FunctionParameter>_ a: <SimpleTypeIdentifier>Float</SimpleTypeIdentifier></FunctionParameter>) -> <SimpleTypeIdentifier>Float </SimpleTypeIdentifier></FunctionSignature><CodeBlock>{ <ReturnStmt>return <SequenceExpr><PrefixOperatorExpr>-<FloatLiteralExpr>0.6 </FloatLiteralExpr></PrefixOperatorExpr><BinaryOperatorExpr>+ </BinaryOperatorExpr><FloatLiteralExpr>0.1 </FloatLiteralExpr><BinaryOperatorExpr>- </BinaryOperatorExpr><FloatLiteralExpr>0.3 </FloatLiteralExpr></SequenceExpr></ReturnStmt>}</CodeBlock></FunctionDecl><FunctionDecl>
-  func bar2<FunctionSignature>(<FunctionParameter>a: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier>, </FunctionParameter><FunctionParameter>b: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier>, </FunctionParameter><FunctionParameter>c:<SimpleTypeIdentifier>Int</SimpleTypeIdentifier></FunctionParameter>) -> <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></FunctionSignature><CodeBlock>{ <ReturnStmt>return <IntegerLiteralExpr>1 </IntegerLiteralExpr></ReturnStmt>}</CodeBlock></FunctionDecl><FunctionDecl>
-  func bar3<FunctionSignature>(<FunctionParameter>a: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></FunctionParameter>) -> <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></FunctionSignature><CodeBlock>{ <ReturnStmt>return <IntegerLiteralExpr>1 </IntegerLiteralExpr></ReturnStmt>}</CodeBlock></FunctionDecl><FunctionDecl>
-  func bar4<FunctionSignature>(<FunctionParameter>_ a: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></FunctionParameter>) -> <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></FunctionSignature><CodeBlock>{ <ReturnStmt>return <IntegerLiteralExpr>1 </IntegerLiteralExpr></ReturnStmt>}</CodeBlock></FunctionDecl><FunctionDecl>
-  func foo<FunctionSignature>() </FunctionSignature><CodeBlock>{
-    var a = <StringLiteralExpr>/*comment*/"ab\(x)c"</StringLiteralExpr>/*comment*/
-    var b = <PrefixOperatorExpr>/*comment*/+<IntegerLiteralExpr>2</IntegerLiteralExpr></PrefixOperatorExpr><IdentifierExpr>/*comment*/
+import <AccessPathComponent>ABC</AccessPathComponent></ImportDecl><ImportDecl>
+import <AccessPathComponent>A.</AccessPathComponent><AccessPathComponent>B.</AccessPathComponent><AccessPathComponent>C</AccessPathComponent></ImportDecl><ImportDecl><Attribute>
+@objc </Attribute>import <AccessPathComponent>A.</AccessPathComponent><AccessPathComponent>B</AccessPathComponent></ImportDecl><ImportDecl><Attribute>
+@objc </Attribute>import typealias <AccessPathComponent>A.</AccessPathComponent><AccessPathComponent>B</AccessPathComponent></ImportDecl><ImportDecl>
+import struct <AccessPathComponent>A.</AccessPathComponent><AccessPathComponent>B</AccessPathComponent></ImportDecl><IfConfigDecl>
+
+#if <IdentifierExpr>Blah</IdentifierExpr><ClassDecl>
+class C <MemberDeclBlock>{<FunctionDecl>
+  func bar<FunctionSignature><ParameterClause>(<FunctionParameter>_ a: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></FunctionParameter>) </ParameterClause></FunctionSignature><CodeBlock>{}</CodeBlock></FunctionDecl><FunctionDecl>
+  func bar1<FunctionSignature><ParameterClause>(<FunctionParameter>_ a: <SimpleTypeIdentifier>Float</SimpleTypeIdentifier></FunctionParameter>) </ParameterClause><ReturnClause>-> <SimpleTypeIdentifier>Float </SimpleTypeIdentifier></ReturnClause></FunctionSignature><CodeBlock>{ <ReturnStmt>return <SequenceExpr><PrefixOperatorExpr>-<FloatLiteralExpr>0.6 </FloatLiteralExpr></PrefixOperatorExpr><BinaryOperatorExpr>+ </BinaryOperatorExpr><FloatLiteralExpr>0.1 </FloatLiteralExpr><BinaryOperatorExpr>- </BinaryOperatorExpr><FloatLiteralExpr>0.3 </FloatLiteralExpr></SequenceExpr></ReturnStmt>}</CodeBlock></FunctionDecl><FunctionDecl>
+  func bar2<FunctionSignature><ParameterClause>(<FunctionParameter>a: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier>, </FunctionParameter><FunctionParameter>b: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier>, </FunctionParameter><FunctionParameter>c:<SimpleTypeIdentifier>Int</SimpleTypeIdentifier></FunctionParameter>) </ParameterClause><ReturnClause>-> <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></ReturnClause></FunctionSignature><CodeBlock>{ <ReturnStmt>return <IntegerLiteralExpr>1 </IntegerLiteralExpr></ReturnStmt>}</CodeBlock></FunctionDecl><FunctionDecl>
+  func bar3<FunctionSignature><ParameterClause>(<FunctionParameter>a: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></FunctionParameter>) </ParameterClause><ReturnClause>-> <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></ReturnClause></FunctionSignature><CodeBlock>{ <ReturnStmt>return <IntegerLiteralExpr>1 </IntegerLiteralExpr></ReturnStmt>}</CodeBlock></FunctionDecl><FunctionDecl>
+  func bar4<FunctionSignature><ParameterClause>(<FunctionParameter>_ a: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></FunctionParameter>) </ParameterClause><ReturnClause>-> <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></ReturnClause></FunctionSignature><CodeBlock>{ <ReturnStmt>return <IntegerLiteralExpr>1 </IntegerLiteralExpr></ReturnStmt>}</CodeBlock></FunctionDecl><FunctionDecl>
+  func foo<FunctionSignature><ParameterClause>() </ParameterClause></FunctionSignature><CodeBlock>{<VariableDecl>
+    var <PatternBinding><IdentifierPattern>a </IdentifierPattern><InitializerClause>= <StringLiteralExpr>/*comment*/"ab\(x)c"</StringLiteralExpr></InitializerClause></PatternBinding></VariableDecl><VariableDecl>/*comment*/
+    var <PatternBinding><IdentifierPattern>b </IdentifierPattern><InitializerClause>= <PrefixOperatorExpr>/*comment*/+<IntegerLiteralExpr>2</IntegerLiteralExpr></PrefixOperatorExpr></InitializerClause></PatternBinding></VariableDecl><IdentifierExpr>/*comment*/
     bar</IdentifierExpr>(<FunctionCallArgument><IntegerLiteralExpr>1</IntegerLiteralExpr></FunctionCallArgument>)<IdentifierExpr>
     bar</IdentifierExpr>(<FunctionCallArgument><PrefixOperatorExpr>+<IntegerLiteralExpr>10</IntegerLiteralExpr></PrefixOperatorExpr></FunctionCallArgument>)<IdentifierExpr>
     bar</IdentifierExpr>(<FunctionCallArgument><PrefixOperatorExpr>-<IntegerLiteralExpr>10</IntegerLiteralExpr></PrefixOperatorExpr></FunctionCallArgument>)<IdentifierExpr>
     bar1</IdentifierExpr>(<FunctionCallArgument><PrefixOperatorExpr>-<FloatLiteralExpr>1.1</FloatLiteralExpr></PrefixOperatorExpr></FunctionCallArgument>)<IdentifierExpr>
-    bar1</IdentifierExpr>(<FunctionCallArgument><FloatLiteralExpr>1.1</FloatLiteralExpr></FunctionCallArgument>)
-    var f = <PrefixOperatorExpr>/*comments*/+<FloatLiteralExpr>0.1</FloatLiteralExpr></PrefixOperatorExpr><IdentifierExpr>/*comments*/
+    bar1</IdentifierExpr>(<FunctionCallArgument><FloatLiteralExpr>1.1</FloatLiteralExpr></FunctionCallArgument>)<VariableDecl>
+    var <PatternBinding><IdentifierPattern>f </IdentifierPattern><InitializerClause>= <PrefixOperatorExpr>/*comments*/+<FloatLiteralExpr>0.1</FloatLiteralExpr></PrefixOperatorExpr></InitializerClause></PatternBinding></VariableDecl><IdentifierExpr>/*comments*/
     foo</IdentifierExpr>()
   }</CodeBlock></FunctionDecl><FunctionDecl>
 
-  func foo1<FunctionSignature>() </FunctionSignature><CodeBlock>{<SequenceExpr><DiscardAssignmentExpr>
+  func foo1<FunctionSignature><ParameterClause>() </ParameterClause></FunctionSignature><CodeBlock>{<SequenceExpr><DiscardAssignmentExpr>
     _ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><IdentifierExpr>bar2</IdentifierExpr>(<FunctionCallArgument>a:<IntegerLiteralExpr>1</IntegerLiteralExpr>, </FunctionCallArgument><FunctionCallArgument>b:<IntegerLiteralExpr>2</IntegerLiteralExpr>, </FunctionCallArgument><FunctionCallArgument>c:<IntegerLiteralExpr>2</IntegerLiteralExpr></FunctionCallArgument>)</SequenceExpr><SequenceExpr><DiscardAssignmentExpr>
     _ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><IdentifierExpr>bar2</IdentifierExpr>(<FunctionCallArgument>a:<SequenceExpr><IntegerLiteralExpr>1 </IntegerLiteralExpr><BinaryOperatorExpr>+ </BinaryOperatorExpr><IntegerLiteralExpr>1</IntegerLiteralExpr></SequenceExpr>, </FunctionCallArgument><FunctionCallArgument>b:<SequenceExpr><IntegerLiteralExpr>2 </IntegerLiteralExpr><BinaryOperatorExpr>* </BinaryOperatorExpr><IntegerLiteralExpr>2 </IntegerLiteralExpr><BinaryOperatorExpr>+ </BinaryOperatorExpr><IntegerLiteralExpr>2</IntegerLiteralExpr></SequenceExpr>, </FunctionCallArgument><FunctionCallArgument>c:<SequenceExpr><IntegerLiteralExpr>2 </IntegerLiteralExpr><BinaryOperatorExpr>+ </BinaryOperatorExpr><IntegerLiteralExpr>2</IntegerLiteralExpr></SequenceExpr></FunctionCallArgument>)</SequenceExpr><SequenceExpr><DiscardAssignmentExpr>
     _ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><IdentifierExpr>bar2</IdentifierExpr>(<FunctionCallArgument>a : <IdentifierExpr>bar2</IdentifierExpr>(<FunctionCallArgument>a: <IntegerLiteralExpr>1</IntegerLiteralExpr>, </FunctionCallArgument><FunctionCallArgument>b: <IntegerLiteralExpr>2</IntegerLiteralExpr>, </FunctionCallArgument><FunctionCallArgument>c: <IntegerLiteralExpr>3</IntegerLiteralExpr></FunctionCallArgument>), </FunctionCallArgument><FunctionCallArgument>b: <IntegerLiteralExpr>2</IntegerLiteralExpr>, </FunctionCallArgument><FunctionCallArgument>c: <IntegerLiteralExpr>3</IntegerLiteralExpr></FunctionCallArgument>)</SequenceExpr><SequenceExpr><DiscardAssignmentExpr>
     _ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><IdentifierExpr>bar3</IdentifierExpr>(<FunctionCallArgument>a : <IdentifierExpr>bar3</IdentifierExpr>(<FunctionCallArgument>a: <IdentifierExpr>bar3</IdentifierExpr>(<FunctionCallArgument>a: <IntegerLiteralExpr>1</IntegerLiteralExpr></FunctionCallArgument>)</FunctionCallArgument>)</FunctionCallArgument>)</SequenceExpr><SequenceExpr><DiscardAssignmentExpr>
     _ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><IdentifierExpr>bar4</IdentifierExpr>(<FunctionCallArgument><IdentifierExpr>bar4</IdentifierExpr>(<FunctionCallArgument><IdentifierExpr>bar4</IdentifierExpr>(<FunctionCallArgument><IntegerLiteralExpr>1</IntegerLiteralExpr></FunctionCallArgument>)</FunctionCallArgument>)</FunctionCallArgument>)</SequenceExpr><SequenceExpr><DiscardAssignmentExpr>
+    _ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><DictionaryExpr>[:]</DictionaryExpr></SequenceExpr><SequenceExpr><DiscardAssignmentExpr>
     _ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><ArrayExpr>[<ArrayElement><IntegerLiteralExpr>1</IntegerLiteralExpr>, </ArrayElement><ArrayElement><IntegerLiteralExpr>2</IntegerLiteralExpr>, </ArrayElement><ArrayElement><IntegerLiteralExpr>3</IntegerLiteralExpr>, </ArrayElement><ArrayElement><IntegerLiteralExpr>4</IntegerLiteralExpr></ArrayElement>]</ArrayExpr></SequenceExpr><SequenceExpr><DiscardAssignmentExpr>
     _ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><DictionaryExpr>[<DictionaryElement><IntegerLiteralExpr>1</IntegerLiteralExpr>:<IntegerLiteralExpr>1</IntegerLiteralExpr>, </DictionaryElement><DictionaryElement><IntegerLiteralExpr>2</IntegerLiteralExpr>:<IntegerLiteralExpr>2</IntegerLiteralExpr>, </DictionaryElement><DictionaryElement><IntegerLiteralExpr>3</IntegerLiteralExpr>:<IntegerLiteralExpr>3</IntegerLiteralExpr>, </DictionaryElement><DictionaryElement><IntegerLiteralExpr>4</IntegerLiteralExpr>:<IntegerLiteralExpr>4</IntegerLiteralExpr></DictionaryElement>]</DictionaryExpr></SequenceExpr><SequenceExpr><DiscardAssignmentExpr>
     _ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><ArrayExpr>[<ArrayElement><IdentifierExpr>bar3</IdentifierExpr>(<FunctionCallArgument>a:<IntegerLiteralExpr>1</IntegerLiteralExpr></FunctionCallArgument>), </ArrayElement><ArrayElement><IdentifierExpr>bar3</IdentifierExpr>(<FunctionCallArgument>a:<IntegerLiteralExpr>1</IntegerLiteralExpr></FunctionCallArgument>), </ArrayElement><ArrayElement><IdentifierExpr>bar3</IdentifierExpr>(<FunctionCallArgument>a:<IntegerLiteralExpr>1</IntegerLiteralExpr></FunctionCallArgument>), </ArrayElement><ArrayElement><IdentifierExpr>bar3</IdentifierExpr>(<FunctionCallArgument>a:<IntegerLiteralExpr>1</IntegerLiteralExpr></FunctionCallArgument>)</ArrayElement>]</ArrayExpr></SequenceExpr><SequenceExpr><DiscardAssignmentExpr>
     _ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><DictionaryExpr>[<DictionaryElement><StringLiteralExpr>"a"</StringLiteralExpr>: <IdentifierExpr>bar3</IdentifierExpr>(<FunctionCallArgument>a:<IntegerLiteralExpr>1</IntegerLiteralExpr></FunctionCallArgument>), </DictionaryElement><DictionaryElement><StringLiteralExpr>"b"</StringLiteralExpr>: <IdentifierExpr>bar3</IdentifierExpr>(<FunctionCallArgument>a:<IntegerLiteralExpr>1</IntegerLiteralExpr></FunctionCallArgument>), </DictionaryElement><DictionaryElement><StringLiteralExpr>"c"</StringLiteralExpr>: <IdentifierExpr>bar3</IdentifierExpr>(<FunctionCallArgument>a:<IntegerLiteralExpr>1</IntegerLiteralExpr></FunctionCallArgument>), </DictionaryElement><DictionaryElement><StringLiteralExpr>"d"</StringLiteralExpr>: <IdentifierExpr>bar3</IdentifierExpr>(<FunctionCallArgument>a:<IntegerLiteralExpr>1</IntegerLiteralExpr></FunctionCallArgument>)</DictionaryElement>]</DictionaryExpr></SequenceExpr><IdentifierExpr>
     foo</IdentifierExpr>(<FunctionCallArgument><NilLiteralExpr>nil</NilLiteralExpr>, </FunctionCallArgument><FunctionCallArgument><NilLiteralExpr>nil</NilLiteralExpr>, </FunctionCallArgument><FunctionCallArgument><NilLiteralExpr>nil</NilLiteralExpr></FunctionCallArgument>)
   }</CodeBlock></FunctionDecl><FunctionDecl>
-  func boolAnd<FunctionSignature>() -> <SimpleTypeIdentifier>Bool </SimpleTypeIdentifier></FunctionSignature><CodeBlock>{ <ReturnStmt>return <SequenceExpr><BooleanLiteralExpr>true </BooleanLiteralExpr><BinaryOperatorExpr>&& </BinaryOperatorExpr><BooleanLiteralExpr>false </BooleanLiteralExpr></SequenceExpr></ReturnStmt>}</CodeBlock></FunctionDecl><FunctionDecl>
-  func boolOr<FunctionSignature>() -> <SimpleTypeIdentifier>Bool </SimpleTypeIdentifier></FunctionSignature><CodeBlock>{ <ReturnStmt>return <SequenceExpr><BooleanLiteralExpr>true </BooleanLiteralExpr><BinaryOperatorExpr>|| </BinaryOperatorExpr><BooleanLiteralExpr>false </BooleanLiteralExpr></SequenceExpr></ReturnStmt>}</CodeBlock></FunctionDecl><FunctionDecl>
+  func boolAnd<FunctionSignature><ParameterClause>() </ParameterClause><ReturnClause>-> <SimpleTypeIdentifier>Bool </SimpleTypeIdentifier></ReturnClause></FunctionSignature><CodeBlock>{ <ReturnStmt>return <SequenceExpr><BooleanLiteralExpr>true </BooleanLiteralExpr><BinaryOperatorExpr>&& </BinaryOperatorExpr><BooleanLiteralExpr>false </BooleanLiteralExpr></SequenceExpr></ReturnStmt>}</CodeBlock></FunctionDecl><FunctionDecl>
+  func boolOr<FunctionSignature><ParameterClause>() </ParameterClause><ReturnClause>-> <SimpleTypeIdentifier>Bool </SimpleTypeIdentifier></ReturnClause></FunctionSignature><CodeBlock>{ <ReturnStmt>return <SequenceExpr><BooleanLiteralExpr>true </BooleanLiteralExpr><BinaryOperatorExpr>|| </BinaryOperatorExpr><BooleanLiteralExpr>false </BooleanLiteralExpr></SequenceExpr></ReturnStmt>}</CodeBlock></FunctionDecl><FunctionDecl>
 
-  func foo2<FunctionSignature>() </FunctionSignature><CodeBlock>{<SequenceExpr><DiscardAssignmentExpr>
+  func foo2<FunctionSignature><ParameterClause>() </ParameterClause></FunctionSignature><CodeBlock>{<SequenceExpr><DiscardAssignmentExpr>
     _ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><TernaryExpr><BooleanLiteralExpr>true </BooleanLiteralExpr>? <IntegerLiteralExpr>1 </IntegerLiteralExpr>: <IntegerLiteralExpr>0</IntegerLiteralExpr></TernaryExpr></SequenceExpr><SequenceExpr><DiscardAssignmentExpr>
     _ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><TernaryExpr><TupleExpr>(<TupleElement><SequenceExpr><TernaryExpr><BooleanLiteralExpr>true </BooleanLiteralExpr>? <IntegerLiteralExpr>1 </IntegerLiteralExpr>: <IntegerLiteralExpr>0</IntegerLiteralExpr></TernaryExpr></SequenceExpr></TupleElement>) </TupleExpr>? <TupleExpr>(<TupleElement><SequenceExpr><TernaryExpr><BooleanLiteralExpr>true </BooleanLiteralExpr>? <IntegerLiteralExpr>1 </IntegerLiteralExpr>: <IntegerLiteralExpr>0</IntegerLiteralExpr></TernaryExpr></SequenceExpr></TupleElement>) </TupleExpr>: <TupleExpr>(<TupleElement><SequenceExpr><TernaryExpr><BooleanLiteralExpr>true </BooleanLiteralExpr>? <IntegerLiteralExpr>1 </IntegerLiteralExpr>: <IntegerLiteralExpr>0</IntegerLiteralExpr></TernaryExpr></SequenceExpr></TupleElement>)</TupleExpr></TernaryExpr></SequenceExpr><SequenceExpr><DiscardAssignmentExpr>
     _ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><TupleExpr>(<TupleElement><IntegerLiteralExpr>1</IntegerLiteralExpr>, </TupleElement><TupleElement><IntegerLiteralExpr>2</IntegerLiteralExpr></TupleElement>)</TupleExpr></SequenceExpr><SequenceExpr><DiscardAssignmentExpr>
@@ -48,7 +56,7 @@
     }</CodeBlock>
   }</CodeBlock></FunctionDecl><FunctionDecl>
 
-  func foo3<FunctionSignature>() </FunctionSignature><CodeBlock>{<SequenceExpr><DiscardAssignmentExpr>
+  func foo3<FunctionSignature><ParameterClause>() </ParameterClause></FunctionSignature><CodeBlock>{<SequenceExpr><DiscardAssignmentExpr>
     _ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><ArrayExpr>[<ArrayElement><TypeExpr><SimpleTypeIdentifier>Any</SimpleTypeIdentifier></TypeExpr></ArrayElement>]</ArrayExpr>()</SequenceExpr><SequenceExpr><DiscardAssignmentExpr>
     _ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><MemberAccessExpr><MemberAccessExpr><IdentifierExpr>a</IdentifierExpr>.a</MemberAccessExpr>.a</MemberAccessExpr></SequenceExpr><SequenceExpr><DiscardAssignmentExpr>
     _ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><MemberAccessExpr><IdentifierExpr>a</IdentifierExpr>.b</MemberAccessExpr></SequenceExpr><SequenceExpr><DiscardAssignmentExpr>
@@ -57,19 +65,46 @@
     _ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><IdentifierExpr>a </IdentifierExpr><AsExpr>as <SimpleTypeIdentifier>Bool </SimpleTypeIdentifier></AsExpr><BinaryOperatorExpr>|| </BinaryOperatorExpr><IdentifierExpr>a </IdentifierExpr><AsExpr>as! <SimpleTypeIdentifier>Bool </SimpleTypeIdentifier></AsExpr><BinaryOperatorExpr>|| </BinaryOperatorExpr><IdentifierExpr>a </IdentifierExpr><AsExpr>as? <SimpleTypeIdentifier>Bool</SimpleTypeIdentifier></AsExpr></SequenceExpr><SequenceExpr><DiscardAssignmentExpr>
     _ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><IdentifierExpr>a </IdentifierExpr><IsExpr>is <SimpleTypeIdentifier>Bool</SimpleTypeIdentifier></IsExpr></SequenceExpr>
   }</CodeBlock></FunctionDecl>
-}
+}</MemberDeclBlock></ClassDecl>
 
-typealias A = <SimpleTypeIdentifier>Any</SimpleTypeIdentifier>
-typealias B = (<MemberTypeIdentifier><SimpleTypeIdentifier>Array<GenericArgumentClause><<GenericArgument><SimpleTypeIdentifier>Array<GenericArgumentClause><<GenericArgument><SimpleTypeIdentifier>Any</SimpleTypeIdentifier></GenericArgument>></GenericArgumentClause></SimpleTypeIdentifier></GenericArgument>></GenericArgumentClause></SimpleTypeIdentifier>.Element</MemberTypeIdentifier>)
-typealias C = <ArrayType>[<SimpleTypeIdentifier>Int</SimpleTypeIdentifier>]</ArrayType>
-typealias D = <DictionaryType>[<SimpleTypeIdentifier>Int</SimpleTypeIdentifier>: <SimpleTypeIdentifier>String</SimpleTypeIdentifier>]</DictionaryType>
-typealias E = <MetatypeType><OptionalType><SimpleTypeIdentifier>Int</SimpleTypeIdentifier>?</OptionalType>.Protocol</MetatypeType>
-typealias F = <MetatypeType><ImplicitlyUnwrappedOptionalType><ArrayType>[<SimpleTypeIdentifier>Int</SimpleTypeIdentifier>]</ArrayType>!</ImplicitlyUnwrappedOptionalType>.Type</MetatypeType><StructDecl>
+#endif</IfConfigDecl><IfConfigDecl>
+
+#if <IdentifierExpr>blah</IdentifierExpr><TypealiasDecl>
+typealias A <TypeInitializerClause>= <SimpleTypeIdentifier>Any</SimpleTypeIdentifier></TypeInitializerClause></TypealiasDecl><ElseifDirectiveClause>
+#elseif <IdentifierExpr>blahblah</IdentifierExpr><TypealiasDecl>
+typealias B <TypeInitializerClause>= <TupleType>(<TupleTypeElement><MemberTypeIdentifier><SimpleTypeIdentifier>Array<GenericArgumentClause><<GenericArgument><SimpleTypeIdentifier>Array<GenericArgumentClause><<GenericArgument><SimpleTypeIdentifier>Any</SimpleTypeIdentifier></GenericArgument>></GenericArgumentClause></SimpleTypeIdentifier></GenericArgument>></GenericArgumentClause></SimpleTypeIdentifier>.Element</MemberTypeIdentifier>, </TupleTypeElement><TupleTypeElement>x: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></TupleTypeElement>)</TupleType></TypeInitializerClause></TypealiasDecl></ElseifDirectiveClause><ElseDirectiveClause>
+#else<TypealiasDecl>
+typealias C <TypeInitializerClause>= <ArrayType>[<SimpleTypeIdentifier>Int</SimpleTypeIdentifier>]</ArrayType></TypeInitializerClause></TypealiasDecl></ElseDirectiveClause>
+#endif</IfConfigDecl><TypealiasDecl>
+typealias D <TypeInitializerClause>= <DictionaryType>[<SimpleTypeIdentifier>Int</SimpleTypeIdentifier>: <SimpleTypeIdentifier>String</SimpleTypeIdentifier>]</DictionaryType></TypeInitializerClause></TypealiasDecl><TypealiasDecl>
+typealias E <TypeInitializerClause>= <MetatypeType><OptionalType><SimpleTypeIdentifier>Int</SimpleTypeIdentifier>?</OptionalType>.Protocol</MetatypeType></TypeInitializerClause></TypealiasDecl><TypealiasDecl>
+typealias F <TypeInitializerClause>= <MetatypeType><ImplicitlyUnwrappedOptionalType><ArrayType>[<SimpleTypeIdentifier>Int</SimpleTypeIdentifier>]</ArrayType>!</ImplicitlyUnwrappedOptionalType>.Type</MetatypeType></TypeInitializerClause></TypealiasDecl><TypealiasDecl>
+typealias G <TypeInitializerClause>= <FunctionType>(<TupleTypeElement>a x: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier>, </TupleTypeElement><TupleTypeElement>_ y: <SimpleTypeIdentifier>Int </SimpleTypeIdentifier>... <InitializerClause>= <IntegerLiteralExpr>1</IntegerLiteralExpr></InitializerClause></TupleTypeElement>) throw -> <FunctionType>() -> <TupleType>()</TupleType></FunctionType></FunctionType></TypeInitializerClause></TypealiasDecl><TypealiasDecl>
+typealias H <TypeInitializerClause>= <FunctionType>() rethrows -> <TupleType>()</TupleType></FunctionType></TypeInitializerClause></TypealiasDecl><TypealiasDecl>
+typealias I <TypeInitializerClause>= <FunctionType>(<TupleTypeElement><CompositionType><CompositionTypeElement><SimpleTypeIdentifier>A </SimpleTypeIdentifier>& </CompositionTypeElement><CompositionTypeElement><SimpleTypeIdentifier>B<GenericArgumentClause><<GenericArgument><SimpleTypeIdentifier>C</SimpleTypeIdentifier></GenericArgument>></GenericArgumentClause></SimpleTypeIdentifier></CompositionTypeElement></CompositionType></TupleTypeElement>) -> <CompositionType><CompositionTypeElement><SimpleTypeIdentifier>C </SimpleTypeIdentifier>& </CompositionTypeElement><CompositionTypeElement><SimpleTypeIdentifier>D</SimpleTypeIdentifier></CompositionTypeElement></CompositionType></FunctionType></TypeInitializerClause></TypealiasDecl><TypealiasDecl>
+typealias J <TypeInitializerClause>= <AttributedType>inout <Attribute>@autoclosure </Attribute><FunctionType>() -> <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></FunctionType></AttributedType></TypeInitializerClause></TypealiasDecl><TypealiasDecl>
+typealias K <TypeInitializerClause>= <FunctionType>(<TupleTypeElement><Attribute>@invalidAttr </Attribute><SimpleTypeIdentifier>Int</SimpleTypeIdentifier>, </TupleTypeElement><TupleTypeElement><AttributedType>inout <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></AttributedType>, </TupleTypeElement><TupleTypeElement><AttributedType>__shared <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></AttributedType>, </TupleTypeElement><TupleTypeElement><AttributedType>__owned <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></AttributedType></TupleTypeElement>) -> <TupleType>()</TupleType></FunctionType></TypeInitializerClause></TypealiasDecl><TypealiasDecl><Attribute>
+
+@objc </Attribute><DeclModifier>private </DeclModifier>typealias T<GenericParameterClause><<GenericParameter>a,</GenericParameter><GenericParameter>b</GenericParameter>> </GenericParameterClause><TypeInitializerClause>= <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></TypeInitializerClause></TypealiasDecl><TypealiasDecl><Attribute>
+@objc </Attribute><DeclModifier>private </DeclModifier>typealias T<GenericParameterClause><<GenericParameter>a,</GenericParameter><GenericParameter>b</GenericParameter>></GenericParameterClause></TypealiasDecl><ClassDecl>
+
+class Foo <MemberDeclBlock>{<VariableDecl>
+  let <PatternBinding><IdentifierPattern>bar</IdentifierPattern><TypeAnnotation>: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></TypeAnnotation></PatternBinding></VariableDecl>
+}</MemberDeclBlock></ClassDecl><ClassDecl>
+
+class Bar<TypeInheritanceClause>: <InheritedType><SimpleTypeIdentifier>Foo </SimpleTypeIdentifier></InheritedType></TypeInheritanceClause><MemberDeclBlock>{<VariableDecl>
+  var <PatternBinding><IdentifierPattern>foo</IdentifierPattern><TypeAnnotation>: <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></TypeAnnotation><InitializerClause>= <IntegerLiteralExpr>42</IntegerLiteralExpr></InitializerClause></PatternBinding></VariableDecl>
+}</MemberDeclBlock></ClassDecl><ClassDecl>
+
+class C<GenericParameterClause><<GenericParameter>A, </GenericParameter><GenericParameter>B</GenericParameter>> </GenericParameterClause><GenericWhereClause>where <ConformanceRequirement><SimpleTypeIdentifier>A</SimpleTypeIdentifier>: <SimpleTypeIdentifier>Foo</SimpleTypeIdentifier>, </ConformanceRequirement><SameTypeRequirement><SimpleTypeIdentifier>B </SimpleTypeIdentifier>== <SimpleTypeIdentifier>Bar </SimpleTypeIdentifier></SameTypeRequirement></GenericWhereClause><MemberDeclBlock>{}</MemberDeclBlock></ClassDecl><ClassDecl><Attribute>
+
+@available(*, unavailable)</Attribute><DeclModifier>
+private </DeclModifier>class C <MemberDeclBlock>{}</MemberDeclBlock></ClassDecl><StructDecl>
 
 struct foo <MemberDeclBlock>{<StructDecl>
   struct foo <MemberDeclBlock>{<StructDecl>
     struct foo <MemberDeclBlock>{<FunctionDecl>
-      func foo<FunctionSignature>() </FunctionSignature><CodeBlock>{
+      func foo<FunctionSignature><ParameterClause>() </ParameterClause></FunctionSignature><CodeBlock>{
       }</CodeBlock></FunctionDecl>
     }</MemberDeclBlock></StructDecl>
   }</MemberDeclBlock></StructDecl><StructDecl>
@@ -78,38 +113,157 @@
 
 struct foo <MemberDeclBlock>{<StructDecl><Attribute>
   @available(*, unavailable)</Attribute>
-  struct foo <MemberDeclBlock>{}</MemberDeclBlock></StructDecl><DeclModifier>
-  public </DeclModifier>class foo {<FunctionDecl><Attribute>
+  struct foo <MemberDeclBlock>{}</MemberDeclBlock></StructDecl><ClassDecl><DeclModifier>
+  public </DeclModifier>class foo <MemberDeclBlock>{<FunctionDecl><Attribute>
     @available(*, unavailable)</Attribute><Attribute>
     @objc(fooObjc)</Attribute><DeclModifier>
-    private </DeclModifier><DeclModifier>static </DeclModifier>func foo<FunctionSignature>() </FunctionSignature><CodeBlock>{}</CodeBlock></FunctionDecl>
-  }
+    private </DeclModifier><DeclModifier>static </DeclModifier>func foo<FunctionSignature><ParameterClause>() </ParameterClause></FunctionSignature><CodeBlock>{}</CodeBlock></FunctionDecl>
+  }</MemberDeclBlock></ClassDecl>
 }</MemberDeclBlock></StructDecl><StructDecl>
 
 struct S<GenericParameterClause><<GenericParameter>A, </GenericParameter><GenericParameter>B, </GenericParameter><GenericParameter>C, </GenericParameter><GenericParameter><Attribute>@objc </Attribute>D</GenericParameter>> </GenericParameterClause><GenericWhereClause>where <ConformanceRequirement><SimpleTypeIdentifier>A</SimpleTypeIdentifier>:<SimpleTypeIdentifier>B</SimpleTypeIdentifier>, </ConformanceRequirement><SameTypeRequirement><SimpleTypeIdentifier>B</SimpleTypeIdentifier>==<SimpleTypeIdentifier>C</SimpleTypeIdentifier>, </SameTypeRequirement><ConformanceRequirement><SimpleTypeIdentifier>A </SimpleTypeIdentifier>: <SimpleTypeIdentifier>C</SimpleTypeIdentifier>, </ConformanceRequirement><SameTypeRequirement><MemberTypeIdentifier><SimpleTypeIdentifier>B</SimpleTypeIdentifier>.C </MemberTypeIdentifier>== <MemberTypeIdentifier><SimpleTypeIdentifier>D</SimpleTypeIdentifier>.A</MemberTypeIdentifier>, </SameTypeRequirement><ConformanceRequirement><MemberTypeIdentifier><SimpleTypeIdentifier>A</SimpleTypeIdentifier>.B</MemberTypeIdentifier>: <MemberTypeIdentifier><SimpleTypeIdentifier>C</SimpleTypeIdentifier>.D </MemberTypeIdentifier></ConformanceRequirement></GenericWhereClause><MemberDeclBlock>{}</MemberDeclBlock></StructDecl><StructDecl><DeclModifier>
 
 private </DeclModifier>struct S<GenericParameterClause><<GenericParameter>A, </GenericParameter><GenericParameter>B</GenericParameter>></GenericParameterClause><TypeInheritanceClause>: <InheritedType><SimpleTypeIdentifier>Base </SimpleTypeIdentifier></InheritedType></TypeInheritanceClause><GenericWhereClause>where <ConformanceRequirement><SimpleTypeIdentifier>A</SimpleTypeIdentifier>: <SimpleTypeIdentifier>B </SimpleTypeIdentifier></ConformanceRequirement></GenericWhereClause><MemberDeclBlock>{<StructDecl><DeclModifier>
   private </DeclModifier>struct S<TypeInheritanceClause>: <InheritedType><SimpleTypeIdentifier>A</SimpleTypeIdentifier>, </InheritedType><InheritedType><SimpleTypeIdentifier>B </SimpleTypeIdentifier></InheritedType></TypeInheritanceClause><MemberDeclBlock>{}</MemberDeclBlock></StructDecl>
-}</MemberDeclBlock></StructDecl>
+}</MemberDeclBlock></StructDecl><ProtocolDecl>
 
-protocol P<TypeInheritanceClause>: <InheritedType>class </InheritedType></TypeInheritanceClause>{}<FunctionDecl>
+protocol P<TypeInheritanceClause>: <InheritedType>class </InheritedType></TypeInheritanceClause><MemberDeclBlock>{}</MemberDeclBlock></ProtocolDecl><FunctionDecl>
 
-func foo<FunctionSignature>(<FunctionParameter>_ _: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier>,</FunctionParameter><FunctionParameter>
-         a b: <SimpleTypeIdentifier>Int </SimpleTypeIdentifier>= <SequenceExpr><IntegerLiteralExpr>3 </IntegerLiteralExpr><BinaryOperatorExpr>+ </BinaryOperatorExpr><IntegerLiteralExpr>2</IntegerLiteralExpr></SequenceExpr>,</FunctionParameter><FunctionParameter>
-         _ c: <SimpleTypeIdentifier>Int </SimpleTypeIdentifier>= <IntegerLiteralExpr>2</IntegerLiteralExpr>,</FunctionParameter><FunctionParameter>
-         d _: <SimpleTypeIdentifier>Int </SimpleTypeIdentifier>= <SequenceExpr><TernaryExpr><BooleanLiteralExpr>true </BooleanLiteralExpr>? <IntegerLiteralExpr>2</IntegerLiteralExpr>: <IntegerLiteralExpr>3</IntegerLiteralExpr></TernaryExpr></SequenceExpr>,</FunctionParameter><FunctionParameter><Attribute>
-         @objc </Attribute>e: <SimpleTypeIdentifier>X </SimpleTypeIdentifier>= <BooleanLiteralExpr>true</BooleanLiteralExpr>,</FunctionParameter><FunctionParameter>
-         f: inout <SimpleTypeIdentifier>Int</SimpleTypeIdentifier>,</FunctionParameter><FunctionParameter>
-         g: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier>...</FunctionParameter>) throws -> <DictionaryType>[<SimpleTypeIdentifier>Int</SimpleTypeIdentifier>: <SimpleTypeIdentifier>String</SimpleTypeIdentifier>] </DictionaryType></FunctionSignature><CodeBlock>{}</CodeBlock></FunctionDecl><FunctionDecl>
+func foo<FunctionSignature><ParameterClause>(<FunctionParameter>_ _: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier>,</FunctionParameter><FunctionParameter>
+         a b: <SimpleTypeIdentifier>Int </SimpleTypeIdentifier><InitializerClause>= <SequenceExpr><IntegerLiteralExpr>3 </IntegerLiteralExpr><BinaryOperatorExpr>+ </BinaryOperatorExpr><IntegerLiteralExpr>2</IntegerLiteralExpr></SequenceExpr></InitializerClause>,</FunctionParameter><FunctionParameter>
+         _ c: <SimpleTypeIdentifier>Int </SimpleTypeIdentifier><InitializerClause>= <IntegerLiteralExpr>2</IntegerLiteralExpr></InitializerClause>,</FunctionParameter><FunctionParameter>
+         d _: <SimpleTypeIdentifier>Int </SimpleTypeIdentifier><InitializerClause>= <SequenceExpr><TernaryExpr><BooleanLiteralExpr>true </BooleanLiteralExpr>? <IntegerLiteralExpr>2</IntegerLiteralExpr>: <IntegerLiteralExpr>3</IntegerLiteralExpr></TernaryExpr></SequenceExpr></InitializerClause>,</FunctionParameter><FunctionParameter><Attribute>
+         @objc </Attribute>e: <SimpleTypeIdentifier>X </SimpleTypeIdentifier><InitializerClause>= <BooleanLiteralExpr>true</BooleanLiteralExpr></InitializerClause>,</FunctionParameter><FunctionParameter>
+         f: <AttributedType>inout <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></AttributedType>,</FunctionParameter><FunctionParameter>
+         g: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier>...</FunctionParameter>) </ParameterClause>throws <ReturnClause>-> <DictionaryType>[<SimpleTypeIdentifier>Int</SimpleTypeIdentifier>: <SimpleTypeIdentifier>String</SimpleTypeIdentifier>] </DictionaryType></ReturnClause></FunctionSignature><CodeBlock>{}</CodeBlock></FunctionDecl><FunctionDecl>
 
-func foo<FunctionSignature>(<FunctionParameter>_ a: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></FunctionParameter>) throws -> <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></FunctionSignature><CodeBlock>{}</CodeBlock></FunctionDecl><FunctionDecl>
-func foo<FunctionSignature>( <FunctionParameter>a: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></FunctionParameter>) rethrows -> <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></FunctionSignature><CodeBlock>{}</CodeBlock></FunctionDecl><StructDecl>
+func foo<FunctionSignature><ParameterClause>(<FunctionParameter>_ a: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></FunctionParameter>) </ParameterClause>throws <ReturnClause>-> <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></ReturnClause></FunctionSignature><CodeBlock>{}</CodeBlock></FunctionDecl><FunctionDecl>
+func foo<FunctionSignature><ParameterClause>( <FunctionParameter>a: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></FunctionParameter>) </ParameterClause>rethrows <ReturnClause>-> <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></ReturnClause></FunctionSignature><CodeBlock>{}</CodeBlock></FunctionDecl><StructDecl>
 
 struct C <MemberDeclBlock>{<FunctionDecl><Attribute>
 @objc</Attribute><Attribute>
 @available(*, unavailable)</Attribute><DeclModifier>
-private </DeclModifier><DeclModifier>static </DeclModifier><DeclModifier>override </DeclModifier>func foo<GenericParameterClause><<GenericParameter>a, </GenericParameter><GenericParameter>b, </GenericParameter><GenericParameter>c</GenericParameter>></GenericParameterClause><FunctionSignature>(<FunctionParameter>a b: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier>, </FunctionParameter><FunctionParameter>c: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></FunctionParameter>) throws -> <ArrayType>[<SimpleTypeIdentifier>Int</SimpleTypeIdentifier>] </ArrayType></FunctionSignature><GenericWhereClause>where <SameTypeRequirement><SimpleTypeIdentifier>a</SimpleTypeIdentifier>==<SimpleTypeIdentifier>p1</SimpleTypeIdentifier>, </SameTypeRequirement><ConformanceRequirement><SimpleTypeIdentifier>b</SimpleTypeIdentifier>:<SimpleTypeIdentifier>p2 </SimpleTypeIdentifier></ConformanceRequirement></GenericWhereClause><CodeBlock>{ <IdentifierExpr>ddd </IdentifierExpr>}</CodeBlock></FunctionDecl><FunctionDecl>
-func rootView<FunctionSignature>() -> <SimpleTypeIdentifier>Label </SimpleTypeIdentifier></FunctionSignature><CodeBlock>{}</CodeBlock></FunctionDecl><FunctionDecl><DeclModifier>
-static </DeclModifier>func ==<FunctionSignature>() -> <SimpleTypeIdentifier>bool </SimpleTypeIdentifier></FunctionSignature><CodeBlock>{}</CodeBlock></FunctionDecl><FunctionDecl><DeclModifier>
-static </DeclModifier>func !=<GenericParameterClause><<GenericParameter>a, </GenericParameter><GenericParameter>b, </GenericParameter><GenericParameter>c</GenericParameter>></GenericParameterClause><FunctionSignature>() -> <SimpleTypeIdentifier>bool </SimpleTypeIdentifier></FunctionSignature><CodeBlock>{}</CodeBlock></FunctionDecl>
-}</MemberDeclBlock></StructDecl>
\ No newline at end of file
+private </DeclModifier><DeclModifier>static </DeclModifier><DeclModifier>override </DeclModifier>func foo<GenericParameterClause><<GenericParameter>a, </GenericParameter><GenericParameter>b, </GenericParameter><GenericParameter>c</GenericParameter>></GenericParameterClause><FunctionSignature><ParameterClause>(<FunctionParameter>a b: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier>, </FunctionParameter><FunctionParameter>c: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></FunctionParameter>) </ParameterClause>throws <ReturnClause>-> <ArrayType>[<SimpleTypeIdentifier>Int</SimpleTypeIdentifier>] </ArrayType></ReturnClause></FunctionSignature><GenericWhereClause>where <SameTypeRequirement><SimpleTypeIdentifier>a</SimpleTypeIdentifier>==<SimpleTypeIdentifier>p1</SimpleTypeIdentifier>, </SameTypeRequirement><ConformanceRequirement><SimpleTypeIdentifier>b</SimpleTypeIdentifier>:<SimpleTypeIdentifier>p2 </SimpleTypeIdentifier></ConformanceRequirement></GenericWhereClause><CodeBlock>{ <IdentifierExpr>ddd </IdentifierExpr>}</CodeBlock></FunctionDecl><FunctionDecl>
+func rootView<FunctionSignature><ParameterClause>() </ParameterClause><ReturnClause>-> <SimpleTypeIdentifier>Label </SimpleTypeIdentifier></ReturnClause></FunctionSignature><CodeBlock>{}</CodeBlock></FunctionDecl><FunctionDecl><DeclModifier>
+static </DeclModifier>func ==<FunctionSignature><ParameterClause>() </ParameterClause><ReturnClause>-> <SimpleTypeIdentifier>bool </SimpleTypeIdentifier></ReturnClause></FunctionSignature><CodeBlock>{}</CodeBlock></FunctionDecl><FunctionDecl><DeclModifier>
+static </DeclModifier>func !=<GenericParameterClause><<GenericParameter>a, </GenericParameter><GenericParameter>b, </GenericParameter><GenericParameter>c</GenericParameter>></GenericParameterClause><FunctionSignature><ParameterClause>() </ParameterClause><ReturnClause>-> <SimpleTypeIdentifier>bool </SimpleTypeIdentifier></ReturnClause></FunctionSignature><CodeBlock>{}</CodeBlock></FunctionDecl>
+}</MemberDeclBlock></StructDecl><ProtocolDecl><Attribute>
+
+@objc</Attribute><DeclModifier>
+private </DeclModifier>protocol foo <TypeInheritanceClause>: <InheritedType><SimpleTypeIdentifier>bar </SimpleTypeIdentifier></InheritedType></TypeInheritanceClause><GenericWhereClause>where <SameTypeRequirement><SimpleTypeIdentifier>A</SimpleTypeIdentifier>==<SimpleTypeIdentifier>B </SimpleTypeIdentifier></SameTypeRequirement></GenericWhereClause><MemberDeclBlock>{}</MemberDeclBlock></ProtocolDecl><ProtocolDecl>
+protocol foo <MemberDeclBlock>{ <FunctionDecl>func foo<FunctionSignature><ParameterClause>() </ParameterClause></FunctionSignature></FunctionDecl>}</MemberDeclBlock></ProtocolDecl><ProtocolDecl><DeclModifier>
+private </DeclModifier>protocol foo<MemberDeclBlock>{}</MemberDeclBlock></ProtocolDecl><ProtocolDecl><Attribute>
+@objc</Attribute><DeclModifier>
+public </DeclModifier>protocol foo <GenericWhereClause>where <ConformanceRequirement><SimpleTypeIdentifier>A</SimpleTypeIdentifier>:<SimpleTypeIdentifier>B </SimpleTypeIdentifier></ConformanceRequirement></GenericWhereClause><MemberDeclBlock>{}</MemberDeclBlock></ProtocolDecl><IfConfigDecl>
+
+#if <IdentifierExpr>blah</IdentifierExpr><FunctionDecl>
+func tryfoo<FunctionSignature><ParameterClause>() </ParameterClause></FunctionSignature><CodeBlock>{<TryExpr>
+  try <IdentifierExpr>foo</IdentifierExpr>()</TryExpr><TryExpr>
+  try! <IdentifierExpr>foo</IdentifierExpr>()</TryExpr><TryExpr>
+  try? <IdentifierExpr>foo</IdentifierExpr>()</TryExpr><TryExpr>
+  try! <MemberAccessExpr><IdentifierExpr>foo</IdentifierExpr>().bar</MemberAccessExpr>().foo().bar()</TryExpr>
+}</CodeBlock></FunctionDecl><ElseDirectiveClause>
+#else<FunctionDecl>
+func closure<FunctionSignature><ParameterClause>() </ParameterClause></FunctionSignature><CodeBlock>{<ClosureExpr>
+  {<ClosureSignature><ClosureCaptureSignature>[<ClosureCaptureItem>weak <IdentifierExpr>a</IdentifierExpr>,</ClosureCaptureItem><ClosureCaptureItem>
+    unowned(safe) self,</ClosureCaptureItem><ClosureCaptureItem>
+    b = <IntegerLiteralExpr>3</IntegerLiteralExpr>,</ClosureCaptureItem><ClosureCaptureItem>
+    unowned(unsafe) c = <MemberAccessExpr><IdentifierExpr>foo</IdentifierExpr>().bar</MemberAccessExpr></ClosureCaptureItem>] </ClosureCaptureSignature>in</ClosureSignature>
+  }</ClosureExpr><ClosureExpr>
+  {<ClosureSignature><ClosureCaptureSignature>[] </ClosureCaptureSignature>in </ClosureSignature>}</ClosureExpr><ClosureExpr>
+
+  { <ClosureSignature><ClosureCaptureSignature>[] </ClosureCaptureSignature><ClosureParam>a, </ClosureParam><ClosureParam>b, </ClosureParam><ClosureParam>_ </ClosureParam><ReturnClause>-> <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></ReturnClause>in</ClosureSignature><ReturnStmt>
+    return <IntegerLiteralExpr>2</IntegerLiteralExpr></ReturnStmt>
+  }</ClosureExpr><ClosureExpr>
+  { <ClosureSignature><ClosureCaptureSignature>[] </ClosureCaptureSignature><ParameterClause>(<FunctionParameter>a: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier>, </FunctionParameter><FunctionParameter>b: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier>, </FunctionParameter><FunctionParameter>_: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></FunctionParameter>) </ParameterClause><ReturnClause>-> <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></ReturnClause>in</ClosureSignature><ReturnStmt>
+    return <IntegerLiteralExpr>2</IntegerLiteralExpr></ReturnStmt>
+  }</ClosureExpr><ClosureExpr>
+  { <ClosureSignature><ClosureCaptureSignature>[] </ClosureCaptureSignature><ClosureParam>a, </ClosureParam><ClosureParam>b, </ClosureParam><ClosureParam>_ </ClosureParam>throws <ReturnClause>-> <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></ReturnClause>in</ClosureSignature><ReturnStmt>
+    return <IntegerLiteralExpr>2</IntegerLiteralExpr></ReturnStmt>
+  }</ClosureExpr><ClosureExpr>
+  { <ClosureSignature><ClosureCaptureSignature>[] </ClosureCaptureSignature><ParameterClause>(<FunctionParameter>a: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier>, </FunctionParameter><FunctionParameter>_ b: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></FunctionParameter>) </ParameterClause>throws <ReturnClause>-> <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></ReturnClause>in</ClosureSignature><ReturnStmt>
+    return <IntegerLiteralExpr>2</IntegerLiteralExpr></ReturnStmt>
+  }</ClosureExpr><ClosureExpr>
+  { <ClosureSignature><ClosureParam>a, </ClosureParam><ClosureParam>b </ClosureParam>in </ClosureSignature>}</ClosureExpr><ClosureExpr>
+  {}</ClosureExpr><ClosureExpr>
+  { <ClosureSignature><ClosureParam>s1, </ClosureParam><ClosureParam>s2 </ClosureParam>in </ClosureSignature><SequenceExpr><IdentifierExpr>s1 </IdentifierExpr><BinaryOperatorExpr>> </BinaryOperatorExpr><IdentifierExpr>s2 </IdentifierExpr></SequenceExpr>}</ClosureExpr><ClosureExpr>
+  { <SequenceExpr>$0 <BinaryOperatorExpr>> </BinaryOperatorExpr>$1 </SequenceExpr>}</ClosureExpr>
+}</CodeBlock></FunctionDecl></ElseDirectiveClause>
+#endif</IfConfigDecl><IfConfigDecl>
+
+#if <IdentifierExpr>blah</IdentifierExpr><ElseDirectiveClause>
+#else</ElseDirectiveClause>
+#endif</IfConfigDecl><ClassDecl>
+
+class C <MemberDeclBlock>{<VariableDecl>
+  var <PatternBinding><IdentifierPattern>a</IdentifierPattern><TypeAnnotation>: <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></TypeAnnotation><AccessorBlock>{<AccessorDecl><Attribute>
+    @objc </Attribute><DeclModifier>mutating </DeclModifier>set<AccessorParameter>(value) </AccessorParameter><CodeBlock>{}</CodeBlock></AccessorDecl><AccessorDecl><DeclModifier>
+    mutating </DeclModifier>get <CodeBlock>{ <ReturnStmt>return <IntegerLiteralExpr>3 </IntegerLiteralExpr></ReturnStmt>}</CodeBlock></AccessorDecl><AccessorDecl><Attribute>
+    @objc </Attribute>didSet <CodeBlock>{}</CodeBlock></AccessorDecl><AccessorDecl>
+    willSet<AccessorParameter>(newValue)</AccessorParameter><CodeBlock>{ }</CodeBlock></AccessorDecl>
+  }</AccessorBlock></PatternBinding></VariableDecl><VariableDecl>
+  var <PatternBinding><IdentifierPattern>a </IdentifierPattern><TypeAnnotation>: <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></TypeAnnotation><AccessorBlock>{<ReturnStmt>
+    return <IntegerLiteralExpr>3</IntegerLiteralExpr></ReturnStmt>
+  }</AccessorBlock></PatternBinding></VariableDecl>
+}</MemberDeclBlock></ClassDecl><ProtocolDecl>
+
+protocol P <MemberDeclBlock>{<VariableDecl>
+  var <PatternBinding><IdentifierPattern>a</IdentifierPattern><TypeAnnotation>: <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></TypeAnnotation><AccessorBlock>{ <AccessorDecl>get </AccessorDecl><AccessorDecl>set </AccessorDecl>}</AccessorBlock></PatternBinding></VariableDecl><VariableDecl>
+  var <PatternBinding><IdentifierPattern>a</IdentifierPattern><TypeAnnotation>: <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></TypeAnnotation><AccessorBlock>{}</AccessorBlock></PatternBinding></VariableDecl>
+}</MemberDeclBlock></ProtocolDecl><ClassDecl>
+
+class C <MemberDeclBlock>{<VariableDecl><Attribute>
+  @objc</Attribute><DeclModifier>
+  static </DeclModifier><DeclModifier>private </DeclModifier>var <PatternBinding><IdentifierPattern>a</IdentifierPattern><TypeAnnotation>: <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></TypeAnnotation><InitializerClause>= <IntegerLiteralExpr>3 </IntegerLiteralExpr></InitializerClause><AccessorBlock>{ <ReturnStmt>return <IntegerLiteralExpr>3 </IntegerLiteralExpr></ReturnStmt>}</AccessorBlock>, </PatternBinding><PatternBinding><IdentifierPattern>b</IdentifierPattern><TypeAnnotation>: <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></TypeAnnotation>, </PatternBinding><PatternBinding><IdentifierPattern>c </IdentifierPattern><InitializerClause>= <IntegerLiteralExpr>4</IntegerLiteralExpr></InitializerClause>, </PatternBinding><PatternBinding><IdentifierPattern>d </IdentifierPattern><TypeAnnotation>: <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></TypeAnnotation><AccessorBlock>{ <AccessorDecl>get <CodeBlock>{} </CodeBlock></AccessorDecl><AccessorDecl>get <CodeBlock>{}</CodeBlock></AccessorDecl>}</AccessorBlock>, </PatternBinding><PatternBinding><TuplePattern>(<TuplePatternElement><IdentifierPattern>a</IdentifierPattern>, </TuplePatternElement><TuplePatternElement><IdentifierPattern>b</IdentifierPattern></TuplePatternElement>)</TuplePattern><TypeAnnotation>: <TupleType>(<TupleTypeElement><SimpleTypeIdentifier>Int</SimpleTypeIdentifier>, </TupleTypeElement><TupleTypeElement><SimpleTypeIdentifier>Int</SimpleTypeIdentifier></TupleTypeElement>)</TupleType></TypeAnnotation></PatternBinding></VariableDecl><VariableDecl>
+  let <PatternBinding><TuplePattern>(<TuplePatternElement><IdentifierPattern>a</IdentifierPattern>, </TuplePatternElement><TuplePatternElement><IdentifierPattern>b</IdentifierPattern></TuplePatternElement>) </TuplePattern><InitializerClause>= <TupleExpr>(<TupleElement><IntegerLiteralExpr>1</IntegerLiteralExpr>,</TupleElement><TupleElement><IntegerLiteralExpr>2</IntegerLiteralExpr></TupleElement>)</TupleExpr></InitializerClause>, </PatternBinding><PatternBinding><WildcardPattern>_ </WildcardPattern><InitializerClause>= <IntegerLiteralExpr>4 </IntegerLiteralExpr></InitializerClause><AccessorBlock>{}</AccessorBlock></PatternBinding></VariableDecl><FunctionDecl>
+
+  func patternTests<FunctionSignature><ParameterClause>() </ParameterClause></FunctionSignature><CodeBlock>{
+    for <ValueBindingPattern>let <TuplePattern>(<TuplePatternElement><IdentifierPattern>x</IdentifierPattern>, </TuplePatternElement><TuplePatternElement><WildcardPattern>_</WildcardPattern></TuplePatternElement>) </TuplePattern></ValueBindingPattern>in <IdentifierExpr>foo </IdentifierExpr><CodeBlock>{}</CodeBlock>
+    for <ValueBindingPattern>var <IdentifierPattern>x</IdentifierPattern></ValueBindingPattern><TypeAnnotation>: <SimpleTypeIdentifier>Int </SimpleTypeIdentifier></TypeAnnotation>in <IdentifierExpr>foo </IdentifierExpr><CodeBlock>{}</CodeBlock>
+  }</CodeBlock></FunctionDecl>
+}</MemberDeclBlock></ClassDecl><DoStmt>
+
+do <CodeBlock>{
+  switch <IdentifierExpr>foo </IdentifierExpr>{
+    case <ValueBindingPattern>let <IdentifierPattern>a</IdentifierPattern></ValueBindingPattern>: <BreakStmt>break</BreakStmt>
+    case <ValueBindingPattern>let <ExpressionPattern><SequenceExpr><UnresolvedPatternExpr><IdentifierPattern>a </IdentifierPattern></UnresolvedPatternExpr><AsExpr>as <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></AsExpr></SequenceExpr></ExpressionPattern></ValueBindingPattern>: <BreakStmt>break</BreakStmt>
+    case <ValueBindingPattern>let <ExpressionPattern><TupleExpr>(<TupleElement><UnresolvedPatternExpr><IdentifierPattern>a</IdentifierPattern></UnresolvedPatternExpr>, </TupleElement><TupleElement><UnresolvedPatternExpr><IdentifierPattern>b</IdentifierPattern></UnresolvedPatternExpr></TupleElement>)</TupleExpr></ExpressionPattern></ValueBindingPattern>: <BreakStmt>break</BreakStmt>
+    case <ExpressionPattern><TupleExpr>(<TupleElement><UnresolvedPatternExpr><ValueBindingPattern>let <IdentifierPattern>a</IdentifierPattern></ValueBindingPattern></UnresolvedPatternExpr>, </TupleElement><TupleElement><UnresolvedPatternExpr><ValueBindingPattern>var <IdentifierPattern>b</IdentifierPattern></ValueBindingPattern></UnresolvedPatternExpr></TupleElement>)</TupleExpr></ExpressionPattern>: <BreakStmt>break</BreakStmt>
+    case <IsTypePattern>is <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></IsTypePattern>: <BreakStmt>break</BreakStmt>
+    case <ValueBindingPattern>let <ExpressionPattern>.bar(<FunctionCallArgument><UnresolvedPatternExpr><IdentifierPattern>x</IdentifierPattern></UnresolvedPatternExpr></FunctionCallArgument>)</ExpressionPattern></ValueBindingPattern>: <BreakStmt>break</BreakStmt>
+    case <ExpressionPattern><MemberAccessExpr><IdentifierExpr>MyEnum</IdentifierExpr>.foo</MemberAccessExpr></ExpressionPattern>: <BreakStmt>break</BreakStmt>
+    case <ValueBindingPattern>let <ExpressionPattern><SequenceExpr><UnresolvedPatternExpr><IdentifierPattern>a </IdentifierPattern></UnresolvedPatternExpr><AsExpr>as <SimpleTypeIdentifier>Int</SimpleTypeIdentifier></AsExpr></SequenceExpr></ExpressionPattern></ValueBindingPattern>: <BreakStmt>break</BreakStmt>
+    case <ValueBindingPattern>let <ExpressionPattern><UnresolvedPatternExpr><IdentifierPattern>a</IdentifierPattern></UnresolvedPatternExpr>?</ExpressionPattern></ValueBindingPattern>: <BreakStmt>break</BreakStmt>
+  }
+}</CodeBlock></DoStmt><FunctionDecl>
+
+func statementTests<FunctionSignature><ParameterClause>() </ParameterClause></FunctionSignature><CodeBlock>{<DoStmt>
+  do <CodeBlock>{
+  } </CodeBlock><CatchClause>catch <ExpressionPattern><TupleExpr>(<TupleElement><UnresolvedPatternExpr><ValueBindingPattern>var <IdentifierPattern>x</IdentifierPattern></ValueBindingPattern></UnresolvedPatternExpr>, </TupleElement><TupleElement><UnresolvedPatternExpr><ValueBindingPattern>let <IdentifierPattern>y</IdentifierPattern></ValueBindingPattern></UnresolvedPatternExpr></TupleElement>) </TupleExpr></ExpressionPattern><CodeBlock>{
+  } </CodeBlock></CatchClause><CatchClause>catch <WhereClause>where <BooleanLiteralExpr>false </BooleanLiteralExpr></WhereClause><CodeBlock>{
+  } </CodeBlock></CatchClause><CatchClause>catch <ValueBindingPattern>let <IdentifierPattern>e </IdentifierPattern></ValueBindingPattern><WhereClause>where <SequenceExpr><MemberAccessExpr><IdentifierExpr>e</IdentifierExpr>.foo </MemberAccessExpr><BinaryOperatorExpr>== </BinaryOperatorExpr><IdentifierExpr>bar </IdentifierExpr></SequenceExpr></WhereClause><CodeBlock>{
+  } </CodeBlock></CatchClause><CatchClause>catch <CodeBlock>{
+  }</CodeBlock></CatchClause></DoStmt><RepeatWhileStmt>
+  repeat <CodeBlock>{ } </CodeBlock>while <BooleanLiteralExpr>true</BooleanLiteralExpr></RepeatWhileStmt><RepeatWhileStmt>
+  LABEL: repeat <CodeBlock>{ } </CodeBlock>while <BooleanLiteralExpr>false</BooleanLiteralExpr></RepeatWhileStmt><DoStmt>
+  LABEL: do <CodeBlock>{}</CodeBlock></DoStmt>
+  LABEL: switch <IdentifierExpr>foo </IdentifierExpr>{
+    case <ExpressionPattern><IntegerLiteralExpr>1</IntegerLiteralExpr></ExpressionPattern>:<FallthroughStmt>
+      fallthrough</FallthroughStmt>
+    case <ExpressionPattern><IntegerLiteralExpr>2</IntegerLiteralExpr></ExpressionPattern>:<BreakStmt>
+      break LABEL</BreakStmt>
+    case <ExpressionPattern><IntegerLiteralExpr>3</IntegerLiteralExpr></ExpressionPattern>:<BreakStmt>
+      break</BreakStmt>
+  }
+
+  for <IdentifierPattern>a </IdentifierPattern>in <IdentifierExpr>b </IdentifierExpr><CodeBlock>{<DeferStmt>
+    defer <CodeBlock>{ <TupleExpr>() </TupleExpr>}</CodeBlock></DeferStmt>
+    if <IdentifierExpr>c </IdentifierExpr><CodeBlock>{<ThrowStmt>
+      throw <IdentifierExpr>MyError</IdentifierExpr>()</ThrowStmt><ContinueStmt>
+      continue</ContinueStmt>
+    } </CodeBlock>else <CodeBlock>{<ContinueStmt>
+      continue LABEL</ContinueStmt>
+    }</CodeBlock>
+  }</CodeBlock>
+
+}</CodeBlock></FunctionDecl>
diff --git a/test/Syntax/round_trip_parse_gen.swift b/test/Syntax/round_trip_parse_gen.swift
index 0decabe..19f8baf 100644
--- a/test/Syntax/round_trip_parse_gen.swift
+++ b/test/Syntax/round_trip_parse_gen.swift
@@ -3,6 +3,13 @@
 // RUN: %swift-syntax-test -input-source-filename %s -parse-gen -print-node-kind > %t.withkinds
 // RUN: diff -u %S/Outputs/round_trip_parse_gen.swift.withkinds %t.withkinds
 
+import ABC
+import A.B.C
+@objc import A.B
+@objc import typealias A.B
+import struct A.B
+
+#if Blah
 class C {
   func bar(_ a: Int) {}
   func bar1(_ a: Float) -> Float { return -0.6 + 0.1 - 0.3 }
@@ -27,6 +34,7 @@
     _ = bar2(a : bar2(a: 1, b: 2, c: 3), b: 2, c: 3)
     _ = bar3(a : bar3(a: bar3(a: 1)))
     _ = bar4(bar4(bar4(1)))
+    _ = [:]
     _ = [1, 2, 3, 4]
     _ = [1:1, 2:2, 3:3, 4:4]
     _ = [bar3(a:1), bar3(a:1), bar3(a:1), bar3(a:1)]
@@ -59,12 +67,39 @@
   }
 }
 
+#endif
+
+#if blah
 typealias A = Any
-typealias B = (Array<Array<Any>>.Element)
+#elseif blahblah
+typealias B = (Array<Array<Any>>.Element, x: Int)
+#else
 typealias C = [Int]
+#endif
 typealias D = [Int: String]
 typealias E = Int?.Protocol
 typealias F = [Int]!.Type
+typealias G = (a x: Int, _ y: Int ... = 1) throw -> () -> ()
+typealias H = () rethrows -> ()
+typealias I = (A & B<C>) -> C & D
+typealias J = inout @autoclosure () -> Int
+typealias K = (@invalidAttr Int, inout Int, __shared Int, __owned Int) -> ()
+
+@objc private typealias T<a,b> = Int
+@objc private typealias T<a,b>
+
+class Foo {
+  let bar: Int
+}
+
+class Bar: Foo {
+  var foo: Int = 42
+}
+
+class C<A, B> where A: Foo, B == Bar {}
+
+@available(*, unavailable)
+private class C {}
 
 struct foo {
   struct foo {
@@ -112,4 +147,123 @@
 func rootView() -> Label {}
 static func ==() -> bool {}
 static func !=<a, b, c>() -> bool {}
-}
\ No newline at end of file
+}
+
+@objc
+private protocol foo : bar where A==B {}
+protocol foo { func foo() }
+private protocol foo{}
+@objc
+public protocol foo where A:B {}
+
+#if blah
+func tryfoo() {
+  try foo()
+  try! foo()
+  try? foo()
+  try! foo().bar().foo().bar()
+}
+#else
+func closure() {
+  {[weak a,
+    unowned(safe) self,
+    b = 3,
+    unowned(unsafe) c = foo().bar] in
+  }
+  {[] in }
+
+  { [] a, b, _ -> Int in
+    return 2
+  }
+  { [] (a: Int, b: Int, _: Int) -> Int in
+    return 2
+  }
+  { [] a, b, _ throws -> Int in
+    return 2
+  }
+  { [] (a: Int, _ b: Int) throws -> Int in
+    return 2
+  }
+  { a, b in }
+  {}
+  { s1, s2 in s1 > s2 }
+  { $0 > $1 }
+}
+#endif
+
+#if blah
+#else
+#endif
+
+class C {
+  var a: Int {
+    @objc mutating set(value) {}
+    mutating get { return 3 }
+    @objc didSet {}
+    willSet(newValue){ }
+  }
+  var a : Int {
+    return 3
+  }
+}
+
+protocol P {
+  var a: Int { get set }
+  var a: Int {}
+}
+
+class C {
+  @objc
+  static private var a: Int = 3 { return 3 }, b: Int, c = 4, d : Int { get {} get {}}, (a, b): (Int, Int)
+  let (a, b) = (1,2), _ = 4 {}
+
+  func patternTests() {
+    for let (x, _) in foo {}
+    for var x: Int in foo {}
+  }
+}
+
+do {
+  switch foo {
+    case let a: break
+    case let a as Int: break
+    case let (a, b): break
+    case (let a, var b): break
+    case is Int: break
+    case let .bar(x): break
+    case MyEnum.foo: break
+    case let a as Int: break
+    case let a?: break
+  }
+}
+
+func statementTests() {
+  do {
+  } catch (var x, let y) {
+  } catch where false {
+  } catch let e where e.foo == bar {
+  } catch {
+  }
+  repeat { } while true
+  LABEL: repeat { } while false
+  LABEL: do {}
+  LABEL: switch foo {
+    case 1:
+      fallthrough
+    case 2:
+      break LABEL
+    case 3:
+      break
+  }
+
+  for a in b {
+    defer { () }
+    if c {
+      throw MyError()
+      continue
+    } else {
+      continue LABEL
+    }
+  }
+
+}
diff --git a/test/TBD/class.swift b/test/TBD/class.swift
index d81f4bd..43b9007 100644
--- a/test/TBD/class.swift
+++ b/test/TBD/class.swift
@@ -1,4 +1,5 @@
 // RUN: %target-swift-frontend -emit-ir -o- -parse-as-library -module-name test -validate-tbd-against-ir=missing %s
+// RUN: %target-swift-frontend -enable-resilience -emit-ir -o- -parse-as-library -module-name test -validate-tbd-against-ir=missing %s
 
 open class OpenNothing {}
 
diff --git a/test/TBD/class_objc.swift b/test/TBD/class_objc.swift
index b01358b..1aa3ab2 100644
--- a/test/TBD/class_objc.swift
+++ b/test/TBD/class_objc.swift
@@ -1,4 +1,5 @@
 // RUN: %target-swift-frontend -emit-ir -o- -parse-as-library -module-name test -import-objc-header %S/Inputs/objc_class_header.h -validate-tbd-against-ir=all %s
+// RUN: %target-swift-frontend -enable-resilience -emit-ir -o- -parse-as-library -module-name test -import-objc-header %S/Inputs/objc_class_header.h -validate-tbd-against-ir=all %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/api-digester/Outputs/macro-gen.def b/test/api-digester/Outputs/macro-gen.def
index 7811115..7f20e7a 100644
--- a/test/api-digester/Outputs/macro-gen.def
+++ b/test/api-digester/Outputs/macro-gen.def
@@ -2,21 +2,21 @@
 #ifndef SDK_CHANGE
 #define SDK_CHANGE(NODE_KIND, DIFF_KIND, CHILD_INDEX, LEFT_USR, RIGHT_USR, LEFT_COMMENT, RIGHT_COMMENT, MODULENAME)
 #endif
-SDK_CHANGE(Function, TypeRewritten, "0", "s:12macrogenleft2C1C4foo2SSSi_SitF", "", "String", "Int", "macrogenleft")
-SDK_CHANGE(Function, TypeRewritten, "1", "s:12macrogenleft2C1C4foo2SSSi_SitF", "", "Int", "() -> ()", "macrogenleft")
-SDK_CHANGE(Function, TypeRewritten, "2", "s:12macrogenleft2C1C4foo2SSSi_SitF", "", "Int", "String", "macrogenleft")
-SDK_CHANGE(Function, Rename, "0", "s:12macrogenleft2S1V4foo5ySi1x_Si1ytF", "", "foo5(x:y:)", "foo5(x:y:z:)", "macrogenleft")
-SDK_CHANGE(Function, WrapOptional, "0", "s:12macrogenleft2S1V4foo6S2i1x_Si1ytF", "", "", "", "macrogenleft")
-SDK_CHANGE(Function, WrapOptional, "2", "s:12macrogenleft2S1V4foo6S2i1x_Si1ytF", "", "", "", "macrogenleft")
-SDK_CHANGE(Function, UnwrapOptional, "0", "s:12macrogenleft2S1V4foo7SiSgSi1x_AE1ytF", "", "", "", "macrogenleft")
-SDK_CHANGE(Function, UnwrapOptional, "2", "s:12macrogenleft2S1V4foo7SiSgSi1x_AE1ytF", "", "", "", "macrogenleft")
-SDK_CHANGE(Function, ImplicitOptionalToOptional, "0", "s:12macrogenleft2S1V4foo8SQySiGSi1x_AE1ytF", "", "", "", "macrogenleft")
-SDK_CHANGE(Function, ImplicitOptionalToOptional, "2", "s:12macrogenleft2S1V4foo8SQySiGSi1x_AE1ytF", "", "", "", "macrogenleft")
-SDK_CHANGE(Function, WrapOptional, "2:0", "s:12macrogenleft2S1V4foo9ySays10DictionaryVySiSSSgGG1x_SaySiG1ytF", "", "", "", "macrogenleft")
-SDK_CHANGE(Function, UnwrapOptional, "1:0:1", "s:12macrogenleft2S1V4foo9ySays10DictionaryVySiSSSgGG1x_SaySiG1ytF", "", "", "", "macrogenleft")
-SDK_CHANGE(Function, WrapOptional, "1:1:1:1:1:0", "s:12macrogenleft2S1V5foo10ySSSi_s10DictionaryVySiAFySSSaySiGGGtc1x_tF", "", "", "", "macrogenleft")
-SDK_CHANGE(Function, TypeRewritten, "1:1:1:1", "s:12macrogenleft2S1V5foo11ySSSi_s10DictionaryVySiAFySSSaySiGGGtc1x_tF", "", "[String : [Int]]", "Int", "macrogenleft")
-SDK_CHANGE(Function, TypeRewritten, "1:1:1:1:1:0:0:0:0", "s:12macrogenleft2S1V5foo12ySSSi_s10DictionaryVySiAFySSSaySiGGGtc1x_tF", "", "Int", "String", "macrogenleft")
-SDK_CHANGE(Constructor, TypeRewritten, "1", "s:12macrogenleft2S1VACSicfc", "", "Int", "Double", "macrogenleft")
+SDK_CHANGE(Function, TypeRewritten, "0", "s:12macrogenleft2C1C4foo2ySSSi_SitF", "", "String", "Int", "macrogenleft")
+SDK_CHANGE(Function, TypeRewritten, "1", "s:12macrogenleft2C1C4foo2ySSSi_SitF", "", "Int", "() -> ()", "macrogenleft")
+SDK_CHANGE(Function, TypeRewritten, "2", "s:12macrogenleft2C1C4foo2ySSSi_SitF", "", "Int", "String", "macrogenleft")
+SDK_CHANGE(Function, Rename, "0", "s:12macrogenleft2S1V4foo51x1yySi_SitF", "", "foo5(x:y:)", "foo5(x:y:z:)", "macrogenleft")
+SDK_CHANGE(Function, WrapOptional, "0", "s:12macrogenleft2S1V4foo61x1yS2i_SitF", "", "", "", "macrogenleft")
+SDK_CHANGE(Function, WrapOptional, "2", "s:12macrogenleft2S1V4foo61x1yS2i_SitF", "", "", "", "macrogenleft")
+SDK_CHANGE(Function, UnwrapOptional, "0", "s:12macrogenleft2S1V4foo71x1ySiSgSi_AGtF", "", "", "", "macrogenleft")
+SDK_CHANGE(Function, UnwrapOptional, "2", "s:12macrogenleft2S1V4foo71x1ySiSgSi_AGtF", "", "", "", "macrogenleft")
+SDK_CHANGE(Function, ImplicitOptionalToOptional, "0", "s:12macrogenleft2S1V4foo81x1ySQySiGSi_AGtF", "", "", "", "macrogenleft")
+SDK_CHANGE(Function, ImplicitOptionalToOptional, "2", "s:12macrogenleft2S1V4foo81x1ySQySiGSi_AGtF", "", "", "", "macrogenleft")
+SDK_CHANGE(Function, WrapOptional, "2:0", "s:12macrogenleft2S1V4foo91x1yySays10DictionaryVySiSSSgGG_SaySiGtF", "", "", "", "macrogenleft")
+SDK_CHANGE(Function, UnwrapOptional, "1:0:1", "s:12macrogenleft2S1V4foo91x1yySays10DictionaryVySiSSSgGG_SaySiGtF", "", "", "", "macrogenleft")
+SDK_CHANGE(Function, WrapOptional, "1:1:1:1:1:0", "s:12macrogenleft2S1V5foo101xySSSi_s10DictionaryVySiAGySSSaySiGGGtc_tF", "", "", "", "macrogenleft")
+SDK_CHANGE(Function, TypeRewritten, "1:1:1:1", "s:12macrogenleft2S1V5foo111xySSSi_s10DictionaryVySiAGySSSaySiGGGtc_tF", "", "[String : [Int]]", "Int", "macrogenleft")
+SDK_CHANGE(Function, TypeRewritten, "1:1:1:1:1:0:0:0:0", "s:12macrogenleft2S1V5foo121xySSSi_s10DictionaryVySiAGySSSaySiGGGtc_tF", "", "Int", "String", "macrogenleft")
+SDK_CHANGE(Constructor, TypeRewritten, "1", "s:12macrogenleft2S1VyACSicfc", "", "Int", "Double", "macrogenleft")
 #undef SDK_CHANGE
 
diff --git a/test/api-digester/Outputs/macro-gen.json b/test/api-digester/Outputs/macro-gen.json
index 5293c92..a5c1ed1 100644
--- a/test/api-digester/Outputs/macro-gen.json
+++ b/test/api-digester/Outputs/macro-gen.json
@@ -4,7 +4,7 @@
     "NodeKind": "Constructor",
     "NodeAnnotation": "TypeRewritten",
     "ChildIndex": "1",
-    "LeftUsr": "s:12macrogenleft2S1VACSicfc",
+    "LeftUsr": "s:12macrogenleft2S1VyACSicfc",
     "LeftComment": "Int",
     "RightUsr": "",
     "RightComment": "Double",
@@ -15,7 +15,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "Rename",
     "ChildIndex": "0",
-    "LeftUsr": "s:12macrogenleft2S1V4foo5ySi1x_Si1ytF",
+    "LeftUsr": "s:12macrogenleft2S1V4foo51x1yySi_SitF",
     "LeftComment": "foo5(x:y:)",
     "RightUsr": "",
     "RightComment": "foo5(x:y:z:)",
@@ -26,7 +26,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "WrapOptional",
     "ChildIndex": "0",
-    "LeftUsr": "s:12macrogenleft2S1V4foo6S2i1x_Si1ytF",
+    "LeftUsr": "s:12macrogenleft2S1V4foo61x1yS2i_SitF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -37,7 +37,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "WrapOptional",
     "ChildIndex": "2",
-    "LeftUsr": "s:12macrogenleft2S1V4foo6S2i1x_Si1ytF",
+    "LeftUsr": "s:12macrogenleft2S1V4foo61x1yS2i_SitF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -48,7 +48,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "UnwrapOptional",
     "ChildIndex": "0",
-    "LeftUsr": "s:12macrogenleft2S1V4foo7SiSgSi1x_AE1ytF",
+    "LeftUsr": "s:12macrogenleft2S1V4foo71x1ySiSgSi_AGtF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -59,7 +59,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "UnwrapOptional",
     "ChildIndex": "2",
-    "LeftUsr": "s:12macrogenleft2S1V4foo7SiSgSi1x_AE1ytF",
+    "LeftUsr": "s:12macrogenleft2S1V4foo71x1ySiSgSi_AGtF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -70,7 +70,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "ImplicitOptionalToOptional",
     "ChildIndex": "0",
-    "LeftUsr": "s:12macrogenleft2S1V4foo8SQySiGSi1x_AE1ytF",
+    "LeftUsr": "s:12macrogenleft2S1V4foo81x1ySQySiGSi_AGtF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -81,7 +81,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "ImplicitOptionalToOptional",
     "ChildIndex": "2",
-    "LeftUsr": "s:12macrogenleft2S1V4foo8SQySiGSi1x_AE1ytF",
+    "LeftUsr": "s:12macrogenleft2S1V4foo81x1ySQySiGSi_AGtF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -92,7 +92,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "UnwrapOptional",
     "ChildIndex": "1:0:1",
-    "LeftUsr": "s:12macrogenleft2S1V4foo9ySays10DictionaryVySiSSSgGG1x_SaySiG1ytF",
+    "LeftUsr": "s:12macrogenleft2S1V4foo91x1yySays10DictionaryVySiSSSgGG_SaySiGtF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -103,7 +103,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "WrapOptional",
     "ChildIndex": "2:0",
-    "LeftUsr": "s:12macrogenleft2S1V4foo9ySays10DictionaryVySiSSSgGG1x_SaySiG1ytF",
+    "LeftUsr": "s:12macrogenleft2S1V4foo91x1yySays10DictionaryVySiSSSgGG_SaySiGtF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -114,7 +114,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "WrapOptional",
     "ChildIndex": "1:1:1:1:1:0",
-    "LeftUsr": "s:12macrogenleft2S1V5foo10ySSSi_s10DictionaryVySiAFySSSaySiGGGtc1x_tF",
+    "LeftUsr": "s:12macrogenleft2S1V5foo101xySSSi_s10DictionaryVySiAGySSSaySiGGGtc_tF",
     "LeftComment": "",
     "RightUsr": "",
     "RightComment": "",
@@ -125,7 +125,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "TypeRewritten",
     "ChildIndex": "1:1:1:1",
-    "LeftUsr": "s:12macrogenleft2S1V5foo11ySSSi_s10DictionaryVySiAFySSSaySiGGGtc1x_tF",
+    "LeftUsr": "s:12macrogenleft2S1V5foo111xySSSi_s10DictionaryVySiAGySSSaySiGGGtc_tF",
     "LeftComment": "[String : [Int]]",
     "RightUsr": "",
     "RightComment": "Int",
@@ -136,7 +136,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "TypeRewritten",
     "ChildIndex": "1:1:1:1:1:0:0:0:0",
-    "LeftUsr": "s:12macrogenleft2S1V5foo12ySSSi_s10DictionaryVySiAFySSSaySiGGGtc1x_tF",
+    "LeftUsr": "s:12macrogenleft2S1V5foo121xySSSi_s10DictionaryVySiAGySSSaySiGGGtc_tF",
     "LeftComment": "Int",
     "RightUsr": "",
     "RightComment": "String",
@@ -147,7 +147,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "TypeRewritten",
     "ChildIndex": "0",
-    "LeftUsr": "s:12macrogenleft2C1C4foo2SSSi_SitF",
+    "LeftUsr": "s:12macrogenleft2C1C4foo2ySSSi_SitF",
     "LeftComment": "String",
     "RightUsr": "",
     "RightComment": "Int",
@@ -158,7 +158,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "TypeRewritten",
     "ChildIndex": "1",
-    "LeftUsr": "s:12macrogenleft2C1C4foo2SSSi_SitF",
+    "LeftUsr": "s:12macrogenleft2C1C4foo2ySSSi_SitF",
     "LeftComment": "Int",
     "RightUsr": "",
     "RightComment": "() -> ()",
@@ -169,7 +169,7 @@
     "NodeKind": "Function",
     "NodeAnnotation": "TypeRewritten",
     "ChildIndex": "2",
-    "LeftUsr": "s:12macrogenleft2C1C4foo2SSSi_SitF",
+    "LeftUsr": "s:12macrogenleft2C1C4foo2ySSSi_SitF",
     "LeftComment": "Int",
     "RightUsr": "",
     "RightComment": "String",
diff --git a/test/attr/accessibility.swift b/test/attr/accessibility.swift
index 7a6df00..8a3b038 100644
--- a/test/attr/accessibility.swift
+++ b/test/attr/accessibility.swift
@@ -90,7 +90,9 @@
 private protocol TestProtocol {
   private associatedtype Foo // expected-error {{'private' modifier cannot be applied to this declaration}} {{3-11=}}
   internal var Bar: Int { get } // expected-error {{'internal' modifier cannot be used in protocols}} {{3-12=}}
+  // expected-note@-1 {{protocol requirements implicitly have the same access as the protocol itself}}
   public func baz() // expected-error {{'public' modifier cannot be used in protocols}} {{3-10=}}
+  // expected-note@-1 {{protocol requirements implicitly have the same access as the protocol itself}}
 }
 
 public(set) func publicSetFunc() {} // expected-error {{'public' modifier cannot be applied to this declaration}} {{1-13=}}
diff --git a/test/attr/attr_objc_override.swift b/test/attr/attr_objc_override.swift
index 564f863..65ac906 100644
--- a/test/attr/attr_objc_override.swift
+++ b/test/attr/attr_objc_override.swift
@@ -1,4 +1,4 @@
-// RUN: %target-typecheck-verify-swift
+// RUN: %target-typecheck-verify-swift -swift-version 4
 //
 // REQUIRES: objc_interop
 
@@ -8,11 +8,19 @@
 }
 
 @objc class ObjCClass {}
+struct SwiftStruct { }
 
 class A {
   @objc subscript (a: ObjCClass) -> ObjCClass { // expected-note{{overridden declaration here has type '(ObjCClass) -> ObjCClass'}}
     get { return ObjCClass() }
   }
+
+  func bar() { } // expected-note{{add '@objc' to make this declaration overridable}}{{3-3=@objc }}
+}
+
+extension A {
+  func foo() { } // expected-note{{add '@objc' to make this declaration overridable}}{{3-3=@objc }}
+  func wibble(_: SwiftStruct) { } // expected-note{{overridden declaration is here}}
 }
 
 class B : A {
@@ -20,4 +28,12 @@
   @objc subscript (a: ObjCClass) -> AnyObject { // expected-error{{overriding keyed subscript with incompatible type '(ObjCClass) -> AnyObject'}}
     get { return self }
   }
+
+  override func foo() { } // expected-error{{overriding non-@objc declarations from extensions is not supported}}
+
+  override func wibble(_: SwiftStruct) { } // expected-error{{overriding declarations in extensions is not supported}}
+}
+
+extension B {
+  override func bar() { } // expected-error{{overriding non-@objc declarations from extensions is not supported}}
 }
diff --git a/test/attr/attr_override.swift b/test/attr/attr_override.swift
index a103267..de9e0b0 100644
--- a/test/attr/attr_override.swift
+++ b/test/attr/attr_override.swift
@@ -67,7 +67,7 @@
     set { }
   }
 
-  func overriddenInExtension() {} // expected-note {{overridden declaration is here}}
+  func overriddenInExtension() {} // expected-note {{overr}}
 }
 
 class B : A {
@@ -140,7 +140,7 @@
 }
 
 extension B {
-  override func overriddenInExtension() {} // expected-error{{overriding declarations in extensions is not supported}}
+  override func overriddenInExtension() {} // expected-error{{overr}}
 }
 
 struct S {
diff --git a/test/attr/attr_versioned.swift b/test/attr/attr_versioned.swift
index 37b2956..bcfa549 100644
--- a/test/attr/attr_versioned.swift
+++ b/test/attr/attr_versioned.swift
@@ -41,6 +41,7 @@
 
   public func publicRequirement() -> T
   // expected-error@-1 {{'public' modifier cannot be used in protocols}}
+  // expected-note@-2 {{protocol requirements implicitly have the same access as the protocol itself}}
 
   @_versioned func versionedRequirement() -> T
   // expected-error@-1 {{'@_versioned' attribute cannot be used in protocols}}
diff --git a/test/decl/class/classes.swift b/test/decl/class/classes.swift
index 6868d93..879e609 100644
--- a/test/decl/class/classes.swift
+++ b/test/decl/class/classes.swift
@@ -6,7 +6,7 @@
   func g() -> (B, B) { return (B(), B()) } // expected-error {{declaration 'g()' cannot override more than one superclass declaration}}
   override func h() -> (A, B) { return (B(), B()) } // expected-note {{'h()' previously overridden here}}
   override func h() -> (B, A) { return (B(), B()) } // expected-error {{'h()' has already been overridden}}
-  func i() {} // expected-error {{overriding declarations from extensions is not supported}}
+  func i() {} // expected-error {{overri}}
   override func j() -> Int { return 0 }
   func j() -> Float { return 0.0 }
   func k() -> Float { return 0.0 }
@@ -39,7 +39,7 @@
   }
 }
 extension A {
-  func i() {} // expected-note{{overridden declaration is here}}
+  func i() {} // expected-note{{overri}}
 }
 func f() {
   let x = B()
diff --git a/test/decl/ext/generic.swift b/test/decl/ext/generic.swift
index 7bea40f..130b65f 100644
--- a/test/decl/ext/generic.swift
+++ b/test/decl/ext/generic.swift
@@ -138,7 +138,7 @@
 
 extension Array where Element == String { }
 
-extension GenericClass : P3 where T : P3 { } // expected-error{{conditional conformance of 'GenericClass<T>' to 'P3' depends on an experimental feature (SE-0143)}}
+extension GenericClass : P3 where T : P3 { }
 
 extension GenericClass where Self : P3 { }
 // expected-error@-1{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'GenericClass'?}} {{30-34=GenericClass}}
diff --git a/test/decl/func/static_func.swift b/test/decl/func/static_func.swift
index 4574282..3084972 100644
--- a/test/decl/func/static_func.swift
+++ b/test/decl/func/static_func.swift
@@ -61,21 +61,21 @@
 }
 
 class C {
-  static func f1() {} // expected-note 3{{overridden declaration is here}}
+  static func f1() {} // expected-note 3{{overri}}
   class func f2() {}
   class func f3() {}
-  class func f4() {} // expected-note {{overridden declaration is here}}
-  class func f5() {} // expected-note {{overridden declaration is here}}
+  class func f4() {} // expected-note {{overri}}
+  class func f5() {} // expected-note {{overri}}
   static final func f6() {} // expected-error {{static declarations are already final}} {{10-16=}}
-  final class func f7() {} // expected-note 3{{overridden declaration is here}}
+  final class func f7() {} // expected-note 3{{overri}}
 }
 
 extension C {
   static func ef1() {}
-  class func ef2() {} // expected-note {{overridden declaration is here}}
-  class func ef3() {} // expected-note {{overridden declaration is here}}
-  class func ef4() {} // expected-note {{overridden declaration is here}}
-  class func ef5() {} // expected-note {{overridden declaration is here}}
+  class func ef2() {} // expected-note {{overri}}
+  class func ef3() {} // expected-note {{overri}}
+  class func ef4() {} // expected-note {{overri}}
+  class func ef5() {} // expected-note {{overri}}
 }
 
 class C_Derived : C {
@@ -83,8 +83,8 @@
   override class func f2() {}
   class override func f3() {}
 
-  override class func ef2() {} // expected-error {{overriding declarations from extensions is not supported}}
-  class override func ef3() {} // expected-error {{overriding declarations from extensions is not supported}}
+  override class func ef2() {} // expected-error {{not supported}}
+  class override func ef3() {} // expected-error {{not supported}}
   override static func f7() {} // expected-error {{static method overrides a 'final' class method}}
 }
 
@@ -98,11 +98,11 @@
 }
 
 extension C_Derived {
-  override class func f4() {} // expected-error {{overriding declarations in extensions is not supported}}
-  class override func f5() {} // expected-error {{overriding declarations in extensions is not supported}}
+  override class func f4() {} // expected-error {{not supported}}
+  class override func f5() {} // expected-error {{not supported}}
 
-  override class func ef4() {} // expected-error {{overriding declarations in extensions is not supported}}
-  class override func ef5() {} // expected-error {{overriding declarations in extensions is not supported}}
+  override class func ef4() {} // expected-error {{not supported}}
+  class override func ef5() {} // expected-error {{not supported}}
 }
 
 protocol P {
diff --git a/test/decl/inherit/override.swift b/test/decl/inherit/override.swift
index abe2b9a..b71aa4b 100644
--- a/test/decl/inherit/override.swift
+++ b/test/decl/inherit/override.swift
@@ -4,22 +4,22 @@
 @objc class ObjCClassB : ObjCClassA {}
 
 class A { 
-  func f1() { } // expected-note{{overridden declaration is here}}
-  func f2() -> A { } // expected-note{{overridden declaration is here}}
+  func f1() { } // expected-note{{overri}}
+  func f2() -> A { } // expected-note{{overri}}
 
-  @objc func f3() { } // expected-note{{overridden declaration is here}}
-  @objc func f4() -> ObjCClassA { } // expected-note{{overridden declaration is here}}
-  @objc var v1: Int { return 0 } // expected-note{{overridden declaration is here}}
-  @objc var v2: Int { return 0 } // expected-note{{overridden declaration is here}}
-  @objc var v3: Int = 0 // expected-note{{overridden declaration is here}}
+  @objc func f3() { } // expected-note{{overri}}
+  @objc func f4() -> ObjCClassA { } // expected-note{{overri}}
+  @objc var v1: Int { return 0 } // expected-note{{overri}}
+  @objc var v2: Int { return 0 } // expected-note{{overri}}
+  @objc var v3: Int = 0 // expected-note{{overri}}
 
   dynamic func f3D() { } // expected-error{{'dynamic' instance method 'f3D()' must also be '@objc'}}{{3-3=@objc }}
   dynamic func f4D() -> ObjCClassA { } // expected-error{{'dynamic' instance method 'f4D()' must also be '@objc'}}{{3-3=@objc }}
 }
 
 extension A {
-  func f5() { } // expected-note{{overridden declaration is here}}
-  func f6() -> A { } // expected-note{{overridden declaration is here}}
+  func f5() { } // expected-note{{overri}}
+  func f6() -> A { } // expected-note{{overri}}
 
   @objc func f7() { }
   @objc func f8() -> ObjCClassA { }
@@ -28,8 +28,8 @@
 class B : A { }
 
 extension B { 
-  func f1() { }  // expected-error{{overriding declarations in extensions is not supported}}
-  func f2() -> B { } // expected-error{{overriding declarations in extensions is not supported}}
+  func f1() { }  // expected-error{{overri}}
+  func f2() -> B { } // expected-error{{overri}}
 
   override func f3() { } // expected-error{{cannot override a non-dynamic class declaration from an extension}}
   override func f4() -> ObjCClassB { } // expected-error{{cannot override a non-dynamic class declaration from an extension}}
@@ -46,7 +46,7 @@
   override func f3D() { }
   override func f4D() -> ObjCClassB { }
 
-  func f5() { }  // expected-error{{overriding declarations in extensions is not supported}}
+  func f5() { }  // expected-error{{overridi}}
   func f6() -> A { }  // expected-error{{overriding declarations in extensions is not supported}}
 
   @objc override func f7() { }
diff --git a/test/decl/protocol/req/associated_type_inference.swift b/test/decl/protocol/req/associated_type_inference.swift
index 5885342..5954131 100644
--- a/test/decl/protocol/req/associated_type_inference.swift
+++ b/test/decl/protocol/req/associated_type_inference.swift
@@ -400,3 +400,72 @@
 
 struct P14b<Value> { }
 extension P14b: P14 { }
+
+// Associated type defaults in overridden associated types.
+struct X15 { }
+struct OtherX15 { }
+
+protocol P15a {
+  associatedtype A = X15
+}
+
+protocol P15b : P15a {
+  associatedtype A
+}
+
+protocol P15c : P15b {
+  associatedtype A
+}
+
+protocol P15d {
+  associatedtype A = X15
+}
+
+protocol P15e : P15b, P15d {
+  associatedtype A
+}
+
+protocol P15f {
+  associatedtype A = OtherX15
+}
+
+protocol P15g: P15c, P15f {
+  associatedtype A // expected-note{{protocol requires nested type 'A'; do you want to add it?}}
+}
+
+
+struct X15a : P15a { }
+struct X15b : P15b { }
+struct X15c : P15c { }
+struct X15d : P15d { }
+
+// Ambiguity.
+// FIXME: Better diagnostic here?
+struct X15g : P15g { } // expected-error{{type 'X15g' does not conform to protocol 'P15g'}}
+
+// Associated type defaults in overidden associated types that require
+// substitution.
+struct X16<T> { }
+
+protocol P16 {
+  associatedtype A = X16<Self>
+}
+
+protocol P16a : P16 {
+  associatedtype A
+}
+
+protocol P16b : P16a {
+  associatedtype A
+}
+
+struct X16b : P16b { }
+
+// Refined protocols that tie associated types to a fixed type.
+protocol P17 {
+  associatedtype T
+}
+
+protocol Q17 : P17 where T == Int { }
+
+struct S17 : Q17 { }
diff --git a/test/decl/protocol/req/associated_type_typealias_implements.swift b/test/decl/protocol/req/associated_type_typealias_implements.swift
new file mode 100644
index 0000000..8c85bef
--- /dev/null
+++ b/test/decl/protocol/req/associated_type_typealias_implements.swift
@@ -0,0 +1,38 @@
+// RUN: %target-typecheck-verify-swift
+
+protocol P { }
+
+protocol Q {
+  associatedtype T
+  associatedtype U // expected-note 2{{protocol requires nested type 'U'; do you want to add it?}}
+}
+
+protocol R: Q {
+}
+
+struct XT: P { }
+struct XTWithoutP { }
+
+struct XU { }
+
+extension R where T: P {
+  @_implements(Q, U)
+  typealias _Default_U = XU
+}
+
+struct Y1: R {
+  typealias T = XT
+  // okay: infers U = XU
+}
+
+struct Y2: R { // expected-error{{type 'Y2' does not conform to protocol 'Q'}}
+  typealias T = XTWithoutP
+
+  // FIXME: More detail from diagnostic.
+  // error: T: P fails
+}
+
+struct Y3: Q { // expected-error{{type 'Y3' does not conform to protocol 'Q'}}
+  typealias T = XT
+  // FIXME: More detail from diagnostic.
+}
diff --git a/test/decl/typealias/protocol.swift b/test/decl/typealias/protocol.swift
index b2d5e68..c00fab4 100644
--- a/test/decl/typealias/protocol.swift
+++ b/test/decl/typealias/protocol.swift
@@ -278,3 +278,15 @@
 
 extension P10 where V == Int { } // expected-warning 3{{'V' is deprecated: just use Int, silly}}
 // expected-warning@-1{{neither type in same-type constraint ('P10.V' (aka 'Int') or 'Int') refers to a generic parameter  or associated type}}
+
+// rdar://problem/36003312
+protocol P11 {
+  typealias A = Y11
+}
+
+struct X11<T: P11> { }
+struct Y11: P11 { }
+
+extension P11 {
+  func foo(_: X11<Self.A>) { }
+}
diff --git a/test/decl/var/properties.swift b/test/decl/var/properties.swift
index a1b2411..5d38e62 100644
--- a/test/decl/var/properties.swift
+++ b/test/decl/var/properties.swift
@@ -1,4 +1,4 @@
-// RUN: %target-typecheck-verify-swift -enable-experimental-conditional-conformances -typecheck
+// RUN: %target-typecheck-verify-swift
 
 func markUsed<T>(_ t: T) {}
 
@@ -1121,7 +1121,7 @@
 
 // <rdar://problem/17391625> Swift Compiler Crashes when Declaring a Variable and didSet in an Extension
 class rdar17391625 {
-  var prop = 42  // expected-note {{overridden declaration is here}}
+  var prop = 42  // expected-note {{overri}}
 }
 
 extension rdar17391625 {
@@ -1137,7 +1137,7 @@
 
 extension rdar17391625derived {
   // Not a stored property, computed because it is an override.
-  override var prop: Int { // expected-error {{overriding declarations in extensions is not supported}}
+  override var prop: Int { // expected-error {{overri}}
   didSet {
   }
   }
diff --git a/test/multifile/Inputs/default-witness.swift b/test/multifile/Inputs/default-witness.swift
new file mode 100644
index 0000000..6d0dbd8
--- /dev/null
+++ b/test/multifile/Inputs/default-witness.swift
@@ -0,0 +1,9 @@
+public protocol Node: Source { }
+
+public protocol Source {
+    associatedtype Output
+}
+
+public final class GraphNode<U>: Node {
+    public typealias Output = U
+}
diff --git a/test/multifile/Inputs/keypath.swift b/test/multifile/Inputs/keypath.swift
new file mode 100644
index 0000000..0866617
--- /dev/null
+++ b/test/multifile/Inputs/keypath.swift
@@ -0,0 +1,20 @@
+final class C<T> {
+  var a = 0
+  var b = 0
+
+  subscript(x: Int) -> Int { return x }
+}
+
+class D<T> {
+  var a = 0
+  var b = 0
+
+  subscript(x: Int) -> Int { return x }
+}
+
+protocol P {
+  var a: Int { get set }
+  var b: Int { get set }
+
+  subscript(x: Int) -> Int { get set }
+}
diff --git a/test/multifile/default-witness.swift b/test/multifile/default-witness.swift
new file mode 100644
index 0000000..65f5aae
--- /dev/null
+++ b/test/multifile/default-witness.swift
@@ -0,0 +1,10 @@
+// RUN: %target-swift-frontend -typecheck %S/Inputs/default-witness.swift -primary-file %s -enable-resilience
+
+public protocol GraphType {
+    func insert<U>(_: GraphNode<U>, _: GraphNode<U>)
+}
+
+public extension GraphType {
+    func insert<N: Node>(_: N, _: GraphNode<N.Output>) {}
+}
+
diff --git a/test/multifile/keypath.swift b/test/multifile/keypath.swift
new file mode 100644
index 0000000..2d7462e
--- /dev/null
+++ b/test/multifile/keypath.swift
@@ -0,0 +1,14 @@
+// RUN: %target-swift-frontend -emit-ir %S/Inputs/keypath.swift -primary-file %s
+
+func f<T>(_: T) {
+  _ = \C<T>.b
+  _ = \C<T>[0]
+
+  _ = \D<T>.b
+  _ = \D<T>[0]
+
+  _ = \P.b
+
+  // FIXME: crashes
+  // _ = \P[0]
+}
diff --git a/test/refactoring/SyntacticRename/Outputs/variables/ivar-x.swift.expected b/test/refactoring/SyntacticRename/Outputs/variables/ivar-x.swift.expected
index 9547812..833685e 100644
--- a/test/refactoring/SyntacticRename/Outputs/variables/ivar-x.swift.expected
+++ b/test/refactoring/SyntacticRename/Outputs/variables/ivar-x.swift.expected
@@ -31,3 +31,10 @@
 var (a, /*pattern-b:def*/b) = (1, 2)
 print(a + /*pattern-b*/b)
 
+struct S {
+	lazy var lazyVal: Int = {
+		let /*lazy:def*/myVal = 0
+		return /*lazy:ref*/myVal
+	}()
+}
+
diff --git a/test/refactoring/SyntacticRename/Outputs/variables/lazy.swift.expected b/test/refactoring/SyntacticRename/Outputs/variables/lazy.swift.expected
new file mode 100644
index 0000000..f1563e1
--- /dev/null
+++ b/test/refactoring/SyntacticRename/Outputs/variables/lazy.swift.expected
@@ -0,0 +1,40 @@
+var /*var-y:def*/y = 3
+/*var-y*/y = /*var-y*/y + 2 + /*var-y*/y
+
+struct Struct {
+	let /*ivar-x:def*/x: Int
+	var y: Int
+
+	func sum() -> Int {
+		return /*ivar-x*/x + y
+	}
+}
+
+let aStruct = Struct(x: 10, y: 11)
+print(aStruct . /*ivar-x*/x + aStruct.y)
+var cat = {(a: Int) in aStruct . /*ivar-x*/x}
+
+var aTuple = (1, 1)
+
+switch aTuple {
+case (let /*pattern-a:def*/a, let b):
+	print(/*pattern-a*/a + b)
+}
+
+var opt = Optional.some(1)
+var opt2 = Optional.some(2)
+
+if let i = opt, let /*var-j:def*/j = opt2 {
+	print(i + /*var-j*/j)
+}
+
+var (a, /*pattern-b:def*/b) = (1, 2)
+print(a + /*pattern-b*/b)
+
+struct S {
+	lazy var lazyVal: Int = {
+		let /*lazy:def*/myNewVal = 0
+		return /*lazy:ref*/myNewVal
+	}()
+}
+
diff --git a/test/refactoring/SyntacticRename/Outputs/variables/pattern-a.swift.expected b/test/refactoring/SyntacticRename/Outputs/variables/pattern-a.swift.expected
index 3a4228c..e1b27ad 100644
--- a/test/refactoring/SyntacticRename/Outputs/variables/pattern-a.swift.expected
+++ b/test/refactoring/SyntacticRename/Outputs/variables/pattern-a.swift.expected
@@ -31,3 +31,10 @@
 var (a, /*pattern-b:def*/b) = (1, 2)
 print(a + /*pattern-b*/b)
 
+struct S {
+	lazy var lazyVal: Int = {
+		let /*lazy:def*/myVal = 0
+		return /*lazy:ref*/myVal
+	}()
+}
+
diff --git a/test/refactoring/SyntacticRename/Outputs/variables/pattern-b.swift.expected b/test/refactoring/SyntacticRename/Outputs/variables/pattern-b.swift.expected
index e2391dc..065e0ce 100644
--- a/test/refactoring/SyntacticRename/Outputs/variables/pattern-b.swift.expected
+++ b/test/refactoring/SyntacticRename/Outputs/variables/pattern-b.swift.expected
@@ -31,3 +31,10 @@
 var (a, /*pattern-b:def*/bee) = (1, 2)
 print(a + /*pattern-b*/bee)
 
+struct S {
+	lazy var lazyVal: Int = {
+		let /*lazy:def*/myVal = 0
+		return /*lazy:ref*/myVal
+	}()
+}
+
diff --git a/test/refactoring/SyntacticRename/Outputs/variables/var-j.swift.expected b/test/refactoring/SyntacticRename/Outputs/variables/var-j.swift.expected
index 156dbef..e7bc788 100644
--- a/test/refactoring/SyntacticRename/Outputs/variables/var-j.swift.expected
+++ b/test/refactoring/SyntacticRename/Outputs/variables/var-j.swift.expected
@@ -31,3 +31,10 @@
 var (a, /*pattern-b:def*/b) = (1, 2)
 print(a + /*pattern-b*/b)
 
+struct S {
+	lazy var lazyVal: Int = {
+		let /*lazy:def*/myVal = 0
+		return /*lazy:ref*/myVal
+	}()
+}
+
diff --git a/test/refactoring/SyntacticRename/Outputs/variables/var-y.swift.expected b/test/refactoring/SyntacticRename/Outputs/variables/var-y.swift.expected
index 6d7fd90..7946cca 100644
--- a/test/refactoring/SyntacticRename/Outputs/variables/var-y.swift.expected
+++ b/test/refactoring/SyntacticRename/Outputs/variables/var-y.swift.expected
@@ -31,3 +31,10 @@
 var (a, /*pattern-b:def*/b) = (1, 2)
 print(a + /*pattern-b*/b)
 
+struct S {
+	lazy var lazyVal: Int = {
+		let /*lazy:def*/myVal = 0
+		return /*lazy:ref*/myVal
+	}()
+}
+
diff --git a/test/refactoring/SyntacticRename/variables.swift b/test/refactoring/SyntacticRename/variables.swift
index 98753f2..10f962b 100644
--- a/test/refactoring/SyntacticRename/variables.swift
+++ b/test/refactoring/SyntacticRename/variables.swift
@@ -31,6 +31,13 @@
 var (a, /*pattern-b:def*/b) = (1, 2)
 print(a + /*pattern-b*/b)
 
+struct S {
+	lazy var lazyVal: Int = {
+		let /*lazy:def*/myVal = 0
+		return /*lazy:ref*/myVal
+	}()
+}
+
 // RUN: rm -rf %t.result && mkdir -p %t.result
 // RUN: %refactor -syntactic-rename -source-filename %s -pos="var-y" -old-name "y" -new-name "yack" >> %t.result/variables_var-y.swift
 // RUN: diff -u %S/Outputs/variables/var-y.swift.expected %t.result/variables_var-y.swift
@@ -42,3 +49,5 @@
 // RUN: diff -u %S/Outputs/variables/var-j.swift.expected %t.result/variables_var-j.swift
 // RUN: %refactor -syntactic-rename -source-filename %s -pos="pattern-b" -old-name "b" -new-name "bee" >> %t.result/variables_pattern-b.swift
 // RUN: diff -u %S/Outputs/variables/pattern-b.swift.expected %t.result/variables_pattern-b.swift
+// RUN: %refactor -syntactic-rename -source-filename %s -pos="lazy" -old-name "myVal" -new-name "myNewVal" >> %t.result/variables_lazy.swift
+// RUN: diff -u %S/Outputs/variables/lazy.swift.expected %t.result/variables_lazy.swift
diff --git a/test/sil-func-extractor/basic.swift b/test/sil-func-extractor/basic.swift
index b04a786..e73b4aa 100644
--- a/test/sil-func-extractor/basic.swift
+++ b/test/sil-func-extractor/basic.swift
@@ -9,12 +9,12 @@
 
 // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="_T05basic3fooSiyF" | %FileCheck %s -check-prefix=EXTRACT-FOO
 // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="_T05basic1XV4testyyF" | %FileCheck %s -check-prefix=EXTRACT-TEST
-// RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="_T05basic7VehicleCACSi1n_tcfc" | %FileCheck %s -check-prefix=EXTRACT-INIT
+// RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="_T05basic7VehicleC1nACSi_tcfc" | %FileCheck %s -check-prefix=EXTRACT-INIT
 // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="_T05basic7VehicleC3nowSiyF" | %FileCheck %s -check-prefix=EXTRACT-NOW
 
 
 // EXTRACT-FOO-NOT: sil hidden @_T05basic1XV4testyyF : $@convention(method) (X) -> () {
-// EXTRACT-FOO-NOT: sil hidden @_T05basic7VehicleCACSi1n_tcfc : $@convention(method) (Int, @guaranteed Vehicle) -> @owned Vehicle {
+// EXTRACT-FOO-NOT: sil hidden @_T05basic7VehicleC1nACSi_tcfc : $@convention(method) (Int, @guaranteed Vehicle) -> @owned Vehicle {
 // EXTRACT-FOO-NOT: sil hidden @_T05basic7VehicleC3nowSiyF : $@convention(method) (@guaranteed Vehicle) -> Int {
 
 // EXTRACT-FOO-LABEL: sil [serialized] @_T05basic3fooSiyF : $@convention(thin) () -> Int {
@@ -25,7 +25,7 @@
 
 
 // EXTRACT-TEST-NOT: sil hidden @_T05basic3fooSiyF : $@convention(thin) () -> Int {
-// EXTRACT-TEST-NOT: sil hidden @_T05basic7VehicleCACSi1n_tcfc : $@convention(method) (Int, @guaranteed Vehicle) -> @owned Vehicle {
+// EXTRACT-TEST-NOT: sil hidden @_T05basic7VehicleC1nACSi_tcfc : $@convention(method) (Int, @guaranteed Vehicle) -> @owned Vehicle {
 // EXTRACT-TEST-NOT: sil hidden @_T05basic7VehicleC3nowSiyF : $@convention(method) (@guaranteed Vehicle) -> Int {
 
 // EXTRACT-TEST-LABEL:  sil [serialized] @_T05basic1XV4testyyF : $@convention(method) (X) -> () {
@@ -41,7 +41,7 @@
 // EXTRACT-INIT-NOT: sil [serialized] @_T05basic1XV4testyyF : $@convention(method) (X) -> () {
 // EXTRACT-INIT-NOT: sil [serialized] @_T05basic7VehicleC3nowSiyF : $@convention(method) (@owned Vehicle) -> Int {
 
-// EXTRACT-INIT-LABEL:   sil [serialized] @_T05basic7VehicleCACSi1n_tcfc : $@convention(method) (Int, @owned Vehicle) -> @owned Vehicle {
+// EXTRACT-INIT-LABEL:   sil [serialized] @_T05basic7VehicleC1nACSi_tcfc : $@convention(method) (Int, @owned Vehicle) -> @owned Vehicle {
 // EXTRACT-INIT:         bb0
 // EXTRACT-INIT-NEXT:      ref_element_addr
 // EXTRACT-INIT-NEXT:      begin_access [modify] [dynamic]
@@ -52,7 +52,7 @@
 
 // EXTRACT-NOW-NOT: sil [serialized] @_T05basic3fooSiyF : $@convention(thin) () -> Int {
 // EXTRACT-NOW-NOT: sil [serialized] @_T05basic1XV4testyyF : $@convention(method) (X) -> () {
-// EXTRACT-NOW-NOT: sil [serialized] @_T05basic7VehicleCACSi1n_tcfc : $@convention(method) (Int, @guaranteed Vehicle) -> @owned Vehicle {
+// EXTRACT-NOW-NOT: sil [serialized] @_T05basic7VehicleC1nACSi_tcfc : $@convention(method) (Int, @guaranteed Vehicle) -> @owned Vehicle {
 
 // EXTRACT-NOW-LABEL:   sil [serialized] @_T05basic7VehicleC3nowSiyF : $@convention(method) (@guaranteed Vehicle) -> Int {
 // EXTRACT-NOW:         bb0
diff --git a/test/stdlib/FlatMapDeprecation.swift b/test/stdlib/FlatMapDeprecation.swift
new file mode 100644
index 0000000..4567b2b
--- /dev/null
+++ b/test/stdlib/FlatMapDeprecation.swift
@@ -0,0 +1,32 @@
+// RUN: %target-typecheck-verify-swift %s
+
+func flatMapOnSequence<
+  S : Sequence
+>(xs: S, f: (S.Element) -> S.Element?) {
+  _ = xs.flatMap(f) // expected-warning {{deprecated}} expected-note {{compactMap}}
+}
+
+func flatMapOnLazySequence<
+  S : LazySequenceProtocol
+>(xs: S, f: (S.Element) -> S.Element?) {
+  _ = xs.flatMap(f) // expected-warning {{deprecated}} expected-note {{compactMap}}
+}
+
+func flatMapOnLazyCollection<
+  C : LazyCollectionProtocol
+>(xs: C, f: (C.Element) -> C.Element?) {
+  _ = xs.flatMap(f) // expected-warning {{deprecated}} expected-note {{compactMap}}
+}
+
+func flatMapOnLazyBidirectionalCollection<
+  C : LazyCollectionProtocol & BidirectionalCollection
+>(xs: C, f: (C.Element) -> C.Element?)
+where C.Elements : BidirectionalCollection {
+  _ = xs.flatMap(f) // expected-warning {{deprecated}} expected-note {{compactMap}}
+}
+
+func flatMapOnCollectinoOfStrings<
+  C : Collection
+>(xs: C, f: (C.Element) -> String?) {
+  _ = xs.flatMap(f) // expected-warning {{deprecated}} expected-note {{compactMap}}
+}
diff --git a/test/stdlib/FloatingPointIR.swift b/test/stdlib/FloatingPointIR.swift
index 13e44b1..09aff78 100644
--- a/test/stdlib/FloatingPointIR.swift
+++ b/test/stdlib/FloatingPointIR.swift
@@ -33,34 +33,34 @@
 #endif
 }
 
-// i386: call swiftcc void @_T015FloatingPointIR13acceptFloat32ySfF{{.*}}(float 1.000000e+00)
-// i386: call swiftcc void @_T015FloatingPointIR13acceptFloat64ySdF{{.*}}(double 1.000000e+00)
-// i386: call swiftcc void @_T015FloatingPointIR13acceptFloat80ys0E0VF{{.*}}(x86_fp80 0xK3FFF8000000000000000)
+// i386: call swiftcc void @_T015FloatingPointIR13acceptFloat32yySfF{{.*}}(float 1.000000e+00)
+// i386: call swiftcc void @_T015FloatingPointIR13acceptFloat64yySdF{{.*}}(double 1.000000e+00)
+// i386: call swiftcc void @_T015FloatingPointIR13acceptFloat80yys0E0VF{{.*}}(x86_fp80 0xK3FFF8000000000000000)
 
-// x86_64: call swiftcc void @_T015FloatingPointIR13acceptFloat32ySfF{{.*}}(float 1.000000e+00)
-// x86_64: call swiftcc void @_T015FloatingPointIR13acceptFloat64ySdF{{.*}}(double 1.000000e+00)
-// x86_64: call swiftcc void @_T015FloatingPointIR13acceptFloat80ys0E0VF{{.*}}(x86_fp80 0xK3FFF8000000000000000)
+// x86_64: call swiftcc void @_T015FloatingPointIR13acceptFloat32yySfF{{.*}}(float 1.000000e+00)
+// x86_64: call swiftcc void @_T015FloatingPointIR13acceptFloat64yySdF{{.*}}(double 1.000000e+00)
+// x86_64: call swiftcc void @_T015FloatingPointIR13acceptFloat80yys0E0VF{{.*}}(x86_fp80 0xK3FFF8000000000000000)
 
-// armv7: call swiftcc void @_T015FloatingPointIR13acceptFloat32ySfF{{.*}}(float 1.000000e+00)
-// armv7: call swiftcc void @_T015FloatingPointIR13acceptFloat64ySdF{{.*}}(double 1.000000e+00)
+// armv7: call swiftcc void @_T015FloatingPointIR13acceptFloat32yySfF{{.*}}(float 1.000000e+00)
+// armv7: call swiftcc void @_T015FloatingPointIR13acceptFloat64yySdF{{.*}}(double 1.000000e+00)
 
-// armv7s: call swiftcc void @_T015FloatingPointIR13acceptFloat32ySfF{{.*}}(float 1.000000e+00)
-// armv7s: call swiftcc void @_T015FloatingPointIR13acceptFloat64ySdF{{.*}}(double 1.000000e+00)
+// armv7s: call swiftcc void @_T015FloatingPointIR13acceptFloat32yySfF{{.*}}(float 1.000000e+00)
+// armv7s: call swiftcc void @_T015FloatingPointIR13acceptFloat64yySdF{{.*}}(double 1.000000e+00)
 
-// armv7k: call swiftcc void @_T015FloatingPointIR13acceptFloat32ySfF{{.*}}(float 1.000000e+00)
-// armv7k: call swiftcc void @_T015FloatingPointIR13acceptFloat64ySdF{{.*}}(double 1.000000e+00)
+// armv7k: call swiftcc void @_T015FloatingPointIR13acceptFloat32yySfF{{.*}}(float 1.000000e+00)
+// armv7k: call swiftcc void @_T015FloatingPointIR13acceptFloat64yySdF{{.*}}(double 1.000000e+00)
 
-// arm64: call swiftcc void @_T015FloatingPointIR13acceptFloat32ySfF{{.*}}(float 1.000000e+00)
-// arm64: call swiftcc void @_T015FloatingPointIR13acceptFloat64ySdF{{.*}}(double 1.000000e+00)
+// arm64: call swiftcc void @_T015FloatingPointIR13acceptFloat32yySfF{{.*}}(float 1.000000e+00)
+// arm64: call swiftcc void @_T015FloatingPointIR13acceptFloat64yySdF{{.*}}(double 1.000000e+00)
 
-// aarch64: call swiftcc void @_T015FloatingPointIR13acceptFloat32ySfF{{.*}}(float 1.000000e+00)
-// aarch64: call swiftcc void @_T015FloatingPointIR13acceptFloat64ySdF{{.*}}(double 1.000000e+00)
+// aarch64: call swiftcc void @_T015FloatingPointIR13acceptFloat32yySfF{{.*}}(float 1.000000e+00)
+// aarch64: call swiftcc void @_T015FloatingPointIR13acceptFloat64yySdF{{.*}}(double 1.000000e+00)
 
-// powerpc64: call swiftcc void @_T015FloatingPointIR13acceptFloat32ySfF{{.*}}(float 1.000000e+00)
-// powerpc64: call swiftcc void @_T015FloatingPointIR13acceptFloat64ySdF{{.*}}(double 1.000000e+00)
+// powerpc64: call swiftcc void @_T015FloatingPointIR13acceptFloat32yySfF{{.*}}(float 1.000000e+00)
+// powerpc64: call swiftcc void @_T015FloatingPointIR13acceptFloat64yySdF{{.*}}(double 1.000000e+00)
 
-// powerpc64le: call swiftcc void @_T015FloatingPointIR13acceptFloat32ySfF{{.*}}(float 1.000000e+00)
-// powerpc64le: call swiftcc void @_T015FloatingPointIR13acceptFloat64ySdF{{.*}}(double 1.000000e+00)
+// powerpc64le: call swiftcc void @_T015FloatingPointIR13acceptFloat32yySfF{{.*}}(float 1.000000e+00)
+// powerpc64le: call swiftcc void @_T015FloatingPointIR13acceptFloat64yySdF{{.*}}(double 1.000000e+00)
 
-// s390x: call swiftcc void @_T015FloatingPointIR13acceptFloat32ySfF{{.*}}(float 1.000000e+00)
-// s390x: call swiftcc void @_T015FloatingPointIR13acceptFloat64ySdF{{.*}}(double 1.000000e+00)
+// s390x: call swiftcc void @_T015FloatingPointIR13acceptFloat32yySfF{{.*}}(float 1.000000e+00)
+// s390x: call swiftcc void @_T015FloatingPointIR13acceptFloat64yySdF{{.*}}(double 1.000000e+00)
diff --git a/test/stdlib/Optional.swift b/test/stdlib/Optional.swift
index d3e3320..30c4b94 100644
--- a/test/stdlib/Optional.swift
+++ b/test/stdlib/Optional.swift
@@ -327,13 +327,11 @@
 
 OptionalTests.test("Casting Optional Traps") {
   let nx: C? = nil
-  expectCrashLater()
-  _blackHole(anyToAny(nx, Int.self))
+  expectCrash { _blackHole(anyToAny(nx, Int.self)) }
 }
 OptionalTests.test("Casting Optional Any Traps") {
   let nx: X? = X()
-  expectCrashLater()
-  _blackHole(anyToAny(nx as Any, Optional<Int>.self))
+  expectCrash { _blackHole(anyToAny(nx as Any, Optional<Int>.self)) }
 }
 
 class TestNoString {}
diff --git a/test/stdlib/Repeat.swift b/test/stdlib/Repeat.swift
new file mode 100644
index 0000000..a86a412
--- /dev/null
+++ b/test/stdlib/Repeat.swift
@@ -0,0 +1,33 @@
+// RUN: %target-run-simple-swift
+// REQUIRES: executable_test
+
+import StdlibUnittest
+
+let RepeatTests = TestSuite("Repeated")
+RepeatTests.test("repeatElement") {
+  let sequence = repeatElement(1, count: 5)
+  expectEqual(sequence.count, 5)
+  expectEqualSequence(sequence, [1, 1, 1, 1, 1])
+  expectEqual(sequence.startIndex, 0)
+  expectEqual(sequence.endIndex, 5)
+  expectEqual(sequence[0], 1)
+}
+
+RepeatTests.test("associated-types") {
+  typealias Subject = Repeated<String>
+  expectRandomAccessCollectionAssociatedTypes(
+      collectionType: Subject.self,
+      iteratorType: IndexingIterator<Subject>.self,
+      subSequenceType: Slice<Subject>.self,
+      indexType: Int.self,
+      indicesType: CountableRange<Int>.self)
+}
+
+RepeatTests.test("out-of-bounds") {
+  let sequence = repeatElement(0, count: 1)
+  expectCrashLater()
+  _ = sequence[sequence.count]
+}
+
+runAllTests()
+
diff --git a/test/stmt/foreach.swift b/test/stmt/foreach.swift
index 12df84c..2394502 100644
--- a/test/stmt/foreach.swift
+++ b/test/stmt/foreach.swift
@@ -1,4 +1,4 @@
-// RUN: %target-typecheck-verify-swift -enable-experimental-conditional-conformances
+// RUN: %target-typecheck-verify-swift
 
 // Bad containers and ranges
 struct BadContainer1 {
diff --git a/test/type/types.swift b/test/type/types.swift
index 5d16cef..05baa81 100644
--- a/test/type/types.swift
+++ b/test/type/types.swift
@@ -188,3 +188,7 @@
   return "hello"
 }
 var _: sr5505 = sr5505 // expected-error {{use of undeclared type 'sr5505'}}
+
+typealias A = (inout Int ..., Int ... = [42, 12]) -> Void // expected-error {{'inout' must not be used on variadic parameters}}
+                                                          // expected-error@-1 {{only a single element can be variadic}} {{35-39=}}
+                                                          // expected-error@-2 {{default argument not permitted in a tuple type}} {{39-49=}}
diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt
index 055dc27..3e11df2 100644
--- a/tools/CMakeLists.txt
+++ b/tools/CMakeLists.txt
@@ -1,3 +1,6 @@
+# Add generated libSyntax headers to global dependencies.
+list(APPEND LLVM_COMMON_DEPENDS swift-syntax-generated-headers)
+
 add_swift_tool_subdirectory(driver)
 add_swift_tool_subdirectory(sil-opt)
 add_swift_tool_subdirectory(swift-ide-test)
diff --git a/tools/SourceKit/include/SourceKit/Core/LangSupport.h b/tools/SourceKit/include/SourceKit/Core/LangSupport.h
index 117fc80..d246099 100644
--- a/tools/SourceKit/include/SourceKit/Core/LangSupport.h
+++ b/tools/SourceKit/include/SourceKit/Core/LangSupport.h
@@ -286,7 +286,7 @@
   StringRef ModuleInterfaceName;
   /// This is an (offset,length) pair.
   /// It is set only if the declaration has a source location.
-  llvm::Optional<std::pair<unsigned, unsigned>> DeclarationLoc;
+  llvm::Optional<std::pair<unsigned, unsigned>> DeclarationLoc = None;
   /// Set only if the declaration has a source location.
   StringRef Filename;
   /// For methods this lists the USRs of the overrides in the class hierarchy.
diff --git a/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.h b/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.h
index 051a1d4..2b7bc56 100644
--- a/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.h
+++ b/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.h
@@ -33,6 +33,7 @@
   bool addInnerResults = false;
   bool addInnerOperators = true;
   bool addInitsToTopLevel = false;
+  bool callPatternHeuristics = true;
   bool hideUnderscores = true;
   bool reallyHideAllUnderscores = false;
   bool hideLowPriority = true;
diff --git a/tools/SourceKit/lib/SwiftLang/SwiftASTManager.cpp b/tools/SourceKit/lib/SwiftLang/SwiftASTManager.cpp
index ab2283e..7f41b6b 100644
--- a/tools/SourceKit/lib/SwiftLang/SwiftASTManager.cpp
+++ b/tools/SourceKit/lib/SwiftLang/SwiftASTManager.cpp
@@ -88,6 +88,8 @@
   }
 
   void applyTo(CompilerInvocation &CompInvok) const;
+  void applyToSubstitutingInputs(CompilerInvocation &CompInvok,
+                                 FrontendInputs &&Inputs) const;
   void profile(llvm::FoldingSetNodeID &ID) const;
   void raw(std::vector<std::string> &Args, std::string &PrimaryFile) const;
 
@@ -132,6 +134,11 @@
 void InvocationOptions::applyTo(CompilerInvocation &CompInvok) const {
   CompInvok = this->Invok;
 }
+void InvocationOptions::applyToSubstitutingInputs(
+    CompilerInvocation &CompInvok, FrontendInputs &&inputs) const {
+  CompInvok = this->Invok;
+  CompInvok.getFrontendOptions().Inputs = inputs;
+}
 
 void InvocationOptions::raw(std::vector<std::string> &Args,
                             std::string &PrimaryFile) const {
@@ -231,15 +238,20 @@
 
 struct FileContent {
   ImmutableTextSnapshotRef Snapshot;
+  std::string Filename;
   std::unique_ptr<llvm::MemoryBuffer> Buffer;
+  bool IsPrimary;
   BufferStamp Stamp;
 
-  FileContent(ImmutableTextSnapshotRef Snapshot,
-              std::unique_ptr<llvm::MemoryBuffer> Buffer,
+  FileContent(ImmutableTextSnapshotRef Snapshot, std::string Filename,
+              std::unique_ptr<llvm::MemoryBuffer> Buffer, bool IsPrimary,
               BufferStamp Stamp)
-    : Snapshot(std::move(Snapshot)),
-      Buffer(std::move(Buffer)),
-      Stamp(Stamp) {}
+      : Snapshot(std::move(Snapshot)), Filename(Filename),
+        Buffer(std::move(Buffer)), IsPrimary(IsPrimary), Stamp(Stamp) {}
+
+  explicit operator InputFile() const {
+    return InputFile(Filename, IsPrimary, Buffer.get());
+  }
 };
 
 class ASTProducer : public ThreadSafeRefCountedBase<ASTProducer> {
@@ -284,6 +296,11 @@
   ASTUnitRef createASTUnit(SwiftASTManager::Implementation &MgrImpl,
                            ArrayRef<ImmutableTextSnapshotRef> Snapshots,
                            std::string &Error);
+
+  void findSnapshotAndOpenFiles(SwiftASTManager::Implementation &MgrImpl,
+                                ArrayRef<ImmutableTextSnapshotRef> Snapshots,
+                                SmallVectorImpl<FileContent> &Contents,
+                                std::string &Error) const;
 };
 
 typedef IntrusiveRefCntPtr<ASTProducer> ASTProducerRef;
@@ -330,7 +347,8 @@
                            "sourcekit.swift.ASTBuilding" };
 
   ASTProducerRef getASTProducer(SwiftInvocationRef InvokRef);
-  FileContent getFileContent(StringRef FilePath, std::string &Error);
+  FileContent getFileContent(StringRef FilePath, bool IsPrimary,
+                             std::string &Error);
   BufferStamp getBufferStamp(StringRef FilePath);
   std::unique_ptr<llvm::MemoryBuffer> getMemoryBuffer(StringRef Filename,
                                                       std::string &Error);
@@ -355,7 +373,7 @@
 
   StringRef Filename = Invocation.getOutputFilename();
   if (Filename.empty()) {
-    if (!Invocation.getFrontendOptions().Inputs.hasInputFilenames()) {
+    if (!Invocation.getFrontendOptions().Inputs.hasInputs()) {
       Invocation.setModuleName("__main__");
       return;
     }
@@ -391,6 +409,48 @@
   }
 }
 
+static FrontendInputs
+convertFileContentsToInputs(const SmallVectorImpl<FileContent> &contents) {
+  FrontendInputs inputs;
+  for (const FileContent &content : contents)
+    inputs.addInput(InputFile(content));
+  return inputs;
+}
+
+static FrontendInputs
+resolveSymbolicLinksInInputs(FrontendInputs &inputs,
+                             StringRef UnresolvedPrimaryFile,
+                             std::string &Error) {
+  unsigned primaryCount = 0;
+  std::string PrimaryFile =
+      SwiftLangSupport::resolvePathSymlinks(UnresolvedPrimaryFile);
+  // FIXME: The frontend should be dealing with symlinks, maybe similar to
+  // clang's FileManager ?
+  FrontendInputs replacementInputs;
+  for (const InputFile &input : inputs.getAllFiles()) {
+    std::string newFilename =
+        SwiftLangSupport::resolvePathSymlinks(input.file());
+    bool newIsPrimary = input.isPrimary() ||
+                        (!PrimaryFile.empty() && PrimaryFile == newFilename);
+    if (newIsPrimary) {
+      ++primaryCount;
+    }
+    assert(primaryCount < 2 && "cannot handle multiple primaries");
+    replacementInputs.addInput(
+        InputFile(newFilename, newIsPrimary, input.buffer()));
+  }
+
+  if (PrimaryFile.empty() || primaryCount == 1) {
+    return replacementInputs;
+  }
+
+  llvm::SmallString<64> Err;
+  llvm::raw_svector_ostream OS(Err);
+  OS << "'" << PrimaryFile << "' is not part of the input files";
+  Error = OS.str();
+  return replacementInputs;
+}
+
 bool SwiftASTManager::initCompilerInvocation(CompilerInvocation &Invocation,
                                              ArrayRef<const char *> OrigArgs,
                                              DiagnosticEngine &Diags,
@@ -400,21 +460,15 @@
   sanitizeCompilerArgs(OrigArgs, Args);
 
   Invocation.setRuntimeResourcePath(Impl.RuntimeResourcePath);
-  bool Err = Invocation.parseArgs(Args, Diags);
-  if (Err) {
+  if (Invocation.parseArgs(Args, Diags)) {
     // FIXME: Get the actual diagnostic.
     Error = "error when parsing the compiler arguments";
-    return Err;
+    return true;
   }
-
-  // FIXME: The frontend should be dealing with symlinks, maybe similar to
-  // clang's FileManager ?
-  std::string PrimaryFile =
-    SwiftLangSupport::resolvePathSymlinks(UnresolvedPrimaryFile);
-  Invocation.getFrontendOptions().Inputs.transformInputFilenames(
-      [](std::string s) -> std::string {
-        return SwiftLangSupport::resolvePathSymlinks(s);
-      });
+  Invocation.getFrontendOptions().Inputs = resolveSymbolicLinksInInputs(
+      Invocation.getFrontendOptions().Inputs, UnresolvedPrimaryFile, Error);
+  if (!Error.empty())
+    return true;
 
   ClangImporterOptions &ImporterOpts = Invocation.getClangImporterOptions();
   ImporterOpts.DetailedPreprocessingRecord = true;
@@ -437,29 +491,7 @@
   FrontendOpts.IndexStorePath.clear();
   ImporterOpts.IndexStorePath.clear();
 
-  if (!PrimaryFile.empty()) {
-    Optional<unsigned> PrimaryIndex;
-    for (auto i :
-         indices(Invocation.getFrontendOptions().Inputs.getInputFilenames())) {
-      auto &CurFile =
-          Invocation.getFrontendOptions().Inputs.getInputFilenames()[i];
-      if (PrimaryFile == CurFile) {
-        PrimaryIndex = i;
-        break;
-      }
-    }
-    if (!PrimaryIndex) {
-      llvm::SmallString<64> Err;
-      llvm::raw_svector_ostream OS(Err);
-      OS << "'" << PrimaryFile << "' is not part of the input files";
-      Error = OS.str();
-      return true;
-    }
-    Invocation.getFrontendOptions().Inputs.setPrimaryInput(
-        SelectedInput(*PrimaryIndex));
-  }
-
-  return Err;
+  return false;
 }
 
 bool SwiftASTManager::initCompilerInvocation(CompilerInvocation &CompInvok,
@@ -541,23 +573,25 @@
 }
 
 static FileContent getFileContentFromSnap(ImmutableTextSnapshotRef Snap,
-                                          StringRef FilePath) {
+                                          bool IsPrimary, StringRef FilePath) {
   auto Buf = llvm::MemoryBuffer::getMemBufferCopy(
       Snap->getBuffer()->getText(), FilePath);
-  return FileContent(Snap, std::move(Buf), Snap->getStamp());
+  return FileContent(Snap, FilePath, std::move(Buf), IsPrimary,
+                     Snap->getStamp());
 }
 
-FileContent
-SwiftASTManager::Implementation::getFileContent(StringRef UnresolvedPath,
-                                                std::string &Error) {
+FileContent SwiftASTManager::Implementation::getFileContent(
+    StringRef UnresolvedPath, bool IsPrimary, std::string &Error) {
   std::string FilePath = SwiftLangSupport::resolvePathSymlinks(UnresolvedPath);
   if (auto EditorDoc = EditorDocs.findByPath(FilePath))
-    return getFileContentFromSnap(EditorDoc->getLatestSnapshot(), FilePath);
+    return getFileContentFromSnap(EditorDoc->getLatestSnapshot(), IsPrimary,
+                                  FilePath);
 
   // FIXME: Is there a way to get timestamp and buffer for a file atomically ?
   auto Stamp = getBufferStamp(FilePath);
   auto Buffer = getMemoryBuffer(FilePath, Error);
-  return FileContent(nullptr, std::move(Buffer), Stamp);
+  return FileContent(nullptr, UnresolvedPath, std::move(Buffer), IsPrimary,
+                     Stamp);
 }
 
 BufferStamp SwiftASTManager::Implementation::getBufferStamp(StringRef FilePath){
@@ -673,9 +707,10 @@
   // Check if the inputs changed.
   SmallVector<BufferStamp, 8> InputStamps;
   InputStamps.reserve(
-      Invok.Opts.Invok.getFrontendOptions().Inputs.inputFilenameCount());
-  for (auto &File :
-       Invok.Opts.Invok.getFrontendOptions().Inputs.getInputFilenames()) {
+      Invok.Opts.Invok.getFrontendOptions().Inputs.inputCount());
+  for (const auto &input :
+       Invok.Opts.Invok.getFrontendOptions().Inputs.getAllFiles()) {
+    StringRef File = input.file();
     bool FoundSnapshot = false;
     for (auto &Snap : Snapshots) {
       if (Snap->getFilename() == File) {
@@ -688,7 +723,7 @@
       InputStamps.push_back(MgrImpl.getBufferStamp(File));
   }
   assert(InputStamps.size() ==
-         Invok.Opts.Invok.getFrontendOptions().Inputs.inputFilenameCount());
+         Invok.Opts.Invok.getFrontendOptions().Inputs.inputCount());
   if (Stamps != InputStamps)
     return true;
 
@@ -759,32 +794,8 @@
   Stamps.clear();
   DependencyStamps.clear();
 
-  const InvocationOptions &Opts = InvokRef->Impl.Opts;
-
   SmallVector<FileContent, 8> Contents;
-  for (auto &File :
-       Opts.Invok.getFrontendOptions().Inputs.getInputFilenames()) {
-    bool FoundSnapshot = false;
-    for (auto &Snap : Snapshots) {
-      if (Snap->getFilename() == File) {
-        FoundSnapshot = true;
-        Contents.push_back(getFileContentFromSnap(Snap, File));
-        break;
-      }
-    }
-    if (FoundSnapshot)
-      continue;
-
-    auto Content = MgrImpl.getFileContent(File, Error);
-    if (!Content.Buffer) {
-      LOG_WARN_FUNC("failed getting file contents for " << File << ": " << Error);
-      // File may not exist, continue and recover as if it was empty.
-      Content.Buffer = llvm::MemoryBuffer::getNewMemBuffer(0, File);
-    }
-    Contents.push_back(std::move(Content));
-  }
-  assert(Contents.size() ==
-         Opts.Invok.getFrontendOptions().Inputs.inputFilenameCount());
+  findSnapshotAndOpenFiles(MgrImpl, Snapshots, Contents, Error);
 
   for (auto &Content : Contents)
     Stamps.push_back(Content.Stamp);
@@ -792,8 +803,8 @@
   trace::SwiftInvocation TraceInfo;
 
   if (trace::enabled()) {
-    TraceInfo.Args.PrimaryFile = Opts.PrimaryFile;
-    TraceInfo.Args.Args = Opts.Args;
+    TraceInfo.Args.PrimaryFile = InvokRef->Impl.Opts.PrimaryFile;
+    TraceInfo.Args.Args = InvokRef->Impl.Opts.Args;
   }
 
   ASTUnitRef ASTRef = new ASTUnit(++ASTUnitGeneration, MgrImpl.Stats);
@@ -804,7 +815,6 @@
     if (trace::enabled()) {
       TraceInfo.addFile(Content.Buffer->getBufferIdentifier(),
                         Content.Buffer->getBuffer());
-
     }
   }
   auto &CompIns = ASTRef->Impl.CompInst;
@@ -814,10 +824,10 @@
   CompIns.addDiagnosticConsumer(&Consumer);
 
   CompilerInvocation Invocation;
-  Opts.applyTo(Invocation);
+  InvokRef->Impl.Opts.applyToSubstitutingInputs(
+      Invocation, convertFileContentsToInputs(Contents));
+
   Invocation.getLangOptions().KeepSyntaxInfoInSourceFile = true;
-  for (auto &Content : Contents)
-    Invocation.addInputBuffer(Content.Buffer.get());
 
   if (CompIns.setup(Invocation)) {
     // FIXME: Report the diagnostic.
@@ -879,3 +889,36 @@
 
   return ASTRef;
 }
+
+void ASTProducer::findSnapshotAndOpenFiles(
+    SwiftASTManager::Implementation &MgrImpl,
+    ArrayRef<ImmutableTextSnapshotRef> Snapshots,
+    SmallVectorImpl<FileContent> &Contents, std::string &Error) const {
+  const InvocationOptions &Opts = InvokRef->Impl.Opts;
+  for (const auto &input :
+       Opts.Invok.getFrontendOptions().Inputs.getAllFiles()) {
+    StringRef File = input.file();
+    bool IsPrimary = input.isPrimary();
+    bool FoundSnapshot = false;
+    for (auto &Snap : Snapshots) {
+      if (Snap->getFilename() == File) {
+        FoundSnapshot = true;
+        Contents.push_back(getFileContentFromSnap(Snap, IsPrimary, File));
+        break;
+      }
+    }
+    if (FoundSnapshot)
+      continue;
+
+    auto Content = MgrImpl.getFileContent(File, IsPrimary, Error);
+    if (!Content.Buffer) {
+      LOG_WARN_FUNC("failed getting file contents for " << File << ": "
+                                                        << Error);
+      // File may not exist, continue and recover as if it was empty.
+      Content.Buffer = llvm::MemoryBuffer::getNewMemBuffer(0, File);
+    }
+    Contents.push_back(std::move(Content));
+  }
+  assert(Contents.size() ==
+         Opts.Invok.getFrontendOptions().Inputs.inputCount());
+}
diff --git a/tools/SourceKit/lib/SwiftLang/SwiftCompletion.cpp b/tools/SourceKit/lib/SwiftLang/SwiftCompletion.cpp
index 501641f..45d45a4 100644
--- a/tools/SourceKit/lib/SwiftLang/SwiftCompletion.cpp
+++ b/tools/SourceKit/lib/SwiftLang/SwiftCompletion.cpp
@@ -144,7 +144,7 @@
   if (Failed) {
     return false;
   }
-  if (!Invocation.getFrontendOptions().Inputs.hasInputFilenames()) {
+  if (!Invocation.getFrontendOptions().Inputs.hasInputs()) {
     Error = "no input filenames specified";
     return false;
   }
@@ -473,13 +473,13 @@
   }
   unsigned DescEnd = SS.size();
 
-  if (Result->getName().empty() || DescBegin == DescEnd) {
+  if (DescBegin == DescEnd) {
     LOG_FUNC_SECTION_WARN {
       llvm::SmallString<64> LogMessage;
       llvm::raw_svector_ostream LogMessageOs(LogMessage);
 
-      LogMessageOs << "Code completion result with empty name and/or "
-                      "description was ignored: \n";
+      LogMessageOs << "Code completion result with empty description "
+                      "was ignored: \n";
       Result->print(LogMessageOs);
 
       *Log << LogMessage;
@@ -815,6 +815,7 @@
   static UIdent KeyAddInnerResults("key.codecomplete.addinnerresults");
   static UIdent KeyAddInnerOperators("key.codecomplete.addinneroperators");
   static UIdent KeyAddInitsToTopLevel("key.codecomplete.addinitstotoplevel");
+  static UIdent KeyCallPatternHeuristics("key.codecomplete.callpatternheuristics");
   static UIdent KeyFuzzyMatching("key.codecomplete.fuzzymatching");
   static UIdent KeyTopNonLiteral("key.codecomplete.showtopnonliteralresults");
   static UIdent KeyContextWeight("key.codecomplete.sort.contextweight");
@@ -836,6 +837,7 @@
   from.valueForOption(KeyAddInnerResults, to.addInnerResults);
   from.valueForOption(KeyAddInnerOperators, to.addInnerOperators);
   from.valueForOption(KeyAddInitsToTopLevel, to.addInitsToTopLevel);
+  from.valueForOption(KeyCallPatternHeuristics, to.callPatternHeuristics);
   from.valueForOption(KeyFuzzyMatching, to.fuzzyMatching);
   from.valueForOption(KeyContextWeight, to.semanticContextWeight);
   from.valueForOption(KeyFuzzyWeight, to.fuzzyMatchWeight);
@@ -1194,6 +1196,8 @@
   std::vector<const char *> extendedArgs(args.begin(), args.end());
   if (CCOpts.addInitsToTopLevel)
     extendedArgs.push_back("-code-complete-inits-in-postfix-expr");
+  if (CCOpts.callPatternHeuristics)
+    extendedArgs.push_back("-code-complete-call-pattern-heuristics");
 
   // Invoke completion.
   std::string error;
diff --git a/tools/SourceKit/lib/SwiftLang/SwiftDocSupport.cpp b/tools/SourceKit/lib/SwiftLang/SwiftDocSupport.cpp
index 640ce9b..1948bf3 100644
--- a/tools/SourceKit/lib/SwiftLang/SwiftDocSupport.cpp
+++ b/tools/SourceKit/lib/SwiftLang/SwiftDocSupport.cpp
@@ -771,13 +771,14 @@
 
 static bool makeParserAST(CompilerInstance &CI, StringRef Text,
                           CompilerInvocation Invocation) {
-  Invocation.clearInputs();
+  Invocation.getFrontendOptions().Inputs.clearInputs();
   Invocation.setModuleName("main");
   Invocation.setInputKind(InputFileKind::IFK_Swift);
 
   std::unique_ptr<llvm::MemoryBuffer> Buf;
   Buf = llvm::MemoryBuffer::getMemBuffer(Text, "<module-interface>");
-  Invocation.addInputBuffer(Buf.get());
+  Invocation.getFrontendOptions().Inputs.addInput(
+      InputFile(Buf.get()->getBufferIdentifier(), false, Buf.get()));
   if (CI.setup(Invocation))
     return true;
   CI.performParseOnly();
@@ -1091,8 +1092,8 @@
 
   EditorDiagConsumer DiagConsumer;
   CI.addDiagnosticConsumer(&DiagConsumer);
-
-  Invocation.addInputBuffer(InputBuf);
+  Invocation.getFrontendOptions().Inputs.addInput(
+      InputFile(InputBuf->getBufferIdentifier(), false, InputBuf));
   if (CI.setup(Invocation))
     return true;
   DiagConsumer.setInputBufferIDs(CI.getInputBufferIDs());
@@ -1364,7 +1365,8 @@
     return nullptr;
   }
   Invocation.setInputKind(InputFileKind::IFK_Swift);
-  Invocation.addInputBuffer(InputBuf);
+  Invocation.getFrontendOptions().Inputs.addInput(
+      InputFile(InputBuf->getBufferIdentifier(), false, InputBuf));
 
   if (ParseCI.setup(Invocation)) {
     Error = "Compiler invocation set up failed";
@@ -1439,7 +1441,7 @@
                                     StringRef Error)> Receiver) {
   CompilerInvocation Invocation;
   Invocation.getClangImporterOptions().ImportForwardDeclarations = true;
-  Invocation.clearInputs();
+  Invocation.getFrontendOptions().Inputs.clearInputs();
 
   CompilerInstance CI;
   // Display diagnostics to stderr.
diff --git a/tools/SourceKit/lib/SwiftLang/SwiftEditorInterfaceGen.cpp b/tools/SourceKit/lib/SwiftLang/SwiftEditorInterfaceGen.cpp
index bbfcf52..abcb1a0 100644
--- a/tools/SourceKit/lib/SwiftLang/SwiftEditorInterfaceGen.cpp
+++ b/tools/SourceKit/lib/SwiftLang/SwiftEditorInterfaceGen.cpp
@@ -228,13 +228,14 @@
 
 static bool makeParserAST(CompilerInstance &CI, StringRef Text,
                           CompilerInvocation Invocation) {
-  Invocation.clearInputs();
+  Invocation.getFrontendOptions().Inputs.clearInputs();
   Invocation.setModuleName("main");
   Invocation.setInputKind(InputFileKind::IFK_Swift);
 
   std::unique_ptr<llvm::MemoryBuffer> Buf;
   Buf = llvm::MemoryBuffer::getMemBuffer(Text, "<module-interface>");
-  Invocation.addInputBuffer(Buf.get());
+  Invocation.getFrontendOptions().Inputs.addInput(
+      InputFile(Buf.get()->getBufferIdentifier(), false, Buf.get()));
   if (CI.setup(Invocation))
     return true;
   CI.performParseOnly();
@@ -401,7 +402,7 @@
   // Display diagnostics to stderr.
   CI.addDiagnosticConsumer(&IFaceGenCtx->Impl.DiagConsumer);
 
-  Invocation.clearInputs();
+  Invocation.getFrontendOptions().Inputs.clearInputs();
   if (CI.setup(Invocation)) {
     ErrMsg = "Error during invocation setup";
     return nullptr;
diff --git a/tools/SourceKit/lib/SwiftLang/SwiftIndexing.cpp b/tools/SourceKit/lib/SwiftLang/SwiftIndexing.cpp
index 918bbf7..ff78da5 100644
--- a/tools/SourceKit/lib/SwiftLang/SwiftIndexing.cpp
+++ b/tools/SourceKit/lib/SwiftLang/SwiftIndexing.cpp
@@ -279,7 +279,7 @@
     return;
   }
 
-  if (!Invocation.getFrontendOptions().Inputs.hasInputFilenames()) {
+  if (!Invocation.getFrontendOptions().Inputs.hasInputs()) {
     IdxConsumer.failed("no input filenames specified");
     return;
   }
diff --git a/tools/SourceKit/lib/SwiftLang/SwiftSourceDocInfo.cpp b/tools/SourceKit/lib/SwiftLang/SwiftSourceDocInfo.cpp
index a96492b..7aaa022 100644
--- a/tools/SourceKit/lib/SwiftLang/SwiftSourceDocInfo.cpp
+++ b/tools/SourceKit/lib/SwiftLang/SwiftSourceDocInfo.cpp
@@ -1218,7 +1218,7 @@
       SourceLoc Loc =
         Lexer::getLocForStartOfToken(SM, BufferID, Offset);
       if (Loc.isInvalid()) {
-        Receiver({});
+        Receiver(CursorInfoData());
         return;
       }
 
@@ -1281,7 +1281,7 @@
       CursorInfoResolver Resolver(AstUnit->getPrimarySourceFile());
       ResolvedCursorInfo CursorInfo = Resolver.resolve(Loc);
       if (CursorInfo.isInvalid()) {
-        Receiver({});
+        Receiver(CursorInfoData());
         return;
       }
       CompilerInvocation CompInvok;
@@ -1313,7 +1313,7 @@
                           /*TryExistingAST=*/false, CancelOnSubsequentRequest,
                           Receiver);
           } else {
-            Receiver({});
+            Receiver(CursorInfoData());
           }
         }
         return;
@@ -1343,7 +1343,7 @@
           }
         }
 
-        Receiver({});
+        Receiver(CursorInfoData());
         return;
       }
       case CursorInfoKind::Invalid: {
@@ -1360,7 +1360,7 @@
 
     void failed(StringRef Error) override {
       LOG_WARN_FUNC("cursor info failed: " << Error);
-      Receiver({});
+      Receiver(CursorInfoData());
     }
   };
 
@@ -1595,7 +1595,7 @@
               {}, *this, Invok, {}, Receiver);
         }
       } else {
-        Receiver({});
+        Receiver(CursorInfoData());
       }
     });
     return;
@@ -1606,7 +1606,7 @@
   if (!Invok) {
     // FIXME: Report it as failed request.
     LOG_WARN_FUNC("failed to create an ASTInvocation: " << Error);
-    Receiver({});
+    Receiver(CursorInfoData());
     return;
   }
 
@@ -1752,7 +1752,7 @@
 
       if (USR.startswith("c:")) {
         LOG_WARN_FUNC("lookup for C/C++/ObjC USRs not implemented");
-        Receiver({});
+        Receiver(CursorInfoData());
         return;
       }
 
@@ -1761,7 +1761,7 @@
       Decl *D = ide::getDeclFromUSR(context, USR, error);
 
       if (!D) {
-        Receiver({});
+        Receiver(CursorInfoData());
         return;
       }
 
@@ -1790,7 +1790,7 @@
                                  /*TryExistingAST=*/false,
                                  CancelOnSubsequentRequest, Receiver);
           } else {
-            Receiver({});
+            Receiver(CursorInfoData());
           }
         }
       }
@@ -1804,7 +1804,7 @@
 
     void failed(StringRef Error) override {
       LOG_WARN_FUNC("cursor info failed: " << Error);
-      Receiver({});
+      Receiver(CursorInfoData());
     }
   };
 
@@ -1824,7 +1824,7 @@
     std::function<void(const CursorInfoData &)> receiver) {
   if (auto IFaceGenRef = IFaceGenContexts.get(filename)) {
     LOG_WARN_FUNC("info from usr for generated interface not implemented yet");
-    receiver({});
+    receiver(CursorInfoData());
     return;
   }
 
@@ -1833,7 +1833,7 @@
   if (!invok) {
     // FIXME: Report it as failed request.
     LOG_WARN_FUNC("failed to create an ASTInvocation: " << error);
-    receiver({});
+    receiver(CursorInfoData());
     return;
   }
 
diff --git a/tools/SwiftSyntax/CMakeLists.txt b/tools/SwiftSyntax/CMakeLists.txt
index 96eff28..0c75780 100644
--- a/tools/SwiftSyntax/CMakeLists.txt
+++ b/tools/SwiftSyntax/CMakeLists.txt
@@ -3,6 +3,11 @@
   # filename.
   SwiftSyntax.swift
   AtomicCache.swift
+  Diagnostic.swift
+  DiagnosticConsumer.swift
+  DiagnosticEngine.swift
+  JSONDiagnosticConsumer.swift
+  PrintingDiagnosticConsumer.swift
   RawSyntax.swift
   SourcePresence.swift
   SwiftcInvocation.swift
diff --git a/tools/SwiftSyntax/Diagnostic.swift b/tools/SwiftSyntax/Diagnostic.swift
new file mode 100644
index 0000000..a802f0a
--- /dev/null
+++ b/tools/SwiftSyntax/Diagnostic.swift
@@ -0,0 +1,289 @@
+//===--------------- Diagnostics.swift - Diagnostic Emitter ---------------===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+// This file provides the Diagnostic, Note, and FixIt types.
+//===----------------------------------------------------------------------===//
+
+import Foundation
+
+/// Represents a source location in a Swift file.
+public struct SourceLocation: Codable {
+  /// The line in the file where this location resides.
+  public let line: Int
+
+  /// The UTF-8 byte offset from the beginning of the line where this location
+  /// resides.
+  public let column: Int
+
+  /// The UTF-8 byte offset into the file where this location resides.
+  public let offset: Int
+
+  /// The file in which this location resides.
+  public let file: String
+
+  public init(line: Int, column: Int, offset: Int, file: String) {
+    self.line = line
+    self.column = column
+    self.offset = offset
+    self.file = file
+  }
+}
+
+/// Represents a start and end location in a Swift file.
+public struct SourceRange: Codable {
+  /// The beginning location in the source range.
+  public let start: SourceLocation
+
+  /// The beginning location in the source range.
+  public let end: SourceLocation
+
+  public init(start: SourceLocation, end: SourceLocation) {
+    self.start = start
+    self.end = end
+  }
+}
+
+/// A FixIt represents a change to source code in order to "correct" a
+/// diagnostic.
+public enum FixIt: Codable {
+  /// Remove the characters from the source file over the provided source range.
+  case remove(SourceRange)
+
+  /// Insert, at the provided source location, the provided string.
+  case insert(SourceLocation, String)
+
+  /// Replace the characters at the provided source range with the provided
+  /// string.
+  case replace(SourceRange, String)
+
+  enum CodingKeys: String, CodingKey {
+    case type
+    case range
+    case location
+    case string
+  }
+
+  public init(from decoder: Decoder) throws {
+    let container = try decoder.container(keyedBy: CodingKeys.self)
+    let type = try container.decode(String.self, forKey: .type)
+    switch type {
+    case "remove":
+      let range = try container.decode(SourceRange.self, forKey: .range)
+      self = .remove(range)
+    case "insert":
+      let string = try container.decode(String.self, forKey: .string)
+      let loc = try container.decode(SourceLocation.self, forKey: .location)
+      self = .insert(loc, string)
+    case "replace": 
+      let string = try container.decode(String.self, forKey: .string)
+      let range = try container.decode(SourceRange.self, forKey: .range)
+      self = .replace(range, string)
+    default:
+      fatalError("unknown FixIt type \(type)")
+    }
+  }
+
+  public func encode(to encoder: Encoder) throws {
+    var container = encoder.container(keyedBy: CodingKeys.self)
+    switch self {
+    case let .remove(range):
+      try container.encode(range, forKey: .range)
+    case let .insert(location, string):
+      try container.encode(location, forKey: .location)
+      try container.encode(string, forKey: .string)
+    case let .replace(range, string):
+      try container.encode(range, forKey: .range)
+      try container.encode(string, forKey: .string)
+    }
+  }
+
+  /// The source range associated with a FixIt. If this is an insertion,
+  /// it is a range with the same start and end location.
+  public var range: SourceRange {
+    switch self {
+    case .remove(let range): return range
+    case .replace(let range, _): return range
+    case .insert(let loc, _): return SourceRange(start: loc, end: loc)
+    }
+  }
+
+  /// The text associated with this FixIt. If this is a removal, the text is
+  /// the empty string.
+  public var text: String {
+    switch self {
+    case .remove(_): return ""
+    case .insert(_, let text), .replace(_, let text): return text
+    }
+  }
+}
+
+/// A Note attached to a Diagnostic. This provides more context for a specific
+/// error, and optionally allows for FixIts.
+public struct Note: Codable {
+  /// The note's message.
+  public let message: Diagnostic.Message
+
+  /// The source location where the note should point.
+  public let location: SourceLocation?
+
+  /// An array of source ranges that should be highlighted.
+  public let highlights: [SourceRange]
+
+  /// An array of FixIts that apply to this note.
+  public let fixIts: [FixIt]
+
+  /// Constructs a new Note from the constituent parts.
+  internal init(message: Diagnostic.Message, location: SourceLocation?,
+                highlights: [SourceRange], fixIts: [FixIt]) {
+    precondition(message.severity == .note,
+                 "notes can only have the `note` severity")
+    self.message = message
+    self.location = location
+    self.highlights = highlights
+    self.fixIts = fixIts
+  }
+
+  /// Converts this Note to a Diagnostic for serialization.
+  func asDiagnostic() -> Diagnostic {
+    return Diagnostic(message: message, location: location, notes: [],
+                      highlights: highlights, fixIts: fixIts)
+  }
+}
+
+/// A Diagnostic message that can be emitted regarding some piece of code.
+public struct Diagnostic: Codable {
+  public struct Message: Codable {
+    /// The severity of diagnostic. This can be note, error, or warning.
+    public let severity: Severity
+
+    /// A string containing the contents of the diagnostic.
+    public let text: String
+
+    /// Creates a diagnostic message with the provided severity and text.
+    public init(_ severity: Severity, _ text: String) {
+      self.severity = severity
+      self.text = text
+    }
+  }
+
+  // These values must match clang/Frontend/SerializedDiagnostics.h
+  /// The severity of the diagnostic.
+  public enum Severity: UInt8, Codable {
+    case note = 1
+    case warning = 2
+    case error = 3
+  }
+
+  /// The diagnostic's message.
+  public let message: Message
+
+  /// The location the diagnostic should point.
+  public let location: SourceLocation?
+
+  /// An array of notes providing more context for this diagnostic.
+  public let notes: [Note]
+
+  /// An array of source ranges to highlight.
+  public let highlights: [SourceRange]
+
+  /// An array of possible FixIts to apply to this diagnostic.
+  public let fixIts: [FixIt]
+
+  /// A diagnostic builder that 
+  public struct Builder {
+    /// An in-flight array of notes.
+    internal var notes = [Note]()
+
+    /// An in-flight array of highlighted source ranges.
+    internal var highlights = [SourceRange]()
+
+    /// An in-flight array of FixIts.
+    internal var fixIts = [FixIt]()
+
+    internal init() {}
+
+    /// Adds a Note to the diagnostic builder.
+    /// - parameters:
+    ///   - message: The message associated with the note. This must have the
+    ///              `.note` severity.
+    ///   - location: The source location to which this note is attached.
+    ///   - highlights: Any source ranges that should be highlighted by this
+    ///                 note.
+    ///   - fixIts: Any FixIts that should be attached to this note.
+    public mutating func note(_ message: Message,
+                              location: SourceLocation? = nil,
+                              highlights: [SourceRange] = [], 
+                              fixIts: [FixIt] = []) {
+      self.notes.append(Note(message: message, location: location,
+                             highlights: highlights, fixIts: fixIts))
+    }
+
+    /// Adds the provided source ranges as highlights of this diagnostic.
+    public mutating func highlight(_ ranges: SourceRange...) {
+      self.highlights += ranges
+    }
+
+    /// Adds a FixIt to remove the contents of the provided SourceRange.
+    /// When applied, this FixIt will delete the characters corresponding to
+    /// this range in the original source file.
+    public mutating func fixItRemove(_ sourceRange: SourceRange) {
+      fixIts.append(.remove(sourceRange))
+    }
+
+    /// Adds a FixIt to insert the provided text at the provided SourceLocation
+    /// in the file where the location resides.
+    public mutating
+    func fixItInsert(_ text: String, at sourceLocation: SourceLocation) {
+      fixIts.append(.insert(sourceLocation, text))
+    }
+
+    /// Adds a FixIt to replace the contents of the source file corresponding
+    /// to the provided SourceRange with the provided text.
+    public mutating 
+    func fixItReplace(_ sourceRange: SourceRange, with text: String) {
+      fixIts.append(.replace(sourceRange, text))
+    }
+  }
+
+  /// Creates a new Diagnostic with the provided message, pointing to the
+  /// provided location (if any).
+  /// This initializer also takes a closure that will be passed a Diagnostic
+  /// Builder as an inout parameter. Use this closure to add notes, highlights,
+  /// and FixIts to the diagnostic through the Builder's API.
+  /// - parameters:
+  ///   - message: The diagnostic's message.
+  ///   - location: The location the diagnostic is attached to.
+  ///   - actions: A closure that's used to attach notes and highlights to
+  ///              diagnostics.
+  init(message: Message, location: SourceLocation?,
+       actions: ((inout Builder) -> Void)?) {
+    var builder = Builder()
+    actions?(&builder)
+    self.init(message: message, location: location, notes: builder.notes,
+              highlights: builder.highlights, fixIts: builder.fixIts)
+  }
+
+  /// Creates a new Diagnostic with the provided message, pointing to the
+  /// provided location (if any).
+  /// - parameters:
+  ///   - message: The diagnostic's message.
+  ///   - location: The location the diagnostic is attached to.
+  ///   - highlights: An array of SourceRanges which will be highlighted when
+  ///                 the diagnostic is presented.
+  init(message: Message, location: SourceLocation?, notes: [Note],
+       highlights: [SourceRange], fixIts: [FixIt]) {
+    self.message = message
+    self.location = location
+    self.notes = notes
+    self.highlights = highlights
+    self.fixIts = fixIts
+  }
+}
diff --git a/tools/SwiftSyntax/DiagnosticConsumer.swift b/tools/SwiftSyntax/DiagnosticConsumer.swift
new file mode 100644
index 0000000..5851547
--- /dev/null
+++ b/tools/SwiftSyntax/DiagnosticConsumer.swift
@@ -0,0 +1,24 @@
+//===---------- DiagnosticConsumer.swift - Diagnostic Consumer ------------===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+// This file provides the DiagnosticConsumer protocol.
+//===----------------------------------------------------------------------===//
+
+/// An object that intends to receive notifications when diagnostics are
+/// emitted.
+public protocol DiagnosticConsumer {
+  /// Handle the provided diagnostic which has just been registered with the
+  /// DiagnosticEngine.
+  func handle(_ diagnostic: Diagnostic)
+
+  /// Finalize the consumption of diagnostics, flushing to disk if necessary.
+  func finalize()
+}
diff --git a/tools/SwiftSyntax/DiagnosticEngine.swift b/tools/SwiftSyntax/DiagnosticEngine.swift
new file mode 100644
index 0000000..2f653ce
--- /dev/null
+++ b/tools/SwiftSyntax/DiagnosticEngine.swift
@@ -0,0 +1,61 @@
+//===------------ DiagnosticEngine.swift - Diagnostic Engine --------------===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+// This file provides the DiagnosticEngine, the class used to register
+// and output diagnostics.
+//===----------------------------------------------------------------------===//
+
+import Foundation
+
+/// The DiagnosticEngine allows Swift tools to emit diagnostics.
+public class DiagnosticEngine {
+  /// Creates a new DiagnosticEngine with no diagnostics.
+  public init() {
+  }
+
+  /// The list of consumers of the diagnostic passing through this engine.
+  internal var consumers = [DiagnosticConsumer]()
+
+  public private(set) var diagnostics = [Diagnostic]()
+
+  /// Adds the provided consumer to the consumers list.
+  func addConsumer(_ consumer: DiagnosticConsumer) {
+    consumers.append(consumer)
+
+    // Start the consumer with all previous diagnostics.
+    for diagnostic in diagnostics {
+      consumer.handle(diagnostic)
+    }
+  }
+
+  /// Registers a diagnostic with the diagnostic engine.
+  /// - parameters:
+  ///   - message: The message for the diagnostic. This message includes
+  ///              a severity and text that will be conveyed when the diagnostic
+  ///              is serialized.
+  public func diagnose(_ message: Diagnostic.Message,
+                       location: SourceLocation? = nil,
+                       actions: ((inout Diagnostic.Builder) -> Void)? = nil) {
+    let diagnostic = Diagnostic(message: message, location: location, 
+                                actions: actions)
+    diagnostics.append(diagnostic)
+    for consumer in consumers {
+      consumer.handle(diagnostic)
+    }
+  }
+
+  /// Tells each consumer to finalize their diagnostic output.
+  deinit {
+    for consumer in consumers {
+      consumer.finalize()
+    }
+  }
+}
diff --git a/tools/SwiftSyntax/JSONDiagnosticConsumer.swift b/tools/SwiftSyntax/JSONDiagnosticConsumer.swift
new file mode 100644
index 0000000..24e7351
--- /dev/null
+++ b/tools/SwiftSyntax/JSONDiagnosticConsumer.swift
@@ -0,0 +1,79 @@
+//===--- JSONDiagnosticConsumer.swift - JSON Serializer for Diagnostics ---===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+// This file provides a JSON serializer for compiler diagnostics emitted using
+// the DiagnosticEngine.
+//===----------------------------------------------------------------------===//
+
+import Foundation
+
+public final class JSONDiagnosticConsumer: DiagnosticConsumer {
+  /// Enumerates the possible places this consumer might output diagnostics.
+  private enum OutputFormat {
+    case url(URL)
+    case stdout
+  }
+
+  /// The current set of diagnostics that have been emitted.
+  private var diagnostics = [Diagnostic]()
+
+  /// The output format this consumer will output the generated JSON to.
+  private let outputFormat: OutputFormat
+
+  /// Creates a JSONDiagnosticConsumer that will output the generated JSON
+  /// to a file at the given URL.
+  /// - parameter outputURL: The URL that the consumer will write JSON
+  ///                        diagnostics to.
+  /// - note: If a file exists at the URL already, it will be overwritten.
+  public init(outputURL: URL) {
+    self.outputFormat = .url(outputURL)
+  }
+
+  /// Creates a JSONDiagnosticConsumer that will output the generated JSON
+  /// to standard output.
+  public init() {
+    self.outputFormat = .stdout
+  }
+
+  /// Adds the diagnostic to the list of registered diagnostics.
+  public func handle(_ diagnostic: Diagnostic) {
+    self.diagnostics.append(diagnostic)
+  }
+
+  /// Writes the contents of the diagnostics as JSON out to the specified
+  /// output location.
+  public func finalize() {
+    do {
+      let encoder = JSONEncoder()
+      encoder.outputFormatting = .prettyPrinted
+      let data = try encoder.encode(diagnostics)
+      switch outputFormat {
+      case .url(let url):
+        if FileManager.default.fileExists(atPath: url.path) {
+          try FileManager.default.removeItem(at: url)
+        }
+        FileManager.default.createFile(atPath: url.path, contents: data)
+      case .stdout:
+        FileHandle.standardOutput.write(data)
+      }
+    } catch {
+      let dummyEngine = DiagnosticEngine()
+      let printingConsumer = PrintingDiagnosticConsumer()
+      dummyEngine.addConsumer(printingConsumer)
+      dummyEngine.diagnose(.couldNotOutputJSON)
+    }
+  }
+}
+
+extension Diagnostic.Message {
+    static let couldNotOutputJSON =
+        Diagnostic.Message(.error, "failed emitting JSON diagnostics")
+}
\ No newline at end of file
diff --git a/tools/SwiftSyntax/PrintingDiagnosticConsumer.swift b/tools/SwiftSyntax/PrintingDiagnosticConsumer.swift
new file mode 100644
index 0000000..5afbc56
--- /dev/null
+++ b/tools/SwiftSyntax/PrintingDiagnosticConsumer.swift
@@ -0,0 +1,59 @@
+//===-- PrintingDiagnosticConsumer.swift - Printing Diagnsostic Consumer --===//
+//
+// This source file is part of the Swift.org open source project
+//
+// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+//
+//===----------------------------------------------------------------------===//
+// This file provides a diagnostic consumer that formats and prints errors to
+// stderr.
+//===----------------------------------------------------------------------===//
+
+import Foundation
+
+/// PrintingDiagnosticConsumer formats diagnostics and prints them to the
+/// console.
+public class PrintingDiagnosticConsumer: DiagnosticConsumer {
+  /// Creates a new PrintingDiagnosticConsumer.
+  public init() {
+  }
+
+  /// Writes the text of the diagnostic to stderr.
+  func write<T: CustomStringConvertible>(_ msg: T) {
+    FileHandle.standardError.write("\(msg)".data(using: .utf8)!)
+  }
+
+  /// Prints the contents of a diagnostic to stderr.
+  public func handle(_ diagnostic: Diagnostic) {
+    write(diagnostic)
+    for note in diagnostic.notes {
+      write(note.asDiagnostic())
+    }
+  }
+
+  /// Prints each of the fields in a diagnositic to stderr.
+  public func write(_ diagnostic: Diagnostic) {
+    if let loc = diagnostic.location {
+      write("\(loc.file):\(loc.line):\(loc.column): ")
+    } else {
+      write("<unknown>:0:0: ")
+    }
+    switch diagnostic.message.severity {
+    case .note: write("note: ")
+    case .warning: write("warning: ")
+    case .error: write("error: ")
+    }
+    write(diagnostic.message.text)
+    write("\n")
+
+    // TODO: Write original file contents out and highlight them.
+  }
+
+  public func finalize() {
+    // Do nothing
+  }
+}
diff --git a/tools/SwiftSyntax/SwiftSyntax.swift b/tools/SwiftSyntax/SwiftSyntax.swift
index c3a3244..b736d35 100644
--- a/tools/SwiftSyntax/SwiftSyntax.swift
+++ b/tools/SwiftSyntax/SwiftSyntax.swift
@@ -14,6 +14,12 @@
 
 import Foundation
 
+#if os(macOS)
+import Darwin
+#elseif os(Linux)
+import Glibc
+#endif
+
 /// A list of possible errors that could be encountered while parsing a
 /// Syntax tree.
 public enum ParserError: Error {
diff --git a/tools/SwiftSyntax/SyntaxFactory.swift.gyb b/tools/SwiftSyntax/SyntaxFactory.swift.gyb
index 0a72dfb..c200fa5 100644
--- a/tools/SwiftSyntax/SyntaxFactory.swift.gyb
+++ b/tools/SwiftSyntax/SyntaxFactory.swift.gyb
@@ -120,21 +120,18 @@
                          rightParen: makeRightParenToken())
   }
 
-  public static func makeTupleTypeElement(label: TokenSyntax?,
+  public static func makeTupleTypeElement(name: TokenSyntax?,
     colon: TokenSyntax?, type: TypeSyntax,
-    comma: TokenSyntax?) -> TupleTypeElementSyntax {
-    let annotation = makeTypeAnnotation(attributes: makeBlankAttributeList(),
-                                        inOutKeyword: nil,
-                                        type: type)
-    return makeTupleTypeElement(label: label, colon: colon, 
-                                typeAnnotation: annotation,
-                                comma: comma)
+    trailingComma: TokenSyntax?) -> TupleTypeElementSyntax {
+    return makeTupleTypeElement(inOut: nil, name: name, secondName: nil,
+                                colon: colon, type: type, ellipsis: nil,
+                                initializer: nil, trailingComma: trailingComma)
   }
 
   public static func makeTupleTypeElement(type: TypeSyntax,
-    comma: TokenSyntax?) -> TupleTypeElementSyntax  {
-    return makeTupleTypeElement(label: nil, colon: nil, 
-                                type: type, comma: comma)
+    trailingComma: TokenSyntax?) -> TupleTypeElementSyntax  {
+    return makeTupleTypeElement(name: nil, colon: nil, 
+                                type: type, trailingComma: trailingComma)
   }
 
   public static func makeGenericParameter(name: TokenSyntax,
diff --git a/tools/SwiftSyntax/Trivia.swift b/tools/SwiftSyntax/Trivia.swift
index fb54aac..6986b1f 100644
--- a/tools/SwiftSyntax/Trivia.swift
+++ b/tools/SwiftSyntax/Trivia.swift
@@ -43,6 +43,9 @@
     case "Newline":
       let value = try container.decode(Int.self, forKey: .value)
       self = .newlines(value)
+    case "CarriageReturn":
+      let value = try container.decode(Int.self, forKey: .value)
+      self = .carriageReturns(value)
     case "Backtick":
       let value = try container.decode(Int.self, forKey: .value)
       self = .backticks(value)
@@ -68,7 +71,7 @@
       throw DecodingError.valueNotFound(String.self, context)
     }
   }
-  
+
   public func encode(to encoder: Encoder) throws {
     var container = encoder.container(keyedBy: CodingKeys.self)
     switch self {
@@ -96,6 +99,9 @@
     case .newlines(let count):
       try container.encode("Newline", forKey: .kind)
       try container.encode(count, forKey: .value)
+    case .carriageReturns(let count):
+      try container.encode("CarriageReturn", forKey: .kind)
+      try container.encode(count, forKey: .value)
     case .spaces(let count):
       try container.encode("Space", forKey: .kind)
       try container.encode(count, forKey: .value)
@@ -105,10 +111,10 @@
     case .verticalTabs(let count):
       try container.encode("VerticalTab", forKey: .kind)
       try container.encode(count, forKey: .value)
-      
+
     }
   }
-  
+
   /// A space ' ' character.
   case spaces(Int)
 
@@ -123,7 +129,10 @@
 
   /// A newline '\n' character.
   case newlines(Int)
-  
+
+  /// A carriage-return '\r' character.
+  case carriageReturns(Int)
+
   /// A backtick '`' character, used to escape identifiers.
   case backticks(Int)
 
@@ -158,6 +167,7 @@
     case let .verticalTabs(count): printRepeated("\u{2B7F}", count: count)
     case let .formfeeds(count): printRepeated("\u{240C}", count: count)
     case let .newlines(count): printRepeated("\n", count: count)
+    case let .carriageReturns(count): printRepeated("\r", count: count)
     case let .backticks(count): printRepeated("`", count: count)
     case let .lineComment(text),
          let .blockComment(text),
@@ -167,6 +177,47 @@
       target.write(text)
     }
   }
+
+  /// Computes the information from this trivia to inform the source locations
+  /// of the associated tokens.
+  /// Specifically, walks through the trivia and keeps track of every newline
+  /// to give a number of how many newlines and UTF8 characters appear in the
+  /// trivia, along with the UTF8 offset of the last column.
+  func characterSizes() -> (lines: Int, lastColumn: Int, utf8Length: Int) {
+    switch self {
+    case .spaces(let n),
+         .tabs(let n),
+         .verticalTabs(let n),
+         .formfeeds(let n),
+         .backticks(let n):
+      return (lines: 0, lastColumn: n, utf8Length: n)
+    case .newlines(let n):
+      return (lines: n, lastColumn: 0, utf8Length: n)
+    case .carriageReturns(let n):
+      return (lines: n, lastColumn: 0, utf8Length: n)
+    case .lineComment(let text),
+         .docLineComment(let text):
+      let length = text.utf8.count
+      return (lines: 0, lastColumn: length, utf8Length: length)
+    case .blockComment(let text),
+         .docBlockComment(let text),
+         .garbageText(let text):
+      var lines = 0
+      var col = 0
+      var total = 0
+      for char in text.utf8 {
+        total += 1
+        if char == 0x0a /* ASCII newline */
+          || char == 0x0d /* ASCII carriage-return */{
+          col = 0
+          lines += 1
+        } else {
+          col += 1
+        }
+      }
+      return (lines: lines, lastColumn: col, utf8Length: total)
+    }
+  }
 }
 
 /// A collection of leading or trailing trivia. This is the main data structure
@@ -178,7 +229,7 @@
   public init(pieces: [TriviaPiece]) {
     self.pieces = pieces
   }
-  
+
   public init(from decoder: Decoder) throws {
     var container = try decoder.unkeyedContainer()
     var pieces = [TriviaPiece]()
@@ -187,7 +238,7 @@
     }
     self.pieces = pieces
   }
-  
+
   public func encode(to encoder: Encoder) throws {
     var container = encoder.unkeyedContainer()
     for piece in pieces {
@@ -232,7 +283,13 @@
   public static func newlines(_ count: Int) -> Trivia {
     return [.newlines(count)]
   }
-  
+
+  /// Return a piece of trivia for some number of carriage-return characters
+  /// in a row.
+  public static func carriageReturns(_ count: Int) -> Trivia {
+    return [.carriageReturns(count)]
+  }
+
   /// Return a piece of trivia for some number of backtick '`' characters
   /// in a row.
   public static func backticks(_ count: Int) -> Trivia {
@@ -263,6 +320,20 @@
   public static func garbageText(_ text: String) -> Trivia {
     return [.garbageText(text)]
   }
+
+  /// Computes the total sizes and offsets of all pieces in this Trivia.
+  func characterSizes() -> (lines: Int, lastColumn: Int, utf8Length: Int) {
+    var lines = 0
+    var lastColumn = 0
+    var length = 0
+    for piece in pieces {
+      let (ln, col, len) = piece.characterSizes()
+      lines += ln
+      lastColumn = col
+      length += len
+    }
+    return (lines: lines, lastColumn: lastColumn, utf8Length: length)
+  }
 }
 
 /// Conformance for Trivia to the Collection protocol.
@@ -270,15 +341,15 @@
   public var startIndex: Int {
     return pieces.startIndex
   }
-  
+
   public var endIndex: Int {
     return pieces.endIndex
   }
-  
+
   public func index(after i: Int) -> Int {
     return pieces.index(after: i)
   }
-  
+
   public subscript(_ index: Int) -> TriviaPiece {
     return pieces[index]
   }
diff --git a/tools/driver/modulewrap_main.cpp b/tools/driver/modulewrap_main.cpp
index 397a394..52e555d 100644
--- a/tools/driver/modulewrap_main.cpp
+++ b/tools/driver/modulewrap_main.cpp
@@ -43,7 +43,7 @@
   std::vector<std::string> InputFilenames;
 
 public:
-  bool hasUniqueInputFilename() const { return InputFilenames.size() == 1; }
+  bool hasSingleInput() const { return InputFilenames.size() == 1; }
   const std::string &getFilenameOfFirstInput() const {
     return InputFilenames[0];
   }
@@ -131,7 +131,7 @@
     return 1;
   }
 
-  if (!Invocation.hasUniqueInputFilename()) {
+  if (!Invocation.hasSingleInput()) {
     Instance.getDiags().diagnose(SourceLoc(),
                                  diag::error_mode_requires_one_input_file);
     return 1;
diff --git a/tools/sil-func-extractor/SILFunctionExtractor.cpp b/tools/sil-func-extractor/SILFunctionExtractor.cpp
index 0a812af..14131b1 100644
--- a/tools/sil-func-extractor/SILFunctionExtractor.cpp
+++ b/tools/sil-func-extractor/SILFunctionExtractor.cpp
@@ -256,8 +256,9 @@
 
   serialization::ExtendedValidationInfo extendedInfo;
   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
-      Invocation.setUpInputForSILTool(InputFilename, ModuleName, true,
-                                      extendedInfo);
+      Invocation.setUpInputForSILTool(InputFilename, ModuleName,
+                                      /*alwaysSetModuleToMain*/ true,
+                                      /*bePrimary*/ false, extendedInfo);
   if (!FileBufOrErr) {
     fprintf(stderr, "Error! Failed to open file: %s\n", InputFilename.c_str());
     exit(-1);
diff --git a/tools/sil-llvm-gen/SILLLVMGen.cpp b/tools/sil-llvm-gen/SILLLVMGen.cpp
index 5498216..e59f796 100644
--- a/tools/sil-llvm-gen/SILLLVMGen.cpp
+++ b/tools/sil-llvm-gen/SILLLVMGen.cpp
@@ -169,8 +169,9 @@
 
   serialization::ExtendedValidationInfo extendedInfo;
   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
-      Invocation.setUpInputForSILTool(InputFilename, ModuleName, false,
-                                      extendedInfo);
+      Invocation.setUpInputForSILTool(InputFilename, ModuleName,
+                                      /*alwaysSetModuleToMain*/ false,
+                                      /*bePrimary*/ !PerformWMO, extendedInfo);
   if (!FileBufOrErr) {
     fprintf(stderr, "Error! Failed to open file: %s\n", InputFilename.c_str());
     exit(-1);
@@ -180,11 +181,6 @@
   PrintingDiagnosticConsumer PrintDiags;
   CI.addDiagnosticConsumer(&PrintDiags);
 
-  if (!PerformWMO) {
-    Invocation.getFrontendOptions().Inputs.setPrimaryInputForInputFilename(
-        InputFilename);
-  }
-
   if (CI.setup(Invocation))
     return 1;
 
diff --git a/tools/sil-nm/SILNM.cpp b/tools/sil-nm/SILNM.cpp
index b3eddc9..6e9d6ce 100644
--- a/tools/sil-nm/SILNM.cpp
+++ b/tools/sil-nm/SILNM.cpp
@@ -170,8 +170,9 @@
 
   serialization::ExtendedValidationInfo extendedInfo;
   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
-      Invocation.setUpInputForSILTool(InputFilename, ModuleName, true,
-                                      extendedInfo);
+      Invocation.setUpInputForSILTool(InputFilename, ModuleName,
+                                      /*alwaysSetModuleToMain*/ true,
+                                      /*bePrimary*/ false, extendedInfo);
   if (!FileBufOrErr) {
     fprintf(stderr, "Error! Failed to open file: %s\n", InputFilename.c_str());
     exit(-1);
diff --git a/tools/sil-opt/SILOpt.cpp b/tools/sil-opt/SILOpt.cpp
index 128d14c..12e0f03 100644
--- a/tools/sil-opt/SILOpt.cpp
+++ b/tools/sil-opt/SILOpt.cpp
@@ -195,12 +195,6 @@
     "assume-parsing-unqualified-ownership-sil", llvm::cl::Hidden, llvm::cl::init(false),
     llvm::cl::desc("Assume all parsed functions have unqualified ownership"));
 
-static llvm::cl::opt<bool>
-EnableExperimentalConditionalConformances(
-  "enable-experimental-conditional-conformances", llvm::cl::Hidden,
-  llvm::cl::init(false),
-  llvm::cl::desc("Enable experimental implementation of SE-0143: Conditional Conformances"));
-
 /// Regular expression corresponding to the value given in one of the
 /// -pass-remarks* command line flags. Passes whose name matches this regexp
 /// will emit a diagnostic.
@@ -304,8 +298,7 @@
     llvm::Triple(Target).isOSDarwin();
 
   Invocation.getLangOptions().EnableSILOpaqueValues = EnableSILOpaqueValues;
-  Invocation.getLangOptions().EnableConditionalConformances |=
-    EnableExperimentalConditionalConformances;
+
   Invocation.getLangOptions().OptimizationRemarkPassedPattern =
       createOptRemarkRegex(PassRemarksPassed);
   Invocation.getLangOptions().OptimizationRemarkMissedPattern =
@@ -351,8 +344,9 @@
 
   serialization::ExtendedValidationInfo extendedInfo;
   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
-      Invocation.setUpInputForSILTool(InputFilename, ModuleName, false,
-                                      extendedInfo);
+      Invocation.setUpInputForSILTool(InputFilename, ModuleName,
+                                      /*alwaysSetModuleToMain*/ false,
+                                      /*bePrimary*/ !PerformWMO, extendedInfo);
   if (!FileBufOrErr) {
     fprintf(stderr, "Error! Failed to open file: %s\n", InputFilename.c_str());
     exit(-1);
@@ -362,11 +356,6 @@
   PrintingDiagnosticConsumer PrintDiags;
   CI.addDiagnosticConsumer(&PrintDiags);
 
-  if (!PerformWMO) {
-    Invocation.getFrontendOptions().Inputs.setPrimaryInputForInputFilename(
-        InputFilename);
-  }
-
   if (CI.setup(Invocation))
     return 1;
 
diff --git a/tools/swift-ide-test/swift-ide-test.cpp b/tools/swift-ide-test/swift-ide-test.cpp
index d4a4c7b..a6b1568 100644
--- a/tools/swift-ide-test/swift-ide-test.cpp
+++ b/tools/swift-ide-test/swift-ide-test.cpp
@@ -333,6 +333,11 @@
     llvm::cl::desc(
         "Include initializers when completing a postfix expression"),
     llvm::cl::cat(Category));
+static llvm::cl::opt<bool> CodeCompleteCallPatternHeuristics(
+    "code-complete-call-pattern-heuristics",
+    llvm::cl::desc(
+        "Use heuristics to guess whether we want call pattern completions"),
+    llvm::cl::cat(Category));
 
 static llvm::cl::opt<bool>
 ObjCForwardDeclarations("enable-objc-forward-declarations",
@@ -717,7 +722,7 @@
 
   Invocation.setCodeCompletionFactory(CompletionCallbacksFactory.get());
   if (!SecondSourceFileName.empty()) {
-    Invocation.addInputFilename(SecondSourceFileName);
+    Invocation.getFrontendOptions().Inputs.addInputFile(SecondSourceFileName);
   }
   CompilerInstance CI;
 
@@ -943,7 +948,7 @@
                             bool RunTypeChecker,
                             bool Playground) {
   CompilerInvocation Invocation(InitInvok);
-  Invocation.addInputFilename(SourceFilename);
+  Invocation.getFrontendOptions().Inputs.addInputFile(SourceFilename);
   Invocation.getLangOptions().DisableAvailabilityChecking = false;
 
   CompilerInstance CI;
@@ -986,7 +991,7 @@
   }
 
   CompilerInvocation Invocation(InitInvok);
-  Invocation.addInputFilename(SourceFilename);
+  Invocation.getFrontendOptions().Inputs.addInputFile(SourceFilename);
 
   CompilerInstance CI;
 
@@ -1164,7 +1169,7 @@
                                  StringRef SourceFilename) {
   CompilerInvocation Invocation(InitInvok);
   Invocation.getLangOptions().KeepSyntaxInfoInSourceFile = true;
-  Invocation.addInputFilename(SourceFilename);
+  Invocation.getFrontendOptions().Inputs.addInputFile(SourceFilename);
 
   CompilerInstance CI;
 
@@ -1420,7 +1425,7 @@
                                 StringRef SourceFilename,
                                 bool TerminalOutput) {
   CompilerInvocation Invocation(InitInvok);
-  Invocation.addInputFilename(SourceFilename);
+  Invocation.getFrontendOptions().Inputs.addInputFile(SourceFilename);
 
   CompilerInstance CI;
 
@@ -1485,7 +1490,7 @@
                       StringRef MangledNameToFind,
                       StringRef DebugClientDiscriminator) {
   CompilerInvocation Invocation(InitInvok);
-  Invocation.addInputFilename(SourceFilename);
+  Invocation.getFrontendOptions().Inputs.addInputFile(SourceFilename);
 
   CompilerInstance CI;
 
@@ -1916,8 +1921,7 @@
                                      StringRef SourceFilename,
                                      bool AnnotatePrint) {
   CompilerInvocation Invocation(InitInvok);
-  Invocation.addInputFilename(SourceFilename);
-  Invocation.getFrontendOptions().Inputs.setPrimaryInputToFirstFile();
+  Invocation.getFrontendOptions().Inputs.addPrimaryInputFile(SourceFilename);
   Invocation.getLangOptions().AttachCommentsToDecls = true;
   CompilerInstance CI;
   // Display diagnostics to stderr.
@@ -1947,8 +1951,7 @@
                         const PrintOptions &Options,
                         bool AnnotatePrint) {
   CompilerInvocation Invocation(InitInvok);
-  Invocation.addInputFilename(SourceFilename);
-  Invocation.getFrontendOptions().Inputs.setPrimaryInputToFirstFile();
+  Invocation.getFrontendOptions().Inputs.addPrimaryInputFile(SourceFilename);
   Invocation.getLangOptions().AttachCommentsToDecls = true;
   CompilerInstance CI;
   // Display diagnostics to stderr.
@@ -2059,7 +2062,7 @@
                         StringRef SourceFilename,
                         bool FullyQualifiedTypes) {
   CompilerInvocation Invocation(InitInvok);
-  Invocation.addInputFilename(SourceFilename);
+  Invocation.getFrontendOptions().Inputs.addInputFile(SourceFilename);
 
   CompilerInstance CI;
   // Display diagnostics to stderr.
@@ -2288,7 +2291,7 @@
 static int doDumpComments(const CompilerInvocation &InitInvok,
                           StringRef SourceFilename) {
   CompilerInvocation Invocation(InitInvok);
-  Invocation.addInputFilename(SourceFilename);
+  Invocation.getFrontendOptions().Inputs.addInputFile(SourceFilename);
   Invocation.getLangOptions().AttachCommentsToDecls = true;
   CompilerInstance CI;
   // Display diagnostics to stderr.
@@ -2310,7 +2313,7 @@
                            StringRef SourceFilename,
                            StringRef CommentsXMLSchema) {
   CompilerInvocation Invocation(InitInvok);
-  Invocation.addInputFilename(SourceFilename);
+  Invocation.getFrontendOptions().Inputs.addInputFile(SourceFilename);
   Invocation.getLangOptions().AttachCommentsToDecls = true;
   Invocation.getLangOptions().EnableObjCAttrRequiresFoundation = false;
 
@@ -2440,7 +2443,7 @@
   if (!Pair.hasValue())
     return 1;
   CompilerInvocation Invocation(InitInvok);
-  Invocation.addInputFilename(FileName);
+  Invocation.getFrontendOptions().Inputs.addInputFile(FileName);
   CompilerInstance CI;
   if (CI.setup(Invocation))
     return 1;
@@ -2486,7 +2489,7 @@
                                           const StringRef FileName,
                                           const StringRef Usr) {
   CompilerInvocation Invocation(InitInvok);
-  Invocation.addInputFilename(FileName);
+  Invocation.getFrontendOptions().Inputs.addInputFile(FileName);
   CompilerInstance CI;
   if (CI.setup(Invocation))
     return 1;
@@ -2645,7 +2648,7 @@
 static int doReconstructType(const CompilerInvocation &InitInvok,
                              StringRef SourceFilename) {
   CompilerInvocation Invocation(InitInvok);
-  Invocation.addInputFilename(SourceFilename);
+  Invocation.getFrontendOptions().Inputs.addInputFile(SourceFilename);
   Invocation.getLangOptions().DisableAvailabilityChecking = false;
 
   CompilerInstance CI;
@@ -2679,7 +2682,7 @@
   auto StartLineCol = StartOp.getValue();
   auto EndLineCol = EndOp.getValue();
   CompilerInvocation Invocation(InitInvok);
-  Invocation.addInputFilename(SourceFileName);
+  Invocation.getFrontendOptions().Inputs.addInputFile(SourceFileName);
   Invocation.getLangOptions().DisableAvailabilityChecking = false;
   Invocation.getLangOptions().KeepSyntaxInfoInSourceFile = true;
 
@@ -2781,7 +2784,7 @@
                                 StringRef SourceFileName, bool indexLocals) {
 
   CompilerInvocation Invocation(InitInvok);
-  Invocation.addInputFilename(SourceFileName);
+  Invocation.getFrontendOptions().Inputs.addInputFile(SourceFileName);
   Invocation.getLangOptions().DisableAvailabilityChecking = false;
   Invocation.getLangOptions().TypoCorrectionLimit = 0;
 
@@ -2846,7 +2849,7 @@
 static int doPrintUSRs(const CompilerInvocation &InitInvok,
                        StringRef SourceFilename) {
   CompilerInvocation Invocation(InitInvok);
-  Invocation.addInputFilename(SourceFilename);
+  Invocation.getFrontendOptions().Inputs.addInputFile(SourceFilename);
 
   ClangImporterOptions &ImporterOpts = Invocation.getClangImporterOptions();
   ImporterOpts.DetailedPreprocessingRecord = true;
@@ -2992,7 +2995,7 @@
   CompilerInvocation InitInvok;
 
   for (auto &File : options::InputFilenames)
-    InitInvok.addInputFilename(File);
+    InitInvok.getFrontendOptions().Inputs.addInputFile(File);
   if (!options::InputFilenames.empty())
     InitInvok.setInputKind(InputFileKind::IFK_Swift_Library);
 
@@ -3047,6 +3050,8 @@
     !options::DisableAccessControl;
   InitInvok.getLangOptions().CodeCompleteInitsInPostfixExpr |=
       options::CodeCompleteInitsInPostfixExpr;
+  InitInvok.getLangOptions().CodeCompleteCallPatternHeuristics |=
+      options::CodeCompleteCallPatternHeuristics;
   InitInvok.getLangOptions().InferImportAsMember |=
     options::InferImportAsMember;
   InitInvok.getLangOptions().EnableSwift3ObjCInference =
diff --git a/tools/swift-refactor/swift-refactor.cpp b/tools/swift-refactor/swift-refactor.cpp
index fc048f6..e40c7a1 100644
--- a/tools/swift-refactor/swift-refactor.cpp
+++ b/tools/swift-refactor/swift-refactor.cpp
@@ -229,12 +229,12 @@
   Invocation.setMainExecutablePath(
     llvm::sys::fs::getMainExecutable(argv[0],
     reinterpret_cast<void *>(&anchorForGetMainExecutable)));
-  Invocation.addInputFilename(options::SourceFilename);
+  Invocation.getFrontendOptions().Inputs.addInputFile(options::SourceFilename);
   Invocation.getLangOptions().AttachCommentsToDecls = true;
   Invocation.getLangOptions().KeepSyntaxInfoInSourceFile = true;
 
   for (auto FileName : options::InputFilenames)
-    Invocation.addInputFilename(FileName);
+    Invocation.getFrontendOptions().Inputs.addInputFile(FileName);
   Invocation.setModuleName(options::ModuleName);
   CompilerInstance CI;
   // Display diagnostics to stderr.
diff --git a/tools/swift-syntax-test/swift-syntax-test.cpp b/tools/swift-syntax-test/swift-syntax-test.cpp
index 1bb6b73..cb7066f 100644
--- a/tools/swift-syntax-test/swift-syntax-test.cpp
+++ b/tools/swift-syntax-test/swift-syntax-test.cpp
@@ -135,7 +135,7 @@
                           const char *MainExecutablePath) {
   CompilerInvocation Invocation;
   Invocation.getLangOptions().KeepSyntaxInfoInSourceFile = true;
-  Invocation.addInputFilename(InputFileName);
+  Invocation.getFrontendOptions().Inputs.addInputFile(InputFileName);
   Invocation.setMainExecutablePath(
     llvm::sys::fs::getMainExecutable(MainExecutablePath,
       reinterpret_cast<void *>(&anchorForGetMainExecutable)));
diff --git a/unittests/Parse/CMakeLists.txt b/unittests/Parse/CMakeLists.txt
index 19dd7aa..b7c2f38 100644
--- a/unittests/Parse/CMakeLists.txt
+++ b/unittests/Parse/CMakeLists.txt
@@ -1,6 +1,7 @@
 add_swift_unittest(SwiftParseTests
   BuildConfigTests.cpp
   LexerTests.cpp
+  LexerTriviaTests.cpp
   TokenizerTests.cpp
 )
 
diff --git a/unittests/Parse/LexerTests.cpp b/unittests/Parse/LexerTests.cpp
index 31a2903..75cc8d3 100644
--- a/unittests/Parse/LexerTests.cpp
+++ b/unittests/Parse/LexerTests.cpp
@@ -111,6 +111,155 @@
   EXPECT_EQ(Toks[1].getLength(), 0U);
 }
 
+TEST_F(LexerTest, ContentStartHashbangSkip) {
+  const char *Source = "#!/usr/bin/swift\naaa";
+  
+  LangOptions LangOpts;
+  SourceManager SourceMgr;
+  unsigned BufferID = SourceMgr.addMemBufferCopy(StringRef(Source));
+  
+  Lexer L(LangOpts, SourceMgr, BufferID, /*Diags=*/nullptr, /*InSILMode=*/false);
+  
+  Token Tok;
+  
+  L.lex(Tok);
+  ASSERT_EQ(tok::identifier, Tok.getKind());
+  ASSERT_EQ("aaa", Tok.getText());
+  ASSERT_EQ(SourceMgr.getLocForOffset(BufferID, 17), Tok.getLoc());
+}
+
+TEST_F(LexerTest, ContentStartHashbangSkipUTF8BOM) {
+  const char *Source = "\xEF\xBB\xBF" "#!/usr/bin/swift\naaa";
+  
+  LangOptions LangOpts;
+  SourceManager SourceMgr;
+  unsigned BufferID = SourceMgr.addMemBufferCopy(StringRef(Source));
+  
+  Lexer L(LangOpts, SourceMgr, BufferID, /*Diags=*/nullptr, /*InSILMode=*/false);
+  
+  Token Tok;
+  
+  L.lex(Tok);
+  ASSERT_EQ(tok::identifier, Tok.getKind());
+  ASSERT_EQ("aaa", Tok.getText());
+  ASSERT_EQ(SourceMgr.getLocForOffset(BufferID, 20), Tok.getLoc());
+}
+
+TEST_F(LexerTest, ContentStartOperatorLeftBound) {
+  const char *Source = "+a";
+  
+  LangOptions LangOpts;
+  SourceManager SourceMgr;
+  unsigned BufferID = SourceMgr.addMemBufferCopy(StringRef(Source));
+  
+  Lexer L(LangOpts, SourceMgr, BufferID, /*Diags=*/nullptr, /*InSILMode=*/false);
+  
+  Token Tok;
+  
+  L.lex(Tok);
+  ASSERT_EQ(tok::oper_prefix, Tok.getKind());
+  ASSERT_EQ("+", Tok.getText());
+  ASSERT_EQ(SourceMgr.getLocForOffset(BufferID, 0), Tok.getLoc());
+}
+
+TEST_F(LexerTest, ContentStartOperatorLeftBoundUTF8BOM) {
+  const char *Source = "\xEF\xBB\xBF" "+a";
+  
+  LangOptions LangOpts;
+  SourceManager SourceMgr;
+  unsigned BufferID = SourceMgr.addMemBufferCopy(StringRef(Source));
+  
+  Lexer L(LangOpts, SourceMgr, BufferID, /*Diags=*/nullptr, /*InSILMode=*/false);
+  
+  Token Tok;
+  
+  L.lex(Tok);
+  ASSERT_EQ(tok::oper_prefix, Tok.getKind());
+  ASSERT_EQ("+", Tok.getText());
+  ASSERT_EQ(SourceMgr.getLocForOffset(BufferID, 3), Tok.getLoc());
+}
+
+TEST_F(LexerTest, ContentStartConflictMarker) {
+  const char *Source =
+    "<<<<<<< HEAD\n"
+    "xxx\n"
+    "=======\n"
+    "yyy\n"
+    ">>>>>>> 12345670\n"
+    "aaa";
+  
+  LangOptions LangOpts;
+  SourceManager SourceMgr;
+  unsigned BufferID = SourceMgr.addMemBufferCopy(StringRef(Source));
+  
+  Lexer L(LangOpts, SourceMgr, BufferID, /*Diags=*/nullptr, /*InSILMode=*/false);
+  
+  Token Tok;
+  
+  L.lex(Tok);
+  ASSERT_EQ(tok::identifier, Tok.getKind());
+  ASSERT_EQ("aaa", Tok.getText());
+}
+
+TEST_F(LexerTest, ContentStartConflictMarkerUTF8BOM) {
+  const char *Source =
+  "\xEF\xBB\xBF"
+  "<<<<<<< HEAD\n"
+  "xxx\n"
+  "=======\n"
+  "yyy\n"
+  ">>>>>>> 12345670\n"
+  "aaa";
+  
+  LangOptions LangOpts;
+  SourceManager SourceMgr;
+  unsigned BufferID = SourceMgr.addMemBufferCopy(StringRef(Source));
+  
+  Lexer L(LangOpts, SourceMgr, BufferID, /*Diags=*/nullptr, /*InSILMode=*/false);
+  
+  Token Tok;
+  
+  L.lex(Tok);
+  ASSERT_EQ(tok::identifier, Tok.getKind());
+  ASSERT_EQ("aaa", Tok.getText());
+}
+
+TEST_F(LexerTest, ContentStartTokenIsStartOfLine) {
+  const char *Source = "aaa";
+  
+  LangOptions LangOpts;
+  SourceManager SourceMgr;
+  unsigned BufferID = SourceMgr.addMemBufferCopy(StringRef(Source));
+  
+  Lexer L(LangOpts, SourceMgr, BufferID, /*Diags=*/nullptr, /*InSILMode=*/false);
+  
+  Token Tok;
+  
+  L.lex(Tok);
+  ASSERT_EQ(tok::identifier, Tok.getKind());
+  ASSERT_EQ("aaa", Tok.getText());
+  ASSERT_EQ(SourceMgr.getLocForOffset(BufferID, 0), Tok.getLoc());
+  ASSERT_TRUE(Tok.isAtStartOfLine());
+}
+
+TEST_F(LexerTest, ContentStartTokenIsStartOfLineUTF8BOM) {
+  const char *Source = "\xEF\xBB\xBF" "aaa";
+  
+  LangOptions LangOpts;
+  SourceManager SourceMgr;
+  unsigned BufferID = SourceMgr.addMemBufferCopy(StringRef(Source));
+  
+  Lexer L(LangOpts, SourceMgr, BufferID, /*Diags=*/nullptr, /*InSILMode=*/false);
+  
+  Token Tok;
+  
+  L.lex(Tok);
+  ASSERT_EQ(tok::identifier, Tok.getKind());
+  ASSERT_EQ("aaa", Tok.getText());
+  ASSERT_EQ(SourceMgr.getLocForOffset(BufferID, 3), Tok.getLoc());
+  ASSERT_TRUE(Tok.isAtStartOfLine());
+}
+
 TEST_F(LexerTest, RestoreBasic) {
   const char *Source = "aaa \t\0 bbb ccc";
 
@@ -132,7 +281,7 @@
   ASSERT_EQ("bbb", Tok.getText());
   ASSERT_FALSE(Tok.isAtStartOfLine());
 
-  Lexer::State S = L.getStateForBeginningOfToken(Tok);
+  LexerState S = L.getStateForBeginningOfToken(Tok);
 
   L.lex(Tok);
   ASSERT_EQ(tok::identifier, Tok.getKind());
@@ -179,7 +328,7 @@
   ASSERT_EQ("bbb", Tok.getText());
   ASSERT_TRUE(Tok.isAtStartOfLine());
 
-  Lexer::State S = L.getStateForBeginningOfToken(Tok);
+  LexerState S = L.getStateForBeginningOfToken(Tok);
 
   L.lex(Tok);
   ASSERT_EQ(tok::identifier, Tok.getKind());
@@ -231,7 +380,7 @@
   ASSERT_EQ("bbb", Tok.getText());
   ASSERT_FALSE(Tok.isAtStartOfLine());
 
-  Lexer::State S = L.getStateForBeginningOfToken(Tok);
+  LexerState S = L.getStateForBeginningOfToken(Tok);
 
   L.lex(Tok);
   ASSERT_EQ(tok::identifier, Tok.getKind());
@@ -260,55 +409,6 @@
   ASSERT_EQ(tok::eof, Tok.getKind());
 }
 
-TEST_F(LexerTest, RestoreWithTrivia) {
-  using namespace swift::syntax;
-  StringRef SourceStr = "aaa \n bbb /*C*/ccc";
-
-  LangOptions LangOpts;
-  SourceManager SourceMgr;
-  unsigned BufferID = SourceMgr.addMemBufferCopy(SourceStr);
-
-  Lexer L(LangOpts, SourceMgr, BufferID, /*Diags=*/nullptr, /*InSILMode=*/false,
-          CommentRetentionMode::AttachToNextToken,
-          TriviaRetentionMode::WithTrivia);
-
-  Token Tok;
-  Trivia LeadingTrivia, TrailingTrivia;
-
-  L.lex(Tok, LeadingTrivia, TrailingTrivia);
-  ASSERT_EQ(tok::identifier, Tok.getKind());
-  ASSERT_EQ("aaa", Tok.getText());
-  ASSERT_TRUE(Tok.isAtStartOfLine());
-  ASSERT_EQ(LeadingTrivia, Trivia());
-  ASSERT_EQ(TrailingTrivia, (Trivia{{TriviaPiece::spaces(1)}}));
-
-  L.lex(Tok, LeadingTrivia, TrailingTrivia);
-  ASSERT_EQ(tok::identifier, Tok.getKind());
-  ASSERT_EQ("bbb", Tok.getText());
-  ASSERT_TRUE(Tok.isAtStartOfLine());
-  ASSERT_EQ(LeadingTrivia,
-            (Trivia{{TriviaPiece::newlines(1), TriviaPiece::spaces(1)}}));
-  ASSERT_EQ(TrailingTrivia, (Trivia{{TriviaPiece::spaces(1)}}));
-
-  Lexer::State S = L.getStateForBeginningOfToken(Tok, LeadingTrivia);
-
-  L.lex(Tok, LeadingTrivia, TrailingTrivia);
-  ASSERT_EQ(tok::identifier, Tok.getKind());
-  ASSERT_EQ("ccc", Tok.getText());
-  ASSERT_FALSE(Tok.isAtStartOfLine());
-  ASSERT_EQ(LeadingTrivia, (Trivia{{TriviaPiece::blockComment("/*C*/")}}));
-  ASSERT_EQ(TrailingTrivia, Trivia());
-
-  L.restoreState(S);
-  L.lex(Tok, LeadingTrivia, TrailingTrivia);
-  ASSERT_EQ(tok::identifier, Tok.getKind());
-  ASSERT_EQ("bbb", Tok.getText());
-  ASSERT_TRUE(Tok.isAtStartOfLine());
-  ASSERT_EQ(LeadingTrivia,
-            (Trivia{{TriviaPiece::newlines(1), TriviaPiece::spaces(1)}}));
-  ASSERT_EQ(TrailingTrivia, (Trivia{{TriviaPiece::spaces(1)}}));
-}
-
 TEST_F(LexerTest, getLocForStartOfToken) {
   const char *Source = "aaa \n \tbbb \"hello\" \"-\\(val)-\"";
 
diff --git a/unittests/Parse/LexerTriviaTests.cpp b/unittests/Parse/LexerTriviaTests.cpp
new file mode 100644
index 0000000..23eaf31
--- /dev/null
+++ b/unittests/Parse/LexerTriviaTests.cpp
@@ -0,0 +1,186 @@
+#include "swift/Basic/LangOptions.h"
+#include "swift/Basic/SourceManager.h"
+#include "swift/Parse/Lexer.h"
+#include "swift/Subsystems.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "gtest/gtest.h"
+
+using namespace swift;
+using namespace swift::syntax;
+using namespace llvm;
+
+class LexerTriviaTest : public ::testing::Test {};
+
+TEST_F(LexerTriviaTest, RestoreWithTrivia) {
+  using namespace swift::syntax;
+  StringRef SourceStr = "aaa \n bbb /*C*/ccc";
+
+  LangOptions LangOpts;
+  SourceManager SourceMgr;
+  unsigned BufferID = SourceMgr.addMemBufferCopy(SourceStr);
+
+  Lexer L(LangOpts, SourceMgr, BufferID, /*Diags=*/nullptr, /*InSILMode=*/false,
+          CommentRetentionMode::AttachToNextToken,
+          TriviaRetentionMode::WithTrivia);
+
+  Token Tok;
+  Trivia LeadingTrivia, TrailingTrivia;
+
+  L.lex(Tok, LeadingTrivia, TrailingTrivia);
+  ASSERT_EQ(tok::identifier, Tok.getKind());
+  ASSERT_EQ("aaa", Tok.getText());
+  ASSERT_TRUE(Tok.isAtStartOfLine());
+  ASSERT_EQ(LeadingTrivia, Trivia());
+  ASSERT_EQ(TrailingTrivia, (Trivia{{TriviaPiece::spaces(1)}}));
+
+  L.lex(Tok, LeadingTrivia, TrailingTrivia);
+  ASSERT_EQ(tok::identifier, Tok.getKind());
+  ASSERT_EQ("bbb", Tok.getText());
+  ASSERT_TRUE(Tok.isAtStartOfLine());
+  ASSERT_EQ(LeadingTrivia,
+            (Trivia{{TriviaPiece::newlines(1), TriviaPiece::spaces(1)}}));
+  ASSERT_EQ(TrailingTrivia, (Trivia{{TriviaPiece::spaces(1)}}));
+
+  LexerState S = L.getStateForBeginningOfToken(Tok, LeadingTrivia);
+
+  L.lex(Tok, LeadingTrivia, TrailingTrivia);
+  ASSERT_EQ(tok::identifier, Tok.getKind());
+  ASSERT_EQ("ccc", Tok.getText());
+  ASSERT_FALSE(Tok.isAtStartOfLine());
+  ASSERT_EQ(LeadingTrivia, (Trivia{{TriviaPiece::blockComment("/*C*/")}}));
+  ASSERT_EQ(TrailingTrivia, Trivia());
+
+  L.restoreState(S);
+  L.lex(Tok, LeadingTrivia, TrailingTrivia);
+  ASSERT_EQ(tok::identifier, Tok.getKind());
+  ASSERT_EQ("bbb", Tok.getText());
+  ASSERT_TRUE(Tok.isAtStartOfLine());
+  ASSERT_EQ(LeadingTrivia,
+            (Trivia{{TriviaPiece::newlines(1), TriviaPiece::spaces(1)}}));
+  ASSERT_EQ(TrailingTrivia, (Trivia{{TriviaPiece::spaces(1)}}));
+}
+
+TEST_F(LexerTriviaTest, TriviaHashbang) {
+  StringRef SourceStr = "#!/bin/swift\naaa";
+
+  LangOptions LangOpts;
+  SourceManager SourceMgr;
+  unsigned BufferID = SourceMgr.addMemBufferCopy(SourceStr);
+
+  Lexer L(LangOpts, SourceMgr, BufferID, /*Diags=*/nullptr, /*InSILMode=*/false,
+          CommentRetentionMode::AttachToNextToken,
+          TriviaRetentionMode::WithTrivia);
+
+  Token Tok;
+  Trivia LeadingTrivia, TrailingTrivia;
+  L.lex(Tok, LeadingTrivia, TrailingTrivia);
+
+  ASSERT_EQ(tok::identifier, Tok.getKind());
+  ASSERT_EQ("aaa", Tok.getText());
+  ASSERT_TRUE(Tok.isAtStartOfLine());
+  ASSERT_EQ(LeadingTrivia,
+            (Trivia{{TriviaPiece::garbageText("#!/bin/swift"),
+                     TriviaPiece::newlines(1)}}));
+}
+
+TEST_F(LexerTriviaTest, TriviaHashbangAfterBOM) {
+  StringRef SourceStr = "\xEF\xBB\xBF" "#!/bin/swift\naaa";
+
+  LangOptions LangOpts;
+  SourceManager SourceMgr;
+  unsigned BufferID = SourceMgr.addMemBufferCopy(SourceStr);
+
+  Lexer L(LangOpts, SourceMgr, BufferID, /*Diags=*/nullptr, /*InSILMode=*/false,
+          CommentRetentionMode::AttachToNextToken,
+          TriviaRetentionMode::WithTrivia);
+
+  Token Tok;
+  Trivia LeadingTrivia, TrailingTrivia;
+  L.lex(Tok, LeadingTrivia, TrailingTrivia);
+
+  ASSERT_EQ(tok::identifier, Tok.getKind());
+  ASSERT_EQ("aaa", Tok.getText());
+  ASSERT_TRUE(Tok.isAtStartOfLine());
+
+  // FIXME: This should include UTF8-BOM as a GarbargeText trivia.
+  ASSERT_EQ(LeadingTrivia,
+            (Trivia{{TriviaPiece::garbageText("#!/bin/swift"),
+                     TriviaPiece::newlines(1)}}));
+}
+
+TEST_F(LexerTriviaTest, TriviaConflictMarker) {
+  using namespace swift::syntax;
+  StringRef SourceStr =
+      "aaa\n"
+      "<<<<<<< HEAD:conflict_markers.swift\n"
+      "new\n"
+      "=======\n"
+      "old\n"
+      ">>>>>>> 18844bc65229786b96b89a9fc7739c0f:conflict_markers.swift\n"
+      "bbb\n";
+
+  LangOptions LangOpts;
+  SourceManager SourceMgr;
+  unsigned BufferID = SourceMgr.addMemBufferCopy(SourceStr);
+
+  Lexer L(LangOpts, SourceMgr, BufferID, /*Diags=*/nullptr, /*InSILMode=*/false,
+          CommentRetentionMode::AttachToNextToken,
+          TriviaRetentionMode::WithTrivia);
+
+  Token Tok;
+  Trivia LeadingTrivia, TrailingTrivia;
+
+  L.lex(Tok, LeadingTrivia, TrailingTrivia);
+  ASSERT_EQ(tok::identifier, Tok.getKind());
+  ASSERT_EQ("aaa", Tok.getText());
+
+  L.lex(Tok, LeadingTrivia, TrailingTrivia);
+  ASSERT_EQ(tok::identifier, Tok.getKind());
+  ASSERT_EQ("bbb", Tok.getText());
+  ASSERT_TRUE(Tok.isAtStartOfLine());
+  StringRef expectedTrivia =
+      "<<<<<<< HEAD:conflict_markers.swift\n"
+      "new\n"
+      "=======\n"
+      "old\n"
+      ">>>>>>> 18844bc65229786b96b89a9fc7739c0f:conflict_markers.swift";
+  ASSERT_EQ(LeadingTrivia, (Trivia{{TriviaPiece::newlines(1),
+                                    TriviaPiece::garbageText(expectedTrivia),
+                                    TriviaPiece::newlines(1)}}));
+}
+
+TEST_F(LexerTriviaTest, TriviaCarriageReturn) {
+  using namespace swift::syntax;
+  StringRef SourceStr = "aaa\r\rbbb\r";
+
+  LangOptions LangOpts;
+  SourceManager SourceMgr;
+  unsigned BufferID = SourceMgr.addMemBufferCopy(SourceStr);
+
+  Lexer L(LangOpts, SourceMgr, BufferID, /*Diags=*/nullptr, /*InSILMode=*/false,
+          CommentRetentionMode::AttachToNextToken,
+          TriviaRetentionMode::WithTrivia);
+
+  Token Tok;
+  Trivia LeadingTrivia, TrailingTrivia;
+
+  L.lex(Tok, LeadingTrivia, TrailingTrivia);
+  ASSERT_EQ(tok::identifier, Tok.getKind());
+  ASSERT_EQ("aaa", Tok.getText());
+  ASSERT_TRUE(Tok.isAtStartOfLine());
+  ASSERT_EQ(LeadingTrivia, Trivia());
+  ASSERT_EQ(TrailingTrivia, Trivia());
+
+  L.lex(Tok, LeadingTrivia, TrailingTrivia);
+  ASSERT_EQ(tok::identifier, Tok.getKind());
+  ASSERT_EQ("bbb", Tok.getText());
+  ASSERT_TRUE(Tok.isAtStartOfLine());
+  ASSERT_EQ(LeadingTrivia, (Trivia{{TriviaPiece::carriageReturns(2)}}));
+  ASSERT_EQ(TrailingTrivia, Trivia());
+
+  L.lex(Tok, LeadingTrivia, TrailingTrivia);
+  ASSERT_EQ(tok::eof, Tok.getKind());
+  ASSERT_TRUE(Tok.isAtStartOfLine());
+  ASSERT_EQ(LeadingTrivia, (Trivia{{TriviaPiece::carriageReturns(1)}}));
+  ASSERT_EQ(TrailingTrivia, Trivia());
+}
diff --git a/unittests/Syntax/DeclSyntaxTests.cpp b/unittests/Syntax/DeclSyntaxTests.cpp
index 2311e4a..6435e8b 100644
--- a/unittests/Syntax/DeclSyntaxTests.cpp
+++ b/unittests/Syntax/DeclSyntaxTests.cpp
@@ -45,9 +45,9 @@
     SyntaxFactory::makeTokenList({LParen, Set, RParen}));
 
   ASSERT_EQ(Private.getRaw(), Mod.getName().getRaw());
-  ASSERT_EQ(LParen.getRaw(), Mod.getDetail()[0].getRaw());
-  ASSERT_EQ(Set.getRaw(), Mod.getDetail()[1].getRaw());
-  ASSERT_EQ(RParen.getRaw(), Mod.getDetail()[2].getRaw());
+  ASSERT_EQ(LParen.getRaw(), Mod.getDetail().getValue()[0].getRaw());
+  ASSERT_EQ(Set.getRaw(), Mod.getDetail().getValue()[1].getRaw());
+  ASSERT_EQ(RParen.getRaw(), Mod.getDetail().getValue()[2].getRaw());
 }
 
 TEST(DeclSyntaxTests, DeclModifierWithAPIs) {
@@ -103,10 +103,10 @@
     auto Array = SyntaxFactory::makeIdentifier("Array", {}, {});
     auto Array_Int =
         SyntaxFactory::makeSimpleTypeIdentifier(Array, GenericArgs);
-
+    auto TypeInit = SyntaxFactory::makeTypeInitializerClause(Assignment,
+                                                             Array_Int);
     SyntaxFactory::makeTypealiasDecl(None, None, Typealias,
-                                     Subsequence, GenericParams,
-                                     Assignment, Array_Int)
+                                     Subsequence, GenericParams, TypeInit)
       .print(OS);
     ASSERT_EQ(OS.str().str(),
               "typealias MyCollection<Element> = Array<Element>");
@@ -140,7 +140,7 @@
 
   auto Array = SyntaxFactory::makeIdentifier("Array", {}, {});
   auto Array_Int = SyntaxFactory::makeSimpleTypeIdentifier(Array, GenericArgs);
-
+  auto Type_Init = SyntaxFactory::makeTypeInitializerClause(Equal, Array_Int);
   {
     SmallString<1> Scratch;
     llvm::raw_svector_ostream OS(Scratch);
@@ -148,8 +148,7 @@
       .withTypealiasKeyword(Typealias)
       .withIdentifier(MyCollection)
       .withGenericParameterClause(GenericParams)
-      .withEquals(Equal)
-      .withType(Array_Int)
+      .withInitializer(Type_Init)
       .print(OS);
     ASSERT_EQ(OS.str().str(),
               "typealias MyCollection<Element> = Array<Element>");
@@ -187,13 +186,12 @@
 
   auto Array = SyntaxFactory::makeIdentifier("Array", {}, {});
   auto Array_Int = SyntaxFactory::makeSimpleTypeIdentifier(Array, GenericArgs);
-
+  auto Type_Init = SyntaxFactory::makeTypeInitializerClause(Equal, Array_Int);
   TypealiasDeclSyntaxBuilder()
     .useTypealiasKeyword(Typealias)
     .useIdentifier(MyCollection)
     .useGenericParameterClause(GenericParams)
-    .useEquals(Equal)
-    .useType(Array_Int)
+    .useInitializer(Type_Init)
     .build()
     .print(OS);
   ASSERT_EQ(OS.str().str(),
@@ -209,7 +207,6 @@
   auto Colon = SyntaxFactory::makeColonToken({}, Trivia::spaces(1));
   auto Int = SyntaxFactory::makeTypeIdentifier("Int", {},
                                                Trivia::spaces(1));
-  auto IntAnnotation = SyntaxFactory::makeTypeAnnotation({}, None, Int);
   auto NoEllipsis = TokenSyntax::missingToken(tok::identifier, "...");
   auto Equal = SyntaxFactory::makeEqualToken({}, Trivia::spaces(1));
 
@@ -217,11 +214,12 @@
   auto OneDigits = SyntaxFactory::makeIntegerLiteral("1", {}, {});
   auto One = SyntaxFactory::makePrefixOperatorExpr(Sign,
     SyntaxFactory::makeIntegerLiteralExpr(OneDigits));
+  auto DefaultArg = SyntaxFactory::makeInitializerClause(Equal, One);
   auto Comma = SyntaxFactory::makeCommaToken({}, Trivia::spaces(1));
 
-  return SyntaxFactory::makeFunctionParameter(None, ExternalName, LocalName, Colon,
-                                              Int, NoEllipsis, Equal,
-                                              One, Comma);
+  return SyntaxFactory::makeFunctionParameter(None, ExternalName, LocalName,
+                                              Colon, Int, NoEllipsis,
+                                              DefaultArg, Comma);
 }
 
 TEST(DeclSyntaxTests, FunctionParameterMakeAPIs) {
@@ -246,7 +244,6 @@
   auto Colon = SyntaxFactory::makeColonToken({}, Trivia::spaces(1));
   auto Int = SyntaxFactory::makeTypeIdentifier("Int", {},
                                                Trivia::spaces(1));
-  auto IntAnnotation = SyntaxFactory::makeTypeAnnotation({}, None, Int);
   auto NoEllipsis = TokenSyntax::missingToken(tok::identifier, "...");
   auto Equal = SyntaxFactory::makeEqualToken({}, Trivia::spaces(1));
 
@@ -254,11 +251,12 @@
   auto OneDigits = SyntaxFactory::makeIntegerLiteral("1", {}, {});
   auto One = SyntaxFactory::makePrefixOperatorExpr(Sign,
     SyntaxFactory::makeIntegerLiteralExpr(OneDigits));
+  auto DefaultArg = SyntaxFactory::makeInitializerClause(Equal, One);
   auto Comma = SyntaxFactory::makeCommaToken({}, {});
 
-  auto Param = SyntaxFactory::makeFunctionParameter(None, ExternalName, LocalName,
-                                                    Colon, Int,
-                                                    NoEllipsis, Equal, One,
+  auto Param = SyntaxFactory::makeFunctionParameter(None, ExternalName,
+                                                    LocalName, Colon, Int,
+                                                    NoEllipsis, DefaultArg,
                                                     Comma);
 
   ASSERT_EQ(ExternalName.getRaw(), Param.getFirstName().getRaw());
@@ -269,10 +267,10 @@
   auto GottenType2 = Param.getTypeAnnotation();
   ASSERT_TRUE(GottenType.hasSameIdentityAs(GottenType2));
 
-  ASSERT_EQ(Equal.getRaw(), Param.getDefaultEquals()->getRaw());
+  ASSERT_EQ(DefaultArg.getRaw(), Param.getDefaultArgument()->getRaw());
 
-  auto GottenDefaultValue = Param.getDefaultValue().getValue();
-  auto GottenDefaultValue2 = Param.getDefaultValue().getValue();
+  auto GottenDefaultValue = Param.getDefaultArgument()->getValue();
+  auto GottenDefaultValue2 = Param.getDefaultArgument()->getValue();
   ASSERT_TRUE(GottenDefaultValue.hasSameIdentityAs(GottenDefaultValue2));
 
   ASSERT_EQ(Comma.getRaw(), Param.getTrailingComma()->getRaw());
@@ -280,10 +278,10 @@
   // Test that llvm::None is returned for non-token missing children:
   auto Decimated = Param
     .withTypeAnnotation(llvm::None)
-    .withDefaultValue(llvm::None);
+    .withDefaultArgument(llvm::None);
 
   ASSERT_TRUE(Decimated.getTypeAnnotation().isMissing());
-  ASSERT_FALSE(Decimated.getDefaultValue().hasValue());
+  ASSERT_FALSE(Decimated.getDefaultArgument().hasValue());
 }
 
 TEST(DeclSyntaxTests, FunctionParameterWithAPIs) {
@@ -294,12 +292,12 @@
                                              Trivia::spaces(1));
   auto Int = SyntaxFactory::makeTypeIdentifier("Int", {},
                                                Trivia::spaces(1));
-  auto IntAnnotation = SyntaxFactory::makeTypeAnnotation({}, None, Int);
   auto Equal = SyntaxFactory::makeEqualToken({}, Trivia::spaces(1));
 
   auto NoSign = TokenSyntax::missingToken(tok::oper_prefix, "");
   auto OneDigits = SyntaxFactory::makeIntegerLiteral("1", {}, {});
   auto One = SyntaxFactory::makeIntegerLiteralExpr(OneDigits);
+  auto DefaultArg = SyntaxFactory::makeInitializerClause(Equal, One);
   auto Comma = SyntaxFactory::makeCommaToken({}, {});
 
   {
@@ -310,8 +308,7 @@
       .withSecondName(LocalName)
       .withColon(Colon)
       .withTypeAnnotation(Int)
-      .withDefaultEquals(Equal)
-      .withDefaultValue(One)
+      .withDefaultArgument(DefaultArg)
       .withTrailingComma(Comma)
       .print(OS);
     ASSERT_EQ(OS.str().str(), "for integer : Int = 1,");
@@ -321,9 +318,9 @@
     llvm::raw_svector_ostream OS(Scratch);
     getCannedFunctionParameter()
       .withTypeAnnotation(llvm::None)
-      .withDefaultValue(llvm::None)
+      .withDefaultArgument(llvm::None)
       .print(OS);
-    ASSERT_EQ(OS.str().str(), "with radius: = , ");
+    ASSERT_EQ(OS.str().str(), "with radius: , ");
   }
 }
 
@@ -358,13 +355,13 @@
     .appending(Param)
     .castTo<FunctionParameterListSyntax>();
   auto RParen = SyntaxFactory::makeRightParenToken({}, Trivia::spaces(1));
+  auto Parameter = SyntaxFactory::makeParameterClause(LParen, List, RParen);
   auto Throws = SyntaxFactory::makeThrowsKeyword({}, Trivia::spaces(1));
   auto Arrow = SyntaxFactory::makeArrowToken({}, Trivia::spaces(1));
-  auto NoAttributes = SyntaxFactory::makeBlankAttributeList();
   auto Int = SyntaxFactory::makeTypeIdentifier("Int", {}, Trivia::spaces(1));
+  auto Return = SyntaxFactory::makeReturnClause(Arrow, Int);
 
-  return SyntaxFactory::makeFunctionSignature(LParen, List, RParen, Throws,
-                                              Arrow, NoAttributes, Int);
+  return SyntaxFactory::makeFunctionSignature(Parameter, Throws, Return);
 }
 
 TEST(DeclSyntaxTests, FunctionSignatureMakeAPIs) {
@@ -396,19 +393,21 @@
   auto RParen = SyntaxFactory::makeRightParenToken({}, Trivia::spaces(1));
   auto Throws = SyntaxFactory::makeThrowsKeyword({}, Trivia::spaces(1));
   auto Arrow = SyntaxFactory::makeArrowToken({}, Trivia::spaces(1));
-  auto NoAttributes = SyntaxFactory::makeBlankAttributeList();
+
   auto Int = SyntaxFactory::makeTypeIdentifier("Int", {}, {});
 
-  auto Sig = SyntaxFactory::makeFunctionSignature(LParen, List, RParen, Throws,
-                                                  Arrow, NoAttributes, Int);
+  auto Sig = SyntaxFactory::makeFunctionSignature(
+    SyntaxFactory::makeParameterClause(LParen, List, RParen),
+    Throws,
+    SyntaxFactory::makeReturnClause(Arrow, Int));
 
-  ASSERT_EQ(LParen.getRaw(), Sig.getLeftParen().getRaw());
+  ASSERT_EQ(LParen.getRaw(), Sig.getInput().getLeftParen().getRaw());
 
   {
     SmallString<48> Scratch;
     llvm::raw_svector_ostream OS(Scratch);
-    auto GottenList1 = Sig.getParameterList();
-    auto GottenList2 = Sig.getParameterList();
+    auto GottenList1 = Sig.getInput().getParameterList();
+    auto GottenList2 = Sig.getInput().getParameterList();
     ASSERT_TRUE(GottenList1.hasSameIdentityAs(GottenList2));
     GottenList1.print(OS);
     ASSERT_EQ(OS.str().str(),
@@ -417,25 +416,16 @@
               "with radius: Int = -1, ");
   }
 
-  ASSERT_EQ(RParen.getRaw(), Sig.getRightParen().getRaw());
+  ASSERT_EQ(RParen.getRaw(), Sig.getInput().getRightParen().getRaw());
   ASSERT_EQ(Throws.getRaw(), Sig.getThrowsOrRethrowsKeyword()->getRaw());
   ASSERT_EQ(Sig.getThrowsOrRethrowsKeyword()->getTokenKind(), tok::kw_throws);
-  ASSERT_EQ(Arrow.getRaw(), Sig.getArrow()->getRaw());
-
-  {
-    SmallString<48> Scratch;
-    llvm::raw_svector_ostream OS(Scratch);
-    auto GottenAttrs1 = Sig.getReturnTypeAttributes().getValue();
-    auto GottenAttrs2 = Sig.getReturnTypeAttributes().getValue();
-    ASSERT_TRUE(GottenAttrs1.hasSameIdentityAs(GottenAttrs2));
-    ASSERT_EQ(OS.str().str(), "");
-  }
+  ASSERT_EQ(Arrow.getRaw(), Sig.getOutput()->getArrow().getRaw());
 
   {
     SmallString<3> Scratch;
     llvm::raw_svector_ostream OS(Scratch);
-    auto GottenReturnType1 = Sig.getReturnType().getValue();
-    auto GottenReturnType2 = Sig.getReturnType().getValue();
+    auto GottenReturnType1 = Sig.getOutput()->getReturnType();
+    auto GottenReturnType2 = Sig.getOutput()->getReturnType();
     ASSERT_TRUE(GottenReturnType1.hasSameIdentityAs(GottenReturnType2));
     GottenReturnType1.print(OS);
     ASSERT_EQ(OS.str().str(), "Int");
@@ -453,19 +443,16 @@
   auto RParen = SyntaxFactory::makeRightParenToken({}, Trivia::spaces(1));
   auto Throws = SyntaxFactory::makeThrowsKeyword({}, Trivia::spaces(1));
   auto Arrow = SyntaxFactory::makeArrowToken({}, Trivia::spaces(1));
-  auto NoAttributes = SyntaxFactory::makeBlankAttributeList();
   auto Int = SyntaxFactory::makeTypeIdentifier("Int", {}, {});
 
+  auto Parameter = SyntaxFactory::makeParameterClause(LParen, List, RParen);
+  auto Return = SyntaxFactory::makeReturnClause(Arrow, Int);
   SmallString<48> Scratch;
   llvm::raw_svector_ostream OS(Scratch);
   SyntaxFactory::makeBlankFunctionSignature()
-    .withLeftParen(LParen)
-    .withParameterList(List)
-    .withRightParen(RParen)
+    .withInput(Parameter)
     .withThrowsOrRethrowsKeyword(Throws)
-    .withReturnTypeAttributes(NoAttributes)
-    .withArrow(Arrow)
-    .withReturnType(Int)
+    .withOutput(Return)
     .print(OS);
   ASSERT_EQ(OS.str().str(),
             "(with radius: Int = -1, "
diff --git a/unittests/Syntax/TypeSyntaxTests.cpp b/unittests/Syntax/TypeSyntaxTests.cpp
index b3f6009..eb278bd 100644
--- a/unittests/Syntax/TypeSyntaxTests.cpp
+++ b/unittests/Syntax/TypeSyntaxTests.cpp
@@ -220,18 +220,17 @@
 
     TupleTypeSyntaxBuilder Builder;
     Builder.useLeftParen(SyntaxFactory::makeLeftParenToken({}, {}));
+    auto Int = SyntaxFactory::makeTypeIdentifier("Int", {}, {});
     auto Comma = SyntaxFactory::makeCommaToken({}, { Trivia::spaces(1) });
     auto Colon = SyntaxFactory::makeColonToken({}, { Trivia::spaces(1) });
-    auto Int = SyntaxFactory::makeTypeIdentifier("Int", {}, {});
     auto xLabel = SyntaxFactory::makeIdentifier("x", {} , {});
     auto xTypeElt = SyntaxFactory::makeTupleTypeElement(xLabel, Colon,
                                                         Int, Comma);
-    auto yLabel = SyntaxFactory::makeIdentifier("y", {} , {});
     auto inout = SyntaxFactory::makeInoutKeyword({}, { Trivia::spaces(1) });
-    auto yTypeAnnotation = SyntaxFactory::makeTypeAnnotation({}, inout, Int);
+    auto yLabel = SyntaxFactory::makeIdentifier("y", {} , {});
     auto yTypeElt = SyntaxFactory::makeTupleTypeElement(yLabel, Colon,
-                                                        yTypeAnnotation,
-                                                        None);
+                                                        Int)
+      .withInOut(inout);
     Builder.addTupleTypeElement(xTypeElt);
     Builder.addTupleTypeElement(yTypeElt);
     Builder.useRightParen(SyntaxFactory::makeRightParenToken({}, {}));
@@ -239,7 +238,7 @@
     auto TupleType = Builder.build();
     TupleType.print(OS);
 
-    ASSERT_EQ(OS.str(), "(x: Int, y: inout Int)");
+    ASSERT_EQ(OS.str(), "(x: Int, inout y: Int)");
   }
 }
 
@@ -472,9 +471,8 @@
   auto RightParen = SyntaxFactory::makeRightParenToken({},
                                                        {Trivia::spaces(1)});
   auto Int = SyntaxFactory::makeTypeIdentifier("Int", {}, {});
-  auto IntAnnotation = SyntaxFactory::makeTypeAnnotation({}, None, Int);
-  auto IntArg = SyntaxFactory::makeBlankFunctionTypeArgument()
-    .withTypeAnnotation(IntAnnotation);
+  auto IntArg = SyntaxFactory::makeBlankTupleTypeElement()
+    .withType(Int);
   auto Throws = SyntaxFactory::makeThrowsKeyword({}, { Trivia::spaces(1) });
   auto Rethrows = SyntaxFactory::makeRethrowsKeyword({},
                                                        { Trivia::spaces(1) });
@@ -486,22 +484,20 @@
 
     auto x = SyntaxFactory::makeIdentifier("x", {}, {});
     auto y = SyntaxFactory::makeIdentifier("y", {}, {});
-    auto xArg = SyntaxFactory::makeBlankFunctionTypeArgument()
-      .withExternalName(x)
+    auto xArg = SyntaxFactory::makeBlankTupleTypeElement()
+      .withName(x)
       .withColon(Colon)
-      .withTypeAnnotation(IntAnnotation)
+      .withType(Int)
       .withTrailingComma(Comma);
-    auto yArg = SyntaxFactory::makeBlankFunctionTypeArgument()
-      .withExternalName(y)
+    auto yArg = SyntaxFactory::makeBlankTupleTypeElement()
+      .withName(y)
       .withColon(Colon)
-      .withTypeAnnotation(IntAnnotation);
+      .withType(Int);
 
-    auto Attrs = SyntaxFactory::makeBlankAttributeList();
-    auto TypeList = SyntaxFactory::makeFunctionTypeArgumentList({
+    auto TypeList = SyntaxFactory::makeTupleTypeElementList({
       xArg, yArg
     });
-    SyntaxFactory::makeFunctionType(Attrs,
-                                    LeftParen,
+    SyntaxFactory::makeFunctionType(LeftParen,
                                     TypeList,
                                     RightParen,
                                     Throws,
@@ -514,13 +510,11 @@
   {
     SmallString<48> Scratch;
     llvm::raw_svector_ostream OS(Scratch);
-    auto Attrs = SyntaxFactory::makeBlankAttributeList();
-    auto TypeList = SyntaxFactory::makeFunctionTypeArgumentList({
+    auto TypeList = SyntaxFactory::makeTupleTypeElementList({
       IntArg.withTrailingComma(Comma),
       IntArg
     });
-    SyntaxFactory::makeFunctionType(Attrs,
-                                    LeftParen,
+    SyntaxFactory::makeFunctionType(LeftParen,
                                     TypeList,
                                     RightParen,
                                     Rethrows,
@@ -532,11 +526,9 @@
   {
     SmallString<48> Scratch;
     llvm::raw_svector_ostream OS(Scratch);
-    auto Attrs = SyntaxFactory::makeBlankAttributeList();
-    auto TypeList = SyntaxFactory::makeBlankFunctionTypeArgumentList();
+    auto TypeList = SyntaxFactory::makeBlankTupleTypeElementList();
     auto Void = SyntaxFactory::makeVoidTupleType();
-    SyntaxFactory::makeFunctionType(Attrs,
-                                    LeftParen,
+    SyntaxFactory::makeFunctionType(LeftParen,
                                     TypeList,
                                     RightParen,
                                     TokenSyntax::missingToken(tok::kw_throws,
@@ -545,17 +537,15 @@
                                     Void).print(OS);
     ASSERT_EQ(OS.str().str(), "() -> ()");
   }
-
-}
+} 
 
 TEST(TypeSyntaxTests, FunctionTypeWithAPIs) {
   auto Comma = SyntaxFactory::makeCommaToken({}, { Trivia::spaces(1) });
   auto LeftParen = SyntaxFactory::makeLeftParenToken({}, {});
   auto RightParen = SyntaxFactory::makeRightParenToken({}, Trivia::spaces(1));
   auto Int = SyntaxFactory::makeTypeIdentifier("Int", {}, {});
-  auto IntAnnotation = SyntaxFactory::makeTypeAnnotation({}, None, Int);
-  auto IntArg = SyntaxFactory::makeFunctionTypeArgument(None, None, None,
-                                                        IntAnnotation, None);
+  auto IntArg = SyntaxFactory::makeTupleTypeElement(None, None, None, None,
+                                                    Int, None, None, None);
   auto Throws = SyntaxFactory::makeThrowsKeyword({}, { Trivia::spaces(1) });
   auto Rethrows = SyntaxFactory::makeRethrowsKeyword({},
                                                        { Trivia::spaces(1) });
@@ -567,16 +557,15 @@
     auto x = SyntaxFactory::makeIdentifier("x", {}, {});
     auto y = SyntaxFactory::makeIdentifier("y", {}, {});
     auto Colon = SyntaxFactory::makeColonToken({}, Trivia::spaces(1));
-    auto intAnnotation = SyntaxFactory::makeTypeAnnotation({}, None, Int);
-    auto xArg = SyntaxFactory::makeFunctionTypeArgument(x, None, Colon,
-                                                        intAnnotation, Comma);
-    auto yArg = SyntaxFactory::makeFunctionTypeArgument(y, None, Colon,
-                                                        intAnnotation, None);
+    auto xArg = SyntaxFactory::makeTupleTypeElement(None, x, None, Colon,
+                                                    Int, None, None, Comma);
+    auto yArg = SyntaxFactory::makeTupleTypeElement(None, y, None, Colon,
+                                                    Int, None, None, None);
 
     SyntaxFactory::makeBlankFunctionType()
       .withLeftParen(LeftParen)
-      .addFunctionTypeArgument(xArg)
-      .addFunctionTypeArgument(yArg)
+      .addTupleTypeElement(xArg)
+      .addTupleTypeElement(yArg)
       .withRightParen(RightParen)
       .withThrowsOrRethrowsKeyword(Throws)
       .withArrow(Arrow)
@@ -593,8 +582,8 @@
     SyntaxFactory::makeBlankFunctionType()
       .withLeftParen(LeftParen)
       .withRightParen(RightParen)
-      .addFunctionTypeArgument(IntArg.withTrailingComma(Comma))
-      .addFunctionTypeArgument(IntArg)
+      .addTupleTypeElement(IntArg.withTrailingComma(Comma))
+      .addTupleTypeElement(IntArg)
       .withThrowsOrRethrowsKeyword(Rethrows)
       .withArrow(Arrow)
       .withReturnType(Int)
@@ -619,8 +608,6 @@
 TEST(TypeSyntaxTests, FunctionTypeBuilderAPIs) {
   auto Comma = SyntaxFactory::makeCommaToken({}, { Trivia::spaces(1) });
   auto Int = SyntaxFactory::makeTypeIdentifier("Int", {}, {});
-  auto IntAnnotation =
-    SyntaxFactory::makeTypeAnnotation({}, None, Int);
   auto LeftParen = SyntaxFactory::makeLeftParenToken({}, {});
   auto RightParen = SyntaxFactory::makeRightParenToken({},
                                                          {Trivia::spaces(1)});
@@ -636,15 +623,15 @@
     auto x = SyntaxFactory::makeIdentifier("x", {}, {});
     auto y = SyntaxFactory::makeIdentifier("y", {}, {});
     auto Colon = SyntaxFactory::makeColonToken({}, Trivia::spaces(1));
-    auto xArg = SyntaxFactory::makeFunctionTypeArgument(x, None, Colon,
-                                                        IntAnnotation, Comma);
-    auto yArg = SyntaxFactory::makeFunctionTypeArgument(y, None, Colon,
-                                                        IntAnnotation, None);
+    auto xArg = SyntaxFactory::makeTupleTypeElement(None, x, None, Colon,
+                                                    Int, None, None, Comma);
+    auto yArg = SyntaxFactory::makeTupleTypeElement(None, y, None, Colon,
+                                                    Int, None, None, None);
 
     Builder.useLeftParen(LeftParen)
       .useRightParen(RightParen)
-      .addFunctionTypeArgument(xArg)
-      .addFunctionTypeArgument(yArg)
+      .addTupleTypeElement(xArg)
+      .addTupleTypeElement(yArg)
       .useThrowsOrRethrowsKeyword(Throws)
       .useArrow(Arrow)
       .useReturnType(Int);
@@ -657,13 +644,12 @@
     SmallString<48> Scratch;
     llvm::raw_svector_ostream OS(Scratch);
     FunctionTypeSyntaxBuilder Builder;
-    auto IntArg = SyntaxFactory::makeFunctionTypeArgument(None, None,
-                                                          None, IntAnnotation,
-                                                          None);
+    auto IntArg = SyntaxFactory::makeTupleTypeElement(None, None, None, None,
+                                                      Int, None, None, None);
     Builder.useLeftParen(LeftParen)
       .useRightParen(RightParen)
-      .addFunctionTypeArgument(IntArg.withTrailingComma(Comma))
-      .addFunctionTypeArgument(IntArg)
+      .addTupleTypeElement(IntArg.withTrailingComma(Comma))
+      .addTupleTypeElement(IntArg)
       .useThrowsOrRethrowsKeyword(Rethrows)
       .useArrow(Arrow)
       .useReturnType(Int);
diff --git a/unittests/runtime/Metadata.cpp b/unittests/runtime/Metadata.cpp
index 83ee516..af9493e 100644
--- a/unittests/runtime/Metadata.cpp
+++ b/unittests/runtime/Metadata.cpp
@@ -912,7 +912,8 @@
   // The last witness is computed dynamically at instantiation time.
   ((void **) instantiatedTable)[2] = (void *) 345;
 
-  auto conditionalTables = (WitnessTableSlice *)instantiationArgs;
+  auto conditionalTables =
+      reinterpret_cast<const WitnessTableSlice *>(instantiationArgs);
 
   EXPECT_EQ(conditionalTables->count, 1UL);
   EXPECT_EQ(conditionalTables->tables[0], (void *)678);
@@ -1036,14 +1037,21 @@
 
         EXPECT_NE(instantiatedTable, table->Pattern.get());
 
-        EXPECT_EQ(((void **) instantiatedTable)[-2], (void *) 0);
-        EXPECT_EQ(((void **) instantiatedTable)[-1], (void *) 678);
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[-2],
+                  reinterpret_cast<void *>(0));
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[-1],
+                  reinterpret_cast<void *>(678));
 
-        EXPECT_EQ(((void **) instantiatedTable)[0], (void *) 123);
-        EXPECT_EQ(((void **) instantiatedTable)[1], (void *) 234);
-        EXPECT_EQ(((void **) instantiatedTable)[2], (void *) 345);
-        EXPECT_EQ(((void **) instantiatedTable)[3], (void *) 456);
-        EXPECT_EQ(((void **) instantiatedTable)[4], (void *) 567);
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[0],
+                  reinterpret_cast<void *>(123));
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[1],
+                  reinterpret_cast<void *>(234));
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[2],
+                  reinterpret_cast<void *>(345));
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[3],
+                  reinterpret_cast<void *>(456));
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[4],
+                  reinterpret_cast<void *>(567));
 
         return instantiatedTable;
       });
@@ -1068,14 +1076,21 @@
 
         EXPECT_NE(instantiatedTable, table->Pattern.get());
 
-        EXPECT_EQ(((void **) instantiatedTable)[-2], (void *) 0);
-        EXPECT_EQ(((void **) instantiatedTable)[-1], (void *) 678);
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[-2],
+                  reinterpret_cast<void *>(0));
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[-1],
+                  reinterpret_cast<void *>(678));
 
-        EXPECT_EQ(((void **) instantiatedTable)[0], (void *) 123);
-        EXPECT_EQ(((void **) instantiatedTable)[1], (void *) 234);
-        EXPECT_EQ(((void **) instantiatedTable)[2], (void *) 345);
-        EXPECT_EQ(((void **) instantiatedTable)[3], (void *) 456);
-        EXPECT_EQ(((void **) instantiatedTable)[4], (void *) fakeDefaultWitness2);
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[0],
+                  reinterpret_cast<void *>(123));
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[1],
+                  reinterpret_cast<void *>(234));
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[2],
+                  reinterpret_cast<void *>(345));
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[3],
+                  reinterpret_cast<void *>(456));
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[4],
+                  reinterpret_cast<void *>(fakeDefaultWitness2));
 
         return instantiatedTable;
       });
@@ -1101,14 +1116,21 @@
 
         EXPECT_NE(instantiatedTable, table->Pattern.get());
 
-        EXPECT_EQ(((void **) instantiatedTable)[-2], (void *) 0);
-        EXPECT_EQ(((void **) instantiatedTable)[-1], (void *) 678);
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[-2],
+                  reinterpret_cast<void *>(0));
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[-1],
+                  reinterpret_cast<void *>(678));
 
-        EXPECT_EQ(((void **) instantiatedTable)[0], (void *) 123);
-        EXPECT_EQ(((void **) instantiatedTable)[1], (void *) 234);
-        EXPECT_EQ(((void **) instantiatedTable)[2], (void *) 345);
-        EXPECT_EQ(((void **) instantiatedTable)[3], (void *) fakeDefaultWitness1);
-        EXPECT_EQ(((void **) instantiatedTable)[4], (void *) fakeDefaultWitness2);
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[0],
+                  reinterpret_cast<void *>(123));
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[1],
+                  reinterpret_cast<void *>(234));
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[2],
+                  reinterpret_cast<void *>(345));
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[3],
+                  reinterpret_cast<void *>(fakeDefaultWitness1));
+        EXPECT_EQ(reinterpret_cast<void * const *>(instantiatedTable)[4],
+                  reinterpret_cast<void *>(fakeDefaultWitness2));
 
         return instantiatedTable;
       });
diff --git a/unittests/runtime/Stdlib.cpp b/unittests/runtime/Stdlib.cpp
index cd59fba..2956123 100644
--- a/unittests/runtime/Stdlib.cpp
+++ b/unittests/runtime/Stdlib.cpp
@@ -137,21 +137,21 @@
 // ErrorObject
 
 SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
-int _T0s13_getErrorCodeSiSPyxGs0B0RzlF(void *) {
+int _T0s13_getErrorCodeySiSPyxGs0B0RzlF(void *) {
   abort();
 }
 
 SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
-void *_T0s23_getErrorDomainNSStringyXlSPyxGs0B0RzlF(void *) {
+void *_T0s23_getErrorDomainNSStringyyXlSPyxGs0B0RzlF(void *) {
   abort();
 }
 
 SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
-void *_T0s29_getErrorUserInfoNSDictionaryyXlSgSPyxGs0B0RzlF(void *) {
+void *_T0s29_getErrorUserInfoNSDictionaryyyXlSgSPyxGs0B0RzlF(void *) {
   abort();
 }
 
 SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
-void *_T0s32_getErrorEmbeddedNSErrorIndirectyXlSgSPyxGs0B0RzlF(void *) {
+void *_T0s32_getErrorEmbeddedNSErrorIndirectyyXlSgSPyxGs0B0RzlF(void *) {
   abort();
 }
diff --git a/utils/build-script-impl b/utils/build-script-impl
index 1b4ac56..effa26e 100755
--- a/utils/build-script-impl
+++ b/utils/build-script-impl
@@ -2002,7 +2002,7 @@
                 if [ "${SKIP_BUILD_LLVM}" ] ; then
                     # We can't skip the build completely because the standalone
                     # build of Swift depend on these.
-                    build_targets=(llvm-tblgen clang-headers)
+                    build_targets=(llvm-tblgen clang-headers intrinsics_gen clang-tablegen-targets)
                 fi
 
                 if [ "${HOST_LIBTOOL}" ] ; then
diff --git a/utils/check-incremental b/utils/check-incremental
index 459c41b..82576e7 100755
--- a/utils/check-incremental
+++ b/utils/check-incremental
@@ -64,11 +64,12 @@
         elif arg == '-o':
             next_arg_is_output = True
 
-    if not write_obj_file or output_file is None:
-        return
-
     new_args = sys.argv[1:]
 
+    if not write_obj_file or output_file is None:
+        subprocess.check_call(new_args)
+        return
+
     if VERBOSE:
         print("Reference compilation of " + output_file + ":")
 
@@ -86,7 +87,8 @@
         # This is the most important check: is the output file exactly the
         # same.
         if reference_md5 != second_md5:
-            sys.exit("non-determinism when generating: " + output_file)
+            sys.exit("non-determinism when generating: " + output_file +
+                     "\ncommand line:\n" + " ".join(new_args))
 
         # This is the bonus check: does the compiler not re-write the output
         # file. (For compilations < 1sec this check may succeed even if the
diff --git a/utils/check-incrementalc b/utils/check-incrementalc
new file mode 100644
index 0000000..17b0d8a
--- /dev/null
+++ b/utils/check-incrementalc
Binary files differ
diff --git a/utils/gyb_syntax_support/Child.py b/utils/gyb_syntax_support/Child.py
index 9a0eb74..c28be20 100644
--- a/utils/gyb_syntax_support/Child.py
+++ b/utils/gyb_syntax_support/Child.py
@@ -9,7 +9,7 @@
     restricted subset of acceptable kinds or texts.
     """
     def __init__(self, name, kind, is_optional=False,
-                 token_choices=None, text_choices=None):
+                 token_choices=None, text_choices=None, node_choices=None):
         self.name = name
         self.swift_name = lowercase_first_word(name)
         self.syntax_kind = kind
@@ -39,6 +39,19 @@
         # token against the choices.
         self.text_choices = text_choices or []
 
+        # A list of valid choices for a child
+        self.node_choices = node_choices or []
+
+        # Check the choices are either empty or multiple
+        assert len(self.node_choices) != 1
+
+        # Check node choices are well-formed
+        for choice in self.node_choices:
+            assert not choice.is_optional, \
+                "node choice %s cannot be optional" % choice.name
+            assert not choice.node_choices, \
+                "node choice %s cannot have further choices" % choice.name
+
     def is_token(self):
         """
         Returns true if this child has a token kind.
diff --git a/utils/gyb_syntax_support/DeclNodes.py b/utils/gyb_syntax_support/DeclNodes.py
index 29ca15a..782f167 100644
--- a/utils/gyb_syntax_support/DeclNodes.py
+++ b/utils/gyb_syntax_support/DeclNodes.py
@@ -4,6 +4,13 @@
 
 
 DECL_NODES = [
+    # initializer -> '=' type
+    Node('TypeInitializerClause', kind='Syntax',
+         children=[
+             Child('Equal', kind='EqualToken'),
+             Child('Value', kind='Type'),
+         ]),
+
     # typealias-declaration -> attributes? access-level-modifier? 'typealias'
     #                            typealias-name generic-parameter-clause?
     #                            typealias-assignment
@@ -13,38 +20,45 @@
          children=[
              Child('Attributes', kind='AttributeList',
                    is_optional=True),
-             Child('AccessLevelModifier', kind='AccessLevelModifier',
+             Child('AccessLevelModifier', kind='DeclModifier',
                    is_optional=True),
              Child('TypealiasKeyword', kind='TypealiasToken'),
              Child('Identifier', kind='IdentifierToken'),
              Child('GenericParameterClause', kind='GenericParameterClause',
                    is_optional=True),
-             Child('Equals', kind='EqualToken'),
-             Child('Type', kind='Type'),
+             Child('Initializer', kind='TypeInitializerClause',
+                   is_optional=True)
          ]),
 
     Node('FunctionParameterList', kind='SyntaxCollection',
          element='FunctionParameter'),
 
-    # function-signature ->
-    #   '(' parameter-list? ')' (throws | rethrows)? '->'? attributes? type?
-    Node('FunctionSignature', kind='Syntax',
+    Node('ParameterClause', kind='Syntax',
          children=[
              Child('LeftParen', kind='LeftParenToken'),
              Child('ParameterList', kind='FunctionParameterList'),
              Child('RightParen', kind='RightParenToken'),
+         ]),
+
+    # -> Type
+    Node('ReturnClause', kind='Syntax',
+         children=[
+             Child('Arrow', kind='ArrowToken'),
+             Child('ReturnType', kind='Type'),
+         ]),
+
+    # function-signature ->
+    #   '(' parameter-list? ')' (throws | rethrows)? '->'? type?
+    Node('FunctionSignature', kind='Syntax',
+         children=[
+             Child('Input', kind='ParameterClause'),
              Child('ThrowsOrRethrowsKeyword', kind='Token',
                    is_optional=True,
                    token_choices=[
                        'ThrowsToken',
                        'RethrowsToken',
                    ]),
-             Child('Arrow', kind='ArrowToken',
-                   is_optional=True),
-             Child('ReturnTypeAttributes', kind='AttributeList',
-                   is_optional=True),
-             Child('ReturnType', kind='Type',
-                   is_optional=True),
+             Child('Output', kind='ReturnClause', is_optional=True),
          ]),
 
     # else-if-directive-clause -> '#elseif' expr stmt-list
@@ -62,7 +76,8 @@
              Child('PoundIf', kind='PoundIfToken'),
              Child('Condition', kind='Expr'),
              Child('Body', kind='StmtList'),
-             Child('ElseifDirectiveClauses', kind='ElseifDirectiveClauseList'),
+             Child('ElseifDirectiveClauses', kind='ElseifDirectiveClauseList',
+                   is_optional=True),
              Child('ElseClause', kind='ElseDirectiveClause',
                    is_optional=True),
              Child('PoundEndif', kind='PoundEndifToken'),
@@ -78,7 +93,7 @@
                        'fileprivate', 'internal', 'public', 'open',
                        'mutating', 'nonmutating',
                    ]),
-             Child('Detail', kind='TokenList'),
+             Child('Detail', kind='TokenList', is_optional=True),
          ]),
 
     Node('InheritedType', kind='Syntax',
@@ -97,6 +112,30 @@
              Child('InheritedTypeCollection', kind='InheritedTypeList'),
          ]),
 
+    # class-declaration -> attributes? access-level-modifier?
+    #                      'class' class-name
+    #                      generic-parameter-clause?
+    #                      type-inheritance-clause?
+    #                      generic-where-clause?
+    #                     '{' class-members ''
+    # class-name -> identifier
+    Node('ClassDecl', kind='Decl',
+         children=[
+             Child('Attributes', kind='AttributeList',
+                   is_optional=True),
+             Child('AccessLevelModifier', kind='DeclModifier',
+                   is_optional=True),
+             Child('ClassKeyword', kind='ClassToken'),
+             Child('Identifier', kind='IdentifierToken'),
+             Child('GenericParameterClause', kind='GenericParameterClause',
+                   is_optional=True),
+             Child('InheritanceClause', kind='TypeInheritanceClause',
+                   is_optional=True),
+             Child('GenericWhereClause', kind='GenericWhereClause',
+                   is_optional=True),
+             Child('Members', kind='MemberDeclBlock'),
+         ]),
+
     # struct-declaration -> attributes? access-level-modifier?
     #                         'struct' struct-name
     #                         generic-parameter-clause?
@@ -121,6 +160,21 @@
              Child('Members', kind='MemberDeclBlock'),
          ]),
 
+    Node('ProtocolDecl', kind='Decl',
+         children=[
+             Child('Attributes', kind='AttributeList',
+                   is_optional=True),
+             Child('AccessLevelModifier', kind='DeclModifier',
+                   is_optional=True),
+             Child('ProtocolKeyword', kind='ProtocolToken'),
+             Child('Identifier', kind='IdentifierToken'),
+             Child('InheritanceClause', kind='TypeInheritanceClause',
+                   is_optional=True),
+             Child('GenericWhereClause', kind='GenericWhereClause',
+                   is_optional=True),
+             Child('Members', kind='MemberDeclBlock'),
+         ]),
+
     Node('MemberDeclBlock', kind='Syntax',
          children=[
              Child('LeftBrace', kind='LeftBraceToken'),
@@ -145,6 +199,13 @@
              Child('Body', kind='StmtList')
          ]),
 
+    # initializer -> '=' expr
+    Node('InitializerClause', kind='Syntax',
+         children=[
+             Child('Equal', kind='EqualToken'),
+             Child('Value', kind='Expr'),
+         ]),
+
     # parameter ->
     # external-parameter-name? local-parameter-name ':'
     #   type '...'? '='? expression? ','?
@@ -169,9 +230,7 @@
              Child('TypeAnnotation', kind='Type'),
              Child('Ellipsis', kind='Token',
                    is_optional=True),
-             Child('DefaultEquals', kind='EqualToken',
-                   is_optional=True),
-             Child('DefaultValue', kind='Expr',
+             Child('DefaultArgument', kind='InitializerClause',
                    is_optional=True),
              Child('TrailingComma', kind='CommaToken',
                    is_optional=True),
@@ -221,7 +280,8 @@
              Child('Signature', kind='FunctionSignature'),
              Child('GenericWhereClause', kind='GenericWhereClause',
                    is_optional=True),
-             Child('Body', kind='CodeBlock'),
+             # the body is not necessary inside a protocol definition
+             Child('Body', kind='CodeBlock', is_optional=True),
          ]),
 
     # else-if-directive-clause-list -> else-if-directive-clause
@@ -251,4 +311,81 @@
              Child('CloseParen', kind='RightParenToken',
                    is_optional=True),
          ]),
+
+    Node('AccessPathComponent', kind='Syntax',
+         children=[
+            Child('Name', kind='IdentifierToken'),
+            Child('TrailingDot', kind='PeriodToken', is_optional=True),
+         ]),
+
+    Node('AccessPath', kind='SyntaxCollection', element='AccessPathComponent'),
+
+    Node('ImportDecl', kind='Decl',
+         children=[
+             Child('Attributes', kind='AttributeList', is_optional=True),
+             Child('ImportTok', kind='ImportToken'),
+             Child('ImportKind', kind='Token', is_optional=True,
+                   token_choices=[
+                      'TypealiasToken', 'StructToken', 'ClassToken',
+                      'EnumToken', 'ProtocolToken', 'VarToken', 'LetToken',
+                      'FuncToken',
+                   ]),
+             Child('Path', kind='AccessPath'),
+         ]),
+
+    # (value)
+    Node('AccessorParameter', kind='Syntax',
+         children=[
+             Child('LeftParen', kind='LeftParenToken'),
+             Child('Name', kind='IdentifierToken'),
+             Child('RightParen', kind='RightParenToken'),
+         ]),
+
+    Node('AccessorDecl', kind='Decl',
+         children=[
+             Child('Attributes', kind='AttributeList', is_optional=True),
+             Child('Modifier', kind='DeclModifier', is_optional=True),
+             Child('AccessorKind', kind='Token',
+                   text_choices=[
+                      'get', 'set', 'didSet', 'willSet',
+                   ]),
+             Child('Parameter', kind='AccessorParameter', is_optional=True),
+             Child('Body', kind='CodeBlock', is_optional=True),
+         ]),
+
+    Node('AccessorList', kind="SyntaxCollection", element='AccessorDecl'),
+
+    Node('AccessorBlock', kind="Syntax",
+         children=[
+             Child('LeftBrace', kind='LeftBraceToken'),
+             Child('AccessorListOrStmtList', kind='Syntax',
+                   node_choices=[
+                      Child('Accessors', kind='AccessorList'),
+                      Child('Statements', kind='StmtList')]),
+             Child('RightBrace', kind='RightBraceToken'),
+         ]),
+
+    # Pattern: Type = Value { get {} },
+    Node('PatternBinding', kind="Syntax",
+         children=[
+             Child('Pattern', kind='Pattern'),
+             Child('TypeAnnotation', kind='TypeAnnotation', is_optional=True),
+             Child('Initializer', kind='InitializerClause', is_optional=True),
+             Child('Accesor', kind='AccessorBlock', is_optional=True),
+             Child('TrailingComma', kind='CommaToken', is_optional=True),
+         ]),
+
+    Node('PatternBindingList', kind="SyntaxCollection",
+         element='PatternBinding'),
+
+    Node('VariableDecl', kind='Decl',
+         children=[
+             Child('Attributes', kind='AttributeList', is_optional=True),
+             Child('Modifiers', kind='ModifierList', is_optional=True),
+             Child('LetOrVarKeyword', kind='Token',
+                   token_choices=[
+                       'LetToken', 'VarToken',
+                   ]),
+             Child('Bindings', kind='PatternBindingList'),
+         ]),
 ]
diff --git a/utils/gyb_syntax_support/ExprNodes.py b/utils/gyb_syntax_support/ExprNodes.py
index a3ff794..e3ebe08 100644
--- a/utils/gyb_syntax_support/ExprNodes.py
+++ b/utils/gyb_syntax_support/ExprNodes.py
@@ -6,7 +6,7 @@
     # &x
     Node('InOutExpr', kind='Expr',
          children=[
-             Child('Ampersand', kind='AmpersandToken'),
+             Child('Ampersand', kind='PrefixAmpersandToken'),
              Child('Identifier', kind='IdentifierToken'),
          ]),
 
@@ -32,7 +32,7 @@
     # try foo()
     # try? foo()
     # try! foo()
-    Node('TryOperator', kind='Syntax',
+    Node('TryExpr', kind='Expr',
          children=[
              Child('TryKeyword', kind='TryToken'),
              Child('QuestionOrExclamationMark', kind='Token',
@@ -41,6 +41,7 @@
                        'PostfixQuestionMarkToken',
                        'ExclamationMarkToken',
                    ]),
+             Child('Expression', kind='Expr'),
          ]),
 
     # An identifier expression.
@@ -73,6 +74,10 @@
              Child('Elements', kind='ExprList'),
          ]),
 
+    Node('ExprList', kind='SyntaxCollection',
+         element='Expr',
+         element_name='Expression'),
+
     # A #line expression.
     Node('PoundLineExpr', kind='Expr',
          children=[
@@ -151,7 +156,11 @@
     Node('DictionaryExpr', kind='Expr',
          children=[
              Child('LeftSquare', kind='LeftSquareToken'),
-             Child('Elements', kind='DictionaryElementList'),
+             Child('Content', kind='Syntax',
+                   node_choices=[
+                       Child('Colon', kind='ColonToken'),
+                       Child('Elements', kind='DictionaryElementList'),
+                   ]),
              Child('RightSquare', kind='RightSquareToken'),
          ]),
 
@@ -262,4 +271,64 @@
          children=[
              Child('Type', kind='Type'),
          ]),
+
+    Node('ClosureCaptureItem', kind='Syntax',
+         children=[
+             Child("Specifier", kind='TokenList', is_optional=True),
+             Child("Name", kind='IdentifierToken', is_optional=True),
+             Child('AssignToken', kind='EqualToken', is_optional=True),
+             Child("Expression", kind='Expr'),
+             Child('TrailingComma', kind='CommaToken', is_optional=True),
+         ]),
+
+    Node('ClosureCaptureItemList', kind='SyntaxCollection',
+         element='ClosureCaptureItem'),
+
+    Node('ClosureCaptureSignature', kind='Syntax',
+         children=[
+             Child('LeftSquare', kind='LeftSquareToken'),
+             Child('Items', kind='ClosureCaptureItemList', is_optional=True),
+             Child('RightSquare', kind='RightSquareToken'),
+         ]),
+
+    Node('ClosureParam', kind='Syntax',
+         children=[
+             Child('Name', kind='Token',
+                   token_choices=[
+                       'IdentifierToken',
+                       'WildcardToken',
+                   ]),
+             Child('TrailingComma', kind='CommaToken', is_optional=True),
+         ]),
+
+    # a, b, c
+    Node('ClosureParamList', kind='SyntaxCollection', element='ClosureParam'),
+
+    Node('ClosureSignature', kind='Syntax',
+         children=[
+             Child('Capture', kind='ClosureCaptureSignature',
+                   is_optional=True),
+             Child('Input', kind='Syntax', is_optional=True,
+                   node_choices=[
+                       Child('SimpleInput', kind='ClosureParamList'),
+                       Child('Input', kind='ParameterClause'),
+                   ]),
+             Child('ThrowsTok', kind='ThrowsToken', is_optional=True),
+             Child('Output', kind='ReturnClause', is_optional=True),
+             Child('InTok', kind='InToken'),
+         ]),
+
+    Node('ClosureExpr', kind='Expr',
+         children=[
+             Child('LeftBrace', kind='LeftBraceToken'),
+             Child('Signature', kind='ClosureSignature', is_optional=True),
+             Child('Statements', kind='StmtList'),
+             Child('RightBrace', kind='RightBraceToken'),
+         ]),
+
+    # unresolved-pattern-expr -> pattern
+    Node('UnresolvedPatternExpr', kind='Expr',
+         children=[
+             Child('Pattern', kind='Pattern'),
+         ]),
 ]
diff --git a/utils/gyb_syntax_support/PatternNodes.py b/utils/gyb_syntax_support/PatternNodes.py
index 71ab0c4..f8ebb5b 100644
--- a/utils/gyb_syntax_support/PatternNodes.py
+++ b/utils/gyb_syntax_support/PatternNodes.py
@@ -2,6 +2,14 @@
 from Node import Node  # noqa: I201
 
 PATTERN_NODES = [
+
+    # type-annotation -> ':' type
+    Node('TypeAnnotation', kind='Syntax',
+         children=[
+             Child('Colon', kind='ColonToken'),
+             Child('Type', kind='Type'),
+         ]),
+
     # enum-case-pattern -> type-identifier? '.' identifier tuple-pattern?
     Node('EnumCasePattern', kind='Pattern',
          children=[
@@ -20,19 +28,17 @@
              Child('Type', kind='Type'),
          ]),
 
-    # optional-pattern -> identifier '?'
+    # optional-pattern -> pattern '?'
     Node('OptionalPattern', kind='Pattern',
          children=[
-             Child('Identifier', kind='IdentifierToken'),
+             Child('SubPattern', kind='Pattern'),
              Child('QuestionMark', kind='PostfixQuestionMarkToken'),
          ]),
 
-    # identifier-pattern -> identifier type-annotation?
+    # identifier-pattern -> identifier
     Node('IdentifierPattern', kind='Pattern',
          children=[
-             Child('Identifier', kind='IdentifierToken'),
-             Child('TypeAnnotation', kind='TypeAnnotation',
-                   is_optional=True),
+             Child('Identifier', kind='IdentifierToken')
          ]),
 
     # as-pattern -> pattern 'as' type
@@ -43,14 +49,12 @@
              Child('Type', kind='Type'),
          ]),
 
-    # tuple-pattern -> '(' tuple-pattern-element-list ')' type-annotation?
+    # tuple-pattern -> '(' tuple-pattern-element-list ')'
     Node('TuplePattern', kind='Pattern',
          children=[
              Child('OpenParen', kind='LeftParenToken'),
              Child('Elements', kind='TuplePatternElementList'),
              Child('CloseParen', kind='RightParenToken'),
-             Child('TypeAnnotation', kind='TypeAnnotation',
-                   is_optional=True),
          ]),
 
     # wildcard-pattern -> '_' type-annotation?
@@ -66,7 +70,7 @@
          children=[
              Child('LabelName', kind='IdentifierToken',
                    is_optional=True),
-             Child('LabelColon', kind='ColonToken',
+             Child('Colon', kind='ColonToken',
                    is_optional=True),
              Child('Pattern', kind='Pattern'),
              Child('Comma', kind='CommaToken',
diff --git a/utils/gyb_syntax_support/StmtNodes.py b/utils/gyb_syntax_support/StmtNodes.py
index 34049bc..14949e7 100644
--- a/utils/gyb_syntax_support/StmtNodes.py
+++ b/utils/gyb_syntax_support/StmtNodes.py
@@ -73,14 +73,10 @@
                    is_optional=True),
          ]),
 
-    Node('ExprList', kind='SyntaxCollection',
-         element='Expr',
-         element_name='Expression'),
-
     Node('WhereClause', kind='Syntax',
          children=[
              Child('WhereKeyword', kind='WhereToken'),
-             Child('Expressions', kind='ExprList'),
+             Child('GuardResult', kind='Expr'),
          ]),
 
     # for-in-stmt -> label? ':'? 'for' 'case'? pattern 'in' expr 'where'?
@@ -134,7 +130,8 @@
                    is_optional=True),
              Child('DoKeyword', kind='DoToken'),
              Child('Body', kind='CodeBlock'),
-             Child('CatchClauses', kind='CatchClauseList'),
+             Child('CatchClauses', kind='CatchClauseList',
+                   is_optional=True),
              Child('Semicolon', kind='SemicolonToken',
                    is_optional=True),
          ]),
diff --git a/utils/gyb_syntax_support/Token.py b/utils/gyb_syntax_support/Token.py
index 9704bdd..83411ec 100644
--- a/utils/gyb_syntax_support/Token.py
+++ b/utils/gyb_syntax_support/Token.py
@@ -124,7 +124,7 @@
     Token('RightSquareBracket', 'r_square', text=']'),
     Token('LeftAngle', 'l_angle', text='<'),
     Token('RightAngle', 'r_angle', text='>'),
-    Token('Ampersand', 'amp_prefix', text='&'),
+    Token('PrefixAmpersand', 'amp_prefix', text='&'),
     Token('PostfixQuestionMark', 'question_postfix', text='?'),
     Token('InfixQuestionMark', 'question_infix', text='?'),
     Token('ExclamationMark', 'exclaim_postfix', text='!'),
diff --git a/utils/gyb_syntax_support/TypeNodes.py b/utils/gyb_syntax_support/TypeNodes.py
index 8f3856f..d3f3597 100644
--- a/utils/gyb_syntax_support/TypeNodes.py
+++ b/utils/gyb_syntax_support/TypeNodes.py
@@ -79,27 +79,58 @@
              Child('ExclamationMark', kind='ExclamationMarkToken'),
          ]),
 
-    # throwing-specifier -> 'throws' | 'rethrows'
-    # function-type -> attribute-list '(' function-type-argument-list ')'
-    #   throwing-specifier? '->'? type?
-    Node('FunctionType', kind='Type',
+    # composition-type-element -> type '&'
+    Node('CompositionTypeElement', kind='Syntax',
          children=[
-             Child('TypeAttributes', kind='AttributeList'),
-             Child('LeftParen', kind='LeftParenToken'),
-             Child('ArgumentList', kind='FunctionTypeArgumentList'),
-             Child('RightParen', kind='RightParenToken'),
-             Child('ThrowsOrRethrowsKeyword', kind='Token',
-                   is_optional=True,
-                   token_choices=[
-                       'ThrowsToken',
-                       'RethrowsToken',
-                   ]),
-             Child('Arrow', kind='ArrowToken',
-                   is_optional=True),
-             Child('ReturnType', kind='Type',
+             Child('Type', kind='Type'),
+             Child('Ampersand', kind='Token',
+                   text_choices=['&'],
                    is_optional=True),
          ]),
 
+    # composition-typeelement-list -> composition-type-element
+    #   composition-type-element-list?
+    Node('CompositionTypeElementList', kind='SyntaxCollection',
+         element='CompositionTypeElement'),
+
+    # composition-type -> composition-type-element-list
+    Node('CompositionType', kind='Type',
+         children=[
+             Child('Elements', kind='CompositionTypeElementList'),
+         ]),
+
+    # tuple-type-element -> identifier? ':'? type-annotation ','?
+    Node('TupleTypeElement', kind='Syntax',
+         children=[
+             Child('InOut', kind='InOutToken',
+                   is_optional=True),
+             Child('Name', kind='Token',
+                   is_optional=True,
+                   token_choices=[
+                       'IdentifierToken',
+                       'WildcardToken'
+                   ]),
+             Child('SecondName', kind='Token',
+                   is_optional=True,
+                   token_choices=[
+                       'IdentifierToken',
+                       'WildcardToken'
+                   ]),
+             Child('Colon', kind='ColonToken',
+                   is_optional=True),
+             Child('Type', kind='Type'),
+             Child('Ellipsis', kind='Token',
+                   is_optional=True),
+             Child('Initializer', kind='InitializerClause',
+                   is_optional=True),
+             Child('TrailingComma', kind='CommaToken',
+                   is_optional=True),
+         ]),
+
+    # tuple-type-element-list -> tuple-type-element tuple-type-element-list?
+    Node('TupleTypeElementList', kind='SyntaxCollection',
+         element='TupleTypeElement'),
+
     # tuple-type -> '(' tuple-type-element-list ')'
     Node('TupleType', kind='Type',
          children=[
@@ -108,42 +139,34 @@
              Child('RightParen', kind='RightParenToken'),
          ]),
 
-    # tuple-type-element -> identifier? ':'? type-annotation ','?
-    Node('TupleTypeElement', kind='Syntax',
+    # throwing-specifier -> 'throws' | 'rethrows'
+    # function-type -> attribute-list '(' function-type-argument-list ')'
+    #   throwing-specifier? '->'? type?
+    Node('FunctionType', kind='Type',
          children=[
-             Child('Label', kind='IdentifierToken',
-                   is_optional=True),
-             Child('Colon', kind='ColonToken',
-                   is_optional=True),
-             Child('TypeAnnotation', kind='TypeAnnotation'),
-             Child('Comma', kind='CommaToken',
-                   is_optional=True),
+             Child('LeftParen', kind='LeftParenToken'),
+             Child('Arguments', kind='TupleTypeElementList'),
+             Child('RightParen', kind='RightParenToken'),
+             Child('ThrowsOrRethrowsKeyword', kind='Token',
+                   is_optional=True,
+                   token_choices=[
+                       'ThrowsToken',
+                       'RethrowsToken',
+                   ]),
+             Child('Arrow', kind='ArrowToken'),
+             Child('ReturnType', kind='Type'),
          ]),
 
-    # type-annotation -> attribute-list 'inout'? type
-    Node('TypeAnnotation', kind='Syntax',
+    # attributed-type -> type-specifier? attribute-list? type
+    # type-specifiyer -> 'inout' | '__owned' | '__unowned'
+    Node('AttributedType', kind='Type',
          children=[
-             Child('Attributes', kind='AttributeList'),
-             Child('InOutKeyword', kind='InoutToken',
+             Child('Specifier', kind='Token',
+                   text_choices=['inout', '__shared', '__owned'],
                    is_optional=True),
-             Child('Type', kind='Type'),
-         ]),
-
-    # protocol-composition-element-list -> protocol-composition-element
-    #   protocol-composition-element-list?
-    Node('ProtocolCompositionElementList', kind='SyntaxCollection',
-         element='ProtocolCompositionElement'),
-
-    # tuple-type-element-list -> tuple-type-element tuple-type-element-list?
-    Node('TupleTypeElementList', kind='SyntaxCollection',
-         element='TupleTypeElement'),
-
-    # protocol-composition-element -> type-identifier '&'
-    Node('ProtocolCompositionElement', kind='Syntax',
-         children=[
-             Child('ProtocolType', kind='Type'),
-             Child('Ampersand', kind='AmpersandToken',
+             Child('Attributes', kind='AttributeList',
                    is_optional=True),
+             Child('BaseType', kind='Type'),
          ]),
 
     # generic-argument-list -> generic-argument generic-argument-list?
@@ -167,30 +190,4 @@
              Child('Arguments', kind='GenericArgumentList'),
              Child('RightAngleBracket', kind='RightAngleToken'),
          ]),
-
-    # function-type-argument -> identifier? identifier? ':'
-    #   type-annotation ','?
-    Node('FunctionTypeArgument', kind='Syntax',
-         children=[
-             Child('ExternalName', kind='IdentifierToken',
-                   is_optional=True),
-             Child('LocalName', kind='IdentifierToken',
-                   is_optional=True),
-             Child('Colon', kind='ColonToken',
-                   is_optional=True),
-             Child('TypeAnnotation', kind='TypeAnnotation'),
-             Child('TrailingComma', kind='CommaToken',
-                   is_optional=True),
-         ]),
-
-    # function-type-argument-list -> function-type-argument
-    #   function-type-argument-list?
-    Node('FunctionTypeArgumentList', kind='SyntaxCollection',
-         element='FunctionTypeArgument'),
-
-    # protocol-composition-type -> protocol-composition-elements
-    Node('ProtocolCompositionType', kind='Type',
-         children=[
-             Child('Elements', kind='ProtocolCompositionElementList'),
-         ]),
 ]
diff --git a/utils/gyb_syntax_support/__init__.py b/utils/gyb_syntax_support/__init__.py
index 36ded62..824448f 100644
--- a/utils/gyb_syntax_support/__init__.py
+++ b/utils/gyb_syntax_support/__init__.py
@@ -28,6 +28,8 @@
     else:
         missing_kind = "Unknown" if child.syntax_kind == "Syntax" \
                        else child.syntax_kind
+        if child.node_choices:
+            return make_missing_child(child.node_choices[0])
         return 'RawSyntax::missing(SyntaxKind::%s)' % missing_kind
 
 
diff --git a/utils/round-trip-syntax-test b/utils/round-trip-syntax-test
index b00da1c..29eefe3 100755
--- a/utils/round-trip-syntax-test
+++ b/utils/round-trip-syntax-test
@@ -172,7 +172,7 @@
                                  args.skip_bad_syntax)
                    for filename in all_input_files]
 
-    failed = reduce(lambda a, b: a and b,
+    failed = reduce(lambda a, b: a or b,
                     map(run_task, lex_tasks + parse_tasks))
     sys.exit(1 if failed else 0)
 
diff --git a/utils/scale-test b/utils/scale-test
index f494e3d..fd290a0 100755
--- a/utils/scale-test
+++ b/utils/scale-test
@@ -102,6 +102,8 @@
         d = ensure_tmpdir(args.tmpdir)
         inputs = [write_input_file(args, ast, d, i) for i in rng]
         primary = inputs[primary_idx]
+        # frontend no longer accepts duplicate inputs
+        del inputs[primary_idx]
         ofile = "out.o"
 
         mode = "-c"
diff --git a/utils/update_checkout.py b/utils/update_checkout.py
index 8221365..b460e1b 100755
--- a/utils/update_checkout.py
+++ b/utils/update_checkout.py
@@ -225,8 +225,9 @@
         print("Cloning '" + repo_name + "'")
 
         if skip_history:
-            shell.run(['git', 'clone', '--recursive', '--depth', '1',
-                       remote, repo_name], echo=True)
+            shell.run(['git', 'clone', '--recursive', '--depth', '1', 
+                       '--branch', repo_branch, remote, repo_name],
+                      echo=True)
         else:
             shell.run(['git', 'clone', '--recursive', remote,
                        repo_name], echo=True)
diff --git a/validation-test/IDE/crashers_2_fixed/0017-editorplacehoder-at-eof.swift b/validation-test/IDE/crashers_2_fixed/0017-editorplacehoder-at-eof.swift
new file mode 100644
index 0000000..92eb1fe
--- /dev/null
+++ b/validation-test/IDE/crashers_2_fixed/0017-editorplacehoder-at-eof.swift
@@ -0,0 +1,4 @@
+// RUN: %target-swift-ide-test -structure -source-filename=%s
+// rdar://problem/36081659
+
+var str = <#T##String#>
diff --git a/validation-test/PrintAsObjC/reintroduced-new.m b/validation-test/PrintAsObjC/reintroduced-new.m
deleted file mode 100644
index a595e79..0000000
--- a/validation-test/PrintAsObjC/reintroduced-new.m
+++ /dev/null
@@ -1,26 +0,0 @@
-// REQUIRES: objc_interop
-
-// RUN: %empty-directory(%t)
-
-// FIXME: BEGIN -enable-source-import hackaround
-// RUN:  %target-swift-frontend(mock-sdk: -sdk %S/../../test/Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../../test/Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift
-// FIXME: END -enable-source-import hackaround
-
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../../test/Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/Inputs/reintroduced-new.swift -disable-objc-attr-requires-foundation-module -module-name main
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../../test/Inputs/clang-importer-sdk -I %t) -parse-as-library %t/main.swiftmodule -typecheck -emit-objc-header-path %t/generated.h -disable-objc-attr-requires-foundation-module
-// RUN: not %clang -fsyntax-only -x objective-c %s -include %t/generated.h -fobjc-arc -fmodules -Werror -isysroot %S/../../test/Inputs/clang-importer-sdk 2>&1 | %FileCheck %s
-
-// CHECK-NOT: error:
-
-void test() {
-  // CHECK: :[[@LINE+1]]:{{[0-9]+}}: error: 'init' is unavailable
-  (void)[[Base alloc] init];
-   // CHECK-NOT: error:
-  (void)[[Sub alloc] init];
-  // CHECK: :[[@LINE+1]]:{{[0-9]+}}: error: 'new' is unavailable
-  (void)[Base new];
-   // CHECK-NOT: error:
-  (void)[Sub new];
-}
-
-// CHECK-NOT: error:
\ No newline at end of file
diff --git a/validation-test/compiler_crashers_fixed/28779-parent-parent-is-nominaltype-parent-is-boundgenerictype-parent-is-unboundgeneric.swift b/validation-test/compiler_crashers/28779-parent-parent-is-nominaltype-parent-is-boundgenerictype-parent-is-unboundgeneric.swift
similarity index 88%
rename from validation-test/compiler_crashers_fixed/28779-parent-parent-is-nominaltype-parent-is-boundgenerictype-parent-is-unboundgeneric.swift
rename to validation-test/compiler_crashers/28779-parent-parent-is-nominaltype-parent-is-boundgenerictype-parent-is-unboundgeneric.swift
index e507d78..631ea5a 100644
--- a/validation-test/compiler_crashers_fixed/28779-parent-parent-is-nominaltype-parent-is-boundgenerictype-parent-is-unboundgeneric.swift
+++ b/validation-test/compiler_crashers/28779-parent-parent-is-nominaltype-parent-is-boundgenerictype-parent-is-unboundgeneric.swift
@@ -6,5 +6,5 @@
 // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
 
 // REQUIRES: asserts
-// RUN: not %target-swift-frontend %s -emit-ir
+// RUN: not --crash %target-swift-frontend %s -emit-ir
 protocol P{func a:Self.a.a{}class a{class a
diff --git a/validation-test/compiler_crashers_2_fixed/0134-rdar35947198.swift b/validation-test/compiler_crashers_2_fixed/0134-rdar35947198.swift
new file mode 100644
index 0000000..fe40466
--- /dev/null
+++ b/validation-test/compiler_crashers_2_fixed/0134-rdar35947198.swift
@@ -0,0 +1,52 @@
+// RUN: %target-swift-frontend %s -O -emit-sil | %FileCheck %s
+
+// CHECK-LABEL: sil shared [transparent] [thunk] @_T0Sf4main7NumProtA2aBP5valueSdyFTW : $@convention(witness_method: NumProt) (@in_guaranteed Float) -> Double
+// CHECK-NOT: %1 = load %0 : $*Float
+// CHECK-NOT: function_ref @_T0Sf4mainE5valueSdyF : $@convention(method) (Float) -> Double
+// CHECK: %1 = struct_element_addr %0 : $*Float, #Float._value // user: %2
+// CHECK: %2 = load %1 : $*Builtin.FPIEEE32               // user: %3
+// CHECK: %3 = builtin "fpext_FPIEEE32_FPIEEE64"(%2 : $Builtin.FPIEEE32) : $Builtin.FPIEEE64 // user: %4
+// CHECK: %4 = struct $Double (%3 : $Builtin.FPIEEE64)    // user: %5
+// CHECK: return %4 : $Double
+
+public protocol NumProt: Prot {
+    func value() -> Double
+}
+
+extension Float: NumProt {
+    public func value() -> Double {
+        return Double(self)
+    }
+}
+
+public protocol Prot: CustomStringConvertible {
+    func getOp() -> Op
+}
+
+extension Prot {
+    public func getOp() -> Op {
+        return Op("\(self) ")
+    }
+}
+
+public protocol CompProt: Prot {}
+
+open class Op: CompProt {
+    fileprivate var valueText = ""
+    
+    open var description: String {
+        return "42"
+    }
+    
+    open func getOp() -> Op {
+        return self
+    }
+
+    public init(_ value: Double) {
+        self.valueText = "\(value)"
+    }
+
+    public init(_ operationString: String) {
+        self.valueText = operationString
+    }
+}
diff --git a/validation-test/compiler_crashers_2_fixed/0135-rdar26140749.swift b/validation-test/compiler_crashers_2_fixed/0135-rdar26140749.swift
new file mode 100644
index 0000000..f3886fc
--- /dev/null
+++ b/validation-test/compiler_crashers_2_fixed/0135-rdar26140749.swift
@@ -0,0 +1,13 @@
+// RUN: not %target-swift-frontend %s -typecheck
+
+protocol ProtocolWithCount: Collection {
+    var count : UInt64 { get }
+}
+
+class ClassWithoutCount : ProtocolWithCount {
+//    var count: UInt64 = 0
+    var startIndex: UInt64 { get { return 0 }}
+    var endIndex: UInt64 { get { return 0 }}
+    subscript(i:UInt64) -> Int64 { get {return 0}}
+}
+
diff --git a/validation-test/compiler_crashers_2_fixed/0136-rdar35082483.swift b/validation-test/compiler_crashers_2_fixed/0136-rdar35082483.swift
new file mode 100644
index 0000000..5df35be
--- /dev/null
+++ b/validation-test/compiler_crashers_2_fixed/0136-rdar35082483.swift
@@ -0,0 +1,20 @@
+// RUN: not %target-swift-frontend %s -typecheck
+
+struct S : Sequence {
+  struct Iterator : IteratorProtocol {
+    mutating func next() -> Int? {
+      fatalError()
+    }
+  }
+
+  func makeIterator() -> Iterator {
+    fatalError()
+  }
+}
+
+extension S : Collection {
+  typealias Index = Int
+
+  var startIndex: Int { return 0 }
+  var endIndex: Int { return 1 }
+}
diff --git a/validation-test/stdlib/Collection/FlattenCollection.swift.gyb b/validation-test/stdlib/Collection/FlattenCollection.swift.gyb
new file mode 100644
index 0000000..26849a5
--- /dev/null
+++ b/validation-test/stdlib/Collection/FlattenCollection.swift.gyb
@@ -0,0 +1,77 @@
+// -*- swift -*-
+// RUN: %target-run-simple-swiftgyb
+// REQUIRES: executable_test
+
+import SwiftPrivate
+import StdlibUnittest
+import StdlibCollectionUnittest
+
+var tests = TestSuite("FlattenCollection")
+
+%{
+variations = [('', 'Sequence'), ('', 'Collection'), ('Bidirectional', 'Collection')]
+}%
+
+// Test collections using value types as elements.
+% for (traversal, kind) in variations:
+tests.add${traversal}${kind}Tests(
+  make${kind}: { (elements: [OpaqueValue<Int>]) -> Flatten${kind}<Minimal${traversal}${kind}<Minimal${traversal}${kind}<OpaqueValue<Int>>>> in
+    Minimal${traversal}${kind}(elements: elements.map { Minimal${traversal}${kind}(elements: [$0]) }).joined()
+  },
+  wrapValue: identity,
+  extractValue: identity,
+  make${kind}OfEquatable: { (elements: [MinimalEquatableValue]) -> Flatten${kind}<Minimal${traversal}${kind}<Minimal${traversal}${kind}<MinimalEquatableValue>>> in
+    Minimal${traversal}${kind}(elements: elements.map { Minimal${traversal}${kind}(elements: [$0]) }).joined()
+  },
+  wrapValueIntoEquatable: identityEq,
+  extractValueFromEquatable: identityEq
+)
+% end
+
+// Test collections using reference types as elements.
+% for (traversal, kind) in variations:
+tests.add${traversal}${kind}Tests(
+  make${kind}: { (elements: [LifetimeTracked]) -> Flatten${kind}<Minimal${traversal}${kind}<Minimal${traversal}${kind}<LifetimeTracked>>> in
+    Minimal${traversal}${kind}(elements: elements.map { Minimal${traversal}${kind}(elements: [$0]) }).joined()
+  },
+  wrapValue: { (element: OpaqueValue<Int>) in
+    LifetimeTracked(element.value, identity: element.identity)
+  },
+  extractValue: { (element: LifetimeTracked) in
+    OpaqueValue(element.value, identity: element.identity)
+  },
+  make${kind}OfEquatable: { (elements: [LifetimeTracked]) -> Flatten${kind}<Minimal${traversal}${kind}<Minimal${traversal}${kind}<LifetimeTracked>>> in
+    Minimal${traversal}${kind}(elements: elements.map { Minimal${traversal}${kind}(elements: [$0]) }).joined()
+  },
+  wrapValueIntoEquatable: { (element: MinimalEquatableValue) in
+    LifetimeTracked(element.value, identity: element.identity)
+  },
+  extractValueFromEquatable: { (element: LifetimeTracked) in
+    MinimalEquatableValue(element.value, identity: element.identity)
+  }
+)
+% end
+
+// Test collection instances and iterators.
+% for (traversal, kind) in variations:
+tests.test("FlattenCollection instances (${traversal}${kind})") {
+  do {
+    let expected : [String] = []
+    let base: [[String]] = [[], [], []]
+    check${traversal}${kind}(
+      expected,
+      Minimal${traversal}${kind}(elements: base).joined(),
+      sameValue: { $0 == $1 })
+  }
+  do {
+    let expected = ["apple", "orange", "banana", "grapefruit", "lychee"]
+    let base = [["apple", "orange"], ["banana", "grapefruit"], ["lychee"]]
+    check${traversal}${kind}(
+      expected,
+      Minimal${traversal}${kind}(elements: base).joined(),
+      sameValue: { $0 == $1 })
+  }
+}
+% end
+
+runAllTests()
diff --git a/validation-test/stdlib/CollectionDiagnostics.swift b/validation-test/stdlib/CollectionDiagnostics.swift
index 0063b43..f1158bc 100644
--- a/validation-test/stdlib/CollectionDiagnostics.swift
+++ b/validation-test/stdlib/CollectionDiagnostics.swift
@@ -7,8 +7,7 @@
 // Check that Collection.SubSequence is constrained to Collection.
 //
 
-// expected-error@+2 {{type 'CollectionWithBadSubSequence' does not conform to protocol 'Collection'}}
-// expected-error@+1 {{type 'CollectionWithBadSubSequence' does not conform to protocol 'Sequence'}}
+// expected-error@+1 {{type 'CollectionWithBadSubSequence' does not conform to protocol 'Collection'}}
 struct CollectionWithBadSubSequence : Collection {
   var startIndex: MinimalIndex {
     fatalError("unreachable")
@@ -22,7 +21,6 @@
     fatalError("unreachable")
   }
 
-  // expected-note@+2 {{possibly intended match}}
   // expected-note@+1 {{possibly intended match}}
   typealias SubSequence = OpaqueValue<Int8>
 }
diff --git a/validation-test/stdlib/CollectionType.swift.gyb b/validation-test/stdlib/CollectionType.swift.gyb
index f826161..0f287a3 100644
--- a/validation-test/stdlib/CollectionType.swift.gyb
+++ b/validation-test/stdlib/CollectionType.swift.gyb
@@ -853,4 +853,28 @@
 % end
 
 
+struct RACollectionWithIntIndex<T> {
+  var contents: [T]
+}
+
+extension RACollectionWithIntIndex: RandomAccessCollection {
+  var startIndex: Int { return contents.startIndex }
+  var endIndex: Int { return contents.endIndex }
+  subscript(index: Int) -> T {
+    get { return contents[index] }
+    set { }
+  }
+}
+
+CollectionTypeTests.test("AssociatedTypes/RACollectionWithIntIndex") {
+  typealias C = RACollectionWithIntIndex<Void>
+  expectCollectionAssociatedTypes(
+    collectionType: C.self,
+    iteratorType: IndexingIterator<C>.self,
+    subSequenceType: Slice<C>.self,
+    indexType: Int.self,
+    indicesType: CountableRange<Int>.self)
+}
+
+
 runAllTests()
diff --git a/validation-test/stdlib/ExistentialCollection.swift.gyb b/validation-test/stdlib/ExistentialCollection.swift.gyb
index 2a65c85..4e98beb 100644
--- a/validation-test/stdlib/ExistentialCollection.swift.gyb
+++ b/validation-test/stdlib/ExistentialCollection.swift.gyb
@@ -72,9 +72,9 @@
 
     // This is a really complicated type of no interest to our
     // clients.
-    let iterator: LazyMapIterator<
-        IndexingIterator<CountableRange<Int>>, OpaqueValue<Int>
-      > = lazyStrings.makeIterator()
+    let iterator: LazyMapSequence<
+      CountableRange<Int>, OpaqueValue<Int>
+    >.Iterator = lazyStrings.makeIterator()
     return AnyIterator(iterator)
   }
   expectEqual([0, 1, 2, 3, 4], Array(digits()).map { $0.value })
@@ -258,7 +258,7 @@
 %   end
 
   do {
-    var startIndex = c.startIndex
+    let startIndex = c.startIndex
     var badBounds = c.index(c.startIndex, offsetBy: 3)..<c.endIndex
 
     Log.subscriptIndex.expectIncrement(Base.self) {
diff --git a/validation-test/stdlib/Lazy.swift.gyb b/validation-test/stdlib/Lazy.swift.gyb
index 22e4a79..9518334 100644
--- a/validation-test/stdlib/Lazy.swift.gyb
+++ b/validation-test/stdlib/Lazy.swift.gyb
@@ -437,7 +437,7 @@
     underestimatedCount: .value(42))
   var lazySeq = s.lazy
   expectType(
-    Lazy${TraversalCollection}<
+    LazyCollection<
       Minimal${TraversalCollection}<OpaqueValue<Int>>
     >.self,
     &lazySeq)
@@ -555,7 +555,7 @@
     underestimatedCount: .value(42))
   var reversed = base.lazy.reversed()
   expectType(
-    Lazy${TraversalCollection}<
+    LazyCollection<
       ${ReversedType}<Minimal${TraversalCollection}<OpaqueValue<Int>>>
     >.self, &reversed)
 
@@ -564,7 +564,7 @@
 
   var reversedTwice = reversed.reversed()
   expectType(
-    Lazy${TraversalCollection}<
+    LazyCollection<
       ${ReversedType}<${ReversedType}<
         Minimal${TraversalCollection}<OpaqueValue<Int>>
       >>>.self, &reversedTwice)
@@ -594,7 +594,7 @@
 //===----------------------------------------------------------------------===//
 
 // Check that the generic parameter is called 'Base'.
-extension ReversedIndex where Base : TestProtocol1 {
+extension ReversedCollection.Index where Base : TestProtocol1 {
   var _baseIsTestProtocol1: Bool {
     fatalError("not implemented")
   }
@@ -617,7 +617,7 @@
 //===----------------------------------------------------------------------===//
 
 // Check that the generic parameter is called 'Base'.
-extension ReversedIndex
+extension ReversedCollection.Index
     where Base : TestProtocol1, Base : RandomAccessCollection {
   var _baseIsTestProtocol1: Bool {
     fatalError("not implemented")
@@ -699,13 +699,13 @@
   let base = Minimal${TraversalCollection}(elements: expected)
   var actual = base.lazy
 
-  expectType(Lazy${TraversalCollection}<
+  expectType(LazyCollection<
     Minimal${TraversalCollection}<OpaqueValue<Int>>
   >.self, &actual)
 
   // Asking for .lazy again doesn't re-wrap the type
   var again = actual.lazy
-  expectType(Lazy${TraversalCollection}<
+  expectType(LazyCollection<
     Minimal${TraversalCollection}<OpaqueValue<Int>>
   >.self, &again)
 
@@ -863,7 +863,7 @@
   typealias Subject = LazyMapSequence<Base, OpaqueValue<Int32>>
   expectSequenceAssociatedTypes(
     sequenceType: Subject.self,
-    iteratorType: LazyMapIterator<Base.Iterator, OpaqueValue<Int32>>.self,
+    iteratorType: LazyMapSequence<Base, OpaqueValue<Int32>>.Iterator.self,
     subSequenceType: AnySequence<OpaqueValue<Int32>>.self)
 }
 
@@ -872,7 +872,7 @@
   typealias Subject = LazyMapCollection<Base, OpaqueValue<Int32>>
   expectCollectionAssociatedTypes(
     collectionType: Subject.self,
-    iteratorType: LazyMapIterator<Base.Iterator, OpaqueValue<Int32>>.self,
+    iteratorType: LazyMapCollection<Base, OpaqueValue<Int32>>.Iterator.self,
     subSequenceType: LazyMapCollection<Base.SubSequence, OpaqueValue<Int32>>.self,
     indexType: Base.Index.self,
     indicesType: Base.Indices.self)
@@ -883,7 +883,7 @@
   typealias Subject = LazyMapCollection<Base, OpaqueValue<Int32>>
   expectBidirectionalCollectionAssociatedTypes(
     collectionType: Subject.self,
-    iteratorType: LazyMapIterator<Base.Iterator, OpaqueValue<Int32>>.self,
+    iteratorType: LazyMapCollection<Base, OpaqueValue<Int32>>.Iterator.self,
     subSequenceType: LazyMapCollection<Base.SubSequence, OpaqueValue<Int32>>.self,
     indexType: Base.Index.self,
     indicesType: Base.Indices.self)
@@ -894,7 +894,7 @@
   typealias Subject = LazyMapCollection<Base, OpaqueValue<Int32>>
   expectRandomAccessCollectionAssociatedTypes(
     collectionType: Subject.self,
-    iteratorType: LazyMapIterator<Base.Iterator, OpaqueValue<Int32>>.self,
+    iteratorType: LazyMapCollection<Base, OpaqueValue<Int32>>.Iterator.self,
     subSequenceType: LazyMapCollection<Base.SubSequence, OpaqueValue<Int32>>.self,
     indexType: Base.Index.self,
     indicesType: Base.Indices.self)
@@ -1022,7 +1022,7 @@
 // the first selects even numbers and the second selects odd numbers,
 // both from an underlying sequence of whole numbers.
 func checkFilterIteratorBase<  S : Sequence, I>(_ s1: S, _ s2: S)
-where S.Iterator == LazyFilterIterator<I>, I.Element == OpaqueValue<Int> {
+where S.Iterator == LazyFilterSequence<I>.Iterator, I.Element == OpaqueValue<Int> {
   var iter1 = s1.makeIterator()
   expectEqual(0, iter1.next()!.value)
   expectEqual(2, iter1.next()!.value)
@@ -1143,7 +1143,7 @@
   typealias Subject = LazyFilterSequence<Base>
   expectSequenceAssociatedTypes(
     sequenceType: Subject.self,
-    iteratorType: LazyFilterIterator<Base.Iterator>.self,
+    iteratorType: LazyFilterSequence<Base>.Iterator.self,
     subSequenceType: AnySequence<OpaqueValue<Int>>.self)
 }
 
@@ -1152,7 +1152,7 @@
   typealias Subject = LazyFilterCollection<Base>
   expectCollectionAssociatedTypes(
     collectionType: Subject.self,
-    iteratorType: LazyFilterIterator<Base.Iterator>.self,
+    iteratorType: LazyFilterCollection<Base>.Iterator.self,
     subSequenceType: LazyFilterCollection<Base.SubSequence>.self,
     indexType: Base.Index.self,
     indicesType: DefaultIndices<Subject>.self)
@@ -1163,10 +1163,10 @@
   typealias Subject = LazyFilterCollection<Base>
   expectBidirectionalCollectionAssociatedTypes(
     collectionType: Subject.self,
-    iteratorType: LazyFilterIterator<Base.Iterator>.self,
+    iteratorType: LazyFilterCollection<Base>.Iterator.self,
     subSequenceType: LazyFilterCollection<Base.SubSequence>.self,
     indexType: Base.Index.self,
-    indicesType: DefaultBidirectionalIndices<Subject>.self)
+    indicesType: DefaultIndices<Subject>.self)
 }
 
 tests.test("lazy.filter/TypeInference") {
@@ -1260,7 +1260,7 @@
 
   % for Traversal in 'Forward', 'Bidirectional':
   %   TraversalCollection = collectionForTraversal(Traversal)
-    tests.test("Flatten${TraversalCollection}/\(data)") {
+    tests.test("FlattenCollection/${Traversal}/\(data)") {
       let base = Minimal${TraversalCollection}(
         elements: data.map { Minimal${TraversalCollection}(elements: $0) })
 
@@ -1275,7 +1275,7 @@
         "unexpected laziness in \(type(of: flattened))")
     }
 
-    tests.test("Flatten${TraversalCollection}/Lazy\(data)") {
+    tests.test("FlattenCollection/${Traversal}/Lazy\(data)") {
       // Checking that flatten doesn't remove laziness
       let base = Minimal${TraversalCollection}(
         elements: data.map { Minimal${TraversalCollection}(elements: $0) }
@@ -1360,7 +1360,7 @@
     // FIXME(ABI)#82 (Associated Types with where clauses): SubSequence should be `LazyFilterBidirectionalCollection<Base.Slice>`.
     subSequenceType: Slice<Subject>.self,
     indexType: LazyPrefixWhileIndex<Base>.self,
-    indicesType: DefaultBidirectionalIndices<Subject>.self)
+    indicesType: DefaultIndices<Subject>.self)
 }
 
 //===--- LazyDropWhile ----------------------------------------------------===//
@@ -1418,7 +1418,7 @@
     // FIXME(ABI)#83 (Associated Types with where clauses): SubSequence should be `LazyFilterBidirectionalCollection<Base.Slice>`.
     subSequenceType: Slice<Subject>.self,
     indexType: LazyDropWhileIndex<Base>.self,
-    indicesType: DefaultBidirectionalIndices<Subject>.self)
+    indicesType: DefaultIndices<Subject>.self)
 }
 
 runAllTests()
diff --git a/validation-test/stdlib/MicroStdlib/Inputs/RuntimeStubs.c b/validation-test/stdlib/MicroStdlib/Inputs/RuntimeStubs.c
index 74cc302..f4fe6cd 100644
--- a/validation-test/stdlib/MicroStdlib/Inputs/RuntimeStubs.c
+++ b/validation-test/stdlib/MicroStdlib/Inputs/RuntimeStubs.c
@@ -7,6 +7,6 @@
 void _swift_slowDealloc(void) {}
 void _swift_storeEnumTagSinglePayload(void) {}
 void swift_allocateGenericValueMetadata(void) {}
-void swift_initEnumValueWitnessTableSinglePayload(void) {}
+void swift_initEnumMetadataSinglePayload(void) {}
 void _swift_retain(){}
 void swift_allocBox(){}
diff --git a/validation-test/stdlib/RangeReplaceable.swift.gyb b/validation-test/stdlib/RangeReplaceable.swift.gyb
index 5052074..d2c7208 100644
--- a/validation-test/stdlib/RangeReplaceable.swift.gyb
+++ b/validation-test/stdlib/RangeReplaceable.swift.gyb
@@ -2,9 +2,6 @@
 // RUN: %target-run-simple-swiftgyb
 // REQUIRES: executable_test
 
-// FIXME: rdar://35646292
-// XFAIL: resilient_stdlib
-
 import StdlibUnittest
 import StdlibCollectionUnittest
 
diff --git a/validation-test/stdlib/SequenceType.swift.gyb b/validation-test/stdlib/SequenceType.swift.gyb
index ae91910..9f8f19e 100644
--- a/validation-test/stdlib/SequenceType.swift.gyb
+++ b/validation-test/stdlib/SequenceType.swift.gyb
@@ -1022,8 +1022,8 @@
 //===----------------------------------------------------------------------===//
 
 // Check generic parameter names.
-extension Zip2Iterator
-  where Iterator1 : TestProtocol1, Iterator2 : TestProtocol1 {
+extension Zip2Sequence.Iterator
+  where Sequence1 : TestProtocol1, Sequence2 : TestProtocol1 {
 
   var _generator1IsTestProtocol1: Bool {
     fatalError("not implemented")