Merge pull request #15148 from compnerd/msvc-sdk

diff --git a/CMakeLists.txt b/CMakeLists.txt
index bc10278..efd96b9 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -11,19 +11,15 @@
 list(APPEND CMAKE_MODULE_PATH
     "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules")
 
-# Make a job pool for things that can't yet be distributed
-cmake_host_system_information(
-  RESULT localhost_logical_cores QUERY NUMBER_OF_LOGICAL_CORES)
-set_property(GLOBAL PROPERTY JOB_POOLS local_jobs=${localhost_logical_cores})
-# Put linking in that category
-set_property(GLOBAL PROPERTY JOB_POOL_LINK local_jobs)
-
 ENABLE_LANGUAGE(C)
 
 # First include general CMake utilities.
+include(SwiftLocalJobPool)
 include(SwiftUtils)
 include(CheckSymbolExists)
 
+initialize_local_jobpool()
+
 #
 # User-configurable options that control the inclusion and default build
 # behavior for components which may not strictly be necessary (tools, examples,
diff --git a/cmake/modules/SwiftLocalJobPool.cmake b/cmake/modules/SwiftLocalJobPool.cmake
new file mode 100644
index 0000000..8958a0b
--- /dev/null
+++ b/cmake/modules/SwiftLocalJobPool.cmake
@@ -0,0 +1,15 @@
+
+function(initialize_local_jobpool)
+  # Make a job pool for things that can't yet be distributed
+  cmake_host_system_information(
+    RESULT localhost_logical_cores QUERY NUMBER_OF_LOGICAL_CORES)
+  set_property(GLOBAL PROPERTY JOB_POOLS local_jobs=${localhost_logical_cores})
+  # Put linking in that category.
+  set_property(GLOBAL PROPERTY JOB_POOL_LINK local_jobs)
+endfunction()
+
+function(add_target_to_local_jobpool target)
+  set_property(TARGET ${target} PROPERTY JOB_POOL_COMPILE local_jobs)
+  # We do not need to set link jobs to be in local_jobs since above, we make
+  # linking always local.
+endfunction()
diff --git a/cmake/modules/SwiftSource.cmake b/cmake/modules/SwiftSource.cmake
index 0e4b414..8f5070f 100644
--- a/cmake/modules/SwiftSource.cmake
+++ b/cmake/modules/SwiftSource.cmake
@@ -1,4 +1,5 @@
 include(SwiftUtils)
+include(SwiftLocalJobPool)
 
 # Process the sources within the given variable, pulling out any Swift
 # sources to be compiled with 'swift' directly. This updates
@@ -433,6 +434,7 @@
       COMMAND ""
       OUTPUT ${obj_dirs}
       COMMENT "Generating obj dirs for ${first_output}")
+  add_target_to_local_jobpool(${obj_dirs_dependency_target})
 
   # Generate the api notes if we need them.
   if (apinotes_outputs)
@@ -449,6 +451,7 @@
           ${depends_create_apinotes}
           ${obj_dirs_dependency_target}
         COMMENT "Generating API notes ${first_output}")
+    add_target_to_local_jobpool(${api_notes_dependency_target})
   endif()
 
   # Then we can compile both the object files and the swiftmodule files
@@ -476,6 +479,7 @@
         ${swift_ide_test_dependency} ${api_notes_dependency_target}
         ${obj_dirs_dependency_target}
       COMMENT "Compiling ${first_output}")
+  add_target_to_local_jobpool(${dependency_target})
   set("${dependency_target_out_var_name}" "${dependency_target}" PARENT_SCOPE)
 
   # This is the target to generate:
@@ -511,6 +515,7 @@
           ${swift_ide_test_dependency} ${api_notes_dependency_target}
           ${obj_dirs_dependency_target}
         COMMENT "Generating ${module_file}")
+    add_target_to_local_jobpool(${module_dependency_target})
     set("${dependency_module_target_out_var_name}" "${module_dependency_target}" PARENT_SCOPE)
 
     # This is the target to generate the .sib files. It is not built by default.
@@ -528,6 +533,7 @@
           ${obj_dirs_dependency_target}
         COMMENT "Generating ${sib_file}"
         EXCLUDE_FROM_ALL)
+    add_target_to_local_jobpool(${sib_dependency_target})
     set("${dependency_sib_target_out_var_name}" "${sib_dependency_target}" PARENT_SCOPE)
 
     add_custom_command_target(
@@ -544,6 +550,7 @@
           ${obj_dirs_dependency_target}
         COMMENT "Generating ${sibopt_file}"
         EXCLUDE_FROM_ALL)
+    add_target_to_local_jobpool(${sibopt_dependency_target})
     set("${dependency_sibopt_target_out_var_name}" "${sibopt_dependency_target}" PARENT_SCOPE)
 
     # This is the target to generate the .sibgen files. It is not built by default.
@@ -561,6 +568,7 @@
           ${obj_dirs_dependency_target}
           COMMENT "Generating ${sibgen_file}"
           EXCLUDE_FROM_ALL)
+    add_target_to_local_jobpool(${sibgen_dependency_target})
     set("${dependency_sibgen_target_out_var_name}" "${sibgen_dependency_target}" PARENT_SCOPE)
   endif()
 
diff --git a/docs/WindowsBuild.md b/docs/WindowsBuild.md
index 734729b..7bf7324 100644
--- a/docs/WindowsBuild.md
+++ b/docs/WindowsBuild.md
@@ -121,8 +121,6 @@
   two hours depending on your system.
 - You may need to adjust the `SWIFT_WINDOWS_LIB_DIRECTORY` parameter depending on
   your target platform or Windows SDK version.
-- While the commands here use MSVC to build, using `clang-cl` is recommended (see
-  the **Clang-cl** section below).
 ```cmd
 mkdir "%swift_source_dir%/build/Ninja-DebugAssert/swift-windows-amd64/ninja"
 pushd "%swift_source_dir%/build/Ninja-DebugAssert/swift-windows-amd64/ninja"
diff --git a/include/swift/AST/AttrKind.h b/include/swift/AST/AttrKind.h
index e80c2c6..e67569a 100644
--- a/include/swift/AST/AttrKind.h
+++ b/include/swift/AST/AttrKind.h
@@ -23,7 +23,7 @@
 namespace swift {
 
 /// The associativity of a binary operator.
-enum class Associativity : unsigned char {
+enum class Associativity : uint8_t {
   /// Non-associative operators cannot be written next to other
   /// operators with the same precedence.  Relational operators are
   /// typically non-associative.
diff --git a/include/swift/AST/Builtins.h b/include/swift/AST/Builtins.h
index f12dc48..57578db 100644
--- a/include/swift/AST/Builtins.h
+++ b/include/swift/AST/Builtins.h
@@ -39,7 +39,7 @@
 Type getBuiltinType(ASTContext &Context, StringRef Name);
 
 /// OverloadedBuiltinKind - Whether and how a builtin is overloaded.
-enum class OverloadedBuiltinKind : unsigned char {
+enum class OverloadedBuiltinKind : uint8_t {
   /// The builtin is not overloaded.
   None,
 
diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h
index f18d160..66d360e 100644
--- a/include/swift/AST/Decl.h
+++ b/include/swift/AST/Decl.h
@@ -3879,7 +3879,7 @@
 };
 
 /// The safety semantics of this addressor.
-enum class AddressorKind : unsigned char {
+enum class AddressorKind : uint8_t {
   /// \brief This is not an addressor.
   NotAddressor,
   /// \brief This is an unsafe addressor; it simply returns an address.
@@ -3896,7 +3896,7 @@
 };
 
 /// Whether an access to storage is for reading, writing, or both.
-enum class AccessKind : unsigned char {
+enum class AccessKind : uint8_t {
   /// The access is just to read the current value.
   Read,
 
@@ -3908,11 +3908,11 @@
 };
 
 /// The way to actually evaluate an access to storage.
-enum class AccessStrategy : unsigned char {
+enum class AccessStrategy : uint8_t {
   /// The decl is a VarDecl with its own backing storage; evaluate its
   /// address directly.
   Storage,
-  
+
   /// The decl is a VarDecl with storage defined by a property behavior;
   /// this access may initialize or reassign the storage based on dataflow.
   BehaviorStorage,
diff --git a/include/swift/AST/Expr.h b/include/swift/AST/Expr.h
index 0e38da3..c6be668 100644
--- a/include/swift/AST/Expr.h
+++ b/include/swift/AST/Expr.h
@@ -104,7 +104,7 @@
   Last_CheckedCastKind = Swift3BridgingDowncast,
 };
 
-enum class AccessSemantics : unsigned char {
+enum class AccessSemantics : uint8_t {
   /// On a property or subscript reference, this is a direct access to
   /// the underlying storage.  On a function reference, this is a
   /// non-polymorphic access to a particular implementation.
@@ -113,7 +113,7 @@
   /// On a property or subscript reference, this is a direct,
   /// non-polymorphic access to the getter/setter accessors.
   DirectToAccessor,
-  
+
   /// On a property or subscript reference, this is an access to a property
   /// behavior that may be an initialization. Reads always go through the
   /// 'get' accessor on the property. Writes may go through the 'init' or
diff --git a/include/swift/AST/GenericSignatureBuilder.h b/include/swift/AST/GenericSignatureBuilder.h
index ca901bf..6cf3b17 100644
--- a/include/swift/AST/GenericSignatureBuilder.h
+++ b/include/swift/AST/GenericSignatureBuilder.h
@@ -445,19 +445,16 @@
   /// Note that we have added the nested type nestedPA
   void addedNestedType(PotentialArchetype *nestedPA);
 
-  /// Add a rewrite rule that makes \c otherPA a part of the given equivalence
-  /// class.
+  /// Add a rewrite rule from that makes the two types equivalent.
   ///
   /// \returns true if a new rewrite rule was added, and false otherwise.
-  bool addSameTypeRewriteRule(EquivalenceClass *equivClass,
-                              PotentialArchetype *otherPA);
+  bool addSameTypeRewriteRule(CanType type1, CanType type2);
 
-  /// \brief Add a new conformance requirement specifying that the given
-  /// potential archetypes are equivalent.
-  ConstraintResult addSameTypeRequirementBetweenArchetypes(
-                                               PotentialArchetype *T1,
-                                               PotentialArchetype *T2,
-                                               const RequirementSource *Source);
+  /// \brief Add a same-type requirement between two types that are known to
+  /// refer to type parameters.
+  ConstraintResult addSameTypeRequirementBetweenTypeParameters(
+                                         ResolvedType type1, ResolvedType type2,
+                                         const RequirementSource *source);
   
   /// \brief Add a new conformance requirement specifying that the given
   /// potential archetype is bound to a concrete type.
@@ -811,11 +808,27 @@
   bool areInSameEquivalenceClass(Type type1, Type type2);
 
   /// Simplify the given dependent type down to its canonical representation.
-  ///
-  /// \returns null if the type involved dependent member types that
-  /// don't have associated types.
   Type getCanonicalTypeParameter(Type type);
 
+  /// For each requirement in \c sig, create a new signature without it and see
+  /// if the requirement is satisfied in it.
+  ///
+  /// Specifically, for each Requirement \c req in \c sig, create a new
+  /// signature incorporating all of those in \c baseSig (if not null) and the
+  /// other requirements from \c sig, and if \c req is satisfied in this new
+  /// signature add it to \c redundant, otherwise add it to \c nonRedundant.
+  ///
+  /// If \c includeRedundantRequirements is true, all requirements from \c sig
+  /// (other than \c req) are added; if it is false, requirements already found
+  /// to be redundant are also not added (i.e. the contents of \c redundant at
+  /// that point in time).
+  static void
+  dropAndCompareEachRequirement(ASTContext &context, GenericSignature *baseSig,
+                                GenericSignature *sig,
+                                bool includeRedundantRequirements,
+                                SmallVectorImpl<Requirement> &redundant,
+                                SmallVectorImpl<Requirement> &nonRedundant);
+
   /// Verify the correctness of the given generic signature.
   ///
   /// This routine will test that the given generic signature is both minimal
diff --git a/include/swift/AST/LayoutConstraint.h b/include/swift/AST/LayoutConstraint.h
index 961fa8a..12b5980 100644
--- a/include/swift/AST/LayoutConstraint.h
+++ b/include/swift/AST/LayoutConstraint.h
@@ -31,7 +31,7 @@
 class ASTPrinter;
 
 /// Describes a layout constraint information.
-enum class LayoutConstraintKind : unsigned char {
+enum class LayoutConstraintKind : uint8_t {
   // It is not a known layout constraint.
   UnknownLayout,
   // It is a layout constraint representing a trivial type of an unknown size.
diff --git a/include/swift/AST/Types.h b/include/swift/AST/Types.h
index b57ee74..4bc945b 100644
--- a/include/swift/AST/Types.h
+++ b/include/swift/AST/Types.h
@@ -290,7 +290,7 @@
     HasCachedType : 1
   );
 
-  enum { NumFlagBits = 5 };
+  enum { NumFlagBits = 8 };
   SWIFT_INLINE_BITFIELD(ParenType, SugarType, NumFlagBits,
     /// Whether there is an original type.
     Flags : NumFlagBits
@@ -2367,7 +2367,7 @@
 END_CAN_TYPE_WRAPPER(DynamicSelfType, Type)
 
 /// A language-level calling convention.
-enum class SILFunctionLanguage : unsigned char {
+enum class SILFunctionLanguage : uint8_t {
   /// A variation of the Swift calling convention.
   Swift = 0,
 
diff --git a/include/swift/Basic/PrettyStackTrace.h b/include/swift/Basic/PrettyStackTrace.h
index b7e3f42..036bdfa 100644
--- a/include/swift/Basic/PrettyStackTrace.h
+++ b/include/swift/Basic/PrettyStackTrace.h
@@ -16,6 +16,10 @@
 #include "llvm/Support/PrettyStackTrace.h"
 #include "llvm/ADT/StringRef.h"
 
+namespace llvm {
+  class MemoryBuffer;
+}
+
 namespace swift {
 
 /// A PrettyStackTraceEntry for performing an action involving a StringRef.
@@ -31,6 +35,15 @@
   void print(llvm::raw_ostream &OS) const override;
 };
 
+/// A PrettyStackTraceEntry to dump the contents of a file.
+class PrettyStackTraceFileContents : public llvm::PrettyStackTraceEntry {
+  const llvm::MemoryBuffer &Buffer;
+public:
+  explicit PrettyStackTraceFileContents(const llvm::MemoryBuffer &buffer)
+    : Buffer(buffer) {}
+  void print(llvm::raw_ostream &OS) const override;
+};
+
 } // end namespace swift
 
 #endif // SWIFT_BASIC_PRETTYSTACKTRACE_H
diff --git a/include/swift/Demangling/ManglingMacros.h b/include/swift/Demangling/ManglingMacros.h
index f3e09b4..9c35415 100644
--- a/include/swift/Demangling/ManglingMacros.h
+++ b/include/swift/Demangling/ManglingMacros.h
@@ -34,6 +34,8 @@
 #define METADATA_MANGLING N
 #define METATYPE_MANGLING m
 #define EMPTY_TUPLE_MANGLING yt
+#define ANY_MANGLING yp
+#define ANYOBJECT_MANGLING yXl
 #define NO_ARGS_MANGLING yy
 #define FUNC_TYPE_MANGLING c
 #define NOESCAPE_FUNC_TYPE_MANGLING XE
diff --git a/include/swift/Frontend/ArgsToFrontendInputsConverter.h b/include/swift/Frontend/ArgsToFrontendInputsConverter.h
index d2afd97..f6b1e03 100644
--- a/include/swift/Frontend/ArgsToFrontendInputsConverter.h
+++ b/include/swift/Frontend/ArgsToFrontendInputsConverter.h
@@ -42,21 +42,28 @@
 class ArgsToFrontendInputsConverter {
   DiagnosticEngine &Diags;
   const llvm::opt::ArgList &Args;
-  FrontendInputsAndOutputs &InputsAndOutputs;
 
   llvm::opt::Arg const *const FilelistPathArg;
   llvm::opt::Arg const *const PrimaryFilelistPathArg;
 
-  SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 4> BuffersToKeepAlive;
+  /// A place to keep alive any buffers that are loaded as part of setting up
+  /// the frontend inputs.
+  SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 4> ConfigurationFileBuffers;
 
   llvm::SetVector<StringRef> Files;
 
 public:
   ArgsToFrontendInputsConverter(DiagnosticEngine &diags,
-                                const llvm::opt::ArgList &args,
-                                FrontendInputsAndOutputs &inputsAndOutputs);
+                                const llvm::opt::ArgList &args);
 
-  bool convert();
+  /// Produces a FrontendInputsAndOutputs object with the inputs populated from
+  /// the arguments the converter was initialized with.
+  ///
+  /// \param buffers If present, buffers read in the processing of the frontend
+  /// inputs will be saved here. These should only be used for debugging
+  /// purposes.
+  Optional<FrontendInputsAndOutputs> convert(
+      SmallVectorImpl<std::unique_ptr<llvm::MemoryBuffer>> *buffers);
 
 private:
   bool enforceFilelistExclusion();
@@ -66,11 +73,19 @@
                              llvm::function_ref<void(StringRef)> fn);
   bool addFile(StringRef file);
   Optional<std::set<StringRef>> readPrimaryFiles();
-  std::set<StringRef>
-  createInputFilesConsumingPrimaries(std::set<StringRef> primaryFiles);
-  bool checkForMissingPrimaryFiles(std::set<StringRef> primaryFiles);
 
-  bool isSingleThreadedWMO() const;
+  /// Returns the newly set-up FrontendInputsAndOutputs, as well as a set of
+  /// any unused primary files (those that do not correspond to an input).
+  std::pair<FrontendInputsAndOutputs, std::set<StringRef>>
+  createInputFilesConsumingPrimaries(std::set<StringRef> primaryFiles);
+
+  /// Emits an error for each file in \p unusedPrimaryFiles.
+  ///
+  /// \returns true if \p unusedPrimaryFiles is non-empty.
+  bool diagnoseUnusedPrimaryFiles(std::set<StringRef> unusedPrimaryFiles);
+
+  bool
+  isSingleThreadedWMO(const FrontendInputsAndOutputs &inputsAndOutputs) const;
 };
 
 } // namespace swift
diff --git a/include/swift/Frontend/ArgsToFrontendOptionsConverter.h b/include/swift/Frontend/ArgsToFrontendOptionsConverter.h
index e418c1a..dc37ab9d 100644
--- a/include/swift/Frontend/ArgsToFrontendOptionsConverter.h
+++ b/include/swift/Frontend/ArgsToFrontendOptionsConverter.h
@@ -69,7 +69,13 @@
                                  FrontendOptions &Opts)
       : Diags(Diags), Args(Args), Opts(Opts) {}
 
-  bool convert();
+  /// Populates the FrontendOptions the converter was initialized with.
+  ///
+  /// \param buffers If present, buffers read in the processing of the frontend
+  /// options will be saved here. These should only be used for debugging
+  /// purposes.
+  bool convert(
+      SmallVectorImpl<std::unique_ptr<llvm::MemoryBuffer>> *buffers);
 
   static FrontendOptions::ActionType
   determineRequestedAction(const llvm::opt::ArgList &);
diff --git a/include/swift/Frontend/Frontend.h b/include/swift/Frontend/Frontend.h
index 46aef96..a1f59ae 100644
--- a/include/swift/Frontend/Frontend.h
+++ b/include/swift/Frontend/Frontend.h
@@ -86,11 +86,19 @@
   /// default values given the /absence/ of a flag. This is because \c parseArgs
   /// may be used to modify an already partially configured invocation.
   ///
+  /// Any configuration files loaded as a result of parsing arguments will be
+  /// stored in \p ConfigurationFileBuffers, if non-null. The contents of these
+  /// buffers should \e not be interpreted by the caller; they are only present
+  /// in order to make it possible to reproduce how these arguments were parsed
+  /// if the compiler ends up crashing or exhibiting other bad behavior.
+  ///
   /// If non-empty, relative search paths are resolved relative to
   /// \p workingDirectory.
   ///
   /// \returns true if there was an error, false on success.
   bool parseArgs(ArrayRef<const char *> Args, DiagnosticEngine &Diags,
+                 SmallVectorImpl<std::unique_ptr<llvm::MemoryBuffer>>
+                     *ConfigurationFileBuffers = nullptr,
                  StringRef workingDirectory = {});
 
   /// Sets specific options based on the given serialized Swift binary data.
diff --git a/include/swift/Parse/Lexer.h b/include/swift/Parse/Lexer.h
index 9440aa6..644e9a7 100644
--- a/include/swift/Parse/Lexer.h
+++ b/include/swift/Parse/Lexer.h
@@ -92,22 +92,6 @@
   /// Pointer to the next not consumed character.
   const char *CurPtr;
 
-  /// @{
-  /// Members that are *not* permanent lexer state.  The values only make sense
-  /// during the lexImpl() invocation.  These variables are declared as members
-  /// rather than locals so that we don't have to thread them through to all
-  /// lexing helpers.
-
-  /// Points to the point in the source buffer where we started scanning for
-  /// the current token.  Thus, the range [LastCommentBlockStart, CurPtr)
-  /// covers all comments and whitespace that we skipped, and the token itself.
-  const char *LastCommentBlockStart = nullptr;
-
-  /// True if we have seen a comment while scanning for the current token.
-  bool SeenComment = false;
-
-  /// @}
-
   Token NextToken;
   
   /// \brief This is true if we're lexing a .sil file instead of a .swift
@@ -459,14 +443,6 @@
     return BufferStart + SourceMgr.getLocOffsetInBuffer(Loc, BufferID);
   }
 
-  StringRef getSubstring(const char *Start, unsigned Length) const {
-    assert(Start >= BufferStart && Start <= BufferEnd);
-    unsigned BytesUntilBufferEnd = BufferEnd - Start;
-    if (Length > BytesUntilBufferEnd)
-      Length = BytesUntilBufferEnd;
-    return StringRef(Start, Length);
-  }
-
   void lexImpl();
   InFlightDiagnostic diagnose(const char *Loc, Diagnostic Diag);
   
diff --git a/include/swift/Parse/Parser.h b/include/swift/Parse/Parser.h
index 9759253..19891ae 100644
--- a/include/swift/Parse/Parser.h
+++ b/include/swift/Parse/Parser.h
@@ -276,7 +276,7 @@
   /// Describes the kind of a lexical structure marker, indicating
   /// what kind of structural element we started parsing at a
   /// particular location.
-  enum class StructureMarkerKind : unsigned char {
+  enum class StructureMarkerKind : uint8_t {
     /// The start of a declaration.
     Declaration,
     /// The start of a statement.
diff --git a/include/swift/Remote/MetadataReader.h b/include/swift/Remote/MetadataReader.h
index a331b43..cbf3f05 100644
--- a/include/swift/Remote/MetadataReader.h
+++ b/include/swift/Remote/MetadataReader.h
@@ -284,7 +284,6 @@
         return BuiltType();
       return readNominalTypeFromMetadata(Meta, skipArtificialSubclasses);
     case MetadataKind::Struct:
-      return readNominalTypeFromMetadata(Meta);
     case MetadataKind::Enum:
     case MetadataKind::Optional:
       return readNominalTypeFromMetadata(Meta);
@@ -419,16 +418,20 @@
       return BuiltExist;
     }
     case MetadataKind::ForeignClass: {
-      auto Foreign = cast<TargetForeignClassMetadata<Runtime>>(Meta);
+      auto descriptorAddr = readAddressOfNominalTypeDescriptor(Meta);
+      if (!descriptorAddr)
+        return BuiltType();
+      auto descriptor = readContextDescriptor(descriptorAddr);
+      if (!descriptor)
+        return BuiltType();
 
-      StoredPointer namePtr =
-        resolveRelativeField(Meta,
-                             asFullMetadata(Foreign)->Name);
-      if (namePtr == 0)
+      // Build the demangling tree from the context tree.
+      Demangle::NodeFactory nodeFactory;
+      auto node = buildNominalTypeMangling(descriptor, nodeFactory);
+      if (!node)
         return BuiltType();
-      std::string name;
-      if (!Reader->readString(RemoteAddress(namePtr), name))
-        return BuiltType();
+
+      auto name = Demangle::mangleNode(node);
       auto BuiltForeign = Builder.createForeignClassType(std::move(name));
       TypeCache[MetadataAddress] = BuiltForeign;
       return BuiltForeign;
@@ -1006,6 +1009,11 @@
       auto valueMeta = cast<TargetValueMetadata<Runtime>>(metadata);
       return valueMeta->getDescription();
     }
+        
+    case MetadataKind::ForeignClass: {
+      auto foreignMeta = cast<TargetForeignClassMetadata<Runtime>>(metadata);
+      return foreignMeta->Description;
+    }
 
     default:
       return 0;
diff --git a/include/swift/Runtime/Metadata.h b/include/swift/Runtime/Metadata.h
index 12d4515..9253e8c 100644
--- a/include/swift/Runtime/Metadata.h
+++ b/include/swift/Runtime/Metadata.h
@@ -1612,21 +1612,11 @@
     /// flag is set.
     RelativeDirectPointer<InitializationFunction_t> InitializationFunction;
     
-    /// The uniquing key for the metadata record. Metadata records with the
-    /// same Name string are considered equivalent by the runtime, and the
-    /// runtime will pick one to be canonical.
-    RelativeDirectPointer<const char> Name;
-
     mutable std::atomic<CacheValue> Cache;
   };
 
   struct HeaderType : HeaderPrefix, TargetTypeMetadataHeader<Runtime> {};
 
-  TargetPointer<Runtime, const char> getName() const {
-    return reinterpret_cast<TargetPointer<Runtime, const char>>(
-      asFullMetadata(this)->Name.get());
-  }
-
   CacheValue getCacheValue() const {
     /// NB: This can be a relaxed-order load if there is no initialization
     /// function. On platforms Swift currently targets, consume is no more
@@ -1941,7 +1931,7 @@
   FullMetadata<TupleTypeMetadata> METADATA_SYM(EMPTY_TUPLE_MANGLING);
 
 template <typename Runtime> struct TargetProtocolDescriptor;
-  
+
 /// An array of protocol descriptors with a header and tail-allocated elements.
 template <typename Runtime>
 struct TargetProtocolDescriptorList {
@@ -2131,6 +2121,10 @@
     : TargetMetadata<Runtime>(MetadataKind::Existential),
       Flags(ExistentialTypeFlags()), Protocols() {}
   
+  explicit constexpr TargetExistentialTypeMetadata(ExistentialTypeFlags Flags)
+    : TargetMetadata<Runtime>(MetadataKind::Existential),
+      Flags(Flags), Protocols() {}
+
   /// Get the representation form this existential type uses.
   ExistentialTypeRepresentation getRepresentation() const;
   
@@ -2192,6 +2186,17 @@
 using ExistentialTypeMetadata
   = TargetExistentialTypeMetadata<InProcess>;
 
+/// The standard metadata for the empty protocol composition type, Any.
+SWIFT_RUNTIME_EXPORT
+const
+  FullMetadata<ExistentialTypeMetadata> METADATA_SYM(ANY_MANGLING);
+
+/// The standard metadata for the empty class-constrained protocol composition
+/// type, AnyObject.
+SWIFT_RUNTIME_EXPORT
+const
+  FullMetadata<ExistentialTypeMetadata> METADATA_SYM(ANYOBJECT_MANGLING);
+
 /// The basic layout of an existential metatype type.
 template <typename Runtime>
 struct TargetExistentialMetatypeContainer {
@@ -2654,7 +2659,7 @@
 
 template<typename Runtime>
 struct TargetGenericContextDescriptorHeader {
-  uint32_t NumParams, NumRequirements, NumKeyArguments, NumExtraArguments;
+  uint16_t NumParams, NumRequirements, NumKeyArguments, NumExtraArguments;
   
   uint32_t getNumArguments() const {
     return NumKeyArguments + NumExtraArguments;
diff --git a/include/swift/SIL/Consumption.h b/include/swift/SIL/Consumption.h
index 56921e8..b279ef8 100644
--- a/include/swift/SIL/Consumption.h
+++ b/include/swift/SIL/Consumption.h
@@ -30,7 +30,7 @@
 enum IsInitialization_t : bool { IsNotInitialization, IsInitialization };
 
 /// The behavior of a dynamic cast operation on the source value.
-enum class CastConsumptionKind : unsigned char {
+enum class CastConsumptionKind : uint8_t {
   /// The source value is always taken, regardless of whether the cast
   /// succeeds.  That is, if the cast fails, the source value is
   /// destroyed.
diff --git a/include/swift/SIL/InstructionUtils.h b/include/swift/SIL/InstructionUtils.h
index b2ac4f1..4f4755c 100644
--- a/include/swift/SIL/InstructionUtils.h
+++ b/include/swift/SIL/InstructionUtils.h
@@ -48,6 +48,11 @@
 /// upcasts and downcasts.
 SILValue stripClassCasts(SILValue V);
 
+/// Return the underlying SILValue after stripping off non-projection address
+/// casts. The result will still be an address--this does not look through
+/// pointer-to-address.
+SILValue stripAddressAccess(SILValue V);
+
 /// Return the underlying SILValue after stripping off all address projection
 /// instructions.
 SILValue stripAddressProjections(SILValue V);
@@ -87,6 +92,10 @@
 /// type may be changed by a cast.
 SingleValueInstruction *getSingleValueCopyOrCast(SILInstruction *I);
 
+/// Return true if this instruction terminates a SIL-level scope. Scope end
+/// instructions do not produce a result.
+bool isEndOfScopeMarker(SILInstruction *user);
+
 /// Return true if the given instruction has no effect on it's operand values
 /// and produces no result. These are typically end-of scope markers.
 ///
diff --git a/include/swift/SIL/SILBuilder.h b/include/swift/SIL/SILBuilder.h
index 6505905..0190452 100644
--- a/include/swift/SIL/SILBuilder.h
+++ b/include/swift/SIL/SILBuilder.h
@@ -47,6 +47,7 @@
   SILBasicBlock *BB;
   SILBasicBlock::iterator InsertPt;
   const SILDebugScope *CurDebugScope = nullptr;
+  Optional<SILLocation> CurDebugLocOverride = None;
 
   /// If this pointer is non-null, then any inserted instruction is
   /// recorded in this list.
@@ -141,6 +142,18 @@
   void setCurrentDebugScope(const SILDebugScope *DS) { CurDebugScope = DS; }
   const SILDebugScope *getCurrentDebugScope() const { return CurDebugScope; }
 
+  /// Apply a debug location override. If loc is None, the current override is
+  /// removed. Otherwise, newly created debug locations use the given location.
+  /// Note: the override location does not apply to debug_value[_addr].
+  void applyDebugLocOverride(Optional<SILLocation> loc) {
+    CurDebugLocOverride = loc;
+  }
+
+  /// Get the current debug location override.
+  Optional<SILLocation> getCurrentDebugLocOverride() const {
+    return CurDebugLocOverride;
+  }
+
   /// Convenience function for building a SILDebugLocation.
   SILDebugLocation getSILDebugLocation(SILLocation Loc) {
     // FIXME: Audit all uses and enable this assertion.
@@ -148,7 +161,8 @@
     auto Scope = getCurrentDebugScope();
     if (!Scope && F)
         Scope = F->getDebugScope();
-    return SILDebugLocation(Loc, Scope);
+    auto overriddenLoc = CurDebugLocOverride ? *CurDebugLocOverride : Loc;
+    return SILDebugLocation(overriddenLoc, Scope);
   }
 
   //===--------------------------------------------------------------------===//
@@ -733,16 +747,9 @@
   }
 
   DebugValueInst *createDebugValue(SILLocation Loc, SILValue src,
-                                   SILDebugVariable Var) {
-    return insert(DebugValueInst::create(getSILDebugLocation(Loc), src,
-                                         getModule(), Var));
-  }
-  DebugValueAddrInst *
-  createDebugValueAddr(SILLocation Loc, SILValue src,
-                       SILDebugVariable Var) {
-    return insert(DebugValueAddrInst::create(getSILDebugLocation(Loc), src,
-                                             getModule(), Var));
-  }
+                                   SILDebugVariable Var);
+  DebugValueAddrInst *createDebugValueAddr(SILLocation Loc, SILValue src,
+                                           SILDebugVariable Var);
 
   LoadWeakInst *createLoadWeak(SILLocation Loc, SILValue src, IsTake_t isTake) {
     return insert(new (getModule())
@@ -2095,6 +2102,35 @@
   }
 };
 
+/// Apply a debug location override for the duration of the current scope.
+class DebugLocOverrideRAII {
+  SILBuilder &Builder;
+  Optional<SILLocation> oldOverride;
+#ifndef NDEBUG
+  Optional<SILLocation> installedOverride;
+#endif
+
+public:
+  DebugLocOverrideRAII(SILBuilder &B, Optional<SILLocation> Loc) : Builder(B) {
+    oldOverride = B.getCurrentDebugLocOverride();
+    Builder.applyDebugLocOverride(Loc);
+#ifndef NDEBUG
+    installedOverride = Loc;
+#endif
+  }
+
+  ~DebugLocOverrideRAII() {
+    assert(Builder.getCurrentDebugLocOverride() == installedOverride &&
+           "Restoring debug location override to an unexpected state");
+    Builder.applyDebugLocOverride(oldOverride);
+  }
+
+  DebugLocOverrideRAII(const DebugLocOverrideRAII &) = delete;
+  DebugLocOverrideRAII &operator=(const DebugLocOverrideRAII &) = delete;
+  DebugLocOverrideRAII(DebugLocOverrideRAII &&) = delete;
+  DebugLocOverrideRAII &operator=(DebugLocOverrideRAII &&) = delete;
+};
+
 } // end swift namespace
 
 #endif
diff --git a/include/swift/SIL/SILLinkage.h b/include/swift/SIL/SILLinkage.h
index 47008dd..6559bb7 100644
--- a/include/swift/SIL/SILLinkage.h
+++ b/include/swift/SIL/SILLinkage.h
@@ -29,7 +29,7 @@
 /// first does not, perhaps by reading a value out of it (and then
 /// ignoring the result) or retaining it (and then releasing it
 /// later).
-enum class SILLinkage : unsigned char {
+enum class SILLinkage : uint8_t {
   /// This object definition is visible to multiple Swift modules (and
   /// thus potentially across linkage-unit boundaries).  There are no
   /// other object definitions with this name in the program.
@@ -79,7 +79,7 @@
   /// module. Besides that caveat this should be treated exactly the same as
   /// shared.
   SharedExternal,
-  
+
   /// The same as SharedExternal, except that the definition is private in the
   /// other module. This can only occur if an inlined fragile function from
   /// another module references a private definition in the other module.
@@ -109,7 +109,7 @@
 };
 
 /// The scope in which a subclassable class can be subclassed.
-enum class SubclassScope : unsigned char {
+enum class SubclassScope : uint8_t {
   /// This class can be subclassed in other modules.
   External,
 
diff --git a/include/swift/SILOptimizer/Analysis/SimplifyInstruction.h b/include/swift/SILOptimizer/Analysis/SimplifyInstruction.h
index b9404b2..145e6c9 100644
--- a/include/swift/SILOptimizer/Analysis/SimplifyInstruction.h
+++ b/include/swift/SILOptimizer/Analysis/SimplifyInstruction.h
@@ -16,6 +16,10 @@
 //
 //===----------------------------------------------------------------------===//
 
+#ifndef SWIFT_SILOPTIMIZER_ANALYSIS_SIMPLIFYINSTRUCTION_H
+#define SWIFT_SILOPTIMIZER_ANALYSIS_SIMPLIFYINSTRUCTION_H
+
+#include "swift/SIL/SILBasicBlock.h"
 #include "swift/SIL/SILInstruction.h"
 
 namespace swift {
@@ -28,6 +32,16 @@
 /// returned, otherwise a null SILValue is returned.
 SILValue simplifyInstruction(SILInstruction *I);
 
+/// Replace an instruction with a simplified result and erase it. If the
+/// instruction initiates a scope, do not replace the end of its scope; it will
+/// be deleted along with its parent.
+///
+/// If it is nonnull, eraseNotify will be called before each instruction is
+/// deleted.
+void replaceAllSimplifiedUsesAndErase(
+    SILInstruction *I, SILValue result,
+    std::function<void(SILInstruction *)> eraseNotify = nullptr);
+
 /// Simplify invocations of builtin operations that may overflow.
 /// All such operations return a tuple (result, overflow_flag).
 /// This function try to simplify such operations, but returns only a
@@ -39,3 +53,5 @@
 SILValue simplifyOverflowBuiltinInstruction(BuiltinInst *BI);
 
 } // end namespace swift
+
+#endif // SWIFT_SILOPTIMIZER_ANALYSIS_SIMPLIFYINSTRUCTION_H
diff --git a/include/swift/Syntax/Trivia.h.gyb b/include/swift/Syntax/Trivia.h.gyb
index 94b74dd..be9e112 100644
--- a/include/swift/Syntax/Trivia.h.gyb
+++ b/include/swift/Syntax/Trivia.h.gyb
@@ -170,6 +170,8 @@
     }
   }
 
+  bool isComment() const;
+
   void accumulateAbsolutePosition(AbsolutePosition &Pos) const;
   
   /// Try to compose this and Next to one TriviaPiece.
diff --git a/lib/AST/ConformanceLookupTable.h b/lib/AST/ConformanceLookupTable.h
index 3a08deb..18f93d3 100644
--- a/lib/AST/ConformanceLookupTable.h
+++ b/lib/AST/ConformanceLookupTable.h
@@ -42,7 +42,7 @@
 class ConformanceLookupTable {
   /// Describes the stage at which a particular nominal type or
   /// extension's conformances has been processed.
-  enum class ConformanceStage : unsigned char {
+  enum class ConformanceStage : uint8_t {
     /// The explicit conformances have been recorded in the lookup table.
     RecordedExplicit,
 
diff --git a/lib/AST/GenericSignature.cpp b/lib/AST/GenericSignature.cpp
index c8d446b..d4edd74 100644
--- a/lib/AST/GenericSignature.cpp
+++ b/lib/AST/GenericSignature.cpp
@@ -23,10 +23,17 @@
 #include "swift/AST/PrettyStackTrace.h"
 #include "swift/AST/Types.h"
 #include "swift/Basic/STLExtras.h"
+#include "llvm/ADT/Statistic.h"
 #include <functional>
 
 using namespace swift;
 
+#define DEBUG_TYPE "Generic signature"
+STATISTIC(NumRedundantRequirements,
+          "# of redundant requirements found in signature differencing");
+STATISTIC(NumNonRedundantRequirements,
+          "# of non-redundant requirements found in signature differencing");
+
 void ConformanceAccessPath::print(raw_ostream &out) const {
   interleave(begin(), end(),
              [&](const Entry &entry) {
@@ -770,6 +777,7 @@
 
 SmallVector<Requirement, 4> GenericSignature::requirementsNotSatisfiedBy(
                                                  GenericSignature *otherSig) {
+  auto &ctxt = getASTContext();
   SmallVector<Requirement, 4> result;
 
   // If the signatures are the same, all requirements are satisfied.
@@ -783,10 +791,52 @@
   }
 
   // Find the requirements that aren't satisfied.
-  for (const auto &req : getRequirements()) {
-    if (!otherSig->isRequirementSatisfied(req))
-      result.push_back(req);
-  }
+  //
+  // This is unfortunately quadratic in the size of getRequirements(), but some
+  // arrangements of signatures result in different canonicalizations that mean
+  // a requirement in `this` is satisfied by `otherSig`, but not in
+  // isolation. Specifically, consider:
+  //
+  // otherSig == <T, U where U: P1>
+  // this == <T, U where T: P1, T == U>`
+  //
+  // `T: P1` is implied by `U: P1` and `T == U` together, but just checking T:
+  // P1 in `otherSig` won't find this, because it misses the T == U
+  // connection. We don't currently know of a great way to handle this in
+  // general, and instead have to do a brute-force search.
+
+  SmallVector<Requirement, 4> redundant;
+  GenericSignatureBuilder::dropAndCompareEachRequirement(
+      ctxt, otherSig, this,
+      /*includeRedundantRequirements=*/false, redundant, result);
+
+  NumNonRedundantRequirements += result.size();
+  NumRedundantRequirements += redundant.size();
+
+#ifndef NDEBUG
+  // `otherSig + result` should be `this`, so let's check it.
+  GenericSignatureBuilder builder(ctxt);
+
+  // otherSig may have fewer generic parameters, so we can't use
+  // addGenericSignature directly.
+
+  auto source =
+      GenericSignatureBuilder::FloatingRequirementSource::forAbstract();
+  for (auto gp : getGenericParams())
+    builder.addGenericParameter(gp);
+  for (auto req : otherSig->getRequirements())
+    builder.addRequirement(req, source, nullptr);
+  for (auto req : result)
+    builder.addRequirement(req, source, nullptr);
+
+  auto newSig = std::move(builder).computeGenericSignature(
+      SourceLoc(),
+      /*allowConcreteGenericParams=*/true,
+      /*allowBuilderToMove=*/true);
+
+  assert(newSig->getCanonicalSignature() == getCanonicalSignature() &&
+         "signature differencing removed too many requirements");
+#endif
 
   return result;
 }
diff --git a/lib/AST/GenericSignatureBuilder.cpp b/lib/AST/GenericSignatureBuilder.cpp
index 0d96054..158ab66 100644
--- a/lib/AST/GenericSignatureBuilder.cpp
+++ b/lib/AST/GenericSignatureBuilder.cpp
@@ -166,17 +166,17 @@
   ///
   /// \returns the path, or None if it contained unresolved dependent member
   /// types.
-  Optional<RewritePath> static createPath(Type type);
+  RewritePath static createPath(Type type);
 
   /// Decompose a type into a path.
   ///
   /// \param path Will be filled in with the components of the path, in
   /// reverse order.
   ///
-  /// \returns the generic parameter at the start of the path, or \c None if
-  ///
-  Optional<GenericParamKey>
-  static createPath(Type type, SmallVectorImpl<AssociatedTypeDecl *> &path);
+  /// \returns the generic parameter at the start of the path.
+  static GenericParamKey createPath(
+                                Type type,
+                                SmallVectorImpl<AssociatedTypeDecl *> &path);
 
   /// Compute the longer common prefix between this path and \c other.
   RewritePath commonPath(const RewritePath &other) const;
@@ -216,11 +216,11 @@
                   EquivalenceClass &equivClass)
     : builder(builder), equivClass(equivClass) { }
 
-  Optional<RewritePath> getAnchorPath() {
-    if (anchorPath) return anchorPath;
+  const RewritePath &getAnchorPath() {
+    if (anchorPath) return *anchorPath;
 
     anchorPath = RewritePath::createPath(equivClass.getAnchor(builder, { }));
-    return anchorPath;
+    return *anchorPath;
   }
 };
 
@@ -437,9 +437,9 @@
   /// Equivalence classes that are not currently being used.
   std::vector<void *> FreeEquivalenceClasses;
 
-  /// The roots of the rewrite tree.
-  DenseMap<const EquivalenceClass *, std::unique_ptr<RewriteTreeNode>>
-    RewriteTreeRoots;
+  /// The roots of the rewrite tree, keyed on the canonical, dependent
+  /// types.
+  DenseMap<CanType, std::unique_ptr<RewriteTreeNode>> RewriteTreeRoots;
 
   /// The generation number for the term-rewriting system, which is
   /// increased every time a new rule gets added.
@@ -482,15 +482,12 @@
   /// Deallocate the given equivalence class, returning it to the free list.
   void deallocateEquivalenceClass(EquivalenceClass *equivClass);
 
-  /// Retrieve the rewrite tree root for the given equivalence class,
-  /// if present.
-  RewriteTreeNode *getRewriteTreeRootIfPresent(
-                                      const EquivalenceClass *equivClass);
+  /// Retrieve the rewrite tree root for the given anchor type.
+  RewriteTreeNode *getRewriteTreeRootIfPresent(CanType anchor);
 
-  /// Retrieve the rewrite tree root for the given equivalence class,
+  /// Retrieve the rewrite tree root for the given anchor type,
   /// creating it if needed.
-  RewriteTreeNode *getOrCreateRewriteTreeRoot(
-                                        const EquivalenceClass *equivClass);
+  RewriteTreeNode *getOrCreateRewriteTreeRoot(CanType anchor);
 
   /// Minimize the rewrite tree by minimizing the right-hand sides and
   /// removing redundant rules.
@@ -2293,8 +2290,8 @@
   bool updatedAnchor = false;
   for (auto member : members) {
     auto anchorType =
-      builder.getCanonicalTypeParameter(member->getDependentType(genericParams));
-    if (!anchorType) continue;
+      builder.getCanonicalTypeParameter(
+                                    member->getDependentType(genericParams));
 
 #ifndef NDEBUG
     // Check that we get consistent results from all of the anchors.
@@ -2493,7 +2490,11 @@
   out << "\n";
 
   if (builder) {
-    if (auto rewriteRoot = builder->Impl->getRewriteTreeRootIfPresent(this)) {
+    CanType anchorType =
+      const_cast<EquivalenceClass *>(this)->getAnchor(*builder, { })
+        ->getCanonicalType();
+    if (auto rewriteRoot =
+          builder->Impl->getRewriteTreeRootIfPresent(anchorType)) {
       out << "---Rewrite tree---\n";
       rewriteRoot->dump(out);
     }
@@ -3173,30 +3174,23 @@
   }
 }
 
-Optional<RewritePath> RewritePath::createPath(Type type) {
+RewritePath RewritePath::createPath(Type type) {
   SmallVector<AssociatedTypeDecl *, 4> path;
-  if (auto genericParam = createPath(type, path)) {
-    return RewritePath(*genericParam, path, Reverse);
-  }
-
-  return None;
+  auto genericParam = createPath(type, path);
+  return RewritePath(genericParam, path, Reverse);
 }
 
-Optional<GenericParamKey>
-RewritePath::createPath(Type type,
-                        SmallVectorImpl<AssociatedTypeDecl *> &path) {
+GenericParamKey RewritePath::createPath(
+                                Type type,
+                                SmallVectorImpl<AssociatedTypeDecl *> &path) {
   while (auto depMemTy = type->getAs<DependentMemberType>()) {
     auto assocType = depMemTy->getAssocType();
-    if (!assocType) return None;
-
+    assert(assocType && "Unresolved dependent member type");
     path.push_back(assocType);
     type = depMemTy->getBase();
   }
 
-  auto genericParam = type->getAs<GenericTypeParamType>();
-  if (!genericParam) return None;
-
-  return GenericParamKey(genericParam);
+  return type->castTo<GenericTypeParamType>();
 }
 
 RewritePath RewritePath::commonPath(const RewritePath &other) const {
@@ -3244,15 +3238,14 @@
     return CanType(::formDependentType(ctx, *base, getPath()));
 
   assert(anchorPathCache && "Need an anchor path cache");
-  Optional<RewritePath> anchorPath = anchorPathCache->getAnchorPath();
-  if (!anchorPath) return CanType();
+  const RewritePath &anchorPath = anchorPathCache->getAnchorPath();
 
   // Add the relative path to the anchor path.
   SmallVector<AssociatedTypeDecl *, 4> absolutePath;
-  absolutePath.append(anchorPath->getPath().begin(),
-                      anchorPath->getPath().end());
+  absolutePath.append(anchorPath.getPath().begin(),
+                      anchorPath.getPath().end());
   absolutePath.append(getPath().begin(), getPath().end());
-  return CanType(::formDependentType(ctx, *anchorPath->getBase(),
+  return CanType(::formDependentType(ctx, *anchorPath.getBase(),
                                      absolutePath));
 
 }
@@ -3551,8 +3544,8 @@
 
 RewriteTreeNode *
 GenericSignatureBuilder::Implementation::getRewriteTreeRootIfPresent(
-                                          const EquivalenceClass *equivClass) {
-  auto known = RewriteTreeRoots.find(equivClass);
+                                          CanType anchor) {
+  auto known = RewriteTreeRoots.find(anchor);
   if (known != RewriteTreeRoots.end()) return known->second.get();
 
   return nullptr;
@@ -3560,11 +3553,11 @@
 
 RewriteTreeNode *
 GenericSignatureBuilder::Implementation::getOrCreateRewriteTreeRoot(
-                                          const EquivalenceClass *equivClass) {
-  auto known = RewriteTreeRoots.find(equivClass);
+                                          CanType anchor) {
+  auto known = RewriteTreeRoots.find(anchor);
   if (known != RewriteTreeRoots.end()) return known->second.get();
 
-  auto &root = RewriteTreeRoots[equivClass];
+  auto &root = RewriteTreeRoots[anchor];
   root = std::unique_ptr<RewriteTreeNode>(new RewriteTreeNode(nullptr));
   return root.get();
 }
@@ -3593,7 +3586,8 @@
 
   // Minimize the right-hand sides of each rule in the tree.
   for (auto &equivClass : EquivalenceClasses) {
-    auto root = RewriteTreeRoots.find(&equivClass);
+    CanType anchorType = equivClass.getAnchor(builder, { })->getCanonicalType();
+    auto root = RewriteTreeRoots.find(anchorType);
     if (root == RewriteTreeRoots.end()) continue;
 
     AnchorPathCache anchorPathCache(builder, equivClass);
@@ -3618,9 +3612,9 @@
       ++NumRewriteRhsSimplified;
 
       // Determine replacement path, which might be relative to the anchor.
-      auto canonicalRhsPath = *RewritePath::createPath(canonicalRhsType);
+      auto canonicalRhsPath = RewritePath::createPath(canonicalRhsType);
       auto anchorPath = anchorPathCache.getAnchorPath();
-      if (auto prefix = anchorPath->commonPath(canonicalRhsPath)) {
+      if (auto prefix = anchorPath.commonPath(canonicalRhsPath)) {
         unsigned prefixLength = prefix.getPath().size();
         RelativeRewritePath replacementRhsPath =
           canonicalRhsPath.getPath().slice(prefixLength);
@@ -3648,7 +3642,8 @@
 
   // Minimize the right-hand sides of each rule in the tree.
   for (auto &equivClass : EquivalenceClasses) {
-    auto root = RewriteTreeRoots.find(&equivClass);
+    CanType anchorType = equivClass.getAnchor(builder, { })->getCanonicalType();
+    auto root = RewriteTreeRoots.find(anchorType);
     if (root == RewriteTreeRoots.end()) continue;
 
     AnchorPathCache anchorPathCache(builder, equivClass);
@@ -3663,7 +3658,6 @@
 
       // Simplify the left-hand type.
       Type simplifiedLhsType = builder.getCanonicalTypeParameter(lhsType);
-      if (!simplifiedLhsType) return RewriteTreeNode::RuleAction::none();
 
       // Compute the type of the right-hand side.
       Type rhsType = rhs.formDependentType(ctx, &anchorPathCache);
@@ -3680,25 +3674,13 @@
   }
 }
 
-bool GenericSignatureBuilder::addSameTypeRewriteRule(
-                                                EquivalenceClass *equivClass,
-                                                PotentialArchetype *otherPA){
-  // Simplify both sides in the hope of uncovering a common path.
-  Type simplifiedType1 = equivClass->getAnchor(*this, { });
-  if (!simplifiedType1) return false;
-
-  Type simplifiedType2;
-  if (auto otherEquivClass = otherPA->getEquivalenceClassIfPresent())
-    simplifiedType2 = otherEquivClass->getAnchor(*this, { });
-  else
-    simplifiedType2 = getCanonicalTypeParameter(otherPA->getDependentType({ }));
-  if (!simplifiedType2) return false;
-
+bool GenericSignatureBuilder::addSameTypeRewriteRule(CanType type1,
+                                                     CanType type2) {
   // We already effectively have this rewrite rule.
-  if (simplifiedType1->isEqual(simplifiedType2)) return false;
+  if (type1 == type2) return false;
 
-  auto path1 = *RewritePath::createPath(simplifiedType1);
-  auto path2 = *RewritePath::createPath(simplifiedType2);
+  auto path1 = RewritePath::createPath(type1);
+  auto path2 = RewritePath::createPath(type2);
 
   // Look for a common prefix. When we have one, form a rewrite rule using
   // relative paths.
@@ -3712,14 +3694,13 @@
     if (compareDependentPaths(relPath1, relPath2) < 0)
       std::swap(relPath1, relPath2);
 
-    // Find the equivalence class for the prefix.
+    // Find the anchor for the prefix.
     CanType commonType = prefix.formDependentType(getASTContext());
-    auto equivClass =
-      resolveEquivalenceClass(commonType, ArchetypeResolutionKind::WellFormed);
-    assert(equivClass && "Prefix cannot be resolved?");
+    CanType commonAnchor =
+      getCanonicalTypeParameter(commonType)->getCanonicalType();
 
     // Add the rewrite rule.
-    auto root = Impl->getOrCreateRewriteTreeRoot(equivClass);
+    auto root = Impl->getOrCreateRewriteTreeRoot(commonAnchor);
     return root->addRewriteRule(
                           relPath1,
                           RewritePath(None, relPath2, RewritePath::Forward));
@@ -3728,44 +3709,36 @@
   // Otherwise, form a rewrite rule with absolute paths.
 
   // Find the better path and make sure it's in path2.
-  if (compareDependentTypes(simplifiedType1, simplifiedType2) < 0) {
+  if (compareDependentTypes(type1, type2) < 0) {
     std::swap(path1, path2);
-    std::swap(simplifiedType1, simplifiedType2);
+    std::swap(type1, type2);
   }
 
   // Add the rewrite rule.
   Type firstBase =
     GenericTypeParamType::get(path1.getBase()->Depth, path1.getBase()->Index,
                               getASTContext());
-  auto baseEquivClass =
-    resolveEquivalenceClass(firstBase, ArchetypeResolutionKind::WellFormed);
-  assert(baseEquivClass && "Base cannot be resolved?");
-
-  auto root = Impl->getOrCreateRewriteTreeRoot(baseEquivClass);
+  CanType baseAnchor =
+    getCanonicalTypeParameter(firstBase)->getCanonicalType();
+  auto root = Impl->getOrCreateRewriteTreeRoot(baseAnchor);
   return root->addRewriteRule(path1.getPath(), path2);
 }
 
 Type GenericSignatureBuilder::getCanonicalTypeParameter(Type type) {
   auto initialPath = RewritePath::createPath(type);
-  if (!initialPath) return nullptr;
-
   auto genericParamType =
-    GenericTypeParamType::get(initialPath->getBase()->Depth,
-                              initialPath->getBase()->Index,
+    GenericTypeParamType::get(initialPath.getBase()->Depth,
+                              initialPath.getBase()->Index,
                               getASTContext());
-  auto initialEquivClass =
-    resolveEquivalenceClass(genericParamType,
-                            ArchetypeResolutionKind::WellFormed);
-  if (!initialEquivClass) return nullptr;
 
   unsigned startIndex = 0;
-  auto equivClass = initialEquivClass;
   Type currentType = genericParamType;
-  SmallVector<AssociatedTypeDecl *, 4> path(initialPath->getPath().begin(),
-                                            initialPath->getPath().end());
+  SmallVector<AssociatedTypeDecl *, 4> path(initialPath.getPath().begin(),
+                                            initialPath.getPath().end());
   bool simplified = false;
   do {
-    if (auto rootNode = Impl->getRewriteTreeRootIfPresent(equivClass)) {
+    CanType currentAnchor = currentType->getCanonicalType();
+    if (auto rootNode = Impl->getRewriteTreeRootIfPresent(currentAnchor)) {
       // Find the best rewrite rule for the path starting at startIndex.
       auto match =
         rootNode->bestRewritePath(genericParamType,
@@ -3795,17 +3768,12 @@
           genericParamType =
             GenericTypeParamType::get(newBase->Depth, newBase->Index,
                                       getASTContext());
-          initialEquivClass =
-            resolveEquivalenceClass(genericParamType,
-                                    ArchetypeResolutionKind::WellFormed);
-          assert(initialEquivClass && "Must have an equivalence class");
         }
 
         // Move back to the beginning; we may have opened up other rewrites.
         simplified = true;
         startIndex = 0;
         currentType = genericParamType;
-        equivClass = initialEquivClass;
         continue;
       }
     }
@@ -3813,12 +3781,7 @@
     // If we've hit the end of the path, we're done.
     if (startIndex >= path.size()) break;
 
-    // FIXME: It would be nice if there were a better way to get the equivalence
-    // class of a named nested type.
     currentType = DependentMemberType::get(currentType, path[startIndex++]);
-    equivClass =
-      resolveEquivalenceClass(currentType, ArchetypeResolutionKind::WellFormed);
-    if (!equivClass) break;
   } while (true);
 
   return formDependentType(genericParamType, path);
@@ -4865,14 +4828,18 @@
 }
 
 ConstraintResult
-GenericSignatureBuilder::addSameTypeRequirementBetweenArchetypes(
-       PotentialArchetype *OrigT1,
-       PotentialArchetype *OrigT2,
-       const RequirementSource *Source) 
+GenericSignatureBuilder::addSameTypeRequirementBetweenTypeParameters(
+                                         ResolvedType type1, ResolvedType type2,
+                                         const RequirementSource *source)
 {
+  // Both sides are type parameters; equate them.
+  // FIXME: Realizes potential archetypes far too early.
+  auto OrigT1 = type1.realizePotentialArchetype(*this);
+  auto OrigT2 = type2.realizePotentialArchetype(*this);
+
   // Record the same-type constraint, and bail out if it was already known.
   if (!OrigT1->getOrCreateEquivalenceClass(*this)
-        ->recordSameTypeConstraint(OrigT1, OrigT2, Source))
+        ->recordSameTypeConstraint(OrigT1, OrigT2, source))
     return ConstraintResult::Resolved;
 
   // Operate on the representatives
@@ -4889,10 +4856,15 @@
     std::swap(OrigT1, OrigT2);
   }
 
-  // Add a rewrite rule to map T2 down to the anchor.
   auto equivClass = T1->getOrCreateEquivalenceClass(*this);
-  if (addSameTypeRewriteRule(equivClass, T2))
-    ++Impl->RewriteGeneration;
+  auto equivClass2 = T2->getEquivalenceClassIfPresent();
+
+  // Determine the anchor types of the two equivalence classes.
+  CanType anchor1 = equivClass->getAnchor(*this, { })->getCanonicalType();
+  CanType anchor2 =
+    (equivClass2 ? equivClass2->getAnchor(*this, { })
+                 : getCanonicalTypeParameter(T2->getDependentType({ })))
+      ->getCanonicalType();
 
   // Merge the equivalence classes.
   equivClass->modified(*this);
@@ -4902,7 +4874,6 @@
     equivClass->addMember(equiv);
 
   // Grab the old equivalence class, if present. We'll deallocate it at the end.
-  auto equivClass2 = T2->getEquivalenceClassIfPresent();
   SWIFT_DEFER {
     if (equivClass2)
       Impl->deallocateEquivalenceClass(equivClass2);
@@ -4918,31 +4889,35 @@
                                    equivClass->sameTypeConstraints.end(),
                                    equivClass2->sameTypeConstraints.begin(),
                                    equivClass2->sameTypeConstraints.end());
+  }
 
-    // Combine the rewrite rules.
-    if (auto rewriteRoot2 = Impl->getOrCreateRewriteTreeRoot(equivClass2)) {
-      if (auto rewriteRoot1 = Impl->getOrCreateRewriteTreeRoot(equivClass)) {
-        // Merge the second rewrite tree into the first.
-        if (rewriteRoot2->mergeInto(rewriteRoot1))
-          ++Impl->RewriteGeneration;
-        Impl->RewriteTreeRoots.erase(equivClass2);
-      } else {
-        // Take the second rewrite tree and make it the first.
-        auto root2Entry = Impl->RewriteTreeRoots.find(equivClass2);
-        auto root2Ptr = std::move(root2Entry->second);
-        Impl->RewriteTreeRoots.erase(root2Entry);
-        (void)Impl->RewriteTreeRoots.insert({equivClass, std::move(root2Ptr)});
-      }
+  // Combine the rewrite rules.
+  if (auto rewriteRoot2 = Impl->getOrCreateRewriteTreeRoot(anchor2)) {
+    if (auto rewriteRoot1 = Impl->getOrCreateRewriteTreeRoot(anchor1)) {
+      // Merge the second rewrite tree into the first.
+      if (rewriteRoot2->mergeInto(rewriteRoot1))
+        ++Impl->RewriteGeneration;
+      Impl->RewriteTreeRoots.erase(anchor2);
+    } else {
+      // Take the second rewrite tree and make it the first.
+      auto root2Entry = Impl->RewriteTreeRoots.find(anchor2);
+      auto root2Ptr = std::move(root2Entry->second);
+      Impl->RewriteTreeRoots.erase(root2Entry);
+      (void)Impl->RewriteTreeRoots.insert({anchor1, std::move(root2Ptr)});
     }
   }
 
+  // Add a rewrite rule to map the anchor of T2 down to the anchor of T1.
+  if (addSameTypeRewriteRule(anchor2, anchor1))
+    ++Impl->RewriteGeneration;
+
   // Same-type-to-concrete requirements.
   bool t1IsConcrete = !equivClass->concreteType.isNull();
   bool t2IsConcrete = equivClass2 && !equivClass2->concreteType.isNull();
   if (t2IsConcrete) {
     if (t1IsConcrete) {
       (void)addSameTypeRequirement(equivClass->concreteType,
-                                   equivClass2->concreteType, Source,
+                                   equivClass2->concreteType, source,
                                    UnresolvedHandlingKind::GenerateConstraints,
                                    SameTypeConflictCheckedLater());
     } else {
@@ -5187,15 +5162,9 @@
                         source.getSource(*this, type1.getDependentType(*this)));
   }
 
-  // Both sides are type parameters; equate them.
-  // FIXME: Realizes potential archetypes far too early.
-  auto pa1 = type1.realizePotentialArchetype(*this);
-  auto pa2 = type2.realizePotentialArchetype(*this);
-
-  return addSameTypeRequirementBetweenArchetypes(
-                     pa1, pa2,
-                     source.getSource(*this,
-                                      type2.getDependentType(*this)));
+  return addSameTypeRequirementBetweenTypeParameters(
+                     type1, type2,
+                     source.getSource(*this, type2.getDependentType(*this)));
 }
 
 ConstraintResult GenericSignatureBuilder::addInheritedRequirements(
@@ -7438,32 +7407,58 @@
 
 #pragma mark Generic signature verification
 
-void GenericSignatureBuilder::verifyGenericSignature(ASTContext &context,
-                                                     GenericSignature *sig) {
-  llvm::errs() << "Validating generic signature: ";
-  sig->print(llvm::errs());
-  llvm::errs() << "\n";
+void GenericSignatureBuilder::dropAndCompareEachRequirement(
+    ASTContext &context, GenericSignature *baseSig, GenericSignature *sig,
+    bool includeRedundantRequirements, SmallVectorImpl<Requirement> &redundant,
+    SmallVectorImpl<Requirement> &nonRedundant) {
+#ifndef NDEBUG
+  // `baseSig`'s params should be a subset of `sig`, meaning <A where ...>, <A,
+  // B where ...> (respectively) is okay, but the reverse is not.
+  if (baseSig) {
+    auto canSigParams = sig->getCanonicalSignature()->getGenericParams();
+    for (auto baseParam :
+         baseSig->getCanonicalSignature()->getGenericParams()) {
+      assert(llvm::is_contained(canSigParams, baseParam) &&
+             "baseSig params aren't a subset of sig");
+    }
+  }
+#endif
 
-  // Try removing each requirement in turn.
   auto genericParams = sig->getGenericParams();
   auto requirements = sig->getRequirements();
   for (unsigned victimIndex : indices(requirements)) {
-    PrettyStackTraceGenericSignature debugStack("verifying", sig, victimIndex);
+    PrettyStackTraceGenericSignature debugStack("dropping & comparing", sig,
+                                                victimIndex);
 
     // Form a new generic signature builder.
     GenericSignatureBuilder builder(context);
 
-    // Add the generic parameters.
+    // Add the generic parameters, and specifically those from the main
+    // signature, since it may have more
     for (auto gp : genericParams)
       builder.addGenericParameter(gp);
 
-    // Add the requirements *except* the victim.
+    // Add the appropriate requirements
     auto source = FloatingRequirementSource::forAbstract();
-    for (unsigned i : indices(requirements)) {
-      if (i != victimIndex)
-        builder.addRequirement(requirements[i], source, nullptr);
+    // First, the universal requirements from the base
+    if (baseSig) {
+      for (auto req : baseSig->getRequirements())
+        builder.addRequirement(req, source, nullptr);
     }
 
+    // Next, the requirements from the interesting signature.  Sometimes we have
+    // to add all of the leading ones, and others times only those that we've
+    // already decided aren't redundant:
+    auto leadingReqs = includeRedundantRequirements
+                           ? requirements.slice(0, victimIndex)
+                           : nonRedundant;
+    // We definitely have to add all of the remaining trailing ones:
+    auto trailingReqs = requirements.slice(victimIndex + 1);
+
+    for (auto reqs : {leadingReqs, trailingReqs})
+      for (auto req : reqs)
+        builder.addRequirement(req, source, nullptr);
+
     // Finalize the generic signature. If there were any errors, we formed
     // an invalid signature, so just continue.
     if (builder.Impl->HadAnyError) continue;
@@ -7475,23 +7470,40 @@
                                       /*allowConcreteGenericParams=*/true,
                                       /*allowBuilderToMove=*/true);
 
-    // If the removed requirement is satisfied by the new generic signature,
-    // it is redundant. Complain.
-    if (newSig->isRequirementSatisfied(requirements[victimIndex])) {
-      SmallString<32> reqString;
-      {
-        llvm::raw_svector_ostream out(reqString);
-        requirements[victimIndex].print(out, PrintOptions());
-      }
-      context.Diags.diagnose(SourceLoc(), diag::generic_signature_not_minimal,
-                             reqString, sig->getAsString());
-    }
+    auto req = requirements[victimIndex];
+    if (newSig->isRequirementSatisfied(req))
+      redundant.push_back(req);
+    else
+      nonRedundant.push_back(req);
 
     // Canonicalize the signature to check that it is canonical.
     (void)newSig->getCanonicalSignature();
   }
 }
 
+void GenericSignatureBuilder::verifyGenericSignature(ASTContext &context,
+                                                     GenericSignature *sig) {
+  llvm::errs() << "Validating generic signature: ";
+  sig->print(llvm::errs());
+  llvm::errs() << "\n";
+
+  SmallVector<Requirement, 4> redundant;
+  SmallVector<Requirement, 4> _nonRedundant;
+  dropAndCompareEachRequirement(context, /*baseSig=*/nullptr, sig,
+                                /*includeRedundantRequirements=*/true,
+                                redundant, _nonRedundant);
+  for (auto req : redundant) {
+    // Oops, the signature wasn't minimal: complain.
+    SmallString<32> reqString;
+    {
+      llvm::raw_svector_ostream out(reqString);
+      req.print(out, PrintOptions());
+    }
+    context.Diags.diagnose(SourceLoc(), diag::generic_signature_not_minimal,
+                           reqString, sig->getAsString());
+  }
+}
+
 void GenericSignatureBuilder::verifyGenericSignaturesInModule(
                                                         ModuleDecl *module) {
   LoadedFile *loadedFile = nullptr;
diff --git a/lib/Basic/PrettyStackTrace.cpp b/lib/Basic/PrettyStackTrace.cpp
index 16927a6..a7673b5 100644
--- a/lib/Basic/PrettyStackTrace.cpp
+++ b/lib/Basic/PrettyStackTrace.cpp
@@ -17,6 +17,7 @@
 
 #include "swift/Basic/PrettyStackTrace.h"
 #include "swift/Basic/QuotedString.h"
+#include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/raw_ostream.h"
 
 using namespace swift;
@@ -24,3 +25,11 @@
 void PrettyStackTraceStringAction::print(llvm::raw_ostream &out) const {
   out << "While " << Action << ' ' << QuotedString(TheString) << '\n';
 }
+
+void PrettyStackTraceFileContents::print(llvm::raw_ostream &out) const {
+  out << "Contents of " << Buffer.getBufferIdentifier() << ":\n---\n"
+      << Buffer.getBuffer();
+  if (!Buffer.getBuffer().endswith("\n"))
+    out << '\n';
+  out << "---\n";
+}
diff --git a/lib/Demangling/Demangler.cpp b/lib/Demangling/Demangler.cpp
index ae82735..dcb6640 100644
--- a/lib/Demangling/Demangler.cpp
+++ b/lib/Demangling/Demangler.cpp
@@ -2103,10 +2103,16 @@
                                 Conf, AssocTypePath, ProtoTy);
     }
     case 'y': {
+      if (auto sig = popNode(Node::Kind::DependentGenericSignature))
+        return createWithChildren(Node::Kind::OutlinedCopy,
+                                  popNode(Node::Kind::Type), sig);
       return createWithChild(Node::Kind::OutlinedCopy,
                              popNode(Node::Kind::Type));
     }
     case 'e': {
+      if (auto sig = popNode(Node::Kind::DependentGenericSignature))
+        return createWithChildren(Node::Kind::OutlinedCopy,
+                                  popNode(Node::Kind::Type), sig);
       return createWithChild(Node::Kind::OutlinedConsume,
                              popNode(Node::Kind::Type));
     }
diff --git a/lib/Demangling/NodePrinter.cpp b/lib/Demangling/NodePrinter.cpp
index f1620f7..14bb8b0 100644
--- a/lib/Demangling/NodePrinter.cpp
+++ b/lib/Demangling/NodePrinter.cpp
@@ -892,10 +892,14 @@
   case Node::Kind::OutlinedCopy:
     Printer << "outlined copy of ";
     print(Node->getChild(0));
+    if (Node->getNumChildren() > 1)
+      print(Node->getChild(1));
     return nullptr;
   case Node::Kind::OutlinedConsume:
     Printer << "outlined consume of ";
     print(Node->getChild(0));
+    if (Node->getNumChildren() > 1)
+      print(Node->getChild(1));
     return nullptr;
   case Node::Kind::OutlinedRetain:
     Printer << "outlined retain of ";
diff --git a/lib/Demangling/Remangler.cpp b/lib/Demangling/Remangler.cpp
index 0090b6b..8c89cb1 100644
--- a/lib/Demangling/Remangler.cpp
+++ b/lib/Demangling/Remangler.cpp
@@ -1837,12 +1837,12 @@
 }
 
 void Remangler::mangleOutlinedCopy(Node *node) {
-  mangleSingleChildNode(node);
+  mangleChildNodes(node);
   Buffer << "Wy";
 }
 
 void Remangler::mangleOutlinedConsume(Node *node) {
-  mangleSingleChildNode(node);
+  mangleChildNodes(node);
   Buffer << "We";
 }
 
diff --git a/lib/Driver/Compilation.cpp b/lib/Driver/Compilation.cpp
index 78107c0..c0c882b 100644
--- a/lib/Driver/Compilation.cpp
+++ b/lib/Driver/Compilation.cpp
@@ -15,6 +15,7 @@
 #include "swift/AST/DiagnosticEngine.h"
 #include "swift/AST/DiagnosticsDriver.h"
 #include "swift/Basic/Program.h"
+#include "swift/Basic/STLExtras.h"
 #include "swift/Basic/Statistic.h"
 #include "swift/Basic/TaskQueue.h"
 #include "swift/Basic/Version.h"
@@ -724,31 +725,31 @@
         Batches.push_back(Comp.addJob(std::move(J)));
     }
 
-    /// Inspect current batch \p i of the \p Partition currently being built
-    /// and, if that batch is "full" (in the sense of holding an evenly-divided
-    /// portion of NumJobs) then advance \p i to the next batch index in the
-    /// partition.
-    void maybeAdvanceToNextPartition(size_t &i,
-                                     BatchPartition const &Partition,
-                                     size_t NumJobs) {
-      assert(i < Partition.size());
-      size_t Remainder = NumJobs % Partition.size();
-      size_t TargetSize = NumJobs / Partition.size();
-      // Spread remainder evenly across partitions by adding 1 to the target
-      // size of the first Remainder of them.
-      if (i < Remainder)
-        TargetSize++;
-      if (Partition[i].size() >= TargetSize)
-        ++i;
-      assert(i < Partition.size());
-    }
-
-    /// Shuffle \p Batchable if -driver-batch-seed is nonzero.
-    void maybeShuffleBatchable(std::vector<const Job *> &Batchable) {
+    /// Build a vector of partition indices, one per Job: the i'th index says
+    /// which batch of the partition the i'th Job will be assigned to. If we are
+    /// shuffling due to -driver-batch-seed, the returned indices will not be
+    /// arranged in contiguous runs. We shuffle partition-indices here, not
+    /// elements themselves, to preserve the invariant that each batch is a
+    /// subsequence of the full set of inputs, not just a subset.
+    std::vector<size_t>
+    assignJobsToPartitions(size_t PartitionSize,
+                           size_t NumJobs) {
+      size_t Remainder = NumJobs % PartitionSize;
+      size_t TargetSize = NumJobs / PartitionSize;
+      std::vector<size_t> PartitionIndex;
+      PartitionIndex.reserve(NumJobs);
+      for (size_t P = 0; P < PartitionSize; ++P) {
+        // Spread remainder evenly across partitions by adding 1 to the target
+        // size of the first Remainder of them.
+        size_t FillCount = TargetSize + ((P < Remainder) ? 1 : 0);
+        std::fill_n(std::back_inserter(PartitionIndex), FillCount, P);
+      }
       if (Comp.BatchSeed != 0) {
         std::minstd_rand gen(Comp.BatchSeed);
-        std::shuffle(Batchable.begin(), Batchable.end(), gen);
+        std::shuffle(PartitionIndex.begin(), PartitionIndex.end(), gen);
       }
+      assert(PartitionIndex.size() == NumJobs);
+      return PartitionIndex;
     }
 
     /// Create \c NumberOfParallelCommands batches and assign each job to a
@@ -762,28 +763,28 @@
       }
 
       assert(!Partition.empty());
-      maybeShuffleBatchable(Batchable);
-
-      size_t i = 0;
+      auto PartitionIndex = assignJobsToPartitions(Partition.size(),
+                                                   Batchable.size());
+      assert(PartitionIndex.size() == Batchable.size());
       auto const &TC = Comp.getToolChain();
-      for (const Job *Cmd : Batchable) {
-        maybeAdvanceToNextPartition(i, Partition, Batchable.size());
-        std::vector<const Job*> &P = Partition[i];
-        if (P.empty() || TC.jobsAreBatchCombinable(Comp, P[0], Cmd)) {
-          if (Comp.ShowJobLifecycle)
-            llvm::outs() << "Adding " << LogJob(Cmd)
-                         << " to batch " << i << '\n';
-          P.push_back(Cmd);
-        } else {
-          // Strange but theoretically possible that we have a batchable job
-          // that's not combinable with others; tack a new batch on for it.
-          if (Comp.ShowJobLifecycle)
-            llvm::outs() << "Adding " << LogJob(Cmd)
-                         << " to new batch " << Partition.size() << '\n';
-          Partition.push_back(std::vector<const Job*>());
-          Partition.back().push_back(Cmd);
-        }
-      }
+      for_each(Batchable, PartitionIndex, [&](const Job *Cmd, size_t Idx) {
+          assert(Idx < Partition.size());
+          std::vector<const Job*> &P = Partition[Idx];
+          if (P.empty() || TC.jobsAreBatchCombinable(Comp, P[0], Cmd)) {
+            if (Comp.ShowJobLifecycle)
+              llvm::outs() << "Adding " << LogJob(Cmd)
+                           << " to batch " << Idx << '\n';
+            P.push_back(Cmd);
+          } else {
+            // Strange but theoretically possible that we have a batchable job
+            // that's not combinable with others; tack a new batch on for it.
+            if (Comp.ShowJobLifecycle)
+              llvm::outs() << "Adding " << LogJob(Cmd)
+                           << " to new batch " << Partition.size() << '\n';
+            Partition.push_back(std::vector<const Job*>());
+            Partition.back().push_back(Cmd);
+          }
+        });
     }
 
     // FIXME: at the moment we're not passing OutputFileMaps to frontends, so
diff --git a/lib/Driver/ToolChain.cpp b/lib/Driver/ToolChain.cpp
index ec93a55..9e4997d 100644
--- a/lib/Driver/ToolChain.cpp
+++ b/lib/Driver/ToolChain.cpp
@@ -280,6 +280,35 @@
   return false;
 }
 
+/// Debugging only: return whether the set of \p jobs is an ordered subsequence
+/// of the sequence of top-level input files in the \c Compilation \p C.
+static bool
+jobsAreSubsequenceOfCompilationInputs(ArrayRef<const Job *> jobs,
+                                      Compilation &C) {
+  llvm::SmallVector<const Job *, 16> sortedJobs;
+  llvm::StringMap<const Job *> jobsByInput;
+  for (const Job *J : jobs) {
+    const CompileJobAction *CJA = cast<CompileJobAction>(&J->getSource());
+    const InputAction* IA = findSingleSwiftInput(CJA);
+    auto R = jobsByInput.insert(std::make_pair(IA->getInputArg().getValue(),
+                                               J));
+    assert(R.second);
+  }
+  for (const InputPair &P : C.getInputFiles()) {
+    auto I = jobsByInput.find(P.second->getValue());
+    if (I != jobsByInput.end()) {
+      sortedJobs.push_back(I->second);
+    }
+  }
+  if (sortedJobs.size() != jobs.size())
+    return false;
+  for (size_t i = 0; i < sortedJobs.size(); ++i) {
+    if (sortedJobs[i] != jobs[i])
+      return false;
+  }
+  return true;
+}
+
 /// Construct a \c BatchJob by merging the constituent \p jobs' CommandOutput,
 /// input \c Job and \c Action members. Call through to \c constructInvocation
 /// on \p BatchJob, to build the \c InvocationInfo.
@@ -287,17 +316,11 @@
 ToolChain::constructBatchJob(ArrayRef<const Job *> jobs,
                              Compilation &C) const
 {
-#ifndef NDEBUG
-  // Verify that the equivalence relation on the jobs also holds pairwise.
-  for (auto *A : jobs) {
-    for (auto *B : jobs) {
-      assert(jobsAreBatchCombinable(C, A, B));
-    }
-  }
-#endif
   if (jobs.empty())
     return nullptr;
 
+  assert(jobsAreSubsequenceOfCompilationInputs(jobs, C));
+
   // Synthetic OutputInfo is a slightly-modified version of the initial
   // compilation's OI.
   auto OI = C.getOutputInfo();
diff --git a/lib/Frontend/ArgsToFrontendInputsConverter.cpp b/lib/Frontend/ArgsToFrontendInputsConverter.cpp
index ceb6f2e..3fc47cb 100644
--- a/lib/Frontend/ArgsToFrontendInputsConverter.cpp
+++ b/lib/Frontend/ArgsToFrontendInputsConverter.cpp
@@ -13,6 +13,7 @@
 #include "swift/Frontend/ArgsToFrontendInputsConverter.h"
 
 #include "swift/AST/DiagnosticsFrontend.h"
+#include "swift/Basic/Defer.h"
 #include "swift/Frontend/ArgsToFrontendOutputsConverter.h"
 #include "swift/Frontend/FrontendOptions.h"
 #include "swift/Option/Options.h"
@@ -30,33 +31,47 @@
 using namespace llvm::opt;
 
 ArgsToFrontendInputsConverter::ArgsToFrontendInputsConverter(
-    DiagnosticEngine &diags, const ArgList &args,
-    FrontendInputsAndOutputs &inputsAndOutputs)
-    : Diags(diags), Args(args), InputsAndOutputs(inputsAndOutputs),
+    DiagnosticEngine &diags, const ArgList &args)
+    : Diags(diags), Args(args),
       FilelistPathArg(args.getLastArg(options::OPT_filelist)),
       PrimaryFilelistPathArg(args.getLastArg(options::OPT_primary_filelist)) {}
 
-bool ArgsToFrontendInputsConverter::convert() {
+Optional<FrontendInputsAndOutputs> ArgsToFrontendInputsConverter::convert(
+    SmallVectorImpl<std::unique_ptr<llvm::MemoryBuffer>> *buffers) {
+  SWIFT_DEFER {
+    if (buffers) {
+      std::move(ConfigurationFileBuffers.begin(),
+                ConfigurationFileBuffers.end(),
+                std::back_inserter(*buffers));
+      // Clearing the original list of buffers isn't strictly necessary, but
+      // makes the behavior more sensible if we were to call convert() again.
+      ConfigurationFileBuffers.clear();
+    }
+  };
+
   if (enforceFilelistExclusion())
-    return true;
+    return None;
+
   if (FilelistPathArg ? readInputFilesFromFilelist()
                       : readInputFilesFromCommandLine())
-    return true;
+    return None;
   Optional<std::set<StringRef>> primaryFiles = readPrimaryFiles();
   if (!primaryFiles)
-    return true;
-  std::set<StringRef> unusedPrimaryFiles =
+    return None;
+
+  FrontendInputsAndOutputs result;
+  std::set<StringRef> unusedPrimaryFiles;
+  std::tie(result, unusedPrimaryFiles) =
       createInputFilesConsumingPrimaries(*primaryFiles);
 
-  if (checkForMissingPrimaryFiles(unusedPrimaryFiles))
-    return true;
+  if (diagnoseUnusedPrimaryFiles(unusedPrimaryFiles))
+    return None;
 
   // Must be set before iterating over inputs needing outputs.
-  InputsAndOutputs.setIsSingleThreadedWMO(isSingleThreadedWMO());
-
-  InputsAndOutputs.setBypassBatchModeChecks(
+  result.setBypassBatchModeChecks(
       Args.hasArg(options::OPT_bypass_batch_mode_checks));
-  return false;
+
+  return std::move(result);
 }
 
 bool ArgsToFrontendInputsConverter::enforceFilelistExclusion() {
@@ -114,7 +129,7 @@
        llvm::make_range(llvm::line_iterator(*filelistBufferOrError->get()),
                         llvm::line_iterator()))
     fn(file);
-  BuffersToKeepAlive.push_back(std::move(*filelistBufferOrError));
+  ConfigurationFileBuffers.push_back(std::move(*filelistBufferOrError));
   return false;
 }
 
@@ -137,34 +152,38 @@
   return primaryFiles;
 }
 
-std::set<StringRef>
+std::pair<FrontendInputsAndOutputs, std::set<StringRef>>
 ArgsToFrontendInputsConverter::createInputFilesConsumingPrimaries(
     std::set<StringRef> primaryFiles) {
+  bool hasAnyPrimaryFiles = !primaryFiles.empty();
+
+  FrontendInputsAndOutputs result;
   for (auto &file : Files) {
     bool isPrimary = primaryFiles.count(file) > 0;
-    InputsAndOutputs.addInput(InputFile(file, isPrimary));
+    result.addInput(InputFile(file, isPrimary));
     if (isPrimary)
       primaryFiles.erase(file);
   }
-  return primaryFiles;
+
+  if (!Files.empty() && !hasAnyPrimaryFiles) {
+    Optional<std::vector<std::string>> userSuppliedNamesOrErr =
+        OutputFilesComputer::getOutputFilenamesFromCommandLineOrFilelist(Args,
+                                                                         Diags);
+    if (userSuppliedNamesOrErr && userSuppliedNamesOrErr->size() == 1)
+      result.setIsSingleThreadedWMO(true);
+  }
+
+  return {std::move(result), std::move(primaryFiles)};
 }
 
-bool ArgsToFrontendInputsConverter::checkForMissingPrimaryFiles(
+bool ArgsToFrontendInputsConverter::diagnoseUnusedPrimaryFiles(
     std::set<StringRef> primaryFiles) {
   for (auto &file : primaryFiles) {
     // Catch "swiftc -frontend -c -filelist foo -primary-file
     // some-file-not-in-foo".
-    assert(FilelistPathArg && "Missing primary with no filelist");
+    assert(FilelistPathArg && "Unused primary with no filelist");
     Diags.diagnose(SourceLoc(), diag::error_primary_file_not_found, file,
                    FilelistPathArg->getValue());
   }
   return !primaryFiles.empty();
 }
-
-bool ArgsToFrontendInputsConverter::isSingleThreadedWMO() const {
-  Optional<std::vector<std::string>> userSuppliedNamesOrErr =
-      OutputFilesComputer::getOutputFilenamesFromCommandLineOrFilelist(Args,
-                                                                       Diags);
-  return InputsAndOutputs.hasInputs() && !InputsAndOutputs.hasPrimaryInputs() &&
-         userSuppliedNamesOrErr && userSuppliedNamesOrErr->size() == 1;
-}
diff --git a/lib/Frontend/ArgsToFrontendOptionsConverter.cpp b/lib/Frontend/ArgsToFrontendOptionsConverter.cpp
index 697f015..07024f4 100644
--- a/lib/Frontend/ArgsToFrontendOptionsConverter.cpp
+++ b/lib/Frontend/ArgsToFrontendOptionsConverter.cpp
@@ -45,7 +45,8 @@
 LLVM_ATTRIBUTE_NOINLINE
 static void debugFailWithCrash() { LLVM_BUILTIN_TRAP; }
 
-bool ArgsToFrontendOptionsConverter::convert() {
+bool ArgsToFrontendOptionsConverter::convert(
+    SmallVectorImpl<std::unique_ptr<llvm::MemoryBuffer>> *buffers) {
   using namespace options;
 
   handleDebugCrashGroupArguments();
@@ -93,9 +94,11 @@
 
   computeDumpScopeMapLocations();
 
-  if (ArgsToFrontendInputsConverter(Diags, Args, Opts.InputsAndOutputs)
-          .convert())
+  Optional<FrontendInputsAndOutputs> inputsAndOutputs =
+      ArgsToFrontendInputsConverter(Diags, Args).convert(buffers);
+  if (!inputsAndOutputs)
     return true;
+  Opts.InputsAndOutputs = std::move(inputsAndOutputs).getValue();
 
   Opts.RequestedAction = determineRequestedAction(Args);
 
diff --git a/lib/Frontend/CompilerInvocation.cpp b/lib/Frontend/CompilerInvocation.cpp
index b522760..c1b0790 100644
--- a/lib/Frontend/CompilerInvocation.cpp
+++ b/lib/Frontend/CompilerInvocation.cpp
@@ -81,9 +81,11 @@
   llvm_unreachable("Unhandled InputFileKind in switch.");
 }
 
-static bool ParseFrontendArgs(FrontendOptions &opts, ArgList &args,
-                              DiagnosticEngine &diags) {
-  return ArgsToFrontendOptionsConverter(diags, args, opts).convert();
+static bool ParseFrontendArgs(
+    FrontendOptions &opts, ArgList &args, DiagnosticEngine &diags,
+    SmallVectorImpl<std::unique_ptr<llvm::MemoryBuffer>> *buffers) {
+  ArgsToFrontendOptionsConverter converter(diags, args, opts);
+  return converter.convert(buffers);
 }
 
 static void diagnoseSwiftVersion(Optional<version::Version> &vers, Arg *verArg,
@@ -978,9 +980,12 @@
   return false;
 }
 
-bool CompilerInvocation::parseArgs(ArrayRef<const char *> Args,
-                                   DiagnosticEngine &Diags,
-                                   StringRef workingDirectory) {
+bool CompilerInvocation::parseArgs(
+    ArrayRef<const char *> Args,
+    DiagnosticEngine &Diags,
+    SmallVectorImpl<std::unique_ptr<llvm::MemoryBuffer>>
+        *ConfigurationFileBuffers,
+    StringRef workingDirectory) {
   using namespace options;
 
   if (Args.empty())
@@ -1006,7 +1011,8 @@
     return true;
   }
 
-  if (ParseFrontendArgs(FrontendOpts, ParsedArgs, Diags)) {
+  if (ParseFrontendArgs(FrontendOpts, ParsedArgs, Diags,
+                        ConfigurationFileBuffers)) {
     return true;
   }
 
diff --git a/lib/Frontend/DiagnosticVerifier.cpp b/lib/Frontend/DiagnosticVerifier.cpp
index 604bb78..e43fc97 100644
--- a/lib/Frontend/DiagnosticVerifier.cpp
+++ b/lib/Frontend/DiagnosticVerifier.cpp
@@ -17,9 +17,10 @@
 #include "swift/Frontend/DiagnosticVerifier.h"
 #include "swift/Basic/SourceManager.h"
 #include "swift/Parse/Lexer.h"
+#include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/raw_ostream.h"
-#include <fstream>
+
 using namespace swift;
 
 namespace {
@@ -688,9 +689,12 @@
   
   // Retain the end of the file.
   Result.append(LastPos, bufferRange.end());
-  
-  std::ofstream outs(memBuffer->getBufferIdentifier());
-  outs << Result;
+
+  std::error_code error;
+  llvm::raw_fd_ostream outs(memBuffer->getBufferIdentifier(), error,
+                            llvm::sys::fs::OpenFlags::F_None);
+  if (!error)
+    outs << Result;
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/lib/FrontendTool/FrontendTool.cpp b/lib/FrontendTool/FrontendTool.cpp
index 743c1d7..72a7239 100644
--- a/lib/FrontendTool/FrontendTool.cpp
+++ b/lib/FrontendTool/FrontendTool.cpp
@@ -41,6 +41,7 @@
 #include "swift/Basic/JSONSerialization.h"
 #include "swift/Basic/LLVMContext.h"
 #include "swift/Basic/LLVMInitialize.h"
+#include "swift/Basic/PrettyStackTrace.h"
 #include "swift/Basic/SourceManager.h"
 #include "swift/Basic/Statistic.h"
 #include "swift/Basic/Timer.h"
@@ -1661,10 +1662,32 @@
   llvm::sys::fs::current_path(workingDirectory);
 
   // Parse arguments.
-  if (Invocation.parseArgs(Args, Instance->getDiags(), workingDirectory)) {
+  SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 4> configurationFileBuffers;
+  if (Invocation.parseArgs(Args, Instance->getDiags(),
+                           &configurationFileBuffers, workingDirectory)) {
     return finishDiagProcessing(1);
   }
 
+  // Make an array of PrettyStackTrace objects to dump the configuration files
+  // we used to parse the arguments. These are RAII objects, so they and the
+  // buffers they refer to must be kept alive in order to be useful. (That is,
+  // we want them to be alive for the entire rest of performFrontend.)
+  //
+  // This can't be a SmallVector or similar because PrettyStackTraces can't be
+  // moved (or copied)...and it can't be an array of non-optionals because
+  // PrettyStackTraces can't be default-constructed. So we end up with a
+  // dynamically-sized array of optional PrettyStackTraces, which get
+  // initialized by iterating over the buffers we collected above.
+  auto configurationFileStackTraces =
+      llvm::make_unique<Optional<PrettyStackTraceFileContents>[]>(
+        configurationFileBuffers.size());
+  for_each(configurationFileBuffers.begin(), configurationFileBuffers.end(),
+           &configurationFileStackTraces[0],
+           [](const std::unique_ptr<llvm::MemoryBuffer> &buffer,
+              Optional<PrettyStackTraceFileContents> &trace) {
+    trace.emplace(*buffer);
+  });
+
   // Setting DWARF Version depend on platform
   IRGenOptions &IRGenOpts = Invocation.getIRGenOptions();
   IRGenOpts.DWARFVersion = swift::DWARFVersion;
diff --git a/lib/IDE/APIDigesterData.cpp b/lib/IDE/APIDigesterData.cpp
index 8e7450d..cc6d032 100644
--- a/lib/IDE/APIDigesterData.cpp
+++ b/lib/IDE/APIDigesterData.cpp
@@ -309,7 +309,7 @@
 #define DIFF_ITEM_KEY_KIND_STRING(NAME) StringRef NAME;
 #define DIFF_ITEM_KEY_KIND_INT(NAME) Optional<int> NAME;
 #include "swift/IDE/DigesterEnums.def"
-  for (auto Pair : *Node) {
+  for (auto &Pair : *Node) {
     switch(parseKeyKind(getScalarString(Pair.getKey()))) {
 #define DIFF_ITEM_KEY_KIND_STRING(NAME)                                       \
     case DiffItemKeyKind::KK_##NAME:                                          \
diff --git a/lib/IDE/TypeReconstruction.cpp b/lib/IDE/TypeReconstruction.cpp
index 4e65f65..906a27d 100644
--- a/lib/IDE/TypeReconstruction.cpp
+++ b/lib/IDE/TypeReconstruction.cpp
@@ -1157,6 +1157,40 @@
   return (in_matches && out_matches);
 }
 
+static void VisitNodePrivateDeclName(
+    ASTContext *ast,
+    Demangle::NodePointer parent_node,
+    Demangle::NodePointer cur_node, VisitNodeResult &result) {
+  DeclKind decl_kind = GetKindAsDeclKind(parent_node->getKind());
+
+  if (cur_node->getNumChildren() != 2) {
+    if (result._error.empty())
+      result._error = stringWithFormat(
+          "unable to retrieve content for Node::Kind::PrivateDeclName");
+    return;
+  }
+
+  Demangle::NodePointer priv_decl_id_node(cur_node->getChild(0));
+  Demangle::NodePointer id_node(cur_node->getChild(1));
+
+  if (!priv_decl_id_node->hasText() || !id_node->hasText()) {
+    if (result._error.empty())
+      result._error = stringWithFormat(
+          "unable to retrieve content for Node::Kind::PrivateDeclName");
+    return;
+  }
+
+  if (!FindFirstNamedDeclWithKind(ast, ast->getIdentifier(id_node->getText()),
+                                  decl_kind, result,
+                                  priv_decl_id_node->getText().str())) {
+    if (result._error.empty())
+      result._error = stringWithFormat(
+          "unable to find Node::Kind::PrivateDeclName '%s' in '%s'",
+          id_node->getText().str().c_str(),
+          priv_decl_id_node->getText().str().c_str());
+  }
+}
+
 // VisitNodeFunction gets used for Function, Variable and Allocator:
 static void VisitNodeFunction(
     ASTContext *ast,
@@ -1191,6 +1225,25 @@
       VisitNode(ast, *pos, decl_scope_result);
       break;
 
+    case Demangle::Node::Kind::PrivateDeclName: {
+      VisitNodePrivateDeclName(ast, cur_node, child, decl_scope_result);
+
+      // No results found, giving up.
+      if (decl_scope_result._decls.empty())
+        break;
+
+      std::copy(decl_scope_result._decls.begin(),
+                decl_scope_result._decls.end(),
+                back_inserter(identifier_result._decls));
+      std::copy(decl_scope_result._types.begin(),
+                decl_scope_result._types.end(),
+                back_inserter(identifier_result._types));
+      identifier_result._module = decl_scope_result._module;
+      if (decl_scope_result._decls.size() == 1)
+        found_univocous = true;
+      break;
+    }
+
     case Demangle::Node::Kind::LabelList: {
       for (const auto &label : **pos) {
         if (label->getKind() == Demangle::Node::Kind::FirstElementMarker)
@@ -1670,40 +1723,6 @@
   }
 }
 
-static void VisitNodePrivateDeclName(
-    ASTContext *ast,
-    Demangle::NodePointer parent_node,
-    Demangle::NodePointer cur_node, VisitNodeResult &result) {
-  DeclKind decl_kind = GetKindAsDeclKind(parent_node->getKind());
-
-  if (cur_node->getNumChildren() != 2) {
-    if (result._error.empty())
-      result._error = stringWithFormat(
-          "unable to retrieve content for Node::Kind::PrivateDeclName");
-    return;
-  }
-
-  Demangle::NodePointer priv_decl_id_node(cur_node->getChild(0));
-  Demangle::NodePointer id_node(cur_node->getChild(1));
-
-  if (!priv_decl_id_node->hasText() || !id_node->hasText()) {
-    if (result._error.empty())
-      result._error = stringWithFormat(
-          "unable to retrieve content for Node::Kind::PrivateDeclName");
-    return;
-  }
-
-  if (!FindFirstNamedDeclWithKind(ast, ast->getIdentifier(id_node->getText()),
-                                  decl_kind, result,
-                                  priv_decl_id_node->getText().str())) {
-    if (result._error.empty())
-      result._error = stringWithFormat(
-          "unable to find Node::Kind::PrivateDeclName '%s' in '%s'",
-          id_node->getText().str().c_str(),
-          priv_decl_id_node->getText().str().c_str());
-  }
-}
-
 static void VisitNodeRelatedEntityDeclName(
     ASTContext *ast,
     Demangle::NodePointer parent_node,
diff --git a/lib/IRGen/GenCast.h b/lib/IRGen/GenCast.h
index 86f0ed7..1043674 100644
--- a/lib/IRGen/GenCast.h
+++ b/lib/IRGen/GenCast.h
@@ -34,7 +34,7 @@
   class Explosion;
 
   /// Discriminator for checked cast modes.
-  enum class CheckedCastMode : unsigned char {
+  enum class CheckedCastMode : uint8_t {
     Unconditional,
     Conditional,
   };
diff --git a/lib/IRGen/GenEnum.cpp b/lib/IRGen/GenEnum.cpp
index f0efd44..5c55613 100644
--- a/lib/IRGen/GenEnum.cpp
+++ b/lib/IRGen/GenEnum.cpp
@@ -677,6 +677,14 @@
                      cast<FixedTypeInfo>(TI)->getFixedSize().getValueInBits(),
                      true);
     }
+
+    bool isSingleRetainablePointer(ResilienceExpansion expansion,
+                                   ReferenceCounting *rc) const override {
+      auto singleton = getSingleton();
+      if (!singleton)
+        return false;
+      return singleton->isSingleRetainablePointer(expansion, rc);
+    }
   };
 
   /// Implementation strategy for no-payload enums, in other words, 'C-like'
@@ -1423,15 +1431,35 @@
       PayloadTypesAndTagType.push_back(type);
     }
   }
+  
+  static std::pair<CanType, CanGenericSignature>
+  getTypeAndGenericSignatureForManglingOutlineFunction(SILType type) {
+    auto loweredType = type.getSwiftRValueType();
+    if (loweredType->hasArchetype()) {
+      GenericEnvironment *env = nullptr;
+      loweredType.findIf([&env](Type t) -> bool {
+        if (auto arch = t->getAs<ArchetypeType>()) {
+          env = arch->getGenericEnvironment();
+          return true;
+        }
+        return false;
+      });
+      assert(env && "has archetype but no archetype?!");
+      return {loweredType->mapTypeOutOfContext()->getCanonicalType(),
+              env->getGenericSignature()->getCanonicalSignature()};
+    }
+    return {loweredType, nullptr};
+  }
 
   static llvm::Function *createOutlineLLVMFunction(
       IRGenModule &IGM, std::string &name,
-      SmallVector<llvm::Type *, 2> &PayloadTypesAndTagType) {
+      ArrayRef<llvm::Type *> PayloadTypesAndTagType) {
     auto consumeTy = llvm::FunctionType::get(IGM.VoidTy, PayloadTypesAndTagType,
                                              /*isVarArg*/ false);
     auto func =
-        llvm::Function::Create(consumeTy, llvm::GlobalValue::InternalLinkage,
+        llvm::Function::Create(consumeTy, llvm::GlobalValue::LinkOnceODRLinkage,
                                llvm::StringRef(name), IGM.getModule());
+    func->setVisibility(llvm::GlobalValue::HiddenVisibility);
     func->setAttributes(IGM.constructInitialAttributes());
     func->setDoesNotThrow();
     func->setCallingConv(IGM.DefaultCC);
@@ -1490,14 +1518,19 @@
 
     unsigned NumExtraInhabitantTagValues = ~0U;
 
-    llvm::Function *copyEnumFunction = nullptr;
-    llvm::Function *consumeEnumFunction = nullptr;
+    SILType loweredType;
+    mutable llvm::Function *copyEnumFunction = nullptr;
+    mutable llvm::Function *consumeEnumFunction = nullptr;
     SmallVector<llvm::Type *, 2> PayloadTypesAndTagType;
 
-    llvm::Function *emitCopyEnumFunction(IRGenModule &IGM, EnumDecl *theEnum) {
+    llvm::Function *
+    emitCopyEnumFunction(IRGenModule &IGM, SILType theEnumType) const {
       IRGenMangler Mangler;
-      std::string name = Mangler.mangleOutlinedCopyFunction(
-          theEnum->getAsNominalTypeOrNominalTypeExtensionContext());
+      auto manglingBits =
+        getTypeAndGenericSignatureForManglingOutlineFunction(theEnumType);
+      std::string name =
+        Mangler.mangleOutlinedCopyFunction(manglingBits.first,
+                                           manglingBits.second);
       auto func = createOutlineLLVMFunction(IGM, name, PayloadTypesAndTagType);
 
       IRGenFunction IGF(IGM, func);
@@ -1528,9 +1561,13 @@
     }
 
     llvm::Function *emitConsumeEnumFunction(IRGenModule &IGM,
-                                            EnumDecl *theEnum) {
+                                            SILType theEnumType) const {
       IRGenMangler Mangler;
-      std::string name = Mangler.mangleOutlinedConsumeFunction(theEnum);
+      auto manglingBits =
+        getTypeAndGenericSignatureForManglingOutlineFunction(theEnumType);
+      std::string name =
+        Mangler.mangleOutlinedConsumeFunction(manglingBits.first,
+                                              manglingBits.second);
       auto func = createOutlineLLVMFunction(IGM, name, PayloadTypesAndTagType);
 
       IRGenFunction IGF(IGM, func);
@@ -2274,7 +2311,8 @@
         return;
 
       case Normal: {
-        assert(copyEnumFunction && "Did not create copy function for enum");
+        if (!copyEnumFunction)
+          copyEnumFunction = emitCopyEnumFunction(IGF.IGM, loweredType);
         Explosion tmp;
         fillExplosionForOutlinedCall(IGF, src, tmp);
         llvm::CallInst *call =
@@ -2307,8 +2345,8 @@
         return;
 
       case Normal: {
-        assert(consumeEnumFunction &&
-               "Did not create consume function for enum");
+        if (!consumeEnumFunction)
+          consumeEnumFunction = emitConsumeEnumFunction(IGF.IGM, loweredType);
         Explosion tmp;
         fillExplosionForOutlinedCall(IGF, src, tmp);
         llvm::CallInst *call =
@@ -2977,13 +3015,18 @@
     ReferenceCounting Refcounting;
     bool AllowFixedLayoutOptimizations;
 
-    llvm::Function *copyEnumFunction = nullptr;
-    llvm::Function *consumeEnumFunction = nullptr;
+    SILType loweredType;
+    mutable llvm::Function *copyEnumFunction = nullptr;
+    mutable llvm::Function *consumeEnumFunction = nullptr;
     SmallVector<llvm::Type *, 2> PayloadTypesAndTagType;
 
-    llvm::Function *emitCopyEnumFunction(IRGenModule &IGM, EnumDecl *theEnum) {
+    llvm::Function *emitCopyEnumFunction(IRGenModule &IGM, SILType type) const {
       IRGenMangler Mangler;
-      std::string name = Mangler.mangleOutlinedCopyFunction(theEnum);
+      auto manglingBits =
+        getTypeAndGenericSignatureForManglingOutlineFunction(type);
+      std::string name =
+        Mangler.mangleOutlinedCopyFunction(manglingBits.first,
+                                           manglingBits.second);
       auto func = createOutlineLLVMFunction(IGM, name, PayloadTypesAndTagType);
 
       IRGenFunction IGF(IGM, func);
@@ -3007,14 +3050,17 @@
     }
 
     llvm::Function *emitConsumeEnumFunction(IRGenModule &IGM,
-                                            EnumDecl *theEnum) {
+                                            SILType type) const {
       IRGenMangler Mangler;
-      std::string name = Mangler.mangleOutlinedConsumeFunction(theEnum);
+      auto manglingBits =
+        getTypeAndGenericSignatureForManglingOutlineFunction(type);
+      std::string name =
+        Mangler.mangleOutlinedConsumeFunction(manglingBits.first,
+                                              manglingBits.second);
       auto func = createOutlineLLVMFunction(IGM, name, PayloadTypesAndTagType);
 
       IRGenFunction IGF(IGM, func);
       Explosion src = IGF.collectParameters();
-
       auto parts = destructureAndTagLoadableEnumFromOutlined(IGF, src);
 
       forNontrivialPayloads(IGF, parts.tag, [&](unsigned tagIndex,
@@ -4021,7 +4067,8 @@
 
       case BitwiseTakable:
       case Normal: {
-        assert(copyEnumFunction && "Did not create copy function for enum");
+        if (!copyEnumFunction)
+          copyEnumFunction = emitCopyEnumFunction(IGF.IGM, loweredType);
         Explosion tmp;
         fillExplosionForOutlinedCall(IGF, src, tmp);
         llvm::CallInst *call =
@@ -4062,8 +4109,8 @@
 
       case BitwiseTakable:
       case Normal: {
-        assert(consumeEnumFunction &&
-               "Did not create consume function for enum");
+        if (!consumeEnumFunction)
+          consumeEnumFunction = emitConsumeEnumFunction(IGF.IGM, loweredType);
         Explosion tmp;
         fillExplosionForOutlinedCall(IGF, src, tmp);
         llvm::CallInst *call =
@@ -5354,6 +5401,10 @@
                               SILType T) const override {
       return Strategy.storeExtraInhabitant(IGF, index, dest, T);
     }
+    bool isSingleRetainablePointer(ResilienceExpansion expansion,
+                                   ReferenceCounting *rc) const override {
+      return Strategy.isSingleRetainablePointer(expansion, rc);
+    }
   };
 
   /// TypeInfo for fixed-layout, address-only enum types.
@@ -5725,8 +5776,7 @@
       payloadTI.isBitwiseTakable(ResilienceExpansion::Maximal));
   if (TIK >= Loadable && CopyDestroyKind == Normal) {
     computePayloadTypesAndTagType(TC.IGM, *TI, PayloadTypesAndTagType);
-    copyEnumFunction = emitCopyEnumFunction(TC.IGM, theEnum);
-    consumeEnumFunction = emitConsumeEnumFunction(TC.IGM, theEnum);
+    loweredType = Type;
   }
 
   return const_cast<TypeInfo *>(TI);
@@ -5916,8 +5966,7 @@
   if (TIK >= Loadable &&
       (CopyDestroyKind == Normal || CopyDestroyKind == BitwiseTakable)) {
     computePayloadTypesAndTagType(TC.IGM, *TI, PayloadTypesAndTagType);
-    copyEnumFunction = emitCopyEnumFunction(TC.IGM, theEnum);
-    consumeEnumFunction = emitConsumeEnumFunction(TC.IGM, theEnum);
+    loweredType = Type;
   }
 
   return const_cast<TypeInfo *>(TI);
diff --git a/lib/IRGen/GenEnum.h b/lib/IRGen/GenEnum.h
index 24dbbd6..b12eef5 100644
--- a/lib/IRGen/GenEnum.h
+++ b/lib/IRGen/GenEnum.h
@@ -436,6 +436,11 @@
       llvm::MapVector<CanType, llvm::Value *> &typeToMetadataVec,
       SILType T) const = 0;
 
+  virtual bool isSingleRetainablePointer(ResilienceExpansion expansion,
+                                         ReferenceCounting *rc) const {
+    return false;
+  }
+  
 private:
   EnumImplStrategy(const EnumImplStrategy &) = delete;
   EnumImplStrategy &operator=(const EnumImplStrategy &) = delete;
diff --git a/lib/IRGen/GenMeta.cpp b/lib/IRGen/GenMeta.cpp
index b4694f7..997336b 100644
--- a/lib/IRGen/GenMeta.cpp
+++ b/lib/IRGen/GenMeta.cpp
@@ -505,6 +505,10 @@
   // The empty tuple type has a singleton metadata.
   if (auto tuple = dyn_cast<TupleType>(type))
     return tuple->getNumElements() == 0;
+  
+  // Any and AnyObject have singleton metadata.
+  if (type->isAny() || type->isAnyObject())
+    return true;
 
   // The builtin types generally don't require metadata, but some of them
   // have nodes in the runtime anyway.
@@ -988,8 +992,24 @@
       if (auto metatype = tryGetLocal(type))
         return metatype;
 
-      auto layout = type.getExistentialLayout();
+      // Any and AnyObject have singleton metadata in the runtime.
+      llvm::Constant *singletonMetadata = nullptr;
+      if (type->isAny())
+        singletonMetadata = IGF.IGM.getAnyExistentialMetadata();
+      if (type->isAnyObject())
+        singletonMetadata = IGF.IGM.getAnyObjectExistentialMetadata();
+      
+      if (singletonMetadata) {
+        llvm::Constant *indices[] = {
+          llvm::ConstantInt::get(IGF.IGM.Int32Ty, 0),
+          llvm::ConstantInt::get(IGF.IGM.Int32Ty, 1)
+        };
+        return llvm::ConstantExpr::getInBoundsGetElementPtr(
+            /*Ty=*/nullptr, singletonMetadata, indices);
+      }
 
+      auto layout = type.getExistentialLayout();
+      
       auto protocols = layout.getProtocols();
 
       // Collect references to the protocol descriptors.
@@ -2344,10 +2364,10 @@
     void addGenericParametersHeader() {
       // Drop placeholders for the counts. We'll fill these in when we emit
       // the related sections.
-      GenericParamCount = B.addPlaceholderWithSize(IGM.Int32Ty);
-      GenericRequirementCount = B.addPlaceholderWithSize(IGM.Int32Ty);
-      GenericKeyArgumentCount = B.addPlaceholderWithSize(IGM.Int32Ty);
-      GenericExtraArgumentCount = B.addPlaceholderWithSize(IGM.Int32Ty);
+      GenericParamCount = B.addPlaceholderWithSize(IGM.Int16Ty);
+      GenericRequirementCount = B.addPlaceholderWithSize(IGM.Int16Ty);
+      GenericKeyArgumentCount = B.addPlaceholderWithSize(IGM.Int16Ty);
+      GenericExtraArgumentCount = B.addPlaceholderWithSize(IGM.Int16Ty);
     }
     
     void addGenericParameters() {
@@ -2369,7 +2389,9 @@
         B.addInt(IGM.Int8Ty, 0);
       
       // Fill in the parameter count.
-      B.fillPlaceholderWithInt(*GenericParamCount, IGM.Int32Ty,
+      assert(canSig->getGenericParams().size() <= UINT16_MAX
+             && "way too generic");
+      B.fillPlaceholderWithInt(*GenericParamCount, IGM.Int16Ty,
                                canSig->getGenericParams().size());
     }
     
@@ -2392,16 +2414,21 @@
                             asImpl().getGenericSignature()->getRequirements());
 
       // Fill in the final requirement count.
-      B.fillPlaceholderWithInt(*GenericRequirementCount, IGM.Int32Ty,
+      assert(metadata.NumRequirements <= UINT16_MAX
+             && "way too generic");
+      B.fillPlaceholderWithInt(*GenericRequirementCount, IGM.Int16Ty,
                                metadata.NumRequirements);
       NumGenericKeyArguments += metadata.NumGenericKeyArguments;
       NumGenericExtraArguments += metadata.NumGenericExtraArguments;
     }
 
     void finishGenericParameters() {
-      B.fillPlaceholderWithInt(*GenericKeyArgumentCount, IGM.Int32Ty,
+      assert(NumGenericKeyArguments <= UINT16_MAX
+             && NumGenericExtraArguments <= UINT16_MAX
+             && "way too generic");
+      B.fillPlaceholderWithInt(*GenericKeyArgumentCount, IGM.Int16Ty,
                                NumGenericKeyArguments);
-      B.fillPlaceholderWithInt(*GenericExtraArgumentCount, IGM.Int32Ty,
+      B.fillPlaceholderWithInt(*GenericExtraArgumentCount, IGM.Int16Ty,
                                NumGenericExtraArguments);
     }
 
@@ -5509,9 +5536,6 @@
     void layout() {
       if (asImpl().requiresInitializationFunction())
         asImpl().addInitializationFunction();
-      else
-        asImpl().addPaddingForInitializationFunction();
-      asImpl().addForeignName();
       asImpl().addForeignFlags();
       super::layout();
     }
@@ -5556,13 +5580,8 @@
       IGF.Builder.CreateRetVoid();
 
       B.addRelativeAddress(fn);
-    }
-    
-    void addPaddingForInitializationFunction() {
-      // The initialization function field is placed at the least offset of the
-      // record so it can be omitted when not needed. However, the metadata
-      // record is still pointer-aligned, so on 64 bit platforms we need to
-      // occupy the space to keep the rest of the record with the right layout.
+      
+      // Keep pointer alignment on 64-bit platforms for further fields.
       switch (IGM.getPointerSize().getValue()) {
       case 4:
         break;
@@ -5573,7 +5592,7 @@
         llvm_unreachable("unsupported word size");
       }
     }
-
+    
     void noteAddressPoint() {
       AddressPoint = B.getNextOffsetFromGlobal();
     }
diff --git a/lib/IRGen/GenStruct.cpp b/lib/IRGen/GenStruct.cpp
index 8ccbe10..83651d9 100644
--- a/lib/IRGen/GenStruct.cpp
+++ b/lib/IRGen/GenStruct.cpp
@@ -262,6 +262,14 @@
       field.getTypeInfo().storeExtraInhabitant(IGF, index, fieldAddr,
                                           field.getType(IGF.IGM, structType));
     }
+       
+    bool isSingleRetainablePointer(ResilienceExpansion expansion,
+                                   ReferenceCounting *rc) const override {
+      auto fields = asImpl().getFields();
+      if (fields.size() != 1)
+        return false;
+      return fields[0].getTypeInfo().isSingleRetainablePointer(expansion, rc);
+    }
     
     void verify(IRGenTypeVerifierFunction &IGF,
                 llvm::Value *metadata,
diff --git a/lib/IRGen/GenValueWitness.cpp b/lib/IRGen/GenValueWitness.cpp
index 5a823d1..a2f4f5a 100644
--- a/lib/IRGen/GenValueWitness.cpp
+++ b/lib/IRGen/GenValueWitness.cpp
@@ -1060,6 +1060,98 @@
                     concreteLoweredType, concreteTI);
 }
 
+static constexpr uint64_t sizeAndAlignment(Size size, Alignment alignment) {
+  return ((uint64_t)size.getValue() << 32) | alignment.getValue();
+}
+
+/// Return a reference to a known value witness table from the runtime
+/// that's suitable for the given type, if there is one, or return null
+/// if we should emit a new one.
+static llvm::Constant *
+getAddrOfKnownValueWitnessTable(IRGenModule &IGM, CanType type) {
+  // Native PE binaries shouldn't reference data symbols across DLLs, so disable
+  // this on Windows.
+  if (IGM.useDllStorage())
+    return nullptr;
+  
+  if (auto nom = type->getAnyNominal()) {
+    // TODO: Generic metadata patterns relative-reference their VWT, which won't
+    // work if it's in a different module without supporting indirection through
+    // the GOT.
+    if (nom->isGenericContext())
+      return nullptr;
+    // TODO: Enums need additional value witnesses for their tag manipulation.
+    if (isa<EnumDecl>(nom))
+      return nullptr;
+  }
+  
+  type = getFormalTypeInContext(type);
+  
+  auto &ti = IGM.getTypeInfoForUnlowered(AbstractionPattern::getOpaque(), type);
+  // We only have witnesses for fixed type info.
+  auto *fixedTI = dyn_cast<FixedTypeInfo>(&ti);
+  if (!fixedTI)
+    return nullptr;
+  
+  CanType witnessSurrogate;
+
+  // Handle common POD type layouts.
+  auto &C = type->getASTContext();
+  ReferenceCounting refCounting;
+  if (fixedTI->isPOD(ResilienceExpansion::Maximal)
+      && fixedTI->getFixedExtraInhabitantCount(IGM) == 0) {
+    // Reuse one of the integer witnesses if applicable.
+    switch (sizeAndAlignment(fixedTI->getFixedSize(),
+                             fixedTI->getFixedAlignment())) {
+    case sizeAndAlignment(Size(0), Alignment(1)):
+      witnessSurrogate = TupleType::getEmpty(C);
+      break;
+    case sizeAndAlignment(Size(1), Alignment(1)):
+      witnessSurrogate = BuiltinIntegerType::get(8, C)->getCanonicalType();
+      break;
+    case sizeAndAlignment(Size(2), Alignment(2)):
+      witnessSurrogate = BuiltinIntegerType::get(16, C)->getCanonicalType();
+      break;
+    case sizeAndAlignment(Size(4), Alignment(4)):
+      witnessSurrogate = BuiltinIntegerType::get(32, C)->getCanonicalType();
+      break;
+    case sizeAndAlignment(Size(8), Alignment(8)):
+      witnessSurrogate = BuiltinIntegerType::get(64, C)->getCanonicalType();
+      break;
+    case sizeAndAlignment(Size(16), Alignment(16)):
+      witnessSurrogate = BuiltinIntegerType::get(128, C)->getCanonicalType();
+      break;
+    case sizeAndAlignment(Size(32), Alignment(32)):
+      witnessSurrogate = BuiltinIntegerType::get(256, C)->getCanonicalType();
+      break;
+    case sizeAndAlignment(Size(64), Alignment(64)):
+      witnessSurrogate = BuiltinIntegerType::get(512, C)->getCanonicalType();
+      break;
+    }
+  } else if (fixedTI->isSingleRetainablePointer(ResilienceExpansion::Maximal,
+                                                &refCounting)) {
+    switch (refCounting) {
+    case ReferenceCounting::Native:
+      witnessSurrogate = C.TheNativeObjectType;
+      break;
+    case ReferenceCounting::ObjC:
+    case ReferenceCounting::Block:
+    case ReferenceCounting::Unknown:
+      witnessSurrogate = C.TheUnknownObjectType;
+      break;
+    case ReferenceCounting::Bridge:
+      witnessSurrogate = C.TheBridgeObjectType;
+      break;
+    case ReferenceCounting::Error:
+      break;
+    }
+  }
+  
+  if (witnessSurrogate)
+    return IGM.getAddrOfValueWitnessTable(witnessSurrogate);
+  return nullptr;
+}
+
 /// Emit a value-witness table for the given type, which is assumed to
 /// be non-dependent.
 llvm::Constant *irgen::emitValueWitnessTable(IRGenModule &IGM,
@@ -1068,7 +1160,16 @@
   // We shouldn't emit global value witness tables for generic type instances.
   assert(!isa<BoundGenericType>(abstractType) &&
          "emitting VWT for generic instance");
-
+  
+  // See if we can use a prefab witness table from the runtime.
+  // Note that we can't do this on Windows since the PE loader does not support
+  // cross-DLL pointers in data.
+  if (!isPattern) {
+    if (auto known = getAddrOfKnownValueWitnessTable(IGM, abstractType)) {
+      return known;
+    }
+  }
+  
   // We should never be making a pattern if the layout isn't fixed.
   // The reverse can be true for types whose layout depends on
   // resilient types.
diff --git a/lib/IRGen/HeapTypeInfo.h b/lib/IRGen/HeapTypeInfo.h
index 15021eb..ded80e4 100644
--- a/lib/IRGen/HeapTypeInfo.h
+++ b/lib/IRGen/HeapTypeInfo.h
@@ -32,7 +32,7 @@
   
 /// The kind of 'isa' encoding a heap object uses to reference its heap
 /// metadata.
-enum class IsaEncoding : unsigned char {
+enum class IsaEncoding : uint8_t {
   /// The object stores a plain pointer to its heap metadata as its first word.
   Pointer,
   /// The object's isa is managed by the Objective-C runtime and must be
@@ -43,7 +43,7 @@
   /// way.
   Unknown = ObjC,
 };
-  
+
 /// HeapTypeInfo - A type designed for use implementing a type
 /// which consists solely of something reference-counted.
 ///
diff --git a/lib/IRGen/IRGen.h b/lib/IRGen/IRGen.h
index 47ff1b9..50066ad 100644
--- a/lib/IRGen/IRGen.h
+++ b/lib/IRGen/IRGen.h
@@ -78,10 +78,10 @@
 }
 
 /// The kind of reference counting implementation a heap object uses.
-enum class ReferenceCounting : unsigned char {
+enum class ReferenceCounting : uint8_t {
   /// The object uses native Swift reference counting.
   Native,
-  
+
   /// The object uses ObjC reference counting.
   ///
   /// When ObjC interop is enabled, native Swift class objects are also ObjC
@@ -90,20 +90,20 @@
   ///
   /// Blocks are always ObjC reference counting compatible.
   ObjC,
-  
+
   /// The object uses _Block_copy/_Block_release reference counting.
   ///
   /// This is a strict subset of ObjC; all blocks are also ObjC reference
   /// counting compatible. The block is assumed to have already been moved to
   /// the heap so that _Block_copy returns the same object back.
   Block,
-  
+
   /// The object has an unknown reference counting implementation.
   ///
   /// This uses maximally-compatible reference counting entry points in the
   /// runtime.
   Unknown,
-  
+
   /// Cases prior to this one are binary-compatible with Unknown reference
   /// counting.
   LastUnknownCompatible = Unknown,
@@ -115,7 +115,7 @@
   /// runtime, with a masking layer on top. A bit inside the pointer is used
   /// to signal native Swift refcounting.
   Bridge,
-  
+
   /// The object uses ErrorType's reference counting entry points.
   Error,
 };
@@ -135,16 +135,16 @@
 };
 
 /// Whether a function requires extra data.
-enum class ExtraData : unsigned char {
+enum class ExtraData : uint8_t {
   /// The function requires no extra data.
   None,
 
   /// The function requires a retainable object pointer of extra data.
   Retainable,
-  
+
   /// The function takes its block object as extra data.
   Block,
-  
+
   Last_ExtraData = Block
 };
 
@@ -159,7 +159,7 @@
 ///
 /// See the comment in RelativePointer.h.
 
-enum class SymbolReferenceKind : unsigned char {
+enum class SymbolReferenceKind : uint8_t {
   /// An absolute reference to the object, i.e. an ordinary pointer.
   ///
   /// Generally well-suited for when C compatibility is a must, dynamic
@@ -295,11 +295,11 @@
 public:
   typedef uint32_t int_type;
 
-  Alignment() : Value(0) {}
-  explicit Alignment(int_type Value) : Value(Value) {}
+  constexpr Alignment() : Value(0) {}
+  constexpr explicit Alignment(int_type Value) : Value(Value) {}
 
-  int_type getValue() const { return Value; }
-  int_type getMaskValue() const { return Value - 1; }
+  constexpr int_type getValue() const { return Value; }
+  constexpr int_type getMaskValue() const { return Value - 1; }
 
   bool isOne() const { return Value == 1; }
   bool isZero() const { return Value == 0; }
@@ -349,7 +349,7 @@
   /// Is this the "invalid" size value?
   bool isInvalid() const { return *this == Size::invalid(); }
 
-  int_type getValue() const { return Value; }
+  constexpr int_type getValue() const { return Value; }
   
   int_type getValueInBits() const { return Value * 8; }
 
diff --git a/lib/IRGen/IRGenDebugInfo.cpp b/lib/IRGen/IRGenDebugInfo.cpp
index d361fd9..3d20d1f 100644
--- a/lib/IRGen/IRGenDebugInfo.cpp
+++ b/lib/IRGen/IRGenDebugInfo.cpp
@@ -1251,14 +1251,15 @@
     case TypeKind::BuiltinVector: {
       (void)MangledName; // FIXME emit the name somewhere.
       auto *BuiltinVectorTy = BaseTy->castTo<BuiltinVectorType>();
-      DebugTypeInfo ElemDbgTy(DbgTy.getDeclContext(),
-                              DbgTy.getGenericEnvironment(),
-                              BuiltinVectorTy->getElementType(),
-                              DbgTy.StorageType, DbgTy.size, DbgTy.align, true);
-      auto Subscripts = nullptr;
-      return DBuilder.createVectorType(BuiltinVectorTy->getNumElements(),
+      auto ElemTy = BuiltinVectorTy->getElementType();
+      auto ElemDbgTy = DebugTypeInfo::getFromTypeInfo(
+          DbgTy.getDeclContext(), DbgTy.getGenericEnvironment(), ElemTy,
+          IGM.getTypeInfoForUnlowered(ElemTy));
+      unsigned Count = BuiltinVectorTy->getNumElements();
+      auto Subscript = DBuilder.getOrCreateSubrange(0, Count ? Count : -1);
+      return DBuilder.createVectorType(SizeInBits,
                                        AlignInBits, getOrCreateType(ElemDbgTy),
-                                       Subscripts);
+                                       DBuilder.getOrCreateArray(Subscript));
     }
 
     // Reference storage types.
diff --git a/lib/IRGen/IRGenMangler.h b/lib/IRGen/IRGenMangler.h
index 06e0043..3f61f96 100644
--- a/lib/IRGen/IRGenMangler.h
+++ b/lib/IRGen/IRGenMangler.h
@@ -233,26 +233,32 @@
     return mangleConformanceSymbol(Type(), C, "MA");
   }
 
-  std::string mangleOutlinedCopyFunction(const GenericTypeDecl *Decl) {
+  std::string mangleOutlinedCopyFunction(CanType ty,
+                                         CanGenericSignature sig) {
     beginMangling();
-    appendAnyGenericType(Decl);
+    appendType(ty);
+    if (sig)
+      appendGenericSignature(sig);
     appendOperator("Wy");
     return finalize();
   }
-  std::string mangleOutlinedConsumeFunction(const GenericTypeDecl *Decl) {
+  std::string mangleOutlinedConsumeFunction(CanType ty,
+                                            CanGenericSignature sig) {
     beginMangling();
-    appendAnyGenericType(Decl);
+    appendType(ty);
+    if (sig)
+      appendGenericSignature(sig);
     appendOperator("We");
     return finalize();
   }
 
-  std::string mangleOutlinedRetainFunction(const Type t) {
+  std::string mangleOutlinedRetainFunction(Type t) {
     beginMangling();
     appendType(t);
     appendOperator("Wr");
     return finalize();
   }
-  std::string mangleOutlinedReleaseFunction(const Type t) {
+  std::string mangleOutlinedReleaseFunction(Type t) {
     beginMangling();
     appendType(t);
     appendOperator("Ws");
diff --git a/lib/IRGen/IRGenModule.cpp b/lib/IRGen/IRGenModule.cpp
index ed748c7..f2dad2f 100644
--- a/lib/IRGen/IRGenModule.cpp
+++ b/lib/IRGen/IRGenModule.cpp
@@ -562,19 +562,28 @@
   return { global, address };
 }
 
-llvm::Constant *IRGenModule::getEmptyTupleMetadata() {
-  if (EmptyTupleMetadata)
-    return EmptyTupleMetadata;
-
-  EmptyTupleMetadata = Module.getOrInsertGlobal(
-                          MANGLE_AS_STRING(METADATA_SYM(EMPTY_TUPLE_MANGLING)),
-                          FullTypeMetadataStructTy);
-  if (useDllStorage())
-    cast<llvm::GlobalVariable>(EmptyTupleMetadata)
-        ->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
-  return EmptyTupleMetadata;
+#define KNOWN_METADATA_ACCESSOR(NAME, SYM) \
+llvm::Constant *IRGenModule::get##NAME() { \
+  if (NAME) \
+    return NAME; \
+  NAME = Module.getOrInsertGlobal( \
+                          SYM, \
+                          FullTypeMetadataStructTy); \
+  if (useDllStorage()) \
+    cast<llvm::GlobalVariable>(NAME) \
+        ->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); \
+  return NAME; \
 }
 
+KNOWN_METADATA_ACCESSOR(EmptyTupleMetadata,
+                        MANGLE_AS_STRING(METADATA_SYM(EMPTY_TUPLE_MANGLING)))
+KNOWN_METADATA_ACCESSOR(AnyExistentialMetadata,
+                        MANGLE_AS_STRING(METADATA_SYM(ANY_MANGLING)))
+KNOWN_METADATA_ACCESSOR(AnyObjectExistentialMetadata,
+                        MANGLE_AS_STRING(METADATA_SYM(ANYOBJECT_MANGLING)))
+
+#undef KNOWN_METADATA_ACCESSOR
+
 llvm::Constant *IRGenModule::getObjCEmptyCachePtr() {
   if (ObjCEmptyCachePtr)
     return ObjCEmptyCachePtr;
diff --git a/lib/IRGen/IRGenModule.h b/lib/IRGen/IRGenModule.h
index 7825fb6..5150bc7 100644
--- a/lib/IRGen/IRGenModule.h
+++ b/lib/IRGen/IRGenModule.h
@@ -1023,6 +1023,8 @@
 //--- Runtime ---------------------------------------------------------------
 public:
   llvm::Constant *getEmptyTupleMetadata();
+  llvm::Constant *getAnyExistentialMetadata();
+  llvm::Constant *getAnyObjectExistentialMetadata();
   llvm::Constant *getObjCEmptyCachePtr();
   llvm::Constant *getObjCEmptyVTablePtr();
   llvm::InlineAsm *getObjCRetainAutoreleasedReturnValueMarker();
@@ -1034,6 +1036,8 @@
 
 private:
   llvm::Constant *EmptyTupleMetadata = nullptr;
+  llvm::Constant *AnyExistentialMetadata = nullptr;
+  llvm::Constant *AnyObjectExistentialMetadata = nullptr;
   llvm::Constant *ObjCEmptyCachePtr = nullptr;
   llvm::Constant *ObjCEmptyVTablePtr = nullptr;
   llvm::Constant *ObjCISAMaskPtr = nullptr;
diff --git a/lib/IRGen/IRGenSIL.cpp b/lib/IRGen/IRGenSIL.cpp
index 9d7582a..3ca4b5b 100644
--- a/lib/IRGen/IRGenSIL.cpp
+++ b/lib/IRGen/IRGenSIL.cpp
@@ -26,6 +26,7 @@
 #include "llvm/ADT/MapVector.h"
 #include "llvm/ADT/SmallBitVector.h"
 #include "llvm/ADT/TinyPtrVector.h"
+#include "llvm/Support/SaveAndRestore.h"
 #include "llvm/Support/Debug.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/Basic/TargetInfo.h"
@@ -1552,6 +1553,12 @@
     return;
 
   PrettyStackTraceSILFunction stackTrace("emitting IR", f);
+  llvm::SaveAndRestore<SourceFile *> SetCurSourceFile(CurSourceFile);
+  if (auto dc = f->getDeclContext()) {
+    if (auto sf = dc->getParentSourceFile()) {
+      CurSourceFile = sf;
+    }
+  }
   IRGenSILFunction(*this, f).emitSILFunction();
 }
 
diff --git a/lib/IRGen/MemberAccessStrategy.h b/lib/IRGen/MemberAccessStrategy.h
index b847c2d..06e9f88 100644
--- a/lib/IRGen/MemberAccessStrategy.h
+++ b/lib/IRGen/MemberAccessStrategy.h
@@ -27,12 +27,12 @@
 /// A class which describes how to access a particular physical member.
 class MemberAccessStrategy {
 public:
-  enum class OffsetKind : unsigned char {
+  enum class OffsetKind : uint8_t {
     /// A word-size offset that represents a number of bytes.
     Bytes_Word,
   };
 
-  enum class Kind : unsigned char {
+  enum class Kind : uint8_t {
     /// The member has complex or overlapping storage.  It cannot be
     /// accessed simply by projecting out to a particular offset.
     Complex,
diff --git a/lib/Parse/Lexer.cpp b/lib/Parse/Lexer.cpp
index 047e880..816c6b4 100644
--- a/lib/Parse/Lexer.cpp
+++ b/lib/Parse/Lexer.cpp
@@ -278,8 +278,14 @@
     Kind = tok::eof;
   }
   unsigned CommentLength = 0;
-  if (RetainComments == CommentRetentionMode::AttachToNextToken && SeenComment)
-    CommentLength = TokStart - LastCommentBlockStart;
+  if (RetainComments == CommentRetentionMode::AttachToNextToken) {
+    auto Iter = llvm::find_if(LeadingTrivia, [](const TriviaPiece &Piece) {
+      return Piece.isComment();
+    });
+    for (auto End = LeadingTrivia.end(); Iter != End; Iter++) {
+      CommentLength += Iter->getTextLength();
+    }
+  }
 
   StringRef TokenText { TokStart, static_cast<size_t>(CurPtr - TokStart) };
 
@@ -600,24 +606,16 @@
 
 
 tok Lexer::kindOfIdentifier(StringRef Str, bool InSILMode) {
-  tok Kind = llvm::StringSwitch<tok>(Str)
-#define KEYWORD(kw) \
-    .Case(#kw, tok::kw_##kw)
+#define SIL_KEYWORD(kw)
+#define KEYWORD(kw) if (Str == #kw) return tok::kw_##kw;
 #include "swift/Syntax/TokenKinds.def"
-    .Default(tok::identifier);
 
   // SIL keywords are only active in SIL mode.
-  switch (Kind) {
-#define SIL_KEYWORD(kw) \
-    case tok::kw_##kw:
+  if (InSILMode) {
+#define SIL_KEYWORD(kw) if (Str == #kw) return tok::kw_##kw;
 #include "swift/Syntax/TokenKinds.def"
-      if (!InSILMode)
-        Kind = tok::identifier;
-      break;
-    default:
-      break;
   }
-  return Kind;
+  return tok::identifier;
 }
 
 /// lexIdentifier - Match [a-zA-Z_][a-zA-Z_$0-9]*
@@ -644,15 +642,6 @@
      ++CurPtr;
      return formToken(tok::r_square_lit, TokStart);
   }
-  
-  // Allow a hashbang #! line at the beginning of the file.
-  if (CurPtr - 1 == ContentStart && *CurPtr == '!') {
-    --CurPtr;
-    if (BufferID != SourceMgr.getHashbangBufferID())
-      diagnose(CurPtr, diag::lex_hashbang_not_allowed);
-    skipHashbang(/*EatNewline=*/true);
-    return lexImpl();
-  }
 
   // Scan for [a-zA-Z]+ to see what we match.
   const char *tmpPtr = CurPtr;
@@ -2177,10 +2166,6 @@
     NextToken.setAtStartOfLine(false);
   }
 
-  // Remember where we started so that we can find the comment range.
-  LastCommentBlockStart = CurPtr;
-  SeenComment = false;
-
   lexTrivia(LeadingTrivia, /* IsForTrailingTrivia */ false);
 
   // Remember the start of the token so we can form the text range.
@@ -2270,14 +2255,12 @@
   case '/':
     if (CurPtr[0] == '/') {  // "//"
       skipSlashSlashComment(/*EatNewline=*/true);
-      SeenComment = true;
       assert(isKeepingComments() &&
              "Non token comment should be eaten by lexTrivia as LeadingTrivia");
       return formToken(tok::comment, TokStart);
     }
     if (CurPtr[0] == '*') { // "/*"
       skipSlashStarComment();
-      SeenComment = true;
       assert(isKeepingComments() &&
              "Non token comment should be eaten by lexTrivia as LeadingTrivia");
       return formToken(tok::comment, TokStart);
@@ -2410,7 +2393,6 @@
       break;
     } else if (*CurPtr == '/') {
       // '// ...' comment.
-      SeenComment = true;
       bool isDocComment = CurPtr[1] == '/';
       skipSlashSlashComment(/*EatNewline=*/false);
       size_t Length = CurPtr - TriviaStart;
@@ -2420,7 +2402,6 @@
       goto Restart;
     } else if (*CurPtr == '*') {
       // '/* ... */' comment.
-      SeenComment = true;
       bool isDocComment = CurPtr[1] == '*';
       skipSlashStarComment();
       size_t Length = CurPtr - TriviaStart;
diff --git a/lib/Parse/ParseExpr.cpp b/lib/Parse/ParseExpr.cpp
index cbc527d..66e0fdb 100644
--- a/lib/Parse/ParseExpr.cpp
+++ b/lib/Parse/ParseExpr.cpp
@@ -3089,6 +3089,12 @@
 ParserResult<Expr> Parser::parseTrailingClosure(SourceRange calleeRange) {
   SourceLoc braceLoc = Tok.getLoc();
 
+  // Record the line numbers for the diagnostics below.
+  // Note that *do not* move this to after 'parseExprClosure()' it slows down
+  // 'getLineNumber()' call because of cache in SourceMgr.
+  auto origLine = SourceMgr.getLineNumber(calleeRange.End);
+  auto braceLine = SourceMgr.getLineNumber(braceLoc);
+
   // Parse the closure.
   ParserResult<Expr> closure = parseExprClosure();
   if (closure.isNull())
@@ -3097,8 +3103,6 @@
   // Warn if the trailing closure is separated from its callee by more than
   // one line. A single-line separation is acceptable for a trailing closure
   // call, and will be diagnosed later only if the call fails to typecheck.
-  auto origLine = SourceMgr.getLineNumber(calleeRange.End);
-  auto braceLine = SourceMgr.getLineNumber(braceLoc);
   if (braceLine > origLine + 1) {
     diagnose(braceLoc, diag::trailing_closure_after_newlines);
     diagnose(calleeRange.Start, diag::trailing_closure_callee_here);
diff --git a/lib/Parse/ParseStmt.cpp b/lib/Parse/ParseStmt.cpp
index 5915b16..c186946 100644
--- a/lib/Parse/ParseStmt.cpp
+++ b/lib/Parse/ParseStmt.cpp
@@ -1599,6 +1599,7 @@
 ///   stmt-while:
 ///     (identifier ':')? 'while' expr-basic stmt-brace
 ParserResult<Stmt> Parser::parseStmtWhile(LabeledStmtInfo LabelInfo) {
+  SyntaxContext->setCreateSyntax(SyntaxKind::WhileStmt);
   SourceLoc WhileLoc = consumeToken(tok::kw_while);
 
   Scope S(this, ScopeKind::WhileVars);
diff --git a/lib/SIL/InstructionUtils.cpp b/lib/SIL/InstructionUtils.cpp
index 0eb3a1d..d3f1a4f 100644
--- a/lib/SIL/InstructionUtils.cpp
+++ b/lib/SIL/InstructionUtils.cpp
@@ -14,6 +14,7 @@
 #include "swift/SIL/InstructionUtils.h"
 #include "swift/AST/SubstitutionMap.h"
 #include "swift/Basic/NullablePtr.h"
+#include "swift/SIL/DebugUtils.h"
 #include "swift/SIL/Projection.h"
 #include "swift/SIL/SILArgument.h"
 #include "swift/SIL/SILBasicBlock.h"
@@ -181,6 +182,18 @@
   }
 }
 
+SILValue swift::stripAddressAccess(SILValue V) {
+  while (true) {
+    switch (V->getKind()) {
+    default:
+      return V;
+    case ValueKind::BeginBorrowInst:
+    case ValueKind::BeginAccessInst:
+      V = cast<SingleValueInstruction>(V)->getOperand(0);
+    }
+  }
+}
+
 SILValue swift::stripAddressProjections(SILValue V) {
   while (true) {
     V = stripSinglePredecessorArgs(V);
@@ -249,19 +262,23 @@
   }
 }
 
-bool swift::isIncidentalUse(SILInstruction *user) {
+// Does this instruction terminate a SIL-level scope?
+bool swift::isEndOfScopeMarker(SILInstruction *user) {
   switch (user->getKind()) {
   default:
     return false;
-  case SILInstructionKind::DebugValueInst:
   case SILInstructionKind::EndAccessInst:
   case SILInstructionKind::EndBorrowInst:
   case SILInstructionKind::EndLifetimeInst:
-  case SILInstructionKind::FixLifetimeInst:
     return true;
   }
 }
 
+bool swift::isIncidentalUse(SILInstruction *user) {
+  return isEndOfScopeMarker(user) || isDebugInst(user)
+         || isa<FixLifetimeInst>(user);
+}
+
 bool swift::onlyAffectsRefCount(SILInstruction *user) {
   switch (user->getKind()) {
   default:
diff --git a/lib/SIL/SILBuilder.cpp b/lib/SIL/SILBuilder.cpp
index bca1cff..80265f3 100644
--- a/lib/SIL/SILBuilder.cpp
+++ b/lib/SIL/SILBuilder.cpp
@@ -521,3 +521,20 @@
               return P.createAddressProjection(*this, Loc, V).get();
             });
 }
+
+DebugValueInst *SILBuilder::createDebugValue(SILLocation Loc, SILValue src,
+                                             SILDebugVariable Var) {
+  // Debug location overrides cannot apply to debug value instructions.
+  DebugLocOverrideRAII LocOverride{*this, None};
+  return insert(
+      DebugValueInst::create(getSILDebugLocation(Loc), src, getModule(), Var));
+}
+
+DebugValueAddrInst *SILBuilder::createDebugValueAddr(SILLocation Loc,
+                                                     SILValue src,
+                                                     SILDebugVariable Var) {
+  // Debug location overrides cannot apply to debug addr instructions.
+  DebugLocOverrideRAII LocOverride{*this, None};
+  return insert(DebugValueAddrInst::create(getSILDebugLocation(Loc), src,
+                                           getModule(), Var));
+}
diff --git a/lib/SIL/ValueOwnershipKindClassifier.cpp b/lib/SIL/ValueOwnershipKindClassifier.cpp
index 1dfb81a..d201e3f 100644
--- a/lib/SIL/ValueOwnershipKindClassifier.cpp
+++ b/lib/SIL/ValueOwnershipKindClassifier.cpp
@@ -148,6 +148,20 @@
 // If both the operand and the result are nontrivial, then either the types must
 // be compatible so that TBAA doesn't allow the destroy to be hoisted above uses
 // of the cast, or the programmer must use Builtin.fixLifetime.
+//
+// FIXME
+// -----
+//
+// SR-7175: Since we model this as unowned, then we must copy the
+// value before use. This directly contradicts the semantics mentioned
+// above since we will copy the value upon any use lest we use an
+// unowned value in an owned or guaranteed way. So really all we will
+// do here is perhaps add a copy slightly earlier unless the unowned
+// value immediately is cast to something trivial. In such a case, we
+// should be able to simplify the cast to just a trivial value and
+// then eliminate the copy. That being said, we should investigate
+// this since this is used in reinterpret_cast which is important from
+// a performance perspective.
 CONSTANT_OR_TRIVIAL_OWNERSHIP_INST(Unowned, UncheckedBitwiseCast)
 
 // A thin_to_thick instruction can return a trivial (@noescape) type.
diff --git a/lib/SILGen/ArgumentSource.h b/lib/SILGen/ArgumentSource.h
index 036a46e..15fae63 100644
--- a/lib/SILGen/ArgumentSource.h
+++ b/lib/SILGen/ArgumentSource.h
@@ -49,7 +49,7 @@
 /// working with multiple ArgumentSources should document the order in
 /// which they plan to evaluate them.
 class ArgumentSource {
-  enum class Kind : unsigned char {
+  enum class Kind : uint8_t {
     Invalid,
     RValue,
     LValue,
diff --git a/lib/SILGen/SILGenBridging.cpp b/lib/SILGen/SILGenBridging.cpp
index 710efca..101b1d8 100644
--- a/lib/SILGen/SILGenBridging.cpp
+++ b/lib/SILGen/SILGenBridging.cpp
@@ -1063,9 +1063,8 @@
     // Bitcast to Optional. This provides a barrier to the optimizer to prevent
     // it from attempting to eliminate null checks.
     auto optionalBridgedTy = SILType::getOptionalType(loweredBridgedTy);
-    auto optionalV =
-      SGF.B.createUncheckedBitCast(loc, v.getValue(), optionalBridgedTy);
-    auto optionalMV = ManagedValue(optionalV, v.getCleanup());
+    auto optionalMV =
+      SGF.B.createUncheckedBitCast(loc, v, optionalBridgedTy);
     return SGF.emitApplyOfLibraryIntrinsic(loc,
                            SGF.getASTContext().getBridgeAnyObjectToAny(nullptr),
                            SubstitutionMap(), optionalMV, C)
diff --git a/lib/SILGen/SILGenBuilder.cpp b/lib/SILGen/SILGenBuilder.cpp
index 9cba6dc..fe80671 100644
--- a/lib/SILGen/SILGenBuilder.cpp
+++ b/lib/SILGen/SILGenBuilder.cpp
@@ -702,7 +702,30 @@
                                                    ManagedValue value,
                                                    SILType type) {
   CleanupCloner cloner(*this, value);
-  SILValue cast = createUncheckedBitCast(loc, value.forward(SGF), type);
+  SILValue cast = createUncheckedBitCast(loc, value.getValue(), type);
+
+  // Currently SILBuilder::createUncheckedBitCast only produces these
+  // instructions. We assert here to make sure if this changes, this code is
+  // updated.
+  assert((isa<UncheckedTrivialBitCastInst>(cast) ||
+          isa<UncheckedRefCastInst>(cast) ||
+          isa<UncheckedBitwiseCastInst>(cast)) &&
+         "SILGenBuilder is out of sync with SILBuilder.");
+
+  // If we have a trivial inst, just return early.
+  if (isa<UncheckedTrivialBitCastInst>(cast))
+    return ManagedValue::forUnmanaged(cast);
+
+  // If we perform an unchecked bitwise case, then we are producing a new RC
+  // identity implying that we need a copy of the casted value to be returned so
+  // that the inputs/outputs of the case have separate ownership.
+  if (isa<UncheckedBitwiseCastInst>(cast)) {
+    return ManagedValue::forUnmanaged(cast).copy(SGF, loc);
+  }
+
+  // Otherwise, we forward the cleanup of the input value and place the cleanup
+  // on the cast value since unchecked_ref_cast is "forwarding".
+  value.forward(SGF);
   return cloner.clone(cast);
 }
 
@@ -871,3 +894,10 @@
             });
   return cloner.clone(createTuple(loc, type, forwardedValues));
 }
+
+ManagedValue SILGenBuilder::createUncheckedAddrCast(SILLocation loc, ManagedValue op,
+                                                    SILType resultTy) {
+  CleanupCloner cloner(*this, op);
+  SILValue cast = createUncheckedAddrCast(loc, op.forward(SGF), resultTy);
+  return cloner.clone(cast);
+}
diff --git a/lib/SILGen/SILGenBuilder.h b/lib/SILGen/SILGenBuilder.h
index d1b5420..26cce6f 100644
--- a/lib/SILGen/SILGenBuilder.h
+++ b/lib/SILGen/SILGenBuilder.h
@@ -310,6 +310,10 @@
   ManagedValue createUncheckedRefCast(SILLocation loc, ManagedValue original,
                                       SILType type);
 
+  using SILBuilder::createUncheckedAddrCast;
+  ManagedValue createUncheckedAddrCast(SILLocation loc, ManagedValue op,
+                                       SILType resultTy);
+
   using SILBuilder::createUncheckedBitCast;
   ManagedValue createUncheckedBitCast(SILLocation loc, ManagedValue original,
                                       SILType type);
diff --git a/lib/SILGen/SILGenExpr.cpp b/lib/SILGen/SILGenExpr.cpp
index 3149b26..16affcc 100644
--- a/lib/SILGen/SILGenExpr.cpp
+++ b/lib/SILGen/SILGenExpr.cpp
@@ -10,7 +10,6 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "SILGen.h"
 #include "ArgumentScope.h"
 #include "ArgumentSource.h"
 #include "Callee.h"
@@ -21,16 +20,18 @@
 #include "LValue.h"
 #include "RValue.h"
 #include "ResultPlan.h"
+#include "SILGen.h"
 #include "SILGenDynamicCast.h"
 #include "Scope.h"
+#include "SwitchEnumBuilder.h"
 #include "Varargs.h"
 #include "swift/AST/ASTContext.h"
+#include "swift/AST/ASTMangler.h"
 #include "swift/AST/Decl.h"
 #include "swift/AST/DiagnosticsCommon.h"
 #include "swift/AST/Expr.h"
 #include "swift/AST/ForeignErrorConvention.h"
 #include "swift/AST/GenericEnvironment.h"
-#include "swift/AST/ASTMangler.h"
 #include "swift/AST/ParameterList.h"
 #include "swift/AST/ProtocolConformance.h"
 #include "swift/AST/SubstitutionMap.h"
@@ -4202,6 +4203,9 @@
 /// Flattens one level of optional from a nested optional value.
 static ManagedValue flattenOptional(SILGenFunction &SGF, SILLocation loc,
                                     ManagedValue optVal) {
+  // This code assumes that we have a +1 value.
+  assert(optVal.isPlusOne(SGF));
+
   // FIXME: Largely copied from SILGenFunction::emitOptionalToOptional.
   auto contBB = SGF.createBasicBlock();
   auto isNotPresentBB = SGF.createBasicBlock();
@@ -4212,57 +4216,54 @@
   assert(resultTy.getSwiftRValueType().getOptionalObjectType() &&
          "input was not a nested optional value");
 
-  // If the result is address-only, we need to return something in memory,
-  // otherwise the result is the BBArgument in the merge point.
-  SILValue result;
-  if (resultTL.isAddressOnly())
-    result = SGF.emitTemporaryAllocation(loc, resultTy);
-  else
-    result = contBB->createPHIArgument(resultTy, ValueOwnershipKind::Owned);
-
-  // Branch on whether the input is optional, this doesn't consume the value.
-  auto isPresent = SGF.emitDoesOptionalHaveValue(loc, optVal.getValue());
-  SGF.B.createCondBranch(loc, isPresent, isPresentBB, isNotPresentBB);
-
-  // If it's present, apply the recursive transformation to the value.
-  SGF.B.emitBlock(isPresentBB);
-  SILValue branchArg;
-  {
-    // Don't allow cleanups to escape the conditional block.
-    FullExpr presentScope(SGF.Cleanups, CleanupLocation::get(loc));
-
-    // Pull the value out.  This will load if the value is not address-only.
-    auto &inputTL = SGF.getTypeLowering(optVal.getType());
-    auto resultValue = SGF.emitUncheckedGetOptionalValueFrom(loc, optVal,
-                                                             inputTL);
-
-    // Inject that into the result type if the result is address-only.
-    if (resultTL.isAddressOnly())
-      resultValue.forwardInto(SGF, loc, result);
-    else
-      branchArg = resultValue.forward(SGF);
-  }
-  if (branchArg)
-    SGF.B.createBranch(loc, contBB, branchArg);
-  else
-    SGF.B.createBranch(loc, contBB);
-
-  // If it's not present, inject 'nothing' into the result.
-  SGF.B.emitBlock(isNotPresentBB);
+  SILValue contBBArg;
+  TemporaryInitializationPtr addrOnlyResultBuf;
   if (resultTL.isAddressOnly()) {
-    SGF.emitInjectOptionalNothingInto(loc, result, resultTL);
-    SGF.B.createBranch(loc, contBB);
+    addrOnlyResultBuf = SGF.emitTemporary(loc, resultTL);
   } else {
-    branchArg = SGF.getOptionalNoneValue(loc, resultTL);
-    SGF.B.createBranch(loc, contBB, branchArg);
+    contBBArg = contBB->createPHIArgument(resultTy, ValueOwnershipKind::Owned);
   }
 
+  SwitchEnumBuilder SEB(SGF.B, loc, optVal);
+
+  auto *someDecl = SGF.getASTContext().getOptionalSomeDecl();
+  SEB.addCase(someDecl, isPresentBB, contBB, [&](ManagedValue input,
+                                                 SwitchCaseFullExpr &scope) {
+    if (resultTL.isAddressOnly()) {
+      SILValue addr =
+          addrOnlyResultBuf->getAddressForInPlaceInitialization(SGF, loc);
+      input = SGF.B.createUncheckedTakeEnumDataAddr(
+          loc, input, someDecl, input.getType().getOptionalObjectType());
+      SGF.B.createCopyAddr(loc, input.getValue(), addr, IsNotTake,
+                           IsInitialization);
+      scope.exitAndBranch(loc);
+      return;
+    }
+    scope.exitAndBranch(loc, input.forward(SGF));
+  });
+  SEB.addCase(
+      SGF.getASTContext().getOptionalNoneDecl(), isNotPresentBB, contBB,
+      [&](ManagedValue input, SwitchCaseFullExpr &scope) {
+        if (resultTL.isAddressOnly()) {
+          SILValue addr =
+              addrOnlyResultBuf->getAddressForInPlaceInitialization(SGF, loc);
+          SGF.emitInjectOptionalNothingInto(loc, addr, resultTL);
+          scope.exitAndBranch(loc);
+          return;
+        }
+
+        auto mv = SGF.B.createManagedOptionalNone(loc, resultTy).forward(SGF);
+        scope.exitAndBranch(loc, mv);
+      });
+  std::move(SEB).emit();
+
   // Continue.
   SGF.B.emitBlock(contBB);
-  if (resultTL.isAddressOnly())
-    return SGF.emitManagedBufferWithCleanup(result, resultTL);
-
-  return SGF.emitManagedRValueWithCleanup(result, resultTL);
+  if (resultTL.isAddressOnly()) {
+    addrOnlyResultBuf->finishInitialization(SGF);
+    return addrOnlyResultBuf->getManagedAddress();
+  }
+  return SGF.emitManagedRValueWithCleanup(contBBArg, resultTL);
 }
 
 static ManagedValue
diff --git a/lib/SILGen/SILGenPattern.cpp b/lib/SILGen/SILGenPattern.cpp
index 3f25973..73def58 100644
--- a/lib/SILGen/SILGenPattern.cpp
+++ b/lib/SILGen/SILGenPattern.cpp
@@ -421,6 +421,13 @@
     : SGF(SGF), PatternMatchStmt(S),
       CompletionHandler(completionHandler) {}
 
+  Optional<SILLocation> getSubjectLocationOverride(SILLocation loc) const {
+    if (auto *Switch = dyn_cast<SwitchStmt>(PatternMatchStmt))
+      if (!Switch->isImplicit())
+        return SILLocation(Switch->getSubjectExpr());
+    return None;
+  }
+
   void emitDispatch(ClauseMatrix &matrix, ArgArray args,
                     const FailureHandler &failure);
 
@@ -1144,6 +1151,7 @@
 void PatternMatchEmission::bindExprPattern(ExprPattern *pattern,
                                            ConsumableManagedValue value,
                                            const FailureHandler &failure) {
+  DebugLocOverrideRAII LocOverride{SGF.B, getSubjectLocationOverride(pattern)};
   FullExpr scope(SGF.Cleanups, CleanupLocation(pattern));
   bindVariable(pattern, pattern->getMatchVar(), value,
                pattern->getType()->getCanonicalType(),
diff --git a/lib/SILGen/SILGenPoly.cpp b/lib/SILGen/SILGenPoly.cpp
index 16491e4..1726561 100644
--- a/lib/SILGen/SILGenPoly.cpp
+++ b/lib/SILGen/SILGenPoly.cpp
@@ -415,12 +415,9 @@
     // If the conversion is trivial, just cast.
     if (SGF.SGM.Types.checkForABIDifferences(v.getType(), loweredResultTy)
           == TypeConverter::ABIDifference::Trivial) {
-      SILValue result = v.getValue();
       if (v.getType().isAddress())
-        result = SGF.B.createUncheckedAddrCast(Loc, result, loweredResultTy);
-      else
-        result = SGF.B.createUncheckedBitCast(Loc, result, loweredResultTy);
-      return ManagedValue(result, v.getCleanup());
+        return SGF.B.createUncheckedAddrCast(Loc, v, loweredResultTy);
+      return SGF.B.createUncheckedBitCast(Loc, v, loweredResultTy);
     }
 
     auto transformOptionalPayload =
diff --git a/lib/SILGen/SwitchEnumBuilder.cpp b/lib/SILGen/SwitchEnumBuilder.cpp
index 935d043..901091b 100644
--- a/lib/SILGen/SwitchEnumBuilder.cpp
+++ b/lib/SILGen/SwitchEnumBuilder.cpp
@@ -106,7 +106,7 @@
       input = builder.createOwnedPHIArgument(optional.getType());
     }
     handler(input, presentScope);
-    assert(!builder.hasValidInsertionPoint());
+    builder.clearInsertionPoint();
   }
 
   for (NormalCaseData &caseData : caseDataArray) {
@@ -133,7 +133,7 @@
       }
     }
     handler(input, presentScope);
-    assert(!builder.hasValidInsertionPoint());
+    builder.clearInsertionPoint();
   }
 
   // If we are asked to create a default block and it is specified that the
@@ -154,6 +154,6 @@
       input = builder.createOwnedPHIArgument(optional.getType());
     }
     handler(input, presentScope);
-    assert(!builder.hasValidInsertionPoint());
+    builder.clearInsertionPoint();
   }
 }
diff --git a/lib/SILOptimizer/Analysis/SimplifyInstruction.cpp b/lib/SILOptimizer/Analysis/SimplifyInstruction.cpp
index 97561a0..e49864d 100644
--- a/lib/SILOptimizer/Analysis/SimplifyInstruction.cpp
+++ b/lib/SILOptimizer/Analysis/SimplifyInstruction.cpp
@@ -12,10 +12,11 @@
 
 #define DEBUG_TYPE "sil-simplify"
 #include "swift/SILOptimizer/Analysis/SimplifyInstruction.h"
-#include "swift/SILOptimizer/Analysis/ValueTracking.h"
-#include "swift/SILOptimizer/Utils/Local.h"
+#include "swift/SIL/InstructionUtils.h"
 #include "swift/SIL/PatternMatch.h"
 #include "swift/SIL/SILVisitor.h"
+#include "swift/SILOptimizer/Analysis/ValueTracking.h"
+#include "swift/SILOptimizer/Utils/Local.h"
 
 using namespace swift;
 using namespace swift::PatternMatch;
@@ -54,6 +55,7 @@
     visitUncheckedTrivialBitCastInst(UncheckedTrivialBitCastInst *UTBCI);
     SILValue visitThinFunctionToPointerInst(ThinFunctionToPointerInst *TFTPI);
     SILValue visitPointerToThinFunctionInst(PointerToThinFunctionInst *PTTFI);
+    SILValue visitBeginAccessInst(BeginAccessInst *BAI);
 
     SILValue simplifyOverflowBuiltin(BuiltinInst *BI);
   };
@@ -451,6 +453,16 @@
   return SILValue();
 }
 
+SILValue InstSimplifier::visitBeginAccessInst(BeginAccessInst *BAI) {
+  // Remove "dead" begin_access.
+  if (llvm::all_of(BAI->getUses(), [](Operand *operand) -> bool {
+        return isIncidentalUse(operand->getUser());
+      })) {
+    return BAI->getOperand();
+  }
+  return SILValue();
+}
+
 static SILValue simplifyBuiltin(BuiltinInst *BI) {
   const IntrinsicInfo &Intrinsic = BI->getIntrinsicInfo();
 
@@ -698,6 +710,34 @@
   return InstSimplifier().visit(I);
 }
 
+/// Replace an instruction with a simplified result, including any debug uses,
+/// and erase the instruction. If the instruction initiates a scope, do not
+/// replace the end of its scope; it will be deleted along with its parent.
+void swift::replaceAllSimplifiedUsesAndErase(
+    SILInstruction *I, SILValue result,
+    std::function<void(SILInstruction *)> eraseNotify) {
+
+  auto *SVI = cast<SingleValueInstruction>(I);
+  assert(SVI != result && "Cannot RAUW a value with itself");
+
+  // Only SingleValueInstructions are currently simplified.
+  while (!SVI->use_empty()) {
+    Operand *use = *SVI->use_begin();
+    SILInstruction *user = use->getUser();
+    // Erase the end of scope marker.
+    if (isEndOfScopeMarker(user)) {
+      if (eraseNotify)
+        eraseNotify(user);
+      user->eraseFromParent();
+      continue;
+    }
+    use->set(result);
+  }
+  I->eraseFromParent();
+  if (eraseNotify)
+    eraseNotify(I);
+}
+
 /// Simplify invocations of builtin operations that may overflow.
 /// All such operations return a tuple (result, overflow_flag).
 /// This function try to simplify such operations, but returns only a
diff --git a/lib/SILOptimizer/IPO/LetPropertiesOpts.cpp b/lib/SILOptimizer/IPO/LetPropertiesOpts.cpp
index 775fbcb..eb014e5 100644
--- a/lib/SILOptimizer/IPO/LetPropertiesOpts.cpp
+++ b/lib/SILOptimizer/IPO/LetPropertiesOpts.cpp
@@ -19,9 +19,10 @@
 //===----------------------------------------------------------------------===//
 
 #define DEBUG_TYPE "let-properties-opt"
-#include "swift/SIL/SILInstruction.h"
-#include "swift/SIL/SILBasicBlock.h"
 #include "swift/SIL/DebugUtils.h"
+#include "swift/SIL/InstructionUtils.h"
+#include "swift/SIL/SILBasicBlock.h"
+#include "swift/SIL/SILInstruction.h"
 #include "swift/SIL/SILLinkage.h"
 #include "swift/SILOptimizer/PassManager/Passes.h"
 #include "swift/SILOptimizer/PassManager/Transforms.h"
@@ -201,7 +202,10 @@
     };
 
     // Look for any instructions accessing let properties.
-    if (auto proj = dyn_cast<RefElementAddrInst>(Load)) {
+    if (isa<RefElementAddrInst>(Load) || isa<StructElementAddrInst>(Load)
+        || isa<BeginAccessInst>(Load)) {
+      auto proj = cast<SingleValueInstruction>(Load);
+
       // Copy the initializer into the function
       // Replace the access to a let property by the value
       // computed by this initializer.
@@ -210,6 +214,14 @@
       for (auto UI = proj->use_begin(), E = proj->use_end(); UI != E;) {
         auto *User = UI->getUser();
         ++UI;
+
+        if (isIncidentalUse(User))
+          continue;
+
+        // A nested begin_access will be mapped as a separate "Load".
+        if (isa<BeginAccessInst>(User))
+          continue;
+
         if (isa<StoreInst>(User))
           continue;
 
@@ -231,23 +243,6 @@
       proj->eraseFromParent();
       ++NumReplaced;
       ChangedFunctions.insert(F);
-    }  else if (auto proj = dyn_cast<StructElementAddrInst>(Load)) {
-      // Copy the initializer into the function
-      // Replace the access to a let property by the value
-      // computed by this initializer.
-      SILValue clonedInit = cloneInitAt(proj);
-      SILBuilderWithScope B(proj);
-      for (auto UI = proj->use_begin(), E = proj->use_end(); UI != E;) {
-        auto *User = UI->getUser();
-        ++UI;
-        if (isa<StoreInst>(User))
-          continue;
-        replaceLoadSequence(User, clonedInit, B);
-        eraseUsesOfInstruction(User);
-        User->eraseFromParent();
-        ++NumReplaced;
-      }
-      ChangedFunctions.insert(F);
     }
   }
 
@@ -422,7 +417,7 @@
   if (auto SI = dyn_cast<StructInst>(I)) {
     value = SI->getFieldValue(Property);
   } else if (auto SI = dyn_cast<StoreInst>(I)) {
-    auto Dest = SI->getDest();
+    auto Dest = stripAddressAccess(SI->getDest());
 
     assert(((isa<RefElementAddrInst>(Dest) &&
              cast<RefElementAddrInst>(Dest)->getField() == Property) ||
@@ -524,9 +519,12 @@
 
   if (isa<StructElementAddrInst>(I) || isa<TupleElementAddrInst>(I)) {
     auto projection = cast<SingleValueInstruction>(I);
-    for (auto Use : getNonDebugUses(projection))
+    for (auto Use : getNonDebugUses(projection)) {
+      if (isIncidentalUse(Use->getUser()))
+        continue;
       if (!isValidPropertyLoad(Use->getUser()))
         return false;
+    }
     return true;
   }
 
@@ -545,11 +543,19 @@
                      << "':\n";
         llvm::dbgs() << "The instructions are:\n"; I->dumpInContext());
 
-  if (isa<RefElementAddrInst>(I) || isa<StructElementAddrInst>(I)) {
+  if (isa<RefElementAddrInst>(I) || isa<StructElementAddrInst>(I)
+      || isa<BeginAccessInst>(I)) {
     // Check if there is a store to this property.
     auto projection = cast<SingleValueInstruction>(I);
     for (auto Use : getNonDebugUses(projection)) {
       auto *User = Use->getUser();
+      if (isIncidentalUse(User))
+        continue;
+
+      // Each begin_access is analyzed as a separate property access. Do not
+      // consider a begin_access a use of the current projection.
+      if (isa<BeginAccessInst>(User))
+        continue;
 
       if (auto *SI = dyn_cast<StoreInst>(User)) {
         // There is a store into this property.
@@ -595,7 +601,12 @@
         // It includes referencing this specific property (both reads and
         // stores), as well as implicit stores by means of e.g.
         // a struct instruction.
-        if (auto *REAI = dyn_cast<RefElementAddrInst>(&I)) {
+        if (auto *BAI = dyn_cast<BeginAccessInst>(&I)) {
+          if (auto *REAI =
+                  dyn_cast<RefElementAddrInst>(stripAddressAccess(BAI))) {
+            collectPropertyAccess(BAI, REAI->getField(), NonRemovable);
+          }
+        } else if (auto *REAI = dyn_cast<RefElementAddrInst>(&I)) {
           collectPropertyAccess(REAI, REAI->getField(), NonRemovable);
         } else if (auto *SEI = dyn_cast<StructExtractInst>(&I)) {
           collectPropertyAccess(SEI, SEI->getField(), NonRemovable);
diff --git a/lib/SILOptimizer/Mandatory/DefiniteInitialization.cpp b/lib/SILOptimizer/Mandatory/DefiniteInitialization.cpp
index ce6ff666..82f1ef1 100644
--- a/lib/SILOptimizer/Mandatory/DefiniteInitialization.cpp
+++ b/lib/SILOptimizer/Mandatory/DefiniteInitialization.cpp
@@ -191,11 +191,7 @@
 //===----------------------------------------------------------------------===//
 
 namespace {
-  enum class DIKind : unsigned char {
-    No,
-    Yes,
-    Partial
-  };
+enum class DIKind : uint8_t { No, Yes, Partial };
 } // end anonymous namespace
 
 /// This implements the lattice merge operation for 2 optional DIKinds.
diff --git a/lib/SILOptimizer/SILCombiner/SILCombine.cpp b/lib/SILOptimizer/SILCombiner/SILCombine.cpp
index 71fd610..b45ef4d 100644
--- a/lib/SILOptimizer/SILCombiner/SILCombine.cpp
+++ b/lib/SILOptimizer/SILCombiner/SILCombine.cpp
@@ -149,13 +149,16 @@
       DEBUG(llvm::dbgs() << "SC: Simplify Old = " << *I << '\n'
                          << "    New = " << *Result << '\n');
 
-      // Everything uses the new instruction now.
-      replaceInstUsesWith(*cast<SingleValueInstruction>(I), Result);
+      // Erase the simplified instruction and any instructions that end its
+      // scope. Nothing needs to be added to the worklist except for Result,
+      // because the instruction and all non-replaced users will be deleted.
+      replaceAllSimplifiedUsesAndErase(
+          I, Result,
+          [this](SILInstruction *Deleted) { Worklist.remove(Deleted); });
 
       // Push the new instruction and any users onto the worklist.
       Worklist.addUsersToWorklist(Result);
 
-      eraseInstFromFunction(*I);
       MadeChange = true;
       continue;
     }
diff --git a/lib/SILOptimizer/Transforms/CSE.cpp b/lib/SILOptimizer/Transforms/CSE.cpp
index 57ddbdb..4f7c206 100644
--- a/lib/SILOptimizer/Transforms/CSE.cpp
+++ b/lib/SILOptimizer/Transforms/CSE.cpp
@@ -782,17 +782,19 @@
   bool Changed = false;
 
   // See if any instructions in the block can be eliminated.  If so, do it.  If
-  // not, add them to AvailableValues.
-  for (SILBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
-    SILInstruction *Inst = &*I;
-    ++I;
+  // not, add them to AvailableValues. Assume the block terminator can't be
+  // erased.
+  for (SILBasicBlock::iterator nextI = BB->begin(), E = BB->end();
+       nextI != E;) {
+    SILInstruction *Inst = &*nextI;
+    ++nextI;
 
     DEBUG(llvm::dbgs() << "SILCSE VISITING: " << *Inst << "\n");
 
     // Dead instructions should just be removed.
     if (isInstructionTriviallyDead(Inst)) {
       DEBUG(llvm::dbgs() << "SILCSE DCE: " << *Inst << '\n');
-      eraseFromParentWithDebugInsts(Inst, I);
+      eraseFromParentWithDebugInsts(Inst, nextI);
       Changed = true;
       ++NumSimplify;
       continue;
@@ -803,8 +805,11 @@
     if (SILValue V = simplifyInstruction(Inst)) {
       DEBUG(llvm::dbgs() << "SILCSE SIMPLIFY: " << *Inst << "  to: " << *V
             << '\n');
-      cast<SingleValueInstruction>(Inst)->replaceAllUsesWith(V);
-      Inst->eraseFromParent();
+      replaceAllSimplifiedUsesAndErase(Inst, V,
+                                       [&nextI](SILInstruction *deleteI) {
+                                         if (nextI == deleteI->getIterator())
+                                           ++nextI;
+                                       });
       Changed = true;
       ++NumSimplify;
       continue;
@@ -828,10 +833,10 @@
       // Instructions producing a new opened archetype need a special handling,
       // because replacing these instructions may require a replacement
       // of the opened archetype type operands in some of the uses.
-      if (!isa<OpenExistentialRefInst>(Inst) ||
-          processOpenExistentialRef(cast<OpenExistentialRefInst>(Inst),
-                                    cast<OpenExistentialRefInst>(AvailInst),
-                                    I)) {
+      if (!isa<OpenExistentialRefInst>(Inst)
+          || processOpenExistentialRef(cast<OpenExistentialRefInst>(Inst),
+                                       cast<OpenExistentialRefInst>(AvailInst),
+                                       nextI)) {
         Inst->replaceAllUsesPairwiseWith(AvailInst);
         Inst->eraseFromParent();
         Changed = true;
diff --git a/lib/SILOptimizer/Transforms/SimplifyCFG.cpp b/lib/SILOptimizer/Transforms/SimplifyCFG.cpp
index 347fcef..6cf28ed 100644
--- a/lib/SILOptimizer/Transforms/SimplifyCFG.cpp
+++ b/lib/SILOptimizer/Transforms/SimplifyCFG.cpp
@@ -1115,11 +1115,8 @@
       // unreachable block. In this case it can reference itself as operand.
       if (Result && Result != I) {
         DEBUG(llvm::dbgs() << "simplify branch operand " << *I);
-        I->replaceAllUsesWith(Result);
-        if (isInstructionTriviallyDead(I)) {
-          eraseFromParentWithDebugInsts(I);
-          Simplified = true;
-        }
+        replaceAllSimplifiedUsesAndErase(I, Result);
+        Simplified = true;
       }
     }
   }
diff --git a/lib/SILOptimizer/Utils/Local.cpp b/lib/SILOptimizer/Utils/Local.cpp
index a3523b1..f08984d 100644
--- a/lib/SILOptimizer/Utils/Local.cpp
+++ b/lib/SILOptimizer/Utils/Local.cpp
@@ -1320,8 +1320,7 @@
     if (!S)
       continue;
 
-    SVI->replaceAllUsesWith(S);
-    SVI->eraseFromParent();
+    replaceAllSimplifiedUsesAndErase(SVI, S);
     Changed = true;
   }
 
diff --git a/lib/Sema/CSBindings.cpp b/lib/Sema/CSBindings.cpp
index 2248a6c..e83be40 100644
--- a/lib/Sema/CSBindings.cpp
+++ b/lib/Sema/CSBindings.cpp
@@ -197,6 +197,135 @@
   Bindings.push_back(std::move(binding));
 }
 
+Optional<ConstraintSystem::PotentialBinding>
+ConstraintSystem::getPotentialBindingForRelationalConstraint(
+    PotentialBindings &result, Constraint *constraint,
+    bool &hasDependentMemberRelationalConstraints,
+    bool &hasNonDependentMemberRelationalConstraints,
+    bool &addOptionalSupertypeBindings) {
+  assert(constraint->getClassification() ==
+             ConstraintClassification::Relational &&
+         "only relational constraints handled here");
+
+  auto *typeVar = result.TypeVar;
+
+  // Record constraint which contributes to the
+  // finding of potential bindings.
+  result.Sources.insert(constraint);
+
+  auto first = simplifyType(constraint->getFirstType());
+  auto second = simplifyType(constraint->getSecondType());
+
+  if (first->is<TypeVariableType>() && first->isEqual(second))
+    return None;
+
+  Type type;
+  AllowedBindingKind kind;
+  if (first->getAs<TypeVariableType>() == typeVar) {
+    // Upper bound for this type variable.
+    type = second;
+    kind = AllowedBindingKind::Subtypes;
+  } else if (second->getAs<TypeVariableType>() == typeVar) {
+    // Lower bound for this type variable.
+    type = first;
+    kind = AllowedBindingKind::Supertypes;
+  } else {
+    // Can't infer anything.
+    if (result.InvolvesTypeVariables)
+      return None;
+
+    // Check whether both this type and another type variable are
+    // inferable.
+    SmallPtrSet<TypeVariableType *, 4> typeVars;
+    findInferableTypeVars(first, typeVars);
+    findInferableTypeVars(second, typeVars);
+    if (typeVars.size() > 1 && typeVars.count(typeVar))
+      result.InvolvesTypeVariables = true;
+    return None;
+  }
+
+  // Do not attempt to bind to ErrorType.
+  if (type->hasError())
+    return None;
+
+  // If the source of the binding is 'OptionalObject' constraint
+  // and type variable is on the left-hand side, that means
+  // that it _has_ to be of optional type, since the right-hand
+  // side of the constraint is object type of the optional.
+  if (constraint->getKind() == ConstraintKind::OptionalObject &&
+      kind == AllowedBindingKind::Subtypes) {
+    type = OptionalType::get(type);
+  }
+
+  // If the type we'd be binding to is a dependent member, don't try to
+  // resolve this type variable yet.
+  if (type->is<DependentMemberType>()) {
+    if (!ConstraintSystem::typeVarOccursInType(typeVar, type,
+                                               &result.InvolvesTypeVariables)) {
+      hasDependentMemberRelationalConstraints = true;
+    }
+    return None;
+  }
+  hasNonDependentMemberRelationalConstraints = true;
+
+  // Check whether we can perform this binding.
+  // FIXME: this has a super-inefficient extraneous simplifyType() in it.
+  bool isNilLiteral = false;
+  bool *isNilLiteralPtr = nullptr;
+  if (!addOptionalSupertypeBindings && kind == AllowedBindingKind::Supertypes)
+    isNilLiteralPtr = &isNilLiteral;
+  if (auto boundType = checkTypeOfBinding(typeVar, type, isNilLiteralPtr)) {
+    type = *boundType;
+    if (type->hasTypeVariable())
+      result.InvolvesTypeVariables = true;
+  } else {
+    // If the bound is a 'nil' literal type, add optional supertype bindings.
+    if (isNilLiteral) {
+      addOptionalSupertypeBindings = true;
+      return None;
+    }
+
+    result.InvolvesTypeVariables = true;
+    return None;
+  }
+
+  // Don't deduce autoclosure types or single-element, non-variadic
+  // tuples.
+  if (shouldBindToValueType(constraint)) {
+    if (auto funcTy = type->getAs<FunctionType>()) {
+      if (funcTy->isAutoClosure())
+        type = funcTy->getResult();
+    }
+
+    type = type->getWithoutImmediateLabel();
+  }
+
+  // Make sure we aren't trying to equate type variables with different
+  // lvalue-binding rules.
+  if (auto otherTypeVar =
+          type->lookThroughAllOptionalTypes()->getAs<TypeVariableType>()) {
+    if (typeVar->getImpl().canBindToLValue() !=
+        otherTypeVar->getImpl().canBindToLValue())
+      return None;
+  }
+
+  // BindParam constraints are not reflexive and must be treated specially.
+  if (constraint->getKind() == ConstraintKind::BindParam) {
+    if (kind == AllowedBindingKind::Subtypes) {
+      if (auto *lvt = type->getAs<LValueType>()) {
+        type = InOutType::get(lvt->getObjectType());
+      }
+    } else if (kind == AllowedBindingKind::Supertypes) {
+      if (auto *iot = type->getAs<InOutType>()) {
+        type = LValueType::get(iot->getObjectType());
+      }
+    }
+    kind = AllowedBindingKind::Exact;
+  }
+
+  return PotentialBinding{type, kind, constraint->getKind()};
+}
+
 /// \brief Retrieve the set of potential type bindings for the given
 /// representative type variable, along with flags indicating whether
 /// those types should be opened.
@@ -238,9 +367,39 @@
     case ConstraintKind::ArgumentTupleConversion:
     case ConstraintKind::OperatorArgumentTupleConversion:
     case ConstraintKind::OperatorArgumentConversion:
-    case ConstraintKind::OptionalObject:
-      // Relational constraints: break out to look for types above/below.
+    case ConstraintKind::OptionalObject: {
+      auto binding = getPotentialBindingForRelationalConstraint(
+          result, constraint, hasDependentMemberRelationalConstraints,
+          hasNonDependentMemberRelationalConstraints,
+          addOptionalSupertypeBindings);
+      if (!binding)
+        break;
+
+      auto type = binding->BindingType;
+      if (exactTypes.insert(type->getCanonicalType()).second) {
+        result.addPotentialBinding(*binding);
+
+        if (auto *locator = typeVar->getImpl().getLocator()) {
+          auto path = locator->getPath();
+          auto voidType = TupleType::getEmpty(getASTContext());
+
+          // If this is a type variable representing closure result,
+          // which is on the right-side of some relational constraint
+          // let's have it try `Void` as well because there is an
+          // implicit conversion `() -> T` to `() -> Void` and this
+          // helps to avoid creating a thunk to support it.
+          if (!path.empty() &&
+              path.back().getKind() == ConstraintLocator::ClosureResult &&
+              binding->Kind == AllowedBindingKind::Supertypes &&
+              exactTypes.insert(voidType->getCanonicalType()).second) {
+            result.addPotentialBinding(
+                {voidType, binding->Kind, constraint->getKind()},
+                /*allowJoinMeet=*/false);
+          }
+        }
+      }
       break;
+    }
 
     case ConstraintKind::BridgingConversion:
     case ConstraintKind::CheckedCast:
@@ -249,7 +408,7 @@
     case ConstraintKind::KeyPath:
     case ConstraintKind::KeyPathApplication:
       // Constraints from which we can't do anything.
-      continue;
+      break;
 
     case ConstraintKind::DynamicTypeOf: {
       // Direct binding of the left-hand side could result
@@ -264,7 +423,7 @@
       }
 
       // This is right-hand side, let's continue.
-      continue;
+      break;
     }
 
     case ConstraintKind::Defaultable:
@@ -274,13 +433,13 @@
         defaultableConstraints.push_back(constraint);
         hasNonDependentMemberRelationalConstraints = true;
       }
-      continue;
+      break;
 
     case ConstraintKind::Disjunction:
       // FIXME: Recurse into these constraints to see whether this
       // type variable is fully bound by any of them.
       result.InvolvesTypeVariables = true;
-      continue;
+      break;
 
     case ConstraintKind::ConformsTo:
     case ConstraintKind::SelfObjectOfProtocol:
@@ -350,7 +509,7 @@
                                     constraint->getProtocol()});
       }
 
-      continue;
+      break;
     }
 
     case ConstraintKind::ApplicableFunction:
@@ -373,7 +532,8 @@
                             typeVars);
       if (typeVars.size() > 1 && typeVars.count(typeVar))
         result.InvolvesTypeVariables = true;
-      continue;
+
+      break;
     }
 
     case ConstraintKind::ValueMember:
@@ -395,130 +555,8 @@
               &result.InvolvesTypeVariables)) {
         result.FullyBound = true;
       }
-      continue;
+      break;
     }
-
-    // Handle relational constraints.
-    assert(constraint->getClassification() ==
-               ConstraintClassification::Relational &&
-           "only relational constraints handled here");
-
-    // Record constraint which contributes to the
-    // finding of pontential bindings.
-    result.Sources.insert(constraint);
-
-    auto first = simplifyType(constraint->getFirstType());
-    auto second = simplifyType(constraint->getSecondType());
-
-    if (first->is<TypeVariableType>() && first->isEqual(second))
-      continue;
-
-    Type type;
-    AllowedBindingKind kind;
-    if (first->getAs<TypeVariableType>() == typeVar) {
-      // Upper bound for this type variable.
-      type = second;
-      kind = AllowedBindingKind::Subtypes;
-    } else if (second->getAs<TypeVariableType>() == typeVar) {
-      // Lower bound for this type variable.
-      type = first;
-      kind = AllowedBindingKind::Supertypes;
-    } else {
-      // Can't infer anything.
-      if (result.InvolvesTypeVariables)
-        continue;
-
-      // Check whether both this type and another type variable are
-      // inferable.
-      SmallPtrSet<TypeVariableType *, 4> typeVars;
-      findInferableTypeVars(first, typeVars);
-      findInferableTypeVars(second, typeVars);
-      if (typeVars.size() > 1 && typeVars.count(typeVar))
-        result.InvolvesTypeVariables = true;
-      continue;
-    }
-    
-    // Do not attempt to bind to ErrorType.
-    if (type->hasError())
-      continue;
-
-    // If the source of the binding is 'OptionalObject' constraint
-    // and type variable is on the left-hand side, that means
-    // that it _has_ to be of optional type, since the right-hand
-    // side of the constraint is object type of the optional.
-    if (constraint->getKind() == ConstraintKind::OptionalObject &&
-        kind == AllowedBindingKind::Subtypes) {
-      type = OptionalType::get(type);
-    }
-
-    // If the type we'd be binding to is a dependent member, don't try to
-    // resolve this type variable yet.
-    if (type->is<DependentMemberType>()) {
-      if (!ConstraintSystem::typeVarOccursInType(
-              typeVar, type, &result.InvolvesTypeVariables)) {
-        hasDependentMemberRelationalConstraints = true;
-      }
-      continue;
-    }
-    hasNonDependentMemberRelationalConstraints = true;
-
-    // Check whether we can perform this binding.
-    // FIXME: this has a super-inefficient extraneous simplifyType() in it.
-    bool isNilLiteral = false;
-    bool *isNilLiteralPtr = nullptr;
-    if (!addOptionalSupertypeBindings && kind == AllowedBindingKind::Supertypes)
-      isNilLiteralPtr = &isNilLiteral;
-    if (auto boundType = checkTypeOfBinding(typeVar, type, isNilLiteralPtr)) {
-      type = *boundType;
-      if (type->hasTypeVariable())
-        result.InvolvesTypeVariables = true;
-    } else {
-      // If the bound is a 'nil' literal type, add optional supertype bindings.
-      if (isNilLiteral) {
-        addOptionalSupertypeBindings = true;
-        continue;
-      }
-
-      result.InvolvesTypeVariables = true;
-      continue;
-    }
-
-    // Don't deduce autoclosure types or single-element, non-variadic
-    // tuples.
-    if (shouldBindToValueType(constraint)) {
-      if (auto funcTy = type->getAs<FunctionType>()) {
-        if (funcTy->isAutoClosure())
-          type = funcTy->getResult();
-      }
-
-      type = type->getWithoutImmediateLabel();
-    }
-
-    // Make sure we aren't trying to equate type variables with different
-    // lvalue-binding rules.
-    if (auto otherTypeVar =
-            type->lookThroughAllOptionalTypes()->getAs<TypeVariableType>()) {
-      if (typeVar->getImpl().canBindToLValue() !=
-          otherTypeVar->getImpl().canBindToLValue())
-        continue;
-    }
-
-    // BindParam constraints are not reflexive and must be treated specially.
-    if (constraint->getKind() == ConstraintKind::BindParam) {
-      if (kind == AllowedBindingKind::Subtypes) {
-        if (auto *lvt = type->getAs<LValueType>()) {
-          type = InOutType::get(lvt->getObjectType());
-        }
-      } else if (kind == AllowedBindingKind::Supertypes) {
-        if (auto *iot = type->getAs<InOutType>()) {
-          type = LValueType::get(iot->getObjectType());
-        }
-      }
-      kind = AllowedBindingKind::Exact;
-    }
-
-    if (exactTypes.insert(type->getCanonicalType()).second)
-      result.addPotentialBinding({type, kind, constraint->getKind()});
   }
 
   // If we have any literal constraints, check whether there is already a
diff --git a/lib/Sema/ConstraintSystem.h b/lib/Sema/ConstraintSystem.h
index f757103..27db3d8 100644
--- a/lib/Sema/ConstraintSystem.h
+++ b/lib/Sema/ConstraintSystem.h
@@ -2666,7 +2666,7 @@
 
 private:
   /// The kind of bindings that are permitted.
-  enum class AllowedBindingKind : unsigned char {
+  enum class AllowedBindingKind : uint8_t {
     /// Only the exact type.
     Exact,
     /// Supertypes of the specified type.
@@ -2676,7 +2676,7 @@
   };
 
   /// The kind of literal binding found.
-  enum class LiteralBindingKind : unsigned char {
+  enum class LiteralBindingKind : uint8_t {
     None,
     Collection,
     Float,
@@ -2866,6 +2866,12 @@
   Optional<Type> checkTypeOfBinding(TypeVariableType *typeVar, Type type,
                                     bool *isNilLiteral = nullptr);
   Optional<PotentialBindings> determineBestBindings();
+  Optional<ConstraintSystem::PotentialBinding>
+  getPotentialBindingForRelationalConstraint(
+      PotentialBindings &result, Constraint *constraint,
+      bool &hasDependentMemberRelationalConstraints,
+      bool &hasNonDependentMemberRelationalConstraints,
+      bool &addOptionalSupertypeBindings);
   PotentialBindings getPotentialBindings(TypeVariableType *typeVar);
 
   bool
diff --git a/lib/Sema/TypeCheckProtocol.h b/lib/Sema/TypeCheckProtocol.h
index d4cf20d..e1a41e6 100644
--- a/lib/Sema/TypeCheckProtocol.h
+++ b/lib/Sema/TypeCheckProtocol.h
@@ -148,7 +148,7 @@
 
 /// \brief The result of matching a particular declaration to a given
 /// requirement.
-enum class MatchKind : unsigned char {
+enum class MatchKind : uint8_t {
   /// \brief The witness matched the requirement exactly.
   ExactMatch,
 
diff --git a/lib/Serialization/Serialization.cpp b/lib/Serialization/Serialization.cpp
index 7833007..e6b40b8 100644
--- a/lib/Serialization/Serialization.cpp
+++ b/lib/Serialization/Serialization.cpp
@@ -4347,7 +4347,7 @@
     if (!MapNode) {
       return true;
     }
-    for (auto Pair : *MapNode) {
+    for (auto &Pair : *MapNode) {
       auto *Key = dyn_cast_or_null<llvm::yaml::ScalarNode>(Pair.getKey());
       auto *Value = dyn_cast_or_null<llvm::yaml::SequenceNode>(Pair.getValue());
 
diff --git a/lib/Syntax/Trivia.cpp.gyb b/lib/Syntax/Trivia.cpp.gyb
index 44b2c94..c626214 100644
--- a/lib/Syntax/Trivia.cpp.gyb
+++ b/lib/Syntax/Trivia.cpp.gyb
@@ -44,6 +44,19 @@
   OS << ')';
 }
 
+bool TriviaPiece::isComment() const {
+  switch (Kind) {
+% for trivia in TRIVIAS:
+  case TriviaKind::${trivia.name}:
+% if trivia.is_comment:
+    return true;
+% else:
+    return false;
+% end
+% end
+  }
+}
+
 void TriviaPiece::accumulateAbsolutePosition(AbsolutePosition &Pos) const {
   switch (Kind) {
 % for trivia in TRIVIAS:
diff --git a/stdlib/public/Platform/Platform.swift b/stdlib/public/Platform/Platform.swift
index a71d299..05b6ee4 100644
--- a/stdlib/public/Platform/Platform.swift
+++ b/stdlib/public/Platform/Platform.swift
@@ -57,9 +57,10 @@
   }
 }
 
-extension DarwinBoolean : Equatable {}
-public func ==(lhs: DarwinBoolean, rhs: DarwinBoolean) -> Bool {
-  return lhs.boolValue == rhs.boolValue
+extension DarwinBoolean : Equatable {
+  public static func ==(lhs: DarwinBoolean, rhs: DarwinBoolean) -> Bool {
+    return lhs.boolValue == rhs.boolValue
+  }
 }
 
 public // COMPILER_INTRINSIC
diff --git a/stdlib/public/SDK/CoreMedia/CMTime.swift b/stdlib/public/SDK/CoreMedia/CMTime.swift
index a37a8ba..ecfb1cf 100644
--- a/stdlib/public/SDK/CoreMedia/CMTime.swift
+++ b/stdlib/public/SDK/CoreMedia/CMTime.swift
@@ -99,34 +99,36 @@
   return time.hasBeenRounded
 }
 
-// CMTimeAdd
-public func + (addend1: CMTime, addend2: CMTime) -> CMTime {
-  return CMTimeAdd(addend1, addend2)
+extension CMTime {
+  // CMTimeAdd
+  public static func + (addend1: CMTime, addend2: CMTime) -> CMTime {
+    return CMTimeAdd(addend1, addend2)
+  }
+  
+  // CMTimeSubtract
+  public static func - (minuend: CMTime, subtrahend: CMTime) -> CMTime {
+    return CMTimeSubtract(minuend, subtrahend)
+  }
 }
 
-// CMTimeSubtract
-public func - (minuend: CMTime, subtrahend: CMTime) -> CMTime {
-  return CMTimeSubtract(minuend, subtrahend)
-}
-
-extension CMTime : Equatable, Comparable {}
-
 // CMTimeCompare
-public func < (time1: CMTime, time2: CMTime) -> Bool {
-  return CMTimeCompare(time1, time2) < 0
-}
-public func <= (time1: CMTime, time2: CMTime) -> Bool {
-  return CMTimeCompare(time1, time2) <= 0
-}
-public func > (time1: CMTime, time2: CMTime) -> Bool {
-  return CMTimeCompare(time1, time2) > 0
-}
-public func >= (time1: CMTime, time2: CMTime) -> Bool {
-  return CMTimeCompare(time1, time2) >= 0
-}
-public func == (time1: CMTime, time2: CMTime) -> Bool {
-  return CMTimeCompare(time1, time2) == 0
-}
-public func != (time1: CMTime, time2: CMTime) -> Bool {
-  return CMTimeCompare(time1, time2) != 0
+extension CMTime : Equatable, Comparable {
+  public static func < (time1: CMTime, time2: CMTime) -> Bool {
+    return CMTimeCompare(time1, time2) < 0
+  }
+  public static func <= (time1: CMTime, time2: CMTime) -> Bool {
+    return CMTimeCompare(time1, time2) <= 0
+  }
+  public static func > (time1: CMTime, time2: CMTime) -> Bool {
+    return CMTimeCompare(time1, time2) > 0
+  }
+  public static func >= (time1: CMTime, time2: CMTime) -> Bool {
+    return CMTimeCompare(time1, time2) >= 0
+  }
+  public static func == (time1: CMTime, time2: CMTime) -> Bool {
+    return CMTimeCompare(time1, time2) == 0
+  }
+  public static func != (time1: CMTime, time2: CMTime) -> Bool {
+    return CMTimeCompare(time1, time2) != 0
+  }
 }
diff --git a/stdlib/public/SDK/CoreMedia/CMTimeRange.swift b/stdlib/public/SDK/CoreMedia/CMTimeRange.swift
index 6050e0e..c27974d 100644
--- a/stdlib/public/SDK/CoreMedia/CMTimeRange.swift
+++ b/stdlib/public/SDK/CoreMedia/CMTimeRange.swift
@@ -74,14 +74,13 @@
   return range.isEmpty
 }
 
-extension CMTimeRange : Equatable {}
-
 // CMTimeRangeEqual
-public func == (range1: CMTimeRange, range2: CMTimeRange) -> Bool {
-  return CMTimeRangeEqual(range1, range2)
+extension CMTimeRange : Equatable {
+  public static func == (range1: CMTimeRange, range2: CMTimeRange) -> Bool {
+    return CMTimeRangeEqual(range1, range2)
+  }
+  
+  public static func != (range1: CMTimeRange, range2: CMTimeRange) -> Bool {
+    return !CMTimeRangeEqual(range1, range2)
+  }  
 }
-
-public func != (range1: CMTimeRange, range2: CMTimeRange) -> Bool {
-  return !CMTimeRangeEqual(range1, range2)
-}
-
diff --git a/stdlib/public/SDK/Dispatch/Dispatch.swift b/stdlib/public/SDK/Dispatch/Dispatch.swift
index edeaafb..b507306 100644
--- a/stdlib/public/SDK/Dispatch/Dispatch.swift
+++ b/stdlib/public/SDK/Dispatch/Dispatch.swift
@@ -114,10 +114,10 @@
 		self.qosClass = qosClass
 		self.relativePriority = relativePriority
 	}
-}
 
-public func ==(a: DispatchQoS, b: DispatchQoS) -> Bool {
-	return a.qosClass == b.qosClass && a.relativePriority == b.relativePriority
+	public static func ==(a: DispatchQoS, b: DispatchQoS) -> Bool {
+		return a.qosClass == b.qosClass && a.relativePriority == b.relativePriority
+	}
 }
 
 /// 
diff --git a/stdlib/public/SDK/ObjectiveC/ObjectiveC.swift b/stdlib/public/SDK/ObjectiveC/ObjectiveC.swift
index dbf43f1..9639638 100644
--- a/stdlib/public/SDK/ObjectiveC/ObjectiveC.swift
+++ b/stdlib/public/SDK/ObjectiveC/ObjectiveC.swift
@@ -112,11 +112,11 @@
   }
 }
 
-public func ==(lhs: Selector, rhs: Selector) -> Bool {
-  return sel_isEqual(lhs, rhs)
-}
-
 extension Selector : Equatable, Hashable {
+  public static func ==(lhs: Selector, rhs: Selector) -> Bool {
+    return sel_isEqual(lhs, rhs)
+  }
+
   /// The hash value.
   ///
   /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
@@ -199,6 +199,10 @@
 // FIXME: what about NSObjectProtocol?
 
 extension NSObject : Equatable, Hashable {
+  public static func == (lhs: NSObject, rhs: NSObject) -> Bool {
+    return lhs.isEqual(rhs)
+  }
+
   /// The hash value.
   ///
   /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
@@ -212,10 +216,6 @@
   }
 }
 
-public func == (lhs: NSObject, rhs: NSObject) -> Bool {
-  return lhs.isEqual(rhs)
-}
-
 extension NSObject : CVarArg {
   /// Transform `self` into a series of machine words that can be
   /// appropriately interpreted by C varargs
diff --git a/stdlib/public/SDK/UIKit/UIKit.swift b/stdlib/public/SDK/UIKit/UIKit.swift
index abf0015..531631a 100644
--- a/stdlib/public/SDK/UIKit/UIKit.swift
+++ b/stdlib/public/SDK/UIKit/UIKit.swift
@@ -39,24 +39,24 @@
 // Equatable types.
 //===----------------------------------------------------------------------===//
 
-@_transparent // @fragile
-public func == (lhs: UIEdgeInsets, rhs: UIEdgeInsets) -> Bool {
-  return lhs.top == rhs.top &&
-         lhs.left == rhs.left &&
-         lhs.bottom == rhs.bottom &&
-         lhs.right == rhs.right
+extension UIEdgeInsets : Equatable {
+  @_transparent // @fragile
+  public static func == (lhs: UIEdgeInsets, rhs: UIEdgeInsets) -> Bool {
+    return lhs.top == rhs.top &&
+           lhs.left == rhs.left &&
+           lhs.bottom == rhs.bottom &&
+           lhs.right == rhs.right
+  }
 }
 
-extension UIEdgeInsets : Equatable {}
-
-@_transparent // @fragile
-public func == (lhs: UIOffset, rhs: UIOffset) -> Bool {
-  return lhs.horizontal == rhs.horizontal &&
-         lhs.vertical == rhs.vertical
+extension UIOffset : Equatable {
+  @_transparent // @fragile
+  public static func == (lhs: UIOffset, rhs: UIOffset) -> Bool {
+    return lhs.horizontal == rhs.horizontal &&
+           lhs.vertical == rhs.vertical
+  }
 }
 
-extension UIOffset : Equatable {}
-
 //===----------------------------------------------------------------------===//
 // Numeric backed types
 //===----------------------------------------------------------------------===//
diff --git a/stdlib/public/SwiftOnoneSupport/SwiftOnoneSupport.swift b/stdlib/public/SwiftOnoneSupport/SwiftOnoneSupport.swift
index ce1b1ff..8966c21 100644
--- a/stdlib/public/SwiftOnoneSupport/SwiftOnoneSupport.swift
+++ b/stdlib/public/SwiftOnoneSupport/SwiftOnoneSupport.swift
@@ -25,7 +25,7 @@
       var a = [Element](repeating: sampleValue, count: 1)
 
       // Read array element
-      let _ =  a[0]
+      _ = a[0]
 
       // Set array elements
       for j in 1..<a.count {
@@ -42,7 +42,7 @@
       a[0] = sampleValue
 
       // Get count and capacity
-      let _ = a.count + a.capacity
+      _ = a.count + a.capacity
 
       // Iterate over array
       for e in a {
@@ -63,7 +63,7 @@
       a.reserveCapacity(100)
 
       // Sort array
-      let _ = a.sorted { (a: Element, b: Element) in a < b }
+      _ = a.sorted { (a: Element, b: Element) in a < b }
       a.sort { (a: Element, b: Element) in a < b }
 
       // force specialization of append.
@@ -80,7 +80,7 @@
       var a = [Element](repeating: sampleValue, count: 1)
 
       // Read array element
-      let _ =  a[0]
+      _ = a[0]
 
       // Set array elements
       for j in 0..<a.count {
@@ -96,7 +96,7 @@
       a[0] = sampleValue
 
       // Get length and capacity
-      let _ = a.count + a.capacity
+      _ = a.count + a.capacity
 
       // Iterate over array
       for e in a {
diff --git a/stdlib/public/core/ClosedRange.swift b/stdlib/public/core/ClosedRange.swift
index d721765..33255b9 100644
--- a/stdlib/public/core/ClosedRange.swift
+++ b/stdlib/public/core/ClosedRange.swift
@@ -127,6 +127,7 @@
 }
 
 extension ClosedRange where Bound : Strideable, Bound.Stride : SignedInteger {
+  @_fixed_layout
   public enum Index {
     case pastEnd
     case inRange(Bound)
@@ -382,7 +383,7 @@
 
 extension ClosedRange : CustomStringConvertible {
   /// A textual representation of the range.
-  @_inlineable // FIXME(sil-serialize-all)...\(
+  @_inlineable // FIXME(sil-serialize-all)...
   public var description: String {
     return "\(lowerBound)...\(upperBound)"
   }
diff --git a/stdlib/public/core/Optional.swift b/stdlib/public/core/Optional.swift
index 459b249..26e3dbf 100644
--- a/stdlib/public/core/Optional.swift
+++ b/stdlib/public/core/Optional.swift
@@ -453,7 +453,7 @@
   ///   - rhs: A value to match against `nil`.
   @_inlineable // FIXME(sil-serialize-all)
   @_transparent
-  static public func ~=(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
+  public static func ~=(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
     switch rhs {
     case .some(_):
       return false
@@ -488,7 +488,7 @@
   ///   - rhs: A `nil` literal.
   @_inlineable // FIXME(sil-serialize-all)
   @_transparent
-  static public func ==(lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool {
+  public static func ==(lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool {
     switch lhs {
     case .some(_):
       return false
@@ -520,7 +520,7 @@
   ///   - rhs: A `nil` literal.
   @_inlineable // FIXME(sil-serialize-all)
   @_transparent
-  static public func !=(lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool {
+  public static func !=(lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool {
     switch lhs {
     case .some(_):
       return true
@@ -552,7 +552,7 @@
   ///   - rhs: A value to compare to `nil`.
   @_inlineable // FIXME(sil-serialize-all)
   @_transparent
-  static public func ==(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
+  public static func ==(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
     switch rhs {
     case .some(_):
       return false
@@ -584,7 +584,7 @@
   ///   - rhs: A value to compare to `nil`.
   @_inlineable // FIXME(sil-serialize-all)
   @_transparent
-  static public func !=(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
+  public static func !=(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
     switch rhs {
     case .some(_):
       return true
diff --git a/stdlib/public/core/RuntimeFunctionCounters.swift b/stdlib/public/core/RuntimeFunctionCounters.swift
index 18d99db..0efb2a682 100644
--- a/stdlib/public/core/RuntimeFunctionCounters.swift
+++ b/stdlib/public/core/RuntimeFunctionCounters.swift
@@ -115,10 +115,10 @@
   /// Get the names of all runtime functions whose calls are being
   /// tracked.
   @_silgen_name("_swift_getRuntimeFunctionNames")
-  static public func _getRuntimeFunctionNames() ->
+  public static func _getRuntimeFunctionNames() ->
     UnsafePointer<UnsafePointer<CChar>>
 
-  static public func getRuntimeFunctionNames() -> [String] {
+  public static func getRuntimeFunctionNames() -> [String] {
     let names = _RuntimeFunctionCounters._getRuntimeFunctionNames()
     let numRuntimeFunctionCounters =
       _RuntimeFunctionCounters.getNumRuntimeFunctionCounters()
@@ -134,26 +134,26 @@
   /// Get the offsets of the collected runtime function counters inside
   /// the state.
   @_silgen_name("_swift_getRuntimeFunctionCountersOffsets")
-  static public func getRuntimeFunctionCountersOffsets() ->
+  public static func getRuntimeFunctionCountersOffsets() ->
     UnsafePointer<UInt16>
 
   /// Get the number of different runtime functions whose calls are being
   /// tracked.
   @_silgen_name("_swift_getNumRuntimeFunctionCounters")
-  static public func getNumRuntimeFunctionCounters() -> Int
+  public static func getNumRuntimeFunctionCounters() -> Int
 
   /// Dump all per-object runtime function counters.
   @_silgen_name("_swift_dumpObjectsRuntimeFunctionPointers")
-  static public func dumpObjectsRuntimeFunctionPointers()
+  public static func dumpObjectsRuntimeFunctionPointers()
 
   @discardableResult
   @_silgen_name("_swift_setGlobalRuntimeFunctionCountersUpdateHandler")
-  static public func setGlobalRuntimeFunctionCountersUpdateHandler(
+  public static func setGlobalRuntimeFunctionCountersUpdateHandler(
     handler: RuntimeFunctionCountersUpdateHandler?
   ) -> RuntimeFunctionCountersUpdateHandler?
 
   /// Collect all references inside the object using Mirrors.
-  static public func collectAllReferencesInsideObject(_ value: Any) ->
+  public static func collectAllReferencesInsideObject(_ value: Any) ->
     [UnsafeRawPointer] {
     var visited : [ObjectIdentifier : Int] = [:]
     var references: [UnsafeRawPointer] = []
diff --git a/stdlib/public/core/String.swift b/stdlib/public/core/String.swift
index 0024ada..1517582 100644
--- a/stdlib/public/core/String.swift
+++ b/stdlib/public/core/String.swift
@@ -36,10 +36,8 @@
   var utf16: UTF16View { get }
   var unicodeScalars: UnicodeScalarView { get }
 
-#if _runtime(_ObjC)
   func hasPrefix(_ prefix: String) -> Bool
   func hasSuffix(_ prefix: String) -> Bool
-#endif
 
   func lowercased() -> String
   func uppercased() -> String
diff --git a/stdlib/public/core/StringLegacy.swift b/stdlib/public/core/StringLegacy.swift
index bab461c..2227903 100644
--- a/stdlib/public/core/StringLegacy.swift
+++ b/stdlib/public/core/StringLegacy.swift
@@ -84,35 +84,36 @@
   }
 }
 
-#if _runtime(_ObjC)
-/// Determines if `theString` starts with `prefix` comparing the strings under
-/// canonical equivalence.
-@_inlineable // FIXME(sil-serialize-all)
-@_versioned // FIXME(sil-serialize-all)
-@_silgen_name("swift_stdlib_NSStringHasPrefixNFD")
-internal func _stdlib_NSStringHasPrefixNFD(
-  _ theString: AnyObject, _ prefix: AnyObject) -> Bool
 
-@_inlineable // FIXME(sil-serialize-all)
-@_versioned // FIXME(sil-serialize-all)
-@_silgen_name("swift_stdlib_NSStringHasPrefixNFDPointer")
-internal func _stdlib_NSStringHasPrefixNFDPointer(
-  _ theString: OpaquePointer, _ prefix: OpaquePointer) -> Bool
+// TODO: since this is generally useful, make public via evolution proposal.
+extension BidirectionalCollection {
+  @_inlineable
+  @_versioned
+  internal func _ends<Suffix: BidirectionalCollection>(
+    with suffix: Suffix, by areEquivalent: (Element,Element) -> Bool
+  ) -> Bool where Suffix.Element == Element {
+    var (i,j) = (self.endIndex,suffix.endIndex)
+    while i != self.startIndex, j != suffix.startIndex {
+      self.formIndex(before: &i)
+      suffix.formIndex(before: &j)
+      if !areEquivalent(self[i],suffix[j]) { return false }
+    } 
+    return j == suffix.startIndex
+  }
+}
 
-/// Determines if `theString` ends with `suffix` comparing the strings under
-/// canonical equivalence.
-@_inlineable // FIXME(sil-serialize-all)
-@_versioned // FIXME(sil-serialize-all)
-@_silgen_name("swift_stdlib_NSStringHasSuffixNFD")
-internal func _stdlib_NSStringHasSuffixNFD(
-  _ theString: AnyObject, _ suffix: AnyObject) -> Bool
-@_inlineable // FIXME(sil-serialize-all)
-@_versioned // FIXME(sil-serialize-all)
-@_silgen_name("swift_stdlib_NSStringHasSuffixNFDPointer")
-internal func _stdlib_NSStringHasSuffixNFDPointer(
-  _ theString: OpaquePointer, _ suffix: OpaquePointer) -> Bool
+extension BidirectionalCollection where Element: Equatable {
+  @_inlineable
+  @_versioned
+  internal func _ends<Suffix: BidirectionalCollection>(
+    with suffix: Suffix
+  ) -> Bool where Suffix.Element == Element {
+      return _ends(with: suffix, by: ==)
+  }
+}
 
-extension String {
+
+extension StringProtocol {
   /// Returns a Boolean value indicating whether the string begins with the
   /// specified prefix.
   ///
@@ -142,40 +143,9 @@
   ///
   /// - Parameter prefix: A possible prefix to test against this string.
   /// - Returns: `true` if the string begins with `prefix`; otherwise, `false`.
-  @_inlineable // FIXME(sil-serialize-all)
-  public func hasPrefix(_ prefix: String) -> Bool {
-    let prefixCount = prefix._guts.count
-    if prefixCount == 0 {
-      return true
-    }
-    if _fastPath(!self._guts._isOpaque && !prefix._guts._isOpaque) {
-      let result: Bool
-      if self._guts.isASCII && prefix._guts.isASCII {
-        let selfASCII = self._guts._unmanagedASCIIView
-        let prefixASCII = prefix._guts._unmanagedASCIIView
-        if prefixASCII.count > selfASCII.count {
-          // Prefix is longer than self.
-          result = false
-        } else {
-          result = (0 as CInt) == _stdlib_memcmp(
-            selfASCII.rawStart,
-            prefixASCII.rawStart,
-            prefixASCII.count)
-        }
-      } else {
-        let lhsStr = _NSContiguousString(_unmanaged: self._guts)
-        let rhsStr = _NSContiguousString(_unmanaged: prefix._guts)
-        result = lhsStr._unsafeWithNotEscapedSelfPointerPair(rhsStr) {
-          return _stdlib_NSStringHasPrefixNFDPointer($0, $1)
-        }
-      }
-      _fixLifetime(self)
-      _fixLifetime(prefix)
-      return result
-    }
-    return _stdlib_NSStringHasPrefixNFD(
-      self._bridgeToObjectiveCImpl(),
-      prefix._bridgeToObjectiveCImpl())
+  @_inlineable
+  public func hasPrefix<Prefix: StringProtocol>(_ prefix: Prefix) -> Bool {
+    return self.starts(with: prefix)
   }
 
   /// Returns a Boolean value indicating whether the string ends with the
@@ -207,15 +177,52 @@
   ///
   /// - Parameter suffix: A possible suffix to test against this string.
   /// - Returns: `true` if the string ends with `suffix`; otherwise, `false`.
+  @_inlineable
+  public func hasSuffix<Suffix: StringProtocol>(_ suffix: Suffix) -> Bool {
+    return self._ends(with: suffix)
+  }
+}
+
+extension String {
+  @_inlineable // FIXME(sil-serialize-all)
+  public func hasPrefix(_ prefix: String) -> Bool {
+    let prefixCount = prefix._guts.count
+    if prefixCount == 0 { return true }
+
+    if _fastPath(!self._guts._isOpaque && !prefix._guts._isOpaque) {
+      if self._guts.isASCII && prefix._guts.isASCII {
+        let result: Bool
+        let selfASCII = self._guts._unmanagedASCIIView
+        let prefixASCII = prefix._guts._unmanagedASCIIView
+        if prefixASCII.count > selfASCII.count {
+          // Prefix is longer than self.
+          result = false
+        } else {
+          result = (0 as CInt) == _stdlib_memcmp(
+            selfASCII.rawStart,
+            prefixASCII.rawStart,
+            prefixASCII.count)
+        }
+        _fixLifetime(self)
+        _fixLifetime(prefix)
+        return result
+      }
+      else {
+        
+      }
+    }
+
+    return self.starts(with: prefix)
+  }
+
   @_inlineable // FIXME(sil-serialize-all)
   public func hasSuffix(_ suffix: String) -> Bool {
     let suffixCount = suffix._guts.count
-    if suffixCount == 0 {
-      return true
-    }
+    if suffixCount == 0 { return true }
+
     if _fastPath(!self._guts._isOpaque && !suffix._guts._isOpaque) {
-      let result: Bool
       if self._guts.isASCII && suffix._guts.isASCII {
+        let result: Bool
         let selfASCII = self._guts._unmanagedASCIIView
         let suffixASCII = suffix._guts._unmanagedASCIIView
         if suffixASCII.count > self._guts.count {
@@ -227,26 +234,15 @@
             suffixASCII.rawStart,
             suffixASCII.count)
         }
-      } else {
-        let lhsStr = _NSContiguousString(_unmanaged: self._guts)
-        let rhsStr = _NSContiguousString(_unmanaged: suffix._guts)
-        result = lhsStr._unsafeWithNotEscapedSelfPointerPair(rhsStr) {
-          return _stdlib_NSStringHasSuffixNFDPointer($0, $1)
-        }
+        _fixLifetime(self)
+        _fixLifetime(suffix)
+        return result
       }
-      _fixLifetime(self)
-      _fixLifetime(suffix)
-      return result
     }
-    return _stdlib_NSStringHasSuffixNFD(
-      self._bridgeToObjectiveCImpl(),
-      suffix._bridgeToObjectiveCImpl())
+
+    return self._ends(with: suffix)
   }
 }
-#else
-// FIXME: Implement hasPrefix and hasSuffix without objc
-// rdar://problem/18878343
-#endif
 
 // Conversions to string from other types.
 extension String {
diff --git a/stdlib/public/core/Substring.swift.gyb b/stdlib/public/core/Substring.swift.gyb
index 22e36a8..10b3eac 100644
--- a/stdlib/public/core/Substring.swift.gyb
+++ b/stdlib/public/core/Substring.swift.gyb
@@ -525,22 +525,6 @@
   }
 }
 
-#if _runtime(_ObjC)
-
-extension Substring {
-  @_inlineable // FIXME(sil-serialize-all)
-  public func hasPrefix(_ prefix: String) -> Bool {
-    return String(self).hasPrefix(prefix)
-  }
-
-  @_inlineable // FIXME(sil-serialize-all)
-  public func hasSuffix(_ suffix: String) -> Bool {
-    return String(self).hasSuffix(suffix)
-  }
-}
-
-#endif
-
 extension Substring : RangeReplaceableCollection {
   @_inlineable // FIXME(sil-serialize-all)
   public init<S : Sequence>(_ elements: S)
diff --git a/stdlib/public/core/UnsafePointer.swift.gyb b/stdlib/public/core/UnsafePointer.swift.gyb
index 4e314bd..a3d8eed 100644
--- a/stdlib/public/core/UnsafePointer.swift.gyb
+++ b/stdlib/public/core/UnsafePointer.swift.gyb
@@ -428,7 +428,7 @@
   /// - Parameter count: The amount of memory to allocate, counted in instances
   ///   of `Pointee`.
   @_inlineable
-  static public func allocate(capacity count: Int)
+  public static func allocate(capacity count: Int)
     -> UnsafeMutablePointer<Pointee> {
     let size = MemoryLayout<Pointee>.stride * count
     let rawPtr =
diff --git a/stdlib/public/runtime/Demangle.cpp b/stdlib/public/runtime/Demangle.cpp
index 760dd58..4a3f522 100644
--- a/stdlib/public/runtime/Demangle.cpp
+++ b/stdlib/public/runtime/Demangle.cpp
@@ -279,6 +279,11 @@
     description = structType->Description;
     break;
   }
+  case MetadataKind::ForeignClass: {
+    auto foreignType = static_cast<const ForeignClassMetadata *>(type);
+    description = foreignType->Description;
+    break;
+  }
   default:
     return nullptr;
   }
@@ -349,6 +354,7 @@
   case MetadataKind::Enum:
   case MetadataKind::Optional:
   case MetadataKind::Struct:
+  case MetadataKind::ForeignClass:
     return _buildDemanglingForNominalType(type, Dem);
   case MetadataKind::ObjCClassWrapper: {
 #if SWIFT_OBJC_INTEROP
@@ -367,10 +373,6 @@
     return nullptr;
 #endif
   }
-  case MetadataKind::ForeignClass: {
-    auto foreign = static_cast<const ForeignClassMetadata *>(type);
-    return Dem.demangleType(foreign->getName());
-  }
   case MetadataKind::Existential: {
     auto exis = static_cast<const ExistentialTypeMetadata *>(type);
     
diff --git a/stdlib/public/runtime/KnownMetadata.cpp b/stdlib/public/runtime/KnownMetadata.cpp
index 05e2c37..7b88495 100644
--- a/stdlib/public/runtime/KnownMetadata.cpp
+++ b/stdlib/public/runtime/KnownMetadata.cpp
@@ -191,3 +191,4 @@
     nullptr                    // Labels
   }
 };
+
diff --git a/stdlib/public/runtime/Metadata.cpp b/stdlib/public/runtime/Metadata.cpp
index 6426937..6fb851a 100644
--- a/stdlib/public/runtime/Metadata.cpp
+++ b/stdlib/public/runtime/Metadata.cpp
@@ -30,7 +30,6 @@
 #include <algorithm>
 #include <cctype>
 #include <condition_variable>
-#include <iostream>
 #include <new>
 #if defined(_WIN32)
 #define WIN32_LEAN_AND_MEAN
@@ -2296,6 +2295,36 @@
 static const ValueWitnessTable OpaqueExistentialValueWitnesses_1 =
   ValueWitnessTableForBox<OpaqueExistentialBox<1>>::table;
 
+/// The standard metadata for Any.
+const FullMetadata<ExistentialTypeMetadata> swift::
+METADATA_SYM(ANY_MANGLING) = {
+  { &OpaqueExistentialValueWitnesses_0 }, // ValueWitnesses
+  ExistentialTypeMetadata(
+    ExistentialTypeFlags() // Flags
+      .withNumWitnessTables(0)
+      .withClassConstraint(ProtocolClassConstraint::Any)
+      .withHasSuperclass(false)
+      .withSpecialProtocol(SpecialProtocol::None)),
+};
+
+/// The standard metadata for AnyObject.
+const FullMetadata<ExistentialTypeMetadata> swift::
+METADATA_SYM(ANYOBJECT_MANGLING) = {
+  {
+#if SWIFT_OBJC_INTEROP
+    &VALUE_WITNESS_SYM(BO)
+#else
+    &VALUE_WITNESS_SYM(Bo)
+#endif
+  },
+  ExistentialTypeMetadata(
+    ExistentialTypeFlags() // Flags
+      .withNumWitnessTables(0)
+      .withClassConstraint(ProtocolClassConstraint::Class)
+      .withHasSuperclass(false)
+      .withSpecialProtocol(SpecialProtocol::None)),
+};
+
 /// The uniquing structure for opaque existential value witness tables.
 static SimpleGlobalCache<OpaqueExistentialValueWitnessTableCacheEntry>
 OpaqueExistentialValueWitnessTables;
@@ -2616,10 +2645,20 @@
                                   size_t numProtocols,
                                   const ProtocolDescriptor * const *protocols) {
 
+  // The empty compositions Any and AnyObject have fixed metadata.
+  if (numProtocols == 0 && !superclassConstraint) {
+    switch (classConstraint) {
+    case ProtocolClassConstraint::Any:
+      return &METADATA_SYM(ANY_MANGLING);
+    case ProtocolClassConstraint::Class:
+      return &METADATA_SYM(ANYOBJECT_MANGLING);
+    }
+  }
+
   // We entrust that the compiler emitting the call to
   // swift_getExistentialTypeMetadata always sorts the `protocols` array using
   // a globally stable ordering that's consistent across modules.
-
+  
   // Ensure that the "class constraint" bit is set whenever we have a
   // superclass or a one of the protocols is class-bound.
   assert(classConstraint == ProtocolClassConstraint::Class ||
@@ -2709,28 +2748,42 @@
 /***************************************************************************/
 
 namespace {
-  /// A string whose data is globally-allocated.
-  struct GlobalString {
-    StringRef Data;
-    /*implicit*/ GlobalString(StringRef data) : Data(data) {}
+  /// A reference to a context descriptor, used as a uniquing key.
+  struct ContextDescriptorKey {
+    const TypeContextDescriptor *Data;
   };
 } // end anonymous namespace
 
 template <>
-struct llvm::DenseMapInfo<GlobalString> {
-  static GlobalString getEmptyKey() {
-    return StringRef((const char*) 0, 0);
+struct llvm::DenseMapInfo<ContextDescriptorKey> {
+  static ContextDescriptorKey getEmptyKey() {
+    return ContextDescriptorKey{(const TypeContextDescriptor*) 0};
   }
-  static GlobalString getTombstoneKey() {
-    return StringRef((const char*) 1, 0);
+  static ContextDescriptorKey getTombstoneKey() {
+    return ContextDescriptorKey{(const TypeContextDescriptor*) 1};
   }
-  static unsigned getHashValue(const GlobalString &val) {
+  static unsigned getHashValue(ContextDescriptorKey val) {
+    if ((uintptr_t)val.Data <= 1) {
+      return llvm::hash_value(val.Data);
+    }
+
+    // Hash by name.
+    // In full generality, we'd get a better hash by walking up the entire
+    // descriptor tree and hashing names all along the way, and we'd be faster
+    // if we special cased unique keys by hashing pointers. In practice, this
+    // is only used to unique foreign metadata records, which only ever appear
+    // in the "C" or "ObjC" special context, and are never unique.
+    
     // llvm::hash_value(StringRef) is, unfortunately, defined out of
     // line in a library we otherwise would not need to link against.
-    return llvm::hash_combine_range(val.Data.begin(), val.Data.end());
+    StringRef name(val.Data->Name.get());
+    return llvm::hash_combine_range(name.begin(), name.end());
   }
-  static bool isEqual(const GlobalString &lhs, const GlobalString &rhs) {
-    return lhs.Data == rhs.Data;
+  static bool isEqual(ContextDescriptorKey lhs, ContextDescriptorKey rhs) {
+    if ((uintptr_t)lhs.Data <= 1 || (uintptr_t)rhs.Data <= 1) {
+      return lhs.Data == rhs.Data;
+    }
+    return equalContexts(lhs.Data, rhs.Data);
   }
 };
 
@@ -2740,7 +2793,7 @@
 struct ForeignTypeState {
   Mutex Lock;
   ConditionVariable InitializationWaiters;
-  llvm::DenseMap<GlobalString, const ForeignTypeMetadata *> Types;
+  llvm::DenseMap<ContextDescriptorKey, const ForeignTypeMetadata *> Types;
 };
 } // end anonymous namespace
 
@@ -2756,7 +2809,9 @@
 
   // Okay, check the global map.
   auto &foreignTypes = ForeignTypes.get();
-  GlobalString key(nonUnique->getName());
+  ContextDescriptorKey key{nonUnique->getTypeContextDescriptor()};
+  assert(key.Data
+         && "all foreign metadata should have a type context descriptor");
   bool hasInit = cache.hasInitializationFunction();
 
   const ForeignTypeMetadata *uniqueMetadata;
diff --git a/stdlib/public/stubs/SwiftNativeNSXXXBase.mm.gyb b/stdlib/public/stubs/SwiftNativeNSXXXBase.mm.gyb
index 0642352..842981d 100644
--- a/stdlib/public/stubs/SwiftNativeNSXXXBase.mm.gyb
+++ b/stdlib/public/stubs/SwiftNativeNSXXXBase.mm.gyb
@@ -144,55 +144,6 @@
   return Result;
 }
 
-SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
-bool swift_stdlib_NSStringHasPrefixNFD(NSString *theString,
-                                       NSString *prefix) {
-  auto Length = CFStringGetLength((__bridge CFStringRef)theString);
-  int Result = CFStringFindWithOptions(
-      (__bridge CFStringRef)theString, (__bridge CFStringRef)prefix,
-      CFRangeMake(0, Length), kCFCompareAnchored | kCFCompareNonliteral,
-      nullptr);
-  SWIFT_CC_PLUSONE_GUARD(swift_unknownRelease(theString));
-  SWIFT_CC_PLUSONE_GUARD(swift_unknownRelease(prefix));
-  return Result;
-}
-
-SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
-bool swift_stdlib_NSStringHasPrefixNFDPointer(void *theString,
-                                              void *prefix) {
-  auto Length = CFStringGetLength((__bridge CFStringRef)theString);
-  int Result = CFStringFindWithOptions(
-      (__bridge CFStringRef)theString, (__bridge CFStringRef)prefix,
-      CFRangeMake(0, Length), kCFCompareAnchored | kCFCompareNonliteral,
-      nullptr);
-  return Result;
-}
-
-SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
-bool
-swift_stdlib_NSStringHasSuffixNFD(NSString *SWIFT_NS_RELEASES_ARGUMENT theString,
-                                  NSString *SWIFT_NS_RELEASES_ARGUMENT suffix) {
-  auto Length = CFStringGetLength((__bridge CFStringRef)theString);
-  int Result = CFStringFindWithOptions(
-      (__bridge CFStringRef)theString, (__bridge CFStringRef)suffix,
-      CFRangeMake(0, Length),
-      kCFCompareAnchored | kCFCompareBackwards | kCFCompareNonliteral, nullptr);
-  SWIFT_CC_PLUSONE_GUARD(swift_unknownRelease(theString));
-  SWIFT_CC_PLUSONE_GUARD(swift_unknownRelease(suffix));
-  return Result;
-}
-
-SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
-bool swift_stdlib_NSStringHasSuffixNFDPointer(void *theString,
-                                              void *suffix) {
-  auto Length = CFStringGetLength((__bridge CFStringRef)theString);
-  int Result = CFStringFindWithOptions(
-      (__bridge CFStringRef)theString, (__bridge CFStringRef)suffix,
-      CFRangeMake(0, Length),
-      kCFCompareAnchored | kCFCompareBackwards | kCFCompareNonliteral, nullptr);
-  return Result;
-}
-
 SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
 void swift_stdlib_CFSetGetValues(NSSet *SWIFT_NS_RELEASES_ARGUMENT set,
                                  const void **values) {
diff --git a/test/ClangImporter/Inputs/static_inline.swift b/test/ClangImporter/Inputs/static_inline.swift
new file mode 100644
index 0000000..7ac39eb
--- /dev/null
+++ b/test/ClangImporter/Inputs/static_inline.swift
@@ -0,0 +1,3 @@
+@_inlineable public func testit(x: Int32) -> Int32 {
+  return c_inline_func(x)
+}
diff --git a/test/ClangImporter/availability_returns_twice.swift b/test/ClangImporter/availability_returns_twice.swift
index f0cee90..537c184 100644
--- a/test/ClangImporter/availability_returns_twice.swift
+++ b/test/ClangImporter/availability_returns_twice.swift
@@ -1,6 +1,6 @@
 // RUN: %target-swift-frontend -typecheck -verify %s
 
-#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
+#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
   import Darwin
   typealias JumpBuffer = Int32
 #else
diff --git a/test/ClangImporter/clang_builtins.swift b/test/ClangImporter/clang_builtins.swift
index 73ef91e..b9a72eb 100644
--- a/test/ClangImporter/clang_builtins.swift
+++ b/test/ClangImporter/clang_builtins.swift
@@ -3,7 +3,7 @@
 // RUN: not %target-swift-frontend -swift-version 4 -typecheck %s 2> %t.4.txt
 // RUN: %FileCheck -check-prefix=CHECK-4 -check-prefix=CHECK-%target-runtime-4 %s < %t.4.txt
 
-#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
+#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
   import Darwin
 #else
   import Glibc
@@ -27,7 +27,7 @@
   // CHECK-4: [[@LINE-2]]:16: error: cannot convert value of type '({{.+}}) -> Int'{{( [(]aka .+[)])?}} to specified type 'Int'
 }
 
-#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
+#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
 // These functions aren't consistently available across platforms, so only
 // test for them on Apple platforms.
 func testApple() {
diff --git a/test/ClangImporter/objc_ir.swift b/test/ClangImporter/objc_ir.swift
index 7f9b8c2..3313b80 100644
--- a/test/ClangImporter/objc_ir.swift
+++ b/test/ClangImporter/objc_ir.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-clang-importer-objc-overlays
 // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -I %S/Inputs/custom-modules -emit-ir -g -o - -primary-file %s | %FileCheck %s
diff --git a/test/ClangImporter/optional.swift b/test/ClangImporter/optional.swift
index c510215..b55edaf 100644
--- a/test/ClangImporter/optional.swift
+++ b/test/ClangImporter/optional.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules -emit-silgen -o - %s | %FileCheck %s
 
 // REQUIRES: objc_interop
diff --git a/test/ClangImporter/plus_zero_objc_ir.swift b/test/ClangImporter/plus_zero_objc_ir.swift
index 4ea8181..c31afe7 100644
--- a/test/ClangImporter/plus_zero_objc_ir.swift
+++ b/test/ClangImporter/plus_zero_objc_ir.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-clang-importer-objc-overlays
 // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -I %S/Inputs/custom-modules -emit-ir -g -o - -primary-file %s | %FileCheck %s
diff --git a/test/ClangImporter/plus_zero_optional.swift b/test/ClangImporter/plus_zero_optional.swift
index f36c2af..2143b38 100644
--- a/test/ClangImporter/plus_zero_optional.swift
+++ b/test/ClangImporter/plus_zero_optional.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules -enable-sil-ownership -emit-silgen -o - %s | %FileCheck %s
 
 // REQUIRES: objc_interop
diff --git a/test/ClangImporter/plus_zero_serialization-sil.swift b/test/ClangImporter/plus_zero_serialization-sil.swift
index 2c063a6..fb5a358 100644
--- a/test/ClangImporter/plus_zero_serialization-sil.swift
+++ b/test/ClangImporter/plus_zero_serialization-sil.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module-path %t/Test.swiftmodule -emit-sil -o /dev/null -module-name Test %s -sdk "" -import-objc-header %S/Inputs/serialization-sil.h -enable-sil-ownership
 // RUN: %target-sil-func-extractor %t/Test.swiftmodule -sil-print-debuginfo  -func='$S4Test16testPartialApplyyySoAA_pF' -o - | %FileCheck %s
diff --git a/test/ClangImporter/serialization-sil.swift b/test/ClangImporter/serialization-sil.swift
index eeb1d66..db01987 100644
--- a/test/ClangImporter/serialization-sil.swift
+++ b/test/ClangImporter/serialization-sil.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module-path %t/Test.swiftmodule -emit-sil -o /dev/null -module-name Test %s -sdk "" -import-objc-header %S/Inputs/serialization-sil.h
 // RUN: %target-sil-func-extractor %t/Test.swiftmodule -sil-print-debuginfo  -func='$S4Test16testPartialApplyyySoAA_pF' -o - | %FileCheck %s
diff --git a/test/ClangImporter/static_inline.swift b/test/ClangImporter/static_inline.swift
index 10da321..a18d5a0 100644
--- a/test/ClangImporter/static_inline.swift
+++ b/test/ClangImporter/static_inline.swift
@@ -2,16 +2,18 @@
 
 // Check if SIL printing+parsing of a clang imported function works.
 
-// RUN: %target-swift-frontend -parse-as-library -module-name=test -emit-sil %s -import-objc-header %S/Inputs/static_inline.h -o %t/test.sil
-// RUN: %FileCheck < %t/test.sil %s
-// RUN: %target-swift-frontend -parse-as-library -module-name=test -O -emit-ir %t/test.sil -import-objc-header %S/Inputs/static_inline.h | %FileCheck --check-prefix=CHECK-IR %s
+// RUN: %target-swift-frontend -parse-as-library -module-name=static_inline -emit-sil %S/Inputs/static_inline.swift -import-objc-header %S/Inputs/static_inline.h -o %t/static_inline.sil
+// RUN: %FileCheck < %t/static_inline.sil %s
+// RUN: %target-swift-frontend -parse-as-library -module-name=static_inline -O -emit-ir %t/static_inline.sil -import-objc-header %S/Inputs/static_inline.h | %FileCheck --check-prefix=CHECK-IR %s
 
 // CHECK: sil shared [serializable] [clang c_inline_func] @c_inline_func : $@convention(c) (Int32) -> Int32
 
-// CHECK-IR-LABEL: define{{.*}} i32 @"$S4test6testit1xs5Int32VAE_tF"(i32)
+// CHECK-IR-LABEL: define{{.*}} i32 @"$S13static_inline6testit1xs5Int32VAE_tF"(i32)
 // CHECK-IR: = add {{.*}}, 27
 // CHECK-IR: ret
 
-public func testit(x: Int32) -> Int32 {
-  return c_inline_func(x)
+import static_inline
+
+public func mytest(x: Int32) -> Int32 {
+  return testit(x: x)
 }
diff --git a/test/ClangImporter/static_inline_serialize.swift b/test/ClangImporter/static_inline_serialize.swift
new file mode 100644
index 0000000..087282c
--- /dev/null
+++ b/test/ClangImporter/static_inline_serialize.swift
@@ -0,0 +1,19 @@
+// RUN: %empty-directory(%t)
+
+// Try serialization of clang-generated functions.
+
+// RUN: %target-swift-frontend -parse-as-library -module-name=static_inline -emit-module %S/Inputs/static_inline.swift -import-objc-header %S/Inputs/static_inline.h -o %t/static_inline.swiftmodule
+// RUN: %target-swift-frontend -module-name test -O -emit-sil %s -I %t | %FileCheck %s
+// RUN: %target-swift-frontend -module-name test -O -emit-ir %s -I %t | %FileCheck --check-prefix=CHECK-IR %s
+
+// CHECK: sil shared_external [clang c_inline_func] @c_inline_func : $@convention(c) (Int32) -> Int32
+
+// CHECK-IR-LABEL: define{{.*}} i32 @"$S4test6mytest1xs5Int32VAE_tF"(i32)
+// CHECK-IR: = add {{.*}}, 27
+// CHECK-IR: ret
+
+import static_inline
+
+public func mytest(x: Int32) -> Int32 {
+  return testit(x: x)
+}
diff --git a/test/Constraints/closures.swift b/test/Constraints/closures.swift
index 005ba6c..5e20b6b 100644
--- a/test/Constraints/closures.swift
+++ b/test/Constraints/closures.swift
@@ -35,19 +35,22 @@
 
 func inoutToSharedConversions() {
   func fooOW<T, U>(_ f : (__owned T) -> U) {}
-  fooOW({ (x : Int) in return Int(5) }) // '__owned'-to-'__owned' allowed
+  fooOW({ (x : Int) in return Int(5) }) // defaut-to-'__owned' allowed
+  fooOW({ (x : __owned Int) in return Int(5) }) // '__owned'-to-'__owned' allowed
   fooOW({ (x : __shared Int) in return Int(5) }) // '__shared'-to-'__owned' allowed
-  fooOW({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(_) -> _'}}
+  fooOW({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(__owned _) -> _'}}
   
   func fooIO<T, U>(_ f : (inout T) -> U) {}
   fooIO({ (x : inout Int) in return Int(5) }) // 'inout'-to-'inout' allowed
-  fooIO({ (x : __shared Int) in return Int(5) }) // expected-error {{cannot convert value of type '(__shared Int) -> Int' to expected argument type '(inout _) -> _'}}
   fooIO({ (x : Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(inout _) -> _'}}
+  fooIO({ (x : __shared Int) in return Int(5) }) // expected-error {{cannot convert value of type '(__shared Int) -> Int' to expected argument type '(inout _) -> _'}}
+  fooIO({ (x : __owned Int) in return Int(5) }) // expected-error {{cannot convert value of type '(__owned Int) -> Int' to expected argument type '(inout _) -> _'}}
 
   func fooSH<T, U>(_ f : (__shared T) -> U) {}
   fooSH({ (x : __shared Int) in return Int(5) }) // '__shared'-to-'__shared' allowed
+  fooSH({ (x : __owned Int) in return Int(5) }) // '__owned'-to-'__shared' allowed
   fooSH({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(__shared _) -> _'}}
-  fooSH({ (x : Int) in return Int(5) }) // '__owned'-to-'__shared' allowed
+  fooSH({ (x : Int) in return Int(5) }) // default-to-'__shared' allowed
 }
 
 // Autoclosure
@@ -652,3 +655,38 @@
      str.replaceSubrange(range, with: str[range].reversed())
   }])
 }
+
+protocol P_37790062 {
+  associatedtype T
+  var elt: T { get }
+}
+
+func rdar37790062() {
+  struct S<T> {
+    init(_ a: () -> T, _ b: () -> T) {}
+  }
+
+  class C1 : P_37790062 {
+    typealias T = Int
+    var elt: T { return 42 }
+  }
+
+  class C2 : P_37790062 {
+    typealias T = (String, Int, Void)
+    var elt: T { return ("question", 42, ()) }
+  }
+
+  func foo() -> Int { return 42 }
+  func bar() -> Void {}
+  func baz() -> (String, Int) { return ("question", 42) }
+  func bzz<T>(_ a: T) -> T { return a }
+  func faz<T: P_37790062>(_ a: T) -> T.T { return a.elt }
+
+  _ = S({ foo() }, { bar() }) // expected-warning {{result of call to 'foo()' is unused}}
+  _ = S({ baz() }, { bar() }) // expected-warning {{result of call to 'baz()' is unused}}
+  _ = S({ bzz(("question", 42)) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}}
+  _ = S({ bzz(String.self) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}}
+  _ = S({ bzz(((), (()))) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}}
+  _ = S({ bzz(C1()) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}}
+  _ = S({ faz(C2()) }, { bar() }) // expected-warning {{result of call to 'faz' is unused}}
+}
diff --git a/test/Constraints/rdar37790062.swift b/test/Constraints/rdar37790062.swift
new file mode 100644
index 0000000..13d2f8c
--- /dev/null
+++ b/test/Constraints/rdar37790062.swift
@@ -0,0 +1,46 @@
+// RUN: %target-typecheck-verify-swift
+
+protocol A {
+  associatedtype V
+  associatedtype E: Error
+
+  init(value: V)
+  init(error: E)
+
+  func foo<U>(value: (V) -> U, error: (E) -> U) -> U
+}
+
+enum R<T, E: Error> : A {
+  case foo(T)
+  case bar(E)
+
+  init(value: T) { self = .foo(value) }
+  init(error: E) { self = .bar(error) }
+
+  func foo<R>(value: (T) -> R, error: (E) -> R) -> R {
+    fatalError()
+  }
+}
+
+protocol P {
+  associatedtype V
+
+  @discardableResult
+  func baz(callback: @escaping (V) -> Void) -> Self
+}
+
+class C<V> : P {
+  func baz(callback: @escaping (V) -> Void) -> Self { return self }
+}
+class D<T, E: Error> : C<R<T, E>> {
+  init(fn: (_ ret: @escaping (V) -> Void) -> Void) {}
+}
+
+extension A where V: P, V.V: A, E == V.V.E {
+  func bar() -> D<V.V.V, V.V.E> {
+    return D { complete in
+      foo(value: { promise in promise.baz { result in } },
+          error: { complete(R(error: $0)) })
+    }
+  }
+}
diff --git a/test/DebugInfo/closure-multivalue.swift b/test/DebugInfo/closure-multivalue.swift
index c724ad1..fe50f4c 100644
--- a/test/DebugInfo/closure-multivalue.swift
+++ b/test/DebugInfo/closure-multivalue.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // rdar://problem/23727705:
 // RUN-DISABLED: %target-swift-frontend -O %s -disable-llvm-optzns -emit-ir -g -o - | %FileCheck %s
 import StdlibUnittest
@@ -36,8 +37,8 @@
 // Verify that a reabstraction thunk does not have a line number.
 // CHECK-O0-NOT: DW_OP_bit_piece
 // CHECK-O0-NOT: DW_OP_bit_piece
-// CHECK-O0: !DILocalVariable(name: "a", arg: 1{{.*}} line: 18,
+// CHECK-O0: !DILocalVariable(name: "a", arg: 1{{.*}} line: 19,
 // CHECK-O0-NOT: DW_OP_bit_piece
-// CHECK-O0: !DILocalVariable(name: "b", arg: 2{{.*}} line: 18,
+// CHECK-O0: !DILocalVariable(name: "b", arg: 2{{.*}} line: 19,
 // CHECK-O0-NOT: DW_OP_bit_piece
 // CHECK-O0: !DISubprogram(linkageName: "$SS2SSbs5Error_pIgxxdzo_S2SSbsAA_pIegiidzo_TR",
diff --git a/test/DebugInfo/generic_args.swift b/test/DebugInfo/generic_args.swift
index a0974eb..b1247d8 100644
--- a/test/DebugInfo/generic_args.swift
+++ b/test/DebugInfo/generic_args.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -primary-file %s -emit-ir -verify -g -o - | %FileCheck %s
 
 func markUsed<T>(_ t: T) {}
diff --git a/test/DebugInfo/plus_zero_closure-multivalue.swift b/test/DebugInfo/plus_zero_closure-multivalue.swift
index f77552f..4f0d363 100644
--- a/test/DebugInfo/plus_zero_closure-multivalue.swift
+++ b/test/DebugInfo/plus_zero_closure-multivalue.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // rdar://problem/23727705:
 // RUN-DISABLED: %target-swift-frontend -O %s -disable-llvm-optzns -emit-ir -g -o - | %FileCheck %s
 import StdlibUnittest
@@ -36,8 +37,8 @@
 // Verify that a reabstraction thunk does not have a line number.
 // CHECK-O0-NOT: DW_OP_bit_piece
 // CHECK-O0-NOT: DW_OP_bit_piece
-// CHECK-O0: !DILocalVariable(name: "a", arg: 1{{.*}} line: 17,
+// CHECK-O0: !DILocalVariable(name: "a", arg: 1{{.*}} line: 19,
 // CHECK-O0-NOT: DW_OP_bit_piece
-// CHECK-O0: !DILocalVariable(name: "b", arg: 2{{.*}} line: 17,
+// CHECK-O0: !DILocalVariable(name: "b", arg: 2{{.*}} line: 19,
 // CHECK-O0-NOT: DW_OP_bit_piece
 // CHECK-O0: !DISubprogram(linkageName: "$SS2SSbs5Error_pIgggdzo_S2SSbsAA_pIegnndzo_TR",
diff --git a/test/DebugInfo/plus_zero_generic_args.swift b/test/DebugInfo/plus_zero_generic_args.swift
index e4de262..090929a 100644
--- a/test/DebugInfo/plus_zero_generic_args.swift
+++ b/test/DebugInfo/plus_zero_generic_args.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -primary-file %s -emit-ir -verify -g -o - | %FileCheck %s
 
 func markUsed<T>(_ t: T) {}
diff --git a/test/DebugInfo/plus_zero_resilience.swift b/test/DebugInfo/plus_zero_resilience.swift
index 0e50528..cedfa85 100644
--- a/test/DebugInfo/plus_zero_resilience.swift
+++ b/test/DebugInfo/plus_zero_resilience.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 //
 // Compile the external swift module.
diff --git a/test/DebugInfo/resilience.swift b/test/DebugInfo/resilience.swift
index 5f78283..c7dce2f 100644
--- a/test/DebugInfo/resilience.swift
+++ b/test/DebugInfo/resilience.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 //
 // Compile the external swift module.
diff --git a/test/DebugInfo/vector.swift b/test/DebugInfo/vector.swift
new file mode 100644
index 0000000..d83ee8c
--- /dev/null
+++ b/test/DebugInfo/vector.swift
@@ -0,0 +1,20 @@
+// RUN: %target-swift-frontend -emit-ir -g %s -o - -parse-stdlib | %FileCheck %s
+// REQUIRES: OS=macosx
+
+// CHECK: !DICompositeType(tag: DW_TAG_array_type, baseType: ![[FLOAT:[0-9]+]], size: 64, flags: DIFlagVector, elements: ![[ELTS:[0-9]+]])
+// CHECK: ![[FLOAT]] = !DIBasicType(name: "$SBf32_D", size: 32, encoding: DW_ATE_float)
+// CHECK: ![[ELTS]] = !{![[SR:[0-9]+]]}
+// CHECK: ![[SR]] = !DISubrange(count: 2)
+
+
+import Swift
+public struct float2 {
+  public var _vector: Builtin.Vec2xFPIEEE32
+  public subscript(index: Int) -> Float {
+    get {
+      let elt = Builtin.extractelement_Vec2xFPIEEE32_Int32(_vector,
+        Int32(index)._value)
+      return Float(_bits: elt)
+    }
+  }
+}
diff --git a/test/Driver/batch_mode.swift b/test/Driver/batch_mode.swift
index 2bbf0ab..0607375 100644
--- a/test/Driver/batch_mode.swift
+++ b/test/Driver/batch_mode.swift
@@ -18,10 +18,32 @@
 // SEED0: Forming into 4 batches
 // SEED0: Adding {compile: {{file-01-.*}} <= file-01.swift} to batch 0
 // SEED0: Adding {compile: {{file-02-.*}} <= file-02.swift} to batch 0
+// SEED0: Adding {compile: {{file-03-.*}} <= file-03.swift} to batch 0
+// SEED0: Adding {compile: {{file-04-.*}} <= file-04.swift} to batch 0
+// SEED0: Adding {compile: {{file-05-.*}} <= file-05.swift} to batch 0
+// SEED0: Adding {compile: {{file-06-.*}} <= file-06.swift} to batch 0
+// SEED0: Adding {compile: {{file-07-.*}} <= file-07.swift} to batch 0
+// SEED0: Adding {compile: {{file-08-.*}} <= file-08.swift} to batch 0
 // SEED0: Adding {compile: {{file-09-.*}} <= file-09.swift} to batch 1
 // SEED0: Adding {compile: {{file-10-.*}} <= file-10.swift} to batch 1
+// SEED0: Adding {compile: {{file-11-.*}} <= file-11.swift} to batch 1
+// SEED0: Adding {compile: {{file-12-.*}} <= file-12.swift} to batch 1
+// SEED0: Adding {compile: {{file-13-.*}} <= file-13.swift} to batch 1
+// SEED0: Adding {compile: {{file-14-.*}} <= file-14.swift} to batch 1
+// SEED0: Adding {compile: {{file-15-.*}} <= file-15.swift} to batch 1
+// SEED0: Adding {compile: {{file-16-.*}} <= file-16.swift} to batch 1
+// SEED0: Adding {compile: {{file-17-.*}} <= file-17.swift} to batch 2
+// SEED0: Adding {compile: {{file-18-.*}} <= file-18.swift} to batch 2
 // SEED0: Adding {compile: {{file-19-.*}} <= file-19.swift} to batch 2
 // SEED0: Adding {compile: {{file-20-.*}} <= file-20.swift} to batch 2
+// SEED0: Adding {compile: {{file-21-.*}} <= file-21.swift} to batch 2
+// SEED0: Adding {compile: {{file-22-.*}} <= file-22.swift} to batch 2
+// SEED0: Adding {compile: {{file-23-.*}} <= file-23.swift} to batch 2
+// SEED0: Adding {compile: {{file-24-.*}} <= file-24.swift} to batch 3
+// SEED0: Adding {compile: {{file-25-.*}} <= file-25.swift} to batch 3
+// SEED0: Adding {compile: {{file-26-.*}} <= file-26.swift} to batch 3
+// SEED0: Adding {compile: {{file-27-.*}} <= file-27.swift} to batch 3
+// SEED0: Adding {compile: {{file-28-.*}} <= file-28.swift} to batch 3
 // SEED0: Adding {compile: {{file-29-.*}} <= file-29.swift} to batch 3
 // SEED0: Adding {compile: {{file-30-.*}} <= file-30.swift} to batch 3
 // SEED0: Forming batch job from 8 constituents
@@ -35,10 +57,36 @@
 //
 // SEED1: Found 30 batchable jobs
 // SEED1: Forming into 4 batches
-// SEED1: Adding {compile: file-{{.*}} <= file-{{.*}}.swift} to batch 0
-// SEED1: Adding {compile: file-{{.*}} <= file-{{.*}}.swift} to batch 1
-// SEED1: Adding {compile: file-{{.*}} <= file-{{.*}}.swift} to batch 2
-// SEED1: Adding {compile: file-{{.*}} <= file-{{.*}}.swift} to batch 3
+// SEED1: Adding {compile: {{file-01-.*}} <= file-01.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-02-.*}} <= file-02.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-03-.*}} <= file-03.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-04-.*}} <= file-04.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-05-.*}} <= file-05.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-06-.*}} <= file-06.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-07-.*}} <= file-07.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-08-.*}} <= file-08.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-09-.*}} <= file-09.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-10-.*}} <= file-10.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-11-.*}} <= file-11.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-12-.*}} <= file-12.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-13-.*}} <= file-13.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-14-.*}} <= file-14.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-15-.*}} <= file-15.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-16-.*}} <= file-16.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-17-.*}} <= file-17.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-18-.*}} <= file-18.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-19-.*}} <= file-19.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-20-.*}} <= file-20.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-21-.*}} <= file-21.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-22-.*}} <= file-22.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-23-.*}} <= file-23.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-24-.*}} <= file-24.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-25-.*}} <= file-25.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-26-.*}} <= file-26.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-27-.*}} <= file-27.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-28-.*}} <= file-28.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-29-.*}} <= file-29.swift} to batch {{[0-3]}}
+// SEED1: Adding {compile: {{file-30-.*}} <= file-30.swift} to batch {{[0-3]}}
 // SEED1: Forming batch job from 8 constituents
 // SEED1: Forming batch job from 8 constituents
 // SEED1: Forming batch job from 7 constituents
@@ -50,10 +98,36 @@
 //
 // SEED2: Found 30 batchable jobs
 // SEED2: Forming into 4 batches
-// SEED2: Adding {compile: file-{{.*}} <= file-{{.*}}.swift} to batch 0
-// SEED2: Adding {compile: file-{{.*}} <= file-{{.*}}.swift} to batch 1
-// SEED2: Adding {compile: file-{{.*}} <= file-{{.*}}.swift} to batch 2
-// SEED2: Adding {compile: file-{{.*}} <= file-{{.*}}.swift} to batch 3
+// SEED2: Adding {compile: {{file-01-.*}} <= file-01.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-02-.*}} <= file-02.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-03-.*}} <= file-03.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-04-.*}} <= file-04.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-05-.*}} <= file-05.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-06-.*}} <= file-06.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-07-.*}} <= file-07.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-08-.*}} <= file-08.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-09-.*}} <= file-09.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-10-.*}} <= file-10.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-11-.*}} <= file-11.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-12-.*}} <= file-12.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-13-.*}} <= file-13.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-14-.*}} <= file-14.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-15-.*}} <= file-15.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-16-.*}} <= file-16.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-17-.*}} <= file-17.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-18-.*}} <= file-18.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-19-.*}} <= file-19.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-20-.*}} <= file-20.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-21-.*}} <= file-21.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-22-.*}} <= file-22.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-23-.*}} <= file-23.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-24-.*}} <= file-24.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-25-.*}} <= file-25.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-26-.*}} <= file-26.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-27-.*}} <= file-27.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-28-.*}} <= file-28.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-29-.*}} <= file-29.swift} to batch {{[0-3]}}
+// SEED2: Adding {compile: {{file-30-.*}} <= file-30.swift} to batch {{[0-3]}}
 // SEED2: Forming batch job from 8 constituents
 // SEED2: Forming batch job from 8 constituents
 // SEED2: Forming batch job from 7 constituents
diff --git a/test/Driver/batch_mode_aux_file_order.swift b/test/Driver/batch_mode_aux_file_order.swift
new file mode 100644
index 0000000..5366371
--- /dev/null
+++ b/test/Driver/batch_mode_aux_file_order.swift
@@ -0,0 +1,20 @@
+// When multiple additional-outputs on the same command-line are no longer
+// supported (i.e. when we've moved to mandatory use of output file maps for
+// communicating multiple additional-outputs to frontends) this test will no
+// longer make sense, and should be removed.
+//
+// RUN: %empty-directory(%t)
+// RUN: touch %t/file-01.swift %t/file-02.swift %t/file-03.swift %t/file-04.swift %t/file-05.swift
+// RUN: touch %t/file-06.swift %t/file-07.swift %t/file-08.swift %t/file-09.swift
+//
+// RUN: %swiftc_driver -enable-batch-mode -driver-batch-seed 1 -driver-print-jobs -driver-skip-execution -j 3 -emit-module -module-name foo %t/file-01.swift %t/file-02.swift %t/file-03.swift %t/file-04.swift %t/file-05.swift %t/file-06.swift %t/file-07.swift %t/file-08.swift %t/file-09.swift >%t/out.txt
+// RUN: %FileCheck %s <%t/out.txt
+//
+// Each batch should get 3 primaries; check that each has 3 modules _in the same numeric order_.
+//
+// CHECK: {{.*}}/swift {{.*}}-primary-file {{[^ ]*}}/file-[[A1:[0-9]+]].swift {{.*}}-primary-file {{[^ ]*}}/file-[[A2:[0-9]+]].swift {{.*}}-primary-file {{[^ ]*}}/file-[[A3:[0-9]+]].swift
+// CHECK-SAME: -o {{.*}}/file-[[A1]]-{{[a-z0-9]+}}.swiftmodule -o {{.*}}/file-[[A2]]-{{[a-z0-9]+}}.swiftmodule -o {{.*}}/file-[[A3]]-{{[a-z0-9]+}}.swiftmodule
+// CHECK: {{.*}}/swift {{.*}}-primary-file {{[^ ]*}}/file-[[B1:[0-9]+]].swift {{.*}}-primary-file {{[^ ]*}}/file-[[B2:[0-9]+]].swift {{.*}}-primary-file {{[^ ]*}}/file-[[B3:[0-9]+]].swift
+// CHECK-SAME: -o {{.*}}/file-[[B1]]-{{[a-z0-9]+}}.swiftmodule -o {{.*}}/file-[[B2]]-{{[a-z0-9]+}}.swiftmodule -o {{.*}}/file-[[B3]]-{{[a-z0-9]+}}.swiftmodule
+// CHECK: {{.*}}/swift {{.*}}-primary-file {{[^ ]*}}/file-[[C1:[0-9]+]].swift {{.*}}-primary-file {{[^ ]*}}/file-[[C2:[0-9]+]].swift {{.*}}-primary-file {{[^ ]*}}/file-[[C3:[0-9]+]].swift
+// CHECK-SAME: -o {{.*}}/file-[[C1]]-{{[a-z0-9]+}}.swiftmodule -o {{.*}}/file-[[C2]]-{{[a-z0-9]+}}.swiftmodule -o {{.*}}/file-[[C3]]-{{[a-z0-9]+}}.swiftmodule
diff --git a/test/Frontend/crash.swift b/test/Frontend/crash.swift
new file mode 100644
index 0000000..455f8fa
--- /dev/null
+++ b/test/Frontend/crash.swift
@@ -0,0 +1,14 @@
+// RUN: echo %s > %t.filelist.txt
+// RUN: not --crash %target-swift-frontend -typecheck -debug-crash-after-parse -filelist %t.filelist.txt 2>&1 | %FileCheck %s
+
+// Check that we see the contents of the input file list in the crash log.
+// CHECK-LABEL: Stack dump
+// CHECK-NEXT: Program arguments: {{.*swift(c?)}} -frontend
+// CHECK-NEXT: Contents of {{.*}}.filelist.txt:
+// CHECK-NEXT: ---
+// CHECK-NEXT: test/Frontend/crash.swift{{$}}
+// CHECK-NEXT: ---
+
+func anchor() {}
+anchor()
+
diff --git a/test/Fuzzing/fuzzer_test.swift b/test/Fuzzing/fuzzer_test.swift
index 054bf41..3795c4c 100644
--- a/test/Fuzzing/fuzzer_test.swift
+++ b/test/Fuzzing/fuzzer_test.swift
@@ -8,7 +8,7 @@
 // XFAIL: OS=watchos
 // CHECK: Crash!
 
-#if os(OSX) || os(iOS)
+#if os(macOS) || os(iOS)
 import Darwin
 #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin)
 import Glibc
diff --git a/test/Fuzzing/fuzzer_test_simpler.swift b/test/Fuzzing/fuzzer_test_simpler.swift
index 94e9b6c..beade8e 100644
--- a/test/Fuzzing/fuzzer_test_simpler.swift
+++ b/test/Fuzzing/fuzzer_test_simpler.swift
@@ -8,7 +8,7 @@
 // XFAIL: OS=tvos
 // XFAIL: OS=watchos
 
-#if os(OSX) || os(iOS)
+#if os(macOS) || os(iOS)
 import Darwin
 #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin)
 import Glibc
diff --git a/test/Generics/conditional_conformances.swift b/test/Generics/conditional_conformances.swift
index 0c3c2fe..7bf73da 100644
--- a/test/Generics/conditional_conformances.swift
+++ b/test/Generics/conditional_conformances.swift
@@ -307,11 +307,7 @@
 // expected-note@-1{{'TwoDisjointConformances<T>' declares conformance to protocol 'P2' here}}
 
 
-// FIXME: these cases should be equivalent (and both with the same output as the
-// first), but the second one choses T as the representative of the
-// equivalence class containing both T and U in the extension's generic
-// signature, meaning the stored conditional requirement is T: P1, which isn't
-// true in the original type's generic signature.
+// rdar://problem/34944318
 struct RedundancyOrderDependenceGood<T: P1, U> {}
 // CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundancyOrderDependenceGood<T, T>
 // CHECK-NEXT: (normal_conformance type=RedundancyOrderDependenceGood<T, U> protocol=P2
@@ -320,7 +316,6 @@
 struct RedundancyOrderDependenceBad<T, U: P1> {}
 // CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundancyOrderDependenceBad<T, T>
 // CHECK-NEXT: (normal_conformance type=RedundancyOrderDependenceBad<T, U> protocol=P2
-// CHECK-NEXT:   conforms_to: T P1
 // CHECK-NEXT:   same_type: T U)
 extension RedundancyOrderDependenceBad: P2 where T: P1, T == U {}
 
diff --git a/test/IDE/coloring_configs.swift b/test/IDE/coloring_configs.swift
index 6bd6393..69445d0 100644
--- a/test/IDE/coloring_configs.swift
+++ b/test/IDE/coloring_configs.swift
@@ -280,8 +280,8 @@
 // CHECK: <kw>class</kw> NestedPoundIf {
     func foo1() {
 // CHECK: <kw>func</kw> foo1() {
-        #if os(OSX)
-// CHECK: <#kw>#if</#kw> <#id>os</#id>(<#id>OSX</#id>)
+        #if os(macOS)
+// CHECK: <#kw>#if</#kw> <#id>os</#id>(<#id>macOS</#id>)
           var a = 1
 // CHECK: <kw>var</kw> a = <int>1</int>
             #if USE_METAL
diff --git a/test/IDE/reconstruct_type_from_mangled_name.swift b/test/IDE/reconstruct_type_from_mangled_name.swift
index 560910d..ebab1a2 100644
--- a/test/IDE/reconstruct_type_from_mangled_name.swift
+++ b/test/IDE/reconstruct_type_from_mangled_name.swift
@@ -267,8 +267,7 @@
 
 fileprivate struct VeryPrivateData {}
 
-// FIXME
-// CHECK: decl: FAILURE for 'privateFunction'
+// CHECK: decl: fileprivate func privateFunction(_ d: VeryPrivateData) for 'privateFunction'
 fileprivate func privateFunction(_ d: VeryPrivateData) {}
 
 struct HasSubscript {
@@ -306,3 +305,12 @@
     set {}
   }
 }
+
+private
+// CHECK: decl: private func patatino<T>(_ vers1: T, _ vers2: T) -> Bool where T : Comparable for
+func patatino<T: Comparable>(_ vers1: T, _ vers2: T) -> Bool {
+  // CHECK: decl: FAILURE   for 'T' usr=s:14swift_ide_test8patatino33_D7B956AE2D93947DFA67A1ECF93EF238LLySbx_xts10ComparableRzlF1TL_xmfp decl
+  // CHECK: decl: let vers1: T      for 'vers1' usr=s:14swift_ide_test8patatino33_D7B956AE2D93947DFA67A1ECF93EF238LLySbx_xts10ComparableRzlF5vers1L_xvp
+  // CHECK: decl: let vers2: T      for 'vers2' usr=s:14swift_ide_test8patatino33_D7B956AE2D93947DFA67A1ECF93EF238LLySbx_xts10ComparableRzlF5vers2L_xvp
+  return vers1 < vers2;
+}
diff --git a/test/IDE/structure.swift b/test/IDE/structure.swift
index edee06d..87bbdfd 100644
--- a/test/IDE/structure.swift
+++ b/test/IDE/structure.swift
@@ -154,7 +154,7 @@
 
 class NestedPoundIf{
     func foo1() {
-        #if os(OSX)
+        #if os(macOS)
           var a = 1
             #if USE_METAL
               var b = 2
diff --git a/test/IRGen/Inputs/ObjectiveC.swift b/test/IRGen/Inputs/ObjectiveC.swift
index 7457f48..0e155bb 100644
--- a/test/IRGen/Inputs/ObjectiveC.swift
+++ b/test/IRGen/Inputs/ObjectiveC.swift
@@ -2,8 +2,8 @@
 @_exported import ObjectiveC
 
 public struct ObjCBool : CustomStringConvertible {
-#if os(OSX) || (os(iOS) && (arch(i386) || arch(arm)))
-  // On OS X and 32-bit iOS, Objective-C's BOOL type is a "signed char".
+#if os(macOS) || (os(iOS) && (arch(i386) || arch(arm)))
+  // On macOS and 32-bit iOS, Objective-C's BOOL type is a "signed char".
   private var value: Int8
 
   public init(_ value: Bool) {
diff --git a/test/IRGen/access_control.sil b/test/IRGen/access_control.sil
index eabd2f4..9da2a39 100644
--- a/test/IRGen/access_control.sil
+++ b/test/IRGen/access_control.sil
@@ -4,23 +4,19 @@
 import Swift
 
 public struct PublicStruct { var x: Int }
-// CHECK: @"$S14access_control12PublicStructVWV" = internal constant
 // CHECK: @"$S14access_control12PublicStructVMn" = {{(protected )?}}constant
 // CHECK: @"$S14access_control12PublicStructVMf" = internal constant
 
 internal struct InternalStruct { var x: Int }
-// CHECK: @"$S14access_control14InternalStructVWV" = internal constant
 // CHECK: @"$S14access_control14InternalStructVMn" = hidden constant
 // CHECK: @"$S14access_control14InternalStructVMf" = internal constant
 
 private struct PrivateStruct { var x: Int }
-// CHECK: @"$S14access_control13PrivateStruct33_8F630B0A1EEF3ED34B761E3ED76C95A8LLVWV" = internal constant
 // CHECK: @"$S14access_control13PrivateStruct33_8F630B0A1EEF3ED34B761E3ED76C95A8LLVMn" = hidden constant
 // CHECK: @"$S14access_control13PrivateStruct33_8F630B0A1EEF3ED34B761E3ED76C95A8LLVMf" = internal constant
 
 func local() {
   struct LocalStruct { var x: Int }
-  // CHECK: @"$S14access_control5localyyF11LocalStructL_VWV" = internal constant
   // CHECK: @"$S14access_control5localyyF11LocalStructL_VMn" = hidden constant
   // CHECK: @"$S14access_control5localyyF11LocalStructL_VMf" = internal constant
 }
diff --git a/test/IRGen/big_types_corner_cases.swift b/test/IRGen/big_types_corner_cases.swift
index 7d3886d..9f98aa9 100644
--- a/test/IRGen/big_types_corner_cases.swift
+++ b/test/IRGen/big_types_corner_cases.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -enable-large-loadable-types %s -emit-ir | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize
 // REQUIRES: optimized_stdlib
 // UNSUPPORTED: resilient_stdlib
@@ -46,8 +47,8 @@
 ]
 
 // CHECK-LABEL: define{{( protected)?}} internal swiftcc void @"$S22big_types_corner_cases21OptionalInoutFuncTypeC7executeyys5Error_pSgFyyXEfU_"(%T22big_types_corner_cases9BigStructVSg* nocapture dereferenceable({{.*}}), %T22big_types_corner_cases21OptionalInoutFuncTypeC*, %T22big_types_corner_cases9BigStructVSgs5Error_pSgIegcx_Sg* nocapture dereferenceable({{.*}})
-// CHECK: call void @"$SSqWy
-// CHECK: call void @"$SSqWe
+// CHECK: call void @"$S22big_types_corner_cases9BigStructVSgs5Error_pSgIegcx_SgWy"
+// CHECK: call void @"$S22big_types_corner_cases9BigStructVSgs5Error_pSgIegcx_SgWe"
 // CHECK: ret void
 
 public func f1_returns_BigType(_ x: BigStruct) -> BigStruct {
diff --git a/test/IRGen/builtins.swift b/test/IRGen/builtins.swift
index 7046e14..1712d28 100644
--- a/test/IRGen/builtins.swift
+++ b/test/IRGen/builtins.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -parse-stdlib -primary-file %s -emit-ir -o - -disable-objc-attr-requires-foundation-module | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime
 
 // REQUIRES: CPU=x86_64
diff --git a/test/IRGen/cf.sil b/test/IRGen/cf.sil
index e4a8735..f25ffc6 100644
--- a/test/IRGen/cf.sil
+++ b/test/IRGen/cf.sil
@@ -10,20 +10,14 @@
 // CHECK: [[MUTABLE_REFRIGERATOR:%TSo24CCMutableRefrigeratorRefa]] = type
 // CHECK: [[OBJC:%objc_object]] = type
 
-// CHECK: [[REFRIGERATOR_NAME:@.*]] = private constant [23 x i8] c"So17CCRefrigeratorRefa\00"
-
 // CHECK-32: @"$SSo17CCRefrigeratorRefaN" = linkonce_odr hidden global <{ {{.*}} }> <{
-// CHECK-32-SAME: [[REFRIGERATOR_NAME]] to i32
 // CHECK-32-SAME: i32 0,
 // CHECK-32-SAME: i8** @"$SBOWV", i32 16, {{.*}}"$SSo17CCRefrigeratorRefaMn", [[TYPE]]* null, i8* null, i8* null, i8* null }>
 
 // CHECK-64: @"$SSo17CCRefrigeratorRefaN" = linkonce_odr hidden global <{ {{.*}} }> <{
-// CHECK-64-SAME: i32 0,
-// CHECK-64-SAME: i32 trunc {{.*}} [[REFRIGERATOR_NAME]] to i64
 // CHECK-64-SAME: i64 0,
 // CHECK-64-SAME: i8** @"$SBOWV", i64 16, {{.*}}"$SSo17CCRefrigeratorRefaMn", [[TYPE]]* null, i8* null, i8* null, i8* null }>
 
-// CHECK: [[MUTABLE_REFRIGERATOR_MANGLED_NAME:@.*]] = private constant [30 x i8] c"So24CCMutableRefrigeratorRefa\00"
 // CHECK: [[MUTABLE_REFRIGERATOR_NAME:@.*]] = private constant [25 x i8] c"CCMutableRefrigeratorRef\00"
 
 // CHECK-64: @"$SSo24CCMutableRefrigeratorRefaMn" = linkonce_odr hidden constant
@@ -33,7 +27,7 @@
 
 // CHECK-64: @"$SSo24CCMutableRefrigeratorRefaN" = linkonce_odr hidden global <{ {{.*}} }> <{
 // CHECK-64-SAME: @initialize_metadata_CCMutableRefrigerator
-// CHECK-64-SAME: i32 trunc {{.*}} [[MUTABLE_REFRIGERATOR_MANGLED_NAME]] to i64
+// CHECK-64-SAME: i32 0,
 // CHECK-64-SAME: i64 1,
 // CHECK-64-SAME: i8** @"$SBOWV", i64 16, {{.*}}"$SSo24CCMutableRefrigeratorRefaMn", [[TYPE]]* bitcast{{.*}}@"$SSo17CCRefrigeratorRefaN{{.*}} to %swift.type*), i8* null, i8* null, i8* null }>
 
@@ -63,8 +57,8 @@
 // CHECK-NEXT: ret void
 
 // CHECK:    define linkonce_odr hidden [[TYPE]]* @"$SSo17CCRefrigeratorRefaMa"()
-// CHECK-32:    call [[TYPE]]* @swift_getForeignTypeMetadata([[TYPE]]* bitcast (i8* getelementptr inbounds (i8, i8* bitcast ({{.*}}* @"$SSo17CCRefrigeratorRefaN" to i8*), i32 12) to [[TYPE]]*))
-// CHECK-64:    call [[TYPE]]* @swift_getForeignTypeMetadata([[TYPE]]* bitcast (i8* getelementptr inbounds (i8, i8* bitcast ({{.*}}* @"$SSo17CCRefrigeratorRefaN" to i8*), i64 24) to [[TYPE]]*))
+// CHECK-32:    call [[TYPE]]* @swift_getForeignTypeMetadata([[TYPE]]* bitcast (i8* getelementptr inbounds (i8, i8* bitcast ({{.*}}* @"$SSo17CCRefrigeratorRefaN" to i8*), i32 8) to [[TYPE]]*))
+// CHECK-64:    call [[TYPE]]* @swift_getForeignTypeMetadata([[TYPE]]* bitcast (i8* getelementptr inbounds (i8, i8* bitcast ({{.*}}* @"$SSo17CCRefrigeratorRefaN" to i8*), i64 16) to [[TYPE]]*))
 
 // CHECK:    define private void @initialize_metadata_CCMutableRefrigerator(%swift.type*)
 // CHECK-64:   [[T0:%.*]] = bitcast %swift.type* %0 to i8**
diff --git a/test/IRGen/class_bounded_generics.swift b/test/IRGen/class_bounded_generics.swift
index f1db660..07a5677 100644
--- a/test/IRGen/class_bounded_generics.swift
+++ b/test/IRGen/class_bounded_generics.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -emit-ir -primary-file %s -disable-objc-attr-requires-foundation-module | %FileCheck %s
 
 // REQUIRES: CPU=x86_64
diff --git a/test/IRGen/class_metadata.swift b/test/IRGen/class_metadata.swift
index 9344172..e1c978b 100644
--- a/test/IRGen/class_metadata.swift
+++ b/test/IRGen/class_metadata.swift
@@ -80,13 +80,13 @@
 //   Instantiation pattern.
 // CHECK-SAME: i32 {{.*}} @"$S14class_metadata1CCMP"
 //   Generic parameter count.
-// CHECK-SAME: i32 1,
+// CHECK-SAME: i16 1,
 //   Generic requirement count.
-// CHECK-SAME: i32 0,
+// CHECK-SAME: i16 0,
 //   Key generic arguments count.
-// CHECK-SAME: i32 1,
+// CHECK-SAME: i16 1,
 //   Extra generic arguments count.
-// CHECK-SAME: i32 0,
+// CHECK-SAME: i16 0,
 //   Generic parameter descriptor #1: flags. -128 == 0x80 == Key
 // CHECK-SAME: i8 -128,
 ///  Padding.
diff --git a/test/IRGen/enum.sil b/test/IRGen/enum.sil
index 8a0bd9d..50b6ec2 100644
--- a/test/IRGen/enum.sil
+++ b/test/IRGen/enum.sil
@@ -119,7 +119,7 @@
 // --       generic instantiation pattern
 // CHECK-SAME:   @"$S4enum16DynamicSingletonOMP"
 // --       generic parameters, requirements, key, extra
-// CHECK-SAME:   i32 1, i32 0, i32 1, i32 0
+// CHECK-SAME:   i16 1, i16 0, i16 1, i16 0
 // --       generic param
 // CHECK-SAME:   i8 -128,
 // CHECK-SAME: }>
diff --git a/test/IRGen/enum_function.sil b/test/IRGen/enum_function.sil
index 36a9b86..571ca11b 100644
--- a/test/IRGen/enum_function.sil
+++ b/test/IRGen/enum_function.sil
@@ -16,7 +16,7 @@
 // CHECK-32:  define hidden swiftcc void @test1([[WORD:i32]], [[WORD]])
 sil hidden @test1 : $@convention(thin) (@owned Optional<() -> ()>) -> () {
 bb0(%0 : $Optional<() -> ()>):
-  // CHECK: call void @"$SSqWy"
+  // CHECK: call void @"$SIey_SgWy"
   retain_value %0 : $Optional<() -> ()>
 
   // CHECK: icmp eq i64 %0, 0
diff --git a/test/IRGen/enum_resilience.swift b/test/IRGen/enum_resilience.swift
index 7c3393a..3d9c2c1 100644
--- a/test/IRGen/enum_resilience.swift
+++ b/test/IRGen/enum_resilience.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
 // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
diff --git a/test/IRGen/foreign_types.sil b/test/IRGen/foreign_types.sil
index da66e54..b82a51f 100644
--- a/test/IRGen/foreign_types.sil
+++ b/test/IRGen/foreign_types.sil
@@ -16,8 +16,7 @@
 // CHECK-SAME: @"$SSo12AmazingColorVMa"
 
 // CHECK-LABEL: @"$SSo14HasNestedUnionV18__Unnamed_struct_sVN" = linkonce_odr hidden global
-// CHECK-SAME:  [[INT:i[0-9]+]] sub ([[INT]] ptrtoint
-// CHECK-SAME:  [[INT]] 0,
+// CHECK-SAME:  [[INT:i[0-9]+]] 0,
 // CHECK-SAME:  @"$SSo14HasNestedUnionV18__Unnamed_struct_sVWV"
 // CHECK-SAME:  [[INT]] 1,
 // CHECK-SAME:  @"$SSo14HasNestedUnionV18__Unnamed_struct_sVMn"
diff --git a/test/IRGen/generic_classes.sil b/test/IRGen/generic_classes.sil
index 7b55b34..935367d 100644
--- a/test/IRGen/generic_classes.sil
+++ b/test/IRGen/generic_classes.sil
@@ -34,7 +34,7 @@
 // --       template instantiation pattern
 // CHECK-SAME:   @"$S15generic_classes11RootGenericCMP"
 // --       generic parameters, requirements, key arguments, extra arguments
-// CHECK-SAME:   i32 1, i32 0, i32 1, i32 0
+// CHECK-SAME:   i16 1, i16 0, i16 1, i16 0
 // --       vtable offset
 // CHECK-SAME:   i32 11,
 // --       vtable size
diff --git a/test/IRGen/generic_classes_objc.sil b/test/IRGen/generic_classes_objc.sil
index 9823a83..6343d41 100644
--- a/test/IRGen/generic_classes_objc.sil
+++ b/test/IRGen/generic_classes_objc.sil
@@ -69,6 +69,6 @@
 protocol P2 { }
 
 // CHECK: @"$S20generic_classes_objc16Generic3WithReqsCMn" = hidden constant
-// CHECK-SAME: i32 3, i32 3, i32 3, i32 2
+// CHECK-SAME: i16 3, i16 3, i16 3, i16 2
 class Generic3WithReqs<T: P1, U: P2, V: P2> { }
-sil_vtable Generic3WithReqs { }
\ No newline at end of file
+sil_vtable Generic3WithReqs { }
diff --git a/test/IRGen/generic_metatypes.swift b/test/IRGen/generic_metatypes.swift
index fef162f..dfe740a 100644
--- a/test/IRGen/generic_metatypes.swift
+++ b/test/IRGen/generic_metatypes.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %swift -target x86_64-apple-macosx10.9 -emit-ir -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-64 %s
 // RUN: %swift -target i386-apple-ios7.0 -emit-ir -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-32 %s
 // RUN: %swift -target x86_64-apple-ios7.0 -emit-ir -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-64 %s
diff --git a/test/IRGen/generic_metatypes_arm.swift b/test/IRGen/generic_metatypes_arm.swift
index 58bfd76..5d7c1e6 100644
--- a/test/IRGen/generic_metatypes_arm.swift
+++ b/test/IRGen/generic_metatypes_arm.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %swift -target armv7-apple-ios7.0 -module-name generic_metatypes -emit-ir -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-32 %s
 // RUN: %swift -target arm64-apple-ios7.0 -emit-ir -module-name generic_metatypes -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-64 %s
 // RUN: %swift -target armv7-apple-tvos9.0 -emit-ir -module-name generic_metatypes -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-32 %s
diff --git a/test/IRGen/generic_structs.sil b/test/IRGen/generic_structs.sil
index c6b67a3..f76883c 100644
--- a/test/IRGen/generic_structs.sil
+++ b/test/IRGen/generic_structs.sil
@@ -50,7 +50,7 @@
 // CHECK-SAME:   [{{[0-9]+}} x i8*]* @"$S15generic_structs13SingleDynamicVMI"
 // CHECK-SAME:   @"$S15generic_structs13SingleDynamicVMP"
 // --       generic params, requirements, key args, extra args
-// CHECK-SAME:   i32 1, i32 0, i32 1, i32 0
+// CHECK-SAME:   i16 1, i16 0, i16 1, i16 0
 // --       generic parameters
 // CHECK-SAME:   <i8 0x80>
 // CHECK-SAME: }>
@@ -73,7 +73,7 @@
 // --       field offset vector offset
 // CHECK-SAME: i32 6,
 // --       generic params, requirements, key args, extra args
-// CHECK-SAME: i32 2, i32 2, i32 2, i32 2,
+// CHECK-SAME: i16 2, i16 2, i16 2, i16 2,
 // --       generic parameters
 // CHECK-SAME: <i8 0x80>, <i8 0x80>,
 // --       generic requirement
diff --git a/test/IRGen/generic_tuples.swift b/test/IRGen/generic_tuples.swift
index 9f2968d..2932a14 100644
--- a/test/IRGen/generic_tuples.swift
+++ b/test/IRGen/generic_tuples.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -primary-file %s | %FileCheck %s
 
 // Make sure that optimization passes don't choke on storage types for generic tuples
diff --git a/test/IRGen/generic_types.swift b/test/IRGen/generic_types.swift
index ec61a28..945ba35 100644
--- a/test/IRGen/generic_types.swift
+++ b/test/IRGen/generic_types.swift
@@ -32,13 +32,13 @@
 // -- instantiation pattern
 // CHECK-SAME:   @"$S13generic_types1ACMP"
 // -- num generic params
-// CHECK-SAME:   i32 1,
+// CHECK-SAME:   i16 1,
 // -- num generic requirement
-// CHECK-SAME:   i32 0,
+// CHECK-SAME:   i16 0,
 // -- num key arguments
-// CHECK-SAME:   i32 1,
+// CHECK-SAME:   i16 1,
 // -- num extra arguments
-// CHECK-SAME:   i32 0,
+// CHECK-SAME:   i16 0,
 // -- parameter descriptor 1
 // CHECK-SAME:   i8 -128,
 
diff --git a/test/IRGen/keypaths.sil b/test/IRGen/keypaths.sil
index 3c736a8..74b5f2e 100644
--- a/test/IRGen/keypaths.sil
+++ b/test/IRGen/keypaths.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // -- Convert <i32 0x...> constants to decimal constants that LLVM will print
 // RUN: %utils/chex.py < %s > %t/keypaths.sil
diff --git a/test/IRGen/keypaths_objc.sil b/test/IRGen/keypaths_objc.sil
index bd94794..3e6dd45 100644
--- a/test/IRGen/keypaths_objc.sil
+++ b/test/IRGen/keypaths_objc.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %utils/chex.py < %s > %t/keypaths_objc.sil
 // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-ir %t/keypaths_objc.sil | %FileCheck %t/keypaths_objc.sil --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize
diff --git a/test/IRGen/lazy_metadata.swift b/test/IRGen/lazy_metadata.swift
index 9085e70..3c4a7fe 100644
--- a/test/IRGen/lazy_metadata.swift
+++ b/test/IRGen/lazy_metadata.swift
@@ -13,13 +13,6 @@
 // CHECK-DAG: @"$S4test7StructDVMF" =
 // CHECK-DAG: @"$S4test7StructEVMF" =
 
-// value witness tables
-// CHECK-DAG: @"$S4test7StructAVWV" =
-// CHECK-DAG: @"$S4test7StructBVWV" =
-// CHECK-DAG: @"$S4test7StructCVWV" =
-// CHECK-DEAD-NOT: @"$S4test7StructDVWV"
-// CHECK-DAG: @"$S4test7StructEVWV" =
-
 // nominal type descriptors
 // CHECK-DAG: @"$S4test7StructAVMn" =
 // CHECK-DAG: @"$S4test7StructBVMn" =
diff --git a/test/IRGen/local_types.swift b/test/IRGen/local_types.swift
index 9ccc51c..b5579bb 100644
--- a/test/IRGen/local_types.swift
+++ b/test/IRGen/local_types.swift
@@ -9,14 +9,14 @@
 import local_types_helper
 
 public func singleFunc() {
-  // CHECK-DAG: @"$S11local_types10singleFuncyyF06SingleD6StructL_VWV" = internal constant
+  // CHECK-DAG: @"$S11local_types10singleFuncyyF06SingleD6StructL_VMf" = internal constant
   struct SingleFuncStruct {
     let i: Int
   }
 }
 
 public let singleClosure: () -> () = {
-  // CHECK-DAG: @"$S11local_types13singleClosureyycvpfiyycfU_06SingleD6StructL_VWV" = internal constant
+  // CHECK-DAG: @"$S11local_types13singleClosureyycvpfiyycfU_06SingleD6StructL_VMf" = internal constant
   struct SingleClosureStruct {
     let i: Int
   }
@@ -24,7 +24,7 @@
 
 public struct PatternStruct {
   public var singlePattern: Int = ({
-    // CHECK-DAG: @"$S11local_types13PatternStructV06singleC0SivpfiSiyXEfU_06SinglecD0L_VWV" = internal constant
+    // CHECK-DAG: @"$S11local_types13PatternStructV06singleC0SivpfiSiyXEfU_06SinglecD0L_VMf" = internal constant
     struct SinglePatternStruct {
       let i: Int
     }
@@ -33,7 +33,7 @@
 }
 
 public func singleDefaultArgument(i: Int = {
-  // CHECK-DAG: @"$S11local_types21singleDefaultArgument1iySi_tFfA_SiycfU_06SingledE6StructL_VWV" = internal constant
+  // CHECK-DAG: @"$S11local_types21singleDefaultArgument1iySi_tFfA_SiycfU_06SingledE6StructL_VMf" = internal constant
   struct SingleDefaultArgumentStruct {
     let i: Int
   }
diff --git a/test/IRGen/lowered_optional_self_metadata.sil b/test/IRGen/lowered_optional_self_metadata.sil
index 8f14c95..f60a4ab 100644
--- a/test/IRGen/lowered_optional_self_metadata.sil
+++ b/test/IRGen/lowered_optional_self_metadata.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir %s
 sil_stage canonical
 
diff --git a/test/IRGen/objc.swift b/test/IRGen/objc.swift
index 0a15e37..22bd2e8 100644
--- a/test/IRGen/objc.swift
+++ b/test/IRGen/objc.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-irgen-test-overlays
 // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s
diff --git a/test/IRGen/objc_retainAutoreleasedReturnValue.swift b/test/IRGen/objc_retainAutoreleasedReturnValue.swift
index 65c781c..ca06d42 100644
--- a/test/IRGen/objc_retainAutoreleasedReturnValue.swift
+++ b/test/IRGen/objc_retainAutoreleasedReturnValue.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -target x86_64-apple-macosx10.12 -assume-parsing-unqualified-ownership-sil -import-objc-header %S/Inputs/StaticInline.h %s -emit-ir | %FileCheck %s
 // RUN: %target-swift-frontend -O -target x86_64-apple-macosx10.12 -assume-parsing-unqualified-ownership-sil -import-objc-header %S/Inputs/StaticInline.h %s -emit-ir | %FileCheck %s --check-prefix=OPT
 
diff --git a/test/IRGen/plus_zero_big_types_corner_cases.swift b/test/IRGen/plus_zero_big_types_corner_cases.swift
index 05b8339..257dc49 100644
--- a/test/IRGen/plus_zero_big_types_corner_cases.swift
+++ b/test/IRGen/plus_zero_big_types_corner_cases.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -enable-large-loadable-types %s -emit-ir | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize
 // REQUIRES: optimized_stdlib
 // UNSUPPORTED: resilient_stdlib
diff --git a/test/IRGen/plus_zero_builtins.swift b/test/IRGen/plus_zero_builtins.swift
index b4479ad..4bb33e0 100644
--- a/test/IRGen/plus_zero_builtins.swift
+++ b/test/IRGen/plus_zero_builtins.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -parse-stdlib -primary-file %s -emit-ir -o - -disable-objc-attr-requires-foundation-module | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime
 
 // REQUIRES: CPU=x86_64
diff --git a/test/IRGen/plus_zero_class_bounded_generics.swift b/test/IRGen/plus_zero_class_bounded_generics.swift
index 304f545..6a536fd 100644
--- a/test/IRGen/plus_zero_class_bounded_generics.swift
+++ b/test/IRGen/plus_zero_class_bounded_generics.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -emit-ir -primary-file %s -disable-objc-attr-requires-foundation-module | %FileCheck %s
 
 // REQUIRES: CPU=x86_64
diff --git a/test/IRGen/plus_zero_enum_resilience.swift b/test/IRGen/plus_zero_enum_resilience.swift
index 8332486..599e35cb 100644
--- a/test/IRGen/plus_zero_enum_resilience.swift
+++ b/test/IRGen/plus_zero_enum_resilience.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
 // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
diff --git a/test/IRGen/plus_zero_generic_metatypes.swift b/test/IRGen/plus_zero_generic_metatypes.swift
index 0249939..0880594 100644
--- a/test/IRGen/plus_zero_generic_metatypes.swift
+++ b/test/IRGen/plus_zero_generic_metatypes.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %swift -target x86_64-apple-macosx10.9 -emit-ir -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-64 %s
 // RUN: %swift -target i386-apple-ios7.0 -emit-ir -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-32 %s
 // RUN: %swift -target x86_64-apple-ios7.0 -emit-ir -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-64 %s
diff --git a/test/IRGen/plus_zero_generic_metatypes_arm.swift b/test/IRGen/plus_zero_generic_metatypes_arm.swift
index ad87734..758ec0c 100644
--- a/test/IRGen/plus_zero_generic_metatypes_arm.swift
+++ b/test/IRGen/plus_zero_generic_metatypes_arm.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %swift -target armv7-apple-ios7.0 -module-name generic_metatypes -emit-ir -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-32 %s
 // RUN: %swift -target arm64-apple-ios7.0 -emit-ir -module-name generic_metatypes -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-64 %s
 // RUN: %swift -target armv7-apple-tvos9.0 -emit-ir -module-name generic_metatypes -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-32 %s
diff --git a/test/IRGen/plus_zero_generic_tuples.swift b/test/IRGen/plus_zero_generic_tuples.swift
index c45781d..3ca9a82 100644
--- a/test/IRGen/plus_zero_generic_tuples.swift
+++ b/test/IRGen/plus_zero_generic_tuples.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -primary-file %s | %FileCheck %s
 
 // Make sure that optimization passes don't choke on storage types for generic tuples
diff --git a/test/IRGen/plus_zero_keypaths.sil b/test/IRGen/plus_zero_keypaths.sil
index 7cafbd0..0f26931 100644
--- a/test/IRGen/plus_zero_keypaths.sil
+++ b/test/IRGen/plus_zero_keypaths.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // -- Convert <i32 0x...> constants to decimal constants that LLVM will print
 // RUN: %utils/chex.py < %s > %t/keypaths.sil
diff --git a/test/IRGen/plus_zero_keypaths_objc.sil b/test/IRGen/plus_zero_keypaths_objc.sil
index 1504309..3ef5026 100644
--- a/test/IRGen/plus_zero_keypaths_objc.sil
+++ b/test/IRGen/plus_zero_keypaths_objc.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %utils/chex.py < %s > %t/keypaths_objc.sil
 // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-ir %t/keypaths_objc.sil | %FileCheck %t/keypaths_objc.sil --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize
diff --git a/test/IRGen/plus_zero_lowered_optional_self_metadata.sil b/test/IRGen/plus_zero_lowered_optional_self_metadata.sil
index 005e8bb..6180497 100644
--- a/test/IRGen/plus_zero_lowered_optional_self_metadata.sil
+++ b/test/IRGen/plus_zero_lowered_optional_self_metadata.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir %s
 sil_stage canonical
 
diff --git a/test/IRGen/plus_zero_objc.swift b/test/IRGen/plus_zero_objc.swift
index 634a5a6..4a316d7 100644
--- a/test/IRGen/plus_zero_objc.swift
+++ b/test/IRGen/plus_zero_objc.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-irgen-test-overlays
 // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s
diff --git a/test/IRGen/plus_zero_objc_retainAutoreleasedReturnValue.swift b/test/IRGen/plus_zero_objc_retainAutoreleasedReturnValue.swift
index 67bf5d9..f4e530c 100644
--- a/test/IRGen/plus_zero_objc_retainAutoreleasedReturnValue.swift
+++ b/test/IRGen/plus_zero_objc_retainAutoreleasedReturnValue.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -target x86_64-apple-macosx10.12 -assume-parsing-unqualified-ownership-sil -import-objc-header %S/Inputs/StaticInline.h %s -emit-ir | %FileCheck %s
 // RUN: %target-swift-frontend -O -target x86_64-apple-macosx10.12 -assume-parsing-unqualified-ownership-sil -import-objc-header %S/Inputs/StaticInline.h %s -emit-ir | %FileCheck %s --check-prefix=OPT
 
diff --git a/test/IRGen/plus_zero_runtime_calling_conventions.swift b/test/IRGen/plus_zero_runtime_calling_conventions.swift
index 8322258..117a08d 100644
--- a/test/IRGen/plus_zero_runtime_calling_conventions.swift
+++ b/test/IRGen/plus_zero_runtime_calling_conventions.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -parse-as-library -emit-ir %s | %FileCheck %s
 // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -parse-as-library -O -emit-ir %s | %FileCheck --check-prefix=OPT-CHECK %s
 
diff --git a/test/IRGen/plus_zero_struct_resilience.swift b/test/IRGen/plus_zero_struct_resilience.swift
index 6f0bdf7..aa8a4ca 100644
--- a/test/IRGen/plus_zero_struct_resilience.swift
+++ b/test/IRGen/plus_zero_struct_resilience.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
 // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
diff --git a/test/IRGen/runtime_calling_conventions.swift b/test/IRGen/runtime_calling_conventions.swift
index 74ca835..96ab501 100644
--- a/test/IRGen/runtime_calling_conventions.swift
+++ b/test/IRGen/runtime_calling_conventions.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -parse-as-library -emit-ir %s | %FileCheck %s
 // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -parse-as-library -O -emit-ir %s | %FileCheck --check-prefix=OPT-CHECK %s
 
diff --git a/test/IRGen/struct_resilience.swift b/test/IRGen/struct_resilience.swift
index 2118662..bf2e4f1 100644
--- a/test/IRGen/struct_resilience.swift
+++ b/test/IRGen/struct_resilience.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
 // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
diff --git a/test/IRGen/weak.sil b/test/IRGen/weak.sil
index 6f23e84..178111b 100644
--- a/test/IRGen/weak.sil
+++ b/test/IRGen/weak.sil
@@ -77,7 +77,7 @@
 // CHECK-NEXT: store i8** [[TMPTAB]], i8*** [[T0]], align 8
 // CHECK-NEXT: [[T0:%.*]] = getelementptr inbounds { [[WEAK]], i8** }, { [[WEAK]], i8** }* [[X]], i32 0, i32 0
 // CHECK-NEXT: call [[WEAK]]* @swift_unknownWeakAssign([[WEAK]]* returned [[T0]], [[UNKNOWN]]* [[TMPOBJ]])
-// CHECK: call void @"$SSqWe"
+// CHECK: call void @"$S4weak1P_pSgWe"
 
 sil @test_weak_alloc_stack : $@convention(thin) (Optional<P>) -> () {
 bb0(%0 : $Optional<P>):
diff --git a/test/Interpreter/SDK/Foundation_test.swift b/test/Interpreter/SDK/Foundation_test.swift
index 50dfc96..f41b2a3 100644
--- a/test/Interpreter/SDK/Foundation_test.swift
+++ b/test/Interpreter/SDK/Foundation_test.swift
@@ -252,7 +252,7 @@
   let _: CFArrayEqualCallBack = { DarwinBoolean($0 == $1) }
 }
 
-#if os(OSX)
+#if os(macOS)
 FoundationTestSuite.test("NSRectEdge/constants") {
   // Check that the following constants have the correct type and value.
   //
diff --git a/test/Interpreter/SDK/c_pointers.swift b/test/Interpreter/SDK/c_pointers.swift
index f7f3657..c295c14 100644
--- a/test/Interpreter/SDK/c_pointers.swift
+++ b/test/Interpreter/SDK/c_pointers.swift
@@ -6,7 +6,7 @@
 // REQUIRES: objc_interop
 
 import Foundation
-#if os(OSX)
+#if os(macOS)
 import AppKit
 typealias XXColor = NSColor
 #endif
@@ -28,7 +28,7 @@
 let nsRed = XXColor(cgColor: cgRed)
 
 var r: CGFloat = 0.5, g: CGFloat = 0.5, b: CGFloat = 0.5, a: CGFloat = 0.5
-#if os(OSX)
+#if os(macOS)
 nsRed!.getRed(&r, green: &g, blue: &b, alpha: &a)
 #else
 nsRed.getRed(&r, green: &g, blue: &b, alpha: &a)
diff --git a/test/Interpreter/SDK/cf_extensions.swift b/test/Interpreter/SDK/cf_extensions.swift
index 57aa920..9dcc3cb 100644
--- a/test/Interpreter/SDK/cf_extensions.swift
+++ b/test/Interpreter/SDK/cf_extensions.swift
@@ -6,7 +6,7 @@
 import Foundation
 import StdlibUnittest
 
-#if os(OSX)
+#if os(macOS)
 import AppKit
 #endif
 
diff --git a/test/Interpreter/SDK/cf_type_bridging.swift b/test/Interpreter/SDK/cf_type_bridging.swift
index e755645..23dfa86 100644
--- a/test/Interpreter/SDK/cf_type_bridging.swift
+++ b/test/Interpreter/SDK/cf_type_bridging.swift
@@ -3,7 +3,7 @@
 
 // REQUIRES: objc_interop
 
-#if os(OSX)
+#if os(macOS)
 import AppKit
 #endif
 #if os(iOS) || os(tvOS) || os(watchOS)
diff --git a/test/Interpreter/SDK/libc.swift b/test/Interpreter/SDK/libc.swift
index 13a0e17..0e1dd7d 100644
--- a/test/Interpreter/SDK/libc.swift
+++ b/test/Interpreter/SDK/libc.swift
@@ -9,7 +9,7 @@
 // TODO: rdar://problem/33388782
 // REQUIRES: CPU=x86_64
 
-#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
+#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
   import Darwin
 #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
   import Glibc
diff --git a/test/Interpreter/SDK/objc_ns_enum.swift b/test/Interpreter/SDK/objc_ns_enum.swift
index e125436..b2c5d1d 100644
--- a/test/Interpreter/SDK/objc_ns_enum.swift
+++ b/test/Interpreter/SDK/objc_ns_enum.swift
@@ -8,7 +8,7 @@
 // strict checking if we get a guarantee that certain types don't have
 // hidden or future enumeration values.)
 
-#if os(OSX)
+#if os(macOS)
 import AppKit
 
 print(NSButtonType(rawValue: 20721)!.rawValue)
diff --git a/test/Migrator/Inputs/Cities.swift b/test/Migrator/Inputs/Cities.swift
index 76dcf4f..b863417 100644
--- a/test/Migrator/Inputs/Cities.swift
+++ b/test/Migrator/Inputs/Cities.swift
@@ -10,7 +10,7 @@
   open func noosa() -> [[String : Cities]?] { return [] }
   open func maroochy(x: Int?, y: Int?) {}
   public struct CityKind {
-    static public let Town = 1
+    public static let Town = 1
   }
 }
 
diff --git a/test/Parse/ConditionalCompilation/basicIdentity.swift b/test/Parse/ConditionalCompilation/basicIdentity.swift
index 14072e7..a067063 100644
--- a/test/Parse/ConditionalCompilation/basicIdentity.swift
+++ b/test/Parse/ConditionalCompilation/basicIdentity.swift
@@ -63,3 +63,9 @@
 var w = Foo()
 #endif
 var x = w
+
+// Test os(macOS) as well
+#if os(macOS)
+var y = Foo()
+#endif
+var z = y
diff --git a/test/PrintAsObjC/accessibility.swift b/test/PrintAsObjC/accessibility.swift
index bbe7d07..e509860 100644
--- a/test/PrintAsObjC/accessibility.swift
+++ b/test/PrintAsObjC/accessibility.swift
@@ -37,7 +37,7 @@
 
 
 #if MAIN
-#if os(OSX)
+#if os(macOS)
 import AppKit
 
 @NSApplicationMain
diff --git a/test/Reflection/capture_descriptors.sil b/test/Reflection/capture_descriptors.sil
index 5630624..86325f8 100644
--- a/test/Reflection/capture_descriptors.sil
+++ b/test/Reflection/capture_descriptors.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // REQUIRES: no_asan
 // RUN: %empty-directory(%t)
 // RUN: %target-build-swift %s -emit-module -emit-library -module-name capture_descriptors -o %t/capture_descriptors.%target-dylib-extension
diff --git a/test/Reflection/plus_zero_capture_descriptors.sil b/test/Reflection/plus_zero_capture_descriptors.sil
index dab2c61..937feb6 100644
--- a/test/Reflection/plus_zero_capture_descriptors.sil
+++ b/test/Reflection/plus_zero_capture_descriptors.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // REQUIRES: no_asan
 // RUN: %empty-directory(%t)
 // RUN: %target-build-swift %s -emit-module -emit-library -module-name capture_descriptors -o %t/capture_descriptors.%target-dylib-extension
diff --git a/test/Runtime/demangleToMetadata.swift b/test/Runtime/demangleToMetadata.swift
index 6ea0fc0..a2a8c1a 100644
--- a/test/Runtime/demangleToMetadata.swift
+++ b/test/Runtime/demangleToMetadata.swift
@@ -68,7 +68,7 @@
 
   // Ownership parameters.
   expectEqual(type(of: f1_shared), _typeByMangledName("yyyXlhc")!)
-  expectEqual(type(of: f1_owned), _typeByMangledName("yyyXlc")!)
+  expectEqual(type(of: f1_owned), _typeByMangledName("yyyXlnc")!)
 
   // Mix-and-match.
   expectEqual(type(of: f2_variadic_inout), _typeByMangledName("yyytd_ytztc")!)
diff --git a/test/SIL/Parser/apply_with_substitution.sil b/test/SIL/Parser/apply_with_substitution.sil
index bce0544..2e8b7ff 100644
--- a/test/SIL/Parser/apply_with_substitution.sil
+++ b/test/SIL/Parser/apply_with_substitution.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend %s -emit-silgen | %FileCheck %s
 
 // rdar://14443287
diff --git a/test/SIL/Parser/bound_generic.sil b/test/SIL/Parser/bound_generic.sil
index 73e681b..91022a8 100644
--- a/test/SIL/Parser/bound_generic.sil
+++ b/test/SIL/Parser/bound_generic.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend %s -emit-silgen | %FileCheck %s
 
 // rdar://14443287
diff --git a/test/SIL/Parser/generic_signature_with_depth.swift b/test/SIL/Parser/generic_signature_with_depth.swift
index 6dc1e51..5e1ebee 100644
--- a/test/SIL/Parser/generic_signature_with_depth.swift
+++ b/test/SIL/Parser/generic_signature_with_depth.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend %s -emit-silgen | %target-sil-opt | %FileCheck %s
 
 protocol mmGeneratorType {
diff --git a/test/SIL/Parser/keypath.sil b/test/SIL/Parser/keypath.sil
index f2dad3d..6c90dec 100644
--- a/test/SIL/Parser/keypath.sil
+++ b/test/SIL/Parser/keypath.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-sil-opt %s | %target-sil-opt | %FileCheck %s
 
 sil_stage canonical
diff --git a/test/SIL/Parser/plus_zero_apply_with_substitution.sil b/test/SIL/Parser/plus_zero_apply_with_substitution.sil
index a63e3c0..287d85e 100644
--- a/test/SIL/Parser/plus_zero_apply_with_substitution.sil
+++ b/test/SIL/Parser/plus_zero_apply_with_substitution.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend %s -emit-silgen | %FileCheck %s
 
 // rdar://14443287
diff --git a/test/SIL/Parser/plus_zero_bound_generic.sil b/test/SIL/Parser/plus_zero_bound_generic.sil
index c535ee7..2d054ac 100644
--- a/test/SIL/Parser/plus_zero_bound_generic.sil
+++ b/test/SIL/Parser/plus_zero_bound_generic.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend %s -emit-silgen | %FileCheck %s
 
 // rdar://14443287
diff --git a/test/SIL/Parser/plus_zero_generic_signature_with_depth.swift b/test/SIL/Parser/plus_zero_generic_signature_with_depth.swift
index f25a2a4..a3699f9 100644
--- a/test/SIL/Parser/plus_zero_generic_signature_with_depth.swift
+++ b/test/SIL/Parser/plus_zero_generic_signature_with_depth.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend %s -emit-silgen | %target-sil-opt | %FileCheck %s
 
 protocol mmGeneratorType {
diff --git a/test/SIL/Parser/plus_zero_keypath.sil b/test/SIL/Parser/plus_zero_keypath.sil
index 7c9b0a0..7b94b57 100644
--- a/test/SIL/Parser/plus_zero_keypath.sil
+++ b/test/SIL/Parser/plus_zero_keypath.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-sil-opt %s | %target-sil-opt | %FileCheck %s
 
 sil_stage canonical
diff --git a/test/SIL/Serialization/deserialize_generic.sil b/test/SIL/Serialization/deserialize_generic.sil
index 4d22ac5..97bb1a1 100644
--- a/test/SIL/Serialization/deserialize_generic.sil
+++ b/test/SIL/Serialization/deserialize_generic.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_generic.swift
 // RUN: %target-sil-opt -assume-parsing-unqualified-ownership-sil -linker -I %t %s | %FileCheck %s
diff --git a/test/SIL/Serialization/deserialize_generic_marker.sil b/test/SIL/Serialization/deserialize_generic_marker.sil
index b63ef5c..5910f05 100644
--- a/test/SIL/Serialization/deserialize_generic_marker.sil
+++ b/test/SIL/Serialization/deserialize_generic_marker.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_generic_marker.swift
 // RUN: %target-sil-opt -assume-parsing-unqualified-ownership-sil -linker -I %t %s | %FileCheck %s
diff --git a/test/SIL/Serialization/keypath.sil b/test/SIL/Serialization/keypath.sil
index 73a927d..0a5a404 100644
--- a/test/SIL/Serialization/keypath.sil
+++ b/test/SIL/Serialization/keypath.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // First parse this and then emit a *.sib. Then read in the *.sib, then recreate
 // RUN: %empty-directory(%t)
 // RUN: %target-sil-opt %s -emit-sib -o %t/tmp.sib -module-name boxes
diff --git a/test/SIL/Serialization/plus_zero_deserialize_generic.sil b/test/SIL/Serialization/plus_zero_deserialize_generic.sil
index d8aa071..10a9db5 100644
--- a/test/SIL/Serialization/plus_zero_deserialize_generic.sil
+++ b/test/SIL/Serialization/plus_zero_deserialize_generic.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_generic.swift
 // RUN: %target-sil-opt -assume-parsing-unqualified-ownership-sil -linker -I %t %s | %FileCheck %s
diff --git a/test/SIL/Serialization/plus_zero_deserialize_generic_marker.sil b/test/SIL/Serialization/plus_zero_deserialize_generic_marker.sil
index bb3984d..53a1ccd 100644
--- a/test/SIL/Serialization/plus_zero_deserialize_generic_marker.sil
+++ b/test/SIL/Serialization/plus_zero_deserialize_generic_marker.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_generic_marker.swift
 // RUN: %target-sil-opt -assume-parsing-unqualified-ownership-sil -linker -I %t %s | %FileCheck %s
diff --git a/test/SIL/Serialization/plus_zero_keypath.sil b/test/SIL/Serialization/plus_zero_keypath.sil
index 00a9747..7f9a33f 100644
--- a/test/SIL/Serialization/plus_zero_keypath.sil
+++ b/test/SIL/Serialization/plus_zero_keypath.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // First parse this and then emit a *.sib. Then read in the *.sib, then recreate
 // RUN: %empty-directory(%t)
 // RUN: %target-sil-opt %s -emit-sib -o %t/tmp.sib -module-name boxes
diff --git a/test/SILGen/access_marker_gen.swift b/test/SILGen/access_marker_gen.swift
index 974aa66..ed41275 100644
--- a/test/SILGen/access_marker_gen.swift
+++ b/test/SILGen/access_marker_gen.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -parse-as-library -Xllvm -sil-full-demangle -enforce-exclusivity=checked -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name access_marker_gen -parse-as-library -Xllvm -sil-full-demangle -enforce-exclusivity=checked -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func modify<T>(_ x: inout T) {}
 
diff --git a/test/SILGen/accessors.swift b/test/SILGen/accessors.swift
index 5a85c8d..fc78f69 100644
--- a/test/SILGen/accessors.swift
+++ b/test/SILGen/accessors.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name accessors -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 // Hold a reference to do to magically become non-POD.
 class Reference {}
diff --git a/test/SILGen/address_only_types.swift b/test/SILGen/address_only_types.swift
index bc02604..36702e5 100644
--- a/test/SILGen/address_only_types.swift
+++ b/test/SILGen/address_only_types.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -parse-as-library -parse-stdlib -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name address_only_types -enable-sil-ownership -parse-as-library -parse-stdlib -emit-silgen %s | %FileCheck %s
 
 precedencegroup AssignmentPrecedence { assignment: true }
 
diff --git a/test/SILGen/addressors.swift b/test/SILGen/addressors.swift
index a1186cd..c6d654c 100644
--- a/test/SILGen/addressors.swift
+++ b/test/SILGen/addressors.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -emit-sil %s | %FileCheck %s
 // RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -emit-silgen %s | %FileCheck %s -check-prefix=SILGEN
 // RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -emit-ir %s
diff --git a/test/SILGen/apply_abstraction_nested.swift b/test/SILGen/apply_abstraction_nested.swift
index 6ea71bd..e4b2f7f 100644
--- a/test/SILGen/apply_abstraction_nested.swift
+++ b/test/SILGen/apply_abstraction_nested.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -enable-sil-ownership -emit-silgen %s | %FileCheck %s
 
 infix operator ~> { precedence 255 associativity left }
diff --git a/test/SILGen/argument_labels.swift b/test/SILGen/argument_labels.swift
index 4702392..0297dc2 100644
--- a/test/SILGen/argument_labels.swift
+++ b/test/SILGen/argument_labels.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name argument_labels -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 public struct X { }
 public struct Y { }
diff --git a/test/SILGen/argument_shuffle_swift3.swift b/test/SILGen/argument_shuffle_swift3.swift
index d28323c..9f7877e 100644
--- a/test/SILGen/argument_shuffle_swift3.swift
+++ b/test/SILGen/argument_shuffle_swift3.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s -swift-version 3 | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name argument_shuffle_swift3 -emit-silgen -enable-sil-ownership %s -swift-version 3 | %FileCheck %s
 
 func fn(_: Any) {}
 
diff --git a/test/SILGen/array_literal_abstraction.swift b/test/SILGen/array_literal_abstraction.swift
index 074cf18..98c34d8 100644
--- a/test/SILGen/array_literal_abstraction.swift
+++ b/test/SILGen/array_literal_abstraction.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name array_literal_abstraction -emit-silgen %s | %FileCheck %s
 
 // Verify that reabstraction happens when forming container literals.
 // <rdar://problem/16039286>
diff --git a/test/SILGen/auto_closures.swift b/test/SILGen/auto_closures.swift
index f87040c..0d9eab3 100644
--- a/test/SILGen/auto_closures.swift
+++ b/test/SILGen/auto_closures.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -parse-stdlib -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name auto_closures  -parse-stdlib -emit-silgen %s | %FileCheck %s
 
 struct Bool {}
 var false_ = Bool()
diff --git a/test/SILGen/borrow.swift b/test/SILGen/borrow.swift
index 35c3c73..e6b0fb1 100644
--- a/test/SILGen/borrow.swift
+++ b/test/SILGen/borrow.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name borrow -enable-sil-ownership -parse-stdlib -emit-silgen %s | %FileCheck %s
 
 import Swift
 
diff --git a/test/SILGen/boxed_existentials.swift b/test/SILGen/boxed_existentials.swift
index 92210e8..f9f213c 100644
--- a/test/SILGen/boxed_existentials.swift
+++ b/test/SILGen/boxed_existentials.swift
@@ -1,6 +1,7 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen %s | %FileCheck %s
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen %s | %FileCheck %s --check-prefix=GUARANTEED
+
+// RUN: %target-swift-frontend -module-name boxed_existentials -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name boxed_existentials -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen %s | %FileCheck %s --check-prefix=GUARANTEED
 
 func test_type_lowering(_ x: Error) { }
 // CHECK-LABEL: sil hidden @$S18boxed_existentials18test_type_loweringyys5Error_pF : $@convention(thin) (@owned Error) -> () {
diff --git a/test/SILGen/call_chain_reabstraction.swift b/test/SILGen/call_chain_reabstraction.swift
index bca5a66..3dbc0fc 100644
--- a/test/SILGen/call_chain_reabstraction.swift
+++ b/test/SILGen/call_chain_reabstraction.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name call_chain_reabstraction -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 struct A {
         func g<U>(_ recur: (A, U) -> U) -> (A, U) -> U {
diff --git a/test/SILGen/capture_typed_boxes.swift b/test/SILGen/capture_typed_boxes.swift
index 50a806e..c903cc3 100644
--- a/test/SILGen/capture_typed_boxes.swift
+++ b/test/SILGen/capture_typed_boxes.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name capture_typed_boxes -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func foo(_ x: Int) -> () -> Int {
   var x = x
diff --git a/test/SILGen/casts.swift b/test/SILGen/casts.swift
index 74e7718..b7f9571 100644
--- a/test/SILGen/casts.swift
+++ b/test/SILGen/casts.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name casts -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 class B { }
 class D : B { }
diff --git a/test/SILGen/cf.swift b/test/SILGen/cf.swift
index ebc2c23..acb26e3 100644
--- a/test/SILGen/cf.swift
+++ b/test/SILGen/cf.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -import-cf-types -sdk %S/Inputs %s -emit-silgen -o - | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name cf -import-cf-types -sdk %S/Inputs %s -emit-silgen -o - | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/class_bound_protocols.swift b/test/SILGen/class_bound_protocols.swift
index b190ced..d402d77 100644
--- a/test/SILGen/class_bound_protocols.swift
+++ b/test/SILGen/class_bound_protocols.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -parse-stdlib -parse-as-library -module-name Swift -emit-silgen %s | %FileCheck %s
 
 enum Optional<T> {
diff --git a/test/SILGen/class_resilience.swift b/test/SILGen/class_resilience.swift
index e821bc5..e3b12a8 100644
--- a/test/SILGen/class_resilience.swift
+++ b/test/SILGen/class_resilience.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
 // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift
-// RUN: %target-swift-frontend -I %t -emit-silgen -enable-sil-ownership -enable-resilience %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name class_resilience -I %t -emit-silgen -enable-sil-ownership -enable-resilience %s | %FileCheck %s
 
 import resilient_class
 
diff --git a/test/SILGen/closures.swift b/test/SILGen/closures.swift
index ca0d033..ef46636 100644
--- a/test/SILGen/closures.swift
+++ b/test/SILGen/closures.swift
@@ -1,6 +1,7 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s
-// RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -parse-as-library -emit-silgen  %s | %FileCheck %s --check-prefix=GUARANTEED
+
+// RUN: %target-swift-frontend -module-name closures -enable-sil-ownership -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name closures -enable-sil-ownership -parse-stdlib -parse-as-library -emit-silgen  %s | %FileCheck %s --check-prefix=GUARANTEED
 
 import Swift
 
diff --git a/test/SILGen/collection_downcast.swift b/test/SILGen/collection_downcast.swift
index b3768d4..abd6e92 100644
--- a/test/SILGen/collection_downcast.swift
+++ b/test/SILGen/collection_downcast.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name collection_downcast -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/collection_subtype_downcast.swift b/test/SILGen/collection_subtype_downcast.swift
index 821115f..65eb897 100644
--- a/test/SILGen/collection_subtype_downcast.swift
+++ b/test/SILGen/collection_subtype_downcast.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -sdk %S/Inputs %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name collection_subtype_downcast -emit-silgen -enable-sil-ownership -sdk %S/Inputs %s | %FileCheck %s
 
 struct S { var x, y: Int }
 
diff --git a/test/SILGen/collection_subtype_upcast.swift b/test/SILGen/collection_subtype_upcast.swift
index d6d4ad9..9608b1c 100644
--- a/test/SILGen/collection_subtype_upcast.swift
+++ b/test/SILGen/collection_subtype_upcast.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -sdk %S/Inputs %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name collection_subtype_upcast -emit-silgen -enable-sil-ownership -sdk %S/Inputs %s | %FileCheck %s
 
 struct S { var x, y: Int }
 
diff --git a/test/SILGen/collection_upcast.swift b/test/SILGen/collection_upcast.swift
index faecb5b..b9f7dea 100644
--- a/test/SILGen/collection_upcast.swift
+++ b/test/SILGen/collection_upcast.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name collection_upcast -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
 
 // FIXME: rdar://problem/19648117 Needs splitting objc parts out
 // XFAIL: linux
diff --git a/test/SILGen/constrained_extensions.swift b/test/SILGen/constrained_extensions.swift
index f6e8418..ae97751 100644
--- a/test/SILGen/constrained_extensions.swift
+++ b/test/SILGen/constrained_extensions.swift
@@ -1,7 +1,8 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -primary-file %s | %FileCheck %s
-// RUN: %target-swift-frontend -emit-sil -O -primary-file %s > /dev/null
-// RUN: %target-swift-frontend -emit-ir -primary-file %s > /dev/null
+
+// RUN: %target-swift-frontend -module-name constrained_extensions -emit-silgen -enable-sil-ownership -primary-file %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name constrained_extensions -emit-sil -O -primary-file %s > /dev/null
+// RUN: %target-swift-frontend -module-name constrained_extensions -emit-ir -primary-file %s > /dev/null
 
 extension Array where Element == Int {
   // CHECK-LABEL: sil @$SSa22constrained_extensionsSiRszlE1xSaySiGyt_tcfC : $@convention(method) (@thin Array<Int>.Type) -> @owned Array<Int>
diff --git a/test/SILGen/default_arguments.swift b/test/SILGen/default_arguments.swift
index ad11d44..19b85af 100644
--- a/test/SILGen/default_arguments.swift
+++ b/test/SILGen/default_arguments.swift
@@ -1,9 +1,10 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 3 %s | %FileCheck %s
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 3 %s | %FileCheck %s --check-prefix=NEGATIVE
 
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 4 %s | %FileCheck %s
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 4 %s | %FileCheck %s --check-prefix=NEGATIVE
+// RUN: %target-swift-frontend -module-name default_arguments -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 3 %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name default_arguments -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 3 %s | %FileCheck %s --check-prefix=NEGATIVE
+
+// RUN: %target-swift-frontend -module-name default_arguments -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 4 %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name default_arguments -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 4 %s | %FileCheck %s --check-prefix=NEGATIVE
 
 // __FUNCTION__ used as top-level parameter produces the module name.
 // CHECK-LABEL: sil @main
diff --git a/test/SILGen/default_arguments_generic.swift b/test/SILGen/default_arguments_generic.swift
index 4755f22..47eee51 100644
--- a/test/SILGen/default_arguments_generic.swift
+++ b/test/SILGen/default_arguments_generic.swift
@@ -1,6 +1,7 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -swift-version 3 %s | %FileCheck %s
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -swift-version 4 %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name default_arguments_generic -emit-silgen -enable-sil-ownership -swift-version 3 %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name default_arguments_generic -emit-silgen -enable-sil-ownership -swift-version 4 %s | %FileCheck %s
 
 func foo<T: ExpressibleByIntegerLiteral>(_: T.Type, x: T = 0) { }
 
diff --git a/test/SILGen/default_arguments_serialized.swift b/test/SILGen/default_arguments_serialized.swift
index 2308dcd..c606585 100644
--- a/test/SILGen/default_arguments_serialized.swift
+++ b/test/SILGen/default_arguments_serialized.swift
@@ -1,12 +1,13 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module-path %t/default_arguments_other.swiftmodule -emit-module -swift-version 4 -primary-file %S/Inputs/default_arguments_other.swift
 
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 3 -I %t %s | %FileCheck %s --check-prefix=SWIFT3 --check-prefix=CHECK
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 4 -I %t %s | %FileCheck %s --check-prefix=SWIFT4 --check-prefix=CHECK
+// RUN: %target-swift-frontend -module-name default_arguments_serialized -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 3 -I %t %s | %FileCheck %s --check-prefix=SWIFT3 --check-prefix=CHECK
+// RUN: %target-swift-frontend -module-name default_arguments_serialized -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 4 -I %t %s | %FileCheck %s --check-prefix=SWIFT4 --check-prefix=CHECK
 
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-sil -O -swift-version 3 -I %t %s | %FileCheck %s --check-prefix=OPT
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-sil -O -swift-version 4 -I %t %s | %FileCheck %s --check-prefix=OPT
+// RUN: %target-swift-frontend -module-name default_arguments_serialized -Xllvm -sil-full-demangle -enable-sil-ownership -emit-sil -O -swift-version 3 -I %t %s | %FileCheck %s --check-prefix=OPT
+// RUN: %target-swift-frontend -module-name default_arguments_serialized -Xllvm -sil-full-demangle -enable-sil-ownership -emit-sil -O -swift-version 4 -I %t %s | %FileCheck %s --check-prefix=OPT
 
 // Check that default arguments are serialized in Swift 4 mode.
 
diff --git a/test/SILGen/dependent_member_lowering.swift b/test/SILGen/dependent_member_lowering.swift
index 86aad55..61c6e5e 100644
--- a/test/SILGen/dependent_member_lowering.swift
+++ b/test/SILGen/dependent_member_lowering.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name dependent_member_lowering -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 protocol P {
   associatedtype A
diff --git a/test/SILGen/downcast_reabstraction.swift b/test/SILGen/downcast_reabstraction.swift
index 3a07b17..539edca 100644
--- a/test/SILGen/downcast_reabstraction.swift
+++ b/test/SILGen/downcast_reabstraction.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name downcast_reabstraction -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 // CHECK-LABEL: sil hidden @$S22downcast_reabstraction19condFunctionFromAnyyyypF
 // CHECK:         checked_cast_addr_br take_always Any in [[IN:%.*]] : $*Any to () -> () in [[OUT:%.*]] : $*@callee_guaranteed (@in ()) -> @out (), [[YES:bb[0-9]+]], [[NO:bb[0-9]+]]
diff --git a/test/SILGen/dynamic.swift b/test/SILGen/dynamic.swift
index 49806ca..80d40f0 100644
--- a/test/SILGen/dynamic.swift
+++ b/test/SILGen/dynamic.swift
@@ -1,9 +1,10 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-silgen-test-overlays
 
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -emit-silgen | %FileCheck %s
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -emit-sil -verify
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name dynamic -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -emit-silgen | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name dynamic -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -emit-sil -verify
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/dynamic_lookup.swift b/test/SILGen/dynamic_lookup.swift
index b55f1f0..d670188 100644
--- a/test/SILGen/dynamic_lookup.swift
+++ b/test/SILGen/dynamic_lookup.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module %s | %FileCheck %s
 // RUN: %target-swift-frontend -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module  %s | %FileCheck %s --check-prefix=GUARANTEED
 
diff --git a/test/SILGen/dynamic_lookup_throws.swift b/test/SILGen/dynamic_lookup_throws.swift
index 178909d..78678d0 100644
--- a/test/SILGen/dynamic_lookup_throws.swift
+++ b/test/SILGen/dynamic_lookup_throws.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-clang-importer-objc-overlays
 
diff --git a/test/SILGen/dynamic_self.swift b/test/SILGen/dynamic_self.swift
index fc284ae..6a1ec20 100644
--- a/test/SILGen/dynamic_self.swift
+++ b/test/SILGen/dynamic_self.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module | %FileCheck %s
 // RUN: %target-swift-frontend -emit-sil -O %s -disable-objc-attr-requires-foundation-module
 // RUN: %target-swift-frontend -emit-ir %s -disable-objc-attr-requires-foundation-module
diff --git a/test/SILGen/enum.swift b/test/SILGen/enum.swift
index f16ea12..e4c577f 100644
--- a/test/SILGen/enum.swift
+++ b/test/SILGen/enum.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -parse-stdlib -parse-as-library -emit-silgen -enable-sil-ownership -module-name Swift %s | %FileCheck %s
 
 precedencegroup AssignmentPrecedence { assignment: true }
diff --git a/test/SILGen/enum_resilience.swift b/test/SILGen/enum_resilience.swift
index d2f2145..b0482b7 100644
--- a/test/SILGen/enum_resilience.swift
+++ b/test/SILGen/enum_resilience.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
 // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
-// RUN: %target-swift-frontend -I %t -enable-sil-ownership -emit-silgen -enable-resilience %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name enum_resilience -I %t -enable-sil-ownership -emit-silgen -enable-resilience %s | %FileCheck %s
 
 import resilient_enum
 
diff --git a/test/SILGen/erasure_reabstraction.swift b/test/SILGen/erasure_reabstraction.swift
index 10c6e39..5535eb6 100644
--- a/test/SILGen/erasure_reabstraction.swift
+++ b/test/SILGen/erasure_reabstraction.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 struct Foo {}
diff --git a/test/SILGen/existential_erasure.swift b/test/SILGen/existential_erasure.swift
index 15bf015..f1e31e5 100644
--- a/test/SILGen/existential_erasure.swift
+++ b/test/SILGen/existential_erasure.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name existential_erasure -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 protocol P {
   func downgrade(_ m68k: Bool) -> Self
diff --git a/test/SILGen/expressions.swift b/test/SILGen/expressions.swift
index 6de0dea..60d6424 100644
--- a/test/SILGen/expressions.swift
+++ b/test/SILGen/expressions.swift
@@ -1,7 +1,8 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: echo "public var x = Int()" | %target-swift-frontend -module-name FooBar -emit-module -o %t -
-// RUN: %target-swift-frontend -parse-stdlib -emit-silgen -enable-sil-ownership %s -I%t -disable-access-control | %FileCheck %s
+// RUN: %target-swift-frontend -parse-stdlib -module-name expressions -emit-silgen -enable-sil-ownership %s -I%t -disable-access-control | %FileCheck %s
 
 import Swift
 import FooBar
diff --git a/test/SILGen/extensions_objc.swift b/test/SILGen/extensions_objc.swift
index 7015fa7..3dada50 100644
--- a/test/SILGen/extensions_objc.swift
+++ b/test/SILGen/extensions_objc.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -sdk %S/Inputs %s -I %S/Inputs -enable-source-import -emit-silgen -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name extensions_objc -sdk %S/Inputs %s -I %S/Inputs -enable-source-import -emit-silgen -enable-sil-ownership | %FileCheck %s
 //
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/external_definitions.swift b/test/SILGen/external_definitions.swift
index e7a1090..6b216f8 100644
--- a/test/SILGen/external_definitions.swift
+++ b/test/SILGen/external_definitions.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -sdk %S/Inputs %s -emit-silgen -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: objc_interop
diff --git a/test/SILGen/final.swift b/test/SILGen/final.swift
index dd24729..07322f7 100644
--- a/test/SILGen/final.swift
+++ b/test/SILGen/final.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name final -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 class TestClass {
 
diff --git a/test/SILGen/force_cast_chained_optional.swift b/test/SILGen/force_cast_chained_optional.swift
index 2eae970..bdb9775 100644
--- a/test/SILGen/force_cast_chained_optional.swift
+++ b/test/SILGen/force_cast_chained_optional.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name force_cast_chained_optional -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 class Foo {
   var bar: Bar!
diff --git a/test/SILGen/foreach.swift b/test/SILGen/foreach.swift
index 6dd219b..663f72f 100644
--- a/test/SILGen/foreach.swift
+++ b/test/SILGen/foreach.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name foreach -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 //////////////////
 // Declarations //
diff --git a/test/SILGen/foreign_errors.swift b/test/SILGen/foreign_errors.swift
index 65bc729..368db04 100644
--- a/test/SILGen/foreign_errors.swift
+++ b/test/SILGen/foreign_errors.swift
@@ -1,7 +1,8 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-clang-importer-objc-overlays
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-silgen -parse-as-library %s | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -module-name foreign_errors -emit-silgen -parse-as-library %s | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/function_conversion.swift b/test/SILGen/function_conversion.swift
index 2266959..05bc743 100644
--- a/test/SILGen/function_conversion.swift
+++ b/test/SILGen/function_conversion.swift
@@ -1,6 +1,7 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -primary-file %s | %FileCheck %s
-// RUN: %target-swift-frontend -emit-ir -enable-sil-ownership -primary-file %s
+
+// RUN: %target-swift-frontend -module-name function_conversion -emit-silgen -enable-sil-ownership -primary-file %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name function_conversion -emit-ir -enable-sil-ownership -primary-file %s
 
 // Check SILGen against various FunctionConversionExprs emitted by Sema.
 
diff --git a/test/SILGen/function_conversion_objc.swift b/test/SILGen/function_conversion_objc.swift
index fcd20ec..fa2853c 100644
--- a/test/SILGen/function_conversion_objc.swift
+++ b/test/SILGen/function_conversion_objc.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -sdk %S/Inputs %s -I %S/Inputs -enable-sil-ownership -enable-source-import -emit-silgen -verify | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name function_conversion_objc -sdk %S/Inputs %s -I %S/Inputs -enable-sil-ownership -enable-source-import -emit-silgen -verify | %FileCheck %s
 
 import Foundation
 
diff --git a/test/SILGen/functions.swift b/test/SILGen/functions.swift
index bc02381..c306c53 100644
--- a/test/SILGen/functions.swift
+++ b/test/SILGen/functions.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name functions -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 import Swift // just for Optional
 
diff --git a/test/SILGen/generic_casts.swift b/test/SILGen/generic_casts.swift
index 56d6d8d..a69f69d 100644
--- a/test/SILGen/generic_casts.swift
+++ b/test/SILGen/generic_casts.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-runtime %s
+
+// RUN: %target-swift-frontend -module-name generic_casts -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-runtime %s
 
 protocol ClassBound : class {}
 protocol NotClassBound {}
diff --git a/test/SILGen/generic_closures.swift b/test/SILGen/generic_closures.swift
index 7cabd10..c0ff38f 100644
--- a/test/SILGen/generic_closures.swift
+++ b/test/SILGen/generic_closures.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -parse-stdlib -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name generic_closures  -parse-stdlib -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 import Swift
 
diff --git a/test/SILGen/generic_property_base_lifetime.swift b/test/SILGen/generic_property_base_lifetime.swift
index 7338fee..b4670a7 100644
--- a/test/SILGen/generic_property_base_lifetime.swift
+++ b/test/SILGen/generic_property_base_lifetime.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name generic_property_base_lifetime -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
 
 protocol ProtocolA: class {
     var intProp: Int { get set }
diff --git a/test/SILGen/generic_tuples.swift b/test/SILGen/generic_tuples.swift
index c2330dd..fa6423e 100644
--- a/test/SILGen/generic_tuples.swift
+++ b/test/SILGen/generic_tuples.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -parse-as-library -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name generic_tuples -emit-silgen -parse-as-library -enable-sil-ownership %s | %FileCheck %s
 
 
 func dup<T>(_ x: T) -> (T, T) { return (x,x) }
diff --git a/test/SILGen/generic_witness.swift b/test/SILGen/generic_witness.swift
index 98dfffe..db10dae 100644
--- a/test/SILGen/generic_witness.swift
+++ b/test/SILGen/generic_witness.swift
@@ -1,6 +1,7 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
-// RUN: %target-swift-frontend -emit-ir -enable-sil-ownership %s
+
+// RUN: %target-swift-frontend -module-name generic_witness -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name generic_witness -emit-ir -enable-sil-ownership %s
 
 protocol Runcible {
   func runce<A>(_ x: A)
diff --git a/test/SILGen/guaranteed_normal_args.swift b/test/SILGen/guaranteed_normal_args.swift
index 250a763..b06fd68 100644
--- a/test/SILGen/guaranteed_normal_args.swift
+++ b/test/SILGen/guaranteed_normal_args.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -parse-as-library -module-name Swift -parse-stdlib -emit-silgen -enable-sil-ownership -enable-guaranteed-normal-arguments %s | %FileCheck %s
 
 // This test checks specific codegen related to normal arguments being passed at
diff --git a/test/SILGen/guaranteed_self.swift b/test/SILGen/guaranteed_self.swift
index 02e4524..efa45ba 100644
--- a/test/SILGen/guaranteed_self.swift
+++ b/test/SILGen/guaranteed_self.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name guaranteed_self -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
 
 protocol Fooable {
   init()
diff --git a/test/SILGen/if_while_binding.swift b/test/SILGen/if_while_binding.swift
index 9564b01..43284d8 100644
--- a/test/SILGen/if_while_binding.swift
+++ b/test/SILGen/if_while_binding.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name if_while_binding -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func foo() -> String? { return "" }
 func bar() -> String? { return "" }
diff --git a/test/SILGen/implicitly_unwrapped_optional.swift b/test/SILGen/implicitly_unwrapped_optional.swift
index 5307d7f..45a6417 100644
--- a/test/SILGen/implicitly_unwrapped_optional.swift
+++ b/test/SILGen/implicitly_unwrapped_optional.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name implicitly_unwrapped_optional -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func foo(f f: (() -> ())!) {
   var f: (() -> ())! = f
diff --git a/test/SILGen/indirect_enum.swift b/test/SILGen/indirect_enum.swift
index b384995..cf42307 100644
--- a/test/SILGen/indirect_enum.swift
+++ b/test/SILGen/indirect_enum.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-print-debuginfo -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name indirect_enum -Xllvm -sil-print-debuginfo -emit-silgen %s | %FileCheck %s
 
 indirect enum TreeA<T> {
   case Nil
diff --git a/test/SILGen/inlineable_attribute.swift b/test/SILGen/inlineable_attribute.swift
index 747abcc..b6edb9b 100644
--- a/test/SILGen/inlineable_attribute.swift
+++ b/test/SILGen/inlineable_attribute.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -emit-verbose-sil %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name inlineable_attribute -emit-silgen -enable-sil-ownership -emit-verbose-sil %s | %FileCheck %s
 
 // CHECK-LABEL: sil [serialized] @$S20inlineable_attribute15fragileFunctionyyF : $@convention(thin) () -> ()
 @_inlineable public func fragileFunction() {
diff --git a/test/SILGen/inlineable_attribute_objc.swift b/test/SILGen/inlineable_attribute_objc.swift
index a7ff8d5..c106aec 100644
--- a/test/SILGen/inlineable_attribute_objc.swift
+++ b/test/SILGen/inlineable_attribute_objc.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-silgen-test-overlays
 
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -sil-full-demangle -primary-file %s -emit-silgen | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name inlineable_attribute_objc -Xllvm -sil-full-demangle -primary-file %s -emit-silgen | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/keypath_application.swift b/test/SILGen/keypath_application.swift
index 66a8fb7..5d93636 100644
--- a/test/SILGen/keypath_application.swift
+++ b/test/SILGen/keypath_application.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 class A {}
diff --git a/test/SILGen/keypaths.swift b/test/SILGen/keypaths.swift
index 55fc6ab..156fa2f 100644
--- a/test/SILGen/keypaths.swift
+++ b/test/SILGen/keypaths.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name keypaths -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 struct S<T> {
   var x: T
diff --git a/test/SILGen/let_decls.swift b/test/SILGen/let_decls.swift
index 493c2db..10b7de2 100644
--- a/test/SILGen/let_decls.swift
+++ b/test/SILGen/let_decls.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name let_decls -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func takeClosure(_ a : () -> Int) {}
 
diff --git a/test/SILGen/lifetime.swift b/test/SILGen/lifetime.swift
index 1700a7f..4bf882e 100644
--- a/test/SILGen/lifetime.swift
+++ b/test/SILGen/lifetime.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -parse-as-library -emit-silgen -primary-file %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name lifetime -Xllvm -sil-full-demangle -parse-as-library -emit-silgen -primary-file %s | %FileCheck %s
 
 struct Buh<T> {
   var x: Int {
diff --git a/test/SILGen/mangling.swift b/test/SILGen/mangling.swift
index 6fffed4..28d0764 100644
--- a/test/SILGen/mangling.swift
+++ b/test/SILGen/mangling.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name mangling -Xllvm -sil-full-demangle -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/materializeForSet.swift b/test/SILGen/materializeForSet.swift
index be4c1a4..b407618 100644
--- a/test/SILGen/materializeForSet.swift
+++ b/test/SILGen/materializeForSet.swift
@@ -1,6 +1,7 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
-// RUN: %target-swift-frontend -emit-silgen -enforce-exclusivity=unchecked %s | %FileCheck --check-prefix=UNCHECKED %s
+
+// RUN: %target-swift-frontend -module-name materializeForSet -emit-silgen %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name materializeForSet -emit-silgen -enforce-exclusivity=unchecked %s | %FileCheck --check-prefix=UNCHECKED %s
 
 class Base {
   var stored: Int = 0
diff --git a/test/SILGen/metatype_abstraction.swift b/test/SILGen/metatype_abstraction.swift
index 1ee4e9d..4854874 100644
--- a/test/SILGen/metatype_abstraction.swift
+++ b/test/SILGen/metatype_abstraction.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -module-name Swift -parse-stdlib %s | %FileCheck %s
 
 enum Optional<Wrapped> {
diff --git a/test/SILGen/multi_file.swift b/test/SILGen/multi_file.swift
index 9be3c89..5974625 100644
--- a/test/SILGen/multi_file.swift
+++ b/test/SILGen/multi_file.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -primary-file %s %S/Inputs/multi_file_helper.swift | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name multi_file -emit-silgen -enable-sil-ownership -primary-file %s %S/Inputs/multi_file_helper.swift | %FileCheck %s
 
 func markUsed<T>(_ t: T) {}
 
diff --git a/test/SILGen/nested_generics.swift b/test/SILGen/nested_generics.swift
index b639d7d..f63c3aa 100644
--- a/test/SILGen/nested_generics.swift
+++ b/test/SILGen/nested_generics.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-silgen  -parse-as-library %s | %FileCheck %s
-// RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-sil -parse-as-library %s > /dev/null
-// RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-sil -O -parse-as-library %s > /dev/null
-// RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-ir -parse-as-library %s > /dev/null
+
+// RUN: %target-swift-frontend -module-name nested_generics -enable-sil-ownership -Xllvm -sil-full-demangle -emit-silgen  -parse-as-library %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name nested_generics -enable-sil-ownership -Xllvm -sil-full-demangle -emit-sil -parse-as-library %s > /dev/null
+// RUN: %target-swift-frontend -module-name nested_generics -enable-sil-ownership -Xllvm -sil-full-demangle -emit-sil -O -parse-as-library %s > /dev/null
+// RUN: %target-swift-frontend -module-name nested_generics -enable-sil-ownership -Xllvm -sil-full-demangle -emit-ir -parse-as-library %s > /dev/null
 
 // TODO:
 // - test generated SIL -- mostly we're just testing mangling here
diff --git a/test/SILGen/nested_types_referencing_nested_functions.swift b/test/SILGen/nested_types_referencing_nested_functions.swift
index d6a8d6d..122a787 100644
--- a/test/SILGen/nested_types_referencing_nested_functions.swift
+++ b/test/SILGen/nested_types_referencing_nested_functions.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name nested_types_referencing_nested_functions -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 do {
   func foo() { bar(2) }
diff --git a/test/SILGen/newtype.swift b/test/SILGen/newtype.swift
index 1f7b6f2..3d47dcc 100644
--- a/test/SILGen/newtype.swift
+++ b/test/SILGen/newtype.swift
@@ -1,7 +1,8 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import  %s | %FileCheck %s -check-prefix=CHECK-RAW
 
-// RUN: %target-swift-frontend -emit-sil -sdk %S/Inputs -I %S/Inputs -enable-source-import  %s | %FileCheck %s -check-prefix=CHECK-CANONICAL
+// RUN: %target-swift-frontend -module-name newtype -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import  %s | %FileCheck %s -check-prefix=CHECK-RAW
+
+// RUN: %target-swift-frontend -module-name newtype -emit-sil -sdk %S/Inputs -I %S/Inputs -enable-source-import  %s | %FileCheck %s -check-prefix=CHECK-CANONICAL
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/noescape_reabstraction.swift b/test/SILGen/noescape_reabstraction.swift
index 4bfeb40..87de7be 100644
--- a/test/SILGen/noescape_reabstraction.swift
+++ b/test/SILGen/noescape_reabstraction.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name noescape_reabstraction -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 struct S {}
 
diff --git a/test/SILGen/objc_attr_NSManaged.swift b/test/SILGen/objc_attr_NSManaged.swift
index 0a60635..5c4c456 100644
--- a/test/SILGen/objc_attr_NSManaged.swift
+++ b/test/SILGen/objc_attr_NSManaged.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -sdk %S/Inputs %s -I %S/Inputs -enable-source-import -emit-silgen -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name objc_attr_NSManaged -sdk %S/Inputs %s -I %S/Inputs -enable-source-import -emit-silgen -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/objc_attr_NSManaged_multi.swift b/test/SILGen/objc_attr_NSManaged_multi.swift
index 9b4f085..60c475a 100644
--- a/test/SILGen/objc_attr_NSManaged_multi.swift
+++ b/test/SILGen/objc_attr_NSManaged_multi.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -sdk %S/Inputs -primary-file %s %S/objc_attr_NSManaged.swift -I %S/Inputs -enable-source-import -emit-silgen -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name objc_attr_NSManaged_multi -sdk %S/Inputs -primary-file %s %S/objc_attr_NSManaged.swift -I %S/Inputs -enable-source-import -emit-silgen -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/objc_blocks_bridging.swift b/test/SILGen/objc_blocks_bridging.swift
index 8984176..720e32f 100644
--- a/test/SILGen/objc_blocks_bridging.swift
+++ b/test/SILGen/objc_blocks_bridging.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-silgen-test-overlays
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -verify -emit-silgen -I %S/Inputs -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -verify -emit-silgen -I %S/Inputs -disable-objc-attr-requires-foundation-module -enable-sil-ownership  %s | %FileCheck %s --check-prefix=GUARANTEED
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_blocks_bridging -verify -emit-silgen -I %S/Inputs -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_blocks_bridging -verify -emit-silgen -I %S/Inputs -disable-objc-attr-requires-foundation-module -enable-sil-ownership  %s | %FileCheck %s --check-prefix=GUARANTEED
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/objc_bridged_results.swift b/test/SILGen/objc_bridged_results.swift
index 94c6cbb..048c43f 100644
--- a/test/SILGen/objc_bridged_results.swift
+++ b/test/SILGen/objc_bridged_results.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-silgen-test-overlays
 
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-silgen %s -Xllvm -sil-print-debuginfo -import-objc-header %S/Inputs/objc_bridged_results.h -enable-sil-ownership | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_bridged_results -emit-silgen %s -Xllvm -sil-print-debuginfo -import-objc-header %S/Inputs/objc_bridged_results.h -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/objc_bridging.swift b/test/SILGen/objc_bridging.swift
index 28b2ed6..7f64255 100644
--- a/test/SILGen/objc_bridging.swift
+++ b/test/SILGen/objc_bridging.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-silgen-test-overlays
 // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-module -o %t -I %S/../Inputs/ObjCBridging %S/../Inputs/ObjCBridging/Appliances.swift
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -I %S/../Inputs/ObjCBridging -Xllvm -sil-full-demangle -emit-silgen %s -enable-sil-ownership | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-cpu --check-prefix=CHECK-%target-os-%target-cpu
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_bridging -I %S/../Inputs/ObjCBridging -Xllvm -sil-full-demangle -emit-silgen %s -enable-sil-ownership | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-cpu --check-prefix=CHECK-%target-os-%target-cpu
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/objc_bridging_any.swift b/test/SILGen/objc_bridging_any.swift
index 3ca525e..efcb643 100644
--- a/test/SILGen/objc_bridging_any.swift
+++ b/test/SILGen/objc_bridging_any.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -Xllvm -sil-print-debuginfo -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name objc_bridging_any -Xllvm -sil-print-debuginfo -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 // REQUIRES: objc_interop
 
 import Foundation
diff --git a/test/SILGen/objc_bridging_peephole.swift b/test/SILGen/objc_bridging_peephole.swift
index 09954bb..642625d 100644
--- a/test/SILGen/objc_bridging_peephole.swift
+++ b/test/SILGen/objc_bridging_peephole.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name objc_bridging_peephole -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 // REQUIRES: objc_interop
 
 import Foundation
diff --git a/test/SILGen/objc_currying.swift b/test/SILGen/objc_currying.swift
index 036ca8c..77ef9ad 100644
--- a/test/SILGen/objc_currying.swift
+++ b/test/SILGen/objc_currying.swift
@@ -1,7 +1,8 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-silgen-test-overlays
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -enable-sil-ownership -emit-silgen %s | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_currying -enable-sil-ownership -emit-silgen %s | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/objc_dictionary_bridging.swift b/test/SILGen/objc_dictionary_bridging.swift
index 74dd95e..80dd5ca 100644
--- a/test/SILGen/objc_dictionary_bridging.swift
+++ b/test/SILGen/objc_dictionary_bridging.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-silgen-test-overlays
 
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_dictionary_bridging -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/objc_error.swift b/test/SILGen/objc_error.swift
index b9ee4d3..2c524db 100644
--- a/test/SILGen/objc_error.swift
+++ b/test/SILGen/objc_error.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-clang-importer-objc-overlays
 
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -module-name objc_error -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/objc_extensions.swift b/test/SILGen/objc_extensions.swift
index 639b8aa..b124177 100644
--- a/test/SILGen/objc_extensions.swift
+++ b/test/SILGen/objc_extensions.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -emit-silgen -sdk %S/Inputs/ -I %S/Inputs -enable-source-import %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name objc_extensions -enable-sil-ownership -emit-silgen -sdk %S/Inputs/ -I %S/Inputs -enable-source-import %s | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/objc_imported_generic.swift b/test/SILGen/objc_imported_generic.swift
index 586aea6..b0b6960 100644
--- a/test/SILGen/objc_imported_generic.swift
+++ b/test/SILGen/objc_imported_generic.swift
@@ -1,7 +1,8 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen %s -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name objc_imported_generic -emit-silgen %s -enable-sil-ownership | %FileCheck %s
 // For integration testing, ensure we get through IRGen too.
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-ir -verify -DIRGEN_INTEGRATION_TEST %s
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name objc_imported_generic -emit-ir -verify -DIRGEN_INTEGRATION_TEST %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/objc_ownership_conventions.swift b/test/SILGen/objc_ownership_conventions.swift
index ec991b6..98a9003 100644
--- a/test/SILGen/objc_ownership_conventions.swift
+++ b/test/SILGen/objc_ownership_conventions.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name objc_ownership_conventions -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/objc_protocol_native_thunk.swift b/test/SILGen/objc_protocol_native_thunk.swift
index bde4e32..43db289 100644
--- a/test/SILGen/objc_protocol_native_thunk.swift
+++ b/test/SILGen/objc_protocol_native_thunk.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/objc_protocols.swift b/test/SILGen/objc_protocols.swift
index 15a0ed2..96474cb 100644
--- a/test/SILGen/objc_protocols.swift
+++ b/test/SILGen/objc_protocols.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name objc_protocols -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/objc_set_bridging.swift b/test/SILGen/objc_set_bridging.swift
index 5e79cfd..b53285a 100644
--- a/test/SILGen/objc_set_bridging.swift
+++ b/test/SILGen/objc_set_bridging.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-silgen-test-overlays
 
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-silgen %s -enable-sil-ownership | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_set_bridging -emit-silgen %s -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/objc_thunks.swift b/test/SILGen/objc_thunks.swift
index f6f8d3f..8d5e75b 100644
--- a/test/SILGen/objc_thunks.swift
+++ b/test/SILGen/objc_thunks.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -Xllvm -sil-print-debuginfo -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -emit-verbose-sil -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name objc_thunks -Xllvm -sil-full-demangle -Xllvm -sil-print-debuginfo -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -emit-verbose-sil -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/opaque_ownership.swift b/test/SILGen/opaque_ownership.swift
index a1a1921..fb5d712 100644
--- a/test/SILGen/opaque_ownership.swift
+++ b/test/SILGen/opaque_ownership.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -enable-sil-opaque-values -enable-sil-ownership -emit-sorted-sil -Xllvm -sil-full-demangle -emit-silgen -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck %s
 // RUN: %target-swift-frontend -target x86_64-apple-macosx10.9 -enable-sil-opaque-values -enable-sil-ownership -emit-sorted-sil -Xllvm -sil-full-demangle -emit-silgen -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck --check-prefix=CHECK-OSX %s
 
@@ -171,7 +172,7 @@
   case minus
 }
 
-#if os(OSX)
+#if os(macOS)
 // Test open_existential_value used in a conversion context.
 // (the actual bridging call is dropped because we don't import Swift).
 // ---
@@ -196,7 +197,7 @@
 
 public protocol Error {}
 
-#if os(OSX)
+#if os(macOS)
 // Test open_existential_box_value in a conversion context.
 // ---
 // CHECK-OSX-LABEL: sil @$Ss3foo1eys5Error_pSg_tF : $@convention(thin) (@owned Optional<Error>) -> () {
diff --git a/test/SILGen/opaque_values_silgen.swift b/test/SILGen/opaque_values_silgen.swift
index 6c9931b..acc52b3 100644
--- a/test/SILGen/opaque_values_silgen.swift
+++ b/test/SILGen/opaque_values_silgen.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -enable-sil-opaque-values -emit-sorted-sil -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime
 
 // UNSUPPORTED: resilient_stdlib
diff --git a/test/SILGen/opaque_values_silgen_lib.swift b/test/SILGen/opaque_values_silgen_lib.swift
index 3d69099..e33eb51 100644
--- a/test/SILGen/opaque_values_silgen_lib.swift
+++ b/test/SILGen/opaque_values_silgen_lib.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -enable-sil-ownership -enable-sil-opaque-values -emit-sorted-sil -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -emit-silgen -module-name Swift %s | %FileCheck %s
 // UNSUPPORTED: resilient_stdlib
 
diff --git a/test/SILGen/optional-cast.swift b/test/SILGen/optional-cast.swift
index 6a1c2f7..003a597 100644
--- a/test/SILGen/optional-cast.swift
+++ b/test/SILGen/optional-cast.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 class A {}
diff --git a/test/SILGen/optional.swift b/test/SILGen/optional.swift
index 3cc67b5..383c755 100644
--- a/test/SILGen/optional.swift
+++ b/test/SILGen/optional.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name optional -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func testCall(_ f: (() -> ())?) {
   f?()
diff --git a/test/SILGen/optional_lvalue.swift b/test/SILGen/optional_lvalue.swift
index 153200f..06934da 100644
--- a/test/SILGen/optional_lvalue.swift
+++ b/test/SILGen/optional_lvalue.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name optional_lvalue -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 // CHECK-LABEL: sil hidden @$S15optional_lvalue07assign_a1_B0yySiSgz_SitF
 // CHECK:         [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<Int>
diff --git a/test/SILGen/owned.swift b/test/SILGen/owned.swift
index bee04be..9b4e12a 100644
--- a/test/SILGen/owned.swift
+++ b/test/SILGen/owned.swift
@@ -22,3 +22,9 @@
         let r = ref
     }
 }
+
+// rdar://problem/38390524
+// CHECK-LABEL: sil hidden @$S5owned19oneUnnamedArgument1yyAA14ValueAggregateVnF : $@convention(thin) (@owned ValueAggregate) -> () {
+func oneUnnamedArgument1(_: __owned ValueAggregate) {}
+// CHECK-LABEL: sil hidden @$S5owned19oneUnnamedArgument2yyAA12RefAggregateCnF : $@convention(thin) (@owned RefAggregate) -> () {
+func oneUnnamedArgument2(_: __owned RefAggregate) {}
diff --git a/test/SILGen/partial_apply_generic.swift b/test/SILGen/partial_apply_generic.swift
index 94c032c..fd94aff 100644
--- a/test/SILGen/partial_apply_generic.swift
+++ b/test/SILGen/partial_apply_generic.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name partial_apply_generic -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 protocol Panda {
   associatedtype Cuddles : Foo
diff --git a/test/SILGen/partial_apply_protocol.swift b/test/SILGen/partial_apply_protocol.swift
index 60e3e0d..1c8310b 100644
--- a/test/SILGen/partial_apply_protocol.swift
+++ b/test/SILGen/partial_apply_protocol.swift
@@ -1,6 +1,7 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -emit-silgen -primary-file %s | %FileCheck %s
-// RUN: %target-swift-frontend -enable-sil-ownership -emit-ir -primary-file %s
+
+// RUN: %target-swift-frontend -module-name partial_apply_protocol -enable-sil-ownership -emit-silgen -primary-file %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name partial_apply_protocol -enable-sil-ownership -emit-ir -primary-file %s
 
 protocol Clonable {
   func clone() -> Self
diff --git a/test/SILGen/partial_apply_protocol_class_refinement_method.swift b/test/SILGen/partial_apply_protocol_class_refinement_method.swift
index ca2450c..d53fbc2 100644
--- a/test/SILGen/partial_apply_protocol_class_refinement_method.swift
+++ b/test/SILGen/partial_apply_protocol_class_refinement_method.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name partial_apply_protocol_class_refinement_method -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 protocol P { func foo() }
 protocol Q: class, P {}
diff --git a/test/SILGen/partial_apply_super.swift b/test/SILGen/partial_apply_super.swift
index 685ee8c..74e6533 100644
--- a/test/SILGen/partial_apply_super.swift
+++ b/test/SILGen/partial_apply_super.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_struct.swiftmodule -module-name resilient_struct %S/../Inputs/resilient_struct.swift
 // RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_class.swiftmodule -module-name resilient_class %S/../Inputs/resilient_class.swift
-// RUN: %target-swift-frontend -enable-resilience -emit-silgen -parse-as-library -I %t %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name partial_apply_super -enable-resilience -emit-silgen -parse-as-library -I %t %s | %FileCheck %s
 
 import resilient_class
 
diff --git a/test/SILGen/pgo_checked_cast.swift b/test/SILGen/pgo_checked_cast.swift
index 41db5fd..2f5afcb 100644
--- a/test/SILGen/pgo_checked_cast.swift
+++ b/test/SILGen/pgo_checked_cast.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-build-swift %s -profile-generate -Xfrontend -disable-incremental-llvm-codegen -module-name pgo_checked_cast -o %t/main
 // RUN: env LLVM_PROFILE_FILE=%t/default.profraw %target-run %t/main
diff --git a/test/SILGen/pgo_switchenum.swift b/test/SILGen/pgo_switchenum.swift
index 9978fa6..65966dc 100644
--- a/test/SILGen/pgo_switchenum.swift
+++ b/test/SILGen/pgo_switchenum.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-build-swift %s -profile-generate -Xfrontend -disable-incremental-llvm-codegen -module-name pgo_switchenum -o %t/main
 // RUN: env LLVM_PROFILE_FILE=%t/default.profraw %target-run %t/main
diff --git a/test/SILGen/plus_zero_access_marker_gen.swift b/test/SILGen/plus_zero_access_marker_gen.swift
index 6781648..ee71398 100644
--- a/test/SILGen/plus_zero_access_marker_gen.swift
+++ b/test/SILGen/plus_zero_access_marker_gen.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -parse-as-library -Xllvm -sil-full-demangle -enforce-exclusivity=checked -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name access_marker_gen -parse-as-library -Xllvm -sil-full-demangle -enforce-exclusivity=checked -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func modify<T>(_ x: inout T) {}
 
diff --git a/test/SILGen/plus_zero_accessors.swift b/test/SILGen/plus_zero_accessors.swift
index 47ebf94..814e0ee 100644
--- a/test/SILGen/plus_zero_accessors.swift
+++ b/test/SILGen/plus_zero_accessors.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name accessors -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 // Hold a reference to do to magically become non-POD.
 class Reference {}
@@ -64,9 +65,8 @@
 // CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]]
 
 // CHECK:    [[WRITEBACK]]([[CALLBACK_ADDR:%.*]] : @trivial $Builtin.RawPointer):
-// CHECK-NEXT: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout A, @thick A.Type) -> ()
+// CHECK-NEXT: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed A, @thick A.Type) -> ()
 // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $A
-// SEMANTIC SIL TODO: This is an issue caused by the callback for materializeForSet in the class case taking the value as @inout when it should really take it as @guaranteed.
 // CHECK-NEXT: store_borrow [[ARG]] to [[TEMP2]] : $*A
 // CHECK-NEXT: [[T0:%.*]] = metatype $@thick A.Type
 // CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[ADDR]] : $*OrdinarySub to $Builtin.RawPointer
@@ -121,7 +121,7 @@
 // CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]]
 //
 // CHECK:    [[WRITEBACK]]([[CALLBACK_ADDR:%.*]] : @trivial $Builtin.RawPointer):
-// CHECK-NEXT: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout B, @thick B.Type) -> ()
+// CHECK-NEXT: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed B, @thick B.Type) -> ()
 // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $B
 // CHECK-NEXT: store_borrow [[ARG]] to [[TEMP2]] : $*B
 // CHECK-NEXT: [[T0:%.*]] = metatype $@thick B.Type
@@ -147,7 +147,7 @@
 // CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]]
 //
 // CHECK:    [[WRITEBACK]]([[CALLBACK_ADDR:%.*]] : @trivial $Builtin.RawPointer):
-// CHECK-NEXT: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout B, @thick B.Type) -> ()
+// CHECK-NEXT: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed B, @thick B.Type) -> ()
 // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $B
 // CHECK-NEXT: store_borrow [[ARG]] to [[TEMP2]] : $*B
 // CHECK-NEXT: [[T0:%.*]] = metatype $@thick B.Type
diff --git a/test/SILGen/plus_zero_address_only_types.swift b/test/SILGen/plus_zero_address_only_types.swift
index e270074..878219f 100644
--- a/test/SILGen/plus_zero_address_only_types.swift
+++ b/test/SILGen/plus_zero_address_only_types.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -parse-as-library -parse-stdlib -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name address_only_types -enable-sil-ownership -parse-as-library -parse-stdlib -emit-silgen %s | %FileCheck %s
 
 precedencegroup AssignmentPrecedence { assignment: true }
 
diff --git a/test/SILGen/plus_zero_addressors.swift b/test/SILGen/plus_zero_addressors.swift
index 0a02140..6dbf9ca 100644
--- a/test/SILGen/plus_zero_addressors.swift
+++ b/test/SILGen/plus_zero_addressors.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -emit-sil %s | %FileCheck %s
 // RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -emit-silgen %s | %FileCheck %s -check-prefix=SILGEN
 // RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -emit-ir %s
@@ -355,7 +356,7 @@
 // CHECK:   strong_release [[OWNER]] : $Builtin.NativeObject
 
 //   materializeForSet callback for G.value
-// CHECK-LABEL: sil private [transparent] @$S10addressors1GC5values5Int32VvmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout G, @thick G.Type) -> () {
+// CHECK-LABEL: sil private [transparent] @$S10addressors1GC5values5Int32VvmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed G, @thick G.Type) -> () {
 // CHECK: bb0([[BUFFER:%0]] : $Builtin.RawPointer, [[STORAGE:%1]] : $*Builtin.UnsafeValueBuffer, [[SELF:%2]] : $*G, [[SELFTYPE:%3]] : $@thick G.Type):
 // CHECK:   [[T0:%.*]] = project_value_buffer $Builtin.NativeObject in [[STORAGE]] : $*Builtin.UnsafeValueBuffer
 // CHECK:   [[OWNER:%.*]] = load [[T0]]
@@ -476,7 +477,7 @@
 // CHECK:   strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject>
 
 //   materializeForSet callback for I.value
-// CHECK-LABEL: sil private [transparent] @$S10addressors1IC5values5Int32VvmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout I, @thick I.Type) -> () {
+// CHECK-LABEL: sil private [transparent] @$S10addressors1IC5values5Int32VvmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed I, @thick I.Type) -> () {
 // CHECK: bb0([[BUFFER:%0]] : $Builtin.RawPointer, [[STORAGE:%1]] : $*Builtin.UnsafeValueBuffer, [[SELF:%2]] : $*I, [[SELFTYPE:%3]] : $@thick I.Type):
 // CHECK:   [[T0:%.*]] = project_value_buffer $Optional<Builtin.NativeObject> in [[STORAGE]] : $*Builtin.UnsafeValueBuffer
 // CHECK:   [[OWNER:%.*]] = load [[T0]]
diff --git a/test/SILGen/plus_zero_apply_abstraction_nested.swift b/test/SILGen/plus_zero_apply_abstraction_nested.swift
index f1143d9..89d75eb 100644
--- a/test/SILGen/plus_zero_apply_abstraction_nested.swift
+++ b/test/SILGen/plus_zero_apply_abstraction_nested.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -enable-sil-ownership -emit-silgen %s | %FileCheck %s
 
 infix operator ~> { precedence 255 associativity left }
diff --git a/test/SILGen/plus_zero_argument_labels.swift b/test/SILGen/plus_zero_argument_labels.swift
index 95bb1d6..8ea28c8 100644
--- a/test/SILGen/plus_zero_argument_labels.swift
+++ b/test/SILGen/plus_zero_argument_labels.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name argument_labels -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 public struct X { }
 public struct Y { }
diff --git a/test/SILGen/plus_zero_argument_shuffle_swift3.swift b/test/SILGen/plus_zero_argument_shuffle_swift3.swift
index d76bb29..7cdda82 100644
--- a/test/SILGen/plus_zero_argument_shuffle_swift3.swift
+++ b/test/SILGen/plus_zero_argument_shuffle_swift3.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s -swift-version 3 | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name argument_shuffle_swift3 -emit-silgen -enable-sil-ownership %s -swift-version 3 | %FileCheck %s
 
 func fn(_: Any) {}
 
diff --git a/test/SILGen/plus_zero_array_literal_abstraction.swift b/test/SILGen/plus_zero_array_literal_abstraction.swift
index d7f1e36..57e6b6d 100644
--- a/test/SILGen/plus_zero_array_literal_abstraction.swift
+++ b/test/SILGen/plus_zero_array_literal_abstraction.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name array_literal_abstraction -emit-silgen %s | %FileCheck %s
 
 // Verify that reabstraction happens when forming container literals.
 // <rdar://problem/16039286>
diff --git a/test/SILGen/plus_zero_auto_closures.swift b/test/SILGen/plus_zero_auto_closures.swift
index 0adc57e..2fffe7a 100644
--- a/test/SILGen/plus_zero_auto_closures.swift
+++ b/test/SILGen/plus_zero_auto_closures.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -parse-stdlib -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name auto_closures  -parse-stdlib -emit-silgen %s | %FileCheck %s
 
 struct Bool {}
 var false_ = Bool()
diff --git a/test/SILGen/plus_zero_borrow.swift b/test/SILGen/plus_zero_borrow.swift
index 5dcec6f..43a128e 100644
--- a/test/SILGen/plus_zero_borrow.swift
+++ b/test/SILGen/plus_zero_borrow.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name borrow -enable-sil-ownership -parse-stdlib -emit-silgen %s | %FileCheck %s
 
 import Swift
 
diff --git a/test/SILGen/plus_zero_boxed_existentials.swift b/test/SILGen/plus_zero_boxed_existentials.swift
index 70b4197..2a544be 100644
--- a/test/SILGen/plus_zero_boxed_existentials.swift
+++ b/test/SILGen/plus_zero_boxed_existentials.swift
@@ -1,6 +1,7 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen %s | %FileCheck %s
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen %s | %FileCheck %s --check-prefix=GUARANTEED
+
+// RUN: %target-swift-frontend -module-name boxed_existentials -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name boxed_existentials -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen %s | %FileCheck %s --check-prefix=GUARANTEED
 
 func test_type_lowering(_ x: Error) { }
 // CHECK-LABEL: sil hidden @$S18boxed_existentials18test_type_loweringyys5Error_pF : $@convention(thin) (@guaranteed Error) -> () {
diff --git a/test/SILGen/plus_zero_call_chain_reabstraction.swift b/test/SILGen/plus_zero_call_chain_reabstraction.swift
index 123c453..c9d8e6f 100644
--- a/test/SILGen/plus_zero_call_chain_reabstraction.swift
+++ b/test/SILGen/plus_zero_call_chain_reabstraction.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name call_chain_reabstraction -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 struct A {
         func g<U>(_ recur: (A, U) -> U) -> (A, U) -> U {
diff --git a/test/SILGen/plus_zero_capture_typed_boxes.swift b/test/SILGen/plus_zero_capture_typed_boxes.swift
index c33dad1..995cd61 100644
--- a/test/SILGen/plus_zero_capture_typed_boxes.swift
+++ b/test/SILGen/plus_zero_capture_typed_boxes.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name capture_typed_boxes -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func foo(_ x: Int) -> () -> Int {
   var x = x
diff --git a/test/SILGen/plus_zero_casts.swift b/test/SILGen/plus_zero_casts.swift
index 6944bbd..13a3763 100644
--- a/test/SILGen/plus_zero_casts.swift
+++ b/test/SILGen/plus_zero_casts.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name casts -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 class B { }
 class D : B { }
diff --git a/test/SILGen/plus_zero_cf.swift b/test/SILGen/plus_zero_cf.swift
index ac4e227..215bc08 100644
--- a/test/SILGen/plus_zero_cf.swift
+++ b/test/SILGen/plus_zero_cf.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -import-cf-types -sdk %S/Inputs %s -emit-silgen -o - | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name cf -import-cf-types -sdk %S/Inputs %s -emit-silgen -o - | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_class_bound_protocols.swift b/test/SILGen/plus_zero_class_bound_protocols.swift
index a6b66b8..3cf9139 100644
--- a/test/SILGen/plus_zero_class_bound_protocols.swift
+++ b/test/SILGen/plus_zero_class_bound_protocols.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -parse-stdlib -parse-as-library -module-name Swift -emit-silgen %s | %FileCheck %s
 
 enum Optional<T> {
diff --git a/test/SILGen/plus_zero_class_resilience.swift b/test/SILGen/plus_zero_class_resilience.swift
index 5421688..c456a99 100644
--- a/test/SILGen/plus_zero_class_resilience.swift
+++ b/test/SILGen/plus_zero_class_resilience.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
 // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift
-// RUN: %target-swift-frontend -I %t -emit-silgen -enable-sil-ownership -enable-resilience %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name class_resilience -I %t -emit-silgen -enable-sil-ownership -enable-resilience %s | %FileCheck %s
 
 import resilient_class
 
diff --git a/test/SILGen/plus_zero_closures.swift b/test/SILGen/plus_zero_closures.swift
index 2442f4b..1707dbd 100644
--- a/test/SILGen/plus_zero_closures.swift
+++ b/test/SILGen/plus_zero_closures.swift
@@ -1,6 +1,7 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s
-// RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -parse-as-library -emit-silgen  %s | %FileCheck %s --check-prefix=GUARANTEED
+
+// RUN: %target-swift-frontend -module-name closures -enable-sil-ownership -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name closures -enable-sil-ownership -parse-stdlib -parse-as-library -emit-silgen  %s | %FileCheck %s --check-prefix=GUARANTEED
 
 import Swift
 
diff --git a/test/SILGen/plus_zero_collection_downcast.swift b/test/SILGen/plus_zero_collection_downcast.swift
index 30f16af..eacfa6f 100644
--- a/test/SILGen/plus_zero_collection_downcast.swift
+++ b/test/SILGen/plus_zero_collection_downcast.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name collection_downcast -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_collection_subtype_downcast.swift b/test/SILGen/plus_zero_collection_subtype_downcast.swift
index 251eb9e..ec141d0 100644
--- a/test/SILGen/plus_zero_collection_subtype_downcast.swift
+++ b/test/SILGen/plus_zero_collection_subtype_downcast.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -sdk %S/Inputs %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name collection_subtype_downcast -emit-silgen -enable-sil-ownership -sdk %S/Inputs %s | %FileCheck %s
 
 struct S { var x, y: Int }
 
diff --git a/test/SILGen/plus_zero_collection_subtype_upcast.swift b/test/SILGen/plus_zero_collection_subtype_upcast.swift
index a0d1a13..88338c0 100644
--- a/test/SILGen/plus_zero_collection_subtype_upcast.swift
+++ b/test/SILGen/plus_zero_collection_subtype_upcast.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -sdk %S/Inputs %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name collection_subtype_upcast -emit-silgen -enable-sil-ownership -sdk %S/Inputs %s | %FileCheck %s
 
 struct S { var x, y: Int }
 
diff --git a/test/SILGen/plus_zero_collection_upcast.swift b/test/SILGen/plus_zero_collection_upcast.swift
index c0bb574..90e4985 100644
--- a/test/SILGen/plus_zero_collection_upcast.swift
+++ b/test/SILGen/plus_zero_collection_upcast.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name collection_upcast -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
 
 // FIXME: rdar://problem/19648117 Needs splitting objc parts out
 // XFAIL: linux
diff --git a/test/SILGen/plus_zero_constrained_extensions.swift b/test/SILGen/plus_zero_constrained_extensions.swift
index c925a1e..9b28d7f 100644
--- a/test/SILGen/plus_zero_constrained_extensions.swift
+++ b/test/SILGen/plus_zero_constrained_extensions.swift
@@ -1,7 +1,8 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -primary-file %s | %FileCheck %s
-// RUN: %target-swift-frontend -emit-sil -O -primary-file %s > /dev/null
-// RUN: %target-swift-frontend -emit-ir -primary-file %s > /dev/null
+
+// RUN: %target-swift-frontend -module-name constrained_extensions -emit-silgen -enable-sil-ownership -primary-file %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name constrained_extensions -emit-sil -O -primary-file %s > /dev/null
+// RUN: %target-swift-frontend -module-name constrained_extensions -emit-ir -primary-file %s > /dev/null
 
 extension Array where Element == Int {
   // CHECK-LABEL: sil @$SSa22constrained_extensionsSiRszlE1xSaySiGyt_tcfC : $@convention(method) (@thin Array<Int>.Type) -> @owned Array<Int>
@@ -138,7 +139,7 @@
 extension GenericClass where Y == () {
   // CHECK-LABEL: sil @$S22constrained_extensions12GenericClassCAAytRs_rlE5valuexvg : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> @out X
   // CHECK-LABEL: sil @$S22constrained_extensions12GenericClassCAAytRs_rlE5valuexvs : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> ()
-  // CHECK-LABEL: sil shared [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlE5valuexvmytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> ()
+  // CHECK-LABEL: sil shared [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlE5valuexvmytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> ()
   // CHECK-LABEL: sil [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlE5valuexvm : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed GenericClass<X, ()>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
   public var value: X {
     get { while true {} }
@@ -147,7 +148,7 @@
 
   // CHECK-LABEL: sil @$S22constrained_extensions12GenericClassCAAytRs_rlE5emptyytvg : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> ()
   // CHECK-LABEL: sil @$S22constrained_extensions12GenericClassCAAytRs_rlE5emptyytvs : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> ()
-  // CHECK-LABEL: sil shared [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlE5emptyytvmytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> ()
+  // CHECK-LABEL: sil shared [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlE5emptyytvmytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> ()
   // CHECK-LABEL: sil [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlE5emptyytvm : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed GenericClass<X, ()>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
   public var empty: Y {
     get { return () }
@@ -156,7 +157,7 @@
 
   // CHECK-LABEL: sil @$S22constrained_extensions12GenericClassCAAytRs_rlEyxyt_tcig : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> @out X
   // CHECK-LABEL: sil @$S22constrained_extensions12GenericClassCAAytRs_rlEyxyt_tcis : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> ()
-  // CHECK-LABEL: sil shared [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlEyxyt_tcimytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> ()
+  // CHECK-LABEL: sil shared [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlEyxyt_tcimytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> ()
   // CHECK-LABEL: sil [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlEyxyt_tcim : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed GenericClass<X, ()>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
   public subscript(_: Y) -> X {
     get { while true {} }
@@ -165,7 +166,7 @@
 
   // CHECK-LABEL: sil @$S22constrained_extensions12GenericClassCAAytRs_rlEyyxcig : $@convention(method) <X, Y where Y == ()> (@in_guaranteed X, @guaranteed GenericClass<X, ()>) -> ()
   // CHECK-LABEL: sil @$S22constrained_extensions12GenericClassCAAytRs_rlEyyxcis : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> ()
-  // CHECK-LABEL: sil shared [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlEyyxcimytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> ()
+  // CHECK-LABEL: sil shared [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlEyyxcimytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> ()
   // CHECK-LABEL: sil [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlEyyxcim : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed X, @guaranteed GenericClass<X, ()>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
   public subscript(_: X) -> Y {
     get { while true {} }
diff --git a/test/SILGen/plus_zero_default_arguments.swift b/test/SILGen/plus_zero_default_arguments.swift
index ad5ff0e..645a1f5 100644
--- a/test/SILGen/plus_zero_default_arguments.swift
+++ b/test/SILGen/plus_zero_default_arguments.swift
@@ -1,9 +1,10 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 3 %s | %FileCheck %s
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 3 %s | %FileCheck %s --check-prefix=NEGATIVE
 
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 4 %s | %FileCheck %s
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 4 %s | %FileCheck %s --check-prefix=NEGATIVE
+// RUN: %target-swift-frontend -module-name default_arguments -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 3 %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name default_arguments -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 3 %s | %FileCheck %s --check-prefix=NEGATIVE
+
+// RUN: %target-swift-frontend -module-name default_arguments -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 4 %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name default_arguments -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 4 %s | %FileCheck %s --check-prefix=NEGATIVE
 
 // __FUNCTION__ used as top-level parameter produces the module name.
 // CHECK-LABEL: sil @main
diff --git a/test/SILGen/plus_zero_default_arguments_generic.swift b/test/SILGen/plus_zero_default_arguments_generic.swift
index b382f5b..1477fcc 100644
--- a/test/SILGen/plus_zero_default_arguments_generic.swift
+++ b/test/SILGen/plus_zero_default_arguments_generic.swift
@@ -1,6 +1,7 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -swift-version 3 %s | %FileCheck %s
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -swift-version 4 %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name default_arguments_generic -emit-silgen -enable-sil-ownership -swift-version 3 %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name default_arguments_generic -emit-silgen -enable-sil-ownership -swift-version 4 %s | %FileCheck %s
 
 func foo<T: ExpressibleByIntegerLiteral>(_: T.Type, x: T = 0) { }
 
diff --git a/test/SILGen/plus_zero_default_arguments_serialized.swift b/test/SILGen/plus_zero_default_arguments_serialized.swift
index 1472952..8da51e7 100644
--- a/test/SILGen/plus_zero_default_arguments_serialized.swift
+++ b/test/SILGen/plus_zero_default_arguments_serialized.swift
@@ -1,12 +1,13 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module-path %t/default_arguments_other.swiftmodule -emit-module -swift-version 4 -primary-file %S/Inputs/default_arguments_other.swift
 
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 3 -I %t %s | %FileCheck %s --check-prefix=SWIFT3 --check-prefix=CHECK
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 4 -I %t %s | %FileCheck %s --check-prefix=SWIFT4 --check-prefix=CHECK
+// RUN: %target-swift-frontend -module-name default_arguments_serialized -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 3 -I %t %s | %FileCheck %s --check-prefix=SWIFT3 --check-prefix=CHECK
+// RUN: %target-swift-frontend -module-name default_arguments_serialized -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen -swift-version 4 -I %t %s | %FileCheck %s --check-prefix=SWIFT4 --check-prefix=CHECK
 
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-sil -O -swift-version 3 -I %t %s | %FileCheck %s --check-prefix=OPT
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-sil -O -swift-version 4 -I %t %s | %FileCheck %s --check-prefix=OPT
+// RUN: %target-swift-frontend -module-name default_arguments_serialized -Xllvm -sil-full-demangle -enable-sil-ownership -emit-sil -O -swift-version 3 -I %t %s | %FileCheck %s --check-prefix=OPT
+// RUN: %target-swift-frontend -module-name default_arguments_serialized -Xllvm -sil-full-demangle -enable-sil-ownership -emit-sil -O -swift-version 4 -I %t %s | %FileCheck %s --check-prefix=OPT
 
 // Check that default arguments are serialized in Swift 4 mode.
 
diff --git a/test/SILGen/plus_zero_dependent_member_lowering.swift b/test/SILGen/plus_zero_dependent_member_lowering.swift
index be5785f..b051e99 100644
--- a/test/SILGen/plus_zero_dependent_member_lowering.swift
+++ b/test/SILGen/plus_zero_dependent_member_lowering.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name dependent_member_lowering -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 protocol P {
   associatedtype A
diff --git a/test/SILGen/plus_zero_downcast_reabstraction.swift b/test/SILGen/plus_zero_downcast_reabstraction.swift
index 52608d2..a16c28f 100644
--- a/test/SILGen/plus_zero_downcast_reabstraction.swift
+++ b/test/SILGen/plus_zero_downcast_reabstraction.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name downcast_reabstraction -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 // CHECK-LABEL: sil hidden @$S22downcast_reabstraction19condFunctionFromAnyyyypF
 // CHECK:         checked_cast_addr_br take_always Any in [[IN:%.*]] : $*Any to () -> () in [[OUT:%.*]] : $*@callee_guaranteed (@in_guaranteed ()) -> @out (), [[YES:bb[0-9]+]], [[NO:bb[0-9]+]]
diff --git a/test/SILGen/plus_zero_dynamic.swift b/test/SILGen/plus_zero_dynamic.swift
index 2376ae7..344a6ab 100644
--- a/test/SILGen/plus_zero_dynamic.swift
+++ b/test/SILGen/plus_zero_dynamic.swift
@@ -1,9 +1,10 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-silgen-test-overlays
 
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -emit-silgen | %FileCheck %s
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -emit-sil -verify
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name dynamic -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -emit-silgen | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name dynamic -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -emit-sil -verify
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_dynamic_lookup.swift b/test/SILGen/plus_zero_dynamic_lookup.swift
index 64062f5..83317fa 100644
--- a/test/SILGen/plus_zero_dynamic_lookup.swift
+++ b/test/SILGen/plus_zero_dynamic_lookup.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module %s | %FileCheck %s
 // RUN: %target-swift-frontend -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module  %s | %FileCheck %s --check-prefix=GUARANTEED
 
diff --git a/test/SILGen/plus_zero_dynamic_lookup_throws.swift b/test/SILGen/plus_zero_dynamic_lookup_throws.swift
index 6b2a455..e5ee3c0 100644
--- a/test/SILGen/plus_zero_dynamic_lookup_throws.swift
+++ b/test/SILGen/plus_zero_dynamic_lookup_throws.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-clang-importer-objc-overlays
 
diff --git a/test/SILGen/plus_zero_dynamic_self.swift b/test/SILGen/plus_zero_dynamic_self.swift
index d02f276..855d20d 100644
--- a/test/SILGen/plus_zero_dynamic_self.swift
+++ b/test/SILGen/plus_zero_dynamic_self.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s -disable-objc-attr-requires-foundation-module | %FileCheck %s
 // RUN: %target-swift-frontend -emit-sil -O %s -disable-objc-attr-requires-foundation-module
 // RUN: %target-swift-frontend -emit-ir %s -disable-objc-attr-requires-foundation-module
diff --git a/test/SILGen/plus_zero_enum.swift b/test/SILGen/plus_zero_enum.swift
index 53a818c..d68f765 100644
--- a/test/SILGen/plus_zero_enum.swift
+++ b/test/SILGen/plus_zero_enum.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -parse-stdlib -parse-as-library -emit-silgen -enable-sil-ownership -module-name Swift %s | %FileCheck %s
 
 precedencegroup AssignmentPrecedence { assignment: true }
diff --git a/test/SILGen/plus_zero_enum_resilience.swift b/test/SILGen/plus_zero_enum_resilience.swift
index 7b5ac8a..cb50fa7 100644
--- a/test/SILGen/plus_zero_enum_resilience.swift
+++ b/test/SILGen/plus_zero_enum_resilience.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
 // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
-// RUN: %target-swift-frontend -I %t -enable-sil-ownership -emit-silgen -enable-resilience %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name enum_resilience -I %t -enable-sil-ownership -emit-silgen -enable-resilience %s | %FileCheck %s
 
 import resilient_enum
 
diff --git a/test/SILGen/plus_zero_erasure_reabstraction.swift b/test/SILGen/plus_zero_erasure_reabstraction.swift
index 1c2c0eb..b426126 100644
--- a/test/SILGen/plus_zero_erasure_reabstraction.swift
+++ b/test/SILGen/plus_zero_erasure_reabstraction.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 struct Foo {}
diff --git a/test/SILGen/plus_zero_existential_erasure.swift b/test/SILGen/plus_zero_existential_erasure.swift
index a60024f..4286322 100644
--- a/test/SILGen/plus_zero_existential_erasure.swift
+++ b/test/SILGen/plus_zero_existential_erasure.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name existential_erasure -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 protocol P {
   func downgrade(_ m68k: Bool) -> Self
diff --git a/test/SILGen/plus_zero_expressions.swift b/test/SILGen/plus_zero_expressions.swift
index 293c8fe..19634f9 100644
--- a/test/SILGen/plus_zero_expressions.swift
+++ b/test/SILGen/plus_zero_expressions.swift
@@ -1,7 +1,8 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: echo "public var x = Int()" | %target-swift-frontend -module-name FooBar -emit-module -o %t -
-// RUN: %target-swift-frontend -parse-stdlib -emit-silgen -enable-sil-ownership %s -I%t -disable-access-control | %FileCheck %s
+// RUN: %target-swift-frontend -parse-stdlib -module-name expressions -emit-silgen -enable-sil-ownership %s -I%t -disable-access-control | %FileCheck %s
 
 import Swift
 import FooBar
diff --git a/test/SILGen/plus_zero_extensions_objc.swift b/test/SILGen/plus_zero_extensions_objc.swift
index 24a9cb7..d84b0ee 100644
--- a/test/SILGen/plus_zero_extensions_objc.swift
+++ b/test/SILGen/plus_zero_extensions_objc.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -sdk %S/Inputs %s -I %S/Inputs -enable-source-import -emit-silgen -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name extensions_objc -sdk %S/Inputs %s -I %S/Inputs -enable-source-import -emit-silgen -enable-sil-ownership | %FileCheck %s
 //
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_external_definitions.swift b/test/SILGen/plus_zero_external_definitions.swift
index eed168f..0f6017d 100644
--- a/test/SILGen/plus_zero_external_definitions.swift
+++ b/test/SILGen/plus_zero_external_definitions.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -sdk %S/Inputs %s -emit-silgen -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: objc_interop
diff --git a/test/SILGen/plus_zero_final.swift b/test/SILGen/plus_zero_final.swift
index 3e9133b..7452af7 100644
--- a/test/SILGen/plus_zero_final.swift
+++ b/test/SILGen/plus_zero_final.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name final -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 class TestClass {
 
diff --git a/test/SILGen/plus_zero_force_cast_chained_optional.swift b/test/SILGen/plus_zero_force_cast_chained_optional.swift
index d903e82..d01c859 100644
--- a/test/SILGen/plus_zero_force_cast_chained_optional.swift
+++ b/test/SILGen/plus_zero_force_cast_chained_optional.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name force_cast_chained_optional -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 class Foo {
   var bar: Bar!
diff --git a/test/SILGen/plus_zero_foreach.swift b/test/SILGen/plus_zero_foreach.swift
index 7a3589b..2c8fbff 100644
--- a/test/SILGen/plus_zero_foreach.swift
+++ b/test/SILGen/plus_zero_foreach.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name foreach -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 //////////////////
 // Declarations //
diff --git a/test/SILGen/plus_zero_foreign_errors.swift b/test/SILGen/plus_zero_foreign_errors.swift
index d004d8f..eb7c0bc 100644
--- a/test/SILGen/plus_zero_foreign_errors.swift
+++ b/test/SILGen/plus_zero_foreign_errors.swift
@@ -1,7 +1,8 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-clang-importer-objc-overlays
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-silgen -parse-as-library %s | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -module-name foreign_errors -emit-silgen -parse-as-library %s | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_function_conversion.swift b/test/SILGen/plus_zero_function_conversion.swift
index a3dc163..eaefe6e 100644
--- a/test/SILGen/plus_zero_function_conversion.swift
+++ b/test/SILGen/plus_zero_function_conversion.swift
@@ -1,6 +1,7 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -primary-file %s | %FileCheck %s
-// RUN: %target-swift-frontend -emit-ir -enable-sil-ownership -primary-file %s
+
+// RUN: %target-swift-frontend -module-name function_conversion -emit-silgen -enable-sil-ownership -primary-file %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name function_conversion -emit-ir -enable-sil-ownership -primary-file %s
 
 // Check SILGen against various FunctionConversionExprs emitted by Sema.
 
diff --git a/test/SILGen/plus_zero_function_conversion_objc.swift b/test/SILGen/plus_zero_function_conversion_objc.swift
index 3314382..1dc64e6 100644
--- a/test/SILGen/plus_zero_function_conversion_objc.swift
+++ b/test/SILGen/plus_zero_function_conversion_objc.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -sdk %S/Inputs %s -I %S/Inputs -enable-sil-ownership -enable-source-import -emit-silgen -verify | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name function_conversion_objc -sdk %S/Inputs %s -I %S/Inputs -enable-sil-ownership -enable-source-import -emit-silgen -verify | %FileCheck %s
 
 import Foundation
 
diff --git a/test/SILGen/plus_zero_functions.swift b/test/SILGen/plus_zero_functions.swift
index e43048d..dbc6c1c 100644
--- a/test/SILGen/plus_zero_functions.swift
+++ b/test/SILGen/plus_zero_functions.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name functions -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 import Swift // just for Optional
 
diff --git a/test/SILGen/plus_zero_generic_casts.swift b/test/SILGen/plus_zero_generic_casts.swift
index 1f857b0..bd9c2cd 100644
--- a/test/SILGen/plus_zero_generic_casts.swift
+++ b/test/SILGen/plus_zero_generic_casts.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-runtime %s
+
+// RUN: %target-swift-frontend -module-name generic_casts -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-runtime %s
 
 protocol ClassBound : class {}
 protocol NotClassBound {}
diff --git a/test/SILGen/plus_zero_generic_closures.swift b/test/SILGen/plus_zero_generic_closures.swift
index 174912d..6e211c5 100644
--- a/test/SILGen/plus_zero_generic_closures.swift
+++ b/test/SILGen/plus_zero_generic_closures.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -parse-stdlib -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name generic_closures  -parse-stdlib -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 import Swift
 
diff --git a/test/SILGen/plus_zero_generic_property_base_lifetime.swift b/test/SILGen/plus_zero_generic_property_base_lifetime.swift
index 17f3823..0ac207d 100644
--- a/test/SILGen/plus_zero_generic_property_base_lifetime.swift
+++ b/test/SILGen/plus_zero_generic_property_base_lifetime.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name generic_property_base_lifetime -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
 
 protocol ProtocolA: class {
     var intProp: Int { get set }
diff --git a/test/SILGen/plus_zero_generic_tuples.swift b/test/SILGen/plus_zero_generic_tuples.swift
index d3053a1..53193e6 100644
--- a/test/SILGen/plus_zero_generic_tuples.swift
+++ b/test/SILGen/plus_zero_generic_tuples.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -parse-as-library -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name generic_tuples -emit-silgen -parse-as-library -enable-sil-ownership %s | %FileCheck %s
 
 
 func dup<T>(_ x: T) -> (T, T) { return (x,x) }
diff --git a/test/SILGen/plus_zero_generic_witness.swift b/test/SILGen/plus_zero_generic_witness.swift
index a450270..f5998e7 100644
--- a/test/SILGen/plus_zero_generic_witness.swift
+++ b/test/SILGen/plus_zero_generic_witness.swift
@@ -1,6 +1,7 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
-// RUN: %target-swift-frontend -emit-ir -enable-sil-ownership %s
+
+// RUN: %target-swift-frontend -module-name generic_witness -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name generic_witness -emit-ir -enable-sil-ownership %s
 
 protocol Runcible {
   func runce<A>(_ x: A)
diff --git a/test/SILGen/plus_zero_guaranteed_normal_args.swift b/test/SILGen/plus_zero_guaranteed_normal_args.swift
index fdcec6c..da3ca90 100644
--- a/test/SILGen/plus_zero_guaranteed_normal_args.swift
+++ b/test/SILGen/plus_zero_guaranteed_normal_args.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -parse-as-library -module-name Swift -parse-stdlib -emit-silgen -enable-sil-ownership -enable-guaranteed-normal-arguments %s | %FileCheck %s
 
 // This test checks specific codegen related to normal arguments being passed at
diff --git a/test/SILGen/plus_zero_guaranteed_self.swift b/test/SILGen/plus_zero_guaranteed_self.swift
index f8f4faa..2a6c85d 100644
--- a/test/SILGen/plus_zero_guaranteed_self.swift
+++ b/test/SILGen/plus_zero_guaranteed_self.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name guaranteed_self -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
 
 protocol Fooable {
   init()
diff --git a/test/SILGen/plus_zero_if_while_binding.swift b/test/SILGen/plus_zero_if_while_binding.swift
index 4152501..1c1ec5a 100644
--- a/test/SILGen/plus_zero_if_while_binding.swift
+++ b/test/SILGen/plus_zero_if_while_binding.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name if_while_binding -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func foo() -> String? { return "" }
 func bar() -> String? { return "" }
diff --git a/test/SILGen/plus_zero_implicitly_unwrapped_optional.swift b/test/SILGen/plus_zero_implicitly_unwrapped_optional.swift
index 55f3112..e172739 100644
--- a/test/SILGen/plus_zero_implicitly_unwrapped_optional.swift
+++ b/test/SILGen/plus_zero_implicitly_unwrapped_optional.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name implicitly_unwrapped_optional -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func foo(f f: (() -> ())!) {
   var f: (() -> ())! = f
diff --git a/test/SILGen/plus_zero_indirect_enum.swift b/test/SILGen/plus_zero_indirect_enum.swift
index 2d609f0..4c8e0a2 100644
--- a/test/SILGen/plus_zero_indirect_enum.swift
+++ b/test/SILGen/plus_zero_indirect_enum.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-print-debuginfo -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name indirect_enum -Xllvm -sil-print-debuginfo -emit-silgen %s | %FileCheck %s
 
 indirect enum TreeA<T> {
   case Nil
diff --git a/test/SILGen/plus_zero_inlineable_attribute.swift b/test/SILGen/plus_zero_inlineable_attribute.swift
index 097ea60..cfe3797 100644
--- a/test/SILGen/plus_zero_inlineable_attribute.swift
+++ b/test/SILGen/plus_zero_inlineable_attribute.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -emit-verbose-sil %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name inlineable_attribute -emit-silgen -enable-sil-ownership -emit-verbose-sil %s | %FileCheck %s
 
 // CHECK-LABEL: sil [serialized] @$S20inlineable_attribute15fragileFunctionyyF : $@convention(thin) () -> ()
 @_inlineable public func fragileFunction() {
diff --git a/test/SILGen/plus_zero_inlineable_attribute_objc.swift b/test/SILGen/plus_zero_inlineable_attribute_objc.swift
index a963567..60a07a2 100644
--- a/test/SILGen/plus_zero_inlineable_attribute_objc.swift
+++ b/test/SILGen/plus_zero_inlineable_attribute_objc.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-silgen-test-overlays
 
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -sil-full-demangle -primary-file %s -emit-silgen | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name inlineable_attribute_objc -Xllvm -sil-full-demangle -primary-file %s -emit-silgen | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_keypath_application.swift b/test/SILGen/plus_zero_keypath_application.swift
index 1dbd44e..5922afe 100644
--- a/test/SILGen/plus_zero_keypath_application.swift
+++ b/test/SILGen/plus_zero_keypath_application.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 class A {}
diff --git a/test/SILGen/plus_zero_keypaths.swift b/test/SILGen/plus_zero_keypaths.swift
index db06785..d95a3dc 100644
--- a/test/SILGen/plus_zero_keypaths.swift
+++ b/test/SILGen/plus_zero_keypaths.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name keypaths -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 struct S<T> {
   var x: T
diff --git a/test/SILGen/plus_zero_let_decls.swift b/test/SILGen/plus_zero_let_decls.swift
index d0f7379..6c27b28 100644
--- a/test/SILGen/plus_zero_let_decls.swift
+++ b/test/SILGen/plus_zero_let_decls.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name let_decls -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func takeClosure(_ a : () -> Int) {}
 
diff --git a/test/SILGen/plus_zero_lifetime.swift b/test/SILGen/plus_zero_lifetime.swift
index f5917ab..c238b78 100644
--- a/test/SILGen/plus_zero_lifetime.swift
+++ b/test/SILGen/plus_zero_lifetime.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -parse-as-library -emit-silgen -primary-file %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name lifetime -Xllvm -sil-full-demangle -parse-as-library -emit-silgen -primary-file %s | %FileCheck %s
 
 struct Buh<T> {
   var x: Int {
@@ -386,7 +387,7 @@
   // CHECK: [[ADDR:%.*]] = pointer_to_address [[PTR]]
   // CHECK: [[MARKED_ADDR:%.*]] = mark_dependence [[ADDR]] : $*Aleph on [[R2]]
   // CHECK: {{.*}}([[CALLBACK_ADDR:%.*]] : 
-  // CHECK: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout RefWithProp, @thick RefWithProp.Type) -> ()
+  // CHECK: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed RefWithProp, @thick RefWithProp.Type) -> ()
   // CHECK: [[TEMP:%.*]] = alloc_stack $RefWithProp
   // CHECK: store [[R2]] to [init] [[TEMP]]
   // CHECK: apply [[CALLBACK]]({{.*}}, [[STORAGE]], [[TEMP]], {{%.*}})
diff --git a/test/SILGen/plus_zero_mangling.swift b/test/SILGen/plus_zero_mangling.swift
index a0357ce..8d5d973 100644
--- a/test/SILGen/plus_zero_mangling.swift
+++ b/test/SILGen/plus_zero_mangling.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name mangling -Xllvm -sil-full-demangle -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_materializeForSet.swift b/test/SILGen/plus_zero_materializeForSet.swift
index f742400a..6e350c8 100644
--- a/test/SILGen/plus_zero_materializeForSet.swift
+++ b/test/SILGen/plus_zero_materializeForSet.swift
@@ -1,6 +1,7 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
-// RUN: %target-swift-frontend -emit-silgen -enforce-exclusivity=unchecked %s | %FileCheck --check-prefix=UNCHECKED %s
+
+// RUN: %target-swift-frontend -module-name materializeForSet -emit-silgen %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name materializeForSet -emit-silgen -enforce-exclusivity=unchecked %s | %FileCheck --check-prefix=UNCHECKED %s
 
 class Base {
   var stored: Int = 0
@@ -23,7 +24,7 @@
 // UNCHECKED:   return [[T3]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
 // UNCHECKED: }
 
-// CHECK-LABEL: sil private [transparent] @$S17materializeForSet4BaseC8computedSivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Base, @thick Base.Type) -> () {
+// CHECK-LABEL: sil private [transparent] @$S17materializeForSet4BaseC8computedSivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed Base, @thick Base.Type) -> () {
 // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Base, [[SELFTYPE:%.*]] : $@thick Base.Type):
 // CHECK:   [[T0:%.*]] = load_borrow [[SELF]]
 // CHECK:   [[T1:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int
@@ -38,7 +39,7 @@
 // CHECK:   [[T1:%.*]] = apply [[T0]]([[SELF]])
 // CHECK:   store [[T1]] to [trivial] [[ADDR]] : $*Int
 // CHECK:   [[BUFFER:%.*]] = address_to_pointer [[ADDR]]
-// CHECK:   [[T0:%.*]] = function_ref @$S17materializeForSet4BaseC8computedSivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Base, @thick Base.Type) -> ()
+// CHECK:   [[T0:%.*]] = function_ref @$S17materializeForSet4BaseC8computedSivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed Base, @thick Base.Type) -> ()
 // CHECK:   [[T2:%.*]] = thin_function_to_pointer [[T0]]
 // CHECK:   [[T3:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T2]] : $Builtin.RawPointer
 // CHECK:   [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[T3]] : $Optional<Builtin.RawPointer>)
@@ -77,7 +78,7 @@
 
 extension Derived : Abstractable {}
 
-// CHECK-LABEL: sil private [transparent] @$S17materializeForSet7DerivedCAA12AbstractableA2aDP14storedFunction6ResultQzycvmytfU_TW : $@convention(witness_method: Abstractable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Derived, @thick Derived.Type) -> ()
+// CHECK-LABEL: sil private [transparent] @$S17materializeForSet7DerivedCAA12AbstractableA2aDP14storedFunction6ResultQzycvmytfU_TW : $@convention(witness_method: Abstractable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed Derived, @thick Derived.Type) -> ()
 // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived, %3 : $@thick Derived.Type):
 // CHECK-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived
 // CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base
@@ -218,8 +219,8 @@
 // CHECK-NEXT: destroy_addr [[OUT]] : $*@callee_guaranteed () -> Int
 // CHECK-NEXT: store [[NEWVALUE]] to [init] [[RESULT_ADDR]] : $*@callee_guaranteed () -> @out Int
 // CHECK-NEXT: [[ADDR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_guaranteed () -> @out Int to $Builtin.RawPointer
-// CHECK:      [[CALLBACK_FN:%.*]] = function_ref @$S17materializeForSet7DerivedCAA12AbstractableA2aDP14staticFunction6ResultQzycvmZytfU_TW : $@convention(witness_method: Abstractable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout @thick Derived.Type, @thick Derived.Type.Type) -> ()
-// CHECK-NEXT: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] : $@convention(witness_method: Abstractable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout @thick Derived.Type, @thick Derived.Type.Type) -> () to $Builtin.RawPointer
+// CHECK:      [[CALLBACK_FN:%.*]] = function_ref @$S17materializeForSet7DerivedCAA12AbstractableA2aDP14staticFunction6ResultQzycvmZytfU_TW : $@convention(witness_method: Abstractable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed @thick Derived.Type, @thick Derived.Type.Type) -> ()
+// CHECK-NEXT: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] : $@convention(witness_method: Abstractable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed @thick Derived.Type, @thick Derived.Type.Type) -> () to $Builtin.RawPointer
 // CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] : $Builtin.RawPointer
 // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[ADDR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
 // CHECK-NEXT: dealloc_stack [[OUT]] : $*@callee_guaranteed () -> Int
@@ -264,7 +265,7 @@
 // CHECK:   [[T1:%.*]] = apply [[T0]]([[SELF]])
 // CHECK:   store [[T1]] to [trivial] [[T2]] : $*Int
 // CHECK:   [[BUFFER:%.*]] = address_to_pointer [[T2]]
-// CHECK:   [[CALLBACK_FN:%.*]] = function_ref @$S17materializeForSet06HasDidC0C6storedSivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasDidSet, @thick HasDidSet.Type) -> ()
+// CHECK:   [[CALLBACK_FN:%.*]] = function_ref @$S17materializeForSet06HasDidC0C6storedSivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed HasDidSet, @thick HasDidSet.Type) -> ()
 // CHECK:   [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]]
 // CHECK:   [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]]
 // CHECK:   [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
@@ -283,7 +284,7 @@
 // CHECK:   [[T1:%.*]] = apply [[T0]]([[SELF]])
 // CHECK:   store [[T1]] to [trivial] [[T2]] : $*Int
 // CHECK:   [[BUFFER:%.*]] = address_to_pointer [[T2]]
-// CHECK:   [[CALLBACK_FN:%.*]] = function_ref @$S17materializeForSet06HasDidC0C8computedSivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasDidSet, @thick HasDidSet.Type) -> ()
+// CHECK:   [[CALLBACK_FN:%.*]] = function_ref @$S17materializeForSet06HasDidC0C8computedSivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed HasDidSet, @thick HasDidSet.Type) -> ()
 // CHECK:   [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]]
 // CHECK:   [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]]
 // CHECK:   [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
@@ -296,7 +297,7 @@
     didSet {}
   }
 
-// CHECK-LABEL: sil private [transparent] @$S17materializeForSet012HasStoredDidC0C6storedSivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasStoredDidSet, @thick HasStoredDidSet.Type) -> () {
+// CHECK-LABEL: sil private [transparent] @$S17materializeForSet012HasStoredDidC0C6storedSivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed HasStoredDidSet, @thick HasStoredDidSet.Type) -> () {
 // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*HasStoredDidSet, [[METATYPE:%.*]] : $@thick HasStoredDidSet.Type):
 // CHECK:   [[SELF_VALUE:%.*]] = load_borrow [[SELF]] : $*HasStoredDidSet
 // CHECK:   [[BUFFER_ADDR:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int
@@ -313,7 +314,7 @@
 // CHECK:   [[T1:%.*]] = apply [[T0]]([[SELF]])
 // CHECK:   store [[T1]] to [trivial] [[T2]] : $*Int
 // CHECK:   [[BUFFER:%.*]] = address_to_pointer [[T2]]
-// CHECK:   [[CALLBACK_FN:%.*]] = function_ref @$S17materializeForSet012HasStoredDidC0C6storedSivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasStoredDidSet, @thick HasStoredDidSet.Type) -> ()
+// CHECK:   [[CALLBACK_FN:%.*]] = function_ref @$S17materializeForSet012HasStoredDidC0C6storedSivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed HasStoredDidSet, @thick HasStoredDidSet.Type) -> ()
 // CHECK:   [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]]
 // CHECK:   [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]]
 // CHECK:   [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
@@ -333,7 +334,7 @@
 // CHECK:   end_access [[READ]] : $*@sil_weak Optional<HasWeak>
 // CHECK:   store [[T1]] to [init] [[T2]] : $*Optional<HasWeak>
 // CHECK:   [[BUFFER:%.*]] = address_to_pointer [[T2]]
-// CHECK:   [[T0:%.*]] = function_ref @$S17materializeForSet7HasWeakC7weakvarACSgXwvmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasWeak, @thick HasWeak.Type) -> () 
+// CHECK:   [[T0:%.*]] = function_ref @$S17materializeForSet7HasWeakC7weakvarACSgXwvmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed HasWeak, @thick HasWeak.Type) -> () 
 // CHECK:   [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, {{.*}} : $Optional<Builtin.RawPointer>)
 // CHECK:   return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
 // CHECK: }
@@ -345,7 +346,7 @@
 // UNCHECKED:   [[T1:%.*]] = load_weak [[T0]] : $*@sil_weak Optional<HasWeak>
 // UNCHECKED:   store [[T1]] to [init] [[T2]] : $*Optional<HasWeak>
 // UNCHECKED:   [[BUFFER:%.*]] = address_to_pointer [[T2]]
-// UNCHECKED:   [[T0:%.*]] = function_ref @$S17materializeForSet7HasWeakC7weakvarACSgXwvmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasWeak, @thick HasWeak.Type) -> () 
+// UNCHECKED:   [[T0:%.*]] = function_ref @$S17materializeForSet7HasWeakC7weakvarACSgXwvmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed HasWeak, @thick HasWeak.Type) -> () 
 // UNCHECKED:   [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, {{.*}} : $Optional<Builtin.RawPointer>)
 // UNCHECKED:   return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
 // UNCHECKED: }
@@ -661,6 +662,25 @@
   f.computed = f.computed
 }
 
+// Odd corner case -- mutating getter, non-mutating setter
+protocol BackwardMutationProtocol {
+  var value: Int {
+    mutating get
+    nonmutating set
+  }
+}
+
+struct BackwardMutation : BackwardMutationProtocol {
+  var value: Int {
+    mutating get { return 0 }
+    nonmutating set { }
+  }
+}
+
+func doBackwardMutation(m: inout BackwardMutationProtocol) {
+  m.value += 1
+}
+
 // CHECK-LABEL: sil_vtable DerivedForOverride {
 // CHECK:   #BaseForOverride.valueStored!getter.1: (BaseForOverride) -> () -> Int : @$S17materializeForSet07DerivedB8OverrideC11valueStoredSivg
 // CHECK:   #BaseForOverride.valueStored!setter.1: (BaseForOverride) -> (Int) -> () : @$S17materializeForSet07DerivedB8OverrideC11valueStoredSivs
diff --git a/test/SILGen/plus_zero_metatype_abstraction.swift b/test/SILGen/plus_zero_metatype_abstraction.swift
index 8dfa81f..55c2296 100644
--- a/test/SILGen/plus_zero_metatype_abstraction.swift
+++ b/test/SILGen/plus_zero_metatype_abstraction.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -module-name Swift -parse-stdlib %s | %FileCheck %s
 
 enum Optional<Wrapped> {
diff --git a/test/SILGen/plus_zero_multi_file.swift b/test/SILGen/plus_zero_multi_file.swift
index aaccbcc..d6ee120 100644
--- a/test/SILGen/plus_zero_multi_file.swift
+++ b/test/SILGen/plus_zero_multi_file.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -primary-file %s %S/Inputs/multi_file_helper.swift | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name multi_file -emit-silgen -enable-sil-ownership -primary-file %s %S/Inputs/multi_file_helper.swift | %FileCheck %s
 
 func markUsed<T>(_ t: T) {}
 
diff --git a/test/SILGen/plus_zero_nested_generics.swift b/test/SILGen/plus_zero_nested_generics.swift
index 32abb9f..032e824 100644
--- a/test/SILGen/plus_zero_nested_generics.swift
+++ b/test/SILGen/plus_zero_nested_generics.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-silgen  -parse-as-library %s | %FileCheck %s
-// RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-sil -parse-as-library %s > /dev/null
-// RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-sil -O -parse-as-library %s > /dev/null
-// RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-ir -parse-as-library %s > /dev/null
+
+// RUN: %target-swift-frontend -module-name nested_generics -enable-sil-ownership -Xllvm -sil-full-demangle -emit-silgen  -parse-as-library %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name nested_generics -enable-sil-ownership -Xllvm -sil-full-demangle -emit-sil -parse-as-library %s > /dev/null
+// RUN: %target-swift-frontend -module-name nested_generics -enable-sil-ownership -Xllvm -sil-full-demangle -emit-sil -O -parse-as-library %s > /dev/null
+// RUN: %target-swift-frontend -module-name nested_generics -enable-sil-ownership -Xllvm -sil-full-demangle -emit-ir -parse-as-library %s > /dev/null
 
 // TODO:
 // - test generated SIL -- mostly we're just testing mangling here
diff --git a/test/SILGen/plus_zero_nested_types_referencing_nested_functions.swift b/test/SILGen/plus_zero_nested_types_referencing_nested_functions.swift
index a0aa92e..b22c70a 100644
--- a/test/SILGen/plus_zero_nested_types_referencing_nested_functions.swift
+++ b/test/SILGen/plus_zero_nested_types_referencing_nested_functions.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name nested_types_referencing_nested_functions -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 do {
   func foo() { bar(2) }
diff --git a/test/SILGen/plus_zero_newtype.swift b/test/SILGen/plus_zero_newtype.swift
index 778e1bb..9754f28 100644
--- a/test/SILGen/plus_zero_newtype.swift
+++ b/test/SILGen/plus_zero_newtype.swift
@@ -1,7 +1,8 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import  %s | %FileCheck %s -check-prefix=CHECK-RAW
 
-// RUN: %target-swift-frontend -emit-sil -sdk %S/Inputs -I %S/Inputs -enable-source-import  %s | %FileCheck %s -check-prefix=CHECK-CANONICAL
+// RUN: %target-swift-frontend -module-name newtype -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import  %s | %FileCheck %s -check-prefix=CHECK-RAW
+
+// RUN: %target-swift-frontend -module-name newtype -emit-sil -sdk %S/Inputs -I %S/Inputs -enable-source-import  %s | %FileCheck %s -check-prefix=CHECK-CANONICAL
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_noescape_reabstraction.swift b/test/SILGen/plus_zero_noescape_reabstraction.swift
index 36d8a93..4b6f37c 100644
--- a/test/SILGen/plus_zero_noescape_reabstraction.swift
+++ b/test/SILGen/plus_zero_noescape_reabstraction.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name noescape_reabstraction -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 struct S {}
 
diff --git a/test/SILGen/plus_zero_objc_attr_NSManaged.swift b/test/SILGen/plus_zero_objc_attr_NSManaged.swift
index 64754aa..50d2dae 100644
--- a/test/SILGen/plus_zero_objc_attr_NSManaged.swift
+++ b/test/SILGen/plus_zero_objc_attr_NSManaged.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -sdk %S/Inputs %s -I %S/Inputs -enable-source-import -emit-silgen -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name objc_attr_NSManaged -sdk %S/Inputs %s -I %S/Inputs -enable-source-import -emit-silgen -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: objc_interop
 
@@ -103,7 +104,7 @@
 	@NSManaged final var entityID: String
 }
 
-// CHECK-LABEL: sil private @$S19objc_attr_NSManaged11FinalEntityC8entityIDSSvmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout FinalEntity, @thick FinalEntity.Type) -> ()
+// CHECK-LABEL: sil private @$S19objc_attr_NSManaged11FinalEntityC8entityIDSSvmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed FinalEntity, @thick FinalEntity.Type) -> ()
 // CHECK: objc_method {{.*}} : $FinalEntity, #FinalEntity.entityID!setter.1.foreign
 // CHECK: return
 
diff --git a/test/SILGen/plus_zero_objc_attr_NSManaged_multi.swift b/test/SILGen/plus_zero_objc_attr_NSManaged_multi.swift
index c1c9a5f..4ea9911 100644
--- a/test/SILGen/plus_zero_objc_attr_NSManaged_multi.swift
+++ b/test/SILGen/plus_zero_objc_attr_NSManaged_multi.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -sdk %S/Inputs -primary-file %s %S/objc_attr_NSManaged.swift -I %S/Inputs -enable-source-import -emit-silgen -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name objc_attr_NSManaged_multi -sdk %S/Inputs -primary-file %s %S/objc_attr_NSManaged.swift -I %S/Inputs -enable-source-import -emit-silgen -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_objc_blocks_bridging.swift b/test/SILGen/plus_zero_objc_blocks_bridging.swift
index 06b79c0..46dfd8d 100644
--- a/test/SILGen/plus_zero_objc_blocks_bridging.swift
+++ b/test/SILGen/plus_zero_objc_blocks_bridging.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-silgen-test-overlays
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -verify -emit-silgen -I %S/Inputs -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -verify -emit-silgen -I %S/Inputs -disable-objc-attr-requires-foundation-module -enable-sil-ownership  %s | %FileCheck %s --check-prefix=GUARANTEED
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_blocks_bridging -verify -emit-silgen -I %S/Inputs -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_blocks_bridging -verify -emit-silgen -I %S/Inputs -disable-objc-attr-requires-foundation-module -enable-sil-ownership  %s | %FileCheck %s --check-prefix=GUARANTEED
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_objc_bridged_results.swift b/test/SILGen/plus_zero_objc_bridged_results.swift
index 862c5b1..6d97f1a 100644
--- a/test/SILGen/plus_zero_objc_bridged_results.swift
+++ b/test/SILGen/plus_zero_objc_bridged_results.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-silgen-test-overlays
 
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-silgen %s -Xllvm -sil-print-debuginfo -import-objc-header %S/Inputs/objc_bridged_results.h -enable-sil-ownership | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_bridged_results -emit-silgen %s -Xllvm -sil-print-debuginfo -import-objc-header %S/Inputs/objc_bridged_results.h -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_objc_bridging.swift b/test/SILGen/plus_zero_objc_bridging.swift
index c4c6e1a..e79401c 100644
--- a/test/SILGen/plus_zero_objc_bridging.swift
+++ b/test/SILGen/plus_zero_objc_bridging.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-silgen-test-overlays
 // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-module -o %t -I %S/../Inputs/ObjCBridging %S/../Inputs/ObjCBridging/Appliances.swift
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -I %S/../Inputs/ObjCBridging -Xllvm -sil-full-demangle -emit-silgen %s -enable-sil-ownership | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-cpu --check-prefix=CHECK-%target-os-%target-cpu
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_bridging -I %S/../Inputs/ObjCBridging -Xllvm -sil-full-demangle -emit-silgen %s -enable-sil-ownership | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-cpu --check-prefix=CHECK-%target-os-%target-cpu
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_objc_bridging_any.swift b/test/SILGen/plus_zero_objc_bridging_any.swift
index 6e994ee..3ab1549 100644
--- a/test/SILGen/plus_zero_objc_bridging_any.swift
+++ b/test/SILGen/plus_zero_objc_bridging_any.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -Xllvm -sil-print-debuginfo -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name objc_bridging_any -Xllvm -sil-print-debuginfo -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 // REQUIRES: objc_interop
 
 import Foundation
diff --git a/test/SILGen/plus_zero_objc_bridging_peephole.swift b/test/SILGen/plus_zero_objc_bridging_peephole.swift
index 8797bc5..55bba58 100644
--- a/test/SILGen/plus_zero_objc_bridging_peephole.swift
+++ b/test/SILGen/plus_zero_objc_bridging_peephole.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name objc_bridging_peephole -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 // REQUIRES: objc_interop
 
 import Foundation
diff --git a/test/SILGen/plus_zero_objc_currying.swift b/test/SILGen/plus_zero_objc_currying.swift
index 8094585..9f1f9eb 100644
--- a/test/SILGen/plus_zero_objc_currying.swift
+++ b/test/SILGen/plus_zero_objc_currying.swift
@@ -1,7 +1,8 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-silgen-test-overlays
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -enable-sil-ownership -emit-silgen %s | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_currying -enable-sil-ownership -emit-silgen %s | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_objc_dictionary_bridging.swift b/test/SILGen/plus_zero_objc_dictionary_bridging.swift
index cee9ad3..48b24f9 100644
--- a/test/SILGen/plus_zero_objc_dictionary_bridging.swift
+++ b/test/SILGen/plus_zero_objc_dictionary_bridging.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-silgen-test-overlays
 
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_dictionary_bridging -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_objc_error.swift b/test/SILGen/plus_zero_objc_error.swift
index e48d19c..226aac3b 100644
--- a/test/SILGen/plus_zero_objc_error.swift
+++ b/test/SILGen/plus_zero_objc_error.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-clang-importer-objc-overlays
 
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -module-name objc_error -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_objc_extensions.swift b/test/SILGen/plus_zero_objc_extensions.swift
index 96a4c49..1e5ca90 100644
--- a/test/SILGen/plus_zero_objc_extensions.swift
+++ b/test/SILGen/plus_zero_objc_extensions.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -emit-silgen -sdk %S/Inputs/ -I %S/Inputs -enable-source-import %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name objc_extensions -enable-sil-ownership -emit-silgen -sdk %S/Inputs/ -I %S/Inputs -enable-source-import %s | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_objc_imported_generic.swift b/test/SILGen/plus_zero_objc_imported_generic.swift
index f874ba7..958bede 100644
--- a/test/SILGen/plus_zero_objc_imported_generic.swift
+++ b/test/SILGen/plus_zero_objc_imported_generic.swift
@@ -1,7 +1,8 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen %s -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name objc_imported_generic -emit-silgen %s -enable-sil-ownership | %FileCheck %s
 // For integration testing, ensure we get through IRGen too.
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-ir -verify -DIRGEN_INTEGRATION_TEST %s
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name objc_imported_generic -emit-ir -verify -DIRGEN_INTEGRATION_TEST %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_objc_ownership_conventions.swift b/test/SILGen/plus_zero_objc_ownership_conventions.swift
index 3ef9bb6..e8c95f7 100644
--- a/test/SILGen/plus_zero_objc_ownership_conventions.swift
+++ b/test/SILGen/plus_zero_objc_ownership_conventions.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name objc_ownership_conventions -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_objc_protocol_native_thunk.swift b/test/SILGen/plus_zero_objc_protocol_native_thunk.swift
index 3d75ecf..767561d 100644
--- a/test/SILGen/plus_zero_objc_protocol_native_thunk.swift
+++ b/test/SILGen/plus_zero_objc_protocol_native_thunk.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_objc_protocols.swift b/test/SILGen/plus_zero_objc_protocols.swift
index 5052509..fe8d618 100644
--- a/test/SILGen/plus_zero_objc_protocols.swift
+++ b/test/SILGen/plus_zero_objc_protocols.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name objc_protocols -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_objc_set_bridging.swift b/test/SILGen/plus_zero_objc_set_bridging.swift
index 3c790c1..c4fdbc4 100644
--- a/test/SILGen/plus_zero_objc_set_bridging.swift
+++ b/test/SILGen/plus_zero_objc_set_bridging.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %build-silgen-test-overlays
 
-// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-silgen %s -enable-sil-ownership | %FileCheck %s
+// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_set_bridging -emit-silgen %s -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_objc_thunks.swift b/test/SILGen/plus_zero_objc_thunks.swift
index 0a40a32..e9b1f0f 100644
--- a/test/SILGen/plus_zero_objc_thunks.swift
+++ b/test/SILGen/plus_zero_objc_thunks.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -Xllvm -sil-print-debuginfo -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -emit-verbose-sil -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name objc_thunks -Xllvm -sil-full-demangle -Xllvm -sil-print-debuginfo -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -emit-verbose-sil -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_opaque_ownership.swift b/test/SILGen/plus_zero_opaque_ownership.swift
index 622ffaf..5a0651f 100644
--- a/test/SILGen/plus_zero_opaque_ownership.swift
+++ b/test/SILGen/plus_zero_opaque_ownership.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -enable-sil-opaque-values -enable-sil-ownership -emit-sorted-sil -Xllvm -sil-full-demangle -emit-silgen -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck %s
 // RUN: %target-swift-frontend -target x86_64-apple-macosx10.9 -enable-sil-opaque-values -enable-sil-ownership -emit-sorted-sil -Xllvm -sil-full-demangle -emit-silgen -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck --check-prefix=CHECK-OSX %s
 
@@ -164,7 +165,7 @@
   case minus
 }
 
-#if os(OSX)
+#if os(macOS)
 // Test open_existential_value used in a conversion context.
 // (the actual bridging call is dropped because we don't import Swift).
 // ---
@@ -187,7 +188,7 @@
 
 public protocol Error {}
 
-#if os(OSX)
+#if os(macOS)
 // Test open_existential_box_value in a conversion context.
 // ---
 // CHECK-OSX-LABEL: sil @$Ss3foo1eys5Error_pSg_tF : $@convention(thin) (@guaranteed Optional<Error>) -> () {
diff --git a/test/SILGen/plus_zero_opaque_values_silgen.swift b/test/SILGen/plus_zero_opaque_values_silgen.swift
index 1c7f8f7..0d8ff59 100644
--- a/test/SILGen/plus_zero_opaque_values_silgen.swift
+++ b/test/SILGen/plus_zero_opaque_values_silgen.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -enable-sil-opaque-values -emit-sorted-sil -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime
 
 // UNSUPPORTED: resilient_stdlib
diff --git a/test/SILGen/plus_zero_opaque_values_silgen_lib.swift b/test/SILGen/plus_zero_opaque_values_silgen_lib.swift
index fa43ee0..ffd9aa6 100644
--- a/test/SILGen/plus_zero_opaque_values_silgen_lib.swift
+++ b/test/SILGen/plus_zero_opaque_values_silgen_lib.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -enable-sil-ownership -enable-sil-opaque-values -emit-sorted-sil -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -emit-silgen -module-name Swift %s | %FileCheck %s
 // UNSUPPORTED: resilient_stdlib
 
diff --git a/test/SILGen/plus_zero_optional-cast.swift b/test/SILGen/plus_zero_optional-cast.swift
index 0c0ca83..6bff640 100644
--- a/test/SILGen/plus_zero_optional-cast.swift
+++ b/test/SILGen/plus_zero_optional-cast.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 class A {}
diff --git a/test/SILGen/plus_zero_optional.swift b/test/SILGen/plus_zero_optional.swift
index 038a0ab..944e77a 100644
--- a/test/SILGen/plus_zero_optional.swift
+++ b/test/SILGen/plus_zero_optional.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name optional -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func testCall(_ f: (() -> ())?) {
   f?()
diff --git a/test/SILGen/plus_zero_optional_lvalue.swift b/test/SILGen/plus_zero_optional_lvalue.swift
index d2a4f17..5ed54db1b 100644
--- a/test/SILGen/plus_zero_optional_lvalue.swift
+++ b/test/SILGen/plus_zero_optional_lvalue.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name optional_lvalue -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 // CHECK-LABEL: sil hidden @$S15optional_lvalue07assign_a1_B0yySiSgz_SitF
 // CHECK:         [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<Int>
diff --git a/test/SILGen/plus_zero_partial_apply_generic.swift b/test/SILGen/plus_zero_partial_apply_generic.swift
index dc1f4c5..318ffb0 100644
--- a/test/SILGen/plus_zero_partial_apply_generic.swift
+++ b/test/SILGen/plus_zero_partial_apply_generic.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name partial_apply_generic -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 protocol Panda {
   associatedtype Cuddles : Foo
diff --git a/test/SILGen/plus_zero_partial_apply_protocol.swift b/test/SILGen/plus_zero_partial_apply_protocol.swift
index ba46add..7977418 100644
--- a/test/SILGen/plus_zero_partial_apply_protocol.swift
+++ b/test/SILGen/plus_zero_partial_apply_protocol.swift
@@ -1,6 +1,7 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -emit-silgen -primary-file %s | %FileCheck %s
-// RUN: %target-swift-frontend -enable-sil-ownership -emit-ir -primary-file %s
+
+// RUN: %target-swift-frontend -module-name partial_apply_protocol -enable-sil-ownership -emit-silgen -primary-file %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name partial_apply_protocol -enable-sil-ownership -emit-ir -primary-file %s
 
 protocol Clonable {
   func clone() -> Self
diff --git a/test/SILGen/plus_zero_partial_apply_protocol_class_refinement_method.swift b/test/SILGen/plus_zero_partial_apply_protocol_class_refinement_method.swift
index ec4c8be..cfaae00 100644
--- a/test/SILGen/plus_zero_partial_apply_protocol_class_refinement_method.swift
+++ b/test/SILGen/plus_zero_partial_apply_protocol_class_refinement_method.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name partial_apply_protocol_class_refinement_method -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 protocol P { func foo() }
 protocol Q: class, P {}
diff --git a/test/SILGen/plus_zero_partial_apply_super.swift b/test/SILGen/plus_zero_partial_apply_super.swift
index 0a823f1..583f755 100644
--- a/test/SILGen/plus_zero_partial_apply_super.swift
+++ b/test/SILGen/plus_zero_partial_apply_super.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
-// RUN: %target-swift-frontend -enable-sil-ownership -I %t -emit-module -emit-module-path=%t/resilient_struct.swiftmodule -module-name resilient_struct %S/../Inputs/resilient_struct.swift
-// RUN: %target-swift-frontend -enable-sil-ownership -I %t -emit-module -emit-module-path=%t/resilient_class.swiftmodule -module-name resilient_class %S/../Inputs/resilient_class.swift
-// RUN: %target-swift-frontend -enable-sil-ownership -enable-resilience -emit-silgen -parse-as-library -I %t %s | %FileCheck %s
+// RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_struct.swiftmodule -module-name resilient_struct %S/../Inputs/resilient_struct.swift
+// RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_class.swiftmodule -module-name resilient_class %S/../Inputs/resilient_class.swift
+// RUN: %target-swift-frontend -module-name partial_apply_super -enable-resilience -emit-silgen -parse-as-library -I %t %s | %FileCheck %s
 
 import resilient_class
 
diff --git a/test/SILGen/plus_zero_pgo_checked_cast.swift b/test/SILGen/plus_zero_pgo_checked_cast.swift
index a479e87..735e164 100644
--- a/test/SILGen/plus_zero_pgo_checked_cast.swift
+++ b/test/SILGen/plus_zero_pgo_checked_cast.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-build-swift %s -profile-generate -Xfrontend -disable-incremental-llvm-codegen -module-name pgo_checked_cast -o %t/main
 // RUN: env LLVM_PROFILE_FILE=%t/default.profraw %target-run %t/main
diff --git a/test/SILGen/plus_zero_pgo_switchenum.swift b/test/SILGen/plus_zero_pgo_switchenum.swift
index 405912d..ca7e710 100644
--- a/test/SILGen/plus_zero_pgo_switchenum.swift
+++ b/test/SILGen/plus_zero_pgo_switchenum.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-build-swift %s -Xfrontend -enable-sil-ownership -profile-generate -Xfrontend -disable-incremental-llvm-codegen -module-name pgo_switchenum -o %t/main
 // RUN: env LLVM_PROFILE_FILE=%t/default.profraw %target-run %t/main
diff --git a/test/SILGen/plus_zero_pointer_conversion.swift b/test/SILGen/plus_zero_pointer_conversion.swift
index a07a9cf..0ab761d 100644
--- a/test/SILGen/plus_zero_pointer_conversion.swift
+++ b/test/SILGen/plus_zero_pointer_conversion.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name pointer_conversion -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
 
 // FIXME: rdar://problem/19648117 Needs splitting objc parts out
 // XFAIL: linux
diff --git a/test/SILGen/plus_zero_properties.swift b/test/SILGen/plus_zero_properties.swift
index 76dd9c9..e7398e7 100644
--- a/test/SILGen/plus_zero_properties.swift
+++ b/test/SILGen/plus_zero_properties.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name properties -Xllvm -sil-full-demangle -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module %s | %FileCheck %s
 
 var zero: Int = 0
 
@@ -233,7 +234,7 @@
   // -- writeback to val.ref.val_prop
   // CHECK: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]]
   // CHECK: [[WRITEBACK]]([[CALLBACK_ADDR:%.*]] : $Builtin.RawPointer):
-  // CHECK: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Ref, @thick Ref.Type) -> ()
+  // CHECK: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed Ref, @thick Ref.Type) -> ()
   // CHECK: [[REF_MAT:%.*]] = alloc_stack $Ref
   // CHECK: store [[VAL_REF]] to [init] [[REF_MAT]]
   // CHECK: [[T0:%.*]] = metatype $@thick Ref.Type
diff --git a/test/SILGen/plus_zero_property_abstraction.swift b/test/SILGen/plus_zero_property_abstraction.swift
index ab74768..33991ac 100644
--- a/test/SILGen/plus_zero_property_abstraction.swift
+++ b/test/SILGen/plus_zero_property_abstraction.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name property_abstraction -enable-sil-ownership -emit-silgen %s | %FileCheck %s
 
 struct Int {
   mutating func foo() {}
diff --git a/test/SILGen/plus_zero_protocol_extensions.swift b/test/SILGen/plus_zero_protocol_extensions.swift
index ec1dd26..2dd16f1 100644
--- a/test/SILGen/plus_zero_protocol_extensions.swift
+++ b/test/SILGen/plus_zero_protocol_extensions.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name protocol_extensions -disable-objc-attr-requires-foundation-module -emit-silgen %s | %FileCheck %s
 
 public protocol P1 {
   func reqP1a()
diff --git a/test/SILGen/plus_zero_protocol_optional.swift b/test/SILGen/plus_zero_protocol_optional.swift
index 25e1dd6..671c5d4 100644
--- a/test/SILGen/plus_zero_protocol_optional.swift
+++ b/test/SILGen/plus_zero_protocol_optional.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name protocol_optional -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s
 
 @objc protocol P1 {
   @objc optional func method(_ x: Int)
diff --git a/test/SILGen/plus_zero_protocol_resilience.swift b/test/SILGen/plus_zero_protocol_resilience.swift
index df24b0f..bb682ac 100644
--- a/test/SILGen/plus_zero_protocol_resilience.swift
+++ b/test/SILGen/plus_zero_protocol_resilience.swift
@@ -1,7 +1,8 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
-// RUN: %target-swift-frontend -emit-module -enable-sil-ownership -enable-resilience -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift
-// RUN: %target-swift-frontend -I %t -emit-silgen -enable-sil-ownership -enable-resilience %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name protocol_resilience -emit-module -enable-sil-ownership -enable-resilience -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift
+// RUN: %target-swift-frontend -module-name protocol_resilience -I %t -emit-silgen -enable-sil-ownership -enable-resilience %s | %FileCheck %s
 
 import resilient_protocol
 
diff --git a/test/SILGen/plus_zero_protocols.swift b/test/SILGen/plus_zero_protocols.swift
index 20cb940..728ea06 100644
--- a/test/SILGen/plus_zero_protocols.swift
+++ b/test/SILGen/plus_zero_protocols.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name protocols -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 //===----------------------------------------------------------------------===//
 // Calling Existential Subscripts
diff --git a/test/SILGen/plus_zero_reabstract-tuple.swift b/test/SILGen/plus_zero_reabstract-tuple.swift
index 8553bba..75a3b50 100644
--- a/test/SILGen/plus_zero_reabstract-tuple.swift
+++ b/test/SILGen/plus_zero_reabstract-tuple.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -enable-sil-ownership -emit-silgen -verify %s | %FileCheck %s
 
 // SR-3090:
diff --git a/test/SILGen/plus_zero_reabstract.swift b/test/SILGen/plus_zero_reabstract.swift
index 03389c7..6c37099 100644
--- a/test/SILGen/plus_zero_reabstract.swift
+++ b/test/SILGen/plus_zero_reabstract.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name reabstract -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func takeFn<T>(_ f : (T) -> T?) {}
 func liftOptional(_ x : Int) -> Int? { return x }
diff --git a/test/SILGen/plus_zero_reabstract_lvalue.swift b/test/SILGen/plus_zero_reabstract_lvalue.swift
index 66a9907..1905f4c 100644
--- a/test/SILGen/plus_zero_reabstract_lvalue.swift
+++ b/test/SILGen/plus_zero_reabstract_lvalue.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 struct MyMetatypeIsThin {}
diff --git a/test/SILGen/plus_zero_result_abstraction.swift b/test/SILGen/plus_zero_result_abstraction.swift
index af83741..81911dc 100644
--- a/test/SILGen/plus_zero_result_abstraction.swift
+++ b/test/SILGen/plus_zero_result_abstraction.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name result_abstraction -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 struct S {}
 struct R {}
diff --git a/test/SILGen/plus_zero_retaining_globals.swift b/test/SILGen/plus_zero_retaining_globals.swift
index 481a643..fd48daf 100644
--- a/test/SILGen/plus_zero_retaining_globals.swift
+++ b/test/SILGen/plus_zero_retaining_globals.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/globals.h -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name retaining_globals -import-objc-header %S/Inputs/globals.h -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 // REQUIRES: objc_interop
 
 
diff --git a/test/SILGen/plus_zero_rethrows.swift b/test/SILGen/plus_zero_rethrows.swift
index 0b5dfe7..e9cadab 100644
--- a/test/SILGen/plus_zero_rethrows.swift
+++ b/test/SILGen/plus_zero_rethrows.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -emit-sil -verify %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name rethrows -enable-sil-ownership -emit-sil -verify %s | %FileCheck %s
 
 @discardableResult
 func rethrower(_ fn: () throws -> Int) rethrows -> Int {
diff --git a/test/SILGen/plus_zero_scalar_to_tuple_args.swift b/test/SILGen/plus_zero_scalar_to_tuple_args.swift
index b6bfb8a..438095c 100644
--- a/test/SILGen/plus_zero_scalar_to_tuple_args.swift
+++ b/test/SILGen/plus_zero_scalar_to_tuple_args.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name scalar_to_tuple_args -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func inoutWithDefaults(_ x: inout Int, y: Int = 0, z: Int = 0) {}
 func inoutWithCallerSideDefaults(_ x: inout Int, y: Int = #line) {}
diff --git a/test/SILGen/plus_zero_shared.swift b/test/SILGen/plus_zero_shared.swift
index 46ec6da..0889de8 100644
--- a/test/SILGen/plus_zero_shared.swift
+++ b/test/SILGen/plus_zero_shared.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
 
 // REQUIRES: owned_parameters
diff --git a/test/SILGen/plus_zero_sil_locations.swift b/test/SILGen/plus_zero_sil_locations.swift
index 19f9b55..3c8546d 100644
--- a/test/SILGen/plus_zero_sil_locations.swift
+++ b/test/SILGen/plus_zero_sil_locations.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -Xllvm -sil-print-debuginfo -emit-verbose-sil -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name sil_locations -emit-silgen -Xllvm -sil-print-debuginfo -emit-verbose-sil -enable-sil-ownership %s | %FileCheck %s
 
 // FIXME: Not sure if this an ideal source info for the branch - 
 // it points to if, not the last instruction in the block.
@@ -77,7 +78,7 @@
 func useTemplateTest() -> Int {
   return templateTest(5);
   // CHECK-LABEL: sil hidden @$S13sil_locations15useTemplateTestSiyF
-  // CHECK: function_ref @$SSi2{{[_0-9a-zA-Z]*}}fC :{{.*}}, loc "{{.*}}":77
+  // CHECK: function_ref @$SSi2{{[_0-9a-zA-Z]*}}fC :{{.*}}, loc "{{.*}}":79
 }
 
 func foo(_ x: Int) -> Int {
diff --git a/test/SILGen/plus_zero_source_location.swift b/test/SILGen/plus_zero_source_location.swift
index b61fef9..979e3fb 100644
--- a/test/SILGen/plus_zero_source_location.swift
+++ b/test/SILGen/plus_zero_source_location.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -Xllvm -sil-print-debuginfo -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name source_location -Xllvm -sil-full-demangle -Xllvm -sil-print-debuginfo -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func printSourceLocation(file: String = #file, line: Int = #line) {}
 
diff --git a/test/SILGen/plus_zero_specialize_attr.swift b/test/SILGen/plus_zero_specialize_attr.swift
index 7ee8a18..71f73c3 100644
--- a/test/SILGen/plus_zero_specialize_attr.swift
+++ b/test/SILGen/plus_zero_specialize_attr.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -emit-verbose-sil %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name specialize_attr -emit-silgen -enable-sil-ownership -emit-verbose-sil %s | %FileCheck %s
 
 // CHECK-LABEL: @_specialize(exported: false, kind: full, where T == Int, U == Float)
 // CHECK-NEXT: func specializeThis<T, U>(_ t: T, u: U)
diff --git a/test/SILGen/plus_zero_statements.swift b/test/SILGen/plus_zero_statements.swift
index d3fe1bd..fbfea10 100644
--- a/test/SILGen/plus_zero_statements.swift
+++ b/test/SILGen/plus_zero_statements.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -parse-as-library -emit-silgen -enable-sil-ownership -verify %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name statements -Xllvm -sil-full-demangle -parse-as-library -emit-silgen -enable-sil-ownership -verify %s | %FileCheck %s
 
 class MyClass { 
   func foo() { }
diff --git a/test/SILGen/plus_zero_struct_resilience.swift b/test/SILGen/plus_zero_struct_resilience.swift
index b11d502..eb68e0e 100644
--- a/test/SILGen/plus_zero_struct_resilience.swift
+++ b/test/SILGen/plus_zero_struct_resilience.swift
@@ -1,7 +1,8 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
-// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -enable-sil-ownership -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
-// RUN: %target-swift-frontend -I %t -enable-sil-ownership -emit-silgen -enable-resilience %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name struct_resilience -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -enable-sil-ownership -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
+// RUN: %target-swift-frontend -module-name struct_resilience -I %t -enable-sil-ownership -emit-silgen -enable-resilience %s | %FileCheck %s
 
 import resilient_struct
 
diff --git a/test/SILGen/plus_zero_subclass_existentials.swift b/test/SILGen/plus_zero_subclass_existentials.swift
index 0189ede..cdef1fd 100644
--- a/test/SILGen/plus_zero_subclass_existentials.swift
+++ b/test/SILGen/plus_zero_subclass_existentials.swift
@@ -1,6 +1,7 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -parse-as-library -primary-file %s -verify | %FileCheck %s
-// RUN: %target-swift-frontend -emit-ir -parse-as-library -primary-file %s
+
+// RUN: %target-swift-frontend -module-name subclass_existentials -Xllvm -sil-full-demangle -emit-silgen -parse-as-library -primary-file %s -verify | %FileCheck %s
+// RUN: %target-swift-frontend -module-name subclass_existentials -emit-ir -parse-as-library -primary-file %s
 
 // Note: we pass -verify above to ensure there are no spurious
 // compiler warnings relating to casts.
diff --git a/test/SILGen/plus_zero_super.swift b/test/SILGen/plus_zero_super.swift
index 5184967..bbd8219 100644
--- a/test/SILGen/plus_zero_super.swift
+++ b/test/SILGen/plus_zero_super.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_struct.swiftmodule -module-name resilient_struct %S/../Inputs/resilient_struct.swift
 // RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_class.swiftmodule -module-name resilient_class %S/../Inputs/resilient_class.swift
-// RUN: %target-swift-frontend -emit-silgen -parse-as-library -I %t %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name super -emit-silgen -parse-as-library -I %t %s | %FileCheck %s
 
 import resilient_class
 
diff --git a/test/SILGen/plus_zero_switch.swift b/test/SILGen/plus_zero_switch.swift
index e81e078..6c13049 100644
--- a/test/SILGen/plus_zero_switch.swift
+++ b/test/SILGen/plus_zero_switch.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name switch -emit-silgen %s | %FileCheck %s
 
 func markUsed<T>(_ t: T) {}
 
diff --git a/test/SILGen/plus_zero_switch_abstraction.swift b/test/SILGen/plus_zero_switch_abstraction.swift
index 86ebbc9..aec5b2e 100644
--- a/test/SILGen/plus_zero_switch_abstraction.swift
+++ b/test/SILGen/plus_zero_switch_abstraction.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -parse-stdlib %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name switch_abstraction -emit-silgen -enable-sil-ownership -parse-stdlib %s | %FileCheck %s
 
 struct A {}
 
diff --git a/test/SILGen/plus_zero_switch_isa.swift b/test/SILGen/plus_zero_switch_isa.swift
index 7ad4e70..1a50b5c 100644
--- a/test/SILGen/plus_zero_switch_isa.swift
+++ b/test/SILGen/plus_zero_switch_isa.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name switch_isa -emit-silgen %s | %FileCheck %s
 
 func markUsed<T>(_ t: T) {}
 
diff --git a/test/SILGen/plus_zero_switch_multiple_entry_address_only.swift b/test/SILGen/plus_zero_switch_multiple_entry_address_only.swift
index 1e70918..0d3cbca 100644
--- a/test/SILGen/plus_zero_switch_multiple_entry_address_only.swift
+++ b/test/SILGen/plus_zero_switch_multiple_entry_address_only.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend %s -emit-silgen | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name switch_multiple_entry_address_only %s -emit-silgen | %FileCheck %s
 
 enum E {
 case a(Any)
diff --git a/test/SILGen/plus_zero_switch_var.swift b/test/SILGen/plus_zero_switch_var.swift
index becf093..4ae81d4 100644
--- a/test/SILGen/plus_zero_switch_var.swift
+++ b/test/SILGen/plus_zero_switch_var.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name switch_var -emit-silgen %s | %FileCheck %s
 
 // TODO: Implement tuple equality in the library.
 // BLOCKED: <rdar://problem/13822406>
diff --git a/test/SILGen/plus_zero_testable-multifile-other.swift b/test/SILGen/plus_zero_testable-multifile-other.swift
index b517849..ffec7ac 100644
--- a/test/SILGen/plus_zero_testable-multifile-other.swift
+++ b/test/SILGen/plus_zero_testable-multifile-other.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // This test is paired with testable-multifile.swift.
 
 // RUN: %empty-directory(%t)
diff --git a/test/SILGen/plus_zero_tuples.swift b/test/SILGen/plus_zero_tuples.swift
index c0e0a3d..3427db0 100644
--- a/test/SILGen/plus_zero_tuples.swift
+++ b/test/SILGen/plus_zero_tuples.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name tuples -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 class C {}
 
 enum Foo {
diff --git a/test/SILGen/plus_zero_types.swift b/test/SILGen/plus_zero_types.swift
index ff5aae4..f8903b5 100644
--- a/test/SILGen/plus_zero_types.swift
+++ b/test/SILGen/plus_zero_types.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -parse-as-library -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 class C {
diff --git a/test/SILGen/plus_zero_unmanaged.swift b/test/SILGen/plus_zero_unmanaged.swift
index 0a8d7b2..b3217ff 100644
--- a/test/SILGen/plus_zero_unmanaged.swift
+++ b/test/SILGen/plus_zero_unmanaged.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -emit-sil %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name unmanaged -enable-sil-ownership -emit-sil %s | %FileCheck %s
 
 class C {}
 
diff --git a/test/SILGen/plus_zero_unmanaged_ownership.swift b/test/SILGen/plus_zero_unmanaged_ownership.swift
index 8384266..3b8850f 100644
--- a/test/SILGen/plus_zero_unmanaged_ownership.swift
+++ b/test/SILGen/plus_zero_unmanaged_ownership.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -module-name Swift -emit-silgen %s | %FileCheck %s
 
 class C {}
diff --git a/test/SILGen/plus_zero_unowned.swift b/test/SILGen/plus_zero_unowned.swift
index ff712fb..7845c73 100644
--- a/test/SILGen/plus_zero_unowned.swift
+++ b/test/SILGen/plus_zero_unowned.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name unowned -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func takeClosure(_ fn: () -> Int) {}
 
diff --git a/test/SILGen/plus_zero_vtable_thunks_reabstraction_final.swift b/test/SILGen/plus_zero_vtable_thunks_reabstraction_final.swift
index 4cd5aee..197e0a3 100644
--- a/test/SILGen/plus_zero_vtable_thunks_reabstraction_final.swift
+++ b/test/SILGen/plus_zero_vtable_thunks_reabstraction_final.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name vtable_thunks_reabstraction_final -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 protocol Fooable {
   func foo(_ x: Int) -> Int?
diff --git a/test/SILGen/plus_zero_vtables_objc.swift b/test/SILGen/plus_zero_vtables_objc.swift
index ef5fbb0..d05a728 100644
--- a/test/SILGen/plus_zero_vtables_objc.swift
+++ b/test/SILGen/plus_zero_vtables_objc.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -sdk %S/Inputs -emit-silgen -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name vtables_objc -enable-sil-ownership -sdk %S/Inputs -emit-silgen -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/plus_zero_weak.swift b/test/SILGen/plus_zero_weak.swift
index 919a55f..039a2ab 100644
--- a/test/SILGen/plus_zero_weak.swift
+++ b/test/SILGen/plus_zero_weak.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name weak -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 class C {
   func f() -> Int { return 42 }
diff --git a/test/SILGen/plus_zero_weak_multiple_modules.swift b/test/SILGen/plus_zero_weak_multiple_modules.swift
index 2c97546..19160ab 100644
--- a/test/SILGen/plus_zero_weak_multiple_modules.swift
+++ b/test/SILGen/plus_zero_weak_multiple_modules.swift
@@ -1,7 +1,8 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -emit-module-path=%t/weak_other.swiftmodule -module-name=weak_other %S/Inputs/weak_other.swift
-// RUN: %target-swift-frontend -I %t -emit-silgen -enable-sil-ownership %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime
+// RUN: %target-swift-frontend -module-name weak_multiple_modules -I %t -emit-silgen -enable-sil-ownership %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime
 
 import weak_other
 
diff --git a/test/SILGen/plus_zero_without_actually_escaping.swift b/test/SILGen/plus_zero_without_actually_escaping.swift
index cce3e9c..c588d4e 100644
--- a/test/SILGen/plus_zero_without_actually_escaping.swift
+++ b/test/SILGen/plus_zero_without_actually_escaping.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name without_actually_escaping -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 var escapeHatch: Any = 0
 
diff --git a/test/SILGen/plus_zero_witness_same_type.swift b/test/SILGen/plus_zero_witness_same_type.swift
index 93335d1..3658e49 100644
--- a/test/SILGen/plus_zero_witness_same_type.swift
+++ b/test/SILGen/plus_zero_witness_same_type.swift
@@ -1,6 +1,7 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
-// RUN: %target-swift-frontend -enable-sil-ownership -emit-ir %s
+
+// RUN: %target-swift-frontend -module-name witness_same_type -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name witness_same_type -enable-sil-ownership -emit-ir %s
 
 protocol Fooable {
   associatedtype Bar
diff --git a/test/SILGen/plus_zero_witness_tables.swift b/test/SILGen/plus_zero_witness_tables.swift
index e188c03..6b46ffe 100644
--- a/test/SILGen/plus_zero_witness_tables.swift
+++ b/test/SILGen/plus_zero_witness_tables.swift
@@ -1,9 +1,10 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module > %t.sil
+
+// RUN: %target-swift-frontend -module-name witness_tables -emit-silgen -enable-sil-ownership -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module > %t.sil
 // RUN: %FileCheck -check-prefix=TABLE -check-prefix=TABLE-ALL %s < %t.sil
 // RUN: %FileCheck -check-prefix=SYMBOL %s < %t.sil
 
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module -enable-testing > %t.testable.sil
+// RUN: %target-swift-frontend -module-name witness_tables -emit-silgen -enable-sil-ownership -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module -enable-testing > %t.testable.sil
 // RUN: %FileCheck -check-prefix=TABLE-TESTABLE -check-prefix=TABLE-ALL %s < %t.testable.sil
 // RUN: %FileCheck -check-prefix=SYMBOL-TESTABLE %s < %t.testable.sil
 
diff --git a/test/SILGen/plus_zero_witnesses.swift b/test/SILGen/plus_zero_witnesses.swift
index f618418..4ba0428 100644
--- a/test/SILGen/plus_zero_witnesses.swift
+++ b/test/SILGen/plus_zero_witnesses.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name witnesses -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
 
 infix operator <~> {}
 
diff --git a/test/SILGen/plus_zero_witnesses_class.swift b/test/SILGen/plus_zero_witnesses_class.swift
index 3ec494b..2bae1fe 100644
--- a/test/SILGen/plus_zero_witnesses_class.swift
+++ b/test/SILGen/plus_zero_witnesses_class.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_zero_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name witnesses_class -enable-sil-ownership -emit-silgen %s | %FileCheck %s
 
 protocol Fooable: class {
   func foo()
diff --git a/test/SILGen/pointer_conversion.swift b/test/SILGen/pointer_conversion.swift
index 9d540d2..bdea8e1 100644
--- a/test/SILGen/pointer_conversion.swift
+++ b/test/SILGen/pointer_conversion.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name pointer_conversion -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
 
 // FIXME: rdar://problem/19648117 Needs splitting objc parts out
 // XFAIL: linux
diff --git a/test/SILGen/properties.swift b/test/SILGen/properties.swift
index 841c8b8..d8b80e9 100644
--- a/test/SILGen/properties.swift
+++ b/test/SILGen/properties.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name properties -Xllvm -sil-full-demangle -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module %s | %FileCheck %s
 
 var zero: Int = 0
 
diff --git a/test/SILGen/property_abstraction.swift b/test/SILGen/property_abstraction.swift
index beb71e7..8f21c5f 100644
--- a/test/SILGen/property_abstraction.swift
+++ b/test/SILGen/property_abstraction.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name property_abstraction -enable-sil-ownership -emit-silgen %s | %FileCheck %s
 
 struct Int {
   mutating func foo() {}
diff --git a/test/SILGen/protocol_extensions.swift b/test/SILGen/protocol_extensions.swift
index f01358e..a7b290b 100644
--- a/test/SILGen/protocol_extensions.swift
+++ b/test/SILGen/protocol_extensions.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name protocol_extensions -disable-objc-attr-requires-foundation-module -emit-silgen %s | %FileCheck %s
 
 public protocol P1 {
   func reqP1a()
diff --git a/test/SILGen/protocol_optional.swift b/test/SILGen/protocol_optional.swift
index 550908f..0b7849a 100644
--- a/test/SILGen/protocol_optional.swift
+++ b/test/SILGen/protocol_optional.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name protocol_optional -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s
 
 @objc protocol P1 {
   @objc optional func method(_ x: Int)
diff --git a/test/SILGen/protocol_resilience.swift b/test/SILGen/protocol_resilience.swift
index f28b215..b9dd1dd 100644
--- a/test/SILGen/protocol_resilience.swift
+++ b/test/SILGen/protocol_resilience.swift
@@ -1,7 +1,8 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
-// RUN: %target-swift-frontend -emit-module -enable-sil-ownership -enable-resilience -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift
-// RUN: %target-swift-frontend -I %t -emit-silgen -enable-sil-ownership -enable-resilience %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name protocol_resilience -emit-module -enable-sil-ownership -enable-resilience -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift
+// RUN: %target-swift-frontend -module-name protocol_resilience -I %t -emit-silgen -enable-sil-ownership -enable-resilience %s | %FileCheck %s
 
 import resilient_protocol
 
diff --git a/test/SILGen/protocols.swift b/test/SILGen/protocols.swift
index 15ff6b3..0bd9758 100644
--- a/test/SILGen/protocols.swift
+++ b/test/SILGen/protocols.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name protocols -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 //===----------------------------------------------------------------------===//
 // Calling Existential Subscripts
diff --git a/test/SILGen/reabstract-tuple.swift b/test/SILGen/reabstract-tuple.swift
index d3cfb5d..4e5d0c7 100644
--- a/test/SILGen/reabstract-tuple.swift
+++ b/test/SILGen/reabstract-tuple.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -enable-sil-ownership -emit-silgen -verify %s | %FileCheck %s
 
 // SR-3090:
diff --git a/test/SILGen/reabstract.swift b/test/SILGen/reabstract.swift
index 8736780..49d6062 100644
--- a/test/SILGen/reabstract.swift
+++ b/test/SILGen/reabstract.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name reabstract -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func takeFn<T>(_ f : (T) -> T?) {}
 func liftOptional(_ x : Int) -> Int? { return x }
diff --git a/test/SILGen/reabstract_lvalue.swift b/test/SILGen/reabstract_lvalue.swift
index 8cbd9b8..61a8b3f 100644
--- a/test/SILGen/reabstract_lvalue.swift
+++ b/test/SILGen/reabstract_lvalue.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 struct MyMetatypeIsThin {}
diff --git a/test/SILGen/result_abstraction.swift b/test/SILGen/result_abstraction.swift
index e2b49e1..64609d5 100644
--- a/test/SILGen/result_abstraction.swift
+++ b/test/SILGen/result_abstraction.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name result_abstraction -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 struct S {}
 struct R {}
diff --git a/test/SILGen/retaining_globals.swift b/test/SILGen/retaining_globals.swift
index 87756cc..991d6ae 100644
--- a/test/SILGen/retaining_globals.swift
+++ b/test/SILGen/retaining_globals.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/globals.h -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name retaining_globals -import-objc-header %S/Inputs/globals.h -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 // REQUIRES: objc_interop
 
 
diff --git a/test/SILGen/rethrows.swift b/test/SILGen/rethrows.swift
index ad23e4a..bec3c93 100644
--- a/test/SILGen/rethrows.swift
+++ b/test/SILGen/rethrows.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -emit-sil -verify %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name rethrows -enable-sil-ownership -emit-sil -verify %s | %FileCheck %s
 
 @discardableResult
 func rethrower(_ fn: () throws -> Int) rethrows -> Int {
diff --git a/test/SILGen/scalar_to_tuple_args.swift b/test/SILGen/scalar_to_tuple_args.swift
index 8fd38f6..c66e53d 100644
--- a/test/SILGen/scalar_to_tuple_args.swift
+++ b/test/SILGen/scalar_to_tuple_args.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name scalar_to_tuple_args -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func inoutWithDefaults(_ x: inout Int, y: Int = 0, z: Int = 0) {}
 func inoutWithCallerSideDefaults(_ x: inout Int, y: Int = #line) {}
diff --git a/test/SILGen/shared.swift b/test/SILGen/shared.swift
index c0af68e..4d6c361 100644
--- a/test/SILGen/shared.swift
+++ b/test/SILGen/shared.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
 
 class RefAggregate {}
diff --git a/test/SILGen/sil_locations.swift b/test/SILGen/sil_locations.swift
index 7614fb1..4176f16 100644
--- a/test/SILGen/sil_locations.swift
+++ b/test/SILGen/sil_locations.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -Xllvm -sil-print-debuginfo -emit-verbose-sil -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name sil_locations -emit-silgen -Xllvm -sil-print-debuginfo -emit-verbose-sil -enable-sil-ownership %s | %FileCheck %s
 
 // FIXME: Not sure if this an ideal source info for the branch - 
 // it points to if, not the last instruction in the block.
@@ -77,7 +78,7 @@
 func useTemplateTest() -> Int {
   return templateTest(5);
   // CHECK-LABEL: sil hidden @$S13sil_locations15useTemplateTestSiyF
-  // CHECK: function_ref @$SSi2{{[_0-9a-zA-Z]*}}fC :{{.*}}, loc "{{.*}}":78
+  // CHECK: function_ref @$SSi2{{[_0-9a-zA-Z]*}}fC :{{.*}}, loc "{{.*}}":79
 }
 
 func foo(_ x: Int) -> Int {
@@ -128,9 +129,9 @@
   var x:Int
   x = 0
   switch (switchfoo(), switchbar()) {
-  // CHECK: store {{.*}}, loc "{{.*}}":[[@LINE+1]]
+  // CHECK: store {{.*}}, loc "{{.*}}":[[@LINE-1]]
   case (1,2):
-  // CHECK: integer_literal $Builtin.Int2048, 2, loc "{{.*}}":[[@LINE-1]]:11
+  // CHECK: integer_literal $Builtin.Int2048, 2, loc "{{.*}}":[[@LINE-3]]:10
   // FIXME: Location info is missing.
   // CHECK: cond_br
   //
diff --git a/test/SILGen/source_location.swift b/test/SILGen/source_location.swift
index 67916ef..3baa45d 100644
--- a/test/SILGen/source_location.swift
+++ b/test/SILGen/source_location.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -Xllvm -sil-print-debuginfo -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name source_location -Xllvm -sil-full-demangle -Xllvm -sil-print-debuginfo -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func printSourceLocation(file: String = #file, line: Int = #line) {}
 
diff --git a/test/SILGen/specialize_attr.swift b/test/SILGen/specialize_attr.swift
index 0c45041..f0ba417 100644
--- a/test/SILGen/specialize_attr.swift
+++ b/test/SILGen/specialize_attr.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -emit-verbose-sil %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name specialize_attr -emit-silgen -enable-sil-ownership -emit-verbose-sil %s | %FileCheck %s
 
 // CHECK-LABEL: @_specialize(exported: false, kind: full, where T == Int, U == Float)
 // CHECK-NEXT: func specializeThis<T, U>(_ t: T, u: U)
diff --git a/test/SILGen/statements.swift b/test/SILGen/statements.swift
index 212f42e..894d092 100644
--- a/test/SILGen/statements.swift
+++ b/test/SILGen/statements.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -parse-as-library -emit-silgen -enable-sil-ownership -verify %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name statements -Xllvm -sil-full-demangle -parse-as-library -emit-silgen -enable-sil-ownership -verify %s | %FileCheck %s
 
 class MyClass { 
   func foo() { }
diff --git a/test/SILGen/struct_resilience.swift b/test/SILGen/struct_resilience.swift
index 5d50e67..221b018 100644
--- a/test/SILGen/struct_resilience.swift
+++ b/test/SILGen/struct_resilience.swift
@@ -1,7 +1,8 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
-// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -enable-sil-ownership -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
-// RUN: %target-swift-frontend -I %t -enable-sil-ownership -emit-silgen -enable-resilience %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name struct_resilience -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -enable-sil-ownership -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
+// RUN: %target-swift-frontend -module-name struct_resilience -I %t -enable-sil-ownership -emit-silgen -enable-resilience %s | %FileCheck %s
 
 import resilient_struct
 
diff --git a/test/SILGen/subclass_existentials.swift b/test/SILGen/subclass_existentials.swift
index dbd0cba..6112ae3 100644
--- a/test/SILGen/subclass_existentials.swift
+++ b/test/SILGen/subclass_existentials.swift
@@ -1,6 +1,7 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -parse-as-library -primary-file %s -verify | %FileCheck %s
-// RUN: %target-swift-frontend -emit-ir -parse-as-library -primary-file %s
+
+// RUN: %target-swift-frontend -module-name subclass_existentials -Xllvm -sil-full-demangle -emit-silgen -parse-as-library -primary-file %s -verify | %FileCheck %s
+// RUN: %target-swift-frontend -module-name subclass_existentials -emit-ir -parse-as-library -primary-file %s
 
 // Note: we pass -verify above to ensure there are no spurious
 // compiler warnings relating to casts.
diff --git a/test/SILGen/super.swift b/test/SILGen/super.swift
index c00184c..fb085fb 100644
--- a/test/SILGen/super.swift
+++ b/test/SILGen/super.swift
@@ -1,8 +1,9 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_struct.swiftmodule -module-name resilient_struct %S/../Inputs/resilient_struct.swift
 // RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_class.swiftmodule -module-name resilient_class %S/../Inputs/resilient_class.swift
-// RUN: %target-swift-frontend -emit-silgen -parse-as-library -I %t %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name super -emit-silgen -parse-as-library -I %t %s | %FileCheck %s
 
 import resilient_class
 
diff --git a/test/SILGen/switch.swift b/test/SILGen/switch.swift
index 175a476..1b0122a 100644
--- a/test/SILGen/switch.swift
+++ b/test/SILGen/switch.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name switch -emit-silgen %s | %FileCheck %s
 
 func markUsed<T>(_ t: T) {}
 
diff --git a/test/SILGen/switch_abstraction.swift b/test/SILGen/switch_abstraction.swift
index 3b8e042..5c64499 100644
--- a/test/SILGen/switch_abstraction.swift
+++ b/test/SILGen/switch_abstraction.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -parse-stdlib %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name switch_abstraction -emit-silgen -enable-sil-ownership -parse-stdlib %s | %FileCheck %s
 
 struct A {}
 
diff --git a/test/SILGen/switch_debuginfo.swift b/test/SILGen/switch_debuginfo.swift
new file mode 100644
index 0000000..2886292
--- /dev/null
+++ b/test/SILGen/switch_debuginfo.swift
@@ -0,0 +1,104 @@
+// RUN: %target-swift-frontend -g -Xllvm -sil-print-debuginfo -emit-silgen %s | %FileCheck %s
+
+func nop1() {}
+func nop2() {}
+
+enum Binary {
+  case On
+  case Off
+}
+
+func isOn(_ b: Binary) -> Bool {
+  return b == .On
+}
+
+// CHECK: [[LOC:loc "[^"]+"]]
+
+// First, check that we don't assign fresh locations to each case statement,
+// except for any relevant debug value instructions.
+// CHECK-LABEL: sil hidden @$S16switch_debuginfo5test11iySi_tF
+func test1(i: Int) {
+  switch i {
+           // CHECK-NOT: [[LOC]]:[[@LINE+1]]
+  case 0:  // CHECK: debug_value {{.*}} : $Int, let, name "$match", [[LOC]]:[[@LINE]]
+           // CHECK-NOT: [[LOC]]:[[@LINE-1]]
+    nop1()
+
+           // CHECK-NOT: [[LOC]]:[[@LINE+1]]
+  case 1:  // CHECK: debug_value {{.*}} : $Int, let, name "$match", [[LOC]]:[[@LINE]]
+           // CHECK-NOT: [[LOC]]:[[@LINE-1]]
+    nop1()
+
+  default: // CHECK-NOT: [[LOC]]:[[@LINE]]
+    nop1()
+  }
+}
+
+// Next, check that case statements and switch subjects have the same locations.
+// CHECK-LABEL: sil hidden @$S16switch_debuginfo5test21sySS_tF
+func test2(s: String) {
+  switch s {
+  case "a": // CHECK: string_literal utf8 "a", [[LOC]]:[[@LINE-1]]:10
+    nop1()
+  case "b": // CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-3]]:10
+    nop2()
+  default:
+    nop1()
+  }
+}
+
+// Fallthrough shouldn't affect case statement locations.
+// CHECK-LABEL: sil hidden @$S16switch_debuginfo5test31sySS_tF
+func test3(s: String) {
+  switch s {
+  case "a", "b":
+    // CHECK: string_literal utf8 "a", [[LOC]]:[[@LINE-2]]:10
+    // CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-3]]:10
+    nop1()
+    fallthrough
+  case "b", "c":
+    // CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-7]]:10
+    // CHECK: string_literal utf8 "c", [[LOC]]:[[@LINE-8]]:10
+    nop2()
+    fallthrough
+  default:
+    nop1()
+  }
+}
+
+// It should be possible to set breakpoints on where clauses.
+// CHECK-LABEL: sil hidden @$S16switch_debuginfo5test41byAA6BinaryO_tF
+func test4(b: Binary) {
+  switch b {
+  case let _        // CHECK-NOT: [[LOC]]:[[@LINE]]
+    where isOn(b):  // CHECK: [[LOC]]:[[@LINE]]:11
+    nop1()
+  case let _        // CHECK-NOT: [[LOC]]:[[@LINE]]
+    where !isOn(b): // CHECK: [[LOC]]:[[@LINE]]:11
+    nop2()
+  default:
+    nop1()
+  }
+}
+
+// Check that we set the right locations before/after nested switches.
+// CHECK-LABEL: sil hidden @$S16switch_debuginfo5test51sySS_tF
+func test5(s: String) {
+  switch s {
+  case "a":         // CHECK: string_literal utf8 "a", [[LOC]]:[[@LINE-1]]:10
+    switch "b" {
+    case "b":       // CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-1]]:12
+      nop1()
+    default:
+      nop2()
+    }
+    if "c" == "c" { // CHECK: string_literal utf8 "c", [[LOC]]:[[@LINE]]
+      nop1()
+    }
+  default:
+    nop1()
+  }
+  if "d" == "d" {   // CHECK: string_literal utf8 "d", [[LOC]]:[[@LINE]]
+    nop1()
+  }
+}
diff --git a/test/SILGen/switch_isa.swift b/test/SILGen/switch_isa.swift
index 4977f99..c1fbf9a 100644
--- a/test/SILGen/switch_isa.swift
+++ b/test/SILGen/switch_isa.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name switch_isa -emit-silgen %s | %FileCheck %s
 
 func markUsed<T>(_ t: T) {}
 
diff --git a/test/SILGen/switch_multiple_entry_address_only.swift b/test/SILGen/switch_multiple_entry_address_only.swift
index 2a94457..96485a8 100644
--- a/test/SILGen/switch_multiple_entry_address_only.swift
+++ b/test/SILGen/switch_multiple_entry_address_only.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend %s -emit-silgen | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name switch_multiple_entry_address_only %s -emit-silgen | %FileCheck %s
 
 enum E {
 case a(Any)
diff --git a/test/SILGen/switch_var.swift b/test/SILGen/switch_var.swift
index cc8b022..8aa584e 100644
--- a/test/SILGen/switch_var.swift
+++ b/test/SILGen/switch_var.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name switch_var -emit-silgen %s | %FileCheck %s
 
 // TODO: Implement tuple equality in the library.
 // BLOCKED: <rdar://problem/13822406>
diff --git a/test/SILGen/testable-multifile-other.swift b/test/SILGen/testable-multifile-other.swift
index e33d15c..50adb2a 100644
--- a/test/SILGen/testable-multifile-other.swift
+++ b/test/SILGen/testable-multifile-other.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // This test is paired with testable-multifile.swift.
 
 // RUN: %empty-directory(%t)
diff --git a/test/SILGen/tuples.swift b/test/SILGen/tuples.swift
index a05a467..e4dbf2d 100644
--- a/test/SILGen/tuples.swift
+++ b/test/SILGen/tuples.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name tuples -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 class C {}
 
 enum Foo {
diff --git a/test/SILGen/types.swift b/test/SILGen/types.swift
index d996b3e..18ff3b9 100644
--- a/test/SILGen/types.swift
+++ b/test/SILGen/types.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -parse-as-library -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 class C {
diff --git a/test/SILGen/unmanaged.swift b/test/SILGen/unmanaged.swift
index c8d98ea..422ccda 100644
--- a/test/SILGen/unmanaged.swift
+++ b/test/SILGen/unmanaged.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -emit-sil %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name unmanaged -enable-sil-ownership -emit-sil %s | %FileCheck %s
 
 class C {}
 
diff --git a/test/SILGen/unmanaged_ownership.swift b/test/SILGen/unmanaged_ownership.swift
index 21d447b..b8f6a40 100644
--- a/test/SILGen/unmanaged_ownership.swift
+++ b/test/SILGen/unmanaged_ownership.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -module-name Swift -emit-silgen %s | %FileCheck %s
 
 class C {}
diff --git a/test/SILGen/unowned.swift b/test/SILGen/unowned.swift
index 7c7e8a8..0c2853e 100644
--- a/test/SILGen/unowned.swift
+++ b/test/SILGen/unowned.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name unowned -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 func takeClosure(_ fn: () -> Int) {}
 
diff --git a/test/SILGen/vtable_thunks_reabstraction_final.swift b/test/SILGen/vtable_thunks_reabstraction_final.swift
index 68e4b6b..ab05615 100644
--- a/test/SILGen/vtable_thunks_reabstraction_final.swift
+++ b/test/SILGen/vtable_thunks_reabstraction_final.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name vtable_thunks_reabstraction_final -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 protocol Fooable {
   func foo(_ x: Int) -> Int?
diff --git a/test/SILGen/vtables_objc.swift b/test/SILGen/vtables_objc.swift
index eb45a91..533be64 100644
--- a/test/SILGen/vtables_objc.swift
+++ b/test/SILGen/vtables_objc.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -sdk %S/Inputs -emit-silgen -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name vtables_objc -enable-sil-ownership -sdk %S/Inputs -emit-silgen -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module | %FileCheck %s
 
 // REQUIRES: objc_interop
 
diff --git a/test/SILGen/weak.swift b/test/SILGen/weak.swift
index 0e2567c..2f5582f 100644
--- a/test/SILGen/weak.swift
+++ b/test/SILGen/weak.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name weak -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 class C {
   func f() -> Int { return 42 }
diff --git a/test/SILGen/weak_multiple_modules.swift b/test/SILGen/weak_multiple_modules.swift
index dcfdd34..a83d513 100644
--- a/test/SILGen/weak_multiple_modules.swift
+++ b/test/SILGen/weak_multiple_modules.swift
@@ -1,7 +1,8 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -emit-module-path=%t/weak_other.swiftmodule -module-name=weak_other %S/Inputs/weak_other.swift
-// RUN: %target-swift-frontend -I %t -emit-silgen -enable-sil-ownership %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime
+// RUN: %target-swift-frontend -module-name weak_multiple_modules -I %t -emit-silgen -enable-sil-ownership %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime
 
 import weak_other
 
diff --git a/test/SILGen/without_actually_escaping.swift b/test/SILGen/without_actually_escaping.swift
index 1719770..8f42687 100644
--- a/test/SILGen/without_actually_escaping.swift
+++ b/test/SILGen/without_actually_escaping.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name without_actually_escaping -emit-silgen -enable-sil-ownership %s | %FileCheck %s
 
 var escapeHatch: Any = 0
 
diff --git a/test/SILGen/witness_same_type.swift b/test/SILGen/witness_same_type.swift
index b5659c5..43d0604 100644
--- a/test/SILGen/witness_same_type.swift
+++ b/test/SILGen/witness_same_type.swift
@@ -1,6 +1,7 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
-// RUN: %target-swift-frontend -enable-sil-ownership -emit-ir %s
+
+// RUN: %target-swift-frontend -module-name witness_same_type -emit-silgen -enable-sil-ownership %s | %FileCheck %s
+// RUN: %target-swift-frontend -module-name witness_same_type -enable-sil-ownership -emit-ir %s
 
 protocol Fooable {
   associatedtype Bar
diff --git a/test/SILGen/witness_tables.swift b/test/SILGen/witness_tables.swift
index 9e0f98b..42ae3dc 100644
--- a/test/SILGen/witness_tables.swift
+++ b/test/SILGen/witness_tables.swift
@@ -1,9 +1,10 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module > %t.sil
+
+// RUN: %target-swift-frontend -module-name witness_tables -emit-silgen -enable-sil-ownership -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module > %t.sil
 // RUN: %FileCheck -check-prefix=TABLE -check-prefix=TABLE-ALL %s < %t.sil
 // RUN: %FileCheck -check-prefix=SYMBOL %s < %t.sil
 
-// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module -enable-testing > %t.testable.sil
+// RUN: %target-swift-frontend -module-name witness_tables -emit-silgen -enable-sil-ownership -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module -enable-testing > %t.testable.sil
 // RUN: %FileCheck -check-prefix=TABLE-TESTABLE -check-prefix=TABLE-ALL %s < %t.testable.sil
 // RUN: %FileCheck -check-prefix=SYMBOL-TESTABLE %s < %t.testable.sil
 
diff --git a/test/SILGen/witnesses.swift b/test/SILGen/witnesses.swift
index e78392d..c336647 100644
--- a/test/SILGen/witnesses.swift
+++ b/test/SILGen/witnesses.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name witnesses -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
 
 infix operator <~> {}
 
diff --git a/test/SILGen/witnesses_class.swift b/test/SILGen/witnesses_class.swift
index 64ca7a1..d269343 100644
--- a/test/SILGen/witnesses_class.swift
+++ b/test/SILGen/witnesses_class.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend -enable-sil-ownership -emit-silgen %s | %FileCheck %s
+
+// RUN: %target-swift-frontend -module-name witnesses_class -enable-sil-ownership -emit-silgen %s | %FileCheck %s
 
 protocol Fooable: class {
   func foo()
diff --git a/test/SILOptimizer/Inputs/TestMod.sil b/test/SILOptimizer/Inputs/TestMod.sil
index 9ae4a7a..ff36d56 100644
--- a/test/SILOptimizer/Inputs/TestMod.sil
+++ b/test/SILOptimizer/Inputs/TestMod.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // Test module for the specialize_cg_update_crash.sil test.
 
 sil_stage canonical
diff --git a/test/SILOptimizer/Inputs/plus_zero_TestMod.sil b/test/SILOptimizer/Inputs/plus_zero_TestMod.sil
index 62126fb..d0e1d1b 100644
--- a/test/SILOptimizer/Inputs/plus_zero_TestMod.sil
+++ b/test/SILOptimizer/Inputs/plus_zero_TestMod.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // Test module for the specialize_cg_update_crash.sil test.
 
 sil_stage canonical
diff --git a/test/SILOptimizer/access_enforcement_noescape.swift b/test/SILOptimizer/access_enforcement_noescape.swift
index ef753a5..5a33d56 100644
--- a/test/SILOptimizer/access_enforcement_noescape.swift
+++ b/test/SILOptimizer/access_enforcement_noescape.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -enable-sil-ownership -enforce-exclusivity=checked -Onone -emit-sil -swift-version 4 -verify -parse-as-library %s
 // RUN: %target-swift-frontend -enable-sil-ownership -enforce-exclusivity=checked -Onone -emit-sil -swift-version 3 -parse-as-library %s | %FileCheck %s
 // REQUIRES: asserts
diff --git a/test/SILOptimizer/access_marker_mandatory.swift b/test/SILOptimizer/access_marker_mandatory.swift
index be19716..6c2034a 100644
--- a/test/SILOptimizer/access_marker_mandatory.swift
+++ b/test/SILOptimizer/access_marker_mandatory.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -enable-sil-ownership -parse-as-library -Xllvm -sil-full-demangle -emit-sil -Onone -enforce-exclusivity=checked %s | %FileCheck %s
 
 public struct S {
diff --git a/test/SILOptimizer/access_marker_verify.swift b/test/SILOptimizer/access_marker_verify.swift
index 3e7cd7f..d0757a2 100644
--- a/test/SILOptimizer/access_marker_verify.swift
+++ b/test/SILOptimizer/access_marker_verify.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -enable-verify-exclusivity -enforce-exclusivity=checked -enable-sil-ownership -emit-silgen -swift-version 4 -parse-as-library %s | %FileCheck %s
 // RUN: %target-swift-frontend -enable-verify-exclusivity -enforce-exclusivity=checked -enable-sil-ownership -Onone -emit-sil -swift-version 4 -parse-as-library %s
 // RUN: %target-swift-frontend -enable-verify-exclusivity -enforce-exclusivity=checked -enable-sil-ownership -O -emit-sil -swift-version 4 -parse-as-library %s
diff --git a/test/SILOptimizer/array_element_propagation.sil b/test/SILOptimizer/array_element_propagation.sil
index 438b01a..10a6a81 100644
--- a/test/SILOptimizer/array_element_propagation.sil
+++ b/test/SILOptimizer/array_element_propagation.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-sil-opt -assume-parsing-unqualified-ownership-sil -array-element-propagation %s | %FileCheck %s
 sil_stage canonical
 
diff --git a/test/SILOptimizer/bridged_casts_folding.swift b/test/SILOptimizer/bridged_casts_folding.swift
index 1716b1f..da0c384 100644
--- a/test/SILOptimizer/bridged_casts_folding.swift
+++ b/test/SILOptimizer/bridged_casts_folding.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -O -emit-sil %s | %FileCheck %s
 
 // REQUIRES: objc_interop
diff --git a/test/SILOptimizer/capture_promotion_generic_context.sil b/test/SILOptimizer/capture_promotion_generic_context.sil
index 7287e75..09c7a8c 100644
--- a/test/SILOptimizer/capture_promotion_generic_context.sil
+++ b/test/SILOptimizer/capture_promotion_generic_context.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-sil -O -Xllvm -sil-fso-enable-generics=false %s | %FileCheck %s
 
 sil_stage raw
diff --git a/test/SILOptimizer/capture_promotion_generic_context_ownership.sil b/test/SILOptimizer/capture_promotion_generic_context_ownership.sil
index e2dc783..b668147 100644
--- a/test/SILOptimizer/capture_promotion_generic_context_ownership.sil
+++ b/test/SILOptimizer/capture_promotion_generic_context_ownership.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -enable-sil-ownership -emit-sil -O -Xllvm -sil-fso-enable-generics=false %s | %FileCheck %s
 
 sil_stage raw
diff --git a/test/SILOptimizer/cast_folding_no_bridging.sil b/test/SILOptimizer/cast_folding_no_bridging.sil
index ed7a539..555e641 100644
--- a/test/SILOptimizer/cast_folding_no_bridging.sil
+++ b/test/SILOptimizer/cast_folding_no_bridging.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -O -emit-sil %s | %FileCheck %s
 // REQUIRES: objc_interop
 
diff --git a/test/SILOptimizer/cast_folding_objc_generics.swift b/test/SILOptimizer/cast_folding_objc_generics.swift
index d6ad317..63af559 100644
--- a/test/SILOptimizer/cast_folding_objc_generics.swift
+++ b/test/SILOptimizer/cast_folding_objc_generics.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -O -emit-sil %s | %FileCheck %s
 // REQUIRES: objc_interop
 
diff --git a/test/SILOptimizer/cast_folding_objc_no_foundation.swift b/test/SILOptimizer/cast_folding_objc_no_foundation.swift
index 17a88ee..8495282 100644
--- a/test/SILOptimizer/cast_folding_objc_no_foundation.swift
+++ b/test/SILOptimizer/cast_folding_objc_no_foundation.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -O -emit-sil %s | %FileCheck %s
 // REQUIRES: objc_interop
 
diff --git a/test/SILOptimizer/devirt_covariant_return.swift b/test/SILOptimizer/devirt_covariant_return.swift
index be2da43..12f75fc 100644
--- a/test/SILOptimizer/devirt_covariant_return.swift
+++ b/test/SILOptimizer/devirt_covariant_return.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -O -Xllvm -disable-sil-cm-rr-cm=0   -Xllvm -sil-inline-generics=false -primary-file %s -emit-sil -sil-inline-threshold 1000 -Xllvm -sil-disable-pass=ObjectOutliner -sil-verify-all | %FileCheck %s
 
 // Make sure that we can dig all the way through the class hierarchy and
diff --git a/test/SILOptimizer/devirt_default_case.swift b/test/SILOptimizer/devirt_default_case.swift
index 5d86209..60cd7f2 100644
--- a/test/SILOptimizer/devirt_default_case.swift
+++ b/test/SILOptimizer/devirt_default_case.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -O -module-name devirt_default_case -emit-sil %s | %FileCheck -check-prefix=CHECK -check-prefix=CHECK-NORMAL %s
 // RUN: %target-swift-frontend -O -module-name devirt_default_case -emit-sil -enable-testing %s | %FileCheck -check-prefix=CHECK -check-prefix=CHECK-TESTABLE %s
 
diff --git a/test/SILOptimizer/devirt_nested_class.swift b/test/SILOptimizer/devirt_nested_class.swift
index 520ffc6..f222d28 100644
--- a/test/SILOptimizer/devirt_nested_class.swift
+++ b/test/SILOptimizer/devirt_nested_class.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -emit-sil -O %s | %FileCheck %s
 
 fileprivate class Outer<T> {
diff --git a/test/SILOptimizer/devirt_protocol_method_invocations.swift b/test/SILOptimizer/devirt_protocol_method_invocations.swift
index d05e1ba..5fc29ef 100644
--- a/test/SILOptimizer/devirt_protocol_method_invocations.swift
+++ b/test/SILOptimizer/devirt_protocol_method_invocations.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -O -emit-sil %s | %FileCheck %s
 
 protocol PPP {
diff --git a/test/SILOptimizer/devirt_speculative_nested.swift b/test/SILOptimizer/devirt_speculative_nested.swift
index 41bbdfa..152ffbb 100644
--- a/test/SILOptimizer/devirt_speculative_nested.swift
+++ b/test/SILOptimizer/devirt_speculative_nested.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend %s -parse-as-library -O -emit-sil | %FileCheck %s
 // RUN: %target-swift-frontend %s -parse-as-library -Osize -emit-sil
 //
diff --git a/test/SILOptimizer/devirt_value_metatypes.swift b/test/SILOptimizer/devirt_value_metatypes.swift
index 69ce24f..6158924 100644
--- a/test/SILOptimizer/devirt_value_metatypes.swift
+++ b/test/SILOptimizer/devirt_value_metatypes.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -emit-sil -O %s | %FileCheck %s
 
 open class A {
diff --git a/test/SILOptimizer/devirt_witness_method_conformance.swift b/test/SILOptimizer/devirt_witness_method_conformance.swift
index b8f8c66..e68f670 100644
--- a/test/SILOptimizer/devirt_witness_method_conformance.swift
+++ b/test/SILOptimizer/devirt_witness_method_conformance.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -O -emit-ir  -primary-file %s | %FileCheck %s
 // This is a swift file because the crash doesn't reproduce with SIL.
 @inline(never)
diff --git a/test/SILOptimizer/let_properties_opts.swift b/test/SILOptimizer/let_properties_opts.swift
index d0c96e8..4f29e49 100644
--- a/test/SILOptimizer/let_properties_opts.swift
+++ b/test/SILOptimizer/let_properties_opts.swift
@@ -1,5 +1,6 @@
 // REQUIRES: plus_one_runtime
-// RUN: %target-swift-frontend %s -O -emit-sil | %FileCheck -check-prefix=CHECK-WMO %s
+
+// RUN: %target-swift-frontend %s -O -enforce-exclusivity=checked -emit-sil | %FileCheck -check-prefix=CHECK-WMO %s
 // RUN: %target-swift-frontend -primary-file %s -O -emit-sil | %FileCheck %s
 
 // Test propagation of non-static let properties with compile-time constant values.
diff --git a/test/SILOptimizer/mandatory_inlining.swift b/test/SILOptimizer/mandatory_inlining.swift
index 0f5d34d..f5512b0 100644
--- a/test/SILOptimizer/mandatory_inlining.swift
+++ b/test/SILOptimizer/mandatory_inlining.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -enable-sil-ownership -sil-verify-all -primary-file %s -emit-sil -o - -verify | %FileCheck %s
 
 // These tests are deliberately shallow, because I do not want to depend on the
diff --git a/test/SILOptimizer/performance_inliner.sil b/test/SILOptimizer/performance_inliner.sil
index acdedf0..0f1c747 100644
--- a/test/SILOptimizer/performance_inliner.sil
+++ b/test/SILOptimizer/performance_inliner.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-sil-opt -assume-parsing-unqualified-ownership-sil -enable-sil-verify-all %s -inline -sil-combine | %FileCheck %s
 
 sil_stage canonical
diff --git a/test/SILOptimizer/plus_zero_access_enforcement_noescape.swift b/test/SILOptimizer/plus_zero_access_enforcement_noescape.swift
index 07fb511..37eb3c2 100644
--- a/test/SILOptimizer/plus_zero_access_enforcement_noescape.swift
+++ b/test/SILOptimizer/plus_zero_access_enforcement_noescape.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -enable-sil-ownership -enforce-exclusivity=checked -Onone -emit-sil -swift-version 4 -verify -parse-as-library %s
 // RUN: %target-swift-frontend -enable-sil-ownership -enforce-exclusivity=checked -Onone -emit-sil -swift-version 3 -parse-as-library %s | %FileCheck %s
 // REQUIRES: asserts
diff --git a/test/SILOptimizer/plus_zero_access_marker_mandatory.swift b/test/SILOptimizer/plus_zero_access_marker_mandatory.swift
index dde3001..6bc68ea 100644
--- a/test/SILOptimizer/plus_zero_access_marker_mandatory.swift
+++ b/test/SILOptimizer/plus_zero_access_marker_mandatory.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -enable-sil-ownership -parse-as-library -Xllvm -sil-full-demangle -emit-sil -Onone -enforce-exclusivity=checked %s | %FileCheck %s
 
 public struct S {
diff --git a/test/SILOptimizer/plus_zero_access_marker_verify.swift b/test/SILOptimizer/plus_zero_access_marker_verify.swift
index f24f230..ad65c82 100644
--- a/test/SILOptimizer/plus_zero_access_marker_verify.swift
+++ b/test/SILOptimizer/plus_zero_access_marker_verify.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -enable-verify-exclusivity -enforce-exclusivity=checked -enable-sil-ownership -emit-silgen -swift-version 4 -parse-as-library %s | %FileCheck %s
 // RUN: %target-swift-frontend -enable-verify-exclusivity -enforce-exclusivity=checked -enable-sil-ownership -Onone -emit-sil -swift-version 4 -parse-as-library %s
 // RUN: %target-swift-frontend -enable-verify-exclusivity -enforce-exclusivity=checked -enable-sil-ownership -O -emit-sil -swift-version 4 -parse-as-library %s
@@ -749,7 +750,7 @@
 // CHECK-NOT: begin_access
 // CHECK:   store [[PA]] to [init] [[ADR]] : $*@callee_guaranteed () -> @out Int
 // CHECK:   [[PTR:%.*]] = address_to_pointer [[ADR]] : $*@callee_guaranteed () -> @out Int to $Builtin.RawPointer
-// CHECK:   [[FPTR:%.*]] = thin_function_to_pointer %{{.*}} : $@convention(witness_method: Abstractable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout C, @thick C.Type) -> () to $Builtin.RawPointer
+// CHECK:   [[FPTR:%.*]] = thin_function_to_pointer %{{.*}} : $@convention(witness_method: Abstractable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed C, @thick C.Type) -> () to $Builtin.RawPointer
 // CHECK:   [[ENUM:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[FPTR]] : $Builtin.RawPointer
 // CHECK:   [[R:%.*]] = tuple ([[PTR]] : $Builtin.RawPointer, [[ENUM]] : $Optional<Builtin.RawPointer>)
 // CHECK:   return [[R]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
diff --git a/test/SILOptimizer/plus_zero_array_element_propagation.sil b/test/SILOptimizer/plus_zero_array_element_propagation.sil
index 8973b9a..7363872 100644
--- a/test/SILOptimizer/plus_zero_array_element_propagation.sil
+++ b/test/SILOptimizer/plus_zero_array_element_propagation.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-sil-opt -assume-parsing-unqualified-ownership-sil -array-element-propagation %s | %FileCheck %s
 sil_stage canonical
 
diff --git a/test/SILOptimizer/plus_zero_bridged_casts_folding.swift b/test/SILOptimizer/plus_zero_bridged_casts_folding.swift
index 5ef60d6..55d2938 100644
--- a/test/SILOptimizer/plus_zero_bridged_casts_folding.swift
+++ b/test/SILOptimizer/plus_zero_bridged_casts_folding.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -O -emit-sil %s | %FileCheck %s
 
 // REQUIRES: objc_interop
diff --git a/test/SILOptimizer/plus_zero_capture_promotion_generic_context.sil b/test/SILOptimizer/plus_zero_capture_promotion_generic_context.sil
index 8f08930..9fc8f6f 100644
--- a/test/SILOptimizer/plus_zero_capture_promotion_generic_context.sil
+++ b/test/SILOptimizer/plus_zero_capture_promotion_generic_context.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-sil -O -Xllvm -sil-fso-enable-generics=false %s | %FileCheck %s
 
 sil_stage raw
diff --git a/test/SILOptimizer/plus_zero_capture_promotion_generic_context_ownership.sil b/test/SILOptimizer/plus_zero_capture_promotion_generic_context_ownership.sil
index 77ac818..9049baf 100644
--- a/test/SILOptimizer/plus_zero_capture_promotion_generic_context_ownership.sil
+++ b/test/SILOptimizer/plus_zero_capture_promotion_generic_context_ownership.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -enable-sil-ownership -emit-sil -O -Xllvm -sil-fso-enable-generics=false %s | %FileCheck %s
 
 sil_stage raw
diff --git a/test/SILOptimizer/plus_zero_cast_folding_no_bridging.sil b/test/SILOptimizer/plus_zero_cast_folding_no_bridging.sil
index 4b4c661..fa01ca5 100644
--- a/test/SILOptimizer/plus_zero_cast_folding_no_bridging.sil
+++ b/test/SILOptimizer/plus_zero_cast_folding_no_bridging.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -O -emit-sil %s | %FileCheck %s
 // REQUIRES: objc_interop
 
diff --git a/test/SILOptimizer/plus_zero_cast_folding_objc_generics.swift b/test/SILOptimizer/plus_zero_cast_folding_objc_generics.swift
index effe201..a7b1826 100644
--- a/test/SILOptimizer/plus_zero_cast_folding_objc_generics.swift
+++ b/test/SILOptimizer/plus_zero_cast_folding_objc_generics.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -O -emit-sil %s | %FileCheck %s
 // REQUIRES: objc_interop
 
diff --git a/test/SILOptimizer/plus_zero_cast_folding_objc_no_foundation.swift b/test/SILOptimizer/plus_zero_cast_folding_objc_no_foundation.swift
index 5648147..86a36d4 100644
--- a/test/SILOptimizer/plus_zero_cast_folding_objc_no_foundation.swift
+++ b/test/SILOptimizer/plus_zero_cast_folding_objc_no_foundation.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -O -emit-sil %s | %FileCheck %s
 // REQUIRES: objc_interop
 
diff --git a/test/SILOptimizer/plus_zero_devirt_covariant_return.swift b/test/SILOptimizer/plus_zero_devirt_covariant_return.swift
index 8c12f8d..7bc2716 100644
--- a/test/SILOptimizer/plus_zero_devirt_covariant_return.swift
+++ b/test/SILOptimizer/plus_zero_devirt_covariant_return.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -O -Xllvm -disable-sil-cm-rr-cm=0   -Xllvm -sil-inline-generics=false -primary-file %s -emit-sil -sil-inline-threshold 1000 -Xllvm -sil-disable-pass=ObjectOutliner -sil-verify-all | %FileCheck %s
 
 // Make sure that we can dig all the way through the class hierarchy and
diff --git a/test/SILOptimizer/plus_zero_devirt_default_case.swift b/test/SILOptimizer/plus_zero_devirt_default_case.swift
index c6eeaa8..1551296 100644
--- a/test/SILOptimizer/plus_zero_devirt_default_case.swift
+++ b/test/SILOptimizer/plus_zero_devirt_default_case.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -O -module-name devirt_default_case -emit-sil %s | %FileCheck -check-prefix=CHECK -check-prefix=CHECK-NORMAL %s
 // RUN: %target-swift-frontend -O -module-name devirt_default_case -emit-sil -enable-testing %s | %FileCheck -check-prefix=CHECK -check-prefix=CHECK-TESTABLE %s
 
diff --git a/test/SILOptimizer/plus_zero_devirt_nested_class.swift b/test/SILOptimizer/plus_zero_devirt_nested_class.swift
index 936d6d9..81f6153 100644
--- a/test/SILOptimizer/plus_zero_devirt_nested_class.swift
+++ b/test/SILOptimizer/plus_zero_devirt_nested_class.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -emit-sil -O %s | %FileCheck %s
 
 fileprivate class Outer<T> {
diff --git a/test/SILOptimizer/plus_zero_devirt_protocol_method_invocations.swift b/test/SILOptimizer/plus_zero_devirt_protocol_method_invocations.swift
index 2b1a325..f4c6008 100644
--- a/test/SILOptimizer/plus_zero_devirt_protocol_method_invocations.swift
+++ b/test/SILOptimizer/plus_zero_devirt_protocol_method_invocations.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -O -emit-sil %s | %FileCheck %s
 
 protocol PPP {
diff --git a/test/SILOptimizer/plus_zero_devirt_speculative_nested.swift b/test/SILOptimizer/plus_zero_devirt_speculative_nested.swift
index bc6a9e8..ac4abd1 100644
--- a/test/SILOptimizer/plus_zero_devirt_speculative_nested.swift
+++ b/test/SILOptimizer/plus_zero_devirt_speculative_nested.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend %s -parse-as-library -O -emit-sil | %FileCheck %s
 // RUN: %target-swift-frontend %s -parse-as-library -Osize -emit-sil
 //
diff --git a/test/SILOptimizer/plus_zero_devirt_value_metatypes.swift b/test/SILOptimizer/plus_zero_devirt_value_metatypes.swift
index b324eab..548a292 100644
--- a/test/SILOptimizer/plus_zero_devirt_value_metatypes.swift
+++ b/test/SILOptimizer/plus_zero_devirt_value_metatypes.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -emit-sil -O %s | %FileCheck %s
 
 open class A {
diff --git a/test/SILOptimizer/plus_zero_devirt_witness_method_conformance.swift b/test/SILOptimizer/plus_zero_devirt_witness_method_conformance.swift
index f3da042..b0c74dd 100644
--- a/test/SILOptimizer/plus_zero_devirt_witness_method_conformance.swift
+++ b/test/SILOptimizer/plus_zero_devirt_witness_method_conformance.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -O -emit-ir  -primary-file %s | %FileCheck %s
 // This is a swift file because the crash doesn't reproduce with SIL.
 @inline(never)
diff --git a/test/SILOptimizer/plus_zero_let_properties_opts.swift b/test/SILOptimizer/plus_zero_let_properties_opts.swift
index 12be391..abff5e4 100644
--- a/test/SILOptimizer/plus_zero_let_properties_opts.swift
+++ b/test/SILOptimizer/plus_zero_let_properties_opts.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend %s -O -emit-sil | %FileCheck -check-prefix=CHECK-WMO %s
 // RUN: %target-swift-frontend -primary-file %s -O -emit-sil | %FileCheck %s
 
diff --git a/test/SILOptimizer/plus_zero_mandatory_inlining.swift b/test/SILOptimizer/plus_zero_mandatory_inlining.swift
index 3dec6cb..9bebff3 100644
--- a/test/SILOptimizer/plus_zero_mandatory_inlining.swift
+++ b/test/SILOptimizer/plus_zero_mandatory_inlining.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -enable-sil-ownership -sil-verify-all -primary-file %s -emit-sil -o - -verify | %FileCheck %s
 
 // These tests are deliberately shallow, because I do not want to depend on the
diff --git a/test/SILOptimizer/plus_zero_performance_inliner.sil b/test/SILOptimizer/plus_zero_performance_inliner.sil
index e19b0c9..b36dd6d 100644
--- a/test/SILOptimizer/plus_zero_performance_inliner.sil
+++ b/test/SILOptimizer/plus_zero_performance_inliner.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-sil-opt -assume-parsing-unqualified-ownership-sil -enable-sil-verify-all %s -inline -sil-combine | %FileCheck %s
 
 sil_stage canonical
diff --git a/test/SILOptimizer/plus_zero_spec_archetype_method.swift b/test/SILOptimizer/plus_zero_spec_archetype_method.swift
index f76cf39..0ebf230 100644
--- a/test/SILOptimizer/plus_zero_spec_archetype_method.swift
+++ b/test/SILOptimizer/plus_zero_spec_archetype_method.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -O -Xllvm -sil-disable-pass=FunctionSignatureOpts -disable-arc-opts -emit-sil -primary-file %s | %FileCheck %s
 
 // We can't deserialize apply_inst with subst lists. When radar://14443304
diff --git a/test/SILOptimizer/plus_zero_specialize_anyobject.swift b/test/SILOptimizer/plus_zero_specialize_anyobject.swift
index 5d5326c..647c362 100644
--- a/test/SILOptimizer/plus_zero_specialize_anyobject.swift
+++ b/test/SILOptimizer/plus_zero_specialize_anyobject.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend  -O -sil-inline-threshold 0 -emit-sil -primary-file %s | %FileCheck %s
 
 // rdar://problem/20338028
diff --git a/test/SILOptimizer/plus_zero_specialize_cg_update_crash.sil b/test/SILOptimizer/plus_zero_specialize_cg_update_crash.sil
index 01b0190..0762b26 100644
--- a/test/SILOptimizer/plus_zero_specialize_cg_update_crash.sil
+++ b/test/SILOptimizer/plus_zero_specialize_cg_update_crash.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -parse-stdlib -parse-as-library  -module-name TestMod %S/Inputs/TestMod.sil -emit-module-path %t/TestMod.swiftmodule
 // RUN: %target-sil-opt -assume-parsing-unqualified-ownership-sil -enable-sil-verify-all -inline -I %t %s | %FileCheck %s
diff --git a/test/SILOptimizer/plus_zero_specialize_checked_cast_branch.swift b/test/SILOptimizer/plus_zero_specialize_checked_cast_branch.swift
index 4f6073d..766c005 100644
--- a/test/SILOptimizer/plus_zero_specialize_checked_cast_branch.swift
+++ b/test/SILOptimizer/plus_zero_specialize_checked_cast_branch.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend  -emit-sil -O -sil-inline-threshold 0 %s -o - | %FileCheck %s
 
 class C {}
diff --git a/test/SILOptimizer/plus_zero_specialize_dynamic_self.swift b/test/SILOptimizer/plus_zero_specialize_dynamic_self.swift
index 4348be6..9c2e44c 100644
--- a/test/SILOptimizer/plus_zero_specialize_dynamic_self.swift
+++ b/test/SILOptimizer/plus_zero_specialize_dynamic_self.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -Xllvm -sil-inline-generics -emit-sil -O -primary-file %s | %FileCheck %s
 
 protocol P {}
diff --git a/test/SILOptimizer/plus_zero_specialize_inherited_multifile.swift b/test/SILOptimizer/plus_zero_specialize_inherited_multifile.swift
index 387094d..f3a5b49 100644
--- a/test/SILOptimizer/plus_zero_specialize_inherited_multifile.swift
+++ b/test/SILOptimizer/plus_zero_specialize_inherited_multifile.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -primary-file %s %S/Inputs/specialize_inherited_multifile.swift -O -emit-sil -sil-verify-all | %FileCheck %s
 
 @_optimize(none) func takesBase<T : Base>(t: T) {}
diff --git a/test/SILOptimizer/plus_zero_specialize_partial_apply.swift b/test/SILOptimizer/plus_zero_specialize_partial_apply.swift
index 9297335..e9498f0 100644
--- a/test/SILOptimizer/plus_zero_specialize_partial_apply.swift
+++ b/test/SILOptimizer/plus_zero_specialize_partial_apply.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // First check the SIL.
 // RUN: %target-swift-frontend -O -Xllvm -sil-disable-pass=FunctionSignatureOpts -module-name=test -emit-sil -primary-file %s | %FileCheck %s
 
diff --git a/test/SILOptimizer/plus_zero_specialize_same_type_constraint.swift b/test/SILOptimizer/plus_zero_specialize_same_type_constraint.swift
index f8db643..ba13e51 100644
--- a/test/SILOptimizer/plus_zero_specialize_same_type_constraint.swift
+++ b/test/SILOptimizer/plus_zero_specialize_same_type_constraint.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend  -O -emit-sil -primary-file %s | %FileCheck %s
 
 protocol FirstChild {}
diff --git a/test/SILOptimizer/plus_zero_specialize_self.swift b/test/SILOptimizer/plus_zero_specialize_self.swift
index b181e3e..5c3cbcf 100644
--- a/test/SILOptimizer/plus_zero_specialize_self.swift
+++ b/test/SILOptimizer/plus_zero_specialize_self.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -Xllvm -sil-full-demangle  -O -sil-inline-threshold 0 -emit-sil -primary-file %s | %FileCheck %s
 
 // CHECK-NOT: generic specialization <Swift.AnyObject, Self> of specialize_self.cast <A, B>(A) -> Swift.Optional<B>
diff --git a/test/SILOptimizer/plus_zero_specialize_self_conforming.swift b/test/SILOptimizer/plus_zero_specialize_self_conforming.swift
index 1c01bc2..e593dde 100644
--- a/test/SILOptimizer/plus_zero_specialize_self_conforming.swift
+++ b/test/SILOptimizer/plus_zero_specialize_self_conforming.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -emit-sil -O -primary-file %s | %FileCheck %s
 
 // REQUIRES: objc_interop
diff --git a/test/SILOptimizer/plus_zero_specialize_unconditional_checked_cast.swift b/test/SILOptimizer/plus_zero_specialize_unconditional_checked_cast.swift
index 6f6977d..663b767 100644
--- a/test/SILOptimizer/plus_zero_specialize_unconditional_checked_cast.swift
+++ b/test/SILOptimizer/plus_zero_specialize_unconditional_checked_cast.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend  -Xllvm -sil-disable-pass=FunctionSignatureOpts -emit-sil -o - -O %s | %FileCheck %s
 
 //////////////////
diff --git a/test/SILOptimizer/plus_zero_specialized_anyobject_conformance.swift b/test/SILOptimizer/plus_zero_specialized_anyobject_conformance.swift
index 5cc511e..306893d 100644
--- a/test/SILOptimizer/plus_zero_specialized_anyobject_conformance.swift
+++ b/test/SILOptimizer/plus_zero_specialized_anyobject_conformance.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend  -O -sil-inline-threshold 0 -emit-sil -primary-file %s | %FileCheck %s
 
 // rdar://problem/31910351
diff --git a/test/SILOptimizer/sil_simplify_instrs.sil b/test/SILOptimizer/sil_simplify_instrs.sil
index 46c8d42..18241af 100644
--- a/test/SILOptimizer/sil_simplify_instrs.sil
+++ b/test/SILOptimizer/sil_simplify_instrs.sil
@@ -313,3 +313,42 @@
 // CHECK-NEXT: return %1 : $(Builtin.Int64, Builtin.Int64, Builtin.Int64)
 }
 
+public class A {
+  var b: B
+  init(b: B)
+  deinit
+}
+
+public class B {
+  var x: Int
+  init(x: Int)
+  deinit
+}
+
+// simplify access markers
+sil @simplify_accesssil : $@convention(method) (@guaranteed A) -> () {
+bb0(%0 : $A):
+  %badr = ref_element_addr %0 : $A, #A.b
+  %ba1 = begin_access [read] [dynamic] %badr : $*B
+  end_access %ba1 : $*B
+  %ba2 = begin_access [read] [dynamic] %badr : $*B
+  fix_lifetime %ba2 : $*B
+  end_access %ba2 : $*B
+  %ba3 = begin_access [read] [dynamic] %badr : $*B
+  %b = load %ba3 : $*B
+  end_access %ba3 : $*B
+  %xadr = ref_element_addr %b : $B, #B.x
+  %xaccess = begin_access [read] [dynamic] %xadr : $*Int
+  end_access %xaccess : $*Int
+
+  %r = tuple ()
+  return %r : $()
+}
+
+// CHECK-LABEL: sil @simplify_accesssil : $@convention(method) (@guaranteed A) -> () {
+// CHECK: bb0(%0 : $A):
+// CHECK-NEXT: [[ADR:%.*]] = ref_element_addr %0 : $A, #A.b
+// CHECK-NEXT: fix_lifetime [[ADR]] : $*B
+// CHECK-NEXT: %{{.*}} = tuple ()
+// CHECK-NEXT: return %{{.*}} : $()
+// CHECK-LABEL: } // end sil function 'simplify_accesssil'
diff --git a/test/SILOptimizer/spec_archetype_method.swift b/test/SILOptimizer/spec_archetype_method.swift
index c1bdc18..3c709b6 100644
--- a/test/SILOptimizer/spec_archetype_method.swift
+++ b/test/SILOptimizer/spec_archetype_method.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -O -Xllvm -sil-disable-pass=FunctionSignatureOpts -disable-arc-opts -emit-sil -primary-file %s | %FileCheck %s
 
 // We can't deserialize apply_inst with subst lists. When radar://14443304
diff --git a/test/SILOptimizer/specialize_anyobject.swift b/test/SILOptimizer/specialize_anyobject.swift
index 3549297..8fec718 100644
--- a/test/SILOptimizer/specialize_anyobject.swift
+++ b/test/SILOptimizer/specialize_anyobject.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend  -O -sil-inline-threshold 0 -emit-sil -primary-file %s | %FileCheck %s
 
 // rdar://problem/20338028
diff --git a/test/SILOptimizer/specialize_cg_update_crash.sil b/test/SILOptimizer/specialize_cg_update_crash.sil
index 317bdce..a483621 100644
--- a/test/SILOptimizer/specialize_cg_update_crash.sil
+++ b/test/SILOptimizer/specialize_cg_update_crash.sil
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -parse-stdlib -parse-as-library  -module-name TestMod %S/Inputs/TestMod.sil -emit-module-path %t/TestMod.swiftmodule
 // RUN: %target-sil-opt -assume-parsing-unqualified-ownership-sil -enable-sil-verify-all -inline -I %t %s | %FileCheck %s
diff --git a/test/SILOptimizer/specialize_checked_cast_branch.swift b/test/SILOptimizer/specialize_checked_cast_branch.swift
index 87f8234..f3064e8 100644
--- a/test/SILOptimizer/specialize_checked_cast_branch.swift
+++ b/test/SILOptimizer/specialize_checked_cast_branch.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend  -emit-sil -O -sil-inline-threshold 0 %s -o - | %FileCheck %s
 
 class C {}
diff --git a/test/SILOptimizer/specialize_dynamic_self.swift b/test/SILOptimizer/specialize_dynamic_self.swift
index 835abec..53e71ad 100644
--- a/test/SILOptimizer/specialize_dynamic_self.swift
+++ b/test/SILOptimizer/specialize_dynamic_self.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -Xllvm -sil-inline-generics -emit-sil -O -primary-file %s | %FileCheck %s
 
 protocol P {}
diff --git a/test/SILOptimizer/specialize_inherited_multifile.swift b/test/SILOptimizer/specialize_inherited_multifile.swift
index f6921c0..64e8725 100644
--- a/test/SILOptimizer/specialize_inherited_multifile.swift
+++ b/test/SILOptimizer/specialize_inherited_multifile.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -primary-file %s %S/Inputs/specialize_inherited_multifile.swift -O -emit-sil -sil-verify-all | %FileCheck %s
 
 @_optimize(none) func takesBase<T : Base>(t: T) {}
diff --git a/test/SILOptimizer/specialize_partial_apply.swift b/test/SILOptimizer/specialize_partial_apply.swift
index db5172e..32e91a6 100644
--- a/test/SILOptimizer/specialize_partial_apply.swift
+++ b/test/SILOptimizer/specialize_partial_apply.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // First check the SIL.
 // RUN: %target-swift-frontend -O -Xllvm -sil-disable-pass=FunctionSignatureOpts -module-name=test -emit-sil -primary-file %s | %FileCheck %s
 
diff --git a/test/SILOptimizer/specialize_same_type_constraint.swift b/test/SILOptimizer/specialize_same_type_constraint.swift
index e80cda3..ffad109 100644
--- a/test/SILOptimizer/specialize_same_type_constraint.swift
+++ b/test/SILOptimizer/specialize_same_type_constraint.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend  -O -emit-sil -primary-file %s | %FileCheck %s
 
 protocol FirstChild {}
diff --git a/test/SILOptimizer/specialize_self.swift b/test/SILOptimizer/specialize_self.swift
index 4384da9..e57b9e0 100644
--- a/test/SILOptimizer/specialize_self.swift
+++ b/test/SILOptimizer/specialize_self.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -Xllvm -sil-full-demangle  -O -sil-inline-threshold 0 -emit-sil -primary-file %s | %FileCheck %s
 
 // CHECK-NOT: generic specialization <Swift.AnyObject, Self> of specialize_self.cast <A, B>(A) -> Swift.Optional<B>
diff --git a/test/SILOptimizer/specialize_self_conforming.swift b/test/SILOptimizer/specialize_self_conforming.swift
index 847fa94e..0815655 100644
--- a/test/SILOptimizer/specialize_self_conforming.swift
+++ b/test/SILOptimizer/specialize_self_conforming.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -emit-sil -O -primary-file %s | %FileCheck %s
 
 // REQUIRES: objc_interop
diff --git a/test/SILOptimizer/specialize_unconditional_checked_cast.swift b/test/SILOptimizer/specialize_unconditional_checked_cast.swift
index 31ab14a..8361256 100644
--- a/test/SILOptimizer/specialize_unconditional_checked_cast.swift
+++ b/test/SILOptimizer/specialize_unconditional_checked_cast.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend  -Xllvm -sil-disable-pass=FunctionSignatureOpts -emit-sil -o - -O %s | %FileCheck %s
 
 //////////////////
diff --git a/test/SILOptimizer/specialized_anyobject_conformance.swift b/test/SILOptimizer/specialized_anyobject_conformance.swift
index d127df0..2bed1e6 100644
--- a/test/SILOptimizer/specialized_anyobject_conformance.swift
+++ b/test/SILOptimizer/specialized_anyobject_conformance.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend  -O -sil-inline-threshold 0 -emit-sil -primary-file %s | %FileCheck %s
 
 // rdar://problem/31910351
diff --git a/test/Sanitizers/tsan.swift b/test/Sanitizers/tsan.swift
index b7ffc43..3b793f5 100644
--- a/test/Sanitizers/tsan.swift
+++ b/test/Sanitizers/tsan.swift
@@ -7,7 +7,7 @@
 // https://bugs.swift.org/browse/SR-6622
 // XFAIL: linux
 
-#if os(OSX) || os(iOS)
+#if os(macOS) || os(iOS)
 import Darwin
 #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin)
 import Glibc
@@ -38,7 +38,7 @@
 var racey_x: Int;
 
 for _ in 1...5 {
-#if os(OSX) || os(iOS)
+#if os(macOS) || os(iOS)
   var t : pthread_t?
 #else
   var t : pthread_t = 0
@@ -49,7 +49,7 @@
 
     return nil
   }, nil)
-#if os(OSX) || os(iOS)
+#if os(macOS) || os(iOS)
   threads.append(t!)
 #else
   threads.append(t)
diff --git a/test/Sema/fixed_ambiguities/plus_zero_rdar27198177.swift b/test/Sema/fixed_ambiguities/plus_zero_rdar27198177.swift
index 39fbc60..da42923 100644
--- a/test/Sema/fixed_ambiguities/plus_zero_rdar27198177.swift
+++ b/test/Sema/fixed_ambiguities/plus_zero_rdar27198177.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -emit-sil -verify %s -swift-version 4 | %FileCheck %s
 
 let arr = ["A", "B", "C"]
diff --git a/test/Sema/fixed_ambiguities/plus_zero_rdar33142386.swift b/test/Sema/fixed_ambiguities/plus_zero_rdar33142386.swift
index ea617e2..8bd4385 100644
--- a/test/Sema/fixed_ambiguities/plus_zero_rdar33142386.swift
+++ b/test/Sema/fixed_ambiguities/plus_zero_rdar33142386.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -emit-sil -verify %s -swift-version 4 | %FileCheck %s
 
 let x: String = "ultimate question"
diff --git a/test/Sema/fixed_ambiguities/plus_zero_rdar35623181.swift b/test/Sema/fixed_ambiguities/plus_zero_rdar35623181.swift
index 43e9c26..dcf598f 100644
--- a/test/Sema/fixed_ambiguities/plus_zero_rdar35623181.swift
+++ b/test/Sema/fixed_ambiguities/plus_zero_rdar35623181.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -emit-sil -verify %s | %FileCheck %s
 
 extension Sequence where Element == String {
diff --git a/test/Sema/fixed_ambiguities/plus_zero_rdar36333688.swift b/test/Sema/fixed_ambiguities/plus_zero_rdar36333688.swift
index 81b8f77..7317ec6 100644
--- a/test/Sema/fixed_ambiguities/plus_zero_rdar36333688.swift
+++ b/test/Sema/fixed_ambiguities/plus_zero_rdar36333688.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %target-swift-frontend -emit-sil -verify %s | %FileCheck %s
 
 infix operator +=+ : AdditionPrecedence
diff --git a/test/Sema/fixed_ambiguities/rdar27198177.swift b/test/Sema/fixed_ambiguities/rdar27198177.swift
index bd240b3..15662ec 100644
--- a/test/Sema/fixed_ambiguities/rdar27198177.swift
+++ b/test/Sema/fixed_ambiguities/rdar27198177.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -emit-sil -verify %s -swift-version 4 | %FileCheck %s
 
 let arr = ["A", "B", "C"]
diff --git a/test/Sema/fixed_ambiguities/rdar33142386.swift b/test/Sema/fixed_ambiguities/rdar33142386.swift
index e6fd493..8c3fd2f 100644
--- a/test/Sema/fixed_ambiguities/rdar33142386.swift
+++ b/test/Sema/fixed_ambiguities/rdar33142386.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -emit-sil -verify %s -swift-version 4 | %FileCheck %s
 
 let x: String = "ultimate question"
diff --git a/test/Sema/fixed_ambiguities/rdar35623181.swift b/test/Sema/fixed_ambiguities/rdar35623181.swift
index d3278c8..f5ff35f 100644
--- a/test/Sema/fixed_ambiguities/rdar35623181.swift
+++ b/test/Sema/fixed_ambiguities/rdar35623181.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -emit-sil -verify %s | %FileCheck %s
 
 extension Sequence where Element == String {
diff --git a/test/Sema/fixed_ambiguities/rdar36333688.swift b/test/Sema/fixed_ambiguities/rdar36333688.swift
index 3417b6a..c91de62 100644
--- a/test/Sema/fixed_ambiguities/rdar36333688.swift
+++ b/test/Sema/fixed_ambiguities/rdar36333688.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %target-swift-frontend -emit-sil -verify %s | %FileCheck %s
 
 infix operator +=+ : AdditionPrecedence
diff --git a/test/Serialization/Recovery/typedefs-in-enums.swift b/test/Serialization/Recovery/typedefs-in-enums.swift
index 11eb25f..f151471 100644
--- a/test/Serialization/Recovery/typedefs-in-enums.swift
+++ b/test/Serialization/Recovery/typedefs-in-enums.swift
@@ -34,7 +34,7 @@
   case problematic(Any, WrappedInt)
   case alsoOkay(Any, Any, Any)
 
-  static public func ==(a: BadEnum, b: BadEnum) -> Bool {
+  public static func ==(a: BadEnum, b: BadEnum) -> Bool {
     return false
   }
 }
@@ -45,7 +45,7 @@
   case noPayload
   case perfectlyOkayPayload(Int)
 
-  static public func ==(a: GenericBadEnum<T>, b: GenericBadEnum<T>) -> Bool {
+  public static func ==(a: GenericBadEnum<T>, b: GenericBadEnum<T>) -> Bool {
     return false
   }
 }
@@ -57,7 +57,7 @@
   case plainOldAlias(Any, UnwrappedInt)
   case other(Int)
 
-  static public func ==(a: OkayEnum, b: OkayEnum) -> Bool {
+  public static func ==(a: OkayEnum, b: OkayEnum) -> Bool {
     return false
   }
 }
diff --git a/test/Serialization/function.swift b/test/Serialization/function.swift
index 93e74be..274a3e4 100644
--- a/test/Serialization/function.swift
+++ b/test/Serialization/function.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_func.swift
 // RUN: llvm-bcanalyzer %t/def_func.swiftmodule | %FileCheck %s
diff --git a/test/Serialization/objc.swift b/test/Serialization/objc.swift
index d2ba2bf..4315dbb 100644
--- a/test/Serialization/objc.swift
+++ b/test/Serialization/objc.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_objc.swift -disable-objc-attr-requires-foundation-module
 // RUN: llvm-bcanalyzer %t/def_objc.swiftmodule | %FileCheck %s
diff --git a/test/Serialization/plus_zero_function.swift b/test/Serialization/plus_zero_function.swift
index 0332f22..f7444b1 100644
--- a/test/Serialization/plus_zero_function.swift
+++ b/test/Serialization/plus_zero_function.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_func.swift
 // RUN: llvm-bcanalyzer %t/def_func.swiftmodule | %FileCheck %s
diff --git a/test/Serialization/plus_zero_objc.swift b/test/Serialization/plus_zero_objc.swift
index 787e961..1c315b6 100644
--- a/test/Serialization/plus_zero_objc.swift
+++ b/test/Serialization/plus_zero_objc.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_objc.swift -disable-objc-attr-requires-foundation-module
 // RUN: llvm-bcanalyzer %t/def_objc.swiftmodule | %FileCheck %s
diff --git a/test/Serialization/plus_zero_serialize_attr.swift b/test/Serialization/plus_zero_serialize_attr.swift
index ea32612..9d89e08 100644
--- a/test/Serialization/plus_zero_serialize_attr.swift
+++ b/test/Serialization/plus_zero_serialize_attr.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -parse-as-library -o %t %s
 // RUN: llvm-bcanalyzer %t/serialize_attr.swiftmodule | %FileCheck %s -check-prefix=BCANALYZER
diff --git a/test/Serialization/plus_zero_transparent-std.swift b/test/Serialization/plus_zero_transparent-std.swift
index 0a92f03..b4c7a70 100644
--- a/test/Serialization/plus_zero_transparent-std.swift
+++ b/test/Serialization/plus_zero_transparent-std.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -parse-stdlib -o %t %S/Inputs/def_transparent_std.swift
 // RUN: llvm-bcanalyzer %t/def_transparent_std.swiftmodule | %FileCheck %s
diff --git a/test/Serialization/plus_zero_transparent.swift b/test/Serialization/plus_zero_transparent.swift
index 3fd2497..85951b6 100644
--- a/test/Serialization/plus_zero_transparent.swift
+++ b/test/Serialization/plus_zero_transparent.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_zero_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_transparent.swift
 // RUN: llvm-bcanalyzer %t/def_transparent.swiftmodule | %FileCheck %s
diff --git a/test/Serialization/serialize_attr.swift b/test/Serialization/serialize_attr.swift
index 501abe1..9280b15 100644
--- a/test/Serialization/serialize_attr.swift
+++ b/test/Serialization/serialize_attr.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -parse-as-library -o %t %s
 // RUN: llvm-bcanalyzer %t/serialize_attr.swiftmodule | %FileCheck %s -check-prefix=BCANALYZER
diff --git a/test/Serialization/transparent-std.swift b/test/Serialization/transparent-std.swift
index 1e51fae..504cbb1 100644
--- a/test/Serialization/transparent-std.swift
+++ b/test/Serialization/transparent-std.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -parse-stdlib -o %t %S/Inputs/def_transparent_std.swift
 // RUN: llvm-bcanalyzer %t/def_transparent_std.swiftmodule | %FileCheck %s
diff --git a/test/Serialization/transparent.swift b/test/Serialization/transparent.swift
index 89f29dd..fe6173f 100644
--- a/test/Serialization/transparent.swift
+++ b/test/Serialization/transparent.swift
@@ -1,4 +1,5 @@
 // REQUIRES: plus_one_runtime
+
 // RUN: %empty-directory(%t)
 // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_transparent.swift
 // RUN: llvm-bcanalyzer %t/def_transparent.swiftmodule | %FileCheck %s
diff --git a/test/SwiftSyntax/AbsolutePosition.swift b/test/SwiftSyntax/AbsolutePosition.swift
new file mode 100644
index 0000000..cb5f317
--- /dev/null
+++ b/test/SwiftSyntax/AbsolutePosition.swift
@@ -0,0 +1,100 @@
+// RUN: %target-run-simple-swift
+// REQUIRES: executable_test
+// REQUIRES: OS=macosx
+// REQUIRES: objc_interop
+
+import StdlibUnittest
+import Foundation
+import SwiftSyntax
+import SwiftLang
+
+func getInput(_ file: String) -> URL {
+  var result = URL(fileURLWithPath: #file)
+  result.deleteLastPathComponent()
+  result.appendPathComponent("Inputs")
+  result.appendPathComponent(file)
+  return result
+}
+
+
+class FuncRenamer: SyntaxRewriter {
+  override func visit(_ node: FunctionDeclSyntax) ->DeclSyntax {
+    return (super.visit(node) as! FunctionDeclSyntax).withIdentifier(
+      SyntaxFactory.makeIdentifier("anotherName"))
+  }
+}
+
+var PositionTests = TestSuite("AbsolutePositionTests")
+
+PositionTests.test("Visitor") {
+  expectDoesNotThrow({
+    let content = try SwiftLang.parse(getInput("visitor.swift"))
+    let source = try String(contentsOf: getInput("visitor.swift"))
+    let parsed = try SourceFileSyntax.decodeSourceFileSyntax(content)
+    expectEqual(parsed.position.byteOffset, 0)
+    expectEqual(parsed.eofToken.positionAfterSkippingLeadingTrivia.byteOffset,
+                source.count)
+    expectEqual(parsed.position.byteOffset, 0)
+    expectEqual(parsed.byteSize, source.count)
+  })
+}
+
+PositionTests.test("Closure") {
+  expectDoesNotThrow({
+    let content = try SwiftLang.parse(getInput("closure.swift"))
+    let source = try String(contentsOf: getInput("closure.swift"))
+    let parsed = try SourceFileSyntax.decodeSourceFileSyntax(content)
+    expectEqual(parsed.eofToken.positionAfterSkippingLeadingTrivia.byteOffset,
+                source.count)
+    expectEqual(parsed.position.byteOffset, 0)
+    expectEqual(parsed.byteSize, source.count)
+  })
+}
+
+PositionTests.test("Rename") {
+  expectDoesNotThrow({
+    let content = try SwiftLang.parse(getInput("visitor.swift"))
+    let parsed = try SourceFileSyntax.decodeSourceFileSyntax(content)
+    let renamed = FuncRenamer().visit(parsed) as! SourceFileSyntax
+    let renamedSource = renamed.description
+    expectEqual(renamed.eofToken.positionAfterSkippingLeadingTrivia.byteOffset,
+                renamedSource.count)
+    expectEqual(renamed.byteSize, renamedSource.count)
+  })
+}
+
+PositionTests.test("CurrentFile") {
+  expectDoesNotThrow({
+    let content = try SwiftLang.parse(URL(fileURLWithPath: #file))
+    let parsed = try SourceFileSyntax.decodeSourceFileSyntax(content)
+    class Visitor: SyntaxVisitor {
+      override func visitPre(_ node: Syntax) {
+        _ = node.position
+        _ = node.byteSize
+        _ = node.positionAfterSkippingLeadingTrivia
+      }
+    }
+    Visitor().visit(parsed)
+  })
+}
+
+PositionTests.test("Recursion") {
+  expectDoesNotThrow({
+    var l = [CodeBlockItemSyntax]()
+    let idx = 2000
+    for _ in 0...idx {
+      l.append(SyntaxFactory.makeCodeBlockItem(
+        item: SyntaxFactory.makeReturnStmt(
+          returnKeyword: SyntaxFactory.makeToken(.returnKeyword, presence: .present)
+            .withTrailingTrivia(.newlines(1)), expression: nil), semicolon: nil))
+    }
+    let root = SyntaxFactory.makeSourceFile(
+      statements: SyntaxFactory.makeCodeBlockItemList(l),
+      eofToken: SyntaxFactory.makeToken(.eof, presence: .present))
+    _ = root.statements[idx].position
+    _ = root.statements[idx].byteSize
+    _ = root.statements[idx].positionAfterSkippingLeadingTrivia
+  })
+}
+
+runAllTests()
diff --git a/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds b/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds
index 1d0ad45..e0b719a 100644
--- a/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds
+++ b/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds
@@ -319,7 +319,9 @@
   } </CodeBlock></CatchClause><CatchClause>catch <CodeBlock>{
   }</CodeBlock></CatchClause></DoStmt><RepeatWhileStmt>
   repeat <CodeBlock>{ } </CodeBlock>while <BooleanLiteralExpr>true</BooleanLiteralExpr></RepeatWhileStmt><RepeatWhileStmt>
-  LABEL: repeat <CodeBlock>{ } </CodeBlock>while <BooleanLiteralExpr>false</BooleanLiteralExpr></RepeatWhileStmt><DoStmt>
+  LABEL: repeat <CodeBlock>{ } </CodeBlock>while <BooleanLiteralExpr>false</BooleanLiteralExpr></RepeatWhileStmt><WhileStmt>
+  while <ConditionElement><BooleanLiteralExpr>true </BooleanLiteralExpr></ConditionElement><CodeBlock>{ }</CodeBlock></WhileStmt><WhileStmt>
+  LABEL: while <ConditionElement><BooleanLiteralExpr>true </BooleanLiteralExpr></ConditionElement><CodeBlock>{ }</CodeBlock></WhileStmt><DoStmt>
   LABEL: do <CodeBlock>{}</CodeBlock></DoStmt>
   LABEL: switch <IdentifierExpr>foo </IdentifierExpr>{
     case <ExpressionPattern><IntegerLiteralExpr>1</IntegerLiteralExpr></ExpressionPattern>:<FallthroughStmt>
diff --git a/test/Syntax/round_trip_parse_gen.swift b/test/Syntax/round_trip_parse_gen.swift
index f80a5bf..7d229cc 100644
--- a/test/Syntax/round_trip_parse_gen.swift
+++ b/test/Syntax/round_trip_parse_gen.swift
@@ -320,6 +320,8 @@
   }
   repeat { } while true
   LABEL: repeat { } while false
+  while true { }
+  LABEL: while true { }
   LABEL: do {}
   LABEL: switch foo {
     case 1:
diff --git a/test/stdlib/CodableTests.swift b/test/stdlib/CodableTests.swift
index 8498145..566398c 100644
--- a/test/stdlib/CodableTests.swift
+++ b/test/stdlib/CodableTests.swift
@@ -117,7 +117,7 @@
 // MARK: - Tests
 class TestCodable : TestCodableSuper {
     // MARK: - AffineTransform
-#if os(OSX)
+#if os(macOS)
     lazy var affineTransformValues: [Int : AffineTransform] = [
         #line : AffineTransform.identity,
         #line : AffineTransform(),
@@ -776,7 +776,7 @@
     "test_UUID_Plist" : TestCodable.test_UUID_Plist,
 ]
 
-#if os(OSX)
+#if os(macOS)
     tests["test_AffineTransform_JSON"] = TestCodable.test_AffineTransform_JSON
     tests["test_AffineTransform_Plist"] = TestCodable.test_AffineTransform_Plist
 #endif
diff --git a/test/stdlib/FloatConstants.swift b/test/stdlib/FloatConstants.swift
index e3847f4..5d40927 100644
--- a/test/stdlib/FloatConstants.swift
+++ b/test/stdlib/FloatConstants.swift
@@ -1,6 +1,6 @@
 // RUN: %target-typecheck-verify-swift
 
-#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
+#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
 import Darwin
 #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
 import Glibc
diff --git a/test/stdlib/MathConstants.swift b/test/stdlib/MathConstants.swift
index fd3c3a0..2ecc54d 100644
--- a/test/stdlib/MathConstants.swift
+++ b/test/stdlib/MathConstants.swift
@@ -1,6 +1,6 @@
 // RUN: %target-typecheck-verify-swift
 
-#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
+#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
 import Darwin
 #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
 import Glibc
diff --git a/test/stdlib/Metal.swift b/test/stdlib/Metal.swift
index cb6d50e..682df24 100644
--- a/test/stdlib/Metal.swift
+++ b/test/stdlib/Metal.swift
@@ -72,7 +72,7 @@
       /* Setup */
 
       let device = MTLCreateSystemDefaultDevice()!
-      #if os(OSX)
+      #if os(macOS)
         let options = MTLResourceOptions.storageModeManaged
       #else
         let options = MTLResourceOptions.storageModePrivate
@@ -81,7 +81,7 @@
 
       /* Call APIs */
 
-      #if os(OSX)
+      #if os(macOS)
         buf.didModifyRange(0..<4)
       #endif
       buf.addDebugMarker("test marker", range: 0..<4)
@@ -97,7 +97,7 @@
       let queue = device.makeCommandQueue()!
       let cmdBuf = queue.makeCommandBuffer()!
 
-      #if os(OSX)
+      #if os(macOS)
         let options = MTLResourceOptions.storageModeManaged
       #else
         let options = MTLResourceOptions.storageModePrivate
@@ -162,7 +162,7 @@
       let queue = device.makeCommandQueue()!
       let cmdBuf = queue.makeCommandBuffer()!
 
-      #if os(OSX)
+      #if os(macOS)
         let options = MTLResourceOptions.storageModeManaged
       #else
         let options = MTLResourceOptions.storageModePrivate
@@ -182,7 +182,7 @@
       let encoder = cmdBuf.makeRenderCommandEncoder(descriptor: rpDesc)!
       encoder.useResources([buf], usage: MTLResourceUsage.read)
       encoder.useHeaps([heap])
-      #if os(OSX)
+      #if os(macOS)
         encoder.setViewports([MTLViewport()])
         encoder.setScissorRects([MTLScissorRect(x:0, y:0, width:1, height:1)])
       #endif
diff --git a/test/stdlib/NSStringAPI.swift b/test/stdlib/NSStringAPI.swift
index ac7bd20..cf9afb9 100644
--- a/test/stdlib/NSStringAPI.swift
+++ b/test/stdlib/NSStringAPI.swift
@@ -1329,7 +1329,7 @@
 }
 
 func getHomeDir() -> String {
-#if os(OSX)
+#if os(macOS)
   return String(cString: getpwuid(getuid()).pointee.pw_dir)
 #elseif os(iOS) || os(tvOS) || os(watchOS)
   // getpwuid() returns null in sandboxed apps under iOS simulator.
diff --git a/test/stdlib/NSValueBridging.swift.gyb b/test/stdlib/NSValueBridging.swift.gyb
index 685aadf..5b322b8 100644
--- a/test/stdlib/NSValueBridging.swift.gyb
+++ b/test/stdlib/NSValueBridging.swift.gyb
@@ -59,7 +59,7 @@
 // For historic reasons, macOS has different NSValue methods for the
 // CoreGraphics types from other Apple platforms.
 
-#if os(OSX)
+#if os(macOS)
 
 ${ testCase("CGRect",            "CGRect(x: 17, y: 38, width: 6, height: 79)", "rect",  "(==)") }
 ${ testCase("CGPoint",           "CGPoint(x: 17, y: 38)",                      "point", "(==)") }
diff --git a/test/stdlib/Reflection_objc.swift b/test/stdlib/Reflection_objc.swift
index 28286f7..414221c 100644
--- a/test/stdlib/Reflection_objc.swift
+++ b/test/stdlib/Reflection_objc.swift
@@ -15,7 +15,7 @@
 import Swift
 import Foundation
 
-#if os(OSX)
+#if os(macOS)
 import AppKit
 
 typealias OSImage = NSImage
diff --git a/test/stdlib/Runtime.swift.gyb b/test/stdlib/Runtime.swift.gyb
index e386aac..67ee2bf 100644
--- a/test/stdlib/Runtime.swift.gyb
+++ b/test/stdlib/Runtime.swift.gyb
@@ -9,7 +9,7 @@
 import StdlibUnittest
 import SwiftShims
 
-#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
+#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
 import Darwin
 #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
 import Glibc
@@ -553,7 +553,7 @@
 }
 
 Runtime.test("SwiftError layout constants for LLDB") {
-#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
+#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
   let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: -2)
 #elseif os(Linux)
   let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: 0)
@@ -565,7 +565,7 @@
     dlsym(RTLD_DEFAULT, "_swift_lldb_offsetof_SwiftError_typeMetadata")!
   let sizeof_SwiftError =
     dlsym(RTLD_DEFAULT, "_swift_lldb_sizeof_SwiftError")!
-#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
+#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
 #if arch(i386) || arch(arm)
   expectEqual(20, offsetof_SwiftError_typeMetadata.load(as: UInt.self))
   expectEqual(36, sizeof_SwiftError.load(as: UInt.self))
@@ -1671,7 +1671,7 @@
 
 // _stdlib_isOSVersionAtLeast is broken for
 // watchOS. rdar://problem/20234735
-#if os(OSX) || os(iOS) || os(tvOS) || os(watchOS)
+#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
   // This test assumes that no version component on an OS we test upon
   // will ever be greater than 1066 and that every major version will always
   // be greater than 1.
diff --git a/test/stdlib/RuntimeObjC.swift b/test/stdlib/RuntimeObjC.swift
index 795fefb..140b349 100644
--- a/test/stdlib/RuntimeObjC.swift
+++ b/test/stdlib/RuntimeObjC.swift
@@ -512,54 +512,6 @@
   expectEqual(0, nsStringCanaryCount)
 }
 
-RuntimeFoundationWrappers.test("_stdlib_NSStringHasPrefixNFDPointer/NoLeak") {
-  nsStringCanaryCount = 0
-  autoreleasepool {
-    let a = NSStringCanary()
-    let b = NSStringCanary()
-    expectEqual(2, nsStringCanaryCount)
-    let ptrA = unsafeBitCast(a, to: OpaquePointer.self)
-    let ptrB = unsafeBitCast(b, to: OpaquePointer.self)
-    _stdlib_NSStringHasPrefixNFDPointer(ptrA, ptrB)
-  }
-  expectEqual(0, nsStringCanaryCount)
-}
-
-RuntimeFoundationWrappers.test("_stdlib_NSStringHasSuffixNFDPointer/NoLeak") {
-  nsStringCanaryCount = 0
-  autoreleasepool {
-    let a = NSStringCanary()
-    let b = NSStringCanary()
-    expectEqual(2, nsStringCanaryCount)
-    let ptrA = unsafeBitCast(a, to: OpaquePointer.self)
-    let ptrB = unsafeBitCast(b, to: OpaquePointer.self)
-    _stdlib_NSStringHasSuffixNFDPointer(ptrA, ptrB)
-  }
-  expectEqual(0, nsStringCanaryCount)
-}
-
-RuntimeFoundationWrappers.test("_stdlib_NSStringHasPrefixNFD/NoLeak") {
-  nsStringCanaryCount = 0
-  autoreleasepool {
-    let a = NSStringCanary()
-    let b = NSStringCanary()
-    expectEqual(2, nsStringCanaryCount)
-    _stdlib_NSStringHasPrefixNFD(a, b)
-  }
-  expectEqual(0, nsStringCanaryCount)
-}
-
-RuntimeFoundationWrappers.test("_stdlib_NSStringHasSuffixNFD/NoLeak") {
-  nsStringCanaryCount = 0
-  autoreleasepool {
-    let a = NSStringCanary()
-    let b = NSStringCanary()
-    expectEqual(2, nsStringCanaryCount)
-    _stdlib_NSStringHasSuffixNFD(a, b)
-  }
-  expectEqual(0, nsStringCanaryCount)
-}
-
 RuntimeFoundationWrappers.test("_stdlib_NSStringLowercaseString/NoLeak") {
   nsStringCanaryCount = 0
   autoreleasepool {
diff --git a/test/stdlib/StringAPI.swift b/test/stdlib/StringAPI.swift
index 6c7662e..0e23f20 100644
--- a/test/stdlib/StringAPI.swift
+++ b/test/stdlib/StringAPI.swift
@@ -272,22 +272,11 @@
 let substringTests = tests.map {
   (test: ComparisonTest) -> ComparisonTest in
   switch (test.expectedUnicodeCollation, test.lhs, test.rhs) {
-  case (.eq, "\u{0}", "\u{0}"):
-    return test.replacingPredicate(.objCRuntime(
-      "https://bugs.swift.org/browse/SR-332"))
 
   case (.gt, "\r\n", "\n"):
     return test.replacingPredicate(.objCRuntime(
       "blocked on rdar://problem/19036555"))
 
-  case (.eq, "\u{0301}", "\u{0341}"):
-    return test.replacingPredicate(.objCRuntime(
-      "https://bugs.swift.org/browse/SR-243"))
-
-  case (.lt, "\u{1F1E7}", "\u{1F1E7}\u{1F1E7}"):
-    return test.replacingPredicate(.objCRuntime(
-      "https://bugs.swift.org/browse/SR-367"))
-
   default:
     return test
   }
diff --git a/test/stdlib/StringCompatibility.swift b/test/stdlib/StringCompatibility.swift
index fb0031e..22c68d1 100644
--- a/test/stdlib/StringCompatibility.swift
+++ b/test/stdlib/StringCompatibility.swift
@@ -116,8 +116,6 @@
   }
 }
 
-#if _runtime(_ObjC)
-
 extension MyString {
   public func hasPrefix(_ prefix: String) -> Bool {
     return self.base.hasPrefix(prefix)
@@ -128,8 +126,6 @@
   }
 }
 
-#endif
-
 extension MyString : StringProtocol {
   typealias UTF8Index = String.UTF8Index
   typealias UTF16Index = String.UTF16Index
diff --git a/test/stdlib/TestAffineTransform.swift b/test/stdlib/TestAffineTransform.swift
index ad2b07a..a0b384a 100644
--- a/test/stdlib/TestAffineTransform.swift
+++ b/test/stdlib/TestAffineTransform.swift
@@ -12,7 +12,7 @@
 
 import Foundation
 
-#if os(OSX)
+#if os(macOS)
 
 #if FOUNDATION_XCTEST
 import XCTest
diff --git a/test/stdlib/TestURL.swift b/test/stdlib/TestURL.swift
index 637e043..8c0128c 100644
--- a/test/stdlib/TestURL.swift
+++ b/test/stdlib/TestURL.swift
@@ -67,7 +67,7 @@
         }
     }
     
-#if os(OSX)
+#if os(macOS)
     func testQuarantineProperties() {
         // Test the quarantine stuff; it has special logic
         if #available(OSX 10.11, iOS 9.0, *) {
@@ -383,7 +383,7 @@
 URLTests.test("testBasics") { TestURL().testBasics() }
 URLTests.test("testProperties") { TestURL().testProperties() }
 URLTests.test("testSetProperties") { TestURL().testSetProperties() }
-#if os(OSX)
+#if os(macOS)
 URLTests.test("testQuarantineProperties") { TestURL().testQuarantineProperties() }
 #endif
 URLTests.test("testMoreSetProperties") { TestURL().testMoreSetProperties() }
diff --git a/test/stdlib/os.swift b/test/stdlib/os.swift
index 55db1b4..11dfe00 100644
--- a/test/stdlib/os.swift
+++ b/test/stdlib/os.swift
@@ -17,6 +17,7 @@
     os_log("test2: %@", "test")
   }
 
+  /* FIXME: currently disabled: rdar://problem/38354907
   osAPI.test("logData") {
     let data = "hello logging world".data(using: .utf8)!
 
@@ -26,6 +27,7 @@
       os_log("%.*P", OpaquePointer(bytes))
     }
   }
+  */
   osAPI.test("newLog") {
     let newLog = OSLog(subsystem: "com.apple.Swift", category: "Test")
     os_log("test", log: newLog)
diff --git a/tools/SourceKit/include/SourceKit/Support/Logging.h b/tools/SourceKit/include/SourceKit/Support/Logging.h
index 5ee48e1..cf2d19f 100644
--- a/tools/SourceKit/include/SourceKit/Support/Logging.h
+++ b/tools/SourceKit/include/SourceKit/Support/Logging.h
@@ -40,7 +40,7 @@
 /// \endcode
 class Logger : public llvm::RefCountedBase<Logger> {
 public:
-  enum class Level : unsigned char {
+  enum class Level : uint8_t {
     /// \brief No logging.
     None = 0,
     /// \brief Warning level.
diff --git a/tools/SwiftSyntax/RawSyntax.swift b/tools/SwiftSyntax/RawSyntax.swift
index cf9bc92..bce0e0b 100644
--- a/tools/SwiftSyntax/RawSyntax.swift
+++ b/tools/SwiftSyntax/RawSyntax.swift
@@ -193,3 +193,52 @@
     }
   }
 }
+
+extension RawSyntax {
+  func accumulateAbsolutePosition(_ pos: AbsolutePosition) {
+    switch self {
+    case .node(_, let layout, _):
+      for child in layout {
+        guard let child = child else { continue }
+        child.accumulateAbsolutePosition(pos)
+      }
+    case let .token(kind, leadingTrivia, trailingTrivia, presence):
+      guard case .present = presence else { return }
+      for piece in leadingTrivia {
+        piece.accumulateAbsolutePosition(pos)
+      }
+      pos.add(text: kind.text)
+      for piece in trailingTrivia {
+        piece.accumulateAbsolutePosition(pos)
+      }
+    }
+  }
+
+  func accumulateLeadingTrivia(_ pos: AbsolutePosition) -> Bool {
+    switch self {
+    case .node(_, let layout, _):
+      for child in layout {
+        guard let child = child else { continue }
+        if child.accumulateLeadingTrivia(pos) {
+          return true
+        }
+      }
+      return false
+    case let .token(_, leadingTrivia, _, presence):
+      guard case .present = presence else { return false }
+      for piece in leadingTrivia {
+        piece.accumulateAbsolutePosition(pos)
+      }
+      return true
+    }
+  }
+
+  var isSourceFile: Bool {
+    switch self {
+    case .node(let kind, _, _):
+      return kind == SyntaxKind.sourceFile
+    default:
+      return false
+    }
+  }
+}
diff --git a/tools/SwiftSyntax/Syntax.swift b/tools/SwiftSyntax/Syntax.swift
index efce76f..9b936a8 100644
--- a/tools/SwiftSyntax/Syntax.swift
+++ b/tools/SwiftSyntax/Syntax.swift
@@ -74,14 +74,14 @@
     return data.childCaches.count
   }
 
-  /// Whether or not this node it marked as `present`.
+  /// Whether or not this node is marked as `present`.
   public var isPresent: Bool {
-    return raw.presence == .present
+    return raw.isPresent
   }
 
-  /// Whether or not this node it marked as `missing`.
+  /// Whether or not this node is marked as `missing`.
   public var isMissing: Bool {
-    return raw.presence == .missing
+    return raw.isMissing
   }
 
   /// Whether or not this node represents an Expression.
@@ -120,6 +120,24 @@
     return data.indexInParent
   }
 
+  /// The absolute position of the starting point this node. If the first token
+  /// is with leading trivia, the position points to the start of the leading
+  /// trivia.
+  public var position: AbsolutePosition {
+    return data.position
+  }
+
+  /// The absolute position of the starting point of this node, skipping any
+  /// leading trivia attached to the first token syntax.
+  public var positionAfterSkippingLeadingTrivia: AbsolutePosition {
+    return data.positionAfterSkippingLeadingTrivia
+  }
+
+  /// The textual byte length of this node including leading and trailing trivia.
+  public var byteSize: Int {
+    return data.byteSize
+  }
+
   /// The root of the tree in which this node resides.
   public var root: Syntax {
     return makeSyntax(root: _root,  data: _root)
@@ -185,7 +203,9 @@
   public var text: String {
     return tokenKind.text
   }
-
+  
+  /// Returns a new TokenSyntax with its kind replaced
+  /// by the provided token kind.
   public func withKind(_ tokenKind: TokenKind) -> TokenSyntax {
     guard case let .token(_, leadingTrivia, trailingTrivia, presence) = raw else {
       fatalError("TokenSyntax must have token as its raw")
diff --git a/tools/SwiftSyntax/SyntaxData.swift b/tools/SwiftSyntax/SyntaxData.swift
index 7e3c55d..12b8c37 100644
--- a/tools/SwiftSyntax/SyntaxData.swift
+++ b/tools/SwiftSyntax/SyntaxData.swift
@@ -38,6 +38,64 @@
 
   let childCaches: [AtomicCache<SyntaxData>]
 
+  let positionCache: AtomicCache<AbsolutePosition>
+
+  fileprivate func calculatePosition() -> AbsolutePosition {
+    guard let parent = parent else {
+      assert(raw.isSourceFile, "cannot find SourceFileSyntax as root")
+      // If this node is SourceFileSyntax, its location is the start of the file.
+      return AbsolutePosition()
+    }
+
+    // If the node is the first child of its parent, the location is same with
+    // the parent's location.
+    guard indexInParent != 0 else { return parent.position }
+
+    // Otherwise, the location is same with the previous sibling's location
+    // adding the stride of the sibling.
+    for idx in (0..<indexInParent).reversed() {
+      if let sibling = parent.cachedChild(at: idx) {
+        let pos = sibling.position.copy()
+        sibling.raw.accumulateAbsolutePosition(pos)
+        return pos
+      }
+    }
+    return parent.position
+  }
+
+  var position: AbsolutePosition {
+    return positionCache.value { return calculatePosition() }
+  }
+
+  var positionAfterSkippingLeadingTrivia: AbsolutePosition {
+    let result = position.copy()
+    _ = raw.accumulateLeadingTrivia(result)
+    return result
+  }
+
+  fileprivate func getNextSiblingPos() -> AbsolutePosition {
+    // If this node is root, the position of the next sibling is the end of
+    // this node.
+    guard let parent = parent else {
+      assert(raw.isSourceFile, "cannot find SourceFileSyntax as root")
+      let result = self.position.copy()
+      raw.accumulateAbsolutePosition(result)
+      return result
+    }
+
+    // Find the first valid sibling and return its position.
+    for i in indexInParent+1..<parent.raw.layout.count {
+      guard let sibling = parent.cachedChild(at: i) else { continue }
+      return sibling.position
+    }
+    // Otherwise, use the parent's sibling instead.
+    return parent.getNextSiblingPos()
+  }
+
+  var byteSize: Int {
+    return getNextSiblingPos().byteOffset - self.position.byteOffset
+  }
+
   /// Creates a SyntaxData with the provided raw syntax, pointing to the
   /// provided index, in the provided parent.
   /// - Parameters:
@@ -51,6 +109,7 @@
     self.indexInParent = indexInParent
     self.parent = parent
     self.childCaches = raw.layout.map { _ in AtomicCache<SyntaxData>() }
+    self.positionCache = AtomicCache<AbsolutePosition>()
   }
 
   /// The index path from this node to the root. This can be used to uniquely
@@ -198,3 +257,62 @@
     return lhs === rhs
   }
 }
+
+/// An absolute position in a source file as text - the absolute byteOffset from
+/// the start, line, and column.
+public class AbsolutePosition {
+  public private(set) var byteOffset: Int = 0
+  public private(set) var line: Int = 1
+  public private(set) var column: Int = 1
+
+  internal func copy() -> AbsolutePosition {
+    let result = AbsolutePosition()
+    result.byteOffset = byteOffset
+    result.line = line
+    result.column = column
+    return result
+  }
+
+  /// Add some number of columns to the position.
+  internal func add(columns: Int) {
+    column += columns
+    byteOffset += columns
+  }
+
+  /// Add some number of newlines to the position, resetting the column.
+  /// Size is byte size of newline char.
+  /// '\n' and '\r' are 1, '\r\n' is 2.
+  internal func add(lines: Int, size: Int) {
+    line += lines
+    column = 1
+    byteOffset += lines * size
+  }
+
+  /// Use some text as a reference for adding to the absolute position,
+  /// taking note of newlines, etc.
+  internal func add(text: String) {
+    guard let chars = text.cString(using: .utf8) else {
+      return
+    }
+    let cr: CChar = 13
+    let nl: CChar = 10
+    var idx = chars.startIndex
+    while chars[idx] != 0 {
+      let c = chars[idx]
+      idx += 1
+      switch c {
+      case cr:
+        if chars[idx] == nl {
+          add(lines: 1, size: 2)
+          idx += 1
+        } else {
+          add(lines: 1, size: 1)
+        }
+      case nl:
+        add(lines: 1, size: 1)
+      default:
+        add(columns: 1)
+      }
+    }
+  }
+}
diff --git a/tools/SwiftSyntax/Trivia.swift.gyb b/tools/SwiftSyntax/Trivia.swift.gyb
index 29f765b..54406ea 100644
--- a/tools/SwiftSyntax/Trivia.swift.gyb
+++ b/tools/SwiftSyntax/Trivia.swift.gyb
@@ -256,3 +256,22 @@
 public func +(lhs: Trivia, rhs: Trivia) -> Trivia {
   return Trivia(pieces: lhs.pieces + rhs.pieces)
 }
+
+extension TriviaPiece {
+  func accumulateAbsolutePosition(_ pos: AbsolutePosition) {
+    switch self {
+% for trivia in TRIVIAS:
+%   if trivia.is_new_line:
+    case let .${trivia.lower_name}s(count):
+      pos.add(lines: count, size: ${trivia.characters_len()})
+%   elif trivia.is_collection():
+    case let .${trivia.lower_name}s(count):
+      pos.add(columns: count)
+%   else:
+    case let .${trivia.lower_name}(text):
+      pos.add(text: text)
+%   end
+% end
+  }
+  }
+}
diff --git a/tools/swift-api-digester/swift-api-digester.cpp b/tools/swift-api-digester/swift-api-digester.cpp
index fbf14b9..8a41b3e 100644
--- a/tools/swift-api-digester/swift-api-digester.cpp
+++ b/tools/swift-api-digester/swift-api-digester.cpp
@@ -939,7 +939,7 @@
   SDKNodeInitInfo Info(Ctx);
   NodeVector Children;
 
-  for (auto Pair : *Node) {
+  for (auto &Pair : *Node) {
     switch(parseKeyKind(GetScalarString(Pair.getKey()))) {
     case KeyKind::KK_kind:
       Kind = parseSDKNodeKind(GetScalarString(Pair.getValue()));
diff --git a/utils/gyb_syntax_support/Trivia.py b/utils/gyb_syntax_support/Trivia.py
index fe32541..d996845 100644
--- a/utils/gyb_syntax_support/Trivia.py
+++ b/utils/gyb_syntax_support/Trivia.py
@@ -3,12 +3,13 @@
 
 class Trivia(object):
     def __init__(self, name, comment, characters=[], swift_characters=[],
-                 is_new_line=False):
+                 is_new_line=False, is_comment=False):
         self.name = name
         self.comment = comment
         self.characters = characters
         self.lower_name = lowercase_first_word(name)
         self.is_new_line = is_new_line
+        self.is_comment = is_comment
 
         # Swift sometimes doesn't support escaped characters like \f or \v;
         # we should allow specifying alternatives explicitly.
@@ -44,14 +45,18 @@
            'A backtick \'`\' character, used to escape identifiers.',
            characters=['`']),
 
-    Trivia('LineComment', 'A developer line comment, starting with \'//\''),
+    Trivia('LineComment', 'A developer line comment, starting with \'//\'',
+           is_comment=True),
     Trivia('BlockComment',
            'A developer block comment, starting with \'/*\' and ending with'
-           ' \'*/\'.'),
+           ' \'*/\'.',
+           is_comment=True),
     Trivia('DocLineComment',
-           'A documentation line comment, starting with \'///\'.'),
+           'A documentation line comment, starting with \'///\'.',
+           is_comment=True),
     Trivia('DocBlockComment',
            'A documentation block comment, starting with \'/**\' and ending '
-           'with \'*/\'.'),
+           'with \'*/\'.',
+           is_comment=True),
     Trivia('GarbageText', 'Any skipped garbage text.'),
 ]
diff --git a/utils/update-checkout-config.json b/utils/update-checkout-config.json
index 44968dd..a530238 100644
--- a/utils/update-checkout-config.json
+++ b/utils/update-checkout-config.json
@@ -191,14 +191,14 @@
         "swift-4.2-branch" : {
             "aliases": ["swift-4.2-branch"],
             "repos": {
-                "llvm": "swift-4.1-branch",
-                "clang": "swift-4.1-branch",
+                "llvm": "swift-4.2-branch",
+                "clang": "swift-4.2-branch",
                 "swift": "swift-4.2-branch",
                 "lldb": "swift-4.2-branch",
                 "cmark": "master",
                 "llbuild": "master",
                 "swiftpm": "master",
-                "compiler-rt": "swift-4.1-branch",
+                "compiler-rt": "swift-4.2-branch",
                 "swift-corelibs-xctest": "master",
                 "swift-corelibs-foundation": "master",
                 "swift-corelibs-libdispatch": "master",
diff --git a/validation-test/stdlib/Lazy.swift.gyb b/validation-test/stdlib/Lazy.swift.gyb
index 8e2393b..1f3ff08 100644
--- a/validation-test/stdlib/Lazy.swift.gyb
+++ b/validation-test/stdlib/Lazy.swift.gyb
@@ -12,6 +12,10 @@
 // RUN: %target-run-simple-swiftgyb
 // REQUIRES: executable_test
 
+// <rdar://35797159> [Associated Type Inference]
+// heap-use-after-free ASTContext::getSpecializedConformance
+// llvm::FoldingSetBase::InsertNode
+// REQUIRES: OS=macosx || no_asan
 
 import StdlibUnittest
 import StdlibCollectionUnittest
diff --git a/validation-test/stdlib/MicroStdlib/Inputs/RuntimeStubs.c b/validation-test/stdlib/MicroStdlib/Inputs/RuntimeStubs.c
index eaa1120..fc88d14 100644
--- a/validation-test/stdlib/MicroStdlib/Inputs/RuntimeStubs.c
+++ b/validation-test/stdlib/MicroStdlib/Inputs/RuntimeStubs.c
@@ -1,6 +1,9 @@
 int $SBi32_N;
 int $SBi64_N;
 int $SBi8_N;
+int $SBi32_WV;
+int $SBi64_WV;
+int $SBi8_WV;
 void swift_getEnumCaseSinglePayload(void) {}
 void swift_getGenericMetadata(void) {}
 void swift_slowAlloc(void) {}