Merge pull request #14163 from gottesmm/swift-4.1-branch_rdar36509461

[4.1][sil] When expanding aggregate instructions, do so consistently based…
diff --git a/README.md b/README.md
index 7ef4f79..c0e977d 100644
--- a/README.md
+++ b/README.md
@@ -54,7 +54,7 @@
 
 #### macOS
 
-To build for macOS, you need [Xcode 9.2 beta 2](https://developer.apple.com/xcode/downloads/).
+To build for macOS, you need [Xcode 9.3 beta](https://developer.apple.com/xcode/downloads/).
 The required version of Xcode changes frequently, and is often a beta release.
 Check this document or the host information on <https://ci.swift.org> for the
 current required version.
diff --git a/include/swift/AST/DiagnosticsSema.def b/include/swift/AST/DiagnosticsSema.def
index ece78b1..4048894 100644
--- a/include/swift/AST/DiagnosticsSema.def
+++ b/include/swift/AST/DiagnosticsSema.def
@@ -1405,6 +1405,10 @@
      (Type, Type, Type, Type, StringRef))
 NOTE(types_not_equal_requirement,none,
      "requirement specified as %0 == %1%2", (Type, Type, StringRef))
+ERROR(type_is_not_a_class,none,
+      "%0 requires that %1 be a class type", (Type, Type, Type))
+NOTE(anyobject_requirement,none,
+     "requirement specified as %0 : 'AnyObject'%2", (Type, Type, StringRef))
 ERROR(non_class_cannot_conform_to_class_protocol,none,
       "non-class type %0 cannot conform to class protocol %1",
       (Type, Type))
diff --git a/include/swift/AST/Types.h b/include/swift/AST/Types.h
index 197a12b..688f2a2 100644
--- a/include/swift/AST/Types.h
+++ b/include/swift/AST/Types.h
@@ -670,6 +670,16 @@
   /// with a class type.
   bool mayHaveSuperclass();
 
+  /// Determine whether this type satisfies a class layout constraint, written
+  /// `T: AnyObject` in the source.
+  ///
+  /// A class layout constraint is satisfied when we have a single retainable
+  /// pointer as the representation, which includes:
+  /// - @objc existentials
+  /// - class constrained archetypes
+  /// - classes
+  bool satisfiesClassConstraint();
+
   /// \brief Determine whether this type can be used as a base type for AST
   /// name lookup, which is the case for nominal types, protocol compositions
   /// and archetypes.
diff --git a/lib/AST/ProtocolConformance.cpp b/lib/AST/ProtocolConformance.cpp
index 0c15ad8..af9f491 100644
--- a/lib/AST/ProtocolConformance.cpp
+++ b/lib/AST/ProtocolConformance.cpp
@@ -530,8 +530,9 @@
   if (Loader)
     resolveLazyInfo();
 
-  if (TypeWitnesses.find(assocType) != TypeWitnesses.end()) {
-    return true;
+  auto found = TypeWitnesses.find(assocType);
+  if (found != TypeWitnesses.end()) {
+    return !found->getSecond().first.isNull();
   }
   if (resolver) {
     PrettyStackTraceRequirement trace("resolving", this, assocType);
@@ -556,24 +557,25 @@
   if (known != TypeWitnesses.end())
     return known->second;
 
-  // If this conformance is in a state where it is inferring type witnesses,
-  // check tentative witnesses.
-  if (getState() == ProtocolConformanceState::CheckingTypeWitnesses) {
-    // If there is a tentative-type-witness function, use it.
-    if (options.getTentativeTypeWitness) {
-     if (Type witnessType =
-           Type(options.getTentativeTypeWitness(this, assocType)))
-       return { witnessType, nullptr };
-    }
+  // If there is a tentative-type-witness function, use it.
+  if (options.getTentativeTypeWitness) {
+   if (Type witnessType =
+         Type(options.getTentativeTypeWitness(this, assocType)))
+     return { witnessType, nullptr };
+  }
 
-    // Otherwise, we fail; this is the only case in which we can return a
-    // null type.
+  // If this conformance is in a state where it is inferring type witnesses but
+  // we didn't find anything, fail.
+  if (getState() == ProtocolConformanceState::CheckingTypeWitnesses) {
     return { Type(), nullptr };
   }
 
   // Otherwise, resolve the type witness.
   PrettyStackTraceRequirement trace("resolving", this, assocType);
   assert(resolver && "Unable to resolve type witness");
+
+  // Block recursive resolution of this type witness.
+  TypeWitnesses[assocType] = { Type(), nullptr };
   resolver->resolveTypeWitness(this, assocType);
 
   known = TypeWitnesses.find(assocType);
@@ -586,7 +588,9 @@
                                                TypeDecl *typeDecl) const {
   assert(getProtocol() == cast<ProtocolDecl>(assocType->getDeclContext()) &&
          "associated type in wrong protocol");
-  assert(TypeWitnesses.count(assocType) == 0 && "Type witness already known");
+  assert((TypeWitnesses.count(assocType) == 0 ||
+          TypeWitnesses[assocType].first.isNull()) &&
+         "Type witness already known");
   assert((!isComplete() || isInvalid()) && "Conformance already complete?");
   assert(!type->hasArchetype() && "type witnesses must be interface types");
   TypeWitnesses[assocType] = std::make_pair(type, typeDecl);
diff --git a/lib/AST/Type.cpp b/lib/AST/Type.cpp
index 161a98c..51b6cd8 100644
--- a/lib/AST/Type.cpp
+++ b/lib/AST/Type.cpp
@@ -1445,6 +1445,10 @@
   return is<DynamicSelfType>();
 }
 
+bool TypeBase::satisfiesClassConstraint() {
+  return mayHaveSuperclass() || isObjCExistentialType();
+}
+
 Type TypeBase::getSuperclass() {
   auto *nominalDecl = getAnyNominal();
   auto *classDecl = dyn_cast_or_null<ClassDecl>(nominalDecl);
diff --git a/lib/SIL/SILVerifier.cpp b/lib/SIL/SILVerifier.cpp
index 3376344..5981cd2 100644
--- a/lib/SIL/SILVerifier.cpp
+++ b/lib/SIL/SILVerifier.cpp
@@ -2311,9 +2311,18 @@
         if (inst->isTypeDependentOperand(*use))
           continue;
         switch (inst->getKind()) {
+        case SILInstructionKind::MarkDependenceInst:
+          break;
         case SILInstructionKind::ApplyInst:
         case SILInstructionKind::TryApplyInst:
         case SILInstructionKind::PartialApplyInst:
+          // Non-Mutating set pattern that allows a inout (that can't really
+          // write back.
+          if (auto *AI = dyn_cast<ApplyInst>(inst)) {
+            if (isa<PointerToThinFunctionInst>(AI->getCallee())) {
+              break;
+            }
+          }
           if (isConsumingOrMutatingApplyUse(use))
             return true;
           else
diff --git a/lib/SIL/TypeLowering.cpp b/lib/SIL/TypeLowering.cpp
index 7c0b2ca..b7bbd21 100644
--- a/lib/SIL/TypeLowering.cpp
+++ b/lib/SIL/TypeLowering.cpp
@@ -2290,10 +2290,8 @@
   // Classes, class-constrained archetypes, and pure-ObjC existential types
   // all have single retainable pointer representation; optionality change
   // is allowed.
-  if ((type1.getSwiftRValueType()->mayHaveSuperclass() ||
-       type1.getSwiftRValueType()->isObjCExistentialType()) &&
-      (type2.getSwiftRValueType()->mayHaveSuperclass() ||
-       type2.getSwiftRValueType()->isObjCExistentialType()))
+  if (type1.getSwiftRValueType()->satisfiesClassConstraint() &&
+      type2.getSwiftRValueType()->satisfiesClassConstraint())
     return ABIDifference::Trivial;
 
   // Function parameters are ABI compatible if their differences are
diff --git a/lib/SILOptimizer/Utils/Local.cpp b/lib/SILOptimizer/Utils/Local.cpp
index 5c5ef11..d85ebb0 100644
--- a/lib/SILOptimizer/Utils/Local.cpp
+++ b/lib/SILOptimizer/Utils/Local.cpp
@@ -1457,8 +1457,10 @@
     } else if (isConditional) {
       SILBasicBlock *CastSuccessBB = Inst->getFunction()->createBasicBlock();
       CastSuccessBB->createPHIArgument(SILBridgedTy, ValueOwnershipKind::Owned);
-      NewI = Builder.createCheckedCastBranch(Loc, false, Load, SILBridgedTy,
-                                             CastSuccessBB, ConvFailBB);
+      auto *CCBI = Builder.createCheckedCastBranch(Loc, false, Load,
+                                      SILBridgedTy, CastSuccessBB, ConvFailBB);
+      NewI = CCBI;
+      splitEdge(CCBI, /* EdgeIdx to ConvFailBB */ 1);
       Builder.setInsertionPoint(CastSuccessBB);
       SrcOp = CastSuccessBB->getArgument(0);
     } else {
diff --git a/lib/Sema/CSSimplify.cpp b/lib/Sema/CSSimplify.cpp
index 41aaa90..26f8448 100644
--- a/lib/Sema/CSSimplify.cpp
+++ b/lib/Sema/CSSimplify.cpp
@@ -1329,14 +1329,7 @@
   if (auto layoutConstraint = layout.getLayoutConstraint()) {
     if (layoutConstraint->isClass()) {
       if (kind == ConstraintKind::ConformsTo) {
-        // Conformance to AnyObject is defined by having a single
-        // retainable pointer representation:
-        //
-        // - @objc existentials
-        // - class constrained archetypes
-        // - classes
-        if (!type1->isObjCExistentialType() &&
-            !type1->mayHaveSuperclass())
+        if (!type1->satisfiesClassConstraint())
           return SolutionKind::Error;
       } else {
         // Subtype relation to AnyObject also allows class-bound
diff --git a/lib/Sema/ConstraintSystem.cpp b/lib/Sema/ConstraintSystem.cpp
index ca5f5b9..73244f0 100644
--- a/lib/Sema/ConstraintSystem.cpp
+++ b/lib/Sema/ConstraintSystem.cpp
@@ -954,6 +954,29 @@
   return { valueType, valueType };
 }
 
+static NominalTypeDecl *getInnermostConformingDC(TypeChecker &TC,
+                                                 DeclContext *DC,
+                                                 ProtocolDecl *protocol) {
+  do {
+    if (DC->isTypeContext()) {
+      auto *NTD = DC->getAsNominalTypeOrNominalTypeExtensionContext();
+      auto type = NTD->getDeclaredType();
+
+      ConformanceCheckOptions options;
+      options |= ConformanceCheckFlags::InExpression;
+      options |= ConformanceCheckFlags::SuppressDependencyTracking;
+      options |= ConformanceCheckFlags::SkipConditionalRequirements;
+
+      auto result =
+          TC.conformsToProtocol(type, protocol, NTD->getDeclContext(), options);
+
+      if (result)
+        return NTD;
+    }
+  } while ((DC = DC->getParent()));
+
+  return nullptr;
+}
 /// Bind type variables for archetypes that are determined from
 /// context.
 ///
@@ -1015,8 +1038,18 @@
       // parameters, or because this generic parameter was constrained
       // away into a concrete type.
       if (found != replacements.end()) {
+        Type contextTy;
+
+        if (genericEnv) {
+          contextTy = genericEnv->mapTypeIntoContext(paramTy);
+        } else {
+          auto *protocol = parentDC->getAsProtocolOrProtocolExtensionContext();
+          auto conformingDC = getInnermostConformingDC(cs.TC, cs.DC, protocol);
+          assert(conformingDC);
+          contextTy = conformingDC->getDeclaredTypeInContext();
+        }
+
         auto typeVar = found->second;
-        auto contextTy = genericEnv->mapTypeIntoContext(paramTy);
         cs.addConstraint(ConstraintKind::Bind, typeVar, contextTy,
                          locatorPtr);
       }
diff --git a/lib/Sema/TypeCheckConstraints.cpp b/lib/Sema/TypeCheckConstraints.cpp
index ab4641d..20af9bd 100644
--- a/lib/Sema/TypeCheckConstraints.cpp
+++ b/lib/Sema/TypeCheckConstraints.cpp
@@ -2827,9 +2827,7 @@
 
 bool TypeChecker::isSubstitutableFor(Type type, ArchetypeType *archetype,
                                      DeclContext *dc) {
-  if (archetype->requiresClass() &&
-      !type->mayHaveSuperclass() &&
-      !type->isObjCExistentialType())
+  if (archetype->requiresClass() && !type->satisfiesClassConstraint())
     return false;
 
   if (auto superclass = archetype->getSuperclass()) {
diff --git a/lib/Sema/TypeCheckGeneric.cpp b/lib/Sema/TypeCheckGeneric.cpp
index e100ab9..68fbc6a 100644
--- a/lib/Sema/TypeCheckGeneric.cpp
+++ b/lib/Sema/TypeCheckGeneric.cpp
@@ -366,6 +366,8 @@
                                 TypeSubstitutionFn substitutions) {
   llvm::SmallPtrSet<GenericTypeParamType *, 2> knownGenericParams;
   for (auto type : types) {
+    if (type.isNull()) continue;
+
     type.visit([&](Type type) {
       if (auto gp = type->getAs<GenericTypeParamType>()) {
         knownGenericParams.insert(
@@ -1373,12 +1375,16 @@
         break;
       }
 
-      case RequirementKind::Layout: {
-        // TODO: Statically check if a the first type
-        // conforms to the layout constraint, once we
-        // support such static checks.
-        continue;
-      }
+      case RequirementKind::Layout:
+        // TODO: Statically check other layout constraints, once they can
+        // be spelled in Swift.
+        if (req.getLayoutConstraint()->isClass() &&
+            !firstType->satisfiesClassConstraint()) {
+          diagnostic = diag::type_is_not_a_class;
+          diagnosticNote = diag::anyobject_requirement;
+          requirementFailure = true;
+        }
+        break;
 
       case RequirementKind::Superclass:
         // Superclass requirements.
diff --git a/lib/Sema/TypeCheckProtocol.cpp b/lib/Sema/TypeCheckProtocol.cpp
index d20e1db..38227c5 100644
--- a/lib/Sema/TypeCheckProtocol.cpp
+++ b/lib/Sema/TypeCheckProtocol.cpp
@@ -1796,8 +1796,8 @@
 
   // If we already recoded this type witness, there's nothing to do.
   if (Conformance->hasTypeWitness(assocType)) {
-    assert(Conformance->getTypeWitness(assocType, nullptr)
-             ->isEqual(type) && "Conflicting type witness deductions");
+    assert(Conformance->getTypeWitness(assocType, nullptr)->isEqual(type) &&
+           "Conflicting type witness deductions");
     return;
   }
 
@@ -2656,8 +2656,12 @@
   auto *depTy = DependentMemberType::get(proto->getSelfInterfaceType(),
                                          assocType);
 
+  if (type->hasError())
+    return ErrorType::get(tc.Context);
+
   Type contextType = type->hasTypeParameter() ? dc->mapTypeIntoContext(type)
                                               : type;
+
   if (auto superclass = genericSig->getSuperclassBound(depTy)) {
     if (!superclass->isExactSuperclassOf(contextType))
       return superclass;
@@ -2688,11 +2692,9 @@
     }
   }
 
-  if (genericSig->requiresClass(depTy)) {
-    if (!contextType->isObjCExistentialType() &&
-        !contextType->mayHaveSuperclass())
-      return CheckTypeWitnessResult(tc.Context.getAnyObjectType());
-  }
+  if (genericSig->requiresClass(depTy) &&
+      !contextType->satisfiesClassConstraint())
+    return CheckTypeWitnessResult(tc.Context.getAnyObjectType());
 
   // Success!
   return CheckTypeWitnessResult();
@@ -2747,6 +2749,16 @@
     }
   }
 
+  // If there are no viable witnesses, and all nonviable candidates came from
+  // protocol extensions, treat this as "missing".
+  if (viable.empty() &&
+      std::find_if(nonViable.begin(), nonViable.end(),
+                   [](const std::pair<TypeDecl *, CheckTypeWitnessResult> &x) {
+                     return x.first->getDeclContext()
+                        ->getAsProtocolOrProtocolExtensionContext() == nullptr;
+                   }) == nonViable.end())
+    return ResolveWitnessResult::Missing;
+
   // If there is a single viable candidate, form a substitution for it.
   if (viable.size() == 1) {
     auto interfaceType = viable.front().second;
@@ -2781,7 +2793,8 @@
     [nonViable](NormalProtocolConformance *conformance) {
       auto &diags = conformance->getDeclContext()->getASTContext().Diags;
       for (auto candidate : nonViable) {
-        if (candidate.first->getDeclaredInterfaceType()->hasError())
+        if (candidate.first->getDeclaredInterfaceType()->hasError() ||
+            candidate.second.isError())
           continue;
 
         diags.diagnose(
diff --git a/lib/Sema/TypeCheckProtocol.h b/lib/Sema/TypeCheckProtocol.h
index 375dd9d..d4cf20d 100644
--- a/lib/Sema/TypeCheckProtocol.h
+++ b/lib/Sema/TypeCheckProtocol.h
@@ -78,7 +78,9 @@
   bool isConformanceRequirement() const {
     return Requirement->isExistentialType();
   }
-
+  bool isError() const {
+    return Requirement->is<ErrorType>();
+  }
   explicit operator bool() const { return !Requirement.isNull(); }
 };
 
diff --git a/lib/Sema/TypeCheckProtocolInference.cpp b/lib/Sema/TypeCheckProtocolInference.cpp
index 055318d..45bd357 100644
--- a/lib/Sema/TypeCheckProtocolInference.cpp
+++ b/lib/Sema/TypeCheckProtocolInference.cpp
@@ -818,7 +818,7 @@
 
   if (auto failed = checkTypeWitness(tc, dc, proto, assocType, defaultType)) {
     // Record the failure, if we haven't seen one already.
-    if (!failedDefaultedAssocType) {
+    if (!failedDefaultedAssocType && !failed.isError()) {
       failedDefaultedAssocType = defaultedAssocType;
       failedDefaultedWitness = defaultType;
       failedDefaultedResult = failed;
@@ -1680,6 +1680,9 @@
         diags.diagnose(assocType, diag::bad_associated_type_deduction,
                        assocType->getFullName(), proto->getFullName());
         for (const auto &failed : failedSet) {
+          if (failed.Result.isError())
+            continue;
+
           diags.diagnose(failed.Witness,
                          diag::associated_type_deduction_witness_failed,
                          failed.Requirement->getFullName(),
diff --git a/lib/Sema/TypeCheckType.cpp b/lib/Sema/TypeCheckType.cpp
index 1e439ef..e6ab389 100644
--- a/lib/Sema/TypeCheckType.cpp
+++ b/lib/Sema/TypeCheckType.cpp
@@ -223,8 +223,7 @@
                                                Type dynamicType,
                                                Type valueType) {
   // We can only bridge from class or Objective-C existential types.
-  if (!dynamicType->isObjCExistentialType() &&
-      !dynamicType->mayHaveSuperclass())
+  if (!dynamicType->satisfiesClassConstraint())
     return Type();
 
   // If the value type cannot be bridged, we're done.
diff --git a/stdlib/public/SDK/ARKit/ARKit.swift b/stdlib/public/SDK/ARKit/ARKit.swift
index a2baa6a..6e77654 100644
--- a/stdlib/public/SDK/ARKit/ARKit.swift
+++ b/stdlib/public/SDK/ARKit/ARKit.swift
@@ -27,6 +27,10 @@
             
             /** Tracking is limited due to a lack of features visible to the camera. */
             case insufficientFeatures
+
+            /** Tracking is limited due to a relocalization in progress. */
+            @available(iOS, introduced: 11.3)
+            case relocalizing
         }
         
         /** Tracking is not available. */
@@ -49,10 +53,20 @@
         case .limited:
             let reason: TrackingState.Reason
             
-            switch __trackingStateReason {
-            case .initializing: reason = .initializing
-            case .excessiveMotion: reason = .excessiveMotion
-            default: reason = .insufficientFeatures
+            if #available(iOS 11.3, *) {
+                switch __trackingStateReason {
+                case .initializing: reason = .initializing
+                case .relocalizing: reason = .relocalizing
+                case .excessiveMotion: reason = .excessiveMotion
+                default: reason = .insufficientFeatures
+                }
+            }
+            else {
+                switch __trackingStateReason {
+                case .initializing: reason = .initializing
+                case .excessiveMotion: reason = .excessiveMotion
+                default: reason = .insufficientFeatures
+                }
             }
             
             return .limited(reason)
@@ -105,3 +119,38 @@
         return Array(buffer)
     }
 }
+
+@available(iOS, introduced: 11.3)
+extension ARPlaneGeometry {
+    /**
+     The mesh vertices of the geometry.
+     */
+    @nonobjc public var vertices: [vector_float3] {
+        let buffer = UnsafeBufferPointer(start: __vertices, count: Int(__vertexCount))
+        return Array(buffer)
+    }
+    
+    /**
+     The texture coordinates of the geometry.
+     */
+    @nonobjc public var textureCoordinates: [vector_float2] {
+        let buffer = UnsafeBufferPointer(start: __textureCoordinates, count: Int(__textureCoordinateCount))
+        return Array(buffer)
+    }
+    
+    /**
+     The triangle indices of the geometry.
+     */
+    @nonobjc public var triangleIndices: [Int16] {
+        let buffer = UnsafeBufferPointer(start: __triangleIndices, count: Int(triangleCount * 3))
+        return Array(buffer)
+    }
+    
+    /**
+     The vertices of the geometry's outermost boundary.
+     */
+    @nonobjc public var boundaryVertices: [vector_float3] {
+        let buffer = UnsafeBufferPointer(start: __boundaryVertices, count: Int(__boundaryVertexCount))
+        return Array(buffer)
+    }
+}
diff --git a/test/Constraints/diagnostics.swift b/test/Constraints/diagnostics.swift
index a431c54..9940e2b 100644
--- a/test/Constraints/diagnostics.swift
+++ b/test/Constraints/diagnostics.swift
@@ -234,8 +234,8 @@
 
 // <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment
 protocol r21553065Protocol {}
-class r21553065Class<T : AnyObject> {}
-_ = r21553065Class<r21553065Protocol>()  // expected-error {{'r21553065Protocol' is not convertible to 'AnyObject'}}
+class r21553065Class<T : AnyObject> {} // expected-note{{requirement specified as 'T' : 'AnyObject'}}
+_ = r21553065Class<r21553065Protocol>()  // expected-error {{'r21553065Class' requires that 'r21553065Protocol' be a class type}}
 
 // Type variables not getting erased with nested closures
 struct Toe {
diff --git a/test/Constraints/generics.swift b/test/Constraints/generics.swift
index 8e9ae7d..6fd0152 100644
--- a/test/Constraints/generics.swift
+++ b/test/Constraints/generics.swift
@@ -265,7 +265,9 @@
 struct FullyGeneric<Foo> {} // expected-note 11 {{'Foo' declared as parameter to type 'FullyGeneric'}} expected-note 1 {{generic type 'FullyGeneric' declared here}}
 
 struct AnyClassBound<Foo: AnyObject> {} // expected-note {{'Foo' declared as parameter to type 'AnyClassBound'}} expected-note {{generic type 'AnyClassBound' declared here}}
+// expected-note@-1{{requirement specified as 'Foo' : 'AnyObject'}}
 struct AnyClassBound2<Foo> where Foo: AnyObject {} // expected-note {{'Foo' declared as parameter to type 'AnyClassBound2'}}
+// expected-note@-1{{requirement specified as 'Foo' : 'AnyObject' [with Foo = Any]}}
 
 struct ProtoBound<Foo: SubProto> {} // expected-note {{'Foo' declared as parameter to type 'ProtoBound'}} expected-note {{generic type 'ProtoBound' declared here}}
 struct ProtoBound2<Foo> where Foo: SubProto {} // expected-note {{'Foo' declared as parameter to type 'ProtoBound2'}}
@@ -301,11 +303,11 @@
   _ = FullyGeneric<Any>()
 
   _ = AnyClassBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<AnyObject>}}
-  _ = AnyClassBound<Any>() // expected-error {{'Any' is not convertible to 'AnyObject'}}
+  _ = AnyClassBound<Any>() // expected-error {{'AnyClassBound' requires that 'Any' be a class type}}
   _ = AnyClassBound<AnyObject>()
 
   _ = AnyClassBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{21-21=<AnyObject>}}
-  _ = AnyClassBound2<Any>() // expected-error {{'Any' is not convertible to 'AnyObject'}}
+  _ = AnyClassBound2<Any>() // expected-error {{'AnyClassBound2' requires that 'Any' be a class type}}
   _ = AnyClassBound2<AnyObject>()
 
   _ = ProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{17-17=<<#Foo: SubProto#>>}}
diff --git a/test/Constraints/same_types.swift b/test/Constraints/same_types.swift
index b22ae3b..210c8de 100644
--- a/test/Constraints/same_types.swift
+++ b/test/Constraints/same_types.swift
@@ -1,7 +1,7 @@
 // RUN: %target-typecheck-verify-swift -verify-ignore-unknown
 
 protocol Fooable {
-  associatedtype Foo
+  associatedtype Foo // expected-note{{protocol requires nested type 'Foo'; do you want to add it?}}
 
   var foo: Foo { get }
 }
@@ -148,7 +148,7 @@
 
 struct Brunch<U : Fooable> where U.Foo == X {}
 
-struct BadFooable : Fooable {
+struct BadFooable : Fooable { // expected-error{{type 'BadFooable' does not conform to protocol 'Fooable'}}
   typealias Foo = DoesNotExist // expected-error{{use of undeclared type 'DoesNotExist'}}
   var foo: Foo { while true {} }
 }
diff --git a/test/Generics/class_constraint.swift b/test/Generics/class_constraint.swift
new file mode 100644
index 0000000..473a4d8
--- /dev/null
+++ b/test/Generics/class_constraint.swift
@@ -0,0 +1,27 @@
+// RUN: %target-typecheck-verify-swift
+
+struct X<T: AnyObject> { } // expected-note 4{{requirement specified as 'T' : 'AnyObject'}}
+
+class C { }
+struct S { }
+
+protocol P { }
+
+let okay0: X<C>
+
+struct Y<T: AnyObject> {
+  let okay1: X<T>
+}
+
+struct Y2<T: C> {
+  let okay2: X<T>
+}
+
+let bad0: X<C & P> // expected-error{{'X' requires that 'C & P' be a class type}}
+let bad1: X<P> // expected-error{{'X' requires that 'P' be a class type}}
+let bad2: X<S> // expected-error{{'X' requires that 'S' be a class type}}
+
+struct Z<U> {
+  let bad3: X<U> // expected-error{{'X' requires that 'U' be a class type}}
+}
+
diff --git a/test/Generics/existential_restrictions.swift b/test/Generics/existential_restrictions.swift
index d109ccf..b13ca76 100644
--- a/test/Generics/existential_restrictions.swift
+++ b/test/Generics/existential_restrictions.swift
@@ -53,7 +53,7 @@
 class GOP<T : OP> {}
 class GCP<T : CP> {}
 class GSP<T : SP> {}
-class GAO<T : AnyObject> {}
+class GAO<T : AnyObject> {} // expected-note 2{{requirement specified as 'T' : 'AnyObject'}}
 
 func blackHole(_ t: Any) {}
 
@@ -61,9 +61,9 @@
   blackHole(GP<P>()) // expected-error{{using 'P' as a concrete type conforming to protocol 'P' is not supported}}
   blackHole(GOP<OP>())
   blackHole(GCP<CP>()) // expected-error{{using 'CP' as a concrete type conforming to protocol 'CP' is not supported}}
-  blackHole(GAO<P>()) // expected-error{{'P' is not convertible to 'AnyObject'}}
+  blackHole(GAO<P>()) // expected-error{{'GAO' requires that 'P' be a class type}}
   blackHole(GAO<OP>())
-  blackHole(GAO<CP>()) // expected-error{{'CP' is not convertible to 'AnyObject'}}
+  blackHole(GAO<CP>()) // expected-error{{'GAO' requires that 'CP' be a class type}}
   blackHole(GSP<SP>()) // expected-error{{'SP' cannot be used as a type conforming to protocol 'SP' because 'SP' has static requirements}}
   blackHole(GAO<AnyObject>())
 }
diff --git a/test/Interpreter/conditional_conformances_warning.swift b/test/Interpreter/conditional_conformances_warning.swift
index 37a0d49..6b3695d 100644
--- a/test/Interpreter/conditional_conformances_warning.swift
+++ b/test/Interpreter/conditional_conformances_warning.swift
@@ -1,6 +1,7 @@
 // RUN: rm -rf %t  &&  mkdir -p %t
 // RUN: %target-build-swift %s -o %t/a.out
 // RUN: %target-run %t/a.out 2>&1 | %FileCheck %s -check-prefix=CHECK_WARNINGS
+// REQUIRES: executable_test
 protocol P {
   func foo()
 }
diff --git a/test/SILGen/protocols.swift b/test/SILGen/protocols.swift
index 171acba..de3788c 100644
--- a/test/SILGen/protocols.swift
+++ b/test/SILGen/protocols.swift
@@ -415,6 +415,27 @@
 // CHECK:      [[TEMPORARY:%.*]] = address_to_pointer [[TEMPORARY_ADDR]] : $*Int to $Builtin.RawPointer
 // CHECK:      apply [[CALLBACK]]<T>
 
+public struct Val {
+  public var x: Int = 0
+}
+
+public protocol Proto {
+  var val: Val { get nonmutating set}
+}
+
+public func test(_ p: Proto) {
+  p.val.x += 1
+}
+
+// CHECK-LABEL: sil @_T09protocols4test{{.*}}: $@convention(thin) (@in Proto) -> ()
+// CHECK: [[OPEN:%.*]] = open_existential_addr immutable_access
+// CHECK: [[MAT:%.*]] = witness_method $@opened("{{.*}}") Proto, #Proto.val!materializeForSet
+// CHECK: [[BUF:%.*]] = apply [[MAT]]
+// CHECK: [[WB:%.*]] = pointer_to_thin_function
+// This use looks like it is mutating but really is not. We use to assert in the SIL verifier.
+// CHECK: apply [[WB]]{{.*}}({{.*}}[[OPEN]]
+// CHECK: return
+
 // CHECK-LABEL: sil_witness_table hidden ClassWithGetter: PropertyWithGetter module protocols {
 // CHECK-NEXT:  method #PropertyWithGetter.a!getter.1: {{.*}} : @_T09protocols15ClassWithGetterCAA08PropertycD0A2aDP1aSivgTW
 // CHECK-NEXT: }
diff --git a/test/SILOptimizer/bridged_casts_crash.sil b/test/SILOptimizer/bridged_casts_crash.sil
new file mode 100644
index 0000000..cffcaa5
--- /dev/null
+++ b/test/SILOptimizer/bridged_casts_crash.sil
@@ -0,0 +1,45 @@
+// RUN: %target-sil-opt -assume-parsing-unqualified-ownership-sil -performance-constant-propagation %s | %FileCheck %s
+
+// REQUIRES: objc_interop
+
+sil_stage canonical
+
+import Builtin
+import Swift
+import Foundation
+
+class TestObjCKeyTy : NSObject {
+  override init()
+}
+struct TestBridgedKeyTy : _ObjectiveCBridgeable {
+  func _bridgeToObjectiveC() -> TestObjCKeyTy
+  static func _forceBridgeFromObjectiveC(_ x: TestObjCKeyTy, result: inout TestBridgedKeyTy?)
+  static func _conditionallyBridgeFromObjectiveC(_ x: TestObjCKeyTy, result: inout TestBridgedKeyTy?) -> Bool
+  static func _unconditionallyBridgeFromObjectiveC(_ source: TestObjCKeyTy?) -> TestBridgedKeyTy
+}
+
+// Test that we don't crash in the verifier because of a critical edge
+
+// CHECK-LABEL: testit
+// CHECK: checked_cast_br
+sil @testit : $@convention(thin) (@owned NSObject) -> () {
+bb0(%0 : $NSObject):
+  %73 = alloc_stack $NSObject
+  store %0 to %73 : $*NSObject
+  %75 = alloc_stack $Optional<TestBridgedKeyTy>
+  %76 = init_enum_data_addr %75 : $*Optional<TestBridgedKeyTy>, #Optional.some!enumelt.1
+  %77 = load %73 : $*NSObject
+  checked_cast_addr_br take_always NSObject in %73 : $*NSObject to TestBridgedKeyTy in %76 : $*TestBridgedKeyTy, bb1, bb2
+
+bb1:
+  br bb3
+
+bb2:
+  br bb3
+
+bb3:
+  dealloc_stack %75 : $*Optional<TestBridgedKeyTy>
+  dealloc_stack %73 : $*NSObject
+  %r = tuple ()
+  return %r : $()
+}
diff --git a/test/SourceKit/CursorInfo/rdar_35819975.swift b/test/SourceKit/CursorInfo/rdar_35819975.swift
new file mode 100644
index 0000000..880489a
--- /dev/null
+++ b/test/SourceKit/CursorInfo/rdar_35819975.swift
@@ -0,0 +1,13 @@
+// Checks that we don't crash
+// RUN: %sourcekitd-test -req=cursor -pos=10:5 %s -- %s | %FileCheck %s
+// RUN: %sourcekitd-test -req=cursor -pos=11:11 %s -- %s | %FileCheck --check-prefix=CHECK2 %s
+// CHECK: source.lang.swift.ref.class
+// CHECK2: source.lang.swift.ref.function.constructor
+
+class Bar<T> {
+  class Inner {}
+  func foo() {
+    Inner()
+    Inner.init()
+  }
+}
diff --git a/test/decl/nested/type_in_function.swift b/test/decl/nested/type_in_function.swift
index ab62acb..a0c6fde 100644
--- a/test/decl/nested/type_in_function.swift
+++ b/test/decl/nested/type_in_function.swift
@@ -23,7 +23,7 @@
 }
 
 protocol Racoon {
-  associatedtype Stripes
+  associatedtype Stripes // expected-note{{protocol requires nested type 'Stripes'; do you want to add it?}}
 }
 
 // Types inside generic functions -- not supported yet
@@ -117,7 +117,7 @@
   }
 
   func middleFunction() {
-    struct ConformingType : Racoon {
+    struct ConformingType : Racoon { // expected-error{{type 'ConformingType' does not conform to protocol 'Racoon'}}
     // expected-error@-1 {{type 'ConformingType' cannot be nested in generic function 'middleFunction()'}}
       typealias Stripes = A
     }
diff --git a/test/decl/protocol/req/associated_type_inference.swift b/test/decl/protocol/req/associated_type_inference.swift
index 5954131..187b2d0 100644
--- a/test/decl/protocol/req/associated_type_inference.swift
+++ b/test/decl/protocol/req/associated_type_inference.swift
@@ -469,3 +469,34 @@
 protocol Q17 : P17 where T == Int { }
 
 struct S17 : Q17 { }
+
+// Typealiases from protocol extensions should not inhibit associated type
+// inference.
+protocol P18 {
+  associatedtype A
+}
+
+protocol P19 : P18 {
+  associatedtype B
+}
+
+extension P18 where Self: P19 {
+  typealias A = B
+}
+
+struct X18<A> : P18 { }
+
+// rdar://problem/16316115
+protocol HasAssoc {
+  associatedtype Assoc
+}
+
+struct DefaultAssoc {}
+
+protocol RefinesAssocWithDefault: HasAssoc {
+  associatedtype Assoc = DefaultAssoc
+}
+
+struct Foo: RefinesAssocWithDefault {
+}
+
diff --git a/tools/SourceKit/lib/SwiftLang/SwiftSourceDocInfo.cpp b/tools/SourceKit/lib/SwiftLang/SwiftSourceDocInfo.cpp
index a96492b..7d1a749 100644
--- a/tools/SourceKit/lib/SwiftLang/SwiftSourceDocInfo.cpp
+++ b/tools/SourceKit/lib/SwiftLang/SwiftSourceDocInfo.cpp
@@ -694,7 +694,6 @@
 static bool passCursorInfoForDecl(SourceFile* SF,
                                   const ValueDecl *VD,
                                   const ModuleDecl *MainModule,
-                                  const Type Ty,
                                   const Type ContainerTy,
                                   bool IsRef,
                                   bool RetrieveRefactoring,
@@ -710,7 +709,7 @@
     return true;
 
   SmallString<64> SS;
-  auto BaseType = findBaseTypeForReplacingArchetype(VD, Ty);
+  auto BaseType = findBaseTypeForReplacingArchetype(VD, ContainerTy);
   bool InSynthesizedExtension = false;
   if (BaseType) {
     if (auto Target = BaseType->getAnyNominal()) {
@@ -1293,11 +1292,17 @@
                                 CompInvok, Receiver);
         return;
       case CursorInfoKind::ValueRef: {
-        ValueDecl *VD = CursorInfo.CtorTyRef ? CursorInfo.CtorTyRef : CursorInfo.ValueD;
+        ValueDecl *VD = CursorInfo.ValueD;
+        Type ContainerType = CursorInfo.ContainerType;
+        if (CursorInfo.CtorTyRef) {
+          // Treat constructor calls, e.g. MyType(), as the type itself,
+          // rather than its constructor.
+          VD = CursorInfo.CtorTyRef;
+          ContainerType = Type();
+        }
         bool Failed = passCursorInfoForDecl(&AstUnit->getPrimarySourceFile(),
                                             VD, MainModule,
-                                            CursorInfo.ContainerType,
-                                            CursorInfo.ContainerType,
+                                            ContainerType,
                                             CursorInfo.IsRef,
                                             Actionables,
                                             CursorInfo,
@@ -1589,7 +1594,7 @@
           // FIXME: Should pass the main module for the interface but currently
           // it's not necessary.
           passCursorInfoForDecl(
-              /*SourceFile*/nullptr, Entity.Dcl, /*MainModule*/ nullptr, Type(),
+              /*SourceFile*/nullptr, Entity.Dcl, /*MainModule*/ nullptr,
               Type(), Entity.IsRef, Actionables, ResolvedCursorInfo(),
               /*OrigBufferID=*/None, SourceLoc(),
               {}, *this, Invok, {}, Receiver);
@@ -1780,7 +1785,7 @@
         }
         bool Failed =
             passCursorInfoForDecl(/*SourceFile*/nullptr, VD, MainModule, selfTy,
-                                  Type(), /*IsRef=*/false, false, ResolvedCursorInfo(),
+                                  /*IsRef=*/false, false, ResolvedCursorInfo(),
                                   BufferID, SourceLoc(), {}, Lang, CompInvok,
                                   PreviousASTSnaps, Receiver);
         if (Failed) {
diff --git a/validation-test/compiler_crashers_2_fixed/0138-rdar36449760.swift b/validation-test/compiler_crashers_2_fixed/0138-rdar36449760.swift
new file mode 100644
index 0000000..114d5b8
--- /dev/null
+++ b/validation-test/compiler_crashers_2_fixed/0138-rdar36449760.swift
@@ -0,0 +1,41 @@
+// RUN: not %target-swift-frontend %s -typecheck
+
+protocol A {
+  var question: String { get }
+
+  struct B {
+    var answer: Int = 42
+
+    func foo(a: A) {
+      _ = a.question
+    }
+  }
+}
+
+class C : A {
+  var question: String = "ultimate question"
+
+  func foo() -> B {}
+  func bar() -> A.B {}
+  func baz(b: B) {
+    _ = b.answer
+  }
+}
+
+class D : A {
+  var question: String = ""
+
+  struct E {
+    func baz(b: B) {
+      _ = b.answer
+    }
+  }
+}
+
+class F<T> : A {
+  var question: String = ""
+
+  func foo(b: B) {
+    _ = b.answer
+  }
+}
diff --git a/validation-test/compiler_crashers_2_fixed/0138-rdar36453271.swift b/validation-test/compiler_crashers_2_fixed/0138-rdar36453271.swift
new file mode 100644
index 0000000..580ea9e
--- /dev/null
+++ b/validation-test/compiler_crashers_2_fixed/0138-rdar36453271.swift
@@ -0,0 +1,13 @@
+// RUN: %target-swift-frontend %s -emit-ir -o 0
+
+extension Slice where Base == UnsafeBufferPointer<UInt16> {
+  var rebased: UnsafeBufferPointer<UInt16> {
+    return UnsafeBufferPointer(rebasing: self)
+  }
+}
+
+extension Slice where Base == UnsafeMutableBufferPointer<UInt16> {
+  var rebased: UnsafeMutableBufferPointer<UInt16> {
+    return UnsafeMutableBufferPointer(rebasing: self)
+  }
+}
diff --git a/validation-test/compiler_crashers_2_fixed/0140-sr6746.swift b/validation-test/compiler_crashers_2_fixed/0140-sr6746.swift
new file mode 100644
index 0000000..5388e11
--- /dev/null
+++ b/validation-test/compiler_crashers_2_fixed/0140-sr6746.swift
@@ -0,0 +1,8 @@
+// RUN: not %target-swift-frontend %s -typecheck
+struct Foo: Strideable {
+    // typealias Stride = Int
+    let x: Int
+
+    func distance(to other: Foo) -> Foo.Stride { return abs(other.x - x) }
+    func advanced(by n: Foo.Stride) -> Foo { return Foo(x: x + n) }
+}
diff --git a/validation-test/compiler_crashers/28769-conformance-gettypewitness-assoctype-nullptr-isequal-type-conflicting-type-witne.swift b/validation-test/compiler_crashers_fixed/28769-conformance-gettypewitness-assoctype-nullptr-isequal-type-conflicting-type-witne.swift
similarity index 85%
rename from validation-test/compiler_crashers/28769-conformance-gettypewitness-assoctype-nullptr-isequal-type-conflicting-type-witne.swift
rename to validation-test/compiler_crashers_fixed/28769-conformance-gettypewitness-assoctype-nullptr-isequal-type-conflicting-type-witne.swift
index 81e2b26..c19a806 100644
--- a/validation-test/compiler_crashers/28769-conformance-gettypewitness-assoctype-nullptr-isequal-type-conflicting-type-witne.swift
+++ b/validation-test/compiler_crashers_fixed/28769-conformance-gettypewitness-assoctype-nullptr-isequal-type-conflicting-type-witne.swift
@@ -5,6 +5,6 @@
 // See https://swift.org/LICENSE.txt for license information
 // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
 
-// REQUIRES: asserts
-// RUN: not --crash %target-swift-frontend %s -emit-ir
+
+// RUN: not %target-swift-frontend %s -emit-ir
 protocol P{{}func a{}typealias e}struct A:P{typealias e:Self.a{}typealias e:Self.a{}typealias e:P
diff --git a/validation-test/compiler_crashers/28854-known-typewitnesses-end-didnt-resolve-witness.swift b/validation-test/compiler_crashers_fixed/28854-known-typewitnesses-end-didnt-resolve-witness.swift
similarity index 84%
rename from validation-test/compiler_crashers/28854-known-typewitnesses-end-didnt-resolve-witness.swift
rename to validation-test/compiler_crashers_fixed/28854-known-typewitnesses-end-didnt-resolve-witness.swift
index e2bee9f..c20988b 100644
--- a/validation-test/compiler_crashers/28854-known-typewitnesses-end-didnt-resolve-witness.swift
+++ b/validation-test/compiler_crashers_fixed/28854-known-typewitnesses-end-didnt-resolve-witness.swift
@@ -5,8 +5,8 @@
 // See https://swift.org/LICENSE.txt for license information
 // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
 
-// REQUIRES: asserts
-// RUN: not --crash %target-swift-frontend %s -emit-ir
+
+// RUN: not %target-swift-frontend %s -emit-ir
 @objc protocol A
 {
 typealias a