Merge pull request #4828 from apple/stdlib-improve-range-checking-for-strideable-indices

stdlib: Improve range checking in default implementations for strideable indices
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a478b66..04b05c9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -206,7 +206,7 @@
 
 * [SE-0131][]:
 
-  The standard library provides a new type `AnyHashable` for use in heterogenous
+  The standard library provides a new type `AnyHashable` for use in heterogeneous
   hashed collections. Untyped `NSDictionary` and `NSSet` APIs from Objective-C
   now import as `[AnyHashable: Any]` and `Set<AnyHashable>`.
 
@@ -561,7 +561,7 @@
 
 * [SE-0046][]:
 
-  Function parameters now have consistent labelling across all function
+  Function parameters now have consistent labeling across all function
   parameters. With this update the first parameter declarations will
   now match the existing behavior of the second and later parameters.
   This change makes the language simpler.
diff --git a/docs/PatternMatching.rst b/docs/PatternMatching.rst
index 935a870..9247fe9 100644
--- a/docs/PatternMatching.rst
+++ b/docs/PatternMatching.rst
@@ -25,7 +25,7 @@
   float and double; eventually maybe others.
 * Function types.
 * Tuples. Heterogeneous fixed-length products. Swift's system
-  provides two basic kinds of element: positional and labelled.
+  provides two basic kinds of element: positional and labeled.
 * Arrays. Homogeneous fixed-length aggregates.
 * Algebraic data types (ADTs), introduce by enum.  Nominal closed
   disjoint unions of heterogeneous types.
@@ -787,8 +787,8 @@
   *-pattern-tuple-element ::= *-pattern
   *-pattern-tuple-element ::= identifier '=' *-pattern
 
-Tuples are interesting because of the labelled / non-labelled
-distinction. Especially with labelled elements, it is really nice to
+Tuples are interesting because of the labeled / non-labeled
+distinction. Especially with labeled elements, it is really nice to
 be able to ignore all the elements you don't care about. This grammar
 permits some prefix or set of labels to be matched and the rest to be
 ignored.
diff --git a/docs/SIL.rst b/docs/SIL.rst
index 4444e7c..27bbfcb 100644
--- a/docs/SIL.rst
+++ b/docs/SIL.rst
@@ -440,7 +440,7 @@
     parameter.
 
 - A SIL function type declares the conventions for its parameters.
-  The parameters are written as an unlabelled tuple; the elements of that
+  The parameters are written as an unlabeled tuple; the elements of that
   tuple must be legal SIL types, optionally decorated with one of the
   following convention attributes.
 
@@ -482,7 +482,7 @@
   - Otherwise, the parameter is an unowned direct parameter.
 
 - A SIL function type declares the conventions for its results.
-  The results are written as an unlabelled tuple; the elements of that
+  The results are written as an unlabeled tuple; the elements of that
   tuple must be legal SIL types, optionally decorated with one of the
   following convention attributes.  Indirect and direct results may
   be interleaved.
diff --git a/docs/StdlibAPIGuidelines.rst b/docs/StdlibAPIGuidelines.rst
index ff6cacf..de7ca59 100644
--- a/docs/StdlibAPIGuidelines.rst
+++ b/docs/StdlibAPIGuidelines.rst
@@ -155,7 +155,7 @@
       func toInt() -> Int // OK
     }
 
-* Even unlabelled parameter names should be meaningful as they'll be
+* Even unlabeled parameter names should be meaningful as they'll be
   referred to in comments and visible in "generated headers"
   (cmd-click in Xcode):
 
diff --git a/include/swift/AST/ASTScope.h b/include/swift/AST/ASTScope.h
index f42c266..5a47b2e 100644
--- a/include/swift/AST/ASTScope.h
+++ b/include/swift/AST/ASTScope.h
@@ -188,7 +188,7 @@
 
       /// The next element that should be considered in the source file.
       ///
-      /// This accomodates the expansion of source files.
+      /// This accommodates the expansion of source files.
       mutable unsigned nextElement;
     } sourceFile;
 
@@ -613,7 +613,7 @@
   /// \seealso getDeclContext().
   DeclContext *getInnermostEnclosingDeclContext() const;
 
-  /// Retrueve the declarations whose names are directly bound by this scope.
+  /// Retrieve the declarations whose names are directly bound by this scope.
   ///
   /// The declarations bound in this scope aren't available in the immediate
   /// parent of this scope, but will still be visible in child scopes (unless
diff --git a/include/swift/AST/ArchetypeBuilder.h b/include/swift/AST/ArchetypeBuilder.h
index ef5be3f..4cdc4c1 100644
--- a/include/swift/AST/ArchetypeBuilder.h
+++ b/include/swift/AST/ArchetypeBuilder.h
@@ -543,7 +543,8 @@
   /// Add a conformance to this potential archetype.
   ///
   /// \returns true if the conformance was new, false if it already existed.
-  bool addConformance(ProtocolDecl *proto, const RequirementSource &source,
+  bool addConformance(ProtocolDecl *proto, bool updateExistingSource,
+                      const RequirementSource &source,
                       ArchetypeBuilder &builder);
 
   /// Retrieve the superclass of this archetype.
diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h
index 0eb7ccb..2938d95 100644
--- a/include/swift/AST/Decl.h
+++ b/include/swift/AST/Decl.h
@@ -1702,7 +1702,7 @@
   // Return the first variable initialized by this pattern.
   VarDecl *getAnchoringVarDecl() const;
 
-  // Retrieve the declaration context for the intializer.
+  // Retrieve the declaration context for the initializer.
   DeclContext *getInitContext() const { return InitContext; }
 
   /// Override the initializer context.
diff --git a/include/swift/AST/DiagnosticsSema.def b/include/swift/AST/DiagnosticsSema.def
index a3bcd49..8648cdb 100644
--- a/include/swift/AST/DiagnosticsSema.def
+++ b/include/swift/AST/DiagnosticsSema.def
@@ -908,10 +908,6 @@
 ERROR(attribute_requires_single_argument,none,
       "'%0' requires a function with one argument", (StringRef))
 
-ERROR(inout_cant_be_variadic,none,
-      "inout arguments cannot be variadic", ())
-ERROR(inout_only_parameter,none,
-      "'inout' is only valid in parameter lists", ())
 ERROR(var_parameter_not_allowed,none,
       "parameters may not have the 'var' specifier", ())
 
@@ -1841,10 +1837,12 @@
 // Type Check Attributes
 //------------------------------------------------------------------------------
 
-ERROR(attr_only_only_one_decl_kind,none,
+ERROR(attr_only_one_decl_kind,none,
       "%0 may only be used on '%1' declarations", (DeclAttribute,StringRef))
-ERROR(attr_only_only_on_parameters,none,
+ERROR(attr_only_on_parameters,none,
       "%0 may only be used on parameters", (StringRef))
+ERROR(attr_not_on_variadic_parameters,none,
+      "%0 may not be used on variadic parameters", (StringRef))
 
 
 ERROR(override_final,none,
@@ -2135,8 +2133,8 @@
       ())
 ERROR(inout_expr_outside_of_call,none,
       "'&' can only appear immediately in a call argument list", ())
-ERROR(collection_literal_heterogenous,none,
-      "heterogenous collection literal could only be inferred to %0; add"
+ERROR(collection_literal_heterogeneous,none,
+      "heterogeneous collection literal could only be inferred to %0; add"
       " explicit type annotation if this is intentional", (Type))
 ERROR(collection_literal_empty,none,
       "empty collection literal requires an explicit type", ())
diff --git a/include/swift/Remote/MetadataReader.h b/include/swift/Remote/MetadataReader.h
index 4f3203f..2def3a4 100644
--- a/include/swift/Remote/MetadataReader.h
+++ b/include/swift/Remote/MetadataReader.h
@@ -242,7 +242,7 @@
         if (element->getKind() != NodeKind::TupleElement)
           return BuiltType();
 
-        // If the tuple element is labelled, add its label to 'labels'.
+        // If the tuple element is labeled, add its label to 'labels'.
         unsigned typeChildIndex = 0;
         if (element->getChild(0)->getKind() == NodeKind::TupleElementName) {
           // Add spaces to terminate all the previous labels if this
diff --git a/include/swift/SIL/SILInstruction.h b/include/swift/SIL/SILInstruction.h
index b466a37..293a38b 100644
--- a/include/swift/SIL/SILInstruction.h
+++ b/include/swift/SIL/SILInstruction.h
@@ -198,7 +198,7 @@
   /// Return the array of mutable operands for this instruction.
   MutableArrayRef<Operand> getAllOperands();
 
-  /// Return the array of mutable type depedent operands for this instruction.
+  /// Return the array of mutable type dependent operands for this instruction.
   MutableArrayRef<Operand> getTypeDependentOperands();
 
   unsigned getNumOperands() const { return getAllOperands().size(); }
diff --git a/include/swift/SIL/SILVisitor.h b/include/swift/SIL/SILVisitor.h
index d644c9a..313ac0d 100644
--- a/include/swift/SIL/SILVisitor.h
+++ b/include/swift/SIL/SILVisitor.h
@@ -31,7 +31,7 @@
 public:
   ImplClass &asImpl() { return static_cast<ImplClass &>(*this); }
 
-  // Peform any required pre-processing before visiting.
+  // Perform any required pre-processing before visiting.
   // Sub-classes can override it to provide their custom
   // pre-processing steps.
   void beforeVisit(ValueBase *V) {
diff --git a/include/swift/SILOptimizer/Analysis/EpilogueARCAnalysis.h b/include/swift/SILOptimizer/Analysis/EpilogueARCAnalysis.h
index 36ed8f5..4b655c5 100644
--- a/include/swift/SILOptimizer/Analysis/EpilogueARCAnalysis.h
+++ b/include/swift/SILOptimizer/Analysis/EpilogueARCAnalysis.h
@@ -87,7 +87,7 @@
   /// The exit blocks of the function.
   llvm::SmallPtrSet<SILBasicBlock *, 2> ExitBlocks;
 
-  /// Return true if this is a function exitting block this epilogue ARC
+  /// Return true if this is a function exiting block this epilogue ARC
   /// matcher is interested in. 
   bool isInterestedFunctionExitingBlock(SILBasicBlock *BB) {
     if (EpilogueARCKind::Release == Kind)  
diff --git a/include/swift/SILOptimizer/PassManager/PassManager.h b/include/swift/SILOptimizer/PassManager/PassManager.h
index 3916716..fdac151 100644
--- a/include/swift/SILOptimizer/PassManager/PassManager.h
+++ b/include/swift/SILOptimizer/PassManager/PassManager.h
@@ -77,7 +77,7 @@
 
   /// Stores for each function the number of levels of specializations it is
   /// derived from an original function. E.g. if a function is a signature
-  /// optimized specialization of a generic specialiation, it has level 2.
+  /// optimized specialization of a generic specialization, it has level 2.
   /// This is used to avoid an infinite amount of functions pushed on the
   /// worklist (e.g. caused by a bug in a specializing optimization).
   llvm::DenseMap<SILFunction *, int> DerivationLevels;
diff --git a/lib/AST/ASTDumper.cpp b/lib/AST/ASTDumper.cpp
index 28cb573..7b5be24 100644
--- a/lib/AST/ASTDumper.cpp
+++ b/lib/AST/ASTDumper.cpp
@@ -539,21 +539,23 @@
       if (GenericTypeDecl *GTD = dyn_cast<GenericTypeDecl>(VD))
         printGenericParameters(OS, GTD->getGenericParams());
 
-      OS << " type='";
-      if (VD->hasType())
-        VD->getType().print(OS);
-      else
-        OS << "<null type>";
+      if (!VD->hasType() || !VD->getType()->is<PolymorphicFunctionType>()) {
+        OS << " type='";
+        if (VD->hasType())
+          VD->getType().print(OS);
+        else
+          OS << "<null type>";
+        OS << '\'';
+      }
 
       if (VD->hasInterfaceType() &&
           (!VD->hasType() ||
            VD->getInterfaceType().getPointer() != VD->getType().getPointer())) {
-        OS << "' interface type='";
+        OS << " interface type='";
         VD->getInterfaceType()->getCanonicalType().print(OS);
+        OS << '\'';
       }
 
-      OS << '\'';
-
       if (VD->hasAccessibility()) {
         OS << " access=";
         switch (VD->getFormalAccess()) {
@@ -1519,7 +1521,7 @@
     Indent -= 2;
   }
 
-  void printRecLabelled(Expr *E, StringRef label) {
+  void printRecLabeled(Expr *E, StringRef label) {
     Indent += 2;
     OS.indent(Indent);
     OS << '(' << label << '\n';
@@ -1941,11 +1943,11 @@
     printRec(E->getSubExpr());
     if (auto keyConversion = E->getKeyConversion()) {
       OS << '\n';
-      printRecLabelled(keyConversion.Conversion, "key_conversion");
+      printRecLabeled(keyConversion.Conversion, "key_conversion");
     }
     if (auto valueConversion = E->getValueConversion()) {
       OS << '\n';
-      printRecLabelled(valueConversion.Conversion, "value_conversion");
+      printRecLabeled(valueConversion.Conversion, "value_conversion");
     }
     OS << ')';
   }
diff --git a/lib/AST/ArchetypeBuilder.cpp b/lib/AST/ArchetypeBuilder.cpp
index 20a6077..1374a54 100644
--- a/lib/AST/ArchetypeBuilder.cpp
+++ b/lib/AST/ArchetypeBuilder.cpp
@@ -269,18 +269,20 @@
 
 bool ArchetypeBuilder::PotentialArchetype::addConformance(
        ProtocolDecl *proto, 
+       bool updateExistingSource,
        const RequirementSource &source,
        ArchetypeBuilder &builder) {
   auto rep = getRepresentative();
   if (rep != this)
-    return rep->addConformance(proto, source, builder);
+    return rep->addConformance(proto, updateExistingSource, source, builder);
 
   // Check whether we already know about this conformance.
   auto known = ConformsTo.find(proto);
   if (known != ConformsTo.end()) {
     // We already have this requirement. Update the requirement source
     // appropriately.
-    updateRequirementSource(known->second, source);
+    if (updateExistingSource)
+      updateRequirementSource(known->second, source);
     return false;
   }
 
@@ -915,7 +917,7 @@
   auto T = PAT->getRepresentative();
 
   // Add the requirement, if we haven't done so already.
-  if (!T->addConformance(Proto, Source, *this))
+  if (!T->addConformance(Proto, /*updateExistingSource=*/true, Source, *this))
     return false;
 
   RequirementSource InnerSource(RequirementSource::Redundant, Source.getLoc());
@@ -1186,7 +1188,20 @@
     T1->ArchetypeOrConcreteType = NestedType::forConcreteType(concrete2);
     T1->SameTypeSource = T2->SameTypeSource;
   }
-  
+
+  // Don't mark requirements as redundant if they come from one of our
+  // child archetypes. This is a targeted fix -- more general cases
+  // continue to break. In general, we need to detect cycles in the
+  // archetype graph and not propagate requirement source information
+  // along back edges.
+  bool creatingCycle = false;
+  auto T2Parent = T2;
+  while(T2Parent != nullptr) {
+    if (T2Parent->getRepresentative() == T1)
+      creatingCycle = true;
+    T2Parent = T2Parent->getParent();
+  }
+
   // Make T1 the representative of T2, merging the equivalence classes.
   T2->Representative = T1;
   T2->SameTypeSource = Source;
@@ -1197,7 +1212,8 @@
 
   // Add all of the protocol conformance requirements of T2 to T1.
   for (auto conforms : T2->ConformsTo) {
-    T1->addConformance(conforms.first, conforms.second, *this);
+    T1->addConformance(conforms.first, /*updateExistingSource=*/!creatingCycle,
+                       conforms.second, *this);
   }
 
   // Recursively merge the associated types of T2 into T1.
@@ -1350,7 +1366,8 @@
     assocType->setInvalid();
 
     // FIXME: Drop this protocol.
-    pa->addConformance(proto, RequirementSource(kind, loc), *this);
+    pa->addConformance(proto, /*updateExistingSource=*/true,
+                       RequirementSource(kind, loc), *this);
   };
 
   // If the abstract type parameter already has an archetype assigned,
@@ -1497,7 +1514,7 @@
     PotentialArchetype *pa = resolveArchetype(req.getFirstType());
     assert(pa && "Re-introducing invalid requirement");
     // FIXME: defensively return if assertions are disabled until we figure out
-    // how this sitatuaion can occur and fix it properly.
+    // how this situation can occur and fix it properly.
     if (!pa)
       return;
 
diff --git a/lib/AST/DiagnosticEngine.cpp b/lib/AST/DiagnosticEngine.cpp
index 281217d..f891106 100644
--- a/lib/AST/DiagnosticEngine.cpp
+++ b/lib/AST/DiagnosticEngine.cpp
@@ -380,8 +380,8 @@
 
     // If we're complaining about a function type, don't "aka" just because of
     // differences in the argument or result types.
-    if (showAKA && type->is<FunctionType>() &&
-        isa<FunctionType>(type.getPointer()))
+    if (showAKA && type->is<AnyFunctionType>() &&
+        isa<AnyFunctionType>(type.getPointer()))
       showAKA = false;
 
     // Don't unwrap intentional sugar types like T? or [T].
diff --git a/lib/AST/Module.cpp b/lib/AST/Module.cpp
index a0598b8..d311a01 100644
--- a/lib/AST/Module.cpp
+++ b/lib/AST/Module.cpp
@@ -673,7 +673,7 @@
   if (auto archetype = type->getAs<ArchetypeType>()) {
 
     // The archetype builder drops conformance requirements that are made
-    // redundant by a superclass requirement, so check for a cocnrete
+    // redundant by a superclass requirement, so check for a concrete
     // conformance first, since an abstract conformance might not be
     // able to be resolved by a substitution that makes the archetype
     // concrete.
diff --git a/lib/AST/NameLookup.cpp b/lib/AST/NameLookup.cpp
index 2934c47..db5513a 100644
--- a/lib/AST/NameLookup.cpp
+++ b/lib/AST/NameLookup.cpp
@@ -580,7 +580,7 @@
           continue;
         }
 
-        // Top-level declarations have no lokup of their own.
+        // Top-level declarations have no lookup of their own.
         if (isa<TopLevelCodeDecl>(dc)) continue;
 
         // Typealiases have no lookup of their own.
diff --git a/lib/FrontendTool/FrontendTool.cpp b/lib/FrontendTool/FrontendTool.cpp
index b4f5089..c5db150 100644
--- a/lib/FrontendTool/FrontendTool.cpp
+++ b/lib/FrontendTool/FrontendTool.cpp
@@ -623,7 +623,7 @@
     if (Info.ID == diag::init_not_instance_member.ID)
       return false;
     // Renaming enum cases interacts poorly with the swift migrator by
-    // reverting changes made by the mgirator.
+    // reverting changes made by the migrator.
     if (Info.ID == diag::could_not_find_enum_case.ID)
       return false;
 
diff --git a/lib/IRGen/GenReflection.cpp b/lib/IRGen/GenReflection.cpp
index 0110eea..1d7f457 100644
--- a/lib/IRGen/GenReflection.cpp
+++ b/lib/IRGen/GenReflection.cpp
@@ -633,7 +633,10 @@
   MetadataSourceMap getMetadataSourceMap() {
     MetadataSourceMap SourceMap;
 
-    if (!OrigCalleeType->isPolymorphic())
+    // Generic parameters of pseudogeneric functions do not have
+    // runtime metadata.
+    if (!OrigCalleeType->isPolymorphic() ||
+        OrigCalleeType->isPseudogeneric())
       return SourceMap;
 
     // Any generic parameters that are not fulfilled are passed in via the
@@ -703,6 +706,19 @@
 
     for (auto ElementType : getElementTypes()) {
       auto SwiftType = ElementType.getSwiftRValueType();
+
+      // Erase pseudogeneric captures down to AnyObject.
+      if (OrigCalleeType->isPseudogeneric()) {
+        SwiftType = SwiftType.transform([&](Type t) -> Type {
+          if (auto *archetype = t->getAs<ArchetypeType>()) {
+            assert(archetype->requiresClass() && "don't know what to do");
+            return IGM.Context.getProtocol(KnownProtocolKind::AnyObject)
+                ->getDeclaredType();
+          }
+          return t;
+        })->getCanonicalType();
+      }
+
       auto InterfaceType = Caller.mapTypeOutOfContext(SwiftType);
       CaptureTypes.push_back(InterfaceType->getCanonicalType());
     }
diff --git a/lib/IRGen/IRGenSIL.cpp b/lib/IRGen/IRGenSIL.cpp
index e5c10cd..126f557 100644
--- a/lib/IRGen/IRGenSIL.cpp
+++ b/lib/IRGen/IRGenSIL.cpp
@@ -606,7 +606,7 @@
                   DVI->getValue(), 0, DVI->getVariable(), DVI->getExpression(),
                   DVI->getDebugLoc(), &*CurBB->getFirstInsertionPt());
             else
-              // Found all dbg.value instrinsics describing this location.
+              // Found all dbg.value intrinsics describing this location.
               break;
         }
       }
diff --git a/lib/Parse/ParseExpr.cpp b/lib/Parse/ParseExpr.cpp
index 1358f7f..25d67a6 100644
--- a/lib/Parse/ParseExpr.cpp
+++ b/lib/Parse/ParseExpr.cpp
@@ -2461,7 +2461,7 @@
                                       rightLoc,
                                       trailingClosure);
 
-  // A tuple with a single, unlabelled element is just parentheses.
+  // A tuple with a single, unlabeled element is just parentheses.
   if (subExprs.size() == 1 &&
       (subExprNames.empty() || subExprNames[0].empty())) {
     return makeParserResult(
diff --git a/lib/SILGen/SILGenBridging.cpp b/lib/SILGen/SILGenBridging.cpp
index 8dfe156..7f38796 100644
--- a/lib/SILGen/SILGenBridging.cpp
+++ b/lib/SILGen/SILGenBridging.cpp
@@ -337,29 +337,43 @@
             blockInterfaceTy->getParameters().end(),
             std::back_inserter(params));
 
-  // The block invoke function must be pseudogeneric. This should be OK for now
-  // since a bridgeable function's parameters and returns should all be
-  // trivially representable in ObjC so not need to exercise the type metadata.
-  //
-  // Ultimately we may need to capture generic parameters in block storage, but
-  // that will require a redesign of the interface to support dependent-layout
-  // context. Currently we don't capture anything directly into a block but a
-  // Swift closure, but that's totally dumb.
+  auto extInfo =
+      SILFunctionType::ExtInfo()
+        .withRepresentation(SILFunctionType::Representation::CFunctionPointer);
+
+  CanGenericSignature genericSig;
+  GenericEnvironment *genericEnv = nullptr;
+  ArrayRef<Substitution> subs;
+  if (fnTy->hasArchetype() || blockTy->hasArchetype()) {
+    genericSig = F.getLoweredFunctionType()->getGenericSignature();
+    genericEnv = F.getGenericEnvironment();
+
+    subs = F.getForwardingSubstitutions();
+
+    // The block invoke function must be pseudogeneric. This should be OK for now
+    // since a bridgeable function's parameters and returns should all be
+    // trivially representable in ObjC so not need to exercise the type metadata.
+    //
+    // Ultimately we may need to capture generic parameters in block storage, but
+    // that will require a redesign of the interface to support dependent-layout
+    // context. Currently we don't capture anything directly into a block but a
+    // Swift closure, but that's totally dumb.
+    if (genericSig)
+      extInfo = extInfo.withIsPseudogeneric();
+  }
+
   auto invokeTy =
-    SILFunctionType::get(F.getLoweredFunctionType()->getGenericSignature(),
-                     SILFunctionType::ExtInfo()
-                       .withRepresentation(SILFunctionType::Representation::
-                                           CFunctionPointer)
-                       .withIsPseudogeneric(),
-                     ParameterConvention::Direct_Unowned,
-                     params,
-                     blockInterfaceTy->getAllResults(),
-                     blockInterfaceTy->getOptionalErrorResult(),
-                     getASTContext());
+    SILFunctionType::get(genericSig,
+                         extInfo,
+                         ParameterConvention::Direct_Unowned,
+                         params,
+                         blockInterfaceTy->getAllResults(),
+                         blockInterfaceTy->getOptionalErrorResult(),
+                         getASTContext());
 
   // Create the invoke function. Borrow the mangling scheme from reabstraction
   // thunks, which is what we are in spirit.
-  auto thunk = SGM.getOrCreateReabstractionThunk(F.getGenericEnvironment(),
+  auto thunk = SGM.getOrCreateReabstractionThunk(genericEnv,
                                                  invokeTy,
                                                  fnTy,
                                                  blockTy,
@@ -367,7 +381,7 @@
 
   // Build it if necessary.
   if (thunk->empty()) {
-    thunk->setGenericEnvironment(F.getGenericEnvironment());
+    thunk->setGenericEnvironment(genericEnv);
     SILGenFunction thunkSGF(SGM, *thunk);
     auto loc = RegularLocation::getAutoGeneratedLocation();
     buildFuncToBlockInvokeBody(thunkSGF, loc, blockTy, storageTy, fnTy);
@@ -385,7 +399,7 @@
   
   auto stackBlock = B.createInitBlockStorageHeader(loc, storage, invokeFn,
                                       SILType::getPrimitiveObjectType(blockTy),
-                                      getForwardingSubstitutions());
+                                      subs);
 
   // Copy the block so we have an independent heap object we can hand off.
   auto heapBlock = B.createCopyBlock(loc, stackBlock);
@@ -603,10 +617,16 @@
   CanSILFunctionType substFnTy;
   SmallVector<Substitution, 4> subs;
 
+  auto genericEnv = F.getGenericEnvironment();
+
   // Declare the thunk.
   auto blockTy = block.getType().castTo<SILFunctionType>();
+
   auto thunkTy = buildThunkType(block, funcTy, substFnTy, subs);
-  auto thunk = SGM.getOrCreateReabstractionThunk(F.getGenericEnvironment(),
+  if (!thunkTy->isPolymorphic())
+    genericEnv = nullptr;
+
+  auto thunk = SGM.getOrCreateReabstractionThunk(genericEnv,
                                                  thunkTy,
                                                  blockTy,
                                                  funcTy,
@@ -615,7 +635,7 @@
   // Build it if necessary.
   if (thunk->empty()) {
     SILGenFunction thunkSGF(SGM, *thunk);
-    thunk->setGenericEnvironment(F.getGenericEnvironment());
+    thunk->setGenericEnvironment(genericEnv);
     auto loc = RegularLocation::getAutoGeneratedLocation();
     buildBlockToFuncThunkBody(thunkSGF, loc, blockTy, funcTy);
   }
diff --git a/lib/SILGen/SILGenDecl.cpp b/lib/SILGen/SILGenDecl.cpp
index 6726997..323d7e5 100644
--- a/lib/SILGen/SILGenDecl.cpp
+++ b/lib/SILGen/SILGenDecl.cpp
@@ -2083,7 +2083,7 @@
     // makes the actual thunk.
     mangler.append("_TTR");
     if (auto generics = thunkType->getGenericSignature()) {
-      mangler.append('G');
+      mangler.append(thunkType->isPseudogeneric() ? 'g' : 'G');
       mangler.setModuleContext(M.getSwiftModule());
       mangler.mangleGenericSignature(generics);
     }
diff --git a/lib/SILGen/SILGenExpr.cpp b/lib/SILGen/SILGenExpr.cpp
index 8a51274..7f543d3 100644
--- a/lib/SILGen/SILGenExpr.cpp
+++ b/lib/SILGen/SILGenExpr.cpp
@@ -2040,7 +2040,7 @@
     auto UnsafeRawPointer = SGF.getASTContext().getUnsafeRawPointerDecl();
     auto UnsafeRawPtrTy =
       SGF.getLoweredType(UnsafeRawPointer->getDeclaredInterfaceType());
-    SILType BulitinRawPtrTy = SILType::getRawPointerType(SGF.getASTContext());
+    SILType BuiltinRawPtrTy = SILType::getRawPointerType(SGF.getASTContext());
 
 
     auto DSOGlobal = SGF.SGM.M.lookUpGlobalVariable("__dso_handle");
@@ -2048,11 +2048,11 @@
       DSOGlobal = SILGlobalVariable::create(SGF.SGM.M,
                                             SILLinkage::HiddenExternal,
                                             IsNotFragile, "__dso_handle",
-                                            BulitinRawPtrTy);
+                                            BuiltinRawPtrTy);
     auto DSOAddr = SGF.B.createGlobalAddr(SILLoc, DSOGlobal);
 
     auto DSOPointer = SGF.B.createAddressToPointer(SILLoc, DSOAddr,
-                                                   BulitinRawPtrTy);
+                                                   BuiltinRawPtrTy);
 
     auto UnsafeRawPtrStruct = SGF.B.createStruct(SILLoc, UnsafeRawPtrTy,
                                                  { DSOPointer });
diff --git a/lib/SILGen/SILGenPoly.cpp b/lib/SILGen/SILGenPoly.cpp
index bd4711a..6a2003d 100644
--- a/lib/SILGen/SILGenPoly.cpp
+++ b/lib/SILGen/SILGenPoly.cpp
@@ -2314,11 +2314,24 @@
   // on the result type.
   assert(expectedType->getExtInfo().hasContext());
 
-  // Just use the generic signature from the context.
-  // This isn't necessarily optimal.
-  auto genericSig = F.getLoweredFunctionType()->getGenericSignature();
-  auto subsArray = F.getForwardingSubstitutions();
-  subs.append(subsArray.begin(), subsArray.end());
+  auto extInfo = expectedType->getExtInfo()
+    .withRepresentation(SILFunctionType::Representation::Thin);
+
+  // Use the generic signature from the context if the thunk involves
+  // generic parameters.
+  CanGenericSignature genericSig;
+  GenericEnvironment *genericEnv = nullptr;
+  if (expectedType->hasArchetype() || sourceType->hasArchetype()) {
+    genericSig = F.getLoweredFunctionType()->getGenericSignature();
+    genericEnv = F.getGenericEnvironment();
+    auto subsArray = F.getForwardingSubstitutions();
+    subs.append(subsArray.begin(), subsArray.end());
+
+    // If our parent function was pseudogeneric, this thunk must also be
+    // pseudogeneric, since we have no way to pass generic parameters.
+    if (F.getLoweredFunctionType()->isPseudogeneric())
+      extInfo = extInfo.withIsPseudogeneric();
+  }
 
   // Add the function type as the parameter.
   SmallVector<SILParameterInfo, 4> params;
@@ -2328,10 +2341,7 @@
                     sourceType->getExtInfo().hasContext()
                       ? DefaultThickCalleeConvention
                       : ParameterConvention::Direct_Unowned});
-  
-  auto extInfo = expectedType->getExtInfo()
-    .withRepresentation(SILFunctionType::Representation::Thin);
-  
+
   // Map the parameter and expected types out of context to get the interface
   // type of the thunk.
   SmallVector<SILParameterInfo, 4> interfaceParams;
@@ -2401,10 +2411,15 @@
   // Declare the thunk.
   SmallVector<Substitution, 4> substitutions;
   CanSILFunctionType substFnType;
+
   auto thunkType = gen.buildThunkType(fn, expectedType,
                                   substFnType, substitutions);
+  auto genericEnv = gen.F.getGenericEnvironment();
+  if (!thunkType->isPolymorphic())
+    genericEnv = nullptr;
+
   auto thunk = gen.SGM.getOrCreateReabstractionThunk(
-                                       gen.F.getGenericEnvironment(),
+                                       genericEnv,
                                        thunkType,
                                        fn.getType().castTo<SILFunctionType>(),
                                        expectedType,
@@ -2413,7 +2428,7 @@
   // Build it if necessary.
   if (thunk->empty()) {
     // Borrow the context archetypes from the enclosing function.
-    thunk->setGenericEnvironment(gen.F.getGenericEnvironment());
+    thunk->setGenericEnvironment(genericEnv);
     SILGenFunction thunkSGF(gen.SGM, *thunk);
     auto loc = RegularLocation::getAutoGeneratedLocation();
     buildThunkBody(thunkSGF, loc,
diff --git a/lib/SILOptimizer/PassManager/Passes.cpp b/lib/SILOptimizer/PassManager/Passes.cpp
index 9893140..dd8eb6a 100644
--- a/lib/SILOptimizer/PassManager/Passes.cpp
+++ b/lib/SILOptimizer/PassManager/Passes.cpp
@@ -308,7 +308,7 @@
   PM.setStageName("MidLevel");
   AddSSAPasses(PM, OptimizationLevelKind::MidLevel);
   
-  // Specialy partially applied functions with dead arguments as a preparation
+  // Specialize partially applied functions with dead arguments as a preparation
   // for CapturePropagation.
   PM.addDeadArgSignatureOpt();
 
diff --git a/lib/SILOptimizer/Transforms/ARCCodeMotion.cpp b/lib/SILOptimizer/Transforms/ARCCodeMotion.cpp
index cc2d193..1f14b7b 100644
--- a/lib/SILOptimizer/Transforms/ARCCodeMotion.cpp
+++ b/lib/SILOptimizer/Transforms/ARCCodeMotion.cpp
@@ -278,7 +278,7 @@
   RetainBlockState(bool IsEntry, unsigned size, bool MultiIteration) {
     // Iterative forward data flow.
     BBSetIn.resize(size, false);
-    // Initilize to true if we are running optimistic data flow, i.e.
+    // Initialize to true if we are running optimistic data flow, i.e.
     // MultiIteration is true.
     BBSetOut.resize(size, MultiIteration);
     BBMaxSet.resize(size, !IsEntry && MultiIteration);
@@ -475,7 +475,7 @@
       continue;
     for (auto IP : Iter->second) {
       // we are about to insert a new retain instruction before the insertion
-      // point. Check if the previous instruction is reuseable, reuse it, do
+      // point. Check if the previous instruction is reusable, reuse it, do
       // not insert new instruction and delete old one.
       if (auto I = getPrevReusableInst(IP, Iter->first)) {
         RCInstructions.erase(I);
@@ -620,7 +620,7 @@
   /// constructor.
   ReleaseBlockState(bool IsExit, unsigned size, bool MultiIteration) {
     // backward data flow.
-    // Initilize to true if we are running optimistic data flow, i.e.
+    // Initialize to true if we are running optimistic data flow, i.e.
     // MultiIteration is true.
     BBSetIn.resize(size, MultiIteration);
     BBSetOut.resize(size, false);
@@ -859,7 +859,7 @@
       continue;
     for (auto IP : Iter->second) {
       // we are about to insert a new release instruction before the insertion
-      // point. Check if the successor instruction is reuseable, reuse it, do
+      // point. Check if the successor instruction is reusable, reuse it, do
       // not insert new instruction and delete old one.
       if (auto I = getPrevReusableInst(IP, Iter->first)) {
         RCInstructions.erase(I);
diff --git a/lib/SILOptimizer/Utils/Local.cpp b/lib/SILOptimizer/Utils/Local.cpp
index d4d5386..4b872e5 100644
--- a/lib/SILOptimizer/Utils/Local.cpp
+++ b/lib/SILOptimizer/Utils/Local.cpp
@@ -1678,7 +1678,7 @@
   }
 
   // Compensate different owning conventions of the replaced cast instruction
-  // and the inserted convertion function.
+  // and the inserted conversion function.
   bool needRetainBeforeCall = false;
   bool needReleaseAfterCall = false;
   bool needReleaseInSucc = false;
diff --git a/lib/Sema/ConstraintSystem.cpp b/lib/Sema/ConstraintSystem.cpp
index d4c9727..1867521 100644
--- a/lib/Sema/ConstraintSystem.cpp
+++ b/lib/Sema/ConstraintSystem.cpp
@@ -835,7 +835,7 @@
     // If this is a curried reference to an instance method, where 'self' is
     // being applied, e.g., "ClassName.instanceMethod(self)", remove the
     // argument labels from the resulting function type. The 'self' parameter is
-    // always unlabled, so this operation is a no-op for the actual application.
+    // always unlabeled, so this operation is a no-op for the actual application.
     return isCurriedInstanceReference ? func->getNumParameterLists() : 1;
 
   case FunctionRefKind::DoubleApply:
diff --git a/lib/Sema/ConstraintSystem.h b/lib/Sema/ConstraintSystem.h
index 8c6096f..f824e98 100644
--- a/lib/Sema/ConstraintSystem.h
+++ b/lib/Sema/ConstraintSystem.h
@@ -1034,13 +1034,13 @@
               ContextualTypePurpose ctp = ContextualTypePurpose::CTP_Unused)
         : E(expr), TC(cs.TC), DC(cs.DC), CT(ct), CTP(ctp) {}
 
-    /// \brief Return underlaying expression.
+    /// \brief Return underlying expression.
     Expr *getExpr() const { return E; }
 
     /// \brief Try to solve this candidate sub-expression
     /// and re-write it's OSR domains afterwards.
     ///
-    /// \returs true on solver failure, false otherwise.
+    /// \returns true on solver failure, false otherwise.
     bool solve();
 
     /// \brief Apply solutions found by solver as reduced OSR sets for
@@ -2033,7 +2033,7 @@
                        FreeTypeVariableBinding allowFreeTypeVariables);
 
   /// \brief Find reduced domains of disjunction constraints for given
-  /// expression, this is achived to solving individual sub-expressions
+  /// expression, this is achieved to solving individual sub-expressions
   /// and combining resolving types. Such algorithm is called directional
   /// path consistency because it goes from children to parents for all
   /// related sub-expressions taking union of their domains.
@@ -2052,7 +2052,7 @@
   /// \param allowFreeTypeVariables How to bind free type variables in
   /// the solution.
   ///
-  /// \returns Error is an error occured, Solved is system is consistent
+  /// \returns Error is an error occurred, Solved is system is consistent
   /// and solutions were found, Unsolved otherwise.
   SolutionKind solve(Expr *&expr,
                      Type convertType,
diff --git a/lib/Sema/MiscDiagnostics.cpp b/lib/Sema/MiscDiagnostics.cpp
index 43bba5d..c6027f6 100644
--- a/lib/Sema/MiscDiagnostics.cpp
+++ b/lib/Sema/MiscDiagnostics.cpp
@@ -387,7 +387,7 @@
         TC.diagnose(c->getLoc(), diag::collection_literal_empty)
           .highlight(c->getSourceRange());
       else {
-        TC.diagnose(c->getLoc(), diag::collection_literal_heterogenous,
+        TC.diagnose(c->getLoc(), diag::collection_literal_heterogeneous,
                     c->getType())
           .highlight(c->getSourceRange())
           .fixItInsertAfter(c->getEndLoc(), " as " + c->getType()->getString());
@@ -956,7 +956,7 @@
       // This is probably a conversion from a value of labeled tuple type to
       // a scalar.
       // FIXME: We want this issue to disappear completely when single-element
-      // labelled tuples go away.
+      // labeled tuples go away.
       if (auto tupleTy = expr->getType()->getRValueType()->getAs<TupleType>()) {
         int scalarFieldIdx = tupleTy->getElementForScalarInit();
         if (scalarFieldIdx >= 0) {
@@ -1197,7 +1197,7 @@
     if (overrideFnTy && baseFnTy &&
         // The overriding function type should be no escaping.
         overrideFnTy->getExtInfo().isNoEscape() &&
-        // The overriden function type should be escaping.
+        // The overridden function type should be escaping.
         !baseFnTy->getExtInfo().isNoEscape()) {
       diag.fixItInsert(typeRange.Start, "@escaping ");
       return true;
diff --git a/lib/Sema/TypeCheckAttr.cpp b/lib/Sema/TypeCheckAttr.cpp
index 9f8db09..8c420b9 100644
--- a/lib/Sema/TypeCheckAttr.cpp
+++ b/lib/Sema/TypeCheckAttr.cpp
@@ -680,7 +680,7 @@
     }
 
     if (!OnlyKind.empty())
-      Checker.diagnoseAndRemoveAttr(attr, diag::attr_only_only_one_decl_kind,
+      Checker.diagnoseAndRemoveAttr(attr, diag::attr_only_one_decl_kind,
                                     attr, OnlyKind);
     else if (attr->isDeclModifier())
       Checker.diagnoseAndRemoveAttr(attr, diag::invalid_decl_modifier, attr);
@@ -1469,6 +1469,8 @@
   //   checked and diagnosed.
   // - This does not make use of Archetypes since it is directly substituting
   //   in place of GenericTypeParams.
+  //
+  // FIXME: Refactor to use GenericSignature->getSubstitutions()?
   SmallVector<Substitution, 4> substitutions;
   auto currentModule = FD->getParentModule();
   Type currentFromTy;
@@ -1521,7 +1523,7 @@
       auto superTy = req.getSecondType().subst(currentModule, subMap, None);
       if (!TC.isSubtypeOf(firstTy, superTy, DC)) {
         TC.diagnose(attr->getLocation(), diag::type_does_not_inherit,
-                    FD->getType(), firstTy, superTy);
+                    FD->getInterfaceType(), firstTy, superTy);
       }
       break;
     }
@@ -1531,8 +1533,8 @@
       auto firstTy = req.getFirstType().subst(currentModule, subMap, None);
       auto sameTy = req.getSecondType().subst(currentModule, subMap, None);
       if (!firstTy->isEqual(sameTy)) {
-        TC.diagnose(attr->getLocation(), diag::types_not_equal, FD->getType(),
-                    firstTy, sameTy);
+        TC.diagnose(attr->getLocation(), diag::types_not_equal,
+                    FD->getInterfaceType(), firstTy, sameTy);
 
         return;
       }
@@ -1570,7 +1572,7 @@
       checkAutoClosureAttr(pd, attr);
     else {
       AttributeEarlyChecker Checker(*this, var);
-      Checker.diagnoseAndRemoveAttr(attr, diag::attr_only_only_one_decl_kind,
+      Checker.diagnoseAndRemoveAttr(attr, diag::attr_only_one_decl_kind,
                                     attr, "parameter");
     }
   }
@@ -1579,7 +1581,7 @@
       checkNoEscapeAttr(pd, attr);
     else {
       AttributeEarlyChecker Checker(*this, var);
-      Checker.diagnoseAndRemoveAttr(attr, diag::attr_only_only_one_decl_kind,
+      Checker.diagnoseAndRemoveAttr(attr, diag::attr_only_one_decl_kind,
                                     attr, "parameter");
     }
   }
diff --git a/lib/Sema/TypeCheckDecl.cpp b/lib/Sema/TypeCheckDecl.cpp
index 3ac4100..e6d63e7 100644
--- a/lib/Sema/TypeCheckDecl.cpp
+++ b/lib/Sema/TypeCheckDecl.cpp
@@ -5188,7 +5188,7 @@
     DiagnosticTransaction tentativeDiags(TC.Diags);
 
     {
-      Type baseTy = base->getType();
+      Type baseTy = base->getInterfaceType();
       if (baseTy->is<ErrorType>())
         return false;
 
diff --git a/lib/Sema/TypeCheckPattern.cpp b/lib/Sema/TypeCheckPattern.cpp
index 0016feb..5a90d09 100644
--- a/lib/Sema/TypeCheckPattern.cpp
+++ b/lib/Sema/TypeCheckPattern.cpp
@@ -738,21 +738,21 @@
                                   TypeChecker &TC) {
   if (auto ty = decl->getTypeLoc().getType())
     return ty->is<ErrorType>();
-  
+
+  // If the element is a variadic parameter, resolve the parameter type as if
+  // it were in non-parameter position, since we want functions to be
+  // @escaping in this case.
+  auto elementOptions = (options |
+                         (decl->isVariadic() ? TR_VariadicFunctionInput
+                                             : TR_FunctionInput));
   bool hadError = TC.validateType(decl->getTypeLoc(), DC,
-                                  options|TR_FunctionInput, resolver);
+                                  elementOptions, resolver);
   
   Type Ty = decl->getTypeLoc().getType();
   if (decl->isVariadic() && !hadError) {
-    // If isn't legal to declare something both inout and variadic.
-    if (Ty->is<InOutType>()) {
-      TC.diagnose(decl->getStartLoc(), diag::inout_cant_be_variadic);
+    Ty = TC.getArraySliceType(decl->getStartLoc(), Ty);
+    if (Ty.isNull()) {
       hadError = true;
-    } else {
-      Ty = TC.getArraySliceType(decl->getStartLoc(), Ty);
-      if (Ty.isNull()) {
-        hadError = true;
-      }
     }
     decl->getTypeLoc().setType(Ty);
   }
diff --git a/lib/Sema/TypeCheckProtocol.cpp b/lib/Sema/TypeCheckProtocol.cpp
index 3c0bfaf..9627e96 100644
--- a/lib/Sema/TypeCheckProtocol.cpp
+++ b/lib/Sema/TypeCheckProtocol.cpp
@@ -2075,7 +2075,7 @@
       if (auto CD = Adopter->getAsClassOrClassExtensionContext()) {
         if (!CD->isFinal() && Adopter->isExtensionContext()) {
           // In this case, user should mark class as 'final' or define 
-          // 'required' intializer directly in the class definition.
+          // 'required' initializer directly in the class definition.
           AddFixit = false;
         } else if (!CD->isFinal()) {
           Printer << "required ";
diff --git a/lib/Sema/TypeCheckType.cpp b/lib/Sema/TypeCheckType.cpp
index c79e6dd..ef3cc11 100644
--- a/lib/Sema/TypeCheckType.cpp
+++ b/lib/Sema/TypeCheckType.cpp
@@ -1802,6 +1802,8 @@
   bool isFunctionParam =
     options.contains(TR_FunctionInput) ||
     options.contains(TR_ImmediateFunctionInput);
+  bool isVariadicFunctionParam =
+    options.contains(TR_VariadicFunctionInput);
 
   // The type we're working with, in case we want to build it differently
   // based on the attributes we see.
@@ -1982,7 +1984,9 @@
     // @autoclosure is only valid on parameters.
     if (!isFunctionParam && attrs.has(TAK_autoclosure)) {
       TC.diagnose(attrs.getLoc(TAK_autoclosure),
-                  diag::attr_only_only_on_parameters, "@autoclosure");
+                  isVariadicFunctionParam
+                      ? diag::attr_not_on_variadic_parameters
+                      : diag::attr_only_on_parameters, "@autoclosure");
       attrs.clearAttribute(TAK_autoclosure);
     }
 
@@ -2433,7 +2437,11 @@
   // inout is only valid for function parameters.
   if (!(options & TR_FunctionInput) &&
       !(options & TR_ImmediateFunctionInput)) {
-    TC.diagnose(repr->getInOutLoc(), diag::inout_only_parameter);
+    TC.diagnose(repr->getInOutLoc(),
+                (options & TR_VariadicFunctionInput)
+                    ? diag::attr_not_on_variadic_parameters
+                    : diag::attr_only_on_parameters,
+                "'inout'");
     repr->setInvalid();
     return ErrorType::get(Context);
   }
@@ -2553,38 +2561,58 @@
     if (options & TR_ImmediateFunctionInput)
       elementOptions |= TR_FunctionInput;
   }
-  
-  for (auto tyR : repr->getElements()) {
-    NamedTypeRepr *namedTyR = dyn_cast<NamedTypeRepr>(tyR);
-    if (namedTyR && !(options & TR_ImmediateFunctionInput)) {
-      Type ty = resolveType(namedTyR->getTypeRepr(), elementOptions);
-      if (!ty || ty->is<ErrorType>()) return ty;
 
-      elements.push_back(TupleTypeElt(ty, namedTyR->getName()));
-    } else {
-      // FIXME: Preserve and serialize parameter names in function types, maybe
-      // with a new sugar type.
-      Type ty = resolveType(namedTyR ? namedTyR->getTypeRepr() : tyR,
-                            elementOptions);
-      if (!ty || ty->is<ErrorType>()) return ty;
+  bool complained = false;
 
-      elements.push_back(TupleTypeElt(ty));
-    }
+  // Variadic tuples are not permitted.
+  if (repr->hasEllipsis() &&
+      !(options & TR_ImmediateFunctionInput)) {
+    TC.diagnose(repr->getEllipsisLoc(), diag::tuple_ellipsis);
+    repr->removeEllipsis();
+    complained = true;
   }
 
-  // Tuple representations are limited outside of function inputs.
+  for (auto tyR : repr->getElements()) {
+    NamedTypeRepr *namedTyR = dyn_cast<NamedTypeRepr>(tyR);
+    Type ty;
+    Identifier name;
+    bool variadic = false;
+
+    // If the element has a label, stash the label and get the underlying type.
+    if (namedTyR) {
+      // FIXME: Preserve and serialize parameter names in function types, maybe
+      // with a new sugar type.
+      if (!(options & TR_ImmediateFunctionInput))
+        name = namedTyR->getName();
+
+      tyR = namedTyR->getTypeRepr();
+    }
+
+    // If the element is a variadic parameter, resolve the parameter type as if
+    // it were in non-parameter position, since we want functions to be
+    // @escaping in this case.
+    auto thisElementOptions = elementOptions;
+    if (repr->hasEllipsis() &&
+        elements.size() == repr->getEllipsisIndex()) {
+      thisElementOptions = withoutContext(elementOptions);
+      thisElementOptions |= TR_VariadicFunctionInput;
+      variadic = true;
+    }
+
+    ty = resolveType(tyR, thisElementOptions);
+    if (!ty || ty->is<ErrorType>()) return ty;
+
+    // If the element is a variadic parameter, the underlying type is actually
+    // an ArraySlice of the element type.
+    if (variadic)
+      ty = TC.getArraySliceType(repr->getEllipsisLoc(), ty);
+
+    elements.push_back(TupleTypeElt(ty, name, variadic));
+  }
+
+  // Single-element labeled tuples are not permitted outside of declarations
+  // or SIL, either.
   if (!(options & TR_ImmediateFunctionInput)) {
-    bool complained = false;
-
-    // Variadic tuples are not permitted.
-    if (repr->hasEllipsis()) {
-      TC.diagnose(repr->getEllipsisLoc(), diag::tuple_ellipsis);
-      repr->removeEllipsis();
-      complained = true;
-    } 
-
-    // Single-element labeled tuples are not permitted outside of declarations
-    // or SIL, either.
     if (elements.size() == 1 && elements[0].hasName()
         && !(options & TR_SILType)
         && !(options & TR_EnumCase)) {
@@ -2600,14 +2628,6 @@
     }
   }
 
-  if (repr->hasEllipsis()) {
-    auto &element = elements[repr->getEllipsisIndex()];
-    Type baseTy = element.getType();
-    Type fullTy = TC.getArraySliceType(repr->getEllipsisLoc(), baseTy);
-    Identifier name = element.getName();
-    element = TupleTypeElt(fullTy, name, true);
-  }
-
   return TupleType::get(elements, Context);
 }
 
diff --git a/lib/Sema/TypeChecker.h b/lib/Sema/TypeChecker.h
index 42d1fa6..118ef9e 100644
--- a/lib/Sema/TypeChecker.h
+++ b/lib/Sema/TypeChecker.h
@@ -344,58 +344,61 @@
   /// Whether this is the immediate input type to a function type,
   TR_ImmediateFunctionInput = 0x80,
 
+  /// Whether this is a variadic function input.
+  TR_VariadicFunctionInput = 0x100,
+
   /// Whether we are in the result type of a function body that is
   /// known to produce dynamic Self.
-  TR_DynamicSelfResult = 0x100,
+  TR_DynamicSelfResult = 0x200,
 
   /// Whether this is a resolution based on a non-inferred type pattern.
-  TR_FromNonInferredPattern = 0x200,
+  TR_FromNonInferredPattern = 0x400,
 
   /// Whether we are the variable type in a for/in statement.
-  TR_EnumerationVariable = 0x400,
+  TR_EnumerationVariable = 0x800,
 
   /// Whether we are looking only in the generic signature of the context
   /// we're searching, rather than the entire context.
-  TR_GenericSignature = 0x800,
+  TR_GenericSignature = 0x1000,
 
   /// Whether this type is the referent of a global type alias.
-  TR_GlobalTypeAlias = 0x1000,
+  TR_GlobalTypeAlias = 0x2000,
 
   /// Whether this type is the value carried in an enum case.
-  TR_EnumCase = 0x2000,
+  TR_EnumCase = 0x4000,
 
   /// Whether this type is being used in an expression or local declaration.
   ///
   /// This affects what sort of dependencies are recorded when resolving the
   /// type.
-  TR_InExpression = 0x4000,
+  TR_InExpression = 0x8000,
 
   /// Whether this type resolution is guaranteed not to affect downstream files.
-  TR_KnownNonCascadingDependency = 0x8000,
+  TR_KnownNonCascadingDependency = 0x10000,
 
   /// Whether we should allow references to unavailable types.
-  TR_AllowUnavailable = 0x10000,
+  TR_AllowUnavailable = 0x20000,
 
   /// Whether this is the payload subpattern of an enum pattern.
-  TR_EnumPatternPayload = 0x20000,
+  TR_EnumPatternPayload = 0x40000,
 
   /// Whether we are binding an extension declaration, which limits
   /// the lookup.
-  TR_ExtensionBinding = 0x40000,
+  TR_ExtensionBinding = 0x80000,
 
   /// Whether we are in the inheritance clause of a nominal type declaration
   /// or extension.
-  TR_InheritanceClause = 0x80000,
+  TR_InheritanceClause = 0x100000,
 
   /// Whether we should resolve only the structure of the resulting
   /// type rather than its complete semantic properties.
-  TR_ResolveStructure = 0x100000,
+  TR_ResolveStructure = 0x200000,
 
   /// Whether this is the type of an editor placeholder.
-  TR_EditorPlaceholder = 0x200000,
+  TR_EditorPlaceholder = 0x400000,
 
   /// Whether we are in a type argument for an optional
-  TR_ImmediateOptionalTypeArgument = 0x400000,
+  TR_ImmediateOptionalTypeArgument = 0x800000,
 };
 
 /// Option set describing how type resolution should work.
@@ -411,6 +414,7 @@
 withoutContext(TypeResolutionOptions options, bool preserveSIL = false) {
   options -= TR_ImmediateFunctionInput;
   options -= TR_FunctionInput;
+  options -= TR_VariadicFunctionInput;
   options -= TR_EnumCase;
   options -= TR_ImmediateOptionalTypeArgument;
   if (!preserveSIL) options -= TR_SILType;
diff --git a/stdlib/public/core/AnyHashable.swift b/stdlib/public/core/AnyHashable.swift
index 0a71501..526af3c 100644
--- a/stdlib/public/core/AnyHashable.swift
+++ b/stdlib/public/core/AnyHashable.swift
@@ -25,7 +25,7 @@
   ///     class Derived1 : Base {}
   ///     class Derived2 : Base, _HasCustomAnyHashableRepresentation {
   ///       func _toCustomAnyHashable() -> AnyHashable? {
-  ///         // `Derived2` is canonicalized to `Devired1`.
+  ///         // `Derived2` is canonicalized to `Derived1`.
   ///         let customRepresentation = Derived1()
   ///
   ///         // Wrong:
@@ -233,7 +233,7 @@
 /// as `AnyHashable`.
 ///
 /// Completely ignores the `_HasCustomAnyHashableRepresentation`
-/// conformance, if it exstis.
+/// conformance, if it exists.
 @_silgen_name("_swift_stdlib_makeAnyHashableUsingDefaultRepresentation")
 public // COMPILER_INTRINSIC (actually, called from the runtime)
 func _stdlib_makeAnyHashableUsingDefaultRepresentation<H : Hashable>(
diff --git a/stdlib/public/core/FloatingPoint.swift.gyb b/stdlib/public/core/FloatingPoint.swift.gyb
index 828e26f..3d35141 100644
--- a/stdlib/public/core/FloatingPoint.swift.gyb
+++ b/stdlib/public/core/FloatingPoint.swift.gyb
@@ -183,7 +183,7 @@
   ///     // x == 0.375
   ///
   /// This initializer is equivalent to the following calculation, where `**`
-  /// is exponentation, computed as if by a single, correctly rounded,
+  /// is exponentiation, computed as if by a single, correctly rounded,
   /// floating-point operation:
   ///
   ///     let sign: FloatingPointSign = .plus
@@ -240,7 +240,7 @@
   init(signOf: Self, magnitudeOf: Self)
 
 % for src_ty in all_integer_types(word_bits):
-  /// Creates a new value, rounded to the closest possible representatation.
+  /// Creates a new value, rounded to the closest possible representation.
   ///
   /// If two representable values are equally close, the result is the value
   /// with more trailing zeros in its significand bit pattern.
@@ -1607,7 +1607,7 @@
   /// A binary floating-point type's `exponentBitCount` imposes a limit on the
   /// range of the exponent for normal, finite values. The *exponent bias* of
   /// a type `F` can be calculated as the following, where `**` is
-  /// exponentation:
+  /// exponentiation:
   ///
   ///     let bias = 2 ** (F.exponentBitCount - 1) - 1
   ///
diff --git a/stdlib/public/core/FloatingPointParsing.swift.gyb b/stdlib/public/core/FloatingPointParsing.swift.gyb
index e113b57..b1f213d 100644
--- a/stdlib/public/core/FloatingPointParsing.swift.gyb
+++ b/stdlib/public/core/FloatingPointParsing.swift.gyb
@@ -46,7 +46,7 @@
   /// Creates a new instance from the given string.
   ///
   /// The string passed as `text` can represent a real number in decimal or
-  /// hexadecimal format or special floating-point values for infinty and NaN
+  /// hexadecimal format or special floating-point values for infinity and NaN
   /// ("not a number").
   ///
   /// The given string may begin with a plus or minus sign character (`+` or
diff --git a/stdlib/public/core/HashedCollections.swift.gyb b/stdlib/public/core/HashedCollections.swift.gyb
index 7624053..ed46193 100644
--- a/stdlib/public/core/HashedCollections.swift.gyb
+++ b/stdlib/public/core/HashedCollections.swift.gyb
@@ -655,6 +655,9 @@
   /// be the first element that was added to the set. The set must not be
   /// empty.
   ///
+  /// - Complexity: Amortized O(1) if the set does not wrap a bridged `NSSet`.
+  ///   If the set wraps a bridged `NSSet`, the performance is unspecified.
+  ///
   /// - Returns: A member of the set.
   @discardableResult
   public mutating func removeFirst() -> Element {
diff --git a/stdlib/public/core/Policy.swift b/stdlib/public/core/Policy.swift
index 78e5630..56051c7 100644
--- a/stdlib/public/core/Policy.swift
+++ b/stdlib/public/core/Policy.swift
@@ -162,17 +162,17 @@
 /// Swift's `String` type.
 ///
 ///     if let message = s as? String {
-///         print("Succesful cast to String: \(message)")
+///         print("Successful cast to String: \(message)")
 ///     }
-///     // Prints "Succesful cast to String: This is a bridged string."
+///     // Prints "Successful cast to String: This is a bridged string."
 ///
 /// If you have prior knowledge that an `AnyObject` instance has a particular
 /// type, you can use the unconditional downcast operator (`as!`). Performing
 /// an invalid cast triggers a runtime error.
 ///
 ///     let message = s as! String
-///     print("Succesful cast to String: \(message)")
-///     // Prints "Succesful cast to String: This is a bridged string."
+///     print("Successful cast to String: \(message)")
+///     // Prints "Successful cast to String: This is a bridged string."
 ///
 ///     let badCase = v as! String
 ///     // Runtime error
diff --git a/stdlib/public/core/Zip.swift b/stdlib/public/core/Zip.swift
index 38e47bc..a0f2122 100644
--- a/stdlib/public/core/Zip.swift
+++ b/stdlib/public/core/Zip.swift
@@ -10,7 +10,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-/// Creates a sequence of pairs built out of two underyling sequences.
+/// Creates a sequence of pairs built out of two underlying sequences.
 ///
 /// In the `Zip2Sequence` instance returned by this function, the elements of
 /// the *i*th pair are the *i*th elements of each underlying sequence. The
diff --git a/stdlib/public/runtime/AnyHashableSupport.cpp b/stdlib/public/runtime/AnyHashableSupport.cpp
index e463940..4e62c73 100644
--- a/stdlib/public/runtime/AnyHashableSupport.cpp
+++ b/stdlib/public/runtime/AnyHashableSupport.cpp
@@ -64,7 +64,7 @@
     return 0;
   }
 };
-} // end unnamed namesapce
+} // end unnamed namespace
 
 // FIXME(performance): consider merging this cache into the regular
 // protocol conformance cache.
diff --git a/stdlib/public/runtime/Reflection.mm b/stdlib/public/runtime/Reflection.mm
index 3b77a7b..b10546a 100644
--- a/stdlib/public/runtime/Reflection.mm
+++ b/stdlib/public/runtime/Reflection.mm
@@ -445,7 +445,7 @@
   memcpy(temporaryValue->getWitnessTables(), weakContainer->getWitnessTables(),
          valueWitnessesSize);
 
-  // This MagicMirror constructor creates a box to hold the loaded refernce
+  // This MagicMirror constructor creates a box to hold the loaded reference
   // value, which becomes the new owner for the value.
   new (outMirror) MagicMirror(reinterpret_cast<OpaqueValue *>(temporaryValue),
                               type, /*take*/ true);
diff --git a/test/Constraints/array_literal.swift b/test/Constraints/array_literal.swift
index 36ca35a..37d6d9b 100644
--- a/test/Constraints/array_literal.swift
+++ b/test/Constraints/array_literal.swift
@@ -123,11 +123,11 @@
 /// Check for defaulting the element type to 'Any'.
 func defaultToAny(i: Int, s: String) {
   let a1 = [1, "a", 3.5]
-  // expected-error@-1{{heterogenous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
+  // expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
   let _: Int = a1  // expected-error{{value of type '[Any]'}}
 
   let a2: Array = [1, "a", 3.5]
-  // expected-error@-1{{heterogenous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
+  // expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
 
   let _: Int = a2  // expected-error{{value of type '[Any]'}}
 
diff --git a/test/Constraints/dictionary_literal.swift b/test/Constraints/dictionary_literal.swift
index 34aa3d7..2e7ee09 100644
--- a/test/Constraints/dictionary_literal.swift
+++ b/test/Constraints/dictionary_literal.swift
@@ -69,7 +69,7 @@
 
 func testDefaultExistentials() {
   let _ = ["a" : 1, "b" : 2.5, "c" : "hello"]
-  // expected-error@-1{{heterogenous collection literal could only be inferred to 'Dictionary<String, Any>'; add explicit type annotation if this is intentional}}{{46-46= as Dictionary<String, Any>}}
+  // expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<String, Any>'; add explicit type annotation if this is intentional}}{{46-46= as Dictionary<String, Any>}}
 
   let _: [String : Any] = ["a" : 1, "b" : 2.5, "c" : "hello"]
 
@@ -81,14 +81,14 @@
   let _ = ["a" : 1, 
             "b" : [ "a", 2, 3.14159 ],
             "c" : [ "a" : 2, "b" : 3.5] ]
-  // expected-error@-3{{heterogenous collection literal could only be inferred to 'Dictionary<String, Any>'; add explicit type annotation if this is intentional}}
+  // expected-error@-3{{heterogeneous collection literal could only be inferred to 'Dictionary<String, Any>'; add explicit type annotation if this is intentional}}
 
   let d3 = ["b" : B(), "c" : C()]
   let _: Int = d3 // expected-error{{value of type 'Dictionary<String, A>'}}
 
   let _ = ["a" : B(), 17 : "seventeen", 3.14159 : "Pi"]
-  // expected-error@-1{{heterogenous collection literal could only be inferred to 'Dictionary<AnyHashable, Any>'}}
+  // expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<AnyHashable, Any>'}}
 
   let _ = ["a" : "hello", 17 : "string"]
-  // expected-error@-1{{heterogenous collection literal could only be inferred to 'Dictionary<AnyHashable, String>'}}
+  // expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<AnyHashable, String>'}}
 }
diff --git a/test/Constraints/override.swift b/test/Constraints/override.swift
index 7ac4022..f2380bd 100644
--- a/test/Constraints/override.swift
+++ b/test/Constraints/override.swift
@@ -28,5 +28,5 @@
 }
 
 class Sub2 : Base2 {
-  override func foo<T>(a : (T) ->()) {} // expected-error {{method does not override any method from its superclass}} expected-note{{type does not match superclass instance method with type '<T> (a: (T) -> ()) -> ()'}}{{28-28=@escaping }}
+  override func foo<T>(a : (T) ->()) {} // expected-error {{method does not override any method from its superclass}} expected-note{{type does not match superclass instance method with type '(@escaping (T) -> ()) -> ()'}}{{28-28=@escaping }}
 }
diff --git a/test/IRGen/objc_extensions.swift b/test/IRGen/objc_extensions.swift
index 15b7fd4..83553a3 100644
--- a/test/IRGen/objc_extensions.swift
+++ b/test/IRGen/objc_extensions.swift
@@ -160,7 +160,7 @@
   @NSManaged var woof: Int
 }
 
-class  SwiftSubGizmo : SwiftBaseGizmo {
+class SwiftSubGizmo : SwiftBaseGizmo {
 
   // Don't crash on this call. Emit an objC method call to super.
   //
diff --git a/test/IRGen/same_type_constraints.swift b/test/IRGen/same_type_constraints.swift
index 61bb861..e2b78a4 100644
--- a/test/IRGen/same_type_constraints.swift
+++ b/test/IRGen/same_type_constraints.swift
@@ -42,3 +42,19 @@
      d = Dict()
   }
 }
+
+// This used to hit an infinite loop - <rdar://problem/27018457>
+public protocol CodingType {
+    associatedtype ValueType
+}
+
+public protocol ValueCoding {
+    associatedtype Coder: CodingType
+}
+
+func foo<Self>(s: Self)
+where Self : CodingType,
+      Self.ValueType: ValueCoding,
+      Self.ValueType.Coder == Self {
+  print(Self.ValueType.self)
+}
diff --git a/test/Reflection/capture_descriptors.sil b/test/Reflection/capture_descriptors.sil
index b70ac99..9501e55 100644
--- a/test/Reflection/capture_descriptors.sil
+++ b/test/Reflection/capture_descriptors.sil
@@ -191,6 +191,28 @@
 // CHECK-NEXT:   (reference_capture index=0))
 
 
+// Pseudogeneric caller and pseudogeneric callee -- type parameters are
+// erased at runtime.
+
+sil @pseudogeneric_callee : $@convention(thin) @pseudogeneric <T : AnyObject, U : AnyObject> (@owned T, @owned U) -> () {
+bb0(%t: $T, %u: $U):
+  %12 = tuple ()
+  return %12 : $()
+}
+
+sil @pseudogeneric_caller : $@convention(thin) @pseudogeneric <A : AnyObject, B : AnyObject, C : AnyObject> (@owned A, @owned B) -> @owned @pseudogeneric @callee_owned () -> () {
+bb0(%a: $A, %b: $B):
+  %f = function_ref @pseudogeneric_callee : $@convention(thin) @pseudogeneric <T : AnyObject, U : AnyObject> (@owned T, @owned U) -> ()
+  %c = partial_apply %f<A, B>(%a, %b) : $@convention(thin) @pseudogeneric <A : AnyObject, B : AnyObject> (@owned A, @owned B) -> ()
+  return %c : $@pseudogeneric @callee_owned () -> ()
+}
+
+// CHECK:      - Capture types:
+// CHECK-NEXT:   (protocol Swift.AnyObject)
+// CHECK-NEXT:   (protocol Swift.AnyObject)
+// CHECK-NEXT: - Metadata sources:
+
+
 // Capturing lowered function types
 
 sil @function_callee : $@convention(thin) (@convention(thin) () -> (), @convention(c) () -> (), @convention(block) () -> (), @convention(thick) () -> (), @convention(method) () -> (), @convention(witness_method) () -> ()) -> () {
diff --git a/test/SILGen/generic_closures.swift b/test/SILGen/generic_closures.swift
index 0fb75c6..8cf325b 100644
--- a/test/SILGen/generic_closures.swift
+++ b/test/SILGen/generic_closures.swift
@@ -109,8 +109,8 @@
   }
 
   // CHECK-LABEL: sil hidden @_TFC16generic_closures13NestedGeneric20nested_reabstraction{{.*}}
-  //   CHECK:       [[REABSTRACT:%.*]] = function_ref @_TTRG__rXFo___XFo_iT__iT__
-  //   CHECK:       partial_apply [[REABSTRACT]]<U, T>
+  //   CHECK:       [[REABSTRACT:%.*]] = function_ref @_TTRXFo___XFo_iT__iT__
+  //   CHECK:       partial_apply [[REABSTRACT]]
   func nested_reabstraction<T>(_ x: T) -> Optionable<() -> ()> {
     return .some({})
   }
@@ -213,8 +213,8 @@
   let _: () -> () = inner_generic_nocapture
   // CHECK: [[FN:%.*]] = function_ref @_TFF16generic_closures13outer_genericurFT1tx1iSi_T_L_23inner_generic_nocaptureu__rFT1uqd___qd__ : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0) -> @out τ_1_0
   // CHECK: [[CLOSURE:%.*]] = partial_apply [[FN]]<T, ()>() : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0) -> @out τ_1_0
-  // CHECK: [[THUNK:%.*]] = function_ref @_TTRGrXFo_iT__iT__XFo___
-  // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [[THUNK]]<T>([[CLOSURE]])
+  // CHECK: [[THUNK:%.*]] = function_ref @_TTRXFo_iT__iT__XFo___
+  // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [[THUNK]]([[CLOSURE]])
   // CHECK: strong_release [[THUNK_CLOSURE]]
 
   // CHECK: [[FN:%.*]] = function_ref @_TFF16generic_closures13outer_genericurFT1tx1iSi_T_L_23inner_generic_nocaptureu__rFT1uqd___qd__ : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0) -> @out τ_1_0
@@ -223,8 +223,8 @@
 
   // CHECK: [[FN:%.*]] = function_ref @_TFF16generic_closures13outer_genericurFT1tx1iSi_T_L_14inner_generic1u__rfT1uqd___Si : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, Int) -> Int
   // CHECK: [[CLOSURE:%.*]] = partial_apply [[FN]]<T, ()>(%1) : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, Int) -> Int
-  // CHECK: [[THUNK:%.*]] = function_ref @_TTRGrXFo_iT__dSi_XFo__dSi_
-  // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [[THUNK]]<T>([[CLOSURE]])
+  // CHECK: [[THUNK:%.*]] = function_ref @_TTRXFo_iT__dSi_XFo__dSi_
+  // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [[THUNK]]([[CLOSURE]])
   // CHECK: strong_release [[THUNK_CLOSURE]]
   let _: () -> Int = inner_generic1
 
diff --git a/test/SILGen/generic_objc_block_bridge.swift b/test/SILGen/generic_objc_block_bridge.swift
index 8a42e69..6d540c7 100644
--- a/test/SILGen/generic_objc_block_bridge.swift
+++ b/test/SILGen/generic_objc_block_bridge.swift
@@ -14,4 +14,4 @@
   }
 }
 
-// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRGrXFdCb_dSi_dSi_XFo_dSi_dSi_ : $@convention(thin) <GenericParamName> (Int, @owned @convention(block) (Int) -> Int) -> Int {
+// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFdCb_dSi_dSi_XFo_dSi_dSi_ : $@convention(thin) (Int, @owned @convention(block) (Int) -> Int) -> Int {
diff --git a/test/SILGen/objc_blocks_bridging.swift b/test/SILGen/objc_blocks_bridging.swift
index 2e7dbca..11a0a7d 100644
--- a/test/SILGen/objc_blocks_bridging.swift
+++ b/test/SILGen/objc_blocks_bridging.swift
@@ -135,3 +135,21 @@
   // CHECK: function_ref @_TTRXFo___XFdCb___
   noescapeNonnullBlockAlias { }
 }
+
+class ObjCClass : NSObject {}
+
+extension ObjCClass {
+  func someDynamicMethod(closure: (() -> ()) -> ()) {}
+}
+
+struct GenericStruct<T> {
+  let closure: (() -> ()) -> ()
+
+  func doStuff(o: ObjCClass) {
+    o.someDynamicMethod(closure: closure)
+  }
+}
+
+// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_oXFo_____XFdCb_dXFdCb_____ : $@convention(c) (@inout_aliasable @block_storage @callee_owned (@owned @callee_owned () -> ()) -> (), @convention(block) () -> ()) -> ()
+// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFdCb___XFo___ : $@convention(thin) (@owned @convention(block) () -> ()) -> ()
+
diff --git a/test/SILGen/objc_bridging_any.swift b/test/SILGen/objc_bridging_any.swift
index 78d4b34..33da4d6 100644
--- a/test/SILGen/objc_bridging_any.swift
+++ b/test/SILGen/objc_bridging_any.swift
@@ -422,7 +422,7 @@
   // CHECK-NEXT:  strong_release [[RESULT]]
   // CHECK-NEXT:  return [[BLOCK]]
 
-  // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iP___XFdCb_dPs9AnyObject___ : $@convention(c) @pseudogeneric (@inout_aliasable @block_storage @callee_owned (@in Any) -> (), AnyObject) -> ()
+  // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iP___XFdCb_dPs9AnyObject___ : $@convention(c) (@inout_aliasable @block_storage @callee_owned (@in Any) -> (), AnyObject) -> ()
   // CHECK:     bb0(%0 : $*@block_storage @callee_owned (@in Any) -> (), %1 : $AnyObject):
   // CHECK-NEXT:  [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage %0
   // CHECK-NEXT:  [[FUNCTION:%.*]] = load [[BLOCK_STORAGE_ADDR]]
@@ -493,7 +493,7 @@
   // CHECK-NEXT:  strong_release [[FUNCTION]]
   // CHECK-NEXT:  return [[BLOCK]]
 
-  // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__iP__XFdCb__aPs9AnyObject__ : $@convention(c) @pseudogeneric (@inout_aliasable @block_storage @callee_owned () -> @out Any) -> @autoreleased AnyObject
+  // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__iP__XFdCb__aPs9AnyObject__ : $@convention(c) (@inout_aliasable @block_storage @callee_owned () -> @out Any) -> @autoreleased AnyObject
   // CHECK:     bb0(%0 : $*@block_storage @callee_owned () -> @out Any):
   // CHECK-NEXT:  [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage %0
   // CHECK-NEXT:  [[FUNCTION:%.*]] = load [[BLOCK_STORAGE_ADDR]]
diff --git a/test/SILGen/objc_imported_generic.swift b/test/SILGen/objc_imported_generic.swift
index 99d33bb..57ea05d 100644
--- a/test/SILGen/objc_imported_generic.swift
+++ b/test/SILGen/objc_imported_generic.swift
@@ -77,7 +77,7 @@
 // CHECK-LABEL: sil @_TF21objc_imported_generic20genericBlockBridging
 // CHECK:         [[BLOCK_TO_FUNC:%.*]] = function_ref @_TTRGRxs9AnyObjectx21objc_imported_generic7AnsiblerXFdCb_dx_ax_XFo_ox_ox_
 // CHECK:         partial_apply [[BLOCK_TO_FUNC]]<T, {{.*}}>
-// CHECK:         [[FUNC_TO_BLOCK:%.*]] = function_ref @_TTRGRxs9AnyObjectx21objc_imported_generic7AnsiblerXFo_ox_ox_XFdCb_dx_ax_
+// CHECK:         [[FUNC_TO_BLOCK:%.*]] = function_ref @_TTRgRxs9AnyObjectx21objc_imported_generic7AnsiblerXFo_ox_ox_XFdCb_dx_ax_
 // CHECK:         init_block_storage_header {{.*}} invoke [[FUNC_TO_BLOCK]]<T,{{.*}}>
 
 // CHECK-LABEL: sil @_TF21objc_imported_generic20arraysOfGenericParam
diff --git a/test/SILGen/property_abstraction.swift b/test/SILGen/property_abstraction.swift
index 71d5efb..265cf06 100644
--- a/test/SILGen/property_abstraction.swift
+++ b/test/SILGen/property_abstraction.swift
@@ -128,5 +128,5 @@
 // CHECK:   [[F1:%.*]] = thin_to_thick_function [[F0]]
 // CHECK:   [[SETTER:%.*]] = witness_method $F, #Factory.builder!setter.1
 // CHECK:   [[REABSTRACTOR:%.*]] = function_ref @_TTR
-// CHECK:   [[F2:%.*]] = partial_apply [[REABSTRACTOR]]<F>([[F1]])
+// CHECK:   [[F2:%.*]] = partial_apply [[REABSTRACTOR]]([[F1]])
 // CHECK:   apply [[SETTER]]<F, MyClass>([[F2]], [[PB]])
diff --git a/test/Sema/complex_expressions.swift b/test/Sema/complex_expressions.swift
index 497e648..f3e9b03 100644
--- a/test/Sema/complex_expressions.swift
+++ b/test/Sema/complex_expressions.swift
@@ -35,7 +35,7 @@
 }
 
 // SR-2102:
-// DictionaryExpr was too complex to be solved in resonable time
+// DictionaryExpr was too complex to be solved in reasonable time
 
 let M_PI: Double = 3.1415926535897931
 let M_E : Double = 2.7182818284590451
diff --git a/test/attr/attr_autoclosure.swift b/test/attr/attr_autoclosure.swift
index bc6a9e3..4b87314 100644
--- a/test/attr/attr_autoclosure.swift
+++ b/test/attr/attr_autoclosure.swift
@@ -156,3 +156,7 @@
   takesAutoclosure(fn()) // ok
 }
 
+// expected-error @+1 {{@autoclosure may not be used on variadic parameters}}
+func variadicAutoclosure(_ fn: @autoclosure () -> ()...) {
+  for _ in fn {}
+}
diff --git a/test/attr/attr_escaping.swift b/test/attr/attr_escaping.swift
index 890b545..6b87608 100644
--- a/test/attr/attr_escaping.swift
+++ b/test/attr/attr_escaping.swift
@@ -127,3 +127,18 @@
     deepOptionalClosure = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}}
   }
 }
+
+// Check that functions in vararg position are @escaping
+func takesEscapingFunction(fn: @escaping () -> ()) {}
+func takesArrayOfFunctions(array: [() -> ()]) {}
+
+func takesVarargsOfFunctions(fns: () -> ()...) {
+  takesArrayOfFunctions(array: fns)
+  for fn in fns {
+    takesEscapingFunction(fn: fn)
+  }
+}
+
+func takesNoEscapeFunction(fn: () -> ()) { // expected-note {{parameter 'fn' is implicitly non-escaping}}
+  takesVarargsOfFunctions(fns: fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
+}
diff --git a/test/attr/attr_inout.swift b/test/attr/attr_inout.swift
index 615197c..e361efa 100644
--- a/test/attr/attr_inout.swift
+++ b/test/attr/attr_inout.swift
@@ -4,10 +4,10 @@
 
 func h(_ : inout Int) -> (inout Int) -> (inout Int) -> Int { }
 
-func ff(x: (inout Int, inout Float)) { } //  expected-error {{'inout' is only valid in parameter lists}}  
+func ff(x: (inout Int, inout Float)) { } //  expected-error {{'inout' may only be used on parameters}}
 
 enum inout_carrier {
-  case carry(inout Int) // expected-error {{'inout' is only valid in parameter lists}}
+  case carry(inout Int) // expected-error {{'inout' may only be used on parameters}}
 }
 
 func deprecated(inout x: Int) {} // expected-error {{'inout' before a parameter name is not allowed, place it before the parameter type instead}}
diff --git a/test/attr/attr_specialize.swift b/test/attr/attr_specialize.swift
index 69dea77..3e8478b 100644
--- a/test/attr/attr_specialize.swift
+++ b/test/attr/attr_specialize.swift
@@ -66,12 +66,12 @@
   typealias Element = Float
 }
 @_specialize(FloatElement)
-@_specialize(IntElement) // expected-error{{'<T : HasElt where T.Element == Float> (T) -> ()' requires the types 'IntElement.Element' (aka 'Int') and 'Float' be equivalent}}
+@_specialize(IntElement) // expected-error{{'<T where T : HasElt, T.Element == Float> (T) -> ()' requires the types 'IntElement.Element' (aka 'Int') and 'Float' be equivalent}}
 func sameTypeRequirement<T : HasElt>(_ t: T) where T.Element == Float {}
 
 class Base {}
 class Sub : Base {}
 class NonSub {}
 @_specialize(Sub)
-@_specialize(NonSub) // expected-error{{'<T : Base> (T) -> ()' requires that 'NonSub' inherit from 'Base'}}
+@_specialize(NonSub) // expected-error{{'<T where T : Base> (T) -> ()' requires that 'NonSub' inherit from 'Base'}}
 func superTypeRequirement<T : Base>(_ t: T) {}
diff --git a/test/decl/func/vararg.swift b/test/decl/func/vararg.swift
index c95d25c..1d938b6 100644
--- a/test/decl/func/vararg.swift
+++ b/test/decl/func/vararg.swift
@@ -19,7 +19,7 @@
 func f4(_ a: Int..., b: Int) { }
 
 // rdar://16008564
-func inoutVariadic(_ i: inout Int...) {  // expected-error {{inout arguments cannot be variadic}}
+func inoutVariadic(_ i: inout Int...) {  // expected-error {{'inout' may not be used on variadic parameters}}
 }
 
 // rdar://19722429
diff --git a/test/decl/protocol/conforms/fixit_stub.swift b/test/decl/protocol/conforms/fixit_stub.swift
index 2c6d3aa..11aa512 100644
--- a/test/decl/protocol/conforms/fixit_stub.swift
+++ b/test/decl/protocol/conforms/fixit_stub.swift
@@ -3,6 +3,7 @@
 protocol Protocol1 {
   func foo(arg1: Int, arg2: String) -> String // expected-note{{protocol requires function 'foo(arg1:arg2:)' with type '(Int, String) -> String'; do you want to add a stub?}} {{27-27=\n    func foo(arg1: Int, arg2: String) -> String {\n        <#code#>\n    \}\n}}
   func bar() throws -> String // expected-note{{protocol requires function 'bar()' with type '() throws -> String'; do you want to add a stub?}} {{27-27=\n    func bar() throws -> String {\n        <#code#>\n    \}\n}}
+  func generic<T>(t: T) // expected-note{{protocol requires function 'generic(t:)' with type '<T> (t: T) -> ()'; do you want to add a stub?}} {{27-27=\n    func generic<T>(t: T) {\n        <#code#>\n    \}\n}}
   init(arg: Int) // expected-note{{protocol requires initializer 'init(arg:)' with type '(arg: Int)'; do you want to add a stub?}} {{27-27=\n    required init(arg: Int) {\n        <#code#>\n    \}\n}}
   var baz: Int { get } // expected-note{{protocol requires property 'baz' with type 'Int'; do you want to add a stub?}} {{27-27=\n    var baz: Int\n}}
   var baz2: Int { get set } // expected-note{{protocol requires property 'baz2' with type 'Int'; do you want to add a stub?}} {{27-27=\n    var baz2: Int\n}}
diff --git a/test/expr/capture/generic_params.swift b/test/expr/capture/generic_params.swift
index f23545d..149797d 100644
--- a/test/expr/capture/generic_params.swift
+++ b/test/expr/capture/generic_params.swift
@@ -2,7 +2,7 @@
 
 func doSomething<T>(_ t: T) {}
 
-// CHECK: func_decl "outerGeneric(t:x:)"<T> type='<T> (t: T, x: AnyObject) -> ()'
+// CHECK: func_decl "outerGeneric(t:x:)"<T> interface type='<τ_0_0> (t: τ_0_0, x: AnyObject) -> ()'
 
 func outerGeneric<T>(t: T, x: AnyObject) {
   // Simple case -- closure captures outer generic parameter
@@ -20,13 +20,13 @@
 
   // Nested generic functions always capture outer generic parameters, even if
   // they're not mentioned in the function body
-  // CHECK: func_decl "innerGeneric(u:)"<U> type='<U> (u: U) -> ()' {{.*}} captures=(<generic> )
+  // CHECK: func_decl "innerGeneric(u:)"<U> interface type='<τ_0_0, τ_1_0> (u: τ_1_0) -> ()' {{.*}} captures=(<generic> )
   func innerGeneric<U>(u: U) {}
 
   // Make sure we look through typealiases
   typealias TT = (a: T, b: T)
 
-  // CHECK: func_decl "localFunction(tt:)" type='<T> (tt: TT) -> ()' {{.*}} captures=(<generic> )
+  // CHECK: func_decl "localFunction(tt:)" interface type='<τ_0_0> (tt: (a: τ_0_0, b: τ_0_0)) -> ()' {{.*}} captures=(<generic> )
   func localFunction(tt: TT) {}
 
   // CHECK: closure_expr type='(TT) -> ()' {{.*}} captures=(<generic> )
diff --git a/test/type/types.swift b/test/type/types.swift
index c935d81..f96cffc 100644
--- a/test/type/types.swift
+++ b/test/type/types.swift
@@ -44,9 +44,9 @@
 
 var i = Int?(42)
 
-var bad_io : (Int) -> (inout Int, Int)  // expected-error {{'inout' is only valid in parameter lists}}
+var bad_io : (Int) -> (inout Int, Int)  // expected-error {{'inout' may only be used on parameters}}
 
-func bad_io2(_ a: (inout Int, Int)) {}    // expected-error {{'inout' is only valid in parameter lists}}
+func bad_io2(_ a: (inout Int, Int)) {}    // expected-error {{'inout' may only be used on parameters}}
 
 // <rdar://problem/15588967> Array type sugar default construction syntax doesn't work
 func test_array_construct<T>(_: T) {
@@ -148,12 +148,12 @@
 let bb2 = [Int!](repeating: nil, count: 2)
 
 // <rdar://problem/21560309> inout allowed on function return type
-func r21560309<U>(_ body: (_: inout Int) -> inout U) {}  // expected-error {{'inout' is only valid in parameter lists}}
+func r21560309<U>(_ body: (_: inout Int) -> inout U) {}  // expected-error {{'inout' may only be used on parameters}}
 r21560309 { x in x }
 
 // <rdar://problem/21949448> Accepts-invalid: 'inout' shouldn't be allowed on stored properties
 class r21949448 {
-  var myArray: inout [Int] = []   // expected-error {{'inout' is only valid in parameter lists}}
+  var myArray: inout [Int] = []   // expected-error {{'inout' may only be used on parameters}}
 }
 
 // SE-0066 - Standardize function type argument syntax to require parentheses
diff --git a/validation-test/IDE/crashers/091-swift-typechecker-computedefaultaccessibility.swift b/validation-test/IDE/crashers/091-swift-typechecker-computedefaultaccessibility.swift
new file mode 100644
index 0000000..87cfa00
--- /dev/null
+++ b/validation-test/IDE/crashers/091-swift-typechecker-computedefaultaccessibility.swift
@@ -0,0 +1,3 @@
+// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s
+// REQUIRES: asserts
+protocol A{typealias e}extension A{typealias e:e l#^A^#
\ No newline at end of file
diff --git a/validation-test/compiler_crashers/28421-swift-constraints-constraintsystem-diagnosefailureforexpr.swift b/validation-test/compiler_crashers/28421-swift-constraints-constraintsystem-diagnosefailureforexpr.swift
new file mode 100644
index 0000000..b7da7a2
--- /dev/null
+++ b/validation-test/compiler_crashers/28421-swift-constraints-constraintsystem-diagnosefailureforexpr.swift
@@ -0,0 +1,14 @@
+// This source file is part of the Swift.org open source project
+// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See http://swift.org/LICENSE.txt for license information
+// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
+
+// RUN: not --crash %target-swift-frontend %s -parse
+// REQUIRES: asserts
+{
+extension{{
+}init(){a{}{
+for b
+(
diff --git a/validation-test/stdlib/NSNumberBridging.swift.gyb b/validation-test/stdlib/NSNumberBridging.swift.gyb
index 8461b24..acd9f27 100644
--- a/validation-test/stdlib/NSNumberBridging.swift.gyb
+++ b/validation-test/stdlib/NSNumberBridging.swift.gyb
@@ -107,7 +107,7 @@
 }
 
 NSNumberTests.test("_SwiftTypePreservingNSNumber.classForCoder") {
-  // Check that internal subclass is not achived.
+  // Check that internal subclass is not archived.
   let n: NSNumber = (42 as Int)._bridgeToObjectiveC()
   expectTrue(isTypePreservingNSNumber(n))
   expectEqual("NSNumber", String(describing: n.classForCoder))