Merge pull request #17594 from rintaro/4.2-ide-complete-rdar41227754

[4.2][CodeComplete] Typecheck SubscriptDecl context prior to completion
diff --git a/include/swift/ABI/MetadataValues.h b/include/swift/ABI/MetadataValues.h
index e92dd07..e970e58 100644
--- a/include/swift/ABI/MetadataValues.h
+++ b/include/swift/ABI/MetadataValues.h
@@ -1176,6 +1176,12 @@
     ///
     /// Meaningful for all type-descriptor kinds.
     IsReflectable = 2,
+    
+    /// Set if the type is a Clang-importer-synthesized related entity. After
+    /// the null terminator for the type name is another null-terminated string
+    /// containing the tag that discriminates the entity from other synthesized
+    /// declarations associated with the same declaration.
+    IsSynthesizedRelatedEntity = 3,
 
     /// Set if the context descriptor is includes metadata for dynamically
     /// constructing a class's vtables at metadata instantiation time.
@@ -1208,6 +1214,10 @@
   FLAGSET_DEFINE_FLAG_ACCESSORS(IsCTypedef, isCTypedef, setIsCTypedef)
   FLAGSET_DEFINE_FLAG_ACCESSORS(IsReflectable, isReflectable, setIsReflectable)
 
+  FLAGSET_DEFINE_FLAG_ACCESSORS(IsSynthesizedRelatedEntity,
+                                isSynthesizedRelatedEntity,
+                                setIsSynthesizedRelatedEntity)
+
   FLAGSET_DEFINE_FLAG_ACCESSORS(Class_HasVTable,
                                 class_hasVTable,
                                 class_setHasVTable)
diff --git a/include/swift/AST/DiagnosticsSema.def b/include/swift/AST/DiagnosticsSema.def
index 47addcd..e1b37d9 100644
--- a/include/swift/AST/DiagnosticsSema.def
+++ b/include/swift/AST/DiagnosticsSema.def
@@ -2702,12 +2702,19 @@
 // Partial application of foreign functions not supported
 ERROR(partial_application_of_function_invalid,none,
       "partial application of %select{"
-        "function with 'inout' parameters|"
         "'mutating' method|"
         "'super.init' initializer chain|"
         "'self.init' initializer delegation"
       "}0 is not allowed",
       (unsigned))
+WARNING(partial_application_of_function_invalid_swift4,none,
+      "partial application of %select{"
+        "'mutating' method|"
+        "'super.init' initializer chain|"
+        "'self.init' initializer delegation"
+      "}0 is not allowed; calling the function has undefined behavior and will "
+      "be an error in future Swift versions",
+      (unsigned))
 
 ERROR(self_assignment_var,none,
       "assigning a variable to itself", ())
diff --git a/include/swift/Demangling/DemangleNodes.def b/include/swift/Demangling/DemangleNodes.def
index 83670b5..27cb3be 100644
--- a/include/swift/Demangling/DemangleNodes.def
+++ b/include/swift/Demangling/DemangleNodes.def
@@ -36,7 +36,6 @@
 NODE(BoundGenericEnum)
 NODE(BoundGenericStructure)
 NODE(BoundGenericOtherNominalType)
-NODE(BoundGenericTypeAlias)
 NODE(BuiltinTypeName)
 NODE(CFunctionPointer)
 CONTEXT_NODE(Class)
diff --git a/include/swift/IDE/DigesterEnums.def b/include/swift/IDE/DigesterEnums.def
index bb0cfc9..ec3327d 100644
--- a/include/swift/IDE/DigesterEnums.def
+++ b/include/swift/IDE/DigesterEnums.def
@@ -172,6 +172,7 @@
 SPECIAL_CASE_ID(NSOpenGLGetVersion)
 SPECIAL_CASE_ID(ToIntMax)
 SPECIAL_CASE_ID(ToUIntMax)
+SPECIAL_CASE_ID(UIApplicationMain)
 
 #undef SPECIAL_CASE_ID
 #undef DIFF_ITEM_KEY_KIND_INT
diff --git a/include/swift/Remote/MetadataReader.h b/include/swift/Remote/MetadataReader.h
index 9d64ea2..55ecb4c 100644
--- a/include/swift/Remote/MetadataReader.h
+++ b/include/swift/Remote/MetadataReader.h
@@ -1136,12 +1136,13 @@
   Demangle::NodePointer
   buildNominalTypeMangling(ContextDescriptorRef descriptor,
                            Demangle::NodeFactory &nodeFactory) {
-    std::vector<std::pair<Demangle::Node::Kind, std::string>>
+    std::vector<std::pair<Demangle::Node::Kind, Demangle::NodePointer>>
       nameComponents;
     ContextDescriptorRef parent = descriptor;
     
     while (parent) {
       std::string nodeName;
+      std::string relatedTag;
       Demangle::Node::Kind nodeKind;
       
       auto getTypeName = [&]() -> bool {
@@ -1149,7 +1150,16 @@
           reinterpret_cast<const TargetTypeContextDescriptor<Runtime> *>
             (parent.getLocalBuffer());
         auto nameAddress = resolveRelativeField(parent, typeBuffer->Name);
-        return Reader->readString(RemoteAddress(nameAddress), nodeName);
+        if (!Reader->readString(RemoteAddress(nameAddress), nodeName))
+          return false;
+        
+        if (typeBuffer->isSynthesizedRelatedEntity()) {
+          nameAddress += nodeName.size() + 1;
+          if (!Reader->readString(RemoteAddress(nameAddress), relatedTag))
+            return false;
+        }
+        
+        return true;
       };
       
       bool isTypeContext = false;
@@ -1208,8 +1218,17 @@
         else if (typeFlags.isCTypedef())
           nodeKind = Demangle::Node::Kind::TypeAlias;
       }
+      
+      auto nameNode = nodeFactory.createNode(Node::Kind::Identifier,
+                                             nodeName);
+      if (!relatedTag.empty()) {
+        auto relatedNode =
+          nodeFactory.createNode(Node::Kind::RelatedEntityDeclName, relatedTag);
+        relatedNode->addChild(nameNode, nodeFactory);
+        nameNode = relatedNode;
+      }
 
-      nameComponents.emplace_back(nodeKind, nodeName);
+      nameComponents.emplace_back(nodeKind, nameNode);
       
       parent = readParentContextDescriptor(parent);
     }
@@ -1222,13 +1241,11 @@
     auto moduleInfo = std::move(nameComponents.back());
     nameComponents.pop_back();
     auto demangling =
-      nodeFactory.createNode(Node::Kind::Module, moduleInfo.second);
+      nodeFactory.createNode(Node::Kind::Module, moduleInfo.second->getText());
     for (auto &component : reversed(nameComponents)) {
-      auto name = nodeFactory.createNode(Node::Kind::Identifier,
-                                         component.second);
       auto parent = nodeFactory.createNode(component.first);
       parent->addChild(demangling, nodeFactory);
-      parent->addChild(name, nodeFactory);
+      parent->addChild(component.second, nodeFactory);
       demangling = parent;
     }
     
diff --git a/include/swift/Runtime/Metadata.h b/include/swift/Runtime/Metadata.h
index 9689c29..e473285 100644
--- a/include/swift/Runtime/Metadata.h
+++ b/include/swift/Runtime/Metadata.h
@@ -3511,6 +3511,21 @@
 
   llvm::ArrayRef<GenericParamDescriptor> getGenericParams() const;
 
+  bool isSynthesizedRelatedEntity() const {
+    return getTypeContextDescriptorFlags().isSynthesizedRelatedEntity();
+  }
+
+  /// Return the tag used to discriminate declarations synthesized by the
+  /// Clang importer and give them stable identities.
+  StringRef getSynthesizedDeclRelatedEntityTag() const {
+    if (!isSynthesizedRelatedEntity())
+      return {};
+    // The tag name comes after the null terminator for the name.
+    const char *nameBegin = Name.get();
+    auto *nameEnd = nameBegin + strlen(nameBegin) + 1;
+    return nameEnd;
+  }
+
   /// Return the offset of the start of generic arguments in the nominal
   /// type's metadata. The returned value is measured in sizeof(void*).
   int32_t getGenericArgumentOffset() const;
diff --git a/include/swift/SILOptimizer/Analysis/ARCAnalysis.h b/include/swift/SILOptimizer/Analysis/ARCAnalysis.h
index 31e508f..f98e4ba 100644
--- a/include/swift/SILOptimizer/Analysis/ARCAnalysis.h
+++ b/include/swift/SILOptimizer/Analysis/ARCAnalysis.h
@@ -13,16 +13,17 @@
 #ifndef SWIFT_SILOPTIMIZER_ANALYSIS_ARCANALYSIS_H
 #define SWIFT_SILOPTIMIZER_ANALYSIS_ARCANALYSIS_H
 
+#include "swift/Basic/LLVM.h"
 #include "swift/SIL/SILArgument.h"
-#include "swift/SIL/SILValue.h"
 #include "swift/SIL/SILBasicBlock.h"
+#include "swift/SIL/SILValue.h"
 #include "swift/SILOptimizer/Analysis/AliasAnalysis.h"
 #include "swift/SILOptimizer/Analysis/PostOrderAnalysis.h"
 #include "swift/SILOptimizer/Analysis/RCIdentityAnalysis.h"
 #include "llvm/ADT/BitVector.h"
-#include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/MapVector.h"
 #include "llvm/ADT/SetVector.h"
+#include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/TinyPtrVector.h"
 
 namespace swift {
@@ -147,7 +148,8 @@
 
   /// Return true if all the successors of the EpilogueRetainInsts do not have
   /// a retain. 
-  bool isTransitiveSuccessorsRetainFree(llvm::DenseSet<SILBasicBlock *> BBs);
+  bool
+  isTransitiveSuccessorsRetainFree(const llvm::DenseSet<SILBasicBlock *> &BBs);
 
   /// Finds matching releases in the provided block \p BB.
   RetainKindValue findMatchingRetainsInBasicBlock(SILBasicBlock *BB, SILValue V);
diff --git a/include/swift/Serialization/ModuleFormat.h b/include/swift/Serialization/ModuleFormat.h
index 88cebac..0aa9263 100644
--- a/include/swift/Serialization/ModuleFormat.h
+++ b/include/swift/Serialization/ModuleFormat.h
@@ -55,7 +55,7 @@
 /// describe what change you made. The content of this comment isn't important;
 /// it just ensures a conflict if two people change the module format.
 /// Don't worry about adhering to the 80-column limit for this line.
-const uint16_t VERSION_MINOR = 414; // Last change: track whether xrefs come from Clang
+const uint16_t VERSION_MINOR = 415; // Last change: {strong_retain,copy}_unowned
 
 using DeclIDField = BCFixed<31>;
 
diff --git a/lib/AST/ASTMangler.cpp b/lib/AST/ASTMangler.cpp
index cc88090..0e6cc67 100644
--- a/lib/AST/ASTMangler.cpp
+++ b/lib/AST/ASTMangler.cpp
@@ -739,31 +739,18 @@
       auto aliasTy = cast<NameAliasType>(tybase);
 
       // It's not possible to mangle the context of the builtin module.
-      // For the DWARF output we want to mangle the type alias + context,
-      // unless the type alias references a builtin type.
       TypeAliasDecl *decl = aliasTy->getDecl();
       if (decl->getModuleContext() == decl->getASTContext().TheBuiltinModule) {
         return appendType(aliasTy->getSinglyDesugaredType());
       }
 
-      if (type->isSpecialized()) {
-        // Try to mangle the entire name as a substitution.
-        if (tryMangleSubstitution(tybase))
-          return;
+      // FIXME: We also cannot yet mangle references to typealiases that
+      // involve generics.
+      if (decl->getGenericSignature())
+        return appendSugaredType<NameAliasType>(type);
 
-        appendAnyGenericType(decl);
-        bool isFirstArgList = true;
-        if (auto *nominalType = type->getAs<NominalType>()) {
-          if (nominalType->getParent())
-            type = nominalType->getParent();
-        }
-        appendBoundGenericArgs(type, isFirstArgList);
-        appendRetroactiveConformances(type);
-        appendOperator("G");
-        addSubstitution(type.getPointer());
-        return;
-      }
-
+      // For the DWARF output we want to mangle the type alias + context,
+      // unless the type alias references a builtin type.
       return appendAnyGenericType(decl);
     }
 
diff --git a/lib/AST/ProtocolConformance.cpp b/lib/AST/ProtocolConformance.cpp
index 0273d9d..465d676 100644
--- a/lib/AST/ProtocolConformance.cpp
+++ b/lib/AST/ProtocolConformance.cpp
@@ -134,12 +134,6 @@
                                              ProtocolConformanceRef conformance,
                                              Identifier name,
                                              LazyResolver *resolver) {
-  // For an archetype, retrieve the nested type with the appropriate
-  // name. There are no conformance tables.
-  if (auto archetype = type->getAs<ArchetypeType>()) {
-    return archetype->getNestedType(name);
-  }
-
   // Find the named requirement.
   AssociatedTypeDecl *assocType = nullptr;
   auto members = conformance.getRequirement()->lookupDirect(name);
@@ -153,8 +147,15 @@
   if (!assocType)
     return nullptr;
 
-  if (conformance.isAbstract())
+  if (conformance.isAbstract()) {
+    // For an archetype, retrieve the nested type with the appropriate
+    // name. There are no conformance tables.
+    if (auto archetype = type->getAs<ArchetypeType>()) {
+      return archetype->getNestedType(name);
+    }
+
     return DependentMemberType::get(type, assocType);
+  }
 
   auto concrete = conformance.getConcrete();
   if (!concrete->hasTypeWitness(assocType, resolver)) {
diff --git a/lib/ClangImporter/ImportDecl.cpp b/lib/ClangImporter/ImportDecl.cpp
index 73347e3..35635db 100644
--- a/lib/ClangImporter/ImportDecl.cpp
+++ b/lib/ClangImporter/ImportDecl.cpp
@@ -1188,6 +1188,7 @@
 
   auto call = CallExpr::createImplicit(context, zeroInitializerRef, {}, {});
   call->setType(selfType);
+  call->setThrows(false);
 
   auto assign = new (context) AssignExpr(lhs, SourceLoc(), call,
                                          /*implicit*/ true);
diff --git a/lib/Demangling/Demangler.cpp b/lib/Demangling/Demangler.cpp
index 7d21b60..9d2fa8d 100644
--- a/lib/Demangling/Demangler.cpp
+++ b/lib/Demangling/Demangler.cpp
@@ -1335,9 +1335,6 @@
     case Node::Kind::OtherNominalType:
       kind = Node::Kind::BoundGenericOtherNominalType;
       break;
-    case Node::Kind::TypeAlias:
-      kind = Node::Kind::BoundGenericTypeAlias;
-      break;
     default:
       return nullptr;
   }
diff --git a/lib/Demangling/NodePrinter.cpp b/lib/Demangling/NodePrinter.cpp
index 866318b..7703600 100644
--- a/lib/Demangling/NodePrinter.cpp
+++ b/lib/Demangling/NodePrinter.cpp
@@ -267,7 +267,6 @@
     case Node::Kind::BoundGenericEnum:
     case Node::Kind::BoundGenericStructure:
     case Node::Kind::BoundGenericOtherNominalType:
-    case Node::Kind::BoundGenericTypeAlias:
     case Node::Kind::BuiltinTypeName:
     case Node::Kind::Class:
     case Node::Kind::DependentGenericType:
@@ -1541,7 +1540,6 @@
   case Node::Kind::BoundGenericStructure:
   case Node::Kind::BoundGenericEnum:
   case Node::Kind::BoundGenericOtherNominalType:
-  case Node::Kind::BoundGenericTypeAlias:
     printBoundGeneric(Node);
     return nullptr;
   case Node::Kind::DynamicSelf:
diff --git a/lib/Demangling/OldRemangler.cpp b/lib/Demangling/OldRemangler.cpp
index 30cad13..4c8562a 100644
--- a/lib/Demangling/OldRemangler.cpp
+++ b/lib/Demangling/OldRemangler.cpp
@@ -1875,11 +1875,6 @@
   mangleAnyNominalType(node, ctx);
 }
 
-void Remangler::mangleBoundGenericTypeAlias(Node *node) {
-  EntityContext ctx;
-  mangleAnyNominalType(node, ctx);
-}
-
 void Remangler::mangleTypeList(Node *node) {
   mangleChildNodes(node); // all types
   Out << '_';
diff --git a/lib/Demangling/Remangler.cpp b/lib/Demangling/Remangler.cpp
index ee3807f..8219f88 100644
--- a/lib/Demangling/Remangler.cpp
+++ b/lib/Demangling/Remangler.cpp
@@ -463,7 +463,6 @@
     case Node::Kind::Enum: return mangleAnyGenericType(node, "O");
     case Node::Kind::Class: return mangleAnyGenericType(node, "C");
     case Node::Kind::OtherNominalType: return mangleAnyGenericType(node, "XY");
-    case Node::Kind::TypeAlias: return mangleAnyGenericType(node, "a");
     default:
       unreachable("bad nominal type kind");
   }
@@ -482,8 +481,7 @@
     case Node::Kind::BoundGenericOtherNominalType:
     case Node::Kind::BoundGenericStructure:
     case Node::Kind::BoundGenericEnum:
-    case Node::Kind::BoundGenericClass:
-    case Node::Kind::BoundGenericTypeAlias: {
+    case Node::Kind::BoundGenericClass: {
       NodePointer unboundType = node->getChild(0);
       assert(unboundType->getKind() == Node::Kind::Type);
       NodePointer nominalType = unboundType->getChild(0);
@@ -595,10 +593,6 @@
   mangleAnyNominalType(node);
 }
 
-void Remangler::mangleBoundGenericTypeAlias(Node *node) {
-  mangleAnyNominalType(node);
-}
-
 void Remangler::mangleBuiltinTypeName(Node *node) {
   Buffer << 'B';
   StringRef text = node->getText();
@@ -2037,7 +2031,6 @@
     case Node::Kind::BoundGenericEnum:
     case Node::Kind::BoundGenericClass:
     case Node::Kind::BoundGenericOtherNominalType:
-    case Node::Kind::BoundGenericTypeAlias:
       return true;
 
     case Node::Kind::Structure:
@@ -2073,8 +2066,7 @@
     case Node::Kind::BoundGenericStructure:
     case Node::Kind::BoundGenericEnum:
     case Node::Kind::BoundGenericClass:
-    case Node::Kind::BoundGenericOtherNominalType:
-    case Node::Kind::BoundGenericTypeAlias: {
+    case Node::Kind::BoundGenericOtherNominalType: {
       NodePointer unboundType = node->getChild(0);
       assert(unboundType->getKind() == Node::Kind::Type);
       NodePointer nominalType = unboundType->getChild(0);
diff --git a/lib/IRGen/GenDecl.cpp b/lib/IRGen/GenDecl.cpp
index 975276f..1b9b982 100644
--- a/lib/IRGen/GenDecl.cpp
+++ b/lib/IRGen/GenDecl.cpp
@@ -4115,6 +4115,9 @@
 // layout. Calling isResilient() with this scope will always return false.
 ResilienceExpansion
 IRGenModule::getResilienceExpansionForLayout(NominalTypeDecl *decl) {
+  if (Types.isCompletelyFragile())
+    return ResilienceExpansion::Minimal;
+
   if (isResilient(decl, ResilienceExpansion::Minimal))
     return ResilienceExpansion::Maximal;
 
diff --git a/lib/IRGen/GenMeta.cpp b/lib/IRGen/GenMeta.cpp
index f247427..485a93a 100644
--- a/lib/IRGen/GenMeta.cpp
+++ b/lib/IRGen/GenMeta.cpp
@@ -481,11 +481,21 @@
     }
     
     void addName() {
+      SmallString<32> nameBuf;
       StringRef name;
-      
+
+      // Use the original name with tag for synthesized decls. The tag comes
+      // after the null terminator for the name.
+      if (auto *synthesizedTypeAttr =
+            Type->getAttrs().getAttribute<ClangImporterSynthesizedTypeAttr>()) {
+        nameBuf.append(synthesizedTypeAttr->originalTypeName);
+        nameBuf.push_back('\0');
+        nameBuf.append(synthesizedTypeAttr->getManglingName());
+        
+        name = nameBuf;
       // Try to use the Clang name if there is one.
-      if (auto namedClangDecl =
-                             Mangle::ASTMangler::getClangDeclForMangling(Type)) {
+      } else if (auto namedClangDecl =
+                            Mangle::ASTMangler::getClangDeclForMangling(Type)) {
         name = namedClangDecl->getName();
       } else {
         name = Type->getName().str();
@@ -565,22 +575,18 @@
     /// Flags to indicate Clang-imported declarations so we mangle them
     /// consistently at runtime.
     void getClangImportedFlags(TypeContextDescriptorFlags &flags) const {
-      auto clangDecl = Mangle::ASTMangler::getClangDeclForMangling(Type);
-      if (!clangDecl)
-        return;
-      
-      if (isa<clang::TagDecl>(clangDecl)) {
-        flags.setIsCTag(true);
-        return;
+      if (Type->getAttrs().getAttribute<ClangImporterSynthesizedTypeAttr>()) {
+        flags.setIsSynthesizedRelatedEntity(true);
       }
       
-      if (isa<clang::TypedefNameDecl>(clangDecl)
-          || isa<clang::ObjCCompatibleAliasDecl>(clangDecl)) {
-        flags.setIsCTypedef(true);
-        return;
+      if (auto clangDecl = Mangle::ASTMangler::getClangDeclForMangling(Type)) {
+        if (isa<clang::TagDecl>(clangDecl)) {
+          flags.setIsCTag(true);
+        } else if (isa<clang::TypedefNameDecl>(clangDecl)
+                   || isa<clang::ObjCCompatibleAliasDecl>(clangDecl)) {
+          flags.setIsCTypedef(true);
+        }
       }
-      
-      return;
     }
 
     // Subclasses should provide:
diff --git a/lib/IRGen/IRGenSIL.cpp b/lib/IRGen/IRGenSIL.cpp
index 3e3edf2..fefd65a 100644
--- a/lib/IRGen/IRGenSIL.cpp
+++ b/lib/IRGen/IRGenSIL.cpp
@@ -963,9 +963,7 @@
   void visitRetainValueInst(RetainValueInst *i);
   void visitRetainValueAddrInst(RetainValueAddrInst *i);
   void visitCopyValueInst(CopyValueInst *i);
-  void visitCopyUnownedValueInst(CopyUnownedValueInst *i) {
-    llvm_unreachable("unimplemented");
-  }
+  void visitCopyUnownedValueInst(CopyUnownedValueInst *i);
   void visitReleaseValueInst(ReleaseValueInst *i);
   void visitReleaseValueAddrInst(ReleaseValueAddrInst *i);
   void visitDestroyValueInst(DestroyValueInst *i);
@@ -3844,6 +3842,18 @@
                                                        : irgen::Atomicity::NonAtomic);
 }
 
+void IRGenSILFunction::visitCopyUnownedValueInst(
+    swift::CopyUnownedValueInst *i) {
+  Explosion in = getLoweredExplosion(i->getOperand());
+  auto &ti = getReferentTypeInfo(*this, i->getOperand()->getType());
+  ti.strongRetainUnowned(*this, in, irgen::Atomicity::Atomic);
+  // Semantically we are just passing through the input parameter but as a
+  // strong reference... at LLVM IR level these type differences don't
+  // matter. So just set the lowered explosion appropriately.
+  Explosion output = getLoweredExplosion(i->getOperand());
+  setLoweredExplosion(i, output);
+}
+
 void IRGenSILFunction::visitUnownedRetainInst(swift::UnownedRetainInst *i) {
   Explosion lowered = getLoweredExplosion(i->getOperand());
   auto &ti = getReferentTypeInfo(*this, i->getOperand()->getType());
diff --git a/lib/Migrator/APIDiffMigratorPass.cpp b/lib/Migrator/APIDiffMigratorPass.cpp
index 39dbb03..c507d36 100644
--- a/lib/Migrator/APIDiffMigratorPass.cpp
+++ b/lib/Migrator/APIDiffMigratorPass.cpp
@@ -675,6 +675,23 @@
       }
       return false;
     }
+    case SpecialCaseId::UIApplicationMain: {
+      // If the first argument is CommandLine.argc, replace the second argument
+      // with CommandLine.unsafeArgv
+      CallArgInfo &FirstArg = AllArgs[0];
+      // handle whitespace/line splits around the first arg when matching
+      auto FirstArgSplit =
+        SM.extractText(FirstArg.getEntireCharRange(SM)).rsplit('.');
+      if (!FirstArgSplit.second.empty() &&
+          FirstArgSplit.first.trim() == "CommandLine" &&
+          FirstArgSplit.second.trim() == "argc") {
+        CallArgInfo &SecondArg = AllArgs[1];
+        Editor.replace(SecondArg.getEntireCharRange(SM),
+                       "CommandLine.unsafeArgv");
+        return true;
+      }
+      return false;
+    }
     }
   }
 
diff --git a/lib/Migrator/overlay3.json b/lib/Migrator/overlay3.json
index 19c5d66..d0820c4 100644
--- a/lib/Migrator/overlay3.json
+++ b/lib/Migrator/overlay3.json
@@ -1316,4 +1316,9 @@
     "RightComment": "compactMap",
     "ModuleName": "Swift"
   },
+  {
+    "DiffItemKind": "SpecialCaseDiffItem",
+    "Usr": "c:@F@UIApplicationMain",
+    "SpecialCaseId": "UIApplicationMain"
+  }
 ]
diff --git a/lib/Migrator/overlay4.json b/lib/Migrator/overlay4.json
index 19c5d66..d0820c4 100644
--- a/lib/Migrator/overlay4.json
+++ b/lib/Migrator/overlay4.json
@@ -1316,4 +1316,9 @@
     "RightComment": "compactMap",
     "ModuleName": "Swift"
   },
+  {
+    "DiffItemKind": "SpecialCaseDiffItem",
+    "Usr": "c:@F@UIApplicationMain",
+    "SpecialCaseId": "UIApplicationMain"
+  }
 ]
diff --git a/lib/RemoteAST/RemoteAST.cpp b/lib/RemoteAST/RemoteAST.cpp
index cdeda25..29c67fc 100644
--- a/lib/RemoteAST/RemoteAST.cpp
+++ b/lib/RemoteAST/RemoteAST.cpp
@@ -753,7 +753,17 @@
       if (HadError) return;
       if (decl == Result) return;
       if (!Result) {
-        Result = cast<NominalTypeDecl>(decl);
+        // A synthesized type from the Clang importer may resolve to a
+        // compatibility alias.
+        if (auto resultAlias = dyn_cast<TypeAliasDecl>(decl)) {
+          if (resultAlias->isCompatibilityAlias()) {
+            Result = resultAlias->getUnderlyingTypeLoc().getType()
+                                ->getAnyNominal();
+          }
+        } else {
+          Result = dyn_cast<NominalTypeDecl>(decl);
+        }
+        HadError |= !Result;
       } else {
         HadError = true;
         Result = nullptr;
diff --git a/lib/SIL/Projection.cpp b/lib/SIL/Projection.cpp
index e6c774a..a29f259 100644
--- a/lib/SIL/Projection.cpp
+++ b/lib/SIL/Projection.cpp
@@ -840,6 +840,24 @@
   return Proj->createProjection(B, Loc, Arg);
 }
 
+// Projection tree only supports structs and tuples today.
+static bool isSupportedProjection(const Projection &p) {
+  switch (p.getKind()) {
+  case ProjectionKind::Struct:
+  case ProjectionKind::Tuple:
+    return true;
+  case ProjectionKind::Class:
+  case ProjectionKind::Enum:
+  case ProjectionKind::Box:
+  case ProjectionKind::Upcast:
+  case ProjectionKind::RefCast:
+  case ProjectionKind::BitwiseCast:
+  case ProjectionKind::TailElems:
+  case ProjectionKind::Index:
+    return false;
+  }
+}
+
 void
 ProjectionTreeNode::
 processUsersOfValue(ProjectionTree &Tree,
@@ -863,12 +881,11 @@
       continue;
     }
 
-    // Check whether the user is such a projection.
     auto P = Projection(projectionInst);
 
-    // If we fail to create a projection, add User as a user to this node and
-    // continue.
-    if (!P.isValid()) {
+    // If we fail to create a projection or this is a type of projection that we
+    // do not support, add User as a user to this node and continue.
+    if (!P.isValid() || !isSupportedProjection(P)) {
       DEBUG(llvm::dbgs() << "            Failed to create projection. Adding "
             "to non projection user!\n");
       addNonProjectionUser(Op);
diff --git a/lib/SIL/SILBuilder.cpp b/lib/SIL/SILBuilder.cpp
index 475abd9..afa56f1 100644
--- a/lib/SIL/SILBuilder.cpp
+++ b/lib/SIL/SILBuilder.cpp
@@ -264,7 +264,8 @@
       isa<RetainValueInst>(Inst) || isa<UnownedRetainInst>(Inst) ||
       isa<UnownedReleaseInst>(Inst) || isa<StrongRetainUnownedInst>(Inst) ||
       isa<StoreWeakInst>(Inst) || isa<StrongRetainInst>(Inst) ||
-      isa<AllocStackInst>(Inst) || isa<DeallocStackInst>(Inst))
+      isa<AllocStackInst>(Inst) || isa<DeallocStackInst>(Inst) ||
+      isa<CopyUnownedValueInst>(Inst))
     return false;
 
   // Assign and copyaddr of trivial types cannot drop refcounts, and 'inits'
diff --git a/lib/SIL/SILGlobalVariable.cpp b/lib/SIL/SILGlobalVariable.cpp
index a7eb1ff..a7e8a83 100644
--- a/lib/SIL/SILGlobalVariable.cpp
+++ b/lib/SIL/SILGlobalVariable.cpp
@@ -92,6 +92,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/41433840
+          if (M.getASTContext().LangOpts.Target.isMacOSX())
+            return false;
+  
           if (isa<IntegerLiteralInst>(bi->getArguments()[1]))
             return true;
           break;
diff --git a/lib/SIL/SILVerifier.cpp b/lib/SIL/SILVerifier.cpp
index 2bf1250..028a933 100644
--- a/lib/SIL/SILVerifier.cpp
+++ b/lib/SIL/SILVerifier.cpp
@@ -1866,9 +1866,8 @@
                                          "Operand of unowned_retain");
     require(unownedType->isLoadable(ResilienceExpansion::Maximal),
             "unowned_retain requires unowned type to be loadable");
-    require(F.hasQualifiedOwnership(),
-            "copy_unowned_value is only valid in functions with qualified "
-            "ownership");
+    // *NOTE* We allow copy_unowned_value to be used throughout the entire
+    // pipeline even though it is a higher level instruction.
   }
 
   void checkDestroyValueInst(DestroyValueInst *I) {
diff --git a/lib/SILOptimizer/Analysis/ARCAnalysis.cpp b/lib/SILOptimizer/Analysis/ARCAnalysis.cpp
index c9a3ea2..93e0553 100644
--- a/lib/SILOptimizer/Analysis/ARCAnalysis.cpp
+++ b/lib/SILOptimizer/Analysis/ARCAnalysis.cpp
@@ -498,22 +498,24 @@
   findMatchingRetains(&*BB);
 }
 
-bool
-ConsumedResultToEpilogueRetainMatcher::
-isTransitiveSuccessorsRetainFree(llvm::DenseSet<SILBasicBlock *> BBs) {
+bool ConsumedResultToEpilogueRetainMatcher::isTransitiveSuccessorsRetainFree(
+    const llvm::DenseSet<SILBasicBlock *> &BBs) {
   // For every block with retain, we need to check the transitive
   // closure of its successors are retain-free.
   for (auto &I : EpilogueRetainInsts) {
-    auto *CBB = I->getParent();
-    for (auto &Succ : CBB->getSuccessors()) {
-      if (BBs.find(Succ) != BBs.end())
+    for (auto &Succ : I->getParent()->getSuccessors()) {
+      if (BBs.count(Succ))
         continue;
       return false;
     }
   }
+
+  // FIXME: We are iterating over a DenseSet. That can lead to non-determinism
+  // and is in general pretty inefficient since we are iterating over a hash
+  // table.
   for (auto CBB : BBs) {
     for (auto &Succ : CBB->getSuccessors()) {
-      if (BBs.find(Succ) != BBs.end())
+      if (BBs.count(Succ))
         continue;
       return false;
     }
diff --git a/lib/SILOptimizer/Analysis/EscapeAnalysis.cpp b/lib/SILOptimizer/Analysis/EscapeAnalysis.cpp
index 3370496..f647b02 100644
--- a/lib/SILOptimizer/Analysis/EscapeAnalysis.cpp
+++ b/lib/SILOptimizer/Analysis/EscapeAnalysis.cpp
@@ -1372,6 +1372,7 @@
     case SILInstructionKind::DeallocStackInst:
     case SILInstructionKind::StrongRetainInst:
     case SILInstructionKind::StrongRetainUnownedInst:
+    case SILInstructionKind::CopyUnownedValueInst:
     case SILInstructionKind::RetainValueInst:
     case SILInstructionKind::UnownedRetainInst:
     case SILInstructionKind::BranchInst:
diff --git a/lib/SILOptimizer/Analysis/MemoryBehavior.cpp b/lib/SILOptimizer/Analysis/MemoryBehavior.cpp
index 0b255a6..a0cf8ce 100644
--- a/lib/SILOptimizer/Analysis/MemoryBehavior.cpp
+++ b/lib/SILOptimizer/Analysis/MemoryBehavior.cpp
@@ -152,6 +152,7 @@
   }
   REFCOUNTINC_MEMBEHAVIOR_INST(StrongRetainInst)
   REFCOUNTINC_MEMBEHAVIOR_INST(StrongRetainUnownedInst)
+  REFCOUNTINC_MEMBEHAVIOR_INST(CopyUnownedValueInst)
   REFCOUNTINC_MEMBEHAVIOR_INST(UnownedRetainInst)
   REFCOUNTINC_MEMBEHAVIOR_INST(RetainValueInst)
 #undef REFCOUNTINC_MEMBEHAVIOR_INST
diff --git a/lib/SILOptimizer/Analysis/SideEffectAnalysis.cpp b/lib/SILOptimizer/Analysis/SideEffectAnalysis.cpp
index 26e83a0..d7f750e 100644
--- a/lib/SILOptimizer/Analysis/SideEffectAnalysis.cpp
+++ b/lib/SILOptimizer/Analysis/SideEffectAnalysis.cpp
@@ -481,6 +481,7 @@
     return;
   case SILInstructionKind::StrongRetainInst:
   case SILInstructionKind::StrongRetainUnownedInst:
+  case SILInstructionKind::CopyUnownedValueInst:
   case SILInstructionKind::RetainValueInst:
   case SILInstructionKind::UnownedRetainInst:
     getEffectsOn(I->getOperand(0))->Retains = true;
diff --git a/lib/SILOptimizer/Mandatory/GuaranteedARCOpts.cpp b/lib/SILOptimizer/Mandatory/GuaranteedARCOpts.cpp
index 1381cd1..2691259 100644
--- a/lib/SILOptimizer/Mandatory/GuaranteedARCOpts.cpp
+++ b/lib/SILOptimizer/Mandatory/GuaranteedARCOpts.cpp
@@ -75,6 +75,7 @@
   if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst) ||
       isa<RetainValueInst>(Inst) || isa<UnownedRetainInst>(Inst) ||
       isa<UnownedReleaseInst>(Inst) || isa<StrongRetainUnownedInst>(Inst) ||
+      isa<CopyUnownedValueInst>(Inst) ||
       isa<StoreWeakInst>(Inst) || isa<StrongRetainInst>(Inst) ||
       isa<AllocStackInst>(Inst) || isa<DeallocStackInst>(Inst) ||
       isa<BeginAccessInst>(Inst) || isa<EndAccessInst>(Inst) ||
diff --git a/lib/SILOptimizer/Mandatory/PMOMemoryUseCollector.cpp b/lib/SILOptimizer/Mandatory/PMOMemoryUseCollector.cpp
index de4bc11..3fec285 100644
--- a/lib/SILOptimizer/Mandatory/PMOMemoryUseCollector.cpp
+++ b/lib/SILOptimizer/Mandatory/PMOMemoryUseCollector.cpp
@@ -231,10 +231,6 @@
   /// element we attribute an access to.
   bool InStructSubElement = false;
 
-  /// When walking the use list, if we index into an enum slice, keep track
-  /// of this.
-  bool InEnumSubElement = false;
-
 public:
   ElementUseCollector(const PMOMemoryObjectInfo &TheMemory,
                       SmallVectorImpl<PMOMemoryUse> &Uses,
@@ -294,7 +290,7 @@
   // If we're in a subelement of a struct or enum, just mark the struct, not
   // things that come after it in a parent tuple.
   unsigned NumElements = 1;
-  if (TheMemory.NumElements != 1 && !InStructSubElement && !InEnumSubElement)
+  if (TheMemory.NumElements != 1 && !InStructSubElement)
     NumElements = getElementCountRec(Module, UseTy);
 
   Uses.push_back(PMOMemoryUse(User, Kind, BaseEltNo, NumElements));
@@ -309,7 +305,7 @@
   // If we're walking into a tuple within a struct or enum, don't adjust the
   // BaseElt.  The uses hanging off the tuple_element_addr are going to be
   // counted as uses of the struct or enum itself.
-  if (InStructSubElement || InEnumSubElement)
+  if (InStructSubElement)
     return collectUses(TEAI, BaseEltNo);
 
   // tuple_element_addr P, 42 indexes into the current tuple element.
@@ -554,26 +550,6 @@
       llvm_unreachable("bad parameter convention");
     }
 
-    // init_enum_data_addr is treated like a tuple_element_addr or other
-    // instruction that is looking into the memory object (i.e., the memory
-    // object needs to be explicitly initialized by a copy_addr or some other
-    // use of the projected address).
-    if (auto I = dyn_cast<InitEnumDataAddrInst>(User)) {
-      // If we are in a struct already, bail. With proper analysis, we should be
-      // able to do this optimization.
-      if (InStructSubElement) {
-        return false;
-      }
-
-      // Keep track of the fact that we're inside of an enum.  This informs our
-      // recursion that tuple stores are not scalarized outside, and that stores
-      // should not be treated as partial stores.
-      llvm::SaveAndRestore<bool> X(InEnumSubElement, true);
-      if (!collectUses(I, BaseEltNo))
-        return false;
-      continue;
-    }
-
     // init_existential_addr is modeled as an initialization store.
     if (isa<InitExistentialAddrInst>(User)) {
       // init_existential_addr should not apply to struct subelements.
@@ -585,17 +561,6 @@
       continue;
     }
 
-    // inject_enum_addr is modeled as an initialization store.
-    if (isa<InjectEnumAddrInst>(User)) {
-      // inject_enum_addr the subelement of a struct unless in a ctor.
-      if (InStructSubElement) {
-        return false;
-      }
-      Uses.push_back(
-          PMOMemoryUse(User, PMOUseKind::Initialization, BaseEltNo, 1));
-      continue;
-    }
-
     // open_existential_addr is a use of the protocol value,
     // so it is modeled as a load.
     if (isa<OpenExistentialAddrInst>(User)) {
diff --git a/lib/SILOptimizer/Transforms/DeadStoreElimination.cpp b/lib/SILOptimizer/Transforms/DeadStoreElimination.cpp
index c59d7bf..f222139 100644
--- a/lib/SILOptimizer/Transforms/DeadStoreElimination.cpp
+++ b/lib/SILOptimizer/Transforms/DeadStoreElimination.cpp
@@ -149,6 +149,7 @@
   switch (Inst->getKind()) {
   case SILInstructionKind::StrongRetainInst:
   case SILInstructionKind::StrongRetainUnownedInst:
+  case SILInstructionKind::CopyUnownedValueInst:
   case SILInstructionKind::UnownedRetainInst:
   case SILInstructionKind::RetainValueInst:
   case SILInstructionKind::DeallocStackInst:
diff --git a/lib/SILOptimizer/Transforms/OwnershipModelEliminator.cpp b/lib/SILOptimizer/Transforms/OwnershipModelEliminator.cpp
index c330ee3..a83d85f 100644
--- a/lib/SILOptimizer/Transforms/OwnershipModelEliminator.cpp
+++ b/lib/SILOptimizer/Transforms/OwnershipModelEliminator.cpp
@@ -57,7 +57,6 @@
   bool visitStoreInst(StoreInst *SI);
   bool visitStoreBorrowInst(StoreBorrowInst *SI);
   bool visitCopyValueInst(CopyValueInst *CVI);
-  bool visitCopyUnownedValueInst(CopyUnownedValueInst *CVI);
   bool visitDestroyValueInst(DestroyValueInst *DVI);
   bool visitLoadBorrowInst(LoadBorrowInst *LBI);
   bool visitBeginBorrowInst(BeginBorrowInst *BBI) {
@@ -160,19 +159,6 @@
   return true;
 }
 
-bool OwnershipModelEliminatorVisitor::visitCopyUnownedValueInst(
-    CopyUnownedValueInst *CVI) {
-  B.createStrongRetainUnowned(CVI->getLoc(), CVI->getOperand(),
-                              B.getDefaultAtomicity());
-  // Users of copy_value_unowned expect an owned value. So we need to convert
-  // our unowned value to a ref.
-  auto *UTRI =
-      B.createUnownedToRef(CVI->getLoc(), CVI->getOperand(), CVI->getType());
-  CVI->replaceAllUsesWith(UTRI);
-  CVI->eraseFromParent();
-  return true;
-}
-
 bool OwnershipModelEliminatorVisitor::visitUnmanagedRetainValueInst(
     UnmanagedRetainValueInst *URVI) {
   // Now that we have set the unqualified ownership flag, destroy value
diff --git a/lib/SILOptimizer/Transforms/RedundantLoadElimination.cpp b/lib/SILOptimizer/Transforms/RedundantLoadElimination.cpp
index 8707aee..d1fa5b5 100644
--- a/lib/SILOptimizer/Transforms/RedundantLoadElimination.cpp
+++ b/lib/SILOptimizer/Transforms/RedundantLoadElimination.cpp
@@ -156,6 +156,7 @@
   case SILInstructionKind::IsUniqueInst:
   case SILInstructionKind::IsUniqueOrPinnedInst:
   case SILInstructionKind::FixLifetimeInst:
+  case SILInstructionKind::CopyUnownedValueInst:
     return true;
   default:
     return false;
diff --git a/lib/Sema/MiscDiagnostics.cpp b/lib/Sema/MiscDiagnostics.cpp
index 5a6af26..a5cb986 100644
--- a/lib/Sema/MiscDiagnostics.cpp
+++ b/lib/Sema/MiscDiagnostics.cpp
@@ -86,14 +86,18 @@
     // Selector for the partial_application_of_function_invalid diagnostic
     // message.
     struct PartialApplication {
-      unsigned level : 29;
       enum : unsigned {
-        Function,
         MutatingMethod,
         SuperInit,
         SelfInit,
       };
-      unsigned kind : 3;
+      enum : unsigned {
+        Error,
+        CompatibilityWarning,
+      };
+      unsigned compatibilityWarning: 1;
+      unsigned kind : 2;
+      unsigned level : 29;
     };
 
     // Partial applications of functions that are not permitted.  This is
@@ -104,49 +108,18 @@
     ~DiagnoseWalker() override {
       for (auto &unapplied : InvalidPartialApplications) {
         unsigned kind = unapplied.second.kind;
-        TC.diagnose(unapplied.first->getLoc(),
-                    diag::partial_application_of_function_invalid,
-                    kind);
+        if (unapplied.second.compatibilityWarning) {
+          TC.diagnose(unapplied.first->getLoc(),
+                      diag::partial_application_of_function_invalid_swift4,
+                      kind);
+        } else {
+          TC.diagnose(unapplied.first->getLoc(),
+                      diag::partial_application_of_function_invalid,
+                      kind);
+        }
       }
     }
 
-    /// If this is an application of a function that cannot be partially
-    /// applied, arrange for us to check that it gets fully applied.
-    void recordUnsupportedPartialApply(ApplyExpr *expr, Expr *fnExpr) {
-
-      if (isa<OtherConstructorDeclRefExpr>(fnExpr)) {
-        auto kind = expr->getArg()->isSuperExpr()
-                  ? PartialApplication::SuperInit
-                  : PartialApplication::SelfInit;
-
-        // Partial applications of delegated initializers aren't allowed, and
-        // don't really make sense to begin with.
-        InvalidPartialApplications.insert({ expr, {1, kind} });
-        return;
-      }
-
-      auto fnDeclRef = dyn_cast<DeclRefExpr>(fnExpr);
-      if (!fnDeclRef)
-        return;
-
-      auto fn = dyn_cast<FuncDecl>(fnDeclRef->getDecl());
-      if (!fn)
-        return;
-
-      unsigned kind =
-        fn->isInstanceMember() ? PartialApplication::MutatingMethod
-                               : PartialApplication::Function;
-      
-      // Functions with inout parameters cannot be partially applied.
-      if (!expr->getArg()->getType()->isMaterializable()) {
-        // We need to apply all argument clauses.
-        InvalidPartialApplications.insert({
-          fnExpr, {fn->getNumParameterLists(), kind}
-        });
-      }
-    }
-
-    /// This method is called in post-order over the AST to validate that
     /// methods are fully applied when they can't support partial application.
     void checkInvalidPartialApplication(Expr *E) {
       if (auto AE = dyn_cast<ApplyExpr>(E)) {
@@ -157,8 +130,18 @@
           fnExpr = dotSyntaxExpr->getRHS();
 
         // Check to see if this is a potentially unsupported partial
-        // application.
-        recordUnsupportedPartialApply(AE, fnExpr);
+        // application of a constructor delegation.
+        if (isa<OtherConstructorDeclRefExpr>(fnExpr)) {
+          auto kind = AE->getArg()->isSuperExpr()
+                    ? PartialApplication::SuperInit
+                    : PartialApplication::SelfInit;
+
+          // Partial applications of delegated initializers aren't allowed, and
+          // don't really make sense to begin with.
+          InvalidPartialApplications.insert(
+            {E, {PartialApplication::Error, kind, 1}});
+          return;
+        }
 
         // If this is adding a level to an active partial application, advance
         // it to the next level.
@@ -172,11 +155,36 @@
         InvalidPartialApplications.erase(foundApplication);
         if (level > 1) {
           // We have remaining argument clauses.
-          InvalidPartialApplications.insert({ AE, {level - 1, kind} });
+          // Partial applications were always diagnosed in Swift 4 and before,
+          // so there's no need to preserve the compatibility warning bit.
+          InvalidPartialApplications.insert(
+            {AE, {PartialApplication::Error, kind, level - 1}});
         }
         return;
       }
+      
+      /// If this is a reference to a mutating method, it cannot be partially
+      /// applied or even referenced without full application, so arrange for
+      /// us to check that it gets fully applied.
+      auto fnDeclRef = dyn_cast<DeclRefExpr>(E);
+      if (!fnDeclRef)
+        return;
 
+      auto fn = dyn_cast<FuncDecl>(fnDeclRef->getDecl());
+      if (!fn || !fn->isInstanceMember() || !fn->isMutating())
+        return;
+
+      // Swift 4 and earlier failed to diagnose a reference to a mutating method
+      // without any applications at all, which would get miscompiled into a
+      // function with undefined behavior. Warn for source compatibility.
+      auto errorBehavior = TC.Context.LangOpts.isSwiftVersionAtLeast(5)
+        ? PartialApplication::Error
+        : PartialApplication::CompatibilityWarning;
+
+      InvalidPartialApplications.insert(
+        {fnDeclRef, {errorBehavior,
+                     PartialApplication::MutatingMethod,
+                     fn->getNumParameterLists()}});
     }
 
     // Not interested in going outside a basic expression.
diff --git a/lib/Sema/TypeCheckError.cpp b/lib/Sema/TypeCheckError.cpp
index 43ef5b5..fbd7e42 100644
--- a/lib/Sema/TypeCheckError.cpp
+++ b/lib/Sema/TypeCheckError.cpp
@@ -134,6 +134,9 @@
         fn = conversion->getSubExpr()->getValueProvidingExpr();
       } else if (auto conversion = dyn_cast<BindOptionalExpr>(fn)) {
         fn = conversion->getSubExpr()->getValueProvidingExpr();
+      // Look through optional injections
+      } else if (auto injection = dyn_cast<InjectIntoOptionalExpr>(fn)) {
+        fn = injection->getSubExpr()->getValueProvidingExpr();
       // Look through function conversions.
       } else if (auto conversion = dyn_cast<FunctionConversionExpr>(fn)) {
         fn = conversion->getSubExpr()->getValueProvidingExpr();
diff --git a/lib/Serialization/Deserialization.cpp b/lib/Serialization/Deserialization.cpp
index decc345..c877936 100644
--- a/lib/Serialization/Deserialization.cpp
+++ b/lib/Serialization/Deserialization.cpp
@@ -129,17 +129,6 @@
 const char ExtensionError::ID = '\0';
 void ExtensionError::anchor() {}
 
-LLVM_NODISCARD
-static std::unique_ptr<llvm::ErrorInfoBase> takeErrorInfo(llvm::Error error) {
-  std::unique_ptr<llvm::ErrorInfoBase> result;
-  llvm::handleAllErrors(std::move(error),
-                        [&](std::unique_ptr<llvm::ErrorInfoBase> info) {
-    result = std::move(info);
-  });
-  return result;
-}
-
-
 /// Skips a single record in the bitstream.
 ///
 /// Returns true if the next entry is a record of type \p recordKind.
@@ -4816,27 +4805,42 @@
     }
 
     auto processParameter = [&](TypeID typeID, uint64_t rawConvention)
-                                  -> Optional<SILParameterInfo> {
+                                  -> llvm::Expected<SILParameterInfo> {
       auto convention = getActualParameterConvention(rawConvention);
-      auto type = getType(typeID);
-      if (!convention || !type) return None;
-      return SILParameterInfo(type->getCanonicalType(), *convention);
+      if (!convention) {
+        error();
+        llvm_unreachable("an error is a fatal exit at this point");
+      }
+      auto type = getTypeChecked(typeID);
+      if (!type)
+        return type.takeError();
+      return SILParameterInfo(type.get()->getCanonicalType(), *convention);
     };
 
     auto processYield = [&](TypeID typeID, uint64_t rawConvention)
-                                  -> Optional<SILYieldInfo> {
+                                  -> llvm::Expected<SILYieldInfo> {
       auto convention = getActualParameterConvention(rawConvention);
-      auto type = getType(typeID);
-      if (!convention || !type) return None;
-      return SILYieldInfo(type->getCanonicalType(), *convention);
+      if (!convention) {
+        error();
+        llvm_unreachable("an error is a fatal exit at this point");
+      }
+      auto type = getTypeChecked(typeID);
+      if (!type)
+        return type.takeError();
+      return SILYieldInfo(type.get()->getCanonicalType(), *convention);
     };
 
     auto processResult = [&](TypeID typeID, uint64_t rawConvention)
-                               -> Optional<SILResultInfo> {
+                               -> llvm::Expected<SILResultInfo> {
       auto convention = getActualResultConvention(rawConvention);
-      auto type = getType(typeID);
-      if (!convention || !type) return None;
-      return SILResultInfo(type->getCanonicalType(), *convention);
+      if (!convention) {
+        error();
+        llvm_unreachable("an error is a fatal exit at this point");
+      }
+      auto type = getTypeChecked(typeID);
+      if (!type)
+        return type.takeError();
+      return SILResultInfo(type.get()->getCanonicalType(), *convention);
     };
 
     // Bounds check.  FIXME: overflow
@@ -4855,11 +4859,9 @@
       auto typeID = variableData[nextVariableDataIndex++];
       auto rawConvention = variableData[nextVariableDataIndex++];
       auto param = processParameter(typeID, rawConvention);
-      if (!param) {
-        error();
-        return nullptr;
-      }
-      allParams.push_back(*param);
+      if (!param)
+        return param.takeError();
+      allParams.push_back(param.get());
     }
 
     // Process the yields.
@@ -4869,11 +4871,9 @@
       auto typeID = variableData[nextVariableDataIndex++];
       auto rawConvention = variableData[nextVariableDataIndex++];
       auto yield = processYield(typeID, rawConvention);
-      if (!yield) {
-        error();
-        return nullptr;
-      }
-      allYields.push_back(*yield);
+      if (!yield)
+        return yield.takeError();
+      allYields.push_back(yield.get());
     }
 
     // Process the results.
@@ -4883,11 +4883,9 @@
       auto typeID = variableData[nextVariableDataIndex++];
       auto rawConvention = variableData[nextVariableDataIndex++];
       auto result = processResult(typeID, rawConvention);
-      if (!result) {
-        error();
-        return nullptr;
-      }
-      allResults.push_back(*result);
+      if (!result)
+        return result.takeError();
+      allResults.push_back(result.get());
     }
 
     // Process the error result.
@@ -4895,11 +4893,10 @@
     if (hasErrorResult) {
       auto typeID = variableData[nextVariableDataIndex++];
       auto rawConvention = variableData[nextVariableDataIndex++];
-      errorResult = processResult(typeID, rawConvention);
-      if (!errorResult) {
-        error();
-        return nullptr;
-      }
+      auto maybeErrorResult = processResult(typeID, rawConvention);
+      if (!maybeErrorResult)
+        return maybeErrorResult.takeError();
+      errorResult = maybeErrorResult.get();
     }
 
     Optional<ProtocolConformanceRef> witnessMethodConformance;
diff --git a/lib/Serialization/DeserializationErrors.h b/lib/Serialization/DeserializationErrors.h
index 0703ea4..dc0e952 100644
--- a/lib/Serialization/DeserializationErrors.h
+++ b/lib/Serialization/DeserializationErrors.h
@@ -355,6 +355,41 @@
   }
 };
 
+class SILEntityError : public llvm::ErrorInfo<SILEntityError> {
+  friend ErrorInfo;
+  static const char ID;
+  void anchor() override;
+
+  std::unique_ptr<ErrorInfoBase> underlyingReason;
+  StringRef name;
+public:
+  SILEntityError(StringRef name, std::unique_ptr<ErrorInfoBase> reason)
+      : underlyingReason(std::move(reason)), name(name) {}
+
+  void log(raw_ostream &OS) const override {
+    OS << "could not deserialize SIL entity '" << name << "'";
+    if (underlyingReason) {
+      OS << ": ";
+      underlyingReason->log(OS);
+    }
+  }
+
+  std::error_code convertToErrorCode() const override {
+    return llvm::inconvertibleErrorCode();
+  }
+};
+
+LLVM_NODISCARD
+static inline std::unique_ptr<llvm::ErrorInfoBase>
+takeErrorInfo(llvm::Error error) {
+  std::unique_ptr<llvm::ErrorInfoBase> result;
+  llvm::handleAllErrors(std::move(error),
+                        [&](std::unique_ptr<llvm::ErrorInfoBase> info) {
+    result = std::move(info);
+  });
+  return result;
+}
+
 class PrettyStackTraceModuleFile : public llvm::PrettyStackTraceEntry {
   const char *Action;
   const ModuleFile &MF;
diff --git a/lib/Serialization/DeserializeSIL.cpp b/lib/Serialization/DeserializeSIL.cpp
index 1c2ad04..75b8a45 100644
--- a/lib/Serialization/DeserializeSIL.cpp
+++ b/lib/Serialization/DeserializeSIL.cpp
@@ -12,13 +12,16 @@
 
 #define DEBUG_TYPE "deserialize"
 #include "DeserializeSIL.h"
+
+#include "DeserializationErrors.h"
+#include "SILFormat.h"
+
 #include "swift/Basic/Defer.h"
 #include "swift/Basic/PrettyStackTrace.h"
 #include "swift/AST/GenericSignature.h"
 #include "swift/AST/ProtocolConformance.h"
 #include "swift/AST/PrettyStackTrace.h"
 #include "swift/Serialization/ModuleFile.h"
-#include "SILFormat.h"
 #include "swift/SIL/SILArgument.h"
 #include "swift/SIL/SILBuilder.h"
 #include "swift/SIL/SILDebugScope.h"
@@ -38,6 +41,9 @@
 using namespace swift::serialization::sil_block;
 using namespace llvm::support;
 
+const char SILEntityError::ID = '\0';
+void SILEntityError::anchor() {}
+
 STATISTIC(NumDeserializedFunc, "Number of deserialized SIL functions");
 
 static Optional<StringLiteralInst::Encoding>
@@ -340,7 +346,14 @@
     // Otherwise, look for a function with this name in the module.
     auto iter = FuncTable->find(name);
     if (iter != FuncTable->end()) {
-      fn = readSILFunction(*iter, nullptr, name, /*declarationOnly*/ true);
+      auto maybeFn = readSILFunctionChecked(*iter, nullptr, name,
+                                            /*declarationOnly*/ true);
+      if (maybeFn) {
+        fn = maybeFn.get();
+      } else {
+        // Ignore the failure; we'll synthesize a bogus function instead.
+        llvm::consumeError(maybeFn.takeError());
+      }
     }
   }
 
@@ -363,7 +376,15 @@
   if (iter == FuncTable->end())
     return nullptr;
 
-  return readSILFunction(*iter, nullptr, name, /*declarationOnly*/ true);
+  auto maybeFn = readSILFunctionChecked(*iter, nullptr, name,
+                                        /*declarationOnly*/ true);
+  if (!maybeFn) {
+    // Ignore the failure and just pretend the function doesn't exist
+    llvm::consumeError(maybeFn.takeError());
+    return nullptr;
+  }
+
+  return maybeFn.get();
 }
 
 /// Helper function to find a SILGlobalVariable given its name. It first checks
@@ -387,6 +408,19 @@
                                               StringRef name,
                                               bool declarationOnly,
                                               bool errorIfEmptyBody) {
+  llvm::Expected<SILFunction *> deserialized =
+      readSILFunctionChecked(FID, existingFn, name, declarationOnly,
+                             errorIfEmptyBody);
+  if (!deserialized) {
+    MF->fatal(deserialized.takeError());
+  }
+  return deserialized.get();
+}
+
+llvm::Expected<SILFunction *>
+SILDeserializer::readSILFunctionChecked(DeclID FID, SILFunction *existingFn,
+                                        StringRef name, bool declarationOnly,
+                                        bool errorIfEmptyBody) {
   // We can't deserialize function bodies after IRGen lowering passes have
   // happened since other definitions in the module will no longer be in
   // canonical SIL form.
@@ -445,7 +479,16 @@
     MF->error();
     return nullptr;
   }
-  auto ty = getSILType(MF->getType(funcTyID), SILValueCategory::Object);
+  auto astType = MF->getTypeChecked(funcTyID);
+  if (!astType) {
+    if (!existingFn || errorIfEmptyBody) {
+      return llvm::make_error<SILEntityError>(
+          name, takeErrorInfo(astType.takeError()));
+    }
+    llvm::consumeError(astType.takeError());
+    return existingFn;
+  }
+  auto ty = getSILType(astType.get(), SILValueCategory::Object);
   if (!ty.is<SILFunctionType>()) {
     DEBUG(llvm::dbgs() << "not a function type for SILFunction\n");
     MF->error();
@@ -2433,14 +2476,21 @@
   if (iter == FuncTable->end())
     return nullptr;
 
-  auto Func = readSILFunction(*iter, InFunc, name, /*declarationOnly*/ false);
-  if (Func) {
-    DEBUG(llvm::dbgs() << "Deserialize SIL:\n";
-          Func->dump());
-    assert(InFunc->getName() == Func->getName());
+  auto maybeFunc = readSILFunctionChecked(*iter, InFunc, name,
+                                          /*declarationOnly*/ false);
+  if (!maybeFunc) {
+    // Ignore the error; treat it as if we didn't have a definition.
+    llvm::consumeError(maybeFunc.takeError());
+    return nullptr;
   }
 
-  return Func;
+  if (maybeFunc.get()) {
+    DEBUG(llvm::dbgs() << "Deserialize SIL:\n";
+          maybeFunc.get()->dump());
+    assert(InFunc->getName() == maybeFunc.get()->getName());
+  }
+
+  return maybeFunc.get();
 }
 
 /// Check for existence of a function with a given name and required linkage.
@@ -2517,11 +2567,20 @@
   if (iter == FuncTable->end())
     return nullptr;
 
-  auto Func = readSILFunction(*iter, nullptr, name, declarationOnly);
-  if (Func)
+  auto maybeFunc = readSILFunctionChecked(*iter, nullptr, name,
+                                          declarationOnly);
+
+  if (!maybeFunc) {
+    // Ignore the error; treat it as if we didn't have a definition.
+    llvm::consumeError(maybeFunc.takeError());
+    return nullptr;
+  }
+
+  if (maybeFunc.get()) {
     DEBUG(llvm::dbgs() << "Deserialize SIL:\n";
-          Func->dump());
-  return Func;
+          maybeFunc.get()->dump());
+  }
+  return maybeFunc.get();
 }
 
 SILGlobalVariable *SILDeserializer::readGlobalVar(StringRef Name) {
@@ -2617,8 +2676,12 @@
     auto DI = FuncTable->find(*KI);
     assert(DI != FuncTable->end() && "There should never be a key without data.");
 
-    readSILFunction(*DI, nullptr, *KI, false,
-                    false/*errorIfEmptyBody*/);
+    auto maybeFunc = readSILFunctionChecked(*DI, nullptr, *KI, false,
+                                            false/*errorIfEmptyBody*/);
+    if (!maybeFunc) {
+      // Ignore the error; treat it as if we didn't have a definition.
+      llvm::consumeError(maybeFunc.takeError());
+    }
   }
 }
 
diff --git a/lib/Serialization/DeserializeSIL.h b/lib/Serialization/DeserializeSIL.h
index 15ea040..b4a4f30 100644
--- a/lib/Serialization/DeserializeSIL.h
+++ b/lib/Serialization/DeserializeSIL.h
@@ -79,6 +79,12 @@
     SILFunction *readSILFunction(serialization::DeclID, SILFunction *InFunc,
                                  StringRef Name, bool declarationOnly,
                                  bool errorIfEmptyBody = true);
+    /// Read a SIL function.
+    llvm::Expected<SILFunction *>
+    readSILFunctionChecked(serialization::DeclID, SILFunction *InFunc,
+                           StringRef Name, bool declarationOnly,
+                           bool errorIfEmptyBody = true);
+
     /// Read a SIL basic block within a given SIL function.
     SILBasicBlock *readSILBasicBlock(SILFunction *Fn,
                                      SILBasicBlock *Prev,
diff --git a/stdlib/private/StdlibUnittest/StdlibUnittest.swift b/stdlib/private/StdlibUnittest/StdlibUnittest.swift
index ceb60fc..83d95ef 100644
--- a/stdlib/private/StdlibUnittest/StdlibUnittest.swift
+++ b/stdlib/private/StdlibUnittest/StdlibUnittest.swift
@@ -2410,6 +2410,33 @@
   return hasher.finalize()
 }
 
+/// Test that the elements of `groups` consist of instances that satisfy the
+/// semantic requirements of `Hashable`, with each group defining a distinct
+/// equivalence class under `==`.
+public func checkHashableGroups<Groups: Collection>(
+  _ groups: Groups,
+  _ message: @autoclosure () -> String = "",
+  stackTrace: SourceLocStack = SourceLocStack(),
+  showFrame: Bool = true,
+  file: String = #file, line: UInt = #line
+) where Groups.Element: Collection, Groups.Element.Element: Hashable {
+  let instances = groups.flatMap { $0 }
+  // groupIndices[i] is the index of the element in groups that contains
+  // instances[i].
+  let groupIndices =
+    zip(0..., groups).flatMap { i, group in group.map { _ in i } }
+  func equalityOracle(_ lhs: Int, _ rhs: Int) -> Bool {
+    return groupIndices[lhs] == groupIndices[rhs]
+  }
+  checkHashable(
+    instances,
+    equalityOracle: equalityOracle,
+    hashEqualityOracle: equalityOracle,
+    allowBrokenTransitivity: false,
+    stackTrace: stackTrace.pushIf(showFrame, file: file, line: line),
+    showFrame: false)
+}
+
 /// Test that the elements of `instances` satisfy the semantic requirements of
 /// `Hashable`, using `equalityOracle` to generate equality and hashing
 /// expectations from pairs of positions in `instances`.
diff --git a/stdlib/public/SDK/Foundation/URL.swift b/stdlib/public/SDK/Foundation/URL.swift
index f176a9f..fea2260 100644
--- a/stdlib/public/SDK/Foundation/URL.swift
+++ b/stdlib/public/SDK/Foundation/URL.swift
@@ -412,6 +412,26 @@
     @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
     public var volumeSupportsCompression : Bool? { return _get(.volumeSupportsCompressionKey) }
     
+    /// true if the volume supports clonefile(2).
+    @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
+    public var volumeSupportsFileCloning : Bool? { return _get(.volumeSupportsFileCloningKey) }
+    
+    /// true if the volume supports renamex_np(2)'s RENAME_SWAP option.
+    @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
+    public var volumeSupportsSwapRenaming : Bool? { return _get(.volumeSupportsSwapRenamingKey) }
+    
+    /// true if the volume supports renamex_np(2)'s RENAME_EXCL option.
+    @available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
+    public var volumeSupportsExclusiveRenaming : Bool? { return _get(.volumeSupportsExclusiveRenamingKey) }
+    
+    /// true if the volume supports making files immutable with isUserImmutable or isSystemImmutable.
+    @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
+    public var volumeSupportsImmutableFiles : Bool? { return _get(.volumeSupportsImmutableFilesKey) }
+    
+    /// true if the volume supports setting POSIX access permissions with fileSecurity.
+    @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
+    public var volumeSupportsAccessPermissions : Bool? { return _get(.volumeSupportsAccessPermissionsKey) }
+    
     /// true if this item is synced to the cloud, false if it is only a local file. 
     public var isUbiquitousItem : Bool? { return _get(.isUbiquitousItemKey) }
 
diff --git a/stdlib/public/SDK/Foundation/URLComponents.swift b/stdlib/public/SDK/Foundation/URLComponents.swift
index 95f9cb7..28f71dc 100644
--- a/stdlib/public/SDK/Foundation/URLComponents.swift
+++ b/stdlib/public/SDK/Foundation/URLComponents.swift
@@ -291,6 +291,15 @@
         set { _applyMutation { $0.queryItems = newValue } }
     }
     
+    /// Returns an array of query items for this `URLComponents`, in the order in which they appear in the original query string. Any percent-encoding in a query item name or value is retained
+    ///
+    /// The setter combines an array containing any number of `URLQueryItem`s, each of which represents a single key-value pair, into a query string and sets the `URLComponents` query property. This property assumes the query item names and values are already correctly percent-encoded, and that the query item names do not contain the query item delimiter characters '&' and '='. Attempting to set an incorrectly percent-encoded query item or a query item name with the query item delimiter characters '&' and '=' will cause a `fatalError`.
+    @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
+    public var percentEncodedQueryItems: [URLQueryItem]? {
+        get { return _handle.map { $0.percentEncodedQueryItems } }
+        set { _applyMutation { $0.percentEncodedQueryItems = newValue } }
+    }
+	
     public var hashValue: Int {
         return _handle.map { $0.hash }
     }
diff --git a/stdlib/public/core/AnyHashable.swift b/stdlib/public/core/AnyHashable.swift
index deac970..a7dc0ed 100644
--- a/stdlib/public/core/AnyHashable.swift
+++ b/stdlib/public/core/AnyHashable.swift
@@ -39,21 +39,28 @@
 
 @usableFromInline // FIXME(sil-serialize-all)
 internal protocol _AnyHashableBox {
-  var _typeID: ObjectIdentifier { get }
-  func _unbox<T : Hashable>() -> T?
+  var _canonicalBox: _AnyHashableBox { get }
 
   /// Determine whether values in the boxes are equivalent.
   ///
+  /// - Precondition: `self` and `box` are in canonical form.
   /// - Returns: `nil` to indicate that the boxes store different types, so
   ///   no comparison is possible. Otherwise, contains the result of `==`.
-  func _isEqual(to: _AnyHashableBox) -> Bool?
+  func _isEqual(to box: _AnyHashableBox) -> Bool?
   var _hashValue: Int { get }
   func _hash(into hasher: inout Hasher)
 
   var _base: Any { get }
+  func _unbox<T: Hashable>() -> T?
   func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool
 }
 
+extension _AnyHashableBox {
+  var _canonicalBox: _AnyHashableBox {
+    return self
+  }
+}
+
 @_fixed_layout // FIXME(sil-serialize-all)
 @usableFromInline // FIXME(sil-serialize-all)
 internal struct _ConcreteHashableBox<Base : Hashable> : _AnyHashableBox {
@@ -108,19 +115,6 @@
   }
 }
 
-#if _runtime(_ObjC)
-// Retrieve the custom AnyHashable representation of the value after it
-// has been bridged to Objective-C. This mapping to Objective-C and back
-// turns a non-custom representation into a custom one, which is used as
-// the lowest-common-denominator for comparisons.
-@inlinable // FIXME(sil-serialize-all)
-internal func _getBridgedCustomAnyHashable<T>(_ value: T) -> AnyHashable? {
-  let bridgedValue = _bridgeAnythingToObjectiveC(value)
-  return (bridgedValue as?
-    _HasCustomAnyHashableRepresentation)?._toCustomAnyHashable()
-}
-#endif
-
 /// A type-erased hashable value.
 ///
 /// The `AnyHashable` type forwards equality comparisons and hashing operations
@@ -144,8 +138,11 @@
 public struct AnyHashable {
   @usableFromInline // FIXME(sil-serialize-all)
   internal var _box: _AnyHashableBox
-  @usableFromInline // FIXME(sil-serialize-all)
-  internal var _usedCustomRepresentation: Bool
+
+  @inlinable // FIXME(sil-serialize-all)
+  internal init(_box box: _AnyHashableBox) {
+    self._box = box
+  }
 
   /// Creates a type-erased hashable value that wraps the given instance.
   ///
@@ -167,15 +164,13 @@
   /// - Parameter base: A hashable value to wrap.
   @inlinable // FIXME(sil-serialize-all)
   public init<H : Hashable>(_ base: H) {
-    if let customRepresentation =
+    if let custom =
       (base as? _HasCustomAnyHashableRepresentation)?._toCustomAnyHashable() {
-      self = customRepresentation
-      self._usedCustomRepresentation = true
+      self = custom
       return
     }
 
-    self._box = _ConcreteHashableBox(0 as Int)
-    self._usedCustomRepresentation = false
+    self.init(_box: _ConcreteHashableBox(false)) // Dummy value
     _makeAnyHashableUpcastingToHashableBaseType(
       base,
       storingResultInto: &self)
@@ -184,7 +179,6 @@
   @inlinable // FIXME(sil-serialize-all)
   internal init<H : Hashable>(_usingDefaultRepresentationOf base: H) {
     self._box = _ConcreteHashableBox(base)
-    self._usedCustomRepresentation = false
   }
 
   /// The value wrapped by this instance.
@@ -213,13 +207,11 @@
     if _box._downCastConditional(into: result) { return true }
 
     #if _runtime(_ObjC)
-    // If we used a custom representation, bridge to Objective-C and then
-    // attempt the cast from there.
-    if _usedCustomRepresentation {
-      if let value = _bridgeAnythingToObjectiveC(_box._base) as? T {
-        result.initialize(to: value)
-        return true
-      }
+    // Bridge to Objective-C and then attempt the cast from there.
+    // FIXME: This should also work without the Objective-C runtime.
+    if let value = _bridgeAnythingToObjectiveC(_box._base) as? T {
+      result.initialize(to: value)
+      return true
     }
     #endif
 
@@ -255,34 +247,7 @@
   ///   - rhs: Another type-erased hashable value.
   @inlinable // FIXME(sil-serialize-all)
   public static func == (lhs: AnyHashable, rhs: AnyHashable) -> Bool {
-    // If they're equal, we're done.
-    if let result = lhs._box._isEqual(to: rhs._box) { return result }
-
-    #if _runtime(_ObjC)
-    // If one used a custom representation but the other did not, bridge
-    // the one that did *not* use the custom representation to Objective-C:
-    // if the bridged result has a custom representation, compare those custom
-    // custom representations.
-    if lhs._usedCustomRepresentation != rhs._usedCustomRepresentation {
-      // If the lhs used a custom representation, try comparing against the
-      // custom representation of the bridged rhs (if there is one).
-      if lhs._usedCustomRepresentation {
-        if let customRHS = _getBridgedCustomAnyHashable(rhs._box._base) {
-          return lhs._box._isEqual(to: customRHS._box) ?? false
-        }
-        return false
-      }
-
-      // Otherwise, try comparing the rhs against the custom representation of
-      // the bridged lhs (if there is one).
-      if let customLHS = _getBridgedCustomAnyHashable(lhs._box._base) {
-        return customLHS._box._isEqual(to: rhs._box) ?? false
-      }
-      return false
-    }
-    #endif
-
-    return false
+    return lhs._box._canonicalBox._isEqual(to: rhs._box._canonicalBox) ?? false
   }
 }
 
@@ -290,7 +255,7 @@
   /// The hash value.
   @inlinable // FIXME(sil-serialize-all)
   public var hashValue: Int {
-    return _box._hashValue
+    return _box._canonicalBox._hashValue
   }
 
   /// Hashes the essential components of this value by feeding them into the
@@ -300,7 +265,7 @@
   ///   of this instance.
   @inlinable // FIXME(sil-serialize-all)
   public func hash(into hasher: inout Hasher) {
-    _box._hash(into: &hasher)
+    _box._canonicalBox._hash(into: &hasher)
   }
 }
 
diff --git a/stdlib/public/core/Arrays.swift.gyb b/stdlib/public/core/Arrays.swift.gyb
index 8a4fece..84a2090 100644
--- a/stdlib/public/core/Arrays.swift.gyb
+++ b/stdlib/public/core/Arrays.swift.gyb
@@ -2420,6 +2420,73 @@
   }
 }
 
+extension Array: _HasCustomAnyHashableRepresentation
+  where Element: Hashable {
+  public func _toCustomAnyHashable() -> AnyHashable? {
+    return AnyHashable(_box: _ArrayAnyHashableBox(self))
+  }
+}
+
+internal protocol _ArrayAnyHashableProtocol: _AnyHashableBox {
+  var count: Int { get }
+  subscript(index: Int) -> AnyHashable { get }
+}
+
+internal struct _ArrayAnyHashableBox<Element: Hashable>
+  : _ArrayAnyHashableProtocol {
+  internal let _value: [Element]
+
+  internal init(_ value: [Element]) {
+    self._value = value
+  }
+
+  internal var _base: Any {
+    return _value
+  }
+
+  internal var count: Int {
+    return _value.count
+  }
+
+  internal subscript(index: Int) -> AnyHashable {
+    return _value[index] as AnyHashable
+  }
+
+  func _isEqual(to other: _AnyHashableBox) -> Bool? {
+    guard let other = other as? _ArrayAnyHashableProtocol else { return nil }
+    guard _value.count == other.count else { return false }
+    for i in 0 ..< _value.count {
+      if self[i] != other[i] { return false }
+    }
+    return true
+  }
+
+  var _hashValue: Int {
+    var hasher = Hasher()
+    _hash(into: &hasher)
+    return hasher.finalize()
+  }
+
+  func _hash(into hasher: inout Hasher) {
+    hasher.combine(_value.count) // discriminator
+    for i in 0 ..< _value.count {
+      hasher.combine(self[i])
+    }
+  }
+
+  internal func _unbox<T : Hashable>() -> T? {
+    return _value as? T
+  }
+
+  internal func _downCastConditional<T>(
+    into result: UnsafeMutablePointer<T>
+  ) -> Bool {
+    guard let value = _value as? T else { return false }
+    result.initialize(to: value)
+    return true
+  }
+}
+
 // ${'Local Variables'}:
 // eval: (read-only-mode 1)
 // End:
diff --git a/stdlib/public/core/Collection.swift b/stdlib/public/core/Collection.swift
index ea57e57..a882b40 100644
--- a/stdlib/public/core/Collection.swift
+++ b/stdlib/public/core/Collection.swift
@@ -803,25 +803,6 @@
   ///   `endIndex`.
   func formIndex(after i: inout Index)
 
-  /// Returns a random element of the collection, using the given generator as
-  /// a source for randomness.
-  ///
-  /// You use this method to select a random element from a collection when you
-  /// are using a custom random number generator. For example, call
-  /// `randomElement(using:)` to select a random element from an array of names.
-  ///
-  ///     let names = ["Zoey", "Chloe", "Amani", "Amaia"]
-  ///     let randomName = names.randomElement(using: &myGenerator)!
-  ///     // randomName == "Amani"
-  ///
-  /// - Parameter generator: The random number generator to use when choosing
-  ///   a random element.
-  /// - Returns: A random element from the collection. If the collection is
-  ///   empty, the method returns `nil`.
-  func randomElement<T: RandomNumberGenerator>(
-    using generator: inout T
-  ) -> Element?
-
   @available(*, deprecated, message: "all index distances are now of type Int")
   typealias IndexDistance = Int
 }
diff --git a/stdlib/public/core/Dictionary.swift b/stdlib/public/core/Dictionary.swift
index d9d9428..91a8779 100644
--- a/stdlib/public/core/Dictionary.swift
+++ b/stdlib/public/core/Dictionary.swift
@@ -1515,6 +1515,61 @@
   }
 }
 
+extension Dictionary: _HasCustomAnyHashableRepresentation
+where Value: Hashable {
+  public func _toCustomAnyHashable() -> AnyHashable? {
+    return AnyHashable(_box: _DictionaryAnyHashableBox(self))
+  }
+}
+
+internal struct _DictionaryAnyHashableBox<Key: Hashable, Value: Hashable>
+  : _AnyHashableBox {
+  internal let _value: Dictionary<Key, Value>
+  internal let _canonical: Dictionary<AnyHashable, AnyHashable>
+
+  internal init(_ value: Dictionary<Key, Value>) {
+    self._value = value
+    self._canonical = value as Dictionary<AnyHashable, AnyHashable>
+  }
+
+  internal var _base: Any {
+    return _value
+  }
+
+  internal var _canonicalBox: _AnyHashableBox {
+    return _DictionaryAnyHashableBox<AnyHashable, AnyHashable>(_canonical)
+  }
+
+  internal func _isEqual(to other: _AnyHashableBox) -> Bool? {
+    guard
+      let other = other as? _DictionaryAnyHashableBox<AnyHashable, AnyHashable>
+    else {
+      return nil
+    }
+    return _canonical == other._value
+  }
+
+  internal var _hashValue: Int {
+    return _canonical.hashValue
+  }
+
+  internal func _hash(into hasher: inout Hasher) {
+    _canonical.hash(into: &hasher)
+  }
+
+  internal func _unbox<T: Hashable>() -> T? {
+    return _value as? T
+  }
+
+  internal func _downCastConditional<T>(
+    into result: UnsafeMutablePointer<T>
+  ) -> Bool {
+    guard let value = _value as? T else { return false }
+    result.initialize(to: value)
+    return true
+  }
+}
+
 extension Dictionary: CustomStringConvertible, CustomDebugStringConvertible {
   @inlinable // FIXME(sil-serialize-all)
   internal func _makeDescription() -> String {
diff --git a/stdlib/public/core/FloatingPointTypes.swift.gyb b/stdlib/public/core/FloatingPointTypes.swift.gyb
index a0b5dec..8622e1a 100644
--- a/stdlib/public/core/FloatingPointTypes.swift.gyb
+++ b/stdlib/public/core/FloatingPointTypes.swift.gyb
@@ -1544,6 +1544,13 @@
 
 }
 
+extension ${Self}: _HasCustomAnyHashableRepresentation {
+  // Not @inlinable
+  public func _toCustomAnyHashable() -> AnyHashable? {
+    return AnyHashable(_box: _${Self}AnyHashableBox(self))
+  }
+}
+
 extension ${Self} {
   /// The magnitude of this value.
   ///
@@ -1795,6 +1802,81 @@
 }
 
 //===----------------------------------------------------------------------===//
+// AnyHashable
+//===----------------------------------------------------------------------===//
+
+internal struct _${Self}AnyHashableBox: _AnyHashableBox {
+  internal typealias Base = ${Self}
+  internal let _value: Base
+
+  internal init(_ value: Base) {
+    self._value = value
+  }
+
+  internal var _canonicalBox: _AnyHashableBox {
+    // Float and Double are bridged with NSNumber, so we have to follow
+    // NSNumber's rules for equality.  I.e., we need to make sure equal
+    // numerical values end up in identical boxes after canonicalization, so
+    // that _isEqual will consider them equal and they're hashed the same way.
+    //
+    // Note that these AnyHashable boxes don't currently feed discriminator bits
+    // to the hasher, so we allow repeatable collisions. E.g., -1 will always
+    // collide with UInt64.max.
+    if _value < 0 {
+      if let i = Int64(exactly: _value) {
+        return _IntegerAnyHashableBox(i)
+      }
+    } else {
+      if let i = UInt64(exactly: _value) {
+        return _IntegerAnyHashableBox(i)
+      }
+    }
+    if let d = Double(exactly: _value) {
+      return _DoubleAnyHashableBox(d)
+    }
+    // If a value can't be represented by a Double, keep it in its original
+    // representation so that it won't compare equal to approximations. (So that
+    // we don't round off Float80 values.)
+    return self
+  }
+
+  internal func _isEqual(to box: _AnyHashableBox) -> Bool? {
+    _sanityCheck(Int64(exactly: _value) == nil, "self isn't canonical")
+    _sanityCheck(UInt64(exactly: _value) == nil, "self isn't canonical")
+    if let box = box as? _${Self}AnyHashableBox {
+      return _value == box._value
+    }
+    return nil
+  }
+
+  internal var _hashValue: Int {
+    return Swift._hashValue(for: _value)
+  }
+
+  internal func _hash(into hasher: inout Hasher) {
+    _sanityCheck(Int64(exactly: _value) == nil, "self isn't canonical")
+    _sanityCheck(UInt64(exactly: _value) == nil, "self isn't canonical")
+    hasher.combine(_value)
+  }
+
+  internal var _base: Any {
+    return _value
+  }
+
+  internal func _unbox<T: Hashable>() -> T? {
+    return _value as? T
+  }
+
+  internal func _downCastConditional<T>(
+    into result: UnsafeMutablePointer<T>
+  ) -> Bool {
+    guard let value = _value as? T else { return false }
+    result.initialize(to: value)
+    return true
+  }
+}
+
+//===----------------------------------------------------------------------===//
 // Deprecated operators
 //===----------------------------------------------------------------------===//
 
diff --git a/stdlib/public/core/Integers.swift.gyb b/stdlib/public/core/Integers.swift.gyb
index 0627f64..d9dde80 100644
--- a/stdlib/public/core/Integers.swift.gyb
+++ b/stdlib/public/core/Integers.swift.gyb
@@ -2540,98 +2540,6 @@
 % for Range in ['Range', 'ClosedRange']:
 %   exampleRange = '1..<100' if Range == 'Range' else '1...100'
 
-extension ${Range}
-  where Bound: FixedWidthInteger, Bound.Stride : SignedInteger,
-  Bound.Magnitude: UnsignedInteger
-{
-      
-  /// Returns a random element of the range, using the given generator as
-  /// a source for randomness.
-  ///
-  /// You can use this method to select a random element of a range when you
-  /// are using a custom random number generator. If you're generating a random
-  /// number, in most cases, you should prefer using the `random(in:using:)`
-  /// static method of the desired numeric type. That static method is available
-  /// for both integer and floating point types, and returns a non-optional
-  /// value.
-  ///
-  /// - Parameter generator: The random number generator to use when choosing
-  ///   a random element.
-  /// - Returns: A random element of the range.
-%   if 'Closed' not in Range:
-  ///   If the range is empty, the method returns `nil`.
-%   else:
-  ///   This method never returns `nil`.
-%   end
-  @inlinable
-  public func randomElement<T: RandomNumberGenerator>(
-    using generator: inout T
-  ) -> Element? {
-    guard !isEmpty else {
-      return nil
-    }
-    let isLowerNegative = Bound.isSigned && lowerBound < 0
-    let sameSign = !Bound.isSigned || isLowerNegative == (upperBound < 0)
-%   if 'Closed' not in Range:
-    let delta: Bound.Magnitude
-%   else:
-    var delta: Bound.Magnitude
-%   end
-    if isLowerNegative {
-      delta = sameSign
-        ? lowerBound.magnitude - upperBound.magnitude
-        : lowerBound.magnitude + upperBound.magnitude
-    } else {
-      delta = upperBound.magnitude - lowerBound.magnitude
-    }
-%   if 'Closed' in Range:
-    if delta == Bound.Magnitude.max {
-      return Bound(truncatingIfNeeded: generator.next() as Bound.Magnitude)
-    }
-    delta += 1
-%   end
-    let randomMagnitude = generator.next(upperBound: delta)
-    if sameSign {
-      return lowerBound + Bound(randomMagnitude)
-    } else {
-%     if 'Closed' not in Range:
-      return randomMagnitude < upperBound.magnitude
-        ? Bound(randomMagnitude)
-        : -1 - Bound(randomMagnitude - upperBound.magnitude)
-%     else:
-      return Bound.isSigned && randomMagnitude <= upperBound.magnitude
-        ? Bound(randomMagnitude)
-        : 0 - Bound(randomMagnitude - upperBound.magnitude)
-%     end
-    }
-  }
-  
-  /// Returns a random element of the range, using the given generator as
-  /// a source for randomness.
-  ///
-  /// You can use this method to select a random element of a range when you
-  /// are using a custom random number generator. If you're generating a random
-  /// number, in most cases, you should prefer using the `random(in:)`
-  /// static method of the desired numeric type. That static method is available
-  /// for both integer and floating point types, and returns a non-optional
-  /// value.
-  ///
-  /// This method uses the default random generator, `Random.default`. Calling
-  /// `(${exampleRange}).randomElement()` is equivalent to calling
-  /// `(${exampleRange}).randomElement(using: &Random.default)`.
-  ///
-  /// - Returns: A random element of the range.
-%   if 'Closed' not in Range:
-  ///   If the range is empty, the method returns `nil`.
-%   else:
-  ///   This method never returns `nil`.
-%   end
-  @inlinable
-  public func randomElement() -> Element? {
-    return randomElement(using: &Random.default)
-  }
-}
-
 extension FixedWidthInteger
 where Self.Stride : SignedInteger,
       Self.Magnitude : UnsignedInteger {
@@ -2667,7 +2575,36 @@
       !range.isEmpty,
       "Can't get random value with an empty range"
     )
-    return range.randomElement(using: &generator)!
+
+    // Compute delta, the distance between the lower and upper bounds. This
+    // value may not representable by the type Bound if Bound is signed, but
+    // is always representable as Bound.Magnitude.
+%   if 'Closed' in Range:
+    var delta = Magnitude(truncatingIfNeeded: range.upperBound &- range.lowerBound)
+%   else:
+    let delta = Magnitude(truncatingIfNeeded: range.upperBound &- range.lowerBound)
+%   end
+%   if 'Closed' in Range:
+    // Subtle edge case: if the range is the whole set of representable values,
+    // then adding one to delta to account for a closed range will overflow.
+    // If we used &+ instead, the result would be zero, which isn't helpful,
+    // so we actually need to handle this case separately.
+    if delta == Magnitude.max {
+      return Self(truncatingIfNeeded: generator.next() as Magnitude)
+    }
+    // Need to widen delta to account for the right-endpoint of a closed range.
+    delta += 1
+%   end
+    // The mathematical result we want is lowerBound plus a random value in
+    // 0 ..< delta. We need to be slightly careful about how we do this
+    // arithmetic; the Bound type cannot generally represent the random value,
+    // so we use a wrapping addition on Bound.Magnitude. This will often
+    // overflow, but produces the correct bit pattern for the result when
+    // converted back to Bound.
+    return Self(truncatingIfNeeded:
+      Magnitude(truncatingIfNeeded: range.lowerBound) &+
+      generator.next(upperBound: delta)
+    )
   }
   
   /// Returns a random value within the specified range.
@@ -3890,22 +3827,14 @@
   ///   of this instance.
   @inlinable // FIXME(sil-serialize-all)
   public func hash(into hasher: inout Hasher) {
-    // FIXME(hasher): To correctly bridge `Set`s/`Dictionary`s containing
-    // `AnyHashable`-boxed integers, all integer values are currently required
-    // to hash exactly the same way as the corresponding (U)Int64 value.  To fix
-    // this, we should introduce a custom AnyHashable box for integer values
-    // that sign-extends values to 64 bits.
-    % if bits <= word_bits:
-    hasher._combine(_lowWord)
-    % elif bits == 2 * word_bits:
-    if let word = ${"" if signed else "U"}Int(exactly: self) {
-      hasher._combine(word._lowWord)
-    } else {
-      hasher._combine(UInt64(_value))
-    }
-    % else:
-    fatalError("Unsupported integer width")
-    % end
+    hasher._combine(${U}${Self}(_value))
+  }
+}
+
+extension ${Self} : _HasCustomAnyHashableRepresentation {
+  // Not @inlinable
+  public func _toCustomAnyHashable() -> AnyHashable? {
+    return AnyHashable(_box: _IntegerAnyHashableBox(self))
   }
 }
 
@@ -4257,3 +4186,64 @@
   }
 %   end
 }
+
+internal struct _IntegerAnyHashableBox<
+  Base: FixedWidthInteger
+>: _AnyHashableBox {
+  internal let _value: Base
+
+  internal init(_ value: Base) {
+    self._value = value
+  }
+
+  internal var _canonicalBox: _AnyHashableBox {
+    // We need to follow NSNumber semantics here; the AnyHashable forms of
+    // integer types holding the same mathematical value should compare equal.
+    // Sign-extend value to a 64-bit integer. This will generate hash conflicts
+    // between, say -1 and UInt.max, but that's fine.
+    if _value < 0 {
+      return _IntegerAnyHashableBox<Int64>(Int64(truncatingIfNeeded: _value))
+    }
+    return _IntegerAnyHashableBox<UInt64>(UInt64(truncatingIfNeeded: _value))
+  }
+
+  internal func _isEqual(to box: _AnyHashableBox) -> Bool? {
+    if Base.self == UInt64.self {
+      guard let box = box as? _IntegerAnyHashableBox<UInt64> else { return nil }
+      return _value == box._value
+    }
+    if Base.self == Int64.self {
+      guard let box = box as? _IntegerAnyHashableBox<Int64> else { return nil }
+      return _value == box._value
+    }
+    _preconditionFailure("self isn't canonical")
+  }
+
+  internal var _hashValue: Int {
+    _sanityCheck(Base.self == UInt64.self || Base.self == Int64.self,
+      "self isn't canonical")
+    return _value.hashValue
+  }
+
+  internal func _hash(into hasher: inout Hasher) {
+    _sanityCheck(Base.self == UInt64.self || Base.self == Int64.self,
+      "self isn't canonical")
+    _value.hash(into: &hasher)
+  }
+
+  internal var _base: Any {
+    return _value
+  }
+
+  internal func _unbox<T: Hashable>() -> T? {
+    return _value as? T
+  }
+
+  internal func _downCastConditional<T>(
+    into result: UnsafeMutablePointer<T>
+  ) -> Bool {
+    guard let value = _value as? T else { return false }
+    result.initialize(to: value)
+    return true
+  }
+}
diff --git a/stdlib/public/core/NewtypeWrapper.swift b/stdlib/public/core/NewtypeWrapper.swift
index b535310..9d89f7d 100644
--- a/stdlib/public/core/NewtypeWrapper.swift
+++ b/stdlib/public/core/NewtypeWrapper.swift
@@ -13,9 +13,10 @@
 /// An implementation detail used to implement support importing
 /// (Objective-)C entities marked with the swift_newtype Clang
 /// attribute.
-public protocol _SwiftNewtypeWrapper : RawRepresentable { }
+public protocol _SwiftNewtypeWrapper
+: RawRepresentable, _HasCustomAnyHashableRepresentation { }
 
-extension _SwiftNewtypeWrapper where Self: Hashable, Self.RawValue : Hashable {
+extension _SwiftNewtypeWrapper where Self: Hashable, Self.RawValue: Hashable {
   /// The hash value.
   @inlinable // FIXME(sil-serialize-all)
   public var hashValue: Int {
@@ -33,6 +34,61 @@
   }
 }
 
+extension _SwiftNewtypeWrapper {
+  public func _toCustomAnyHashable() -> AnyHashable? {
+    return nil
+  }
+}
+
+extension _SwiftNewtypeWrapper where Self: Hashable, Self.RawValue: Hashable {
+  public func _toCustomAnyHashable() -> AnyHashable? {
+    return AnyHashable(_box: _NewtypeWrapperAnyHashableBox(self))
+  }
+}
+
+internal struct _NewtypeWrapperAnyHashableBox<Base>: _AnyHashableBox
+where Base: _SwiftNewtypeWrapper & Hashable, Base.RawValue: Hashable {
+  var _value: Base
+
+  init(_ value: Base) {
+    self._value = value
+  }
+
+  var _canonicalBox: _AnyHashableBox {
+    return (_value.rawValue as AnyHashable)._box._canonicalBox
+  }
+
+  func _isEqual(to other: _AnyHashableBox) -> Bool? {
+    _preconditionFailure("_isEqual called on non-canonical AnyHashable box")
+  }
+
+  var _hashValue: Int {
+    _preconditionFailure("_hashValue called on non-canonical AnyHashable box")
+  }
+
+  func _hash(into hasher: inout Hasher) {
+    _preconditionFailure("_hash(into:) called on non-canonical AnyHashable box")
+  }
+
+  var _base: Any { return _value }
+
+  func _unbox<T: Hashable>() -> T? {
+    return _value as? T ?? _value.rawValue as? T
+  }
+
+  func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool {
+    if let value = _value as? T {
+      result.initialize(to: value)
+      return true
+    }
+    if let value = _value.rawValue as? T {
+      result.initialize(to: value)
+      return true
+    }
+    return false
+  }
+}
+
 #if _runtime(_ObjC)
 extension _SwiftNewtypeWrapper where Self.RawValue : _ObjectiveCBridgeable {
   // Note: This is the only default typealias for _ObjectiveCType, because
diff --git a/stdlib/public/core/Set.swift b/stdlib/public/core/Set.swift
index b07168d..85d89d7 100644
--- a/stdlib/public/core/Set.swift
+++ b/stdlib/public/core/Set.swift
@@ -500,6 +500,57 @@
   }
 }
 
+extension Set: _HasCustomAnyHashableRepresentation {
+  public func _toCustomAnyHashable() -> AnyHashable? {
+    return AnyHashable(_box: _SetAnyHashableBox(self))
+  }
+}
+
+internal struct _SetAnyHashableBox<Element: Hashable>: _AnyHashableBox {
+  internal let _value: Set<Element>
+  internal let _canonical: Set<AnyHashable>
+
+  internal init(_ value: Set<Element>) {
+    self._value = value
+    self._canonical = value as Set<AnyHashable>
+  }
+
+  internal var _base: Any {
+    return _value
+  }
+
+  internal var _canonicalBox: _AnyHashableBox {
+    return _SetAnyHashableBox<AnyHashable>(_canonical)
+  }
+
+  internal func _isEqual(to other: _AnyHashableBox) -> Bool? {
+    guard let other = other as? _SetAnyHashableBox<AnyHashable> else {
+      return nil
+    }
+    return _canonical == other._value
+  }
+
+  internal var _hashValue: Int {
+    return _canonical.hashValue
+  }
+
+  internal func _hash(into hasher: inout Hasher) {
+    _canonical.hash(into: &hasher)
+  }
+
+  internal func _unbox<T: Hashable>() -> T? {
+    return _value as? T
+  }
+
+  internal func _downCastConditional<T>(
+    into result: UnsafeMutablePointer<T>
+  ) -> Bool {
+    guard let value = _value as? T else { return false }
+    result.initialize(to: value)
+    return true
+  }
+}
+
 extension Set: SetAlgebra {
 
   /// Inserts the given element in the set if it is not already present.
diff --git a/stdlib/public/runtime/Demangle.cpp b/stdlib/public/runtime/Demangle.cpp
index 4a3f522..21547d7 100644
--- a/stdlib/public/runtime/Demangle.cpp
+++ b/stdlib/public/runtime/Demangle.cpp
@@ -160,8 +160,14 @@
         
         auto typeNode = Dem.createNode(nodeKind);
         typeNode->addChild(node, Dem);
-        auto identifier = Dem.createNode(Node::Kind::Identifier, name);
-        typeNode->addChild(identifier, Dem);
+        auto nameNode = Dem.createNode(Node::Kind::Identifier, name);
+        if (type->isSynthesizedRelatedEntity()) {
+          auto relatedName = Dem.createNode(Node::Kind::RelatedEntityDeclName,
+                                    type->getSynthesizedDeclRelatedEntityTag());
+          relatedName->addChild(nameNode, Dem);
+          nameNode = relatedName;
+        }
+        typeNode->addChild(nameNode, Dem);
         node = typeNode;
         
         // Apply generic arguments if the context is generic.
diff --git a/stdlib/public/runtime/Metadata.cpp b/stdlib/public/runtime/Metadata.cpp
index 66be4c1..47c174e 100644
--- a/stdlib/public/runtime/Metadata.cpp
+++ b/stdlib/public/runtime/Metadata.cpp
@@ -1488,7 +1488,20 @@
         && kind <= ContextDescriptorKind::Type_Last) {
       auto typeA = cast<TypeContextDescriptor>(a);
       auto typeB = cast<TypeContextDescriptor>(b);
-      return strcmp(typeA->Name.get(), typeB->Name.get()) == 0;
+      if (strcmp(typeA->Name.get(), typeB->Name.get()) != 0)
+        return false;
+      
+      // A synthesized entity has to match the related entity tag too.
+      if (typeA->isSynthesizedRelatedEntity()) {
+        if (!typeB->isSynthesizedRelatedEntity())
+          return false;
+        
+        if (typeA->getSynthesizedDeclRelatedEntityTag()
+            != typeB->getSynthesizedDeclRelatedEntityTag())
+          return false;
+      }
+      
+      return true;
     }
     
     // Otherwise, this runtime doesn't know anything about this context kind.
diff --git a/stdlib/public/runtime/MetadataLookup.cpp b/stdlib/public/runtime/MetadataLookup.cpp
index a239b0b..be28b62 100644
--- a/stdlib/public/runtime/MetadataLookup.cpp
+++ b/stdlib/public/runtime/MetadataLookup.cpp
@@ -264,14 +264,31 @@
         }
 
         auto nameNode = node->getChild(1);
-        if (nameNode->getKind() == Demangle::Node::Kind::PrivateDeclName)
-          return false;
-
-        if (nameNode->getText() != type->Name.get())
-          return false;
         
-        node = node->getChild(0);
-        break;
+        // Declarations synthesized by the Clang importer get a small tag
+        // string in addition to their name.
+        if (nameNode->getKind() == Demangle::Node::Kind::RelatedEntityDeclName){
+          if (nameNode->getText() != type->getSynthesizedDeclRelatedEntityTag())
+            return false;
+          
+          nameNode = nameNode->getChild(0);
+        } else if (type->isSynthesizedRelatedEntity()) {
+          return false;
+        }
+        
+        // We should only match public or internal declarations with stable
+        // names. The runtime metadata for private declarations would be
+        // anonymized.
+        if (nameNode->getKind() == Demangle::Node::Kind::Identifier) {
+          if (nameNode->getText() != type->Name.get())
+            return false;
+          
+          node = node->getChild(0);
+          break;
+        }
+        
+        return false;
+
       }
       
       // We don't know about this kind of context, or it doesn't have a stable
@@ -1166,7 +1183,7 @@
     if (typeInfo == nullptr) {
       typeInfo = TypeInfo(&METADATA_SYM(EMPTY_TUPLE_MANGLING), {});
       warning(0, "SWIFT RUNTIME BUG: unable to demangle type of field '%*s'. "
-                 "mangled type name is '%*s'",
+                 "mangled type name is '%*s'\n",
                  (int)name.size(), name.data(),
                  (int)typeName.size(), typeName.data());
     }
@@ -1214,6 +1231,17 @@
         return;
     }
   }
+
+  // If we failed to find the field descriptor metadata for the type, fall
+  // back to returning an empty tuple as a standin.
+  auto typeName = swift_getTypeName(base, /*qualified*/ true);
+  warning(0, "SWIFT RUNTIME BUG: unable to find field metadata for type '%*s'\n",
+             (int)typeName.length, typeName.data);
+  callback("unknown",
+           FieldType()
+             .withType(TypeInfo(&METADATA_SYM(EMPTY_TUPLE_MANGLING), {}))
+             .withIndirect(false)
+             .withWeak(false));
 }
 
 #define OVERRIDE_METADATALOOKUP COMPATIBILITY_OVERRIDE
diff --git a/test/ClangImporter/objc_ir.swift b/test/ClangImporter/objc_ir.swift
index ca3a76e..812b8eb 100644
--- a/test/ClangImporter/objc_ir.swift
+++ b/test/ClangImporter/objc_ir.swift
@@ -363,7 +363,5 @@
 // CHECK: ![[SWIFT_NAME_ALIAS_TYPE]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$SSo14SwiftNameAliasaD", scope: !{{[0-9]+}}, file: !{{[0-9]+}}, baseType: !{{[0-9]+}})
 
 // CHECK: ![[SWIFT_GENERIC_NAME_ALIAS_VAR]] = !DILocalVariable(name: "generic_obj", arg: 1, scope: !{{[0-9]+}}, file: !{{[0-9]+}}, line: {{[0-9]+}}, type: ![[SWIFT_GENERIC_NAME_ALIAS_TYPE:[0-9]+]])
-// CHECK: ![[SWIFT_GENERIC_NAME_ALIAS_TYPE]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$SSo21SwiftGenericNameAliasaySo8NSNumberCGD", scope: !{{[0-9]+}}, file: !{{[0-9]+}}, baseType: !{{[0-9]+}})
 
 // CHECK: ![[SWIFT_CONSTR_GENERIC_NAME_ALIAS_VAR]] = !DILocalVariable(name: "constr_generic_obj", arg: 1, scope: !{{[0-9]+}}, file: !{{[0-9]+}}, line: {{[0-9]+}}, type: ![[SWIFT_CONSTR_GENERIC_NAME_ALIAS_TYPE:[0-9]+]])
-// CHECK: ![[SWIFT_CONSTR_GENERIC_NAME_ALIAS_TYPE]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$SSo27SwiftConstrGenericNameAliasaySo8NSNumberCGD", scope: !{{[0-9]+}}, file: !{{[0-9]+}}, baseType: !{{[0-9]+}})
diff --git a/test/Compatibility/members.swift b/test/Compatibility/members.swift
index 1805106..6af2274 100644
--- a/test/Compatibility/members.swift
+++ b/test/Compatibility/members.swift
@@ -7,5 +7,4 @@
 
 func g0(_: (inout X) -> (Float) -> ()) {}
 
-// This becomes an error in Swift 4 mode -- probably a bug
-g0(X.f1)
+g0(X.f1) // expected-warning{{partial application of 'mutating' method}}
diff --git a/test/Constraints/generic_super_constraint.swift b/test/Constraints/generic_super_constraint.swift
index c227519..4f46e93 100644
--- a/test/Constraints/generic_super_constraint.swift
+++ b/test/Constraints/generic_super_constraint.swift
@@ -17,3 +17,11 @@
   // expected-error@+1{{cannot convert return expression}}
   return (x, y)
 }
+
+// SR-7551 captures a crash on this code.
+class IntegerClass : ExpressibleByIntegerLiteral, Equatable {
+  required init(integerLiteral value: Int) { }
+  static func ==(lhs: IntegerClass, rhs: IntegerClass) -> Bool { return true }
+}
+
+func foo<T: IntegerClass>(_ num: T) { let _ =  num != 0 }
diff --git a/test/Constraints/members.swift b/test/Constraints/members.swift
index 752e33a..4192a11 100644
--- a/test/Constraints/members.swift
+++ b/test/Constraints/members.swift
@@ -1,4 +1,4 @@
-// RUN: %target-typecheck-verify-swift -swift-version 4
+// RUN: %target-typecheck-verify-swift -swift-version 5
 
 ////
 // Members of structs
@@ -28,7 +28,7 @@
 _ = x.f0(i)
 x.f0(i).f1(i)
 
-g0(X.f1)
+g0(X.f1) // expected-error{{partial application of 'mutating' method}}
 
 _ = x.f0(x.f2(1))
 _ = x.f0(1).f2(i)
diff --git a/test/Constraints/mutating_members.swift b/test/Constraints/mutating_members.swift
new file mode 100644
index 0000000..dea386b
--- /dev/null
+++ b/test/Constraints/mutating_members.swift
@@ -0,0 +1,22 @@
+// RUN: %target-swift-frontend -typecheck -verify -swift-version 5 %s
+
+struct Foo {
+  mutating func boom() {}
+}
+
+let x = Foo.boom // expected-error{{partial application of 'mutating' method}}
+var y = Foo()
+let z0 = y.boom // expected-error{{partial application of 'mutating' method}}
+let z1 = Foo.boom(&y) // expected-error{{partial application of 'mutating' method}}
+
+func fromLocalContext() -> (inout Foo) -> () -> () {
+  return Foo.boom // expected-error{{partial application of 'mutating' method}}
+}
+func fromLocalContext2(x: inout Foo, y: Bool) -> () -> () {
+  if y {
+    return x.boom // expected-error{{partial application of 'mutating' method}}
+  } else {
+    return Foo.boom(&x) // expected-error{{partial application of 'mutating' method}}
+  }
+}
+
diff --git a/test/Constraints/mutating_members_compat.swift b/test/Constraints/mutating_members_compat.swift
new file mode 100644
index 0000000..e29fd34
--- /dev/null
+++ b/test/Constraints/mutating_members_compat.swift
@@ -0,0 +1,22 @@
+// RUN: %target-swift-frontend -typecheck -verify -swift-version 4 %s
+
+struct Foo {
+  mutating func boom() {}
+}
+
+let x = Foo.boom // expected-warning{{partial application of 'mutating' method}}
+var y = Foo()
+let z0 = y.boom // expected-error{{partial application of 'mutating' method}}
+let z1 = Foo.boom(&y) // expected-error{{partial application of 'mutating' method}}
+
+func fromLocalContext() -> (inout Foo) -> () -> () {
+  return Foo.boom // expected-warning{{partial application of 'mutating' method}}
+}
+func fromLocalContext2(x: inout Foo, y: Bool) -> () -> () {
+  if y {
+    return x.boom // expected-error{{partial application of 'mutating' method}}
+  } else {
+    return Foo.boom(&x) // expected-error{{partial application of 'mutating' method}}
+  }
+}
+
diff --git a/test/DebugInfo/DumpDeclFromMangledName.swift b/test/DebugInfo/DumpDeclFromMangledName.swift
index 4b8bcef..a81abe3 100644
--- a/test/DebugInfo/DumpDeclFromMangledName.swift
+++ b/test/DebugInfo/DumpDeclFromMangledName.swift
@@ -39,3 +39,56 @@
 }
 
 patatino()
+
+class Foo<T> {
+  var x : T
+  init(_ x : T) {
+    self.x = x
+  }
+}
+
+typealias Patatino<T> = Foo<T>
+
+public struct Outer<T> {
+  public struct Inner { }
+  public struct GenericInner<U> { }
+
+  public typealias Foo<U> = Outer<U>.Inner
+
+  public func blah() {
+    let foo: Foo<Int> = Outer<Int>.Inner()
+  }
+}
+
+extension Outer.GenericInner {
+  public typealias Bar = Int
+
+  public func useBar() {
+    let bar: Bar = 7
+  }
+}
+
+protocol P {
+  associatedtype A
+}
+
+protocol Q {
+  associatedtype B: P
+  typealias ProtocolTypeAliasThing = B.A
+}
+
+struct ConformsToP: P {
+  typealias A = Int
+}
+
+struct ConformsToQ: Q {
+  typealias B = ConformsToP
+}
+
+struct Blah {
+  typealias SomeQ = ConformsToQ
+
+  func foo() {
+    let bar: SomeQ.ProtocolTypeAliasThing? = nil
+  }
+}
diff --git a/test/DebugInfo/guard-let.swift b/test/DebugInfo/guard-let.swift
index 2db51a4..ddf4ee3 100644
--- a/test/DebugInfo/guard-let.swift
+++ b/test/DebugInfo/guard-let.swift
@@ -21,9 +21,13 @@
   use(val)
 }
 
-// With large type optimizations the string is passed indirectly on i386 so
-// there is no shadow copy happening.
+// With large type optimizations the string is passed indirectly on the
+// following architectures so there is no shadow copy happening. As this
+// tests that we're emitting the DI correctly, we can skip running on them.
 // UNSUPPORTED: CPU=i386
+// UNSUPPORTED: CPU=armv7
+// UNSUPPORTED: CPU=armv7s
+// UNSUPPORTED: CPU=armv7k
 
 public func g(_ s : String?)
 {
diff --git a/test/Demangle/Inputs/manglings.txt b/test/Demangle/Inputs/manglings.txt
index a007915..830e783 100644
--- a/test/Demangle/Inputs/manglings.txt
+++ b/test/Demangle/Inputs/manglings.txt
@@ -310,5 +310,4 @@
 _$S3BBBBi0602365061_ ---> _$S3BBBBi0602365061_
 _$S3BBBBv0602365061_ ---> _$S3BBBBv0602365061_
 _T0lxxxmmmTk ---> _T0lxxxmmmTk
-$S4blah8PatatinoaySiGD -> blah.Patatino<Swift.Int>
 
diff --git a/test/IRGen/abi_v7k.swift b/test/IRGen/abi_v7k.swift
index da856ff..33e5c34 100644
--- a/test/IRGen/abi_v7k.swift
+++ b/test/IRGen/abi_v7k.swift
@@ -61,8 +61,7 @@
 // CHECK-LABEL: define hidden swiftcc void @"$S8test_v7k0A5Empty{{.*}}"()
 // V7K-LABEL: _$S8test_v7k0A5Empty
 enum Empty {}
-func testEmpty(x: Empty) -> Empty {
-  return x
+func testEmpty(x: Empty) -> () {
 }
 
 // CHECK-LABEL: define hidden swiftcc i32 @"$S8test_v7k0A6Single{{.*}}"()
diff --git a/test/IRGen/copy_value_destroy_value.sil b/test/IRGen/copy_value_destroy_value.sil
index bfdc2a9..701cbf1 100644
--- a/test/IRGen/copy_value_destroy_value.sil
+++ b/test/IRGen/copy_value_destroy_value.sil
@@ -36,10 +36,22 @@
 // CHECK: call %swift.refcounted* @swift_retain(%swift.refcounted* returned [[VAL2]])
 // CHECK: call void @swift_release(%swift.refcounted* [[VAL1]])
 // CHECK: call void @swift_release(%swift.refcounted* [[VAL2]])
-sil @non_trivial : $@convention(thin) (Foo) -> () {
+sil @non_trivial : $@convention(thin) (@guaranteed Foo) -> () {
 bb0(%0 : $Foo):
   %1 = copy_value %0 : $Foo
   destroy_value %1 : $Foo
   %2 = tuple()
   return %2 : $()
 }
+
+// CHECK: define{{( protected)?}} swiftcc void @non_trivial_unowned(
+// CHECK: call %swift.refcounted* @swift_unownedRetainStrong(%swift.refcounted* returned %0)
+// CHECK: call void @swift_release(%swift.refcounted* %0)
+sil @non_trivial_unowned : $@convention(thin) (@guaranteed Builtin.NativeObject) -> () {
+bb0(%0 : $Builtin.NativeObject):
+  %1 = ref_to_unowned %0 : $Builtin.NativeObject to $@sil_unowned Builtin.NativeObject
+  %2 = copy_unowned_value %1 : $@sil_unowned Builtin.NativeObject
+  destroy_value %2 : $Builtin.NativeObject
+  %9999 = tuple()
+  return %9999 : $()
+}
diff --git a/test/IRGen/enum_resilience_objc.swift b/test/IRGen/enum_resilience_objc.swift
new file mode 100644
index 0000000..1a582d4
--- /dev/null
+++ b/test/IRGen/enum_resilience_objc.swift
@@ -0,0 +1,25 @@
+// RUN: %empty-directory(%t)
+// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
+// RUN: %target-swift-frontend -module-name enum_resilience -I %t -emit-ir -enable-resilience %s | %FileCheck %s -DINT=i%target-ptrsize
+// RUN: %target-swift-frontend -module-name enum_resilience -I %t -emit-ir -enable-resilience -O %s
+
+// REQUIRES: objc_interop
+
+// Because the enum is resilient we cannot pack the tag into the pointer inside of the resilient payload.
+// CHECK: %T15enum_resilience9ContainerC5Multi33_{{.*}}LLO.0 = type <{ [{{(8|4)}} x i8], [1 x i8] }>
+
+import resilient_struct
+
+public class Container {
+  private enum Multi {
+    case none
+    case some(Container)
+    case data(ResilientRef)
+  }
+  private var e: Multi
+  var i: Int
+  init() {
+    e = .none
+    i = 0
+  }
+}
diff --git a/test/Inputs/resilient_struct.swift b/test/Inputs/resilient_struct.swift
index 01982d4..37b52da 100644
--- a/test/Inputs/resilient_struct.swift
+++ b/test/Inputs/resilient_struct.swift
@@ -77,3 +77,17 @@
     self.d = d
   }
 }
+
+public class Referent {}
+
+public struct ResilientWeakRef {
+  public weak var ref: Referent?
+
+  public init (_ r: Referent) {
+    ref = r
+  }
+}
+
+public struct ResilientRef {
+  public var r: Referent
+}
diff --git a/test/Interpreter/enum_resilience.swift b/test/Interpreter/enum_resilience.swift
index 3db9e03..9c68d42 100644
--- a/test/Interpreter/enum_resilience.swift
+++ b/test/Interpreter/enum_resilience.swift
@@ -436,4 +436,28 @@
   expectEqual(Base.self, ResilientMultiPayloadGenericEnumFixedSize<Base>.A.getTypeParameter())
 }
 
+public class Container {
+  private enum Multi {
+    case none
+    case some(Container)
+    case other(ResilientRef)
+  }
+  private var m: Multi
+  var i: Int
+  init() {
+    m = .none
+    i = 0
+    switch self.m {
+      case .none:
+        print("success")
+      case .some(_), .other(_):
+        assert(false, "noooo!")
+    }
+  }
+}
+
+ResilientEnumTestSuite.test("ResilientPrivateEnumMember") {
+  _ = Container()
+}
+
 runAllTests()
diff --git a/test/Interpreter/strong_retain_unowned_mispairing.swift b/test/Interpreter/strong_retain_unowned_mispairing.swift
new file mode 100644
index 0000000..c701adf
--- /dev/null
+++ b/test/Interpreter/strong_retain_unowned_mispairing.swift
@@ -0,0 +1,44 @@
+// RUN: %target-run-simple-opt-O-swift
+// REQUIRES: executable_test
+
+// We were crashing here due to not preserving rc identity. 
+// rdar://41328987
+
+func takeEscaping(closure: @escaping (String) -> Void) {}
+
+public class Helper {
+  weak var o: P?
+
+  @_optimize(none)
+  init(o: P) {
+    self.o = o
+  }
+}
+
+protocol P: class {}
+
+public class Binding: P {
+  private var helper: Helper?
+
+  public init() {
+    helper = Helper(o: self)
+    
+    // Listen to model changes
+    takeEscaping { [unowned self] (value: String) in
+      self.update()
+    }
+
+    takeEscaping { [unowned self] (value: String) in
+      self.update()
+    }
+  }
+
+  func update() {}
+}
+
+@_optimize(none)
+func testCrash() {
+  _ = Binding()
+}
+
+testCrash()
diff --git a/test/Migrator/Inputs/MyAppKit.swift b/test/Migrator/Inputs/MyAppKit.swift
index ed93508..818f136 100644
--- a/test/Migrator/Inputs/MyAppKit.swift
+++ b/test/Migrator/Inputs/MyAppKit.swift
@@ -2,3 +2,4 @@
 public class NSOpenGLOption {}
 public func NSOpenGLGetOption(_ c : NSOpenGLOption, _ p :UnsafePointer<Int>) {}
 public func NSOpenGLSetOption(_ c : NSOpenGLOption, _ p : Int) {}
+public func UIApplicationMain(_ a: Int32, _ b: UnsafeMutablePointer<UnsafeMutablePointer<Int8>>, _ c: String?, _ d: String?) -> Int32 { return 0 }
\ No newline at end of file
diff --git a/test/Migrator/Inputs/SpecialCaseAPI.json b/test/Migrator/Inputs/SpecialCaseAPI.json
index 26c4a98..1518592 100644
--- a/test/Migrator/Inputs/SpecialCaseAPI.json
+++ b/test/Migrator/Inputs/SpecialCaseAPI.json
@@ -13,5 +13,10 @@
     "DiffItemKind": "SpecialCaseDiffItem",
     "Usr": "s:7MySwift0A6DoubleV3absyS2dFZ",
     "SpecialCaseId": "StaticAbsToSwiftAbs"
+  },
+  {
+    "DiffItemKind": "SpecialCaseDiffItem",
+    "Usr": "s:8MyAppKit17UIApplicationMainys5Int32VAD_SpySpys4Int8VGGSSSgAItF",
+    "SpecialCaseId": "UIApplicationMain"
   }
 ]
diff --git a/test/Migrator/api-special-cases.swift b/test/Migrator/api-special-cases.swift
index 4598401..ae563bb 100644
--- a/test/Migrator/api-special-cases.swift
+++ b/test/Migrator/api-special-cases.swift
@@ -8,10 +8,16 @@
 import MyAppKit
 import MySwift
 
-func foo(_ Opt: NSOpenGLOption) {
+func foo(_ Opt: NSOpenGLOption, _ pointer: UnsafeMutablePointer<UnsafeMutablePointer<Int8>>) {
   var Value = 1
   NSOpenGLSetOption(Opt, 1)
   NSOpenGLGetOption(Opt, &Value)
+  UIApplicationMain(CommandLine.argc, pointer, "", "")
+  UIApplicationMain(
+    CommandLine.argc, pointer, "", "")
+  UIApplicationMain( CommandLine . 
+    argc, pointer, "", "")
+  UIApplicationMain(10, pointer, "", "")
 }
 
 do {
diff --git a/test/Migrator/api-special-cases.swift.expected b/test/Migrator/api-special-cases.swift.expected
index e37ccd8..b1ccea2 100644
--- a/test/Migrator/api-special-cases.swift.expected
+++ b/test/Migrator/api-special-cases.swift.expected
@@ -8,10 +8,16 @@
 import MyAppKit
 import MySwift
 
-func foo(_ Opt: NSOpenGLOption) {
+func foo(_ Opt: NSOpenGLOption, _ pointer: UnsafeMutablePointer<UnsafeMutablePointer<Int8>>) {
   var Value = 1
   Opt.globalValue = 1
   Value = Opt.globalValue
+  UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, "", "")
+  UIApplicationMain(
+    CommandLine.argc, CommandLine.unsafeArgv, "", "")
+  UIApplicationMain( CommandLine . 
+    argc, CommandLine.unsafeArgv, "", "")
+  UIApplicationMain(10, pointer, "", "")
 }
 
 do {
diff --git a/test/Migrator/ui-application-main.swift b/test/Migrator/ui-application-main.swift
new file mode 100644
index 0000000..d0ebd8c
--- /dev/null
+++ b/test/Migrator/ui-application-main.swift
@@ -0,0 +1,14 @@
+// RUN: %empty-directory(%t) && %target-swift-frontend -c -update-code -primary-file %s -emit-migrated-file-path %t/ui-application-main.swift.result -emit-remap-file-path %t/ui-application-main.swift.remap -o /dev/null -swift-version 3
+// RUN: diff -u %S/ui-application-main.swift.expected %t/ui-application-main.swift.result
+// RUN: %empty-directory(%t) && %target-swift-frontend -c -update-code -primary-file %s -emit-migrated-file-path %t/ui-application-main.swift.result -emit-remap-file-path %t/ui-application-main.swift.remap -o /dev/null -swift-version 4
+// RUN: diff -u %S/ui-application-main.swift.expected %t/ui-application-main.swift.result
+
+// REQUIRES: OS=ios
+// REQUIRES: objc_interop
+
+import UIKit
+
+func foo(pointer: UnsafeMutablePointer<UnsafeMutablePointer<Int8>>) {
+	UIApplicationMain(CommandLine.argc, pointer, "", "")
+	UIApplicationMain(2, pointer, "", "")
+}
diff --git a/test/Migrator/ui-application-main.swift.expected b/test/Migrator/ui-application-main.swift.expected
new file mode 100644
index 0000000..69fd82c
--- /dev/null
+++ b/test/Migrator/ui-application-main.swift.expected
@@ -0,0 +1,14 @@
+// RUN: %empty-directory(%t) && %target-swift-frontend -c -update-code -primary-file %s -emit-migrated-file-path %t/ui-application-main.swift.result -emit-remap-file-path %t/ui-application-main.swift.remap -o /dev/null -swift-version 3
+// RUN: diff -u %S/ui-application-main.swift.expected %t/ui-application-main.swift.result
+// RUN: %empty-directory(%t) && %target-swift-frontend -c -update-code -primary-file %s -emit-migrated-file-path %t/ui-application-main.swift.result -emit-remap-file-path %t/ui-application-main.swift.remap -o /dev/null -swift-version 4
+// RUN: diff -u %S/ui-application-main.swift.expected %t/ui-application-main.swift.result
+
+// REQUIRES: OS=ios
+// REQUIRES: objc_interop
+
+import UIKit
+
+func foo(pointer: UnsafeMutablePointer<UnsafeMutablePointer<Int8>>) {
+	UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, "", "")
+	UIApplicationMain(2, pointer, "", "")
+}
diff --git a/test/Runtime/Inputs/synthesized_decl_uniqueness.swift b/test/Runtime/Inputs/synthesized_decl_uniqueness.swift
new file mode 100644
index 0000000..5157acc
--- /dev/null
+++ b/test/Runtime/Inputs/synthesized_decl_uniqueness.swift
@@ -0,0 +1,9 @@
+import CoreLocation
+
+public func getCLError() -> Any.Type {
+  return CLError.self
+}
+
+public func getCLErrorCode() -> Any.Type {
+  return CLError.Code.self
+}
diff --git a/test/Runtime/demangleToMetadataObjC.swift b/test/Runtime/demangleToMetadataObjC.swift
index 606f111..11ba20d 100644
--- a/test/Runtime/demangleToMetadataObjC.swift
+++ b/test/Runtime/demangleToMetadataObjC.swift
@@ -5,6 +5,7 @@
 import StdlibUnittest
 import Foundation
 import CoreFoundation
+import CoreLocation
 
 let DemangleToMetadataTests = TestSuite("DemangleToMetadataObjC")
 
@@ -74,5 +75,15 @@
   expectNil(_typeByMangledName("4main3CG4CyAA1DCAA1DCG"))
 }
 
+DemangleToMetadataTests.test("synthesized declarations") {
+  expectEqual(CLError.self, _typeByMangledName("SC7CLErrorLeV")!)
+  expectNil(_typeByMangledName("SC7CLErrorV"))
+  expectEqual(CLError.Code.self, _typeByMangledName("So7CLErrorV")!)
+
+  let error = NSError(domain: NSCocoaErrorDomain, code: 0)
+  let reflectionString = String(reflecting: CLError(_nsError: error))
+  expectTrue(reflectionString.hasPrefix("__C_Synthesized.related decl 'e' for CLError(_nsError:"))
+}
+
 runAllTests()
 
diff --git a/test/Runtime/synthesized_decl_uniqueness.swift b/test/Runtime/synthesized_decl_uniqueness.swift
new file mode 100644
index 0000000..e47aea0
--- /dev/null
+++ b/test/Runtime/synthesized_decl_uniqueness.swift
@@ -0,0 +1,21 @@
+// RUN: %empty-directory(%t)
+// RUN: %target-build-swift -parse-as-library -force-single-frontend-invocation %S/Inputs/synthesized_decl_uniqueness.swift -emit-object -o %t/A.o -module-name A -emit-module-path %t/A.swiftmodule
+// RUN: %target-build-swift -parse-as-library -force-single-frontend-invocation %S/Inputs/synthesized_decl_uniqueness.swift -emit-object -o %t/B.o -module-name B -emit-module-path %t/B.swiftmodule
+// RUN: %target-build-swift -I %t %s %t/A.o %t/B.o -o %t/a.out
+// RUN: %target-run %t/a.out
+
+// REQUIRES: executable_test
+// REQUIRES: objc_interop
+
+import StdlibUnittest
+import A
+import B
+
+var tests = TestSuite("metadata identity for synthesized types")
+
+tests.test("synthesized type identity across modules") {
+  expectEqual(A.getCLError(), B.getCLError())
+  expectEqual(A.getCLErrorCode(), B.getCLErrorCode())
+}
+
+runAllTests()
diff --git a/test/SIL/Serialization/Recovery/Inputs/bad-modules/Types.h b/test/SIL/Serialization/Recovery/Inputs/bad-modules/Types.h
new file mode 100644
index 0000000..a735ae9
--- /dev/null
+++ b/test/SIL/Serialization/Recovery/Inputs/bad-modules/Types.h
@@ -0,0 +1,3 @@
+// struct SoonToBeMissing {
+//   int value;
+// };
diff --git a/test/SIL/Serialization/Recovery/Inputs/bad-modules/module.modulemap b/test/SIL/Serialization/Recovery/Inputs/bad-modules/module.modulemap
new file mode 100644
index 0000000..b811768
--- /dev/null
+++ b/test/SIL/Serialization/Recovery/Inputs/bad-modules/module.modulemap
@@ -0,0 +1 @@
+module Types { header "Types.h" }
diff --git a/test/SIL/Serialization/Recovery/Inputs/good-modules/Types.h b/test/SIL/Serialization/Recovery/Inputs/good-modules/Types.h
new file mode 100644
index 0000000..4b49807
--- /dev/null
+++ b/test/SIL/Serialization/Recovery/Inputs/good-modules/Types.h
@@ -0,0 +1,3 @@
+struct SoonToBeMissing {
+  int value;
+};
diff --git a/test/SIL/Serialization/Recovery/Inputs/good-modules/module.modulemap b/test/SIL/Serialization/Recovery/Inputs/good-modules/module.modulemap
new file mode 100644
index 0000000..b811768
--- /dev/null
+++ b/test/SIL/Serialization/Recovery/Inputs/good-modules/module.modulemap
@@ -0,0 +1 @@
+module Types { header "Types.h" }
diff --git a/test/SIL/Serialization/Recovery/function.sil b/test/SIL/Serialization/Recovery/function.sil
new file mode 100644
index 0000000..311c1b9
--- /dev/null
+++ b/test/SIL/Serialization/Recovery/function.sil
@@ -0,0 +1,26 @@
+// RUN: %empty-directory(%t)
+// RUN: %target-swift-frontend -parse-sil %s -emit-sib -o %t/Library.sib -module-name Library -I %S/Inputs/good-modules -parse-stdlib
+// RUN: %target-sil-opt %t/Library.sib -I %S/Inputs/good-modules | %FileCheck %s
+// RUN: %target-sil-opt %t/Library.sib -I %S/Inputs/bad-modules | %FileCheck -check-prefix=CHECK-RECOVERY %s
+// RUN: %target-sil-opt %t/Library.sib -I %S/Inputs/bad-modules | %FileCheck -check-prefix=CHECK-RECOVERY-NEGATIVE %s
+
+// CHECK-LABEL: sil_stage raw
+// CHECK-RECOVERY-LABEL: sil_stage raw
+
+sil_stage raw
+import Types
+
+// CHECK-LABEL: sil @missingParam : $@convention(thin) (SoonToBeMissing) -> () {
+// CHECK-RECOVERY-NEGATIVE-NOT: sil @missingParam
+sil @missingParam : $@convention(thin) (SoonToBeMissing) -> () {
+entry(%arg: $SoonToBeMissing):
+  %9999 = tuple()
+  return %9999 : $()
+}
+
+// CHECK-LABEL: sil @missingResult : $@convention(thin) () -> SoonToBeMissing {
+// CHECK-RECOVERY-NEGATIVE-NOT: sil @missingResult
+sil @missingResult : $@convention(thin) () -> (SoonToBeMissing) {
+entry:
+  unreachable
+}
diff --git a/test/SILOptimizer/ownership_model_eliminator.sil b/test/SILOptimizer/ownership_model_eliminator.sil
index acd3d16..6b226c6 100644
--- a/test/SILOptimizer/ownership_model_eliminator.sil
+++ b/test/SILOptimizer/ownership_model_eliminator.sil
@@ -114,11 +114,12 @@
   return %9999 : $()
 }
 
+// We no longer lower copy_unowned_value. So make sure that we actually don't.
+//
 // CHECK-LABEL: sil @copy_unowned_value_test : $@convention(thin) (@owned @sil_unowned Builtin.NativeObject) -> () {
 // CHECK: bb0([[ARG:%.*]] : $@sil_unowned Builtin.NativeObject):
-// CHECK-NEXT: strong_retain_unowned [[ARG]] : $@sil_unowned Builtin.NativeObject
-// CHECK-NEXT: [[OWNED_ARG:%.*]] = unowned_to_ref [[ARG]] : $@sil_unowned Builtin.NativeObject to $Builtin.NativeObject
-// CHECK-NEXT: strong_release [[OWNED_ARG]] : $Builtin.NativeObject
+// CHECK-NEXT: [[STRONG:%.*]] = copy_unowned_value [[ARG]] : $@sil_unowned Builtin.NativeObject
+// CHECK-NEXT: strong_release [[STRONG]] : $Builtin.NativeObject
 // CHECK-NEXT: unowned_release [[ARG]] : $@sil_unowned Builtin.NativeObject
 // CHECK-NEXT: tuple ()
 // CHECK-NEXT: return
diff --git a/test/SILOptimizer/predictable_memopt.sil b/test/SILOptimizer/predictable_memopt.sil
index 1a10f8f..4bf5838 100644
--- a/test/SILOptimizer/predictable_memopt.sil
+++ b/test/SILOptimizer/predictable_memopt.sil
@@ -880,4 +880,24 @@
   %4 = load %0 : $*SWithOpt
   dealloc_stack %0 : $*SWithOpt
   return %4 : $SWithOpt
-}
\ No newline at end of file
+}
+
+// We do not support this now, so make sure we do not do anything.
+//
+// CHECK-LABEL: sil @promote_init_enum_data_addr : $@convention(thin)
+// CHECK: alloc_stack
+// CHECK: load
+// CHECK: [[RESULT:%.*]] = load
+// CHECK: return [[RESULT]]
+// CHECK: } // end sil function 'promote_init_enum_data_addr'
+sil @promote_init_enum_data_addr : $@convention(thin) (@in Int) -> Int {
+bb0(%0 : $*Int):
+  %1 = alloc_stack $Optional<Int>
+  %2 = load %0 : $*Int
+  %3 = init_enum_data_addr %1 : $*Optional<Int>, #Optional.some!enumelt.1
+  store %2 to %3 : $*Int
+  inject_enum_addr %1 : $*Optional<Int>, #Optional.some!enumelt.1
+  %4 = load %3 : $*Int
+  dealloc_stack %1 : $*Optional<Int>
+  return %4 : $Int
+}
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/lit.cfg b/test/lit.cfg
index 7edca62..c53fad1 100644
--- a/test/lit.cfg
+++ b/test/lit.cfg
@@ -985,6 +985,16 @@
         '%s %s %%s -o %%t/a.out -module-name main && '
         '%s %%t/a.out'
         % (config.target_build_swift, mcp_opt, config.target_run))
+    config.target_run_simple_opt_O_swift = (
+        '%%empty-directory(%%t) && '
+        '%s %s -O %%s -o %%t/a.out -module-name main && '
+        '%s %%t/a.out'
+        % (config.target_build_swift, mcp_opt, config.target_run))
+    config.target_run_simple_opt_Osize_swift = (
+        '%%empty-directory(%%t) && '
+        '%s %s -Osize %%s -o %%t/a.out -module-name main && '
+        '%s %%t/a.out'
+        % (config.target_build_swift, mcp_opt, config.target_run))
     config.target_run_stdlib_swift = (
         'rm -rf %%t && mkdir -p %%t && '
         '%s %s %%s -o %%t/a.out -module-name main '
@@ -1065,6 +1075,8 @@
 
 config.substitutions.append(('%target-run-simple-swiftgyb', config.target_run_simple_swiftgyb))
 config.substitutions.append(('%target-run-simple-swift', config.target_run_simple_swift))
+config.substitutions.append(('%target-run-simple-opt-O-swift', config.target_run_simple_opt_O_swift))
+config.substitutions.append(('%target-run-simple-opt-Osize-swift', config.target_run_simple_opt_Osize_swift))
 config.substitutions.append(('%target-run-stdlib-swiftgyb', config.target_run_stdlib_swiftgyb))
 config.substitutions.append(('%target-run-stdlib-swift', config.target_run_stdlib_swift))
 config.substitutions.append(('%target-repl-run-simple-swift', subst_target_repl_run_simple_swift))
diff --git a/test/stdlib/AnyHashableCasts.swift.gyb b/test/stdlib/AnyHashableCasts.swift.gyb
index 4eaaf50..3a6f81f 100644
--- a/test/stdlib/AnyHashableCasts.swift.gyb
+++ b/test/stdlib/AnyHashableCasts.swift.gyb
@@ -1,10 +1,10 @@
 // RUN: %empty-directory(%t)
 //
 // RUN: %gyb %s -o %t/AnyHashableCasts.swift
-// RUN: %target-build-swift -g -module-name a %t/AnyHashableCasts.swift -o %t.out
-// RUN: %target-run %t.out
-// RUN: %target-build-swift -g -O -module-name a %t/AnyHashableCasts.swift -o %t.out.optimized
-// RUN: %target-run %t.out.optimized
+// RUN: %line-directive %t/AnyHashableCasts.swift -- %target-build-swift -g -module-name a %t/AnyHashableCasts.swift -o %t.out
+// RUN: %line-directive %t/AnyHashableCasts.swift -- %target-run %t.out
+// RUN: %line-directive %t/AnyHashableCasts.swift -- %target-build-swift -g -O -module-name a %t/AnyHashableCasts.swift -o %t.out.optimized
+// RUN: %line-directive %t/AnyHashableCasts.swift -- %target-run %t.out.optimized
 // REQUIRES: executable_test
 
 import StdlibUnittest
@@ -117,34 +117,129 @@
 % end
 
 #if _runtime(_ObjC)
+// A wrapper type around Int that bridges to NSNumber.
+struct IntWrapper1: _SwiftNewtypeWrapper, Hashable, _ObjectiveCBridgeable {
+  let rawValue: Int
+}
+
+// A wrapper type around Int that bridges to NSNumber.
+struct IntWrapper2: _SwiftNewtypeWrapper, Hashable, _ObjectiveCBridgeable {
+  let rawValue: Int
+}
+
+AnyHashableCasts.test("Wrappers around bridged integers") {
+  let wrapper1: AnyHashable = IntWrapper1(rawValue: 42)
+  let wrapper2: AnyHashable = IntWrapper2(rawValue: 42)
+  let integer: AnyHashable = 42 as Int
+  let byte: AnyHashable = 42 as UInt8
+  let double: AnyHashable = 42.0 as Double
+  let number: AnyHashable = 42 as NSNumber
+
+  // Wrappers compare equal to their wrapped value as AnyHashable.
+  expectEqual(wrapper1, wrapper2)
+  expectEqual(wrapper1, integer)
+  expectEqual(wrapper1, byte)
+  expectEqual(wrapper1, double)
+  expectEqual(wrapper1, number)
+
+  // Original types are preserved in the base property.
+  expectTrue(wrapper1.base is IntWrapper1)
+  expectTrue(wrapper2.base is IntWrapper2)
+  expectTrue(integer.base is Int)
+  expectTrue(byte.base is UInt8)
+  expectTrue(double.base is Double)
+  expectTrue(number.base is NSNumber) // Through bridging
+
+  // AnyHashable forms can be casted to any standard numeric type that can hold
+  // their value.
+  expectNotNil(wrapper1 as? IntWrapper1)
+  expectNotNil(wrapper1 as? IntWrapper2)
+  expectNotNil(wrapper1 as? Int)
+  expectNotNil(wrapper1 as? UInt8)
+  expectNotNil(wrapper1 as? Double)
+  expectNotNil(wrapper1 as? NSNumber)
+
+  expectNotNil(byte as? IntWrapper1)
+  expectNotNil(byte as? IntWrapper2)
+  expectNotNil(byte as? Int)
+  expectNotNil(byte as? UInt8)
+  expectNotNil(byte as? Double)
+  expectNotNil(byte as? NSNumber)
+
+  expectNotNil(integer as? IntWrapper1)
+  expectNotNil(integer as? IntWrapper2)
+  expectNotNil(integer as? Int)
+  expectNotNil(integer as? UInt8)
+  expectNotNil(integer as? Double)
+  expectNotNil(integer as? NSNumber)
+
+  expectNotNil(double as? IntWrapper1)
+  expectNotNil(double as? IntWrapper2)
+  expectNotNil(double as? Int)
+  expectNotNil(double as? UInt8)
+  expectNotNil(double as? Double)
+  expectNotNil(double as? NSNumber)
+
+  expectNotNil(number as? IntWrapper1)
+  expectNotNil(number as? IntWrapper2)
+  expectNotNil(number as? Int)
+  expectNotNil(number as? UInt8)
+  expectNotNil(number as? Double)
+  expectNotNil(number as? NSNumber)
+
+  // We can't cast to a numeric type that can't hold the value.
+  let big: AnyHashable = Int32.max
+  expectNotNil(big as? IntWrapper1)
+  expectNotNil(big as? IntWrapper2)
+  expectNotNil(big as? Int)
+  expectNil(big as? UInt8) // <--
+  expectNotNil(big as? Double)
+  expectNotNil(big as? NSNumber)
+}
+
 // A wrapper type around a String that bridges to NSString.
-struct StringWrapper1 : _SwiftNewtypeWrapper, Hashable, _ObjectiveCBridgeable {
+struct StringWrapper1: _SwiftNewtypeWrapper, Hashable, _ObjectiveCBridgeable {
   let rawValue: String
 }
 
 // A wrapper type around a String that bridges to NSString.
-struct StringWrapper2 : _SwiftNewtypeWrapper, Hashable, _ObjectiveCBridgeable {
+struct StringWrapper2: _SwiftNewtypeWrapper, Hashable, _ObjectiveCBridgeable {
   let rawValue: String
 }
 
-AnyHashableCasts.test("Wrappers around bridged types") {
+AnyHashableCasts.test("Wrappers around bridged strings") {
   let wrapper1Hello: AnyHashable = StringWrapper1(rawValue: "hello")
+  let wrapper2Hello: AnyHashable = StringWrapper2(rawValue: "hello")
   let stringHello: AnyHashable = "hello" as String
   let nsStringHello: AnyHashable = "hello" as NSString
 
-  // Casting from Swift wrapper maintains type identity
+  // Wrappers compare equal to their wrapped value as AnyHashable.
+  expectEqual(wrapper1Hello, wrapper2Hello)
+  expectEqual(wrapper1Hello, stringHello)
+  expectEqual(wrapper1Hello, nsStringHello)
+  expectEqual(wrapper2Hello, stringHello)
+  expectEqual(wrapper2Hello, nsStringHello)
+  expectEqual(stringHello, nsStringHello)
+
+  // Type identity is maintained through the base property.
+  expectTrue(wrapper1Hello.base is StringWrapper1)
+  expectTrue(wrapper2Hello.base is StringWrapper2)
+  expectTrue(stringHello.base is String)
+  expectTrue(nsStringHello.base is NSString) // Through bridging
+
+  // Swift wrapper's AnyHashable form doesn't enfore type identity.
   expectNotNil(wrapper1Hello as? StringWrapper1)
-  expectNil(wrapper1Hello as? StringWrapper2)
-  expectNil(wrapper1Hello as? String)
+  expectNotNil(wrapper1Hello as? StringWrapper2)
+  expectNotNil(wrapper1Hello as? String)
   expectNotNil(wrapper1Hello as? NSString)
 
-  // Casting from String maintains type identity
-  expectNil(stringHello as? StringWrapper1)
-  expectNil(stringHello as? StringWrapper2)
+  // String's AnyHashable form doesn't enfore type identity.
+  expectNotNil(stringHello as? StringWrapper1)
+  expectNotNil(stringHello as? StringWrapper2)
   expectNotNil(stringHello as? String)
   expectNotNil(stringHello as? NSString)
 
-  // Casting form NSString works with anything.
+  // NSString's AnyHashable form doesn't enfore type identity.
   expectNotNil(nsStringHello as? StringWrapper1)
   expectNotNil(nsStringHello as? StringWrapper2)
   expectNotNil(nsStringHello as? String)
diff --git a/test/stdlib/TestURL.swift b/test/stdlib/TestURL.swift
index 8c0128c..21f9205 100644
--- a/test/stdlib/TestURL.swift
+++ b/test/stdlib/TestURL.swift
@@ -178,8 +178,8 @@
     
     func testURLComponents() {
         // Not meant to be a test of all URL components functionality, just some basic bridging stuff
-        let s = "http://www.apple.com/us/search/ipad?src=globalnav"
-        let components = URLComponents(string: s)!
+        let s = "http://www.apple.com/us/search/ipad?src=global%7Cnav"
+        var components = URLComponents(string: s)!
         expectNotNil(components)
         
         expectNotNil(components.host)
@@ -201,7 +201,45 @@
             
             expectEqual("src", first.name)
             expectNotNil(first.value)
-            expectEqual("globalnav", first.value)
+            expectEqual("global|nav", first.value)
+        }
+
+        if #available(OSX 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) {
+            components.percentEncodedQuery = "name1%E2%80%A2=value1%E2%80%A2&name2%E2%80%A2=value2%E2%80%A2"
+            var qi = components.queryItems!
+            expectNotNil(qi)
+            
+            expectEqual(2, qi.count)
+            
+            expectEqual("name1•", qi[0].name)
+            expectNotNil(qi[0].value)
+            expectEqual("value1•", qi[0].value)
+            
+            expectEqual("name2•", qi[1].name)
+            expectNotNil(qi[1].value)
+            expectEqual("value2•", qi[1].value)
+            
+            qi = components.percentEncodedQueryItems!
+            expectNotNil(qi)
+            
+            expectEqual(2, qi.count)
+            
+            expectEqual("name1%E2%80%A2", qi[0].name)
+            expectNotNil(qi[0].value)
+            expectEqual("value1%E2%80%A2", qi[0].value)
+            
+            expectEqual("name2%E2%80%A2", qi[1].name)
+            expectNotNil(qi[0].value)
+            expectEqual("value2%E2%80%A2", qi[1].value)
+            
+            qi[0].name = "%E2%80%A2name1"
+            qi[0].value = "%E2%80%A2value1"
+            qi[1].name = "%E2%80%A2name2"
+            qi[1].value = "%E2%80%A2value2"
+            
+            components.percentEncodedQueryItems = qi
+            
+            expectEqual("%E2%80%A2name1=%E2%80%A2value1&%E2%80%A2name2=%E2%80%A2value2", components.percentEncodedQuery)
         }
     }
     
diff --git a/validation-test/Serialization/Inputs/custom-modules/module.modulemap b/validation-test/Serialization/Inputs/custom-modules/module.modulemap
new file mode 100644
index 0000000..b8ef16f
--- /dev/null
+++ b/validation-test/Serialization/Inputs/custom-modules/module.modulemap
@@ -0,0 +1 @@
+module rdar40899824Helper { header "rdar40899824Helper.h" }
diff --git a/validation-test/Serialization/Inputs/custom-modules/rdar40899824Helper.h b/validation-test/Serialization/Inputs/custom-modules/rdar40899824Helper.h
new file mode 100644
index 0000000..390ee41
--- /dev/null
+++ b/validation-test/Serialization/Inputs/custom-modules/rdar40899824Helper.h
@@ -0,0 +1,13 @@
+#ifndef BAD
+typedef struct {
+  int value;
+} SoonToBeMissing;
+#endif
+
+@interface Impl
+#ifndef BAD
+- (void)use:(SoonToBeMissing)value;
+#endif
+
+- (void)unrelated;
+@end
diff --git a/validation-test/Serialization/rdar40899824.swift b/validation-test/Serialization/rdar40899824.swift
new file mode 100644
index 0000000..1e793d5
--- /dev/null
+++ b/validation-test/Serialization/rdar40899824.swift
@@ -0,0 +1,38 @@
+// RUN: %empty-directory(%t)
+// RUN: %target-build-swift %s -emit-module -o %t/Library.swiftmodule -I %S/Inputs/custom-modules -DLIBRARY -Xfrontend -enable-objc-interop -Xfrontend -disable-objc-attr-requires-foundation-module
+// RUN: %target-swift-frontend %s -I %t -I %S/Inputs/custom-modules -enable-objc-interop -emit-ir > /dev/null
+
+// RUN: %target-swift-frontend %s -I %t -I %S/Inputs/custom-modules -enable-objc-interop -emit-ir -Xcc -DBAD > /dev/null
+// RUN: %target-swift-frontend %s -I %t -I %S/Inputs/custom-modules -enable-objc-interop -emit-ir -Xcc -DBAD -O > /dev/null
+
+#if LIBRARY
+
+import rdar40899824Helper
+
+public protocol Proto: class {
+  func use(_: SoonToBeMissing)
+  func unrelated()
+}
+
+extension Impl: Proto {}
+
+#else // LIBRARY
+
+import Library
+import rdar40899824Helper
+
+func testGeneric<T: Proto>(_ obj: T) {
+  obj.unrelated()
+}
+
+func testExistential(_ obj: Proto) {
+  obj.unrelated()
+}
+
+func test(_ proto: Proto, _ impl: Impl) {
+  impl.unrelated()
+  testGeneric(impl)
+  testExistential(impl)
+}
+
+#endif // LIBRARY
diff --git a/validation-test/compiler_crashers_2_fixed/0165-sr5427.swift b/validation-test/compiler_crashers_2_fixed/0165-sr5427.swift
new file mode 100644
index 0000000..845d263
--- /dev/null
+++ b/validation-test/compiler_crashers_2_fixed/0165-sr5427.swift
@@ -0,0 +1,7 @@
+// RUN: %target-typecheck-verify-swift
+
+// Used to crash with: apply expression is not marked as throwing or
+// non-throwing
+struct SR5427 : Error {}
+func sr5427(op: (() throws -> Void)?) rethrows { try op?() }
+try? sr5427(op: { throw SR5427() })
diff --git a/validation-test/stdlib/AnyHashable.swift.gyb b/validation-test/stdlib/AnyHashable.swift.gyb
index 05084ad..c6fa6cf 100644
--- a/validation-test/stdlib/AnyHashable.swift.gyb
+++ b/validation-test/stdlib/AnyHashable.swift.gyb
@@ -767,6 +767,132 @@
   expectEqual(MinimalHashableRCSwiftError.self, type(of: ah.base))
 }
 
+AnyHashableTests.test("AnyHashable(NumericTypes)/Hashable") {
+  // Numeric types holding mathematically equal values must compare equal and
+  // hash the same way when converted to AnyHashable.
+  let groups: [[AnyHashable]] = [
+    [
+      1 as Int,
+      1 as UInt,
+      1 as Int8,
+      1 as UInt8,
+      1 as Int16,
+      1 as UInt16,
+      1 as Int32,
+      1 as UInt32,
+      1 as Int64,
+      1 as UInt64,
+      1 as Float,
+      1 as Double,
+    ],
+    [
+      42 as Int,
+      42 as UInt,
+      42 as Int8,
+      42 as UInt8,
+      42 as Int16,
+      42 as UInt16,
+      42 as Int32,
+      42 as UInt32,
+      42 as Int64,
+      42 as UInt64,
+      42 as Float,
+      42 as Double,
+    ],
+    [
+      Int(Int32.max),
+      UInt(Int32.max),
+      Int32.max,
+      UInt32(Int32.max),
+      Int64(Int32.max),
+      UInt64(Int32.max),
+      Double(Int32.max),
+    ],
+    [
+      Float.infinity,
+      Double.infinity,
+    ],
+    [
+      0x1.aP1 as Float, // 3.25
+      0x1.aP1 as Double,
+    ],
+    [
+      0x1.a000000000001P1, // 3.25.nextUp, not representable by a Float
+    ]
+  ]
+  checkHashableGroups(groups)
+}
+
+#if !os(Windows) && (arch(i386) || arch(x86_64))
+AnyHashableTests.test("AnyHashable(Float80)/Hashable") {
+  let groups: [[AnyHashable]] = [
+    [
+      42 as Int,
+      42 as Float,
+      42 as Double,
+      42 as Float80,
+    ],
+    [
+      Float.infinity,
+      Double.infinity,
+      Float80.infinity,
+    ],
+    [
+      3.25 as Float,
+      3.25 as Double,
+      3.25 as Float80,
+    ],
+    [
+      0x1.a000000000001P1 as Double, // 3.25.nextUp
+      0x1.a000000000001P1 as Float80,
+    ],
+    [
+      0x1.a000000000000002p1 as Float80, // (3.25 as Float80).nextUp
+    ],
+  ]
+  checkHashableGroups(groups)
+}
+#endif
+
+#if _runtime(_ObjC)
+// A wrapper type around an Int that bridges to NSNumber.
+struct IntWrapper1 : _SwiftNewtypeWrapper, Hashable, _ObjectiveCBridgeable {
+  let rawValue: Int
+}
+
+// A wrapper type around an Int that bridges to NSNumber.
+struct IntWrapper2 : _SwiftNewtypeWrapper, Hashable, _ObjectiveCBridgeable {
+  let rawValue: Int
+}
+
+// A wrapper type around an Int that bridges to NSNumber.
+struct Int8Wrapper : _SwiftNewtypeWrapper, Hashable, _ObjectiveCBridgeable {
+  let rawValue: Int8
+}
+
+AnyHashableTests.test("AnyHashable(IntWrappers)/Hashable") {
+  let groups: [[AnyHashable]] = [
+    [
+      IntWrapper1(rawValue: 42),
+      IntWrapper2(rawValue: 42),
+      Int8Wrapper(rawValue: 42),
+      42,
+      42 as Double,
+      42 as NSNumber,
+    ],
+    [
+      IntWrapper1(rawValue: -23),
+      IntWrapper2(rawValue: -23),
+      Int8Wrapper(rawValue: -23),
+      -23,
+      -23 as Double,
+      -23 as NSNumber,
+    ],
+  ]
+  checkHashableGroups(groups)
+}
+#endif
+
 #if _runtime(_ObjC)
 // A wrapper type around a String that bridges to NSString.
 struct StringWrapper1 : _SwiftNewtypeWrapper, Hashable, _ObjectiveCBridgeable {
@@ -778,126 +904,101 @@
   let rawValue: String
 }
 
-AnyHashableTests.test("AnyHashable(Wrappers)/Hashable") {
-  let values: [AnyHashable] = [
-    StringWrapper1(rawValue: "hello"),
-    StringWrapper2(rawValue: "hello"),
-    "hello" as String,
-    "hello" as NSString,
-    StringWrapper1(rawValue: "world"),
-    StringWrapper2(rawValue: "world"),
-    "world" as String,
-    "world" as NSString,
+AnyHashableTests.test("AnyHashable(StringWrappers)/Hashable") {
+  let groups: [[AnyHashable]] = [
+    [
+      StringWrapper1(rawValue: "hello"),
+      StringWrapper2(rawValue: "hello"),
+      "hello" as String,
+      "hello" as NSString,
+    ],
+    [
+      StringWrapper1(rawValue: "world"),
+      StringWrapper2(rawValue: "world"),
+      "world" as String,
+      "world" as NSString,
+    ]
   ]
-
-  func equalityOracle(_ lhs: Int, _ rhs: Int) -> Bool {
-    // Elements in [0, 3] match 3.
-    if lhs == 3 { return rhs >= 0 && rhs <= 3 }
-    if rhs == 3 { return lhs >= 0 && lhs <= 3 }
-
-    // Elements in [4, 7] match 7.
-    if lhs == 7 { return rhs >= 4 && rhs <= 7 }
-    if rhs == 7 { return lhs >= 4 && lhs <= 7 }
-
-    return lhs == rhs
-  }
-
-  func hashEqualityOracle(_ lhs: Int, _ rhs: Int) -> Bool {
-    // Elements in [0, 3] hash the same, as do elements in [4, 7].
-    return lhs / 4 == rhs / 4
-  }
-
-  checkHashable(
-    values,
-    equalityOracle: equalityOracle,
-    hashEqualityOracle: hashEqualityOracle,
-    allowBrokenTransitivity: true)
+  checkHashableGroups(groups)
 }
 
 AnyHashableTests.test("AnyHashable(Set)/Hashable") {
-  let values: [AnyHashable] = [
-    Set([1, 2, 3]),
-    NSSet(set: [1, 2, 3]),
-    Set([2, 3, 4]),
-    NSSet(set: [2, 3, 4]),
-    Set([Set([1, 2]), Set([3, 4])]),
-    NSSet(set: [NSSet(set: [1, 2]), NSSet(set: [3, 4])]),
-    Set([Set([1, 3]), Set([2, 4])]),
-    NSSet(set: [NSSet(set: [1, 3]), NSSet(set: [2, 4])]),
+  let groups: [[AnyHashable]] = [
+    [
+      Set([1, 2, 3]),
+      Set([1, 2, 3] as [Int8]),
+      Set([1, 2, 3] as [Float]),
+      NSSet(set: [1, 2, 3]),
+    ],
+    [
+      Set([2, 3, 4]),
+      NSSet(set: [2, 3, 4]),
+    ],
+    [
+      Set([Set([1, 2]), Set([3, 4])]),
+      NSSet(set: [NSSet(set: [1, 2]), NSSet(set: [3, 4])]),
+    ],
+    [
+      Set([Set([1, 3]), Set([2, 4])]),
+      NSSet(set: [NSSet(set: [1, 3]), NSSet(set: [2, 4])]),
+    ],
   ]
-
-  func equalityOracle(_ lhs: Int, _ rhs: Int) -> Bool {
-    switch (lhs, rhs) {
-    case (0...1, 0...1): return true
-    case (2...3, 2...3): return true
-    case (4...5, 4...5): return true
-    case (6...7, 6...7): return true
-    default: return false
-    }
-  }
-
-  checkHashable(
-    values,
-    equalityOracle: equalityOracle,
-    allowBrokenTransitivity: true)
+  checkHashableGroups(groups)
 }
 
 AnyHashableTests.test("AnyHashable(Array)/Hashable") {
-  let values: [AnyHashable] = [
-    [1, 2, 3],
-    NSArray(array: [1, 2, 3]),
-    [3, 2, 1],
-    NSArray(array: [3, 2, 1]),
-    [[1, 2], [3, 4]],
-    NSArray(array: [NSArray(array: [1, 2]), NSArray(array: [3, 4])]),
-    [[3, 4], [1, 2]],
-    NSArray(array: [NSArray(array: [3, 4]), NSArray(array: [1, 2])]),
+  let groups: [[AnyHashable]] = [
+    [
+      [1, 2, 3],
+      [1, 2, 3] as [Int8],
+      [1, 2, 3] as [Double],
+      NSArray(array: [1, 2, 3]),
+    ],
+    [
+      [3, 2, 1],
+      [3, 2, 1] as [AnyHashable],
+      NSArray(array: [3, 2, 1]),
+    ],
+    [
+      [[1, 2], [3, 4]],
+      NSArray(array: [NSArray(array: [1, 2]), NSArray(array: [3, 4])]),
+    ],
+    [
+      [[3, 4], [1, 2]],
+      NSArray(array: [NSArray(array: [3, 4]), NSArray(array: [1, 2])]),
+    ]
   ]
-
-  func equalityOracle(_ lhs: Int, _ rhs: Int) -> Bool {
-    switch (lhs, rhs) {
-    case (0...1, 0...1): return true
-    case (2...3, 2...3): return true
-    case (4...5, 4...5): return true
-    case (6...7, 6...7): return true
-    default: return false
-    }
-  }
-
-  checkHashable(values, equalityOracle: equalityOracle,
-                allowBrokenTransitivity: true)
+  checkHashableGroups(groups)
 }
 
 AnyHashableTests.test("AnyHashable(Dictionary)/Hashable") {
-  let values: [AnyHashable] = [
-    ["hello": 1, "world": 2],
-    NSDictionary(dictionary: ["hello": 1, "world": 2]),
-    ["hello": 2, "world": 1],
-    NSDictionary(dictionary: ["hello": 2, "world": 1]),
-    ["hello": ["foo": 1, "bar": 2],
-     "world": ["foo": 2, "bar": 1]],
-    NSDictionary(dictionary: [
-        "hello": ["foo": 1, "bar": 2],
-        "world": ["foo": 2, "bar": 1]]),
-    ["hello": ["foo": 2, "bar": 1],
-     "world": ["foo": 1, "bar": 2]],
-    NSDictionary(dictionary: [
-        "hello": ["foo": 2, "bar": 1],
-        "world": ["foo": 1, "bar": 2]]),
+  let groups: [[AnyHashable]] = [
+    [
+      ["hello": 1, "world": 2] as [String: Int],
+      ["hello": 1, "world": 2] as [String: Int16],
+      ["hello": 1, "world": 2] as [String: Float],
+      NSDictionary(dictionary: ["hello": 1, "world": 2]),
+    ],
+    [
+      ["hello": 2, "world": 1],
+      NSDictionary(dictionary: ["hello": 2, "world": 1]),
+    ],
+    [
+      ["hello": ["foo": 1, "bar": 2],
+        "world": ["foo": 2, "bar": 1]],
+      NSDictionary(dictionary: [
+          "hello": ["foo": 1, "bar": 2],
+          "world": ["foo": 2, "bar": 1]]),
+    ],
+    [
+      ["hello": ["foo": 2, "bar": 1],
+        "world": ["foo": 1, "bar": 2]],
+      NSDictionary(dictionary: [
+          "hello": ["foo": 2, "bar": 1],
+          "world": ["foo": 1, "bar": 2]]),
+    ],
   ]
-
-  func equalityOracle(_ lhs: Int, _ rhs: Int) -> Bool {
-    switch (lhs, rhs) {
-    case (0...1, 0...1): return true
-    case (2...3, 2...3): return true
-    case (4...5, 4...5): return true
-    case (6...7, 6...7): return true
-    default: return false
-    }
-  }
-
-  checkHashable(values, equalityOracle: equalityOracle,
-                allowBrokenTransitivity: true)
+  checkHashableGroups(groups)
 }
 
 AnyHashableTests.test("AnyHashable(_SwiftNativeNSError(MinimalHashablePODSwiftError))/Hashable") {
diff --git a/validation-test/stdlib/DictionaryAnyHashableExtensions.swift b/validation-test/stdlib/DictionaryAnyHashableExtensions.swift
index 8cfaaa6..9d57794 100644
--- a/validation-test/stdlib/DictionaryAnyHashableExtensions.swift
+++ b/validation-test/stdlib/DictionaryAnyHashableExtensions.swift
@@ -6,26 +6,73 @@
 var DictionaryTests = TestSuite("Dictionary")
 
 DictionaryTests.test("index<Hashable>(forKey:)") {
-  let d: [AnyHashable : Int] = [
-    AnyHashable(10) : 1010,
-    AnyHashable(20) : 2020,
-    AnyHashable(30.0) : 3030,
+  let a = AnyHashable(10 as UInt16)
+  let b = AnyHashable(20)
+  let c = AnyHashable(30.0)
+  let d: [AnyHashable: Int] = [
+    a: 1010,
+    b: 2020,
+    c: 3030,
   ]
 
-  expectEqual(1010, d[d.index(forKey: 10)!].value)
-  expectEqual(2020, d[d.index(forKey: 20)!].value)
-  expectEqual(3030, d[d.index(forKey: 30.0)!].value)
+  for (key, k, value) in [(a, 10, 1010), (b, 20, 2020), (c, 30, 3030)] {
+    let index = d.index(forKey: key)!
+    expectEqual(value, d[index].value)
+    // We must be able to look up the same number in any representation.
+    expectEqual(index, d.index(forKey: UInt8(k)))
+    expectEqual(index, d.index(forKey: UInt16(k)))
+    expectEqual(index, d.index(forKey: UInt32(k)))
+    expectEqual(index, d.index(forKey: UInt64(k)))
+    expectEqual(index, d.index(forKey: UInt(k)))
+    expectEqual(index, d.index(forKey: Int8(k)))
+    expectEqual(index, d.index(forKey: Int16(k)))
+    expectEqual(index, d.index(forKey: Int32(k)))
+    expectEqual(index, d.index(forKey: Int64(k)))
+    expectEqual(index, d.index(forKey: Int(k)))
+    expectEqual(index, d.index(forKey: Float(k)))
+    expectEqual(index, d.index(forKey: Double(k)))
 
-  expectNil(d.index(forKey: 10.0))
-  expectNil(d.index(forKey: 20.0))
-  expectNil(d.index(forKey: 30))
+    expectNil(d.index(forKey: String(k)))
+  }
 }
 
 DictionaryTests.test("subscript<Hashable>(_:)") {
-  var d: [AnyHashable : Int] = [
-    AnyHashable(10) : 1010,
-    AnyHashable(20) : 2020,
-    AnyHashable(30.0) : 3030,
+  let a = AnyHashable(10 as UInt16)
+  let b = AnyHashable(20)
+  let c = AnyHashable(30.0)
+  let d: [AnyHashable: Int] = [
+    a: 1010,
+    b: 2020,
+    c: 3030,
+  ]
+
+  for (key, k, value) in [(a, 10, 1010), (b, 20, 2020), (c, 30, 3030)] {
+    let index = d.index(forKey: key)!
+    expectEqual(value, d[key])
+    // We must be able to look up the same number in any representation.
+    expectEqual(value, d[UInt8(k)])
+    expectEqual(value, d[UInt16(k)])
+    expectEqual(value, d[UInt32(k)])
+    expectEqual(value, d[UInt64(k)])
+    expectEqual(value, d[UInt(k)])
+    expectEqual(value, d[Int8(k)])
+    expectEqual(value, d[Int16(k)])
+    expectEqual(value, d[Int32(k)])
+    expectEqual(value, d[Int64(k)])
+    expectEqual(value, d[Int(k)])
+    expectEqual(value, d[Float(k)])
+    expectEqual(value, d[Double(k)])
+
+    expectNil(d[String(k)])
+  }
+}
+
+
+DictionaryTests.test("subscript<Hashable>(_:)/2") {
+  var d: [AnyHashable: Int] = [
+    AnyHashable(10): 1010,
+    AnyHashable(20): 2020,
+    AnyHashable(30.0): 3030,
   ]
 
   expectEqual(1010, d[10])
@@ -100,57 +147,61 @@
     expectEqual(expected, d)
   }
 
-  expectNil(d.updateValue(4040, forKey: 10.0))
+  expectEqual(101010, d.updateValue(4040, forKey: 10.0))
   do {
     let expected: [AnyHashable : Int] = [
-      AnyHashable(10) : 101010,
+      AnyHashable(10) : 4040,
       AnyHashable(20) : 202020,
       AnyHashable(30.0) : 303030,
-      AnyHashable(10.0) : 4040,
     ]
     expectEqual(expected, d)
   }
 
-  expectNil(d.updateValue(5050, forKey: 20.0))
+  expectEqual(202020, d.updateValue(5050, forKey: 20.0))
   do {
     let expected: [AnyHashable : Int] = [
-      AnyHashable(10) : 101010,
-      AnyHashable(20) : 202020,
+      AnyHashable(10) : 4040,
+      AnyHashable(20) : 5050,
       AnyHashable(30.0) : 303030,
-      AnyHashable(10.0) : 4040,
-      AnyHashable(20.0) : 5050,
     ]
     expectEqual(expected, d)
   }
 
-  expectNil(d.updateValue(6060, forKey: 30))
+  expectEqual(303030, d.updateValue(6060, forKey: 30))
   do {
     let expected: [AnyHashable : Int] = [
-      AnyHashable(10) : 101010,
-      AnyHashable(20) : 202020,
-      AnyHashable(30.0) : 303030,
-      AnyHashable(10.0) : 4040,
-      AnyHashable(20.0) : 5050,
-      AnyHashable(30) : 6060,
+      AnyHashable(10) : 4040,
+      AnyHashable(20) : 5050,
+      AnyHashable(30.0) : 6060,
     ]
     expectEqual(expected, d)
   }
 }
 
 DictionaryTests.test("removeValue<Hashable>(forKey:)") {
-  var d: [AnyHashable : Int] = [
-    AnyHashable(10) : 1010,
+  let d: [AnyHashable : Int] = [
+    AnyHashable(10 as UInt8) : 1010,
     AnyHashable(20) : 2020,
     AnyHashable(30.0) : 3030,
   ]
 
-  expectNil(d.removeValue(forKey: 10.0))
-  expectNil(d.removeValue(forKey: 20.0))
-  expectNil(d.removeValue(forKey: 30))
+  for (key, value) in [(10, 1010), (20, 2020), (30, 3030)] {
+    var dd = d
+    expectEqual(value, dd.removeValue(forKey: UInt8(key)))
+    dd = d; expectEqual(value, dd.removeValue(forKey: UInt16(key)))
+    dd = d; expectEqual(value, dd.removeValue(forKey: UInt32(key)))
+    dd = d; expectEqual(value, dd.removeValue(forKey: UInt64(key)))
+    dd = d; expectEqual(value, dd.removeValue(forKey: UInt(key)))
+    dd = d; expectEqual(value, dd.removeValue(forKey: Int8(key)))
+    dd = d; expectEqual(value, dd.removeValue(forKey: Int16(key)))
+    dd = d; expectEqual(value, dd.removeValue(forKey: Int32(key)))
+    dd = d; expectEqual(value, dd.removeValue(forKey: Int64(key)))
+    dd = d; expectEqual(value, dd.removeValue(forKey: Int(key)))
+    dd = d; expectEqual(value, dd.removeValue(forKey: Float(key)))
+    dd = d; expectEqual(value, dd.removeValue(forKey: Double(key)))
 
-  expectEqual(1010, d.removeValue(forKey: 10)!)
-  expectEqual(2020, d.removeValue(forKey: 20)!)
-  expectEqual(3030, d.removeValue(forKey: 30.0)!)
+    dd = d; expectNil(dd.removeValue(forKey: String(key)))
+  }
 }
 
 runAllTests()
diff --git a/validation-test/stdlib/FixedPoint.swift.gyb b/validation-test/stdlib/FixedPoint.swift.gyb
index 7ce5997..dd44fae 100644
--- a/validation-test/stdlib/FixedPoint.swift.gyb
+++ b/validation-test/stdlib/FixedPoint.swift.gyb
@@ -233,22 +233,22 @@
 % for self_ty in all_integer_types(word_bits):
 %   Self = self_ty.stdlib_name
 
-FixedPoint.test("${Self}.hashValue") {
+FixedPoint.test("${Self}.hash(into:)") {
 
 %   for bit_pattern in test_bit_patterns:
 
   do {
 %     input = prepare_bit_pattern(bit_pattern, self_ty.bits, self_ty.is_signed)
     let input = get${Self}(${input})
-    let output = getInt(input.hashValue)
+    var hasher = Hasher()
+    input.hash(into: &hasher)
+    let output = getInt(hasher.finalize())
 
-    var hasher = _SipHash13(_seed: Hasher._seed)
-%     if prepare_bit_pattern(input, word_bits, self_ty.is_signed) == input:
-    hasher._combine(UInt(truncatingIfNeeded: ${input} as ${"" if self_ty.is_signed else "U"}Int))
-%     else:
-    hasher._combine(UInt64(truncatingIfNeeded: input))
-%     end
-    let expected = getInt(Int(truncatingIfNeeded: hasher.finalize()))
+%     reference = prepare_bit_pattern(bit_pattern, self_ty.bits, False)
+    var referenceHasher = Hasher()
+    referenceHasher._combine(${reference} as UInt${self_ty.bits})
+    let expected = referenceHasher.finalize()
+
     expectEqual(expected, output, "input: \(input)")
   }
 
diff --git a/validation-test/stdlib/SetAnyHashableExtensions.swift b/validation-test/stdlib/SetAnyHashableExtensions.swift
index 3ab8cea..54ef1f7 100644
--- a/validation-test/stdlib/SetAnyHashableExtensions.swift
+++ b/validation-test/stdlib/SetAnyHashableExtensions.swift
@@ -28,28 +28,45 @@
 
 SetTests.test("contains<Hashable>(_:)") {
   let s: Set<AnyHashable> = [
-    AnyHashable(1010), AnyHashable(2020), AnyHashable(3030.0)
+    AnyHashable(1010 as UInt16), AnyHashable(2020), AnyHashable(3030.0)
   ]
-  expectTrue(s.contains(1010))
-  expectTrue(s.contains(2020))
-  expectTrue(s.contains(3030.0))
+  for i in [1010, 2020, 3030] {
+    // We must be able to look up the same number in any representation.
+    expectTrue(s.contains(UInt16(i)))
+    expectTrue(s.contains(UInt32(i)))
+    expectTrue(s.contains(UInt64(i)))
+    expectTrue(s.contains(UInt(i)))
+    expectTrue(s.contains(Int16(i)))
+    expectTrue(s.contains(Int32(i)))
+    expectTrue(s.contains(Int64(i)))
+    expectTrue(s.contains(Int(i)))
+    expectTrue(s.contains(Float(i)))
+    expectTrue(s.contains(Double(i)))
 
-  expectFalse(s.contains(1010.0))
-  expectFalse(s.contains(2020.0))
-  expectFalse(s.contains(3030))
+    expectFalse(s.contains(String(i)))
+  }
 }
 
 SetTests.test("index<Hashable>(of:)") {
-  let s: Set<AnyHashable> = [
-    AnyHashable(1010), AnyHashable(2020), AnyHashable(3030.0)
-  ]
-  expectEqual(AnyHashable(1010), s[s.firstIndex(of: 1010)!])
-  expectEqual(AnyHashable(2020), s[s.firstIndex(of: 2020)!])
-  expectEqual(AnyHashable(3030.0), s[s.firstIndex(of: 3030.0)!])
+  let a = AnyHashable(1010 as UInt16)
+  let b = AnyHashable(2020)
+  let c = AnyHashable(3030.0)
+  let s: Set<AnyHashable> = [a, b, c]
+  for (element, i) in [(a, 1010), (b, 2020), (c, 3030)] {
+    let index = s.firstIndex(of: element)!
 
-  expectNil(s.firstIndex(of: 1010.0))
-  expectNil(s.firstIndex(of: 2020.0))
-  expectNil(s.firstIndex(of: 3030))
+    // We must be able to look up the same number in any representation.
+    expectEqual(index, s.firstIndex(of: UInt16(i)))
+    expectEqual(index, s.firstIndex(of: UInt32(i)))
+    expectEqual(index, s.firstIndex(of: UInt64(i)))
+    expectEqual(index, s.firstIndex(of: UInt(i)))
+    expectEqual(index, s.firstIndex(of: Int16(i)))
+    expectEqual(index, s.firstIndex(of: Int32(i)))
+    expectEqual(index, s.firstIndex(of: Int64(i)))
+    expectEqual(index, s.firstIndex(of: Int(i)))
+    expectEqual(index, s.firstIndex(of: Float(i)))
+    expectEqual(index, s.firstIndex(of: Double(i)))
+  }
 }
 
 SetTests.test("insert<Hashable>(_:)") {
@@ -230,5 +247,28 @@
   s.remove(TestHashableDerivedB(2020, identity: 2))
 }
 
+SetTests.test("Hashable/Conversions") {
+  let input: [Set<AnyHashable>] = [
+    [10 as UInt8, 20 as UInt8, 30 as UInt8],
+    [10 as UInt16, 20 as UInt16, 30 as UInt16],
+    [10 as UInt32, 20 as UInt32, 30 as UInt32],
+    [10 as UInt64, 20 as UInt64, 30 as UInt64],
+    [10 as UInt, 20 as UInt, 30 as UInt],
+    [10 as Int8, 20 as Int8, 30 as Int8],
+    [10 as Int16, 20 as Int16, 30 as Int16],
+    [10 as Int32, 20 as Int32, 30 as Int32],
+    [10 as Int64, 20 as Int64, 30 as Int64],
+    [10 as Int, 20 as Int, 30 as Int],
+    [10 as Float, 20 as Float, 30 as Float],
+    [10 as Double, 20 as Double, 30 as Double],
+    [[1, 2, 3] as Set<Int>, [2, 3, 4] as Set<UInt8>, [3, 4, 5] as Set<Float>],
+    [[1, 2, 3] as Set<Int8>, [2, 3, 4] as Set<Double>, [3, 4, 5] as Set<Int32>],
+    [[1, 2, 3] as Set<UInt32>, [2, 3, 4] as Set<Int16>, [3, 4, 5] as Set<UInt>],
+  ]
+
+  checkHashable(input, equalityOracle: { ($0 < 12) == ($1 < 12) })
+}
+
+
 runAllTests()