Merge pull request #10524 from bitjammer/rdar-32877771-markup-print-tags-xml

[Markup] Print Tags in documentation comment XML
diff --git a/benchmark/CMakeLists.txt b/benchmark/CMakeLists.txt
index 2d97f02..d9971cd 100644
--- a/benchmark/CMakeLists.txt
+++ b/benchmark/CMakeLists.txt
@@ -50,7 +50,6 @@
     single-source/ErrorHandling
     single-source/ExistentialPerformance
     single-source/Fibonacci
-    single-source/GlobalClass
     single-source/Hanoi
     single-source/Hash
     single-source/HashQuadratic
diff --git a/benchmark/single-source/GlobalClass.swift b/benchmark/single-source/GlobalClass.swift
deleted file mode 100644
index e9876a5..0000000
--- a/benchmark/single-source/GlobalClass.swift
+++ /dev/null
@@ -1,33 +0,0 @@
-//===--- GlobalClass.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
-//
-//===----------------------------------------------------------------------===//
-
-// Test inline cache with a global class. Make sure the retain|release pair
-// for the fast path is removed in the loop.
-import TestsUtils
-
-class A
-{
-  func f(_ a: Int) -> Int
-  {
-    return a + 1
-  }
-}
-
-var x = 0
-var a = A()
-@inline(never)
-public func run_GlobalClass(_ N: Int) {
-  for _ in 0..<N
-  {
-    x = a.f(x)
-  }
-}
diff --git a/benchmark/single-source/StringBuilder.swift b/benchmark/single-source/StringBuilder.swift
index 9d1d981..3ea3c5d 100644
--- a/benchmark/single-source/StringBuilder.swift
+++ b/benchmark/single-source/StringBuilder.swift
@@ -13,8 +13,8 @@
 import TestsUtils
 
 @inline(never)
-func buildString() -> String {
-  var sb = "a"
+func buildString(_ i: String) -> String {
+  var sb = i
   for str in ["b","c","d","pizza"] {
     sb += str
   }
@@ -24,26 +24,26 @@
 @inline(never)
 public func run_StringBuilder(_ N: Int) {
   for _ in 1...5000*N {
-    _ = buildString()
+    _ = buildString(getString("a"))
   }
 }
 
 @inline(never)
-func addString() -> String {
-  let s = "a" + "b" + "c" + "d" + "pizza"
+func addString(_ i: String) -> String {
+  let s = i + "b" + "c" + "d" + "pizza"
   return s
 }
 
 @inline(never)
 public func run_StringAdder(_ N: Int) {
   for _ in 1...5000*N {
-    _ = addString()
+    _ = addString(getString("a"))
   }
 }
 
 @inline(never)
-func buildStringUTF16() -> String {
-  var sb = "a"
+func buildStringUTF16(_ i: String) -> String {
+  var sb = i
   for str in ["πŸŽ‰","c","d","pizza"] {
     sb += str
   }
@@ -53,14 +53,14 @@
 @inline(never)
 public func run_StringUTF16Builder(_ N: Int) {
   for _ in 1...5000*N {
-    _ = buildStringUTF16()
+    _ = buildStringUTF16("a")
   }
 }
 
 
 @inline(never)
-func buildStringLong() -> String {
-  var sb = "πŸ‘»"
+func buildStringLong(_ i: String) -> String {
+  var sb = i
   let long = "Swift is a multi-paradigm, compiled programming language created for iOS, OS X, watchOS, tvOS and Linux development by Apple Inc. Swift is designed to work with Apple's Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift is intended to be more resilient to erroneous code (\"safer\") than Objective-C and also more concise. It is built with the LLVM compiler framework included in Xcode 6 and later and uses the Objective-C runtime, which allows C, Objective-C, C++ and Swift code to run within a single program."
   sb += long
   return sb
@@ -71,7 +71,7 @@
 @inline(never)
 public func run_StringBuilderLong(_ N: Int) {
   for _ in 1...5000*N {
-    _ = buildStringLong()
+    _ = buildStringLong("πŸ‘»")
   }
 }
 
diff --git a/benchmark/utils/TestsUtils.swift b/benchmark/utils/TestsUtils.swift
index ea8bc7b..b34230c 100644
--- a/benchmark/utils/TestsUtils.swift
+++ b/benchmark/utils/TestsUtils.swift
@@ -98,3 +98,6 @@
 @inline(never)
 public func getInt(_ x: Int) -> Int { return x }
 
+// The same for String.
+@inline(never)
+public func getString(_ s: String) -> String { return s }
diff --git a/benchmark/utils/main.swift b/benchmark/utils/main.swift
index 8e42e7f..225b4c3 100644
--- a/benchmark/utils/main.swift
+++ b/benchmark/utils/main.swift
@@ -55,7 +55,6 @@
 import ErrorHandling
 import ExistentialPerformance
 import Fibonacci
-import GlobalClass
 import Hanoi
 import Hash
 import HashQuadratic
@@ -237,7 +236,6 @@
 addTo(&precommitTests, "EqualSubstringSubstring", run_EqualSubstringSubstring)
 addTo(&precommitTests, "EqualSubstringSubstringGenericEquatable", run_EqualSubstringSubstringGenericEquatable)
 addTo(&precommitTests, "ErrorHandling", run_ErrorHandling)
-addTo(&precommitTests, "GlobalClass", run_GlobalClass)
 addTo(&precommitTests, "Hanoi", run_Hanoi)
 addTo(&precommitTests, "HashTest", run_HashTest)
 addTo(&precommitTests, "Histogram", run_Histogram)
diff --git a/cmake/modules/DarwinSDKs.cmake b/cmake/modules/DarwinSDKs.cmake
index d1cf7e8..8e680e6 100644
--- a/cmake/modules/DarwinSDKs.cmake
+++ b/cmake/modules/DarwinSDKs.cmake
@@ -25,7 +25,7 @@
 if(swift_build_ios_simulator)
   configure_sdk_darwin(
       IOS_SIMULATOR "iOS Simulator" "${SWIFT_DARWIN_DEPLOYMENT_VERSION_IOS}"
-      iphonesimulator ios-simulator ios "x86_64")
+      iphonesimulator ios-simulator ios "i386;x86_64")
   configure_target_variant(
       IOS_SIMULATOR-DA "iOS Debug+Asserts"   IOS_SIMULATOR DA "Debug+Asserts")
   configure_target_variant(
diff --git a/cmake/modules/SwiftSource.cmake b/cmake/modules/SwiftSource.cmake
index 736cb5a..ac97012 100644
--- a/cmake/modules/SwiftSource.cmake
+++ b/cmake/modules/SwiftSource.cmake
@@ -475,7 +475,7 @@
       OUTPUT ${standard_outputs}
       DEPENDS
         ${swift_compiler_tool_dep}
-        ${source_files} ${SWIFTFILE_DEPENDS}
+        ${file_path} ${source_files} ${SWIFTFILE_DEPENDS}
         ${swift_ide_test_dependency} ${api_notes_dependency_target}
         ${obj_dirs_dependency_target}
       COMMENT "Compiling ${first_output}")
diff --git a/include/swift/AST/ProtocolConformance.h b/include/swift/AST/ProtocolConformance.h
index 3c8dad1..37d81e5 100644
--- a/include/swift/AST/ProtocolConformance.h
+++ b/include/swift/AST/ProtocolConformance.h
@@ -398,13 +398,6 @@
     return ContextAndInvalid.getPointer().dyn_cast<AbstractStorageDecl *>();
   }
 
-  bool isSerialized() const {
-    auto *nominal = getType()->getAnyNominal();
-    return nominal->hasFixedLayout() &&
-           getProtocol()->getEffectiveAccess() >= Accessibility::Public &&
-           nominal->getEffectiveAccess() >= Accessibility::Public;
-  }
-
   /// Retrieve the type witness and type decl (if one exists)
   /// for the given associated type.
   std::pair<Type, TypeDecl *>
diff --git a/include/swift/Frontend/FrontendOptions.h b/include/swift/Frontend/FrontendOptions.h
index 4019a4e..021e27b 100644
--- a/include/swift/Frontend/FrontendOptions.h
+++ b/include/swift/Frontend/FrontendOptions.h
@@ -144,6 +144,11 @@
   /// Intended for debugging purposes only.
   unsigned WarnLongExpressionTypeChecking = 0;
 
+  /// If non-zero, overrides the default threshold for how long we let
+  /// the expression type checker run before we consider an expression
+  /// too complex.
+  unsigned SolverExpressionTimeThreshold = 0;
+
   enum ActionType {
     NoneAction, ///< No specific action
     Parse, ///< Parse only
diff --git a/include/swift/IDE/DigesterEnums.def b/include/swift/IDE/DigesterEnums.def
index 4f44e2a..2b0fc31 100644
--- a/include/swift/IDE/DigesterEnums.def
+++ b/include/swift/IDE/DigesterEnums.def
@@ -88,6 +88,7 @@
 KEY(declAttributes)
 KEY(declKind)
 KEY(ownership)
+KEY(superclassUsr)
 
 KNOWN_TYPE(Optional)
 KNOWN_TYPE(ImplicitlyUnwrappedOptional)
diff --git a/include/swift/Option/FrontendOptions.td b/include/swift/Option/FrontendOptions.td
index e561b1b..62926fe 100644
--- a/include/swift/Option/FrontendOptions.td
+++ b/include/swift/Option/FrontendOptions.td
@@ -326,6 +326,8 @@
 def warn_long_expression_type_checking_EQ : Joined<["-"], "warn-long-expression-type-checking=">,
   Alias<warn_long_expression_type_checking>;
 
+def solver_expression_time_threshold_EQ : Joined<["-"], "solver-expression-time-threshold=">;
+
 def enable_source_import : Flag<["-"], "enable-source-import">,
   HelpText<"Enable importing of Swift source files">;
 
diff --git a/include/swift/Runtime/Debug.h b/include/swift/Runtime/Debug.h
index 838d208..7512d1a 100644
--- a/include/swift/Runtime/Debug.h
+++ b/include/swift/Runtime/Debug.h
@@ -139,7 +139,9 @@
 /// non-fatal warning, which should be logged as a runtime issue. Please keep
 /// all integer values pointer-sized.
 struct RuntimeErrorDetails {
-  // ABI version, needs to be "1" currently.
+  static const uintptr_t currentVersion = 2;
+
+  // ABI version, needs to be set to "currentVersion".
   uintptr_t version;
 
   // A short hyphenated string describing the type of the issue, e.g.
@@ -169,11 +171,43 @@
   // and the pointer to the array of extra threads.
   uintptr_t numExtraThreads;
   Thread *threads;
+
+  // Describes a suggested fix-it. Text in [startLine:startColumn,
+  // endLine:endColumn) is to be replaced with replacementText.
+  struct FixIt {
+    const char *filename;
+    uintptr_t startLine;
+    uintptr_t startColumn;
+    uintptr_t endLine;
+    uintptr_t endColumn;
+    const char *replacementText;
+  };
+
+  // Describes some extra information, possible with fix-its, about the current
+  // runtime issue.
+  struct Note {
+    const char *description;
+    uintptr_t numFixIts;
+    FixIt *fixIts;
+  };
+
+  // Number of suggested fix-its, and the pointer to the array of them.
+  uintptr_t numFixIts;
+  FixIt *fixIts;
+
+  // Number of related notes, and the pointer to the array of them.
+  uintptr_t numNotes;
+  Note *notes;
+};
+
+enum: uintptr_t {
+  RuntimeErrorFlagNone = 0,
+  RuntimeErrorFlagFatal = 1 << 0
 };
 
 /// Debugger hook. Calling this stops the debugger with a message and details
 /// about the issues.
-void reportToDebugger(bool isFatal, const char *message,
+void reportToDebugger(uintptr_t flags, const char *message,
                       RuntimeErrorDetails *details = nullptr);
 
 // namespace swift
diff --git a/include/swift/SIL/SILInstruction.h b/include/swift/SIL/SILInstruction.h
index 64da36a..8bc8053 100644
--- a/include/swift/SIL/SILInstruction.h
+++ b/include/swift/SIL/SILInstruction.h
@@ -6400,12 +6400,16 @@
     case ValueKind::TryApplyInst:
       return 0;
     case ValueKind::PartialApplyInst:
+      // The arguments to partial_apply are a suffix of the arguments to the
+      // the actually-called function.
       return getSubstCalleeConv().getNumSILArguments() - getNumArguments();
     default:
       llvm_unreachable("not implemented for this instruction!");
     }
   }
 
+  // Translate the index of the argument to the full apply or partial_apply into
+  // to the corresponding index into the arguments of the called function.
   unsigned getCalleeArgIndex(Operand &oper) {
     assert(oper.getUser() == Inst);
     assert(oper.getOperandNumber() >= getOperandIndexOfFirstArgument());
diff --git a/include/swift/SIL/SILWitnessTable.h b/include/swift/SIL/SILWitnessTable.h
index 40f62c3..3c6b5a1 100644
--- a/include/swift/SIL/SILWitnessTable.h
+++ b/include/swift/SIL/SILWitnessTable.h
@@ -34,8 +34,10 @@
 
 class SILFunction;
 class SILModule;
+class ProtocolConformance;
 class NormalProtocolConformance;
 enum IsSerialized_t : unsigned char;
+enum class ResilienceStrategy : unsigned;
 
 /// A mapping from each requirement of a protocol to the SIL-level entity
 /// satisfying the requirement for a concrete type.
@@ -269,13 +271,18 @@
   void convertToDefinition(ArrayRef<Entry> newEntries,
                            IsSerialized_t isSerialized);
 
+  // Whether a conformance should be serialized.
+  static bool conformanceIsSerialized(ProtocolConformance *conformance,
+                                      ResilienceStrategy strategy,
+                                      bool silSerializeWitnessTables);
+
   /// Print the witness table.
   void print(llvm::raw_ostream &OS, bool Verbose = false) const;
 
   /// Dump the witness table to stderr.
   void dump() const;
 };
-  
+
 } // end swift namespace
 
 //===----------------------------------------------------------------------===//
diff --git a/include/swift/Subsystems.h b/include/swift/Subsystems.h
index 23a348c..a71214c 100644
--- a/include/swift/Subsystems.h
+++ b/include/swift/Subsystems.h
@@ -192,7 +192,8 @@
                            OptionSet<TypeCheckingFlags> Options,
                            unsigned StartElem = 0,
                            unsigned WarnLongFunctionBodies = 0,
-                           unsigned WarnLongExpressionTypeChecking = 0);
+                           unsigned WarnLongExpressionTypeChecking = 0,
+                           unsigned ExpressionTimeoutThreshold = 0);
 
   /// Once type checking is complete, this walks protocol requirements
   /// to resolve default witnesses.
diff --git a/include/swift/TBDGen/TBDGen.h b/include/swift/TBDGen/TBDGen.h
index 3d6b36a..9dfa041 100644
--- a/include/swift/TBDGen/TBDGen.h
+++ b/include/swift/TBDGen/TBDGen.h
@@ -18,7 +18,8 @@
 class FileUnit;
 
 void enumeratePublicSymbols(FileUnit *module, llvm::StringSet<> &symbols,
-                            bool hasMultipleIRGenThreads, bool isWholeModule);
+                            bool hasMultipleIRGenThreads, bool isWholeModule,
+                            bool silSerializeWitnessTables);
 } // end namespace swift
 
 #endif
diff --git a/lib/AST/ASTPrinter.cpp b/lib/AST/ASTPrinter.cpp
index 5293aad..cfe80f9 100644
--- a/lib/AST/ASTPrinter.cpp
+++ b/lib/AST/ASTPrinter.cpp
@@ -2318,8 +2318,6 @@
 
   if (anyVar)
     printDocumentationComment(anyVar);
-  if (decl->isStatic())
-    printStaticKeyword(decl->getCorrectStaticSpelling());
 
   // FIXME: PatternBindingDecls don't have attributes themselves, so just assume
   // the variables all have the same attributes. This isn't exactly true
@@ -2327,6 +2325,12 @@
   if (anyVar) {
     printAttributes(anyVar);
     printAccessibility(anyVar);
+  }
+
+  if (decl->isStatic())
+    printStaticKeyword(decl->getCorrectStaticSpelling());
+
+  if (anyVar) {
     Printer << (anyVar->isSettable(anyVar->getDeclContext()) ? "var " : "let ");
   } else {
     Printer << "let ";
diff --git a/lib/AST/GenericSignatureBuilder.cpp b/lib/AST/GenericSignatureBuilder.cpp
index b62a6da..3ac80c8 100644
--- a/lib/AST/GenericSignatureBuilder.cpp
+++ b/lib/AST/GenericSignatureBuilder.cpp
@@ -2824,7 +2824,7 @@
   // Look through all of the associated types of all of the protocols
   // to which the parent conforms.
   llvm::SmallVector<Identifier, 2> bestMatches;
-  unsigned bestEditDistance = 0;
+  unsigned bestEditDistance = UINT_MAX;
   unsigned maxScore = (name.size() + 1) / 3;
   for (auto proto : pa->getParent()->getConformsTo()) {
     for (auto member : getProtocolMembers(proto)) {
@@ -2836,16 +2836,12 @@
                                          /*AllowReplacements=*/true,
                                          maxScore);
       assert(dist > 0 && "nested type should have matched associated type");
-      if (bestEditDistance == 0 || dist == bestEditDistance) {
-        bestEditDistance = dist;
-        maxScore = bestEditDistance;
-        bestMatches.push_back(assocType->getName());
-      } else if (dist < bestEditDistance) {
-        bestEditDistance = dist;
-        maxScore = bestEditDistance;
+      if (dist < bestEditDistance) {
+        maxScore = bestEditDistance = dist;
         bestMatches.clear();
-        bestMatches.push_back(assocType->getName());
       }
+      if (dist == bestEditDistance)
+        bestMatches.push_back(assocType->getName());
     }
   }
 
diff --git a/lib/ClangImporter/ClangImporter.cpp b/lib/ClangImporter/ClangImporter.cpp
index b60e3db..a703b44 100644
--- a/lib/ClangImporter/ClangImporter.cpp
+++ b/lib/ClangImporter/ClangImporter.cpp
@@ -563,24 +563,6 @@
     }
   }
 
-  if (triple.isOSDarwin()) {
-    std::string minVersionBuf;
-    llvm::raw_string_ostream minVersionOpt{minVersionBuf};
-    minVersionOpt << getMinVersionOptNameForDarwinTriple(triple);
-
-    unsigned major, minor, micro;
-    if (triple.isiOS()) {
-      triple.getiOSVersion(major, minor, micro);
-    } else if (triple.isWatchOS()) {
-      triple.getWatchOSVersion(major, minor, micro);
-    } else {
-      assert(triple.isMacOSX());
-      triple.getMacOSXVersion(major, minor, micro);
-    }
-    minVersionOpt << clang::VersionTuple(major, minor, micro);
-    invocationArgStrs.push_back(std::move(minVersionOpt.str()));
-  }
-
   if (searchPathOpts.SDKPath.empty()) {
     invocationArgStrs.push_back("-Xclang");
     invocationArgStrs.push_back("-nostdsysteminc");
@@ -665,6 +647,24 @@
   invocationArgStrs.push_back("-target");
   invocationArgStrs.push_back(triple.str());
 
+  if (triple.isOSDarwin()) {
+    std::string minVersionBuf;
+    llvm::raw_string_ostream minVersionOpt{minVersionBuf};
+    minVersionOpt << getMinVersionOptNameForDarwinTriple(triple);
+
+    unsigned major, minor, micro;
+    if (triple.isiOS()) {
+      triple.getiOSVersion(major, minor, micro);
+    } else if (triple.isWatchOS()) {
+      triple.getWatchOSVersion(major, minor, micro);
+    } else {
+      assert(triple.isMacOSX());
+      triple.getMacOSXVersion(major, minor, micro);
+    }
+    minVersionOpt << clang::VersionTuple(major, minor, micro);
+    invocationArgStrs.push_back(std::move(minVersionOpt.str()));
+  }
+
   invocationArgStrs.push_back(ImporterImpl::moduleImportBufferName);
 
   if (ctx.LangOpts.EnableAppExtensionRestrictions) {
diff --git a/lib/ClangImporter/ImportDecl.cpp b/lib/ClangImporter/ImportDecl.cpp
index 479bd45..3a1ffaf 100644
--- a/lib/ClangImporter/ImportDecl.cpp
+++ b/lib/ClangImporter/ImportDecl.cpp
@@ -128,7 +128,7 @@
       /*IsStatic*/false,
       /*IsLet*/isLet,
       /*IsCaptureList*/false,
-      SourceLoc(), name, ty, dc);
+      SourceLoc(), name, dc->mapTypeIntoContext(ty), dc);
   if (isImplicit)
     var->setImplicit();
   var->setInterfaceType(ty);
@@ -3167,7 +3167,7 @@
                        /*IsStatic*/false, /*IsLet*/ false,
                        /*IsCaptureList*/false,
                        Impl.importSourceLoc(decl->getLocStart()),
-                       name, type, dc);
+                       name, dc->mapTypeIntoContext(type), dc);
       result->setInterfaceType(type);
 
       // If this is a compatibility stub, mark is as such.
@@ -3388,7 +3388,7 @@
                               /*IsStatic*/ false, /*IsLet*/ false,
                               /*IsCaptureList*/false,
                               Impl.importSourceLoc(decl->getLocation()),
-                              name, type, dc);
+                              name, dc->mapTypeIntoContext(type), dc);
       result->setInterfaceType(type);
 
       // Handle attributes.
@@ -3464,7 +3464,7 @@
                        /*IsLet*/Impl.shouldImportGlobalAsLet(decl->getType()),
                        /*IsCaptureList*/false,
                        Impl.importSourceLoc(decl->getLocation()),
-                       name, type, dc);
+                       name, dc->mapTypeIntoContext(type), dc);
       result->setInterfaceType(type);
 
       // If imported as member, the member should be final.
@@ -4324,7 +4324,6 @@
                                          isInSystemModule(dc),
                                          /*isFullyBridgeable*/false);
         if (superclassType) {
-          superclassType = result->mapTypeOutOfContext(superclassType);
           assert(superclassType->is<ClassType>() ||
                  superclassType->is<BoundGenericClassType>());
           inheritedTypes.push_back(TypeLoc::withoutLoc(superclassType));
@@ -4539,8 +4538,8 @@
           getOverridableAccessibility(dc),
           /*IsStatic*/decl->isClassProperty(), /*IsLet*/false,
           /*IsCaptureList*/false, Impl.importSourceLoc(decl->getLocation()),
-          name, type, dc);
-      result->setInterfaceType(dc->mapTypeOutOfContext(type));
+          name, dc->mapTypeIntoContext(type), dc);
+      result->setInterfaceType(type);
 
       // Turn this into a computed property.
       // FIXME: Fake locations for '{' and '}'?
@@ -4930,6 +4929,7 @@
   auto storedUnderlyingType = Impl.importType(
       decl->getUnderlyingType(), ImportTypeKind::Value, isInSystemModule(dc),
       decl->getUnderlyingType()->isBlockPointerType(), OTK_None);
+
   if (auto objTy = storedUnderlyingType->getAnyOptionalObjectType())
     storedUnderlyingType = objTy;
 
@@ -5288,16 +5288,30 @@
   auto &C = Impl.SwiftContext;
   SmallVector<ParameterList *, 2> bodyParams;
 
-  // There is an inout 'self' when we have an instance method of a
-  // value-semantic type whose 'self' parameter is a
-  // pointer-to-non-const.
+  // There is an inout 'self' when the parameter is a pointer to a non-const
+  // instance of the type we're importing onto. Importing this as a method means
+  // that the method should be treated as mutating in this situation.
   bool selfIsInOut = false;
   if (selfIdx && !dc->getDeclaredTypeOfContext()->hasReferenceSemantics()) {
     auto selfParam = decl->getParamDecl(*selfIdx);
     auto selfParamTy = selfParam->getType();
     if ((selfParamTy->isPointerType() || selfParamTy->isReferenceType()) &&
-        !selfParamTy->getPointeeType().isConstQualified())
+        !selfParamTy->getPointeeType().isConstQualified()) {
       selfIsInOut = true;
+
+      // If there's a swift_newtype, check the levels of indirection: self is
+      // only inout if this is a pointer to the typedef type (which itself is a
+      // pointer).
+      if (auto nominalTypeDecl =
+              dc->getAsNominalTypeOrNominalTypeExtensionContext()) {
+        if (auto clangDCTy = dyn_cast_or_null<clang::TypedefNameDecl>(
+                nominalTypeDecl->getClangDecl()))
+          if (auto newtypeAttr = getSwiftNewtypeAttr(clangDCTy, getVersion()))
+            if (clangDCTy->getUnderlyingType().getCanonicalType() !=
+                selfParamTy->getPointeeType().getCanonicalType())
+              selfIsInOut = false;
+      }
+    }
   }
 
   bodyParams.push_back(ParameterList::createWithoutLoc(ParamDecl::createSelf(
@@ -5474,7 +5488,8 @@
 
   auto property = Impl.createDeclWithClangNode<VarDecl>(
       getter, Accessibility::Public, /*IsStatic*/isStatic, /*isLet*/false,
-      /*IsCaptureList*/false, SourceLoc(), propertyName, swiftPropertyType, dc);
+      /*IsCaptureList*/false, SourceLoc(), propertyName,
+      dc->mapTypeIntoContext(swiftPropertyType), dc);
   property->setInterfaceType(swiftPropertyType);
 
   // Note that we've formed this property.
@@ -7692,11 +7707,11 @@
     var = createDeclWithClangNode<VarDecl>(ClangN, Accessibility::Public,
                                            /*IsStatic*/isStatic, /*IsLet*/false,
                                            /*IsCaptureList*/false, SourceLoc(),
-                                           name, type, dc);
+                                           name, dc->mapTypeIntoContext(type), dc);
   } else {
     var = new (SwiftContext)
         VarDecl(/*IsStatic*/isStatic, /*IsLet*/false, /*IsCaptureList*/false,
-                SourceLoc(), name, type, dc);
+                SourceLoc(), name, dc->mapTypeIntoContext(type), dc);
   }
 
   var->setInterfaceType(type);
diff --git a/lib/ClangImporter/ImportType.cpp b/lib/ClangImporter/ImportType.cpp
index 924be56..8c3204b 100644
--- a/lib/ClangImporter/ImportType.cpp
+++ b/lib/ClangImporter/ImportType.cpp
@@ -565,7 +565,6 @@
       // Pull the corresponding generic type parameter from the imported class.
       const auto *typeParamContext = objcTypeParamDecl->getDeclContext();
       GenericSignature *genericSig = nullptr;
-      GenericEnvironment *genericEnv = nullptr;
       if (auto *category =
             dyn_cast<clang::ObjCCategoryDecl>(typeParamContext)) {
         auto ext = cast_or_null<ExtensionDecl>(
@@ -573,7 +572,6 @@
         if (!ext)
           return ImportResult();
         genericSig = ext->getGenericSignature();
-        genericEnv = ext->getGenericEnvironment();
       } else if (auto *interface =
           dyn_cast<clang::ObjCInterfaceDecl>(typeParamContext)) {
         auto cls = castIgnoringCompatibilityAlias<ClassDecl>(
@@ -581,7 +579,6 @@
         if (!cls)
           return ImportResult();
         genericSig = cls->getGenericSignature();
-        genericEnv = cls->getGenericEnvironment();
       }
       unsigned index = objcTypeParamDecl->getIndex();
       // Pull the generic param decl out of the imported class.
@@ -593,8 +590,8 @@
       if (index > genericSig->getGenericParams().size()) {
         return ImportResult();
       }
-      auto *paramDecl = genericSig->getGenericParams()[index];
-      return ImportResult(genericEnv->mapTypeIntoContext(paramDecl),
+
+      return ImportResult(genericSig->getGenericParams()[index],
                           ImportHint::ObjCPointer);
     }
 
@@ -1585,15 +1582,11 @@
   }
 
   // Import the result type.
-  auto type = importType(clangDecl->getReturnType(),
-                         (isAuditedResult ? ImportTypeKind::AuditedResult
-                                          : ImportTypeKind::Result),
-                         allowNSUIntegerAsInt,
-                         /*isFullyBridgeable*/ true, OptionalityOfReturn);
-  if (!type)
-    return type;
-
-  return dc->mapTypeOutOfContext(type);
+  return importType(clangDecl->getReturnType(),
+                    (isAuditedResult ? ImportTypeKind::AuditedResult
+                                     : ImportTypeKind::Result),
+                    allowNSUIntegerAsInt,
+                    /*isFullyBridgeable*/ true, OptionalityOfReturn);
 }
 
 Type ClangImporter::Implementation::
@@ -1684,10 +1677,11 @@
     auto paramInfo = createDeclWithClangNode<ParamDecl>(
         param, Accessibility::Private,
         /*IsLet*/ true, SourceLoc(), SourceLoc(), name,
-        importSourceLoc(param->getLocation()), bodyName, swiftParamTy,
+        importSourceLoc(param->getLocation()), bodyName,
+        dc->mapTypeIntoContext(swiftParamTy),
         ImportedHeaderUnit);
-    paramInfo->setInterfaceType(
-        dc->mapTypeOutOfContext(swiftParamTy));
+
+    paramInfo->setInterfaceType(swiftParamTy);
 
     if (addNoEscapeAttr)
       paramInfo->getAttrs().add(new (SwiftContext)
@@ -1876,6 +1870,21 @@
   llvm_unreachable("bad error convention");
 }
 
+// Sometimes re-mapping type from one context to another is required,
+// because the other context might have some of the generic parameters
+// bound to concerete types, which means that we might loose generic
+// signature when converting from class method to constructor and that
+// is going to result in incorrect type interpretation of the method.
+static Type mapTypeIntoContext(const DeclContext *fromDC,
+                               const DeclContext *toDC, Type type) {
+  if (fromDC == toDC)
+    return toDC->mapTypeIntoContext(type);
+
+  auto subs = toDC->getDeclaredTypeInContext()->getContextSubstitutionMap(
+                                            toDC->getParentModule(), fromDC);
+  return type.subst(subs);
+}
+
 Type ClangImporter::Implementation::importMethodType(
        const DeclContext *dc,
        const clang::ObjCMethodDecl *clangDecl,
@@ -1910,22 +1919,6 @@
   DeclContext *origDC = importDeclContextOf(clangDecl,
                                             clangDecl->getDeclContext());
   assert(origDC);
-  auto mapTypeIntoContext = [&](Type type) -> Type {
-    if (dc != origDC) {
-      // Replace origDC's archetypes with interface types.
-      type = origDC->mapTypeOutOfContext(type);
-
-      // Get the substitutions that we need to access a member of
-      // 'origDC' on 'dc'.
-      auto subs = dc->getDeclaredTypeInContext()
-          ->getContextSubstitutionMap(dc->getParentModule(), origDC);
-
-      // Apply them to the interface type to produce the final
-      // substituted type.
-      type = type.subst(subs);
-    }
-    return type;
-  };
 
   // Import the result type.
   CanType origSwiftResultTy;
@@ -1986,9 +1979,11 @@
         swiftResultTy = OptionalType::get(OptionalityOfReturn, swiftResultTy);
     }
   }
+
   if (!swiftResultTy)
     return Type();
-  swiftResultTy = mapTypeIntoContext(swiftResultTy);
+
+  swiftResultTy = mapTypeIntoContext(origDC, dc, swiftResultTy);
 
   CanType errorParamType;
 
@@ -2079,6 +2074,8 @@
     if (!swiftParamTy)
       return Type();
 
+    swiftParamTy = mapTypeIntoContext(origDC, dc, swiftParamTy);
+
     // If this is the error parameter, remember it, but don't build it
     // into the parameter type.
     if (paramIsError) {
@@ -2114,20 +2111,16 @@
     }
     ++nameIndex;
 
-    // It doesn't actually matter which DeclContext we use, so just use the
-    // imported header unit.
-    swiftParamTy = mapTypeIntoContext(swiftParamTy);
-
     // Set up the parameter info.
     auto paramInfo
       = createDeclWithClangNode<ParamDecl>(param, Accessibility::Private,
                                            /*IsLet*/ true,
                                            SourceLoc(), SourceLoc(), name,
                                            importSourceLoc(param->getLocation()),
-                                           bodyName, swiftParamTy,
+                                           bodyName,
+                                           swiftParamTy,
                                            ImportedHeaderUnit);
-    paramInfo->setInterfaceType(
-        dc->mapTypeOutOfContext(swiftParamTy));
+    paramInfo->setInterfaceType(dc->mapTypeOutOfContext(swiftParamTy));
 
     if (addNoEscapeAttr) {
       paramInfo->getAttrs().add(
@@ -2193,13 +2186,10 @@
     // Mark that the function type throws.
     extInfo = extInfo.withThrows(true);
   }
- 
-  swiftResultTy = dc->mapTypeOutOfContext(swiftResultTy);
 
   // Form the function type.
-  return FunctionType::get(
-      (*bodyParams)->getInterfaceType(SwiftContext),
-      swiftResultTy, extInfo);
+  return FunctionType::get((*bodyParams)->getInterfaceType(SwiftContext),
+                           dc->mapTypeOutOfContext(swiftResultTy), extInfo);
 }
 
 Type ClangImporter::Implementation::importAccessorMethodType(
@@ -2228,36 +2218,18 @@
   DeclContext *origDC = importDeclContextOf(property,
                                             property->getDeclContext());
   assert(origDC);
-  auto mapTypeIntoContext = [&](Type type) -> Type {
-    if (dc != origDC) {
-      // Replace origDC's archetypes with interface types.
-      type = origDC->mapTypeOutOfContext(type);
-
-      // Get the substitutions that we need to access a member of
-      // 'origDC' on 'dc'.
-      auto subs = dc->getDeclaredTypeInContext()
-          ->getContextSubstitutionMap(dc->getParentModule(), origDC);
-
-      // Apply them to the interface type to produce the final
-      // substituted type.
-      type = type.subst(subs);
-    }
-    return type;
-  };
 
   // Import the property type, independent of what kind of accessor this is.
   Type propertyTy = importPropertyType(property, isFromSystemModule);
   if (!propertyTy)
     return Type();
-  propertyTy = mapTypeIntoContext(propertyTy);
-  Type propertyInterfaceTy = dc->mapTypeOutOfContext(propertyTy);
 
+  propertyTy = mapTypeIntoContext(origDC, dc, propertyTy);
   // Now build up the resulting FunctionType and parameters.
   Type resultTy;
   if (isGetter) {
     *params = ParameterList::createEmpty(SwiftContext);
-    resultTy = propertyInterfaceTy;
-
+    resultTy = dc->mapTypeOutOfContext(propertyTy);
   } else {
     const clang::ParmVarDecl *param = clangDecl->parameters().front();
     ImportedName fullBodyName = importFullName(param, CurrentVersion);
@@ -2272,7 +2244,7 @@
                                            argLabel, nameLoc, bodyName,
                                            propertyTy,
                                            /*dummy DC*/ImportedHeaderUnit);
-    paramInfo->setInterfaceType(propertyInterfaceTy);
+    paramInfo->setInterfaceType(dc->mapTypeOutOfContext(propertyTy));
 
     *params = ParameterList::create(SwiftContext, paramInfo);
     resultTy = SwiftContext.getVoidDecl()->getDeclaredInterfaceType();
diff --git a/lib/Frontend/CompilerInvocation.cpp b/lib/Frontend/CompilerInvocation.cpp
index e894d6c..cf98610 100644
--- a/lib/Frontend/CompilerInvocation.cpp
+++ b/lib/Frontend/CompilerInvocation.cpp
@@ -226,6 +226,16 @@
     }
   }
 
+  if (const Arg *A = Args.getLastArg(OPT_solver_expression_time_threshold_EQ)) {
+    unsigned attempt;
+    if (StringRef(A->getValue()).getAsInteger(10, attempt)) {
+      Diags.diagnose(SourceLoc(), diag::error_invalid_arg_value,
+                     A->getAsString(Args), A->getValue());
+    } else {
+      Opts.SolverExpressionTimeThreshold = attempt;
+    }
+  }
+
   Opts.PlaygroundTransform |= Args.hasArg(OPT_playground);
   if (Args.hasArg(OPT_disable_playground_transform))
     Opts.PlaygroundTransform = false;
diff --git a/lib/Frontend/Frontend.cpp b/lib/Frontend/Frontend.cpp
index 6225c16..0704189 100644
--- a/lib/Frontend/Frontend.cpp
+++ b/lib/Frontend/Frontend.cpp
@@ -519,7 +519,8 @@
         performTypeChecking(MainFile, PersistentState.getTopLevelContext(),
                             TypeCheckOptions, CurTUElem,
                             options.WarnLongFunctionBodies,
-                            options.WarnLongExpressionTypeChecking);
+                            options.WarnLongExpressionTypeChecking,
+                            options.SolverExpressionTimeThreshold);
       }
       CurTUElem = MainFile.Decls.size();
     } while (!Done);
@@ -548,7 +549,8 @@
         performTypeChecking(*SF, PersistentState.getTopLevelContext(),
                             TypeCheckOptions, /*curElem*/ 0,
                             options.WarnLongFunctionBodies,
-                            options.WarnLongExpressionTypeChecking);
+                            options.WarnLongExpressionTypeChecking,
+                            options.SolverExpressionTimeThreshold);
 
   // Even if there were no source files, we should still record known
   // protocols.
diff --git a/lib/FrontendTool/FrontendTool.cpp b/lib/FrontendTool/FrontendTool.cpp
index c188aaa..45a5614 100644
--- a/lib/FrontendTool/FrontendTool.cpp
+++ b/lib/FrontendTool/FrontendTool.cpp
@@ -665,8 +665,10 @@
   }
 
   if (Action == FrontendOptions::EmitTBD) {
-    auto hasMultipleIRGenThreads = Invocation.getSILOptions().NumThreads > 1;
+    const auto &silOpts = Invocation.getSILOptions();
+    auto hasMultipleIRGenThreads = silOpts.NumThreads > 1;
     return writeTBD(Instance.getMainModule(), hasMultipleIRGenThreads,
+                    silOpts.SILSerializeWitnessTables,
                     opts.getSingleOutputFilename());
   }
 
@@ -942,14 +944,16 @@
         !astGuaranteedToCorrespondToSIL)
       break;
 
-    auto hasMultipleIRGenThreads = Invocation.getSILOptions().NumThreads > 1;
+    const auto &silOpts = Invocation.getSILOptions();
+    auto hasMultipleIRGenThreads = silOpts.NumThreads > 1;
     bool error;
     if (PrimarySourceFile)
       error = validateTBD(PrimarySourceFile, *IRModule, hasMultipleIRGenThreads,
-                          allSymbols);
+                          silOpts.SILSerializeWitnessTables, allSymbols);
     else
       error = validateTBD(Instance.getMainModule(), *IRModule,
-                          hasMultipleIRGenThreads, allSymbols);
+                          hasMultipleIRGenThreads,
+                          silOpts.SILSerializeWitnessTables, allSymbols);
     if (error)
       return true;
 
diff --git a/lib/FrontendTool/TBD.cpp b/lib/FrontendTool/TBD.cpp
index 9c68219..1b841d7 100644
--- a/lib/FrontendTool/TBD.cpp
+++ b/lib/FrontendTool/TBD.cpp
@@ -39,7 +39,7 @@
 }
 
 bool swift::writeTBD(ModuleDecl *M, bool hasMultipleIRGenThreads,
-                     StringRef OutputFilename) {
+                     bool silSerializeWitnessTables, StringRef OutputFilename) {
   std::error_code EC;
   llvm::raw_fd_ostream OS(OutputFilename, EC, llvm::sys::fs::F_None);
   if (EC) {
@@ -50,7 +50,7 @@
   llvm::StringSet<> symbols;
   for (auto file : M->getFiles())
     enumeratePublicSymbols(file, symbols, hasMultipleIRGenThreads,
-                           /*isWholeModule=*/true);
+                           /*isWholeModule=*/true, silSerializeWitnessTables);
 
   // Ensure the order is stable.
   for (auto &symbol : sortSymbols(symbols)) {
@@ -125,11 +125,12 @@
 
 bool swift::validateTBD(ModuleDecl *M, llvm::Module &IRModule,
                         bool hasMultipleIRGenThreads,
+                        bool silSerializeWitnessTables,
                         bool diagnoseExtraSymbolsInTBD) {
   llvm::StringSet<> symbols;
   for (auto file : M->getFiles())
     enumeratePublicSymbols(file, symbols, hasMultipleIRGenThreads,
-                           /*isWholeModule=*/true);
+                           /*isWholeModule=*/true, silSerializeWitnessTables);
 
   return validateSymbolSet(M->getASTContext().Diags, symbols, IRModule,
                            diagnoseExtraSymbolsInTBD);
@@ -137,10 +138,11 @@
 
 bool swift::validateTBD(FileUnit *file, llvm::Module &IRModule,
                         bool hasMultipleIRGenThreads,
+                        bool silSerializeWitnessTables,
                         bool diagnoseExtraSymbolsInTBD) {
   llvm::StringSet<> symbols;
   enumeratePublicSymbols(file, symbols, hasMultipleIRGenThreads,
-                         /*isWholeModule=*/false);
+                         /*isWholeModule=*/false, silSerializeWitnessTables);
 
   return validateSymbolSet(file->getParentModule()->getASTContext().Diags,
                            symbols, IRModule, diagnoseExtraSymbolsInTBD);
diff --git a/lib/FrontendTool/TBD.h b/lib/FrontendTool/TBD.h
index cff1720..98b2c8b 100644
--- a/lib/FrontendTool/TBD.h
+++ b/lib/FrontendTool/TBD.h
@@ -25,12 +25,14 @@
 class FrontendOptions;
 
 bool writeTBD(ModuleDecl *M, bool hasMultipleIRGenThreads,
-              llvm::StringRef OutputFilename);
+              bool silSerializeWitnessTables, llvm::StringRef OutputFilename);
 bool inputFileKindCanHaveTBDValidated(InputFileKind kind);
 bool validateTBD(ModuleDecl *M, llvm::Module &IRModule,
-                 bool hasMultipleIRGenThreads, bool diagnoseExtraSymbolsInTBD);
+                 bool hasMultipleIRGenThreads, bool silSerializeWitnessTables,
+                 bool diagnoseExtraSymbolsInTBD);
 bool validateTBD(FileUnit *M, llvm::Module &IRModule,
-                 bool hasMultipleIRGenThreads, bool diagnoseExtraSymbolsInTBD);
+                 bool hasMultipleIRGenThreads, bool silSerializeWitnessTables,
+                 bool diagnoseExtraSymbolsInTBD);
 }
 
 #endif
diff --git a/lib/IRGen/GenCall.cpp b/lib/IRGen/GenCall.cpp
index 1c15f41..79faf83 100644
--- a/lib/IRGen/GenCall.cpp
+++ b/lib/IRGen/GenCall.cpp
@@ -382,7 +382,9 @@
           packed = true;
         elts.push_back(type);
         expandedTyIndicesMap.push_back(idx - 1);
-        lastEnd = end;
+        lastEnd = begin + clang::CharUnits::fromQuantity(
+                              IGM.DataLayout.getTypeAllocSize(type));
+        assert(end <= lastEnd);
       });
 
   auto *coercionType = llvm::StructType::get(ctx, elts, packed);
@@ -419,7 +421,9 @@
           packed = true;
         elts.push_back(type);
         expandedTyIndicesMap.push_back(idx - 1);
-        lastEnd = end;
+        lastEnd = begin + clang::CharUnits::fromQuantity(
+                              IGM.DataLayout.getTypeAllocSize(type));
+        assert(end <= lastEnd);
       });
   auto *overlappedCoercionType = llvm::StructType::get(ctx, elts, packed);
   return {coercionType, overlappedCoercionType};
diff --git a/lib/Index/Index.cpp b/lib/Index/Index.cpp
index 706a158..479b3ed 100644
--- a/lib/Index/Index.cpp
+++ b/lib/Index/Index.cpp
@@ -263,25 +263,6 @@
     if (auto *VD = dyn_cast<ValueDecl>(D)) {
       if (!report(VD))
         return false;
-      if (auto *SD = dyn_cast<SubscriptDecl>(VD)) {
-        // Avoid indexing the indices, only walk the getter/setter.
-        if (SD->getGetter())
-          if (SourceEntityWalker::walk(cast<Decl>(SD->getGetter())))
-            return false;
-        if (SD->getSetter())
-          if (SourceEntityWalker::walk(cast<Decl>(SD->getSetter())))
-            return false;
-        if (SD->hasAddressors()) {
-          if (auto FD = SD->getAddressor())
-            SourceEntityWalker::walk(cast<Decl>(FD));
-          if (Cancelled)
-            return false;
-          if (auto FD = SD->getMutableAddressor())
-            SourceEntityWalker::walk(cast<Decl>(FD));
-        }
-        walkToDeclPost(D);
-        return false; // already walked what we needed.
-      }
     }
     if (auto *ED = dyn_cast<ExtensionDecl>(D))
       return reportExtension(ED);
@@ -885,12 +866,13 @@
 bool IndexSwiftASTWalker::report(ValueDecl *D) {
   if (startEntityDecl(D)) {
     // Pass accessors.
-    if (auto VarD = dyn_cast<VarDecl>(D)) {
+    if (auto StoreD = dyn_cast<AbstractStorageDecl>(D)) {
       auto isNullOrImplicit = [](const Decl *D) -> bool {
         return !D || D->isImplicit();
       };
-      if (isNullOrImplicit(VarD->getGetter()) &&
-          isNullOrImplicit(VarD->getSetter())) {
+      if (isa<VarDecl>(D) && isNullOrImplicit(StoreD->getGetter()) &&
+          isNullOrImplicit(StoreD->getSetter())) {
+        auto VarD = cast<VarDecl>(D);
         // No actual getter or setter, pass 'pseudo' accessors.
         // We create accessor entities so we can implement the functionality
         // of libclang, which reports implicit method property accessor
@@ -903,31 +885,31 @@
         if (!reportPseudoSetterDecl(VarD))
           return false;
       } else {
-        if (auto FD = VarD->getGetter())
+        if (auto FD = StoreD->getGetter())
           SourceEntityWalker::walk(cast<Decl>(FD));
         if (Cancelled)
           return false;
-        if (auto FD = VarD->getSetter())
+        if (auto FD = StoreD->getSetter())
           SourceEntityWalker::walk(cast<Decl>(FD));
         if (Cancelled)
           return false;
       }
-      if (VarD->hasObservers()) {
-        if (auto FD = VarD->getWillSetFunc())
+      if (StoreD->hasObservers()) {
+        if (auto FD = StoreD->getWillSetFunc())
           SourceEntityWalker::walk(cast<Decl>(FD));
         if (Cancelled)
           return false;
-        if (auto FD = VarD->getDidSetFunc())
+        if (auto FD = StoreD->getDidSetFunc())
           SourceEntityWalker::walk(cast<Decl>(FD));
         if (Cancelled)
           return false;
       }
-      if (VarD->hasAddressors()) {
-        if (auto FD = VarD->getAddressor())
+      if (StoreD->hasAddressors()) {
+        if (auto FD = StoreD->getAddressor())
           SourceEntityWalker::walk(cast<Decl>(FD));
         if (Cancelled)
           return false;
-        if (auto FD = VarD->getMutableAddressor())
+        if (auto FD = StoreD->getMutableAddressor())
           SourceEntityWalker::walk(cast<Decl>(FD));
       }
     } else if (auto NTD = dyn_cast<NominalTypeDecl>(D)) {
diff --git a/lib/Parse/ParseDecl.cpp b/lib/Parse/ParseDecl.cpp
index 4225478..0d396c1 100644
--- a/lib/Parse/ParseDecl.cpp
+++ b/lib/Parse/ParseDecl.cpp
@@ -2120,12 +2120,6 @@
 ParserResult<Decl>
 Parser::parseDecl(ParseDeclOptions Flags,
                   llvm::function_ref<void(Decl*)> Handler) {
-  if (Tok.isAny(tok::pound_sourceLocation, tok::pound_line)) {
-    auto LineDirectiveStatus = parseLineDirective(Tok.is(tok::pound_line));
-    if (LineDirectiveStatus.isError())
-      return LineDirectiveStatus;
-    // If success, go on. line directive never produce decls.
-  }
 
   if (Tok.is(tok::pound_if)) {
     auto IfConfigResult = parseIfConfig(
@@ -2768,8 +2762,8 @@
 
   if (P.Tok.is(tok::integer_literal) || P.Tok.is(tok::floating_literal) ||
       (P.Tok.is(tok::unknown) && isdigit(P.Tok.getText()[0]))) {
-    // Per rdar://problem/32316666, using numbers for identifiers is a common
-    // error for beginners, so it's worth handling this in a special way.
+    // Using numbers for identifiers is a common error for beginners, so it's
+    // worth handling this in a special way.
     P.diagnose(P.Tok, diag::number_cant_start_decl_name, DeclKindName);
 
     // Pretend this works as an identifier, which shouldn't be observable since
@@ -2889,6 +2883,13 @@
       .fixItInsert(endOfPrevious, ";");
   }
 
+  if (Tok.isAny(tok::pound_sourceLocation, tok::pound_line)) {
+    auto LineDirectiveStatus = parseLineDirective(Tok.is(tok::pound_line));
+    if (LineDirectiveStatus.isError())
+      skipUntilDeclRBrace(tok::semi, tok::pound_endif);
+    return LineDirectiveStatus;
+  }
+
   auto Result = parseDecl(Options, handler);
   if (Result.isParseError())
     skipUntilDeclRBrace(tok::semi, tok::pound_endif);
diff --git a/lib/Parse/ParseStmt.cpp b/lib/Parse/ParseStmt.cpp
index 1591ef3..6e4c355 100644
--- a/lib/Parse/ParseStmt.cpp
+++ b/lib/Parse/ParseStmt.cpp
@@ -275,7 +275,8 @@
     // Parse the decl, stmt, or expression.
     PreviousHadSemi = false;
     if (isStartOfDecl()
-        && Tok.isNot(tok::pound_if, tok::pound_sourceLocation)) {
+        && Tok.isNot(
+            tok::pound_if, tok::pound_sourceLocation, tok::pound_line)) {
       ParserResult<Decl> DeclResult = 
           parseDecl(IsTopLevel ? PD_AllowTopLevel : PD_Default,
                     [&](Decl *D) {TmpDecls.push_back(D);});
diff --git a/lib/SIL/SILFunctionType.cpp b/lib/SIL/SILFunctionType.cpp
index 82814e2..b255ea5 100644
--- a/lib/SIL/SILFunctionType.cpp
+++ b/lib/SIL/SILFunctionType.cpp
@@ -424,22 +424,12 @@
                 ClassDecl::ForeignKind::CFType) {
             return false;
           }
-          // swift_newtype-ed CF type as foreign class
-          if (auto typedefTy = clangTy->getAs<clang::TypedefType>()) {
-            if (typedefTy->getDecl()->getAttr<clang::SwiftNewtypeAttr>()) {
-              // Make sure that we actually made the struct during import
-              if (auto underlyingType =
-                      substTy->getSwiftNewtypeUnderlyingType()) {
-                if (auto underlyingClass =
-                        underlyingType->getClassOrBoundGenericClass()) {
-                  if (underlyingClass->getForeignClassKind() ==
-                          ClassDecl::ForeignKind::CFType) {
-                    return false;
-                  }
-                }
-              }
-            }
-          }
+        }
+
+        // swift_newtypes are always passed directly
+        if (auto typedefTy = clangTy->getAs<clang::TypedefType>()) {
+          if (typedefTy->getDecl()->getAttr<clang::SwiftNewtypeAttr>())
+            return false;
         }
 
         return true;
diff --git a/lib/SIL/SILWitnessTable.cpp b/lib/SIL/SILWitnessTable.cpp
index 765bf79..34c02a4 100644
--- a/lib/SIL/SILWitnessTable.cpp
+++ b/lib/SIL/SILWitnessTable.cpp
@@ -21,6 +21,7 @@
 
 #include "swift/SIL/SILWitnessTable.h"
 #include "swift/AST/ASTMangler.h"
+#include "swift/AST/Module.h"
 #include "swift/AST/ProtocolConformance.h"
 #include "swift/SIL/SILModule.h"
 #include "llvm/ADT/SmallString.h"
@@ -155,3 +156,18 @@
 Identifier SILWitnessTable::getIdentifier() const {
   return Mod.getASTContext().getIdentifier(Name);
 }
+
+bool SILWitnessTable::conformanceIsSerialized(ProtocolConformance *conformance,
+                                              ResilienceStrategy strategy,
+                                              bool silSerializeWitnessTables) {
+  auto *nominal = conformance->getType()->getAnyNominal();
+  // Only serialize if the witness table is sufficiently static, andresilience
+  // is explicitly enabled for this compilation or if we serialize all eligible
+  // witness tables.
+  return (strategy == ResilienceStrategy::Resilient ||
+          silSerializeWitnessTables) &&
+         nominal->hasFixedLayout() &&
+         conformance->getProtocol()->getEffectiveAccess() >=
+             Accessibility::Public &&
+         nominal->getEffectiveAccess() >= Accessibility::Public;
+}
diff --git a/lib/SILGen/SILGenExpr.cpp b/lib/SILGen/SILGenExpr.cpp
index 2f62685..5d15e24 100644
--- a/lib/SILGen/SILGenExpr.cpp
+++ b/lib/SILGen/SILGenExpr.cpp
@@ -1483,8 +1483,6 @@
     // in the metatype.
     assert(!declRef.getDecl()->getDeclContext()->isTypeContext()
            && "c pointers to static methods not implemented");
-    assert(declRef.getSubstitutions().empty()
-           && "c pointers to generics not implemented");
     loc = declRef.getDecl();
   };
   
diff --git a/lib/SILGen/SILGenPattern.cpp b/lib/SILGen/SILGenPattern.cpp
index 30f751a..69a907f 100644
--- a/lib/SILGen/SILGenPattern.cpp
+++ b/lib/SILGen/SILGenPattern.cpp
@@ -947,6 +947,7 @@
   for (unsigned c = 0; c != numColumns; ++c) {
     unsigned constructorPrefix = getConstructorPrefix(matrix, firstRow, c);
     if (constructorPrefix > longestConstructorPrefix) {
+      longestConstructorPrefix = constructorPrefix;
       bestColumn = c;
     }
   }
diff --git a/lib/SILGen/SILGenType.cpp b/lib/SILGen/SILGenType.cpp
index f0a4d64..c036cc6 100644
--- a/lib/SILGen/SILGenType.cpp
+++ b/lib/SILGen/SILGenType.cpp
@@ -314,17 +314,14 @@
     Serialized = IsNotSerialized;
 
     // Serialize the witness table if we're serializing everything with
-    // -sil-serialize-all.
+    // -sil-serialize-all....
     if (SGM.isMakeModuleFragile())
       Serialized = IsSerialized;
 
-    // Serialize the witness table if the conformance itself thinks it should be
-    // and resilience is explicitly enabled for this compilaiton or if we serialize
-    // all eligible witness tables.
-    if ((SGM.M.getSwiftModule()->getResilienceStrategy() ==
-             ResilienceStrategy::Resilient ||
-         SGM.M.getOptions().SILSerializeWitnessTables) &&
-        Conformance->isSerialized())
+    // ... or if the conformance itself thinks it should be.
+    if (SILWitnessTable::conformanceIsSerialized(
+            Conformance, SGM.M.getSwiftModule()->getResilienceStrategy(),
+            SGM.M.getOptions().SILSerializeWitnessTables))
       Serialized = IsSerialized;
 
     // Not all protocols use witness tables; in this case we just skip
diff --git a/lib/SILOptimizer/Analysis/AccessSummaryAnalysis.cpp b/lib/SILOptimizer/Analysis/AccessSummaryAnalysis.cpp
index 428103c..265f708 100644
--- a/lib/SILOptimizer/Analysis/AccessSummaryAnalysis.cpp
+++ b/lib/SILOptimizer/Analysis/AccessSummaryAnalysis.cpp
@@ -106,6 +106,8 @@
     case ValueKind::ExistentialMetatypeInst:
     case ValueKind::ValueMetatypeInst:
     case ValueKind::LoadInst:
+    case ValueKind::LoadBorrowInst:
+    case ValueKind::EndBorrowInst:
     case ValueKind::OpenExistentialAddrInst:
     case ValueKind::ProjectBlockStorageInst:
       // These likely represent scenarios in which we're not generating
@@ -129,24 +131,46 @@
 /// only ultimately used by an apply, a try_apply or as an argument (but not
 /// the called function) in a partial_apply.
 /// TODO: This really should be checked in the SILVerifier.
-static bool isExpectedUseOfNoEscapePartialApply(SILInstruction *user) {
-  if (!user)
-    return true;
+static bool hasExpectedUsesOfNoEscapePartialApply(Operand *partialApplyUse) {
+  SILInstruction *user = partialApplyUse->getUser();
 
   // It is fine to call the partial apply
-  if (isa<ApplyInst>(user) || isa<TryApplyInst>(user)) {
+  switch (user->getKind()) {
+  case ValueKind::ApplyInst:
+  case ValueKind::TryApplyInst:
     return true;
-  }
 
-  if (isa<ConvertFunctionInst>(user)) {
-    return isExpectedUseOfNoEscapePartialApply(user->getSingleUse()->getUser());
-  }
+  case ValueKind::ConvertFunctionInst:
+    return llvm::all_of(user->getUses(),
+                        hasExpectedUsesOfNoEscapePartialApply);
 
-  if (auto *PAI = dyn_cast<PartialApplyInst>(user)) {
-    return user != PAI->getCallee();
-  }
+  case ValueKind::PartialApplyInst:
+    return partialApplyUse->get() != cast<PartialApplyInst>(user)->getCallee();
 
-  return false;
+  case ValueKind::StoreInst:
+  case ValueKind::DestroyValueInst:
+    // @block_storage is passed by storing it to the stack. We know this is
+    // still nonescaping simply because our original argument convention is
+    // @inout_aliasable. In this SIL, both store and destroy_value are users
+    // of %closure:
+    //
+    // %closure = partial_apply %f1(%arg)
+    //   : $@convention(thin) (@inout_aliasable T) -> ()
+    // %storage = alloc_stack $@block_storage @callee_owned () -> ()
+    // %block_addr = project_block_storage %storage
+    //   : $*@block_storage @callee_owned () -> ()
+    // store %closure to [init] %block_addr : $*@callee_owned () -> ()
+    // %block = init_block_storage_header %storage
+    //     : $*@block_storage @callee_owned () -> (),
+    //   invoke %f2 : $@convention(c)
+    //     (@inout_aliasable @block_storage @callee_owned () -> ()) -> (),
+    //   type $@convention(block) () -> ()
+    // %copy = copy_block %block : $@convention(block) () -> ()
+    // destroy_value %storage : $@callee_owned () -> ()
+    return true;
+  default:
+    return false;
+  }
 }
 #endif
 
@@ -164,15 +188,9 @@
   assert(isa<FunctionRefInst>(apply->getCallee()) &&
          "Noescape partial apply of non-functionref?");
 
-  SILInstruction *user = apply->getSingleUse()->getUser();
-  assert(isExpectedUseOfNoEscapePartialApply(user) &&
+  assert(llvm::all_of(apply->getUses(),
+                      hasExpectedUsesOfNoEscapePartialApply) &&
          "noescape partial_apply has unexpected use!");
-  (void)user;
-
-  // The arguments to partial_apply are a suffix of the arguments to the
-  // the actually-called function. Translate the index of the argument to
-  // the partial_apply into to the corresponding index into the arguments of
-  // the called function.
 
   // The argument index in the called function.
   ApplySite site(apply);
diff --git a/lib/SILOptimizer/Mandatory/AccessEnforcementSelection.cpp b/lib/SILOptimizer/Mandatory/AccessEnforcementSelection.cpp
index 9bd5985..7b56b88 100644
--- a/lib/SILOptimizer/Mandatory/AccessEnforcementSelection.cpp
+++ b/lib/SILOptimizer/Mandatory/AccessEnforcementSelection.cpp
@@ -57,6 +57,11 @@
 namespace {
 // Information about an address-type closure capture.
 // This is only valid for inout_aliasable parameters.
+//
+// TODO: Verify somewhere that we properly handle any non-inout_aliasable
+// partial apply captures or that they never happen. Eventually @inout_aliasable
+// should be simply replaced by @in or @out, once we don't have special aliasing
+// rules.
 struct AddressCapture {
   ApplySite site;
   unsigned calleeArgIdx;
diff --git a/lib/SILOptimizer/Mandatory/DiagnoseStaticExclusivity.cpp b/lib/SILOptimizer/Mandatory/DiagnoseStaticExclusivity.cpp
index e5c3a6c..4a999d1 100644
--- a/lib/SILOptimizer/Mandatory/DiagnoseStaticExclusivity.cpp
+++ b/lib/SILOptimizer/Mandatory/DiagnoseStaticExclusivity.cpp
@@ -985,6 +985,11 @@
 /// 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 checkForViolationsInNoEscapeClosures(
     const StorageMap &Accesses, FullApplySite FAS, AccessSummaryAnalysis *ASA,
     llvm::SmallVectorImpl<ConflictingAccess> &ConflictingAccesses) {
diff --git a/lib/Sema/CSDiag.cpp b/lib/Sema/CSDiag.cpp
index c46956a..25b162c 100644
--- a/lib/Sema/CSDiag.cpp
+++ b/lib/Sema/CSDiag.cpp
@@ -387,9 +387,14 @@
 
   // Find the locators which have the largest numbers of distinct overloads.
   Optional<unsigned> bestOverload;
-  unsigned maxDistinctOverloads = 0;
-  unsigned maxDepth = 0;
-  unsigned minIndex = std::numeric_limits<unsigned>::max();
+  // Overloads are scored by lexicographical comparison of (# of distinct
+  // overloads, depth, *reverse* of the index). N.B. - cannot be used for the
+  // reversing: the score version of index == 0 should be > than that of 1, but
+  // -0 == 0 < UINT_MAX == -1, whereas ~0 == UINT_MAX > UINT_MAX - 1 == ~1.
+  auto score = [](unsigned distinctOverloads, unsigned depth, unsigned index) {
+    return std::make_tuple(distinctOverloads, depth, ~index);
+  };
+  auto bestScore = score(0, 0, std::numeric_limits<unsigned>::max());
 
   // Get a map of expressions to their depths and post-order traversal indices.
   // Heuristically, all other things being equal, we should complain about the
@@ -428,27 +433,10 @@
 
     // If we have more distinct overload choices for this locator than for
     // prior locators, just keep this locator.
-    
-    bool better = false;
-    if (bestOverload) {
-      if (distinctOverloads > maxDistinctOverloads) {
-        better = true;
-      } else if (distinctOverloads == maxDistinctOverloads) {
-        if (depth > maxDepth) {
-          better = true;
-        } else if (depth == maxDepth) {
-          if (index < minIndex) {
-            better = true;
-          }
-        }
-      }
-    }
-
-    if (!bestOverload || better) {
+    auto thisScore = score(distinctOverloads, depth, index);
+    if (thisScore > bestScore) {
+      bestScore = thisScore;
       bestOverload = i;
-      maxDistinctOverloads = distinctOverloads;
-      maxDepth = depth;
-      minIndex = index;
       continue;
     }
 
diff --git a/lib/Sema/CSRanking.cpp b/lib/Sema/CSRanking.cpp
index 533edc6..21809d8 100644
--- a/lib/Sema/CSRanking.cpp
+++ b/lib/Sema/CSRanking.cpp
@@ -85,6 +85,9 @@
 }
 
 bool ConstraintSystem::worseThanBestSolution() const {
+  if (retainAllSolutions())
+    return false;
+
   if (!solverState || !solverState->BestScore ||
       CurrentScore <= *solverState->BestScore)
     return false;
diff --git a/lib/Sema/CSSolver.cpp b/lib/Sema/CSSolver.cpp
index 64ec08a..fbd0205 100644
--- a/lib/Sema/CSSolver.cpp
+++ b/lib/Sema/CSSolver.cpp
@@ -110,7 +110,7 @@
   Solution solution(*this, CurrentScore);
 
   // Update the best score we've seen so far.
-  if (solverState) {
+  if (solverState && !retainAllSolutions()) {
     assert(!solverState->BestScore || CurrentScore <= *solverState->BestScore);
     solverState->BestScore = CurrentScore;
   }
@@ -1499,7 +1499,8 @@
   };
 
   // Allocate new constraint system for sub-expression.
-  ConstraintSystem cs(TC, DC, None);
+  ConstraintSystem cs(TC, DC,
+                      ConstraintSystemFlags::ReturnAllDiscoveredSolutions);
 
   // Cleanup after constraint system generation/solving,
   // because it would assign types to expressions, which
@@ -1985,6 +1986,10 @@
 
   assert(!solverState && "use solveRec for recursive calls");
 
+  // Set up the expression type checker timer.
+  Timer.emplace(expr, TC.getDebugTimeExpressions(),
+                TC.getWarnLongExpressionTypeChecking(), TC.Context);
+
   // Try to shrink the system by reducing disjunction domains. This
   // goes through every sub-expression and generate its own sub-system, to
   // try to reduce the domains of those subexpressions.
@@ -2066,17 +2071,11 @@
   // Solve the system.
   solveRec(solutions, allowFreeTypeVariables);
 
-  // If there is more than one viable system, attempt to pick the best
-  // solution.
-  auto size = solutions.size();
-  if (size > 1 &&
-      !Options.contains(ConstraintSystemFlags::ReturnAllDiscoveredSolutions)) {
-    if (auto best = findBestSolution(solutions, /*minimize=*/false)) {
-      if (*best != 0)
-        solutions[0] = std::move(solutions[*best]);
-      solutions.erase(solutions.begin() + 1, solutions.end());
-    }
-  }
+  // Filter deduced solutions, try to figure out if there is
+  // a single best solution to use, if not explicitly disabled
+  // by constraint system options.
+  if (!retainAllSolutions())
+    filterSolutions(solutions);
 
   // We fail if there is no solution.
   return solutions.empty();
@@ -2289,11 +2288,8 @@
     auto &solutions = partialSolutions[component];
     // If there's a single best solution, keep only that one.
     // Otherwise, the set of solutions will at least have been minimized.
-    if (auto best = findBestSolution(solutions, /*minimize=*/true)) {
-      if (*best > 0)
-        solutions[0] = std::move(solutions[*best]);
-      solutions.erase(solutions.begin() + 1, solutions.end());
-    }
+    if (!retainAllSolutions())
+      filterSolutions(solutions, /*minimize=*/true);
   }
 
   // Produce all combinations of partial solutions.
diff --git a/lib/Sema/ConstraintGraph.cpp b/lib/Sema/ConstraintGraph.cpp
index 5cd63e9..4937aea 100644
--- a/lib/Sema/ConstraintGraph.cpp
+++ b/lib/Sema/ConstraintGraph.cpp
@@ -467,8 +467,8 @@
        TypeVariableType *typeVar,
        SmallVectorImpl<Constraint *> &constraints,
        GatheringKind kind) {
-  auto &node = (*this)[CS.getRepresentative(typeVar)];
-  auto equivClass = node.getEquivalenceClass();
+  auto &reprNode = (*this)[CS.getRepresentative(typeVar)];
+  auto equivClass = reprNode.getEquivalenceClass();
   llvm::SmallPtrSet<TypeVariableType *, 4> typeVars;
   for (auto typeVar : equivClass) {
     if (!typeVars.insert(typeVar).second)
@@ -476,38 +476,40 @@
 
     for (auto constraint : (*this)[typeVar].getConstraints())
       constraints.push_back(constraint);
-  }
 
-  // Retrieve the constraints from adjacent bindings.
-  for (auto adjTypeVar : node.getAdjacencies()) {
-    switch (kind) {
-    case GatheringKind::EquivalenceClass:
-      if (!node.getAdjacency(adjTypeVar).FixedBinding)
-        continue;
-      break;
+    auto &node = (*this)[typeVar];
 
-    case GatheringKind::AllMentions:
-      break;
-    }
+    // Retrieve the constraints from adjacent bindings.
+    for (auto adjTypeVar : node.getAdjacencies()) {
+      switch (kind) {
+      case GatheringKind::EquivalenceClass:
+        if (!node.getAdjacency(adjTypeVar).FixedBinding)
+          continue;
+        break;
 
-    ArrayRef<TypeVariableType *> adjTypeVarsToVisit;
-    switch (kind) {
-    case GatheringKind::EquivalenceClass:
-      adjTypeVarsToVisit = adjTypeVar;
-      break;
+      case GatheringKind::AllMentions:
+        break;
+      }
 
-    case GatheringKind::AllMentions:
-      adjTypeVarsToVisit
-        = (*this)[CS.getRepresentative(adjTypeVar)].getEquivalenceClass();
-      break;
-    }
+      ArrayRef<TypeVariableType *> adjTypeVarsToVisit;
+      switch (kind) {
+      case GatheringKind::EquivalenceClass:
+        adjTypeVarsToVisit = adjTypeVar;
+        break;
 
-    for (auto adjTypeVarEquiv : adjTypeVarsToVisit) {
-      if (!typeVars.insert(adjTypeVarEquiv).second)
-        continue;
+      case GatheringKind::AllMentions:
+        adjTypeVarsToVisit
+          = (*this)[CS.getRepresentative(adjTypeVar)].getEquivalenceClass();
+        break;
+      }
 
-      for (auto constraint : (*this)[adjTypeVarEquiv].getConstraints())
-        constraints.push_back(constraint);
+      for (auto adjTypeVarEquiv : adjTypeVarsToVisit) {
+        if (!typeVars.insert(adjTypeVarEquiv).second)
+          continue;
+
+        for (auto constraint : (*this)[adjTypeVarEquiv].getConstraints())
+          constraints.push_back(constraint);
+      }
     }
   }
 }
diff --git a/lib/Sema/ConstraintSystem.cpp b/lib/Sema/ConstraintSystem.cpp
index d57d0e3..90dc645 100644
--- a/lib/Sema/ConstraintSystem.cpp
+++ b/lib/Sema/ConstraintSystem.cpp
@@ -21,12 +21,31 @@
 #include "swift/Basic/Statistic.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/Support/Compiler.h"
+#include "llvm/Support/Format.h"
 
 using namespace swift;
 using namespace constraints;
 
 #define DEBUG_TYPE "ConstraintSystem"
 
+ExpressionTimer::~ExpressionTimer() {
+  auto elapsed = getElapsedProcessTimeInFractionalSeconds();
+  unsigned elapsedMS = static_cast<unsigned>(elapsed * 1000);
+
+  if (ShouldDump) {
+    // Round up to the nearest 100th of a millisecond.
+    llvm::errs() << llvm::format("%0.2f", ceil(elapsed * 100000) / 100)
+                 << "ms\t";
+    E->getLoc().print(llvm::errs(), Context.SourceMgr);
+    llvm::errs() << "\n";
+  }
+
+  if (WarnLimit != 0 && elapsedMS >= WarnLimit && E->getLoc().isValid())
+    Context.Diags.diagnose(E->getLoc(), diag::debug_long_expression,
+                           elapsedMS, WarnLimit)
+      .highlight(E->getSourceRange());
+}
+
 ConstraintSystem::ConstraintSystem(TypeChecker &tc, DeclContext *dc,
                                    ConstraintSystemOptions options)
   : TC(tc), DC(dc), Options(options),
diff --git a/lib/Sema/ConstraintSystem.h b/lib/Sema/ConstraintSystem.h
index c7c5277..2b0eebb 100644
--- a/lib/Sema/ConstraintSystem.h
+++ b/lib/Sema/ConstraintSystem.h
@@ -36,6 +36,7 @@
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/Timer.h"
 #include "llvm/Support/raw_ostream.h"
 #include <cstddef>
 #include <functional>
@@ -115,6 +116,35 @@
   }
 };
 
+
+class ExpressionTimer {
+  Expr* E;
+  unsigned WarnLimit;
+  bool ShouldDump;
+  ASTContext &Context;
+  llvm::TimeRecord StartTime = llvm::TimeRecord::getCurrentTime();
+
+public:
+  ExpressionTimer(Expr *E, bool shouldDump, unsigned warnLimit,
+                  ASTContext &Context)
+      : E(E), WarnLimit(warnLimit), ShouldDump(shouldDump), Context(Context) {
+  }
+
+  ~ExpressionTimer();
+
+  /// Return the elapsed process time (including fractional seconds)
+  /// as a double.
+  double getElapsedProcessTimeInFractionalSeconds() {
+    llvm::TimeRecord endTime = llvm::TimeRecord::getCurrentTime(false);
+
+    return endTime.getProcessTime() - StartTime.getProcessTime();
+  }
+
+  // Disable emission of warnings about expressions that take longer
+  // than the warning threshold.
+  void disableWarning() { WarnLimit = 0; }
+};
+
 } // end namespace constraints
 
 /// Options that describe how a type variable can be used.
@@ -850,6 +880,7 @@
   TypeChecker &TC;
   DeclContext *DC;
   ConstraintSystemOptions Options;
+  Optional<ExpressionTimer> Timer;
   
   friend class Fix;
   friend class OverloadChoice;
@@ -1382,6 +1413,13 @@
   bool hasFreeTypeVariables();
 
 private:
+  /// \brief Indicates if the constraint system should retain all of the
+  /// solutions it has deduced regardless of their score.
+  bool retainAllSolutions() const {
+    return Options.contains(
+        ConstraintSystemFlags::ReturnAllDiscoveredSolutions);
+  }
+
   /// \brief Finalize this constraint system; we're done attempting to solve
   /// it.
   ///
@@ -1403,8 +1441,28 @@
   /// diagnostic for it and returning true.  If the fixit hint turned out to be
   /// bogus, this returns false and doesn't emit anything.
   bool applySolutionFix(Expr *expr, const Solution &solution, unsigned fixNo);
-  
-  
+
+  /// \brief If there is more than one viable solution,
+  /// attempt to pick the best solution and remove all of the rest.
+  ///
+  /// \param solutions The set of solutions to filter.
+  ///
+  /// \param minimize The flag which idicates if the
+  /// set of solutions should be filtered even if there is
+  /// no single best solution, see `findBestSolution` for
+  /// more details.
+  void filterSolutions(SmallVectorImpl<Solution> &solutions,
+                       bool minimize = false) {
+    if (solutions.size() < 2)
+      return;
+
+    if (auto best = findBestSolution(solutions, minimize)) {
+      if (*best != 0)
+        solutions[0] = std::move(solutions[*best]);
+      solutions.erase(solutions.begin() + 1, solutions.end());
+    }
+  }
+
   /// \brief Restore the type variable bindings to what they were before
   /// we attempted to solve this constraint system.
   ///
@@ -2525,6 +2583,17 @@
   /// \brief Determine if we've already explored too many paths in an
   /// attempt to solve this expression.
   bool getExpressionTooComplex(SmallVectorImpl<Solution> const &solutions) {
+    if (Timer.hasValue()) {
+      auto elapsed = Timer->getElapsedProcessTimeInFractionalSeconds();
+      if (unsigned(elapsed) > TC.getExpressionTimeoutThresholdInSeconds()) {
+        // Disable warnings about expressions that go over the warning
+        // threshold since we're arbitrarily ending evaluation and
+        // emitting an error.
+        Timer->disableWarning();
+        return true;
+      }
+    }
+
     if (!getASTContext().isSwiftVersion3()) {
       if (CountScopes < TypeCounter)
         return false;
diff --git a/lib/Sema/TypeCheckConstraints.cpp b/lib/Sema/TypeCheckConstraints.cpp
index 99b48e2..251a886 100644
--- a/lib/Sema/TypeCheckConstraints.cpp
+++ b/lib/Sema/TypeCheckConstraints.cpp
@@ -42,7 +42,6 @@
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/SaveAndRestore.h"
 #include "llvm/Support/Format.h"
-#include "llvm/Support/Timer.h"
 #include <iterator>
 #include <map>
 #include <memory>
@@ -1777,41 +1776,6 @@
       }
     }
   };
-
-  class ExpressionTimer {
-    Expr* E;
-    unsigned WarnLimit;
-    bool ShouldDump;
-    ASTContext &Context;
-    llvm::TimeRecord StartTime = llvm::TimeRecord::getCurrentTime();
-
-  public:
-    ExpressionTimer(Expr *E, bool shouldDump, unsigned warnLimit,
-                    ASTContext &Context)
-        : E(E), WarnLimit(warnLimit), ShouldDump(shouldDump), Context(Context) {
-    }
-
-    ~ExpressionTimer() {
-      llvm::TimeRecord endTime = llvm::TimeRecord::getCurrentTime(false);
-
-      auto elapsed = endTime.getProcessTime() - StartTime.getProcessTime();
-      unsigned elapsedMS = static_cast<unsigned>(elapsed * 1000);
-
-      if (ShouldDump) {
-        // Round up to the nearest 100th of a millisecond.
-        llvm::errs() << llvm::format("%0.2f", ceil(elapsed * 100000) / 100)
-                     << "ms\t";
-        E->getLoc().print(llvm::errs(), Context.SourceMgr);
-        llvm::errs() << "\n";
-      }
-
-      if (WarnLimit != 0 && elapsedMS >= WarnLimit && E->getLoc().isValid())
-        Context.Diags.diagnose(E->getLoc(), diag::debug_long_expression,
-                               elapsedMS, WarnLimit)
-          .highlight(E->getSourceRange());
-    }
-  };
-
 } // end anonymous namespace
 
 #pragma mark High-level entry points
@@ -1821,11 +1785,6 @@
                                       TypeCheckExprOptions options,
                                       ExprTypeCheckListener *listener,
                                       ConstraintSystem *baseCS) {
-  Optional<ExpressionTimer> timer;
-  if (DebugTimeExpressions || WarnLongExpressionTypeChecking)
-    timer.emplace(expr, DebugTimeExpressions, WarnLongExpressionTypeChecking,
-                  Context);
-
   PrettyStackTraceExpr stackTrace(Context, "type-checking", expr);
 
   // Construct a constraint system from this expression.
diff --git a/lib/Sema/TypeCheckDecl.cpp b/lib/Sema/TypeCheckDecl.cpp
index 0d2ae5f..5ab4700 100644
--- a/lib/Sema/TypeCheckDecl.cpp
+++ b/lib/Sema/TypeCheckDecl.cpp
@@ -1245,12 +1245,14 @@
 
 void swift::makeFinal(ASTContext &ctx, ValueDecl *D) {
   if (D && !D->isFinal()) {
+    assert(!D->isDynamic());
     D->getAttrs().add(new (ctx) FinalAttr(/*IsImplicit=*/true));
   }
 }
 
 void swift::makeDynamic(ASTContext &ctx, ValueDecl *D) {
   if (D && !D->isDynamic()) {
+    assert(!D->isFinal());
     D->getAttrs().add(new (ctx) DynamicAttr(/*IsImplicit=*/true));
   }
 }
@@ -2556,15 +2558,29 @@
 
   // Variables declared with 'let' cannot be 'dynamic'.
   if (auto VD = dyn_cast<VarDecl>(D)) {
-    if (VD->isLet() && !isNSManaged) return;
+    auto staticSpelling = VD->getParentPatternBinding()->getStaticSpelling();
+
+    // The presence of 'static' blocks the inference of 'dynamic'.
+    if (staticSpelling == StaticSpellingKind::KeywordStatic)
+      return;
+
+    if (VD->isLet() && !isNSManaged)
+      return;
   }
 
   // Accessors should not infer 'dynamic' on their own; they can get it from
   // their storage decls.
-  if (auto FD = dyn_cast<FuncDecl>(D))
+  if (auto FD = dyn_cast<FuncDecl>(D)) {
     if (FD->isAccessor())
       return;
 
+    auto staticSpelling = FD->getStaticSpelling();
+
+    // The presence of 'static' bocks the inference of 'dynamic'.
+    if (staticSpelling == StaticSpellingKind::KeywordStatic)
+      return;
+  }
+
   // The presence of 'final' on a class prevents 'dynamic'.
   auto classDecl = D->getDeclContext()->getAsClassOrClassExtensionContext();
   if (!classDecl) return;
@@ -5176,8 +5192,7 @@
 
         // If the storage is dynamic or final, propagate to this accessor.
         if (isObjC &&
-            storage->isDynamic() &&
-            !storage->isFinal())
+            storage->isDynamic())
           makeDynamic(TC.Context, FD);
 
         if (storage->isFinal())
diff --git a/lib/Sema/TypeChecker.cpp b/lib/Sema/TypeChecker.cpp
index 8e8ecd2..e04c7ac 100644
--- a/lib/Sema/TypeChecker.cpp
+++ b/lib/Sema/TypeChecker.cpp
@@ -622,7 +622,8 @@
                                 OptionSet<TypeCheckingFlags> Options,
                                 unsigned StartElem,
                                 unsigned WarnLongFunctionBodies,
-                                unsigned WarnLongExpressionTypeChecking) {
+                                unsigned WarnLongExpressionTypeChecking,
+                                unsigned ExpressionTimeoutThreshold) {
   if (SF.ASTStage == SourceFile::TypeChecked)
     return;
 
@@ -648,6 +649,9 @@
     if (MyTC) {
       MyTC->setWarnLongFunctionBodies(WarnLongFunctionBodies);
       MyTC->setWarnLongExpressionTypeChecking(WarnLongExpressionTypeChecking);
+      if (ExpressionTimeoutThreshold != 0)
+        MyTC->setExpressionTimeoutThreshold(ExpressionTimeoutThreshold);
+
       if (Options.contains(TypeCheckingFlags::DebugTimeFunctionBodies))
         MyTC->enableDebugTimeFunctionBodies();
 
diff --git a/lib/Sema/TypeChecker.h b/lib/Sema/TypeChecker.h
index b8e6d53..bddca16 100644
--- a/lib/Sema/TypeChecker.h
+++ b/lib/Sema/TypeChecker.h
@@ -829,12 +829,16 @@
   /// Intended for debugging purposes only.
   unsigned WarnLongFunctionBodies = 0;
 
-  /// If \p timeInMS is non-zero, warn when type-chcking an expression
-  /// takes longer than this many milliseconds.
+  /// If non-zero, warn when type-chcking an expression takes longer
+  /// than this many milliseconds.
   ///
   /// Intended for debugging purposes only.
   unsigned WarnLongExpressionTypeChecking = 0;
 
+  /// If non-zero, abort the expression type checker if it takes more
+  /// than this many seconds.
+  unsigned ExpressionTimeoutThreshold = 600;
+
   /// If true, the time it takes to type-check each function will be dumped
   /// to llvm::errs().
   bool DebugTimeFunctionBodies = false;
@@ -870,6 +874,10 @@
     DebugTimeExpressions = true;
   }
 
+  bool getDebugTimeExpressions() {
+    return DebugTimeExpressions;
+  }
+
   /// If \p timeInMS is non-zero, warn when a function body takes longer than
   /// this many milliseconds to type-check.
   ///
@@ -878,7 +886,7 @@
     WarnLongFunctionBodies = timeInMS;
   }
 
-  /// If \p timeInMS is non-zero, warn when type-chcking an expression
+  /// If \p timeInMS is non-zero, warn when type-checking an expression
   /// takes longer than this many milliseconds.
   ///
   /// Intended for debugging purposes only.
@@ -886,6 +894,28 @@
     WarnLongExpressionTypeChecking = timeInMS;
   }
 
+  /// Return the current setting for the number of milliseconds
+  /// threshold we use to determine whether to warn about an
+  /// expression taking a long time.
+  unsigned getWarnLongExpressionTypeChecking() {
+    return WarnLongExpressionTypeChecking;
+  }
+
+  /// Set the threshold that determines the upper bound for the number
+  /// of seconds we'll let the expression type checker run before
+  /// considering an expression "too complex".
+  void setExpressionTimeoutThreshold(unsigned timeInSeconds) {
+    ExpressionTimeoutThreshold = timeInSeconds;
+  }
+
+  /// Return the current settting for the threshold that determines
+  /// the upper bound for the number of seconds we'll let the
+  /// expression type checker run before considering an expression
+  /// "too complex".
+  unsigned getExpressionTimeoutThresholdInSeconds() {
+    return ExpressionTimeoutThreshold;
+  }
+
   bool getInImmediateMode() {
     return InImmediateMode;
   }
diff --git a/lib/TBDGen/TBDGen.cpp b/lib/TBDGen/TBDGen.cpp
index 7dd60d4..5d0ae18 100644
--- a/lib/TBDGen/TBDGen.cpp
+++ b/lib/TBDGen/TBDGen.cpp
@@ -24,6 +24,7 @@
 #include "swift/IRGen/Linking.h"
 #include "swift/SIL/FormalLinkage.h"
 #include "swift/SIL/SILDeclRef.h"
+#include "swift/SIL/SILWitnessTable.h"
 #include "swift/SIL/TypeLowering.h"
 #include "llvm/ADT/StringSet.h"
 
@@ -41,6 +42,7 @@
   const UniversalLinkageInfo &UniversalLinkInfo;
   ModuleDecl *SwiftModule;
   bool FileHasEntryPoint;
+  bool SILSerializeWitnessTables;
 
   void addSymbol(StringRef name) {
     auto isNewValue = Symbols.insert(name).second;
@@ -67,9 +69,11 @@
 public:
   TBDGenVisitor(StringSet &symbols,
                 const UniversalLinkageInfo &universalLinkInfo,
-                ModuleDecl *swiftModule, bool fileHasEntryPoint)
+                ModuleDecl *swiftModule, bool fileHasEntryPoint,
+                bool silSerializeWitnessTables)
       : Symbols(symbols), UniversalLinkInfo(universalLinkInfo),
-        SwiftModule(swiftModule), FileHasEntryPoint(fileHasEntryPoint) {}
+        SwiftModule(swiftModule), FileHasEntryPoint(fileHasEntryPoint),
+        SILSerializeWitnessTables(silSerializeWitnessTables) {}
 
   void visitMembers(Decl *D) {
     SmallVector<Decl *, 4> members;
@@ -190,10 +194,12 @@
     // FIXME: the logic around visibility in extensions is confusing, and
     // sometimes witness thunks need to be manually made public.
 
-    auto conformanceIsSerialized = normalConformance->isSerialized();
+    auto conformanceIsFixed = SILWitnessTable::conformanceIsSerialized(
+        normalConformance, SwiftModule->getResilienceStrategy(),
+        SILSerializeWitnessTables);
     auto addSymbolIfNecessary = [&](ValueDecl *valueReq,
                                     SILLinkage witnessLinkage) {
-      if (conformanceIsSerialized &&
+      if (conformanceIsFixed &&
           fixmeWitnessHasLinkageThatNeedsToBePublic(witnessLinkage)) {
         Mangle::ASTMangler Mangler;
         addSymbol(Mangler.mangleWitnessThunk(normalConformance, valueReq));
@@ -390,7 +396,8 @@
 
 void swift::enumeratePublicSymbols(FileUnit *file, StringSet &symbols,
                                    bool hasMultipleIRGenThreads,
-                                   bool isWholeModule) {
+                                   bool isWholeModule,
+                                   bool silSerializeWitnessTables) {
   UniversalLinkageInfo linkInfo(file->getASTContext().LangOpts.Target,
                                 hasMultipleIRGenThreads, isWholeModule);
 
@@ -400,7 +407,7 @@
   auto hasEntryPoint = file->hasEntryPoint();
 
   TBDGenVisitor visitor(symbols, linkInfo, file->getParentModule(),
-                        hasEntryPoint);
+                        hasEntryPoint, silSerializeWitnessTables);
   for (auto d : decls)
     visitor.visit(d);
 
diff --git a/stdlib/public/SDK/Foundation/Data.swift b/stdlib/public/SDK/Foundation/Data.swift
index 702c8c1..bf23743 100644
--- a/stdlib/public/SDK/Foundation/Data.swift
+++ b/stdlib/public/SDK/Foundation/Data.swift
@@ -319,6 +319,7 @@
     
     @inline(__always)
     public func append(_ bytes: UnsafeRawPointer, length: Int) {
+        precondition(length >= 0, "Length of appending bytes must be positive")
         switch _backing {
         case .swift:
             let origLength = _length
@@ -1087,6 +1088,18 @@
         _sliceRange = range
     }
     
+    @_versioned
+    internal func _validateIndex(_ index: Int, message: String? = nil) {
+        precondition(_sliceRange.contains(index), message ?? "Index \(index) is out of bounds of range \(_sliceRange)")
+    }
+    
+    @_versioned
+    internal func _validateRange<R: RangeExpression>(_ range: R) where R.Bound == Int {
+        let r = range.relative(to: 0..<R.Bound.max)
+        precondition(r.lowerBound >= _sliceRange.lowerBound && r.lowerBound <= _sliceRange.upperBound, "Range \(r) is out of bounds of range \(_sliceRange)")
+        precondition(r.upperBound >= _sliceRange.lowerBound && r.upperBound <= _sliceRange.upperBound, "Range \(r) is out of bounds of range \(_sliceRange)")
+    }
+    
     // -----------------------------------
     // MARK: - Properties and Functions
     
@@ -1099,6 +1112,7 @@
         }
         @inline(__always)
         set {
+            precondition(count >= 0, "count must be positive")
             if !isKnownUniquelyReferenced(&_backing) {
                 _backing = _backing.mutableCopy(_sliceRange)
             }
@@ -1142,14 +1156,15 @@
     /// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes.
     @inline(__always)
     public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) {
+        precondition(count >= 0, "count of bytes to copy must be positive")
         if count == 0 { return }
-        memcpy(UnsafeMutableRawPointer(pointer), _backing.bytes!.advanced(by: _sliceRange.lowerBound), count)
+        memcpy(UnsafeMutableRawPointer(pointer), _backing.bytes!.advanced(by: _sliceRange.lowerBound), Swift.min(count, _sliceRange.count))
     }
     
     @inline(__always)
     private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: NSRange) {
         if range.length == 0 { return }
-        memcpy(UnsafeMutableRawPointer(pointer), _backing.bytes!.advanced(by: range.location), range.length)
+        memcpy(UnsafeMutableRawPointer(pointer), _backing.bytes!.advanced(by: range.location), Swift.min(range.length, _sliceRange.count))
     }
     
     /// Copy a subset of the contents of the data to a pointer.
@@ -1174,18 +1189,13 @@
         
         let copyRange : Range<Index>
         if let r = range {
-            guard !r.isEmpty else { return 0 }
-            precondition(r.lowerBound >= 0)
-            precondition(r.lowerBound < cnt, "The range is outside the bounds of the data")
-            
-            precondition(r.upperBound >= 0)
-            precondition(r.upperBound <= cnt, "The range is outside the bounds of the data")
-            
+            guard !r.isEmpty else { return 0 }            
             copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.count))
         } else {
             copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt)
         }
-        
+        _validateRange(copyRange)
+
         guard !copyRange.isEmpty else { return 0 }
         
         let nsRange = NSMakeRange(copyRange.lowerBound, copyRange.upperBound - copyRange.lowerBound)
@@ -1243,6 +1253,7 @@
     public func range(of dataToFind: Data, options: Data.SearchOptions = [], in range: Range<Index>? = nil) -> Range<Index>? {
         let nsRange : NSRange
         if let r = range {
+            _validateRange(r)
             nsRange = NSMakeRange(r.lowerBound, r.upperBound - r.lowerBound)
         } else {
             nsRange = NSMakeRange(0, _backing.length)
@@ -1266,6 +1277,7 @@
     
     @inline(__always)
     public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) {
+        precondition(count >= 0, "count must be positive")
         if count == 0 { return }
         if !isKnownUniquelyReferenced(&_backing) {
             _backing = _backing.mutableCopy(_sliceRange)
@@ -1326,6 +1338,9 @@
     /// - parameter range: The range in the data to set to `0`.
     @inline(__always)
     public mutating func resetBytes(in range: Range<Index>) {
+        // it is worth noting that the range here may be out of bounds of the Data itself (which triggers a growth)
+        precondition(range.lowerBound >= 0, "Ranges must be positive bounds")
+        precondition(range.upperBound >= 0, "Ranges must be positive bounds")
         let range = NSMakeRange(range.lowerBound, range.upperBound - range.lowerBound)
         if !isKnownUniquelyReferenced(&_backing) {
             _backing = _backing.mutableCopy(_sliceRange)
@@ -1346,6 +1361,7 @@
     /// - parameter data: The replacement data.
     @inline(__always)
     public mutating func replaceSubrange(_ subrange: Range<Index>, with data: Data) {
+        _validateRange(subrange)
         let nsRange = NSMakeRange(subrange.lowerBound, subrange.upperBound - subrange.lowerBound)
         let cnt = data.count
         if !isKnownUniquelyReferenced(&_backing) {
@@ -1361,6 +1377,7 @@
     
     @inline(__always)
     public mutating func replaceSubrange(_ subrange: CountableRange<Index>, with data: Data) {
+        _validateRange(subrange)
         let nsRange = NSMakeRange(subrange.lowerBound, subrange.upperBound - subrange.lowerBound)
         let cnt = data.count
         if !isKnownUniquelyReferenced(&_backing) {
@@ -1383,6 +1400,7 @@
     /// - parameter buffer: The replacement bytes.
     @inline(__always)
     public mutating func replaceSubrange<SourceType>(_ subrange: Range<Index>, with buffer: UnsafeBufferPointer<SourceType>) {
+        _validateRange(subrange)
         let nsRange = NSMakeRange(subrange.lowerBound, subrange.upperBound - subrange.lowerBound)
         let bufferCount = buffer.count * MemoryLayout<SourceType>.stride
         
@@ -1405,19 +1423,13 @@
     @inline(__always)
     public mutating func replaceSubrange<ByteCollection : Collection>(_ subrange: Range<Index>, with newElements: ByteCollection)
         where ByteCollection.Iterator.Element == Data.Iterator.Element {
-            
+            _validateRange(subrange)
             // Calculate this once, it may not be O(1)
             let replacementCount: Int = numericCast(newElements.count)
             let currentCount = self.count
             let subrangeCount = subrange.count
             
-            if currentCount < subrange.lowerBound + subrangeCount {
-                if subrangeCount == 0 {
-                    preconditionFailure("location \(subrange.lowerBound) exceeds data count \(currentCount)")
-                } else {
-                    preconditionFailure("range \(subrange) exceeds data count \(currentCount)")
-                }
-            }
+            _validateRange(subrange)
             
             let resultCount = currentCount - subrangeCount + replacementCount
             if resultCount != currentCount {
@@ -1446,6 +1458,7 @@
     
     @inline(__always)
     public mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer, count cnt: Int) {
+        _validateRange(subrange)
         let nsRange = NSMakeRange(subrange.lowerBound, subrange.upperBound - subrange.lowerBound)
         if !isKnownUniquelyReferenced(&_backing) {
             _backing = _backing.mutableCopy(_sliceRange)
@@ -1461,11 +1474,11 @@
     /// - parameter range: The range to copy.
     @inline(__always)
     public func subdata(in range: Range<Index>) -> Data {
+        _validateRange(range)
         let length = count
         if count == 0 {
             return Data()
         }
-        precondition(length >= range.upperBound)
         return _backing.subdata(in: range)
     }
     
@@ -1502,6 +1515,7 @@
     
     @inline(__always)
     public func advanced(by amount: Int) -> Data {
+        _validateIndex(startIndex + amount)
         let length = count - amount
         precondition(length > 0)
         return withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Data in
@@ -1518,10 +1532,12 @@
     public subscript(index: Index) -> UInt8 {
         @inline(__always)
         get {
+            _validateIndex(index)
             return _backing.bytes!.advanced(by: index).assumingMemoryBound(to: UInt8.self).pointee
         }
         @inline(__always)
         set {
+            _validateIndex(index)
             if !isKnownUniquelyReferenced(&_backing) {
                 _backing = _backing.mutableCopy(_sliceRange)
             }
@@ -1532,6 +1548,7 @@
     public subscript(bounds: Range<Index>) -> Data {
         @inline(__always)
         get {
+            _validateRange(bounds)
             return Data(backing: _backing, range: bounds)
         }
         @inline(__always)
@@ -1547,16 +1564,20 @@
             let range = rangeExpression.relative(to: 0..<R.Bound.max)
             let start: Int = numericCast(range.lowerBound)
             let end: Int = numericCast(range.upperBound)
-            return Data(backing: _backing, range: start..<end)
+            let r: Range<Int> = start..<end
+            _validateRange(r)
+            return Data(backing: _backing, range: r)
         }
         @inline(__always)
         set {
             let range = rangeExpression.relative(to: 0..<R.Bound.max)
             let start: Int = numericCast(range.lowerBound)
             let end: Int = numericCast(range.upperBound)
-            replaceSubrange(start..<end, with: newValue)
+            let r: Range<Int> = start..<end
+            _validateRange(r)
+            replaceSubrange(r, with: newValue)
         }
-            
+        
     }
     
     /// The start `Index` in the data.
diff --git a/stdlib/public/SDK/Foundation/IndexPath.swift b/stdlib/public/SDK/Foundation/IndexPath.swift
index a13e314..537230e 100644
--- a/stdlib/public/SDK/Foundation/IndexPath.swift
+++ b/stdlib/public/SDK/Foundation/IndexPath.swift
@@ -290,9 +290,9 @@
                     case 0:
                         return .empty
                     case 1:
-                        return .single(slice[0])
+                        return .single(slice.first!)
                     case 2:
-                        return .pair(slice[0], slice[1])
+                        return .pair(slice.first!, slice.last!)
                     default:
                         return .array(Array<Int>(slice))
                     }
diff --git a/stdlib/public/SDK/Foundation/JSONEncoder.swift b/stdlib/public/SDK/Foundation/JSONEncoder.swift
index 786c2d0..0468da1 100644
--- a/stdlib/public/SDK/Foundation/JSONEncoder.swift
+++ b/stdlib/public/SDK/Foundation/JSONEncoder.swift
@@ -190,7 +190,7 @@
     /// Returns whether a new element can be encoded at this coding path.
     ///
     /// `true` if an element has not yet been encoded at this coding path; `false` otherwise.
-    var canEncodeNewElement: Bool {
+    var canEncodeNewValue: Bool {
         // Every time a new value gets encoded, the key it's encoded for is pushed onto the coding path (even if it's a nil key from an unkeyed container).
         // At the same time, every time a container is requested, a new value gets pushed onto the storage stack.
         // If there are more values on the storage stack than on the coding path, it means the value is requesting more than one container, which violates the precondition.
@@ -200,39 +200,43 @@
         return self.storage.count == self.codingPath.count
     }
 
-    /// Asserts that a new container can be requested at this coding path.
-    /// `preconditionFailure()`s if one cannot be requested.
-    func assertCanRequestNewContainer() {
-        guard self.canEncodeNewElement else {
-            let previousContainerType: String
-            if self.storage.containers.last is NSDictionary {
-                previousContainerType = "keyed"
-            } else if self.storage.containers.last is NSArray {
-                previousContainerType = "unkeyed"
-            } else {
-                previousContainerType = "single value"
-            }
-
-            preconditionFailure("Attempt to encode with new container when already encoded with \(previousContainerType) container.")
-        }
-    }
-
     // MARK: - Encoder Methods
     func container<Key>(keyedBy: Key.Type) -> KeyedEncodingContainer<Key> {
-        assertCanRequestNewContainer()
-        let topContainer = self.storage.pushKeyedContainer()
+        // If an existing keyed container was already requested, return that one.
+        let topContainer: NSMutableDictionary
+        if self.canEncodeNewValue {
+            // We haven't yet pushed a container at this level; do so here.
+            topContainer = self.storage.pushKeyedContainer()
+        } else {
+            guard let container = self.storage.containers.last as? NSMutableDictionary else {
+                preconditionFailure("Attempt to push new keyed encoding container when already previously encoded at this path.")
+            }
+
+            topContainer = container
+        }
+
         let container = _JSONKeyedEncodingContainer<Key>(referencing: self, codingPath: self.codingPath, wrapping: topContainer)
         return KeyedEncodingContainer(container)
     }
 
     func unkeyedContainer() -> UnkeyedEncodingContainer {
-        assertCanRequestNewContainer()
-        let topContainer = self.storage.pushUnkeyedContainer()
+        // If an existing unkeyed container was already requested, return that one.
+        let topContainer: NSMutableArray
+        if self.canEncodeNewValue {
+            // We haven't yet pushed a container at this level; do so here.
+            topContainer = self.storage.pushUnkeyedContainer()
+        } else {
+            guard let container = self.storage.containers.last as? NSMutableArray else {
+                preconditionFailure("Attempt to push new unkeyed encoding container when already previously encoded at this path.")
+            }
+
+            topContainer = container
+        }
+
         return _JSONUnkeyedEncodingContainer(referencing: self, codingPath: self.codingPath, wrapping: topContainer)
     }
 
     func singleValueContainer() -> SingleValueEncodingContainer {
-        assertCanRequestNewContainer()
         return self
     }
 }
@@ -474,106 +478,89 @@
 }
 
 extension _JSONEncoder : SingleValueEncodingContainer {
-    // MARK: - Utility Methods
-
-    /// Asserts that a single value can be encoded at the current coding path (i.e. that one has not already been encoded through this container).
-    /// `preconditionFailure()`s if one cannot be encoded.
-    ///
-    /// This is similar to assertCanRequestNewContainer above.
-    func assertCanEncodeSingleValue() {
-        guard self.canEncodeNewElement else {
-            let previousContainerType: String
-            if self.storage.containers.last is NSDictionary {
-                previousContainerType = "keyed"
-            } else if self.storage.containers.last is NSArray {
-                previousContainerType = "unkeyed"
-            } else {
-                preconditionFailure("Attempt to encode multiple values in a single value container.")
-            }
-
-            preconditionFailure("Attempt to encode with new container when already encoded with \(previousContainerType) container.")
-        }
-    }
-
     // MARK: - SingleValueEncodingContainer Methods
 
+    func assertCanEncodeNewValue() {
+        precondition(self.canEncodeNewValue, "Attempt to encode value through single value container when previously value already encoded.")
+    }
+
     func encodeNil() throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: NSNull())
     }
 
     func encode(_ value: Bool) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: Int) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: Int8) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: Int16) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: Int32) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: Int64) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: UInt) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: UInt8) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: UInt16) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: UInt32) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: UInt64) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: String) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: Float) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         try self.storage.push(container: box(value))
     }
 
     func encode(_ value: Double) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         try self.storage.push(container: box(value))
     }
 
     func encode<T : Encodable>(_ value: T) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         try self.storage.push(container: box(value))
     }
 }
@@ -763,7 +750,7 @@
 
     // MARK: - Coding Path Operations
 
-    override var canEncodeNewElement: Bool {
+    override var canEncodeNewValue: Bool {
         // With a regular encoder, the storage and coding path grow together.
         // A referencing encoder, however, inherits its parents coding path, as well as the key it was created for.
         // We have to take this into account.
diff --git a/stdlib/public/SDK/Foundation/NSCoder.swift b/stdlib/public/SDK/Foundation/NSCoder.swift
index d6d4b8f..b973195 100644
--- a/stdlib/public/SDK/Foundation/NSCoder.swift
+++ b/stdlib/public/SDK/Foundation/NSCoder.swift
@@ -147,9 +147,9 @@
   @nonobjc
   @available(swift, introduced: 4)
   @available(OSX 10.11, iOS 9.0, *)
-  public class func unarchiveTopLevelObjectWithData(_ data: NSData) throws -> Any? {
+  public class func unarchiveTopLevelObjectWithData(_ data: Data) throws -> Any? {
     var error: NSError?
-    let result = __NSKeyedUnarchiverUnarchiveObject(self, data, &error)
+    let result = __NSKeyedUnarchiverUnarchiveObject(self, data as NSData, &error)
     try resolveError(error)
     return result
   }
diff --git a/stdlib/public/SDK/Foundation/PlistEncoder.swift b/stdlib/public/SDK/Foundation/PlistEncoder.swift
index d7203fc..9fdd665 100644
--- a/stdlib/public/SDK/Foundation/PlistEncoder.swift
+++ b/stdlib/public/SDK/Foundation/PlistEncoder.swift
@@ -122,7 +122,7 @@
     /// Returns whether a new element can be encoded at this coding path.
     ///
     /// `true` if an element has not yet been encoded at this coding path; `false` otherwise.
-    var canEncodeNewElement: Bool {
+    var canEncodeNewValue: Bool {
         // Every time a new value gets encoded, the key it's encoded for is pushed onto the coding path (even if it's a nil key from an unkeyed container).
         // At the same time, every time a container is requested, a new value gets pushed onto the storage stack.
         // If there are more values on the storage stack than on the coding path, it means the value is requesting more than one container, which violates the precondition.
@@ -132,39 +132,43 @@
         return self.storage.count == self.codingPath.count
     }
 
-    /// Asserts that a new container can be requested at this coding path.
-    /// `preconditionFailure()`s if one cannot be requested.
-    func assertCanRequestNewContainer() {
-        guard self.canEncodeNewElement else {
-            let previousContainerType: String
-            if self.storage.containers.last is NSDictionary {
-                previousContainerType = "keyed"
-            } else if self.storage.containers.last is NSArray {
-                previousContainerType = "unkeyed"
-            } else {
-                previousContainerType = "single value"
-            }
-
-            preconditionFailure("Attempt to encode with new container when already encoded with \(previousContainerType) container.")
-        }
-    }
-
     // MARK: - Encoder Methods
     func container<Key>(keyedBy: Key.Type) -> KeyedEncodingContainer<Key> {
-        assertCanRequestNewContainer()
-        let topContainer = self.storage.pushKeyedContainer()
+        // If an existing keyed container was already requested, return that one.
+        let topContainer: NSMutableDictionary
+        if self.canEncodeNewValue {
+            // We haven't yet pushed a container at this level; do so here.
+            topContainer = self.storage.pushKeyedContainer()
+        } else {
+            guard let container = self.storage.containers.last as? NSMutableDictionary else {
+                preconditionFailure("Attempt to push new keyed encoding container when already previously encoded at this path.")
+            }
+
+            topContainer = container
+        }
+
         let container = _PlistKeyedEncodingContainer<Key>(referencing: self, codingPath: self.codingPath, wrapping: topContainer)
         return KeyedEncodingContainer(container)
     }
 
     func unkeyedContainer() -> UnkeyedEncodingContainer {
-        assertCanRequestNewContainer()
-        let topContainer = self.storage.pushUnkeyedContainer()
+        // If an existing unkeyed container was already requested, return that one.
+        let topContainer: NSMutableArray
+        if self.canEncodeNewValue {
+            // We haven't yet pushed a container at this level; do so here.
+            topContainer = self.storage.pushUnkeyedContainer()
+        } else {
+            guard let container = self.storage.containers.last as? NSMutableArray else {
+                preconditionFailure("Attempt to push new unkeyed encoding container when already previously encoded at this path.")
+            }
+
+            topContainer = container
+        }
+
         return _PlistUnkeyedEncodingContainer(referencing: self, codingPath: self.codingPath, wrapping: topContainer)
     }
 
     func singleValueContainer() -> SingleValueEncodingContainer {
-        assertCanRequestNewContainer()
         return self
     }
 }
@@ -382,106 +386,89 @@
 }
 
 extension _PlistEncoder : SingleValueEncodingContainer {
-    // MARK: - Utility Methods
-
-    /// Asserts that a single value can be encoded at the current coding path (i.e. that one has not already been encoded through this container).
-    /// `preconditionFailure()`s if one cannot be encoded.
-    ///
-    /// This is similar to assertCanRequestNewContainer above.
-    func assertCanEncodeSingleValue() {
-        guard self.canEncodeNewElement else {
-            let previousContainerType: String
-            if self.storage.containers.last is NSDictionary {
-                previousContainerType = "keyed"
-            } else if self.storage.containers.last is NSArray {
-                previousContainerType = "unkeyed"
-            } else {
-                preconditionFailure("Attempt to encode multiple values in a single value container.")
-            }
-
-            preconditionFailure("Attempt to encode with new container when already encoded with \(previousContainerType) container.")
-        }
-    }
-
     // MARK: - SingleValueEncodingContainer Methods
 
+    func assertCanEncodeNewValue() {
+        precondition(self.canEncodeNewValue, "Attempt to encode value through single value container when previously value already encoded.")
+    }
+
     func encodeNil() throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: _plistNullNSString)
     }
 
     func encode(_ value: Bool) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: Int) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: Int8) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: Int16) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: Int32) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: Int64) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: UInt) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: UInt8) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: UInt16) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: UInt32) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: UInt64) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: String) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: Float) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode(_ value: Double) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         self.storage.push(container: box(value))
     }
 
     func encode<T : Encodable>(_ value: T) throws {
-        assertCanEncodeSingleValue()
+        assertCanEncodeNewValue()
         try self.storage.push(container: box(value))
     }
 }
@@ -576,7 +563,7 @@
 
     // MARK: - Coding Path Operations
 
-    override var canEncodeNewElement: Bool {
+    override var canEncodeNewValue: Bool {
         // With a regular encoder, the storage and coding path grow together.
         // A referencing encoder, however, inherits its parents coding path, as well as the key it was created for.
         // We have to take this into account.
diff --git a/stdlib/public/SDK/Intents/INSearchCallHistoryIntent.swift b/stdlib/public/SDK/Intents/INSearchCallHistoryIntent.swift
index 1e65ae3..27000f1 100644
--- a/stdlib/public/SDK/Intents/INSearchCallHistoryIntent.swift
+++ b/stdlib/public/SDK/Intents/INSearchCallHistoryIntent.swift
@@ -14,27 +14,28 @@
 import Foundation
 
 #if os(iOS) || os(watchOS)
-@available(iOS 11.0, watchOS 4.0, *)
+@available(iOS 10.0, watchOS 3.2, *)
 extension INSearchCallHistoryIntent {
-    @nonobjc
-    public convenience init(
-        dateCreated: INDateComponentsRange? = nil,
-        recipient: INPerson? = nil,
-        callCapabilities: INCallCapabilityOptions,
-        callTypes: INCallRecordTypeOptions,
-        unseen: Bool? = nil
-        ) {
+  @available(iOS 10.0, watchOS 3.2, *)
+  @nonobjc
+  public convenience init(
+    dateCreated: INDateComponentsRange? = nil,
+    recipient: INPerson? = nil,
+    callCapabilities: INCallCapabilityOptions,
+    callTypes: INCallRecordTypeOptions,
+    unseen: Bool? = nil
+  ) {
+    self.init(__dateCreated: dateCreated,
+      recipient: recipient,
+      callCapabilities: callCapabilities,
+      callTypes: callTypes,
+      unseen: unseen.map { NSNumber(value: $0) })
+  }
 
-        self.init(__dateCreated: dateCreated,
-                  recipient: recipient,
-                  callCapabilities: callCapabilities,
-                  callTypes: callTypes,
-                  unseen: unseen.map { NSNumber(value: $0) })
-    }
-    
-    @nonobjc
-    public final var unseen: Bool? {
-        return __unseen?.boolValue
-    }
+  @available(iOS 11.0, watchOS 4.0, *)
+  @nonobjc
+  public final var unseen: Bool? {
+    return __unseen?.boolValue
+  }
 }
 #endif
diff --git a/stdlib/public/core/Codable.swift b/stdlib/public/core/Codable.swift
index 0403cef..5dc5d49 100644
--- a/stdlib/public/core/Codable.swift
+++ b/stdlib/public/core/Codable.swift
@@ -3233,15 +3233,33 @@
 }
 
 //===----------------------------------------------------------------------===//
-// Optional Conformance
+// Optional/Collection Type Conformances
 //===----------------------------------------------------------------------===//
 
+fileprivate func assertTypeIsEncodable<T>(_ type: T.Type, in wrappingType: Any.Type) {
+    guard T.self is Encodable.Type else {
+        if T.self == Encodable.self || T.self == Codable.self {
+            preconditionFailure("\(wrappingType) does not conform to Encodable because Encodable does not conform to itself. You must use a concrete type to encode or decode.")
+        } else {
+            preconditionFailure("\(wrappingType) does not conform to Encodable because \(T.self) does not conform to Encodable.")
+        }
+    }
+}
+
+fileprivate func assertTypeIsDecodable<T>(_ type: T.Type, in wrappingType: Any.Type) {
+    guard T.self is Decodable.Type else {
+        if T.self == Decodable.self || T.self == Codable.self {
+            preconditionFailure("\(wrappingType) does not conform to Decodable because Decodable does not conform to itself. You must use a concrete type to encode or decode.")
+        } else {
+            preconditionFailure("\(wrappingType) does not conform to Decodable because \(T.self) does not conform to Decodable.")
+        }
+    }
+}
+
 // FIXME: Uncomment when conditional conformance is available.
 extension Optional : Encodable /* where Wrapped : Encodable */ {
     public func encode(to encoder: Encoder) throws {
-        guard Wrapped.self is Encodable.Type else {
-            preconditionFailure("\(type(of: self)) does not conform to Encodable because \(Wrapped.self) does not conform to Encodable.")
-        }
+        assertTypeIsEncodable(Wrapped.self, in: type(of: self))
 
         var container = encoder.singleValueContainer()
         switch self {
@@ -3253,12 +3271,9 @@
 
 extension Optional : Decodable /* where Wrapped : Decodable */ {
     public init(from decoder: Decoder) throws {
-        // Initialize self here so we can print type(of: self).
+        // Initialize self here so we can get type(of: self).
         self = .none
-
-        guard Wrapped.self is Decodable.Type else {
-            preconditionFailure("\(type(of: self)) does not conform to Decodable because \(Wrapped.self) does not conform to Decodable.")
-        }
+        assertTypeIsDecodable(Wrapped.self, in: type(of: self))
 
         let container = try decoder.singleValueContainer()
         if !container.decodeNil() {
@@ -3269,16 +3284,10 @@
     }
 }
 
-//===----------------------------------------------------------------------===//
-// Collection Conformances
-//===----------------------------------------------------------------------===//
-
 // FIXME: Uncomment when conditional conformance is available.
 extension Array : Encodable /* where Element : Encodable */ {
     public func encode(to encoder: Encoder) throws {
-        guard Element.self is Encodable.Type else {
-            preconditionFailure("\(type(of: self)) does not conform to Encodable because \(Element.self) does not conform to Encodable.")
-        }
+        assertTypeIsEncodable(Element.self, in: type(of: self))
 
         var container = encoder.unkeyedContainer()
         for element in self {
@@ -3292,12 +3301,9 @@
 
 extension Array : Decodable /* where Element : Decodable */ {
     public init(from decoder: Decoder) throws {
-        // Initialize self here so we can print type(of: self).
+        // Initialize self here so we can get type(of: self).
         self.init()
-
-        guard Element.self is Decodable.Type else {
-            preconditionFailure("\(type(of: self)) does not conform to Decodable because \(Element.self) does not conform to Decodable.")
-        }
+        assertTypeIsDecodable(Element.self, in: type(of: self))
 
         let metaType = (Element.self as! Decodable.Type)
         var container = try decoder.unkeyedContainer()
@@ -3313,9 +3319,7 @@
 
 extension Set : Encodable /* where Element : Encodable */ {
     public func encode(to encoder: Encoder) throws {
-        guard Element.self is Encodable.Type else {
-            preconditionFailure("\(type(of: self)) does not conform to Encodable because \(Element.self) does not conform to Encodable.")
-        }
+        assertTypeIsEncodable(Element.self, in: type(of: self))
 
         var container = encoder.unkeyedContainer()
         for element in self {
@@ -3329,12 +3333,9 @@
 
 extension Set : Decodable /* where Element : Decodable */ {
     public init(from decoder: Decoder) throws {
-        // Initialize self here so we can print type(of: self).
+        // Initialize self here so we can get type(of: self).
         self.init()
-
-        guard Element.self is Decodable.Type else {
-            preconditionFailure("\(type(of: self)) does not conform to Decodable because \(Element.self) does not conform to Decodable.")
-        }
+        assertTypeIsDecodable(Element.self, in: type(of: self))
 
         let metaType = (Element.self as! Decodable.Type)
         var container = try decoder.unkeyedContainer()
@@ -3366,13 +3367,8 @@
 
 extension Dictionary : Encodable /* where Key : Encodable, Value : Encodable */ {
     public func encode(to encoder: Encoder) throws {
-        guard Key.self is Encodable.Type else {
-            preconditionFailure("\(type(of: self)) does not conform to Encodable because \(Key.self) does not conform to Encodable.")
-        }
-
-        guard Value.self is Encodable.Type else {
-            preconditionFailure("\(type(of: self)) does not conform to Encodable because \(Value.self) does not conform to Encodable.")
-        }
+        assertTypeIsEncodable(Key.self, in: type(of: self))
+        assertTypeIsEncodable(Value.self, in: type(of: self))
 
         if Key.self == String.self {
             // Since the keys are already Strings, we can use them as keys directly.
@@ -3411,14 +3407,8 @@
     public init(from decoder: Decoder) throws {
         // Initialize self here so we can print type(of: self).
         self.init()
-
-        guard Key.self is Decodable.Type else {
-            preconditionFailure("\(type(of: self)) does not conform to Decodable because \(Key.self) does not conform to Decodable.")
-        }
-
-        guard Value.self is Decodable.Type else {
-            preconditionFailure("\(type(of: self)) does not conform to Decodable because \(Value.self) does not conform to Decodable.")
-        }
+        assertTypeIsDecodable(Key.self, in: type(of: self))
+        assertTypeIsDecodable(Value.self, in: type(of: self))
 
         if Key.self == String.self {
             // The keys are Strings, so we should be able to expect a keyed container.
diff --git a/stdlib/public/core/DoubleWidth.swift.gyb b/stdlib/public/core/DoubleWidth.swift.gyb
index 2fa5f8a..70ae5d5 100644
--- a/stdlib/public/core/DoubleWidth.swift.gyb
+++ b/stdlib/public/core/DoubleWidth.swift.gyb
@@ -176,9 +176,9 @@
       }
 
       // TODO: move to Int128 just like init(_builtinIntegerLiteral:) ?
-      return (n < _storage.low.countRepresentedWords) ?
+      return (n < _storage.low._countRepresentedWords) ?
         _storage.low._word(at: n) :
-        _storage.high._word(at: n - _storage.low.countRepresentedWords)
+        _storage.high._word(at: n - _storage.low._countRepresentedWords)
     }
   }
 
diff --git a/stdlib/public/core/Integers.swift.gyb b/stdlib/public/core/Integers.swift.gyb
index 77f3533..692f4f8 100644
--- a/stdlib/public/core/Integers.swift.gyb
+++ b/stdlib/public/core/Integers.swift.gyb
@@ -1548,7 +1548,7 @@
   ///
   /// This property is a constant for instances of fixed-width integer types.
   @_transparent
-  public var countRepresentedWords: Int {
+  public var _countRepresentedWords: Int {
     return (self.bitWidth + ${word_bits} - 1) / ${word_bits}
   }
 
@@ -1888,12 +1888,19 @@
 #endif
 
 extension BinaryInteger {
+  // FIXME(integers): Should be removed once words get implemented properly.
+  // Meanhile it allows to conform to the BinaryInteger without implementing
+  // underscored APIs. https://bugs.swift.org/browse/SR-5275
+  public func _word(at n: Int) -> UInt {
+    fatalError("Should be overridden")
+  }
+
   // FIXME(integers): inefficient. Should get rid of _word(at:) and
-  // countRepresentedWords, and make `words` the basic operation.
+  // _countRepresentedWords, and make `words` the basic operation.
   public var words: [UInt] {
     var result = [UInt]()
-    result.reserveCapacity(countRepresentedWords)
-    for i in 0..<self.countRepresentedWords {
+    result.reserveCapacity(_countRepresentedWords)
+    for i in 0..<self._countRepresentedWords {
       result.append(_word(at: i))
     }
     return result
@@ -2321,7 +2328,7 @@
     else {
       var result: Self = source < (0 as T) ? ~0 : 0
       // start with the most significant word
-      var n = source.countRepresentedWords
+      var n = source._countRepresentedWords
       while n >= 0 {
         // masking is OK here because this we have already ensured
         // that Self.bitWidth > ${word_bits}.  Not masking results in
@@ -2794,7 +2801,7 @@
   @_transparent
   public func _word(at n: Int) -> UInt {
     _precondition(n >= 0, "Negative word index")
-    if _fastPath(n < countRepresentedWords) {
+    if _fastPath(n < _countRepresentedWords) {
       let shift = UInt(n._value) &* ${word_bits}
       let bitWidth = UInt(self.bitWidth._value)
       _sanityCheck(shift < bitWidth)
diff --git a/stdlib/public/runtime/Errors.cpp b/stdlib/public/runtime/Errors.cpp
index e939362..d634b4d 100644
--- a/stdlib/public/runtime/Errors.cpp
+++ b/stdlib/public/runtime/Errors.cpp
@@ -244,17 +244,21 @@
 }
 
 LLVM_ATTRIBUTE_NOINLINE SWIFT_RUNTIME_EXPORT
-void _swift_runtime_on_report(bool isFatal, const char *message,
+void _swift_runtime_on_report(uintptr_t flags, const char *message,
                               RuntimeErrorDetails *details) {
   // Do nothing. This function is meant to be used by the debugger.
 
   // The following is necessary to avoid calls from being optimized out.
-  asm volatile("" ::: "memory");
+  asm volatile("" // Do nothing.
+               : // Output list, empty.
+               : "r" (flags), "r" (message), "r" (details) // Input list.
+               : // Clobber list, empty.
+               );
 }
 
-void swift::reportToDebugger(bool isFatal, const char *message,
+void swift::reportToDebugger(uintptr_t flags, const char *message,
                              RuntimeErrorDetails *details) {
-  _swift_runtime_on_report(isFatal, message, details);
+  _swift_runtime_on_report(flags, message, details);
 }
 
 /// Report a fatal error to system console, stderr, and crash logs.
diff --git a/stdlib/public/runtime/Exclusivity.cpp b/stdlib/public/runtime/Exclusivity.cpp
index a5101f9..f144698 100644
--- a/stdlib/public/runtime/Exclusivity.cpp
+++ b/stdlib/public/runtime/Exclusivity.cpp
@@ -113,7 +113,7 @@
     .frames = &oldPC
   };
   RuntimeErrorDetails details = {
-    .version = 1,
+    .version = RuntimeErrorDetails::currentVersion,
     .errorType = "exclusivity-violation",
     .currentStackDescription = newAccess,
     .framesToSkip = framesToSkip,
@@ -121,7 +121,10 @@
     .numExtraThreads = 1,
     .threads = &secondaryThread
   };
-  reportToDebugger(!keepGoing, message, &details);
+  uintptr_t flags = RuntimeErrorFlagNone;
+  if (!keepGoing)
+    flags = RuntimeErrorFlagFatal;
+  reportToDebugger(flags, message, &details);
 
   if (keepGoing) {
     return;
@@ -150,7 +153,7 @@
 
   void setNext(Access *next) {
     NextAndAction =
-      reinterpret_cast<uintptr_t>(next) | (NextAndAction & NextMask);
+      reinterpret_cast<uintptr_t>(next) | (NextAndAction & ActionMask);
   }
 
   ExclusivityFlags getAccessAction() const {
@@ -209,8 +212,11 @@
       return;
     }
 
-    for (Access *last = cur; cur != nullptr; last = cur, cur = cur->getNext()) {
-      if (last == access) {
+    Access *last = cur;
+    for (cur = cur->getNext(); cur != nullptr;
+         last = cur, cur = cur->getNext()) {
+      assert(last->getNext() == cur);
+      if (cur == access) {
         last->setNext(cur->getNext());
         return;
       }
diff --git a/stdlib/public/runtime/SwiftObject.mm b/stdlib/public/runtime/SwiftObject.mm
index cac9ea0..1640322 100644
--- a/stdlib/public/runtime/SwiftObject.mm
+++ b/stdlib/public/runtime/SwiftObject.mm
@@ -1435,13 +1435,30 @@
            sel_getName(selector));
   asprintf(&nullTerminatedFilename, "%*s", (int)filenameLength, filename);
 
-  RuntimeErrorDetails details = {
-    .version = 1,
-    .errorType = "implicit-objc-entrypoint",
-    .framesToSkip = 1
+  RuntimeErrorDetails::FixIt fixit = {
+    .filename = nullTerminatedFilename,
+    .startLine = line,
+    .endLine = line,
+    .startColumn = column,
+    .endColumn = column,
+    .replacementText = "@objc "
   };
-  bool isFatal = reporter == swift::fatalError;
-  reportToDebugger(isFatal, message, &details);
+  RuntimeErrorDetails::Note note = {
+    .description = "add '@objc' to expose this Swift declaration to Objective-C",
+    .numFixIts = 1,
+    .fixIts = &fixit
+  };
+  RuntimeErrorDetails details = {
+    .version = RuntimeErrorDetails::currentVersion,
+    .errorType = "implicit-objc-entrypoint",
+    .framesToSkip = 1,
+    .numNotes = 1,
+    .notes = &note
+  };
+  uintptr_t runtime_error_flags = RuntimeErrorFlagNone;
+  if (reporter == swift::fatalError)
+    runtime_error_flags = RuntimeErrorFlagFatal;
+  reportToDebugger(runtime_error_flags, message, &details);
 
   reporter(flags,
            "*** %s:%zu:%zu: %s; add explicit '@objc' to the declaration to "
diff --git a/test/ClangImporter/Inputs/typedef-with-generic-param.h b/test/ClangImporter/Inputs/typedef-with-generic-param.h
new file mode 100644
index 0000000..f6f6918
--- /dev/null
+++ b/test/ClangImporter/Inputs/typedef-with-generic-param.h
@@ -0,0 +1,9 @@
+#import <Foundation/Foundation.h>
+
+@interface Foo <__covariant T>
+typedef void (^CompletionBlock)(T _Nullable result, NSError *_Nullable error);
+@end
+
+@interface Foo <T> (Convenience)
++ (Foo<T> *)fooWithCompletionBlock: (void (^)(CompletionBlock adapter))block;
+@end
diff --git a/test/ClangImporter/typedef_with_generic_param.swift b/test/ClangImporter/typedef_with_generic_param.swift
new file mode 100644
index 0000000..e80973a
--- /dev/null
+++ b/test/ClangImporter/typedef_with_generic_param.swift
@@ -0,0 +1,10 @@
+// RUN: %target-swift-frontend -typecheck %s -import-objc-header %S/Inputs/typedef-with-generic-param.h 2>&1
+
+// REQUIRES: OS=macosx
+
+typealias Result<T> = (T?, Error?)
+typealias Handler<T> = (Result<T>) -> Void
+
+func foo<T>(_ handler: Handler<T>?) {}
+
+let _ = Foo<AnyObject>(completionBlock: foo)
diff --git a/test/Constraints/diagnostics.swift b/test/Constraints/diagnostics.swift
index 8a1cbb8..0442af3b 100644
--- a/test/Constraints/diagnostics.swift
+++ b/test/Constraints/diagnostics.swift
@@ -983,3 +983,21 @@
 for var i in 0..<10 { // expected-warning {{variable 'i' was never mutated; consider changing to 'let' constant}} {{5-9=}}
   _ = i + 1
 }
+
+// rdar://problem/32726044 - shrink reduced domains too far
+
+public protocol P_32726044 {}
+
+extension Int: P_32726044 {}
+extension Float: P_32726044 {}
+
+public func *(lhs: P_32726044, rhs: P_32726044) -> Double {
+  fatalError()
+}
+
+func rdar32726044() -> Float {
+  var f: Float = 0
+  f = Float(1) * 100 // Ok
+  let _: Float = Float(42) + 0 // Ok
+  return f
+}
diff --git a/test/Constraints/gather_all_adjacencies.swift b/test/Constraints/gather_all_adjacencies.swift
new file mode 100644
index 0000000..b4587dd
--- /dev/null
+++ b/test/Constraints/gather_all_adjacencies.swift
@@ -0,0 +1,38 @@
+// RUN: %target-swift-frontend -typecheck %s
+
+// SR-5120 / rdar://problem/32618740
+protocol InitCollection: Collection {
+  init(_ array: [Iterator.Element])
+}
+
+protocol InitAny {
+  init()
+}
+
+extension Array: InitCollection {
+  init(_ array: [Iterator.Element]) {
+    self = array
+  }
+}
+
+extension String: InitAny {
+  init() {
+    self = "bar"
+  }
+}
+
+class Foo {
+  func foo<T: InitCollection, U: InitAny>(of type: U.Type) -> T
+  where T.Iterator.Element == U
+  {
+    return T.init([U.init()])
+  }
+
+  func foo<T: InitCollection, U: InitAny>(of type: U.Type) -> T?
+  where T.Iterator.Element == U
+  {
+    return T.init([U.init()])
+  }
+}
+
+let _: [String] = Foo().foo(of: String.self)
diff --git a/test/Frontend/embed-bitcode-tvos.ll b/test/Frontend/embed-bitcode-tvos.ll
new file mode 100644
index 0000000..ccac443
--- /dev/null
+++ b/test/Frontend/embed-bitcode-tvos.ll
@@ -0,0 +1,20 @@
+; REQUIRES: CODEGENERATOR=AArch64
+; RUN: llvm-as %s -o %t.bc
+; RUN: %swift -target arm64-apple-tvos9 -c -module-name someModule -embed-bitcode -disable-llvm-optzns -o %t2.o %t.bc -dump-clang-diagnostics 2> %t.diags.txt
+; RUN: llvm-objdump -macho -private-headers %t2.o | %FileCheck %s
+; RUN: %FileCheck -check-prefix CHECK-IMPORTER %s < %t.diags.txt
+
+target triple = "arm64-apple-tvos9.0"
+target datalayout = "e-m:o-i64:64-i128:128-n32:64-S128"
+
+; CHECK: LC_VERSION_MIN_TVOS
+
+; CHECK-IMPORTER: clang
+; CHECK-IMPORTER: -fembed-bitcode
+; CHECK-IMPORTER: -target
+; CHECK-IMPORTER: -mtvos-version-min=9
+; CHECK-IMPORTER-NOT: argument unused
+
+define i32 @f0() nounwind ssp {
+       ret i32 0
+}
diff --git a/test/IDE/Inputs/custom-modules/Newtype.h b/test/IDE/Inputs/custom-modules/Newtype.h
index 3fb29a9..476dbea 100644
--- a/test/IDE/Inputs/custom-modules/Newtype.h
+++ b/test/IDE/Inputs/custom-modules/Newtype.h
@@ -102,3 +102,29 @@
 
 extern const NSSomeContextName NSMyContextName;
 
+typedef struct T *TRef __attribute((swift_newtype(struct)));
+typedef const struct T *ConstTRef __attribute((swift_newtype(struct)));
+extern _Nonnull TRef create_T(void);
+extern _Nonnull ConstTRef create_ConstT(void);
+extern void destroy_T(TRef);
+extern void destroy_ConstT(ConstTRef);
+
+extern void mutate_TRef_Pointee(TRef) __attribute((swift_name("TRef.mutatePointee(self:)")));
+extern void mutate_TRef(TRef *) __attribute((swift_name("TRef.mutate(self:)")));
+extern void use_ConstT(ConstTRef)
+    __attribute((swift_name("ConstTRef.use(self:)")));
+
+
+typedef struct T *__nonnull *TRefRef __attribute((swift_newtype(struct)));
+typedef struct T *__nonnull const *ConstTRefRef __attribute((swift_newtype(struct)));
+extern _Nonnull TRefRef create_TRef(void);
+extern _Nonnull ConstTRefRef create_ConstTRef(void);
+extern void destroy_TRef(TRefRef);
+extern void destroy_ConstTRef(ConstTRefRef);
+
+extern void mutate_TRefRef_Pointee(TRefRef)
+    __attribute((swift_name("TRefRef.mutatePointee(self:)")));
+extern void mutate_TRefRef(TRefRef*)
+    __attribute((swift_name("TRefRef.mutate(self:)")));
+extern void use_ConstTRef(ConstTRefRef)
+    __attribute((swift_name("ConstTRefRef.use(self:)")));
diff --git a/test/IDE/newtype.swift b/test/IDE/newtype.swift
index e3f6402..bd697cd 100644
--- a/test/IDE/newtype.swift
+++ b/test/IDE/newtype.swift
@@ -149,6 +149,54 @@
 // PRINT-NEXT:  extension NSSomeContext.Name {
 // PRINT-NEXT:    static let myContextName: NSSomeContext.Name
 // PRINT-NEXT:  }
+//
+// PRINT-NEXT: struct TRef : RawRepresentable, _SwiftNewtypeWrapper, Equatable, Hashable {
+// PRINT-NEXT:   init(_ rawValue: OpaquePointer)
+// PRINT-NEXT:   init(rawValue: OpaquePointer)
+// PRINT-NEXT:   let rawValue: OpaquePointer
+// PRINT-NEXT:   typealias RawValue = OpaquePointer
+// PRINT-NEXT: }
+// PRINT-NEXT: struct ConstTRef : RawRepresentable, _SwiftNewtypeWrapper, Equatable, Hashable {
+// PRINT-NEXT:   init(_ rawValue: OpaquePointer)
+// PRINT-NEXT:   init(rawValue: OpaquePointer)
+// PRINT-NEXT:   let rawValue: OpaquePointer
+// PRINT-NEXT:   typealias RawValue = OpaquePointer
+// PRINT-NEXT: }
+// PRINT-NEXT: func create_T() -> TRef
+// PRINT-NEXT: func create_ConstT() -> ConstTRef
+// PRINT-NEXT: func destroy_T(_: TRef!)
+// PRINT-NEXT: func destroy_ConstT(_: ConstTRef!)
+// PRINT-NEXT: extension TRef {
+// PRINT-NEXT:   func mutatePointee()
+// PRINT-NEXT:   mutating func mutate()
+// PRINT-NEXT: }
+// PRINT-NEXT: extension ConstTRef {
+// PRINT-NEXT:   func use()
+// PRINT-NEXT: }
+//
+// PRINT-NEXT: struct TRefRef : RawRepresentable, _SwiftNewtypeWrapper, Equatable, Hashable {
+// PRINT-NEXT:   init(_ rawValue: UnsafeMutablePointer<OpaquePointer>)
+// PRINT-NEXT:   init(rawValue: UnsafeMutablePointer<OpaquePointer>)
+// PRINT-NEXT:   let rawValue: UnsafeMutablePointer<OpaquePointer>
+// PRINT-NEXT:   typealias RawValue = UnsafeMutablePointer<OpaquePointer>
+// PRINT-NEXT: }
+// PRINT-NEXT: struct ConstTRefRef : RawRepresentable, _SwiftNewtypeWrapper, Equatable, Hashable {
+// PRINT-NEXT:   init(_ rawValue: UnsafePointer<OpaquePointer>)
+// PRINT-NEXT:   init(rawValue: UnsafePointer<OpaquePointer>)
+// PRINT-NEXT:   let rawValue: UnsafePointer<OpaquePointer>
+// PRINT-NEXT:   typealias RawValue = UnsafePointer<OpaquePointer>
+// PRINT-NEXT: }
+// PRINT-NEXT: func create_TRef() -> TRefRef
+// PRINT-NEXT: func create_ConstTRef() -> ConstTRefRef
+// PRINT-NEXT: func destroy_TRef(_: TRefRef!)
+// PRINT-NEXT: func destroy_ConstTRef(_: ConstTRefRef!)
+// PRINT-NEXT: extension TRefRef {
+// PRINT-NEXT:   func mutatePointee()
+// PRINT-NEXT:   mutating func mutate()
+// PRINT-NEXT: }
+// PRINT-NEXT: extension ConstTRefRef {
+// PRINT-NEXT:   func use()
+// PRINT-NEXT: }
 
 import Newtype
 
diff --git a/test/IRGen/keypaths.sil b/test/IRGen/keypaths.sil
index 9771318..4b638eb 100644
--- a/test/IRGen/keypaths.sil
+++ b/test/IRGen/keypaths.sil
@@ -1,4 +1,7 @@
-// RUN: %target-swift-frontend -emit-ir %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize
+// RUN: rm -rf %t && mkdir -p %t
+// -- Convert <i32 0x...> constants to decimal constants that LLVM will print
+// RUN: %utils/chex.py < %s > %t/keypaths.sil
+// RUN: %target-swift-frontend -emit-ir %s | %FileCheck %t/keypaths.sil --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize
 
 sil_stage canonical
 import Swift
@@ -27,8 +30,8 @@
 // CHECK-SAME: [[WORD]] 0,
 // CHECK-SAME: %swift.type* (i8*)*
 // CHECK-SAME: %swift.type* (i8*)*
-//               -- 0x8000_0004 - instantiable in-line, size 4
-// CHECK-SAME: i32 -2147483644,
+//               -- instantiable in-line, size 4
+// CHECK-SAME: <i32 0x8000_0004>,
 // CHECK-64-SAME: [4 x i8] zeroinitializer,
 // -- offset of S.x
 // CHECK-SAME: i32 0 }>
@@ -38,8 +41,8 @@
 // CHECK-SAME: [[WORD]] 0,
 // CHECK-SAME: %swift.type* (i8*)*
 // CHECK-SAME: %swift.type* (i8*)*
-//               -- 0x8000_0004 - instantiable in-line, size 4
-// CHECK-SAME: i32 -2147483644,
+//               -- instantiable in-line, size 4
+// CHECK-SAME: <i32 0x8000_0004>,
 // CHECK-64-SAME: [4 x i8] zeroinitializer,
 // -- offset of S.y
 // CHECK-32-SAME: i32 4 }>
@@ -50,8 +53,8 @@
 // CHECK-SAME: [[WORD]] 0,
 // CHECK-SAME: %swift.type* (i8*)*
 // CHECK-SAME: %swift.type* (i8*)*
-//               -- 0x8000_0004 - instantiable in-line, size 4
-// CHECK-SAME: i32 -2147483644,
+//               -- instantiable in-line, size 4
+// CHECK-SAME: <i32 0x8000_0004>,
 // CHECK-64-SAME: [4 x i8] zeroinitializer,
 // -- offset of S.z
 // CHECK-32-SAME: i32 16 }>
@@ -62,46 +65,46 @@
 // CHECK-SAME: [[WORD]] 0,
 // CHECK-SAME: %swift.type* (i8*)*
 // CHECK-SAME: %swift.type* (i8*)*
-//               -- 0x8000_0004 - instantiable in-line, size 4
-// CHECK-SAME: i32 -2147483644,
+//               -- instantiable in-line, size 4
+// CHECK-SAME: <i32 0x8000_0004>,
 // CHECK-64-SAME: [4 x i8] zeroinitializer,
 // -- 0x4000_0000 (class) + offset of C.x
-// CHECK-32-SAME: i32 1073741836 }>
-// CHECK-64-SAME: i32 1073741840 }>
+// CHECK-32-SAME: <i32 0x4000_000c> }>
+// CHECK-64-SAME: <i32 0x4000_0010> }>
 
 // -- %e: C.y
 // CHECK: [[KP_E:@keypath.*]] = private global <{ {{.*}} }> <{
 // CHECK-SAME: [[WORD]] 0,
 // CHECK-SAME: %swift.type* (i8*)*
 // CHECK-SAME: %swift.type* (i8*)*
-//               -- 0x8000_0004 - instantiable in-line, size 4
-// CHECK-SAME: i32 -2147483644,
+//               -- instantiable in-line, size 4
+// CHECK-SAME: <i32 0x8000_0004>,
 // CHECK-64-SAME: [4 x i8] zeroinitializer,
 // -- 0x4000_0000 (class) + offset of C.y
-// CHECK-32-SAME: i32 1073741840 }>
-// CHECK-64-SAME: i32 1073741848 }>
+// CHECK-32-SAME: <i32 0x4000_0010> }>
+// CHECK-64-SAME: <i32 0x4000_0018> }>
 
 // -- %f: C.z
 // CHECK: [[KP_F:@keypath.*]] = private global <{ {{.*}} }> <{
 // CHECK-SAME: [[WORD]] 0,
 // CHECK-SAME: %swift.type* (i8*)*
 // CHECK-SAME: %swift.type* (i8*)*
-//               -- 0x8000_0004 - instantiable in-line, size 4
-// CHECK-SAME: i32 -2147483644,
+//               -- instantiable in-line, size 4
+// CHECK-SAME: <i32 0x8000_0004>,
 // CHECK-64-SAME: [4 x i8] zeroinitializer,
 // -- 0x4000_0000 (class) + offset of C.z
-// CHECK-32-SAME: i32 1073741852 }>
-// CHECK-64-SAME: i32 1073741872 }>
+// CHECK-32-SAME: <i32 0x4000_001c> }>
+// CHECK-64-SAME: <i32 0x4000_0030> }>
 
 // -- %g: S.z.x
 // CHECK: [[KP_G:@keypath.*]] = private global <{ {{.*}} }> <{
 // CHECK-SAME: [[WORD]] 0,
 // CHECK-SAME: %swift.type* (i8*)*
 // CHECK-SAME: %swift.type* (i8*)*
-//                  -- 0x8000_000c - instantiable in-line, size 12
-// CHECK-32-SAME: i32 -2147483636,
-//                  -- 0x8000_0014 - instantiable in-line, size 16
-// CHECK-64-SAME: i32 -2147483628,
+//                  -- instantiable in-line, size 12
+// CHECK-32-SAME: <i32 0x8000_000c>,
+//                  -- instantiable in-line, size 20
+// CHECK-64-SAME: <i32 0x8000_0014>,
 // CHECK-64-SAME: [4 x i8] zeroinitializer,
 // -- offset of S.z
 // CHECK-32-SAME: i32 16,
@@ -109,22 +112,22 @@
 // CHECK-64-SAME: [4 x i8] zeroinitializer,
 // CHECK: %swift.type* (i8*)*
 // -- 0x4000_0000 (class) + offset of C.x
-// CHECK-32-SAME: i32 1073741836 }>
-// CHECK-64-SAME: i32 1073741840 }>
+// CHECK-32-SAME: <i32 0x4000_000c> }>
+// CHECK-64-SAME: <i32 0x4000_0010> }>
 
 // -- %h: C.z.x
 // CHECK: [[KP_H:@keypath.*]] = private global <{ {{.*}} }> <{
 // CHECK-SAME: [[WORD]] 0,
 // CHECK-SAME: %swift.type* (i8*)*
 // CHECK-SAME: %swift.type* (i8*)*
-//                  -- 0x8000_000c - instantiable in-line, size 12
-// CHECK-32-SAME: i32 -2147483636,
-//                  -- 0x8000_0014 - instantiable in-line, size 16
-// CHECK-64-SAME: i32 -2147483628,
+//                  -- instantiable in-line, size 12
+// CHECK-32-SAME: <i32 0x8000_000c>,
+//                  -- instantiable in-line, size 20
+// CHECK-64-SAME: <i32 0x8000_0014>,
 // CHECK-64-SAME: [4 x i8] zeroinitializer,
 // -- 0x4000_0000 (class) + offset of C.z
-// CHECK-32-SAME: i32 1073741852,
-// CHECK-64-SAME: i32 1073741872,
+// CHECK-32-SAME: <i32 0x4000_001c>,
+// CHECK-64-SAME: <i32 0x4000_0030>,
 // CHECK-64-SAME: [4 x i8] zeroinitializer,
 // CHECK: %swift.type* (i8*)*
 // -- offset of S.x
@@ -135,13 +138,13 @@
 // CHECK-SAME: [[WORD]] 0,
 // CHECK-SAME: %swift.type* (i8*)*
 // CHECK-SAME: %swift.type* (i8*)*
-//              -- 0x8000_0018 - instantiable in-line, size 24
-// CHECK-64-SAME: i32 -2147483624,
+//              -- instantiable in-line, size 24
+// CHECK-64-SAME: <i32 0x8000_0018>,
 // CHECK-64-SAME: [4 x i8] zeroinitializer,
-//              -- 0x8000_000c - instantiable in-line, size 12
-// CHECK-32-SAME: i32 -2147483636,
-// -- 0x2000_0000 - computed, get-only, identified by function pointer, no args
-// CHECK-SAME: i32 536870912,
+//              -- instantiable in-line, size 12
+// CHECK-32-SAME: <i32 0x8000_000c>,
+// -- computed, get-only, identified by function pointer, no args
+// CHECK-SAME: <i32 0x2000_0000>,
 // CHECK-64-SAME: [4 x i8] zeroinitializer,
 // CHECK-SAME: void ()* @k_id,
 // CHECK-SAME: void (%TSi*, %T8keypaths1SV*)* @k_get }>
@@ -151,13 +154,13 @@
 // CHECK-SAME: [[WORD]] 0,
 // CHECK-SAME: %swift.type* (i8*)*
 // CHECK-SAME: %swift.type* (i8*)*
-//              -- 0x8000_0020 - instantiable in-line, size 32
-// CHECK-64-SAME: i32 -2147483616,
+//              -- instantiable in-line, size 32
+// CHECK-64-SAME: <i32 0x8000_0020>,
 // CHECK-64-SAME: [4 x i8] zeroinitializer,
-//              -- 0x8000_0010 - instantiable in-line, size 16
-// CHECK-32-SAME: i32 -2147483632,
-// -- 0x2a00_0000 - computed, settable, nonmutating, identified by vtable, no args
-// CHECK-SAME: i32 704643072,
+//              -- instantiable in-line, size 16
+// CHECK-32-SAME: <i32 0x8000_0010>,
+// -- computed, settable, nonmutating, identified by vtable, no args
+// CHECK-SAME: <i32 0x2a00_0000>,
 // CHECK-64-SAME: [4 x i8] zeroinitializer,
 // CHECK-SAME: [[WORD]]
 // CHECK-SAME: void (%TSi*, %T8keypaths1CC**)* @l_get,
@@ -168,13 +171,13 @@
 // CHECK-SAME: [[WORD]] 0,
 // CHECK-SAME: %swift.type* (i8*)*
 // CHECK-SAME: %swift.type* (i8*)*
-//              -- 0x8000_0020 - instantiable in-line, size 32
-// CHECK-64-SAME: i32 -2147483616,
+//              -- instantiable in-line, size 32
+// CHECK-64-SAME: <i32 0x8000_0020>,
 // CHECK-64-SAME: [4 x i8] zeroinitializer,
-//              -- 0x8000_0010 - instantiable in-line, size 16
-// CHECK-32-SAME: i32 -2147483632,
-// -- 0x3c00_0000 - computed, settable, nonmutating, identified by property offset, no args
-// CHECK-SAME: i32 1006632960,
+//              -- instantiable in-line, size 16
+// CHECK-32-SAME: <i32 0x8000_0010>,
+// -- computed, settable, nonmutating, identified by property offset, no args
+// CHECK-SAME: <i32 0x3c00_0000>,
 // CHECK-64-SAME: [4 x i8] zeroinitializer,
 // CHECK-SAME: [[WORD]]
 // CHECK-SAME: void (%swift.function*, %T8keypaths1SV*)* @m_get,
@@ -189,8 +192,8 @@
 //             -- size 8
 // CHECK-SAME: i32 8,
 // CHECK-64-SAME: [4 x i8] zeroinitializer,
-//             -- 0x1ffffffe - struct with runtime-resolved offset
-// CHECK-SAME: i32 536870910,
+//             -- struct with runtime-resolved offset
+// CHECK-SAME: <i32 0x1ffffffe>,
 // CHECK-32-SAME: i32 12 }>
 // CHECK-64-SAME: i32 24 }>
 
@@ -202,8 +205,8 @@
 //             -- size 8
 // CHECK-SAME: i32 8,
 // CHECK-64-SAME: [4 x i8] zeroinitializer,
-//             -- 0x1ffffffe - struct with runtime-resolved offset
-// CHECK-SAME: i32 536870910,
+//             -- struct with runtime-resolved offset
+// CHECK-SAME: <i32 0x1ffffffe>,
 // CHECK-32-SAME: i32 16 }>
 // CHECK-64-SAME: i32 32 }>
 
diff --git a/test/IRGen/newtype.swift b/test/IRGen/newtype.swift
index e1ad051..ee50e60 100644
--- a/test/IRGen/newtype.swift
+++ b/test/IRGen/newtype.swift
@@ -158,3 +158,71 @@
     return num
   }
 }
+
+// OPT-LABEL: _T07newtype6mutateyyF
+public func mutate() {
+  // Check for a mismatch in indirectness of the swift_newtype and the Clang
+  // type. These pointers should be passed directly for non-mutating functions,
+  // rather than passing a pointer indirectly. I.e. only 1 overall level of
+  // indirection for non-mutating, 2 for mutating.
+  //
+  // OPT: [[TRefAlloca:%.+]] = alloca %struct.T*,
+  // OPT: [[TRef:%.+]] = tail call %struct.T* @create_T()
+  // OPT: store %struct.T* [[TRef]], %struct.T** [[TRefAlloca]],
+  var myT = create_T()
+
+  // OPT: [[TRefConst:%.+]] = tail call %struct.T* @create_ConstT()
+  let myConstT = create_ConstT()
+
+  // OPT: tail call void @mutate_TRef_Pointee(%struct.T* [[TRef]])
+  myT.mutatePointee()
+
+  // OPT: call void @mutate_TRef(%struct.T** nonnull [[TRefAlloca]])
+  myT.mutate()
+
+  // Since myT itself got mutated, now we have to reload from the alloca
+  //
+  // OPT: [[TRefReloaded:%.+]] = load %struct.T*, %struct.T** [[TRefAlloca]],
+  // OPT: call void @mutate_TRef_Pointee(%struct.T* [[TRefReloaded]])
+  myT.mutatePointee()
+
+  // OPT: call void @use_ConstT(%struct.T* [[TRefConst]])
+  myConstT.use()
+
+  // OPT: ret void
+}
+
+// OPT-LABEL: _T07newtype9mutateRefyyF
+public func mutateRef() {
+  // Check for a mismatch in indirectness of the swift_newtype and the Clang
+  // type. These pointer pointers should be passed directly, rather than passing
+  // a pointer pointer indirectly. I.e. only 2 overall levels of indirection for
+  // non-mutating, 3 for mutating.
+  //
+  // OPT: [[TRefRefAlloca:%.+]] = alloca %struct.T**,
+  // OPT: [[TRefRef:%.+]] = tail call %struct.T** @create_TRef()
+  // OPT: store %struct.T** [[TRefRef]], %struct.T*** [[TRefRefAlloca]]
+  var myTRef = create_TRef()
+
+  // OPT: [[ConstTRefRef:%.+]] = tail call %struct.T** @create_ConstTRef()
+  let myConstTRef = create_ConstTRef()
+
+  // OPT: tail call void @mutate_TRefRef_Pointee(%struct.T** [[TRefRef]])
+  myTRef.mutatePointee()
+
+  // OPT: call void @mutate_TRefRef(%struct.T*** nonnull [[TRefRefAlloca]])
+  myTRef.mutate()
+
+  // Since myTRef itself got mutated, now we have to reload from the alloca
+  //
+  // OPT: [[TRefReloaded:%.+]] = load %struct.T**, %struct.T*** [[TRefRefAlloca]]
+  // OPT: call void @mutate_TRefRef_Pointee(%struct.T** [[TRefReloaded]])
+  myTRef.mutatePointee()
+
+  // OPT: call void @use_ConstTRef(%struct.T** [[ConstTRefRef]])
+  myConstTRef.use()
+
+  // OPT: ret void
+}
+
+
diff --git a/test/Index/kinds.swift b/test/Index/kinds.swift
index 8948202..a831a9e 100644
--- a/test/Index/kinds.swift
+++ b/test/Index/kinds.swift
@@ -37,6 +37,9 @@
       return base
     }
   }
+  // CHECK: [[@LINE-20]]:13 | param/Swift | index | {{.*}} | Def,RelChild | rel: 1
+  // CHECK: [[@LINE-21]]:20 | struct/Swift | Int | {{.*}} | Ref | rel: 0
+  // CHECK: [[@LINE-22]]:28 | struct/Swift | Int | {{.*}} | Ref | rel: 0
 }
 
 // Class
diff --git a/test/Interpreter/simd.swift b/test/Interpreter/simd.swift
new file mode 100644
index 0000000..b1bd7e8
--- /dev/null
+++ b/test/Interpreter/simd.swift
@@ -0,0 +1,31 @@
+// RUN: %target-run-simple-swift | %FileCheck %s
+// REQUIRES: executable_test
+// REQUIRES: OS=macosx
+
+import simd
+
+public struct Vector3f {
+  var f3: float3
+  init() {
+    f3 = float3(0, 1, 2)
+  }
+}
+
+public struct TwoFloat {
+  var f0 : Float
+  var f1 : Float
+  init() {
+    f0 = 0.0
+    f1 = 1.0
+  }
+}
+
+public func test() -> (Vector3f, TwoFloat) {
+  let v = Vector3f()
+  let y = TwoFloat()
+  let r = (v, y)
+  return r
+}
+
+// CHECK: (main.Vector3f(f3: float3(0.0, 1.0, 2.0)), main.TwoFloat(f0: 0.0, f1: 1.0))
+print(test())
diff --git a/test/Misc/expression_too_complex_4.swift b/test/Misc/expression_too_complex_4.swift
new file mode 100644
index 0000000..446149a
--- /dev/null
+++ b/test/Misc/expression_too_complex_4.swift
@@ -0,0 +1,6 @@
+// RUN: %target-typecheck-verify-swift -swift-version 4 -solver-expression-time-threshold=1 -warn-long-expression-type-checking=1 -solver-memory-threshold 1500000000
+
+func test(_ i: Int, _ j: Int) -> Int {
+  return 1 + (((i >> 1) + (i >> 2) + (i >> 3) + (i >> 4) << 1) << 1) & 0x40
+  // expected-error@-1 {{expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions}}
+}
diff --git a/test/Parse/line-directive-executable.swift b/test/Parse/line-directive-executable.swift
new file mode 100644
index 0000000..cc4e268
--- /dev/null
+++ b/test/Parse/line-directive-executable.swift
@@ -0,0 +1,64 @@
+// RUN: %target-run-simple-swift | %FileCheck %s
+// REQUIRES: executable_test
+
+print("START") // CHECK-LABEL: START
+
+func check(file: String = #file, line: Int = #line) {
+    print("\(file):\(line)")
+}
+
+#sourceLocation(file: "a.swift", line: 100)
+check() // CHECK-NEXT: {{^}}a.swift:100
+
+public struct S {
+    #sourceLocation(file: "b.swift", line: 100)
+    func foo() { check() }
+
+    #sourceLocation(file: "c.swift", line: 200)
+
+    func bar() { check() }
+
+    #sourceLocation(file: "d.swift", line: 300)
+}
+check() // CHECK-NEXT: {{^}}d.swift:301
+S().foo() // CHECK-NEXT: {{^}}b.swift:100
+S().bar() // CHECK-NEXT: {{^}}c.swift:201
+
+enum E {
+#sourceLocation(file: "e.swift", line: 400)
+}
+check() // CHECK-NEXT: {{^}}e.swift:401
+
+class C {
+#sourceLocation()
+}
+check() // CHECK-NEXT: .swift:[[@LINE]]
+
+extension C {
+#sourceLocation(file: "f.swift", line: 500)
+    static var file: String { return #file }
+
+    #sourceLocation(file: "g.swift", line: 600)
+    var line: Int { return #line }
+
+#sourceLocation(file: "h.swift", line: 700)
+}
+check() // CHECK-NEXT: {{^}}h.swift:701
+check(file: C.file, line: C().line) // CHECK-NEXT: {{^}}f.swift:600
+
+func test() {
+#sourceLocation(file: "i.swift", line: 800)
+    check()
+#sourceLocation(file: "j.swift", line: 900)
+}
+
+check() // CHECK-NEXT: {{^}}j.swift:902
+test() // CHECK-NEXT: {{^}}i.swift:800
+
+#sourceLocation()
+check() // CHECK-NEXT: .swift:[[@LINE]]
+
+#sourceLocation(file: "k.swift", line: 1000)
+
+
+check() // CHECK-NEXT: {{^}}k.swift:1002
diff --git a/test/Parse/line-directive.swift b/test/Parse/line-directive.swift
index 55a5d5b..8423b68 100644
--- a/test/Parse/line-directive.swift
+++ b/test/Parse/line-directive.swift
@@ -40,3 +40,16 @@
 LABEL:
 #line 200 "labeled.swift"
 #sourceLocation()
+
+class C {
+#sourceLocation(file: "sr5242.swift", line: 100)
+    func foo() {}
+    let bar = 12
+#sourceLocation(file: "sr5242.swift", line: 200)
+}
+enum E {
+#sourceLocation(file: "sr5242.swift", line: 300)
+    case A, B
+    case C, D
+#sourceLocation()
+}
diff --git a/test/Prototypes/BigInt.swift b/test/Prototypes/BigInt.swift
index b474367..c8f0b58 100644
--- a/test/Prototypes/BigInt.swift
+++ b/test/Prototypes/BigInt.swift
@@ -121,7 +121,7 @@
     // FIXME: This is broken on 32-bit arch w/ Word = UInt64
     let wordRatio = UInt.bitWidth / Word.bitWidth
     _sanityCheck(wordRatio != 0)
-    for i in 0..<source.countRepresentedWords {
+    for i in 0..<source._countRepresentedWords {
       var sourceWord = source._word(at: i)
       for _ in 0..<wordRatio {
         _data.append(Word(extendingOrTruncating: sourceWord))
diff --git a/test/SILGen/c_function_pointers.swift b/test/SILGen/c_function_pointers.swift
index 7724353..18e5141 100644
--- a/test/SILGen/c_function_pointers.swift
+++ b/test/SILGen/c_function_pointers.swift
@@ -63,3 +63,9 @@
   init(a: ()) {}
   init(b: ()) {}
 }
+
+func pointers_to_nested_local_functions_in_generics<T>(x: T) -> Int{
+  func foo(y: Int) -> Int { return y }
+
+  return calls(foo, 0)
+}
diff --git a/test/SILGen/indirect_enum.swift b/test/SILGen/indirect_enum.swift
index b3f04cd..030e77d 100644
--- a/test/SILGen/indirect_enum.swift
+++ b/test/SILGen/indirect_enum.swift
@@ -199,18 +199,18 @@
   // CHECK:       [[TUPLE:%.*]] = load_borrow [[TUPLE_ADDR]]
   // CHECK:       [[LEFT:%.*]] = tuple_extract [[TUPLE]] {{.*}}, 0
   // CHECK:       [[RIGHT:%.*]] = tuple_extract [[TUPLE]] {{.*}}, 1
+  // CHECK:       switch_enum [[LEFT]] : $TreeA<T>,
+  // CHECK:          case #TreeA.Leaf!enumelt.1: [[LEAF_CASE_LEFT:bb[0-9]+]],
+  // CHECK:          default [[FAIL_LEFT:bb[0-9]+]]
+
+  // CHECK:     [[LEAF_CASE_LEFT]]([[LEFT_LEAF_BOX:%.*]] : $<τ_0_0> { var τ_0_0 } <T>):
+  // CHECK:       [[LEFT_LEAF_VALUE:%.*]] = project_box [[LEFT_LEAF_BOX]]
   // CHECK:       switch_enum [[RIGHT]] : $TreeA<T>,
   // CHECK:          case #TreeA.Leaf!enumelt.1: [[LEAF_CASE_RIGHT:bb[0-9]+]],
   // CHECK:          default [[FAIL_RIGHT:bb[0-9]+]]
 
   // CHECK:     [[LEAF_CASE_RIGHT]]([[RIGHT_LEAF_BOX:%.*]] : $<τ_0_0> { var τ_0_0 } <T>):
   // CHECK:       [[RIGHT_LEAF_VALUE:%.*]] = project_box [[RIGHT_LEAF_BOX]]
-  // CHECK:       switch_enum [[LEFT]] : $TreeA<T>,
-  // CHECK:          case #TreeA.Leaf!enumelt.1: [[LEAF_CASE_LEFT:bb[0-9]+]],
-  // CHECK:          default [[FAIL_LEFT:bb[0-9]+]]
-  
-  // CHECK:     [[LEAF_CASE_LEFT]]([[LEFT_LEAF_BOX:%.*]] : $<τ_0_0> { var τ_0_0 } <T>):
-  // CHECK:       [[LEFT_LEAF_VALUE:%.*]] = project_box [[LEFT_LEAF_BOX]]
   // CHECK:       copy_addr [[LEFT_LEAF_VALUE]]
   // CHECK:       copy_addr [[RIGHT_LEAF_VALUE]]
   // --           x +1
@@ -218,10 +218,10 @@
   // CHECK:       end_borrow [[BORROWED_ARG]] from [[ARG]]
   // CHECK:       br [[OUTER_CONT]]
 
-  // CHECK:     [[FAIL_LEFT]]:
+  // CHECK:     [[FAIL_RIGHT]]:
   // CHECK:       br [[DEFAULT:bb[0-9]+]]
 
-  // CHECK:     [[FAIL_RIGHT]]:
+  // CHECK:     [[FAIL_LEFT]]:
   // CHECK:       br [[DEFAULT]]
 
   case .Branch(.Leaf(let x), .Leaf(let y)):
@@ -278,16 +278,16 @@
   // CHECK:       [[TUPLE:%.*]] = project_box [[BOX]]
   // CHECK:       [[LEFT:%.*]] = tuple_element_addr [[TUPLE]]
   // CHECK:       [[RIGHT:%.*]] = tuple_element_addr [[TUPLE]]
-  // CHECK:       switch_enum_addr [[RIGHT]] {{.*}}, default [[RIGHT_FAIL:bb[0-9]+]]
-
-  // CHECK:     bb{{.*}}:
-  // CHECK:       copy_addr [[RIGHT]] to [initialization] [[RIGHT_COPY:%.*]] :
-  // CHECK:       [[RIGHT_LEAF:%.*]] = unchecked_take_enum_data_addr [[RIGHT_COPY]] : $*TreeB<T>, #TreeB.Leaf
   // CHECK:       switch_enum_addr [[LEFT]] {{.*}}, default [[LEFT_FAIL:bb[0-9]+]]
 
   // CHECK:     bb{{.*}}:
   // CHECK:       copy_addr [[LEFT]] to [initialization] [[LEFT_COPY:%.*]] :
   // CHECK:       [[LEFT_LEAF:%.*]] = unchecked_take_enum_data_addr [[LEFT_COPY]] : $*TreeB<T>, #TreeB.Leaf
+  // CHECK:       switch_enum_addr [[RIGHT]] {{.*}}, default [[RIGHT_FAIL:bb[0-9]+]]
+
+  // CHECK:     bb{{.*}}:
+  // CHECK:       copy_addr [[RIGHT]] to [initialization] [[RIGHT_COPY:%.*]] :
+  // CHECK:       [[RIGHT_LEAF:%.*]] = unchecked_take_enum_data_addr [[RIGHT_COPY]] : $*TreeB<T>, #TreeB.Leaf
   // CHECK:       copy_addr [take] [[LEFT_LEAF]] to [initialization] [[X:%.*]] :
   // CHECK:       copy_addr [take] [[RIGHT_LEAF]] to [initialization] [[Y:%.*]] :
   // CHECK:       function_ref @_T013indirect_enum1c{{[_0-9a-zA-Z]*}}F
@@ -295,10 +295,10 @@
   // CHECK:       dealloc_stack [[Y]]
   // CHECK:       destroy_addr [[X]]
   // CHECK:       dealloc_stack [[X]]
-  // CHECK-NOT:   destroy_addr [[LEFT_COPY]]
-  // CHECK:       dealloc_stack [[LEFT_COPY]]
   // CHECK-NOT:   destroy_addr [[RIGHT_COPY]]
   // CHECK:       dealloc_stack [[RIGHT_COPY]]
+  // CHECK-NOT:   destroy_addr [[LEFT_COPY]]
+  // CHECK:       dealloc_stack [[LEFT_COPY]]
   // --           box +0
   // CHECK:       destroy_value [[BOX]]
   // CHECK-NOT:   destroy_addr [[TREE_COPY]]
@@ -308,16 +308,16 @@
   case .Branch(.Leaf(let x), .Leaf(let y)):
     c(x, y)
 
-  // CHECK:     [[LEFT_FAIL]]:
-  // CHECK:       destroy_addr [[RIGHT_LEAF]]
-  // CHECK-NOT:   destroy_addr [[RIGHT_COPY]]
-  // CHECK:       dealloc_stack [[RIGHT_COPY]]
+  // CHECK:     [[RIGHT_FAIL]]:
+  // CHECK:       destroy_addr [[LEFT_LEAF]]
+  // CHECK-NOT:   destroy_addr [[LEFT_COPY]]
+  // CHECK:       dealloc_stack [[LEFT_COPY]]
   // CHECK:       destroy_value [[BOX]]
   // CHECK-NOT:   destroy_addr [[TREE_COPY]]
   // CHECK:       dealloc_stack [[TREE_COPY]]
   // CHECK:       br [[INNER_CONT:bb[0-9]+]]
 
-  // CHECK:     [[RIGHT_FAIL]]:
+  // CHECK:     [[LEFT_FAIL]]:
   // CHECK:       destroy_value [[BOX]]
   // CHECK-NOT:   destroy_addr [[TREE_COPY]]
   // CHECK:       dealloc_stack [[TREE_COPY]]
diff --git a/test/SILGen/switch.swift b/test/SILGen/switch.swift
index 41b615f..c5275b4 100644
--- a/test/SILGen/switch.swift
+++ b/test/SILGen/switch.swift
@@ -1071,8 +1071,8 @@
     
   case (.some(let base), .some(let filter)):
     // CHECK: bb2(%10 : $Int):
-    // CHECK-NEXT: debug_value %10 : $Int, let, name "base"
-    // CHECK-NEXT: debug_value %8 : $Int, let, name "filter"
+    // CHECK-NEXT: debug_value %8 : $Int, let, name "base"
+    // CHECK-NEXT: debug_value %10 : $Int, let, name "filter"
     print("both: \(base), \(filter)")
   case (.some(let base), .none), (.none, .some(let base)):
     // CHECK: bb3:
diff --git a/test/SILOptimizer/access_enforcement_noescape.swift b/test/SILOptimizer/access_enforcement_noescape.swift
index 23d3a08..d9c4456 100644
--- a/test/SILOptimizer/access_enforcement_noescape.swift
+++ b/test/SILOptimizer/access_enforcement_noescape.swift
@@ -503,3 +503,62 @@
 //   let c = { x = 42 }
 //   doOneInout(c, &x)
 // }
+
+// Helper
+func doBlockInout(_: @convention(block) ()->(), _: inout Int) {}
+
+// FIXME: This case could be statically enforced, but requires quite a bit of SIL pattern matching.
+func readBlockWriteInout() {
+  var x = 3
+  // Around the call: [modify] [static]
+  // Inside closure: [modify] [static]
+  doBlockInout({ _ = x }, &x)
+}
+
+// CHECK-LABEL: sil hidden @_T027access_enforcement_noescape19readBlockWriteInoutyyF : $@convention(thin) () -> () {
+// CHECK: [[F1:%.*]] = function_ref @_T027access_enforcement_noescape19readBlockWriteInoutyyFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> ()
+// CHECK: [[PA:%.*]] = partial_apply [[F1]](%0) : $@convention(thin) (@inout_aliasable Int) -> ()
+// CHECK-NOT: begin_access
+// CHECK: [[WRITE:%.*]] = begin_access [modify] [static] %0 : $*Int
+// CHECK: apply
+// CHECK: end_access [[WRITE]] : $*Int
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape19readBlockWriteInoutyyF'
+
+// CHECK-LABEL: sil private @_T027access_enforcement_noescape19readBlockWriteInoutyyFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
+// CHECK: begin_access [read] [static] %0 : $*Int
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape19readBlockWriteInoutyyFyycfU_'
+
+// Test AccessSummaryAnalysis.
+//
+// The captured @inout_aliasable argument to `doOne` is re-partially applied,
+// then stored is a box before passing it to doBlockInout.
+func noEscapeBlock() {
+  var x = 3
+  doOne {
+    doBlockInout({ _ = x }, &x)
+  }
+}
+// CHECK-LABEL: sil hidden @_T027access_enforcement_noescape13noEscapeBlockyyF : $@convention(thin) () -> () {
+// CHECK: partial_apply
+// CHECK-NOT: begin_access
+// CHECK: apply
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape13noEscapeBlockyyF'
+
+// CHECK-LABEL: sil private @_T027access_enforcement_noescape13noEscapeBlockyyFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
+// CHECK: [[F1:%.*]] = function_ref @_T027access_enforcement_noescape13noEscapeBlockyyFyycfU_yycfU_ : $@convention(thin) (@inout_aliasable Int) -> ()
+// CHECK: [[PA:%.*]] = partial_apply [[F1]](%0) : $@convention(thin) (@inout_aliasable Int) -> ()
+// CHECK: [[STORAGE:%.*]] = alloc_stack $@block_storage @callee_owned () -> ()
+// CHECK: [[ADDR:%.*]] = project_block_storage %5 : $*@block_storage @callee_owned () -> ()
+// CHECK: store [[PA]] to [[ADDR]] : $*@callee_owned () -> ()
+// CHECK: [[BLOCK:%.*]] = init_block_storage_header [[STORAGE]] : $*@block_storage @callee_owned () -> (), invoke %8 : $@convention(c) (@inout_aliasable @block_storage @callee_owned () -> ()) -> (), type $@convention(block) () -> ()
+// CHECK: [[ARG:%.*]] = copy_block [[BLOCK]] : $@convention(block) () -> ()
+// CHECK: [[WRITE:%.*]] = begin_access [modify] [static] %0 : $*Int
+// CHECK: apply %{{.*}}([[ARG]], [[WRITE]]) : $@convention(thin) (@owned @convention(block) () -> (), @inout Int) -> ()
+// CHECK: end_access [[WRITE]] : $*Int
+// CHECK: dealloc_stack [[STORAGE]] : $*@block_storage @callee_owned () -> ()
+// CHECK: strong_release [[PA]] : $@callee_owned () -> ()
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape13noEscapeBlockyyFyycfU_'
+
+// CHECK-LABEL: sil private @_T027access_enforcement_noescape13noEscapeBlockyyFyycfU_yycfU_ : $@convention(thin) (@inout_aliasable Int) -> () {
+// CHECK: begin_access [read] [static] %0 : $*Int
+// CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape13noEscapeBlockyyFyycfU_yycfU_'
diff --git a/test/SILOptimizer/access_summary_analysis.sil b/test/SILOptimizer/access_summary_analysis.sil
index 92adb96..b07a5eb 100644
--- a/test/SILOptimizer/access_summary_analysis.sil
+++ b/test/SILOptimizer/access_summary_analysis.sil
@@ -228,6 +228,31 @@
   return %8 : $()
 }
 
+// CHECK-LABEL: @reads
+// CHECK-NEXT: (read)
+sil private  @reads : $@convention(thin) (@inout_aliasable Int) -> Int {
+bb0(%0 : $*Int):
+  %3 = begin_access [read] [unknown] %0 : $*Int
+  %4 = load %3 : $*Int
+  end_access %3 : $*Int
+  return %4 : $Int
+}
+
+// CHECK-LABEL: @convertPartialApplyAndPassToPartialApply
+// CHECK-NEXT: (read)
+sil hidden @convertPartialApplyAndPassToPartialApply : $@convention(thin) (@inout_aliasable Int) -> () {
+bb0(%0 : $*Int):
+  %2 = function_ref @takesAutoClosureReturningGeneric : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@owned @callee_owned () -> (@out τ_0_0, @error Error)) -> ()
+  %3 = function_ref @reads : $@convention(thin) (@inout_aliasable Int) -> Int
+  %4 = partial_apply %3(%0) : $@convention(thin) (@inout_aliasable Int) -> Int
+  %5 = convert_function %4 : $@callee_owned () -> Int to $@callee_owned () -> (Int, @error Error)
+  %6 = function_ref @thunkForAutoClosure : $@convention(thin) (@owned @callee_owned () -> (Int, @error Error)) -> (@out Int, @error Error)
+  %7 = partial_apply %6(%5) : $@convention(thin) (@owned @callee_owned () -> (Int, @error Error)) -> (@out Int, @error Error)
+  %8 = apply %2<Int>(%7) : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@owned @callee_owned () -> (@out τ_0_0, @error Error)) -> ()
+  %9 = tuple ()
+  return %9 : $()
+}
+
 // CHECK-LABEL: @selfRecursion
 // CHECK-NEXT: (modify, none)
 sil private @selfRecursion : $@convention(thin) (@inout_aliasable Int, Int) -> () {
diff --git a/test/SILOptimizer/inline_cache_and_arc.swift b/test/SILOptimizer/inline_cache_and_arc.swift
new file mode 100644
index 0000000..0601f30
--- /dev/null
+++ b/test/SILOptimizer/inline_cache_and_arc.swift
@@ -0,0 +1,38 @@
+// RUN: %target-swift-frontend -parse-as-library -O -emit-sil  %s | %FileCheck %s
+// REQUIRES: swift_stdlib_no_asserts,optimized_stdlib,CPU=x86_64
+
+// Test inline cache with a global class. Make sure the retain|release pair
+// for the fast path is removed in the loop.
+
+open class A
+{
+  open func f(_ a: Int) -> Int
+  {
+    return a + 1
+  }
+}
+
+var x = 0
+public var a = A()
+
+public func testit() {
+// CHECK-LABEL: sil @{{.*}}testityyF
+// CHECK:     bb0:
+// CHECK-NOT:   {{.*(retain|release).*}}
+// CHECK:       checked_cast_br
+// CHECK:     bb1{{.*}}:
+// CHECK-NOT:   {{.*(retain|release).*}}
+// CHECK:       return
+// CHECK:     bb2{{.*}}:
+// CHECK-NOT:   {{.*(retain|release|apply).*}}
+// CHECK:       br bb1
+// CHECK:     bb3{{.*}}:
+// CHECK-NEXT:  class_method
+// CHECK-NEXT:  strong_retain
+// CHECK-NEXT:  apply
+// CHECK-NEXT:  strong_release
+// CHECK-NEXT:  br bb1
+
+  x = a.f(x)
+}
+
diff --git a/test/api-digester/Inputs/cake.swift b/test/api-digester/Inputs/cake.swift
index 5a7906c..52595ff 100644
--- a/test/api-digester/Inputs/cake.swift
+++ b/test/api-digester/Inputs/cake.swift
@@ -7,8 +7,10 @@
   public func foo6() -> Void {}
 }
 
-public class C1 {
+public class C0 {}
+
+public class C1: C0 {
 	open class func foo1() {}
 	public weak var Ins : C1?
 	public unowned var Ins2 : C1 = C1()
-}
\ No newline at end of file
+}
diff --git a/test/api-digester/Inputs/cake1.swift b/test/api-digester/Inputs/cake1.swift
index 3932eea..c2f8125 100644
--- a/test/api-digester/Inputs/cake1.swift
+++ b/test/api-digester/Inputs/cake1.swift
@@ -13,6 +13,7 @@
   public weak var CIIns1 : C1?
   public var CIIns2 : C1?
   public func foo3(a : Void?) {}
+  public func foo4(a : Void?) {}
 }
 
 public class C3 {}
diff --git a/test/api-digester/Inputs/cake2.swift b/test/api-digester/Inputs/cake2.swift
index e9407ec..fb4ada9 100644
--- a/test/api-digester/Inputs/cake2.swift
+++ b/test/api-digester/Inputs/cake2.swift
@@ -7,7 +7,11 @@
   public func foo5(x : Int, y: Int, z: Int) {}
 }
 
-public class C1 {
+public class C0 {
+  public func foo4(a : Void?) {}
+}
+
+public class C1: C0 {
   public func foo1() {}
   public func foo2(_ : ()->()) {}
   public var CIIns1 : C1?
diff --git a/test/api-digester/Outputs/Cake.txt b/test/api-digester/Outputs/Cake.txt
index ba2b822..07f1e1d 100644
--- a/test/api-digester/Outputs/Cake.txt
+++ b/test/api-digester/Outputs/Cake.txt
@@ -1,7 +1,6 @@
 
 /* Removed Decls */
 Class C3 has been removed
-Constructor C1.init() has been removed
 Constructor Somestruct2.init(_:) has been removed
 
 /* Moved Decls */
diff --git a/test/api-digester/Outputs/cake.json b/test/api-digester/Outputs/cake.json
index 41ab70d..07e05ee 100644
--- a/test/api-digester/Outputs/cake.json
+++ b/test/api-digester/Outputs/cake.json
@@ -5,6 +5,33 @@
   "children": [
     {
       "kind": "TypeDecl",
+      "name": "C0",
+      "printedName": "C0",
+      "declKind": "Class",
+      "usr": "s:4cake2C0C",
+      "location": "",
+      "moduleName": "cake",
+      "children": [
+        {
+          "kind": "Constructor",
+          "name": "init",
+          "printedName": "init()",
+          "declKind": "Constructor",
+          "usr": "s:4cake2C0CACycfc",
+          "location": "",
+          "moduleName": "cake",
+          "children": [
+            {
+              "kind": "TypeNominal",
+              "name": "C0",
+              "printedName": "C0"
+            }
+          ]
+        }
+      ]
+    },
+    {
+      "kind": "TypeDecl",
       "name": "S1",
       "printedName": "S1",
       "declKind": "Struct",
@@ -95,6 +122,7 @@
       "usr": "s:4cake2C1C",
       "location": "",
       "moduleName": "cake",
+      "superclassUsr": "s:4cake2C0C",
       "children": [
         {
           "kind": "Function",
diff --git a/test/attr/attr_dynamic_infer.swift b/test/attr/attr_dynamic_infer.swift
index 4fc57ba..32b3ced 100644
--- a/test/attr/attr_dynamic_infer.swift
+++ b/test/attr/attr_dynamic_infer.swift
@@ -59,7 +59,7 @@
 @objc class FinalTests {}
 
 extension FinalTests {
-  // CHECK:  @objc final func foo
+  // CHECK: @objc final func foo
   final func foo() { }
 
   // CHECK: @objc final var prop: Super
@@ -77,5 +77,11 @@
     // CHECK: @objc final set
     set { }
   }
+
+  // CHECK: @objc static var x
+  static var x: Int = 0
+
+  // CHECK: @objc static func bar
+  static func bar() { }
 }
 
diff --git a/test/stdlib/TestData.swift b/test/stdlib/TestData.swift
index 470a393..6a1a6b1 100644
--- a/test/stdlib/TestData.swift
+++ b/test/stdlib/TestData.swift
@@ -1236,9 +1236,7 @@
     data.append("hello", count: Int.min)
 }
 
-DataTests.test("bounding failure subscript")
-        .skip(.always("fails with resilient stdlib (rdar://problem/30560514)"))
-        .code {
+DataTests.test("bounding failure subscript") {
     var data = "Hello World".data(using: .utf8)!
     expectCrashLater()
     data[100] = 4
diff --git a/test/stdlib/TestIndexPath.swift b/test/stdlib/TestIndexPath.swift
index 5635612..79112b9 100644
--- a/test/stdlib/TestIndexPath.swift
+++ b/test/stdlib/TestIndexPath.swift
@@ -720,6 +720,14 @@
         let slice = indexPath[1..<1]
         expectEqual(0, slice.count)
     }
+
+    func test_dropFirst() {
+        var pth = IndexPath(indexes:[1,2,3,4])
+        while !pth.isEmpty {
+            // this should not crash 
+            pth = pth.dropFirst()
+        }
+    }
 }
 
 #if !FOUNDATION_XCTEST
@@ -772,5 +780,6 @@
 IndexPathTests.test("test_AnyHashableCreatedFromNSIndexPath") { TestIndexPath().test_AnyHashableCreatedFromNSIndexPath() }
 IndexPathTests.test("test_unconditionallyBridgeFromObjectiveC") { TestIndexPath().test_unconditionallyBridgeFromObjectiveC() }
 IndexPathTests.test("test_slice_1ary") { TestIndexPath().test_slice_1ary() }
+IndexPathTests.test("test_dropFirst") { TestIndexPath().test_dropFirst() }
 runAllTests()
 #endif
diff --git a/test/stdlib/TestJSONEncoder.swift b/test/stdlib/TestJSONEncoder.swift
index 0c70563..0c06e38 100644
--- a/test/stdlib/TestJSONEncoder.swift
+++ b/test/stdlib/TestJSONEncoder.swift
@@ -86,6 +86,12 @@
     _testRoundTrip(of: company)
   }
 
+  func testEncodingClassWhichSharesEncoderWithSuper() {
+    // Employee is a type which shares its encoder & decoder with its superclass, Person.
+    let employee = Employee.testValue
+    _testRoundTrip(of: employee)
+  }
+
   // MARK: - Output Formatting Tests
   func testEncodingOutputFormattingDefault() {
     let expectedJSON = "{\"name\":\"Johnny Appleseed\",\"email\":\"appleseed@apple.com\"}".data(using: .utf8)!
@@ -527,10 +533,6 @@
 fileprivate class Person : Codable, Equatable {
   let name: String
   let email: String
-
-  // FIXME: This property is present only in order to test the expected result of Codable synthesis in the compiler.
-  // We want to test against expected encoded output (to ensure this generates an encodeIfPresent call), but we need an output format for that.
-  // Once we have a VerifyingEncoder for compiler unit tests, we should move this test there.
   let website: URL?
 
   init(name: String, email: String, website: URL? = nil) {
@@ -539,23 +541,86 @@
     self.website = website
   }
 
-  static func ==(_ lhs: Person, _ rhs: Person) -> Bool {
-    return lhs.name == rhs.name &&
-           lhs.email == rhs.email &&
-           lhs.website == rhs.website
+  private enum CodingKeys : String, CodingKey {
+    case name
+    case email
+    case website
   }
 
-  static var testValue: Person {
+  // FIXME: Remove when subclasses (Employee) are able to override synthesized conformance.
+  required init(from decoder: Decoder) throws {
+    let container = try decoder.container(keyedBy: CodingKeys.self)
+    name = try container.decode(String.self, forKey: .name)
+    email = try container.decode(String.self, forKey: .email)
+    website = try container.decodeIfPresent(URL.self, forKey: .website)
+  }
+
+  func encode(to encoder: Encoder) throws {
+    var container = encoder.container(keyedBy: CodingKeys.self)
+    try container.encode(name, forKey: .name)
+    try container.encode(email, forKey: .email)
+    try container.encodeIfPresent(website, forKey: .website)
+  }
+
+  func isEqual(_ other: Person) -> Bool {
+    return self.name == other.name &&
+           self.email == other.email &&
+           self.website == other.website
+  }
+
+  static func ==(_ lhs: Person, _ rhs: Person) -> Bool {
+    return lhs.isEqual(rhs)
+  }
+
+  class var testValue: Person {
     return Person(name: "Johnny Appleseed", email: "appleseed@apple.com")
   }
 }
 
+/// A class which shares its encoder and decoder with its superclass.
+fileprivate class Employee : Person {
+  let id: Int
+
+  init(name: String, email: String, website: URL? = nil, id: Int) {
+    self.id = id
+    super.init(name: name, email: email, website: website)
+  }
+
+  enum CodingKeys : String, CodingKey {
+    case id
+  }
+
+  required init(from decoder: Decoder) throws {
+    let container = try decoder.container(keyedBy: CodingKeys.self)
+    id = try container.decode(Int.self, forKey: .id)
+    try super.init(from: decoder)
+  }
+
+  override func encode(to encoder: Encoder) throws {
+    var container = encoder.container(keyedBy: CodingKeys.self)
+    try container.encode(id, forKey: .id)
+    try super.encode(to: encoder)
+  }
+
+  override func isEqual(_ other: Person) -> Bool {
+    if let employee = other as? Employee {
+      guard self.id == employee.id else { return false }
+    }
+
+    return super.isEqual(other)
+  }
+
+  override class var testValue: Employee {
+    return Employee(name: "Johnny Appleseed", email: "appleseed@apple.com", id: 42)
+  }
+}
+
 /// A simple company struct which encodes as a dictionary of nested values.
 fileprivate struct Company : Codable, Equatable {
   let address: Address
-  var employees: [Person]
+  var employees: [Employee]
 
-  init(address: Address, employees: [Person]) {
+  init(address: Address, employees: [Employee]) {
     self.address = address
     self.employees = employees
   }
@@ -565,7 +630,7 @@
   }
 
   static var testValue: Company {
-    return Company(address: Address.testValue, employees: [Person.testValue])
+    return Company(address: Address.testValue, employees: [Employee.testValue])
   }
 }
 
@@ -797,6 +862,7 @@
 JSONEncoderTests.test("testEncodingTopLevelStructuredSingleStruct") { TestJSONEncoder().testEncodingTopLevelStructuredSingleStruct() }
 JSONEncoderTests.test("testEncodingTopLevelStructuredSingleClass") { TestJSONEncoder().testEncodingTopLevelStructuredSingleClass() }
 JSONEncoderTests.test("testEncodingTopLevelDeepStructuredType") { TestJSONEncoder().testEncodingTopLevelDeepStructuredType()}
+JSONEncoderTests.test("testEncodingClassWhichSharesEncoderWithSuper") { TestJSONEncoder().testEncodingClassWhichSharesEncoderWithSuper() }
 JSONEncoderTests.test("testEncodingOutputFormattingDefault") { TestJSONEncoder().testEncodingOutputFormattingDefault() }
 JSONEncoderTests.test("testEncodingOutputFormattingPrettyPrinted") { TestJSONEncoder().testEncodingOutputFormattingPrettyPrinted() }
 JSONEncoderTests.test("testEncodingOutputFormattingSortedKeys") { TestJSONEncoder().testEncodingOutputFormattingSortedKeys() }
diff --git a/test/stdlib/TestPlistEncoder.swift b/test/stdlib/TestPlistEncoder.swift
index 85b87e8..92615df 100644
--- a/test/stdlib/TestPlistEncoder.swift
+++ b/test/stdlib/TestPlistEncoder.swift
@@ -104,6 +104,13 @@
     _testRoundTrip(of: company, in: .xml)
   }
 
+  func testEncodingClassWhichSharesEncoderWithSuper() {
+    // Employee is a type which shares its encoder & decoder with its superclass, Person.
+    let employee = Employee.testValue
+    _testRoundTrip(of: employee, in: .binary)
+    _testRoundTrip(of: employee, in: .xml)
+  }
+
   // MARK: - Encoder Features
   func testNestedContainerCodingPaths() {
     let encoder = JSONEncoder()
@@ -330,27 +337,94 @@
 fileprivate class Person : Codable, Equatable {
   let name: String
   let email: String
+  let website: URL?
 
-  init(name: String, email: String) {
+  init(name: String, email: String, website: URL? = nil) {
     self.name = name
     self.email = email
+    self.website = website
+  }
+
+  private enum CodingKeys : String, CodingKey {
+    case name
+    case email
+    case website
+  }
+
+  // FIXME: Remove when subclasses (Employee) are able to override synthesized conformance.
+  required init(from decoder: Decoder) throws {
+    let container = try decoder.container(keyedBy: CodingKeys.self)
+    name = try container.decode(String.self, forKey: .name)
+    email = try container.decode(String.self, forKey: .email)
+    website = try container.decodeIfPresent(URL.self, forKey: .website)
+  }
+
+  func encode(to encoder: Encoder) throws {
+    var container = encoder.container(keyedBy: CodingKeys.self)
+    try container.encode(name, forKey: .name)
+    try container.encode(email, forKey: .email)
+    try container.encodeIfPresent(website, forKey: .website)
+  }
+
+  func isEqual(_ other: Person) -> Bool {
+    return self.name == other.name &&
+           self.email == other.email &&
+           self.website == other.website
   }
 
   static func ==(_ lhs: Person, _ rhs: Person) -> Bool {
-    return lhs.name == rhs.name && lhs.email == rhs.email
+    return lhs.isEqual(rhs)
   }
 
-  static var testValue: Person {
+  class var testValue: Person {
     return Person(name: "Johnny Appleseed", email: "appleseed@apple.com")
   }
 }
 
+/// A class which shares its encoder and decoder with its superclass.
+fileprivate class Employee : Person {
+  let id: Int
+
+  init(name: String, email: String, website: URL? = nil, id: Int) {
+    self.id = id
+    super.init(name: name, email: email, website: website)
+  }
+
+  enum CodingKeys : String, CodingKey {
+    case id
+  }
+
+  required init(from decoder: Decoder) throws {
+    let container = try decoder.container(keyedBy: CodingKeys.self)
+    id = try container.decode(Int.self, forKey: .id)
+    try super.init(from: decoder)
+  }
+
+  override func encode(to encoder: Encoder) throws {
+    var container = encoder.container(keyedBy: CodingKeys.self)
+    try container.encode(id, forKey: .id)
+    try super.encode(to: encoder)
+  }
+
+  override func isEqual(_ other: Person) -> Bool {
+    if let employee = other as? Employee {
+      guard self.id == employee.id else { return false }
+    }
+
+    return super.isEqual(other)
+  }
+
+  override class var testValue: Employee {
+    return Employee(name: "Johnny Appleseed", email: "appleseed@apple.com", id: 42)
+  }
+}
+
 /// A simple company struct which encodes as a dictionary of nested values.
 fileprivate struct Company : Codable, Equatable {
   let address: Address
-  var employees: [Person]
+  var employees: [Employee]
 
-  init(address: Address, employees: [Person]) {
+  init(address: Address, employees: [Employee]) {
     self.address = address
     self.employees = employees
   }
@@ -360,7 +434,7 @@
   }
 
   static var testValue: Company {
-    return Company(address: Address.testValue, employees: [Person.testValue])
+    return Company(address: Address.testValue, employees: [Employee.testValue])
   }
 }
 
@@ -550,6 +624,7 @@
 PropertyListEncoderTests.test("testEncodingTopLevelStructuredSingleStruct") { TestPropertyListEncoder().testEncodingTopLevelStructuredSingleStruct() }
 PropertyListEncoderTests.test("testEncodingTopLevelStructuredSingleClass") { TestPropertyListEncoder().testEncodingTopLevelStructuredSingleClass() }
 PropertyListEncoderTests.test("testEncodingTopLevelDeepStructuredType") { TestPropertyListEncoder().testEncodingTopLevelDeepStructuredType() }
+PropertyListEncoderTests.test("testEncodingClassWhichSharesEncoderWithSuper") { TestPropertyListEncoder().testEncodingClassWhichSharesEncoderWithSuper() }
 PropertyListEncoderTests.test("testNestedContainerCodingPaths") { TestPropertyListEncoder().testNestedContainerCodingPaths() }
 PropertyListEncoderTests.test("testSuperEncoderCodingPaths") { TestPropertyListEncoder().testSuperEncoderCodingPaths() }
 runAllTests()
diff --git a/tools/swift-api-digester/swift-api-digester.cpp b/tools/swift-api-digester/swift-api-digester.cpp
index 80533ca..4842b9b 100644
--- a/tools/swift-api-digester/swift-api-digester.cpp
+++ b/tools/swift-api-digester/swift-api-digester.cpp
@@ -299,12 +299,15 @@
   Ownership Ownership = Ownership::Strong;
   std::vector<SDKDeclAttrKind> DeclAttrs;
   std::vector<TypeAttrKind> TypeAttrs;
+  StringRef SuperclassUsr;
   SDKNodeInitInfo(SDKContext &Ctx) : Ctx(Ctx) {}
   SDKNodeInitInfo(SDKContext &Ctx, ValueDecl *VD);
   SDKNodeInitInfo(SDKContext &Ctx, Type Ty);
   SDKNode* createSDKNode(SDKNodeKind Kind);
 };
 
+class SDKNodeRoot;
+
 class SDKNode {
   typedef std::vector<SDKNode*>::iterator ChildIt;
   SDKContext &Ctx;
@@ -351,6 +354,7 @@
   unsigned getChildIndex(NodePtr Child) const;
   const SDKNode* getOnlyChild() const;
   SDKContext &getSDKContext() const { return Ctx; }
+  SDKNodeRoot *getRootNode() const;
   template <typename T> const T *getAs() const;
   template <typename T> T *getAs();
 };
@@ -388,6 +392,27 @@
   bool isStatic() const { return IsStatic; };
 };
 
+class SDKNodeRoot :public SDKNode {
+  /// This keeps track of all decl descendants with USRs.
+  llvm::StringMap<SDKNodeDecl*> DescendantDeclTable;
+
+public:
+  SDKNodeRoot(SDKNodeInitInfo Info) : SDKNode(Info, SDKNodeKind::Root) {}
+  static SDKNode *getInstance(SDKContext &Ctx);
+  static bool classof(const SDKNode *N);
+  void registerDescendant(SDKNode *D) {
+    if (auto DD = dyn_cast<SDKNodeDecl>(D)) {
+      assert(!DD->getUsr().empty());
+      DescendantDeclTable[DD->getUsr()] = DD;
+    }
+  }
+  Optional<SDKNodeDecl*> getDescendantByUsr(StringRef Usr) {
+    if (DescendantDeclTable.count(Usr))
+      return DescendantDeclTable[Usr];
+    return None;
+  }
+};
+
 NodePtr UpdatedNodesMap::findUpdateCounterpart(const SDKNode *Node) const {
   assert(Node->isAnnotatedAs(NodeAnnotation::Updated) && "Not update operation.");
   auto FoundPair = std::find_if(MapImpl.begin(), MapImpl.end(),
@@ -474,9 +499,27 @@
   return *Children.begin();
 }
 
+SDKNodeRoot *SDKNode::getRootNode() const {
+  for (auto *Root = const_cast<SDKNode*>(this); ; Root = Root->getParent()) {
+    if (auto Result = dyn_cast<SDKNodeRoot>(Root))
+      return Result;
+  }
+  llvm_unreachable("Unhandled SDKNodeKind in switch.");
+}
+
 void SDKNode::addChild(SDKNode *Child) {
   Child->Parent = this;
   Children.push_back(Child);
+  if (auto *Root = dyn_cast<SDKNodeRoot>(this)) {
+    struct DeclCollector: public SDKNodeVisitor {
+      SDKNodeRoot &Root;
+      DeclCollector(SDKNodeRoot &Root): Root(Root) {}
+      void visit(NodePtr Node) override {
+        Root.registerDescendant(Node);
+      }
+    } Collector(*Root);
+    SDKNode::preorderVisit(Child, Collector);
+  }
 }
 
 ArrayRef<SDKNode*> SDKNode::getChildren() const {
@@ -601,13 +644,6 @@
     TypeAttributes.end();
 }
 
-class SDKNodeRoot : public SDKNode {
-public:
-  SDKNodeRoot(SDKNodeInitInfo Info) : SDKNode(Info, SDKNodeKind::Root) {}
-  static SDKNode *getInstance(SDKContext &Ctx);
-  static bool classof(const SDKNode *N);
-};
-
 SDKNode *SDKNodeRoot::getInstance(SDKContext &Ctx) {
   SDKNodeInitInfo Info(Ctx);
   Info.Name = Ctx.buffer("TopLevel");
@@ -683,10 +719,33 @@
 }
 
 class SDKNodeTypeDecl : public SDKNodeDecl {
+  StringRef SuperclassUsr;
 public:
-  SDKNodeTypeDecl(SDKNodeInitInfo Info) : SDKNodeDecl(Info,
-                                                      SDKNodeKind::TypeDecl) {}
+  SDKNodeTypeDecl(SDKNodeInitInfo Info) : SDKNodeDecl(Info, SDKNodeKind::TypeDecl),
+                                          SuperclassUsr(Info.SuperclassUsr) {}
   static bool classof(const SDKNode *N);
+  StringRef getSuperClassUsr() const { return SuperclassUsr; }
+
+  Optional<SDKNodeTypeDecl*> getSuperclass() const {
+    if (SuperclassUsr.empty())
+      return None;
+    return (*getRootNode()->getDescendantByUsr(SuperclassUsr))->
+      getAs<SDKNodeTypeDecl>();
+  }
+
+  /// Finding the node through all children, including the inheritted ones,
+  /// whose printed name matches with the given name.
+  Optional<SDKNodeDecl*> lookupChildByPrintedName(StringRef Name) const {
+    for (auto C : getChildren()) {
+      if (C->getPrintedName() == Name)
+        return C->getAs<SDKNodeDecl>();
+    }
+    // Finding from the inheritance chain.
+    if (auto Super = getSuperclass()) {
+      return (*Super)->lookupChildByPrintedName(Name);
+    }
+    return None;
+  }
 };
 
 class SDKNodeTypeAlias : public SDKNodeDecl {
@@ -828,6 +887,9 @@
     case KeyKind::KK_moduleName:
       Info.ModuleName = GetScalarString(Pair.getValue());
       break;
+    case KeyKind::KK_superclassUsr:
+      Info.SuperclassUsr = GetScalarString(Pair.getValue());
+      break;
     case KeyKind::KK_throwing:
       Info.IsThrowing = true;
       break;
@@ -1092,6 +1154,12 @@
     IsThrowing(isFuncThrowing(VD)), IsMutating(isFuncMutating(VD)),
     IsStatic(VD->isStatic()), SelfIndex(getSelfIndex(VD)),
     Ownership(getOwnership(VD)) {
+
+  // Calculate usr for its super class.
+  if (auto *CD = dyn_cast_or_null<ClassDecl>(VD)) {
+    if (auto *Super = CD->getSuperclassDecl())
+      SuperclassUsr = calculateUsr(Ctx, Super);
+  }
   if (VD->getAttrs().getDeprecated(VD->getASTContext()))
     DeclAttrs.push_back(SDKDeclAttrKind::DAK_deprecated);
 }
@@ -1441,6 +1509,13 @@
                               Index);
             }
           }
+          if (auto *TD = dyn_cast<SDKNodeTypeDecl>(value)) {
+            auto Super = TD->getSuperClassUsr();
+            if (!Super.empty()) {
+              out.mapRequired(getKeyContent(Ctx, KeyKind::KK_superclassUsr).data(),
+                              Super);
+            }
+          }
           auto Attributes = D->getDeclAttributes();
           if (!Attributes.empty())
             out.mapRequired(getKeyContent(Ctx, KeyKind::KK_declAttributes).data(),
@@ -2666,7 +2741,8 @@
 SDKNodeDecl *DiagnosisEmitter::findAddedDecl(const SDKNodeDecl *Root) {
   for (auto *Added : AddedDecls) {
     if (Root->getKind() == Added->getKind() &&
-        Root->getPrintedName() == Added->getPrintedName())
+        Root->getPrintedName() == Added->getPrintedName() &&
+        Root->getUsr() == Added->getUsr())
       return Added;
   }
   return nullptr;
@@ -2776,6 +2852,22 @@
         return;
       }
     }
+
+    // We should exlude those declarations that are pulled up to the super classes.
+    bool FoundInSuperclass = false;
+    if (auto PD = dyn_cast<SDKNodeDecl>(Node->getParent())) {
+      if (PD->isAnnotatedAs(NodeAnnotation::Updated)) {
+        // Get the updated counterpart of the parent decl.
+        if (auto RTD = dyn_cast<SDKNodeTypeDecl>(UpdateMap.
+            findUpdateCounterpart(PD))) {
+          // Look up by the printed name in the counterpart.
+          FoundInSuperclass =
+            RTD->lookupChildByPrintedName(Node->getPrintedName()).hasValue();
+        }
+      }
+    }
+    if (FoundInSuperclass)
+      return;
     RemovedDecls.Diags.emplace_back(Node->getDeclKind(),
                                     Node->getFullyQualifiedName(),
                                     Node->isDeprecated());
diff --git a/unittests/runtime/Exclusivity.cpp b/unittests/runtime/Exclusivity.cpp
index ab0e874..35a34fe 100644
--- a/unittests/runtime/Exclusivity.cpp
+++ b/unittests/runtime/Exclusivity.cpp
@@ -16,7 +16,7 @@
 
 using namespace swift;
 
-TEST(TextExclusivity, testNullPC) {
+TEST(TestExclusivity, testNullPC) {
   ValueBuffer scratch, scratch2;
   long var;
   swift_beginAccess(&var, &scratch,
@@ -29,7 +29,7 @@
   swift_endAccess(&scratch);
 }
 
-TEST(TextExclusivity, testPCOne) {
+TEST(TestExclusivity, testPCOne) {
   ValueBuffer scratch, scratch2;
   long var;
   swift_beginAccess(&var, &scratch,
@@ -42,7 +42,7 @@
   swift_endAccess(&scratch);
 }
 
-TEST(TextExclusivity, testBogusPC) {
+TEST(TestExclusivity, testBogusPC) {
   ValueBuffer scratch, scratch2;
   long var;
   swift_beginAccess(&var, &scratch,
@@ -54,3 +54,34 @@
   swift_endAccess(&scratch2);
   swift_endAccess(&scratch);
 }
+
+// rdar://32866493
+TEST(TestExclusivity, testNonNested) {
+  const int N = 5;
+  ValueBuffer scratches[N];
+  long vars[N];
+
+  auto begin = [&](unsigned i) {
+    assert(i < N);
+    swift_beginAccess(&vars[i], &scratches[i], ExclusivityFlags::Modify, 0);
+  };
+  auto end = [&](unsigned i) {
+    assert(i < N);
+    swift_endAccess(&scratches[i]);
+    memset(&scratches[i], /*gibberish*/ 0x99, sizeof(ValueBuffer));
+  };
+  auto accessAll = [&] {
+    for (unsigned i = 0; i != N; ++i) begin(i);
+    for (unsigned i = 0; i != N; ++i) end(i);
+  };
+
+  accessAll();
+  begin(0); begin(1); end(0); end(1);
+  begin(0); begin(1); end(0); end(1);
+  accessAll();
+  begin(1); begin(0); begin(2); end(0); end(2); end(1);
+  accessAll();
+  begin(0); begin(1); begin(2); begin(3); begin(4);
+  end(1); end(4); end(0); end(2); end(3);
+  accessAll();
+}
diff --git a/utils/build-presets.ini b/utils/build-presets.ini
index 3ac8253..cca771d 100644
--- a/utils/build-presets.ini
+++ b/utils/build-presets.ini
@@ -898,6 +898,18 @@
 
 enable-asan
 
+[preset: buildbot_incremental_linux,lsan]
+build-subdir=buildbot_incremental_lsan
+
+release-debuginfo
+assertions
+enable-lsan
+
+dash-dash
+
+build-ninja
+reconfigure
+
 #===------------------------------------------------------------------------===#
 # OS X Package Builders
 #===------------------------------------------------------------------------===#
diff --git a/utils/build-script b/utils/build-script
index 4cad01b..98c7559 100755
--- a/utils/build-script
+++ b/utils/build-script
@@ -682,6 +682,14 @@
         # NOT pass them to build-script-impl.
         if args.enable_asan:
             impl_args += ["--enable-asan"]
+        # If we have lsan, we need to export our suppression list. The actual
+        # passing in of the LSAN flag is done via the normal cmake method. We
+        # do not pass the flag to build-script-impl.
+        if args.enable_lsan:
+            supp_file = os.path.join(SWIFT_SOURCE_ROOT, SWIFT_REPO_NAME,
+                                     "utils",
+                                     "lsan_leaks_suppression_list.txt")
+            os.environ['LSAN_OPTIONS'] = 'suppressions={}'.format(supp_file)
         if args.verbose_build:
             impl_args += ["--verbose-build"]
         if args.install_symroot:
@@ -2018,6 +2026,10 @@
     parser.add_argument(
         "--enable-tsan-runtime",
         help="enable Thread Sanitizer on the swift runtime")
+    parser.add_argument(
+        "--enable-lsan",
+        help="enable Leak Sanitizer for swift tools",
+        action=arguments.action.optional_bool)
 
     parser.add_argument(
         "--compiler-vendor",
diff --git a/utils/build-script-impl b/utils/build-script-impl
index d08bba0..5d42f82 100755
--- a/utils/build-script-impl
+++ b/utils/build-script-impl
@@ -3201,7 +3201,7 @@
             # Copy executables and shared libraries from the `host_install_destdir` to
             # INSTALL_SYMROOT and run dsymutil on them.
             (cd "${host_install_destdir}" &&
-             find ./"${TOOLCHAIN_PREFIX}" -perm -0111 -type f -print | cpio -pdm "${INSTALL_SYMROOT}")
+             find ./"${TOOLCHAIN_PREFIX}" -perm -0111 -type f -print | cpio --insecure -pdm "${INSTALL_SYMROOT}")
 
             # Run dsymutil on executables and shared libraries.
             #
diff --git a/utils/chex.py b/utils/chex.py
new file mode 100755
index 0000000..e84b1fa
--- /dev/null
+++ b/utils/chex.py
@@ -0,0 +1,31 @@
+#!/usr/bin/env python
+# Check HEX -- a stupid filter that allows hexadecimal literals to be checked
+# for in LLVM IR FileCheck tests. It works by replacing occurrences of
+# strings matching the regex /< (i[0-9]+) \s+ (0x[0-9A-Fa-f]+) >/x with the
+# decimal literal equivalent that would really appear in printed LLVM IR.
+
+from __future__ import print_function
+
+import re
+import sys
+
+hex = re.compile(r"""<(i([0-9]+)\s+)0x([0-9A-Fa-f_]+)>""")
+
+
+def hexReplace(match):
+    # Integer type is match group 1
+    ty = match.group(1)
+    # Integer bit width is match group 2
+    bits = int(match.group(2))
+    # Hex value is match group 3
+    value = int(match.group(3).replace("_", ""), base=16)
+    # LLVM prints the decimal value as if it's two's-complement signed in
+    # the given bitwidth, so the printed value will be negative if
+    # greater than 2^(bits - 1)
+    if value >= (1 << (bits - 1)):
+        value -= 1 << bits
+    return ty + str(value)
+
+
+for line in sys.stdin:
+    print(re.sub(hex, hexReplace, line), end="")
diff --git a/utils/lsan_leaks_suppression_list.txt b/utils/lsan_leaks_suppression_list.txt
new file mode 100644
index 0000000..24dd6b9
--- /dev/null
+++ b/utils/lsan_leaks_suppression_list.txt
@@ -0,0 +1,2 @@
+leak:*buildCompilation*
+leak:*llvm::TableGenMain*
diff --git a/utils/swift_build_support/swift_build_support/cmake.py b/utils/swift_build_support/swift_build_support/cmake.py
index 43d6f14..78359cd 100644
--- a/utils/swift_build_support/swift_build_support/cmake.py
+++ b/utils/swift_build_support/swift_build_support/cmake.py
@@ -92,6 +92,8 @@
             sanitizers.append('Undefined')
         if args.enable_tsan:
             sanitizers.append('Thread')
+        if args.enable_lsan:
+            sanitizers.append('Leaks')
         if sanitizers:
             define("LLVM_USE_SANITIZER", ";".join(sanitizers))
 
diff --git a/utils/swift_build_support/tests/test_cmake.py b/utils/swift_build_support/tests/test_cmake.py
index 65b5d20..eb8a41d 100644
--- a/utils/swift_build_support/tests/test_cmake.py
+++ b/utils/swift_build_support/tests/test_cmake.py
@@ -33,6 +33,7 @@
                          enable_asan=False,
                          enable_ubsan=False,
                          enable_tsan=False,
+                         enable_lsan=False,
                          export_compile_commands=False,
                          distcc=False,
                          cmake_generator="Ninja",
@@ -148,6 +149,18 @@
              "-DCMAKE_CXX_COMPILER:PATH=/path/to/clang++",
              "-DCMAKE_MAKE_PROGRAM=" + self.which_ninja(args)])
 
+    def test_common_options_lsan(self):
+        args = self.default_args()
+        args.enable_lsan = True
+        cmake = self.cmake(args)
+        self.assertEqual(
+            list(cmake.common_options()),
+            ["-G", "Ninja",
+             "-DLLVM_USE_SANITIZER=Leaks",
+             "-DCMAKE_C_COMPILER:PATH=/path/to/clang",
+             "-DCMAKE_CXX_COMPILER:PATH=/path/to/clang++",
+             "-DCMAKE_MAKE_PROGRAM=" + self.which_ninja(args)])
+
     def test_common_options_export_compile_commands(self):
         args = self.default_args()
         args.export_compile_commands = True
diff --git a/validation-test/compiler_crashers/28790-conformance-getwitness-requirement-nullptr-getdecl-already-have-a-non-optional-w.swift b/validation-test/compiler_crashers/28790-conformance-getwitness-requirement-nullptr-getdecl-already-have-a-non-optional-w.swift
new file mode 100644
index 0000000..ebd0f1a
--- /dev/null
+++ b/validation-test/compiler_crashers/28790-conformance-getwitness-requirement-nullptr-getdecl-already-have-a-non-optional-w.swift
@@ -0,0 +1,10 @@
+// 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
+
+// REQUIRES: asserts
+// RUN: not --crash %target-swift-frontend %s -emit-ir
+class a:P{class a{}{}func a:a{}func a{}}@objc protocol P{{}func a
diff --git a/validation-test/compiler_crashers/28791-formprotocolrelativetype-swift-protocoldecl-swift-genericsignaturebuilder-potent.swift b/validation-test/compiler_crashers/28791-formprotocolrelativetype-swift-protocoldecl-swift-genericsignaturebuilder-potent.swift
new file mode 100644
index 0000000..5265b58
--- /dev/null
+++ b/validation-test/compiler_crashers/28791-formprotocolrelativetype-swift-protocoldecl-swift-genericsignaturebuilder-potent.swift
@@ -0,0 +1,9 @@
+// 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
+
+// RUN: not --crash %target-swift-frontend %s -emit-ir
+extension CountableRange{class a{protocol P{protocol P{}typealias e:P
diff --git a/validation-test/compiler_crashers/28792-conforms-equivclass-conformsto-end.swift b/validation-test/compiler_crashers/28792-conforms-equivclass-conformsto-end.swift
new file mode 100644
index 0000000..f38207e
--- /dev/null
+++ b/validation-test/compiler_crashers/28792-conforms-equivclass-conformsto-end.swift
@@ -0,0 +1,10 @@
+// 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
+
+// REQUIRES: asserts
+// RUN: not --crash %target-swift-frontend %s -emit-ir
+protocol A:A{struct B{{}var a{class a{class ss:a
diff --git a/validation-test/compiler_crashers/28793-nestedpabyname-didnt-find-the-associated-type-we-wanted.swift b/validation-test/compiler_crashers/28793-nestedpabyname-didnt-find-the-associated-type-we-wanted.swift
new file mode 100644
index 0000000..4e36f16
--- /dev/null
+++ b/validation-test/compiler_crashers/28793-nestedpabyname-didnt-find-the-associated-type-we-wanted.swift
@@ -0,0 +1,13 @@
+// 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
+
+// REQUIRES: asserts
+// RUN: not --crash %target-swift-frontend %s -emit-ir
+protocol A:RangeReplaceableCollection
+protocol P{
+protocol A
+class a:A{}typealias a:A{}typealias a:RangeReplaceableCollection
diff --git a/validation-test/compiler_crashers/28794-swift-type-transformrec-llvm-function-ref-llvm-optional-swift-type-swift-typebas.swift b/validation-test/compiler_crashers/28794-swift-type-transformrec-llvm-function-ref-llvm-optional-swift-type-swift-typebas.swift
new file mode 100644
index 0000000..aaa020a
--- /dev/null
+++ b/validation-test/compiler_crashers/28794-swift-type-transformrec-llvm-function-ref-llvm-optional-swift-type-swift-typebas.swift
@@ -0,0 +1,9 @@
+// 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
+
+// RUN: not --crash %target-swift-frontend %s -emit-ir
+class a<a:{a {}extension{P{}protocol A:a{P{}var f
diff --git a/validation-test/compiler_crashers/28795-inprotocol-isrequirementsignaturecomputed-missing-signature.swift b/validation-test/compiler_crashers/28795-inprotocol-isrequirementsignaturecomputed-missing-signature.swift
new file mode 100644
index 0000000..5cf18bd
--- /dev/null
+++ b/validation-test/compiler_crashers/28795-inprotocol-isrequirementsignaturecomputed-missing-signature.swift
@@ -0,0 +1,11 @@
+// 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
+
+// REQUIRES: asserts
+// RUN: not --crash %target-swift-frontend %s -emit-ir
+protocol A:A.b{func 丏
+protocol b:Collection
diff --git a/validation-test/compiler_crashers/28796-result-second.swift b/validation-test/compiler_crashers/28796-result-second.swift
new file mode 100644
index 0000000..5815439
--- /dev/null
+++ b/validation-test/compiler_crashers/28796-result-second.swift
@@ -0,0 +1,10 @@
+// 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
+
+// REQUIRES: asserts
+// RUN: not --crash %target-swift-frontend %s -emit-ir
+class a<a{{{}}func b{extension{class a<a{{}class a:RangeReplaceableCollection
diff --git a/validation-test/compiler_crashers/28797-declbits-beingvalidated-ibv.swift b/validation-test/compiler_crashers/28797-declbits-beingvalidated-ibv.swift
new file mode 100644
index 0000000..b360a59
--- /dev/null
+++ b/validation-test/compiler_crashers/28797-declbits-beingvalidated-ibv.swift
@@ -0,0 +1,11 @@
+// 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
+
+// REQUIRES: asserts
+// RUN: not --crash %target-swift-frontend %s -emit-ir
+{typealias e:P.a
+protocol P{typealias a=a.b:class a
diff --git a/validation-test/compiler_crashers/28798-swift-genericenvironment-queryinterfacetypesubstitutions-operator-swift-substitu.swift b/validation-test/compiler_crashers/28798-swift-genericenvironment-queryinterfacetypesubstitutions-operator-swift-substitu.swift
new file mode 100644
index 0000000..bda23c2
--- /dev/null
+++ b/validation-test/compiler_crashers/28798-swift-genericenvironment-queryinterfacetypesubstitutions-operator-swift-substitu.swift
@@ -0,0 +1,9 @@
+// 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
+
+// RUN: not --crash %target-swift-frontend %s -emit-ir
+protocol P}{{{<(}}}{}extension P{class a{func<(t:a
diff --git a/validation-test/compiler_crashers/28799-swift-type-subst-swift-substitutionmap-const-swift-substoptions-const.swift b/validation-test/compiler_crashers/28799-swift-type-subst-swift-substitutionmap-const-swift-substoptions-const.swift
new file mode 100644
index 0000000..2ce97d5
--- /dev/null
+++ b/validation-test/compiler_crashers/28799-swift-type-subst-swift-substitutionmap-const-swift-substoptions-const.swift
@@ -0,0 +1,9 @@
+// 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
+
+// RUN: not --crash %target-swift-frontend %s -emit-ir
+protocol P{{}typealias e where f:A:protocol A:A}protocol A:P