Merge pull request #21885 from drodriguez/aapcs64-valist-5

[stdlib][SR-2239][5.0] Implement AAPCS64 variable argument list support.
diff --git a/cmake/modules/StandaloneOverlay.cmake b/cmake/modules/StandaloneOverlay.cmake
index 98f55ef..b12dec1 100644
--- a/cmake/modules/StandaloneOverlay.cmake
+++ b/cmake/modules/StandaloneOverlay.cmake
@@ -60,7 +60,7 @@
 
 # Some overlays include the runtime's headers,
 # and some of those headers are generated at build time.
-add_subdirectory("${SWIFT_SOURCE_DIR}/include" "swift/include")
+add_subdirectory("${SWIFT_SOURCE_DIR}/include" "${SWIFT_SOURCE_DIR}/include")
 
 # Without this line, installing components is broken. This needs refactoring.
 swift_configure_components()
diff --git a/include/swift/ABI/Metadata.h b/include/swift/ABI/Metadata.h
index dc59061..34c2994 100644
--- a/include/swift/ABI/Metadata.h
+++ b/include/swift/ABI/Metadata.h
@@ -2808,21 +2808,79 @@
 using ExtensionContextDescriptor = TargetExtensionContextDescriptor<InProcess>;
 
 template<typename Runtime>
+struct TargetMangledContextName {
+  /// The mangled name of the context.
+  TargetRelativeDirectPointer<Runtime, const char, /*nullable*/ false> name;
+};
+
+template<typename Runtime>
 struct TargetAnonymousContextDescriptor final
     : TargetContextDescriptor<Runtime>,
-      TrailingGenericContextObjects<TargetAnonymousContextDescriptor<Runtime>>
+      TrailingGenericContextObjects<TargetAnonymousContextDescriptor<Runtime>,
+                                    TargetGenericContextDescriptorHeader,
+                                    TargetMangledContextName<Runtime>>
 {
 private:
   using TrailingGenericContextObjects
-    = TrailingGenericContextObjects<TargetAnonymousContextDescriptor<Runtime>>;
+    = TrailingGenericContextObjects<TargetAnonymousContextDescriptor<Runtime>,
+                                    TargetGenericContextDescriptorHeader,
+                                    TargetMangledContextName<Runtime>>;
+  using TrailingObjects =
+    typename TrailingGenericContextObjects::TrailingObjects;
+  friend TrailingObjects;
 
 public:
-  using TrailingGenericContextObjects::getGenericContext;
+  using MangledContextName = TargetMangledContextName<Runtime>;
 
+  using TrailingGenericContextObjects::getGenericContext;
+  using TrailingGenericContextObjects::getGenericContextHeader;
+  using TrailingGenericContextObjects::getFullGenericContextHeader;
+  using TrailingGenericContextObjects::getGenericParams;
+
+  AnonymousContextDescriptorFlags getAnonymousContextDescriptorFlags() const {
+    return AnonymousContextDescriptorFlags(this->Flags.getKindSpecificFlags());
+  }
+
+  /// Whether this anonymous context descriptor contains a full mangled name,
+  /// which can be used to match the anonymous type to its textual form.
+  bool hasMangledName() const {
+    return getAnonymousContextDescriptorFlags().hasMangledName();
+  }
+
+  /// Retrieve the mangled name of this context, or NULL if it was not
+  /// recorded in the metadata.
+  ConstTargetPointer<Runtime, char> getMangledName() const {
+    if (!hasMangledName())
+      return ConstTargetPointer<Runtime, char>();
+
+    return this->template getTrailingObjects<MangledContextName>()->name;
+  }
+
+  /// Retrieve a pointer to the mangled context name structure.
+  const MangledContextName *getMangledContextName() const {
+    if (!hasMangledName())
+      return nullptr;
+
+    return this->template getTrailingObjects<MangledContextName>();
+  }
+
+private:
+  template<typename T>
+  using OverloadToken =
+    typename TrailingGenericContextObjects::template OverloadToken<T>;
+
+  using TrailingGenericContextObjects::numTrailingObjects;
+
+  size_t numTrailingObjects(OverloadToken<MangledContextName>) const {
+    return this->hasMangledNam() ? 1 : 0;
+  }
+
+public:
   static bool classof(const TargetContextDescriptor<Runtime> *cd) {
     return cd->getKind() == ContextDescriptorKind::Anonymous;
   }
 };
+using AnonymousContextDescriptor = TargetAnonymousContextDescriptor<InProcess>;
 
 /// A protocol descriptor.
 ///
diff --git a/include/swift/ABI/MetadataValues.h b/include/swift/ABI/MetadataValues.h
index bf2ce18..f6c5497 100644
--- a/include/swift/ABI/MetadataValues.h
+++ b/include/swift/ABI/MetadataValues.h
@@ -1344,6 +1344,23 @@
                                  setSpecialProtocol)
 };
 
+/// Flags for anonymous type context descriptors. These values are used as the
+/// kindSpecificFlags of the ContextDescriptorFlags for the anonymous context.
+class AnonymousContextDescriptorFlags : public FlagSet<uint16_t> {
+  enum {
+    /// Whether this anonymous context descriptor is followed by its
+    /// mangled name, which can be used to match the descriptor at runtime.
+    HasMangledName = 0,
+  };
+
+public:
+  explicit AnonymousContextDescriptorFlags(uint16_t bits) : FlagSet(bits) {}
+  constexpr AnonymousContextDescriptorFlags() {}
+
+  FLAGSET_DEFINE_FLAG_ACCESSORS(HasMangledName, hasMangledName,
+                                setHasMangledName)
+};
+
 enum class GenericParamKind : uint8_t {
   /// A type parameter.
   Type = 0,
diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h
index f8e96a1..f1df095 100644
--- a/include/swift/AST/Decl.h
+++ b/include/swift/AST/Decl.h
@@ -488,7 +488,7 @@
     HasLazyConformances : 1
   );
 
-  SWIFT_INLINE_BITFIELD_FULL(ProtocolDecl, NominalTypeDecl, 1+1+1+1+1+1+1+2+8+16,
+  SWIFT_INLINE_BITFIELD_FULL(ProtocolDecl, NominalTypeDecl, 1+1+1+1+1+1+1+2+1+8+16,
     /// Whether the \c RequiresClass bit is valid.
     RequiresClassValid : 1,
 
@@ -514,6 +514,9 @@
     /// The stage of the circularity check for this protocol.
     Circularity : 2,
 
+    /// Whether we've computed the inherited protocols list yet.
+    InheritedProtocolsValid : 1,
+
     : NumPadBits,
 
     /// If this is a compiler-known protocol, this will be a KnownProtocolKind
@@ -3569,11 +3572,16 @@
   void createObjCMethodLookup();
 
   struct {
+    /// The superclass decl and a bit to indicate whether the
+    /// superclass was computed yet or not.
+    llvm::PointerIntPair<ClassDecl *, 1, bool> SuperclassDecl;
+
     /// The superclass type and a bit to indicate whether the
     /// superclass was computed yet or not.
-    llvm::PointerIntPair<Type, 1, bool> Superclass;
+    llvm::PointerIntPair<Type, 1, bool> SuperclassType;
   } LazySemanticInfo;
 
+  friend class SuperclassDeclRequest;
   friend class SuperclassTypeRequest;
   friend class TypeChecker;
 
@@ -3887,6 +3895,18 @@
 class ProtocolDecl final : public NominalTypeDecl {
   SourceLoc ProtocolLoc;
 
+  ArrayRef<ProtocolDecl *> InheritedProtocols;
+
+  struct {
+    /// The superclass decl and a bit to indicate whether the
+    /// superclass was computed yet or not.
+    llvm::PointerIntPair<ClassDecl *, 1, bool> SuperclassDecl;
+
+    /// The superclass type and a bit to indicate whether the
+    /// superclass was computed yet or not.
+    llvm::PointerIntPair<Type, 1, bool> SuperclassType;
+  } LazySemanticInfo;
+
   /// The generic signature representing exactly the new requirements introduced
   /// by this protocol.
   const Requirement *RequirementSignature = nullptr;
@@ -3897,12 +3917,9 @@
 
   bool existentialTypeSupportedSlow(LazyResolver *resolver);
 
-  struct {
-    /// The superclass type and a bit to indicate whether the
-    /// superclass was computed yet or not.
-    llvm::PointerIntPair<Type, 1, bool> Superclass;
-  } LazySemanticInfo;
+  ArrayRef<ProtocolDecl *> getInheritedProtocolsSlow();
 
+  friend class SuperclassDeclRequest;
   friend class SuperclassTypeRequest;
   friend class TypeChecker;
 
@@ -3914,7 +3931,12 @@
   using Decl::getASTContext;
 
   /// Retrieve the set of protocols inherited from this protocol.
-  llvm::TinyPtrVector<ProtocolDecl *> getInheritedProtocols() const;
+  ArrayRef<ProtocolDecl *> getInheritedProtocols() const {
+    if (Bits.ProtocolDecl.InheritedProtocolsValid)
+      return InheritedProtocols;
+
+    return const_cast<ProtocolDecl *>(this)->getInheritedProtocolsSlow();
+  }
 
   /// Determine whether this protocol has a superclass.
   bool hasSuperclass() const { return (bool)getSuperclassDecl(); }
diff --git a/include/swift/AST/IRGenOptions.h b/include/swift/AST/IRGenOptions.h
index 3fd4d44..1ca21db 100644
--- a/include/swift/AST/IRGenOptions.h
+++ b/include/swift/AST/IRGenOptions.h
@@ -165,6 +165,9 @@
   /// Emit names of struct stored properties and enum cases.
   unsigned EnableReflectionNames : 1;
 
+  /// Emit mangled names of anonymous context descriptors.
+  unsigned EnableAnonymousContextMangledNames : 1;
+
   /// Enables resilient class layout.
   unsigned EnableClassResilience : 1;
 
@@ -224,7 +227,8 @@
         EmitStackPromotionChecks(false), PrintInlineTree(false),
         EmbedMode(IRGenEmbedMode::None), HasValueNamesSetting(false),
         ValueNames(false), EnableReflectionMetadata(true),
-        EnableReflectionNames(true), EnableClassResilience(false),
+        EnableReflectionNames(true), EnableAnonymousContextMangledNames(false),
+        EnableClassResilience(false),
         EnableResilienceBypass(false), LazyInitializeClassMetadata(false),
         UseIncrementalLLVMCodeGen(true), UseSwiftCall(false),
         GenerateProfile(false), EnableDynamicReplacementChaining(false),
diff --git a/include/swift/AST/NameLookupRequests.h b/include/swift/AST/NameLookupRequests.h
index 7f73230..5f7177a 100644
--- a/include/swift/AST/NameLookupRequests.h
+++ b/include/swift/AST/NameLookupRequests.h
@@ -133,7 +133,7 @@
 /// Request the superclass declaration for the given class.
 class SuperclassDeclRequest :
     public SimpleRequest<SuperclassDeclRequest,
-                         CacheKind::Uncached, // FIXME: Cache these
+                         CacheKind::SeparatelyCached,
                          ClassDecl *,
                          NominalTypeDecl *> {
 public:
@@ -149,6 +149,8 @@
 public:
   // Caching
   bool isCached() const { return true; }
+  Optional<ClassDecl *> getCachedResult() const;
+  void cacheResult(ClassDecl *value) const;
 
   // Cycle handling
   void diagnoseCycle(DiagnosticEngine &diags) const;
diff --git a/include/swift/AST/SearchPathOptions.h b/include/swift/AST/SearchPathOptions.h
index 4cc5c0b..e992af4 100644
--- a/include/swift/AST/SearchPathOptions.h
+++ b/include/swift/AST/SearchPathOptions.h
@@ -72,6 +72,9 @@
 
   /// Don't look in for compiler-provided modules.
   bool SkipRuntimeLibraryImportPath = false;
+  
+  /// Whether the runtime library path is set to the compiler-relative default.
+  bool RuntimeLibraryPathIsDefault = true;
 
   /// Return a hash code of any components from these options that should
   /// contribute to a Swift Bridging PCH hash.
diff --git a/include/swift/Frontend/Frontend.h b/include/swift/Frontend/Frontend.h
index eb9e2ca..c779aeb 100644
--- a/include/swift/Frontend/Frontend.h
+++ b/include/swift/Frontend/Frontend.h
@@ -182,7 +182,7 @@
 
   void setMainExecutablePath(StringRef Path);
 
-  void setRuntimeResourcePath(StringRef Path);
+  void setRuntimeResourcePath(StringRef Path, bool IsDefault = false);
 
   void setSDKPath(const std::string &Path) {
     SearchPathOpts.SDKPath = Path;
diff --git a/include/swift/Option/FrontendOptions.td b/include/swift/Option/FrontendOptions.td
index b902c40..68d3637 100644
--- a/include/swift/Option/FrontendOptions.td
+++ b/include/swift/Option/FrontendOptions.td
@@ -272,6 +272,10 @@
 def enable_llvm_value_names : Flag<["-"], "enable-llvm-value-names">,
   HelpText<"Add names to local values in LLVM IR">;
 
+def enable_anonymous_context_mangled_names :
+  Flag<["-"], "enable-anonymous-context-mangled-names">,
+  HelpText<"Enable emission of mangled names in anonymous context descriptors">;
+
 def disable_reflection_metadata : Flag<["-"], "disable-reflection-metadata">,
   HelpText<"Disable emission of reflection metadata for nominal types">;
 
diff --git a/include/swift/Remote/MetadataReader.h b/include/swift/Remote/MetadataReader.h
index c8d9eb2..3f83919 100644
--- a/include/swift/Remote/MetadataReader.h
+++ b/include/swift/Remote/MetadataReader.h
@@ -594,8 +594,8 @@
         return BuiltType();
 
       // Build the demangling tree from the context tree.
-      Demangle::NodeFactory nodeFactory;
-      auto node = buildContextMangling(descriptor, nodeFactory);
+      Demangler dem;
+      auto node = buildContextMangling(descriptor, dem);
       if (!node || node->getKind() != Node::Kind::Type)
         return BuiltType();
 
@@ -1113,7 +1113,7 @@
       case MetadataKind::Tuple: {
         auto numElementsAddress = address +
           TargetTupleTypeMetadata<Runtime>::getOffsetToNumElements();
-        uint32_t numElements;
+        StoredSize numElements;
         if (!Reader->readInteger(RemoteAddress(numElementsAddress),
                                  &numElements))
           return nullptr;
@@ -1203,7 +1203,7 @@
     }
   }
 
-  /// Given the address of a nominal type descriptor, attempt to read it.
+  /// Given the address of a context descriptor, attempt to read it.
   ContextDescriptorRef
   readContextDescriptor(StoredPointer address) {
     if (address == 0)
@@ -1248,6 +1248,10 @@
       break;
     case ContextDescriptorKind::Anonymous:
       baseSize = sizeof(TargetAnonymousContextDescriptor<Runtime>);
+      if (AnonymousContextDescriptorFlags(flags.getKindSpecificFlags())
+            .hasMangledName()) {
+        baseSize += sizeof(TargetMangledContextName<Runtime>);
+      }
       break;
     case ContextDescriptorKind::Class:
       baseSize = sizeof(TargetClassDescriptor<Runtime>);
@@ -1352,12 +1356,162 @@
     return false;
   }
 
+  /// Read the name from a module, type, or protocol context descriptor.
+  Optional<std::string> readContextDescriptorName(
+      ContextDescriptorRef descriptor,
+      Optional<TypeImportInfo<std::string>> &importInfo) {
+    std::string name;
+    auto context = descriptor.getLocalBuffer();
+
+    // Read the name of a protocol.
+    if (auto protoBuffer =
+            dyn_cast<TargetProtocolDescriptor<Runtime>>(context)) {
+      auto nameAddress = resolveRelativeField(descriptor, protoBuffer->Name);
+      if (Reader->readString(RemoteAddress(nameAddress), name))
+        return name;
+
+      return None;
+    }
+
+    // Read the name of a module.
+    if (auto moduleBuffer =
+            dyn_cast<TargetModuleContextDescriptor<Runtime>>(context)) {
+      auto nameAddress = resolveRelativeField(descriptor, moduleBuffer->Name);
+      if (Reader->readString(RemoteAddress(nameAddress), name))
+        return name;
+
+      return None;
+    }
+
+    // Only type contexts remain.
+    auto typeBuffer = dyn_cast<TargetTypeContextDescriptor<Runtime>>(context);
+    if (!typeBuffer)
+      return None;
+
+    auto nameAddress = resolveRelativeField(descriptor, typeBuffer->Name);
+    if (!Reader->readString(RemoteAddress(nameAddress), name))
+      return None;
+
+    // Read the TypeImportInfo if present.
+    if (typeBuffer->getTypeContextDescriptorFlags().hasImportInfo()) {
+      importInfo.emplace();
+      nameAddress += name.size() + 1;
+
+      while (true) {
+        // Read the next string.
+        std::string temp;
+        if (!Reader->readString(RemoteAddress(nameAddress), temp))
+          return None;
+
+        // If we read an empty string, we're done.
+        if (temp.empty())
+          break;
+
+        // Advance past the string.
+        nameAddress += temp.size() + 1;
+
+        // Collect the import information.  Ignore anything we don't
+        // understand.
+        importInfo->collect</*asserting*/false>(std::move(temp));
+      }
+
+      // Ignore the original if we have an ABI name override.
+      if (!importInfo->ABIName.empty())
+        name = std::move(importInfo->ABIName);
+    }
+
+    return name;
+  }
+
+  /// If we have a context whose parent context is an anonymous context
+  /// that provides the local/private name for the current context,
+  /// produce a mangled node describing the name of \c context.
+  Demangle::NodePointer
+  adoptAnonymousContextName(ContextDescriptorRef contextRef,
+                            Optional<ContextDescriptorRef> &parentContextRef,
+                            Demangler &dem) {
+    if (!parentContextRef || !*parentContextRef)
+      return nullptr;
+
+    auto context = contextRef.getLocalBuffer();
+    auto typeContext = dyn_cast<TargetTypeContextDescriptor<Runtime>>(context);
+    auto protoContext = dyn_cast<TargetProtocolDescriptor<Runtime>>(context);
+    if (!typeContext && !protoContext)
+      return nullptr;
+
+    auto anonymousParent = dyn_cast_or_null<TargetAnonymousContextDescriptor<Runtime>>(
+            parentContextRef->getLocalBuffer());
+    if (!anonymousParent)
+      return nullptr;
+
+    // Only perform this transformation when we have a mangled name describing
+    // the context.
+    if (!anonymousParent->hasMangledName())
+      return nullptr;
+
+    // Read the mangled name.
+    auto mangledContextName = anonymousParent->getMangledContextName();
+    auto mangledNameAddress = resolveRelativeField(*parentContextRef,
+                                                   mangledContextName->name);
+
+    std::string mangledName;
+    if (!Reader->readString(RemoteAddress(mangledNameAddress), mangledName))
+      return nullptr;
+
+    auto mangledNode = dem.demangleSymbol(mangledName);
+    if (!mangledNode)
+      return nullptr;
+
+    if (mangledNode->getKind() == Demangle::Node::Kind::Global)
+      mangledNode = mangledNode->getFirstChild();
+
+    if (mangledNode->getNumChildren() < 2)
+      return nullptr;
+
+    // Dig out the name of the entity.
+    // FIXME: LocalDeclName
+    swift::Demangle::NodePointer nameChild = mangledNode->getChild(1);
+    if (nameChild->getKind() != Node::Kind::PrivateDeclName ||
+        nameChild->getNumChildren() < 2)
+      return nullptr;
+
+    // Make sure we have an identifier where we expect it.
+    auto identifierNode = nameChild->getChild(1);
+    if (identifierNode->getKind() != Node::Kind::Identifier ||
+        !identifierNode->hasText())
+      return nullptr;
+
+    // Read the name of the current context.
+    Optional<TypeImportInfo<std::string>> importInfo;
+    auto contextName = readContextDescriptorName(contextRef, importInfo);
+    if (!contextName)
+      return nullptr;
+
+    // Make sure the name of the current context matches the one in the mangled
+    // name of the parent anonymous context.
+    // FIXME: Use the ABI name here.
+    if (*contextName != identifierNode->getText())
+      return nullptr;
+
+    // We have a match. Update the parent context to skip the anonymous
+    // context entirely.
+    parentContextRef = readParentContextDescriptor(*parentContextRef);
+
+    // Return the name.
+    return nameChild;
+  }
+
   Demangle::NodePointer
   buildContextDescriptorMangling(ContextDescriptorRef descriptor,
-                                 Demangle::NodeFactory &nodeFactory) {
+                                 Demangler &dem) {
     // Read the parent descriptor.
     auto parentDescriptorResult = readParentContextDescriptor(descriptor);
 
+    // If the parent is an anonymous context that provides a complete
+    // name for this node, note that.
+    auto nameNode = adoptAnonymousContextName(
+        descriptor, parentDescriptorResult, dem);
+
     // If there was a problem reading the parent descriptor, we're done.
     if (!parentDescriptorResult) return nullptr;
 
@@ -1365,81 +1519,48 @@
     Demangle::NodePointer parentDemangling = nullptr;
     if (auto parentDescriptor = *parentDescriptorResult) {
       parentDemangling =
-        buildContextDescriptorMangling(parentDescriptor, nodeFactory);
+        buildContextDescriptorMangling(parentDescriptor, dem);
       if (!parentDemangling)
         return nullptr;
     }
 
-    std::string nodeName;
-    std::string relatedTag;
     Demangle::Node::Kind nodeKind;
     Optional<TypeImportInfo<std::string>> importInfo;
 
-    auto getTypeName = [&]() -> bool {
-      auto typeBuffer =
-        reinterpret_cast<const TargetTypeContextDescriptor<Runtime> *>
-          (descriptor.getLocalBuffer());
-      auto nameAddress = resolveRelativeField(descriptor, typeBuffer->Name);
-      if (!Reader->readString(RemoteAddress(nameAddress), nodeName))
-        return false;
+    auto getContextName = [&]() -> bool {
+      if (nameNode)
+        return true;
 
-      // Read the TypeImportInfo if present.
-      if (typeBuffer->getTypeContextDescriptorFlags().hasImportInfo()) {
-        importInfo.emplace();
-        nameAddress += nodeName.size() + 1;
-
-        while (true) {
-          // Read the next string.
-          std::string temp;
-          if (!Reader->readString(RemoteAddress(nameAddress), temp))
-            return false;
-
-          // If we read an empty string, we're done.
-          if (temp.empty())
-            break;
-
-          // Advance past the string.
-          nameAddress += temp.size() + 1;
-
-          // Collect the import information.  Ignore anything we don't
-          // understand.
-          importInfo->collect</*asserting*/false>(std::move(temp));
-        }
-
-        // Ignore the original if we have an ABI name override.
-        if (!importInfo->ABIName.empty())
-          nodeName = std::move(importInfo->ABIName);
+      if (auto name = readContextDescriptorName(descriptor, importInfo)) {
+        nameNode = dem.createNode(Node::Kind::Identifier, std::move(*name));
+        return true;
       }
-      
-      return true;
+
+      return false;
     };
-    
+
     bool isTypeContext = false;
     switch (auto contextKind = descriptor->getKind()) {
     case ContextDescriptorKind::Class:
-      if (!getTypeName())
+      if (!getContextName())
         return nullptr;
       nodeKind = Demangle::Node::Kind::Class;
       isTypeContext = true;
       break;
     case ContextDescriptorKind::Struct:
-      if (!getTypeName())
+      if (!getContextName())
         return nullptr;
       nodeKind = Demangle::Node::Kind::Structure;
       isTypeContext = true;
       break;
     case ContextDescriptorKind::Enum:
-      if (!getTypeName())
+      if (!getContextName())
         return nullptr;
       nodeKind = Demangle::Node::Kind::Enum;
       isTypeContext = true;
       break;
     case ContextDescriptorKind::Protocol: {
-      auto protocolBuffer =
-        reinterpret_cast<const TargetProtocolDescriptor<Runtime> *>
-          (descriptor.getLocalBuffer());
-      auto nameAddress = resolveRelativeField(descriptor, protocolBuffer->Name);
-      if (!Reader->readString(RemoteAddress(nameAddress), nodeName))
+      if (!getContextName())
         return nullptr;
 
       nodeKind = Demangle::Node::Kind::Protocol;
@@ -1454,13 +1575,13 @@
       char addressBuf[18];
       snprintf(addressBuf, sizeof(addressBuf), "$%" PRIx64,
                (uint64_t)descriptor.getAddress());
-      auto anonNode = nodeFactory.createNode(Node::Kind::AnonymousContext);
+      auto anonNode = dem.createNode(Node::Kind::AnonymousContext);
       CharVector addressStr;
-      addressStr.append(addressBuf, nodeFactory);
-      auto name = nodeFactory.createNode(Node::Kind::Identifier, addressStr);
-      anonNode->addChild(name, nodeFactory);
+      addressStr.append(addressBuf, dem);
+      auto name = dem.createNode(Node::Kind::Identifier, addressStr);
+      anonNode->addChild(name, dem);
       if (parentDemangling)
-        anonNode->addChild(parentDemangling, nodeFactory);
+        anonNode->addChild(parentDemangling, dem);
       
       return anonNode;
     }
@@ -1477,12 +1598,13 @@
           (descriptor.getLocalBuffer());
       auto nameAddress
         = resolveRelativeField(descriptor, moduleBuffer->Name);
-      if (!Reader->readString(RemoteAddress(nameAddress), nodeName))
+      std::string moduleName;
+      if (!Reader->readString(RemoteAddress(nameAddress), moduleName))
         return nullptr;
 
       // The form of module contexts is a little different from other
       // contexts; just create the node directly here and return.
-      return nodeFactory.createNode(nodeKind, std::move(nodeName));
+      return dem.createNode(nodeKind, std::move(moduleName));
     }
     
     default:
@@ -1513,15 +1635,13 @@
         nodeKind = Demangle::Node::Kind::Structure;
     }
 
-    auto nameNode = nodeFactory.createNode(Node::Kind::Identifier,
-                                           std::move(nodeName));
-
     // Use private declaration names for anonymous context references.
-    if (parentDemangling->getKind() == Node::Kind::AnonymousContext) {
+    if (parentDemangling->getKind() == Node::Kind::AnonymousContext
+        && nameNode->getKind() == Node::Kind::Identifier) {
       auto privateDeclName =
-        nodeFactory.createNode(Node::Kind::PrivateDeclName);
-      privateDeclName->addChild(parentDemangling->getChild(0), nodeFactory);
-      privateDeclName->addChild(nameNode, nodeFactory);
+        dem.createNode(Node::Kind::PrivateDeclName);
+      privateDeclName->addChild(parentDemangling->getChild(0), dem);
+      privateDeclName->addChild(nameNode, dem);
 
       nameNode = privateDeclName;
       parentDemangling = parentDemangling->getChild(1);
@@ -1529,15 +1649,15 @@
 
     if (importInfo && !importInfo->RelatedEntityName.empty()) {
       auto relatedNode =
-        nodeFactory.createNode(Node::Kind::RelatedEntityDeclName,
+        dem.createNode(Node::Kind::RelatedEntityDeclName,
                                std::move(importInfo->RelatedEntityName));
-      relatedNode->addChild(nameNode, nodeFactory);
+      relatedNode->addChild(nameNode, dem);
       nameNode = relatedNode;
     }
 
-    auto demangling = nodeFactory.createNode(nodeKind);
-    demangling->addChild(parentDemangling, nodeFactory);
-    demangling->addChild(nameNode, nodeFactory);
+    auto demangling = dem.createNode(nodeKind);
+    demangling->addChild(parentDemangling, dem);
+    demangling->addChild(nameNode, dem);
     return demangling;
   }
 
@@ -1545,8 +1665,8 @@
   /// for it.
   Demangle::NodePointer
   buildContextMangling(ContextDescriptorRef descriptor,
-                       Demangle::NodeFactory &nodeFactory) {
-    auto demangling = buildContextDescriptorMangling(descriptor, nodeFactory);
+                       Demangler &dem) {
+    auto demangling = buildContextDescriptorMangling(descriptor, dem);
     if (!demangling)
       return nullptr;
 
@@ -1554,8 +1674,8 @@
     // References to type nodes behave as types in the mangling.
     if (isa<TargetTypeContextDescriptor<Runtime>>(descriptor.getLocalBuffer()) ||
         isa<TargetProtocolDescriptor<Runtime>>(descriptor.getLocalBuffer())) {
-      top = nodeFactory.createNode(Node::Kind::Type);
-      top->addChild(demangling, nodeFactory);
+      top = dem.createNode(Node::Kind::Type);
+      top->addChild(demangling, dem);
     } else {
       top = demangling;
     }
@@ -1568,8 +1688,8 @@
   BuiltNominalTypeDecl
   buildNominalTypeDecl(ContextDescriptorRef descriptor) {
     // Build the demangling tree from the context tree.
-    Demangle::NodeFactory nodeFactory;
-    auto node = buildContextMangling(descriptor, nodeFactory);
+    Demangler dem;
+    auto node = buildContextMangling(descriptor, dem);
     if (!node || node->getKind() != Node::Kind::Type)
       return BuiltNominalTypeDecl();
     BuiltNominalTypeDecl decl = Builder.createNominalTypeDecl(node);
diff --git a/lib/AST/Attr.cpp b/lib/AST/Attr.cpp
index d865881..fe2d9a4 100644
--- a/lib/AST/Attr.cpp
+++ b/lib/AST/Attr.cpp
@@ -536,10 +536,10 @@
   }
 
   case DAK_ObjCRuntimeName: {
-    Printer.printAttrName("@objc");
+    Printer.printAttrName("@_objcRuntimeName");
     Printer << "(";
     auto *attr = cast<ObjCRuntimeNameAttr>(this);
-    Printer << "\"" << attr->Name << "\"";
+    Printer << attr->Name;
     Printer << ")";
     break;
   }
diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp
index c92e02d..3741c08 100644
--- a/lib/AST/Decl.cpp
+++ b/lib/AST/Decl.cpp
@@ -3856,16 +3856,19 @@
   Bits.ProtocolDecl.ExistentialConformsToSelf = false;
   Bits.ProtocolDecl.Circularity
     = static_cast<unsigned>(CircularityCheck::Unchecked);
+  Bits.ProtocolDecl.InheritedProtocolsValid = 0;
   Bits.ProtocolDecl.NumRequirementsInSignature = 0;
   Bits.ProtocolDecl.HasMissingRequirements = false;
   Bits.ProtocolDecl.KnownProtocol = 0;
-  setTrailingWhereClause(TrailingWhere);
+    setTrailingWhereClause(TrailingWhere);
 }
 
-llvm::TinyPtrVector<ProtocolDecl *>
-ProtocolDecl::getInheritedProtocols() const {
-  llvm::TinyPtrVector<ProtocolDecl *> result;
-  SmallPtrSet<const ProtocolDecl *, 4> known;
+ArrayRef<ProtocolDecl *>
+ProtocolDecl::getInheritedProtocolsSlow() {
+  Bits.ProtocolDecl.InheritedProtocolsValid = true;
+
+  llvm::SmallVector<ProtocolDecl *, 2> result;
+  SmallPtrSet<const ProtocolDecl *, 2> known;
   known.insert(this);
   bool anyObject = false;
   for (const auto found :
@@ -3877,7 +3880,9 @@
     }
   }
 
-  return result;
+  auto &ctx = getASTContext();
+  InheritedProtocols = ctx.AllocateCopy(result);
+  return InheritedProtocols;
 }
 
 llvm::TinyPtrVector<AssociatedTypeDecl *>
@@ -3919,7 +3924,10 @@
 void ProtocolDecl::setSuperclass(Type superclass) {
   assert((!superclass || !superclass->hasArchetype())
          && "superclass must be interface type");
-  LazySemanticInfo.Superclass.setPointerAndInt(superclass, true);
+  LazySemanticInfo.SuperclassType.setPointerAndInt(superclass, true);
+  LazySemanticInfo.SuperclassDecl.setPointerAndInt(
+    superclass ? superclass->getClassOrBoundGenericClass() : nullptr,
+    true);
 }
 
 bool ProtocolDecl::walkInheritedProtocols(
@@ -6437,7 +6445,10 @@
 void ClassDecl::setSuperclass(Type superclass) {
   assert((!superclass || !superclass->hasArchetype())
          && "superclass must be interface type");
-  LazySemanticInfo.Superclass.setPointerAndInt(superclass, true);
+  LazySemanticInfo.SuperclassType.setPointerAndInt(superclass, true);
+  LazySemanticInfo.SuperclassDecl.setPointerAndInt(
+    superclass ? superclass->getClassOrBoundGenericClass() : nullptr,
+    true);
 }
 
 ClangNode Decl::getClangNodeImpl() const {
diff --git a/lib/AST/GenericSignatureBuilder.cpp b/lib/AST/GenericSignatureBuilder.cpp
index 1f8b345..60205de 100644
--- a/lib/AST/GenericSignatureBuilder.cpp
+++ b/lib/AST/GenericSignatureBuilder.cpp
@@ -2031,9 +2031,7 @@
     ProtocolDecl *proto = conforms.first;
 
     // Look for an associated type and/or concrete type with this name.
-    auto flags = OptionSet<NominalTypeDecl::LookupDirectFlags>();
-    flags |= NominalTypeDecl::LookupDirectFlags::IgnoreNewExtensions;
-    for (auto member : proto->lookupDirect(name, flags)) {
+    for (auto member : proto->lookupDirect(name)) {
       // If this is an associated type, record whether it is the best
       // associated type we've seen thus far.
       if (auto assocType = dyn_cast<AssociatedTypeDecl>(member)) {
diff --git a/lib/AST/NameLookup.cpp b/lib/AST/NameLookup.cpp
index 61a8866..0b03fe6 100644
--- a/lib/AST/NameLookup.cpp
+++ b/lib/AST/NameLookup.cpp
@@ -267,6 +267,42 @@
         }
       }
 
+      // The Foundation overlay introduced Data.withUnsafeBytes, which is
+      // treated as being ambiguous with SwiftNIO's Data.withUnsafeBytes
+      // extension. Apply a special-case name shadowing rule to use the
+      // latter rather than the former, which be the consequence of a more
+      // significant change to name shadowing in the future.
+      if (auto owningStruct1
+            = firstDecl->getDeclContext()->getSelfStructDecl()) {
+        if (auto owningStruct2
+              = secondDecl->getDeclContext()->getSelfStructDecl()) {
+          if (owningStruct1 == owningStruct2 &&
+              owningStruct1->getName().is("Data") &&
+              isa<FuncDecl>(firstDecl) && isa<FuncDecl>(secondDecl) &&
+              firstDecl->getFullName() == secondDecl->getFullName() &&
+              firstDecl->getBaseName().userFacingName() == "withUnsafeBytes") {
+            // If the second module is the Foundation module and the first
+            // is the NIOFoundationCompat module, the second is shadowed by the
+            // first.
+            if (firstDecl->getModuleContext()->getName()
+                  .is("NIOFoundationCompat") &&
+                secondDecl->getModuleContext()->getName().is("Foundation")) {
+              shadowed.insert(secondDecl);
+              continue;
+            }
+
+            // If it's the other way around, the first declaration is shadowed
+            // by the second.
+            if (secondDecl->getModuleContext()->getName()
+                  .is("NIOFoundationCompat") &&
+                firstDecl->getModuleContext()->getName().is("Foundation")) {
+              shadowed.insert(firstDecl);
+              break;
+            }
+          }
+        }
+      }
+
       // Prefer declarations in an overlay to similar declarations in
       // the Clang module it customizes.
       if (firstDecl->hasClangNode() != secondDecl->hasClangNode()) {
@@ -590,6 +626,14 @@
   auto *extDecl = decl.dyn_cast<ExtensionDecl *>();
 
   DeclContext *dc = protoDecl ? (DeclContext *)protoDecl : (DeclContext *)extDecl;
+
+  // A protocol or extension 'where' clause can reference associated types of
+  // the protocol itself, so we have to start unqualified lookup from 'dc'.
+  //
+  // However, the right hand side of a 'Self' conformance constraint must be
+  // resolved before unqualified lookup into 'dc' can work, so we make an
+  // exception here and begin lookup from the parent context instead.
+  auto *lookupDC = dc->getParent();
   auto requirements = protoDecl ? protoDecl->getTrailingWhereClause()
                                 : extDecl->getTrailingWhereClause();
 
@@ -619,7 +663,7 @@
     // Resolve the right-hand side.
     DirectlyReferencedTypeDecls rhsDecls;
     if (auto typeRepr = req.getConstraintRepr()) {
-      rhsDecls = directReferencesForTypeRepr(evaluator, ctx, typeRepr, dc);
+      rhsDecls = directReferencesForTypeRepr(evaluator, ctx, typeRepr, lookupDC);
     } else if (Type type = req.getConstraint()) {
       rhsDecls = directReferencesForType(type);
     }
diff --git a/lib/AST/NameLookupRequests.cpp b/lib/AST/NameLookupRequests.cpp
index 245e6ca..0a82db6 100644
--- a/lib/AST/NameLookupRequests.cpp
+++ b/lib/AST/NameLookupRequests.cpp
@@ -74,6 +74,30 @@
 //----------------------------------------------------------------------------//
 // Superclass declaration computation.
 //----------------------------------------------------------------------------//
+Optional<ClassDecl *> SuperclassDeclRequest::getCachedResult() const {
+  auto nominalDecl = std::get<0>(getStorage());
+
+  if (auto *classDecl = dyn_cast<ClassDecl>(nominalDecl))
+    if (classDecl->LazySemanticInfo.SuperclassDecl.getInt())
+      return classDecl->LazySemanticInfo.SuperclassDecl.getPointer();
+
+  if (auto *protocolDecl = dyn_cast<ProtocolDecl>(nominalDecl))
+    if (protocolDecl->LazySemanticInfo.SuperclassDecl.getInt())
+      return protocolDecl->LazySemanticInfo.SuperclassDecl.getPointer();
+
+  return None;
+}
+
+void SuperclassDeclRequest::cacheResult(ClassDecl *value) const {
+  auto nominalDecl = std::get<0>(getStorage());
+
+  if (auto *classDecl = dyn_cast<ClassDecl>(nominalDecl))
+    classDecl->LazySemanticInfo.SuperclassDecl.setPointerAndInt(value, true);
+
+  if (auto *protocolDecl = dyn_cast<ProtocolDecl>(nominalDecl))
+    protocolDecl->LazySemanticInfo.SuperclassDecl.setPointerAndInt(value, true);
+}
+
 void SuperclassDeclRequest::diagnoseCycle(DiagnosticEngine &diags) const {
   // FIXME: Improve this diagnostic.
   auto subjectDecl = std::get<0>(getStorage());
@@ -87,7 +111,7 @@
 }
 
 //----------------------------------------------------------------------------//
-// Superclass declaration computation.
+// Extended nominal computation.
 //----------------------------------------------------------------------------//
 Optional<NominalTypeDecl *> ExtendedNominalRequest::getCachedResult() const {
   // Note: if we fail to compute any nominal declaration, it's considered
diff --git a/lib/AST/TypeCheckRequests.cpp b/lib/AST/TypeCheckRequests.cpp
index 442adcb..466ff7c 100644
--- a/lib/AST/TypeCheckRequests.cpp
+++ b/lib/AST/TypeCheckRequests.cpp
@@ -125,12 +125,12 @@
   auto nominalDecl = std::get<0>(getStorage());
 
   if (auto *classDecl = dyn_cast<ClassDecl>(nominalDecl))
-    if (classDecl->LazySemanticInfo.Superclass.getInt())
-      return classDecl->LazySemanticInfo.Superclass.getPointer();
+    if (classDecl->LazySemanticInfo.SuperclassType.getInt())
+      return classDecl->LazySemanticInfo.SuperclassType.getPointer();
 
   if (auto *protocolDecl = dyn_cast<ProtocolDecl>(nominalDecl))
-    if (protocolDecl->LazySemanticInfo.Superclass.getInt())
-      return protocolDecl->LazySemanticInfo.Superclass.getPointer();
+    if (protocolDecl->LazySemanticInfo.SuperclassType.getInt())
+      return protocolDecl->LazySemanticInfo.SuperclassType.getPointer();
 
   return None;
 }
@@ -139,10 +139,10 @@
   auto nominalDecl = std::get<0>(getStorage());
 
   if (auto *classDecl = dyn_cast<ClassDecl>(nominalDecl))
-    classDecl->LazySemanticInfo.Superclass.setPointerAndInt(value, true);
+    classDecl->LazySemanticInfo.SuperclassType.setPointerAndInt(value, true);
 
   if (auto *protocolDecl = dyn_cast<ProtocolDecl>(nominalDecl))
-    protocolDecl->LazySemanticInfo.Superclass.setPointerAndInt(value, true);
+    protocolDecl->LazySemanticInfo.SuperclassType.setPointerAndInt(value, true);
 }
 
 //----------------------------------------------------------------------------//
diff --git a/lib/ClangImporter/ClangImporter.cpp b/lib/ClangImporter/ClangImporter.cpp
index 73c86d7..6b98da3 100644
--- a/lib/ClangImporter/ClangImporter.cpp
+++ b/lib/ClangImporter/ClangImporter.cpp
@@ -1144,6 +1144,14 @@
   if (!DummyIncludeBuffer.isValid()) {
     clang::SourceLocation includeLoc =
         srcMgr.getLocForStartOfFile(srcMgr.getMainFileID());
+    // Picking the beginning of the main FileID as include location is also what
+    // the clang PCH mechanism is doing (see
+    // clang::ASTReader::getImportLocation()). Choose the next source location
+    // here to avoid having the exact same import location as the clang PCH.
+    // Otherwise, if we are using a PCH for bridging header, we'll have
+    // problems with source order comparisons of clang source locations not
+    // being deterministic.
+    includeLoc = includeLoc.getLocWithOffset(1);
     DummyIncludeBuffer = srcMgr.createFileID(
         llvm::make_unique<ZeroFilledMemoryBuffer>(
           256*1024, StringRef(moduleImportBufferName)),
diff --git a/lib/Demangling/NodePrinter.cpp b/lib/Demangling/NodePrinter.cpp
index b2d764e..1ce7b3e 100644
--- a/lib/Demangling/NodePrinter.cpp
+++ b/lib/Demangling/NodePrinter.cpp
@@ -1013,8 +1013,11 @@
   case Node::Kind::AnonymousContext:
     if (Options.QualifyEntities && Options.DisplayExtensionContexts) {
       print(Node->getChild(1));
-      Printer << ".(unknown context at " << Node->getChild(0)->getText() << ")";
-      if (Node->getChild(2)->getNumChildren() > 0) {
+      Printer << ".(unknown context at ";
+      print(Node->getChild(0));
+      Printer << ")";
+      if (Node->getNumChildren() >= 3 &&
+          Node->getChild(2)->getNumChildren() > 0) {
         Printer << '<';
         print(Node->getChild(2));
         Printer << '>';
diff --git a/lib/Demangling/OldRemangler.cpp b/lib/Demangling/OldRemangler.cpp
index 211606f..69e44b2 100644
--- a/lib/Demangling/OldRemangler.cpp
+++ b/lib/Demangling/OldRemangler.cpp
@@ -1910,6 +1910,12 @@
     break;
   }
 
+  case Node::Kind::AnonymousContext:
+    if (node->getNumChildren() > 1) {
+      mangleGenericArgs(node->getChild(1), ctx);
+    }
+    break;
+
   case Node::Kind::Extension: {
     mangleGenericArgs(node->getChild(1), ctx);
     break;
diff --git a/lib/Driver/ToolChains.cpp b/lib/Driver/ToolChains.cpp
index 9250e4d..e4a55c3 100644
--- a/lib/Driver/ToolChains.cpp
+++ b/lib/Driver/ToolChains.cpp
@@ -243,6 +243,12 @@
     arguments.push_back(inputArgs.MakeArgString(workingDirectory));
   }
 
+  // -g implies -enable-anonymous-context-mangled-names, because the extra
+  // metadata aids debugging.
+  if (inputArgs.hasArg(options::OPT_g)) {
+    arguments.push_back("-enable-anonymous-context-mangled-names");
+  }
+
   // Pass through any subsystem flags.
   inputArgs.AddAllArgs(arguments, options::OPT_Xllvm);
   inputArgs.AddAllArgs(arguments, options::OPT_Xcc);
diff --git a/lib/Frontend/CompilerInvocation.cpp b/lib/Frontend/CompilerInvocation.cpp
index c00be92..f21a41a 100644
--- a/lib/Frontend/CompilerInvocation.cpp
+++ b/lib/Frontend/CompilerInvocation.cpp
@@ -39,7 +39,7 @@
   llvm::sys::path::remove_filename(LibPath); // Remove /swift
   llvm::sys::path::remove_filename(LibPath); // Remove /bin
   llvm::sys::path::append(LibPath, "lib", "swift");
-  setRuntimeResourcePath(LibPath.str());
+  setRuntimeResourcePath(LibPath.str(), /*IsDefault=*/true);
 }
 
 static void updateRuntimeLibraryPath(SearchPathOptions &SearchPathOpts,
@@ -53,9 +53,11 @@
   SearchPathOpts.RuntimeLibraryImportPath = LibPath.str();
 }
 
-void CompilerInvocation::setRuntimeResourcePath(StringRef Path) {
+void CompilerInvocation::setRuntimeResourcePath(StringRef Path,
+                                                bool IsDefault) {
   SearchPathOpts.RuntimeResourcePath = Path;
   updateRuntimeLibraryPath(SearchPathOpts, LangOpts.Target);
+  SearchPathOpts.RuntimeLibraryPathIsDefault = IsDefault;
 }
 
 void CompilerInvocation::setTargetTriple(StringRef Triple) {
@@ -1039,6 +1041,9 @@
     Opts.EnableReflectionNames = false;
   }
 
+  if (Args.hasArg(OPT_enable_anonymous_context_mangled_names))
+    Opts.EnableAnonymousContextMangledNames = true;
+
   if (Args.hasArg(OPT_disable_reflection_names)) {
     Opts.EnableReflectionNames = false;
   }
diff --git a/lib/IDE/SyntaxModel.cpp b/lib/IDE/SyntaxModel.cpp
index c88a2e9..9edf65d 100644
--- a/lib/IDE/SyntaxModel.cpp
+++ b/lib/IDE/SyntaxModel.cpp
@@ -425,18 +425,6 @@
   if (isVisitedBeforeInIfConfig(E))
     return {false, E};
 
-  // In SequenceExpr, explicit cast expressions (e.g. 'as', 'is') appear twice.
-  // Skip pointers we've already seen.
-  if (auto SE = dyn_cast<SequenceExpr>(E)) {
-    SmallPtrSet<Expr *, 5> seenExpr;
-    for (auto subExpr : SE->getElements()) {
-      if (!seenExpr.insert(subExpr).second)
-        continue;
-      subExpr->walk(*this);
-    }
-    return { false, SE };
-  }
-
   auto addCallArgExpr = [&](Expr *Elem, TupleExpr *ParentTupleExpr) {
     if (isCurrentCallArgExpr(ParentTupleExpr)) {
       CharSourceRange NR = parameterNameRangeOfCallArg(ParentTupleExpr, Elem);
@@ -558,6 +546,18 @@
                           Closure->getExplicitResultTypeLoc().getSourceRange());
 
     pushStructureNode(SN, Closure);
+  } else if (auto SE = dyn_cast<SequenceExpr>(E)) {
+    // In SequenceExpr, explicit cast expressions (e.g. 'as', 'is') appear
+    // twice. Skip pointers we've already seen.
+    SmallPtrSet<Expr *, 5> seenExpr;
+    for (auto subExpr : SE->getElements()) {
+      if (!seenExpr.insert(subExpr).second) {
+        continue;
+      }
+      llvm::SaveAndRestore<ASTWalker::ParentTy> SetParent(Parent, E);
+      subExpr->walk(*this);
+    }
+    return { false, walkToExprPost(SE) };
   }
 
   return { true, E };
diff --git a/lib/IRGen/GenMeta.cpp b/lib/IRGen/GenMeta.cpp
index b24f2d6..a3678de 100644
--- a/lib/IRGen/GenMeta.cpp
+++ b/lib/IRGen/GenMeta.cpp
@@ -511,6 +511,7 @@
     void layout() {
       super::layout();
       asImpl().addGenericSignature();
+      asImpl().addMangledName();
     }
   
     ConstantReference getParent() {
@@ -530,6 +531,26 @@
       return true;
     }
 
+    uint16_t getKindSpecificFlags() {
+      AnonymousContextDescriptorFlags flags{};
+      flags.setHasMangledName(
+        IGM.IRGen.Opts.EnableAnonymousContextMangledNames);
+
+      return flags.getOpaqueValue();
+    }
+
+    void addMangledName() {
+      if (!IGM.IRGen.Opts.EnableAnonymousContextMangledNames)
+        return;
+
+      IRGenMangler mangler;
+      auto mangledName = mangler.mangleContext(DC);
+      auto mangledNameConstant =
+        IGM.getAddrOfGlobalString(mangledName,
+                                  /*willBeRelativelyAddressed*/ true);
+      B.addRelativeAddress(mangledNameConstant);
+    }
+
     void emit() {
       asImpl().layout();
       auto addr = IGM.getAddrOfAnonymousContextDescriptor(DC,
diff --git a/lib/IRGen/IRGenMangler.h b/lib/IRGen/IRGenMangler.h
index 9f3b7aa..4d92b15 100644
--- a/lib/IRGen/IRGenMangler.h
+++ b/lib/IRGen/IRGenMangler.h
@@ -153,7 +153,13 @@
     appendOperator("MXX");
     return finalize();
   }
-  
+
+  std::string mangleContext(const DeclContext *DC) {
+    beginMangling();
+    appendContext(DC);
+    return finalize();
+  }
+
   std::string mangleBareProtocol(const ProtocolDecl *Decl) {
     beginMangling();
     appendProtocolName(Decl, /*allowStandardSubstitution=*/false);
diff --git a/lib/IRGen/IRGenModule.h b/lib/IRGen/IRGenModule.h
index 41e6a59..8ffd3cc 100644
--- a/lib/IRGen/IRGenModule.h
+++ b/lib/IRGen/IRGenModule.h
@@ -461,7 +461,7 @@
 class IRGenModule {
 public:
   // The ABI version of the Swift data generated by this file.
-  static const uint32_t swiftVersion = 6;
+  static const uint32_t swiftVersion = 7;
 
   IRGenerator &IRGen;
   ASTContext &Context;
diff --git a/lib/Immediate/Immediate.cpp b/lib/Immediate/Immediate.cpp
index 31634d3..8bce4bf 100644
--- a/lib/Immediate/Immediate.cpp
+++ b/lib/Immediate/Immediate.cpp
@@ -51,10 +51,22 @@
 using namespace swift;
 using namespace swift::immediate;
 
+/// The path for Swift libraries in the OS.
+#define OS_LIBRARY_PATH "/usr/lib/swift"
+
 static void *loadRuntimeLib(StringRef runtimeLibPathWithName) {
 #if defined(_WIN32)
   return LoadLibraryA(runtimeLibPathWithName.str().c_str());
 #else
+#if defined(__APPLE__) && defined(__MACH__)
+  if (!llvm::sys::path::is_absolute(runtimeLibPathWithName)) {
+    // Try an absolute path search for Swift in the OS first.
+    llvm::SmallString<128> absolutePath(OS_LIBRARY_PATH);
+    llvm::sys::path::append(absolutePath, runtimeLibPathWithName);
+    auto result = dlopen(absolutePath.c_str(), RTLD_LAZY | RTLD_GLOBAL);
+    if (result) return result;
+  }
+#endif
   return dlopen(runtimeLibPathWithName.str().c_str(), RTLD_LAZY | RTLD_GLOBAL);
 #endif
 }
@@ -66,8 +78,16 @@
   return loadRuntimeLib(Path);
 }
 
-void *swift::immediate::loadSwiftRuntime(StringRef runtimeLibPath) {
-  return loadRuntimeLib("libswiftCore" LTDL_SHLIB_EXT, runtimeLibPath);
+void *swift::immediate::loadSwiftRuntime(StringRef runtimeLibPath,
+                                         bool IsDefault) {
+  StringRef LibName = "libswiftCore" LTDL_SHLIB_EXT;
+#if defined(__APPLE__) && defined(__MACH__)
+  if (IsDefault) {
+    auto result = loadRuntimeLib(LibName);
+    if (result) return result;
+  }
+#endif
+  return loadRuntimeLib(LibName, runtimeLibPath);
 }
 
 static bool tryLoadLibrary(LinkLibrary linkLib,
@@ -240,7 +260,9 @@
   //
   // This must be done here, before any library loading has been done, to avoid
   // racing with the static initializers in user code.
-  auto stdlib = loadSwiftRuntime(Context.SearchPathOpts.RuntimeLibraryPath);
+  auto stdlib = loadSwiftRuntime(
+    Context.SearchPathOpts.RuntimeLibraryPath,
+    Context.SearchPathOpts.RuntimeLibraryPathIsDefault);
   if (!stdlib) {
     CI.getDiags().diagnose(SourceLoc(),
                            diag::error_immediate_mode_missing_stdlib);
diff --git a/lib/Immediate/ImmediateImpl.h b/lib/Immediate/ImmediateImpl.h
index 4ce425d..2caee04 100644
--- a/lib/Immediate/ImmediateImpl.h
+++ b/lib/Immediate/ImmediateImpl.h
@@ -38,7 +38,8 @@
 /// calls or \c null if an error occurred.
 ///
 /// \param runtimeLibPath Path to search for compiler-relative stdlib dylibs.
-void *loadSwiftRuntime(StringRef runtimeLibPath);
+/// \param IsDefault If true, the path is the default compiler-relative path.
+void *loadSwiftRuntime(StringRef runtimeLibPath, bool IsDefault);
 bool tryLoadLibraries(ArrayRef<LinkLibrary> LinkLibraries,
                       SearchPathOptions SearchPathOpts,
                       DiagnosticEngine &Diags);
diff --git a/lib/Immediate/REPL.cpp b/lib/Immediate/REPL.cpp
index a18bf7a..117c2e7 100644
--- a/lib/Immediate/REPL.cpp
+++ b/lib/Immediate/REPL.cpp
@@ -968,7 +968,8 @@
     ASTContext &Ctx = CI.getASTContext();
     Ctx.LangOpts.EnableAccessControl = false;
     if (!ParseStdlib) {
-      if (!loadSwiftRuntime(Ctx.SearchPathOpts.RuntimeLibraryPath)) {
+      if (!loadSwiftRuntime(Ctx.SearchPathOpts.RuntimeLibraryPath,
+                            Ctx.SearchPathOpts.RuntimeLibraryPathIsDefault)) {
         CI.getDiags().diagnose(SourceLoc(),
                                diag::error_immediate_mode_missing_stdlib);
         return;
diff --git a/lib/Migrator/APIDiffMigratorPass.cpp b/lib/Migrator/APIDiffMigratorPass.cpp
index 13a7e8a..ef8f0bf 100644
--- a/lib/Migrator/APIDiffMigratorPass.cpp
+++ b/lib/Migrator/APIDiffMigratorPass.cpp
@@ -1077,6 +1077,31 @@
     return false;
   }
 
+  void handleResultTypeChange(ValueDecl *FD, Expr *Call) {
+    Optional<NodeAnnotation> ChangeKind;
+
+    // look for related change item for the function decl.
+    for (auto Item: getRelatedDiffItems(FD)) {
+      if (auto *CI = dyn_cast<CommonDiffItem>(Item)) {
+        // check if the function's return type has been changed from nonnull
+        // to nullable.
+        if (CI->DiffKind == NodeAnnotation::WrapOptional &&
+            CI->getChildIndices().size() == 1 &&
+            CI->getChildIndices().front() == 0) {
+          ChangeKind = NodeAnnotation::WrapOptional;
+          break;
+        }
+      }
+    }
+    if (!ChangeKind.hasValue())
+      return;
+    // If a function's return type has been changed from nonnull to nullable,
+    // append ! to the original call expression.
+    if (*ChangeKind == NodeAnnotation::WrapOptional) {
+      Editor.insertAfterToken(Call->getSourceRange().End, "!");
+    }
+  }
+
   bool walkToExprPre(Expr *E) override {
     if (E->getSourceRange().isInvalid())
       return false;
@@ -1100,6 +1125,7 @@
           handleTypeHoist(FD, CE, Args);
           handleSpecialCases(FD, CE, Args);
           handleStringRepresentableArg(FD, Args, CE);
+          handleResultTypeChange(FD, CE);
         }
         break;
       }
@@ -1110,15 +1136,16 @@
           handleFunctionCallToPropertyChange(FD, DSC->getFn(), Args);
           handleSpecialCases(FD, CE, Args);
           handleStringRepresentableArg(FD, Args, CE);
+          handleResultTypeChange(FD, CE);
         }
         break;
       }
       case ExprKind::ConstructorRefCall: {
         auto CCE = cast<ConstructorRefCallExpr>(Fn);
         if (auto FD = CCE->getFn()->getReferencedDecl().getDecl()) {
-          auto *CE = CCE->getFn();
           handleFuncRename(FD, CE, Args);
           handleStringRepresentableArg(FD, Args, CE);
+          handleResultTypeChange(FD, CE);
         }
         break;
       }
diff --git a/lib/Migrator/overlay4.json b/lib/Migrator/overlay4.json
index d5fb336..6c2e805 100644
--- a/lib/Migrator/overlay4.json
+++ b/lib/Migrator/overlay4.json
@@ -1332,4 +1332,15 @@
     "RightComment": "firstIndex",
     "ModuleName": "Swift"
   },
+  {
+    "DiffItemKind": "CommonDiffItem",
+    "NodeKind": "Function",
+    "NodeAnnotation": "Rename",
+    "ChildIndex": "0",
+    "LeftUsr": "s:SlsE5index5where5IndexQzSgSb7ElementQzKXE_tKF",
+    "LeftComment": "index",
+    "RightUsr": "",
+    "RightComment": "firstIndex",
+    "ModuleName": "Swift"
+  },
 ]
diff --git a/lib/Migrator/overlay42.json b/lib/Migrator/overlay42.json
index cc6d339..7498140 100644
--- a/lib/Migrator/overlay42.json
+++ b/lib/Migrator/overlay42.json
@@ -10,4 +10,15 @@
     "RightComment": "firstIndex",
     "ModuleName": "Swift"
   },
+  {
+    "DiffItemKind": "CommonDiffItem",
+    "NodeKind": "Function",
+    "NodeAnnotation": "Rename",
+    "ChildIndex": "0",
+    "LeftUsr": "s:SlsE5index5where5IndexQzSgSb7ElementQzKXE_tKF",
+    "LeftComment": "index",
+    "RightUsr": "",
+    "RightComment": "firstIndex",
+    "ModuleName": "Swift"
+  },
 ]
diff --git a/lib/SIL/SILGlobalVariable.cpp b/lib/SIL/SILGlobalVariable.cpp
index 65cb2b1..ad4c880 100644
--- a/lib/SIL/SILGlobalVariable.cpp
+++ b/lib/SIL/SILGlobalVariable.cpp
@@ -119,6 +119,12 @@
           // a pointer+offset relocation.
           // Note that StringObjectOr requires the or'd bits in the first
           // operand to be 0, so the operation is equivalent to an addition.
+  
+          // Temporarily disable static long Strings for macos.
+          // rdar://problem/47467102
+          if (M.getASTContext().LangOpts.Target.isMacOSX())
+            return false;
+  
           if (isa<IntegerLiteralInst>(bi->getArguments()[1]))
             return true;
           break;
diff --git a/lib/SILGen/SILGenExpr.cpp b/lib/SILGen/SILGenExpr.cpp
index 6c05d89..04d3732 100644
--- a/lib/SILGen/SILGenExpr.cpp
+++ b/lib/SILGen/SILGenExpr.cpp
@@ -2285,9 +2285,13 @@
   // Map outer initializations into a tuple of inner initializations:
   //   - fill out the initialization elements with null
   TupleInitialization innerTupleInit;
-  CanTupleType innerTuple =
-    cast<TupleType>(E->getSubExpr()->getType()->getCanonicalType());
-  innerTupleInit.SubInitializations.resize(innerTuple->getNumElements());
+  if (E->isSourceScalar()) {
+    innerTupleInit.SubInitializations.push_back(nullptr);
+  } else {
+    CanTupleType innerTuple =
+      cast<TupleType>(E->getSubExpr()->getType()->getCanonicalType());
+    innerTupleInit.SubInitializations.resize(innerTuple->getNumElements());
+  }
 
   // Map all the outer initializations to their appropriate targets.
   for (unsigned outerIndex = 0; outerIndex != outerInits.size(); outerIndex++) {
@@ -2305,14 +2309,20 @@
 #endif
 
   // Emit the sub-expression into the tuple initialization we just built.
-  emitter.SGF.emitExprInto(E->getSubExpr(), &innerTupleInit);
+  if (E->isSourceScalar()) {
+    emitter.SGF.emitExprInto(E->getSubExpr(),
+                             innerTupleInit.SubInitializations[0].get());
+  } else {
+    emitter.SGF.emitExprInto(E->getSubExpr(), &innerTupleInit);
+  }
 
   outerTupleInit->finishInitialization(emitter.SGF);
 }
 
 RValue RValueEmitter::visitTupleShuffleExpr(TupleShuffleExpr *E,
                                             SGFContext C) {
-  assert(!E->isSourceScalar());
+  // FIXME: Once we're no longer using this code path for enum element payloads,
+  // also assert that !E->isSourceScalar().
   assert(!E->isResultScalar());
 
   // If we're emitting into an initialization, we can try shuffling the
@@ -2326,7 +2336,11 @@
 
   // Emit the sub-expression tuple and destructure it into elements.
   SmallVector<RValue, 4> elements;
-  visit(E->getSubExpr()).extractElements(elements);
+  if (E->isSourceScalar()) {
+    elements.push_back(visit(E->getSubExpr()));
+  } else {
+    visit(E->getSubExpr()).extractElements(elements);
+  }
   
   // Prepare a new tuple to hold the shuffled result.
   RValue result(E->getType()->getCanonicalType());
diff --git a/lib/SILOptimizer/Transforms/PerformanceInliner.cpp b/lib/SILOptimizer/Transforms/PerformanceInliner.cpp
index 31d62e2..4c109d6 100644
--- a/lib/SILOptimizer/Transforms/PerformanceInliner.cpp
+++ b/lib/SILOptimizer/Transforms/PerformanceInliner.cpp
@@ -37,6 +37,10 @@
   "sil-inline-generics", llvm::cl::init(false),
   llvm::cl::desc("Enable inlining of generics"));
 
+llvm::cl::opt<bool>
+    EnableSILAgressiveInlining("sil-agressive-inline", llvm::cl::init(false),
+                               llvm::cl::desc("Enable agressive inlining"));
+
 //===----------------------------------------------------------------------===//
 //                           Performance Inliner
 //===----------------------------------------------------------------------===//
@@ -104,7 +108,7 @@
     /// The benefit of inlining an exclusivity-containing callee.
     /// The exclusivity needs to be: dynamic,
     /// has no nested conflict and addresses known storage
-    ExclusivityBenefit = RemovedCallBenefit + 125,
+    ExclusivityBenefit = RemovedCallBenefit + 10,
 
     /// The benefit of inlining class methods with -Osize.
     /// We only inline very small class methods with -Osize.
@@ -320,6 +324,10 @@
   // the exclusivity heuristic or not. We can *only* do that
   // if AllAccessesBeneficialToInline is true
   int ExclusivityBenefitWeight = 0;
+  int ExclusivityBenefitBase = ExclusivityBenefit;
+  if (EnableSILAgressiveInlining) {
+    ExclusivityBenefitBase += 500;
+  }
 
   SubstitutionMap CalleeSubstMap = AI.getSubstitutionMap();
 
@@ -421,7 +429,8 @@
           if (BAI->hasNoNestedConflict() &&
               (storage.isUniquelyIdentified() ||
                storage.getKind() == AccessedStorage::Class)) {
-            BlockW.updateBenefit(ExclusivityBenefitWeight, ExclusivityBenefit);
+            BlockW.updateBenefit(ExclusivityBenefitWeight,
+                                 ExclusivityBenefitBase);
           } else {
             AllAccessesBeneficialToInline = false;
           }
diff --git a/lib/Sema/TypeCheckError.cpp b/lib/Sema/TypeCheckError.cpp
index a967828..20ead77 100644
--- a/lib/Sema/TypeCheckError.cpp
+++ b/lib/Sema/TypeCheckError.cpp
@@ -155,6 +155,11 @@
       }
     }
     
+    // Constructor delegation.
+    if (auto otherCtorDeclRef = dyn_cast<OtherConstructorDeclRefExpr>(fn)) {
+      return AbstractFunction(otherCtorDeclRef->getDecl());
+    }
+
     // Normal function references.
     if (auto declRef = dyn_cast<DeclRefExpr>(fn)) {
       ValueDecl *decl = declRef->getDecl();
diff --git a/lib/Sema/TypeCheckType.cpp b/lib/Sema/TypeCheckType.cpp
index baf317e..25b59cd 100644
--- a/lib/Sema/TypeCheckType.cpp
+++ b/lib/Sema/TypeCheckType.cpp
@@ -212,8 +212,9 @@
     return DependentMemberType::get(baseTy, assocType);
   }
 
-  // Otherwise, the nested type comes from a concrete type. Substitute the
-  // base type into it.
+  // Otherwise, the nested type comes from a concrete type,
+  // or it's a typealias declared in protocol or protocol extension.
+  // Substitute the base type into it.
   auto concrete = ref->getBoundDecl();
   auto lazyResolver = ctx.getLazyResolver();
   if (lazyResolver)
@@ -221,14 +222,26 @@
   if (!concrete->hasInterfaceType())
     return ErrorType::get(ctx);
 
-  if (concrete->getDeclContext()->getSelfClassDecl()) {
-    // We found a member of a class from a protocol or protocol
-    // extension.
-    //
-    // Get the superclass of the 'Self' type parameter.
-    baseTy = (baseEquivClass->concreteType
-              ? baseEquivClass->concreteType
-              : baseEquivClass->superclass);
+  // Make sure that base type didn't get replaced along the way.
+  assert(baseTy->isTypeParameter());
+
+  // There are two situations possible here:
+  //
+  // 1. Member comes from the protocol, which means that it has been
+  //    found through a conformance constraint placed on base e.g. `T: P`.
+  //    In this case member is a `typealias` declaration located in
+  //    protocol or protocol extension.
+  //
+  // 2. Member comes from struct/enum/class type, which means that it
+  //    has been found through same-type constraint on base e.g. `T == Q`.
+  //
+  // If this is situation #2 we need to make sure to switch base to
+  // a concrete type (according to equivalence class) otherwise we'd
+  // end up using incorrect generic signature while attempting to form
+  // a substituted type for the member we found.
+  if (!concrete->getDeclContext()->getSelfProtocolDecl()) {
+    baseTy = baseEquivClass->concreteType ? baseEquivClass->concreteType
+                                          : baseEquivClass->superclass;
     assert(baseTy);
   }
 
diff --git a/lib/Serialization/Deserialization.cpp b/lib/Serialization/Deserialization.cpp
index 4b162fe..0f2dfae 100644
--- a/lib/Serialization/Deserialization.cpp
+++ b/lib/Serialization/Deserialization.cpp
@@ -1138,21 +1138,20 @@
   return None;
 }
 
-/// Determine whether the two modules are re-exported to the same module.
-static bool reExportedToSameModule(const ModuleDecl *fromModule,
-                                   const ModuleDecl *toModule) {
+static bool isReExportedToModule(const ValueDecl *value,
+                                 const ModuleDecl *expectedModule) {
+  const DeclContext *valueDC = value->getDeclContext();
   auto fromClangModule
-    = dyn_cast<ClangModuleUnit>(fromModule->getFiles().front());
+      = dyn_cast<ClangModuleUnit>(valueDC->getModuleScopeContext());
   if (!fromClangModule)
     return false;
+  std::string exportedName = fromClangModule->getExportedModuleName();
 
   auto toClangModule
-  = dyn_cast<ClangModuleUnit>(toModule->getFiles().front());
-  if (!toClangModule)
-    return false;
-
-  return fromClangModule->getExportedModuleName() ==
-    toClangModule->getExportedModuleName();
+      = dyn_cast<ClangModuleUnit>(expectedModule->getFiles().front());
+  if (toClangModule)
+    return exportedName == toClangModule->getExportedModuleName();
+  return exportedName == expectedModule->getName().str();
 }
 
 /// Remove values from \p values that don't match the expected type or module.
@@ -1195,7 +1194,7 @@
     // module to the original definition in a base module.
     if (expectedModule && !value->hasClangNode() &&
         value->getModuleContext() != expectedModule &&
-        !reExportedToSameModule(value->getModuleContext(), expectedModule))
+        !isReExportedToModule(value, expectedModule))
       return true;
 
     // If we're expecting a member within a constrained extension with a
@@ -1349,6 +1348,7 @@
       if (entry.Kind != llvm::BitstreamEntry::Record)
         return Identifier();
 
+      scratch.clear();
       unsigned recordID = DeclTypeCursor.readRecord(entry.ID, scratch,
                                                     &blobData);
       switch (recordID) {
@@ -1414,9 +1414,9 @@
         IdentifierID IID;
         IdentifierID privateDiscriminator;
         bool importedFromClang = false;
+        bool inProtocolExt = false;
         XRefTypePathPieceLayout::readRecord(scratch, IID, privateDiscriminator,
-                                            /*inProtocolExt*/None,
-                                            importedFromClang);
+                                            inProtocolExt, importedFromClang);
         if (privateDiscriminator)
           goto giveUpFastPath;
 
@@ -1446,9 +1446,8 @@
         if (nestedType) {
           SmallVector<ValueDecl *, 1> singleValueBuffer{nestedType};
           filterValues(/*expectedTy*/Type(), extensionModule, genericSig,
-                       /*isType*/true, /*inProtocolExt*/false,
-                       importedFromClang, /*isStatic*/false, /*ctorInit*/None,
-                       singleValueBuffer);
+                       /*isType*/true, inProtocolExt, importedFromClang,
+                       /*isStatic*/false, /*ctorInit*/None, singleValueBuffer);
           if (!singleValueBuffer.empty()) {
             values.assign({nestedType});
             ++NumNestedTypeShortcuts;
diff --git a/lib/Serialization/Serialization.cpp b/lib/Serialization/Serialization.cpp
index f40a9ad..a7d9a2a 100644
--- a/lib/Serialization/Serialization.cpp
+++ b/lib/Serialization/Serialization.cpp
@@ -1894,10 +1894,12 @@
       discriminator = containingFile->getDiscriminatorForPrivateValue(generic);
     }
 
+    bool isProtocolExt = DC->getParent()->getExtendedProtocolDecl();
+
     XRefTypePathPieceLayout::emitRecord(Out, ScratchRecord, abbrCode,
                                         addDeclBaseNameRef(generic->getName()),
                                         addDeclBaseNameRef(discriminator),
-                                        /*inProtocolExtension*/false,
+                                        isProtocolExt,
                                         generic->hasClangNode());
     break;
   }
diff --git a/lib/Serialization/SerializedModuleLoader.cpp b/lib/Serialization/SerializedModuleLoader.cpp
index cfc2543..c0d3579 100644
--- a/lib/Serialization/SerializedModuleLoader.cpp
+++ b/lib/Serialization/SerializedModuleLoader.cpp
@@ -128,6 +128,23 @@
                      archName, foundArchs);
 }
 
+static std::pair<llvm::SmallString<16>, llvm::SmallString<16>>
+getArchSpecificModuleFileNames(StringRef archName) {
+  llvm::SmallString<16> archFile, archDocFile;
+
+  if (!archName.empty()) {
+    archFile += archName;
+    archFile += '.';
+    archFile += file_types::getExtension(file_types::TY_SwiftModuleFile);
+
+    archDocFile += archName;
+    archDocFile += '.';
+    archDocFile += file_types::getExtension(file_types::TY_SwiftModuleDocFile);
+  }
+
+  return {archFile, archDocFile};
+}
+
 bool
 SerializedModuleLoaderBase::findModule(AccessPathElem moduleID,
            std::unique_ptr<llvm::MemoryBuffer> *moduleBuffer,
@@ -143,19 +160,19 @@
   moduleDocFilename +=
       file_types::getExtension(file_types::TY_SwiftModuleDocFile);
 
-  // FIXME: Which name should we be using here? Do we care about CPU subtypes?
-  // FIXME: At the very least, don't hardcode "arch".
-  llvm::SmallString<16> archName{
-      Ctx.LangOpts.getPlatformConditionValue(PlatformConditionKind::Arch)};
-  llvm::SmallString<16> archFile{archName};
-  llvm::SmallString<16> archDocFile{archName};
-  if (!archFile.empty()) {
-    archFile += '.';
-    archFile += file_types::getExtension(file_types::TY_SwiftModuleFile);
+  StringRef archName = Ctx.LangOpts.Target.getArchName();
+  auto archFileNames = getArchSpecificModuleFileNames(archName);
 
-    archDocFile += '.';
-    archDocFile += file_types::getExtension(file_types::TY_SwiftModuleDocFile);
-  }
+  // FIXME: We used to use "major architecture" names for these files---the
+  // names checked in "#if arch(...)". Fall back to that name in the one case
+  // where it's different from what Swift 4.2 supported: 32-bit ARM platforms.
+  // We should be able to drop this once there's an Xcode that supports the
+  // new names.
+  StringRef alternateArchName;
+  if (Ctx.LangOpts.Target.getArch() == llvm::Triple::ArchType::arm)
+    alternateArchName = "arm";
+  auto alternateArchFileNames =
+      getArchSpecificModuleFileNames(alternateArchName);
 
   llvm::SmallString<128> scratch;
   llvm::SmallString<128> currPath;
@@ -169,10 +186,19 @@
       currPath = path;
       llvm::sys::path::append(currPath, moduleFilename.str());
       err = openModuleFiles(currPath,
-                            archFile.str(), archDocFile.str(),
+                            archFileNames.first, archFileNames.second,
                             moduleBuffer, moduleDocBuffer,
                             scratch);
 
+      if (err == std::errc::no_such_file_or_directory &&
+          !alternateArchName.empty()) {
+        err = openModuleFiles(currPath,
+                              alternateArchFileNames.first,
+                              alternateArchFileNames.second,
+                              moduleBuffer, moduleDocBuffer,
+                              scratch);
+      }
+
       if (err == std::errc::no_such_file_or_directory) {
         addDiagnosticInfoForArchitectureMismatch(
             Ctx, moduleID.second, moduleName, archName, currPath);
@@ -197,9 +223,18 @@
       }
 
       llvm::sys::path::append(currPath, "Modules", moduleFilename.str());
-      auto err = openModuleFiles(currPath, archFile.str(), archDocFile.str(),
+      auto err = openModuleFiles(currPath,
+                                 archFileNames.first, archFileNames.second,
                                  moduleBuffer, moduleDocBuffer, scratch);
 
+      if (err == std::errc::no_such_file_or_directory &&
+          !alternateArchName.empty()) {
+        err = openModuleFiles(currPath,
+                              alternateArchFileNames.first,
+                              alternateArchFileNames.second,
+                              moduleBuffer, moduleDocBuffer, scratch);
+      }
+
       if (err == std::errc::no_such_file_or_directory) {
         addDiagnosticInfoForArchitectureMismatch(
             Ctx, moduleID.second, moduleName, archName, currPath);
diff --git a/stdlib/public/SDK/AppKit/NSGraphics.swift b/stdlib/public/SDK/AppKit/NSGraphics.swift
index 6cc836c..f4e2a7c 100644
--- a/stdlib/public/SDK/AppKit/NSGraphics.swift
+++ b/stdlib/public/SDK/AppKit/NSGraphics.swift
@@ -181,7 +181,10 @@
 }
 
 extension NSAnimationEffect {
-  private class _CompletionHandlerDelegate : NSObject {
+  // NOTE: older overlays called this class _CompletionHandlerDelegate.
+  // The two must coexist without a conflicting ObjC class name, so it
+  // was renamed. The old name must not be used in the new runtime.
+  private class __CompletionHandlerDelegate : NSObject {
     var completionHandler: () -> Void = { }
     @objc func animationEffectDidEnd(_ contextInfo: UnsafeMutableRawPointer?) {
       completionHandler()
@@ -190,7 +193,7 @@
   @available(swift 4)
   public func show(centeredAt centerLocation: NSPoint, size: NSSize,
                    completionHandler: @escaping () -> Void = { }) {
-    let delegate = _CompletionHandlerDelegate()
+    let delegate = __CompletionHandlerDelegate()
     delegate.completionHandler = completionHandler
     // Note that the delegate of `__NSShowAnimationEffect` is retained for the
     // duration of the animation.
@@ -199,7 +202,7 @@
         centerLocation,
         size,
         delegate,
-        #selector(_CompletionHandlerDelegate.animationEffectDidEnd(_:)),
+        #selector(__CompletionHandlerDelegate.animationEffectDidEnd(_:)),
         nil)
   }
 }
diff --git a/stdlib/public/SDK/CoreGraphics/CGFloat.swift.gyb b/stdlib/public/SDK/CoreGraphics/CGFloat.swift.gyb
index 190bd1b..1b8823f 100644
--- a/stdlib/public/SDK/CoreGraphics/CGFloat.swift.gyb
+++ b/stdlib/public/SDK/CoreGraphics/CGFloat.swift.gyb
@@ -347,12 +347,6 @@
   public static var max: CGFloat {
     fatalError("unavailable")
   }
-
-  @available(swift, deprecated: 3.1, obsoleted: 4.0, message: "Please use the `abs(_:)` free function")
-  @_transparent
-  public static func abs(_ x: CGFloat) -> CGFloat {
-    return x.magnitude
-  }
 }
 
 @available(*, unavailable, renamed: "CGFloat.leastNormalMagnitude")
diff --git a/stdlib/public/SDK/Dispatch/Block.swift b/stdlib/public/SDK/Dispatch/Block.swift
index e3558e4..1f9d8b1 100644
--- a/stdlib/public/SDK/Dispatch/Block.swift
+++ b/stdlib/public/SDK/Dispatch/Block.swift
@@ -34,7 +34,12 @@
 	public static let enforceQoS = DispatchWorkItemFlags(rawValue: 0x20)
 }
 
+// NOTE: older overlays had Dispatch.DispatchWorkItem as the ObjC name.
+// The two must coexist, so it was renamed. The old name must not be
+// used in the new runtime. _TtC8Dispatch17_DispatchWorkItem is the
+// mangled name for Dispatch._DispatchWorkItem.
 @available(macOS 10.10, iOS 8.0, *)
+@_objcRuntimeName(_TtC8Dispatch17_DispatchWorkItem)
 public class DispatchWorkItem {
 	internal var _block: _DispatchBlock
 
diff --git a/stdlib/public/SDK/Foundation/CharacterSet.swift b/stdlib/public/SDK/Foundation/CharacterSet.swift
index 3161d6a..68df36e 100644
--- a/stdlib/public/SDK/Foundation/CharacterSet.swift
+++ b/stdlib/public/SDK/Foundation/CharacterSet.swift
@@ -29,7 +29,10 @@
 
 // MARK: -
 
-fileprivate final class _CharacterSetStorage : Hashable {
+// NOTE: older overlays called this class _CharacterSetStorage.
+// The two must coexist without a conflicting ObjC class name, so it
+// was renamed. The old name must not be used in the new runtime.
+fileprivate final class __CharacterSetStorage : Hashable {
     fileprivate enum Backing {
         case immutable(CFCharacterSet)
         case mutable(CFMutableCharacterSet)
@@ -58,7 +61,7 @@
         }
     }
     
-    fileprivate static func ==(lhs : _CharacterSetStorage, rhs : _CharacterSetStorage) -> Bool {
+    fileprivate static func ==(lhs : __CharacterSetStorage, rhs : __CharacterSetStorage) -> Bool {
         switch (lhs._backing, rhs._backing) {
         case (.immutable(let cs1), .immutable(let cs2)):
             return CFEqual(cs1, cs2)
@@ -73,12 +76,12 @@
     
     // MARK: -
     
-    fileprivate func mutableCopy() -> _CharacterSetStorage {
+    fileprivate func mutableCopy() -> __CharacterSetStorage {
         switch _backing {
         case .immutable(let cs):
-            return _CharacterSetStorage(mutableReference: CFCharacterSetCreateMutableCopy(nil, cs))
+            return __CharacterSetStorage(mutableReference: CFCharacterSetCreateMutableCopy(nil, cs))
         case .mutable(let cs):
-            return _CharacterSetStorage(mutableReference: CFCharacterSetCreateMutableCopy(nil, cs))
+            return __CharacterSetStorage(mutableReference: CFCharacterSetCreateMutableCopy(nil, cs))
         }
     }
 
@@ -223,7 +226,7 @@
     
 
     // When the underlying collection does not have a method to return new CharacterSets with changes applied, so we will copy and apply here
-    private static func _apply(_ lhs : _CharacterSetStorage, _ rhs : _CharacterSetStorage, _ f : (CFMutableCharacterSet, CFCharacterSet) -> ()) -> CharacterSet {
+    private static func _apply(_ lhs : __CharacterSetStorage, _ rhs : __CharacterSetStorage, _ f : (CFMutableCharacterSet, CFCharacterSet) -> ()) -> CharacterSet {
         let copyOfMe : CFMutableCharacterSet
         switch lhs._backing {
         case .immutable(let cs):
@@ -239,10 +242,10 @@
             f(copyOfMe, cs)
         }
         
-        return CharacterSet(_uncopiedStorage: _CharacterSetStorage(mutableReference: copyOfMe))
+        return CharacterSet(_uncopiedStorage: __CharacterSetStorage(mutableReference: copyOfMe))
     }
     
-    private func _applyMutation(_ other : _CharacterSetStorage, _ f : (CFMutableCharacterSet, CFCharacterSet) -> ()) {
+    private func _applyMutation(_ other : __CharacterSetStorage, _ f : (CFMutableCharacterSet, CFCharacterSet) -> ()) {
         switch _backing {
         case .immutable(let cs):
             let r = CFCharacterSetCreateMutableCopy(nil, cs)!
@@ -267,47 +270,47 @@
     fileprivate var inverted : CharacterSet {
         switch _backing {
         case .immutable(let cs):
-            return CharacterSet(_uncopiedStorage: _CharacterSetStorage(immutableReference: CFCharacterSetCreateInvertedSet(nil, cs)))
+            return CharacterSet(_uncopiedStorage: __CharacterSetStorage(immutableReference: CFCharacterSetCreateInvertedSet(nil, cs)))
         case .mutable(let cs):
             // Even if input is mutable, the result is immutable
-            return CharacterSet(_uncopiedStorage: _CharacterSetStorage(immutableReference: CFCharacterSetCreateInvertedSet(nil, cs)))
+            return CharacterSet(_uncopiedStorage: __CharacterSetStorage(immutableReference: CFCharacterSetCreateInvertedSet(nil, cs)))
         }
     }
 
-    fileprivate func union(_ other: _CharacterSetStorage) -> CharacterSet {
-        return _CharacterSetStorage._apply(self, other, CFCharacterSetUnion)
+    fileprivate func union(_ other: __CharacterSetStorage) -> CharacterSet {
+        return __CharacterSetStorage._apply(self, other, CFCharacterSetUnion)
     }
     
-    fileprivate func formUnion(_ other: _CharacterSetStorage) {
+    fileprivate func formUnion(_ other: __CharacterSetStorage) {
         _applyMutation(other, CFCharacterSetUnion)
     }
     
-    fileprivate func intersection(_ other: _CharacterSetStorage) -> CharacterSet {
-        return _CharacterSetStorage._apply(self, other, CFCharacterSetIntersect)
+    fileprivate func intersection(_ other: __CharacterSetStorage) -> CharacterSet {
+        return __CharacterSetStorage._apply(self, other, CFCharacterSetIntersect)
     }
     
-    fileprivate func formIntersection(_ other: _CharacterSetStorage) {
+    fileprivate func formIntersection(_ other: __CharacterSetStorage) {
         _applyMutation(other, CFCharacterSetIntersect)
     }
     
-    fileprivate func subtracting(_ other: _CharacterSetStorage) -> CharacterSet {
+    fileprivate func subtracting(_ other: __CharacterSetStorage) -> CharacterSet {
         return intersection(other.inverted._storage)
     }
     
-    fileprivate func subtract(_ other: _CharacterSetStorage) {
+    fileprivate func subtract(_ other: __CharacterSetStorage) {
         _applyMutation(other.inverted._storage, CFCharacterSetIntersect)
     }
     
-    fileprivate func symmetricDifference(_ other: _CharacterSetStorage) -> CharacterSet {
+    fileprivate func symmetricDifference(_ other: __CharacterSetStorage) -> CharacterSet {
         return union(other).subtracting(intersection(other))
     }
     
-    fileprivate func formSymmetricDifference(_ other: _CharacterSetStorage) {
+    fileprivate func formSymmetricDifference(_ other: __CharacterSetStorage) {
         // This feels like cheating
         _backing = symmetricDifference(other)._storage._backing
     }
     
-    fileprivate func isSuperset(of other: _CharacterSetStorage) -> Bool {
+    fileprivate func isSuperset(of other: __CharacterSetStorage) -> Bool {
         switch _backing {
         case .immutable(let cs):
             switch other._backing {
@@ -363,35 +366,35 @@
 public struct CharacterSet : ReferenceConvertible, Equatable, Hashable, SetAlgebra {
     public typealias ReferenceType = NSCharacterSet
     
-    fileprivate var _storage : _CharacterSetStorage
+    fileprivate var _storage : __CharacterSetStorage
     
     // MARK: Init methods
     
     /// Initialize an empty instance.
     public init() {
         // It's unlikely that we are creating an empty character set with no intention to mutate it
-        _storage = _CharacterSetStorage(mutableReference: CFCharacterSetCreateMutable(nil))
+        _storage = __CharacterSetStorage(mutableReference: CFCharacterSetCreateMutable(nil))
     }
     
     /// Initialize with a range of integers.
     ///
     /// It is the caller's responsibility to ensure that the values represent valid `Unicode.Scalar` values, if that is what is desired.
     public init(charactersIn range: Range<Unicode.Scalar>) {
-        _storage = _CharacterSetStorage(immutableReference: CFCharacterSetCreateWithCharactersInRange(nil, _utfRangeToCFRange(range)))
+        _storage = __CharacterSetStorage(immutableReference: CFCharacterSetCreateWithCharactersInRange(nil, _utfRangeToCFRange(range)))
     }
 
     /// Initialize with a closed range of integers.
     ///
     /// It is the caller's responsibility to ensure that the values represent valid `Unicode.Scalar` values, if that is what is desired.
     public init(charactersIn range: ClosedRange<Unicode.Scalar>) {
-        _storage = _CharacterSetStorage(immutableReference: CFCharacterSetCreateWithCharactersInRange(nil, _utfRangeToCFRange(range)))
+        _storage = __CharacterSetStorage(immutableReference: CFCharacterSetCreateWithCharactersInRange(nil, _utfRangeToCFRange(range)))
     }
 
     /// Initialize with the characters in the given string.
     ///
     /// - parameter string: The string content to inspect for characters.
     public init(charactersIn string: __shared String) {
-        _storage = _CharacterSetStorage(immutableReference: CFCharacterSetCreateWithCharactersInString(nil, string as CFString))
+        _storage = __CharacterSetStorage(immutableReference: CFCharacterSetCreateWithCharactersInString(nil, string as CFString))
     }
     
     /// Initialize with a bitmap representation.
@@ -399,7 +402,7 @@
     /// This method is useful for creating a character set object with data from a file or other external data source.
     /// - parameter data: The bitmap representation.
     public init(bitmapRepresentation data: __shared Data) {
-        _storage = _CharacterSetStorage(immutableReference: CFCharacterSetCreateWithBitmapRepresentation(nil, data as CFData))
+        _storage = __CharacterSetStorage(immutableReference: CFCharacterSetCreateWithBitmapRepresentation(nil, data as CFData))
     }
     
     /// Initialize with the contents of a file.
@@ -409,26 +412,26 @@
     public init?(contentsOfFile file: __shared String) {
         do {
             let data = try Data(contentsOf: URL(fileURLWithPath: file), options: .mappedIfSafe)
-            _storage = _CharacterSetStorage(immutableReference: CFCharacterSetCreateWithBitmapRepresentation(nil, data as CFData))
+            _storage = __CharacterSetStorage(immutableReference: CFCharacterSetCreateWithBitmapRepresentation(nil, data as CFData))
         } catch {
             return nil
         }
     }
 
     fileprivate init(_bridged characterSet: __shared NSCharacterSet) {
-        _storage = _CharacterSetStorage(immutableReference: characterSet.copy() as! CFCharacterSet)
+        _storage = __CharacterSetStorage(immutableReference: characterSet.copy() as! CFCharacterSet)
     }
     
     fileprivate init(_uncopiedImmutableReference characterSet: CFCharacterSet) {
-        _storage = _CharacterSetStorage(immutableReference: characterSet)
+        _storage = __CharacterSetStorage(immutableReference: characterSet)
     }
 
-    fileprivate init(_uncopiedStorage : _CharacterSetStorage) {
+    fileprivate init(_uncopiedStorage : __CharacterSetStorage) {
         _storage = _uncopiedStorage
     }
 
     fileprivate init(_builtIn: __shared CFCharacterSetPredefinedSet) {
-        _storage = _CharacterSetStorage(immutableReference: CFCharacterSetGetPredefined(_builtIn))
+        _storage = __CharacterSetStorage(immutableReference: CFCharacterSetGetPredefined(_builtIn))
     }
     
     // MARK: Static functions
diff --git a/stdlib/public/SDK/Foundation/Data.swift b/stdlib/public/SDK/Foundation/Data.swift
index 921f21d..7bd22d1 100644
--- a/stdlib/public/SDK/Foundation/Data.swift
+++ b/stdlib/public/SDK/Foundation/Data.swift
@@ -17,7 +17,7 @@
 #elseif os(Linux)
 import Glibc
 
-@inlinable
+@inlinable // This is @inlinable as trivially computable.
 fileprivate func malloc_good_size(_ size: Int) -> Int {
     return size
 }
@@ -62,14 +62,17 @@
 
 #endif
 
+// Underlying storage representation for medium and large data.
+// Inlinability strategy: methods from here should not inline into InlineSlice or LargeSlice unless trivial.
+// NOTE: older overlays called this class _DataStorage. The two must
+// coexist without a conflicting ObjC class name, so it was renamed.
+// The old name must not be used in the new runtime.
 @usableFromInline
-internal final class _DataStorage {
-    @usableFromInline
-    static let maxSize = Int.max >> 1
-    @usableFromInline
-    static let vmOpsThreshold = NSPageSize() * 4
+internal final class __DataStorage {
+    @usableFromInline static let maxSize = Int.max >> 1
+    @usableFromInline static let vmOpsThreshold = NSPageSize() * 4
     
-    @inlinable
+    @inlinable // This is @inlinable as trivially forwarding, and does not escape the _DataStorage boundary layer.
     static func allocate(_ size: Int, _ clear: Bool) -> UnsafeMutableRawPointer? {
         if clear {
             return calloc(1, size)
@@ -78,12 +81,12 @@
         }
     }
     
-    @inlinable
+    @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
     static func move(_ dest_: UnsafeMutableRawPointer, _ source_: UnsafeRawPointer?, _ num_: Int) {
         var dest = dest_
         var source = source_
         var num = num_
-        if _DataStorage.vmOpsThreshold <= num && ((unsafeBitCast(source, to: Int.self) | Int(bitPattern: dest)) & (NSPageSize() - 1)) == 0 {
+        if __DataStorage.vmOpsThreshold <= num && ((unsafeBitCast(source, to: Int.self) | Int(bitPattern: dest)) & (NSPageSize() - 1)) == 0 {
             let pages = NSRoundDownToMultipleOfPageSize(num)
             NSCopyMemoryPages(source!, dest, pages)
             source = source!.advanced(by: pages)
@@ -95,50 +98,46 @@
         }
     }
     
-    @inlinable
+    @inlinable // This is @inlinable as trivially forwarding, and does not escape the _DataStorage boundary layer.
     static func shouldAllocateCleared(_ size: Int) -> Bool {
         return (size > (128 * 1024))
     }
     
-    @usableFromInline
-    var _bytes: UnsafeMutableRawPointer?
-    @usableFromInline
-    var _length: Int
-    @usableFromInline
-    var _capacity: Int
-    @usableFromInline
-    var _needToZero: Bool
-    @usableFromInline
-    var _deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?
-    @usableFromInline
-    var _offset: Int
+    @usableFromInline var _bytes: UnsafeMutableRawPointer?
+    @usableFromInline var _length: Int
+    @usableFromInline var _capacity: Int
+    @usableFromInline var _needToZero: Bool
+    @usableFromInline var _deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?
+    @usableFromInline var _offset: Int
     
-    @inlinable
+    @inlinable // This is @inlinable as trivially computable.
     var bytes: UnsafeRawPointer? {
         return UnsafeRawPointer(_bytes)?.advanced(by: -_offset)
     }
 
-    @inlinable
+    @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially forwarding.
     @discardableResult
     func withUnsafeBytes<Result>(in range: Range<Int>, apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
         return try apply(UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length)))
     }
     
-    @inlinable
+    @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially forwarding.
     @discardableResult
     func withUnsafeMutableBytes<Result>(in range: Range<Int>, apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
         return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length)))
     }
 
-    @inlinable
+    @inlinable // This is @inlinable as trivially computable.
     var mutableBytes: UnsafeMutableRawPointer? {
         return _bytes?.advanced(by: -_offset)
     }
 
-    @inlinable
-    var capacity: Int { return _capacity }
+    @inlinable // This is @inlinable as trivially computable.
+    var capacity: Int {
+        return _capacity
+    }
     
-    @inlinable
+    @inlinable // This is @inlinable as trivially computable.
     var length: Int {
         get {
             return _length
@@ -148,22 +147,22 @@
         }
     }
     
-    @inlinable
+    @inlinable // This is inlinable as trivially computable.
     var isExternallyOwned: Bool {
-        // all _DataStorages will have some sort of capacity, because empty cases hit the .empty enum _Representation
+        // all __DataStorages will have some sort of capacity, because empty cases hit the .empty enum _Representation
         // anything with 0 capacity means that we have not allocated this pointer and concequently mutation is not ours to make.
         return _capacity == 0
     }
     
-    @inlinable
+    @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
     func ensureUniqueBufferReference(growingTo newLength: Int = 0, clear: Bool = false) {
         guard isExternallyOwned || newLength > _capacity else { return }
 
         if newLength == 0 {
             if isExternallyOwned {
                 let newCapacity = malloc_good_size(_length)
-                let newBytes = _DataStorage.allocate(newCapacity, false)
-                _DataStorage.move(newBytes!, _bytes!, _length)
+                let newBytes = __DataStorage.allocate(newCapacity, false)
+                __DataStorage.move(newBytes!, _bytes!, _length)
                 _freeBytes()
                 _bytes = newBytes
                 _capacity = newCapacity
@@ -171,9 +170,9 @@
             }
         } else if isExternallyOwned {
             let newCapacity = malloc_good_size(newLength)
-            let newBytes = _DataStorage.allocate(newCapacity, clear)
+            let newBytes = __DataStorage.allocate(newCapacity, clear)
             if let bytes = _bytes {
-                _DataStorage.move(newBytes!, bytes, _length)
+                __DataStorage.move(newBytes!, bytes, _length)
             }
             _freeBytes()
             _bytes = newBytes
@@ -182,27 +181,27 @@
             _needToZero = true
         } else {
             let cap = _capacity
-            var additionalCapacity = (newLength >> (_DataStorage.vmOpsThreshold <= newLength ? 2 : 1))
+            var additionalCapacity = (newLength >> (__DataStorage.vmOpsThreshold <= newLength ? 2 : 1))
             if Int.max - additionalCapacity < newLength {
                 additionalCapacity = 0
             }
             var newCapacity = malloc_good_size(Swift.max(cap, newLength + additionalCapacity))
             let origLength = _length
-            var allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity)
+            var allocateCleared = clear && __DataStorage.shouldAllocateCleared(newCapacity)
             var newBytes: UnsafeMutableRawPointer? = nil
             if _bytes == nil {
-                newBytes = _DataStorage.allocate(newCapacity, allocateCleared)
+                newBytes = __DataStorage.allocate(newCapacity, allocateCleared)
                 if newBytes == nil {
                     /* Try again with minimum length */
-                    allocateCleared = clear && _DataStorage.shouldAllocateCleared(newLength)
-                    newBytes = _DataStorage.allocate(newLength, allocateCleared)
+                    allocateCleared = clear && __DataStorage.shouldAllocateCleared(newLength)
+                    newBytes = __DataStorage.allocate(newLength, allocateCleared)
                 }
             } else {
                 let tryCalloc = (origLength == 0 || (newLength / origLength) >= 4)
                 if allocateCleared && tryCalloc {
-                    newBytes = _DataStorage.allocate(newCapacity, true)
+                    newBytes = __DataStorage.allocate(newCapacity, true)
                     if let newBytes = newBytes {
-                        _DataStorage.move(newBytes, _bytes!, origLength)
+                        __DataStorage.move(newBytes, _bytes!, origLength)
                         _freeBytes()
                     }
                 }
@@ -210,9 +209,9 @@
                 if newBytes == nil {
                     allocateCleared = false
                     if _deallocator != nil {
-                        newBytes = _DataStorage.allocate(newCapacity, true)
+                        newBytes = __DataStorage.allocate(newCapacity, true)
                         if let newBytes = newBytes {
-                            _DataStorage.move(newBytes, _bytes!, origLength)
+                            __DataStorage.move(newBytes, _bytes!, origLength)
                             _freeBytes()
                         }
                     } else {
@@ -222,11 +221,11 @@
                 /* Try again with minimum length */
                 if newBytes == nil {
                     newCapacity = malloc_good_size(newLength)
-                    allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity)
+                    allocateCleared = clear && __DataStorage.shouldAllocateCleared(newCapacity)
                     if allocateCleared && tryCalloc {
-                        newBytes = _DataStorage.allocate(newCapacity, true)
+                        newBytes = __DataStorage.allocate(newCapacity, true)
                         if let newBytes = newBytes {
-                            _DataStorage.move(newBytes, _bytes!, origLength)
+                            __DataStorage.move(newBytes, _bytes!, origLength)
                             _freeBytes()
                         }
                     }
@@ -256,7 +255,7 @@
         }
     }
 
-    @inlinable
+    @inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer.
     func _freeBytes() {
         if let bytes = _bytes {
             if let dealloc = _deallocator {
@@ -268,13 +267,13 @@
         _deallocator = nil
     }
 
-    @usableFromInline
+    @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed.
     func enumerateBytes(in range: Range<Int>, _ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Data.Index, _ stop: inout Bool) -> Void) {
         var stopv: Bool = false
         block(UnsafeBufferPointer<UInt8>(start: _bytes?.advanced(by: range.lowerBound - _offset).assumingMemoryBound(to: UInt8.self), count: Swift.min(range.upperBound - range.lowerBound, _length)), 0, &stopv)
     }
     
-    @inlinable
+    @inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer.
     func setLength(_ length: Int) {
         let origLength = _length
         let newLength = length
@@ -288,7 +287,7 @@
         _length = newLength
     }
     
-    @inlinable
+    @inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer.
     func append(_ bytes: UnsafeRawPointer, length: Int) {
         precondition(length >= 0, "Length of appending bytes must not be negative")
         let origLength = _length
@@ -297,75 +296,27 @@
             ensureUniqueBufferReference(growingTo: newLength, clear: false)
         }
         _length = newLength
-        _DataStorage.move(_bytes!.advanced(by: origLength), bytes, length)
+        __DataStorage.move(_bytes!.advanced(by: origLength), bytes, length)
     }
     
-    // fast-path for appending directly from another data storage
-    @inlinable
-    func append(_ otherData: _DataStorage, startingAt start: Int, endingAt end: Int) {
-        let otherLength = otherData.length
-        if otherLength == 0 { return }
-        if let bytes = otherData.bytes {
-            append(bytes.advanced(by: start), length: end - start)
-        }
-    }
-    
-    @inlinable
-    func append(_ otherData: Data) {
-        guard otherData.count > 0 else { return }
-        otherData.withUnsafeBytes {
-            append($0.baseAddress!, length: $0.count)
-        }
-    }
-    
-    @inlinable
-    func increaseLength(by extraLength: Int) {
-        if extraLength == 0 { return }
-        
-        let origLength = _length
-        let newLength = origLength + extraLength
-        if _capacity < newLength || _bytes == nil {
-            ensureUniqueBufferReference(growingTo: newLength, clear: true)
-        } else if _needToZero {
-            memset(_bytes!.advanced(by: origLength), 0, extraLength)
-        }
-        _length = newLength
-    }
-
-    @inlinable
+    @inlinable // This is @inlinable despite escaping the __DataStorage boundary layer because it is trivially computed.
     func get(_ index: Int) -> UInt8 {
         return _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee
     }
     
-    @inlinable
+    @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed.
     func set(_ index: Int, to value: UInt8) {
         ensureUniqueBufferReference()
         _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee = value
     }
 
-    @inlinable
+    @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed.
     func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
         let offsetPointer = UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length))
         UnsafeMutableRawBufferPointer(start: pointer, count: range.upperBound - range.lowerBound).copyMemory(from: offsetPointer)
     }
 
-    @inlinable
-    func replaceBytes(in range: NSRange, with bytes: UnsafeRawPointer?) {
-        if range.length == 0 { return }
-        if _length < range.location + range.length {
-            let newLength = range.location + range.length
-            if _capacity < newLength {
-                ensureUniqueBufferReference(growingTo: newLength, clear: false)
-            }
-            _length = newLength
-        } else {
-            ensureUniqueBufferReference()
-        }
-        _DataStorage.move(_bytes!.advanced(by: range.location - _offset), bytes!, range.length)
-
-    }
-    
-    @inlinable
+    @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
     func replaceBytes(in range_: NSRange, with replacementBytes: UnsafeRawPointer?, length replacementLength: Int) {
         let range = NSRange(location: range_.location - _offset, length: range_.length)
         let currentLength = _length
@@ -398,7 +349,7 @@
         }
     }
     
-    @inlinable
+    @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
     func resetBytes(in range_: Range<Int>) {
         let range = NSRange(location: range_.lowerBound - _offset, length: range_.upperBound - range_.lowerBound)
         if range.length == 0 { return }
@@ -414,21 +365,16 @@
         memset(_bytes!.advanced(by: range.location), 0, range.length)
     }
 
-    @inlinable
-    convenience init() {
-        self.init(capacity: 0)
-    }
-    
-    @usableFromInline
+    @usableFromInline // This is not @inlinable as a non-trivial, non-convenience initializer.
     init(length: Int) {
-        precondition(length < _DataStorage.maxSize)
+        precondition(length < __DataStorage.maxSize)
         var capacity = (length < 1024 * 1024 * 1024) ? length + (length >> 2) : length
-        if _DataStorage.vmOpsThreshold <= capacity {
+        if __DataStorage.vmOpsThreshold <= capacity {
             capacity = NSRoundUpToMultipleOfPageSize(capacity)
         }
         
-        let clear = _DataStorage.shouldAllocateCleared(length)
-        _bytes = _DataStorage.allocate(capacity, clear)!
+        let clear = __DataStorage.shouldAllocateCleared(length)
+        _bytes = __DataStorage.allocate(capacity, clear)!
         _capacity = capacity
         _needToZero = !clear
         _length = 0
@@ -436,51 +382,51 @@
         setLength(length)
     }
     
-    @usableFromInline
-    init(capacity capacity_: Int) {
+    @usableFromInline // This is not @inlinable as a non-convience initializer.
+    init(capacity capacity_: Int = 0) {
         var capacity = capacity_
-        precondition(capacity < _DataStorage.maxSize)
-        if _DataStorage.vmOpsThreshold <= capacity {
+        precondition(capacity < __DataStorage.maxSize)
+        if __DataStorage.vmOpsThreshold <= capacity {
             capacity = NSRoundUpToMultipleOfPageSize(capacity)
         }
         _length = 0
-        _bytes = _DataStorage.allocate(capacity, false)!
+        _bytes = __DataStorage.allocate(capacity, false)!
         _capacity = capacity
         _needToZero = true
         _offset = 0
     }
     
-    @usableFromInline
+    @usableFromInline // This is not @inlinable as a non-convience initializer.
     init(bytes: UnsafeRawPointer?, length: Int) {
-        precondition(length < _DataStorage.maxSize)
+        precondition(length < __DataStorage.maxSize)
         _offset = 0
         if length == 0 {
             _capacity = 0
             _length = 0
             _needToZero = false
             _bytes = nil
-        } else if _DataStorage.vmOpsThreshold <= length {
+        } else if __DataStorage.vmOpsThreshold <= length {
             _capacity = length
             _length = length
             _needToZero = true
-            _bytes = _DataStorage.allocate(length, false)!
-            _DataStorage.move(_bytes!, bytes, length)
+            _bytes = __DataStorage.allocate(length, false)!
+            __DataStorage.move(_bytes!, bytes, length)
         } else {
             var capacity = length
-            if _DataStorage.vmOpsThreshold <= capacity {
+            if __DataStorage.vmOpsThreshold <= capacity {
                 capacity = NSRoundUpToMultipleOfPageSize(capacity)
             }
             _length = length
-            _bytes = _DataStorage.allocate(capacity, false)!
+            _bytes = __DataStorage.allocate(capacity, false)!
             _capacity = capacity
             _needToZero = true
-            _DataStorage.move(_bytes!, bytes, length)
+            __DataStorage.move(_bytes!, bytes, length)
         }
     }
     
-    @usableFromInline
+    @usableFromInline // This is not @inlinable as a non-convience initializer.
     init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?, offset: Int) {
-        precondition(length < _DataStorage.maxSize)
+        precondition(length < __DataStorage.maxSize)
         _offset = offset
         if length == 0 {
             _capacity = 0
@@ -497,32 +443,32 @@
             _needToZero = false
             _bytes = bytes
             _deallocator = deallocator
-        } else if _DataStorage.vmOpsThreshold <= length {
+        } else if __DataStorage.vmOpsThreshold <= length {
             _capacity = length
             _length = length
             _needToZero = true
-            _bytes = _DataStorage.allocate(length, false)!
-            _DataStorage.move(_bytes!, bytes, length)
+            _bytes = __DataStorage.allocate(length, false)!
+            __DataStorage.move(_bytes!, bytes, length)
             if let dealloc = deallocator {
                 dealloc(bytes!, length)
             }
         } else {
             var capacity = length
-            if _DataStorage.vmOpsThreshold <= capacity {
+            if __DataStorage.vmOpsThreshold <= capacity {
                 capacity = NSRoundUpToMultipleOfPageSize(capacity)
             }
             _length = length
-            _bytes = _DataStorage.allocate(capacity, false)!
+            _bytes = __DataStorage.allocate(capacity, false)!
             _capacity = capacity
             _needToZero = true
-            _DataStorage.move(_bytes!, bytes, length)
+            __DataStorage.move(_bytes!, bytes, length)
             if let dealloc = deallocator {
                 dealloc(bytes!, length)
             }
         }
     }
 
-    @usableFromInline
+    @usableFromInline // This is not @inlinable as a non-convience initializer.
     init(immutableReference: NSData, offset: Int) {
         _offset = offset
         _bytes = UnsafeMutableRawPointer(mutating: immutableReference.bytes)
@@ -534,7 +480,7 @@
         }
     }
     
-    @usableFromInline
+    @usableFromInline // This is not @inlinable as a non-convience initializer.
     init(mutableReference: NSMutableData, offset: Int) {
         _offset = offset
         _bytes = mutableReference.mutableBytes
@@ -546,7 +492,7 @@
         }
     }
     
-    @usableFromInline
+    @usableFromInline // This is not @inlinable as a non-convience initializer.
     init(customReference: NSData, offset: Int) {
         _offset = offset
         _bytes = UnsafeMutableRawPointer(mutating: customReference.bytes)
@@ -558,7 +504,7 @@
         }
     }
     
-    @usableFromInline
+    @usableFromInline // This is not @inlinable as a non-convience initializer.
     init(customMutableReference: NSMutableData, offset: Int) {
         _offset = offset
         _bytes = customMutableReference.mutableBytes
@@ -574,12 +520,12 @@
         _freeBytes()
     }
     
-    @inlinable
-    func mutableCopy(_ range: Range<Int>) -> _DataStorage {
-        return _DataStorage(bytes: _bytes?.advanced(by: range.lowerBound - _offset), length: range.upperBound - range.lowerBound, copy: true, deallocator: nil, offset: range.lowerBound)
+    @inlinable // This is @inlinable despite escaping the __DataStorage boundary layer because it is trivially computed.
+    func mutableCopy(_ range: Range<Int>) -> __DataStorage {
+        return __DataStorage(bytes: _bytes?.advanced(by: range.lowerBound - _offset), length: range.upperBound - range.lowerBound, copy: true, deallocator: nil, offset: range.lowerBound)
     }
 
-    @inlinable
+    @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially computed.
     func withInteriorPointerReference<T>(_ range: Range<Int>, _ work: (NSData) throws -> T) rethrows -> T {
         if range.isEmpty {
             return try work(NSData()) // zero length data can be optimized as a singleton
@@ -587,10 +533,8 @@
         return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.upperBound - range.lowerBound, freeWhenDone: false))
     }
 
-    // This is used to create bridged Datas into Objective-C contexts, the class name is private and should not be emitted into clients.
-    // Consequently this should never be inlined.
+    @inline(never) // This is not @inlinable to avoid emission of the private `__NSSwiftData` class name into clients.
     @usableFromInline
-    @inline(never)
     func bridgedReference(_ range: Range<Int>) -> NSData {
         if range.isEmpty {
             return NSData() // zero length data can be optimized as a singleton
@@ -598,21 +542,16 @@
 
         return __NSSwiftData(backing: self, range: range)
     }
-
-    @inlinable
-    func subdata(in range: Range<Data.Index>) -> Data {
-        return Data(bytes: _bytes!.advanced(by: range.lowerBound - _offset), count: range.upperBound - range.lowerBound)
-    }
 }
 
-// NOTE: older runtimes called this _NSSwiftData. The two must
+// NOTE: older overlays called this _NSSwiftData. The two must
 // coexist, so it was renamed. The old name must not be used in the new
 // runtime.
 internal class __NSSwiftData : NSData {
-    var _backing: _DataStorage!
+    var _backing: __DataStorage!
     var _range: Range<Data.Index>!
 
-    convenience init(backing: _DataStorage, range: Range<Data.Index>) {
+    convenience init(backing: __DataStorage, range: Range<Data.Index>) {
         self.init()
         _backing = backing
         _range = range
@@ -676,36 +615,28 @@
     public typealias Index = Int
     public typealias Indices = Range<Int>
 
+    // A small inline buffer of bytes suitable for stack-allocation of small data.
+    // Inlinability strategy: everything here should be inlined for direct operation on the stack wherever possible.
     @usableFromInline
     @_fixed_layout
     internal struct InlineData {
 #if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
-        @usableFromInline
-        typealias Buffer = (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
-                            UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) //len  //enum
-        @usableFromInline
-        var bytes: Buffer
+        @usableFromInline typealias Buffer = (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
+                                              UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) //len  //enum
+        @usableFromInline var bytes: Buffer
 #elseif arch(i386) || arch(arm)
-        @usableFromInline
-        typealias Buffer = (UInt8, UInt8, UInt8, UInt8,
-                            UInt8, UInt8) //len  //enum
-        @usableFromInline
-        var bytes: Buffer
+        @usableFromInline typealias Buffer = (UInt8, UInt8, UInt8, UInt8,
+                                              UInt8, UInt8) //len  //enum
+        @usableFromInline var bytes: Buffer
 #endif
-        @usableFromInline
-        var length: UInt8
+        @usableFromInline var length: UInt8
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially computable.
         static func canStore(count: Int) -> Bool {
             return count <= MemoryLayout<Buffer>.size
         }
 
-        @inlinable
-        init() {
-            self.init(count: 0)
-        }
-
-        @inlinable
+        @inlinable // This is @inlinable as a convenience initializer.
         init(_ srcBuffer: UnsafeRawBufferPointer) {
             self.init(count: srcBuffer.count)
             if srcBuffer.count > 0 {
@@ -715,19 +646,18 @@
             }
         }
 
-        @inlinable
-        init(count: Int) {
+        @inlinable // This is @inlinable as a trivial initializer.
+        init(count: Int = 0) {
             assert(count <= MemoryLayout<Buffer>.size)
 #if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
             bytes = (UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0))
 #elseif arch(i386) || arch(arm)
-            bytes = (UInt8(0), UInt8(0), UInt8(0), UInt8(0),
-                     UInt8(0), UInt8(0))
+            bytes = (UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0))
 #endif
             length = UInt8(count)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a convenience initializer.
         init(_ slice: InlineSlice, count: Int) {
             self.init(count: count)
             Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in
@@ -737,7 +667,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a convenience initializer.
         init(_ slice: LargeSlice, count: Int) {
             self.init(count: count)
             Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in
@@ -747,12 +677,12 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially computable.
         var capacity: Int {
             return MemoryLayout<Buffer>.size
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially computable.
         var count: Int {
             get {
                 return Int(length)
@@ -763,13 +693,17 @@
             }
         }
 
-        @inlinable
-        var startIndex: Int { return 0 }
+        @inlinable // This is @inlinable as trivially computable.
+        var startIndex: Int {
+            return 0
+        }
 
-        @inlinable
-        var endIndex: Int { return count }
+        @inlinable // This is @inlinable as trivially computable.
+        var endIndex: Int {
+            return count
+        }
 
-        @inlinable
+        @inlinable // This is @inlinable as a generic, trivially forwarding function.
         func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
             let count = Int(length)
             return try Swift.withUnsafeBytes(of: bytes) { (rawBuffer) throws -> Result in
@@ -777,7 +711,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a generic, trivially forwarding function.
         mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
             let count = Int(length)
             return try Swift.withUnsafeMutableBytes(of: &bytes) { (rawBuffer) throws -> Result in
@@ -785,7 +719,15 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as tribially computable.
+        mutating func append(byte: UInt8) {
+            let count = self.count
+            assert(count + 1 <= MemoryLayout<Buffer>.size)
+            Swift.withUnsafeMutableBytes(of: &bytes) { $0[count] = byte }
+            self.length += 1
+        }
+
+        @inlinable // This is @inlinable as trivially computable.
         mutating func append(contentsOf buffer: UnsafeRawBufferPointer) {
             guard buffer.count > 0 else { return }
             assert(count + buffer.count <= MemoryLayout<Buffer>.size)
@@ -793,11 +735,11 @@
             _ = Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in
                 rawBuffer.baseAddress?.advanced(by: cnt).copyMemory(from: buffer.baseAddress!, byteCount: buffer.count)
             }
-            length += UInt8(buffer.count)
 
+            length += UInt8(buffer.count)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially computable.
         subscript(index: Index) -> UInt8 {
             get {
                 assert(index <= MemoryLayout<Buffer>.size)
@@ -815,7 +757,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially computable.
         mutating func resetBytes(in range: Range<Index>) {
             assert(range.lowerBound <= MemoryLayout<Buffer>.size)
             assert(range.upperBound <= MemoryLayout<Buffer>.size)
@@ -823,12 +765,13 @@
             if count < range.upperBound {
                 count = range.upperBound
             }
+
             let _ = Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in
                 memset(rawBuffer.baseAddress?.advanced(by: range.lowerBound), 0, range.upperBound - range.lowerBound)
             }
         }
 
-        @inlinable
+        @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
         mutating func replaceSubrange(_ subrange: Range<Index>, with replacementBytes: UnsafeRawPointer?, count replacementLength: Int) {
             assert(subrange.lowerBound <= MemoryLayout<Buffer>.size)
             assert(subrange.upperBound <= MemoryLayout<Buffer>.size)
@@ -852,7 +795,7 @@
             count = resultingLength
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially computable.
         func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
             precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
             precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
@@ -866,123 +809,138 @@
             }
         }
 
-        @inlinable
-        var hashValue: Int {
-            let count = Int(length)
-            return Swift.withUnsafeBytes(of: bytes) { (rawBuffer) -> Int in
-                return Int(bitPattern: CFHashBytes(UnsafeMutablePointer(mutating: rawBuffer.baseAddress?.assumingMemoryBound(to: UInt8.self)), count))
+        @inline(__always) // This should always be inlined into _Representation.hash(into:).
+        func hash(into hasher: inout Hasher) {
+            // **NOTE**: this uses `count` (an Int) and NOT `length` (a UInt8)
+            //           Despite having the same value, they hash differently. InlineSlice and LargeSlice both use `count` (an Int); if you combine the same bytes but with `length` over `count`, you can get a different hash.
+            //
+            // This affects slices, which are InlineSlice and not InlineData:
+            //
+            //   let d = Data([0xFF, 0xFF])                // InlineData
+            //   let s = Data([0, 0xFF, 0xFF]).dropFirst() // InlineSlice
+            //   assert(s == d)
+            //   assert(s.hashValue == d.hashValue)
+            hasher.combine(count)
+
+            Swift.withUnsafeBytes(of: bytes) {
+                // We have access to the full byte buffer here, but not all of it is meaningfully used (bytes past self.length may be garbage).
+                let bytes = UnsafeRawBufferPointer(start: $0.baseAddress, count: self.count)
+                hasher.combine(bytes: bytes)
             }
         }
     }
 
 #if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
-    @usableFromInline
-    internal typealias HalfInt = Int32
+    @usableFromInline internal typealias HalfInt = Int32
 #elseif arch(i386) || arch(arm)
-    @usableFromInline
-    internal typealias HalfInt = Int16
+    @usableFromInline internal typealias HalfInt = Int16
 #endif
 
+    // A buffer of bytes too large to fit in an InlineData, but still small enough to fit a storage pointer + range in two words.
+    // Inlinability strategy: everything here should be easily inlinable as large _DataStorage methods should not inline into here.
     @usableFromInline
     @_fixed_layout
     internal struct InlineSlice {
         // ***WARNING***
         // These ivars are specifically laid out so that they cause the enum _Representation to be 16 bytes on 64 bit platforms. This means we _MUST_ have the class type thing last
-        @usableFromInline
-        var slice: Range<HalfInt>
-        @usableFromInline
-        var storage: _DataStorage
+        @usableFromInline var slice: Range<HalfInt>
+        @usableFromInline var storage: __DataStorage
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially computable.
         static func canStore(count: Int) -> Bool {
             return count < HalfInt.max
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a convenience initializer.
         init(_ buffer: UnsafeRawBufferPointer) {
             assert(buffer.count < HalfInt.max)
-            self.init(_DataStorage(bytes: buffer.baseAddress, length: buffer.count), count: buffer.count)
+            self.init(__DataStorage(bytes: buffer.baseAddress, length: buffer.count), count: buffer.count)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a convenience initializer.
         init(capacity: Int) {
             assert(capacity < HalfInt.max)
-            self.init(_DataStorage(capacity: capacity), count: 0)
+            self.init(__DataStorage(capacity: capacity), count: 0)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a convenience initializer.
         init(count: Int) {
             assert(count < HalfInt.max)
-            self.init(_DataStorage(length: count), count: count)
+            self.init(__DataStorage(length: count), count: count)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a convenience initializer.
         init(_ inline: InlineData) {
             assert(inline.count < HalfInt.max)
-            self.init(inline.withUnsafeBytes { return _DataStorage(bytes: $0.baseAddress, length: $0.count) }, count: inline.count)
+            self.init(inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) }, count: inline.count)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a convenience initializer.
         init(_ inline: InlineData, range: Range<Int>) {
             assert(range.lowerBound < HalfInt.max)
             assert(range.upperBound < HalfInt.max)
-            self.init(inline.withUnsafeBytes { return _DataStorage(bytes: $0.baseAddress, length: $0.count) }, range: range)
+            self.init(inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) }, range: range)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a convenience initializer.
         init(_ large: LargeSlice) {
             assert(large.range.lowerBound < HalfInt.max)
             assert(large.range.upperBound < HalfInt.max)
             self.init(large.storage, range: large.range)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a convenience initializer.
         init(_ large: LargeSlice, range: Range<Int>) {
             assert(range.lowerBound < HalfInt.max)
             assert(range.upperBound < HalfInt.max)
             self.init(large.storage, range: range)
         }
 
-        @inlinable
-        init(_ storage: _DataStorage, count: Int) {
+        @inlinable // This is @inlinable as a trivial initializer.
+        init(_ storage: __DataStorage, count: Int) {
             assert(count < HalfInt.max)
             self.storage = storage
             slice = 0..<HalfInt(count)
         }
 
-        @inlinable
-        init(_ storage: _DataStorage, range: Range<Int>) {
+        @inlinable // This is @inlinable as a trivial initializer.
+        init(_ storage: __DataStorage, range: Range<Int>) {
             assert(range.lowerBound < HalfInt.max)
             assert(range.upperBound < HalfInt.max)
             self.storage = storage
             slice = HalfInt(range.lowerBound)..<HalfInt(range.upperBound)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic).
         mutating func ensureUniqueReference() {
             if !isKnownUniquelyReferenced(&storage) {
                 storage = storage.mutableCopy(self.range)
             }
         }
 
-        @inlinable
-        var startIndex: Int { return Int(slice.lowerBound) }
-        @inlinable
-        var endIndex: Int { return Int(slice.upperBound) }
+        @inlinable // This is @inlinable as trivially computable.
+        var startIndex: Int {
+            return Int(slice.lowerBound)
+        }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially computable.
+        var endIndex: Int {
+            return Int(slice.upperBound)
+        }
+
+        @inlinable // This is @inlinable as trivially computable.
         var capacity: Int {
             return storage.capacity
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic).
         mutating func reserveCapacity(_ minimumCapacity: Int) {
             ensureUniqueReference()
             // the current capacity can be zero (representing externally owned buffer), and count can be greater than the capacity
             storage.ensureUniqueBufferReference(growingTo: Swift.max(minimumCapacity, count))
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially computable.
         var count: Int {
             get {
                 return Int(slice.upperBound - slice.lowerBound)
@@ -995,7 +953,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially computable.
         var range: Range<Int> {
             get {
                 return Int(slice.lowerBound)..<Int(slice.upperBound)
@@ -1007,18 +965,18 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a generic, trivially forwarding function.
         func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
             return try storage.withUnsafeBytes(in: range, apply: apply)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a generic, trivially forwarding function.
         mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
             ensureUniqueReference()
             return try storage.withUnsafeMutableBytes(in: range, apply: apply)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as reasonably small.
         mutating func append(contentsOf buffer: UnsafeRawBufferPointer) {
             assert(endIndex + buffer.count < HalfInt.max)
             ensureUniqueReference()
@@ -1026,7 +984,7 @@
             slice = slice.lowerBound..<HalfInt(Int(slice.upperBound) + buffer.count)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as reasonably small.
         subscript(index: Index) -> UInt8 {
             get {
                 assert(index < HalfInt.max)
@@ -1043,12 +1001,12 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially forwarding.
         func bridgedReference() -> NSData {
             return storage.bridgedReference(self.range)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as reasonably small.
         mutating func resetBytes(in range: Range<Index>) {
             assert(range.lowerBound < HalfInt.max)
             assert(range.upperBound < HalfInt.max)
@@ -1060,7 +1018,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as reasonably small.
         mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer?, count cnt: Int) {
             precondition(startIndex <= subrange.lowerBound, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
             precondition(subrange.lowerBound <= endIndex, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
@@ -1075,7 +1033,7 @@
             slice = slice.lowerBound..<HalfInt(resultingUpper)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as reasonably small.
         func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
             precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
             precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
@@ -1084,79 +1042,90 @@
             storage.copyBytes(to: pointer, from: range)
         }
 
-        @inlinable
-        var hashValue: Int {
-            let hashRange = startIndex..<Swift.min(startIndex + 80, endIndex)
-            return storage.withUnsafeBytes(in: hashRange) {
-                return Int(bitPattern: CFHashBytes(UnsafeMutablePointer(mutating: $0.baseAddress?.assumingMemoryBound(to: UInt8.self)), $0.count))
+        @inline(__always) // This should always be inlined into _Representation.hash(into:).
+        func hash(into hasher: inout Hasher) {
+            hasher.combine(count)
+
+            // At most, hash the first 80 bytes of this data.
+            let range = startIndex ..< Swift.min(startIndex + 80, endIndex)
+            storage.withUnsafeBytes(in: range) {
+                hasher.combine(bytes: $0)
             }
         }
     }
 
+    // A reference wrapper around a Range<Int> for when the range of a data buffer is too large to whole in a single word.
+    // Inlinability strategy: everything should be inlinable as trivial.
     @usableFromInline
     @_fixed_layout
     internal final class RangeReference {
-        @usableFromInline
-        var range: Range<Int>
+        @usableFromInline var range: Range<Int>
 
-        @inlinable
-        var lowerBound: Int { return range.lowerBound }
+        @inlinable @inline(__always) // This is @inlinable as trivially forwarding.
+        var lowerBound: Int {
+            return range.lowerBound
+        }
 
-        @inlinable
-        var upperBound: Int { return range.upperBound }
+        @inlinable @inline(__always) // This is @inlinable as trivially forwarding.
+        var upperBound: Int {
+            return range.upperBound
+        }
 
-        @inlinable
-        var count: Int { return range.upperBound - range.lowerBound }
+        @inlinable @inline(__always) // This is @inlinable as trivially computable.
+        var count: Int {
+            return range.upperBound - range.lowerBound
+        }
 
-        @inlinable
+        @inlinable @inline(__always) // This is @inlinable as a trivial initializer.
         init(_ range: Range<Int>) {
             self.range = range
         }
     }
 
+    // A buffer of bytes whose range is too large to fit in a signle word. Used alongside a RangeReference to make it fit into _Representation's two-word size.
+    // Inlinability strategy: everything here should be easily inlinable as large _DataStorage methods should not inline into here.
     @usableFromInline
     @_fixed_layout
     internal struct LargeSlice {
         // ***WARNING***
         // These ivars are specifically laid out so that they cause the enum _Representation to be 16 bytes on 64 bit platforms. This means we _MUST_ have the class type thing last
-        @usableFromInline
-        var slice: RangeReference
-        @usableFromInline
-        var storage: _DataStorage
+        @usableFromInline var slice: RangeReference
+        @usableFromInline var storage: __DataStorage
 
-        @inlinable
+        @inlinable // This is @inlinable as a convenience initializer.
         init(_ buffer: UnsafeRawBufferPointer) {
-            self.init(_DataStorage(bytes: buffer.baseAddress, length: buffer.count), count: buffer.count)
+            self.init(__DataStorage(bytes: buffer.baseAddress, length: buffer.count), count: buffer.count)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a convenience initializer.
         init(capacity: Int) {
-            self.init(_DataStorage(capacity: capacity), count: 0)
+            self.init(__DataStorage(capacity: capacity), count: 0)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a convenience initializer.
         init(count: Int) {
-            self.init(_DataStorage(length: count), count: count)
+            self.init(__DataStorage(length: count), count: count)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a convenience initializer.
         init(_ inline: InlineData) {
-            self.init(inline.withUnsafeBytes { return _DataStorage(bytes: $0.baseAddress, length: $0.count) }, count: inline.count)
+            let storage = inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) }
+            self.init(storage, count: inline.count)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a trivial initializer.
         init(_ slice: InlineSlice) {
             self.storage = slice.storage
             self.slice = RangeReference(slice.range)
         }
 
-        @inlinable
-        init(_ storage: _DataStorage, count: Int) {
+        @inlinable // This is @inlinable as a trivial initializer.
+        init(_ storage: __DataStorage, count: Int) {
             self.storage = storage
-            slice = RangeReference(0..<count)
+            self.slice = RangeReference(0..<count)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic).
         mutating func ensureUniqueReference() {
             if !isKnownUniquelyReferenced(&storage) {
                 storage = storage.mutableCopy(range)
@@ -1166,25 +1135,29 @@
             }
         }
 
-        @inlinable
-        var startIndex: Int { return slice.range.lowerBound }
+        @inlinable // This is @inlinable as trivially forwarding.
+        var startIndex: Int {
+            return slice.range.lowerBound
+        }
 
-        @inlinable
-        var endIndex: Int { return slice.range.upperBound }
+        @inlinable // This is @inlinable as trivially forwarding.
+        var endIndex: Int {
+          return slice.range.upperBound
+        }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially forwarding.
         var capacity: Int {
             return storage.capacity
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially computable.
         mutating func reserveCapacity(_ minimumCapacity: Int) {
             ensureUniqueReference()
             // the current capacity can be zero (representing externally owned buffer), and count can be greater than the capacity
             storage.ensureUniqueBufferReference(growingTo: Swift.max(minimumCapacity, count))
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially computable.
         var count: Int {
             get {
                 return slice.count
@@ -1196,28 +1169,30 @@
             }
         }
 
-        @inlinable
-        var range: Range<Int> { return slice.range }
+        @inlinable // This is @inlinable as it is trivially forwarding.
+        var range: Range<Int> {
+            return slice.range
+        }
 
-        @inlinable
+        @inlinable // This is @inlinable as a generic, trivially forwarding function.
         func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
             return try storage.withUnsafeBytes(in: range, apply: apply)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a generic, trivially forwarding function.
         mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
             ensureUniqueReference()
             return try storage.withUnsafeMutableBytes(in: range, apply: apply)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as reasonably small.
         mutating func append(contentsOf buffer: UnsafeRawBufferPointer) {
             ensureUniqueReference()
             storage.replaceBytes(in: NSRange(location: range.upperBound, length: storage.length - (range.upperBound - storage._offset)), with: buffer.baseAddress, length: buffer.count)
             slice.range = slice.range.lowerBound..<slice.range.upperBound + buffer.count
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially computable.
         subscript(index: Index) -> UInt8 {
             get {
                 precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)")
@@ -1232,12 +1207,12 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially forwarding.
         func bridgedReference() -> NSData {
             return storage.bridgedReference(self.range)
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as reasonably small.
         mutating func resetBytes(in range: Range<Int>) {
             precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
             ensureUniqueReference()
@@ -1247,7 +1222,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as reasonably small.
         mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer?, count cnt: Int) {
             precondition(startIndex <= subrange.lowerBound, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
             precondition(subrange.lowerBound <= endIndex, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
@@ -1262,7 +1237,7 @@
             slice.range = slice.range.lowerBound..<resultingUpper
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as reasonably small.
         func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
             precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
             precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
@@ -1271,15 +1246,20 @@
             storage.copyBytes(to: pointer, from: range)
         }
 
-        @inlinable
-        var hashValue: Int {
-            let hashRange = startIndex..<Swift.min(startIndex + 80, endIndex)
-            return storage.withUnsafeBytes(in: hashRange) {
-                return Int(bitPattern: CFHashBytes(UnsafeMutablePointer(mutating: $0.baseAddress?.assumingMemoryBound(to: UInt8.self)), CFIndex($0.count)))
+        @inline(__always) // This should always be inlined into _Representation.hash(into:).
+        func hash(into hasher: inout Hasher) {
+            hasher.combine(count)
+
+            // Hash at most the first 80 bytes of this data.
+            let range = startIndex ..< Swift.min(startIndex + 80, endIndex)
+            storage.withUnsafeBytes(in: range) {
+                hasher.combine(bytes: $0)
             }
         }
     }
 
+    // The actual storage for Data's various representations.
+    // Inlinability strategy: almost everything should be inlinable as forwarding the underlying implementations. (Inlining can also help avoid retain-release traffic around pulling values out of enums.)
     @usableFromInline
     @_frozen
     internal enum _Representation {
@@ -1288,7 +1268,7 @@
         case slice(InlineSlice)
         case large(LargeSlice)
 
-        @inlinable
+        @inlinable // This is @inlinable as a trivial initializer.
         init(_ buffer: UnsafeRawBufferPointer) {
             if buffer.count == 0 {
                 self = .empty
@@ -1301,7 +1281,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a trivial initializer.
         init(_ buffer: UnsafeRawBufferPointer, owner: AnyObject) {
             if buffer.count == 0 {
                 self = .empty
@@ -1309,7 +1289,7 @@
                 self = .inline(InlineData(buffer))
             } else {
                 let count = buffer.count
-                let storage = _DataStorage(bytes: UnsafeMutableRawPointer(mutating: buffer.baseAddress), length: count, copy: false, deallocator: { _, _ in
+                let storage = __DataStorage(bytes: UnsafeMutableRawPointer(mutating: buffer.baseAddress), length: count, copy: false, deallocator: { _, _ in
                     _fixLifetime(owner)
                 }, offset: 0)
                 if InlineSlice.canStore(count: count) {
@@ -1320,7 +1300,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a trivial initializer.
         init(capacity: Int) {
             if capacity == 0 {
                 self = .empty
@@ -1333,7 +1313,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a trivial initializer.
         init(count: Int) {
             if count == 0 {
                 self = .empty
@@ -1346,8 +1326,8 @@
             }
         }
 
-        @inlinable
-        init(_ storage: _DataStorage, count: Int) {
+        @inlinable // This is @inlinable as a trivial initializer.
+        init(_ storage: __DataStorage, count: Int) {
             if count == 0 {
                 self = .empty
             } else if InlineData.canStore(count: count) {
@@ -1359,7 +1339,7 @@
             }
         }
 
-        @inlinable
+        @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
         mutating func reserveCapacity(_ minimumCapacity: Int) {
             guard minimumCapacity > 0 else { return }
             switch self {
@@ -1402,7 +1382,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as reasonably small.
         var count: Int {
             get {
                 switch self {
@@ -1413,6 +1393,8 @@
                 }
             }
             set(newValue) {
+                // HACK: The definition of this inline function takes an inout reference to self, giving the optimizer a unique referencing guarantee.
+                //       This allows us to avoid excessive retain-release traffic around modifying enum values, and inlining the function then avoids the additional frame.
                 @inline(__always)
                 func apply(_ representation: inout _Representation, _ newValue: Int) -> _Representation? {
                     switch representation {
@@ -1477,7 +1459,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a generic, trivially forwarding function.
         func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
             switch self {
             case .empty:
@@ -1492,7 +1474,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a generic, trivially forwarding function.
         mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
             switch self {
             case .empty:
@@ -1512,7 +1494,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as a generic, trivially forwarding function.
         func withInteriorPointerReference<T>(_ work: (NSData) throws -> T) rethrows -> T {
             switch self {
             case .empty:
@@ -1528,7 +1510,7 @@
             }
         }
 
-        @inlinable
+        @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
         func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) {
             switch self {
             case .empty:
@@ -1546,7 +1528,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as reasonably small.
         mutating func append(contentsOf buffer: UnsafeRawBufferPointer) {
             switch self {
             case .empty:
@@ -1582,7 +1564,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as reasonably small.
         mutating func resetBytes(in range: Range<Index>) {
             switch self {
             case .empty:
@@ -1600,7 +1582,6 @@
                 }
                 break
             case .inline(var inline):
-
                 if inline.count < range.upperBound {
                     if InlineSlice.canStore(count: range.upperBound) {
                         var slice = InlineSlice(inline)
@@ -1635,7 +1616,7 @@
             }
         }
 
-        @inlinable
+        @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
         mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer?, count cnt: Int) {
             switch self {
             case .empty:
@@ -1718,7 +1699,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially forwarding.
         subscript(index: Index) -> UInt8 {
             get {
                 switch self {
@@ -1746,7 +1727,7 @@
             }
         }
         
-        @inlinable
+        @inlinable // This is @inlinable as reasonably small.
         subscript(bounds: Range<Index>) -> Data {
             get {
                 switch self {
@@ -1796,7 +1777,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially forwarding.
         var startIndex: Int {
             switch self {
             case .empty: return 0
@@ -1806,7 +1787,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially forwarding.
         var endIndex: Int {
             switch self {
             case .empty: return 0
@@ -1816,7 +1797,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially forwarding.
         func bridgedReference() -> NSData {
             switch self {
             case .empty: return NSData()
@@ -1831,7 +1812,7 @@
             }
         }
 
-        @inlinable
+        @inlinable // This is @inlinable as trivially forwarding.
         func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
             switch self {
             case .empty:
@@ -1847,17 +1828,17 @@
             }
         }
         
-        @inlinable
-        var hashValue: Int {
+        @inline(__always) // This should always be inlined into Data.hash(into:).
+        func hash(into hasher: inout Hasher) {
             switch self {
             case .empty:
-                return Int(bitPattern: CFHashBytes(nil, 0))
+                hasher.combine(0)
             case .inline(let inline):
-                return inline.hashValue
+                inline.hash(into: &hasher)
             case .slice(let slice):
-                return slice.hashValue
-            case .large(let slice):
-                return slice.hashValue
+                slice.hash(into: &hasher)
+            case .large(let large):
+                large.hash(into: &hasher)
             }
         }
     }
@@ -1885,8 +1866,7 @@
         /// A custom deallocator.
         case custom((UnsafeMutableRawPointer, Int) -> Void)
         
-        @usableFromInline
-        internal var _deallocator : ((UnsafeMutableRawPointer, Int) -> Void) {
+        @usableFromInline internal var _deallocator : ((UnsafeMutableRawPointer, Int) -> Void) {
 #if DEPLOYMENT_RUNTIME_SWIFT
             switch self {
             case .unmap:
@@ -1922,7 +1902,7 @@
     ///
     /// - parameter bytes: A pointer to the memory. It will be copied.
     /// - parameter count: The number of bytes to copy.
-    @inlinable
+    @inlinable // This is @inlinable as a trivial initializer.
     public init(bytes: UnsafeRawPointer, count: Int) {
         _representation = _Representation(UnsafeRawBufferPointer(start: bytes, count: count))
     }
@@ -1930,7 +1910,7 @@
     /// Initialize a `Data` with copied memory content.
     ///
     /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`.
-    @inlinable
+    @inlinable // This is @inlinable as a trivial, generic initializer.
     public init<SourceType>(buffer: UnsafeBufferPointer<SourceType>) {
         _representation = _Representation(UnsafeRawBufferPointer(buffer))
     }
@@ -1938,7 +1918,7 @@
     /// Initialize a `Data` with copied memory content.
     ///
     /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`.
-    @inlinable
+    @inlinable // This is @inlinable as a trivial, generic initializer.
     public init<SourceType>(buffer: UnsafeMutableBufferPointer<SourceType>) {
         _representation = _Representation(UnsafeRawBufferPointer(buffer))
     }
@@ -1947,7 +1927,7 @@
     ///
     /// - parameter repeatedValue: A byte to initialize the pattern
     /// - parameter count: The number of bytes the data initially contains initialized to the repeatedValue
-    @inlinable
+    @inlinable // This is @inlinable as a convenience initializer.
     public init(repeating repeatedValue: UInt8, count: Int) {
         self.init(count: count)
         withUnsafeMutableBytes { (buffer: UnsafeMutableRawBufferPointer) -> Void in
@@ -1964,7 +1944,7 @@
     /// If the capacity specified in `capacity` is greater than four memory pages in size, this may round the amount of requested memory up to the nearest full page.
     ///
     /// - parameter capacity: The size of the data.
-    @inlinable
+    @inlinable // This is @inlinable as a trivial initializer.
     public init(capacity: Int) {
         _representation = _Representation(capacity: capacity)
     }
@@ -1972,13 +1952,13 @@
     /// Initialize a `Data` with the specified count of zeroed bytes.
     ///
     /// - parameter count: The number of bytes the data initially contains.
-    @inlinable
+    @inlinable // This is @inlinable as a trivial initializer.
     public init(count: Int) {
         _representation = _Representation(count: count)
     }
     
     /// Initialize an empty `Data`.
-    @inlinable
+    @inlinable // This is @inlinable as a trivial initializer.
     public init() {
         _representation = .empty
     }
@@ -1990,14 +1970,14 @@
     /// - parameter bytes: A pointer to the bytes.
     /// - parameter count: The size of the bytes.
     /// - parameter deallocator: Specifies the mechanism to free the indicated buffer, or `.none`.
-    @inlinable
+    @inlinable // This is @inlinable as a trivial initializer.
     public init(bytesNoCopy bytes: UnsafeMutableRawPointer, count: Int, deallocator: Deallocator) {
         let whichDeallocator = deallocator._deallocator
         if count == 0 {
             deallocator._deallocator(bytes, count)
             _representation = .empty
         } else {
-            _representation = _Representation(_DataStorage(bytes: bytes, length: count, copy: false, deallocator: whichDeallocator, offset: 0), count: count)
+            _representation = _Representation(__DataStorage(bytes: bytes, length: count, copy: false, deallocator: whichDeallocator, offset: 0), count: count)
         }
     }
     
@@ -2006,7 +1986,7 @@
     /// - parameter url: The `URL` to read.
     /// - parameter options: Options for the read operation. Default value is `[]`.
     /// - throws: An error in the Cocoa domain, if `url` cannot be read.
-    @inlinable
+    @inlinable // This is @inlinable as a convenience initializer.
     public init(contentsOf url: __shared URL, options: Data.ReadingOptions = []) throws {
         let d = try NSData(contentsOf: url, options: ReadingOptions(rawValue: options.rawValue))
         self.init(bytes: d.bytes, count: d.length)
@@ -2017,7 +1997,7 @@
     /// Returns nil when the input is not recognized as valid Base-64.
     /// - parameter base64String: The string to parse.
     /// - parameter options: Encoding options. Default value is `[]`.
-    @inlinable
+    @inlinable // This is @inlinable as a convenience initializer.
     public init?(base64Encoded base64String: __shared String, options: Data.Base64DecodingOptions = []) {
         if let d = NSData(base64Encoded: base64String, options: Base64DecodingOptions(rawValue: options.rawValue)) {
             self.init(bytes: d.bytes, count: d.length)
@@ -2032,7 +2012,7 @@
     ///
     /// - parameter base64Data: Base-64, UTF-8 encoded input data.
     /// - parameter options: Decoding options. Default value is `[]`.
-    @inlinable
+    @inlinable // This is @inlinable as a convenience initializer.
     public init?(base64Encoded base64Data: __shared Data, options: Data.Base64DecodingOptions = []) {
         if let d = NSData(base64Encoded: base64Data, options: Base64DecodingOptions(rawValue: options.rawValue)) {
             self.init(bytes: d.bytes, count: d.length)
@@ -2060,17 +2040,16 @@
             let providesConcreteBacking = (reference as AnyObject)._providesConcreteBacking?() ?? false
 #endif
             if providesConcreteBacking {
-                _representation = _Representation(_DataStorage(immutableReference: reference.copy() as! NSData, offset: 0), count: length)
+                _representation = _Representation(__DataStorage(immutableReference: reference.copy() as! NSData, offset: 0), count: length)
             } else {
-                _representation = _Representation(_DataStorage(customReference: reference.copy() as! NSData, offset: 0), count: length)
+                _representation = _Representation(__DataStorage(customReference: reference.copy() as! NSData, offset: 0), count: length)
             }
         }
         
     }
     
     // slightly faster paths for common sequences
-    @inlinable
-    @inline(__always)
+    @inlinable // This is @inlinable as an important generic funnel point, despite being a non-trivial initializer.
     public init<S: Sequence>(_ elements: S) where S.Element == UInt8 {
         // If the sequence is already contiguous, access the underlying raw memory directly.
         if let contiguous = elements as? ContiguousBytes {
@@ -2102,12 +2081,22 @@
                 // Copy the contents of buffer...
                 _representation = _Representation(UnsafeRawBufferPointer(start: base, count: endIndex))
 
-                // ... and append the rest byte-wise.
+                // ... and append the rest byte-wise, buffering through an InlineData.
+                var buffer = InlineData()
                 while let element = iter.next() {
-                    Swift.withUnsafeBytes(of: element) {
-                        _representation.append(contentsOf: $0)
+                    if buffer.count < buffer.capacity {
+                        buffer.append(byte: element)
+                    } else {
+                        buffer.withUnsafeBytes { _representation.append(contentsOf: $0) }
+                        buffer.count = 0
                     }
                 }
+
+                // If we've still got bytes left in the buffer (i.e. the loop ended before we filled up the buffer and cleared it out), append them.
+                if buffer.count > 0 {
+                    buffer.withUnsafeBytes { _representation.append(contentsOf: $0) }
+                    buffer.count = 0
+                }
             }
         }
     }
@@ -2128,7 +2117,7 @@
        self.init(bytes)
     }
     
-    @inlinable
+    @inlinable // This is @inlinable as a trivial initializer.
     internal init(representation: _Representation) {
         _representation = representation
     }
@@ -2136,13 +2125,13 @@
     // -----------------------------------
     // MARK: - Properties and Functions
 
-    @inlinable
+    @inlinable // This is @inlinable as trivially forwarding.
     public mutating func reserveCapacity(_ minimumCapacity: Int) {
         _representation.reserveCapacity(minimumCapacity)
     }
     
     /// The number of bytes in the data.
-    @inlinable
+    @inlinable // This is @inlinable as trivially forwarding.
     public var count: Int {
         get {
             return _representation.count
@@ -2153,7 +2142,7 @@
         }
     }
 
-    @inlinable
+    @inlinable // This is @inlinable as trivially computable.
     public var regions: CollectionOfOne<Data> {
         return CollectionOfOne(self)
     }
@@ -2168,7 +2157,7 @@
         }
     }
     
-    @inlinable
+    @inlinable // This is @inlinable as a generic, trivially forwarding function.
     public func withUnsafeBytes<ResultType>(_ body: (UnsafeRawBufferPointer) throws -> ResultType) rethrows -> ResultType {
         return try _representation.withUnsafeBytes(body)
     }
@@ -2184,7 +2173,7 @@
         }
     }
 
-    @inlinable
+    @inlinable // This is @inlinable as a generic, trivially forwarding function.
     public mutating func withUnsafeMutableBytes<ResultType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ResultType) rethrows -> ResultType {
         return try _representation.withUnsafeMutableBytes(body)
     }
@@ -2197,14 +2186,14 @@
     /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into.
     /// - parameter count: The number of bytes to copy.
     /// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes.
-    @inlinable
+    @inlinable // This is @inlinable as trivially forwarding.
     public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) {
         precondition(count >= 0, "count of bytes to copy must not be negative")
         if count == 0 { return }
         _copyBytesHelper(to: UnsafeMutableRawPointer(pointer), from: startIndex..<(startIndex + count))
     }
     
-    @inlinable
+    @inlinable // This is @inlinable as trivially forwarding.
     internal func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
         if range.isEmpty { return }
         _representation.copyBytes(to: pointer, from: range)
@@ -2215,7 +2204,7 @@
     /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into.
     /// - parameter range: The range in the `Data` to copy.
     /// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes.
-    @inlinable
+    @inlinable // This is @inlinable as trivially forwarding.
     public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: Range<Index>) {
         _copyBytesHelper(to: pointer, from: range)
     }
@@ -2227,7 +2216,7 @@
     /// - parameter buffer: A buffer to copy the data into.
     /// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied.
     /// - returns: Number of bytes copied into the destination buffer.
-    @inlinable
+    @inlinable // This is @inlinable as generic and reasonably small.
     public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: Range<Index>? = nil) -> Int {
         let cnt = count
         guard cnt > 0 else { return 0 }
@@ -2293,7 +2282,6 @@
     /// - parameter range: The range of this data in which to perform the search. Default value is `nil`, which means the entire content of this data.
     /// - returns: A `Range` specifying the location of the found data, or nil if a match could not be found.
     /// - precondition: `range` must be in the bounds of the Data.
-    @inlinable
     public func range(of dataToFind: Data, options: Data.SearchOptions = [], in range: Range<Index>? = nil) -> Range<Index>? {
         let nsRange : NSRange
         if let r = range {
@@ -2319,19 +2307,18 @@
         _representation.enumerateBytes(block)
     }
 
-    @inlinable
+    @inlinable // This is @inlinable as a generic, trivially forwarding function.
     internal mutating func _append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) {
         if buffer.isEmpty { return }
         _representation.append(contentsOf: UnsafeRawBufferPointer(buffer))
     }
     
-    @inlinable
+    @inlinable // This is @inlinable as a generic, trivially forwarding function.
     public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) {
         if count == 0 { return }
         _append(UnsafeBufferPointer(start: bytes, count: count))
     }
     
-    @inlinable
     public mutating func append(_ other: Data) {
         guard other.count > 0 else { return }
         other.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
@@ -2342,19 +2329,19 @@
     /// Append a buffer of bytes to the data.
     ///
     /// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`.
-    @inlinable
+    @inlinable // This is @inlinable as a generic, trivially forwarding function.
     public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) {
         _append(buffer)
     }
 
-    @inlinable
+    @inlinable // This is @inlinable as trivially forwarding.
     public mutating func append(contentsOf bytes: [UInt8]) {
         bytes.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) -> Void in
             _append(buffer)
         }
     }
 
-    @inlinable
+    @inlinable // This is @inlinable as an important generic funnel point, despite being non-trivial.
     public mutating func append<S: Sequence>(contentsOf elements: S) where S.Element == Element {
         // If the sequence is already contiguous, access the underlying raw memory directly.
         if let contiguous = elements as? ContiguousBytes {
@@ -2388,12 +2375,22 @@
             // Copy the contents of the buffer...
             _representation.append(contentsOf: UnsafeRawBufferPointer(start: base, count: endIndex))
 
-            /// ... and append the rest byte-wise.
+            // ... and append the rest byte-wise, buffering through an InlineData.
+            var buffer = InlineData()
             while let element = iter.next() {
-                Swift.withUnsafeBytes(of: element) {
-                    _representation.append(contentsOf: $0)
+                if buffer.count < buffer.capacity {
+                    buffer.append(byte: element)
+                } else {
+                    buffer.withUnsafeBytes { _representation.append(contentsOf: $0) }
+                    buffer.count = 0
                 }
             }
+
+            // If we've still got bytes left in the buffer (i.e. the loop ended before we filled up the buffer and cleared it out), append them.
+            if buffer.count > 0 {
+                buffer.withUnsafeBytes { _representation.append(contentsOf: $0) }
+                buffer.count = 0
+            }
         }
     }
     
@@ -2403,7 +2400,7 @@
     ///
     /// If `range` exceeds the bounds of the data, then the data is resized to fit.
     /// - parameter range: The range in the data to set to `0`.
-    @inlinable
+    @inlinable // This is @inlinable as trivially forwarding.
     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 not be negative bounds")
@@ -2418,7 +2415,7 @@
     /// - precondition: The bounds of `subrange` must be valid indices of the collection.
     /// - parameter subrange: The range in the data to replace. If `subrange.lowerBound == data.count && subrange.count == 0` then this operation is an append.
     /// - parameter data: The replacement data.
-    @inlinable
+    @inlinable // This is @inlinable as trivially forwarding.
     public mutating func replaceSubrange(_ subrange: Range<Index>, with data: Data) {
         data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
             _representation.replaceSubrange(subrange, with: buffer.baseAddress, count: buffer.count)
@@ -2432,7 +2429,7 @@
     /// - precondition: The bounds of `subrange` must be valid indices of the collection.
     /// - parameter subrange: The range in the data to replace.
     /// - parameter buffer: The replacement bytes.
-    @inlinable
+    @inlinable // This is @inlinable as a generic, trivially forwarding function.
     public mutating func replaceSubrange<SourceType>(_ subrange: Range<Index>, with buffer: UnsafeBufferPointer<SourceType>) {
         guard !buffer.isEmpty  else { return }
         replaceSubrange(subrange, with: buffer.baseAddress!, count: buffer.count * MemoryLayout<SourceType>.stride)
@@ -2445,7 +2442,7 @@
     /// - precondition: The bounds of `subrange` must be valid indices of the collection.
     /// - parameter subrange: The range in the data to replace.
     /// - parameter newElements: The replacement bytes.
-    @inlinable
+    @inlinable // This is @inlinable as generic and reasonably small.
     public mutating func replaceSubrange<ByteCollection : Collection>(_ subrange: Range<Index>, with newElements: ByteCollection) where ByteCollection.Iterator.Element == Data.Iterator.Element {
         let totalCount = Int(newElements.count)
         _withStackOrHeapBuffer(totalCount) { conditionalBuffer in
@@ -2459,7 +2456,7 @@
         }
     }
     
-    @inlinable
+    @inlinable // This is @inlinable as trivially forwarding.
     public mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer, count cnt: Int) {
         _representation.replaceSubrange(subrange, with: bytes, count: cnt)
     }
@@ -2467,7 +2464,6 @@
     /// Return a new copy of the data in a specified range.
     ///
     /// - parameter range: The range to copy.
-    @inlinable
     public func subdata(in range: Range<Index>) -> Data {
         if isEmpty || range.upperBound - range.lowerBound == 0 {
             return Data()
@@ -2486,7 +2482,7 @@
     ///
     /// - parameter options: The options to use for the encoding. Default value is `[]`.
     /// - returns: The Base-64 encoded string.
-    @inlinable
+    @inlinable // This is @inlinable as trivially forwarding.
     public func base64EncodedString(options: Data.Base64EncodingOptions = []) -> String {
         return _representation.withInteriorPointerReference {
             return $0.base64EncodedString(options: options)
@@ -2497,7 +2493,7 @@
     ///
     /// - parameter options: The options to use for the encoding. Default value is `[]`.
     /// - returns: The Base-64 encoded data.
-    @inlinable
+    @inlinable // This is @inlinable as trivially forwarding.
     public func base64EncodedData(options: Data.Base64EncodingOptions = []) -> Data {
         return _representation.withInteriorPointerReference {
             return $0.base64EncodedData(options: options)
@@ -2508,12 +2504,11 @@
     //
     
     /// The hash value for the data.
-    @inlinable
-    public var hashValue: Int {
-        return _representation.hashValue
+    @inline(never) // This is not inlinable as emission into clients could cause cross-module inconsistencies if they are not all recompiled together.
+    public func hash(into hasher: inout Hasher) {
+        _representation.hash(into: &hasher)
     }
     
-    @inlinable
     public func advanced(by amount: Int) -> Data {
         let length = count - amount
         precondition(length > 0)
@@ -2528,7 +2523,7 @@
     // MARK: Index and Subscript
     
     /// Sets or returns the byte at the specified index.
-    @inlinable
+    @inlinable // This is @inlinable as trivially forwarding.
     public subscript(index: Index) -> UInt8 {
         get {
             return _representation[index]
@@ -2538,7 +2533,7 @@
         }
     }
     
-    @inlinable
+    @inlinable // This is @inlinable as trivially forwarding.
     public subscript(bounds: Range<Index>) -> Data {
         get {
             return _representation[bounds]
@@ -2548,7 +2543,7 @@
         }
     }
     
-    @inlinable
+    @inlinable // This is @inlinable as a generic, trivially forwarding function.
     public subscript<R: RangeExpression>(_ rangeExpression: R) -> Data
         where R.Bound: FixedWidthInteger {
         get {
@@ -2572,7 +2567,7 @@
     }
     
     /// The start `Index` in the data.
-    @inlinable
+    @inlinable // This is @inlinable as trivially forwarding.
     public var startIndex: Index {
         get {
             return _representation.startIndex
@@ -2582,31 +2577,31 @@
     /// The end `Index` into the data.
     ///
     /// This is the "one-past-the-end" position, and will always be equal to the `count`.
-    @inlinable
+    @inlinable // This is @inlinable as trivially forwarding.
     public var endIndex: Index {
         get {
             return _representation.endIndex
         }
     }
     
-    @inlinable
+    @inlinable // This is @inlinable as trivially computable.
     public func index(before i: Index) -> Index {
         return i - 1
     }
     
-    @inlinable
+    @inlinable // This is @inlinable as trivially computable.
     public func index(after i: Index) -> Index {
         return i + 1
     }
     
-    @inlinable
+    @inlinable // This is @inlinable as trivially computable.
     public var indices: Range<Int> {
         get {
             return startIndex..<endIndex
         }
     }
     
-    @inlinable
+    @inlinable // This is @inlinable as a fast-path for emitting into generic Sequence usages.
     public func _copyContents(initializing buffer: UnsafeMutableBufferPointer<UInt8>) -> (Iterator, UnsafeMutableBufferPointer<UInt8>.Index) {
         guard !isEmpty else { return (makeIterator(), buffer.startIndex) }
         let cnt = Swift.min(count, buffer.count)
@@ -2621,7 +2616,7 @@
     /// An iterator over the contents of the data.
     ///
     /// The iterator will increment byte-by-byte.
-    @inlinable
+    @inlinable // This is @inlinable as trivially computable.
     public func makeIterator() -> Data.Iterator {
         return Iterator(self, at: startIndex)
     }
@@ -2639,7 +2634,7 @@
         @usableFromInline internal var _idx: Data.Index
         @usableFromInline internal let _endIdx: Data.Index
         
-        @usableFromInline
+        @usableFromInline // This is @usableFromInline as a non-trivial initializer.
         internal init(_ data: Data, at loc: Data.Index) {
             // The let vars prevent this from being marked as @inlinable
             _data = data
@@ -2655,7 +2650,6 @@
             }
         }
         
-        @inlinable
         public mutating func next() -> UInt8? {
             let idx = _idx
             let bufferSize = MemoryLayout<Buffer>.size
@@ -2699,7 +2693,7 @@
     public var mutableBytes: UnsafeMutableRawPointer { fatalError() }
     
     /// Returns `true` if the two `Data` arguments are equal.
-    @inlinable
+    @inlinable // This is @inlinable as emission into clients is safe -- the concept of equality on Data will not change.
     public static func ==(d1 : Data, d2 : Data) -> Bool {
         let length1 = d1.count
         if length1 != d2.count {
diff --git a/stdlib/public/SDK/Foundation/JSONEncoder.swift b/stdlib/public/SDK/Foundation/JSONEncoder.swift
index 8f90826..d871160 100644
--- a/stdlib/public/SDK/Foundation/JSONEncoder.swift
+++ b/stdlib/public/SDK/Foundation/JSONEncoder.swift
@@ -51,6 +51,11 @@
 //===----------------------------------------------------------------------===//
 
 /// `JSONEncoder` facilitates the encoding of `Encodable` values into JSON.
+// NOTE: older overlays had Foundation.JSONEncoder as the ObjC name.
+// The two must coexist, so it was renamed. The old name must not be
+// used in the new runtime. _TtC10Foundation13__JSONEncoder is the
+// mangled name for Foundation.__JSONEncoder.
+@_objcRuntimeName(_TtC10Foundation13__JSONEncoder)
 open class JSONEncoder {
     // MARK: Options
 
@@ -245,7 +250,7 @@
     /// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`.
     /// - throws: An error if any value throws an error during encoding.
     open func encode<T : Encodable>(_ value: T) throws -> Data {
-        let encoder = _JSONEncoder(options: self.options)
+        let encoder = __JSONEncoder(options: self.options)
 
         guard let topLevel = try encoder.box_(value) else {
             throw EncodingError.invalidValue(value, 
@@ -273,9 +278,12 @@
     }
 }
 
-// MARK: - _JSONEncoder
+// MARK: - __JSONEncoder
 
-fileprivate class _JSONEncoder : Encoder {
+// NOTE: older overlays called this class _JSONEncoder.
+// The two must coexist without a conflicting ObjC class name, so it
+// was renamed. The old name must not be used in the new runtime.
+fileprivate class __JSONEncoder : Encoder {
     // MARK: Properties
 
     /// The encoder's storage.
@@ -405,7 +413,7 @@
     // MARK: Properties
 
     /// A reference to the encoder we're writing to.
-    private let encoder: _JSONEncoder
+    private let encoder: __JSONEncoder
 
     /// A reference to the container we're writing to.
     private let container: NSMutableDictionary
@@ -416,7 +424,7 @@
     // MARK: - Initialization
 
     /// Initializes `self` with the given references.
-    fileprivate init(referencing encoder: _JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableDictionary) {
+    fileprivate init(referencing encoder: __JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableDictionary) {
         self.encoder = encoder
         self.codingPath = codingPath
         self.container = container
@@ -519,11 +527,11 @@
     }
 
     public mutating func superEncoder() -> Encoder {
-        return _JSONReferencingEncoder(referencing: self.encoder, key: _JSONKey.super, convertedKey: _converted(_JSONKey.super), wrapping: self.container)
+        return __JSONReferencingEncoder(referencing: self.encoder, key: _JSONKey.super, convertedKey: _converted(_JSONKey.super), wrapping: self.container)
     }
 
     public mutating func superEncoder(forKey key: Key) -> Encoder {
-        return _JSONReferencingEncoder(referencing: self.encoder, key: key, convertedKey: _converted(key), wrapping: self.container)
+        return __JSONReferencingEncoder(referencing: self.encoder, key: key, convertedKey: _converted(key), wrapping: self.container)
     }
 }
 
@@ -531,7 +539,7 @@
     // MARK: Properties
 
     /// A reference to the encoder we're writing to.
-    private let encoder: _JSONEncoder
+    private let encoder: __JSONEncoder
 
     /// A reference to the container we're writing to.
     private let container: NSMutableArray
@@ -547,7 +555,7 @@
     // MARK: - Initialization
 
     /// Initializes `self` with the given references.
-    fileprivate init(referencing encoder: _JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableArray) {
+    fileprivate init(referencing encoder: __JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableArray) {
         self.encoder = encoder
         self.codingPath = codingPath
         self.container = container
@@ -610,11 +618,11 @@
     }
 
     public mutating func superEncoder() -> Encoder {
-        return _JSONReferencingEncoder(referencing: self.encoder, at: self.container.count, wrapping: self.container)
+        return __JSONReferencingEncoder(referencing: self.encoder, at: self.container.count, wrapping: self.container)
     }
 }
 
-extension _JSONEncoder : SingleValueEncodingContainer {
+extension __JSONEncoder : SingleValueEncodingContainer {
     // MARK: - SingleValueEncodingContainer Methods
 
     fileprivate func assertCanEncodeNewValue() {
@@ -704,7 +712,7 @@
 
 // MARK: - Concrete Value Representations
 
-extension _JSONEncoder {
+extension __JSONEncoder {
     /// Returns the given value boxed in a container appropriate for pushing onto the container stack.
     fileprivate func box(_ value: Bool)   -> NSObject { return NSNumber(value: value) }
     fileprivate func box(_ value: Int)    -> NSObject { return NSNumber(value: value) }
@@ -902,7 +910,7 @@
             return try self.box(value as! [String : Encodable])
         }
 
-        // The value should request a container from the _JSONEncoder.
+        // The value should request a container from the __JSONEncoder.
         let depth = self.storage.count
         do {
             try value.encode(to: self)
@@ -924,11 +932,14 @@
     }
 }
 
-// MARK: - _JSONReferencingEncoder
+// MARK: - __JSONReferencingEncoder
 
-/// _JSONReferencingEncoder is a special subclass of _JSONEncoder which has its own storage, but references the contents of a different encoder.
+/// __JSONReferencingEncoder is a special subclass of __JSONEncoder which has its own storage, but references the contents of a different encoder.
 /// It's used in superEncoder(), which returns a new encoder for encoding a superclass -- the lifetime of the encoder should not escape the scope it's created in, but it doesn't necessarily know when it's done being used (to write to the original container).
-fileprivate class _JSONReferencingEncoder : _JSONEncoder {
+// NOTE: older overlays called this class _JSONReferencingEncoder.
+// The two must coexist without a conflicting ObjC class name, so it
+// was renamed. The old name must not be used in the new runtime.
+fileprivate class __JSONReferencingEncoder : __JSONEncoder {
     // MARK: Reference types.
 
     /// The type of container we're referencing.
@@ -943,7 +954,7 @@
     // MARK: - Properties
 
     /// The encoder we're referencing.
-    fileprivate let encoder: _JSONEncoder
+    fileprivate let encoder: __JSONEncoder
 
     /// The container reference itself.
     private let reference: Reference
@@ -951,7 +962,7 @@
     // MARK: - Initialization
 
     /// Initializes `self` by referencing the given array container in the given encoder.
-    fileprivate init(referencing encoder: _JSONEncoder, at index: Int, wrapping array: NSMutableArray) {
+    fileprivate init(referencing encoder: __JSONEncoder, at index: Int, wrapping array: NSMutableArray) {
         self.encoder = encoder
         self.reference = .array(array, index)
         super.init(options: encoder.options, codingPath: encoder.codingPath)
@@ -960,7 +971,7 @@
     }
 
     /// Initializes `self` by referencing the given dictionary container in the given encoder.
-    fileprivate init(referencing encoder: _JSONEncoder,
+    fileprivate init(referencing encoder: __JSONEncoder,
                      key: CodingKey, convertedKey: __shared CodingKey, wrapping dictionary: NSMutableDictionary) {
         self.encoder = encoder
         self.reference = .dictionary(dictionary, convertedKey.stringValue)
@@ -1004,6 +1015,11 @@
 //===----------------------------------------------------------------------===//
 
 /// `JSONDecoder` facilitates the decoding of JSON into semantic `Decodable` types.
+// NOTE: older overlays had Foundation.JSONDecoder as the ObjC name.
+// The two must coexist, so it was renamed. The old name must not be
+// used in the new runtime. _TtC10Foundation13__JSONDecoder is the
+// mangled name for Foundation.__JSONDecoder.
+@_objcRuntimeName(_TtC10Foundation13__JSONDecoder)
 open class JSONDecoder {
     // MARK: Options
 
@@ -1174,7 +1190,7 @@
             throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: error))
         }
 
-        let decoder = _JSONDecoder(referencing: topLevel, options: self.options)
+        let decoder = __JSONDecoder(referencing: topLevel, options: self.options)
         guard let value = try decoder.unbox(topLevel, as: type) else {
             throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value."))
         }
@@ -1183,9 +1199,12 @@
     }
 }
 
-// MARK: - _JSONDecoder
+// MARK: - __JSONDecoder
 
-fileprivate class _JSONDecoder : Decoder {
+// NOTE: older overlays called this class _JSONDecoder. The two must
+// coexist without a conflicting ObjC class name, so it was renamed.
+// The old name must not be used in the new runtime.
+fileprivate class __JSONDecoder : Decoder {
     // MARK: Properties
 
     /// The decoder's storage.
@@ -1291,7 +1310,7 @@
     // MARK: Properties
 
     /// A reference to the decoder we're reading from.
-    private let decoder: _JSONDecoder
+    private let decoder: __JSONDecoder
 
     /// A reference to the container we're reading from.
     private let container: [String : Any]
@@ -1302,7 +1321,7 @@
     // MARK: - Initialization
 
     /// Initializes `self` by referencing the given decoder and container.
-    fileprivate init(referencing decoder: _JSONDecoder, wrapping container: [String : Any]) {
+    fileprivate init(referencing decoder: __JSONDecoder, wrapping container: [String : Any]) {
         self.decoder = decoder
         switch decoder.options.keyDecodingStrategy {
         case .useDefaultKeys:
@@ -1621,7 +1640,7 @@
         defer { self.decoder.codingPath.removeLast() }
 
         let value: Any = self.container[key.stringValue] ?? NSNull()
-        return _JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
+        return __JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
     }
 
     public func superDecoder() throws -> Decoder {
@@ -1637,7 +1656,7 @@
     // MARK: Properties
 
     /// A reference to the decoder we're reading from.
-    private let decoder: _JSONDecoder
+    private let decoder: __JSONDecoder
 
     /// A reference to the container we're reading from.
     private let container: [Any]
@@ -1651,7 +1670,7 @@
     // MARK: - Initialization
 
     /// Initializes `self` by referencing the given decoder and container.
-    fileprivate init(referencing decoder: _JSONDecoder, wrapping container: [Any]) {
+    fileprivate init(referencing decoder: __JSONDecoder, wrapping container: [Any]) {
         self.decoder = decoder
         self.container = container
         self.codingPath = decoder.codingPath
@@ -1984,11 +2003,11 @@
 
         let value = self.container[self.currentIndex]
         self.currentIndex += 1
-        return _JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
+        return __JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
     }
 }
 
-extension _JSONDecoder : SingleValueDecodingContainer {
+extension __JSONDecoder : SingleValueDecodingContainer {
     // MARK: SingleValueDecodingContainer Methods
 
     private func expectNonNull<T>(_ type: T.Type) throws {
@@ -2079,7 +2098,7 @@
 
 // MARK: - Concrete Value Representations
 
-extension _JSONDecoder {
+extension __JSONDecoder {
     /// Returns the given value unboxed from a container.
     fileprivate func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? {
         guard !(value is NSNull) else { return nil }
diff --git a/stdlib/public/SDK/Foundation/NSDictionary.swift b/stdlib/public/SDK/Foundation/NSDictionary.swift
index 2155e41..e276870 100644
--- a/stdlib/public/SDK/Foundation/NSDictionary.swift
+++ b/stdlib/public/SDK/Foundation/NSDictionary.swift
@@ -147,6 +147,11 @@
 extension NSDictionary : Sequence {
   // FIXME: A class because we can't pass a struct with class fields through an
   // [objc] interface without prematurely destroying the references.
+  // NOTE: older runtimes had
+  // _TtCE10FoundationCSo12NSDictionary8Iterator as the ObjC name. The
+  // two must coexist, so it was renamed. The old name must not be used
+  // in the new runtime.
+  @_objcRuntimeName(_TtCE10FoundationCSo12NSDictionary9_Iterator)
   final public class Iterator : IteratorProtocol {
     var _fastIterator: NSFastEnumerationIterator
     var _dictionary: NSDictionary {
diff --git a/stdlib/public/SDK/Foundation/NSError.swift b/stdlib/public/SDK/Foundation/NSError.swift
index 6c4c212..57a2385 100644
--- a/stdlib/public/SDK/Foundation/NSError.swift
+++ b/stdlib/public/SDK/Foundation/NSError.swift
@@ -74,7 +74,10 @@
 /// Class that implements the informal protocol
 /// NSErrorRecoveryAttempting, which is used by NSError when it
 /// attempts recovery from an error.
-class _NSErrorRecoveryAttempter {
+// NOTE: older overlays called this class _NSErrorRecoveryAttempter.
+// The two must coexist without a conflicting ObjC class name, so it
+// was renamed. The old name must not be used in the new runtime.
+class __NSErrorRecoveryAttempter {
   @objc(attemptRecoveryFromError:optionIndex:delegate:didRecoverSelector:contextInfo:)
   func attemptRecovery(fromError nsError: NSError,
                        optionIndex recoveryOptionIndex: Int,
@@ -252,7 +255,7 @@
 
           case NSRecoveryAttempterErrorKey:
             if error is RecoverableError {
-              return _NSErrorRecoveryAttempter()
+              return __NSErrorRecoveryAttempter()
             }
             return nil
 
@@ -308,7 +311,7 @@
      let recoverableError = error as? RecoverableError {
     result[NSLocalizedRecoveryOptionsErrorKey] =
       recoverableError.recoveryOptions
-    result[NSRecoveryAttempterErrorKey] = _NSErrorRecoveryAttempter()
+    result[NSRecoveryAttempterErrorKey] = __NSErrorRecoveryAttempter()
   }
 
   return result as AnyObject
diff --git a/stdlib/public/SDK/Foundation/NSStringAPI.swift b/stdlib/public/SDK/Foundation/NSStringAPI.swift
index 938f440..4aae381 100644
--- a/stdlib/public/SDK/Foundation/NSStringAPI.swift
+++ b/stdlib/public/SDK/Foundation/NSStringAPI.swift
@@ -178,6 +178,10 @@
   /// Creates a string by copying the data from a given
   /// C array of UTF8-encoded bytes.
   public init?(utf8String bytes: UnsafePointer<CChar>) {
+    if let str = String(validatingUTF8: bytes) {
+      self = str
+      return
+    }
     if let ns = NSString(utf8String: bytes) {
       self = String._unconditionallyBridgeFromObjectiveC(ns)
     } else {
@@ -202,12 +206,18 @@
   /// - Parameters:
   ///   - bytes: A sequence of bytes to interpret using `encoding`.
   ///   - encoding: The ecoding to use to interpret `bytes`.
-  public init? <S: Sequence>(bytes: __shared S, encoding: Encoding)
-    where S.Iterator.Element == UInt8 {
+  public init?<S: Sequence>(bytes: __shared S, encoding: Encoding)
+  where S.Iterator.Element == UInt8 {
     let byteArray = Array(bytes)
+    if encoding == .utf8,
+       let str = byteArray.withUnsafeBufferPointer({ String._tryFromUTF8($0) })
+    {
+      self = str
+      return
+    }
+
     if let ns = NSString(
       bytes: byteArray, length: byteArray.count, encoding: encoding.rawValue) {
-
       self = String._unconditionallyBridgeFromObjectiveC(ns)
     } else {
       return nil
@@ -365,6 +375,10 @@
     cString: UnsafePointer<CChar>,
     encoding enc: Encoding
   ) {
+    if enc == .utf8, let str = String(validatingUTF8: cString) {
+      self = str
+      return
+    }
     if let ns = NSString(cString: cString, encoding: enc.rawValue) {
       self = String._unconditionallyBridgeFromObjectiveC(ns)
     } else {
@@ -381,6 +395,14 @@
   /// Returns a `String` initialized by converting given `data` into
   /// Unicode characters using a given `encoding`.
   public init?(data: __shared Data, encoding: Encoding) {
+    if encoding == .utf8,
+       let str = data.withUnsafeBytes({
+         String._tryFromUTF8($0.bindMemory(to: UInt8.self))
+    }) {
+      self = str
+      return
+    }
+
     guard let s = NSString(data: data, encoding: encoding.rawValue) else { return nil }
     self = String._unconditionallyBridgeFromObjectiveC(s)
   }
diff --git a/stdlib/public/SDK/Foundation/PlistEncoder.swift b/stdlib/public/SDK/Foundation/PlistEncoder.swift
index 151f275..8480c85 100644
--- a/stdlib/public/SDK/Foundation/PlistEncoder.swift
+++ b/stdlib/public/SDK/Foundation/PlistEncoder.swift
@@ -15,6 +15,11 @@
 //===----------------------------------------------------------------------===//
 
 /// `PropertyListEncoder` facilitates the encoding of `Encodable` values into property lists.
+// NOTE: older overlays had Foundation.PropertyListEncoder as the ObjC
+// name. The two must coexist, so it was renamed. The old name must not
+// be used in the new runtime. _TtC10Foundation20_PropertyListEncoder
+// is the mangled name for Foundation._PropertyListEncoder.
+@_objcRuntimeName(_TtC10Foundation20_PropertyListEncoder)
 open class PropertyListEncoder {
 
     // MARK: - Options
@@ -80,7 +85,7 @@
     /// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`.
     /// - throws: An error if any value throws an error during encoding.
     internal func encodeToTopLevelContainer<Value : Encodable>(_ value: Value) throws -> Any {
-        let encoder = _PlistEncoder(options: self.options)
+        let encoder = __PlistEncoder(options: self.options)
         guard let topLevel = try encoder.box_(value) else {
             throw EncodingError.invalidValue(value,
                                              EncodingError.Context(codingPath: [],
@@ -91,9 +96,12 @@
     }
 }
 
-// MARK: - _PlistEncoder
+// MARK: - __PlistEncoder
 
-fileprivate class _PlistEncoder : Encoder {
+// NOTE: older overlays called this class _PlistEncoder. The two must
+// coexist without a conflicting ObjC class name, so it was renamed.
+// The old name must not be used in the new runtime.
+fileprivate class __PlistEncoder : Encoder {
     // MARK: Properties
 
     /// The encoder's storage.
@@ -223,7 +231,7 @@
     // MARK: Properties
 
     /// A reference to the encoder we're writing to.
-    private let encoder: _PlistEncoder
+    private let encoder: __PlistEncoder
 
     /// A reference to the container we're writing to.
     private let container: NSMutableDictionary
@@ -234,7 +242,7 @@
     // MARK: - Initialization
 
     /// Initializes `self` with the given references.
-    fileprivate init(referencing encoder: _PlistEncoder, codingPath: [CodingKey], wrapping container: NSMutableDictionary) {
+    fileprivate init(referencing encoder: __PlistEncoder, codingPath: [CodingKey], wrapping container: NSMutableDictionary) {
         self.encoder = encoder
         self.codingPath = codingPath
         self.container = container
@@ -285,11 +293,11 @@
     }
 
     public mutating func superEncoder() -> Encoder {
-        return _PlistReferencingEncoder(referencing: self.encoder, at: _PlistKey.super, wrapping: self.container)
+        return __PlistReferencingEncoder(referencing: self.encoder, at: _PlistKey.super, wrapping: self.container)
     }
 
     public mutating func superEncoder(forKey key: Key) -> Encoder {
-        return _PlistReferencingEncoder(referencing: self.encoder, at: key, wrapping: self.container)
+        return __PlistReferencingEncoder(referencing: self.encoder, at: key, wrapping: self.container)
     }
 }
 
@@ -297,7 +305,7 @@
     // MARK: Properties
 
     /// A reference to the encoder we're writing to.
-    private let encoder: _PlistEncoder
+    private let encoder: __PlistEncoder
 
     /// A reference to the container we're writing to.
     private let container: NSMutableArray
@@ -313,7 +321,7 @@
     // MARK: - Initialization
 
     /// Initializes `self` with the given references.
-    fileprivate init(referencing encoder: _PlistEncoder, codingPath: [CodingKey], wrapping container: NSMutableArray) {
+    fileprivate init(referencing encoder: __PlistEncoder, codingPath: [CodingKey], wrapping container: NSMutableArray) {
         self.encoder = encoder
         self.codingPath = codingPath
         self.container = container
@@ -364,11 +372,11 @@
     }
 
     public mutating func superEncoder() -> Encoder {
-        return _PlistReferencingEncoder(referencing: self.encoder, at: self.container.count, wrapping: self.container)
+        return __PlistReferencingEncoder(referencing: self.encoder, at: self.container.count, wrapping: self.container)
     }
 }
 
-extension _PlistEncoder : SingleValueEncodingContainer {
+extension __PlistEncoder : SingleValueEncodingContainer {
     // MARK: - SingleValueEncodingContainer Methods
 
     private func assertCanEncodeNewValue() {
@@ -458,7 +466,7 @@
 
 // MARK: - Concrete Value Representations
 
-extension _PlistEncoder {
+extension __PlistEncoder {
 
     /// Returns the given value boxed in a container appropriate for pushing onto the container stack.
     fileprivate func box(_ value: Bool)   -> NSObject { return NSNumber(value: value) }
@@ -489,7 +497,7 @@
             return (value as! NSData)
         }
 
-        // The value should request a container from the _PlistEncoder.
+        // The value should request a container from the __PlistEncoder.
         let depth = self.storage.count
         do {
             try value.encode(to: self)
@@ -511,11 +519,14 @@
     }
 }
 
-// MARK: - _PlistReferencingEncoder
+// MARK: - __PlistReferencingEncoder
 
-/// _PlistReferencingEncoder is a special subclass of _PlistEncoder which has its own storage, but references the contents of a different encoder.
+/// __PlistReferencingEncoder is a special subclass of __PlistEncoder which has its own storage, but references the contents of a different encoder.
 /// It's used in superEncoder(), which returns a new encoder for encoding a superclass -- the lifetime of the encoder should not escape the scope it's created in, but it doesn't necessarily know when it's done being used (to write to the original container).
-fileprivate class _PlistReferencingEncoder : _PlistEncoder {
+// NOTE: older overlays called this class _PlistReferencingEncoder.
+// The two must coexist without a conflicting ObjC class name, so it
+// was renamed. The old name must not be used in the new runtime.
+fileprivate class __PlistReferencingEncoder : __PlistEncoder {
     // MARK: Reference types.
 
     /// The type of container we're referencing.
@@ -530,7 +541,7 @@
     // MARK: - Properties
 
     /// The encoder we're referencing.
-    private let encoder: _PlistEncoder
+    private let encoder: __PlistEncoder
 
     /// The container reference itself.
     private let reference: Reference
@@ -538,7 +549,7 @@
     // MARK: - Initialization
 
     /// Initializes `self` by referencing the given array container in the given encoder.
-    fileprivate init(referencing encoder: _PlistEncoder, at index: Int, wrapping array: NSMutableArray) {
+    fileprivate init(referencing encoder: __PlistEncoder, at index: Int, wrapping array: NSMutableArray) {
         self.encoder = encoder
         self.reference = .array(array, index)
         super.init(options: encoder.options, codingPath: encoder.codingPath)
@@ -547,7 +558,7 @@
     }
 
     /// Initializes `self` by referencing the given dictionary container in the given encoder.
-    fileprivate init(referencing encoder: _PlistEncoder, at key: CodingKey, wrapping dictionary: NSMutableDictionary) {
+    fileprivate init(referencing encoder: __PlistEncoder, at key: CodingKey, wrapping dictionary: NSMutableDictionary) {
         self.encoder = encoder
         self.reference = .dictionary(dictionary, key.stringValue)
         super.init(options: encoder.options, codingPath: encoder.codingPath)
@@ -590,6 +601,11 @@
 //===----------------------------------------------------------------------===//
 
 /// `PropertyListDecoder` facilitates the decoding of property list values into semantic `Decodable` types.
+// NOTE: older overlays had Foundation.PropertyListDecoder as the ObjC
+// name. The two must coexist, so it was renamed. The old name must not
+// be used in the new runtime. _TtC10Foundation20_PropertyListDecoder
+// is the mangled name for Foundation._PropertyListDecoder.
+@_objcRuntimeName(_TtC10Foundation20_PropertyListDecoder)
 open class PropertyListDecoder {
     // MARK: Options
 
@@ -652,7 +668,7 @@
     /// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not a valid property list.
     /// - throws: An error if any value throws an error during decoding.
     internal func decode<T : Decodable>(_ type: T.Type, fromTopLevel container: Any) throws -> T {
-        let decoder = _PlistDecoder(referencing: container, options: self.options)
+        let decoder = __PlistDecoder(referencing: container, options: self.options)
         guard let value = try decoder.unbox(container, as: type) else {
             throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value."))
         }
@@ -661,9 +677,12 @@
     }
 }
 
-// MARK: - _PlistDecoder
+// MARK: - __PlistDecoder
 
-fileprivate class _PlistDecoder : Decoder {
+// NOTE: older overlays called this class _PlistDecoder. The two must
+// coexist without a conflicting ObjC class name, so it was renamed.
+// The old name must not be used in the new runtime.
+fileprivate class __PlistDecoder : Decoder {
     // MARK: Properties
 
     /// The decoder's storage.
@@ -769,7 +788,7 @@
     // MARK: Properties
 
     /// A reference to the decoder we're reading from.
-    private let decoder: _PlistDecoder
+    private let decoder: __PlistDecoder
 
     /// A reference to the container we're reading from.
     private let container: [String : Any]
@@ -780,7 +799,7 @@
     // MARK: - Initialization
 
     /// Initializes `self` by referencing the given decoder and container.
-    fileprivate init(referencing decoder: _PlistDecoder, wrapping container: [String : Any]) {
+    fileprivate init(referencing decoder: __PlistDecoder, wrapping container: [String : Any]) {
         self.decoder = decoder
         self.container = container
         self.codingPath = decoder.codingPath
@@ -1072,7 +1091,7 @@
         defer { self.decoder.codingPath.removeLast() }
 
         let value: Any = self.container[key.stringValue] ?? NSNull()
-        return _PlistDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
+        return __PlistDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
     }
 
     public func superDecoder() throws -> Decoder {
@@ -1088,7 +1107,7 @@
     // MARK: Properties
 
     /// A reference to the decoder we're reading from.
-    private let decoder: _PlistDecoder
+    private let decoder: __PlistDecoder
 
     /// A reference to the container we're reading from.
     private let container: [Any]
@@ -1102,7 +1121,7 @@
     // MARK: - Initialization
 
     /// Initializes `self` by referencing the given decoder and container.
-    fileprivate init(referencing decoder: _PlistDecoder, wrapping container: [Any]) {
+    fileprivate init(referencing decoder: __PlistDecoder, wrapping container: [Any]) {
         self.decoder = decoder
         self.container = container
         self.codingPath = decoder.codingPath
@@ -1434,11 +1453,11 @@
 
         let value = self.container[self.currentIndex]
         self.currentIndex += 1
-        return _PlistDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
+        return __PlistDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
     }
 }
 
-extension _PlistDecoder : SingleValueDecodingContainer {
+extension __PlistDecoder : SingleValueDecodingContainer {
     // MARK: SingleValueDecodingContainer Methods
 
     private func expectNonNull<T>(_ type: T.Type) throws {
@@ -1533,7 +1552,7 @@
 
 // MARK: - Concrete Value Representations
 
-extension _PlistDecoder {
+extension __PlistDecoder {
     /// Returns the given value unboxed from a container.
     fileprivate func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? {
         if let string = value as? String, string == _plistNull { return nil }
diff --git a/stdlib/public/SDK/Network/NWConnection.swift b/stdlib/public/SDK/Network/NWConnection.swift
index 89c4fe0..0c69f19 100644
--- a/stdlib/public/SDK/Network/NWConnection.swift
+++ b/stdlib/public/SDK/Network/NWConnection.swift
@@ -20,6 +20,11 @@
 /// A connection handles establishment of any transport, security, or application-level protocols
 /// required to transmit and receive user data. Multiple protocol instances may be attempted during
 /// the establishment phase of the connection.
+// NOTE: older overlays had Network.NWConnection as the ObjC name.
+// The two must coexist, so it was renamed. The old name must not be
+// used in the new runtime. _TtC7Network13_NWConnection is the
+// mangled name for Network._NWConnection.
+@_objcRuntimeName(_TtC7Network13_NWConnection)
 @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
 public final class NWConnection : CustomDebugStringConvertible {
 
@@ -297,6 +302,8 @@
 	/// Content Context controls options for how data is sent, and access for metadata to send or receive.
 	/// All properties of Content Context are valid for sending. For received Content Context, only the protocolMetadata
 	/// values will be set.
+	// Set the ObjC name of this class to be nested in the customized ObjC name of NWConnection.
+	@_objcRuntimeName(_TtCC7Network13_NWConnection14ContentContext)
 	public class ContentContext {
         internal let nw: nw_content_context_t
 
diff --git a/stdlib/public/SDK/Network/NWListener.swift b/stdlib/public/SDK/Network/NWListener.swift
index e12a560..87e0e0a 100644
--- a/stdlib/public/SDK/Network/NWListener.swift
+++ b/stdlib/public/SDK/Network/NWListener.swift
@@ -22,6 +22,11 @@
 /// accepted connections will represent multiplexed streams on a new or existing transport
 /// binding.
 
+// NOTE: older overlays had Network.NWListener as the ObjC name.
+// The two must coexist, so it was renamed. The old name must not be
+// used in the new runtime. _TtC7Network11_NWListener is the
+// mangled name for Network._NWListener.
+@_objcRuntimeName(_TtC7Network11_NWListener)
 @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
 public final class NWListener: CustomDebugStringConvertible {
 	public var debugDescription: String {
diff --git a/stdlib/public/SDK/Network/NWParameters.swift b/stdlib/public/SDK/Network/NWParameters.swift
index 9880f8b..face2df 100644
--- a/stdlib/public/SDK/Network/NWParameters.swift
+++ b/stdlib/public/SDK/Network/NWParameters.swift
@@ -16,6 +16,11 @@
 /// endpoint requirements); preferences for data transfer and quality of service;
 /// and the protocols to be used for a connection along with any protocol-specific
 /// options.
+// NOTE: older overlays had Network.NWParameters as the ObjC name.
+// The two must coexist, so it was renamed. The old name must not be
+// used in the new runtime. _TtC7Network13_NWParameters is the
+// mangled name for Network._NWParameters.
+@_objcRuntimeName(_TtC7Network13_NWParameters)
 @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
 public final class NWParameters : CustomDebugStringConvertible {
 	public var debugDescription: String {
@@ -422,6 +427,9 @@
 	/// transport-level protocol, and an optional internet-level protocol. If the internet-
 	/// level protocol is not specified, any available and applicable IP address family
 	/// may be used.
+  // Set the ObjC name of this class to be nested in the customized ObjC
+  // name of NWParameters.
+	@_objcRuntimeName(_TtCC7Network13_NWParameters13ProtocolStack)
 	public class ProtocolStack {
 		public var applicationProtocols: [NWProtocolOptions] {
 			set {
diff --git a/stdlib/public/SDK/Network/NWPath.swift b/stdlib/public/SDK/Network/NWPath.swift
index 437aa0c..000552a 100644
--- a/stdlib/public/SDK/Network/NWPath.swift
+++ b/stdlib/public/SDK/Network/NWPath.swift
@@ -225,6 +225,11 @@
 /// The paths will watch the state of multiple interfaces, and allows the
 /// application to enumerate the available interfaces for use in creating connections
 /// or listeners bound to specific interfaces.
+// NOTE: older overlays had Network.NWPathMonitor as the ObjC name.
+// The two must coexist, so it was renamed. The old name must not be
+// used in the new runtime. _TtC7Network14_NWPathMonitor is the
+// mangled name for Network._NWPathMonitor.
+@_objcRuntimeName(_TtC7Network14_NWPathMonitor)
 @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
 public final class NWPathMonitor {
 
diff --git a/stdlib/public/SDK/Network/NWProtocol.swift b/stdlib/public/SDK/Network/NWProtocol.swift
index 1512194..f05e30c 100644
--- a/stdlib/public/SDK/Network/NWProtocol.swift
+++ b/stdlib/public/SDK/Network/NWProtocol.swift
@@ -12,6 +12,11 @@
 
 /// NWProtocolDefinition is an abstract superclass that represents the identifier of a
 /// protocol that can be used with connections and listeners, such as TCP.
+// NOTE: older overlays had Network.NWProtocolDefinition as the ObjC name.
+// The two must coexist, so it was renamed. The old name must not be
+// used in the new runtime. _TtC7Network21_NWProtocolDefinition is the
+// mangled name for Network._NWProtocolDefinition.
+@_objcRuntimeName(_TtC7Network21_NWProtocolDefinition)
 @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
 public class NWProtocolDefinition : Equatable, CustomDebugStringConvertible {
 	public static func == (lhs: NWProtocolDefinition, rhs: NWProtocolDefinition) -> Bool {
@@ -35,6 +40,11 @@
 /// NWProtocolOptions is an abstract superclass that represents a configuration options
 /// that can be used to add a protocol into an NWParameters.ProtocolStack. These options
 /// configure the behavior of a protocol and cannot be changed after starting a connection.
+// NOTE: older overlays had Network.NWProtocolOptions as the ObjC name.
+// The two must coexist, so it was renamed. The old name must not be
+// used in the new runtime. _TtC7Network18_NWProtocolOptions is the
+// mangled name for Network._NWProtocolOptions.
+@_objcRuntimeName(_TtC7Network18_NWProtocolOptions)
 @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
 public class NWProtocolOptions {
 	internal let nw: nw_protocol_options_t
@@ -50,6 +60,11 @@
 /// specific to some content being sent; as well as to retrieve metadata specific to some
 /// content that was received. Each protocol is responsible for defining its own accessor
 /// functions to set and get metadata.
+// NOTE: older overlays had Network.NWProtocolMetadata as the ObjC name.
+// The two must coexist, so it was renamed. The old name must not be
+// used in the new runtime. _TtC7Network19_NWProtocolMetadata is the
+// mangled name for Network._NWProtocolMetadata.
+@_objcRuntimeName(_TtC7Network19_NWProtocolMetadata)
 @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
 public class NWProtocolMetadata {
 	internal let nw: nw_protocol_metadata_t
@@ -60,6 +75,11 @@
 }
 
 /// NWProtocol is an abstract superclass to which protocol implementations conform.
+// NOTE: older overlays had Network.NWProtocol as the ObjC name.
+// The two must coexist, so it was renamed. The old name must not be
+// used in the new runtime. _TtC7Network11_NWProtocol is the
+// mangled name for Network._NWProtocol.
+@_objcRuntimeName(_TtC7Network11_NWProtocol)
 @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
 public class NWProtocol {
 
diff --git a/stdlib/public/SDK/Network/NWProtocolIP.swift b/stdlib/public/SDK/Network/NWProtocolIP.swift
index 45c78f2..1e585bb 100644
--- a/stdlib/public/SDK/Network/NWProtocolIP.swift
+++ b/stdlib/public/SDK/Network/NWProtocolIP.swift
@@ -10,12 +10,20 @@
 //
 //===----------------------------------------------------------------------===//
 
+// NOTE: older overlays had Network.NWProtocolIP as the ObjC name.
+// The two must coexist, so it was renamed. The old name must not be
+// used in the new runtime. _TtC7Network13_NWProtocolIP is the
+// mangled name for Network._NWProtocolIP.
+@_objcRuntimeName(_TtC7Network13_NWProtocolIP)
 @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
 public class NWProtocolIP : NWProtocol {
 	public static let definition: NWProtocolDefinition = {
 		NWProtocolDefinition(nw_protocol_copy_ip_definition(), "ip")
 	}()
 
+  // Set the ObjC name of this class to be nested in the customized ObjC
+  // name of NWProtocolIP.
+  @_objcRuntimeName(_TtCC7Network13_NWProtocolIP7Options)
 	public class Options : NWProtocolOptions {
 		public enum Version {
 			/// Allow any IP version
@@ -167,6 +175,9 @@
 	}
 
 	/// IP Metadata can be sent or received as part of ContentContext
+  // Set the ObjC name of this class to be nested in the customized ObjC
+  // name of NWProtocolIP.
+  @_objcRuntimeName(_TtCC7Network13_NWProtocolIP8Metadata)
 	public class Metadata: NWProtocolMetadata {
 		/// Set ECN flags to be sent on a packet, or get ECN flags
 		/// received on a packet. These flags will not take effect
diff --git a/stdlib/public/SDK/Network/NWProtocolTCP.swift b/stdlib/public/SDK/Network/NWProtocolTCP.swift
index d85d5d7..f7968eb 100644
--- a/stdlib/public/SDK/Network/NWProtocolTCP.swift
+++ b/stdlib/public/SDK/Network/NWProtocolTCP.swift
@@ -10,12 +10,20 @@
 //
 //===----------------------------------------------------------------------===//
 
+// NOTE: older overlays had Network.NWProtocolTCP as the ObjC name.
+// The two must coexist, so it was renamed. The old name must not be
+// used in the new runtime. _TtC7Network14_NWProtocolTCP is the
+// mangled name for Network._NWProtocolTCP.
+@_objcRuntimeName(_TtC7Network14_NWProtocolTCP)
 @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
 public class NWProtocolTCP : NWProtocol {
 	public static let definition: NWProtocolDefinition = {
 		NWProtocolDefinition(nw_protocol_copy_tcp_definition(), "tcp")
 	}()
 
+  // Set the ObjC name of this class to be nested in the customized ObjC
+  // name of NWProtocolTCP.
+  @_objcRuntimeName(_TtCC7Network14_NWProtocolTCP7Options)
 	public class Options : NWProtocolOptions {
 
 		private var _noDelay: Bool = false
@@ -244,6 +252,9 @@
 
 	/// Access TCP metadata using NWConnection.metadata(protocolDefinition: NWProtocolTCP.definition)
 	/// or in received ContentContext
+  // Set the ObjC name of this class to be nested in the customized ObjC
+  // name of NWProtocolTCP.
+  @_objcRuntimeName(_TtCC7Network14_NWProtocolTCP8Metadata)
 	public class Metadata: NWProtocolMetadata {
 		override internal init(_ nw: nw_protocol_metadata_t) {
 			super.init(nw)
diff --git a/stdlib/public/SDK/Network/NWProtocolTLS.swift b/stdlib/public/SDK/Network/NWProtocolTLS.swift
index beb21fa..0522d8d 100644
--- a/stdlib/public/SDK/Network/NWProtocolTLS.swift
+++ b/stdlib/public/SDK/Network/NWProtocolTLS.swift
@@ -10,12 +10,20 @@
 //
 //===----------------------------------------------------------------------===//
 
+// NOTE: older overlays had Network.NWProtocolTLS as the ObjC name.
+// The two must coexist, so it was renamed. The old name must not be
+// used in the new runtime. _TtC7Network14_NWProtocolTLS is the
+// mangled name for Network._NWProtocolTLS.
+@_objcRuntimeName(_TtC7Network14_NWProtocolTLS)
 @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
 public class NWProtocolTLS : NWProtocol {
 	public static let definition: NWProtocolDefinition = {
 		NWProtocolDefinition(nw_protocol_copy_tls_definition(), "tls")
 	}()
 
+  // Set the ObjC name of this class to be nested in the customized ObjC
+  // name of NWProtocolTLS.
+  @_objcRuntimeName(_TtCC7Network14_NWProtocolTLS7Options)
 	public class Options : NWProtocolOptions {
 		/// Access the sec_protocol_options_t for a given network protocol
 		/// options instance. See <Security/SecProtocolOptions.h> for functions
@@ -36,6 +44,9 @@
 
 	/// Access TLS metadata using NWConnection.metadata(protocolDefinition: NWProtocolTLS.definition)
 	/// or in received ContentContext
+  // Set the ObjC name of this class to be nested in the customized ObjC
+  // name of NWNWProtocolTLSProtocolIP.
+  @_objcRuntimeName(_TtCC7Network14_NWProtocolTLS8Metadata)
 	public class Metadata: NWProtocolMetadata {
 		/// Access the sec_protocol_metadata_t for a given network protocol
 		/// metadata instance. See <Security/SecProtocolMetadata.h> for functions
diff --git a/stdlib/public/SDK/Network/NWProtocolUDP.swift b/stdlib/public/SDK/Network/NWProtocolUDP.swift
index fe77087..7f345d7 100644
--- a/stdlib/public/SDK/Network/NWProtocolUDP.swift
+++ b/stdlib/public/SDK/Network/NWProtocolUDP.swift
@@ -10,12 +10,20 @@
 //
 //===----------------------------------------------------------------------===//
 
+// NOTE: older overlays had Network.NWProtocolUDP as the ObjC name.
+// The two must coexist, so it was renamed. The old name must not be
+// used in the new runtime. _TtC7Network14_NWProtocolUDP is the
+// mangled name for Network._NWProtocolUDP.
+@_objcRuntimeName(_TtC7Network14_NWProtocolUDP)
 @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
 public class NWProtocolUDP : NWProtocol {
 	public static let definition: NWProtocolDefinition = {
 		NWProtocolDefinition(nw_protocol_copy_udp_definition(), "udp")
 	}()
 
+  // Set the ObjC name of this class to be nested in the customized ObjC
+  // name of NWProtocolUDP.
+  @_objcRuntimeName(_TtCC7Network14_NWProtocolUDP7Options)
 	public class Options : NWProtocolOptions {
 
 		private var _preferNoChecksum: Bool = false
@@ -42,7 +50,10 @@
 		}
 	}
 
-    public class Metadata: NWProtocolMetadata {
+  // Set the ObjC name of this class to be nested in the customized ObjC
+  // name of NWProtocolUDP.
+  @_objcRuntimeName(_TtCC7Network14_NWProtocolUDP8Metadata)
+  public class Metadata: NWProtocolMetadata {
 		override internal init(_ nw: nw_protocol_metadata_t) {
 			super.init(nw)
 		}
diff --git a/stdlib/public/SDK/SpriteKit/SpriteKit.swift b/stdlib/public/SDK/SpriteKit/SpriteKit.swift
index aa6fd22..6b78367 100644
--- a/stdlib/public/SDK/SpriteKit/SpriteKit.swift
+++ b/stdlib/public/SDK/SpriteKit/SpriteKit.swift
@@ -25,7 +25,7 @@
 // since that method only exists in a private header in SpriteKit, the lookup
 // mechanism by default fails to accept it as a valid AnyObject call
 //
-// NOTE: older runtimes called this _SpriteKitMethodProvider. The two must
+// NOTE: older overlays called this _SpriteKitMethodProvider. The two must
 // coexist, so it was renamed. The old name must not be used in the new
 // runtime.
 @objc class __SpriteKitMethodProvider : NSObject {
diff --git a/stdlib/public/core/AtomicInt.swift.gyb b/stdlib/public/core/AtomicInt.swift.gyb
index 17d3484..62217f2 100644
--- a/stdlib/public/core/AtomicInt.swift.gyb
+++ b/stdlib/public/core/AtomicInt.swift.gyb
@@ -10,7 +10,12 @@
 //
 //===----------------------------------------------------------------------===//
 
+// NOTE: older runtimes had Swift._stdlib_AtomicInt as the ObjC name.
+// The two must coexist, so it was renamed. The old name must not be
+// used in the new runtime. _TtCs18__stdlib_AtomicInt is the mangled
+// name for Swift.__stdlib_AtomicInt
 @available(swift, deprecated: 4.2, obsoleted: 5.0)
+@_objcRuntimeName(_TtCs18__stdlib_AtomicInt)
 public final class _stdlib_AtomicInt {
   internal var _value: Int
 
diff --git a/stdlib/public/core/BridgingBuffer.swift b/stdlib/public/core/BridgingBuffer.swift
index 34d0c3e..c3d0613 100644
--- a/stdlib/public/core/BridgingBuffer.swift
+++ b/stdlib/public/core/BridgingBuffer.swift
@@ -15,7 +15,10 @@
   internal var count: Int
 }
 
-internal final class _BridgingBufferStorage
+// NOTE: older runtimes called this class _BridgingBufferStorage.
+// The two must coexist without a conflicting ObjC class name, so it
+// was renamed. The old name must not be used in the new runtime.
+internal final class __BridgingBufferStorage
   : ManagedBuffer<_BridgingBufferHeader, AnyObject> {
 }
 
@@ -26,7 +29,7 @@
 where Header == _BridgingBufferHeader, Element == AnyObject {
   internal init(_ count: Int) {
     self.init(
-      _uncheckedBufferClass: _BridgingBufferStorage.self,
+      _uncheckedBufferClass: __BridgingBufferStorage.self,
       minimumCapacity: count)
     self.withUnsafeMutablePointerToHeader {
       $0.initialize(to: Header(count))
diff --git a/stdlib/public/core/Builtin.swift b/stdlib/public/core/Builtin.swift
index 761df17..01b9e89 100644
--- a/stdlib/public/core/Builtin.swift
+++ b/stdlib/public/core/Builtin.swift
@@ -668,9 +668,6 @@
   return Bool(Builtin.isUnique(&object))
 }
 
-@_silgen_name("_swift_reallocObject")
-internal func _reallocObject(_ object: UnsafeMutableRawPointer, _ newSizeInBytes: Int) -> UnsafeMutableRawPointer?
-
 /// Returns `true` if `object` is uniquely referenced.
 /// This provides sanity checks on top of the Builtin.
 @_transparent
diff --git a/stdlib/public/core/ClosedRange.swift b/stdlib/public/core/ClosedRange.swift
index d2f972d..db1b1ff 100644
--- a/stdlib/public/core/ClosedRange.swift
+++ b/stdlib/public/core/ClosedRange.swift
@@ -433,6 +433,7 @@
   /// An equivalent range must be representable as a closed range.
   /// For example, passing an empty range as `other` triggers a runtime error,
   /// because an empty range cannot be represented by a closed range instance.
+  @inlinable
   public init(_ other: Range<Bound>) {
     _precondition(!other.isEmpty, "Can't form an empty closed range")
     let upperBound = other.upperBound.advanced(by: -1)
@@ -456,3 +457,26 @@
 // shorthand. TODO: Add documentation
 public typealias CountableClosedRange<Bound: Strideable> = ClosedRange<Bound>
   where Bound.Stride : SignedInteger
+
+extension ClosedRange: Decodable where Bound: Decodable {
+  public init(from decoder: Decoder) throws {
+    var container = try decoder.unkeyedContainer()
+    let lowerBound = try container.decode(Bound.self)
+    let upperBound = try container.decode(Bound.self)
+    guard lowerBound <= upperBound else {
+      throw DecodingError.dataCorrupted(
+        DecodingError.Context(
+          codingPath: decoder.codingPath,
+          debugDescription: "Cannot initialize \(ClosedRange.self) with a lowerBound (\(lowerBound)) greater than upperBound (\(upperBound))"))
+    }
+    self.init(uncheckedBounds: (lower: lowerBound, upper: upperBound))
+  }
+}
+
+extension ClosedRange: Encodable where Bound: Encodable {
+  public func encode(to encoder: Encoder) throws {
+    var container = encoder.unkeyedContainer()
+    try container.encode(self.lowerBound)
+    try container.encode(self.upperBound)
+  }
+}
diff --git a/stdlib/public/core/Codable.swift.gyb b/stdlib/public/core/Codable.swift.gyb
index ee0dd97..d33c4d1 100644
--- a/stdlib/public/core/Codable.swift.gyb
+++ b/stdlib/public/core/Codable.swift.gyb
@@ -1767,6 +1767,40 @@
   }
 }
 
+extension ContiguousArray : Encodable where Element : Encodable {
+  /// Encodes the elements of this contiguous array into the given encoder
+  /// in an unkeyed container.
+  ///
+  /// This function throws an error if any values are invalid for the given
+  /// encoder's format.
+  ///
+  /// - Parameter encoder: The encoder to write data to.
+  public func encode(to encoder: Encoder) throws {
+    var container = encoder.unkeyedContainer()
+    for element in self {
+      try container.encode(element)
+    }
+  }
+}
+
+extension ContiguousArray : Decodable where Element : Decodable {
+  /// Creates a new contiguous array by decoding from the given decoder.
+  ///
+  /// This initializer throws an error if reading from the decoder fails, or
+  /// if the data read is corrupted or otherwise invalid.
+  ///
+  /// - Parameter decoder: The decoder to read data from.
+  public init(from decoder: Decoder) throws {
+    self.init()
+
+    var container = try decoder.unkeyedContainer()
+    while !container.isAtEnd {
+      let element = try container.decode(Element.self)
+      self.append(element)
+    }
+  }
+}
+
 extension Set : Encodable where Element : Encodable {
   /// Encodes the elements of this set into the given encoder in an unkeyed
   /// container.
diff --git a/stdlib/public/core/Dictionary.swift b/stdlib/public/core/Dictionary.swift
index c78dacd..0a66313 100644
--- a/stdlib/public/core/Dictionary.swift
+++ b/stdlib/public/core/Dictionary.swift
@@ -40,7 +40,7 @@
 //       /
 //      |
 //      V
-//   class _RawDictionaryStorage
+//   class __RawDictionaryStorage
 //   +-----------------------------------------------------------+
 //   | <isa>                                                     |
 //   | <refcount>                                                |
@@ -62,7 +62,7 @@
 //   +----------------------------------------------+
 //   | enum Dictionary<K,V>._Variant                |
 //   | +----------------------------------------+   |
-//   | | [ struct _CocoaDictionary              |   |
+//   | | [ struct __CocoaDictionary             |   |
 //   | +---|------------------------------------+   |
 //   +----/-----------------------------------------+
 //       /
@@ -75,9 +75,9 @@
 //   +--------------+
 //     ^
 //     |
-//      \  struct _CocoaDictionary.Index
+//      \  struct __CocoaDictionary.Index
 //   +--|------------------------------------+
-//   |  * base: _CocoaDictionary             |
+//   |  * base: __CocoaDictionary            |
 //   |  allKeys: array of all keys           |
 //   |  currentKeyIndex: index into allKeys  |
 //   +---------------------------------------+
@@ -87,8 +87,8 @@
 // ---------------------------
 //
 // The native backing store is represented by three different classes:
-// * `_RawDictionaryStorage`
-// * `_EmptyDictionarySingleton` (extends Raw)
+// * `__RawDictionaryStorage`
+// * `__EmptyDictionarySingleton` (extends Raw)
 // * `_DictionaryStorage<K: Hashable, V>` (extends Raw)
 //
 // (Hereafter `Raw`, `Empty`, and `Storage`, respectively)
@@ -401,7 +401,7 @@
 
 #if _runtime(_ObjC)
   @inlinable
-  internal init(_cocoa: __owned _CocoaDictionary) {
+  internal init(_cocoa: __owned __CocoaDictionary) {
     _variant = _Variant(cocoa: _cocoa)
   }
 
@@ -422,7 +422,7 @@
       Dictionary can be backed by NSDictionary buffer only when both Key \
       and Value are bridged verbatim to Objective-C
       """)
-    self.init(_cocoa: _CocoaDictionary(_immutableCocoaDictionary))
+    self.init(_cocoa: __CocoaDictionary(_immutableCocoaDictionary))
   }
 #endif
 
@@ -1744,7 +1744,7 @@
     internal enum _Variant {
       case native(_HashTable.Index)
 #if _runtime(_ObjC)
-      case cocoa(_CocoaDictionary.Index)
+      case cocoa(__CocoaDictionary.Index)
 #endif
     }
 
@@ -1766,7 +1766,7 @@
 #if _runtime(_ObjC)
     @inlinable
     @inline(__always)
-    internal init(_cocoa index: __owned _CocoaDictionary.Index) {
+    internal init(_cocoa index: __owned __CocoaDictionary.Index) {
       self.init(_variant: .cocoa(index))
     }
 #endif
@@ -1824,7 +1824,7 @@
 
 #if _runtime(_ObjC)
   @usableFromInline
-  internal var _asCocoa: _CocoaDictionary.Index {
+  internal var _asCocoa: __CocoaDictionary.Index {
     @_transparent
     get {
       switch _variant {
@@ -1925,7 +1925,7 @@
     internal enum _Variant {
       case native(_NativeDictionary<Key, Value>.Iterator)
 #if _runtime(_ObjC)
-      case cocoa(_CocoaDictionary.Iterator)
+      case cocoa(__CocoaDictionary.Iterator)
 #endif
     }
 
@@ -1944,7 +1944,7 @@
 
 #if _runtime(_ObjC)
     @inlinable
-    internal init(_cocoa: __owned _CocoaDictionary.Iterator) {
+    internal init(_cocoa: __owned __CocoaDictionary.Iterator) {
       self.init(_variant: .cocoa(_cocoa))
     }
 #endif
@@ -1998,7 +1998,7 @@
 
 #if _runtime(_ObjC)
   @usableFromInline @_transparent
-  internal var _asCocoa: _CocoaDictionary.Iterator {
+  internal var _asCocoa: __CocoaDictionary.Iterator {
     get {
       switch _variant {
       case .native:
diff --git a/stdlib/public/core/DictionaryBridging.swift b/stdlib/public/core/DictionaryBridging.swift
index f22e00d..23d753a 100644
--- a/stdlib/public/core/DictionaryBridging.swift
+++ b/stdlib/public/core/DictionaryBridging.swift
@@ -35,8 +35,8 @@
     // Temporary var for SOME type safety.
     let nsDictionary: _NSDictionaryCore
 
-    if _storage === _RawDictionaryStorage.empty || count == 0 {
-      nsDictionary = _RawDictionaryStorage.empty
+    if _storage === __RawDictionaryStorage.empty || count == 0 {
+      nsDictionary = __RawDictionaryStorage.empty
     } else if _isBridgedVerbatimToObjectiveC(Key.self),
       _isBridgedVerbatimToObjectiveC(Value.self) {
       nsDictionary = unsafeDowncast(
@@ -56,7 +56,7 @@
   : __SwiftNativeNSEnumerator, _NSEnumerator {
 
   @nonobjc internal var base: _NativeDictionary<Key, Value>
-  @nonobjc internal var bridgedKeys: _BridgingHashBuffer?
+  @nonobjc internal var bridgedKeys: __BridgingHashBuffer?
   @nonobjc internal var nextBucket: _NativeDictionary<Key, Value>.Bucket
   @nonobjc internal var endBucket: _NativeDictionary<Key, Value>.Bucket
 
@@ -186,41 +186,41 @@
 
   /// The buffer for bridged keys, if present.
   @nonobjc
-  private var _bridgedKeys: _BridgingHashBuffer? {
+  private var _bridgedKeys: __BridgingHashBuffer? {
     guard let ref = _stdlib_atomicLoadARCRef(object: _bridgedKeysPtr) else {
       return nil
     }
-    return unsafeDowncast(ref, to: _BridgingHashBuffer.self)
+    return unsafeDowncast(ref, to: __BridgingHashBuffer.self)
   }
 
   /// The buffer for bridged values, if present.
   @nonobjc
-  private var _bridgedValues: _BridgingHashBuffer? {
+  private var _bridgedValues: __BridgingHashBuffer? {
     guard let ref = _stdlib_atomicLoadARCRef(object: _bridgedValuesPtr) else {
       return nil
     }
-    return unsafeDowncast(ref, to: _BridgingHashBuffer.self)
+    return unsafeDowncast(ref, to: __BridgingHashBuffer.self)
   }
 
   /// Attach a buffer for bridged Dictionary keys.
   @nonobjc
-  private func _initializeBridgedKeys(_ storage: _BridgingHashBuffer) {
+  private func _initializeBridgedKeys(_ storage: __BridgingHashBuffer) {
     _stdlib_atomicInitializeARCRef(object: _bridgedKeysPtr, desired: storage)
   }
 
   /// Attach a buffer for bridged Dictionary values.
   @nonobjc
-  private func _initializeBridgedValues(_ storage: _BridgingHashBuffer) {
+  private func _initializeBridgedValues(_ storage: __BridgingHashBuffer) {
     _stdlib_atomicInitializeARCRef(object: _bridgedValuesPtr, desired: storage)
   }
 
   @nonobjc
-  internal func bridgeKeys() -> _BridgingHashBuffer? {
+  internal func bridgeKeys() -> __BridgingHashBuffer? {
     if _isBridgedVerbatimToObjectiveC(Key.self) { return nil }
     if let bridgedKeys = _bridgedKeys { return bridgedKeys }
 
     // Allocate and initialize heap storage for bridged keys.
-    let bridged = _BridgingHashBuffer.allocate(
+    let bridged = __BridgingHashBuffer.allocate(
       owner: native._storage,
       hashTable: native.hashTable)
     for bucket in native.hashTable {
@@ -234,12 +234,12 @@
   }
 
   @nonobjc
-  internal func bridgeValues() -> _BridgingHashBuffer? {
+  internal func bridgeValues() -> __BridgingHashBuffer? {
     if _isBridgedVerbatimToObjectiveC(Value.self) { return nil }
     if let bridgedValues = _bridgedValues { return bridgedValues }
 
     // Allocate and initialize heap storage for bridged values.
-    let bridged = _BridgingHashBuffer.allocate(
+    let bridged = __BridgingHashBuffer.allocate(
       owner: native._storage,
       hashTable: native.hashTable)
     for bucket in native.hashTable {
@@ -263,7 +263,7 @@
   @inline(__always)
   private func _key(
     at bucket: Bucket,
-    bridgedKeys: _BridgingHashBuffer?
+    bridgedKeys: __BridgingHashBuffer?
   ) -> AnyObject {
     if let bridgedKeys = bridgedKeys {
       return bridgedKeys[bucket]
@@ -274,7 +274,7 @@
   @inline(__always)
   private func _value(
     at bucket: Bucket,
-    bridgedValues: _BridgingHashBuffer?
+    bridgedValues: __BridgingHashBuffer?
   ) -> AnyObject {
     if let bridgedValues = bridgedValues {
       return bridgedValues[bucket]
@@ -417,9 +417,13 @@
   }
 }
 
+// NOTE: older runtimes called this struct _CocoaDictionary. The two
+// must coexist without conflicting ObjC class names from the nested
+// classes, so it was renamed. The old names must not be used in the new
+// runtime.
 @usableFromInline
 @_fixed_layout
-internal struct _CocoaDictionary {
+internal struct __CocoaDictionary {
   @usableFromInline
   internal let object: AnyObject
 
@@ -429,14 +433,14 @@
   }
 }
 
-extension _CocoaDictionary {
+extension __CocoaDictionary {
   @usableFromInline
-  internal func isEqual(to other: _CocoaDictionary) -> Bool {
+  internal func isEqual(to other: __CocoaDictionary) -> Bool {
     return _stdlib_NSObject_isEqual(self.object, other.object)
   }
 }
 
-extension _CocoaDictionary: _DictionaryBuffer {
+extension __CocoaDictionary: _DictionaryBuffer {
   @usableFromInline
   internal typealias Key = AnyObject
   @usableFromInline
@@ -545,7 +549,7 @@
   }
 }
 
-extension _CocoaDictionary {
+extension __CocoaDictionary {
   @inlinable
   internal func mapValues<Key: Hashable, Value, T>(
     _ transform: (Value) throws -> T
@@ -560,7 +564,7 @@
   }
 }
 
-extension _CocoaDictionary {
+extension __CocoaDictionary {
   @_fixed_layout
   @usableFromInline
   internal struct Index {
@@ -582,7 +586,7 @@
   }
 }
 
-extension _CocoaDictionary.Index {
+extension __CocoaDictionary.Index {
   // FIXME(cocoa-index): Try using an NSEnumerator to speed this up.
   internal class Storage {
   // Assumption: we rely on NSDictionary.getObjects when being
@@ -592,7 +596,7 @@
 
     /// A reference to the NSDictionary, which owns members in `allObjects`,
     /// or `allKeys`, for NSSet and NSDictionary respectively.
-    internal let base: _CocoaDictionary
+    internal let base: __CocoaDictionary
     // FIXME: swift-3-indexing-model: try to remove the cocoa reference, but
     // make sure that we have a safety check for accessing `allKeys`.  Maybe
     // move both into the dictionary/set itself.
@@ -601,7 +605,7 @@
     internal var allKeys: _BridgingBuffer
 
     internal init(
-      _ base: __owned _CocoaDictionary,
+      _ base: __owned __CocoaDictionary,
       _ allKeys: __owned _BridgingBuffer
     ) {
       self.base = base
@@ -610,7 +614,7 @@
   }
 }
 
-extension _CocoaDictionary.Index {
+extension __CocoaDictionary.Index {
   @usableFromInline
   internal var handleBitPattern: UInt {
     @_effects(readonly)
@@ -620,7 +624,7 @@
   }
 
   @usableFromInline
-  internal var dictionary: _CocoaDictionary {
+  internal var dictionary: __CocoaDictionary {
     @_effects(releasenone)
     get {
       return storage.base
@@ -628,7 +632,7 @@
   }
 }
 
-extension _CocoaDictionary.Index {
+extension __CocoaDictionary.Index {
   @usableFromInline // FIXME(cocoa-index): Make inlinable
   @nonobjc
   internal var key: AnyObject {
@@ -650,12 +654,12 @@
   }
 }
 
-extension _CocoaDictionary.Index: Equatable {
+extension __CocoaDictionary.Index: Equatable {
   @usableFromInline // FIXME(cocoa-index): Make inlinable
   @_effects(readonly)
   internal static func == (
-    lhs: _CocoaDictionary.Index,
-    rhs: _CocoaDictionary.Index
+    lhs: __CocoaDictionary.Index,
+    rhs: __CocoaDictionary.Index
   ) -> Bool {
     _precondition(lhs.storage.base.object === rhs.storage.base.object,
       "Comparing indexes from different dictionaries")
@@ -663,12 +667,12 @@
   }
 }
 
-extension _CocoaDictionary.Index: Comparable {
+extension __CocoaDictionary.Index: Comparable {
   @usableFromInline // FIXME(cocoa-index): Make inlinable
   @_effects(readonly)
   internal static func < (
-    lhs: _CocoaDictionary.Index,
-    rhs: _CocoaDictionary.Index
+    lhs: __CocoaDictionary.Index,
+    rhs: __CocoaDictionary.Index
   ) -> Bool {
     _precondition(lhs.storage.base.object === rhs.storage.base.object,
       "Comparing indexes from different dictionaries")
@@ -676,7 +680,7 @@
   }
 }
 
-extension _CocoaDictionary: Sequence {
+extension __CocoaDictionary: Sequence {
   @usableFromInline
   final internal class Iterator {
     // Cocoa Dictionary iterator has to be a class, otherwise we cannot
@@ -692,7 +696,7 @@
     // `_fastEnumerationState`.  There's code below relying on this.
     internal var _fastEnumerationStackBuf = _CocoaFastEnumerationStackBuf()
 
-    internal let base: _CocoaDictionary
+    internal let base: __CocoaDictionary
 
     internal var _fastEnumerationStatePtr:
       UnsafeMutablePointer<_SwiftNSFastEnumerationState> {
@@ -713,7 +717,7 @@
     internal var itemIndex: Int = 0
     internal var itemCount: Int = 0
 
-    internal init(_ base: __owned _CocoaDictionary) {
+    internal init(_ base: __owned __CocoaDictionary) {
       self.base = base
     }
   }
@@ -725,7 +729,7 @@
   }
 }
 
-extension _CocoaDictionary.Iterator: IteratorProtocol {
+extension __CocoaDictionary.Iterator: IteratorProtocol {
   @usableFromInline
   internal typealias Element = (key: AnyObject, value: AnyObject)
 
@@ -796,7 +800,7 @@
       return Dictionary(_native: _NativeDictionary(nativeStorage))
     }
 
-    if s === _RawDictionaryStorage.empty {
+    if s === __RawDictionaryStorage.empty {
       return Dictionary()
     }
 
diff --git a/stdlib/public/core/DictionaryStorage.swift b/stdlib/public/core/DictionaryStorage.swift
index f3579af..39ac765 100644
--- a/stdlib/public/core/DictionaryStorage.swift
+++ b/stdlib/public/core/DictionaryStorage.swift
@@ -16,10 +16,13 @@
 /// Enough bytes are allocated to hold the bitmap for marking valid entries,
 /// keys, and values. The data layout starts with the bitmap, followed by the
 /// keys, followed by the values.
+// NOTE: older runtimes called this class _RawDictionaryStorage. The two
+// must coexist without a conflicting ObjC class name, so it was
+// renamed. The old name must not be used in the new runtime.
 @_fixed_layout
 @usableFromInline
 @_objc_non_lazy_realization
-internal class _RawDictionaryStorage: __SwiftNativeNSDictionary {
+internal class __RawDictionaryStorage: __SwiftNativeNSDictionary {
   // NOTE: The precise layout of this type is relied on in the runtime to
   // provide a statically allocated empty singleton.  See
   // stdlib/public/stubs/GlobalObjects.cpp for details.
@@ -109,9 +112,12 @@
 
 /// The storage class for the singleton empty set.
 /// The single instance of this class is created by the runtime.
+// NOTE: older runtimes called this class _EmptyDictionarySingleton.
+// The two must coexist without a conflicting ObjC class name, so it was
+// renamed. The old name must not be used in the new runtime.
 @_fixed_layout
 @usableFromInline
-internal class _EmptyDictionarySingleton: _RawDictionaryStorage {
+internal class __EmptyDictionarySingleton: __RawDictionaryStorage {
   @nonobjc
   internal override init(_doNotCallMe: ()) {
     _internalInvariantFailure("This class cannot be directly initialized")
@@ -130,7 +136,7 @@
 }
 
 #if _runtime(_ObjC)
-extension _EmptyDictionarySingleton: _NSDictionaryCore {
+extension __EmptyDictionarySingleton: _NSDictionaryCore {
   @objc(copyWithZone:)
   internal func copy(with zone: _SwiftNSZone?) -> AnyObject {
     return self
@@ -167,7 +173,7 @@
 
   @objc(keyEnumerator)
   internal func keyEnumerator() -> _NSEnumerator {
-    return _SwiftEmptyNSEnumerator()
+    return __SwiftEmptyNSEnumerator()
   }
 
   @objc(getObjects:andKeys:count:)
@@ -180,13 +186,13 @@
 }
 #endif
 
-extension _RawDictionaryStorage {
+extension __RawDictionaryStorage {
   /// The empty singleton that is used for every single Dictionary that is
   /// created without any elements. The contents of the storage should never
   /// be mutated.
   @inlinable
   @nonobjc
-  internal static var empty: _EmptyDictionarySingleton {
+  internal static var empty: __EmptyDictionarySingleton {
     return Builtin.bridgeFromRawPointer(
       Builtin.addressof(&_swiftEmptyDictionarySingleton))
   }
@@ -194,7 +200,7 @@
 
 @usableFromInline
 final internal class _DictionaryStorage<Key: Hashable, Value>
-  : _RawDictionaryStorage, _NSDictionaryCore {
+  : __RawDictionaryStorage, _NSDictionaryCore {
   // This type is made with allocWithTailElems, so no init is ever called.
   // But we still need to have an init to satisfy the compiler.
   @nonobjc
@@ -359,7 +365,7 @@
   @usableFromInline
   @_effects(releasenone)
   internal static func copy(
-    original: _RawDictionaryStorage
+    original: __RawDictionaryStorage
   ) -> _DictionaryStorage {
     return allocate(
       scale: original._scale,
@@ -370,7 +376,7 @@
   @usableFromInline
   @_effects(releasenone)
   static internal func resize(
-    original: _RawDictionaryStorage,
+    original: __RawDictionaryStorage,
     capacity: Int,
     move: Bool
   ) -> _DictionaryStorage {
@@ -389,7 +395,7 @@
   @usableFromInline
   @_effects(releasenone)
   static internal func convert(
-    _ cocoa: _CocoaDictionary,
+    _ cocoa: __CocoaDictionary,
     capacity: Int
   ) -> _DictionaryStorage {
     let scale = _HashTable.scale(forCapacity: capacity)
diff --git a/stdlib/public/core/DictionaryVariant.swift b/stdlib/public/core/DictionaryVariant.swift
index b4f85d3..595f9c8 100644
--- a/stdlib/public/core/DictionaryVariant.swift
+++ b/stdlib/public/core/DictionaryVariant.swift
@@ -35,7 +35,7 @@
   @_fixed_layout
   internal struct _Variant {
     @usableFromInline
-    internal var object: _BridgeStorage<_RawDictionaryStorage>
+    internal var object: _BridgeStorage<__RawDictionaryStorage>
 
     @inlinable
     @inline(__always)
@@ -56,7 +56,7 @@
 #if _runtime(_ObjC)
     @inlinable
     @inline(__always)
-    init(cocoa: __owned _CocoaDictionary) {
+    init(cocoa: __owned __CocoaDictionary) {
       self.object = _BridgeStorage(objC: cocoa.object)
     }
 #endif
@@ -102,8 +102,8 @@
 
 #if _runtime(_ObjC)
   @inlinable
-  internal var asCocoa: _CocoaDictionary {
-    return _CocoaDictionary(object.objCInstance)
+  internal var asCocoa: __CocoaDictionary {
+    return __CocoaDictionary(object.objCInstance)
   }
 #endif
 
diff --git a/stdlib/public/core/Hashing.swift b/stdlib/public/core/Hashing.swift
index 379e83b..1429f5c 100644
--- a/stdlib/public/core/Hashing.swift
+++ b/stdlib/public/core/Hashing.swift
@@ -71,7 +71,10 @@
 #if _runtime(_ObjC)
 /// An NSEnumerator implementation returning zero elements. This is useful when
 /// a concrete element type is not recoverable from the empty singleton.
-final internal class _SwiftEmptyNSEnumerator
+// NOTE: older runtimes called this class _SwiftEmptyNSEnumerator. The two
+// must coexist without conflicting ObjC class names, so it was
+// renamed. The old name must not be used in the new runtime.
+final internal class __SwiftEmptyNSEnumerator
   : __SwiftNativeNSEnumerator, _NSEnumerator {
   internal override required init() {}
 
@@ -107,8 +110,11 @@
 ///
 /// Using a dedicated class for this rather than a _BridgingBuffer makes it easy
 /// to recognize these in heap dumps etc.
-internal final class _BridgingHashBuffer
-  : ManagedBuffer<_BridgingHashBuffer.Header, AnyObject> {
+// NOTE: older runtimes called this class _BridgingHashBuffer.
+// The two must coexist without a conflicting ObjC class name, so it
+// was renamed. The old name must not be used in the new runtime.
+internal final class __BridgingHashBuffer
+  : ManagedBuffer<__BridgingHashBuffer.Header, AnyObject> {
   struct Header {
     internal var owner: AnyObject
     internal var hashTable: _HashTable
@@ -122,11 +128,11 @@
   internal static func allocate(
     owner: AnyObject,
     hashTable: _HashTable
-  ) -> _BridgingHashBuffer {
+  ) -> __BridgingHashBuffer {
     let buffer = self.create(minimumCapacity: hashTable.bucketCount) { _ in
       Header(owner: owner, hashTable: hashTable)
     }
-    return unsafeDowncast(buffer, to: _BridgingHashBuffer.self)
+    return unsafeDowncast(buffer, to: __BridgingHashBuffer.self)
   }
 
   deinit {
diff --git a/stdlib/public/core/IntegerTypes.swift.gyb b/stdlib/public/core/IntegerTypes.swift.gyb
index 747063e..73a66b0 100644
--- a/stdlib/public/core/IntegerTypes.swift.gyb
+++ b/stdlib/public/core/IntegerTypes.swift.gyb
@@ -58,19 +58,6 @@
       llvmName=lambda _: 'shl'),
 ]
 
-IntMax = 'Int%s' % int_max_bits
-UIntMax = 'UInt%s' % int_max_bits
-}%
-
-// FIXME(integers): remove these two aliases
-/// The largest native signed integer type.
-@available(swift, obsoleted: 4.0, renamed: "${IntMax}")
-public typealias IntMax = ${IntMax}
-/// The largest native unsigned integer type.
-@available(swift, obsoleted: 4.0, renamed: "${UIntMax}")
-public typealias UIntMax = ${UIntMax}
-
-%{
 #===-----------------------------------------------------------------------===//
 #===--- Operator Documentation --------------------------------------------===//
 #===-----------------------------------------------------------------------===//
@@ -1628,17 +1615,6 @@
   }
 % end
 
-  @available(swift, obsoleted: 4.0, message: "Use initializers instead")
-  public func to${U}IntMax() -> ${U}Int64 {
-    return numericCast(self)
-  }
-
-  @available(swift, obsoleted: 4, message: "Use bitWidth instead.")
-  public static var _sizeInBits: ${Self} { return ${bits} }
-
-  @available(swift, obsoleted: 4)
-  public static var _sizeInBytes: ${Self} { return ${bits}/8 }
-
   /// Returns `-1` if this value is negative and `1` if it's positive;
   /// otherwise, `0`.
   ///
@@ -1687,36 +1663,6 @@
   }
 }
 
-% for src_type in all_integer_types(word_bits):
-%   srcBits = src_type.bits
-%   srcSigned = src_type.is_signed
-%   Src = src_type.stdlib_name
-%   if should_define_truncating_bit_pattern_init(src_ty=src_type, dst_ty=self_type):
-extension ${Self} {
-  /// Creates a new instance with the same bitwise representation as the least
-  /// significant bits of the given value.
-  ///
-  /// This initializer performs no range or overflow checking. The resulting
-  /// instance may have a different numeric value from `source`.
-  ///
-  /// - Parameter source: An integer to use as the source of the new value's
-  ///   bit pattern.
-  @available(swift, obsoleted: 4.0, renamed: "init(truncatingIfNeeded:)")
-  @_transparent
-  public init(truncatingBitPattern source: ${Src}) {
-    let src = source._value
-%     if self_type.bits == src_type.bits:
-    let dstNotWord = src
-%     else:
-    let dstNotWord = Builtin.trunc_Int${srcBits}_Int${bits}(src)
-%     end
-    self._value = dstNotWord
-  }
-}
-%   end
-% end
-
-
 // FIXME(integers): this section here is to help the typechecker,
 // as it seems to have problems with a pattern where the nonmutating operation
 // is defined on a protocol in terms of a mutating one that is itself defined
@@ -1735,32 +1681,6 @@
 
 %   end
 
-%   for op in maskingShifts:
-
-${operatorComment(x.operator, True)}
-  @available(swift, obsoleted: 4)
-  @_semantics("optimize.sil.specialize.generic.partial.never")
-  @_transparent
-  public static func ${op.nonMaskingOperator}(
-    lhs: ${Self}, rhs: ${Self}
-  ) -> ${Self} {
-    var lhs = lhs
-    ${op.helper}Generic(&lhs, rhs)
-    return lhs
-  }
-
-${assignmentOperatorComment(x.operator, True)}
-  @available(swift, obsoleted: 4)
-  @_semantics("optimize.sil.specialize.generic.partial.never")
-  @_transparent
-  public static func ${op.nonMaskingOperator}=(
-    lhs: inout ${Self}, rhs: ${Self}
-  ) {
-    ${op.helper}Generic(&lhs, rhs)
-  }
-
-%   end
-
   @_transparent
   public static func <= (lhs: ${Self}, rhs: ${Self}) -> Bool {
     return !(rhs < lhs)
diff --git a/stdlib/public/core/Integers.swift b/stdlib/public/core/Integers.swift
index c6e19b6..c7c9eff 100644
--- a/stdlib/public/core/Integers.swift
+++ b/stdlib/public/core/Integers.swift
@@ -3566,145 +3566,6 @@
   return U(x)
 }
 
-// FIXME(integers): These overloads allow expressions like the following in
-// Swift 3 compatibility mode:
-//    let x = 1 << i32
-//    f(i32: x)
-// At the same time, since they are obsolete in Swift 4, this will not cause
-// `u8 << -1` to fail due to an overflow in an unsigned value.
-extension FixedWidthInteger {
-  @available(swift, obsoleted: 4)
-  @_semantics("optimize.sil.specialize.generic.partial.never")
-  @_transparent
-  public static func >>(lhs: Self, rhs: Self) -> Self {
-    var lhs = lhs
-    _nonMaskingRightShiftGeneric(&lhs, rhs)
-    return lhs
-  }
-
-  @available(swift, obsoleted: 4)
-  @_semantics("optimize.sil.specialize.generic.partial.never")
-  @_transparent
-  public static func >>=(lhs: inout Self, rhs: Self) {
-    _nonMaskingRightShiftGeneric(&lhs, rhs)
-  }
-
-  @available(swift, obsoleted: 4)
-  @_semantics("optimize.sil.specialize.generic.partial.never")
-  @_transparent
-  public static func <<(lhs: Self, rhs: Self) -> Self {
-    var lhs = lhs
-    _nonMaskingLeftShiftGeneric(&lhs, rhs)
-    return lhs
-  }
-
-  @available(swift, obsoleted: 4)
-  @_semantics("optimize.sil.specialize.generic.partial.never")
-  @_transparent
-  public static func <<=(lhs: inout Self, rhs: Self) {
-    _nonMaskingLeftShiftGeneric(&lhs, rhs)
-  }
-}
-
-extension FixedWidthInteger {
-  @available(swift, obsoleted: 4, message: "Use addingReportingOverflow(_:) instead.")
-  @inlinable
-  public static func addWithOverflow(
-    _ lhs: Self, _ rhs: Self
-  ) -> (Self, overflow: Bool) {
-    let (partialValue, overflow) =
-      lhs.addingReportingOverflow( rhs)
-    return (partialValue, overflow: overflow)
-  }
-
-  @available(swift, obsoleted: 4, message: "Use subtractingReportingOverflow(_:) instead.")
-  @inlinable
-  public static func subtractWithOverflow(
-    _ lhs: Self, _ rhs: Self
-  ) -> (Self, overflow: Bool) {
-    let (partialValue, overflow) =
-      lhs.subtractingReportingOverflow( rhs)
-    return (partialValue, overflow: overflow)
-  }
-
-  @inlinable
-  @available(swift, obsoleted: 4, message: "Use multipliedReportingOverflow(by:) instead.")
-  public static func multiplyWithOverflow(
-    _ lhs: Self, _ rhs: Self
-  ) -> (Self, overflow: Bool) {
-    let (partialValue, overflow) =
-      lhs.multipliedReportingOverflow(by: rhs)
-    return (partialValue, overflow: overflow)
-  }
-
-  @inlinable
-  @available(swift, obsoleted: 4, message: "Use dividedReportingOverflow(by:) instead.")
-  public static func divideWithOverflow(
-    _ lhs: Self, _ rhs: Self
-  ) -> (Self, overflow: Bool) {
-    let (partialValue, overflow) =
-      lhs.dividedReportingOverflow(by: rhs)
-    return (partialValue, overflow: overflow)
-  }
-
-  @inlinable
-  @available(swift, obsoleted: 4, message: "Use remainderReportingOverflow(dividingBy:) instead.")
-  public static func remainderWithOverflow(
-    _ lhs: Self, _ rhs: Self
-  ) -> (Self, overflow: Bool) {
-    let (partialValue, overflow) =
-      lhs.remainderReportingOverflow(dividingBy: rhs)
-    return (partialValue, overflow: overflow)
-  }
-}
-
-extension BinaryInteger {
-  @inlinable
-  @available(swift, obsoleted: 3.2,
-    message: "Please use FixedWidthInteger protocol as a generic constraint and addingReportingOverflow(_:) method instead.")
-  public static func addWithOverflow(
-    _ lhs: Self, _ rhs: Self
-  ) -> (Self, overflow: Bool) {
-    fatalError("Unavailable")
-  }
-
-  @inlinable
-  @available(swift, obsoleted: 3.2,
-    message: "Please use FixedWidthInteger protocol as a generic constraint and subtractingReportingOverflow(_:) method instead.")
-  public static func subtractWithOverflow(
-    _ lhs: Self, _ rhs: Self
-  ) -> (Self, overflow: Bool) {
-    fatalError("Unavailable")
-  }
-
-  @inlinable
-  @available(swift, obsoleted: 3.2,
-    message: "Please use FixedWidthInteger protocol as a generic constraint and multipliedReportingOverflow(by:) method instead.")
-  public static func multiplyWithOverflow(
-    _ lhs: Self, _ rhs: Self
-  ) -> (Self, overflow: Bool) {
-    fatalError("Unavailable")
-  }
-
-  @inlinable
-  @available(swift, obsoleted: 3.2,
-    message: "Please use FixedWidthInteger protocol as a generic constraint and dividedReportingOverflow(by:) method instead.")
-  public static func divideWithOverflow(
-    _ lhs: Self, _ rhs: Self
-  ) -> (Self, overflow: Bool) {
-    fatalError("Unavailable")
-  }
-
-  @inlinable
-  @available(swift, obsoleted: 3.2,
-    message: "Please use FixedWidthInteger protocol as a generic constraint and remainderReportingOverflow(dividingBy:) method instead.")
-  public static func remainderWithOverflow(
-    _ lhs: Self, _ rhs: Self
-  ) -> (Self, overflow: Bool) {
-    fatalError("Unavailable")
-  }
-}
-
 // FIXME(integers): Absence of &+ causes ambiguity in the code like the
 // following:
 //    func f<T : SignedInteger>(_ x: T, _ y: T) {
@@ -3721,23 +3582,9 @@
   }
 
   @_transparent
-  @available(swift, obsoleted: 4.0,
-      message: "Please use 'FixedWidthInteger' instead of 'SignedInteger' to get '&+' in generic code.")
-  public static func &+ (lhs: Self, rhs: Self) -> Self {
-    return _maskingAdd(lhs, rhs)
-  }
-
-  @_transparent
   public static func _maskingSubtract(_ lhs: Self, _ rhs: Self) -> Self {
     fatalError("Should be overridden in a more specific type")
   }
-
-  @_transparent
-  @available(swift, obsoleted: 4.0,
-      message: "Please use 'FixedWidthInteger' instead of 'SignedInteger' to get '&-' in generic code.")
-  public static func &- (lhs: Self, rhs: Self) -> Self {
-    return _maskingSubtract(lhs, rhs)
-  }
 }
 
 extension SignedInteger where Self : FixedWidthInteger {
diff --git a/stdlib/public/core/ManagedBuffer.swift b/stdlib/public/core/ManagedBuffer.swift
index ab5b74c..67c0a8d 100644
--- a/stdlib/public/core/ManagedBuffer.swift
+++ b/stdlib/public/core/ManagedBuffer.swift
@@ -136,30 +136,6 @@
   }
 }
 
-@inline(never)
-public func tryReallocateUniquelyReferenced<Header, Element, Buffer: ManagedBuffer<Header, Element>>(
-  buffer: inout Buffer,
-  newMinimumCapacity: Int
-) -> Bool {
-  precondition(_isBitwiseTakable(Header.self))
-  precondition(_isBitwiseTakable(Element.self))
-  precondition(isKnownUniquelyReferenced(&buffer))
-
-  let newSizeInBytes = MemoryLayout<Header>.stride
-    + newMinimumCapacity * MemoryLayout<Element>.stride
-
-  return withUnsafeMutablePointer(to: &buffer) {
-    $0.withMemoryRebound(to: UnsafeMutableRawPointer.self, capacity: 1) {
-      if let reallocdObject = _reallocObject($0.pointee, newSizeInBytes) {
-        $0.pointee = reallocdObject
-        return true
-      } else {
-        return false
-      }
-    }
-  }
-}
-
 /// Contains a buffer object, and provides access to an instance of
 /// `Header` and contiguous storage for an arbitrary number of
 /// `Element` instances stored in that buffer.
diff --git a/stdlib/public/core/MigrationSupport.swift b/stdlib/public/core/MigrationSupport.swift
index a0fd8b8..927311d 100644
--- a/stdlib/public/core/MigrationSupport.swift
+++ b/stdlib/public/core/MigrationSupport.swift
@@ -244,26 +244,6 @@
 }
 
 //===--- Slicing Support --------------------------------------------------===//
-// In Swift 3.2, in the absence of type context,
-//
-//   someString.unicodeScalars[
-//     someString.unicodeScalars.startIndex
-//     ..< someString.unicodeScalars.endIndex]
-//
-// was deduced to be of type `String.UnicodeScalarView`.  Provide a
-// more-specific Swift-3-only `subscript` overload that continues to produce
-// `String.UnicodeScalarView`.
-extension String.UnicodeScalarView {
-  @available(swift, obsoleted: 4)
-  public subscript(bounds: Range<Index>) -> String.UnicodeScalarView {
-    Builtin.unreachable()
-  }
-
-  @available(swift, obsoleted: 4)
-  public subscript(bounds: ClosedRange<Index>) -> String.UnicodeScalarView {
-    Builtin.unreachable()
-  }
-}
 
 // @available(swift,deprecated: 5.0, renamed: "Unicode.UTF8")
 public typealias UTF8 = Unicode.UTF8
@@ -327,11 +307,6 @@
     _precondition(range.upperBound <= endIndex,
       "String index range is out of bounds")
   }
-
-  @available(swift, obsoleted: 4)
-  public subscript(bounds: ClosedRange<Index>) -> String {
-    Builtin.unreachable()
-  }
 }
 
 extension Substring : _CustomPlaygroundQuickLookable {
@@ -567,13 +542,6 @@
   ) rethrows -> [ElementOfResult] {
     return try _compactMap(transform)
   }
-
-  @available(swift, obsoleted: 4)
-  public func flatMap(
-    _ transform: (Element) throws -> String
-  ) rethrows -> [String] {
-    return try map(transform)
-  }
 }
 
 extension Collection {
diff --git a/stdlib/public/core/NativeDictionary.swift b/stdlib/public/core/NativeDictionary.swift
index f0a9f91..7aa9708 100644
--- a/stdlib/public/core/NativeDictionary.swift
+++ b/stdlib/public/core/NativeDictionary.swift
@@ -10,7 +10,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-/// A wrapper around _RawDictionaryStorage that provides most of the
+/// A wrapper around __RawDictionaryStorage that provides most of the
 /// implementation of Dictionary.
 @usableFromInline
 @_fixed_layout
@@ -18,20 +18,20 @@
   @usableFromInline
   internal typealias Element = (key: Key, value: Value)
 
-  /// See this comments on _RawDictionaryStorage and its subclasses to
+  /// See this comments on __RawDictionaryStorage and its subclasses to
   /// understand why we store an untyped storage here.
   @usableFromInline
-  internal var _storage: _RawDictionaryStorage
+  internal var _storage: __RawDictionaryStorage
 
   /// Constructs an instance from the empty singleton.
   @inlinable
   internal init() {
-    self._storage = _RawDictionaryStorage.empty
+    self._storage = __RawDictionaryStorage.empty
   }
 
   /// Constructs a dictionary adopting the given storage.
   @inlinable
-  internal init(_ storage: __owned _RawDictionaryStorage) {
+  internal init(_ storage: __owned __RawDictionaryStorage) {
     self._storage = storage
   }
 
@@ -42,12 +42,12 @@
 
 #if _runtime(_ObjC)
   @inlinable
-  internal init(_ cocoa: __owned _CocoaDictionary) {
+  internal init(_ cocoa: __owned __CocoaDictionary) {
     self.init(cocoa, capacity: cocoa.count)
   }
 
   @inlinable
-  internal init(_ cocoa: __owned _CocoaDictionary, capacity: Int) {
+  internal init(_ cocoa: __owned __CocoaDictionary, capacity: Int) {
     _internalInvariant(cocoa.count <= capacity)
     self._storage =
       _DictionaryStorage<Key, Value>.convert(cocoa, capacity: capacity)
@@ -590,7 +590,7 @@
 
 #if _runtime(_ObjC)
   @inlinable
-  func isEqual(to other: _CocoaDictionary) -> Bool {
+  func isEqual(to other: __CocoaDictionary) -> Bool {
     if self.count != other.count { return false }
 
     defer { _fixLifetime(self) }
diff --git a/stdlib/public/core/NativeSet.swift b/stdlib/public/core/NativeSet.swift
index fa7a89e..ec18aef 100644
--- a/stdlib/public/core/NativeSet.swift
+++ b/stdlib/public/core/NativeSet.swift
@@ -10,27 +10,27 @@
 //
 //===----------------------------------------------------------------------===//
 
-/// A wrapper around _RawSetStorage that provides most of the
+/// A wrapper around __RawSetStorage that provides most of the
 /// implementation of Set.
 @usableFromInline
 @_fixed_layout
 internal struct _NativeSet<Element: Hashable> {
-  /// See the comments on _RawSetStorage and its subclasses to understand why we
+  /// See the comments on __RawSetStorage and its subclasses to understand why we
   /// store an untyped storage here.
   @usableFromInline
-  internal var _storage: _RawSetStorage
+  internal var _storage: __RawSetStorage
 
   /// Constructs an instance from the empty singleton.
   @inlinable
   @inline(__always)
   internal init() {
-    self._storage = _RawSetStorage.empty
+    self._storage = __RawSetStorage.empty
   }
 
   /// Constructs a native set adopting the given storage.
   @inlinable
   @inline(__always)
-  internal init(_ storage: __owned _RawSetStorage) {
+  internal init(_ storage: __owned __RawSetStorage) {
     self._storage = storage
   }
 
@@ -41,12 +41,12 @@
 
 #if _runtime(_ObjC)
   @inlinable
-  internal init(_ cocoa: __owned _CocoaSet) {
+  internal init(_ cocoa: __owned __CocoaSet) {
     self.init(cocoa, capacity: cocoa.count)
   }
 
   @inlinable
-  internal init(_ cocoa: __owned _CocoaSet, capacity: Int) {
+  internal init(_ cocoa: __owned __CocoaSet, capacity: Int) {
     _internalInvariant(cocoa.count <= capacity)
     self._storage = _SetStorage<Element>.convert(cocoa, capacity: capacity)
     for element in cocoa {
@@ -439,7 +439,7 @@
 
 #if _runtime(_ObjC)
   @inlinable
-  func isEqual(to other: _CocoaSet) -> Bool {
+  func isEqual(to other: __CocoaSet) -> Bool {
     if self.count != other.count { return false }
 
     defer { _fixLifetime(self) }
diff --git a/stdlib/public/core/Range.swift b/stdlib/public/core/Range.swift
index 25bc133..d425e8f 100644
--- a/stdlib/public/core/Range.swift
+++ b/stdlib/public/core/Range.swift
@@ -405,6 +405,29 @@
   }
 }
 
+extension Range: Decodable where Bound: Decodable {
+  public init(from decoder: Decoder) throws {
+    var container = try decoder.unkeyedContainer()
+    let lowerBound = try container.decode(Bound.self)
+    let upperBound = try container.decode(Bound.self)
+    guard lowerBound <= upperBound else {
+      throw DecodingError.dataCorrupted(
+        DecodingError.Context(
+          codingPath: decoder.codingPath,
+          debugDescription: "Cannot initialize \(Range.self) with a lowerBound (\(lowerBound)) greater than upperBound (\(upperBound))"))
+    }
+    self.init(uncheckedBounds: (lower: lowerBound, upper: upperBound))
+  }
+}
+
+extension Range: Encodable where Bound: Encodable {
+  public func encode(to encoder: Encoder) throws {
+    var container = encoder.unkeyedContainer()
+    try container.encode(self.lowerBound)
+    try container.encode(self.upperBound)
+  }
+}
+
 /// A partial half-open interval up to, but not including, an upper bound.
 ///
 /// You create `PartialRangeUpTo` instances by using the prefix half-open range
@@ -447,6 +470,20 @@
   }
 }
 
+extension PartialRangeUpTo: Decodable where Bound: Decodable {
+  public init(from decoder: Decoder) throws {
+    var container = try decoder.unkeyedContainer()
+    try self.init(container.decode(Bound.self))
+  }
+}
+
+extension PartialRangeUpTo: Encodable where Bound: Encodable {
+  public func encode(to encoder: Encoder) throws {
+    var container = encoder.unkeyedContainer()
+    try container.encode(self.upperBound)
+  }
+}
+
 /// A partial interval up to, and including, an upper bound.
 ///
 /// You create `PartialRangeThrough` instances by using the prefix closed range
@@ -488,6 +525,20 @@
   }
 }
 
+extension PartialRangeThrough: Decodable where Bound: Decodable {
+  public init(from decoder: Decoder) throws {
+    var container = try decoder.unkeyedContainer()
+    try self.init(container.decode(Bound.self))
+  }
+}
+
+extension PartialRangeThrough: Encodable where Bound: Encodable {
+  public func encode(to encoder: Encoder) throws {
+    var container = encoder.unkeyedContainer()
+    try container.encode(self.upperBound)
+  }
+}
+
 /// A partial interval extending upward from a lower bound.
 ///
 /// You create `PartialRangeFrom` instances by using the postfix range operator
@@ -624,6 +675,20 @@
   }
 }
 
+extension PartialRangeFrom: Decodable where Bound: Decodable {
+  public init(from decoder: Decoder) throws {
+    var container = try decoder.unkeyedContainer()
+    try self.init(container.decode(Bound.self))
+  }
+}
+
+extension PartialRangeFrom: Encodable where Bound: Encodable {
+  public func encode(to encoder: Encoder) throws {
+    var container = encoder.unkeyedContainer()
+    try container.encode(self.lowerBound)
+  }
+}
+
 extension Comparable {
   /// Returns a half-open range that contains its lower bound but not its upper
   /// bound.
diff --git a/stdlib/public/core/SIMDVector.swift b/stdlib/public/core/SIMDVector.swift
index 79d0d7d..9351d48 100644
--- a/stdlib/public/core/SIMDVector.swift
+++ b/stdlib/public/core/SIMDVector.swift
@@ -23,7 +23,7 @@
 /// conform to `SIMD`.
 public protocol SIMDStorage {
   /// The type of scalars in the vector space.
-  associatedtype Scalar : Hashable
+  associatedtype Scalar : Codable, Hashable
   
   /// The number of scalars, or elements, in the vector.
   var scalarCount: Int { get }
@@ -51,6 +51,7 @@
 
 /// A SIMD vector of a fixed number of elements.
 public protocol SIMD : SIMDStorage,
+                       Codable,
                        Hashable,
                        CustomStringConvertible,
                        ExpressibleByArrayLiteral {
@@ -85,6 +86,42 @@
     for i in indices { hasher.combine(self[i]) }
   }
   
+  /// Encodes the scalars of this vector into the given encoder in an unkeyed
+  /// container.
+  ///
+  /// This function throws an error if any values are invalid for the given
+  /// encoder's format.
+  ///
+  /// - Parameter encoder: The encoder to write data to.
+  func encode(to encoder: Encoder) throws {
+    var container = encoder.unkeyedContainer()
+    for i in indices {
+      try container.encode(self[i])
+    }
+  }
+  
+  /// Creates a new vector by decoding scalars from the given decoder.
+  ///
+  /// This initializer throws an error if reading from the decoder fails, or
+  /// if the data read is corrupted or otherwise invalid.
+  ///
+  /// - Parameter decoder: The decoder to read data from.
+  init(from decoder: Decoder) throws {
+    self.init()
+    var container = try decoder.unkeyedContainer()
+    guard container.count == scalarCount else {
+      throw DecodingError.dataCorrupted(
+        DecodingError.Context(
+          codingPath: decoder.codingPath,
+          debugDescription: "Expected vector with exactly \(scalarCount) elements."
+        )
+      )
+    }
+    for i in indices {
+      self[i] = try container.decode(Scalar.self)
+    }
+  }
+  
   /// A textual description of the vector.
   var description: String {
     get {
diff --git a/stdlib/public/core/Set.swift b/stdlib/public/core/Set.swift
index b18b8a9..a551e1a 100644
--- a/stdlib/public/core/Set.swift
+++ b/stdlib/public/core/Set.swift
@@ -174,7 +174,7 @@
 
 #if _runtime(_ObjC)
   @inlinable
-  internal init(_cocoa: __owned _CocoaSet) {
+  internal init(_cocoa: __owned __CocoaSet) {
     _variant = _Variant(cocoa: _cocoa)
   }
 
@@ -190,7 +190,7 @@
   init(_immutableCocoaSet: __owned AnyObject) {
     _internalInvariant(_isBridgedVerbatimToObjectiveC(Element.self),
       "Set can be backed by NSSet _variant only when the member type can be bridged verbatim to Objective-C")
-    self.init(_cocoa: _CocoaSet(_immutableCocoaSet))
+    self.init(_cocoa: __CocoaSet(_immutableCocoaSet))
   }
 #endif
 }
@@ -1266,7 +1266,7 @@
     internal enum _Variant {
       case native(_HashTable.Index)
 #if _runtime(_ObjC)
-      case cocoa(_CocoaSet.Index)
+      case cocoa(__CocoaSet.Index)
 #endif
     }
 
@@ -1288,7 +1288,7 @@
 #if _runtime(_ObjC)
     @inlinable
     @inline(__always)
-    internal init(_cocoa index: __owned _CocoaSet.Index) {
+    internal init(_cocoa index: __owned __CocoaSet.Index) {
       self.init(_variant: .cocoa(index))
     }
 #endif
@@ -1349,7 +1349,7 @@
 
 #if _runtime(_ObjC)
   @usableFromInline
-  internal var _asCocoa: _CocoaSet.Index {
+  internal var _asCocoa: __CocoaSet.Index {
     @_transparent
     get {
       switch _variant {
@@ -1454,7 +1454,7 @@
     internal enum _Variant {
       case native(_NativeSet<Element>.Iterator)
 #if _runtime(_ObjC)
-      case cocoa(_CocoaSet.Iterator)
+      case cocoa(__CocoaSet.Iterator)
 #endif
     }
 
@@ -1473,7 +1473,7 @@
 
 #if _runtime(_ObjC)
     @usableFromInline
-    internal init(_cocoa: __owned _CocoaSet.Iterator) {
+    internal init(_cocoa: __owned __CocoaSet.Iterator) {
       self.init(_variant: .cocoa(_cocoa))
     }
 #endif
@@ -1529,7 +1529,7 @@
 
 #if _runtime(_ObjC)
   @usableFromInline @_transparent
-  internal var _asCocoa: _CocoaSet.Iterator {
+  internal var _asCocoa: __CocoaSet.Iterator {
     get {
       switch _variant {
       case .native:
diff --git a/stdlib/public/core/SetBridging.swift b/stdlib/public/core/SetBridging.swift
index 9c9d208..bc84a59 100644
--- a/stdlib/public/core/SetBridging.swift
+++ b/stdlib/public/core/SetBridging.swift
@@ -38,8 +38,8 @@
     // Temporary var for SOME type safety.
     let nsSet: _NSSetCore
 
-    if _storage === _RawSetStorage.empty || count == 0 {
-      nsSet = _RawSetStorage.empty
+    if _storage === __RawSetStorage.empty || count == 0 {
+      nsSet = __RawSetStorage.empty
     } else if _isBridgedVerbatimToObjectiveC(Element.self) {
       nsSet = unsafeDowncast(_storage, to: _SetStorage<Element>.self)
     } else {
@@ -59,7 +59,7 @@
   : __SwiftNativeNSEnumerator, _NSEnumerator {
 
   @nonobjc internal var base: _NativeSet<Element>
-  @nonobjc internal var bridgedElements: _BridgingHashBuffer?
+  @nonobjc internal var bridgedElements: __BridgingHashBuffer?
   @nonobjc internal var nextBucket: _NativeSet<Element>.Bucket
   @nonobjc internal var endBucket: _NativeSet<Element>.Bucket
 
@@ -172,27 +172,27 @@
 
   /// The buffer for bridged Set elements, if present.
   @nonobjc
-  private var _bridgedElements: _BridgingHashBuffer? {
+  private var _bridgedElements: __BridgingHashBuffer? {
     guard let ref = _stdlib_atomicLoadARCRef(object: _bridgedElementsPtr) else {
       return nil
     }
-    return unsafeDowncast(ref, to: _BridgingHashBuffer.self)
+    return unsafeDowncast(ref, to: __BridgingHashBuffer.self)
   }
 
   /// Attach a buffer for bridged Set elements.
   @nonobjc
-  private func _initializeBridgedElements(_ storage: _BridgingHashBuffer) {
+  private func _initializeBridgedElements(_ storage: __BridgingHashBuffer) {
     _stdlib_atomicInitializeARCRef(
       object: _bridgedElementsPtr,
       desired: storage)
   }
 
   @nonobjc
-  internal func bridgeElements() -> _BridgingHashBuffer {
+  internal func bridgeElements() -> __BridgingHashBuffer {
     if let bridgedElements = _bridgedElements { return bridgedElements }
 
     // Allocate and initialize heap storage for bridged objects.
-    let bridged = _BridgingHashBuffer.allocate(
+    let bridged = __BridgingHashBuffer.allocate(
       owner: native._storage,
       hashTable: native.hashTable)
     for bucket in native.hashTable {
@@ -285,9 +285,13 @@
   }
 }
 
+// NOTE: older overlays called this struct _CocoaSet. The two
+// must coexist without conflicting ObjC class names from the nested
+// classes, so it was renamed. The old names must not be used in the new
+// runtime.
 @usableFromInline
 @_fixed_layout
-internal struct _CocoaSet {
+internal struct __CocoaSet {
   @usableFromInline
   internal let object: AnyObject
 
@@ -297,7 +301,7 @@
   }
 }
 
-extension _CocoaSet {
+extension __CocoaSet {
   @usableFromInline
   @_effects(releasenone)
   internal func member(for index: Index) -> AnyObject {
@@ -311,14 +315,14 @@
   }
 }
 
-extension _CocoaSet {
+extension __CocoaSet {
   @usableFromInline
-  internal func isEqual(to other: _CocoaSet) -> Bool {
+  internal func isEqual(to other: __CocoaSet) -> Bool {
     return _stdlib_NSObject_isEqual(self.object, other.object)
   }
 }
 
-extension _CocoaSet: _SetBuffer {
+extension __CocoaSet: _SetBuffer {
   @usableFromInline
   internal typealias Element = AnyObject
 
@@ -404,7 +408,7 @@
   }
 }
 
-extension _CocoaSet {
+extension __CocoaSet {
   @_fixed_layout
   @usableFromInline
   internal struct Index {
@@ -426,7 +430,7 @@
   }
 }
 
-extension _CocoaSet.Index {
+extension __CocoaSet.Index {
   // FIXME(cocoa-index): Try using an NSEnumerator to speed this up.
   internal class Storage {
     // Assumption: we rely on NSDictionary.getObjects when being
@@ -436,7 +440,7 @@
 
     /// A reference to the NSSet, which owns members in `allObjects`,
     /// or `allKeys`, for NSSet and NSDictionary respectively.
-    internal let base: _CocoaSet
+    internal let base: __CocoaSet
     // FIXME: swift-3-indexing-model: try to remove the cocoa reference, but
     // make sure that we have a safety check for accessing `allKeys`.  Maybe
     // move both into the dictionary/set itself.
@@ -445,7 +449,7 @@
     internal var allKeys: _BridgingBuffer
 
     internal init(
-      _ base: __owned _CocoaSet,
+      _ base: __owned __CocoaSet,
       _ allKeys: __owned _BridgingBuffer
     ) {
       self.base = base
@@ -454,7 +458,7 @@
   }
 }
 
-extension _CocoaSet.Index {
+extension __CocoaSet.Index {
   @usableFromInline
   internal var handleBitPattern: UInt {
     @_effects(readonly)
@@ -464,7 +468,7 @@
   }
 }
 
-extension _CocoaSet.Index {
+extension __CocoaSet.Index {
   @usableFromInline // FIXME(cocoa-index): Make inlinable
   @nonobjc
   internal var element: AnyObject {
@@ -486,27 +490,27 @@
   }
 }
 
-extension _CocoaSet.Index: Equatable {
+extension __CocoaSet.Index: Equatable {
   @usableFromInline // FIXME(cocoa-index): Make inlinable
   @_effects(readonly)
-  internal static func == (lhs: _CocoaSet.Index, rhs: _CocoaSet.Index) -> Bool {
+  internal static func == (lhs: __CocoaSet.Index, rhs: __CocoaSet.Index) -> Bool {
     _precondition(lhs.storage.base.object === rhs.storage.base.object,
       "Comparing indexes from different sets")
     return lhs._offset == rhs._offset
   }
 }
 
-extension _CocoaSet.Index: Comparable {
+extension __CocoaSet.Index: Comparable {
   @usableFromInline // FIXME(cocoa-index): Make inlinable
   @_effects(readonly)
-  internal static func < (lhs: _CocoaSet.Index, rhs: _CocoaSet.Index) -> Bool {
+  internal static func < (lhs: __CocoaSet.Index, rhs: __CocoaSet.Index) -> Bool {
     _precondition(lhs.storage.base.object === rhs.storage.base.object,
       "Comparing indexes from different sets")
     return lhs._offset < rhs._offset
   }
 }
 
-extension _CocoaSet: Sequence {
+extension __CocoaSet: Sequence {
   @usableFromInline
   final internal class Iterator {
     // Cocoa Set iterator has to be a class, otherwise we cannot
@@ -522,7 +526,7 @@
     // `_fastEnumerationState`.  There's code below relying on this.
     internal var _fastEnumerationStackBuf = _CocoaFastEnumerationStackBuf()
 
-    internal let base: _CocoaSet
+    internal let base: __CocoaSet
 
     internal var _fastEnumerationStatePtr:
       UnsafeMutablePointer<_SwiftNSFastEnumerationState> {
@@ -543,7 +547,7 @@
     internal var itemIndex: Int = 0
     internal var itemCount: Int = 0
 
-    internal init(_ base: __owned _CocoaSet) {
+    internal init(_ base: __owned __CocoaSet) {
       self.base = base
     }
   }
@@ -554,7 +558,7 @@
   }
 }
 
-extension _CocoaSet.Iterator: IteratorProtocol {
+extension __CocoaSet.Iterator: IteratorProtocol {
   @usableFromInline
   internal typealias Element = AnyObject
 
@@ -618,7 +622,7 @@
       return Set(_native: _NativeSet(nativeStorage))
     }
 
-    if s === _RawSetStorage.empty {
+    if s === __RawSetStorage.empty {
       return Set()
     }
 
diff --git a/stdlib/public/core/SetStorage.swift b/stdlib/public/core/SetStorage.swift
index f4a5086..44936c8 100644
--- a/stdlib/public/core/SetStorage.swift
+++ b/stdlib/public/core/SetStorage.swift
@@ -16,10 +16,13 @@
 /// Enough bytes are allocated to hold the bitmap for marking valid entries,
 /// keys, and values. The data layout starts with the bitmap, followed by the
 /// keys, followed by the values.
+// NOTE: older runtimes called this class _RawSetStorage. The two
+// must coexist without a conflicting ObjC class name, so it was
+// renamed. The old name must not be used in the new runtime.
 @_fixed_layout
 @usableFromInline
 @_objc_non_lazy_realization
-internal class _RawSetStorage: __SwiftNativeNSSet {
+internal class __RawSetStorage: __SwiftNativeNSSet {
   // NOTE: The precise layout of this type is relied on in the runtime to
   // provide a statically allocated empty singleton.  See
   // stdlib/public/stubs/GlobalObjects.cpp for details.
@@ -104,9 +107,12 @@
 
 /// The storage class for the singleton empty set.
 /// The single instance of this class is created by the runtime.
+// NOTE: older runtimes called this class _EmptySetSingleton. The two
+// must coexist without conflicting ObjC class names, so it was renamed.
+// The old names must not be used in the new runtime.
 @_fixed_layout
 @usableFromInline
-internal class _EmptySetSingleton: _RawSetStorage {
+internal class __EmptySetSingleton: __RawSetStorage {
   @nonobjc
   override internal init(_doNotCallMe: ()) {
     _internalInvariantFailure("This class cannot be directly initialized")
@@ -120,18 +126,18 @@
 #endif
 }
 
-extension _RawSetStorage {
+extension __RawSetStorage {
   /// The empty singleton that is used for every single Set that is created
   /// without any elements. The contents of the storage must never be mutated.
   @inlinable
   @nonobjc
-  internal static var empty: _EmptySetSingleton {
+  internal static var empty: __EmptySetSingleton {
     return Builtin.bridgeFromRawPointer(
       Builtin.addressof(&_swiftEmptySetSingleton))
   }
 }
 
-extension _EmptySetSingleton: _NSSetCore {
+extension __EmptySetSingleton: _NSSetCore {
 #if _runtime(_ObjC)
   //
   // NSSet implementation, assuming Self is the empty singleton
@@ -153,7 +159,7 @@
 
   @objc
   internal func objectEnumerator() -> _NSEnumerator {
-    return _SwiftEmptyNSEnumerator()
+    return __SwiftEmptyNSEnumerator()
   }
 
   @objc(countByEnumeratingWithState:objects:count:)
@@ -177,7 +183,7 @@
 
 @usableFromInline
 final internal class _SetStorage<Element: Hashable>
-  : _RawSetStorage, _NSSetCore {
+  : __RawSetStorage, _NSSetCore {
   // This type is made with allocWithTailElems, so no init is ever called.
   // But we still need to have an init to satisfy the compiler.
   @nonobjc
@@ -284,7 +290,7 @@
 extension _SetStorage {
   @usableFromInline
   @_effects(releasenone)
-  internal static func copy(original: _RawSetStorage) -> _SetStorage {
+  internal static func copy(original: __RawSetStorage) -> _SetStorage {
     return .allocate(
       scale: original._scale,
       age: original._age,
@@ -294,7 +300,7 @@
   @usableFromInline
   @_effects(releasenone)
   static internal func resize(
-    original: _RawSetStorage,
+    original: __RawSetStorage,
     capacity: Int,
     move: Bool
   ) -> _SetStorage {
@@ -313,7 +319,7 @@
   @usableFromInline
   @_effects(releasenone)
   static internal func convert(
-    _ cocoa: _CocoaSet,
+    _ cocoa: __CocoaSet,
     capacity: Int
   ) -> _SetStorage {
     let scale = _HashTable.scale(forCapacity: capacity)
diff --git a/stdlib/public/core/SetVariant.swift b/stdlib/public/core/SetVariant.swift
index 24e4e50..355b5188 100644
--- a/stdlib/public/core/SetVariant.swift
+++ b/stdlib/public/core/SetVariant.swift
@@ -31,7 +31,7 @@
   @_fixed_layout
   internal struct _Variant {
     @usableFromInline
-    internal var object: _BridgeStorage<_RawSetStorage>
+    internal var object: _BridgeStorage<__RawSetStorage>
 
     @inlinable
     @inline(__always)
@@ -52,7 +52,7 @@
 #if _runtime(_ObjC)
     @inlinable
     @inline(__always)
-    init(cocoa: __owned _CocoaSet) {
+    init(cocoa: __owned __CocoaSet) {
       self.object = _BridgeStorage(objC: cocoa.object)
     }
 #endif
@@ -103,8 +103,8 @@
 
 #if _runtime(_ObjC)
   @inlinable
-  internal var asCocoa: _CocoaSet {
-    return _CocoaSet(object.objCInstance)
+  internal var asCocoa: __CocoaSet {
+    return __CocoaSet(object.objCInstance)
   }
 #endif
 
@@ -318,7 +318,7 @@
 #if _runtime(_ObjC)
   @inlinable
   internal mutating func _migrateToNative(
-    _ cocoa: _CocoaSet,
+    _ cocoa: __CocoaSet,
     removing member: Element
   ) -> Element {
     // FIXME(performance): fuse data migration and element deletion into one
diff --git a/stdlib/public/core/StringBridge.swift b/stdlib/public/core/StringBridge.swift
index 9986269..21b7cb9 100644
--- a/stdlib/public/core/StringBridge.swift
+++ b/stdlib/public/core/StringBridge.swift
@@ -149,9 +149,9 @@
 #endif
     
     switch _unsafeAddressOfCocoaStringClass(str) {
-    case unsafeBitCast(_StringStorage.self, to: UInt.self):
+    case unsafeBitCast(__StringStorage.self, to: UInt.self):
       self = .storage
-    case unsafeBitCast(_SharedStringStorage.self, to: UInt.self):
+    case unsafeBitCast(__SharedStringStorage.self, to: UInt.self):
       self = .shared
     default:
       self = .cocoa
@@ -216,10 +216,10 @@
   switch _KnownCocoaString(cocoaString) {
   case .storage:
     return _unsafeUncheckedDowncast(
-      cocoaString, to: _StringStorage.self).asString._guts
+      cocoaString, to: __StringStorage.self).asString._guts
   case .shared:
     return _unsafeUncheckedDowncast(
-      cocoaString, to: _SharedStringStorage.self).asString._guts
+      cocoaString, to: __SharedStringStorage.self).asString._guts
 #if !(arch(i386) || arch(arm))
   case .tagged:
     return _StringGuts(_SmallString(taggedCocoa: cocoaString))
@@ -284,7 +284,7 @@
       // TODO: We'd rather emit a valid ObjC object statically than create a
       // shared string class instance.
       let gutsCountAndFlags = _guts._object._countAndFlags
-      return _SharedStringStorage(
+      return __SharedStringStorage(
         immortal: _guts._object.fastUTF8.baseAddress!,
         countAndFlags: _StringObject.CountAndFlags(
           sharedCount: _guts.count, isASCII: gutsCountAndFlags.isASCII))
@@ -302,12 +302,9 @@
 // The @_swift_native_objc_runtime_base attribute
 // This allows us to subclass an Objective-C class and use the fast Swift
 // memory allocator.
-@_fixed_layout // FIXME(sil-serialize-all)
 @objc @_swift_native_objc_runtime_base(__SwiftNativeNSStringBase)
-public class __SwiftNativeNSString {
-  @usableFromInline // FIXME(sil-serialize-all)
-  @objc
-  internal init() {}
+class __SwiftNativeNSString {
+  @objc internal init() {}
   deinit {}
 }
 
diff --git a/stdlib/public/core/StringCreate.swift b/stdlib/public/core/StringCreate.swift
index ec032c1..d647c12 100644
--- a/stdlib/public/core/StringCreate.swift
+++ b/stdlib/public/core/StringCreate.swift
@@ -15,13 +15,33 @@
 internal func _allASCII(_ input: UnsafeBufferPointer<UInt8>) -> Bool {
   // NOTE: Avoiding for-in syntax to avoid bounds checks
   //
-  // TODO(String performance): Vectorize and/or incorporate into validity
-  // checking, perhaps both.
+  // TODO(String performance): SIMD-ize
   //
   let ptr = input.baseAddress._unsafelyUnwrappedUnchecked
   var i = 0
-  while i < input.count {
-    guard ptr[i] <= 0x7F else { return false }
+
+  let count = input.count
+  let stride = MemoryLayout<UInt>.stride
+  let address = Int(bitPattern: ptr)
+
+  let wordASCIIMask = UInt(truncatingIfNeeded: 0x8080_8080_8080_8080 as UInt64)
+  let byteASCIIMask = UInt8(truncatingIfNeeded: wordASCIIMask)
+
+  while (address &+ i) % stride != 0 && i < count {
+    guard ptr[i] & byteASCIIMask == 0 else { return false }
+    i &+= 1
+  }
+
+  while (i &+ stride) <= count {
+    let word: UInt = UnsafePointer(
+      bitPattern: address &+ i
+    )._unsafelyUnwrappedUnchecked.pointee
+    guard word & wordASCIIMask == 0 else { return false }
+    i &+= stride
+  }
+
+  while i < count {
+    guard ptr[i] & byteASCIIMask == 0 else { return false }
     i &+= 1
   }
   return true
@@ -38,16 +58,14 @@
       return String(_StringGuts(smol))
     }
 
-    let storage = _StringStorage.create(initializingFrom: input, isASCII: true)
+    let storage = __StringStorage.create(initializingFrom: input, isASCII: true)
     return storage.asString
   }
 
-  @usableFromInline
-  internal static func _tryFromUTF8(
-    _ input: UnsafeBufferPointer<UInt8>
-  ) -> String? {
+  public // SPI(Foundation)
+  static func _tryFromUTF8(_ input: UnsafeBufferPointer<UInt8>) -> String? {
     guard case .success(let extraInfo) = validateUTF8(input) else {
-        return nil
+      return nil
     }
 
     return String._uncheckedFromUTF8(input, isASCII: extraInfo.isASCII)
@@ -83,7 +101,7 @@
       return String(_StringGuts(smol))
     }
 
-    let storage = _StringStorage.create(
+    let storage = __StringStorage.create(
       initializingFrom: input, isASCII: isASCII)
     return storage.asString
   }
@@ -98,7 +116,7 @@
     }
 
     let isASCII = asciiPreScanResult
-    let storage = _StringStorage.create(
+    let storage = __StringStorage.create(
       initializingFrom: input, isASCII: isASCII)
     return storage.asString
   }
diff --git a/stdlib/public/core/StringGuts.swift b/stdlib/public/core/StringGuts.swift
index 03aeb06..f90a886 100644
--- a/stdlib/public/core/StringGuts.swift
+++ b/stdlib/public/core/StringGuts.swift
@@ -56,11 +56,11 @@
   }
 
   @inline(__always)
-  internal init(_ storage: _StringStorage) {
+  internal init(_ storage: __StringStorage) {
     self.init(_StringObject(storage))
   }
 
-  internal init(_ storage: _SharedStringStorage) {
+  internal init(_ storage: __SharedStringStorage) {
     self.init(_StringObject(storage))
   }
 
diff --git a/stdlib/public/core/StringGutsRangeReplaceable.swift b/stdlib/public/core/StringGutsRangeReplaceable.swift
index f1c918d..fc27b12 100644
--- a/stdlib/public/core/StringGutsRangeReplaceable.swift
+++ b/stdlib/public/core/StringGutsRangeReplaceable.swift
@@ -84,7 +84,7 @@
     if _fastPath(isFastUTF8) {
       let isASCII = self.isASCII
       let storage = self.withFastUTF8 {
-        _StringStorage.create(
+        __StringStorage.create(
           initializingFrom: $0, capacity: growthTarget, isASCII: isASCII)
       }
 
@@ -101,7 +101,7 @@
     // into a StringStorage space.
     let selfUTF8 = Array(String(self).utf8)
     selfUTF8.withUnsafeBufferPointer {
-      self = _StringGuts(_StringStorage.create(
+      self = _StringGuts(__StringStorage.create(
         initializingFrom: $0, capacity: n, isASCII: self.isASCII))
     }
   }
diff --git a/stdlib/public/core/StringObject.swift b/stdlib/public/core/StringObject.swift
index 49b94f3..5bc877f 100644
--- a/stdlib/public/core/StringObject.swift
+++ b/stdlib/public/core/StringObject.swift
@@ -838,13 +838,13 @@
     }
   }
 
-  internal var nativeStorage: _StringStorage {
+  internal var nativeStorage: __StringStorage {
     @inline(__always) get {
 #if arch(i386) || arch(arm)
       guard case .native(let storage) = _variant else {
         _internalInvariantFailure()
       }
-      return _unsafeUncheckedDowncast(storage, to: _StringStorage.self)
+      return _unsafeUncheckedDowncast(storage, to: __StringStorage.self)
 #else
       _internalInvariant(hasNativeStorage)
       return Builtin.reinterpretCast(largeAddressBits)
@@ -852,13 +852,13 @@
     }
   }
 
-  internal var sharedStorage: _SharedStringStorage {
+  internal var sharedStorage: __SharedStringStorage {
     @inline(__always) get {
 #if arch(i386) || arch(arm)
       guard case .native(let storage) = _variant else {
         _internalInvariantFailure()
       }
-      return _unsafeUncheckedDowncast(storage, to: _SharedStringStorage.self)
+      return _unsafeUncheckedDowncast(storage, to: __SharedStringStorage.self)
 #else
       _internalInvariant(largeFastIsShared && !largeIsCocoa)
       _internalInvariant(hasSharedStorage)
@@ -982,7 +982,7 @@
   }
 
   @inline(__always)
-  internal init(_ storage: _StringStorage) {
+  internal init(_ storage: __StringStorage) {
 #if arch(i386) || arch(arm)
     self.init(
       variant: .native(storage),
@@ -996,7 +996,7 @@
 #endif
   }
 
-  internal init(_ storage: _SharedStringStorage) {
+  internal init(_ storage: __SharedStringStorage) {
 #if arch(i386) || arch(arm)
     self.init(
       variant: .native(storage),
@@ -1100,7 +1100,7 @@
       }
       if _countAndFlags.isNativelyStored {
         let anyObj = Builtin.reinterpretCast(largeAddressBits) as AnyObject
-        _internalInvariant(anyObj is _StringStorage)
+        _internalInvariant(anyObj is __StringStorage)
       }
     }
 
diff --git a/stdlib/public/core/StringStorage.swift b/stdlib/public/core/StringStorage.swift
index afb33ec..d6f2694 100644
--- a/stdlib/public/core/StringStorage.swift
+++ b/stdlib/public/core/StringStorage.swift
@@ -76,9 +76,8 @@
       fallthrough
     case (_cocoaUTF8Encoding, _):
       guard maxLength >= count + 1 else { return 0 }
-      let buffer =
-        UnsafeMutableBufferPointer(start: outputPtr, count: maxLength)
-      buffer.initialize(from: UnsafeBufferPointer(start: start, count: count))
+      let buffer = UnsafeMutableBufferPointer(start: outputPtr, count: maxLength)
+      _ = buffer.initialize(from: UnsafeBufferPointer(start: start, count: count))
       buffer[count] = 0
       return 1
     default:
@@ -127,10 +126,10 @@
     switch knownOther {
     case .storage:
       return _nativeIsEqual(
-        _unsafeUncheckedDowncast(other, to: _StringStorage.self))
+        _unsafeUncheckedDowncast(other, to: __StringStorage.self))
     case .shared:
       return _nativeIsEqual(
-        _unsafeUncheckedDowncast(other, to: _SharedStringStorage.self))
+        _unsafeUncheckedDowncast(other, to: __SharedStringStorage.self))
 #if !(arch(i386) || arch(arm))
     case .tagged:
       fallthrough
@@ -173,7 +172,10 @@
 // Optional<_StringBreadcrumbs>.
 //
 
-final internal class _StringStorage
+// NOTE: older runtimes called this class _StringStorage. The two
+// must coexist without conflicting ObjC class names, so it was
+// renamed. The old name must not be used in the new runtime.
+final internal class __StringStorage
   : __SwiftNativeNSString, _AbstractStringStorage {
 #if arch(i386) || arch(arm)
   // The total allocated storage capacity. Note that this includes the required
@@ -300,7 +302,7 @@
 
   @objc(copyWithZone:)
   final internal func copy(with zone: _SwiftNSZone?) -> AnyObject {
-    // While _StringStorage instances aren't immutable in general,
+    // While __StringStorage instances aren't immutable in general,
     // mutations may only occur when instances are uniquely referenced.
     // Therefore, it is safe to return self here; any outstanding Objective-C
     // reference will make the instance non-unique.
@@ -351,13 +353,13 @@
 }
 
 // Creation
-extension _StringStorage {
+extension __StringStorage {
   @_effects(releasenone)
   private static func create(
     realCodeUnitCapacity: Int, countAndFlags: CountAndFlags
-  ) -> _StringStorage {
+  ) -> __StringStorage {
     let storage = Builtin.allocWithTailElems_2(
-      _StringStorage.self,
+      __StringStorage.self,
       realCodeUnitCapacity._builtinWordValue, UInt8.self,
       1._builtinWordValue, Optional<_StringBreadcrumbs>.self)
 #if arch(i386) || arch(arm)
@@ -381,12 +383,12 @@
   @_effects(releasenone)
   private static func create(
     capacity: Int, countAndFlags: CountAndFlags
-  ) -> _StringStorage {
+  ) -> __StringStorage {
     _internalInvariant(capacity >= countAndFlags.count)
 
     let realCapacity = determineCodeUnitCapacity(capacity)
     _internalInvariant(realCapacity > capacity)
-    return _StringStorage.create(
+    return __StringStorage.create(
       realCodeUnitCapacity: realCapacity, countAndFlags: countAndFlags)
   }
 
@@ -395,11 +397,11 @@
     initializingFrom bufPtr: UnsafeBufferPointer<UInt8>,
     capacity: Int,
     isASCII: Bool
-  ) -> _StringStorage {
+  ) -> __StringStorage {
     let countAndFlags = CountAndFlags(
       mortalCount: bufPtr.count, isASCII: isASCII)
     _internalInvariant(capacity >= bufPtr.count)
-    let storage = _StringStorage.create(
+    let storage = __StringStorage.create(
       capacity: capacity, countAndFlags: countAndFlags)
     let addr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked
     storage.mutableStart.initialize(from: addr, count: bufPtr.count)
@@ -410,14 +412,14 @@
   @_effects(releasenone)
   internal static func create(
     initializingFrom bufPtr: UnsafeBufferPointer<UInt8>, isASCII: Bool
-  ) -> _StringStorage {
-    return _StringStorage.create(
+  ) -> __StringStorage {
+    return __StringStorage.create(
       initializingFrom: bufPtr, capacity: bufPtr.count, isASCII: isASCII)
   }
 }
 
 // Usage
-extension _StringStorage {
+extension __StringStorage {
   @inline(__always)
   private var mutableStart: UnsafeMutablePointer<UInt8> {
     return UnsafeMutablePointer(Builtin.projectTailElems(self, UInt8.self))
@@ -505,7 +507,7 @@
 }
 
 // Appending
-extension _StringStorage {
+extension __StringStorage {
   // Perform common post-RRC adjustments and invariant enforcement.
   @_effects(releasenone)
   private func _postRRCAdjust(newCount: Int, newIsASCII: Bool) {
@@ -565,7 +567,7 @@
 }
 
 // Removing
-extension _StringStorage {
+extension __StringStorage {
   @_effects(releasenone)
   internal func remove(from lower: Int, to upper: Int) {
     _internalInvariant(lower <= upper)
@@ -647,7 +649,10 @@
 }
 
 // For shared storage and bridging literals
-final internal class _SharedStringStorage
+// NOTE: older runtimes called this class _SharedStringStorage. The two
+// must coexist without conflicting ObjC class names, so it was
+// renamed. The old name must not be used in the new runtime.
+final internal class __SharedStringStorage
   : __SwiftNativeNSString, _AbstractStringStorage {
   internal var _owner: AnyObject?
   internal var start: UnsafePointer<UInt8>
@@ -776,7 +781,7 @@
 
   @objc(copyWithZone:)
   final internal func copy(with zone: _SwiftNSZone?) -> AnyObject {
-    // While _StringStorage instances aren't immutable in general,
+    // While __StringStorage instances aren't immutable in general,
     // mutations may only occur when instances are uniquely referenced.
     // Therefore, it is safe to return self here; any outstanding Objective-C
     // reference will make the instance non-unique.
@@ -787,7 +792,7 @@
 
 }
 
-extension _SharedStringStorage {
+extension __SharedStringStorage {
 #if !INTERNAL_CHECKS_ENABLED
   @inline(__always)
   internal func _invariantCheck() {}
diff --git a/stdlib/public/core/StringUTF8Validation.swift b/stdlib/public/core/StringUTF8Validation.swift
index a5dba8f..bfb4d14 100644
--- a/stdlib/public/core/StringUTF8Validation.swift
+++ b/stdlib/public/core/StringUTF8Validation.swift
@@ -36,6 +36,10 @@
 private struct UTF8ValidationError: Error {}
 
 internal func validateUTF8(_ buf: UnsafeBufferPointer<UInt8>) -> UTF8ValidationResult {
+  if _allASCII(buf) {
+    return .success(UTF8ExtraInfo(isASCII: true))
+  }
+
   var iter = buf.makeIterator()
   var lastValidIndex = buf.startIndex
 
diff --git a/stdlib/public/core/SwiftNativeNSArray.swift b/stdlib/public/core/SwiftNativeNSArray.swift
index f6a6d1e..1c18175 100644
--- a/stdlib/public/core/SwiftNativeNSArray.swift
+++ b/stdlib/public/core/SwiftNativeNSArray.swift
@@ -160,10 +160,10 @@
       to: Optional<AnyObject>.self)
   }
 
-  internal var _heapBufferBridged: _BridgingBufferStorage? {
+  internal var _heapBufferBridged: __BridgingBufferStorage? {
     if let ref =
       _stdlib_atomicLoadARCRef(object: _heapBufferBridgedPtr) {
-      return unsafeBitCast(ref, to: _BridgingBufferStorage.self)
+      return unsafeBitCast(ref, to: __BridgingBufferStorage.self)
     }
     return nil
   }
@@ -174,7 +174,7 @@
     self._nativeStorage = _nativeStorage
   }
 
-  internal func _destroyBridgedStorage(_ hb: _BridgingBufferStorage?) {
+  internal func _destroyBridgedStorage(_ hb: __BridgingBufferStorage?) {
     if let bridgedStorage = hb {
       let buffer = _BridgingBuffer(bridgedStorage)
       let count = buffer.count
@@ -216,7 +216,7 @@
 
           // Another thread won the race.  Throw out our buffer.
           _destroyBridgedStorage(
-            unsafeDowncast(objects.storage!, to: _BridgingBufferStorage.self))
+            unsafeDowncast(objects.storage!, to: __BridgingBufferStorage.self))
         }
         continue // Try again
       }
diff --git a/stdlib/public/runtime/Metadata.cpp b/stdlib/public/runtime/Metadata.cpp
index 6dc2e3e..ce888e4 100644
--- a/stdlib/public/runtime/Metadata.cpp
+++ b/stdlib/public/runtime/Metadata.cpp
@@ -2204,9 +2204,24 @@
 
   auto string = Demangle::mangleNodeOld(globalNode);
 
-  auto fullNameBuf = (char*)swift_slowAlloc(string.size() + 1, 0);
+  // If the class is in the Swift module, add a $ to the end of the ObjC
+  // name. The old and new Swift libraries must be able to coexist in
+  // the same process, and this avoids warnings due to the ObjC names
+  // colliding.
+  bool addSuffix = strncmp(string.c_str(), "_TtGCs", 6) == 0;
+
+  size_t allocationSize = string.size() + 1;
+  if (addSuffix)
+    allocationSize += 1;
+  
+  auto fullNameBuf = (char*)swift_slowAlloc(allocationSize, 0);
   memcpy(fullNameBuf, string.c_str(), string.size() + 1);
 
+  if (addSuffix) {
+    fullNameBuf[string.size()] = '$';
+    fullNameBuf[string.size() + 1] = '\0';
+  }
+
   auto theMetaclass = (ClassMetadata *)object_getClass((id)theClass);
 
   getROData(theClass)->Name = fullNameBuf;
diff --git a/stdlib/public/runtime/MetadataLookup.cpp b/stdlib/public/runtime/MetadataLookup.cpp
index 6f511cc..073869c 100644
--- a/stdlib/public/runtime/MetadataLookup.cpp
+++ b/stdlib/public/runtime/MetadataLookup.cpp
@@ -1677,11 +1677,15 @@
       replacedFunctionKey->root.get());
 
   // Make sure this entry is not already enabled.
+  // This does not work until we make sure that when a dynamic library is
+  // unloaded all descriptors are removed.
+#if 0
   for (auto *curr = chainRoot; curr != nullptr; curr = curr->next) {
     if (curr == chainEntry.get()) {
       swift::swift_abortDynamicReplacementEnabling();
     }
   }
+#endif
 
   // Unlink the previous entry if we are not chaining.
   if (!shouldChain() && chainRoot->next) {
diff --git a/stdlib/public/runtime/SwiftObject.h b/stdlib/public/runtime/SwiftObject.h
index 10e6d68..a730d51 100644
--- a/stdlib/public/runtime/SwiftObject.h
+++ b/stdlib/public/runtime/SwiftObject.h
@@ -88,11 +88,4 @@
 
 #endif
 
-namespace swift {
-
-SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_SPI
-HeapObject *_swift_reallocObject(HeapObject *obj, size_t size);
-
-}
-
 #endif
diff --git a/stdlib/public/runtime/SwiftObject.mm b/stdlib/public/runtime/SwiftObject.mm
index 14b8c53..db459da 100644
--- a/stdlib/public/runtime/SwiftObject.mm
+++ b/stdlib/public/runtime/SwiftObject.mm
@@ -82,24 +82,6 @@
 #endif
 }
 
-bool isObjCPinned(HeapObject *obj) {
-  #if SWIFT_OBJC_INTEROP
-    /* future: implement checking the relevant objc runtime bits */
-    return true;
-  #else
-    return false;
-  #endif
-}
-
-// returns non-null if realloc was successful
-SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_SPI
-HeapObject *swift::_swift_reallocObject(HeapObject *obj, size_t size) {
- if (isObjCPinned(obj) || obj->refCounts.hasSideTable()) {
-   return nullptr;
- }
- return (HeapObject *)realloc(obj, size);
-}
-
 #if SWIFT_OBJC_INTEROP
 
 /// \brief Replacement for ObjC object_isClass(), which is unavailable on
diff --git a/stdlib/public/stubs/GlobalObjects.cpp b/stdlib/public/stubs/GlobalObjects.cpp
index aeed5ae..a59c3c1 100644
--- a/stdlib/public/stubs/GlobalObjects.cpp
+++ b/stdlib/public/stubs/GlobalObjects.cpp
@@ -28,13 +28,13 @@
 SWIFT_RUNTIME_STDLIB_API
 ClassMetadata CLASS_METADATA_SYM(s19__EmptyArrayStorage);
 
-// _direct type metadata for Swift._EmptyDictionarySingleton
+// _direct type metadata for Swift.__EmptyDictionarySingleton
 SWIFT_RUNTIME_STDLIB_API
-ClassMetadata CLASS_METADATA_SYM(s25_EmptyDictionarySingleton);
+ClassMetadata CLASS_METADATA_SYM(s26__EmptyDictionarySingleton);
 
-// _direct type metadata for Swift._EmptySetSingleton
+// _direct type metadata for Swift.__EmptySetSingleton
 SWIFT_RUNTIME_STDLIB_API
-ClassMetadata CLASS_METADATA_SYM(s18_EmptySetSingleton);
+ClassMetadata CLASS_METADATA_SYM(s19__EmptySetSingleton);
 } // namespace swift
 
 SWIFT_RUNTIME_STDLIB_API
@@ -55,7 +55,7 @@
 swift::_SwiftEmptyDictionarySingleton swift::_swiftEmptyDictionarySingleton = {
   // HeapObject header;
   {
-    &swift::CLASS_METADATA_SYM(s25_EmptyDictionarySingleton), // isa pointer
+    &swift::CLASS_METADATA_SYM(s26__EmptyDictionarySingleton), // isa pointer
   },
   
   // _SwiftDictionaryBodyStorage body;
@@ -82,7 +82,7 @@
 swift::_SwiftEmptySetSingleton swift::_swiftEmptySetSingleton = {
   // HeapObject header;
   {
-    &swift::CLASS_METADATA_SYM(s18_EmptySetSingleton), // isa pointer
+    &swift::CLASS_METADATA_SYM(s19__EmptySetSingleton), // isa pointer
   },
   
   // _SwiftSetBodyStorage body;
diff --git a/test/CircularReferences/protocols.swift b/test/CircularReferences/protocols.swift
new file mode 100644
index 0000000..d071907
--- /dev/null
+++ b/test/CircularReferences/protocols.swift
@@ -0,0 +1,12 @@
+// RUN: %target-typecheck-verify-swift -debug-cycles 2>&1 | %FileCheck --allow-empty %s
+
+// Verify that protocol where clause lookups don't cause cyclic dependencies.
+
+// expected-no-diagnostics
+
+class C { }
+protocol Q { }
+protocol P where Self : Q, Self : C { }
+
+// CHECK-NOT: CYCLE DETECTED
+
diff --git a/test/ClangImporter/private_frameworks.swift b/test/ClangImporter/private_frameworks.swift
index fe36da2..733ec81 100644
--- a/test/ClangImporter/private_frameworks.swift
+++ b/test/ClangImporter/private_frameworks.swift
@@ -12,7 +12,7 @@
 // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-sil -o /dev/null -F %S/Inputs/privateframeworks/withprivate -swift-version 4 %s -import-objc-header %S/Inputs/privateframeworks/bridging-somekitcore.h -verify
 
 // Use the overlay without private frameworks.
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-sil -o /dev/null -F %S/Inputs/privateframeworks/withoutprivate -I %t -swift-version 4 -import-objc-header %S/Inputs/privateframeworks/bridging-somekit.h %s
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-sil -o /dev/null -F %S/Inputs/privateframeworks/withoutprivate -swift-version 4 -import-objc-header %S/Inputs/privateframeworks/bridging-somekit.h %s
 
 // Build the overlay with public frameworks.
 // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -F %S/Inputs/privateframeworks/withoutprivate -o %t %S/Inputs/privateframeworks/overlay/SomeKit.swift
@@ -21,7 +21,18 @@
 // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-sil -o /dev/null -F %S/Inputs/privateframeworks/withprivate -swift-version 4 %s -import-objc-header %S/Inputs/privateframeworks/bridging-somekitcore.h -verify
 
 // Use the overlay without private frameworks.
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-sil -o /dev/null -F %S/Inputs/privateframeworks/withoutprivate -I %t -swift-version 4 %s -import-objc-header %S/Inputs/privateframeworks/bridging-somekit.h 
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-sil -o /dev/null -F %S/Inputs/privateframeworks/withoutprivate -swift-version 4 %s -import-objc-header %S/Inputs/privateframeworks/bridging-somekit.h 
+
+// Use something that uses the overlay.
+// RUN: echo 'import private_frameworks; testErrorConformance()' > %t/main.swift
+
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t -F %S/Inputs/privateframeworks/withprivate -swift-version 4 %s -import-objc-header %S/Inputs/privateframeworks/bridging-somekitcore.h
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-sil -o /dev/null -F %S/Inputs/privateframeworks/withprivate %t/main.swift -verify
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-sil -o /dev/null -F %S/Inputs/privateframeworks/withoutprivate %t/main.swift -verify
+
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t -F %S/Inputs/privateframeworks/withoutprivate -swift-version 4 %s -import-objc-header %S/Inputs/privateframeworks/bridging-somekit.h
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-sil -o /dev/null -F %S/Inputs/privateframeworks/withprivate %t/main.swift -verify
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-sil -o /dev/null -F %S/Inputs/privateframeworks/withoutprivate %t/main.swift -verify
 
 // REQUIRES: objc_interop
 
@@ -50,3 +61,6 @@
   SomeKit.someKitOtherGlobalFunc()
   someKitOtherGlobalFunc()
 }
+
+public struct ErrorsOnly<T: Error> {}
+public func testErrorConformance(_ code: ErrorsOnly<SKWidget.Error>? = nil) {}
diff --git a/test/Driver/debug_anonymous_context_metadata.swift b/test/Driver/debug_anonymous_context_metadata.swift
new file mode 100644
index 0000000..7138ab2
--- /dev/null
+++ b/test/Driver/debug_anonymous_context_metadata.swift
@@ -0,0 +1,4 @@
+// RUN: %target-swiftc_driver -### -g %s 2>&1 | %FileCheck %s
+
+// CHECK: -enable-anonymous-context-mangled-names
+
diff --git a/test/IDE/clang-importing/Inputs/bridge.h b/test/IDE/clang-importing/Inputs/bridge.h
index 920e7aa..77a08a9 100644
--- a/test/IDE/clang-importing/Inputs/bridge.h
+++ b/test/IDE/clang-importing/Inputs/bridge.h
@@ -1 +1,4 @@
+@import Foundation;
 @import somemod1;
+
+void func_in_bridge(void);
diff --git a/test/IDE/clang-importing/complete_with_clang_comments.swift b/test/IDE/clang-importing/complete_with_clang_comments.swift
index dfa17fa..b3816c0 100644
--- a/test/IDE/clang-importing/complete_with_clang_comments.swift
+++ b/test/IDE/clang-importing/complete_with_clang_comments.swift
@@ -1,5 +1,7 @@
-// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP -code-completion-comments=true \
+// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=TOP -code-completion-comments=true \
 // RUN:    -import-objc-header %S/Inputs/bridge.h -I %S/Inputs/somemod1 -I %S/Inputs/somemod2 | %FileCheck %s -check-prefix=CHECK-TOP
+// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=TOP -code-completion-comments=true \
+// RUN:    -import-objc-header %S/Inputs/bridge.h -pch-output-dir %t.pch -I %S/Inputs/somemod1 -I %S/Inputs/somemod2 | %FileCheck %s -check-prefix=CHECK-TOP
 
 // REQUIRES: objc_interop
 
diff --git a/test/IDE/structure.swift b/test/IDE/structure.swift
index bb81c26..783eac6 100644
--- a/test/IDE/structure.swift
+++ b/test/IDE/structure.swift
@@ -282,3 +282,8 @@
 // CHECK: <call><name>completion</name>(<arg><name>a</name>: 1</arg>) <arg><closure>{ (<param>x: <type>Any</type></param>, <param>y: <type>Int</type></param>) -> <type>Int</type> in
 // CHECK:    return x as! Int + y
 // CHECK: }</closure></arg></call>
+
+myFunc(foo: 0,
+       bar: baz == 0)
+// CHECK: <call><name>myFunc</name>(<arg><name>foo</name>: 0</arg>,
+// CHECK:        <arg><name>bar</name>: baz == 0</arg>)</call>
diff --git a/test/IRGen/anonymous_context_descriptors.sil b/test/IRGen/anonymous_context_descriptors.sil
index 3097d5a..82d973b 100644
--- a/test/IRGen/anonymous_context_descriptors.sil
+++ b/test/IRGen/anonymous_context_descriptors.sil
@@ -1,4 +1,5 @@
 // RUN: %target-swift-frontend -emit-ir %s | %FileCheck %s
+// RUN: %target-swift-frontend -emit-ir -enable-anonymous-context-mangled-names %s | %FileCheck %s -check-prefix CHECK-MANGLED
 
 import Builtin
 import Swift
@@ -9,15 +10,30 @@
   private struct Inner<U: P> { }
 }
 
+// Mangled name of the anonymous descriptor
+// CHECK-NOT: private constant [84 x i8] c"$s29anonymous_context_descriptors4BlahC5Inner33_4F495173994818481DD703D65EB08308LLV\00"
+// CHECK-MANGLED: [[INNER_MANGLED:@[0-9]+]] = private constant [84 x i8] c"$s29anonymous_context_descriptors4BlahC5Inner33_4F495173994818481DD703D65EB08308LLV\00"
+
 // Anonymous descriptor
 // CHECK: @"$s29anonymous_context_descriptors4BlahC5Inner33{{.*}}MXX" =
+// CHECK-MANGLED: @"$s29anonymous_context_descriptors4BlahC5Inner33{{.*}}MXX" =
 
 // Flags: anonymous (2) + generic (0x80) + unique (0x40)
 // CHECK-SAME: i32 194
 
+// Flags: anonymous (2) + generic (0x80) + unique (0x40) + has mangled name (0x10000)
+// CHECK-MANGLED-SAME: i32 65730
+
 // Parent
 // CHECK-SAME: $s29anonymous_context_descriptors4BlahCMn
+// CHECK-MANGLED-SAME: $s29anonymous_context_descriptors4BlahCMn
 
 // # generic header
 // CHECK-SAME: i16 2, i16 2
 // CHECK-SAME: i16 4, i16 0
+
+// CHECK-MANGLED-SAME: i16 2, i16 2
+// CHECK-MANGLED-SAME: i16 4, i16 0
+
+// # mangled name
+// CHECK-MANGLED-SAME: [[INNER_MANGLED]]
diff --git a/test/IRGen/objc.swift b/test/IRGen/objc.swift
index d6f68e1..543b565 100644
--- a/test/IRGen/objc.swift
+++ b/test/IRGen/objc.swift
@@ -147,7 +147,7 @@
 // CHECK:  i32 1, !"Objective-C Version", i32 2}
 // CHECK:  i32 1, !"Objective-C Image Info Version", i32 0}
 // CHECK:  i32 1, !"Objective-C Image Info Section", !"__DATA,__objc_imageinfo,regular,no_dead_strip"}
-//   67241472 == (5 << 24) | (0 << 16) | (6 << 8). 
-//     5 and 0 is the current major.minor version. 6 is the Swift ABI version.
-// CHECK:  i32 4, !"Objective-C Garbage Collection", i32 83887616}
-// CHECK:  i32 1, !"Swift Version", i32 6}
+//   83887872 == (5 << 24) | (0 << 16) | (7 << 8). 
+//     5 and 0 is the current major.minor version. 7 is the Swift ABI version.
+// CHECK:  i32 4, !"Objective-C Garbage Collection", i32 83887872}
+// CHECK:  i32 1, !"Swift Version", i32 7}
diff --git a/test/IRGen/static_initializer.sil b/test/IRGen/static_initializer.sil
index 9e6369e..8c64c78 100644
--- a/test/IRGen/static_initializer.sil
+++ b/test/IRGen/static_initializer.sil
@@ -103,25 +103,6 @@
 }
 // CHECK: @static_array_with_empty_element = {{( dllexport)?}}{{(protected )?}}global %T18static_initializer16TestArrayStorageC_tailelems3c { [1 x i64] zeroinitializer, %T18static_initializer16TestArrayStorageC_tailelems3 <{ %swift.refcounted zeroinitializer, %Ts5Int32V <{ i32 2 }>, [1 x i8] undef, [1 x i8] undef }> }, align 8
 
-struct MyString {
-  var buffer: Builtin.BridgeObject
-}
-
-sil_global [let] @string_with_offset : $MyString = {
-  %0 = integer_literal $Builtin.Int64, -9223372036854775808
-  %1 = integer_literal $Builtin.Int1, 0
-  %2 = integer_literal $Builtin.Int64, 32
-  %3 = string_literal utf8 "abc123asd3sdj3basfasdf"
-  %4 = builtin "ptrtoint_Word"(%3 : $Builtin.RawPointer) : $Builtin.Word
-  %5 = builtin "zextOrBitCast_Word_Int64"(%4 : $Builtin.Word) : $Builtin.Int64
-  %6 = builtin "usub_with_overflow_Int64"(%5 : $Builtin.Int64, %2 : $Builtin.Int64, %1 : $Builtin.Int1) : $(Builtin.Int64, Builtin.Int1)
-  %7 = tuple_extract %6 : $(Builtin.Int64, Builtin.Int1), 0
-  %8 = builtin "stringObjectOr_Int64"(%7 : $Builtin.Int64, %0 : $Builtin.Int64) : $Builtin.Int64
-  %9 = value_to_bridge_object %8 : $Builtin.Int64
-  %initval = struct $MyString (%9 : $Builtin.BridgeObject)
-}
-// CHECK: @string_with_offset = {{.*global .*}} <{ %swift.bridge* inttoptr (i64 add (i64 ptrtoint ([23 x i8]* @0 to i64), i64 9223372036854775776) to %swift.bridge*) }>, align 8
-
 // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i8* @_TF2cha1xSi() {{.*}} {
 // CHECK-NEXT: entry:
 // CHECK-NEXT: ret i8* bitcast (%Ts5Int32V* @"$s2ch1xSiv" to i8*)
diff --git a/test/Interpreter/Inputs/dynamic_replacement_dlclose.swift b/test/Interpreter/Inputs/dynamic_replacement_dlclose.swift
new file mode 100644
index 0000000..036eff0
--- /dev/null
+++ b/test/Interpreter/Inputs/dynamic_replacement_dlclose.swift
@@ -0,0 +1,9 @@
+struct A {
+  dynamic var value : Int {
+    return 1
+  }
+}
+
+public func test() -> Int{
+  return A().value
+}
diff --git a/test/Interpreter/Inputs/dynamic_replacement_dlclose2.swift b/test/Interpreter/Inputs/dynamic_replacement_dlclose2.swift
new file mode 100644
index 0000000..3b9e4a1
--- /dev/null
+++ b/test/Interpreter/Inputs/dynamic_replacement_dlclose2.swift
@@ -0,0 +1,8 @@
+@_private(sourceFile: "dynamic_replacement_dlclose.swift") import Module1
+
+extension A {
+  @_dynamicReplacement(for: value)
+  var repl: Int {
+    return 2
+  }
+}
diff --git a/test/Interpreter/dynamic_replacement_dlclose.swift b/test/Interpreter/dynamic_replacement_dlclose.swift
new file mode 100644
index 0000000..59b50e9
--- /dev/null
+++ b/test/Interpreter/dynamic_replacement_dlclose.swift
@@ -0,0 +1,70 @@
+// RUN: %empty-directory(%t)
+// RUN: %target-build-swift-dylib(%t/libModule1.%target-dylib-extension) -DMODULE -module-name Module1 -emit-module -emit-module-path %t/Module1.swiftmodule -swift-version 5 %S/Inputs/dynamic_replacement_dlclose.swift -Xfrontend -enable-private-imports
+// RUN: %target-build-swift-dylib(%t/libModule2.%target-dylib-extension) -I%t -L%t -lModule1 -Xlinker -rpath -Xlinker %t -DMODULE2 -module-name Module2 -emit-module -emit-module-path %t/Module2.swiftmodule -swift-version 5 %S/Inputs/dynamic_replacement_dlclose2.swift
+// RUN: %target-build-swift -I%t -L%t -lModule1 -DMAIN -o %t/main -Xlinker -rpath -Xlinker %t %s -swift-version 5
+// RUN: %target-codesign %t/main %t/libModule1.%target-dylib-extension %t/libModule2.%target-dylib-extension
+// RUN: %target-run %t/main %t/libModule1.%target-dylib-extension %t/libModule2.%target-dylib-extension
+
+
+import Module1
+
+import StdlibUnittest
+
+#if os(Linux)
+  import Glibc
+#elseif os(Windows)
+  import MSVCRT
+  import WinSDK
+#else
+  import Darwin
+#endif
+
+var DynamicallyReplaceable = TestSuite("DynamicallyReplaceable")
+
+
+
+private func target_library_name(_ name: String) -> String {
+#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
+  return "lib\(name).dylib"
+#elseif os(Windows)
+  return "\(name).dll"
+#else
+  return "lib\(name).so"
+#endif
+}
+
+
+DynamicallyReplaceable.test("DynamicallyReplaceable") {
+  var executablePath = CommandLine.arguments[0]
+  executablePath.removeLast(4)
+  expectEqual(1, test())
+  // Now, test with the module containing the replacements.
+
+#if os(Linux)
+	let h = dlopen(target_library_name("Module2"), RTLD_NOW)
+#elseif os(Windows)
+  let h = LoadLibraryA(target_library_name("Module2"))
+#else
+	let h = dlopen(executablePath+target_library_name("Module2"), RTLD_NOW)
+#endif
+
+  expectEqual(2, test())
+
+#if os(Linux)
+  dlclose(h!)
+#elseif os(Windows)
+#else
+  dlclose(h)
+#endif
+
+#if os(Linux)
+  _ = dlopen(target_library_name("Module2"), RTLD_NOW)
+#elseif os(Windows)
+#else
+	_ = dlopen(executablePath+target_library_name("Module2"), RTLD_NOW)
+#endif
+  expectEqual(2, test())
+
+}
+
+runAllTests()
diff --git a/test/Migrator/Inputs/CallExpr.json b/test/Migrator/Inputs/CallExpr.json
new file mode 100644
index 0000000..ec11dd5
--- /dev/null
+++ b/test/Migrator/Inputs/CallExpr.json
@@ -0,0 +1,24 @@
+[
+  {
+    "DiffItemKind": "CommonDiffItem",
+    "NodeKind": "Function",
+    "NodeAnnotation": "WrapOptional",
+    "ChildIndex": "0",
+    "LeftUsr": "s:6CitiesAAC1xABSi_tcfc",
+    "LeftComment": "",
+    "RightUsr": "",
+    "RightComment": "",
+    "ModuleName": "Cities"
+  },
+  {
+    "DiffItemKind": "CommonDiffItem",
+    "NodeKind": "Function",
+    "NodeAnnotation": "WrapOptional",
+    "ChildIndex": "0",
+    "LeftUsr": "s:6CitiesAAC5noosaSaySDySSABGSgGyF",
+    "LeftComment": "",
+    "RightUsr": "",
+    "RightComment": "",
+    "ModuleName": "Cities"
+  }
+]
diff --git a/test/Migrator/call_expr_result.swift b/test/Migrator/call_expr_result.swift
new file mode 100644
index 0000000..01f1c8b
--- /dev/null
+++ b/test/Migrator/call_expr_result.swift
@@ -0,0 +1,13 @@
+// REQUIRES: objc_interop
+// RUN: %empty-directory(%t.mod)
+// RUN: %target-swift-frontend -emit-module -o %t.mod/Cities.swiftmodule %S/Inputs/Cities.swift -module-name Cities -parse-as-library
+// RUN: %empty-directory(%t) && %target-swift-frontend -c -update-code -disable-migrator-fixits -primary-file %s  -I %t.mod -api-diff-data-file %S/Inputs/CallExpr.json -emit-migrated-file-path %t/call_expr_result.swift.result -o /dev/null
+// RUN: diff -u %S/call_expr_result.swift.expected %t/call_expr_result.swift.result
+
+import Cities
+
+func foo() {
+  let c1 = Cities(x: 3)
+  _ = Cities.init(x: 3)
+  _ = c1.noosa()
+}
\ No newline at end of file
diff --git a/test/Migrator/call_expr_result.swift.expected b/test/Migrator/call_expr_result.swift.expected
new file mode 100644
index 0000000..4210d21
--- /dev/null
+++ b/test/Migrator/call_expr_result.swift.expected
@@ -0,0 +1,13 @@
+// REQUIRES: objc_interop
+// RUN: %empty-directory(%t.mod)
+// RUN: %target-swift-frontend -emit-module -o %t.mod/Cities.swiftmodule %S/Inputs/Cities.swift -module-name Cities -parse-as-library
+// RUN: %empty-directory(%t) && %target-swift-frontend -c -update-code -disable-migrator-fixits -primary-file %s  -I %t.mod -api-diff-data-file %S/Inputs/CallExpr.json -emit-migrated-file-path %t/call_expr_result.swift.result -o /dev/null
+// RUN: diff -u %S/call_expr_result.swift.expected %t/call_expr_result.swift.result
+
+import Cities
+
+func foo() {
+  let c1 = Cities(x: 3)!
+  _ = Cities.init(x: 3)!
+  _ = c1.noosa()!
+}
\ No newline at end of file
diff --git a/test/Migrator/rename.swift b/test/Migrator/rename.swift
index 1f66e5b..2b9ca6e 100644
--- a/test/Migrator/rename.swift
+++ b/test/Migrator/rename.swift
@@ -1,5 +1,5 @@
 // REQUIRES: objc_interop
-// RUN: %empty-directory(%t) && %target-swift-frontend -c -update-code -primary-file %s -F %S/mock-sdk -api-diff-data-file %S/Inputs/API.json -emit-migrated-file-path %t/rename.swift.result -emit-remap-file-path %t/rename.swift.remap -o /dev/null
+// RUN: %empty-directory(%t) && %target-swift-frontend -c -update-code -primary-file %s -F %S/mock-sdk -api-diff-data-file %S/Inputs/API.json -emit-migrated-file-path %t/rename.swift.result -emit-remap-file-path %t/rename.swift.remap -o /dev/null -disable-migrator-fixits
 // RUN: diff -u %S/rename.swift.expected %t/rename.swift.result
 
 import Bar
diff --git a/test/Migrator/rename.swift.expected b/test/Migrator/rename.swift.expected
index a19c26d..7f0670e 100644
--- a/test/Migrator/rename.swift.expected
+++ b/test/Migrator/rename.swift.expected
@@ -1,5 +1,5 @@
 // REQUIRES: objc_interop
-// RUN: %empty-directory(%t) && %target-swift-frontend -c -update-code -primary-file %s -F %S/mock-sdk -api-diff-data-file %S/Inputs/API.json -emit-migrated-file-path %t/rename.swift.result -emit-remap-file-path %t/rename.swift.remap -o /dev/null
+// RUN: %empty-directory(%t) && %target-swift-frontend -c -update-code -primary-file %s -F %S/mock-sdk -api-diff-data-file %S/Inputs/API.json -emit-migrated-file-path %t/rename.swift.result -emit-remap-file-path %t/rename.swift.remap -o /dev/null -disable-migrator-fixits
 // RUN: diff -u %S/rename.swift.expected %t/rename.swift.result
 
 import Bar
@@ -16,7 +16,7 @@
   b.barNewInstanceFunc1(newlabel1: 0, newlabel2: 1, newlabel3: 2, newlabel4: 3)
   barGlobalFuncNewName(newlabel: 2)
   _ = NewEnum.enumElement
-  _ = PropertyUserInterface.newMethodPlus()
+  _ = PropertyUserInterface.newMethodPlus()!
   let _: BarBase.Nested
   _ = AwesomeWrapper.newName(is: 0, at: 1, for: 2)
 }
diff --git a/test/Migrator/stdlib_rename.swift b/test/Migrator/stdlib_rename.swift
index 20397f3..d5ae2b3 100644
--- a/test/Migrator/stdlib_rename.swift
+++ b/test/Migrator/stdlib_rename.swift
@@ -6,6 +6,7 @@
 
 func test1(_ a: [String], s: String) {
   _ = a.index(of: s)
+  _ = a.index(where: { _ in true })
 }
 func test2(_ s: String, c: Character) {
   _ = s.index(of: c)
diff --git a/test/Migrator/stdlib_rename.swift.expected b/test/Migrator/stdlib_rename.swift.expected
index f721bf8..04dadba 100644
--- a/test/Migrator/stdlib_rename.swift.expected
+++ b/test/Migrator/stdlib_rename.swift.expected
@@ -6,6 +6,7 @@
 
 func test1(_ a: [String], s: String) {
   _ = a.firstIndex(of: s)
+  _ = a.firstIndex(where: { _ in true })
 }
 func test2(_ s: String, c: Character) {
   _ = s.firstIndex(of: c)
diff --git a/test/Migrator/wrap_optional.swift.expected b/test/Migrator/wrap_optional.swift.expected
index 78fe2b5..1316b6d 100644
--- a/test/Migrator/wrap_optional.swift.expected
+++ b/test/Migrator/wrap_optional.swift.expected
@@ -7,7 +7,7 @@
 import Cities
 
 class MyCities : Cities {
-  override init?(x: Int?) { super.init(x: x) }
+  override init?(x: Int?) { super.init(x: x)! }
   override init?(y: Int) { super.init(y: y) }
   override func newMooloolaba(newX x: Cities?, newY y: Cities) {}
   override func toowoomba(x: [Cities?], y: [Cities?]) {}
diff --git a/test/Misc/stats_dir_tracer.swift b/test/Misc/stats_dir_tracer.swift
index 12795d8..90be632 100644
--- a/test/Misc/stats_dir_tracer.swift
+++ b/test/Misc/stats_dir_tracer.swift
@@ -2,9 +2,9 @@
 // RUN: %target-swiftc_driver -o %t/main -module-name main -stats-output-dir %t %s -trace-stats-events
 // RUN: %FileCheck -input-file %t/*.csv %s
 
-// CHECK: {{[0-9]+,[0-9]+,"exit","typecheck-expr","Sema.NumTypesDeserialized",[0-9]+,[0-9]+,"Call","\[.*stats_dir_tracer.swift.*\]"}}
-// CHECK: {{[0-9]+,[0-9]+,"exit","typecheck-expr","Sema.NumConstraintScopes",[0-9]+,[0-9]+,"Sequence","\[.*stats_dir_tracer.swift.*\]"}}
-// CHECK: {{[0-9]+,[0-9]+,"exit","SuperclassDeclRequest","Sema.SuperclassDeclRequest",[0-9]+,[0-9]+,"Bar","\[.*stats_dir_tracer.swift.*\]"}}
+// CHECK-DAG: {{[0-9]+,[0-9]+,"exit","typecheck-expr","Sema.NumTypesDeserialized",[0-9]+,[0-9]+,"Call","\[.*stats_dir_tracer.swift.*\]"}}
+// CHECK-DAG: {{[0-9]+,[0-9]+,"exit","typecheck-expr","Sema.NumConstraintScopes",[0-9]+,[0-9]+,"Sequence","\[.*stats_dir_tracer.swift.*\]"}}
+// CHECK-DAG: {{[0-9]+,[0-9]+,"exit","SuperclassDeclRequest","Sema.SuperclassDeclRequest",[0-9]+,[0-9]+,"Bar","\[.*stats_dir_tracer.swift.*\]"}}
 
 public func foo() {
     print("hello")
diff --git a/test/NameBinding/Inputs/NIOFoundationCompat.swift b/test/NameBinding/Inputs/NIOFoundationCompat.swift
new file mode 100644
index 0000000..54bae53
--- /dev/null
+++ b/test/NameBinding/Inputs/NIOFoundationCompat.swift
@@ -0,0 +1,9 @@
+import Foundation
+
+extension Data {
+  @_inlineable
+  public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
+    let r: R? = nil
+    return r!
+  }
+}
diff --git a/test/NameBinding/nio_shadowing.swift b/test/NameBinding/nio_shadowing.swift
new file mode 100644
index 0000000..6cf5b39
--- /dev/null
+++ b/test/NameBinding/nio_shadowing.swift
@@ -0,0 +1,11 @@
+// RUN: %empty-directory(%t)
+// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/NIOFoundationCompat.swift
+// RUN: %target-swift-frontend -typecheck %s -I %t -verify
+
+// REQUIRES: objc_interop
+import Foundation
+import NIOFoundationCompat
+
+func test(data: Data) {
+  data.withUnsafeBytes { x in print(x) }
+}
diff --git a/test/RemoteAST/nominal_types.swift b/test/RemoteAST/nominal_types.swift
index b5385bd..4db9ae1 100644
--- a/test/RemoteAST/nominal_types.swift
+++ b/test/RemoteAST/nominal_types.swift
@@ -1,4 +1,4 @@
-// RUN: %target-swift-remoteast-test %s | %FileCheck %s
+// RUN: %target-swift-remoteast-test -enable-anonymous-context-mangled-names %s | %FileCheck %s
 
 // REQUIRES: swift-remoteast-test
 
@@ -92,3 +92,37 @@
 // CHECK: found type: J & K
 printType(KJ.self)
 // CHECK: found type: J & K
+
+struct L {
+  private struct PrivateInner { }
+  private struct PrivateInnerGeneric<T> { }
+
+  static func testPrivate() {
+    // CHECK: L.PrivateInner
+    printType(L.PrivateInner.self)
+
+    // CHECK: L.PrivateInnerGeneric<Int>
+    printType(L.PrivateInnerGeneric<Int>.self)
+
+    // CHECK: L.PrivateInnerGeneric<String>
+    printType(L.PrivateInnerGeneric<String>.self)
+  }
+}
+L.testPrivate()
+
+struct M<T, U> {
+  private struct Inner { }
+  private struct InnerGeneric<V> { }
+
+  static func testPrivate() {
+    // CHECK: M<Int, String>.Inner
+    printType(Inner.self)
+
+    // CHECK: M<Int, String>.InnerGeneric<Double>
+    printType(InnerGeneric<Double>.self)
+
+    // CHECK: M<Int, String>.InnerGeneric<(String, Int)>
+    printType(InnerGeneric<(U, T)>.self)
+  }
+}
+M<Int, String>.testPrivate()
diff --git a/test/SILGen/enum.swift b/test/SILGen/enum.swift
index 6dfc948..9fb8456 100644
--- a/test/SILGen/enum.swift
+++ b/test/SILGen/enum.swift
@@ -1,19 +1,11 @@
-
-// RUN: %target-swift-emit-silgen -parse-stdlib -parse-as-library -enable-sil-ownership -module-name Swift %s | %FileCheck %s
-
-precedencegroup AssignmentPrecedence { assignment: true }
-
-enum Optional<Wrapped> {
-  case none
-  case some(Wrapped)
-}
+// RUN: %target-swift-emit-silgen -parse-as-library -enable-sil-ownership %s | %FileCheck %s
 
 enum Boolish {
   case falsy
   case truthy
 }
 
-// CHECK-LABEL: sil hidden @$ss13Boolish_casesyyF
+// CHECK-LABEL: sil hidden @$s4enum13Boolish_casesyyF
 func Boolish_cases() {
   // CHECK:       [[BOOLISH:%[0-9]+]] = metatype $@thin Boolish.Type
   // CHECK-NEXT:  [[FALSY:%[0-9]+]] = enum $Boolish, #Boolish.falsy!enumelt
@@ -24,18 +16,16 @@
   _ = Boolish.truthy
 }
 
-struct Int {}
-
 enum Optionable {
   case nought
   case mere(Int)
 }
 
-// CHECK-LABEL: sil hidden @$ss16Optionable_casesyySiF
+// CHECK-LABEL: sil hidden @$s4enum16Optionable_casesyySiF
 func Optionable_cases(_ x: Int) {
 
   // CHECK:       [[METATYPE:%.*]] = metatype $@thin Optionable.Type
-  // CHECK:       [[FN:%.*]] = function_ref @$ss10OptionableO4mereyABSicABmF
+  // CHECK:       [[FN:%.*]] = function_ref @$s4enum10OptionableO4mereyACSicACmFTc
   // CHECK-NEXT:  [[CTOR:%.*]] = apply [[FN]]([[METATYPE]])
   // CHECK-NEXT:  destroy_value [[CTOR]]
   _ = Optionable.mere
@@ -45,13 +35,13 @@
   _ = Optionable.mere(x)
 }
 
-// CHECK-LABEL: sil shared [transparent] [thunk] @$ss10OptionableO4mereyABSicABmF
-// CHECK:        [[FN:%.*]] = function_ref @$ss10OptionableO4mereyABSicABmF
+// CHECK-LABEL: sil shared [transparent] [thunk] @$s4enum10OptionableO4mereyACSicACmF
+// CHECK:        [[FN:%.*]] = function_ref @$s4enum10OptionableO4mereyACSicACmF
 // CHECK-NEXT:   [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]](%0)
 // CHECK-NEXT:   return [[METHOD]]
 // CHECK-NEXT: }
 
-// CHECK-LABEL: sil shared [transparent] @$ss10OptionableO4mereyABSicABmF
+// CHECK-LABEL: sil shared [transparent] @$s4enum10OptionableO4mereyACSicACmF
 // CHECK:        [[RES:%.*]] = enum $Optionable, #Optionable.mere!enumelt.1, %0 : $Int
 // CHECK-NEXT:   return [[RES]] : $Optionable
 // CHECK-NEXT: }
@@ -65,11 +55,11 @@
   case phantom(S)
 }
 
-// CHECK-LABEL: sil hidden @$ss17AddressOnly_casesyys1SVF
+// CHECK-LABEL: sil hidden @$s4enum17AddressOnly_casesyyAA1SVF
 func AddressOnly_cases(_ s: S) {
 
   // CHECK:       [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type
-  // CHECK:       [[FN:%.*]] = function_ref @$ss11AddressOnlyO4mereyABs1P_pcABmF
+  // CHECK:       [[FN:%.*]] = function_ref @$s4enum11AddressOnlyO4mereyAcA1P_pcACmFTc
   // CHECK-NEXT:  [[CTOR:%.*]] = apply [[FN]]([[METATYPE]])
   // CHECK-NEXT:  destroy_value [[CTOR]]
   _ = AddressOnly.mere
@@ -105,29 +95,29 @@
   // CHECK:       return
 }
 
-// CHECK-LABEL: sil shared [transparent] [thunk] @$ss11AddressOnlyO4mereyABs1P_pcABmF
-// CHECK:       [[FN:%.*]] = function_ref @$ss11AddressOnlyO4mereyABs1P_pcABmF
+// CHECK-LABEL: sil shared [transparent] [thunk] @$s4enum11AddressOnlyO4mereyAcA1P_pcACmFTc
+// CHECK:       [[FN:%.*]] = function_ref @$s4enum11AddressOnlyO4mereyAcA1P_pcACmF
 // CHECK-NEXT:  [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]](%0)
 // CHECK-NEXT:  // function_ref
-// CHECK-NEXT:  [[CANONICAL_THUNK_FN:%.*]] = function_ref @$ss1P_ps11AddressOnlyOIegir_sAA_pACIegnr_TR : $@convention(thin) (@in_guaranteed P, @guaranteed @callee_guaranteed (@in P) -> @out AddressOnly) -> @out AddressOnly
+// CHECK-NEXT:  [[CANONICAL_THUNK_FN:%.*]] = function_ref @$s4enum1P_pAA11AddressOnlyOIegir_AaB_pADIegnr_TR : $@convention(thin) (@in_guaranteed P, @guaranteed @callee_guaranteed (@in P) -> @out AddressOnly) -> @out AddressOnly
 // CHECK-NEXT:  [[CANONICAL_THUNK:%.*]] = partial_apply [callee_guaranteed] [[CANONICAL_THUNK_FN]]([[METHOD]])
 // CHECK-NEXT:  return [[CANONICAL_THUNK]] : $@callee_guaranteed (@in_guaranteed P) -> @out AddressOnly
 // CHECK-NEXT: }
 
-// CHECK-LABEL: sil shared [transparent] @$ss11AddressOnlyO4mereyABs1P_pcABmF : $@convention
+// CHECK-LABEL: sil shared [transparent] @$s4enum11AddressOnlyO4mereyAcA1P_pcACmF : $@convention
 // CHECK: bb0([[ARG0:%.*]] : @trivial $*AddressOnly, [[ARG1:%.*]] : @trivial $*P, [[ARG2:%.*]] : @trivial $@thin AddressOnly.Type):
 // CHECK:        [[RET_DATA:%.*]] = init_enum_data_addr [[ARG0]] : $*AddressOnly, #AddressOnly.mere!enumelt.1
 // CHECK-NEXT:   copy_addr [take] [[ARG1]] to [initialization] [[RET_DATA]] : $*P
 // CHECK-NEXT:   inject_enum_addr [[ARG0]] : $*AddressOnly, #AddressOnly.mere!enumelt.1
 // CHECK:        return
-// CHECK-NEXT: } // end sil function '$ss11AddressOnlyO4mereyABs1P_pcABmF'
+// CHECK-NEXT: } // end sil function '$s4enum11AddressOnlyO4mereyAcA1P_pcACmF'
 
 enum PolyOptionable<T> {
   case nought
   case mere(T)
 }
 
-// CHECK-LABEL: sil hidden @$ss20PolyOptionable_casesyyxlF
+// CHECK-LABEL: sil hidden @$s4enum20PolyOptionable_casesyyxlF
 func PolyOptionable_cases<T>(_ t: T) {
 
 // CHECK:         [[METATYPE:%.*]] = metatype $@thin PolyOptionable<T>.Type
@@ -154,7 +144,7 @@
 
 // The substituted type is loadable and trivial here
 
-// CHECK-LABEL: sil hidden @$ss32PolyOptionable_specialized_casesyySiF
+// CHECK-LABEL: sil hidden @$s4enum32PolyOptionable_specialized_casesyySiF
 func PolyOptionable_specialized_cases(_ t: Int) {
 
 // CHECK:         [[METATYPE:%.*]] = metatype $@thin PolyOptionable<Int>.Type
@@ -172,35 +162,35 @@
 
 // Regression test for a bug where temporary allocations created as a result of
 // tuple implosion were not deallocated in enum constructors.
-struct String { var ptr: Builtin.NativeObject }
+struct String { var ptr: AnyObject }
 
-enum Foo { case A(P, String) }
+enum Foo { case a(P, String) }
 
-// Curry Thunk for Foo.A(_:)
+// Curry Thunk for Foo.a(_:)
 //
-// CHECK-LABEL: sil shared [transparent] [thunk] @$ss3FooO1AyABs1P_p_SStcABmF
-// CHECK:         [[FN:%.*]] = function_ref @$ss3FooO1AyABs1P_p_SStcABmF
+// CHECK-LABEL: sil shared [transparent] [thunk] @$s4enum3FooO1ayAcA1P_p_AA6StringVtcACmFTc
+// CHECK:         [[FN:%.*]] = function_ref @$s4enum3FooO1ayAcA1P_p_AA6StringVtcACmF
 // CHECK-NEXT:    [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]](%0)
 // CHECK-NEXT:    // function_ref
-// CHECK-NEXT:    [[CANONICAL_THUNK_FN:%.*]] = function_ref @$ss1P_pSSs3FooOIegixr_sAA_pSSACIegngr_TR : $@convention(thin) (@in_guaranteed P, @guaranteed String, @guaranteed @callee_guaranteed (@in P, @owned String) -> @out Foo) -> @out Foo
+// CHECK-NEXT:    [[CANONICAL_THUNK_FN:%.*]] = function_ref @$s4enum1P_pAA6StringVAA3FooOIegixr_AaB_pAdFIegngr_TR : $@convention(thin) (@in_guaranteed P, @guaranteed String, @guaranteed @callee_guaranteed (@in P, @owned String) -> @out Foo) -> @out Foo
 // CHECK-NEXT:    [[CANONICAL_THUNK:%.*]] = partial_apply [callee_guaranteed] [[CANONICAL_THUNK_FN]]([[METHOD]])
 // CHECK-NEXT:    return [[CANONICAL_THUNK]]
 // CHECK-NEXT:  }
 
-// Foo.A(_:)
-// CHECK-LABEL: sil shared [transparent] @$ss3FooO1AyABs1P_p_SStcABmF
+// Foo.a(_:)
+// CHECK-LABEL: sil shared [transparent] @$s4enum3FooO1ayAcA1P_p_AA6StringVtcACmF
 // CHECK: bb0([[ARG0:%.*]] : @trivial $*Foo, [[ARG1:%.*]] : @trivial $*P, [[ARG2:%.*]] : @owned $String, [[ARG3:%.*]] : @trivial $@thin Foo.Type):
-// CHECK:         [[PAYLOAD:%.*]] = init_enum_data_addr [[ARG0]] : $*Foo, #Foo.A!enumelt.1
+// CHECK:         [[PAYLOAD:%.*]] = init_enum_data_addr [[ARG0]] : $*Foo, #Foo.a!enumelt.1
 // CHECK-NEXT:    [[LEFT:%.*]] = tuple_element_addr [[PAYLOAD]] : $*(P, String), 0
 // CHECK-NEXT:    [[RIGHT:%.*]] = tuple_element_addr [[PAYLOAD]] : $*(P, String), 1
 // CHECK-NEXT:    copy_addr [take] [[ARG1]] to [initialization] [[LEFT]] : $*P
 // CHECK-NEXT:    store [[ARG2]] to [init] [[RIGHT]]
-// CHECK-NEXT:    inject_enum_addr [[ARG0]] : $*Foo, #Foo.A!enumelt.1
+// CHECK-NEXT:    inject_enum_addr [[ARG0]] : $*Foo, #Foo.a!enumelt.1
 // CHECK:         return
-// CHECK-NEXT:  } // end sil function '$ss3FooO1AyABs1P_p_SStcABmF'
+// CHECK-NEXT:  } // end sil function '$s4enum3FooO1ayAcA1P_p_AA6StringVtcACmF'
 
 func Foo_cases() {
-  _ = Foo.A
+  _ = Foo.a
 }
 
 enum Indirect<T> {
@@ -213,3 +203,33 @@
 func makeIndirectEnum<T>(_ payload: T) -> Indirect<T> {
   return Indirect.payload((payload, other: payload))
 }
+
+// https://bugs.swift.org/browse/SR-9675
+
+enum TrailingClosureConcrete {
+  case label(fn: () -> Int)
+  case noLabel(() -> Int)
+  case twoElementsLabel(x: Int, fn: () -> Int)
+  case twoElementsNoLabel(_ x: Int, _ fn: () -> Int)
+}
+
+func useTrailingClosureConcrete() {
+  _ = TrailingClosureConcrete.label { 0 }
+  _ = TrailingClosureConcrete.noLabel { 0 }
+  _ = TrailingClosureConcrete.twoElementsLabel(x: 0) { 0 }
+  _ = TrailingClosureConcrete.twoElementsNoLabel(0) { 0 }
+}
+
+enum TrailingClosureGeneric<T> {
+  case label(fn: () -> T)
+  case noLabel(() -> T)
+  case twoElementsLabel(x: T, fn: () -> T)
+  case twoElementsNoLabel(_ x: T, _ fn: () -> T)
+}
+
+func useTrailingClosureGeneric<T>(t: T) {
+  _ = TrailingClosureGeneric<T>.label { t }
+  _ = TrailingClosureGeneric<T>.noLabel { t }
+  _ = TrailingClosureGeneric<T>.twoElementsLabel(x: t) { t }
+  _ = TrailingClosureGeneric<T>.twoElementsNoLabel(t) { t }
+}
\ No newline at end of file
diff --git a/test/SILGen/enum_curry_thunks.swift b/test/SILGen/enum_curry_thunks.swift
index f897085..b73e3e4 100644
--- a/test/SILGen/enum_curry_thunks.swift
+++ b/test/SILGen/enum_curry_thunks.swift
@@ -1,51 +1,51 @@
 // RUN: %target-swift-emit-silgen -parse-as-library %s | %FileCheck %s
 
 enum PartialApplyEnumPayload<T, U> {
-  case Left(T)
-  case Both(T, U)
+  case left(T)
+  case both(T, U)
 
-  case LeftWithLabel(left: T)
-  case BothWithLabel(left: T, right: U)
+  case leftWithLabel(left: T)
+  case bothWithLabel(left: T, right: U)
 
-  case TupleWithLabel(both: (T, U))
+  case tupleWithLabel(both: (T, U))
 
   // Note: SILGen can emit these thunks correctly, but we disabled
   // the feature since calling the constructor directly (without a
   // thunk) doesn't work yet.
-  /* case Variadic(_: Int...)
-  case VariadicWithLabel(indices: Int...)
-  case VariadicTuple(_: (Int, Int)...)
-  case VariadicWithOther(String, _: Int...) */
+  /* case variadic(_: Int...)
+  case variadicWithLabel(indices: Int...)
+  case variadicTuple(_: (Int, Int)...)
+  case variadicWithOther(String, _: Int...) */
 
-  case Autoclosure(@autoclosure () -> ())
+  case autoclosure(@autoclosure () -> ())
 }
 
 struct S {}
 struct C {}
 
 func partialApplyEnumCases(_ x: S, y: C) {
-  _ = PartialApplyEnumPayload<S, C>.Left
-  _ = PartialApplyEnumPayload<S, C>.Both
-  _ = PartialApplyEnumPayload<S, C>.LeftWithLabel
-  _ = PartialApplyEnumPayload<S, C>.TupleWithLabel
-  /* _ = PartialApplyEnumPayload<S, C>.Variadic
-  _ = PartialApplyEnumPayload<S, C>.VariadicWithLabel
-  _ = PartialApplyEnumPayload<S, C>.VariadicTuple
-  _ = PartialApplyEnumPayload<S, C>.VariadicWithOther */
-  _ = PartialApplyEnumPayload<S, C>.Autoclosure
+  _ = PartialApplyEnumPayload<S, C>.left
+  _ = PartialApplyEnumPayload<S, C>.both
+  _ = PartialApplyEnumPayload<S, C>.leftWithLabel
+  _ = PartialApplyEnumPayload<S, C>.tupleWithLabel
+  /* _ = PartialApplyEnumPayload<S, C>.variadic
+  _ = PartialApplyEnumPayload<S, C>.variadicWithLabel
+  _ = PartialApplyEnumPayload<S, C>.variadicTuple
+  _ = PartialApplyEnumPayload<S, C>.variadicWithOther */
+  _ = PartialApplyEnumPayload<S, C>.autoclosure
 }
 
-// CHECK-LABEL: sil shared [transparent] [thunk] @$s17enum_curry_thunks23PartialApplyEnumPayloadO4LeftyACyxq_GxcAEmr0_lFTc : $@convention(thin) <T, U> (@thin PartialApplyEnumPayload<T, U>.Type) -> @owned @callee_guaranteed (@in_guaranteed T) -> @out PartialApplyEnumPayload<T, U> {
-// CHECK-LABEL: sil shared [transparent] @$s17enum_curry_thunks23PartialApplyEnumPayloadO4LeftyACyxq_GxcAEmr0_lF : $@convention(method) <T, U> (@in T, @thin PartialApplyEnumPayload<T, U>.Type) -> @out PartialApplyEnumPayload<T, U> {
+// CHECK-LABEL: sil shared [transparent] [thunk] @$s17enum_curry_thunks23PartialApplyEnumPayloadO4leftyACyxq_GxcAEmr0_lFTc : $@convention(thin) <T, U> (@thin PartialApplyEnumPayload<T, U>.Type) -> @owned @callee_guaranteed (@in_guaranteed T) -> @out PartialApplyEnumPayload<T, U> {
+// CHECK-LABEL: sil shared [transparent] @$s17enum_curry_thunks23PartialApplyEnumPayloadO4leftyACyxq_GxcAEmr0_lF : $@convention(method) <T, U> (@in T, @thin PartialApplyEnumPayload<T, U>.Type) -> @out PartialApplyEnumPayload<T, U> {
 
-// CHECK-LABEL: sil shared [transparent] [thunk] @$s17enum_curry_thunks23PartialApplyEnumPayloadO4BothyACyxq_Gx_q_tcAEmr0_lFTc : $@convention(thin) <T, U> (@thin PartialApplyEnumPayload<T, U>.Type) -> @owned @callee_guaranteed (@in_guaranteed T, @in_guaranteed U) -> @out PartialApplyEnumPayload<T, U> {
-// CHECK-LABEL: sil shared [transparent] @$s17enum_curry_thunks23PartialApplyEnumPayloadO4BothyACyxq_Gx_q_tcAEmr0_lF : $@convention(method) <T, U> (@in T, @in U, @thin PartialApplyEnumPayload<T, U>.Type) -> @out PartialApplyEnumPayload<T, U> {
+// CHECK-LABEL: sil shared [transparent] [thunk] @$s17enum_curry_thunks23PartialApplyEnumPayloadO4bothyACyxq_Gx_q_tcAEmr0_lFTc : $@convention(thin) <T, U> (@thin PartialApplyEnumPayload<T, U>.Type) -> @owned @callee_guaranteed (@in_guaranteed T, @in_guaranteed U) -> @out PartialApplyEnumPayload<T, U> {
+// CHECK-LABEL: sil shared [transparent] @$s17enum_curry_thunks23PartialApplyEnumPayloadO4bothyACyxq_Gx_q_tcAEmr0_lF : $@convention(method) <T, U> (@in T, @in U, @thin PartialApplyEnumPayload<T, U>.Type) -> @out PartialApplyEnumPayload<T, U> {
 
-// CHECK-LABEL: sil shared [transparent] [thunk] @$s17enum_curry_thunks23PartialApplyEnumPayloadO13LeftWithLabelyACyxq_Gx_tcAEmr0_lFTc : $@convention(thin) <T, U> (@thin PartialApplyEnumPayload<T, U>.Type) -> @owned @callee_guaranteed (@in_guaranteed T) -> @out PartialApplyEnumPayload<T, U> {
-// CHECK-LABEL: sil shared [transparent] @$s17enum_curry_thunks23PartialApplyEnumPayloadO13LeftWithLabelyACyxq_Gx_tcAEmr0_lF : $@convention(method) <T, U> (@in T, @thin PartialApplyEnumPayload<T, U>.Type) -> @out PartialApplyEnumPayload<T, U> {
+// CHECK-LABEL: sil shared [transparent] [thunk] @$s17enum_curry_thunks23PartialApplyEnumPayloadO13leftWithLabelyACyxq_Gx_tcAEmr0_lFTc : $@convention(thin) <T, U> (@thin PartialApplyEnumPayload<T, U>.Type) -> @owned @callee_guaranteed (@in_guaranteed T) -> @out PartialApplyEnumPayload<T, U> {
+// CHECK-LABEL: sil shared [transparent] @$s17enum_curry_thunks23PartialApplyEnumPayloadO13leftWithLabelyACyxq_Gx_tcAEmr0_lF : $@convention(method) <T, U> (@in T, @thin PartialApplyEnumPayload<T, U>.Type) -> @out PartialApplyEnumPayload<T, U> {
 
-// CHECK-LABEL: sil shared [transparent] [thunk] @$s17enum_curry_thunks23PartialApplyEnumPayloadO14TupleWithLabelyACyxq_Gx_q_t_tcAEmr0_lFTc : $@convention(thin) <T, U> (@thin PartialApplyEnumPayload<T, U>.Type) -> @owned @callee_guaranteed (@in_guaranteed T, @in_guaranteed U) -> @out PartialApplyEnumPayload<T, U> {
-// CHECK-LABEL: sil shared [transparent] @$s17enum_curry_thunks23PartialApplyEnumPayloadO14TupleWithLabelyACyxq_Gx_q_t_tcAEmr0_lF : $@convention(method) <T, U> (@in T, @in U, @thin PartialApplyEnumPayload<T, U>.Type) -> @out PartialApplyEnumPayload<T, U> {
+// CHECK-LABEL: sil shared [transparent] [thunk] @$s17enum_curry_thunks23PartialApplyEnumPayloadO14tupleWithLabelyACyxq_Gx_q_t_tcAEmr0_lFTc : $@convention(thin) <T, U> (@thin PartialApplyEnumPayload<T, U>.Type) -> @owned @callee_guaranteed (@in_guaranteed T, @in_guaranteed U) -> @out PartialApplyEnumPayload<T, U> {
+// CHECK-LABEL: sil shared [transparent] @$s17enum_curry_thunks23PartialApplyEnumPayloadO14tupleWithLabelyACyxq_Gx_q_t_tcAEmr0_lF : $@convention(method) <T, U> (@in T, @in U, @thin PartialApplyEnumPayload<T, U>.Type) -> @out PartialApplyEnumPayload<T, U> {
 
-// CHECK-LABEL: sil shared [transparent] [thunk] @$s17enum_curry_thunks23PartialApplyEnumPayloadO11AutoclosureyACyxq_GyyXAcAEmr0_lFTc : $@convention(thin) <T, U> (@thin PartialApplyEnumPayload<T, U>.Type) -> @owned @callee_guaranteed (@guaranteed @callee_guaranteed () -> ()) -> @out PartialApplyEnumPayload<T, U> {
-// CHECK-LABEL: sil shared [transparent] @$s17enum_curry_thunks23PartialApplyEnumPayloadO11AutoclosureyACyxq_GyyXAcAEmr0_lF : $@convention(method) <T, U> (@owned @callee_guaranteed () -> (), @thin PartialApplyEnumPayload<T, U>.Type) -> @out PartialApplyEnumPayload<T, U> {
+// CHECK-LABEL: sil shared [transparent] [thunk] @$s17enum_curry_thunks23PartialApplyEnumPayloadO11autoclosureyACyxq_GyyXAcAEmr0_lFTc : $@convention(thin) <T, U> (@thin PartialApplyEnumPayload<T, U>.Type) -> @owned @callee_guaranteed (@guaranteed @callee_guaranteed () -> ()) -> @out PartialApplyEnumPayload<T, U> {
+// CHECK-LABEL: sil shared [transparent] @$s17enum_curry_thunks23PartialApplyEnumPayloadO11autoclosureyACyxq_GyyXAcAEmr0_lF : $@convention(method) <T, U> (@owned @callee_guaranteed () -> (), @thin PartialApplyEnumPayload<T, U>.Type) -> @out PartialApplyEnumPayload<T, U> {
diff --git a/test/SILGen/enum_generic_raw_value.swift b/test/SILGen/enum_generic_raw_value.swift
index 1cf3821..3bc6cfd 100644
--- a/test/SILGen/enum_generic_raw_value.swift
+++ b/test/SILGen/enum_generic_raw_value.swift
@@ -2,10 +2,10 @@
 
 // CHECK-LABEL: sil hidden @$s22enum_generic_raw_value1EO
 enum E<T>: Int {
-  case A = 1
+  case a = 1
 }
 
 // CHECK-LABEL: sil hidden @$s22enum_generic_raw_value1FO
 enum F<T: ExpressibleByIntegerLiteral>: T where T: Equatable {
-  case A = 1
+  case a = 1
 }
diff --git a/test/SILOptimizer/static_strings.swift b/test/SILOptimizer/static_strings.swift
index 6344434..d290735 100644
--- a/test/SILOptimizer/static_strings.swift
+++ b/test/SILOptimizer/static_strings.swift
@@ -1,5 +1,5 @@
-// RUN: %target-swift-frontend -O -emit-ir  %s | %FileCheck %s
-// RUN: %target-swift-frontend -Osize -emit-ir  %s | %FileCheck %s
+// RUN: %target-swift-frontend -O -emit-ir  %s | %FileCheck --check-prefix=CHECK-%target-cpu %s
+// RUN: %target-swift-frontend -Osize -emit-ir  %s | %FileCheck --check-prefix=CHECK-%target-cpu %s
 
 // RUN: %empty-directory(%t) 
 // RUN: %target-build-swift -O -module-name=test %s -o %t/a.out
@@ -12,72 +12,88 @@
 // optimal code for static String variables.
 
 public struct S {
-  // CHECK: {{^@"}}[[SMALL:.*smallstr.*pZ]]" ={{.*}} global {{.*}} inttoptr
+  // CHECK-x86_64: {{^@"}}[[SMALL:.*smallstr.*pZ]]" ={{.*}} global {{.*}} inttoptr
+  // CHECK-arm64: {{^@"}}[[SMALL:.*smallstr.*pZ]]" ={{.*}} global {{.*}} inttoptr
   public static let smallstr = "abc123a"
-  // CHECK: {{^@"}}[[LARGE:.*largestr.*pZ]]" ={{.*}} global {{.*}} inttoptr {{.*}} add
+  // CHECK-arm64: {{^@"}}[[LARGE:.*largestr.*pZ]]" ={{.*}} global {{.*}} inttoptr {{.*}} add
   public static let largestr = "abc123asd3sdj3basfasdf"
-  // CHECK: {{^@"}}[[UNICODE:.*unicodestr.*pZ]]" ={{.*}} global {{.*}} inttoptr {{.*}} add
+  // CHECK-arm64: {{^@"}}[[UNICODE:.*unicodestr.*pZ]]" ={{.*}} global {{.*}} inttoptr {{.*}} add
   public static let unicodestr = "❄️gastroperiodyni"
 }
 
 // unsafeMutableAddressor for S.smallstr
-// CHECK: define {{.*smallstr.*}}u"
-// CHECK-NEXT: entry:
-// CHECK-NEXT:   ret {{.*}} @"[[SMALL]]"
-// CHECK-NEXT: }
+// CHECK-arm64: define {{.*smallstr.*}}u"
+// CHECK-arm64-NEXT: entry:
+// CHECK-arm64-NEXT:   ret {{.*}} @"[[SMALL]]"
+// CHECK-arm64-NEXT: }
+
+// CHECK-x86_64: define {{.*smallstr.*}}u"
+// CHECK-x86_64-NEXT: entry:
+// CHECK-x86_64-NEXT:   ret {{.*}} @"[[SMALL]]"
+// CHECK-x86_64-NEXT: }
 
 // getter for S.smallstr
-// CHECK: define {{.*smallstr.*}}gZ"
-// CHECK-NEXT: entry:
-// CHECK-NEXT:   ret {{.*}}
-// CHECK-NEXT: }
+// CHECK-arm64: define {{.*smallstr.*}}gZ"
+// CHECK-arm64-NEXT: entry:
+// CHECK-arm64-NEXT:   ret {{.*}}
+// CHECK-arm64-NEXT: }
+
+// CHECK-x86_64: define {{.*smallstr.*}}gZ"
+// CHECK-x86_64-NEXT: entry:
+// CHECK-x86_64-NEXT:   ret {{.*}}
+// CHECK-x86_64-NEXT: }
 
 // unsafeMutableAddressor for S.largestr
-// CHECK: define {{.*largestr.*}}u"
-// CHECK-NEXT: entry:
-// CHECK-NEXT:   ret {{.*}} @"[[LARGE]]"
-// CHECK-NEXT: }
+// CHECK-arm64: define {{.*largestr.*}}u"
+// CHECK-arm64-NEXT: entry:
+// CHECK-arm64-NEXT:   ret {{.*}} @"[[LARGE]]"
+// CHECK-arm64-NEXT: }
 
 // getter for S.largestr
-// CHECK: define {{.*largestr.*}}gZ"
-// CHECK-NEXT: entry:
-// CHECK-NEXT:   ret {{.*}}
-// CHECK-NEXT: }
+// CHECK-arm64: define {{.*largestr.*}}gZ"
+// CHECK-arm64-NEXT: entry:
+// CHECK-arm64-NEXT:   ret {{.*}}
+// CHECK-arm64-NEXT: }
 
 // unsafeMutableAddressor for S.unicodestr
-// CHECK: define {{.*unicodestr.*}}u"
-// CHECK-NEXT: entry:
-// CHECK-NEXT:   ret {{.*}} @"[[UNICODE]]"
-// CHECK-NEXT: }
+// CHECK-arm64: define {{.*unicodestr.*}}u"
+// CHECK-arm64-NEXT: entry:
+// CHECK-arm64-NEXT:   ret {{.*}} @"[[UNICODE]]"
+// CHECK-arm64-NEXT: }
 
 // getter for S.unicodestr
-// CHECK: define {{.*unicodestr.*}}gZ"
-// CHECK-NEXT: entry:
-// CHECK-NEXT:   ret {{.*}}
-// CHECK-NEXT: }
+// CHECK-arm64: define {{.*unicodestr.*}}gZ"
+// CHECK-arm64-NEXT: entry:
+// CHECK-arm64-NEXT:   ret {{.*}}
+// CHECK-arm64-NEXT: }
 
-// CHECK-LABEL: define {{.*}}get_smallstr
-// CHECK:      entry:
-// CHECK-NEXT:   ret {{.*}}
-// CHECK-NEXT: }
+// CHECK-arm64-LABEL: define {{.*}}get_smallstr
+// CHECK-arm64:      entry:
+// CHECK-arm64-NEXT:   ret {{.*}}
+// CHECK-arm64-NEXT: }
+
+// CHECK-x86_64-LABEL: define {{.*}}get_smallstr
+// CHECK-x86_64:      entry:
+// CHECK-x86_64-NEXT:   ret {{.*}}
+// CHECK-x86_64-NEXT: }
 @inline(never)
 public func get_smallstr() -> String {
   return S.smallstr
 }
 
-// CHECK-LABEL: define {{.*}}get_largestr
-// CHECK:      entry:
-// CHECK-NEXT:   ret {{.*}}
-// CHECK-NEXT: }
+// CHECK-arm64-LABEL: define {{.*}}get_largestr
+// CHECK-arm64:      entry:
+// CHECK-arm64-NEXT:   ret {{.*}}
+// CHECK-arm64-NEXT: }
 @inline(never)
 public func get_largestr() -> String {
   return S.largestr
 }
 
-// CHECK-LABEL: define {{.*}}get_unicodestr
-// CHECK:      entry:
-// CHECK-NEXT:   ret {{.*}}
-// CHECK-NEXT: }
+// CHECK-arm64-LABEL: define {{.*}}get_unicodestr
+// CHECK-arm64:      entry:
+// CHECK-arm64-NEXT:   ret {{.*}}
+// CHECK-arm64-NEXT: }
 @inline(never)
 public func get_unicodestr() -> String {
   return S.unicodestr
diff --git a/test/Serialization/load-arch-fallback-framework.swift b/test/Serialization/load-arch-fallback-framework.swift
new file mode 100644
index 0000000..c0f2dc4
--- /dev/null
+++ b/test/Serialization/load-arch-fallback-framework.swift
@@ -0,0 +1,18 @@
+// Test the fallback for 32-bit ARM platforms.
+
+// RUN: %empty-directory(%t)
+// RUN: mkdir -p %t/empty.framework/Modules/empty.swiftmodule
+// RUN: %target-swift-frontend -emit-module -o %t/empty.framework/Modules/empty.swiftmodule/arm.swiftmodule %S/../Inputs/empty.swift -module-name empty
+// RUN: %target-swift-frontend -typecheck %s -F %t
+
+// RUN: mv %t/empty.framework/Modules/empty.swiftmodule/arm.swiftmodule %t/empty.framework/Modules/empty.swiftmodule/%target-swiftmodule-name
+// RUN: touch %t/empty.framework/Modules/empty.swiftmodule/arm.swiftmodule
+// RUN: %target-swift-frontend -typecheck %s -F %t
+
+// RUN: rm %t/empty.framework/Modules/empty.swiftmodule/%target-swiftmodule-name
+// RUN: not %target-swift-frontend -typecheck %s -F %t 2>&1 | %FileCheck %s
+
+// REQUIRES: CPU=armv7 || CPU=armv7k || CPU=armv7s
+
+import empty
+// CHECK: :[[@LINE-1]]:8: error: malformed module file: {{.*}}arm.swiftmodule
diff --git a/test/Serialization/load-arch-fallback.swift b/test/Serialization/load-arch-fallback.swift
new file mode 100644
index 0000000..a8f978e
--- /dev/null
+++ b/test/Serialization/load-arch-fallback.swift
@@ -0,0 +1,18 @@
+// Test the fallback for 32-bit ARM platforms.
+
+// RUN: %empty-directory(%t)
+// RUN: mkdir %t/empty.swiftmodule
+// RUN: %target-swift-frontend -emit-module -o %t/empty.swiftmodule/arm.swiftmodule %S/../Inputs/empty.swift -module-name empty
+// RUN: %target-swift-frontend -typecheck %s -I %t
+
+// RUN: mv %t/empty.swiftmodule/arm.swiftmodule %t/empty.swiftmodule/%target-swiftmodule-name
+// RUN: touch %t/empty.swiftmodule/arm.swiftmodule
+// RUN: %target-swift-frontend -typecheck %s -I %t
+
+// RUN: rm %t/empty.swiftmodule/%target-swiftmodule-name
+// RUN: not %target-swift-frontend -typecheck %s -I %t 2>&1 | %FileCheck %s
+
+// REQUIRES: CPU=armv7 || CPU=armv7k || CPU=armv7s
+
+import empty
+// CHECK: :[[@LINE-1]]:8: error: malformed module file: {{.*}}arm.swiftmodule
diff --git a/test/SourceKit/DocumentStructure/rdar47426948.swift b/test/SourceKit/DocumentStructure/rdar47426948.swift
new file mode 100644
index 0000000..fbcd96d
--- /dev/null
+++ b/test/SourceKit/DocumentStructure/rdar47426948.swift
@@ -0,0 +1,40 @@
+// RUN: %sourcekitd-test -req=structure %s -- %s | %FileCheck %s
+
+class C {
+  @IBAction init(foo: Void) {}
+  @IBAction init(bar: ()) {}
+  @IBAction init(baz: Int) {}
+  @IBAction func methodName(foo: ()) {}
+  @IBAction func methodName(bar: Void) {}
+  @IBAction func methodName(baz: Int) {}
+  @IBAction deinit {}
+}
+
+// CHECK: {
+// CHECK:   key.name: "init(foo:)",
+// CHECK-NOT:   key.selector_name
+// CHECK: }
+// CHECK: {
+// CHECK:   key.name: "init(bar:)",
+// CHECK-NOT:   key.selector_name
+// CHECK: }
+// CHECK: {
+// CHECK:   key.name: "init(baz:)",
+// CHECK-NOT:   key.selector_name
+// CHECK: }
+// CHECK: {
+// CHECK:   key.name: "methodName(foo:)",
+// CHECK:   key.selector_name: "methodNameWithFoo:"
+// CHECK: }
+// CHECK: {
+// CHECK:   key.name: "methodName(bar:)",
+// CHECK:   key.selector_name: "methodNameWithBar:"
+// CHECK: }
+// CHECK: {
+// CHECK:   key.name: "methodName(baz:)",
+// CHECK:   key.selector_name: "methodNameWithBaz:"
+// CHECK: }
+// CHECK: {
+// CHECK:   key.name: "deinit",
+// CHECK-NOT:   key.selector_name
+// CHECK: }
diff --git a/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds b/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds
index 2c1af8b..6a050fe 100644
--- a/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds
+++ b/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds
@@ -532,7 +532,7 @@
   @_implements(<ImplementsAttributeArguments><SimpleTypeIdentifier>P</SimpleTypeIdentifier>, x</ImplementsAttributeArguments>)</Attribute>
   var <PatternBinding><IdentifierPattern>y</IdentifierPattern><TypeAnnotation>: <SimpleTypeIdentifier>String</SimpleTypeIdentifier></TypeAnnotation></PatternBinding></VariableDecl></MemberDeclListItem><MemberDeclListItem><FunctionDecl><Attribute>
   @_implements(<ImplementsAttributeArguments><SimpleTypeIdentifier>P</SimpleTypeIdentifier>, g<DeclNameArguments>()</DeclNameArguments></ImplementsAttributeArguments>)</Attribute>
-  func h<FunctionSignature><ParameterClause>() </ParameterClause></FunctionSignature><CodeBlock>{}</CodeBlock></FunctionDecl></MemberDeclListItem><MemberDeclListItem><VariableDecl><Attribute>
+  func h<FunctionSignature><ParameterClause>() </ParameterClause></FunctionSignature><CodeBlock>{ <SequenceExpr><DiscardAssignmentExpr>_ </DiscardAssignmentExpr><AssignmentExpr>= </AssignmentExpr><KeyPathExpr>\<DotSelfExpr>.self </DotSelfExpr></KeyPathExpr></SequenceExpr>}</CodeBlock></FunctionDecl></MemberDeclListItem><MemberDeclListItem><VariableDecl><Attribute>
 
   @available(<AvailabilityArgument>*, </AvailabilityArgument><AvailabilityArgument><AvailabilityLabeledArgument>deprecated: <VersionTuple>1.2</VersionTuple></AvailabilityLabeledArgument>, </AvailabilityArgument><AvailabilityArgument><AvailabilityLabeledArgument>message: "ABC"</AvailabilityLabeledArgument></AvailabilityArgument>)</Attribute><DeclModifier>
   fileprivate(set) </DeclModifier>var <PatternBinding><IdentifierPattern>x</IdentifierPattern><TypeAnnotation>: <SimpleTypeIdentifier>String</SimpleTypeIdentifier></TypeAnnotation></PatternBinding></VariableDecl></MemberDeclListItem>
diff --git a/test/Syntax/round_trip_parse_gen.swift b/test/Syntax/round_trip_parse_gen.swift
index b17b017..960789c 100644
--- a/test/Syntax/round_trip_parse_gen.swift
+++ b/test/Syntax/round_trip_parse_gen.swift
@@ -532,7 +532,7 @@
   @_implements(P, x)
   var y: String
   @_implements(P, g())
-  func h() {}
+  func h() { _ = \.self }
 
   @available(*, deprecated: 1.2, message: "ABC")
   fileprivate(set) var x: String
diff --git a/test/api-digester/Outputs/stability-stdlib-abi.swift.expected b/test/api-digester/Outputs/stability-stdlib-abi.swift.expected
index 8b13789..44dd497 100644
--- a/test/api-digester/Outputs/stability-stdlib-abi.swift.expected
+++ b/test/api-digester/Outputs/stability-stdlib-abi.swift.expected
@@ -1 +1,148 @@
+Class __SwiftNativeNSString has been removed
 
+Class _DictionaryStorage has changed its super class from _RawDictionaryStorage to __RawDictionaryStorage
+Class _EmptyDictionarySingleton has been renamed to Class __EmptyDictionarySingleton
+Class _EmptyDictionarySingleton has changed its super class from _RawDictionaryStorage to __RawDictionaryStorage
+Class _EmptySetSingleton has been renamed to Class __EmptySetSingleton
+Class _EmptySetSingleton has changed its super class from _RawSetStorage to __RawSetStorage
+Class _RawDictionaryStorage has been renamed to Class __RawDictionaryStorage
+Class _RawSetStorage has been renamed to Class __RawSetStorage
+Class _SetStorage has changed its super class from _RawSetStorage to __RawSetStorage
+Constructor Dictionary._Variant.init(cocoa:) has parameter 0 type change from _CocoaDictionary to __CocoaDictionary
+Constructor Dictionary.init(_cocoa:) has parameter 0 type change from _CocoaDictionary to __CocoaDictionary
+Constructor Int.init(truncatingBitPattern:) has been removed
+Constructor Int16.init(truncatingBitPattern:) has been removed
+Constructor Int32.init(truncatingBitPattern:) has been removed
+Constructor Int8.init(truncatingBitPattern:) has been removed
+Constructor Set._Variant.init(cocoa:) has parameter 0 type change from _CocoaSet to __CocoaSet
+Constructor Set.init(_cocoa:) has parameter 0 type change from _CocoaSet to __CocoaSet
+Constructor UInt.init(truncatingBitPattern:) has been removed
+Constructor UInt16.init(truncatingBitPattern:) has been removed
+Constructor UInt32.init(truncatingBitPattern:) has been removed
+Constructor UInt8.init(truncatingBitPattern:) has been removed
+Constructor _CocoaDictionary.init(_:) has return type change from _CocoaDictionary to __CocoaDictionary
+Constructor _CocoaSet.init(_:) has return type change from _CocoaSet to __CocoaSet
+Constructor _NativeDictionary.init(_:) has parameter 0 type change from _CocoaDictionary to __CocoaDictionary
+Constructor _NativeDictionary.init(_:) has parameter 0 type change from _RawDictionaryStorage to __RawDictionaryStorage
+Constructor _NativeDictionary.init(_:capacity:) has parameter 0 type change from _CocoaDictionary to __CocoaDictionary
+Constructor _NativeSet.init(_:) has parameter 0 type change from _CocoaSet to __CocoaSet
+Constructor _NativeSet.init(_:) has parameter 0 type change from _RawSetStorage to __RawSetStorage
+Constructor _NativeSet.init(_:capacity:) has parameter 0 type change from _CocoaSet to __CocoaSet
+Func BinaryInteger.addWithOverflow(_:_:) has been removed
+Func BinaryInteger.divideWithOverflow(_:_:) has been removed
+Func BinaryInteger.multiplyWithOverflow(_:_:) has been removed
+Func BinaryInteger.remainderWithOverflow(_:_:) has been removed
+Func BinaryInteger.subtractWithOverflow(_:_:) has been removed
+Func FixedWidthInteger.<<(_:_:) has been removed
+Func FixedWidthInteger.<<=(_:_:) has been removed
+Func FixedWidthInteger.>>(_:_:) has been removed
+Func FixedWidthInteger.>>=(_:_:) has been removed
+Func FixedWidthInteger.addWithOverflow(_:_:) has been removed
+Func FixedWidthInteger.divideWithOverflow(_:_:) has been removed
+Func FixedWidthInteger.multiplyWithOverflow(_:_:) has been removed
+Func FixedWidthInteger.remainderWithOverflow(_:_:) has been removed
+Func FixedWidthInteger.subtractWithOverflow(_:_:) has been removed
+Func Int.<<(_:_:) has been removed
+Func Int.<<=(_:_:) has been removed
+Func Int.>>(_:_:) has been removed
+Func Int.>>=(_:_:) has been removed
+Func Int.toUIntMax() has been removed
+Func Int16.<<(_:_:) has been removed
+Func Int16.<<=(_:_:) has been removed
+Func Int16.>>(_:_:) has been removed
+Func Int16.>>=(_:_:) has been removed
+Func Int16.toUIntMax() has been removed
+Func Int32.<<(_:_:) has been removed
+Func Int32.<<=(_:_:) has been removed
+Func Int32.>>(_:_:) has been removed
+Func Int32.>>=(_:_:) has been removed
+Func Int32.toUIntMax() has been removed
+Func Int64.<<(_:_:) has been removed
+Func Int64.<<=(_:_:) has been removed
+Func Int64.>>(_:_:) has been removed
+Func Int64.>>=(_:_:) has been removed
+Func Int64.toUIntMax() has been removed
+Func Int8.<<(_:_:) has been removed
+Func Int8.<<=(_:_:) has been removed
+Func Int8.>>(_:_:) has been removed
+Func Int8.>>=(_:_:) has been removed
+Func Int8.toUIntMax() has been removed
+Func Set._Variant._migrateToNative(_:removing:) has parameter 0 type change from _CocoaSet to __CocoaSet
+Func SignedInteger.&+(_:_:) has been removed
+Func SignedInteger.&-(_:_:) has been removed
+Func UInt.<<(_:_:) has been removed
+Func UInt.<<=(_:_:) has been removed
+Func UInt.>>(_:_:) has been removed
+Func UInt.>>=(_:_:) has been removed
+Func UInt.toIntMax() has been removed
+Func UInt16.<<(_:_:) has been removed
+Func UInt16.<<=(_:_:) has been removed
+Func UInt16.>>(_:_:) has been removed
+Func UInt16.>>=(_:_:) has been removed
+Func UInt16.toIntMax() has been removed
+Func UInt32.<<(_:_:) has been removed
+Func UInt32.<<=(_:_:) has been removed
+Func UInt32.>>(_:_:) has been removed
+Func UInt32.>>=(_:_:) has been removed
+Func UInt32.toIntMax() has been removed
+Func UInt64.<<(_:_:) has been removed
+Func UInt64.<<=(_:_:) has been removed
+Func UInt64.>>(_:_:) has been removed
+Func UInt64.>>=(_:_:) has been removed
+Func UInt64.toIntMax() has been removed
+Func UInt8.<<(_:_:) has been removed
+Func UInt8.<<=(_:_:) has been removed
+Func UInt8.>>(_:_:) has been removed
+Func UInt8.>>=(_:_:) has been removed
+Func UInt8.toIntMax() has been removed
+Func _CocoaDictionary.isEqual(to:) has parameter 0 type change from _CocoaDictionary to __CocoaDictionary
+Func _CocoaSet.isEqual(to:) has parameter 0 type change from _CocoaSet to __CocoaSet
+Func _DictionaryStorage.convert(_:capacity:) has parameter 0 type change from _CocoaDictionary to __CocoaDictionary
+Func _DictionaryStorage.copy(original:) has parameter 0 type change from _RawDictionaryStorage to __RawDictionaryStorage
+Func _DictionaryStorage.resize(original:capacity:move:) has parameter 0 type change from _RawDictionaryStorage to __RawDictionaryStorage
+Func _NativeDictionary.isEqual(to:) has parameter 0 type change from _CocoaDictionary to __CocoaDictionary
+Func _NativeSet.isEqual(to:) has parameter 0 type change from _CocoaSet to __CocoaSet
+Func _SetStorage.convert(_:capacity:) has parameter 0 type change from _CocoaSet to __CocoaSet
+Func _SetStorage.copy(original:) has parameter 0 type change from _RawSetStorage to __RawSetStorage
+Func _SetStorage.resize(original:capacity:move:) has parameter 0 type change from _RawSetStorage to __RawSetStorage
+Struct _CocoaDictionary has been renamed to Struct __CocoaDictionary
+Struct _CocoaSet has been renamed to Struct __CocoaSet
+Var Dictionary._Variant.asCocoa has declared type change from _CocoaDictionary to __CocoaDictionary
+Var Dictionary._Variant.object has declared type change from _BridgeStorage<_RawDictionaryStorage> to _BridgeStorage<__RawDictionaryStorage>
+Var Int._sizeInBits has been removed
+Var Int._sizeInBytes has been removed
+Var Int16._sizeInBits has been removed
+Var Int16._sizeInBytes has been removed
+Var Int32._sizeInBits has been removed
+Var Int32._sizeInBytes has been removed
+Var Int64._sizeInBits has been removed
+Var Int64._sizeInBytes has been removed
+Var Int8._sizeInBits has been removed
+Var Int8._sizeInBytes has been removed
+Var Set._Variant.asCocoa has declared type change from _CocoaSet to __CocoaSet
+Var Set._Variant.object has declared type change from _BridgeStorage<_RawSetStorage> to _BridgeStorage<__RawSetStorage>
+Var UInt._sizeInBits has been removed
+Var UInt._sizeInBytes has been removed
+Var UInt16._sizeInBits has been removed
+Var UInt16._sizeInBytes has been removed
+Var UInt32._sizeInBits has been removed
+Var UInt32._sizeInBytes has been removed
+Var UInt64._sizeInBits has been removed
+Var UInt64._sizeInBytes has been removed
+Var UInt8._sizeInBits has been removed
+Var UInt8._sizeInBytes has been removed
+Var _CocoaDictionary.Index.dictionary has declared type change from _CocoaDictionary to __CocoaDictionary
+Var _NativeDictionary._storage has declared type change from _RawDictionaryStorage to __RawDictionaryStorage
+Var _NativeSet._storage has declared type change from _RawSetStorage to __RawSetStorage
+Var _RawDictionaryStorage.empty has declared type change from _EmptyDictionarySingleton to __EmptyDictionarySingleton
+Var _RawSetStorage.empty has declared type change from _EmptySetSingleton to __EmptySetSingleton
+
+Func tryReallocateUniquelyReferenced(buffer:newMinimumCapacity:) has been removed
+
+Protocol SIMD has added inherited protocol Decodable
+Protocol SIMD has added inherited protocol Encodable
+Protocol SIMD has generic signature change from <τ_0_0 : CustomStringConvertible, τ_0_0 : ExpressibleByArrayLiteral, τ_0_0 : Hashable, τ_0_0 : SIMDStorage, τ_0_0.MaskStorage : SIMD, τ_0_0.MaskStorage.Scalar : FixedWidthInteger, τ_0_0.MaskStorage.Scalar : SignedInteger> to <τ_0_0 : CustomStringConvertible, τ_0_0 : Decodable, τ_0_0 : Encodable, τ_0_0 : ExpressibleByArrayLiteral, τ_0_0 : Hashable, τ_0_0 : SIMDStorage, τ_0_0.MaskStorage : SIMD, τ_0_0.MaskStorage.Scalar : FixedWidthInteger, τ_0_0.MaskStorage.Scalar : SignedInteger>
+Protocol SIMDStorage has generic signature change from <τ_0_0.Scalar : Hashable> to <τ_0_0.Scalar : Decodable, τ_0_0.Scalar : Encodable, τ_0_0.Scalar : Hashable>
+Func Sequence.flatMap(_:) has been removed
+Subscript String.UnicodeScalarView.subscript(_:) has been removed
+Subscript Substring.subscript(_:) has been removed
diff --git a/test/api-digester/Outputs/stability-stdlib-source.swift.expected b/test/api-digester/Outputs/stability-stdlib-source.swift.expected
index 8b13789..4b63017 100644
--- a/test/api-digester/Outputs/stability-stdlib-source.swift.expected
+++ b/test/api-digester/Outputs/stability-stdlib-source.swift.expected
@@ -1 +1,5 @@
-
+Func tryReallocateUniquelyReferenced(buffer:newMinimumCapacity:) has been removed
+Protocol SIMD has added inherited protocol Decodable
+Protocol SIMD has added inherited protocol Encodable
+Protocol SIMD has generic signature change from <Self : CustomStringConvertible, Self : ExpressibleByArrayLiteral, Self : Hashable, Self : SIMDStorage, Self.MaskStorage : SIMD, Self.MaskStorage.Scalar : FixedWidthInteger, Self.MaskStorage.Scalar : SignedInteger> to <Self : CustomStringConvertible, Self : Decodable, Self : Encodable, Self : ExpressibleByArrayLiteral, Self : Hashable, Self : SIMDStorage, Self.MaskStorage : SIMD, Self.MaskStorage.Scalar : FixedWidthInteger, Self.MaskStorage.Scalar : SignedInteger>
+Protocol SIMDStorage has generic signature change from <Self.Scalar : Hashable> to <Self.Scalar : Decodable, Self.Scalar : Encodable, Self.Scalar : Hashable>
diff --git a/test/decl/func/rethrows.swift b/test/decl/func/rethrows.swift
index 86ca746..46de659 100644
--- a/test/decl/func/rethrows.swift
+++ b/test/decl/func/rethrows.swift
@@ -584,3 +584,22 @@
 }
 
 Box(unbox: 1) |> suchThat <| { $0 + 1 } // expected-warning {{result of operator '<|' is unused}}
+
+// Constructor delegation -vs- rethrows
+class RethrowingConstructor {
+  init(_ block: () throws -> ()) rethrows {
+    try block()
+  }
+
+  convenience init(bar: Int) {
+    self.init {
+      print("Foo!")
+    }
+  }
+
+  convenience init(baz: Int) throws {
+    try self.init {
+      try throwingFunc()
+    }
+  }
+}
\ No newline at end of file
diff --git a/test/lit.cfg b/test/lit.cfg
index 0fa7b66..3718069 100644
--- a/test/lit.cfg
+++ b/test/lit.cfg
@@ -569,8 +569,6 @@
 if 'swift_interpreter' in config.available_features:
     config.available_features.add('swift-remoteast-test')
 
-config.target_swiftmodule_name = "unknown.swiftmodule"
-config.target_swiftdoc_name = "unknown.swiftdoc"
 config.target_runtime = "unknown"
 
 swift_reflection_test_name = 'swift-reflection-test' + config.variant_suffix
@@ -609,8 +607,6 @@
 
 if run_vendor == 'apple':
     config.available_features.add('objc_interop')
-    config.target_swiftmodule_name = run_cpu + ".swiftmodule"
-    config.target_swiftdoc_name = run_cpu + ".swiftdoc"
     config.target_object_format = "macho"
     config.target_dylib_extension = "dylib"
     config.target_codesign = "codesign -f -s -"
@@ -646,15 +642,6 @@
            lit_config.note('Testing watchOS ' + config.variant_triple)
            xcrun_sdk_name = "watchos"
 
-       if run_cpu == "armv7" or run_cpu == "armv7s" or run_cpu == "armv7k":
-           config.target_swiftmodule_name = "arm.swiftmodule"
-           config.target_swiftdoc_name = "arm.swiftdoc"
-       elif run_cpu == "arm64":
-           config.target_swiftmodule_name = "arm64.swiftmodule"
-           config.target_swiftdoc_name = "arm64.swiftdoc"
-       else:
-           lit_config.fatal("Unknown CPU '%s'" % run_cpu)
-
        config.target_cc_options = (
            "-arch %s -m%s-version-min=%s %s" %
            (run_cpu, run_os, run_vers, clang_mcp_opt))
@@ -809,8 +796,6 @@
       config.target_object_format = "elf"
       config.target_dylib_extension = "so"
       config.target_sdk_name = "linux"
-    config.target_swiftmodule_name = run_cpu + ".swiftmodule"
-    config.target_swiftdoc_name = run_cpu + ".swiftdoc"
     config.target_runtime = "native"
     config.target_swift_autolink_extract = inferSwiftBinary("swift-autolink-extract")
     config.target_build_swift = (
@@ -1270,8 +1255,8 @@
 config.substitutions.insert(0, ('%platform-module-dir', platform_module_dir))
 config.substitutions.insert(0, ('%platform-sdk-overlay-dir', platform_sdk_overlay_dir))
 
-config.substitutions.append(('%target-swiftmodule-name', config.target_swiftmodule_name))
-config.substitutions.append(('%target-swiftdoc-name', config.target_swiftdoc_name))
+config.substitutions.append(('%target-swiftmodule-name', run_cpu + '.swiftmodule'))
+config.substitutions.append(('%target-swiftdoc-name', run_cpu + '.swiftdoc'))
 
 config.substitutions.append(('%target-object-format', config.target_object_format))
 config.substitutions.append(('%target-dylib-extension', config.target_dylib_extension))
diff --git a/test/multifile/typealias/one-module/Inputs/library.swift b/test/multifile/typealias/one-module/Inputs/library.swift
index 756a569..fdbb5ef 100644
--- a/test/multifile/typealias/one-module/Inputs/library.swift
+++ b/test/multifile/typealias/one-module/Inputs/library.swift
@@ -5,3 +5,9 @@
 }
 
 public typealias GenericResult<T> = Result<T, Error>
+
+public protocol Rdar46103190 {}
+extension Rdar46103190 {
+  public typealias Alias = String
+  public typealias Map<K: Hashable> = [K: Self]
+}
diff --git a/test/multifile/typealias/one-module/main.swift b/test/multifile/typealias/one-module/main.swift
index 73ca7b4..e7cf483 100644
--- a/test/multifile/typealias/one-module/main.swift
+++ b/test/multifile/typealias/one-module/main.swift
@@ -5,3 +5,18 @@
 
 func testFunction<T>(withCompletion completion: (Result<T, Error>) -> Void) { }
 testFunction { (result: GenericResult<Int>) in }
+
+extension Rdar46103190 {
+  public typealias AnotherAlias = Self.Alias
+  public typealias StringMap = Map<String>
+}
+
+typealias Rdar46103190Alias<R: Rdar46103190> = R.Map<String>
+
+struct Rdar46103190Impl: Rdar46103190 {}
+
+func test46103190() {
+  let _: String = Rdar46103190Impl.AnotherAlias()
+  let _: [String: Rdar46103190Impl] = Rdar46103190Impl.StringMap()
+  let _: [String: Rdar46103190Impl] = Rdar46103190Alias()
+}
diff --git a/test/multifile/typealias/two-modules/Inputs/library.swift b/test/multifile/typealias/two-modules/Inputs/library.swift
index 756a569..fdbb5ef 100644
--- a/test/multifile/typealias/two-modules/Inputs/library.swift
+++ b/test/multifile/typealias/two-modules/Inputs/library.swift
@@ -5,3 +5,9 @@
 }
 
 public typealias GenericResult<T> = Result<T, Error>
+
+public protocol Rdar46103190 {}
+extension Rdar46103190 {
+  public typealias Alias = String
+  public typealias Map<K: Hashable> = [K: Self]
+}
diff --git a/test/multifile/typealias/two-modules/main.swift b/test/multifile/typealias/two-modules/main.swift
index a48c80a..5fee338 100644
--- a/test/multifile/typealias/two-modules/main.swift
+++ b/test/multifile/typealias/two-modules/main.swift
@@ -14,3 +14,18 @@
 
 func testFunction<T>(withCompletion completion: (Result<T, Error>) -> Void) { }
 testFunction { (result: GenericResult<Int>) in }
+
+extension Rdar46103190 {
+  public typealias AnotherAlias = Self.Alias
+  public typealias StringMap = Map<String>
+}
+
+typealias Rdar46103190Alias<R: Rdar46103190> = R.Map<String>
+
+struct Rdar46103190Impl: Rdar46103190 {}
+
+func test46103190() {
+  let _: String = Rdar46103190Impl.AnotherAlias()
+  let _: [String: Rdar46103190Impl] = Rdar46103190Impl.StringMap()
+  let _: [String: Rdar46103190Impl] = Rdar46103190Alias()
+}
diff --git a/test/stdlib/CodableTests.swift b/test/stdlib/CodableTests.swift
index b7a6a78..23dd0c8 100644
--- a/test/stdlib/CodableTests.swift
+++ b/test/stdlib/CodableTests.swift
@@ -49,7 +49,8 @@
     }
 }
 
-func expectRoundTripEquality<T : Codable>(of value: T, encode: (T) throws -> Data, decode: (Data) throws -> T, lineNumber: Int) where T : Equatable {
+func performEncodeAndDecode<T : Codable>(of value: T, encode: (T) throws -> Data, decode: (T.Type, Data) throws -> T, lineNumber: Int) -> T {
+
     let data: Data
     do {
         data = try encode(value)
@@ -57,12 +58,16 @@
         fatalError("\(#file):\(lineNumber): Unable to encode \(T.self) <\(debugDescription(value))>: \(error)")
     }
 
-    let decoded: T
     do {
-        decoded = try decode(data)
+        return try decode(T.self, data)
     } catch {
         fatalError("\(#file):\(lineNumber): Unable to decode \(T.self) <\(debugDescription(value))>: \(error)")
     }
+}
+
+func expectRoundTripEquality<T : Codable>(of value: T, encode: (T) throws -> Data, decode: (T.Type, Data) throws -> T, lineNumber: Int) where T : Equatable {
+
+    let decoded = performEncodeAndDecode(of: value, encode: encode, decode: decode, lineNumber: lineNumber)
 
     expectEqual(value, decoded, "\(#file):\(lineNumber): Decoded \(T.self) <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
 }
@@ -77,12 +82,12 @@
         return try encoder.encode(value)
     }
 
-    let decode = { (_ data: Data) throws -> T in
+    let decode = { (_ type: T.Type, _ data: Data) throws -> T in
         let decoder = JSONDecoder()
         decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: inf,
                                                                         negativeInfinity: negInf,
                                                                         nan: nan)
-        return try decoder.decode(T.self, from: data)
+        return try decoder.decode(type, from: data)
     }
 
     expectRoundTripEquality(of: value, encode: encode, decode: decode, lineNumber: lineNumber)
@@ -93,8 +98,8 @@
         return try PropertyListEncoder().encode(value)
     }
 
-    let decode = { (_ data: Data) throws -> T in
-        return try PropertyListDecoder().decode(T.self, from: data)
+    let decode = { (_ type: T.Type,_ data: Data) throws -> T in
+        return try PropertyListDecoder().decode(type, from: data)
     }
 
     expectRoundTripEquality(of: value, encode: encode, decode: decode, lineNumber: lineNumber)
@@ -351,6 +356,21 @@
         }
     }
 
+    // MARK: - ClosedRange
+    func test_ClosedRange_JSON() {
+        let value = 0...Int.max
+        let decoded = performEncodeAndDecode(of: value, encode: { try JSONEncoder().encode($0) }, decode: { try JSONDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.upperBound, decoded.upperBound, "\(#file):\(#line): Decoded ClosedRange upperBound <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+        expectEqual(value.lowerBound, decoded.lowerBound, "\(#file):\(#line): Decoded ClosedRange lowerBound <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
+    func test_ClosedRange_Plist() {
+        let value = 0...Int.max
+        let decoded = performEncodeAndDecode(of: value, encode: { try PropertyListEncoder().encode($0) }, decode: { try PropertyListDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.upperBound, decoded.upperBound, "\(#file):\(#line): Decoded ClosedRange upperBound <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+        expectEqual(value.lowerBound, decoded.lowerBound, "\(#file):\(#line): Decoded ClosedRange lowerBound <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
     // MARK: - DateComponents
     lazy var dateComponents: Set<Calendar.Component> = [
         .era, .year, .month, .day, .hour, .minute, .second, .nanosecond,
@@ -545,6 +565,45 @@
         }
     }
 
+    // MARK: - PartialRangeFrom
+    func test_PartialRangeFrom_JSON() {
+        let value = 0...
+        let decoded = performEncodeAndDecode(of: value, encode: { try JSONEncoder().encode($0) }, decode: { try JSONDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.lowerBound, decoded.lowerBound, "\(#file):\(#line): Decoded PartialRangeFrom <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
+    func test_PartialRangeFrom_Plist() {
+        let value = 0...
+        let decoded = performEncodeAndDecode(of: value, encode: { try PropertyListEncoder().encode($0) }, decode: { try PropertyListDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.lowerBound, decoded.lowerBound, "\(#file):\(#line): Decoded PartialRangeFrom <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
+    // MARK: - PartialRangeThrough
+    func test_PartialRangeThrough_JSON() {
+        let value = ...Int.max
+        let decoded = performEncodeAndDecode(of: value, encode: { try JSONEncoder().encode($0) }, decode: { try JSONDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.upperBound, decoded.upperBound, "\(#file):\(#line): Decoded PartialRangeThrough <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
+    func test_PartialRangeThrough_Plist() {
+        let value = ...Int.max
+        let decoded = performEncodeAndDecode(of: value, encode: { try PropertyListEncoder().encode($0) }, decode: { try PropertyListDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.upperBound, decoded.upperBound, "\(#file):\(#line): Decoded PartialRangeThrough <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
+    // MARK: - PartialRangeUpTo
+    func test_PartialRangeUpTo_JSON() {
+        let value = ..<Int.max
+        let decoded = performEncodeAndDecode(of: value, encode: { try JSONEncoder().encode($0) }, decode: { try JSONDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.upperBound, decoded.upperBound, "\(#file):\(#line): Decoded PartialRangeUpTo <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
+    func test_PartialRangeUpTo_Plist() {
+        let value = ..<Int.max
+        let decoded = performEncodeAndDecode(of: value, encode: { try PropertyListEncoder().encode($0) }, decode: { try PropertyListDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.upperBound, decoded.upperBound, "\(#file):\(#line): Decoded PartialRangeUpTo <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
     // MARK: - PersonNameComponents
     @available(macOS 10.11, iOS 9.0, watchOS 2.0, tvOS 9.0, *)
     lazy var personNameComponentsValues: [Int : PersonNameComponents] = [
@@ -567,6 +626,21 @@
         }
     }
 
+    // MARK: - Range
+    func test_Range_JSON() {
+        let value = 0..<Int.max
+        let decoded = performEncodeAndDecode(of: value, encode: { try JSONEncoder().encode($0) }, decode: { try JSONDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.upperBound, decoded.upperBound, "\(#file):\(#line): Decoded Range upperBound <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+        expectEqual(value.lowerBound, decoded.lowerBound, "\(#file):\(#line): Decoded Range lowerBound<\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
+    func test_Range_Plist() {
+        let value = 0..<Int.max
+        let decoded = performEncodeAndDecode(of: value, encode: { try PropertyListEncoder().encode($0) }, decode: { try PropertyListDecoder().decode($0, from: $1)  }, lineNumber: #line)
+        expectEqual(value.upperBound, decoded.upperBound, "\(#file):\(#line): Decoded Range upperBound<\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+        expectEqual(value.lowerBound, decoded.lowerBound, "\(#file):\(#line): Decoded Range lowerBound<\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
+    }
+
     // MARK: - TimeZone
     lazy var timeZoneValues: [Int : TimeZone] = [
         #line : TimeZone(identifier: "America/Los_Angeles")!,
@@ -777,6 +851,8 @@
     "test_CGRect_Plist" : TestCodable.test_CGRect_Plist,
     "test_CGVector_JSON" : TestCodable.test_CGVector_JSON,
     "test_CGVector_Plist" : TestCodable.test_CGVector_Plist,
+    "test_ClosedRange_JSON" : TestCodable.test_ClosedRange_JSON,
+    "test_ClosedRange_Plist" : TestCodable.test_ClosedRange_Plist,
     "test_DateComponents_JSON" : TestCodable.test_DateComponents_JSON,
     "test_DateComponents_Plist" : TestCodable.test_DateComponents_Plist,
     "test_Decimal_JSON" : TestCodable.test_Decimal_JSON,
@@ -789,6 +865,14 @@
     "test_Locale_Plist" : TestCodable.test_Locale_Plist,
     "test_NSRange_JSON" : TestCodable.test_NSRange_JSON,
     "test_NSRange_Plist" : TestCodable.test_NSRange_Plist,
+    "test_PartialRangeFrom_JSON" : TestCodable.test_PartialRangeFrom_JSON,
+    "test_PartialRangeFrom_Plist" : TestCodable.test_PartialRangeFrom_Plist,
+    "test_PartialRangeThrough_JSON" : TestCodable.test_PartialRangeThrough_JSON,
+    "test_PartialRangeThrough_Plist" : TestCodable.test_PartialRangeThrough_Plist,
+    "test_PartialRangeUpTo_JSON" : TestCodable.test_PartialRangeUpTo_JSON,
+    "test_PartialRangeUpTo_Plist" : TestCodable.test_PartialRangeUpTo_Plist,
+    "test_Range_JSON" : TestCodable.test_Range_JSON,
+    "test_Range_Plist" : TestCodable.test_Range_Plist,
     "test_TimeZone_JSON" : TestCodable.test_TimeZone_JSON,
     "test_TimeZone_Plist" : TestCodable.test_TimeZone_Plist,
     "test_URL_JSON" : TestCodable.test_URL_JSON,
diff --git a/test/stdlib/Inputs/DictionaryKeyValueTypesObjC.swift b/test/stdlib/Inputs/DictionaryKeyValueTypesObjC.swift
index 35e87fd..d367e89 100644
--- a/test/stdlib/Inputs/DictionaryKeyValueTypesObjC.swift
+++ b/test/stdlib/Inputs/DictionaryKeyValueTypesObjC.swift
@@ -33,7 +33,7 @@
   let className: NSString = NSStringFromClass(type(of: d)) as NSString
   return [
     "_SwiftDeferredNSDictionary",
-    "_EmptyDictionarySingleton",
+    "__EmptyDictionarySingleton",
     "_DictionaryStorage"].contains {
     className.range(of: $0).length > 0
   }
diff --git a/test/stdlib/IntegerRenames4.swift b/test/stdlib/IntegerRenames4.swift
deleted file mode 100644
index dbc1b1f..0000000
--- a/test/stdlib/IntegerRenames4.swift
+++ /dev/null
@@ -1,31 +0,0 @@
-// RUN: %target-typecheck-verify-swift -swift-version 4
-
-func f<T : SignedInteger>(x: T) {
-  _ = T.addWithOverflow(x, x) // expected-error {{'addWithOverflow' is unavailable: Please use FixedWidthInteger protocol as a generic constraint and addingReportingOverflow(_:) method instead.}}
-  _ = T.subtractWithOverflow(x, x) // expected-error {{'subtractWithOverflow' is unavailable: Please use FixedWidthInteger protocol as a generic constraint and subtractingReportingOverflow(_:) method instead.}}
-  _ = T.multiplyWithOverflow(x, x) // expected-error {{'multiplyWithOverflow' is unavailable: Please use FixedWidthInteger protocol as a generic constraint and multipliedReportingOverflow(by:) method instead.}}
-  _ = T.divideWithOverflow(x, x) // expected-error {{'divideWithOverflow' is unavailable: Please use FixedWidthInteger protocol as a generic constraint and dividedReportingOverflow(by:) method instead.}}
-  _ = T.remainderWithOverflow(x, x) // expected-error {{'remainderWithOverflow' is unavailable: Please use FixedWidthInteger protocol as a generic constraint and remainderReportingOverflow(dividingBy:) method instead.}}
-}
-
-func f<T : FixedWidthInteger>(x: T) {
-  _ = T.addWithOverflow(x, x) // expected-error {{'addWithOverflow' is unavailable: Use addingReportingOverflow(_:) instead.}}
-  _ = T.subtractWithOverflow(x, x) // expected-error {{'subtractWithOverflow' is unavailable: Use subtractingReportingOverflow(_:) instead.}}
-  _ = T.multiplyWithOverflow(x, x) // expected-error {{'multiplyWithOverflow' is unavailable: Use multipliedReportingOverflow(by:) instead.}}
-  _ = T.divideWithOverflow(x, x) // expected-error {{'divideWithOverflow' is unavailable: Use dividedReportingOverflow(by:) instead.}}
-  _ = T.remainderWithOverflow(x, x) // expected-error {{'remainderWithOverflow' is unavailable: Use remainderReportingOverflow(dividingBy:) instead.}}
-}
-
-do {
-  let _: IntMax = 0 // expected-error {{'IntMax' has been renamed to 'Int64'}}
-  let _: UIntMax = 0 // expected-error {{'UIntMax' has been renamed to 'UInt64'}}
-}
-
-func absolutaValuable<T : SignedNumeric & Comparable>(x: T) {
-  _ = T.abs(x) // expected-error {{type 'T' has no member 'abs'}}
-}
-
-func signedIntegerMaskingArithmetics<T : SignedInteger>(x: T) {
-  _ = x &+ x // expected-error {{use 'FixedWidthInteger' instead of 'SignedInteger' to get '&+' in generic code}}
-  _ = x &- x // expected-error {{use 'FixedWidthInteger' instead of 'SignedInteger' to get '&-' in generic code}}
-}
diff --git a/test/stdlib/ManagedBuffer.swift b/test/stdlib/ManagedBuffer.swift
index 8d39d3f..24d288c 100644
--- a/test/stdlib/ManagedBuffer.swift
+++ b/test/stdlib/ManagedBuffer.swift
@@ -40,7 +40,7 @@
 
 struct CountAndCapacity {
   var count: LifetimeTracked
-  var capacity: Int
+  let capacity: Int
 }
 
 // An example of ManagedBuffer, very similar to what Array will use.
@@ -96,23 +96,6 @@
     }
     self.count = count + 2
   }
-
-  class func tryGrow(_ buffer: inout TestManagedBuffer<T>, newCapacity: Int) -> Bool {
-    guard isKnownUniquelyReferenced(&buffer) else {
-      return false
-    }
-    guard newCapacity > buffer.capacity else {
-      return false
-    }
-
-    if tryReallocateUniquelyReferenced(buffer: &buffer,
-                                       newMinimumCapacity: newCapacity) {
-      buffer.header.capacity = newCapacity
-      return true
-    } else {
-      return false
-    }
-  }
 }
 
 class MyBuffer<T> {
@@ -258,35 +241,4 @@
   _fixLifetime(s2)
 }
 
-tests.test("canGrowUsingRealloc") {
-  #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
-  return // realloc currently unsupported on Darwin
-  #endif
-  func testGrow(_ buffer: inout TestManagedBuffer<LifetimeTracked>,
-                newCapacity: Int,
-                shouldSucceed: Bool = true) {
-    let s = TestManagedBuffer.tryGrow(&buffer, newCapacity: newCapacity)
-    expectEqual(s, shouldSucceed)
-    if shouldSucceed {
-      expectLE(newCapacity, buffer.myCapacity)
-      expectGE((newCapacity + 1) * 2, buffer.myCapacity)
-    }
-    repeat {
-      buffer.append(LifetimeTracked(buffer.count))
-    } while buffer.count < buffer.myCapacity - 2
-  }
-
-  var b = TestManagedBuffer<LifetimeTracked>.create(0)
-  // allow some over-allocation
-  expectLE(0, b.myCapacity)
-  expectGE(3, b.myCapacity)
-
-  testGrow(&b, newCapacity: 5)
-  testGrow(&b, newCapacity: 8)
-  testGrow(&b, newCapacity: 1000)
-  testGrow(&b, newCapacity: 16000)
-  var b2 = b
-  testGrow(&b, newCapacity: 2000, shouldSucceed: false)
-}
-
 runAllTests()
diff --git a/test/stdlib/RuntimeObjC.swift b/test/stdlib/RuntimeObjC.swift
index 69fed6e..75e9623 100644
--- a/test/stdlib/RuntimeObjC.swift
+++ b/test/stdlib/RuntimeObjC.swift
@@ -334,6 +334,33 @@
 protocol ProtocolA {}
 protocol ProtocolB {}
 
+class OuterClass {
+    
+    private class PrivateGeneric<T, U> {
+      class InnerGeneric<X> {
+        class Inner { }
+      }
+    }
+    
+    static func getPrivateGenericName() -> String {
+      return NSStringFromClass(OuterClass.PrivateGeneric<Int, Bool>.self)
+    }
+    static func getInnerGenericName() -> String {
+      return NSStringFromClass(OuterClass.PrivateGeneric<Int, Bool>.InnerGeneric<Float>.self)
+    }
+    static func getInnerName() -> String {
+      return NSStringFromClass(OuterClass.PrivateGeneric<Int, Bool>.InnerGeneric<Float>.Inner.self)
+    }
+}
+
+// The private discriminator is not deterministic.
+// Replace it with a constant string.
+func removePrivateDiscriminator(_ symbol: String) -> String {
+  let regexp = try! NSRegularExpression(pattern: "P[0-9]+\\$[0-9a-f]+")
+  let range = NSRange(0..<symbol.count)
+  return regexp.stringByReplacingMatches(in: symbol, range: range, withTemplate: "XXX")
+}
+
 Runtime.test("Generic class ObjC runtime names") {
   expectEqual("_TtGC1a12GenericClassSi_",
               NSStringFromClass(GenericClass<Int>.self))
@@ -385,6 +412,13 @@
   expectEqual("_TtGC1a17MultiGenericClassGVS_13GenericStructSi_GOS_11GenericEnumGS2_Si___",
               NSStringFromClass(MultiGenericClass<GenericStruct<Int>,
                                                   GenericEnum<GenericEnum<Int>>>.self))
+  
+  expectEqual("_TtGCC1a10OuterClassXXXPrivateGeneric_SiSb_",
+              removePrivateDiscriminator(OuterClass.getPrivateGenericName()))
+  expectEqual("_TtGCCC1a10OuterClassXXXPrivateGeneric12InnerGeneric_SiSb_Sf_",
+              removePrivateDiscriminator(OuterClass.getInnerGenericName()))
+  expectEqual("_TtGCCCC1a10OuterClassXXXPrivateGeneric12InnerGeneric5Inner_SiSb_Sf__",
+              removePrivateDiscriminator(OuterClass.getInnerName()))
 }
 
 @objc protocol P {}
diff --git a/test/stdlib/SIMD.swift b/test/stdlib/SIMD.swift
new file mode 100644
index 0000000..6904f9c
--- /dev/null
+++ b/test/stdlib/SIMD.swift
@@ -0,0 +1,91 @@
+// RUN: %target-run-simple-swift
+// REQUIRES: executable_test
+// REQUIRES: objc_interop
+
+import Foundation
+import StdlibUnittest
+
+let SIMDCodableTests = TestSuite("SIMDCodable")
+
+// Round an integer to the closest representable JS integer value
+func jsInteger<T>(_ value: T) -> T
+where T : SIMD, T.Scalar : FixedWidthInteger {
+  // Attempt to round-trip though Double; if that fails it's because the
+  // rounded value is too large to fit in T, so use the largest value that
+  // does fit instead.
+  let upperBound = T.Scalar(Double(T.Scalar.max).nextDown)
+  var result = T()
+  for i in result.indices {
+    result[i] = T.Scalar(exactly: Double(value[i])) ?? upperBound
+  }
+  return result
+}
+
+func testRoundTrip<T>(_ for: T.Type)
+where T : SIMD, T.Scalar : FixedWidthInteger {
+  let input = jsInteger(T.random(in: T.Scalar.min ... T.Scalar.max))
+  let encoder = JSONEncoder()
+  let decoder = JSONDecoder()
+  do {
+    let data = try encoder.encode(input)
+    let output = try decoder.decode(T.self, from: data)
+    expectEqual(input, output)
+  }
+  catch {
+    expectUnreachableCatch(error)
+  }
+}
+
+func testRoundTrip<T>(_ for: T.Type)
+where T : SIMD, T.Scalar : BinaryFloatingPoint,
+      T.Scalar.RawSignificand : FixedWidthInteger {
+  let input = T.random(in: -16 ..< 16)
+  let encoder = JSONEncoder()
+  let decoder = JSONDecoder()
+  do {
+    let data = try encoder.encode(input)
+    let output = try decoder.decode(T.self, from: data)
+    expectEqual(input, output)
+  }
+  catch {
+    expectUnreachableCatch(error)
+  }
+}
+
+// Very basic round-trip test. We can be much more sophisticated in the future,
+// but we want to at least exercise the API. Also need to add some negative
+// tests for the error paths, and test a more substantial set of types.
+SIMDCodableTests.test("roundTrip") {
+  testRoundTrip(SIMD2<Int8>.self)
+  testRoundTrip(SIMD3<Int8>.self)
+  testRoundTrip(SIMD4<Int8>.self)
+  testRoundTrip(SIMD2<UInt8>.self)
+  testRoundTrip(SIMD3<UInt8>.self)
+  testRoundTrip(SIMD4<UInt8>.self)
+  testRoundTrip(SIMD2<Int32>.self)
+  testRoundTrip(SIMD3<Int32>.self)
+  testRoundTrip(SIMD4<Int32>.self)
+  testRoundTrip(SIMD2<UInt32>.self)
+  testRoundTrip(SIMD3<UInt32>.self)
+  testRoundTrip(SIMD4<UInt32>.self)
+  testRoundTrip(SIMD2<Int>.self)
+  testRoundTrip(SIMD3<Int>.self)
+  testRoundTrip(SIMD4<Int>.self)
+  testRoundTrip(SIMD2<UInt>.self)
+  testRoundTrip(SIMD3<UInt>.self)
+  testRoundTrip(SIMD4<UInt>.self)
+/* Apparently these fail to round trip not only for i386 but also on older
+   macOS versions, so we'll disable them entirely for now.
+#if !arch(i386)
+  // https://bugs.swift.org/browse/SR-9759
+  testRoundTrip(SIMD2<Float>.self)
+  testRoundTrip(SIMD3<Float>.self)
+  testRoundTrip(SIMD4<Float>.self)
+  testRoundTrip(SIMD2<Double>.self)
+  testRoundTrip(SIMD3<Double>.self)
+  testRoundTrip(SIMD4<Double>.self)
+#endif
+  */
+}
+
+runAllTests()
diff --git a/test/stdlib/TestData.swift b/test/stdlib/TestData.swift
index ec8606f..50de8f1 100644
--- a/test/stdlib/TestData.swift
+++ b/test/stdlib/TestData.swift
@@ -673,12 +673,6 @@
         expectEqual("SGVsbG8gV29ybGQ=", base64, "trivial base64 conversion should work")
     }
 
-    func test_dataHash() {
-        let dataStruct = "Hello World".data(using: .utf8)!
-        let dataObj = dataStruct as NSData
-        expectEqual(dataObj.hashValue, dataStruct.hashValue, "Data and NSData should have the same hash value")
-    }
-
     func test_base64Data_medium() {
         let data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut at tincidunt arcu. Suspendisse nec sodales erat, sit amet imperdiet ipsum. Etiam sed ornare felis. Nunc mauris turpis, bibendum non lectus quis, malesuada placerat turpis. Nam adipiscing non massa et semper. Nulla convallis semper bibendum. Aliquam dictum nulla cursus mi ultricies, at tincidunt mi sagittis. Nulla faucibus at dui quis sodales. Morbi rutrum, dui id ultrices venenatis, arcu urna egestas felis, vel suscipit mauris arcu quis risus. Nunc venenatis ligula at orci tristique, et mattis purus pulvinar. Etiam ultricies est odio. Nunc eleifend malesuada justo, nec euismod sem ultrices quis. Etiam nec nibh sit amet lorem faucibus dapibus quis nec leo. Praesent sit amet mauris vel lacus hendrerit porta mollis consectetur mi. Donec eget tortor dui. Morbi imperdiet, arcu sit amet elementum interdum, quam nisl tempor quam, vitae feugiat augue purus sed lacus. In ac urna adipiscing purus venenatis volutpat vel et metus. Nullam nec auctor quam. Phasellus porttitor felis ac nibh gravida suscipit tempus at ante. Nunc pellentesque iaculis sapien a mattis. Aenean eleifend dolor non nunc laoreet, non dictum massa aliquam. Aenean quis turpis augue. Praesent augue lectus, mollis nec elementum eu, dignissim at velit. Ut congue neque id ullamcorper pellentesque. Maecenas euismod in elit eu vehicula. Nullam tristique dui nulla, nec convallis metus suscipit eget. Cras semper augue nec cursus blandit. Nulla rhoncus et odio quis blandit. Praesent lobortis dignissim velit ut pulvinar. Duis interdum quam adipiscing dolor semper semper. Nunc bibendum convallis dui, eget mollis magna hendrerit et. Morbi facilisis, augue eu fringilla convallis, mauris est cursus dolor, eu posuere odio nunc quis orci. Ut eu justo sem. Phasellus ut erat rhoncus, faucibus arcu vitae, vulputate erat. Aliquam nec magna viverra, interdum est vitae, rhoncus sapien. Duis tincidunt tempor ipsum ut dapibus. Nullam commodo varius metus, sed sollicitudin eros. Etiam nec odio et dui tempor blandit posuere.".data(using: .utf8)!
         let base64 = data.base64EncodedString()
@@ -1189,6 +1183,49 @@
         expectEqual(Data(bytes: [1]), slice)
     }
 
+    // This test uses `repeatElement` to produce a sequence -- the produced sequence reports its actual count as its `.underestimatedCount`.
+    func test_appendingNonContiguousSequence_exactCount() {
+        var d = Data()
+
+        // d should go from .empty representation to .inline.
+        // Appending a small enough sequence to fit in .inline should actually be copied.
+        d.append(contentsOf: 0x00...0x01)
+        expectEqual(Data([0x00, 0x01]), d)
+
+        // Appending another small sequence should similarly still work.
+        d.append(contentsOf: 0x02...0x02)
+        expectEqual(Data([0x00, 0x01, 0x02]), d)
+
+        // If we append a sequence of elements larger than a single InlineData, the internal append here should buffer.
+        // We want to make sure that buffering in this way does not accidentally drop trailing elements on the floor.
+        d.append(contentsOf: 0x03...0x17)
+        expectEqual(Data([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+                          0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
+                          0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17]), d)
+    }
+
+    // This test is like test_appendingNonContiguousSequence_exactCount but uses a sequence which reports 0 for its `.underestimatedCount`.
+    // This attempts to hit the worst-case scenario of `Data.append<S>(_:)` -- a discontiguous sequence of unknown length.
+    func test_appendingNonContiguousSequence_underestimatedCount() {
+        var d = Data()
+
+        // d should go from .empty representation to .inline.
+        // Appending a small enough sequence to fit in .inline should actually be copied.
+        d.append(contentsOf: (0x00...0x01).makeIterator()) // `.makeIterator()` produces a sequence whose `.underestimatedCount` is 0.
+        expectEqual(Data([0x00, 0x01]), d)
+
+        // Appending another small sequence should similarly still work.
+        d.append(contentsOf: (0x02...0x02).makeIterator()) // `.makeIterator()` produces a sequence whose `.underestimatedCount` is 0.
+        expectEqual(Data([0x00, 0x01, 0x02]), d)
+
+        // If we append a sequence of elements larger than a single InlineData, the internal append here should buffer.
+        // We want to make sure that buffering in this way does not accidentally drop trailing elements on the floor.
+        d.append(contentsOf: (0x03...0x17).makeIterator()) // `.makeIterator()` produces a sequence whose `.underestimatedCount` is 0.
+        expectEqual(Data([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+                          0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
+                          0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17]), d)
+    }
+
     func test_sequenceInitializers() {
         let seq = repeatElement(UInt8(0x02), count: 3) // ensure we fall into the sequence case
         
@@ -3728,7 +3765,6 @@
 DataTests.test("testCopyBytes_ranges") { TestData().testCopyBytes_ranges() }
 DataTests.test("test_base64Data_small") { TestData().test_base64Data_small() }
 DataTests.test("test_base64Data_medium") { TestData().test_base64Data_medium() }
-DataTests.test("test_dataHash") { TestData().test_dataHash() }
 DataTests.test("test_discontiguousEnumerateBytes") { TestData().test_discontiguousEnumerateBytes() }
 DataTests.test("test_basicReadWrite") { TestData().test_basicReadWrite() }
 DataTests.test("test_writeFailure") { TestData().test_writeFailure() }
@@ -3760,6 +3796,8 @@
 DataTests.test("test_copyBytes2") { TestData().test_copyBytes2() }
 DataTests.test("test_sliceOfSliceViaRangeExpression") { TestData().test_sliceOfSliceViaRangeExpression() }
 DataTests.test("test_appendingSlices") { TestData().test_appendingSlices() }
+DataTests.test("test_appendingNonContiguousSequence_exactCount") { TestData().test_appendingNonContiguousSequence_exactCount() }
+DataTests.test("test_appendingNonContiguousSequence_underestimatedCount") { TestData().test_appendingNonContiguousSequence_underestimatedCount() }
 DataTests.test("test_sequenceInitializers") { TestData().test_sequenceInitializers() }
 DataTests.test("test_reversedDataInit") { TestData().test_reversedDataInit() }
 DataTests.test("test_replaceSubrangeReferencingMutable") { TestData().test_replaceSubrangeReferencingMutable() }
diff --git a/tools/SourceKit/lib/SwiftLang/SwiftEditor.cpp b/tools/SourceKit/lib/SwiftLang/SwiftEditor.cpp
index 2d84e86..6f88937 100644
--- a/tools/SourceKit/lib/SwiftLang/SwiftEditor.cpp
+++ b/tools/SourceKit/lib/SwiftLang/SwiftEditor.cpp
@@ -1266,8 +1266,8 @@
   }
 
   StringRef getObjCSelectorName(const Decl *D, SmallString<64> &Buf) {
-    if (auto FuncD = dyn_cast_or_null<AbstractFunctionDecl>(D)) {
-      // We only vend the selector name for @IBAction methods.
+    // We only vend the selector name for @IBAction methods.
+    if (auto FuncD = dyn_cast_or_null<FuncDecl>(D)) {
       if (FuncD->getAttrs().hasAttribute<IBActionAttr>())
         return FuncD->getObjCSelector().getString(Buf);
     }
diff --git a/utils/gyb_syntax_support/ExprNodes.py b/utils/gyb_syntax_support/ExprNodes.py
index fc94746..3fba94f 100644
--- a/utils/gyb_syntax_support/ExprNodes.py
+++ b/utils/gyb_syntax_support/ExprNodes.py
@@ -309,10 +309,10 @@
                    is_optional=True),
          ]),
 
-    # dot-self-expr -> expr '.' 'self'
+    # dot-self-expr -> expr? '.' 'self'
     Node('DotSelfExpr', kind='Expr',
          children=[
-             Child('Expression', kind='Expr'),
+             Child('Expression', kind='Expr', is_optional=True),
              Child('Dot', kind='Token',
                    token_choices=[
                        'PeriodToken', 'PrefixPeriodToken'
diff --git a/validation-test/Runtime/Inputs/class-layout-from-objc/Classes.swift b/validation-test/Runtime/Inputs/class-layout-from-objc/Classes.swift
new file mode 100644
index 0000000..7c45961
--- /dev/null
+++ b/validation-test/Runtime/Inputs/class-layout-from-objc/Classes.swift
@@ -0,0 +1,65 @@
+import Resilient
+import Foundation
+import OneWordSuperclass
+
+public class StaticClass: OneWordSuperclass {
+  @objc var first: Int32 = 0
+  var middle = GrowsToInt64()
+  @objc var last: Int = 0
+
+  @objc public static var offsetOfFirst: Int {
+    // IRGen lays out Swift classes that subclass Objective-C classes as if the
+    // only superclass was NSObject, so the starting (offset % alignment) isn't
+    // always 0. This means that on 32-bit platforms we'll have a gap *before*
+    // 'first' when we need 8-byte alignment, rather than after as you'd see in
+    // a struct (or base class).
+    return max(MemoryLayout<Int>.size, MemoryLayout<GrowsToInt64>.alignment) +
+           MemoryLayout<Int>.size
+  }
+
+  @objc public static var totalSize: Int {
+    return (2 * MemoryLayout<Int>.size) +
+           (2 * MemoryLayout<GrowsToInt64>.size) + // alignment
+           MemoryLayout<Int>.size
+  }
+}
+
+/// This class has the same layout as `StaticClass`, but will be accessed using
+/// `NSClassFromString` instead of `+class`.
+public class DynamicClass: OneWordSuperclass {
+  @objc var first: Int32 = 0
+  var middle = GrowsToInt64()
+  @objc var last: Int = 0
+
+  @objc public static var offsetOfFirst: Int {
+    // See above.
+    return max(MemoryLayout<Int>.size, MemoryLayout<GrowsToInt64>.alignment) +
+           MemoryLayout<Int>.size
+  }
+
+  @objc public static var totalSize: Int {
+    return (2 * MemoryLayout<Int>.size) +
+           (2 * MemoryLayout<GrowsToInt64>.size) + // alignment
+           MemoryLayout<Int>.size
+  }
+}
+
+public class PureSwiftBaseClass {
+  var word: Int64 = 0
+}
+
+public class PureSwiftClass: PureSwiftBaseClass {
+  @objc var first: Int32 = 0
+  var middle = GrowsToInt64()
+  @objc var last: Int = 0
+
+  @objc public static var offsetOfFirst: Int {
+    return (2 * MemoryLayout<Int>.size) + MemoryLayout<Int64>.size
+  }
+
+  @objc public static var totalSize: Int {
+    return (2 * MemoryLayout<Int>.size) + MemoryLayout<Int64>.size +
+           (2 * MemoryLayout<GrowsToInt64>.size) + // alignment
+           MemoryLayout<Int>.size
+  }
+}
diff --git a/validation-test/Runtime/Inputs/class-layout-from-objc/OneWordSuperclass.h b/validation-test/Runtime/Inputs/class-layout-from-objc/OneWordSuperclass.h
new file mode 100644
index 0000000..8abbec0
--- /dev/null
+++ b/validation-test/Runtime/Inputs/class-layout-from-objc/OneWordSuperclass.h
@@ -0,0 +1,4 @@
+@import Foundation;
+
+@interface OneWordSuperclass : NSObject
+@end
diff --git a/validation-test/Runtime/Inputs/class-layout-from-objc/OneWordSuperclass.m b/validation-test/Runtime/Inputs/class-layout-from-objc/OneWordSuperclass.m
new file mode 100644
index 0000000..42d7614
--- /dev/null
+++ b/validation-test/Runtime/Inputs/class-layout-from-objc/OneWordSuperclass.m
@@ -0,0 +1,6 @@
+#import "OneWordSuperclass.h"
+
+@implementation OneWordSuperclass {
+  intptr_t unused;
+}
+@end
diff --git a/validation-test/Runtime/Inputs/class-layout-from-objc/Resilient.swift b/validation-test/Runtime/Inputs/class-layout-from-objc/Resilient.swift
new file mode 100644
index 0000000..a9f4b6e
--- /dev/null
+++ b/validation-test/Runtime/Inputs/class-layout-from-objc/Resilient.swift
@@ -0,0 +1,11 @@
+public struct GrowsToInt64 {
+  #if SMALL
+  var value: Int32
+  #elseif BIG
+  var value: Int64
+  #else
+  #error("Must define SMALL or BIG")
+  #endif
+
+  public init() { self.value = 0 }
+}
diff --git a/validation-test/Runtime/Inputs/class-layout-from-objc/module.modulemap b/validation-test/Runtime/Inputs/class-layout-from-objc/module.modulemap
new file mode 100644
index 0000000..76fb327
--- /dev/null
+++ b/validation-test/Runtime/Inputs/class-layout-from-objc/module.modulemap
@@ -0,0 +1,4 @@
+module OneWordSuperclass {
+  header "OneWordSuperclass.h"
+  export *
+}
diff --git a/validation-test/Runtime/class-layout-from-objc.m b/validation-test/Runtime/class-layout-from-objc.m
new file mode 100644
index 0000000..47cbee4
--- /dev/null
+++ b/validation-test/Runtime/class-layout-from-objc.m
@@ -0,0 +1,78 @@
+// Check that when Objective-C is first to touch a Swift class, it gives the
+// Swift runtime a chance to update instance size and ivar offset metadata.
+
+// RUN: %empty-directory(%t)
+// RUN: %target-build-swift -emit-library -emit-module -o %t/libResilient.dylib %S/Inputs/class-layout-from-objc/Resilient.swift -Xlinker -install_name -Xlinker @executable_path/libResilient.dylib -Xfrontend -enable-resilience -DSMALL
+
+// RUN: %target-clang -c %S/Inputs/class-layout-from-objc/OneWordSuperclass.m -fmodules -fobjc-arc -o %t/OneWordSuperclass.o
+// RUN: %target-build-swift -emit-library -o %t/libClasses.dylib -emit-objc-header-path %t/Classes.h -I %t -I %S/Inputs/class-layout-from-objc/ %S/Inputs/class-layout-from-objc/Classes.swift %t/OneWordSuperclass.o -Xlinker -install_name -Xlinker @executable_path/libClasses.dylib -lResilient -L %t
+// RUN: %target-clang %s -I %S/Inputs/class-layout-from-objc/ -I %t -fmodules -fobjc-arc -o %t/main -lResilient -lClasses -L %t
+// RUN: %target-codesign %t/main %t/libResilient.dylib %t/libClasses.dylib
+// RUN: %target-run %t/main OLD %t/libResilient.dylib %t/libClasses.dylib
+
+// RUN: %target-build-swift -emit-library -emit-module -o %t/libResilient.dylib %S/Inputs/class-layout-from-objc/Resilient.swift -Xlinker -install_name -Xlinker @executable_path/libResilient.dylib -Xfrontend -enable-resilience -DBIG
+// RUN: %target-codesign %t/libResilient.dylib
+// RUN: %target-run %t/main NEW %t/libResilient.dylib %t/libClasses.dylib
+
+// Try again when the class itself is also resilient.
+// RUN: %target-build-swift -emit-library -o %t/libClasses.dylib -emit-objc-header-path %t/Classes.h -I %S/Inputs/class-layout-from-objc/ -I %t %S/Inputs/class-layout-from-objc/Classes.swift %t/OneWordSuperclass.o -Xlinker -install_name -Xlinker @executable_path/libClasses.dylib -lResilient -L %t
+// RUN: %target-codesign %t/libClasses.dylib
+// RUN: %target-run %t/main OLD %t/libResilient.dylib %t/libClasses.dylib
+
+// RUN: %target-build-swift -emit-library -emit-module -o %t/libResilient.dylib %S/Inputs/class-layout-from-objc/Resilient.swift -Xlinker -install_name -Xlinker @executable_path/libResilient.dylib -Xfrontend -enable-resilience -DSMALL
+// RUN: %target-codesign %t/libResilient.dylib
+// RUN: %target-run %t/main NEW %t/libResilient.dylib %t/libClasses.dylib
+
+// REQUIRES: executable_test
+// REQUIRES: objc_interop
+
+#import <objc/runtime.h>
+#import <assert.h>
+#import <dlfcn.h>
+#import <stdbool.h>
+#import <string.h>
+
+#import "Classes.h"
+
+void checkClass(Class c) {
+  assert(c);
+
+  size_t expectedSize = [c totalSize];
+  size_t actualSize = class_getInstanceSize([c class]);
+  NSLog(@"%@: expected size %zd, actual size %zd", c, expectedSize, actualSize);
+  assert(expectedSize == actualSize);
+
+  size_t expectedOffsetOfFirst = [c offsetOfFirst];
+  size_t offsetOfFirst = ivar_getOffset(class_getInstanceVariable(c, "first"));
+  NSLog(@"expected offset of 'first' %zd, actual %zd",
+        expectedOffsetOfFirst, offsetOfFirst);
+  assert(offsetOfFirst == expectedOffsetOfFirst);
+
+  size_t offsetOfLast = ivar_getOffset(class_getInstanceVariable(c, "last"));
+  NSLog(@"offset of 'last' %zd", offsetOfLast);
+  assert(offsetOfLast == actualSize - sizeof(intptr_t));
+}
+
+int main(int argc, const char * const argv[]) {
+  assert(argc > 1);
+
+  if (!strcmp(argv[1], "OLD")) {
+    ;
+  } else if (!strcmp(argv[1], "NEW")) {
+    // Only test the new behavior on a new enough libobjc.
+    if (!dlsym(RTLD_NEXT, "_objc_realizeClassFromSwift")) {
+      fprintf(stderr, "skipping evolution tests; OS too old\n");
+      return EXIT_SUCCESS;
+    }
+  } else {
+    fprintf(stderr, "usage: %s (OLD|NEW)\n", argv[0]);
+    return EXIT_FAILURE;
+  }
+
+  @autoreleasepool {
+    NSLog(@"%zd", class_getInstanceSize([OneWordSuperclass class]));
+    checkClass([StaticClass class]);
+    checkClass(objc_getClass("Classes.DynamicClass"));
+    checkClass(objc_getClass("Classes.PureSwiftClass"));
+  }
+}
diff --git a/validation-test/Sema/Inputs/rdar47334176_types.swift b/validation-test/Sema/Inputs/rdar47334176_types.swift
new file mode 100644
index 0000000..f5266f1
--- /dev/null
+++ b/validation-test/Sema/Inputs/rdar47334176_types.swift
@@ -0,0 +1,10 @@
+public protocol P : class {
+  associatedtype V
+}
+
+public protocol R {
+  associatedtype V
+}
+
+public enum E<V> : R {}
+public class C<V> : R {}
diff --git a/validation-test/Sema/rdar47334176.swift b/validation-test/Sema/rdar47334176.swift
new file mode 100644
index 0000000..cca1c66
--- /dev/null
+++ b/validation-test/Sema/rdar47334176.swift
@@ -0,0 +1,13 @@
+// RUN: %empty-directory(%t)
+// RUN: %target-swift-frontend -emit-module -o %t/rdar47334176_types.swiftmodule %S/Inputs/rdar47334176_types.swift
+// RUN: %target-swift-frontend -I %t -typecheck %s
+
+import rdar47334176_types
+
+// To test all possibilities let's declare one of the types
+// in the same module as function declaration which uses it.
+struct S<V> : R {}
+
+func foo<T : P, U>(_: T?, _: (T.V.V) -> Void) where T.V == E<U> {} // Ok
+func bar<T : P, U>(_: T?, _: (T.V.V) -> Void) where T.V == S<U> {} // Ok
+func baz<T : P, U>(_: T?, _: (T.V.V) -> Void) where T.V == C<U> {} // Ok
diff --git a/validation-test/stdlib/FixedPointDiagnostics.swift.gyb b/validation-test/stdlib/FixedPointDiagnostics.swift.gyb
index dfdaf7f..e0adcb7 100644
--- a/validation-test/stdlib/FixedPointDiagnostics.swift.gyb
+++ b/validation-test/stdlib/FixedPointDiagnostics.swift.gyb
@@ -25,59 +25,6 @@
 var u16 : UInt16 = u // expected-error {{}}
 var u8  : UInt8  = u // expected-error {{}}
 
-func expectSameType<T>(_: T.Type, _: T.Type) {}
-
-func test_truncatingBitPatternAPIIsStableAcrossPlatforms() {
-  // Audit and update this test when adding new integer types.
-  expectSameType(Int64.self, IntMax.self) // expected-error {{'IntMax' has been renamed to 'Int64'}}  
-  expectSameType(UInt64.self, UIntMax.self) // expected-error {{'UIntMax' has been renamed to 'UInt64'}}
-
-  _ = UInt8(truncatingBitPattern: UInt(0)) // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}}
-  _ = UInt16(truncatingBitPattern: UInt(0)) // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}}
-  _ = UInt32(truncatingBitPattern: UInt(0)) // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}}
-  UInt64(truncatingBitPattern: UInt(0)) // expected-error {{incorrect argument label in call (have 'truncatingBitPattern:', expected '_truncatingBits:')}}
-  UInt(truncatingBitPattern: UInt(0)) // expected-error {{cannot invoke initializer for type 'UInt' with an argument list of type '(truncatingBitPattern: UInt)'}} expected-note {{overloads for 'UInt' exist with these partially matching parameter lists: (truncatingBitPattern: UInt64), (truncatingBitPattern: Int64)}}
-
-  _ = Int8(truncatingBitPattern: UInt(0)) // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}}
-  _ = Int16(truncatingBitPattern: UInt(0)) // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}}
-  _ = Int32(truncatingBitPattern: UInt(0)) // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}}
-  Int64(truncatingBitPattern: UInt(0)) // expected-error {{incorrect argument label in call (have 'truncatingBitPattern:', expected '_truncatingBits:')}}
-  Int(truncatingBitPattern: UInt(0)) // expected-error {{}} expected-note * {{}}
-
-  _ = UInt8(truncatingBitPattern: Int(0)) // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}}
-  _ = UInt16(truncatingBitPattern: Int(0)) // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}}
-  _ = UInt32(truncatingBitPattern: Int(0)) // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}}
-  UInt64(truncatingBitPattern: Int(0)) // expected-error {{argument labels '(truncatingBitPattern:)' do not match any available overloads}}
-  // expected-note@-1 {{overloads for 'UInt64' exist with these partially matching parameter lists}}
-  UInt(truncatingBitPattern: Int(0))   // expected-error {{}} expected-note * {{}}
-
-  _ = Int8(truncatingBitPattern: Int(0)) // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}}
-  _ = Int16(truncatingBitPattern: Int(0)) // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}}
-  _ = Int32(truncatingBitPattern: Int(0)) // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}}
-  Int64(truncatingBitPattern: Int(0)) // expected-error {{}} expected-note * {{}}
-  Int(truncatingBitPattern: Int(0))   // expected-error {{}} expected-note * {{}}
-
-  UInt(truncatingBitPattern: UInt8(0))  // expected-error {{}} expected-note * {{}}
-  UInt(truncatingBitPattern: UInt16(0))  // expected-error {{}} expected-note * {{}}
-  UInt(truncatingBitPattern: UInt32(0))  // expected-error {{}} expected-note * {{}}
-  _ = UInt(truncatingBitPattern: UInt64(0)) // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}}
-
-  Int(truncatingBitPattern: UInt8(0))  // expected-error {{}} expected-note * {{}}
-  Int(truncatingBitPattern: UInt16(0)) // expected-error {{}} expected-note * {{}}
-  Int(truncatingBitPattern: UInt32(0)) // expected-error {{}} expected-note * {{}}
-  _ = Int(truncatingBitPattern: UInt64(0)) // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}}
-
-  UInt(truncatingBitPattern: Int8(0))  // expected-error {{}} expected-note * {{}}
-  UInt(truncatingBitPattern: Int16(0)) // expected-error {{}} expected-note * {{}}
-  UInt(truncatingBitPattern: Int32(0)) // expected-error {{}} expected-note * {{}}
-  _ = UInt(truncatingBitPattern: Int64(0)) // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}}
-
-  Int(truncatingBitPattern: Int8(0))  // expected-error {{}} expected-note * {{}}
-  Int(truncatingBitPattern: Int16(0)) // expected-error {{}} expected-note * {{}}
-  Int(truncatingBitPattern: Int32(0)) // expected-error {{}} expected-note * {{}}
-  _ = Int(truncatingBitPattern: Int64(0)) // expected-error {{'init(truncatingBitPattern:)' has been renamed to 'init(truncatingIfNeeded:)'}}
-}
-
 func testMixedSignArithmetic() {
   // Ensure that the generic arithmetic operators for Strideable don't
   // allow mixed-sign arithmetic to compile.  We create a deliberate
diff --git a/validation-test/stdlib/StringNormalization.swift b/validation-test/stdlib/StringNormalization.swift
index edaf495..0126a56 100644
--- a/validation-test/stdlib/StringNormalization.swift
+++ b/validation-test/stdlib/StringNormalization.swift
@@ -21,6 +21,7 @@
 // RUN: %target-run %t/a.out %S/Inputs/NormalizationTest.txt
 // REQUIRES: executable_test
 // REQUIRES: objc_interop
+// REQUIRES: optimized_stdlib
 
 import Swift
 import StdlibUnittest