Merge pull request #12444 from gregomni/6097

diff --git a/lib/Sema/TypeCheckProtocol.cpp b/lib/Sema/TypeCheckProtocol.cpp
index 8149469..5aaab40 100644
--- a/lib/Sema/TypeCheckProtocol.cpp
+++ b/lib/Sema/TypeCheckProtocol.cpp
@@ -3991,7 +3991,7 @@
   Type model = conformance->getType();
   TypeSubstitutionMap substitutions = model->getMemberSubstitutions(witness);
   if (substitutions.empty())
-    return witness->getInterfaceType();
+    return witness->getInterfaceType()->getReferenceStorageReferent();
 
   Type type = witness->getInterfaceType();
   
diff --git a/test/Generics/associated_types.swift b/test/Generics/associated_types.swift
index cf00935..1d62fd1 100644
--- a/test/Generics/associated_types.swift
+++ b/test/Generics/associated_types.swift
@@ -199,3 +199,25 @@
     _ = B.A.isP
   }
 }
+
+// SR-6097
+protocol sr6097 {
+  associatedtype A : AnyObject
+  var aProperty: A { get }
+}
+
+class C1 {}
+class C2 : sr6097 {
+  unowned let aProperty: C1 // should deduce A == C1 despite 'unowned'
+  init() { fatalError() }
+}
+
+protocol sr6097_b {
+  associatedtype A : AnyObject
+  var aProperty: A? { get }
+}
+class C3 : sr6097_b {
+  weak var aProperty: C1? // and same here, despite 'weak'
+  init() { fatalError() }
+}
+