Merge pull request #20557 from brentdax/this-is-why-swift-is-a-memory-safe-language

Fix lookupDirect() use-after-scope bugs
diff --git a/lib/ClangImporter/ImportDecl.cpp b/lib/ClangImporter/ImportDecl.cpp
index b74067c..5782247 100644
--- a/lib/ClangImporter/ImportDecl.cpp
+++ b/lib/ClangImporter/ImportDecl.cpp
@@ -7040,7 +7040,7 @@
 
   auto curObjCClass = cast<clang::ObjCInterfaceDecl>(classDecl->getClangDecl());
 
-  auto inheritConstructors = [&](ArrayRef<ValueDecl *> members,
+  auto inheritConstructors = [&](TinyPtrVector<ValueDecl *> members,
                                  Optional<CtorInitializerKind> kind) {
     const auto &languageVersion =
         Impl.SwiftContext.LangOpts.EffectiveLanguageVersion;
diff --git a/lib/SILOptimizer/Utils/CastOptimizer.cpp b/lib/SILOptimizer/Utils/CastOptimizer.cpp
index cd46b02..e16b917 100644
--- a/lib/SILOptimizer/Utils/CastOptimizer.cpp
+++ b/lib/SILOptimizer/Utils/CastOptimizer.cpp
@@ -354,17 +354,15 @@
 
   auto *NTD = Source.getNominalOrBoundGenericNominal();
   assert(NTD);
-  SmallVector<ValueDecl *, 4> FoundMembers;
-  ArrayRef<ValueDecl *> Members;
-  Members = NTD->lookupDirect(M.getASTContext().Id_bridgeToObjectiveC);
+  auto Members = NTD->lookupDirect(M.getASTContext().Id_bridgeToObjectiveC);
   if (Members.empty()) {
+    SmallVector<ValueDecl *, 4> FoundMembers;
     if (NTD->getDeclContext()->lookupQualified(
             NTD, M.getASTContext().Id_bridgeToObjectiveC,
             NLOptions::NL_ProtocolMembers, FoundMembers)) {
-      Members = FoundMembers;
       // Returned members are starting with the most specialized ones.
       // Thus, the first element is what we are looking for.
-      Members = Members.take_front(1);
+      Members.push_back(FoundMembers.front());
     }
   }
 
diff --git a/lib/Sema/CSDiag.cpp b/lib/Sema/CSDiag.cpp
index 02f91af..5627fd9 100644
--- a/lib/Sema/CSDiag.cpp
+++ b/lib/Sema/CSDiag.cpp
@@ -7084,7 +7084,7 @@
     return false;
   DeclName constrName = TC.getObjectLiteralConstructorName(E);
   assert(constrName);
-  ArrayRef<ValueDecl *> constrs = protocol->lookupDirect(constrName);
+  auto constrs = protocol->lookupDirect(constrName);
   if (constrs.size() != 1 || !isa<ConstructorDecl>(constrs.front()))
     return false;
   auto *constr = cast<ConstructorDecl>(constrs.front());
diff --git a/lib/Sema/CSGen.cpp b/lib/Sema/CSGen.cpp
index 3c9dae5..d1bdfd2 100644
--- a/lib/Sema/CSGen.cpp
+++ b/lib/Sema/CSGen.cpp
@@ -1306,7 +1306,7 @@
       // use the right labels before forming the call to the initializer.
       DeclName constrName = tc.getObjectLiteralConstructorName(expr);
       assert(constrName);
-      ArrayRef<ValueDecl *> constrs = protocol->lookupDirect(constrName);
+      auto constrs = protocol->lookupDirect(constrName);
       if (constrs.size() != 1 || !isa<ConstructorDecl>(constrs.front())) {
         tc.diagnose(protocol, diag::object_literal_broken_proto);
         return nullptr;