[clang] [clang-tools-extra] Upstream zippered sema support (PR #219032)

Ian Anderson via cfe-commits cfe-commits at lists.llvm.org
Wed Aug 26 13:45:56 PDT 2026


https://github.com/ian-twilightcoder created https://github.com/llvm/llvm-project/pull/219032

None

>From e6299d4cbb513bc2267f5d941f72e9c0803223e5 Mon Sep 17 00:00:00 2001
From: Alex Lorenz <aleksei_lorenz at apple.com>
Date: Fri, 30 Mar 2018 15:44:31 -0700
Subject: [PATCH 01/21] Implement Sema iosmac support

rdar://38885683

apple-llvm-split-commit: 40aab84d831ddfc623de95fbbca06de6f0baf0a6
apple-llvm-split-dir: clang/
---
 clang-tools-extra/clangd/FindSymbols.cpp      |    4 +-
 clang-tools-extra/clangd/XRefs.cpp            |    4 +-
 clang/include/clang/AST/DeclBase.h            |   18 +-
 clang/include/clang/AST/ExprObjC.h            |   15 +-
 .../clang/Basic/DiagnosticSemaKinds.td        |    3 +
 clang/include/clang/Basic/TargetInfo.h        |   24 +
 clang/include/clang/Sema/DelayedDiagnostic.h  |   20 +-
 clang/include/clang/Sema/Sema.h               |    9 +-
 clang/lib/AST/DeclBase.cpp                    |   53 +-
 clang/lib/Basic/Targets/ARM.cpp               |    4 +-
 clang/lib/Basic/Targets/OSTargets.cpp         |   14 +-
 clang/lib/Basic/Targets/OSTargets.h           |   21 +-
 clang/lib/CodeGen/CGExprScalar.cpp            |   11 +-
 clang/lib/CodeGen/CGObjC.cpp                  |   55 +-
 clang/lib/CodeGen/CodeGenFunction.h           |    3 +-
 clang/lib/CodeGen/CodeGenModule.h             |    2 +
 clang/lib/Edit/RewriteObjCFoundationAPI.cpp   |    2 +-
 clang/lib/Sema/CodeCompleteConsumer.cpp       |   12 +-
 clang/lib/Sema/DelayedDiagnostic.cpp          |   16 +-
 clang/lib/Sema/SemaAvailability.cpp           | 1198 +++++++++++------
 clang/lib/Sema/SemaDecl.cpp                   |    5 +-
 clang/lib/Sema/SemaDeclAttr.cpp               |   25 +-
 clang/lib/Sema/SemaDeclObjC.cpp               |   45 +-
 clang/lib/Sema/SemaExpr.cpp                   |    4 +-
 clang/lib/Sema/SemaExprObjC.cpp               |   14 +-
 clang/lib/Sema/SemaLookup.cpp                 |    2 +-
 clang/lib/Sema/SemaObjCProperty.cpp           |    9 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp    |    7 +-
 clang/lib/Serialization/ASTReaderStmt.cpp     |    1 +
 clang/lib/Serialization/ASTWriterStmt.cpp     |    1 +
 .../CodeGenObjC/availability-check-zippered.m |   41 +
 .../test/FixIt/fixit-availability-zippered.m  |   23 +
 clang/test/Sema/attr-availability-zippered.c  |  133 ++
 .../unguarded-availability-zippered.m         |   42 +
 clang/tools/libclang/CIndex.cpp               |    5 +-
 35 files changed, 1371 insertions(+), 474 deletions(-)
 create mode 100644 clang/test/CodeGenObjC/availability-check-zippered.m
 create mode 100644 clang/test/FixIt/fixit-availability-zippered.m
 create mode 100644 clang/test/Sema/attr-availability-zippered.c
 create mode 100644 clang/test/SemaObjC/unguarded-availability-zippered.m

diff --git a/clang-tools-extra/clangd/FindSymbols.cpp b/clang-tools-extra/clangd/FindSymbols.cpp
index 2a674d375b5d9..f3a10c281f424 100644
--- a/clang-tools-extra/clangd/FindSymbols.cpp
+++ b/clang-tools-extra/clangd/FindSymbols.cpp
@@ -250,7 +250,7 @@ SymbolTags computeSymbolTags(const NamedDecl &ND) {
   SymbolTags Result = 0;
   const auto IsDef = isUniqueDefinition(&ND);
 
-  if (ND.isDeprecated())
+  if (ND.isDeprecatedInAnyTargetPlatform())
     Result |= toSymbolTagBitmask(SymbolTag::Deprecated);
 
   if (isConst(&ND))
@@ -563,7 +563,7 @@ std::optional<DocumentSymbol> declToSym(ASTContext &Ctx, const NamedDecl &ND) {
   DocumentSymbol SI;
   SI.name = getSymbolName(Ctx, ND);
   SI.kind = SK;
-  SI.deprecated = ND.isDeprecated();
+  SI.deprecated = ND.isDeprecatedInAnyTargetPlatform();
   SI.range = Range{sourceLocToPosition(SM, SymbolRange->getBegin()),
                    sourceLocToPosition(SM, SymbolRange->getEnd())};
   SI.detail = getSymbolDetail(Ctx, ND);
diff --git a/clang-tools-extra/clangd/XRefs.cpp b/clang-tools-extra/clangd/XRefs.cpp
index 86528d806eab3..bfc440302696c 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -1865,7 +1865,7 @@ static std::optional<TypeHierarchyItem>
 declToTypeHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
   auto Result = declToHierarchyItem<TypeHierarchyItem>(ND, TUPath);
   if (Result) {
-    Result->deprecated = ND.isDeprecated();
+    Result->deprecated = ND.isDeprecatedInAnyTargetPlatform();
     // Compute the SymbolID and store it in the 'data' field.
     // This allows typeHierarchy/resolve to be used to
     // resolve children of items returned in a previous request
@@ -1880,7 +1880,7 @@ declToCallHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
   auto Result = declToHierarchyItem<CallHierarchyItem>(ND, TUPath);
   if (!Result)
     return Result;
-  if (ND.isDeprecated())
+  if (ND.isDeprecatedInAnyTargetPlatform())
     Result->tags.push_back(SymbolTag::Deprecated);
   if (auto ID = getSymbolID(&ND))
     Result->data = ID.str();
diff --git a/clang/include/clang/AST/DeclBase.h b/clang/include/clang/AST/DeclBase.h
index 9d233be282dbb..2cf8a792c9df8 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -758,6 +758,13 @@ class alignas(8) Decl {
                   VersionTuple EnclosingVersion = VersionTuple(),
                   StringRef *RealizedPlatform = nullptr) const;
 
+  /// Determine the availability of the given declaration for the given
+  /// target platform and its minimum version.
+  AvailabilityResult
+  getAvailability(StringRef Platform, const VersionTuple &PlatformMinVersion,
+                  std::string *Message = nullptr,
+                  StringRef *RealizedPlatform = nullptr) const;
+
   /// Retrieve the version of the target platform in which this
   /// declaration was introduced.
   ///
@@ -766,14 +773,13 @@ class alignas(8) Decl {
   /// attribute otherwise.
   VersionTuple getVersionIntroduced() const;
 
-  /// Determine whether this declaration is marked 'deprecated'.
+  /// \brief Determine whether this declaration is marked 'deprecated' in any
+  /// target platform that we're compiling for.
   ///
   /// \param Message If non-NULL and the declaration is deprecated,
   /// this will be set to the message describing why the declaration
   /// was deprecated (which may be empty).
-  bool isDeprecated(std::string *Message = nullptr) const {
-    return getAvailability(Message) == AR_Deprecated;
-  }
+  bool isDeprecatedInAnyTargetPlatform(std::string *Message = nullptr) const;
 
   /// Determine whether this declaration is marked 'unavailable'.
   ///
@@ -784,6 +790,10 @@ class alignas(8) Decl {
     return getAvailability(Message) == AR_Unavailable;
   }
 
+  /// \brief Determine whether this declaration is marked 'deprecated' for
+  /// all target platforms that we're compiling for.
+  bool isUnavailabledForAllTargetPlatforms() const;
+
   /// Determine whether this is a weak-imported symbol.
   ///
   /// Weak-imported symbols are typically marked with the
diff --git a/clang/include/clang/AST/ExprObjC.h b/clang/include/clang/AST/ExprObjC.h
index b424530c8447c..39f22c961ce96 100644
--- a/clang/include/clang/AST/ExprObjC.h
+++ b/clang/include/clang/AST/ExprObjC.h
@@ -1736,13 +1736,18 @@ class ObjCAvailabilityCheckExpr : public Expr {
   friend class ASTStmtReader;
 
   VersionTuple VersionToCheck;
+  VersionTuple VariantVersionToCheck;
   SourceLocation AtLoc, RParen;
 
 public:
-  ObjCAvailabilityCheckExpr(VersionTuple VersionToCheck, SourceLocation AtLoc,
-                            SourceLocation RParen, QualType Ty)
+  ObjCAvailabilityCheckExpr(VersionTuple VersionToCheck,
+                            VersionTuple VariantVersionToCheck,
+                            SourceLocation AtLoc, SourceLocation RParen,
+                            QualType Ty)
       : Expr(ObjCAvailabilityCheckExprClass, Ty, VK_PRValue, OK_Ordinary),
-        VersionToCheck(VersionToCheck), AtLoc(AtLoc), RParen(RParen) {
+        VersionToCheck(VersionToCheck),
+        VariantVersionToCheck(VariantVersionToCheck), AtLoc(AtLoc),
+        RParen(RParen) {
     setDependence(ExprDependence::None);
   }
 
@@ -1757,6 +1762,10 @@ class ObjCAvailabilityCheckExpr : public Expr {
   bool hasVersion() const { return !VersionToCheck.empty(); }
   VersionTuple getVersion() const { return VersionToCheck; }
 
+  bool hasVariantVersion() const { return !VariantVersionToCheck.empty(); }
+
+  VersionTuple getVariantVersion() const { return VariantVersionToCheck; }
+
   child_range children() {
     return child_range(child_iterator(), child_iterator());
   }
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index cfb2ee3368201..c6b237c883a2b 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -4300,6 +4300,9 @@ def warn_unguarded_availability_new :
 def warn_unguarded_availability_unavailable_new :
   Warning<warn_unguarded_availability_unavailable.Summary>,
   InGroup<UnguardedAvailabilityNew>;
+def warn_zippered_unguarded_availability :
+  Warning<"%0 is only available on %1 %2 and %3 %4 or newer">,
+  InGroup<UnguardedAvailabilityNew>;
 def note_decl_unguarded_availability_silence : Note<
   "annotate %select{%1|anonymous %1}0 with an availability attribute to silence this warning">;
 def note_unguarded_available_silence : Note<
diff --git a/clang/include/clang/Basic/TargetInfo.h b/clang/include/clang/Basic/TargetInfo.h
index 5a541aaf797fe..66a7ba2bd096f 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -260,6 +260,8 @@ class TargetInfo : public TransferrableTargetInfo,
 
   mutable StringRef PlatformName;
   mutable VersionTuple PlatformMinVersion;
+  mutable StringRef TargetVariantPlatform;
+  mutable VersionTuple TargetVariantPlatformMinVersion;
 
   LLVM_PREFERRED_TYPE(bool)
   unsigned HasAlignMac68kSupport : 1;
@@ -1737,6 +1739,28 @@ class TargetInfo : public TransferrableTargetInfo,
   /// which the program should be compiled.
   VersionTuple getPlatformMinVersion() const { return PlatformMinVersion; }
 
+  /// Returns true when are building for an auxillary target variant platform.
+  bool hasTargetVariantPlatform() const {
+    return !TargetVariantPlatform.empty();
+  }
+
+  /// Retrieve the name of the target variant platform as it is used in the
+  /// availability attribute.
+  StringRef getTargetVariantPlatform() const {
+    assert(hasTargetVariantPlatform() &&
+           "no target variant platform specified");
+    return TargetVariantPlatform;
+  }
+
+  /// Retrieve the minimum desired deployment version of the target variant
+  /// platform,
+  /// for which the program should be compiled.
+  VersionTuple getTargetVariantPlatformMinVersion() const {
+    assert(hasTargetVariantPlatform() &&
+           "no target variant platform specified");
+    return TargetVariantPlatformMinVersion;
+  }
+
   bool isBigEndian() const { return BigEndian; }
   bool isLittleEndian() const { return !BigEndian; }
 
diff --git a/clang/include/clang/Sema/DelayedDiagnostic.h b/clang/include/clang/Sema/DelayedDiagnostic.h
index 0105089a393f1..5e45c3459f151 100644
--- a/clang/include/clang/Sema/DelayedDiagnostic.h
+++ b/clang/include/clang/Sema/DelayedDiagnostic.h
@@ -134,14 +134,13 @@ class DelayedDiagnostic {
 
   void Destroy();
 
-  static DelayedDiagnostic makeAvailability(AvailabilityResult AR,
-                                            ArrayRef<SourceLocation> Locs,
-                                            const NamedDecl *ReferringDecl,
-                                            const NamedDecl *OffendingDecl,
-                                            const ObjCInterfaceDecl *UnknownObjCClass,
-                                            const ObjCPropertyDecl  *ObjCProperty,
-                                            StringRef Msg,
-                                            bool ObjCPropertyAccess);
+  static DelayedDiagnostic
+  makeAvailability(AvailabilityResult AR, ArrayRef<SourceLocation> Locs,
+                   const NamedDecl *ReferringDecl,
+                   const NamedDecl *OffendingDecl,
+                   const ObjCInterfaceDecl *UnknownObjCClass,
+                   const ObjCPropertyDecl *ObjCProperty, StringRef Msg,
+                   bool ObjCPropertyAccess, bool IsTargetVariantPlatform);
 
   static DelayedDiagnostic makeAccess(SourceLocation Loc,
                                       const AccessedEntity &Entity) {
@@ -232,6 +231,10 @@ class DelayedDiagnostic {
     return AvailabilityData.ObjCPropertyAccess;
   }
 
+  bool isTargetVariantPlatform() const {
+    return AvailabilityData.IsTargetVariantPlatform;
+  }
+
 private:
   struct AD {
     const NamedDecl *ReferringDecl;
@@ -244,6 +247,7 @@ class DelayedDiagnostic {
     size_t NumSelectorLocs;
     AvailabilityResult AR;
     bool ObjCPropertyAccess;
+    bool IsTargetVariantPlatform;
   };
 
   struct FTD {
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index dcf112fd8eaa4..42858681fba88 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2466,6 +2466,11 @@ class Sema final : public SemaBase {
 
   void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
 
+  void
+  handleZipperedDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD,
+                                         sema::DelayedDiagnostic &VariantDD,
+                                         Decl *Ctx);
+
   /// Retrieve the current function, if any, that should be analyzed for
   /// potential availability violations.
   sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
@@ -2479,7 +2484,9 @@ class Sema final : public SemaBase {
   void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs);
 
   std::pair<AvailabilityResult, const NamedDecl *>
-  ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
+  ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, StringRef Platform,
+                                   const VersionTuple &PlatformVersion,
+                                   std::string *Message,
                                    ObjCInterfaceDecl *ClassReceiver);
   ///@}
 
diff --git a/clang/lib/AST/DeclBase.cpp b/clang/lib/AST/DeclBase.cpp
index 70f61fa57a682..aff04541c6781 100644
--- a/clang/lib/AST/DeclBase.cpp
+++ b/clang/lib/AST/DeclBase.cpp
@@ -674,15 +674,12 @@ static StringRef getRealizedPlatform(const AvailabilityAttr *A,
 static AvailabilityResult CheckAvailability(ASTContext &Context,
                                             const AvailabilityAttr *A,
                                             std::string *Message,
+                                            StringRef TargetPlatform,
                                             VersionTuple EnclosingVersion) {
-  if (EnclosingVersion.empty())
-    EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
-
   if (EnclosingVersion.empty())
     return AR_Available;
 
   StringRef ActualPlatform = A->getPlatform()->getName();
-  StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
 
   // Match the platform name.
   if (getRealizedPlatform(A, Context) != TargetPlatform)
@@ -779,9 +776,20 @@ static AvailabilityResult CheckAvailability(ASTContext &Context,
 AvailabilityResult Decl::getAvailability(std::string *Message,
                                          VersionTuple EnclosingVersion,
                                          StringRef *RealizedPlatform) const {
+  const TargetInfo &TI = getASTContext().getTargetInfo();
+  return getAvailability(TI.getPlatformName(),
+                         EnclosingVersion.empty() ? TI.getPlatformMinVersion()
+                                                  : EnclosingVersion,
+                         Message, RealizedPlatform);
+}
+
+AvailabilityResult Decl::getAvailability(StringRef Platform,
+                                         const VersionTuple &PlatformMinVersion,
+                                         std::string *Message,
+                                         StringRef *RealizedPlatform) const {
   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
-    return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion,
-                                                    RealizedPlatform);
+    return FTD->getTemplatedDecl()->getAvailability(
+        Platform, PlatformMinVersion, Message, RealizedPlatform);
 
   AvailabilityResult Result = AR_Available;
   std::string ResultMessage;
@@ -806,8 +814,8 @@ AvailabilityResult Decl::getAvailability(std::string *Message,
 
     if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
       Availability = Availability->getEffectiveAttr();
-      AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
-                                                Message, EnclosingVersion);
+      AvailabilityResult AR = CheckAvailability(
+          getASTContext(), Availability, Message, Platform, PlatformMinVersion);
 
       if (AR == AR_Unavailable) {
         if (RealizedPlatform)
@@ -844,6 +852,26 @@ VersionTuple Decl::getVersionIntroduced() const {
   return {};
 }
 
+bool Decl::isDeprecatedInAnyTargetPlatform(std::string *Message) const {
+  const TargetInfo &TI = getASTContext().getTargetInfo();
+  return getAvailability(TI.getPlatformName(), TI.getPlatformMinVersion()) ==
+             AR_Deprecated ||
+         (TI.hasTargetVariantPlatform() &&
+          getAvailability(TI.getTargetVariantPlatform(),
+                          TI.getTargetVariantPlatformMinVersion()) ==
+              AR_Deprecated);
+}
+
+bool Decl::isUnavailabledForAllTargetPlatforms() const {
+  const TargetInfo &TI = getASTContext().getTargetInfo();
+  return getAvailability(TI.getPlatformName(), TI.getPlatformMinVersion()) ==
+             AR_Unavailable &&
+         (!getASTContext().getTargetInfo().hasTargetVariantPlatform() ||
+          getAvailability(TI.getTargetVariantPlatform(),
+                          TI.getTargetVariantPlatformMinVersion()) ==
+              AR_Unavailable);
+}
+
 bool Decl::canBeWeakImported(bool &IsDefinition) const {
   IsDefinition = false;
 
@@ -878,6 +906,7 @@ bool Decl::isWeakImported() const {
   if (!canBeWeakImported(IsDefinition))
     return false;
 
+  const TargetInfo &TI = getASTContext().getTargetInfo();
   for (const auto *A : getMostRecentDecl()->attrs()) {
     if (isa<WeakImportAttr>(A))
       return true;
@@ -885,7 +914,13 @@ bool Decl::isWeakImported() const {
     if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
       Availability = Availability->getEffectiveAttr();
       if (CheckAvailability(getASTContext(), Availability, nullptr,
-                            VersionTuple()) == AR_NotYetIntroduced)
+                            TI.getPlatformName(), TI.getPlatformMinVersion()) ==
+              AR_NotYetIntroduced ||
+          (TI.hasTargetVariantPlatform() &&
+           CheckAvailability(getASTContext(), Availability, nullptr,
+                             TI.getTargetVariantPlatform(),
+                             TI.getTargetVariantPlatformMinVersion()) ==
+               AR_NotYetIntroduced))
         return true;
     }
   }
diff --git a/clang/lib/Basic/Targets/ARM.cpp b/clang/lib/Basic/Targets/ARM.cpp
index 8d6e8d6990e80..0cd4b705bbcb9 100644
--- a/clang/lib/Basic/Targets/ARM.cpp
+++ b/clang/lib/Basic/Targets/ARM.cpp
@@ -1558,5 +1558,7 @@ DarwinARMTargetInfo::DarwinARMTargetInfo(const llvm::Triple &Triple,
 void DarwinARMTargetInfo::getOSDefines(const LangOptions &Opts,
                                        const llvm::Triple &Triple,
                                        MacroBuilder &Builder) const {
-  getDarwinDefines(Builder, Opts, Triple, PlatformName, PlatformMinVersion);
+  getDarwinDefines(Builder, Opts, Triple, /*TargetVariantTriple=*/"",
+                   PlatformName, PlatformMinVersion, TargetVariantPlatform,
+                   TargetVariantPlatformMinVersion);
 }
diff --git a/clang/lib/Basic/Targets/OSTargets.cpp b/clang/lib/Basic/Targets/OSTargets.cpp
index 04d9e13d3c9a6..91f98595dbbf5 100644
--- a/clang/lib/Basic/Targets/OSTargets.cpp
+++ b/clang/lib/Basic/Targets/OSTargets.cpp
@@ -55,8 +55,10 @@ void getAppleMachODefines(MacroBuilder &Builder, const LangOptions &Opts,
 }
 
 void getDarwinDefines(MacroBuilder &Builder, const LangOptions &Opts,
-                      const llvm::Triple &Triple, StringRef &PlatformName,
-                      VersionTuple &PlatformMinVersion) {
+                      const llvm::Triple &Triple, StringRef TargetVariantTriple,
+                      StringRef &PlatformName, VersionTuple &PlatformMinVersion,
+                      StringRef &TargetVariantPlatformName,
+                      VersionTuple &TargetVariantPlatformMinVersion) {
   getAppleMachODefines(Builder, Opts, Triple);
 
   // Darwin's libc doesn't have threads.h
@@ -67,6 +69,14 @@ void getDarwinDefines(MacroBuilder &Builder, const LangOptions &Opts,
   if (Triple.isMacOSX()) {
     Triple.getMacOSXVersion(OsVersion);
     PlatformName = "macos";
+    if (!TargetVariantTriple.empty()) {
+      llvm::Triple TVT(TargetVariantTriple);
+      if (TVT.getOS() == llvm::Triple::IOS &&
+          TVT.getEnvironment() == llvm::Triple::MacABI) {
+        TargetVariantPlatformName = "maccatalyst";
+        TargetVariantPlatformMinVersion = TVT.getiOSVersion();
+      }
+    }
   } else {
     OsVersion = Triple.getOSVersion();
     PlatformName = llvm::Triple::getOSTypeName(Triple.getOS());
diff --git a/clang/lib/Basic/Targets/OSTargets.h b/clang/lib/Basic/Targets/OSTargets.h
index fb5c17cefc004..724406f82b725 100644
--- a/clang/lib/Basic/Targets/OSTargets.h
+++ b/clang/lib/Basic/Targets/OSTargets.h
@@ -38,8 +38,10 @@ void getAppleMachODefines(MacroBuilder &Builder, const LangOptions &Opts,
                           const llvm::Triple &Triple);
 
 void getDarwinDefines(MacroBuilder &Builder, const LangOptions &Opts,
-                      const llvm::Triple &Triple, StringRef &PlatformName,
-                      VersionTuple &PlatformMinVersion);
+                      const llvm::Triple &Triple, StringRef TargetVariantTriple,
+                      StringRef &PlatformName, VersionTuple &PlatformMinVersion,
+                      StringRef &TargetVariantPlatformName,
+                      VersionTuple &TargetVariantPlatform);
 
 template <typename Target>
 class LLVM_LIBRARY_VISIBILITY AppleMachOTargetInfo
@@ -77,8 +79,10 @@ class LLVM_LIBRARY_VISIBILITY DarwinTargetInfo
 protected:
   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
                     MacroBuilder &Builder) const override {
-    getDarwinDefines(Builder, Opts, Triple, this->PlatformName,
-                     this->PlatformMinVersion);
+    getDarwinDefines(Builder, Opts, Triple, TargetVariantTriple,
+                     this->PlatformName, this->PlatformMinVersion,
+                     this->TargetVariantPlatform,
+                     this->TargetVariantPlatformMinVersion);
   }
 
 public:
@@ -87,6 +91,7 @@ class LLVM_LIBRARY_VISIBILITY DarwinTargetInfo
     // By default, no TLS, and we list permitted architecture/OS
     // combinations.
     this->TLSSupported = false;
+    TargetVariantTriple = Opts.DarwinTargetVariantTriple;
 
     if (Triple.isMacOSX())
       this->TLSSupported = !Triple.isMacOSXVersionLT(10, 7);
@@ -185,6 +190,14 @@ class LLVM_LIBRARY_VISIBILITY DarwinTargetInfo
   bool areDefaultedSMFStillPOD(const LangOptions &) const override {
     return false;
   }
+
+  /// Darwin does not support protected visibility.  Darwin's "default"
+  /// is very similar to ELF's "protected";  Darwin requires a "weak"
+  /// attribute on declarations that can be dynamically replaced.
+  bool hasProtectedVisibility() const override { return false; }
+
+private:
+  std::string TargetVariantTriple;
 };
 
 // DragonFlyBSD Target
diff --git a/clang/lib/CodeGen/CGExprScalar.cpp b/clang/lib/CodeGen/CGExprScalar.cpp
index 173931213ce68..5be65e13a34f9 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -635,13 +635,20 @@ class ScalarExprEmitter
 
   Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
     VersionTuple Version = E->getVersion();
+    VersionTuple VariantVersion = E->getVariantVersion();
 
     // If we're checking for a platform older than our minimum deployment
     // target, we can fold the check away.
-    if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
+    if ((Version.empty() && VariantVersion.empty()) ||
+        (!Version.empty() &&
+         Version <= CGF.CGM.getTarget().getPlatformMinVersion() &&
+         (!CGF.CGM.getTarget().hasTargetVariantPlatform() ||
+          (!VariantVersion.empty() &&
+           VariantVersion <=
+               CGF.CGM.getTarget().getTargetVariantPlatformMinVersion()))))
       return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
 
-    return CGF.EmitBuiltinAvailable(Version);
+    return CGF.EmitBuiltinAvailable(Version, VariantVersion);
   }
 
   Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
diff --git a/clang/lib/CodeGen/CGObjC.cpp b/clang/lib/CodeGen/CGObjC.cpp
index b9cbf593fb1c4..73b1cdba09514 100644
--- a/clang/lib/CodeGen/CGObjC.cpp
+++ b/clang/lib/CodeGen/CGObjC.cpp
@@ -4049,9 +4049,11 @@ static llvm::Value *emitIsPlatformVersionAtLeast(CodeGenFunction &CGF,
 }
 
 llvm::Value *
-CodeGenFunction::EmitBuiltinAvailable(const VersionTuple &Version) {
+CodeGenFunction::EmitBuiltinAvailable(const VersionTuple &Version,
+                                      const VersionTuple &VariantVersion) {
   // Darwin uses the new __isPlatformVersionAtLeast family of routines.
-  if (CGM.getTarget().getTriple().isOSDarwin())
+  if (CGM.getTarget().getTriple().isOSDarwin() &&
+      !CGM.getTarget().hasTargetVariantPlatform())
     return emitIsPlatformVersionAtLeast(*this, Version);
 
   if (!CGM.IsOSVersionAtLeastFn) {
@@ -4059,19 +4061,50 @@ CodeGenFunction::EmitBuiltinAvailable(const VersionTuple &Version) {
         llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
     CGM.IsOSVersionAtLeastFn =
         CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
+    llvm::FunctionType *FTy2 = llvm::FunctionType::get(Int32Ty, {}, false);
+    CGM.IsTargetPlatformNativeFn =
+        CGM.CreateRuntimeFunction(FTy2, "__isTargetPlatformNative");
+    CGM.IsTargetVariantOSVersionAtLeastFn =
+        CGM.CreateRuntimeFunction(FTy, "__isTargetVariantOSVersionAtLeast");
   }
 
-  std::optional<unsigned> Min = Version.getMinor(),
-                          SMin = Version.getSubminor();
-  llvm::Value *Args[] = {
-      llvm::ConstantInt::get(CGM.Int32Ty, Version.getMajor()),
-      llvm::ConstantInt::get(CGM.Int32Ty, Min.value_or(0)),
-      llvm::ConstantInt::get(CGM.Int32Ty, SMin.value_or(0))};
+  auto EmitVersionArgs = [&](const VersionTuple &V,
+                             llvm::SmallVectorImpl<llvm::Value *> &Args) {
+    if (V.empty())
+      return;
+    std::optional<unsigned> Min = V.getMinor(), SMin = V.getSubminor();
+    Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, V.getMajor()));
+    Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, Min.value_or(0)));
+    Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, SMin.value_or(0)));
+  };
 
-  llvm::Value *CallRes =
-      EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
+  llvm::SmallVector<llvm::Value *, 3> Args;
+  llvm::SmallVector<llvm::Value *, 3> VariantArgs;
+  EmitVersionArgs(Version, Args);
+  EmitVersionArgs(VariantVersion, VariantArgs);
+
+  llvm::Value *Check = nullptr;
+  if (!Args.empty()) {
+    Check = EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
+  }
+  llvm::Value *VariantCheck = nullptr;
+  if (!VariantArgs.empty()) {
+    VariantCheck = EmitNounwindRuntimeCall(
+        CGM.IsTargetVariantOSVersionAtLeastFn, VariantArgs);
+  }
+  llvm::Value *IsNativeCheck = nullptr;
+  if (CGM.getTarget().hasTargetVariantPlatform()) {
+    IsNativeCheck = EmitNounwindRuntimeCall(CGM.IsTargetPlatformNativeFn);
+    IsNativeCheck = Builder.CreateICmpNE(IsNativeCheck,
+                                         llvm::Constant::getNullValue(Int32Ty));
+    if (!Check)
+      Check = llvm::Constant::getNullValue(Int32Ty);
+    if (!VariantCheck)
+      VariantCheck = llvm::Constant::getNullValue(Int32Ty);
+    Check = Builder.CreateSelect(IsNativeCheck, Check, VariantCheck);
+  }
 
-  return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
+  return Builder.CreateICmpNE(Check, llvm::Constant::getNullValue(Int32Ty));
 }
 
 static bool isFoundationNeededForDarwinAvailabilityCheck(
diff --git a/clang/lib/CodeGen/CodeGenFunction.h b/clang/lib/CodeGen/CodeGenFunction.h
index 7bdc79d86ea0a..3bf62755ac270 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -5028,7 +5028,8 @@ class CodeGenFunction : public CodeGenTypeCache {
   enum class MSVCIntrin;
   llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
 
-  llvm::Value *EmitBuiltinAvailable(const VersionTuple &Version);
+  llvm::Value *EmitBuiltinAvailable(const VersionTuple &Version,
+                                    const VersionTuple &VariantVersion);
 
   llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
   llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
diff --git a/clang/lib/CodeGen/CodeGenModule.h b/clang/lib/CodeGen/CodeGenModule.h
index 1f5ecf734c528..ffca028f65709 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -832,6 +832,8 @@ class CodeGenModule : public CodeGenTypeCache {
   llvm::FunctionCallee IsOSVersionAtLeastFn = nullptr;
   // i32 @__isPlatformVersionAtLeast(i32, i32, i32, i32)
   llvm::FunctionCallee IsPlatformVersionAtLeastFn = nullptr;
+  llvm::FunctionCallee IsTargetPlatformNativeFn = nullptr;
+  llvm::FunctionCallee IsTargetVariantOSVersionAtLeastFn = nullptr;
 
   InstrProfStats &getPGOStats() { return PGOStats; }
   llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
diff --git a/clang/lib/Edit/RewriteObjCFoundationAPI.cpp b/clang/lib/Edit/RewriteObjCFoundationAPI.cpp
index e8d4660fd36b2..fb3d1fef764b0 100644
--- a/clang/lib/Edit/RewriteObjCFoundationAPI.cpp
+++ b/clang/lib/Edit/RewriteObjCFoundationAPI.cpp
@@ -163,7 +163,7 @@ static bool canRewriteToSubscriptSyntax(const ObjCInterfaceDecl *&IFace,
   IFace = maybeAdjustInterfaceForSubscriptingCheck(IFace, Rec, Ctx);
 
   if (const ObjCMethodDecl *MD = IFace->lookupInstanceMethod(subscriptSel)) {
-    if (!MD->isUnavailable())
+    if (!MD->isUnavailabledForAllTargetPlatforms())
       return true;
   }
   return false;
diff --git a/clang/lib/Sema/CodeCompleteConsumer.cpp b/clang/lib/Sema/CodeCompleteConsumer.cpp
index 50a552272f421..750a0f00ecff9 100644
--- a/clang/lib/Sema/CodeCompleteConsumer.cpp
+++ b/clang/lib/Sema/CodeCompleteConsumer.cpp
@@ -19,6 +19,7 @@
 #include "clang/AST/DeclarationName.h"
 #include "clang/AST/Type.h"
 #include "clang/Basic/IdentifierTable.h"
+#include "clang/Basic/TargetInfo.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Sema/Sema.h"
 #include "llvm/ADT/StringExtras.h"
@@ -765,9 +766,16 @@ void PrintingCodeCompleteConsumer::ProcessOverloadCandidates(
 
 /// Retrieve the effective availability of the given declaration.
 static AvailabilityResult getDeclAvailability(const Decl *D) {
-  AvailabilityResult AR = D->getAvailability();
+  // FIXME: Take min of target and target-variant AR for better Xcode
+  // experience?
+  const TargetInfo &TI =
+      D->getTranslationUnitDecl()->getASTContext().getTargetInfo();
+  AvailabilityResult AR =
+      D->getAvailability(TI.getPlatformName(), TI.getPlatformMinVersion());
   if (isa<EnumConstantDecl>(D))
-    AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
+    AR = std::max(AR, cast<Decl>(D->getDeclContext())
+                          ->getAvailability(TI.getPlatformName(),
+                                            TI.getPlatformMinVersion()));
   return AR;
 }
 
diff --git a/clang/lib/Sema/DelayedDiagnostic.cpp b/clang/lib/Sema/DelayedDiagnostic.cpp
index cb2721b92090e..e825abaa5bc71 100644
--- a/clang/lib/Sema/DelayedDiagnostic.cpp
+++ b/clang/lib/Sema/DelayedDiagnostic.cpp
@@ -20,15 +20,12 @@
 using namespace clang;
 using namespace sema;
 
-DelayedDiagnostic
-DelayedDiagnostic::makeAvailability(AvailabilityResult AR,
-                                    ArrayRef<SourceLocation> Locs,
-                                    const NamedDecl *ReferringDecl,
-                                    const NamedDecl *OffendingDecl,
-                                    const ObjCInterfaceDecl *UnknownObjCClass,
-                                    const ObjCPropertyDecl  *ObjCProperty,
-                                    StringRef Msg,
-                                    bool ObjCPropertyAccess) {
+DelayedDiagnostic DelayedDiagnostic::makeAvailability(
+    AvailabilityResult AR, ArrayRef<SourceLocation> Locs,
+    const NamedDecl *ReferringDecl, const NamedDecl *OffendingDecl,
+    const ObjCInterfaceDecl *UnknownObjCClass,
+    const ObjCPropertyDecl *ObjCProperty, StringRef Msg,
+    bool ObjCPropertyAccess, bool IsTargetVariantPlatform) {
   assert(!Locs.empty());
   DelayedDiagnostic DD;
   DD.Kind = Availability;
@@ -53,6 +50,7 @@ DelayedDiagnostic::makeAvailability(AvailabilityResult AR,
 
   DD.AvailabilityData.AR = AR;
   DD.AvailabilityData.ObjCPropertyAccess = ObjCPropertyAccess;
+  DD.AvailabilityData.IsTargetVariantPlatform = IsTargetVariantPlatform;
   return DD;
 }
 
diff --git a/clang/lib/Sema/SemaAvailability.cpp b/clang/lib/Sema/SemaAvailability.cpp
index 28a4b760dbd4d..2c736015c20ca 100644
--- a/clang/lib/Sema/SemaAvailability.cpp
+++ b/clang/lib/Sema/SemaAvailability.cpp
@@ -44,6 +44,7 @@ static bool hasMatchingEnvironmentOrNone(const ASTContext &Context,
 }
 
 static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
+                                                  StringRef TargetPlatform,
                                                   const Decl *D) {
   AvailabilityAttr const *PartialMatch = nullptr;
   // Check each AvailabilityAttr to find the one for this platform.
@@ -73,8 +74,6 @@ static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
           RealizedPlatform = RealizedPlatform.slice(0, suffix);
       }
 
-      StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
-
       // Match the platform name.
       if (RealizedPlatform == TargetPlatform) {
         // Find the best matching attribute for this environment
@@ -96,9 +95,12 @@ static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
 /// \param ClassReceiver If we're checking the method of a class message
 /// send, the class. Otherwise nullptr.
 std::pair<AvailabilityResult, const NamedDecl *>
-Sema::ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
+Sema::ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, StringRef Platform,
+                                       const VersionTuple &PlatformVersion,
+                                       std::string *Message,
                                        ObjCInterfaceDecl *ClassReceiver) {
-  AvailabilityResult Result = D->getAvailability(Message);
+  AvailabilityResult Result =
+      D->getAvailability(Platform, PlatformVersion, Message);
 
   // For typedefs, if the typedef declaration appears available look
   // to the underlying type to see if it is more restrictive.
@@ -121,7 +123,9 @@ Sema::ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
         T = NextT;
         continue;
       }
-      Result = D->getAvailability(Message);
+      /* TO_UPSTREAM(iosmac) ON*/
+      Result = D->getAvailability(Platform, PlatformVersion, Message);
+      /* TO_UPSTREAM(iosmac) OFF*/
       break;
     }
   }
@@ -130,7 +134,7 @@ Sema::ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
   if (const auto *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
     if (IDecl->getDefinition()) {
       D = IDecl->getDefinition();
-      Result = D->getAvailability(Message);
+      Result = D->getAvailability(Platform, PlatformVersion, Message);
     }
   }
 
@@ -138,7 +142,8 @@ Sema::ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
     if (Result == AR_Available) {
       const DeclContext *DC = ECD->getDeclContext();
       if (const auto *TheEnumDecl = dyn_cast<EnumDecl>(DC)) {
-        Result = TheEnumDecl->getAvailability(Message);
+        Result =
+            TheEnumDecl->getAvailability(Platform, PlatformVersion, Message);
         D = TheEnumDecl;
       }
     }
@@ -151,7 +156,7 @@ Sema::ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
       if (Init && Result == AR_Available && MD->isClassMethod() &&
           MD->getSelector() == ObjC().NSAPIObj->getNewSelector() &&
           MD->definedInNSObject(getASTContext())) {
-        Result = Init->getAvailability(Message);
+        Result = Init->getAvailability(Platform, PlatformVersion, Message);
         D = Init;
       }
     }
@@ -165,7 +170,8 @@ Sema::ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
 /// in a deprecated context, but not the other way around.
 static bool ShouldDiagnoseAvailabilityInContext(
     Sema &S, AvailabilityResult K, VersionTuple DeclVersion,
-    const IdentifierInfo *DeclEnv, Decl *Ctx, const NamedDecl *OffendingDecl) {
+    const IdentifierInfo *DeclEnv, Decl *Ctx, const NamedDecl *OffendingDecl,
+    StringRef TargetPlatform, const VersionTuple &TargetPlatformMinVersion) {
   assert(K != AR_Available && "Expected an unavailable declaration here!");
 
   // If this was defined using CF_OPTIONS, etc. then ignore the diagnostic.
@@ -198,19 +204,21 @@ static bool ShouldDiagnoseAvailabilityInContext(
 
   if (K == AR_Deprecated) {
     if (const auto *VD = dyn_cast<VarDecl>(OffendingDecl))
-      if (VD->isLocalVarDeclOrParm() && VD->isDeprecated())
+      if (VD->isLocalVarDeclOrParm() && VD->isDeprecatedInAnyTargetPlatform())
         return true;
   }
 
   // Checks if we should emit the availability diagnostic in the context of C.
   auto CheckContext = [&](const Decl *C) {
     if (K == AR_NotYetIntroduced) {
-      if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C))
+      if (const AvailabilityAttr *AA =
+              getAttrForPlatform(S.Context, TargetPlatform, C))
         if (AA->getEffectiveIntroduced() >= DeclVersion &&
             AA->getEffectiveEnvironment() == DeclEnv)
           return true;
     } else if (K == AR_Deprecated) {
-      if (C->isDeprecated())
+      if (C->getAvailability(TargetPlatform, TargetPlatformMinVersion) ==
+          AR_Deprecated)
         return true;
     } else if (K == AR_Unavailable) {
       // It is perfectly fine to refer to an 'unavailable' Objective-C method
@@ -224,7 +232,8 @@ static bool ShouldDiagnoseAvailabilityInContext(
       }
     }
 
-    if (C->isUnavailable())
+    if (C->getAvailability(TargetPlatform, TargetPlatformMinVersion) ==
+        AR_Unavailable)
       return true;
     return false;
   };
@@ -257,8 +266,12 @@ static bool ShouldDiagnoseAvailabilityInContext(
 
 static unsigned getAvailabilityDiagnosticKind(
     const ASTContext &Context, const VersionTuple &DeploymentVersion,
-    const VersionTuple &DeclVersion, bool HasMatchingEnv) {
-  const auto &Triple = Context.getTargetInfo().getTriple();
+    const VersionTuple &DeclVersion, bool HasMatchingEnv,
+    bool IsTargetVariantCheck = false) {
+  const auto &Triple =
+      IsTargetVariantCheck
+          ? *Context.getTargetInfo().getDarwinTargetVariantTriple()
+          : Context.getTargetInfo().getTriple();
   VersionTuple ForceAvailabilityFromVersion;
   switch (Triple.getOS()) {
   // For iOS, emit the diagnostic even if -Wunguarded-availability is
@@ -395,129 +408,198 @@ createAttributeInsertion(const NamedDecl *D, const SourceManager &SM,
   return AttributeInsertion::createInsertionBefore(D);
 }
 
-/// Actually emit an availability diagnostic for a reference to an unavailable
-/// decl.
-///
-/// \param Ctx The context that the reference occurred in
-/// \param ReferringDecl The exact declaration that was referenced.
-/// \param OffendingDecl A related decl to \c ReferringDecl that has an
-/// availability attribute corresponding to \c K attached to it. Note that this
-/// may not be the same as ReferringDecl, i.e. if an EnumDecl is annotated and
-/// we refer to a member EnumConstantDecl, ReferringDecl is the EnumConstantDecl
-/// and OffendingDecl is the EnumDecl.
-static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
-                                      Decl *Ctx, const NamedDecl *ReferringDecl,
-                                      const NamedDecl *OffendingDecl,
-                                      StringRef Message,
-                                      ArrayRef<SourceLocation> Locs,
-                                      const ObjCInterfaceDecl *UnknownObjCClass,
-                                      const ObjCPropertyDecl *ObjCProperty,
-                                      bool ObjCPropertyAccess) {
-  // Diagnostics for deprecated or unavailable.
-  unsigned diag, diag_message, diag_fwdclass_message;
-  unsigned diag_available_here = diag::note_availability_specified_here;
-  SourceLocation NoteLocation = OffendingDecl->getLocation();
+/// Target-independent information about an availability diagnostic.
+struct PlatformAgnosticAvailabilityDiagInfo {
+  const NamedDecl *ReferringDecl;
+  ArrayRef<SourceLocation> Locs;
+  const ObjCInterfaceDecl *UnknownObjCClass;
+  bool ObjCPropertyAccess;
+
+  PlatformAgnosticAvailabilityDiagInfo(
+      const NamedDecl *ReferringDecl, ArrayRef<SourceLocation> Locs,
+      const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess)
+      : ReferringDecl(ReferringDecl), Locs(Locs),
+        UnknownObjCClass(UnknownObjCClass),
+        ObjCPropertyAccess(ObjCPropertyAccess) {}
+};
 
-  // Matches 'diag::note_property_attribute' options.
-  unsigned property_note_select;
+// Target-specific information about an availability diagnostic.
+struct PlatformSpecificAvailabilityDiag {
+  AvailabilityResult AR;
+  const NamedDecl *OffendingDecl;
+  std::string Message;
+  const ObjCPropertyDecl *ObjCProperty;
+  bool IsTargetVariantPlatform;
+
+  PlatformSpecificAvailabilityDiag(AvailabilityResult AR,
+                                   const NamedDecl *OffendingDecl,
+                                   std::string Message,
+                                   const ObjCPropertyDecl *ObjCProperty,
+                                   bool IsTargetVariantPlatform)
+      : AR(AR), OffendingDecl(OffendingDecl), Message(std::move(Message)),
+        ObjCProperty(ObjCProperty),
+        IsTargetVariantPlatform(IsTargetVariantPlatform) {}
+
+  PlatformSpecificAvailabilityDiag(AvailabilityResult AR,
+                                   const NamedDecl *OffendingDecl,
+                                   bool IsTargetVariantPlatform)
+      : AR(AR), OffendingDecl(OffendingDecl), ObjCProperty(nullptr),
+        IsTargetVariantPlatform(IsTargetVariantPlatform) {}
+
+  /// Returns the location of the note which points to the availability
+  /// attribute.
+  SourceLocation getNoteLocation(Sema &S) const {
+    const TargetInfo &TI = S.getASTContext().getTargetInfo();
+    StringRef Platform = IsTargetVariantPlatform ? TI.getTargetVariantPlatform()
+                                                 : TI.getPlatformName();
+    // The declaration can have multiple availability attributes, we are looking
+    // at one of them.
+    const AvailabilityAttr *A =
+        getAttrForPlatform(S.Context, Platform, OffendingDecl);
+    if (A && A->isInherited()) {
+      for (const Decl *Redecl = OffendingDecl->getMostRecentDecl(); Redecl;
+           Redecl = Redecl->getPreviousDecl()) {
+        const AvailabilityAttr *AForRedecl =
+            getAttrForPlatform(S.Context, Platform, Redecl);
+        if (AForRedecl && !AForRedecl->isInherited()) {
+          // If D is a declaration with inherited attributes, the note should
+          // point to the declaration with actual attributes.
+          return Redecl->getLocation();
+        }
+      }
+    }
+    return OffendingDecl->getLocation();
+  }
+};
 
-  // Matches diag::note_availability_specified_here.
-  unsigned available_here_select_kind;
+// Check if we have to emit an availability diagnostic for a particular target.
+static bool ShouldEmitAvailabilityWarning(
+    Sema &S, Decl *Ctx, const PlatformAgnosticAvailabilityDiagInfo &Info,
+    const PlatformSpecificAvailabilityDiag &PlatformInfo) {
+  const TargetInfo &TI = S.getASTContext().getTargetInfo();
+  StringRef Platform = PlatformInfo.IsTargetVariantPlatform
+                           ? TI.getTargetVariantPlatform()
+                           : TI.getPlatformName();
+  VersionTuple PlatformMinVersion =
+      PlatformInfo.IsTargetVariantPlatform
+          ? TI.getTargetVariantPlatformMinVersion()
+          : TI.getPlatformMinVersion();
 
   VersionTuple DeclVersion;
-  const AvailabilityAttr *AA = getAttrForPlatform(S.Context, OffendingDecl);
   const IdentifierInfo *IIEnv = nullptr;
-  if (AA) {
+  if (const AvailabilityAttr *AA =
+          getAttrForPlatform(S.Context, Platform, PlatformInfo.OffendingDecl)) {
     DeclVersion = AA->getEffectiveIntroduced();
     IIEnv = AA->getEffectiveEnvironment();
   }
 
-  if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, IIEnv, Ctx,
-                                           OffendingDecl))
-    return;
-
-  SourceLocation Loc = Locs.front();
-
-  // The declaration can have multiple availability attributes, we are looking
-  // at one of them.
-  if (AA && AA->isInherited()) {
-    for (const Decl *Redecl = OffendingDecl->getMostRecentDecl(); Redecl;
-         Redecl = Redecl->getPreviousDecl()) {
-      const AvailabilityAttr *AForRedecl =
-          getAttrForPlatform(S.Context, Redecl);
-      if (AForRedecl && !AForRedecl->isInherited()) {
-        // If D is a declaration with inherited attributes, the note should
-        // point to the declaration with actual attributes.
-        NoteLocation = Redecl->getLocation();
-        break;
-      }
-    }
-  }
+  return ShouldDiagnoseAvailabilityInContext(
+      S, PlatformInfo.AR, DeclVersion, IIEnv, Ctx, PlatformInfo.OffendingDecl,
+      Platform, PlatformMinVersion);
+}
 
-  switch (K) {
-  case AR_NotYetIntroduced: {
+/// Emits an availability diagnostic for a not yet introduced declaration.
+static void EmitNotIntroducedAvailabilityWarning(
+    Sema &S, Decl *Ctx, const PlatformAgnosticAvailabilityDiagInfo &Info,
+    const PlatformSpecificAvailabilityDiag &PlatformInfo,
+    const PlatformSpecificAvailabilityDiag *VariantPlatformInfo = nullptr) {
+  assert(PlatformInfo.AR == AR_NotYetIntroduced && "unexpected AR");
+  const TargetInfo &TI = S.Context.getTargetInfo();
+  StringRef TargetPlatform = PlatformInfo.IsTargetVariantPlatform
+                                 ? TI.getTargetVariantPlatform()
+                                 : TI.getPlatformName();
+  const AvailabilityAttr *AA = getAttrForPlatform(
+      S.getASTContext(), TargetPlatform, PlatformInfo.OffendingDecl);
+  assert(AA != nullptr && "expecting valid availability attribute");
+  VersionTuple Introduced = AA->getEffectiveIntroduced();
+  bool EnvironmentMatchesOrNone =
+      hasMatchingEnvironmentOrNone(S.getASTContext(), AA->getEffectiveAttr());
+
+  std::string PlatformName(
+      AvailabilityAttr::getPrettyPlatformName(TargetPlatform));
+  llvm::StringRef TargetEnvironment(
+      llvm::Triple::getEnvironmentTypeName(TI.getTriple().getEnvironment()));
+  llvm::StringRef AttrEnvironment =
+      AA->getEnvironment() ? AA->getEnvironment()->getName() : "";
+  bool UseEnvironment =
+      (!AttrEnvironment.empty() && !TargetEnvironment.empty());
+  unsigned DiagKind;
+  if (VariantPlatformInfo) {
+    DiagKind = diag::warn_zippered_unguarded_availability;
+  } else {
     // We would like to emit the diagnostic even if -Wunguarded-availability is
     // not specified for deployment targets >= to iOS 11 or equivalent or
     // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
     // later.
-    assert(AA != nullptr && "expecting valid availability attribute");
-    VersionTuple Introduced = AA->getEffectiveIntroduced();
-    bool EnvironmentMatchesOrNone =
-        hasMatchingEnvironmentOrNone(S.getASTContext(), AA->getEffectiveAttr());
-
-    const TargetInfo &TI = S.getASTContext().getTargetInfo();
-    std::string PlatformName(
-        AvailabilityAttr::getPrettyPlatformName(TI.getPlatformName()));
-    llvm::StringRef TargetEnvironment(
-        llvm::Triple::getEnvironmentTypeName(TI.getTriple().getEnvironment()));
-    llvm::StringRef AttrEnvironment =
-        AA->getEnvironment() ? AA->getEnvironment()->getName() : "";
-    bool UseEnvironment =
-        (!AttrEnvironment.empty() && !TargetEnvironment.empty());
-
-    unsigned DiagKind = getAvailabilityDiagnosticKind(
+    // FIXME: Should we look at the target-variant platform here too
+    // potentially?
+    DiagKind = getAvailabilityDiagnosticKind(
         S.Context, S.Context.getTargetInfo().getPlatformMinVersion(),
         Introduced, EnvironmentMatchesOrNone);
+  }
 
-    S.Diag(Loc, DiagKind) << OffendingDecl << PlatformName
-                          << Introduced.getAsString() << UseEnvironment
-                          << TargetEnvironment;
+  VersionTuple VariantIntroduced;
+  if (VariantPlatformInfo)
+    VariantIntroduced =
+        getAttrForPlatform(S.getASTContext(), TI.getTargetVariantPlatform(),
+                           VariantPlatformInfo->OffendingDecl)
+            ->getIntroduced();
+  {
+    auto Diag = S.Diag(Info.Locs[0], DiagKind);
+    Diag << Info.ReferringDecl << PlatformName << Introduced.getAsString();
+    if (!VariantPlatformInfo)
+      Diag << UseEnvironment << TargetEnvironment;
+    else
+      Diag << AvailabilityAttr::getPrettyPlatformName(
+                  TI.getTargetVariantPlatform())
+           << VariantIntroduced.getAsString();
+  }
 
-    S.Diag(OffendingDecl->getLocation(),
+  S.Diag(PlatformInfo.OffendingDecl->getLocation(),
+         diag::note_partial_availability_specified_here)
+      << PlatformInfo.OffendingDecl << PlatformName << Introduced.getAsString()
+      << (PlatformInfo.IsTargetVariantPlatform
+              ? TI.getTargetVariantPlatformMinVersion()
+              : TI.getPlatformMinVersion())
+             .getAsString()
+      << UseEnvironment << AttrEnvironment << TargetEnvironment;
+  if (VariantPlatformInfo &&
+      VariantPlatformInfo->OffendingDecl != PlatformInfo.OffendingDecl)
+    S.Diag(VariantPlatformInfo->OffendingDecl->getLocation(),
            diag::note_partial_availability_specified_here)
-        << OffendingDecl << PlatformName << Introduced.getAsString()
-        << S.Context.getTargetInfo().getPlatformMinVersion().getAsString()
-        << UseEnvironment << AttrEnvironment << TargetEnvironment;
-
-    // Do not offer to silence the warning or fixits for HLSL
-    if (S.getLangOpts().HLSL)
-      return;
+        << VariantPlatformInfo->OffendingDecl
+        << AvailabilityAttr::getPrettyPlatformName(
+               TI.getTargetVariantPlatform())
+        << VariantIntroduced.getAsString()
+        << TI.getTargetVariantPlatformMinVersion().getAsString();
+
+  // Do not offer to silence the warning or fixits for HLSL
+  if (S.getLangOpts().HLSL)
+    return;
 
-    if (const auto *Enclosing = findEnclosingDeclToAnnotate(Ctx)) {
-      if (const auto *TD = dyn_cast<TagDecl>(Enclosing))
-        if (TD->getDeclName().isEmpty()) {
-          S.Diag(TD->getLocation(),
-                 diag::note_decl_unguarded_availability_silence)
-              << /*Anonymous*/ 1 << TD->getKindName();
-          return;
-        }
-      auto FixitNoteDiag =
-          S.Diag(Enclosing->getLocation(),
-                 diag::note_decl_unguarded_availability_silence)
-          << /*Named*/ 0 << Enclosing;
-      // Don't offer a fixit for declarations with availability attributes.
-      if (Enclosing->hasAttr<AvailabilityAttr>())
-        return;
-      Preprocessor &PP = S.getPreprocessor();
-      if (!PP.isMacroDefined("API_AVAILABLE"))
+  if (const auto *Enclosing = findEnclosingDeclToAnnotate(Ctx)) {
+    if (const auto *TD = dyn_cast<TagDecl>(Enclosing))
+      if (TD->getDeclName().isEmpty()) {
+        S.Diag(TD->getLocation(),
+               diag::note_decl_unguarded_availability_silence)
+            << /*Anonymous*/ 1 << TD->getKindName();
         return;
-      std::optional<AttributeInsertion> Insertion = createAttributeInsertion(
-          Enclosing, S.getSourceManager(), S.getLangOpts());
-      if (!Insertion)
-        return;
-      StringRef PlatformName =
-          S.getASTContext().getTargetInfo().getPlatformName();
+      }
+    auto FixitNoteDiag = S.Diag(Enclosing->getLocation(),
+                                diag::note_decl_unguarded_availability_silence)
+                         << /*Named*/ 0 << Enclosing;
+    // Don't offer a fixit for declarations with availability attributes.
+    if (Enclosing->hasAttr<AvailabilityAttr>())
+      return;
+    Preprocessor &PP = S.getPreprocessor();
+    if (!PP.isMacroDefined("API_AVAILABLE"))
+      return;
+    std::optional<AttributeInsertion> Insertion = createAttributeInsertion(
+        Enclosing, S.getSourceManager(), S.getLangOpts());
+    if (!Insertion)
+      return;
 
+    auto GetAvailablePlatform = [&](StringRef PlatformName) -> StringRef {
       // Apple's API_AVAILABLE macro expands roughly like this.
       // API_AVAILABLE(ios(17.0))
       // __attribute__((availability(__API_AVAILABLE_PLATFORM_ios(17.0)))
@@ -536,60 +618,120 @@ static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
             return PP.isMacroDefined((MacroPrefix + EquivalentPlatform).str());
           });
       if (AvailablePlatform == EquivalentPlatforms.end())
-        return;
-      std::string Introduced =
-          OffendingDecl->getVersionIntroduced().getAsString();
-      FixitNoteDiag << FixItHint::CreateInsertion(
-          Insertion->Loc,
-          (llvm::Twine(Insertion->Prefix) + "API_AVAILABLE(" +
-           *AvailablePlatform + "(" + Introduced + "))" + Insertion->Suffix)
-              .str());
+        return {};
+      return *AvailablePlatform;
+    };
+
+    StringRef PlatformName = GetAvailablePlatform(TargetPlatform);
+    if (PlatformName.empty())
+      return;
+
+    std::string FixItText;
+    llvm::raw_string_ostream OS(FixItText);
+    OS << Insertion->Prefix << "API_AVAILABLE(" << PlatformName << '('
+       << Introduced.getAsString() << ')';
+    if (VariantPlatformInfo) {
+      StringRef VariantPlatformName =
+          GetAvailablePlatform(TI.getTargetVariantPlatform());
+      if (!VariantPlatformName.empty())
+        OS << ", " << VariantPlatformName << '('
+           << VariantIntroduced.getAsString() << ')';
     }
-    return;
+    OS << ')' << Insertion->Suffix;
+    FixitNoteDiag << FixItHint::CreateInsertion(Insertion->Loc, OS.str());
   }
-  case AR_Deprecated:
-    // Suppress -Wdeprecated-declarations in implicit
-    // functions.
-    if (const auto *FD = dyn_cast_or_null<FunctionDecl>(S.getCurFunctionDecl());
-        FD && FD->isImplicit())
-      return;
+}
 
-    if (ObjCPropertyAccess)
-      diag = diag::warn_property_method_deprecated;
-    else if (S.currentEvaluationContext().IsCaseExpr)
-      diag = diag::warn_deprecated_switch_case;
-    else
-      diag = diag::warn_deprecated;
-
-    diag_message = diag::warn_deprecated_message;
-    diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
-    property_note_select = /* deprecated */ 0;
-    available_here_select_kind = /* deprecated */ 2;
-    if (const auto *AL = OffendingDecl->getAttr<DeprecatedAttr>())
-      NoteLocation = AL->getLocation();
-    break;
+static void EmitZipperedNotIntroducedAvailabilityWarning(
+    Sema &S, Decl *Ctx, const PlatformAgnosticAvailabilityDiagInfo &Info,
+    const PlatformSpecificAvailabilityDiag &PlatformInfo,
+    const PlatformSpecificAvailabilityDiag &VariantPlatformInfo) {
+  EmitNotIntroducedAvailabilityWarning(S, Ctx, Info, PlatformInfo,
+                                       &VariantPlatformInfo);
+}
+
+// Information about the diagnostic for a 'deprecated' or 'unavailable'.
+struct UnavailableDeprecatedAvailabilityDiag {
+  // Diagnostics for deprecated or unavailable.
+  unsigned diag, diag_message, diag_fwdclass_message;
+  unsigned diag_available_here = diag::note_availability_specified_here;
+
+  // Matches 'diag::note_property_attribute' options.
+  unsigned property_note_select;
+
+  // Matches diag::note_availability_specified_here.
+  unsigned available_here_select_kind;
+
+  // An optional note location for the note.
+  SourceLocation NoteLocation;
 
-  case AR_Unavailable:
-    diag = !ObjCPropertyAccess ? diag::err_unavailable
-                               : diag::err_property_method_unavailable;
+  CharSourceRange UseRange;
+  StringRef Replacement;
+
+  UnavailableDeprecatedAvailabilityDiag(
+      Sema &S, const PlatformAgnosticAvailabilityDiagInfo &Info,
+      const PlatformSpecificAvailabilityDiag &PlatformInfo) {
+    const TargetInfo &TI = S.getASTContext().getTargetInfo();
+    StringRef TargetPlatform = PlatformInfo.IsTargetVariantPlatform
+                                   ? TI.getTargetVariantPlatform()
+                                   : TI.getPlatformName();
+    Replacement = "";
+    UseRange = CharSourceRange();
+    if (PlatformInfo.AR == AR_Deprecated) {
+      if (auto AL = PlatformInfo.OffendingDecl->getAttr<DeprecatedAttr>())
+        Replacement = AL->getReplacement();
+      if (auto AL = getAttrForPlatform(S.Context, TargetPlatform,
+                                       PlatformInfo.OffendingDecl))
+        Replacement = AL->getReplacement();
+
+      if (!Replacement.empty())
+        UseRange = CharSourceRange::getCharRange(
+            Info.Locs[0], S.getLocForEndOfToken(Info.Locs[0]));
+    }
+
+    if (PlatformInfo.AR == AR_Deprecated) {
+      if (Info.ObjCPropertyAccess)
+        diag = diag::warn_property_method_deprecated;
+      else if (S.currentEvaluationContext().IsCaseExpr)
+        diag = diag::warn_deprecated_switch_case;
+      else
+        diag = diag::warn_deprecated;
+
+      diag_message = diag::warn_deprecated_message;
+      diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
+      property_note_select = /* deprecated */ 0;
+      available_here_select_kind = /* deprecated */ 2;
+      if (const auto *AL =
+              PlatformInfo.OffendingDecl->getAttr<DeprecatedAttr>())
+        NoteLocation = AL->getLocation();
+      else
+        NoteLocation = PlatformInfo.getNoteLocation(S);
+      return;
+    }
+    assert(PlatformInfo.AR == AR_Unavailable && "unexpected AR");
+
+    diag = !Info.ObjCPropertyAccess ? diag::err_unavailable
+                                    : diag::err_property_method_unavailable;
     diag_message = diag::err_unavailable_message;
     diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
     property_note_select = /* unavailable */ 1;
     available_here_select_kind = /* unavailable */ 0;
+    NoteLocation = PlatformInfo.getNoteLocation(S);
 
-    if (auto AL = OffendingDecl->getAttr<UnavailableAttr>()) {
+    if (auto AL = PlatformInfo.OffendingDecl->getAttr<UnavailableAttr>()) {
       if (AL->isImplicit() && AL->getImplicitReason()) {
         // Most of these failures are due to extra restrictions in ARC;
         // reflect that in the primary diagnostic when applicable.
         auto flagARCError = [&] {
           if (S.getLangOpts().ObjCAutoRefCount &&
               S.getSourceManager().isInSystemHeader(
-                  OffendingDecl->getLocation()))
+                  PlatformInfo.OffendingDecl->getLocation()))
             diag = diag::err_unavailable_in_arc;
         };
 
         switch (AL->getImplicitReason()) {
-        case UnavailableAttr::IR_None: break;
+        case UnavailableAttr::IR_None:
+          break;
 
         case UnavailableAttr::IR_ARCForbiddenType:
           flagARCError();
@@ -620,55 +762,60 @@ static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
         }
       }
     }
-    break;
+  }
 
-  case AR_Available:
-    llvm_unreachable("Warning for availability of available declaration?");
+  bool operator==(const UnavailableDeprecatedAvailabilityDiag &Other) {
+    return diag == Other.diag && diag_message == Other.diag_message &&
+           diag_fwdclass_message == Other.diag_fwdclass_message &&
+           diag_available_here == Other.diag_available_here;
   }
+};
+
+static void EmitUnavailableDeprecatedAvailabilityWarning(
+    Sema &S, StringRef Message,
+    const UnavailableDeprecatedAvailabilityDiag &Diag,
+    const PlatformAgnosticAvailabilityDiagInfo &Info,
+    const PlatformSpecificAvailabilityDiag &PlatformInfo,
+    const UnavailableDeprecatedAvailabilityDiag *VariantDiag = nullptr,
+    const PlatformSpecificAvailabilityDiag *VariantPlatformInfo = nullptr) {
+  // Create the fix-it only when the replacement on both platforms matches.
 
   SmallVector<FixItHint, 12> FixIts;
-  if (K == AR_Deprecated) {
-    StringRef Replacement;
-    if (auto AL = OffendingDecl->getAttr<DeprecatedAttr>())
-      Replacement = AL->getReplacement();
-    if (auto AL = getAttrForPlatform(S.Context, OffendingDecl))
-      Replacement = AL->getReplacement();
-
-    CharSourceRange UseRange;
-    if (!Replacement.empty())
-      UseRange =
-          CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
-    if (UseRange.isValid()) {
-      if (const auto *MethodDecl = dyn_cast<ObjCMethodDecl>(ReferringDecl)) {
-        Selector Sel = MethodDecl->getSelector();
-        SmallVector<StringRef, 12> SelectorSlotNames;
-        std::optional<unsigned> NumParams = tryParseObjCMethodName(
-            Replacement, SelectorSlotNames, S.getLangOpts());
-        if (NumParams && *NumParams == Sel.getNumArgs()) {
-          assert(SelectorSlotNames.size() == Locs.size());
-          for (unsigned I = 0; I < Locs.size(); ++I) {
-            if (!Sel.getNameForSlot(I).empty()) {
-              CharSourceRange NameRange = CharSourceRange::getCharRange(
-                  Locs[I], S.getLocForEndOfToken(Locs[I]));
-              FixIts.push_back(FixItHint::CreateReplacement(
-                  NameRange, SelectorSlotNames[I]));
-            } else
-              FixIts.push_back(
-                  FixItHint::CreateInsertion(Locs[I], SelectorSlotNames[I]));
-          }
-        } else
-          FixIts.push_back(FixItHint::CreateReplacement(UseRange, Replacement));
+  if (Diag.UseRange.isValid() &&
+      (!VariantDiag || Diag.Replacement == VariantDiag->Replacement)) {
+    if (const auto *MethodDecl = dyn_cast<ObjCMethodDecl>(Info.ReferringDecl)) {
+      Selector Sel = MethodDecl->getSelector();
+      SmallVector<StringRef, 12> SelectorSlotNames;
+      std::optional<unsigned> NumParams = tryParseObjCMethodName(
+          Diag.Replacement, SelectorSlotNames, S.getLangOpts());
+      if (NumParams && *NumParams == Sel.getNumArgs()) {
+        assert(SelectorSlotNames.size() == Info.Locs.size());
+        for (unsigned I = 0; I < Info.Locs.size(); ++I) {
+          if (!Sel.getNameForSlot(I).empty()) {
+            CharSourceRange NameRange = CharSourceRange::getCharRange(
+                Info.Locs[I], S.getLocForEndOfToken(Info.Locs[I]));
+            FixIts.push_back(
+                FixItHint::CreateReplacement(NameRange, SelectorSlotNames[I]));
+          } else
+            FixIts.push_back(
+                FixItHint::CreateInsertion(Info.Locs[I], SelectorSlotNames[I]));
+        }
       } else
-        FixIts.push_back(FixItHint::CreateReplacement(UseRange, Replacement));
-    }
+        FixIts.push_back(
+            FixItHint::CreateReplacement(Diag.UseRange, Diag.Replacement));
+    } else
+      FixIts.push_back(
+          FixItHint::CreateReplacement(Diag.UseRange, Diag.Replacement));
   }
 
+  SourceLocation Loc = Info.Locs[0];
+
   // We emit deprecation warning for deprecated specializations
   // when their instantiation stacks originate outside
   // of a system header, even if the diagnostics is suppresed at the
   // point of definition.
   SourceLocation InstantiationLoc =
-      S.getTopMostPointOfInstantiation(ReferringDecl);
+      S.getTopMostPointOfInstantiation(Info.ReferringDecl);
   bool ShouldAllowWarningInSystemHeader =
       InstantiationLoc != Loc &&
       !S.getSourceManager().isInSystemHeader(InstantiationLoc);
@@ -687,23 +834,112 @@ static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
   } SystemWarningOverrideRAII(S.getDiagnostics(),
                               ShouldAllowWarningInSystemHeader);
 
+  auto EmitObjCPropNote = [&]() {
+    if (PlatformInfo.ObjCProperty)
+      S.Diag(PlatformInfo.ObjCProperty->getLocation(),
+             diag::note_property_attribute)
+          << PlatformInfo.ObjCProperty->getDeclName()
+          << Diag.property_note_select;
+    if (VariantPlatformInfo && VariantPlatformInfo->ObjCProperty)
+      S.Diag(VariantPlatformInfo->ObjCProperty->getLocation(),
+             diag::note_property_attribute)
+          << VariantPlatformInfo->ObjCProperty->getDeclName()
+          << VariantDiag->property_note_select;
+  };
   if (!Message.empty()) {
-    S.Diag(Loc, diag_message) << ReferringDecl << Message << FixIts;
-    if (ObjCProperty)
-      S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
-          << ObjCProperty->getDeclName() << property_note_select;
-  } else if (!UnknownObjCClass) {
-    S.Diag(Loc, diag) << ReferringDecl << FixIts;
-    if (ObjCProperty)
-      S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
-          << ObjCProperty->getDeclName() << property_note_select;
+    S.Diag(Loc, Diag.diag_message) << Info.ReferringDecl << Message << FixIts;
+    EmitObjCPropNote();
+  } else if (!Info.UnknownObjCClass) {
+    S.Diag(Loc, Diag.diag) << Info.ReferringDecl << FixIts;
+    EmitObjCPropNote();
   } else {
-    S.Diag(Loc, diag_fwdclass_message) << ReferringDecl << FixIts;
-    S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
+    S.Diag(Loc, Diag.diag_fwdclass_message) << Info.ReferringDecl << FixIts;
+    S.Diag(Info.UnknownObjCClass->getLocation(), diag::note_forward_class);
   }
 
-  S.Diag(NoteLocation, diag_available_here)
-    << OffendingDecl << available_here_select_kind;
+  S.Diag(Diag.NoteLocation, Diag.diag_available_here)
+      << PlatformInfo.OffendingDecl << Diag.available_here_select_kind;
+  if (VariantDiag && VariantDiag->NoteLocation != Diag.NoteLocation)
+    S.Diag(VariantDiag->NoteLocation, VariantDiag->diag_available_here)
+        << VariantPlatformInfo->OffendingDecl
+        << VariantDiag->available_here_select_kind;
+}
+
+/// Actually emit an availability diagnostic for a reference to an unavailable
+/// decl.
+///
+/// \param Ctx The context that the reference occurred in
+/// \param ReferringDecl The exact declaration that was referenced.
+/// \param OffendingDecl A related decl to \c ReferringDecl that has an
+/// availability attribute corresponding to \c K attached to it. Note that this
+/// may not be the same as ReferringDecl, i.e. if an EnumDecl is annotated and
+/// we refer to a member EnumConstantDecl, ReferringDecl is the EnumConstantDecl
+/// and OffendingDecl is the EnumDecl.
+static void DoEmitAvailabilityWarning(
+    Sema &S, Decl *Ctx, const PlatformAgnosticAvailabilityDiagInfo &Info,
+    const PlatformSpecificAvailabilityDiag &PlatformInfo) {
+  if (!ShouldEmitAvailabilityWarning(S, Ctx, Info, PlatformInfo))
+    return;
+
+  if (PlatformInfo.AR == AR_NotYetIntroduced)
+    return EmitNotIntroducedAvailabilityWarning(S, Ctx, Info, PlatformInfo);
+  assert(PlatformInfo.AR != AR_Available &&
+         "expected an unavailable/deprecated AR");
+
+  if (PlatformInfo.AR == AR_Deprecated)
+    // Suppress -Wdeprecated-declarations in implicit
+    // functions.
+    if (const auto *FD = dyn_cast_or_null<FunctionDecl>(S.getCurFunctionDecl());
+        FD && FD->isImplicit())
+      return;
+
+  UnavailableDeprecatedAvailabilityDiag Diag(S, Info, PlatformInfo);
+  EmitUnavailableDeprecatedAvailabilityWarning(S, PlatformInfo.Message, Diag,
+                                               Info, PlatformInfo);
+}
+
+static void DoEmitZipperedAvailabilityWarning(
+    Sema &S, Decl *Ctx, const PlatformAgnosticAvailabilityDiagInfo &Info,
+    const PlatformSpecificAvailabilityDiag &PlatformInfo,
+    const PlatformSpecificAvailabilityDiag &VariantPlatformInfo) {
+  assert(PlatformInfo.IsTargetVariantPlatform == false &&
+         VariantPlatformInfo.IsTargetVariantPlatform == true &&
+         "invalid zippered diag");
+  bool EmitP1 = ShouldEmitAvailabilityWarning(S, Ctx, Info, PlatformInfo);
+  bool EmitP2 =
+      ShouldEmitAvailabilityWarning(S, Ctx, Info, VariantPlatformInfo);
+  if (!EmitP1 && !EmitP2)
+    return;
+  if (EmitP1 && EmitP2) {
+    // Check if we can merge the diagnostic into one.
+    if (PlatformInfo.AR == VariantPlatformInfo.AR) {
+      if (PlatformInfo.AR == AR_NotYetIntroduced) {
+        EmitZipperedNotIntroducedAvailabilityWarning(S, Ctx, Info, PlatformInfo,
+                                                     VariantPlatformInfo);
+        return;
+      }
+      UnavailableDeprecatedAvailabilityDiag D1(S, Info, PlatformInfo);
+      UnavailableDeprecatedAvailabilityDiag D2(S, Info, VariantPlatformInfo);
+      if (D1 == D2) {
+        std::string Message;
+        llvm::raw_string_ostream OS(Message);
+        if (!PlatformInfo.Message.empty() &&
+            !VariantPlatformInfo.Message.empty())
+          OS << PlatformInfo.Message << " and " << VariantPlatformInfo.Message;
+        else if (!PlatformInfo.Message.empty())
+          OS << PlatformInfo.Message;
+        else if (!VariantPlatformInfo.Message.empty())
+          OS << VariantPlatformInfo.Message;
+        EmitUnavailableDeprecatedAvailabilityWarning(
+            S, OS.str(), D1, Info, PlatformInfo, &D2, &VariantPlatformInfo);
+        return;
+      }
+    }
+  }
+  if (EmitP1)
+    DoEmitAvailabilityWarning(S, Ctx, Info, PlatformInfo);
+  if (EmitP2)
+    DoEmitAvailabilityWarning(S, Ctx, Info, VariantPlatformInfo);
 }
 
 void Sema::handleDelayedAvailabilityCheck(DelayedDiagnostic &DD, Decl *Ctx) {
@@ -711,34 +947,39 @@ void Sema::handleDelayedAvailabilityCheck(DelayedDiagnostic &DD, Decl *Ctx) {
          "Expected an availability diagnostic here");
 
   DD.Triggered = true;
-  DoEmitAvailabilityWarning(
-      *this, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityReferringDecl(),
-      DD.getAvailabilityOffendingDecl(), DD.getAvailabilityMessage(),
-      DD.getAvailabilitySelectorLocs(), DD.getUnknownObjCClass(),
-      DD.getObjCProperty(), false);
+  PlatformAgnosticAvailabilityDiagInfo Info(
+      DD.getAvailabilityReferringDecl(), DD.getAvailabilitySelectorLocs(),
+      DD.getUnknownObjCClass(), DD.getObjCPropertyAccess());
+  PlatformSpecificAvailabilityDiag PlatformInfo(
+      DD.getAvailabilityResult(), DD.getAvailabilityOffendingDecl(),
+      DD.getAvailabilityMessage().str(), DD.getObjCProperty(),
+      DD.isTargetVariantPlatform());
+  DoEmitAvailabilityWarning(*this, Ctx, Info, PlatformInfo);
 }
 
-static void EmitAvailabilityWarning(Sema &S, AvailabilityResult AR,
-                                    const NamedDecl *ReferringDecl,
-                                    const NamedDecl *OffendingDecl,
-                                    StringRef Message,
-                                    ArrayRef<SourceLocation> Locs,
-                                    const ObjCInterfaceDecl *UnknownObjCClass,
-                                    const ObjCPropertyDecl *ObjCProperty,
-                                    bool ObjCPropertyAccess) {
-  // Delay if we're currently parsing a declaration.
-  if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
-    S.DelayedDiagnostics.add(
-        DelayedDiagnostic::makeAvailability(
-            AR, Locs, ReferringDecl, OffendingDecl, UnknownObjCClass,
-            ObjCProperty, Message, ObjCPropertyAccess));
-    return;
-  }
+void Sema::handleZipperedDelayedAvailabilityCheck(DelayedDiagnostic &DD,
+                                                  DelayedDiagnostic &VariantDD,
+                                                  Decl *Ctx) {
+  assert(DD.Kind == DelayedDiagnostic::Availability &&
+         VariantDD.Kind == DelayedDiagnostic::Availability &&
+         "Expected an availability diagnostic here");
 
-  Decl *Ctx = cast<Decl>(S.getCurLexicalContext());
-  DoEmitAvailabilityWarning(S, AR, Ctx, ReferringDecl, OffendingDecl,
-                            Message, Locs, UnknownObjCClass, ObjCProperty,
-                            ObjCPropertyAccess);
+  DD.Triggered = true;
+  VariantDD.Triggered = true;
+  PlatformAgnosticAvailabilityDiagInfo Info(
+      DD.getAvailabilityReferringDecl(), DD.getAvailabilitySelectorLocs(),
+      DD.getUnknownObjCClass(), DD.getObjCPropertyAccess());
+  PlatformSpecificAvailabilityDiag PlatformInfo(
+      DD.getAvailabilityResult(), DD.getAvailabilityOffendingDecl(),
+      DD.getAvailabilityMessage().str(), DD.getObjCProperty(),
+      DD.isTargetVariantPlatform());
+  PlatformSpecificAvailabilityDiag VariantPlatformInfo(
+      VariantDD.getAvailabilityResult(),
+      VariantDD.getAvailabilityOffendingDecl(),
+      VariantDD.getAvailabilityMessage().str(), VariantDD.getObjCProperty(),
+      VariantDD.isTargetVariantPlatform());
+  DoEmitZipperedAvailabilityWarning(*this, Ctx, Info, PlatformInfo,
+                                    VariantPlatformInfo);
 }
 
 namespace {
@@ -816,17 +1057,58 @@ class DiagnoseUnguardedAvailability : public DynamicRecursiveASTVisitor {
   Decl *Ctx;
 
   /// Stack of potentially nested 'if (@available(...))'s.
-  SmallVector<VersionTuple, 8> AvailabilityStack;
+  struct ZipperedVersionTuple {
+    std::optional<VersionTuple> Version;
+    std::optional<VersionTuple> VariantVersion;
+
+    static ZipperedVersionTuple make(VersionTuple V) {
+      return {V, std::nullopt};
+    }
+    static ZipperedVersionTuple makeVariant(VersionTuple V) {
+      return {std::nullopt, V};
+    }
+    static ZipperedVersionTuple makeZippered(VersionTuple V,
+                                             VersionTuple VariantV) {
+      return {V, VariantV};
+    }
+  };
+  SmallVector<ZipperedVersionTuple, 8> AvailabilityStack;
   SmallVector<const Stmt *, 16> StmtStack;
 
+  void EmitNotYetIntroducedDiagnostic(
+      NamedDecl *D, SourceRange Range,
+      const PlatformSpecificAvailabilityDiag &PlatformInfo,
+      const PlatformSpecificAvailabilityDiag *VariantPlatformInfo = nullptr);
+
   void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range,
                                 ObjCInterfaceDecl *ClassReceiver = nullptr);
 
 public:
   DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
       : SemaRef(SemaRef), Ctx(Ctx) {
+    const TargetInfo &TI = SemaRef.Context.getTargetInfo();
     AvailabilityStack.push_back(
-        SemaRef.Context.getTargetInfo().getPlatformMinVersion());
+        TI.hasTargetVariantPlatform()
+            ? ZipperedVersionTuple::makeZippered(
+                  TI.getPlatformMinVersion(),
+                  TI.getTargetVariantPlatformMinVersion())
+            : ZipperedVersionTuple::make(TI.getPlatformMinVersion()));
+  }
+
+  // Returns the OS version for the native/variant platform that's guarded by
+  // the @available
+  // checks.
+  const VersionTuple &getGuardedVersion(bool IsTargetVariantPlatform) {
+    if (!SemaRef.Context.getTargetInfo().hasTargetVariantPlatform())
+      return *AvailabilityStack.back().Version;
+    for (const auto &S : llvm::reverse(AvailabilityStack)) {
+      if (IsTargetVariantPlatform) {
+        if (S.VariantVersion)
+          return *S.VariantVersion;
+      } else if (S.Version)
+        return *S.Version;
+    }
+    llvm_unreachable("missing availability version guard");
   }
 
   bool TraverseStmt(Stmt *S) override {
@@ -882,143 +1164,226 @@ class DiagnoseUnguardedAvailability : public DynamicRecursiveASTVisitor {
   bool VisitTypeLoc(TypeLoc Ty) override;
 };
 
+void DiagnoseUnguardedAvailability::EmitNotYetIntroducedDiagnostic(
+    NamedDecl *D, SourceRange Range,
+    const PlatformSpecificAvailabilityDiag &PlatformInfo,
+    const PlatformSpecificAvailabilityDiag *VariantPlatformInfo) {
+  // We would like to emit the diagnostic even if -Wunguarded-availability is
+  // not specified for deployment targets >= to iOS 11 or equivalent or
+  // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
+  // later.
+  const TargetInfo &TI = SemaRef.getASTContext().getTargetInfo();
+  StringRef PlatformNameStrRef = PlatformInfo.IsTargetVariantPlatform
+                                     ? TI.getTargetVariantPlatform()
+                                     : TI.getPlatformName();
+  auto *AA = getAttrForPlatform(SemaRef.getASTContext(), PlatformNameStrRef,
+                                PlatformInfo.OffendingDecl);
+  VersionTuple Introduced = AA->getEffectiveIntroduced();
+
+  std::string PlatformName(
+      AvailabilityAttr::getPrettyPlatformName(PlatformNameStrRef));
+  llvm::StringRef TargetEnvironment(TI.getTriple().getEnvironmentName());
+  bool EnvironmentMatchesOrNone = hasMatchingEnvironmentOrNone(
+      SemaRef.getASTContext(), AA->getEffectiveAttr());
+  llvm::StringRef AttrEnvironment =
+      AA->getEnvironment() ? AA->getEnvironment()->getName() : "";
+  bool UseEnvironment =
+      (!AttrEnvironment.empty() && !TargetEnvironment.empty());
+
+  unsigned DiagKind =
+      VariantPlatformInfo
+          ? diag::warn_zippered_unguarded_availability
+          : getAvailabilityDiagnosticKind(
+                SemaRef.Context,
+                PlatformInfo.IsTargetVariantPlatform
+                    ? TI.getTargetVariantPlatformMinVersion()
+                    : TI.getPlatformMinVersion(),
+                Introduced, EnvironmentMatchesOrNone,
+                /*IsTargetVariantCheck=*/PlatformInfo.IsTargetVariantPlatform);
+
+  VersionTuple VariantIntroduced;
+  if (VariantPlatformInfo)
+    VariantIntroduced = getAttrForPlatform(SemaRef.getASTContext(),
+                                           TI.getTargetVariantPlatform(),
+                                           VariantPlatformInfo->OffendingDecl)
+                            ->getIntroduced();
+  {
+    auto Diag = SemaRef.Diag(Range.getBegin(), DiagKind)
+                << Range << D << PlatformName << Introduced.getAsString();
+    if (!VariantPlatformInfo)
+      Diag << UseEnvironment << TargetEnvironment;
+    else
+      Diag << AvailabilityAttr::getPrettyPlatformName(
+                  TI.getTargetVariantPlatform())
+           << VariantIntroduced.getAsString();
+  }
+
+  SemaRef.Diag(PlatformInfo.OffendingDecl->getLocation(),
+               diag::note_partial_availability_specified_here)
+      << PlatformInfo.OffendingDecl << PlatformName << Introduced.getAsString()
+      << (PlatformInfo.IsTargetVariantPlatform
+              ? TI.getTargetVariantPlatformMinVersion()
+              : TI.getPlatformMinVersion())
+             .getAsString()
+      << UseEnvironment << AttrEnvironment << TargetEnvironment;
+  if (VariantPlatformInfo &&
+      PlatformInfo.OffendingDecl != VariantPlatformInfo->OffendingDecl)
+    SemaRef.Diag(VariantPlatformInfo->OffendingDecl->getLocation(),
+                 diag::note_partial_availability_specified_here)
+        << VariantPlatformInfo->OffendingDecl
+        << AvailabilityAttr::getPrettyPlatformName(
+               TI.getTargetVariantPlatform())
+        << VariantIntroduced.getAsString()
+        << TI.getTargetVariantPlatformMinVersion().getAsString();
+
+  // Do not offer to silence the warning or fixits for HLSL
+  if (SemaRef.getLangOpts().HLSL)
+    return;
+
+  auto FixitDiag =
+      SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
+      << Range << D
+      << (SemaRef.getLangOpts().ObjC ? /*@available*/ 0
+                                     : /*__builtin_available*/ 1);
+
+  // Find the statement which should be enclosed in the if @available check.
+  if (StmtStack.empty())
+    return;
+  const Stmt *StmtOfUse = StmtStack.back();
+  const CompoundStmt *Scope = nullptr;
+  for (const Stmt *S : llvm::reverse(StmtStack)) {
+    if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
+      Scope = CS;
+      break;
+    }
+    if (isBodyLikeChildStmt(StmtOfUse, S)) {
+      // The declaration won't be seen outside of the statement, so we don't
+      // have to wrap the uses of any declared variables in if (@available).
+      // Therefore we can avoid setting Scope here.
+      break;
+    }
+    StmtOfUse = S;
+  }
+  const Stmt *LastStmtOfUse = nullptr;
+  if (isa<DeclStmt>(StmtOfUse) && Scope) {
+    for (const Decl *D : cast<DeclStmt>(StmtOfUse)->decls()) {
+      if (StmtUSEFinder::isContained(StmtStack.back(), D)) {
+        LastStmtOfUse = LastDeclUSEFinder::findLastStmtThatUsesDecl(D, Scope);
+        break;
+      }
+    }
+  }
+
+  const SourceManager &SM = SemaRef.getSourceManager();
+  SourceLocation IfInsertionLoc = SM.getExpansionLoc(StmtOfUse->getBeginLoc());
+  SourceLocation StmtEndLoc =
+      SM.getExpansionRange(
+            (LastStmtOfUse ? LastStmtOfUse : StmtOfUse)->getEndLoc())
+          .getEnd();
+  if (SM.getFileID(IfInsertionLoc) != SM.getFileID(StmtEndLoc))
+    return;
+
+  StringRef Indentation = Lexer::getIndentationForLine(IfInsertionLoc, SM);
+  const char *ExtraIndentation = "    ";
+  std::string FixItString;
+  llvm::raw_string_ostream FixItOS(FixItString);
+  StringRef FixItPlatformName;
+  VersionTuple FixItVersion;
+
+  if (AA->getInferredAttr()) {
+    FixItPlatformName = "anyAppleOS";
+    FixItVersion = AA->getIntroduced();
+  } else {
+    FixItPlatformName =
+        AvailabilityAttr::getPlatformNameSourceSpelling(PlatformName);
+    FixItVersion = Introduced;
+  }
+  FixItOS << "if ("
+          << (SemaRef.getLangOpts().ObjC ? "@available" : "__builtin_available")
+          << "(" << FixItPlatformName << " " << FixItVersion.getAsString();
+  if (VariantPlatformInfo)
+    FixItOS << ", "
+            << AvailabilityAttr::getPlatformNameSourceSpelling(
+                   TI.getTargetVariantPlatform())
+            << " " << VariantIntroduced.getAsString();
+  FixItOS << ", *)) {\n" << Indentation << ExtraIndentation;
+  FixitDiag << FixItHint::CreateInsertion(IfInsertionLoc, FixItOS.str());
+  SourceLocation ElseInsertionLoc = Lexer::findLocationAfterToken(
+      StmtEndLoc, tok::semi, SM, SemaRef.getLangOpts(),
+      /*SkipTrailingWhitespaceAndNewLine=*/false);
+  if (ElseInsertionLoc.isInvalid())
+    ElseInsertionLoc =
+        Lexer::getLocForEndOfToken(StmtEndLoc, 0, SM, SemaRef.getLangOpts());
+  FixItOS.str().clear();
+  FixItOS << "\n"
+          << Indentation << "} else {\n"
+          << Indentation << ExtraIndentation
+          << "// Fallback on earlier versions\n"
+          << Indentation << "}";
+  FixitDiag << FixItHint::CreateInsertion(ElseInsertionLoc, FixItOS.str());
+}
+
 void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
     NamedDecl *D, SourceRange Range, ObjCInterfaceDecl *ReceiverClass) {
-  AvailabilityResult Result;
-  const NamedDecl *OffendingDecl;
-  std::tie(Result, OffendingDecl) =
-      SemaRef.ShouldDiagnoseAvailabilityOfDecl(D, nullptr, ReceiverClass);
-  if (Result != AR_Available) {
+  const TargetInfo &TI = SemaRef.getASTContext().getTargetInfo();
+
+  auto CreatePlatformDiagInfo = [&](bool IsTargetVariantPlatform)
+      -> std::optional<PlatformSpecificAvailabilityDiag> {
+    AvailabilityResult Result;
+    const NamedDecl *OffendingDecl;
+    StringRef PlatformName = IsTargetVariantPlatform
+                                 ? TI.getTargetVariantPlatform()
+                                 : TI.getPlatformName();
+    const VersionTuple &PlatformMinVersion =
+        IsTargetVariantPlatform ? TI.getTargetVariantPlatformMinVersion()
+                                : TI.getPlatformMinVersion();
+    std::tie(Result, OffendingDecl) = SemaRef.ShouldDiagnoseAvailabilityOfDecl(
+        D, PlatformName, PlatformMinVersion, nullptr, ReceiverClass);
     // All other diagnostic kinds have already been handled in
     // DiagnoseAvailabilityOfDecl.
     if (Result != AR_NotYetIntroduced)
-      return;
+      return std::nullopt;
 
-    const AvailabilityAttr *AA =
-      getAttrForPlatform(SemaRef.getASTContext(), OffendingDecl);
+    const AvailabilityAttr *AA = getAttrForPlatform(
+        SemaRef.getASTContext(), PlatformName, OffendingDecl);
     assert(AA != nullptr && "expecting valid availability attribute");
     bool EnvironmentMatchesOrNone = hasMatchingEnvironmentOrNone(
         SemaRef.getASTContext(), AA->getEffectiveAttr());
     VersionTuple Introduced = AA->getEffectiveIntroduced();
 
-    if (EnvironmentMatchesOrNone && AvailabilityStack.back() >= Introduced)
-      return;
+    if (EnvironmentMatchesOrNone &&
+        getGuardedVersion(IsTargetVariantPlatform) >= Introduced)
+      return std::nullopt;
 
     // If the context of this function is less available than D, we should not
     // emit a diagnostic.
-    if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced,
-                                             AA->getEffectiveEnvironment(), Ctx,
-                                             OffendingDecl))
-      return;
-
-    const TargetInfo &TI = SemaRef.getASTContext().getTargetInfo();
-    std::string PlatformName(
-        AvailabilityAttr::getPrettyPlatformName(TI.getPlatformName()));
-    llvm::StringRef TargetEnvironment(TI.getTriple().getEnvironmentName());
-    llvm::StringRef AttrEnvironment =
-        AA->getEnvironment() ? AA->getEnvironment()->getName() : "";
-    bool UseEnvironment =
-        (!AttrEnvironment.empty() && !TargetEnvironment.empty());
-
-    unsigned DiagKind = getAvailabilityDiagnosticKind(
-        SemaRef.Context,
-        SemaRef.Context.getTargetInfo().getPlatformMinVersion(), Introduced,
-        EnvironmentMatchesOrNone);
-
-    SemaRef.Diag(Range.getBegin(), DiagKind)
-        << Range << D << PlatformName << Introduced.getAsString()
-        << UseEnvironment << TargetEnvironment;
-
-    SemaRef.Diag(OffendingDecl->getLocation(),
-                 diag::note_partial_availability_specified_here)
-        << OffendingDecl << PlatformName << Introduced.getAsString()
-        << SemaRef.Context.getTargetInfo().getPlatformMinVersion().getAsString()
-        << UseEnvironment << AttrEnvironment << TargetEnvironment;
-
-    // Do not offer to silence the warning or fixits for HLSL
-    if (SemaRef.getLangOpts().HLSL)
-      return;
-
-    auto FixitDiag =
-        SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
-        << Range << D
-        << (SemaRef.getLangOpts().ObjC ? /*@available*/ 0
-                                       : /*__builtin_available*/ 1);
-
-    // Find the statement which should be enclosed in the if @available check.
-    if (StmtStack.empty())
-      return;
-    const Stmt *StmtOfUse = StmtStack.back();
-    const CompoundStmt *Scope = nullptr;
-    for (const Stmt *S : llvm::reverse(StmtStack)) {
-      if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
-        Scope = CS;
-        break;
-      }
-      if (isBodyLikeChildStmt(StmtOfUse, S)) {
-        // The declaration won't be seen outside of the statement, so we don't
-        // have to wrap the uses of any declared variables in if (@available).
-        // Therefore we can avoid setting Scope here.
-        break;
-      }
-      StmtOfUse = S;
-    }
-    const Stmt *LastStmtOfUse = nullptr;
-    if (isa<DeclStmt>(StmtOfUse) && Scope) {
-      for (const Decl *D : cast<DeclStmt>(StmtOfUse)->decls()) {
-        if (StmtUSEFinder::isContained(StmtStack.back(), D)) {
-          LastStmtOfUse = LastDeclUSEFinder::findLastStmtThatUsesDecl(D, Scope);
-          break;
-        }
-      }
-    }
+    if (!ShouldDiagnoseAvailabilityInContext(
+            SemaRef, Result, Introduced, AA->getEffectiveEnvironment(), Ctx,
+            OffendingDecl, PlatformName, PlatformMinVersion))
+      return std::nullopt;
+    return PlatformSpecificAvailabilityDiag(Result, OffendingDecl,
+                                            IsTargetVariantPlatform);
+  };
 
-    const SourceManager &SM = SemaRef.getSourceManager();
-    SourceLocation IfInsertionLoc =
-        SM.getExpansionLoc(StmtOfUse->getBeginLoc());
-    SourceLocation StmtEndLoc =
-        SM.getExpansionRange(
-              (LastStmtOfUse ? LastStmtOfUse : StmtOfUse)->getEndLoc())
-            .getEnd();
-    if (SM.getFileID(IfInsertionLoc) != SM.getFileID(StmtEndLoc))
-      return;
+  std::optional<PlatformSpecificAvailabilityDiag> PlatformInfo =
+      CreatePlatformDiagInfo(/*IsTargetVariantPlatform=*/false);
+  std::optional<PlatformSpecificAvailabilityDiag> VariantPlatformInfo;
+  if (TI.hasTargetVariantPlatform())
+    VariantPlatformInfo =
+        CreatePlatformDiagInfo(/*IsTargetVariantPlatform=*/true);
+  if (!PlatformInfo && !VariantPlatformInfo)
+    return;
 
-    StringRef Indentation = Lexer::getIndentationForLine(IfInsertionLoc, SM);
-    const char *ExtraIndentation = "    ";
-    std::string FixItString;
-    llvm::raw_string_ostream FixItOS(FixItString);
-    StringRef FixItPlatformName;
-    VersionTuple FixItVersion;
-
-    if (AA->getInferredAttr()) {
-      FixItPlatformName = "anyAppleOS";
-      FixItVersion = AA->getIntroduced();
-    } else {
-      FixItPlatformName = AvailabilityAttr::getPlatformNameSourceSpelling(
-          SemaRef.getASTContext().getTargetInfo().getPlatformName());
-      FixItVersion = AA->getEffectiveIntroduced();
-    }
-    FixItOS << "if ("
-            << (SemaRef.getLangOpts().ObjC ? "@available"
-                                           : "__builtin_available")
-            << "(" << FixItPlatformName << " " << FixItVersion.getAsString()
-            << ", *)) {\n"
-            << Indentation << ExtraIndentation;
-    FixitDiag << FixItHint::CreateInsertion(IfInsertionLoc, FixItOS.str());
-    SourceLocation ElseInsertionLoc = Lexer::findLocationAfterToken(
-        StmtEndLoc, tok::semi, SM, SemaRef.getLangOpts(),
-        /*SkipTrailingWhitespaceAndNewLine=*/false);
-    if (ElseInsertionLoc.isInvalid())
-      ElseInsertionLoc =
-          Lexer::getLocForEndOfToken(StmtEndLoc, 0, SM, SemaRef.getLangOpts());
-    FixItOS.str().clear();
-    FixItOS << "\n"
-            << Indentation << "} else {\n"
-            << Indentation << ExtraIndentation
-            << "// Fallback on earlier versions\n"
-            << Indentation << "}";
-    FixitDiag << FixItHint::CreateInsertion(ElseInsertionLoc, FixItOS.str());
+  if (PlatformInfo) {
+    if (VariantPlatformInfo)
+      EmitNotYetIntroducedDiagnostic(D, Range, *PlatformInfo,
+                                     &*VariantPlatformInfo);
+    else
+      EmitNotYetIntroducedDiagnostic(D, Range, *PlatformInfo);
+    return;
   }
+  if (VariantPlatformInfo)
+    EmitNotYetIntroducedDiagnostic(D, Range, *VariantPlatformInfo);
 }
 
 bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
@@ -1068,16 +1433,34 @@ ExtractedAvailabilityExpr extractAvailabilityExpr(const Expr *IfCond) {
 }
 
 bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
+  VersionTuple CondVersion;
+  VersionTuple VariantCondVersion;
+  if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
+    CondVersion = E->getVersion();
+    VariantCondVersion = E->getVariantVersion();
+
+    bool IsStar = CondVersion.empty() && VariantCondVersion.empty();
+    bool IsCondRedundant =
+        CondVersion <= getGuardedVersion(/*IsTargetVariantPlatform=*/false);
+    bool IsVariantCondRedundant =
+        VariantCondVersion.empty() ||
+        VariantCondVersion <=
+            getGuardedVersion(/*IsTargetVariantPlatform=*/true);
+    // If we're using the '*' case here or if this check is redundant, then we
+    // use the enclosing version to check both branches.
+    if (IsStar || (IsCondRedundant && IsVariantCondRedundant))
+      return TraverseStmt(If->getThen()) && TraverseStmt(If->getElse());
+  }
+
   ExtractedAvailabilityExpr IfCond = extractAvailabilityExpr(If->getCond());
   if (!IfCond.E) {
     // This isn't an availability checking 'if', we can just continue.
     return DynamicRecursiveASTVisitor::TraverseIfStmt(If);
   }
-
-  VersionTuple CondVersion = IfCond.E->getVersion();
+  CondVersion = IfCond.E->getVersion();
   // If we're using the '*' case here or if this check is redundant, then we
   // use the enclosing version to check both branches.
-  if (CondVersion.empty() || CondVersion <= AvailabilityStack.back()) {
+  if (CondVersion.empty() || CondVersion <= AvailabilityStack.back().Version) {
     return TraverseStmt(If->getThen()) && TraverseStmt(If->getElse());
   }
 
@@ -1086,14 +1469,18 @@ bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
   if (IfCond.isNegated) {
     std::swap(Guarded, Unguarded);
   }
-
-  AvailabilityStack.push_back(CondVersion);
+  AvailabilityStack.push_back(ZipperedVersionTuple{
+      CondVersion.empty() ? std::nullopt
+                          : std::optional<VersionTuple>(CondVersion),
+      VariantCondVersion.empty()
+          ? std::nullopt
+          : std::optional<VersionTuple>(VariantCondVersion)});
   bool ShouldContinue = TraverseStmt(Guarded);
+
   AvailabilityStack.pop_back();
 
   return ShouldContinue && TraverseStmt(Unguarded);
 }
-
 } // end anonymous namespace
 
 void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) {
@@ -1133,40 +1520,91 @@ void Sema::DiagnoseAvailabilityOfDecl(NamedDecl *D,
                                       bool ObjCPropertyAccess,
                                       bool AvoidPartialAvailabilityChecks,
                                       ObjCInterfaceDecl *ClassReceiver) {
+  auto CreateAvailabilityDiagnostic = [&](bool IsTargetVariantPlatform)
+      -> std::optional<PlatformSpecificAvailabilityDiag> {
+    std::string Message;
+    AvailabilityResult Result;
+    const NamedDecl *OffendingDecl;
+    // See if this declaration is unavailable, deprecated, or partial.
+    const TargetInfo &TI = getASTContext().getTargetInfo();
+    StringRef Platform = IsTargetVariantPlatform ? TI.getTargetVariantPlatform()
+                                                 : TI.getPlatformName();
+    VersionTuple VT = IsTargetVariantPlatform
+                          ? TI.getTargetVariantPlatformMinVersion()
+                          : TI.getPlatformMinVersion();
+    std::tie(Result, OffendingDecl) = ShouldDiagnoseAvailabilityOfDecl(
+        D, Platform, VT, &Message, ClassReceiver);
+    if (Result == AR_Available)
+      return std::nullopt;
 
-  std::string Message;
-  AvailabilityResult Result;
-  const NamedDecl* OffendingDecl;
-  // See if this declaration is unavailable, deprecated, or partial.
-  std::tie(Result, OffendingDecl) =
-      ShouldDiagnoseAvailabilityOfDecl(D, &Message, ClassReceiver);
-  if (Result == AR_Available)
-    return;
+    if (Result == AR_NotYetIntroduced) {
+      if (AvoidPartialAvailabilityChecks)
+        return std::nullopt;
 
-  if (Result == AR_NotYetIntroduced) {
-    if (AvoidPartialAvailabilityChecks)
-      return;
+      // We need to know the @available context in the current function to
+      // diagnose this use, let DiagnoseUnguardedAvailabilityViolations do that
+      // when we're done parsing the current function.
+      if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) {
+        Context->HasPotentialAvailabilityViolations = true;
+        return std::nullopt;
+      }
+    }
 
-    // We need to know the @available context in the current function to
-    // diagnose this use, let DiagnoseUnguardedAvailabilityViolations do that
-    // when we're done parsing the current function.
-    if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) {
-      Context->HasPotentialAvailabilityViolations = true;
-      return;
+    const ObjCPropertyDecl *ObjCPDecl = nullptr;
+    if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
+      if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
+        AvailabilityResult PDeclResult =
+            PD->getAvailability(Platform, VT, nullptr);
+        if (PDeclResult == Result)
+          ObjCPDecl = PD;
+      }
     }
+
+    return PlatformSpecificAvailabilityDiag(Result, OffendingDecl,
+                                            std::move(Message), ObjCPDecl,
+                                            IsTargetVariantPlatform);
+  };
+  std::optional<PlatformSpecificAvailabilityDiag> TargetAvailabilityDiag =
+      CreateAvailabilityDiagnostic(/*IsTargetVariantPlatform=*/false);
+  std::optional<PlatformSpecificAvailabilityDiag> TargetVariantAvailabilityDiag;
+  if (getASTContext().getTargetInfo().hasTargetVariantPlatform())
+    TargetVariantAvailabilityDiag =
+        CreateAvailabilityDiagnostic(/*IsTargetVariantPlatform=*/true);
+  if (!TargetAvailabilityDiag && !TargetVariantAvailabilityDiag)
+    return;
+
+  PlatformAgnosticAvailabilityDiagInfo Info(D, Locs, UnknownObjCClass,
+                                            ObjCPropertyAccess);
+
+  // Delay if we're currently parsing a declaration.
+  if (DelayedDiagnostics.shouldDelayDiagnostics()) {
+    auto MakeDiag = [&](const PlatformSpecificAvailabilityDiag &PlatformInfo)
+        -> DelayedDiagnostic {
+      return DelayedDiagnostic::makeAvailability(
+          PlatformInfo.AR, Info.Locs, Info.ReferringDecl,
+          PlatformInfo.OffendingDecl, Info.UnknownObjCClass,
+          PlatformInfo.ObjCProperty, PlatformInfo.Message,
+          Info.ObjCPropertyAccess, PlatformInfo.IsTargetVariantPlatform);
+    };
+    if (TargetAvailabilityDiag)
+      DelayedDiagnostics.add(MakeDiag(*TargetAvailabilityDiag));
+    if (TargetVariantAvailabilityDiag)
+      DelayedDiagnostics.add(MakeDiag(*TargetVariantAvailabilityDiag));
+    return;
   }
 
-  const ObjCPropertyDecl *ObjCPDecl = nullptr;
-  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
-    if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
-      AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
-      if (PDeclResult == Result)
-        ObjCPDecl = PD;
+  Decl *Ctx = cast<Decl>(getCurLexicalContext());
+  if (TargetAvailabilityDiag) {
+    if (TargetVariantAvailabilityDiag) {
+      DoEmitZipperedAvailabilityWarning(*this, Ctx, Info,
+                                        *TargetAvailabilityDiag,
+                                        *TargetVariantAvailabilityDiag);
+      return;
     }
+    DoEmitAvailabilityWarning(*this, Ctx, Info, *TargetAvailabilityDiag);
   }
-
-  EmitAvailabilityWarning(*this, Result, D, OffendingDecl, Message, Locs,
-                          UnknownObjCClass, ObjCPDecl, ObjCPropertyAccess);
+  if (TargetVariantAvailabilityDiag)
+    DoEmitAvailabilityWarning(*this, Ctx, Info, *TargetVariantAvailabilityDiag);
 }
 
 void Sema::DiagnoseAvailabilityOfDecl(NamedDecl *D,
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index a99fcb56d1138..2181617de7a6f 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -17205,7 +17205,8 @@ Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
         };
         // Don't issue this warning for unavailable inits or direct subclasses
         // of NSObject.
-        if (!MD->isUnavailable() && !superIsNSObject(MD)) {
+        if (!MD->isUnavailabledForAllTargetPlatforms() &&
+            !superIsNSObject(MD)) {
           Diag(MD->getLocation(),
                diag::warn_objc_designated_init_missing_super_call);
           Diag(InitMethod->getLocation(),
@@ -17215,7 +17216,7 @@ Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
       }
       if (FSI->ObjCWarnForNoInitDelegation) {
         // Don't issue this warning for unavailable inits.
-        if (!MD->isUnavailable())
+        if (!MD->isUnavailabledForAllTargetPlatforms())
           Diag(MD->getLocation(),
                diag::warn_objc_secondary_init_missing_init_call);
         FSI->ObjCWarnForNoInitDelegation = false;
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index a61fc54ade757..d56f136889d2e 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -3012,9 +3012,14 @@ static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
       if (NewAttr)
         D->addAttr(NewAttr);
     }
-  } else if (S.Context.getTargetInfo().getTriple().getOS() ==
-                 llvm::Triple::IOS &&
-             S.Context.getTargetInfo().getTriple().isMacCatalystEnvironment()) {
+  } else if ((S.Context.getTargetInfo().getTriple().getOS() ==
+                  llvm::Triple::IOS &&
+              S.Context.getTargetInfo()
+                  .getTriple()
+                  .isMacCatalystEnvironment()) ||
+             (S.Context.getTargetInfo().hasTargetVariantPlatform() &&
+              S.Context.getTargetInfo().getTargetVariantPlatform() ==
+                  "maccatalyst")) {
     auto GetSDKInfo = [&]() {
       return S.getDarwinSDKInfoForAvailabilityChecking(AL.getRange().getBegin(),
                                                        "macOS");
@@ -9015,8 +9020,20 @@ void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
       case DelayedDiagnostic::Availability:
         // Don't bother giving deprecation/unavailable diagnostics if
         // the decl is invalid.
-        if (!decl->isInvalidDecl())
+        if (!decl->isInvalidDecl()) {
+          if (!diag.isTargetVariantPlatform() && (i + 1) != pool->pool_end()) {
+            DelayedDiagnostic &next = const_cast<DelayedDiagnostic &>(*(i + 1));
+            if (!next.Triggered && next.isTargetVariantPlatform() &&
+                diag.Loc == next.Loc &&
+                diag.getAvailabilityReferringDecl() ==
+                    next.getAvailabilityReferringDecl()) {
+              handleZipperedDelayedAvailabilityCheck(diag, next, decl);
+              ++i;
+              break;
+            }
+          }
           handleDelayedAvailabilityCheck(diag, decl);
+        }
         break;
 
       case DelayedDiagnostic::Access:
diff --git a/clang/lib/Sema/SemaDeclObjC.cpp b/clang/lib/Sema/SemaDeclObjC.cpp
index 04ba528098af4..51da6c624972a 100644
--- a/clang/lib/Sema/SemaDeclObjC.cpp
+++ b/clang/lib/Sema/SemaDeclObjC.cpp
@@ -290,10 +290,13 @@ static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND,
   if (!ND)
     return;
   bool IsCategory = false;
+  // FIXME: Implement support for TVT.
+  StringRef Platform = S.getASTContext().getTargetInfo().getPlatformName();
+  VersionTuple PlatformVersionMin =
+      S.getASTContext().getTargetInfo().getPlatformMinVersion();
   StringRef RealizedPlatform;
   AvailabilityResult Availability = ND->getAvailability(
-      /*Message=*/nullptr, /*EnclosingVersion=*/VersionTuple(),
-      &RealizedPlatform);
+      Platform, PlatformVersionMin, /*Message=*/nullptr, &RealizedPlatform);
   if (Availability != AR_Deprecated) {
     if (isa<ObjCMethodDecl>(ND)) {
       if (Availability != AR_Unavailable)
@@ -310,7 +313,8 @@ static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND,
       return;
     }
     if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
-      if (!CD->getClassInterface()->isDeprecated())
+      if (CD->getClassInterface()->getAvailability(
+              Platform, PlatformVersionMin) != AR_Deprecated)
         return;
       ND = CD->getClassInterface();
       IsCategory = true;
@@ -2243,16 +2247,20 @@ void SemaObjC::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
     Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
 }
 
-static bool shouldWarnUndefinedMethod(const ObjCMethodDecl *M) {
+static bool shouldWarnUndefinedMethod(Sema &S, const ObjCMethodDecl *M) {
   // No point warning no definition of method which is 'unavailable'.
-  return M->getAvailability() != AR_Unavailable;
+  // FIXME: We can warn on a definition of partially unavailable method.
+  return M->getAvailability(
+             S.getASTContext().getTargetInfo().getPlatformName(),
+             S.getASTContext().getTargetInfo().getPlatformMinVersion()) !=
+         AR_Unavailable;
 }
 
 static void WarnUndefinedMethod(Sema &S, ObjCImplDecl *Impl,
                                 ObjCMethodDecl *method, bool &IncompleteImpl,
                                 unsigned DiagID,
                                 NamedDecl *NeededFor = nullptr) {
-  if (!shouldWarnUndefinedMethod(method))
+  if (!shouldWarnUndefinedMethod(S, method))
     return;
 
   // FIXME: For now ignore 'IncompleteImpl'.
@@ -3372,13 +3380,18 @@ void SemaObjC::addMethodToGlobalList(ObjCMethodList *List,
 
       // For methods with the same declaration, the one that is deprecated
       // should be put in the front for better diagnostics.
-      if (Method->isDeprecated() && SameDeclaration &&
-          !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
+      if (Method->isDeprecatedInAnyTargetPlatform() && SameDeclaration &&
+          !ListWithSameDeclaration &&
+          !List->getMethod()->isDeprecatedInAnyTargetPlatform())
         ListWithSameDeclaration = List;
 
-      if (Method->isUnavailable() && SameDeclaration &&
+      // FIXME: What about TVT?
+      if (Method->isUnavailabledForAllTargetPlatforms() && SameDeclaration &&
           !ListWithSameDeclaration &&
-          List->getMethod()->getAvailability() < AR_Deprecated)
+          List->getMethod()->getAvailability(
+              getASTContext().getTargetInfo().getPlatformName(),
+              getASTContext().getTargetInfo().getPlatformMinVersion()) <
+              AR_Deprecated)
         ListWithSameDeclaration = List;
       continue;
     }
@@ -3398,14 +3411,18 @@ void SemaObjC::addMethodToGlobalList(ObjCMethodList *List,
 
     // If a method is deprecated, push it in the global pool.
     // This is used for better diagnostics.
-    if (Method->isDeprecated()) {
-      if (!PrevObjCMethod->isDeprecated())
+    if (Method->isDeprecatedInAnyTargetPlatform()) {
+      if (!PrevObjCMethod->isDeprecatedInAnyTargetPlatform())
         List->setMethod(Method);
     }
+    // FIXME: What about TVT?
     // If the new method is unavailable, push it into global pool
     // unless previous one is deprecated.
-    if (Method->isUnavailable()) {
-      if (PrevObjCMethod->getAvailability() < AR_Deprecated)
+    if (Method->isUnavailabledForAllTargetPlatforms()) {
+      if (PrevObjCMethod->getAvailability(
+              getASTContext().getTargetInfo().getPlatformName(),
+              getASTContext().getTargetInfo().getPlatformMinVersion()) <
+          AR_Deprecated)
         List->setMethod(Method);
     }
 
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 2b524a956ecc4..3ed20095993e5 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -100,8 +100,8 @@ bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
   }
 
   // See if this function is unavailable.
-  if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
-      cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
+  if (TreatUnavailableAsInvalid && D->isUnavailabledForAllTargetPlatforms() &&
+      !cast<Decl>(CurContext)->isUnavailabledForAllTargetPlatforms())
     return false;
 
   if (isa<UnresolvedUsingIfExistsDecl>(D))
diff --git a/clang/lib/Sema/SemaExprObjC.cpp b/clang/lib/Sema/SemaExprObjC.cpp
index 25cc068ec30bd..2de5ee4d2598b 100644
--- a/clang/lib/Sema/SemaExprObjC.cpp
+++ b/clang/lib/Sema/SemaExprObjC.cpp
@@ -5328,13 +5328,23 @@ ExprResult SemaObjC::ActOnObjCAvailabilityCheckExpr(
                           Context.getTargetInfo().getTriple().getOS()))
     Version = *MaybeVersion;
 
+  VersionTuple VariantVersion;
+  if (Context.getTargetInfo().hasTargetVariantPlatform()) {
+    const llvm::Triple *VariantTriple =
+        Context.getTargetInfo().getDarwinTargetVariantTriple();
+    if (auto MaybeVariantVersion = FindSpecVersion(
+            Context.getTargetInfo().getTargetVariantPlatform(),
+            VariantTriple ? VariantTriple->getOS() : llvm::Triple::UnknownOS))
+      VariantVersion = *MaybeVariantVersion;
+  }
+
   // The use of `@available` in the enclosing context should be analyzed to
   // warn when it's used inappropriately (i.e. not if(@available)).
   if (FunctionScopeInfo *Context = SemaRef.getCurFunctionAvailabilityContext())
     Context->HasPotentialAvailabilityViolations = true;
 
-  return new (Context)
-      ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
+  return new (Context) ObjCAvailabilityCheckExpr(Version, VariantVersion, AtLoc,
+                                                 RParen, Context.BoolTy);
 }
 
 /// Prepare a conversion of the given expression to an ObjC object
diff --git a/clang/lib/Sema/SemaLookup.cpp b/clang/lib/Sema/SemaLookup.cpp
index 43129800e9813..e0024e4828095 100644
--- a/clang/lib/Sema/SemaLookup.cpp
+++ b/clang/lib/Sema/SemaLookup.cpp
@@ -4766,7 +4766,7 @@ void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
 
       auto IsDeprecated = [](Decl *D) {
         while (D) {
-          if (D->isDeprecated())
+          if (D->isDeprecatedInAnyTargetPlatform())
             return true;
           D = llvm::dyn_cast_or_null<NamespaceDecl>(D->getDeclContext());
         }
diff --git a/clang/lib/Sema/SemaObjCProperty.cpp b/clang/lib/Sema/SemaObjCProperty.cpp
index 4d7efed23939e..73985e6964ed9 100644
--- a/clang/lib/Sema/SemaObjCProperty.cpp
+++ b/clang/lib/Sema/SemaObjCProperty.cpp
@@ -1927,7 +1927,7 @@ void SemaObjC::DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
                             /* property = */ Prop->getIdentifier(),
                             /* ivar = */ Prop->getDefaultSynthIvarName(Context),
                             Prop->getLocation(), Prop->getQueryKind()));
-    if (PIDecl && !Prop->isUnavailable()) {
+    if (PIDecl && !Prop->isUnavailabledForAllTargetPlatforms()) {
       Diag(Prop->getLocation(), diag::warn_missing_explicit_synthesis);
       Diag(IMPDecl->getLocation(), diag::note_while_in_implementation);
     }
@@ -2075,8 +2075,7 @@ void SemaObjC::DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl *IMPDecl,
     // Is there a matching property synthesize/dynamic?
     if (Prop->isInvalidDecl() ||
         Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional ||
-        PropImplMap.count(Prop) ||
-        Prop->getAvailability() == AR_Unavailable)
+        PropImplMap.count(Prop) || Prop->isUnavailabledForAllTargetPlatforms())
       continue;
 
     // Diagnose unimplemented getters and setters.
@@ -2291,12 +2290,12 @@ void SemaObjC::DiagnoseMissingDesignatedInitOverrides(
       // marked as unavailable.
       bool Ignore = false;
       if (auto *IMD = IFD->getInstanceMethod(MD->getSelector())) {
-        Ignore = IMD->isUnavailable();
+        Ignore = IMD->isUnavailabledForAllTargetPlatforms();
       } else {
         // Check the methods declared in the class extensions too.
         for (auto *Ext : IFD->visible_extensions())
           if (auto *IMD = Ext->getInstanceMethod(MD->getSelector())) {
-            Ignore = IMD->isUnavailable();
+            Ignore = IMD->isUnavailabledForAllTargetPlatforms();
             break;
           }
       }
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 21781f7474e56..b0eac60ce8119 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -4172,8 +4172,13 @@ bool Sema::InstantiateClassTemplateSpecialization(
   if (AlreadyInstantiating)
     return false;
 
+  const TargetInfo &TI = Context.getTargetInfo();
+  StringRef PlatformName = TI.getPlatformName();
+  const VersionTuple &PlatformMinVersion = TI.getPlatformMinVersion();
+
   bool HadAvaibilityWarning =
-      ShouldDiagnoseAvailabilityOfDecl(ClassTemplateSpec, nullptr, nullptr)
+      ShouldDiagnoseAvailabilityOfDecl(ClassTemplateSpec, PlatformName,
+                                       PlatformMinVersion, nullptr, nullptr)
           .first != AR_Available;
 
   ActionResult<CXXRecordDecl *> Pattern =
diff --git a/clang/lib/Serialization/ASTReaderStmt.cpp b/clang/lib/Serialization/ASTReaderStmt.cpp
index 92c555dc427b3..8fb690d800143 100644
--- a/clang/lib/Serialization/ASTReaderStmt.cpp
+++ b/clang/lib/Serialization/ASTReaderStmt.cpp
@@ -1743,6 +1743,7 @@ void ASTStmtReader::VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E)
   E->AtLoc = R.getBegin();
   E->RParen = R.getEnd();
   E->VersionToCheck = Record.readVersionTuple();
+  E->VariantVersionToCheck = Record.readVersionTuple();
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/clang/lib/Serialization/ASTWriterStmt.cpp b/clang/lib/Serialization/ASTWriterStmt.cpp
index 782fecdbd0c80..c1c9cf77feddd 100644
--- a/clang/lib/Serialization/ASTWriterStmt.cpp
+++ b/clang/lib/Serialization/ASTWriterStmt.cpp
@@ -1716,6 +1716,7 @@ void ASTStmtWriter::VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E)
   VisitExpr(E);
   Record.AddSourceRange(E->getSourceRange());
   Record.AddVersionTuple(E->getVersion());
+  Record.AddVersionTuple(E->getVariantVersion());
   Code = serialization::EXPR_OBJC_AVAILABILITY_CHECK;
 }
 
diff --git a/clang/test/CodeGenObjC/availability-check-zippered.m b/clang/test/CodeGenObjC/availability-check-zippered.m
new file mode 100644
index 0000000000000..cde108307d96b
--- /dev/null
+++ b/clang/test/CodeGenObjC/availability-check-zippered.m
@@ -0,0 +1,41 @@
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14 -darwin-target-variant-triple x86_64-apple-ios12-macabi -emit-llvm -o - %s | FileCheck %s
+
+// XFAIL: *
+void use_at_available() {
+
+  // CHECK: call i32 @__isOSVersionAtLeast(i32 10, i32 15, i32 0)
+  // CHECK-NEXT: call i32 @__isTargetPlatformNative()
+  // CHECK-NEXT: icmp ne
+  // CHECK-NEXT: select
+  // CHECK-NEXT: icmp ne
+  if (@available(macos 10.15, *))
+    ;
+
+  // CHECK: call i32 @__isOSVersionAtLeast(i32 10, i32 15, i32 0)
+  // CHECK-NEXT: call i32 @__isTargetVariantOSVersionAtLeast(i32 13, i32 0, i32 0)
+  // CHECK-NEXT: call i32 @__isTargetPlatformNative()
+  // CHECK-NEXT: icmp ne
+  // CHECK-NEXT: select
+  // CHECK-NEXT: icmp ne
+  if (@available(macos 10.15, iosmac 13, *))
+   ;
+
+  // CHECK: call i32 @__isTargetVariantOSVersionAtLeast(i32 13, i32 0, i32 0)
+  // CHECK-NEXT: call i32 @__isTargetPlatformNative()
+  // CHECK-NEXT: icmp ne
+  // CHECK-NEXT: select
+  // CHECK-NEXT: icmp ne
+  if (@available(ios 13, *))
+   ;
+
+  // This check should be folded: our deployment target is 10.11.
+  // CHECK-NOT: call i32 @__isOSVersionAtLeast
+  // CHECK-NOT: call i32 @__isTargetVariantOSVersionAtLeast
+  // CHECK: br i1 true
+  if (__builtin_available(macos 10.11, ios 11, *))
+    ;
+}
+
+// CHECK: declare i32 @__isOSVersionAtLeast(i32, i32, i32)
+// CHECK: declare i32 @__isTargetPlatformNative
+// CHECK: declare i32 @__isTargetVariantOSVersionAtLeast(i32, i32, i32)
diff --git a/clang/test/FixIt/fixit-availability-zippered.m b/clang/test/FixIt/fixit-availability-zippered.m
new file mode 100644
index 0000000000000..82fc8397ff21d
--- /dev/null
+++ b/clang/test/FixIt/fixit-availability-zippered.m
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -fsyntax-only -Wunguarded-availability -fdiagnostics-parseable-fixits -triple x86_64-apple-macos10.14 -darwin-target-variant-triple x86_64-apple-ios12-macabi %s 2>&1 | FileCheck %s
+
+// XFAIL: *
+__attribute__((availability(macOS, introduced=10.15))) __attribute__((availability(ios, introduced=13)))
+int function(void);
+
+int use() {
+  function();
+// CHECK: fix-it:{{.*}}:{[[@LINE-1]]:3-[[@LINE-1]]:3}:"if (@available(macOS 10.15, iOSMac 13, *)) {\n      "
+// CHECK-NEXT: fix-it:{{.*}}:{[[@LINE-2]]:14-[[@LINE-2]]:14}:"\n  } else {\n      // Fallback on earlier versions\n  }"
+}
+
+#define API_AVAILABLE(...) __attribute__((availability(macOS, introduced=10.15))) __attribute__((availability(ios, introduced=13))) // dummy macro
+
+API_AVAILABLE(macos(10.15), ios(13))
+ at interface NewClass
+ at end
+
+ at interface OldButOfferFixit
+ at property(copy) NewClass *prop;
+// CHECK: fix-it:{{.*}}:{[[@LINE-2]]:1-[[@LINE-2]]:1}:"API_AVAILABLE(macos(10.15), iosmac(13))\n"
+
+ at end
diff --git a/clang/test/Sema/attr-availability-zippered.c b/clang/test/Sema/attr-availability-zippered.c
new file mode 100644
index 0000000000000..37a3e6c157722
--- /dev/null
+++ b/clang/test/Sema/attr-availability-zippered.c
@@ -0,0 +1,133 @@
+// RUN: %clang_cc1 "-triple" "x86_64-apple-macos10.14" -darwin-target-variant-triple x86_64-apple-ios12-macabi -fsyntax-only -verify %s
+
+// XFAIL: *
+__attribute__((availability(macos, introduced=10.10, deprecated=10.14), availability(ios, introduced=9, deprecated=12)))
+void bothDeprecated() { // expected-note {{'bothDeprecated' has been explicitly marked deprecated here}}
+}
+
+__attribute__((availability(macos, introduced=10.10, deprecated=10.14), availability(ios, introduced=9, deprecated=13)))
+void macOSDeprecated() { // expected-note {{'macOSDeprecated' has been explicitly marked deprecated here}}
+}
+
+__attribute__((availability(macos, introduced=10.10, deprecated=10.15), availability(ios, introduced=9, deprecated=12)))
+void iOSDeprecated() { // expected-note {{'iOSDeprecated' has been explicitly marked deprecated here}}
+}
+
+__attribute__((availability(macos, introduced=10.10, deprecated=10.15), availability(ios, introduced=9, deprecated=13)))
+void bothNotDeprecated() {
+}
+
+void checkDeprecated() {
+  // The compiler may warn here if the deployment target is older than the version introduced
+  bothDeprecated();  // expected-warning {{'bothDeprecated' is deprecated: first deprecated in macOS 10.14 and first deprecated in iOS (on macOS) 12}}
+  macOSDeprecated(); // expected-warning {{'macOSDeprecated' is deprecated: first deprecated in macOS 10.14}}
+  iOSDeprecated();   // expected-warning {{'iOSDeprecated' is deprecated: first deprecated in iOS (on macOS) 12}}
+  bothNotDeprecated();
+}
+
+__attribute__((availability(macos, unavailable), availability(ios, unavailable)))
+void bothUnavailable() { // expected-note {{'bothUnavailable' has been explicitly marked unavailable here}}
+}
+
+__attribute__((availability(macos, introduced=10.10), availability(ios, unavailable)))
+void iosUnavailable() { // expected-note {{'iosUnavailable' has been explicitly marked unavailable here}}
+}
+
+__attribute__((availability(macos, unavailable), availability(ios, introduced=11)))
+void macOSUnavailable() { // expected-note {{'macOSUnavailable' has been explicitly marked unavailable here}}
+}
+
+__attribute__((availability(macos, introduced=10.10), availability(ios, introduced=11)))
+void bothAvailable() { }
+
+__attribute__((availability(macos, introduced=10.10, obsoleted=10.14), availability(ios, introduced=9, obsoleted=12)))
+void bothObsoleted() { // expected-note {{'bothObsoleted' has been explicitly marked unavailable here}}
+}
+
+void checkUnavailable() {
+  bothUnavailable();  // expected-error {{'bothUnavailable' is unavailable: not available on macOS and not available on iOS (on macOS)}}
+  iosUnavailable(); // expected-error {{'iosUnavailable' is unavailable: not available on iOS (on macOS)}}
+  macOSUnavailable(); // expected-error {{'macOSUnavailable' is unavailable: not available on macOS}}
+  bothAvailable();
+  
+  bothObsoleted(); // expected-error {{'bothObsoleted' is unavailable: obsoleted in macOS 10.14 and obsoleted in iOS (on macOS) 12}}
+}
+
+__attribute__((availability(macos, introduced=10.10, deprecated=10.14)))
+typedef struct ZipperedTypedefDifferentOffendingDecl { // expected-note {{'ZipperedTypedefDifferentOffendingDecl' has been explicitly marked deprecated here}}
+// expected-warning at -1 {{'ZipperedTypedefDifferentOffendingDecl' is deprecated: first deprecated in iOS (on macOS) 12}}
+// expected-note at -2 {{'ZipperedTypedefDifferentOffendingDecl' has been explicitly marked deprecated here}}
+  int x;
+} __attribute__((availability(ios, introduced=9, deprecated=12))) ZipperedTypedefDifferentOffendingDecl_t; // expected-note {{'ZipperedTypedefDifferentOffendingDecl_t' has been explicitly marked deprecated here}}
+
+void checkZipperDiffOffendingDecl() {
+  ZipperedTypedefDifferentOffendingDecl_t tt; // expected-warning {{'ZipperedTypedefDifferentOffendingDecl_t' is deprecated: first deprecated in macOS 10.14 and first deprecated in iOS (on macOS) 12}}
+}
+
+__attribute__((availability(macos, introduced=10.10, deprecated=10.14), availability(ios, unavailable)))
+void mixUnavailableAndDeprecated() {
+  // expected-note at -1 {{'mixUnavailableAndDeprecated' has been explicitly marked unavailable here}}
+  // expected-note at -2 {{'mixUnavailableAndDeprecated' has been explicitly marked deprecated here}}
+}
+
+__attribute__((availability(macos, introduced=10.10, deprecated=10.15), availability(ios, unavailable)))
+void iOSUnavailableMacGood() {
+  // expected-note at -1 {{'iOSUnavailableMacGood' has been explicitly marked unavailable here}}
+}
+
+__attribute__((availability(macos, introduced=10.10, deprecated=10.14), availability(ios, introduced=11)))
+void macOSDeprecatedIOSGood() {
+  // expected-note at -1 {{'macOSDeprecatedIOSGood' has been explicitly marked deprecated here}}
+}
+
+__attribute__((availability(macos, introduced=10.10, deprecated=10.14, replacement="foo"), availability(ios, introduced=9, deprecated=12, replacement="bar")))
+void bothDeprecatedDiffReplacement() { // expected-note {{'bothDeprecatedDiffReplacement' has been explicitly marked deprecated here}}
+}
+
+__attribute__((availability(macos, unavailable, replacement="bar"), availability(ios, unavailable, replacement="foo")))
+void bothUnavailableSameReplacement() { // expected-note {{'bothUnavailableSameReplacement' has been explicitly marked unavailable here}}
+}
+
+__attribute__((availability(ios, unavailable)))
+void justIosUnavailable() { // expected-note {{'justIosUnavailable' has been explicitly marked unavailable here}}
+}
+
+__attribute__((availability(macos, introduced=10.10, deprecated=10.14)))
+void justMacOSDeprecated() { // expected-note {{'justMacOSDeprecated' has been explicitly marked deprecated here}}
+}
+
+void checkMix() {
+  mixUnavailableAndDeprecated();
+  // expected-error at -1 {{'mixUnavailableAndDeprecated' is unavailable: not available on iOS (on macOS)}}
+  // expected-warning at -2 {{'mixUnavailableAndDeprecated' is deprecated: first deprecated in macOS 10.14}}
+  
+  iOSUnavailableMacGood();
+  // expected-error at -1 {{'iOSUnavailableMacGood' is unavailable: not available on iOS (on macOS)}}
+  
+  macOSDeprecatedIOSGood();
+  // expected-warning at -1 {{'macOSDeprecatedIOSGood' is deprecated: first deprecated in macOS 10.14}}
+
+  bothDeprecatedDiffReplacement(); // expected-warning {{'bothDeprecatedDiffReplacement' is deprecated: first deprecated in macOS 10.14 and first deprecated in iOS (on macOS) 12}}
+  
+  bothUnavailableSameReplacement(); // expected-error {{'bothUnavailableSameReplacement' is unavailable: not available on macOS and not available on iOS (on macOS)}}
+  
+  justIosUnavailable(); // expected-error {{'justIosUnavailable' is unavailable: not available on iOS (on macOS)}}
+  
+  justMacOSDeprecated(); // expected-warning {{'justMacOSDeprecated' is deprecated: first deprecated in macOS 10.14}}
+}
+
+int deprecatedFunc() __attribute__((deprecated)); // expected-note {{'deprecatedFunc' has been explicitly marked deprecated here}}
+int unavailFunc() __attribute__((unavailable)); // expected-note {{'unavailFunc' has been explicitly marked unavailable here}}
+
+void a() {
+  int (*ptr)() = deprecatedFunc; // expected-warning {{'deprecatedFunc' is deprecated}}
+  int (*ptr2)() = unavailFunc; // expected-error {{'unavailFunc' is unavailable}}
+}
+
+
+struct IntroducedLaterBoth { } __attribute__((availability(macos, introduced=10.15), availability(ios, introduced=13)));
+// expected-note at -1 {{'IntroducedLaterBoth' has been explicitly marked partial here}}
+
+struct NotYetIntroduced { // expected-note {{annotate 'NotYetIntroduced' with an availability attribute to silence this warning}}
+  struct IntroducedLaterBoth x; // expected-warning {{'IntroducedLaterBoth' is only available on macOS 10.15 and iOS (on macOS) 13 or newer}}
+};
diff --git a/clang/test/SemaObjC/unguarded-availability-zippered.m b/clang/test/SemaObjC/unguarded-availability-zippered.m
new file mode 100644
index 0000000000000..f90c4a7242126
--- /dev/null
+++ b/clang/test/SemaObjC/unguarded-availability-zippered.m
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 -triple x86_64-apple-macos10.14 -darwin-target-variant-triple x86_64-apple-ios12-macabi -fblocks -fsyntax-only -verify %s
+
+// XFAIL: *
+#ifdef NO_WARNING
+  // expected-no-diagnostics
+#endif
+
+
+#define AVAILABLE_PREV_MAC __attribute__((availability(macos, introduced = 10.13)))
+#define AVAILABLE_CURRENT_MAC __attribute__((availability(macos, introduced = 10.14)))
+#define AVAILABLE_NEXT_MAC __attribute__((availability(macos, introduced = 10.15)))
+
+#define AVAILABLE_PREV_IOS __attribute__((availability(ios, introduced = 11)))
+#define AVAILABLE_CURRENT_IOS __attribute__((availability(iOSMac, introduced = 12)))
+#define AVAILABLE_NEXT_IOS __attribute__((availability(ios, introduced = 13)))
+
+void bothPreviouslyAvailable() AVAILABLE_PREV_MAC AVAILABLE_PREV_IOS;
+void bothCurrentlyAvailable() AVAILABLE_CURRENT_MAC AVAILABLE_CURRENT_IOS;
+void bothWillBeAvailable() AVAILABLE_NEXT_MAC AVAILABLE_NEXT_IOS;
+// expected-note at -1 3 {{'bothWillBeAvailable' has been explicitly marked partial here}}
+
+void macOSCurrentlyAvailable() AVAILABLE_CURRENT_MAC AVAILABLE_NEXT_IOS;
+// expected-note at -1 {{'macOSCurrentlyAvailable' has been explicitly marked partial here}}
+
+void test() {
+  bothPreviouslyAvailable();
+  bothCurrentlyAvailable();
+  bothWillBeAvailable(); // expected-warning {{'bothWillBeAvailable' is only available on macOS 10.15 and iOS (on macOS) 13 or newer}}
+  // expected-note at -1{{enclose 'bothWillBeAvailable' in an @available check to silence this warning}}
+  
+  macOSCurrentlyAvailable(); // expected-warning {{'macOSCurrentlyAvailable' is only available on iOS (on macOS) 13 or newer}}
+  // expected-note at -1 {{enclose 'macOSCurrentlyAvailable' in an @available check to silence this warning}}
+  
+  if (@available(ios 13, macos 10.15, *))
+    bothWillBeAvailable();
+  if (@available(ios 13, *))
+    bothWillBeAvailable(); // expected-warning {{'bothWillBeAvailable' is only available on macOS 10.15 or newer}}
+  // expected-note at -1 {{enclose}}
+  if (@available(macos 10.15, *))
+    bothWillBeAvailable(); // expected-warning {{'bothWillBeAvailable' is only available on iOS (on macOS) 13 or newer}}
+  // expected-note at -1 {{enclose}}
+}
diff --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp
index 47b641446576c..0dff1054f3b1e 100644
--- a/clang/tools/libclang/CIndex.cpp
+++ b/clang/tools/libclang/CIndex.cpp
@@ -8893,7 +8893,10 @@ static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
   if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
     return CXAvailability_NotAvailable;
 
-  switch (D->getAvailability()) {
+  const TargetInfo &TI =
+      D->getTranslationUnitDecl()->getASTContext().getTargetInfo();
+  switch (
+      D->getAvailability(TI.getPlatformName(), TI.getPlatformMinVersion())) {
   case AR_Available:
   case AR_NotYetIntroduced:
     if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))

>From 8ce45396ecb486304640d8fd4fa4f60615736648 Mon Sep 17 00:00:00 2001
From: Alex Lorenz <aleksei_lorenz at apple.com>
Date: Mon, 2 Apr 2018 13:15:20 -0700
Subject: [PATCH 02/21] <rdar://problem/39115618> Fix the typo in
 isUnavailableForAllTargetPlatforms

apple-llvm-split-commit: 275dac0e98a4a82e683e1c35bc5a66d5d0138cb5
apple-llvm-split-dir: clang/
---
 clang/include/clang/AST/DeclBase.h          | 2 +-
 clang/lib/AST/DeclBase.cpp                  | 2 +-
 clang/lib/Edit/RewriteObjCFoundationAPI.cpp | 2 +-
 clang/lib/Sema/SemaDecl.cpp                 | 5 ++---
 clang/lib/Sema/SemaDeclObjC.cpp             | 4 ++--
 clang/lib/Sema/SemaExpr.cpp                 | 4 ++--
 clang/lib/Sema/SemaObjCProperty.cpp         | 8 ++++----
 7 files changed, 13 insertions(+), 14 deletions(-)

diff --git a/clang/include/clang/AST/DeclBase.h b/clang/include/clang/AST/DeclBase.h
index 2cf8a792c9df8..936e3a27f60fa 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -792,7 +792,7 @@ class alignas(8) Decl {
 
   /// \brief Determine whether this declaration is marked 'deprecated' for
   /// all target platforms that we're compiling for.
-  bool isUnavailabledForAllTargetPlatforms() const;
+  bool isUnavailableForAllTargetPlatforms() const;
 
   /// Determine whether this is a weak-imported symbol.
   ///
diff --git a/clang/lib/AST/DeclBase.cpp b/clang/lib/AST/DeclBase.cpp
index aff04541c6781..4e9773f53eaac 100644
--- a/clang/lib/AST/DeclBase.cpp
+++ b/clang/lib/AST/DeclBase.cpp
@@ -862,7 +862,7 @@ bool Decl::isDeprecatedInAnyTargetPlatform(std::string *Message) const {
               AR_Deprecated);
 }
 
-bool Decl::isUnavailabledForAllTargetPlatforms() const {
+bool Decl::isUnavailableForAllTargetPlatforms() const {
   const TargetInfo &TI = getASTContext().getTargetInfo();
   return getAvailability(TI.getPlatformName(), TI.getPlatformMinVersion()) ==
              AR_Unavailable &&
diff --git a/clang/lib/Edit/RewriteObjCFoundationAPI.cpp b/clang/lib/Edit/RewriteObjCFoundationAPI.cpp
index fb3d1fef764b0..d499740d3d4aa 100644
--- a/clang/lib/Edit/RewriteObjCFoundationAPI.cpp
+++ b/clang/lib/Edit/RewriteObjCFoundationAPI.cpp
@@ -163,7 +163,7 @@ static bool canRewriteToSubscriptSyntax(const ObjCInterfaceDecl *&IFace,
   IFace = maybeAdjustInterfaceForSubscriptingCheck(IFace, Rec, Ctx);
 
   if (const ObjCMethodDecl *MD = IFace->lookupInstanceMethod(subscriptSel)) {
-    if (!MD->isUnavailabledForAllTargetPlatforms())
+    if (!MD->isUnavailableForAllTargetPlatforms())
       return true;
   }
   return false;
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 2181617de7a6f..5245cae402221 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -17205,8 +17205,7 @@ Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
         };
         // Don't issue this warning for unavailable inits or direct subclasses
         // of NSObject.
-        if (!MD->isUnavailabledForAllTargetPlatforms() &&
-            !superIsNSObject(MD)) {
+        if (!MD->isUnavailableForAllTargetPlatforms() && !superIsNSObject(MD)) {
           Diag(MD->getLocation(),
                diag::warn_objc_designated_init_missing_super_call);
           Diag(InitMethod->getLocation(),
@@ -17216,7 +17215,7 @@ Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
       }
       if (FSI->ObjCWarnForNoInitDelegation) {
         // Don't issue this warning for unavailable inits.
-        if (!MD->isUnavailabledForAllTargetPlatforms())
+        if (!MD->isUnavailableForAllTargetPlatforms())
           Diag(MD->getLocation(),
                diag::warn_objc_secondary_init_missing_init_call);
         FSI->ObjCWarnForNoInitDelegation = false;
diff --git a/clang/lib/Sema/SemaDeclObjC.cpp b/clang/lib/Sema/SemaDeclObjC.cpp
index 51da6c624972a..7b77f6e5c98db 100644
--- a/clang/lib/Sema/SemaDeclObjC.cpp
+++ b/clang/lib/Sema/SemaDeclObjC.cpp
@@ -3386,7 +3386,7 @@ void SemaObjC::addMethodToGlobalList(ObjCMethodList *List,
         ListWithSameDeclaration = List;
 
       // FIXME: What about TVT?
-      if (Method->isUnavailabledForAllTargetPlatforms() && SameDeclaration &&
+      if (Method->isUnavailableForAllTargetPlatforms() && SameDeclaration &&
           !ListWithSameDeclaration &&
           List->getMethod()->getAvailability(
               getASTContext().getTargetInfo().getPlatformName(),
@@ -3418,7 +3418,7 @@ void SemaObjC::addMethodToGlobalList(ObjCMethodList *List,
     // FIXME: What about TVT?
     // If the new method is unavailable, push it into global pool
     // unless previous one is deprecated.
-    if (Method->isUnavailabledForAllTargetPlatforms()) {
+    if (Method->isUnavailableForAllTargetPlatforms()) {
       if (PrevObjCMethod->getAvailability(
               getASTContext().getTargetInfo().getPlatformName(),
               getASTContext().getTargetInfo().getPlatformMinVersion()) <
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 3ed20095993e5..b4d5840187497 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -100,8 +100,8 @@ bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
   }
 
   // See if this function is unavailable.
-  if (TreatUnavailableAsInvalid && D->isUnavailabledForAllTargetPlatforms() &&
-      !cast<Decl>(CurContext)->isUnavailabledForAllTargetPlatforms())
+  if (TreatUnavailableAsInvalid && D->isUnavailableForAllTargetPlatforms() &&
+      !cast<Decl>(CurContext)->isUnavailableForAllTargetPlatforms())
     return false;
 
   if (isa<UnresolvedUsingIfExistsDecl>(D))
diff --git a/clang/lib/Sema/SemaObjCProperty.cpp b/clang/lib/Sema/SemaObjCProperty.cpp
index 73985e6964ed9..5dc5f93e7c317 100644
--- a/clang/lib/Sema/SemaObjCProperty.cpp
+++ b/clang/lib/Sema/SemaObjCProperty.cpp
@@ -1927,7 +1927,7 @@ void SemaObjC::DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
                             /* property = */ Prop->getIdentifier(),
                             /* ivar = */ Prop->getDefaultSynthIvarName(Context),
                             Prop->getLocation(), Prop->getQueryKind()));
-    if (PIDecl && !Prop->isUnavailabledForAllTargetPlatforms()) {
+    if (PIDecl && !Prop->isUnavailableForAllTargetPlatforms()) {
       Diag(Prop->getLocation(), diag::warn_missing_explicit_synthesis);
       Diag(IMPDecl->getLocation(), diag::note_while_in_implementation);
     }
@@ -2075,7 +2075,7 @@ void SemaObjC::DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl *IMPDecl,
     // Is there a matching property synthesize/dynamic?
     if (Prop->isInvalidDecl() ||
         Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional ||
-        PropImplMap.count(Prop) || Prop->isUnavailabledForAllTargetPlatforms())
+        PropImplMap.count(Prop) || Prop->isUnavailableForAllTargetPlatforms())
       continue;
 
     // Diagnose unimplemented getters and setters.
@@ -2290,12 +2290,12 @@ void SemaObjC::DiagnoseMissingDesignatedInitOverrides(
       // marked as unavailable.
       bool Ignore = false;
       if (auto *IMD = IFD->getInstanceMethod(MD->getSelector())) {
-        Ignore = IMD->isUnavailabledForAllTargetPlatforms();
+        Ignore = IMD->isUnavailableForAllTargetPlatforms();
       } else {
         // Check the methods declared in the class extensions too.
         for (auto *Ext : IFD->visible_extensions())
           if (auto *IMD = Ext->getInstanceMethod(MD->getSelector())) {
-            Ignore = IMD->isUnavailabledForAllTargetPlatforms();
+            Ignore = IMD->isUnavailableForAllTargetPlatforms();
             break;
           }
       }

>From 40513fe752ad40a452e37503f036d765fedfdc06 Mon Sep 17 00:00:00 2001
From: Alex Lorenz <aleksei_lorenz at apple.com>
Date: Mon, 2 Apr 2018 10:11:03 -0700
Subject: [PATCH 03/21] Ensure the next delayed diagnostic is an availability
 diagnostic when looking for zippered availability diagnostics

rdar://39089398

apple-llvm-split-commit: adc8de2609b0e7e30bc98a8a5a8349c8c039a03a
apple-llvm-split-dir: clang/
---
 clang/lib/Sema/SemaDeclAttr.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index d56f136889d2e..48f7d5de97f80 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -9023,7 +9023,8 @@ void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
         if (!decl->isInvalidDecl()) {
           if (!diag.isTargetVariantPlatform() && (i + 1) != pool->pool_end()) {
             DelayedDiagnostic &next = const_cast<DelayedDiagnostic &>(*(i + 1));
-            if (!next.Triggered && next.isTargetVariantPlatform() &&
+            if (next.Kind == DelayedDiagnostic::Availability &&
+                !next.Triggered && next.isTargetVariantPlatform() &&
                 diag.Loc == next.Loc &&
                 diag.getAvailabilityReferringDecl() ==
                     next.getAvailabilityReferringDecl()) {

>From c610ef9d67eb6d5c1298715a5e79473e07c91503 Mon Sep 17 00:00:00 2001
From: Alex Lorenz <aleksei_lorenz at apple.com>
Date: Tue, 3 Apr 2018 10:36:37 -0700
Subject: [PATCH 04/21] Emit a call isTargetVariantOSVersionAtLeast when
 compiling for Macabi

rdar://36138960

apple-llvm-split-commit: f2a6eb3ab0b8054147c00bcbd93008d0e079f999
apple-llvm-split-dir: clang/
---
 clang/lib/CodeGen/CGExprScalar.cpp  | 6 +++++-
 clang/lib/CodeGen/CGObjC.cpp        | 8 ++++++--
 clang/lib/CodeGen/CodeGenFunction.h | 3 ++-
 3 files changed, 13 insertions(+), 4 deletions(-)

diff --git a/clang/lib/CodeGen/CGExprScalar.cpp b/clang/lib/CodeGen/CGExprScalar.cpp
index 5be65e13a34f9..5cbf5dce6691f 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -648,7 +648,11 @@ class ScalarExprEmitter
                CGF.CGM.getTarget().getTargetVariantPlatformMinVersion()))))
       return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
 
-    return CGF.EmitBuiltinAvailable(Version, VariantVersion);
+    return CGF.EmitBuiltinAvailable(
+        Version, VariantVersion,
+        /*UseTargetVariantCheck=*/CGF.CGM.getTarget().getTriple().getOS() ==
+                llvm::Triple::IOS &&
+            CGF.CGM.getTarget().getTriple().isMacCatalystEnvironment());
   }
 
   Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
diff --git a/clang/lib/CodeGen/CGObjC.cpp b/clang/lib/CodeGen/CGObjC.cpp
index 73b1cdba09514..ca07dc2c5db3a 100644
--- a/clang/lib/CodeGen/CGObjC.cpp
+++ b/clang/lib/CodeGen/CGObjC.cpp
@@ -4050,7 +4050,8 @@ static llvm::Value *emitIsPlatformVersionAtLeast(CodeGenFunction &CGF,
 
 llvm::Value *
 CodeGenFunction::EmitBuiltinAvailable(const VersionTuple &Version,
-                                      const VersionTuple &VariantVersion) {
+                                      const VersionTuple &VariantVersion,
+                                      bool UseTargetVariantCheck) {
   // Darwin uses the new __isPlatformVersionAtLeast family of routines.
   if (CGM.getTarget().getTriple().isOSDarwin() &&
       !CGM.getTarget().hasTargetVariantPlatform())
@@ -4085,7 +4086,10 @@ CodeGenFunction::EmitBuiltinAvailable(const VersionTuple &Version,
 
   llvm::Value *Check = nullptr;
   if (!Args.empty()) {
-    Check = EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
+    Check = EmitNounwindRuntimeCall(UseTargetVariantCheck
+                                        ? CGM.IsTargetVariantOSVersionAtLeastFn
+                                        : CGM.IsOSVersionAtLeastFn,
+                                    Args);
   }
   llvm::Value *VariantCheck = nullptr;
   if (!VariantArgs.empty()) {
diff --git a/clang/lib/CodeGen/CodeGenFunction.h b/clang/lib/CodeGen/CodeGenFunction.h
index 3bf62755ac270..60ff69ba614b8 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -5029,7 +5029,8 @@ class CodeGenFunction : public CodeGenTypeCache {
   llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
 
   llvm::Value *EmitBuiltinAvailable(const VersionTuple &Version,
-                                    const VersionTuple &VariantVersion);
+                                    const VersionTuple &VariantVersion,
+                                    bool UseTargetVariantCheck);
 
   llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
   llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);

>From 59a1eb19d6289046f2a8ca47cbf22357711074c2 Mon Sep 17 00:00:00 2001
From: Alex Lorenz <aleksei_lorenz at apple.com>
Date: Thu, 5 Apr 2018 13:42:48 -0700
Subject: [PATCH 05/21] Zippered availability: '*' in @available implies that
 the unspecified target/target-variant platform is still available in that
 context.

rdar://39209833

apple-llvm-split-commit: c950bd717ad18b4fbf95074f60a2591b9530a165
apple-llvm-split-dir: clang/
---
 clang/lib/CodeGen/CGObjC.cpp                  |  4 +--
 .../CodeGenObjC/availability-check-zippered.m |  6 ++---
 .../unguarded-availability-zippered.m         | 27 ++++++++++++++++---
 3 files changed, 29 insertions(+), 8 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjC.cpp b/clang/lib/CodeGen/CGObjC.cpp
index ca07dc2c5db3a..662d966452e32 100644
--- a/clang/lib/CodeGen/CGObjC.cpp
+++ b/clang/lib/CodeGen/CGObjC.cpp
@@ -4102,9 +4102,9 @@ CodeGenFunction::EmitBuiltinAvailable(const VersionTuple &Version,
     IsNativeCheck = Builder.CreateICmpNE(IsNativeCheck,
                                          llvm::Constant::getNullValue(Int32Ty));
     if (!Check)
-      Check = llvm::Constant::getNullValue(Int32Ty);
+      Check = llvm::ConstantInt::get(Int32Ty, 1);
     if (!VariantCheck)
-      VariantCheck = llvm::Constant::getNullValue(Int32Ty);
+      VariantCheck = llvm::ConstantInt::get(Int32Ty, 1);
     Check = Builder.CreateSelect(IsNativeCheck, Check, VariantCheck);
   }
 
diff --git a/clang/test/CodeGenObjC/availability-check-zippered.m b/clang/test/CodeGenObjC/availability-check-zippered.m
index cde108307d96b..09f231c1f8d4b 100644
--- a/clang/test/CodeGenObjC/availability-check-zippered.m
+++ b/clang/test/CodeGenObjC/availability-check-zippered.m
@@ -6,7 +6,7 @@ void use_at_available() {
   // CHECK: call i32 @__isOSVersionAtLeast(i32 10, i32 15, i32 0)
   // CHECK-NEXT: call i32 @__isTargetPlatformNative()
   // CHECK-NEXT: icmp ne
-  // CHECK-NEXT: select
+  // CHECK-NEXT: select i1 %{{[0-9]+}}, i32 %{{[0-9]+}}, i32 1
   // CHECK-NEXT: icmp ne
   if (@available(macos 10.15, *))
     ;
@@ -15,7 +15,7 @@ void use_at_available() {
   // CHECK-NEXT: call i32 @__isTargetVariantOSVersionAtLeast(i32 13, i32 0, i32 0)
   // CHECK-NEXT: call i32 @__isTargetPlatformNative()
   // CHECK-NEXT: icmp ne
-  // CHECK-NEXT: select
+  // CHECK-NEXT: select i1 %{{[0-9]+}}, i32 %{{[0-9]+}}, i32 %{{[0-9]+}}
   // CHECK-NEXT: icmp ne
   if (@available(macos 10.15, iosmac 13, *))
    ;
@@ -23,7 +23,7 @@ void use_at_available() {
   // CHECK: call i32 @__isTargetVariantOSVersionAtLeast(i32 13, i32 0, i32 0)
   // CHECK-NEXT: call i32 @__isTargetPlatformNative()
   // CHECK-NEXT: icmp ne
-  // CHECK-NEXT: select
+  // CHECK-NEXT: select i1 %{{[0-9]+}}, i32 1, i32 %{{[0-9]+}}
   // CHECK-NEXT: icmp ne
   if (@available(ios 13, *))
    ;
diff --git a/clang/test/SemaObjC/unguarded-availability-zippered.m b/clang/test/SemaObjC/unguarded-availability-zippered.m
index f90c4a7242126..62a22fed99184 100644
--- a/clang/test/SemaObjC/unguarded-availability-zippered.m
+++ b/clang/test/SemaObjC/unguarded-availability-zippered.m
@@ -17,10 +17,14 @@
 void bothPreviouslyAvailable() AVAILABLE_PREV_MAC AVAILABLE_PREV_IOS;
 void bothCurrentlyAvailable() AVAILABLE_CURRENT_MAC AVAILABLE_CURRENT_IOS;
 void bothWillBeAvailable() AVAILABLE_NEXT_MAC AVAILABLE_NEXT_IOS;
-// expected-note at -1 3 {{'bothWillBeAvailable' has been explicitly marked partial here}}
+// expected-note at -1 4 {{'bothWillBeAvailable' has been explicitly marked partial here}}
 
 void macOSCurrentlyAvailable() AVAILABLE_CURRENT_MAC AVAILABLE_NEXT_IOS;
-// expected-note at -1 {{'macOSCurrentlyAvailable' has been explicitly marked partial here}}
+// expected-note at -1 2 {{'macOSCurrentlyAvailable' has been explicitly marked partial here}}
+
+void macOSNextAvailableiOSNotAvailable() AVAILABLE_NEXT_MAC __attribute__((availability(ios, unavailable)));
+// expected-note at -1 2 {{'macOSNextAvailableiOSNotAvailable' has been explicitly marked unavailable here}}
+// expected-note at -2 {{'macOSNextAvailableiOSNotAvailable' has been explicitly marked partial here}}
 
 void test() {
   bothPreviouslyAvailable();
@@ -30,13 +34,30 @@ void test() {
   
   macOSCurrentlyAvailable(); // expected-warning {{'macOSCurrentlyAvailable' is only available on iOS (on macOS) 13 or newer}}
   // expected-note at -1 {{enclose 'macOSCurrentlyAvailable' in an @available check to silence this warning}}
-  
+
   if (@available(ios 13, macos 10.15, *))
     bothWillBeAvailable();
   if (@available(ios 13, *))
     bothWillBeAvailable(); // expected-warning {{'bothWillBeAvailable' is only available on macOS 10.15 or newer}}
   // expected-note at -1 {{enclose}}
+  if (@available(ios 12, *))
+    bothWillBeAvailable(); // expected-warning {{'bothWillBeAvailable' is only available on macOS 10.15 and iOS (on macOS) 13 or newer}}
+  // expected-note at -1 {{enclose}}
   if (@available(macos 10.15, *))
     bothWillBeAvailable(); // expected-warning {{'bothWillBeAvailable' is only available on iOS (on macOS) 13 or newer}}
   // expected-note at -1 {{enclose}}
+
+  if (@available(macos 10.15, *))
+    macOSCurrentlyAvailable(); // expected-warning {{'macOSCurrentlyAvailable' is only available on iOS (on macOS) 13 or newer}}
+  // expected-note at -1 {{enclose}}
+  if (@available(ios 13, *))
+    macOSCurrentlyAvailable();
+
+  macOSNextAvailableiOSNotAvailable();
+  // expected-error at -1 {{'macOSNextAvailableiOSNotAvailable' is unavailable: not available on iOS (on macOS)}}
+  // expected-warning at -2 {{'macOSNextAvailableiOSNotAvailable' is only available on macOS 10.15 or newer}}
+  // expected-note at -3 {{enclose}}
+
+  if (@available(macos 10.15, *))
+    macOSNextAvailableiOSNotAvailable(); // expected-error {{'macOSNextAvailableiOSNotAvailable' is unavailable: not available on iOS (on macOS)}}
 }

>From 626713a2b1115401c1cd6551ae3226fca4e170e6 Mon Sep 17 00:00:00 2001
From: Alex Lorenz <arphaman at gmail.com>
Date: Fri, 30 Nov 2018 15:15:07 -0800
Subject: [PATCH 06/21] [marzipan] add support for symmetric -target-variant

Initially, -target-variant only allowed you to specify
-target macos and -target-variant ios-macabi only. We actually want to
support the reverse as well, -target ios-macabi and -target-variant macos.
This would allow third parties to better specify their zippering intention:
their code would still preprocess as if it was building for iOS, but they
will be able to take advantage of availability checks for the macOS platform
as well.

<rdar://problem/44963290> Marzipan: Make -target and -target-variant symmetric in Clang

apple-llvm-split-commit: 7150446502adf71d06fad795baad9008b3ccaf26
apple-llvm-split-dir: clang/
---
 clang/lib/Basic/Targets/OSTargets.cpp         | 12 +++-
 clang/lib/CodeGen/CGObjC.cpp                  |  9 ++-
 clang/test/CodeGen/darwin-zippered.c          |  9 +++
 .../CodeGenObjC/availability-check-zippered.m |  7 ++-
 clang/test/Sema/attr-availability-zippered.c  | 56 +++++++++++++++----
 .../unguarded-availability-zippered.m         | 24 +++++---
 6 files changed, 93 insertions(+), 24 deletions(-)
 create mode 100644 clang/test/CodeGen/darwin-zippered.c

diff --git a/clang/lib/Basic/Targets/OSTargets.cpp b/clang/lib/Basic/Targets/OSTargets.cpp
index 91f98595dbbf5..a7bb2489379af 100644
--- a/clang/lib/Basic/Targets/OSTargets.cpp
+++ b/clang/lib/Basic/Targets/OSTargets.cpp
@@ -80,8 +80,18 @@ void getDarwinDefines(MacroBuilder &Builder, const LangOptions &Opts,
   } else {
     OsVersion = Triple.getOSVersion();
     PlatformName = llvm::Triple::getOSTypeName(Triple.getOS());
-    if (PlatformName == "ios" && Triple.isMacCatalystEnvironment())
+    if (PlatformName == "ios" && Triple.isMacCatalystEnvironment()) {
       PlatformName = "maccatalyst";
+      if (!TargetVariantTriple.empty()) {
+        llvm::Triple TVT(TargetVariantTriple);
+        if (TVT.isMacOSX()) {
+          TargetVariantPlatformName = "macos";
+          VersionTuple VariantVersion;
+          TVT.getMacOSXVersion(VariantVersion);
+          TargetVariantPlatformMinVersion = VariantVersion;
+        }
+      }
+    }
   }
 
   // If -target arch-pc-win32-macho option specified, we're
diff --git a/clang/lib/CodeGen/CGObjC.cpp b/clang/lib/CodeGen/CGObjC.cpp
index 662d966452e32..250a6712b4704 100644
--- a/clang/lib/CodeGen/CGObjC.cpp
+++ b/clang/lib/CodeGen/CGObjC.cpp
@@ -4094,7 +4094,9 @@ CodeGenFunction::EmitBuiltinAvailable(const VersionTuple &Version,
   llvm::Value *VariantCheck = nullptr;
   if (!VariantArgs.empty()) {
     VariantCheck = EmitNounwindRuntimeCall(
-        CGM.IsTargetVariantOSVersionAtLeastFn, VariantArgs);
+        UseTargetVariantCheck ? CGM.IsOSVersionAtLeastFn
+                              : CGM.IsTargetVariantOSVersionAtLeastFn,
+        VariantArgs);
   }
   llvm::Value *IsNativeCheck = nullptr;
   if (CGM.getTarget().hasTargetVariantPlatform()) {
@@ -4105,6 +4107,11 @@ CodeGenFunction::EmitBuiltinAvailable(const VersionTuple &Version,
       Check = llvm::ConstantInt::get(Int32Ty, 1);
     if (!VariantCheck)
       VariantCheck = llvm::ConstantInt::get(Int32Ty, 1);
+    // When macOS is the target variant, we should swap the check and the
+    // variant check to ensure that our condition which always checks if the
+    // process is macOS still works.
+    if (UseTargetVariantCheck)
+      std::swap(Check, VariantCheck);
     Check = Builder.CreateSelect(IsNativeCheck, Check, VariantCheck);
   }
 
diff --git a/clang/test/CodeGen/darwin-zippered.c b/clang/test/CodeGen/darwin-zippered.c
new file mode 100644
index 0000000000000..ce405f3a2a1f9
--- /dev/null
+++ b/clang/test/CodeGen/darwin-zippered.c
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14 -darwin-target-variant-triple x86_64-apple-ios12-macabi -emit-llvm -o - %s | FileCheck %s
+
+// RUN: %clang_cc1 -triple x86_64-apple-ios12-macabi -darwin-target-variant-triple x86_64-apple-macosx10.14 -emit-llvm -o - %s | FileCheck --check-prefix=INVERTED %s
+
+// CHECK: !llvm.module.flags = !{!0
+// CHECK:  !0 = !{i32 2, !"darwin.target_variant.triple", !"x86_64-apple-ios12-macabi"}
+
+// INVERTED: !llvm.module.flags = !{!0
+// INVERTED:  !0 = !{i32 2, !"darwin.target_variant.triple", !"x86_64-apple-macosx10.14"}
diff --git a/clang/test/CodeGenObjC/availability-check-zippered.m b/clang/test/CodeGenObjC/availability-check-zippered.m
index 09f231c1f8d4b..5e164e52ca7b9 100644
--- a/clang/test/CodeGenObjC/availability-check-zippered.m
+++ b/clang/test/CodeGenObjC/availability-check-zippered.m
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14 -darwin-target-variant-triple x86_64-apple-ios12-macabi -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-apple-ios12-macabi -darwin-target-variant-triple x86_64-apple-macosx10.14 -emit-llvm -o - %s | FileCheck %s
 
 // XFAIL: *
 void use_at_available() {
@@ -11,9 +12,9 @@ void use_at_available() {
   if (@available(macos 10.15, *))
     ;
 
-  // CHECK: call i32 @__isOSVersionAtLeast(i32 10, i32 15, i32 0)
-  // CHECK-NEXT: call i32 @__isTargetVariantOSVersionAtLeast(i32 13, i32 0, i32 0)
-  // CHECK-NEXT: call i32 @__isTargetPlatformNative()
+  // CHECK-DAG: call i32 @__isOSVersionAtLeast(i32 10, i32 15, i32 0)
+  // CHECK-DAG: call i32 @__isTargetVariantOSVersionAtLeast(i32 13, i32 0, i32 0)
+  // CHECK: call i32 @__isTargetPlatformNative()
   // CHECK-NEXT: icmp ne
   // CHECK-NEXT: select i1 %{{[0-9]+}}, i32 %{{[0-9]+}}, i32 %{{[0-9]+}}
   // CHECK-NEXT: icmp ne
diff --git a/clang/test/Sema/attr-availability-zippered.c b/clang/test/Sema/attr-availability-zippered.c
index 37a3e6c157722..b6ca99425a04e 100644
--- a/clang/test/Sema/attr-availability-zippered.c
+++ b/clang/test/Sema/attr-availability-zippered.c
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 "-triple" "x86_64-apple-macos10.14" -darwin-target-variant-triple x86_64-apple-ios12-macabi -fsyntax-only -verify %s
+// RUN: %clang_cc1 "-triple" x86_64-apple-ios12-macabi -darwin-target-variant-triple "x86_64-apple-macos10.14"  -fsyntax-only -verify -D INVERTED %s
 
 // XFAIL: *
 __attribute__((availability(macos, introduced=10.10, deprecated=10.14), availability(ios, introduced=9, deprecated=12)))
@@ -19,7 +20,12 @@ void bothNotDeprecated() {
 
 void checkDeprecated() {
   // The compiler may warn here if the deployment target is older than the version introduced
-  bothDeprecated();  // expected-warning {{'bothDeprecated' is deprecated: first deprecated in macOS 10.14 and first deprecated in iOS (on macOS) 12}}
+  bothDeprecated();
+#ifndef INVERTED
+  // expected-warning at -2 {{'bothDeprecated' is deprecated: first deprecated in macOS 10.14 and first deprecated in iOS (on macOS) 12}}
+#else
+  // expected-warning at -4 {{'bothDeprecated' is deprecated: first deprecated in iOS (on macOS) 12 and first deprecated in macOS 10.14}}
+#endif
   macOSDeprecated(); // expected-warning {{'macOSDeprecated' is deprecated: first deprecated in macOS 10.14}}
   iOSDeprecated();   // expected-warning {{'iOSDeprecated' is deprecated: first deprecated in iOS (on macOS) 12}}
   bothNotDeprecated();
@@ -45,12 +51,22 @@ void bothObsoleted() { // expected-note {{'bothObsoleted' has been explicitly ma
 }
 
 void checkUnavailable() {
-  bothUnavailable();  // expected-error {{'bothUnavailable' is unavailable: not available on macOS and not available on iOS (on macOS)}}
+  bothUnavailable();
+#ifndef INVERTED
+  // expected-error at -2 {{'bothUnavailable' is unavailable: not available on macOS and not available on iOS (on macOS)}}
+#else
+  // expected-error at -4 {{'bothUnavailable' is unavailable: not available on iOS (on macOS) and not available on macOS}}
+#endif
   iosUnavailable(); // expected-error {{'iosUnavailable' is unavailable: not available on iOS (on macOS)}}
   macOSUnavailable(); // expected-error {{'macOSUnavailable' is unavailable: not available on macOS}}
   bothAvailable();
   
-  bothObsoleted(); // expected-error {{'bothObsoleted' is unavailable: obsoleted in macOS 10.14 and obsoleted in iOS (on macOS) 12}}
+  bothObsoleted();
+#ifndef INVERTED
+  // expected-error at -2 {{'bothObsoleted' is unavailable: obsoleted in macOS 10.14 and obsoleted in iOS (on macOS) 12}}
+#else
+  // expected-error at -4 {{'bothObsoleted' is unavailable: obsoleted in iOS (on macOS) 12 and obsoleted in macOS 10.14}}
+#endif
 }
 
 __attribute__((availability(macos, introduced=10.10, deprecated=10.14)))
@@ -61,7 +77,12 @@ typedef struct ZipperedTypedefDifferentOffendingDecl { // expected-note {{'Zippe
 } __attribute__((availability(ios, introduced=9, deprecated=12))) ZipperedTypedefDifferentOffendingDecl_t; // expected-note {{'ZipperedTypedefDifferentOffendingDecl_t' has been explicitly marked deprecated here}}
 
 void checkZipperDiffOffendingDecl() {
-  ZipperedTypedefDifferentOffendingDecl_t tt; // expected-warning {{'ZipperedTypedefDifferentOffendingDecl_t' is deprecated: first deprecated in macOS 10.14 and first deprecated in iOS (on macOS) 12}}
+  ZipperedTypedefDifferentOffendingDecl_t tt;
+#ifndef INVERTED
+  // expected-warning at -2 {{'ZipperedTypedefDifferentOffendingDecl_t' is deprecated: first deprecated in macOS 10.14 and first deprecated in iOS (on macOS) 12}}
+#else
+  // expected-warning at -4 {{'ZipperedTypedefDifferentOffendingDecl_t' is deprecated: first deprecated in iOS (on macOS) 12 and first deprecated in macOS 10.14}}
+#endif
 }
 
 __attribute__((availability(macos, introduced=10.10, deprecated=10.14), availability(ios, unavailable)))
@@ -107,12 +128,22 @@ void checkMix() {
   macOSDeprecatedIOSGood();
   // expected-warning at -1 {{'macOSDeprecatedIOSGood' is deprecated: first deprecated in macOS 10.14}}
 
-  bothDeprecatedDiffReplacement(); // expected-warning {{'bothDeprecatedDiffReplacement' is deprecated: first deprecated in macOS 10.14 and first deprecated in iOS (on macOS) 12}}
-  
-  bothUnavailableSameReplacement(); // expected-error {{'bothUnavailableSameReplacement' is unavailable: not available on macOS and not available on iOS (on macOS)}}
-  
+  bothDeprecatedDiffReplacement();
+#ifndef INVERTED
+  // expected-warning at -2 {{'bothDeprecatedDiffReplacement' is deprecated: first deprecated in macOS 10.14 and first deprecated in iOS (on macOS) 12}}
+#else
+  // expected-warning at -4 {{'bothDeprecatedDiffReplacement' is deprecated: first deprecated in iOS (on macOS) 12 and first deprecated in macOS 10.14}}
+#endif
+
+  bothUnavailableSameReplacement();
+#ifndef INVERTED
+  // expected-error at -2 {{'bothUnavailableSameReplacement' is unavailable: not available on macOS and not available on iOS (on macOS)}}
+#else
+  // expected-error at -4 {{'bothUnavailableSameReplacement' is unavailable: not available on iOS (on macOS) and not available on macOS}}
+#endif
+
   justIosUnavailable(); // expected-error {{'justIosUnavailable' is unavailable: not available on iOS (on macOS)}}
-  
+
   justMacOSDeprecated(); // expected-warning {{'justMacOSDeprecated' is deprecated: first deprecated in macOS 10.14}}
 }
 
@@ -129,5 +160,10 @@ struct IntroducedLaterBoth { } __attribute__((availability(macos, introduced=10.
 // expected-note at -1 {{'IntroducedLaterBoth' has been explicitly marked partial here}}
 
 struct NotYetIntroduced { // expected-note {{annotate 'NotYetIntroduced' with an availability attribute to silence this warning}}
-  struct IntroducedLaterBoth x; // expected-warning {{'IntroducedLaterBoth' is only available on macOS 10.15 and iOS (on macOS) 13 or newer}}
+  struct IntroducedLaterBoth x;
+#ifndef INVERTED
+  // expected-warning at -2 {{'IntroducedLaterBoth' is only available on macOS 10.15 and iOS (on macOS) 13 or newer}}
+#else
+  // expected-warning at -4 {{'IntroducedLaterBoth' is only available on iOS (on macOS) 13 and macOS 10.15 or newer}}
+#endif
 };
diff --git a/clang/test/SemaObjC/unguarded-availability-zippered.m b/clang/test/SemaObjC/unguarded-availability-zippered.m
index 62a22fed99184..072d853ac0983 100644
--- a/clang/test/SemaObjC/unguarded-availability-zippered.m
+++ b/clang/test/SemaObjC/unguarded-availability-zippered.m
@@ -1,11 +1,8 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macos10.14 -darwin-target-variant-triple x86_64-apple-ios12-macabi -fblocks -fsyntax-only -verify %s
-
-// XFAIL: *
-#ifdef NO_WARNING
-  // expected-no-diagnostics
-#endif
+// RUN: %clang_cc1 -triple x86_64-apple-ios12-macabi -darwin-target-variant-triple x86_64-apple-macos10.14 -fblocks -fsyntax-only -verify -D INVERTED %s
 
 
+// XFAIL: *
 #define AVAILABLE_PREV_MAC __attribute__((availability(macos, introduced = 10.13)))
 #define AVAILABLE_CURRENT_MAC __attribute__((availability(macos, introduced = 10.14)))
 #define AVAILABLE_NEXT_MAC __attribute__((availability(macos, introduced = 10.15)))
@@ -29,8 +26,13 @@
 void test() {
   bothPreviouslyAvailable();
   bothCurrentlyAvailable();
-  bothWillBeAvailable(); // expected-warning {{'bothWillBeAvailable' is only available on macOS 10.15 and iOS (on macOS) 13 or newer}}
-  // expected-note at -1{{enclose 'bothWillBeAvailable' in an @available check to silence this warning}}
+  bothWillBeAvailable(); // expected-note{{enclose 'bothWillBeAvailable' in an @available check to silence this warning}}
+#ifndef INVERTED
+  // expected-warning at -2 {{'bothWillBeAvailable' is only available on macOS 10.15 and iOS (on macOS) 13 or newer}}
+#else
+  // expected-warning at -4 {{'bothWillBeAvailable' is only available on iOS (on macOS) 13 and macOS 10.15 or newer}}
+#endif
+  
   
   macOSCurrentlyAvailable(); // expected-warning {{'macOSCurrentlyAvailable' is only available on iOS (on macOS) 13 or newer}}
   // expected-note at -1 {{enclose 'macOSCurrentlyAvailable' in an @available check to silence this warning}}
@@ -41,8 +43,12 @@ void test() {
     bothWillBeAvailable(); // expected-warning {{'bothWillBeAvailable' is only available on macOS 10.15 or newer}}
   // expected-note at -1 {{enclose}}
   if (@available(ios 12, *))
-    bothWillBeAvailable(); // expected-warning {{'bothWillBeAvailable' is only available on macOS 10.15 and iOS (on macOS) 13 or newer}}
-  // expected-note at -1 {{enclose}}
+    bothWillBeAvailable(); // expected-note {{enclose}}
+#ifndef INVERTED
+  // expected-warning at -2 {{'bothWillBeAvailable' is only available on macOS 10.15 and iOS (on macOS) 13 or newer}}
+#else
+  // expected-warning at -4 {{'bothWillBeAvailable' is only available on iOS (on macOS) 13 and macOS 10.15 or newer}}
+#endif
   if (@available(macos 10.15, *))
     bothWillBeAvailable(); // expected-warning {{'bothWillBeAvailable' is only available on iOS (on macOS) 13 or newer}}
   // expected-note at -1 {{enclose}}

>From 244b11e51e87888566c810ce72dc50e31a3fd583 Mon Sep 17 00:00:00 2001
From: Erik Pilkington <erik.pilkington at gmail.com>
Date: Mon, 14 Jan 2019 15:45:52 -0800
Subject: [PATCH 07/21] Fix up some tests from Alec's
 ed9ffbf6006c421649d1df6b20838d3af166a064.

rdar://33601513

apple-llvm-split-commit: c752dcb1cc994e31b2b7bbdaed7447c74f3879a5
apple-llvm-split-dir: clang/
---
 clang/test/Sema/attr-availability-zippered.c      |  8 ++++++--
 .../SemaObjC/unguarded-availability-zippered.m    | 15 ++++++++++++---
 2 files changed, 18 insertions(+), 5 deletions(-)

diff --git a/clang/test/Sema/attr-availability-zippered.c b/clang/test/Sema/attr-availability-zippered.c
index b6ca99425a04e..679728776ef0b 100644
--- a/clang/test/Sema/attr-availability-zippered.c
+++ b/clang/test/Sema/attr-availability-zippered.c
@@ -156,8 +156,12 @@ void a() {
 }
 
 
-struct IntroducedLaterBoth { } __attribute__((availability(macos, introduced=10.15), availability(ios, introduced=13)));
-// expected-note at -1 {{'IntroducedLaterBoth' has been explicitly marked partial here}}
+struct IntroducedLaterBoth { } __attribute__((availability(macos, introduced=10.15), availability(ios, introduced=14)));
+#ifndef INVERTED
+// expected-note at -2 {{'IntroducedLaterBoth' has been marked as being introduced in macOS 10.15 here, but the deployment target is macOS 10.14.0}}
+#else
+// expected-note at -4 {{'IntroducedLaterBoth' has been marked as being introduced in macCatalyst 14 here, but the deployment target is macCatalyst 13.0.0}}
+#endif
 
 struct NotYetIntroduced { // expected-note {{annotate 'NotYetIntroduced' with an availability attribute to silence this warning}}
   struct IntroducedLaterBoth x;
diff --git a/clang/test/SemaObjC/unguarded-availability-zippered.m b/clang/test/SemaObjC/unguarded-availability-zippered.m
index 072d853ac0983..49449541729d4 100644
--- a/clang/test/SemaObjC/unguarded-availability-zippered.m
+++ b/clang/test/SemaObjC/unguarded-availability-zippered.m
@@ -14,14 +14,23 @@
 void bothPreviouslyAvailable() AVAILABLE_PREV_MAC AVAILABLE_PREV_IOS;
 void bothCurrentlyAvailable() AVAILABLE_CURRENT_MAC AVAILABLE_CURRENT_IOS;
 void bothWillBeAvailable() AVAILABLE_NEXT_MAC AVAILABLE_NEXT_IOS;
-// expected-note at -1 4 {{'bothWillBeAvailable' has been explicitly marked partial here}}
+#ifndef INVERTED
+// expected-note at -2 3 {{'bothWillBeAvailable' has been marked as being introduced in macOS 10.15 here, but the deployment target is macOS 10.14.0}}
+// expected-note at -3 {{'bothWillBeAvailable' has been marked as being introduced in iOS (on macOS) 14 here, but the deployment target is iOS (on macOS) 13.0.0}}
+#else
+// expected-note at -5 3 {{'bothWillBeAvailable' has been marked as being introduced in iOS (on macOS) 14 here, but the deployment target is iOS (on macOS) 13.0.0}}
+// expected-note at -6 {{'bothWillBeAvailable' has been marked as being introduced in macOS 10.15 here, but the deployment target is macOS 10.14.0}}
+#endif
 
 void macOSCurrentlyAvailable() AVAILABLE_CURRENT_MAC AVAILABLE_NEXT_IOS;
-// expected-note at -1 2 {{'macOSCurrentlyAvailable' has been explicitly marked partial here}}
+// #ifndef INVERTED
+// expected-note at -2 2 {{'macOSCurrentlyAvailable' has been marked as being introduced in iOS (on macOS) 14 here, but the deployment target is iOS (on macOS) 13.0.0}}
+// #else
+// #endif
 
 void macOSNextAvailableiOSNotAvailable() AVAILABLE_NEXT_MAC __attribute__((availability(ios, unavailable)));
 // expected-note at -1 2 {{'macOSNextAvailableiOSNotAvailable' has been explicitly marked unavailable here}}
-// expected-note at -2 {{'macOSNextAvailableiOSNotAvailable' has been explicitly marked partial here}}
+// expected-note at -2 {{'macOSNextAvailableiOSNotAvailable' has been marked as being introduced in macOS 10.15 here, but the deployment target is macOS 10.14.0}}
 
 void test() {
   bothPreviouslyAvailable();

>From 74b0c8b26126d5c54cb1b51171a2fbf78548de1a Mon Sep 17 00:00:00 2001
From: Alex Lorenz <arphaman at gmail.com>
Date: Wed, 20 Mar 2019 18:41:07 -0700
Subject: [PATCH 08/21] Disable zippered availability checking

<rdar://problem/49500719> Reenable clang zippered availability checks

apple-llvm-split-commit: 74611f47917501fe700465ee3f2da8938411f6c2
apple-llvm-split-dir: clang/
---
 clang/lib/AST/DeclBase.cpp                            | 5 +++++
 clang/test/FixIt/fixit-availability-zippered.m        | 2 +-
 clang/test/Sema/attr-availability-zippered.c          | 2 +-
 clang/test/SemaObjC/unguarded-availability-zippered.m | 2 +-
 4 files changed, 8 insertions(+), 3 deletions(-)

diff --git a/clang/lib/AST/DeclBase.cpp b/clang/lib/AST/DeclBase.cpp
index 4e9773f53eaac..1a5a764acffae 100644
--- a/clang/lib/AST/DeclBase.cpp
+++ b/clang/lib/AST/DeclBase.cpp
@@ -791,6 +791,11 @@ AvailabilityResult Decl::getAvailability(StringRef Platform,
     return FTD->getTemplatedDecl()->getAvailability(
         Platform, PlatformMinVersion, Message, RealizedPlatform);
 
+  if (getASTContext().getTargetInfo().hasTargetVariantPlatform() &&
+      getASTContext().getTargetInfo().getTargetVariantPlatform() == Platform) {
+    return AR_Available;
+  }
+
   AvailabilityResult Result = AR_Available;
   std::string ResultMessage;
 
diff --git a/clang/test/FixIt/fixit-availability-zippered.m b/clang/test/FixIt/fixit-availability-zippered.m
index 82fc8397ff21d..87fa48a95d4e7 100644
--- a/clang/test/FixIt/fixit-availability-zippered.m
+++ b/clang/test/FixIt/fixit-availability-zippered.m
@@ -1,6 +1,6 @@
 // RUN: %clang_cc1 -fsyntax-only -Wunguarded-availability -fdiagnostics-parseable-fixits -triple x86_64-apple-macos10.14 -darwin-target-variant-triple x86_64-apple-ios12-macabi %s 2>&1 | FileCheck %s
-
 // XFAIL: *
+
 __attribute__((availability(macOS, introduced=10.15))) __attribute__((availability(ios, introduced=13)))
 int function(void);
 
diff --git a/clang/test/Sema/attr-availability-zippered.c b/clang/test/Sema/attr-availability-zippered.c
index 679728776ef0b..1373434eaf979 100644
--- a/clang/test/Sema/attr-availability-zippered.c
+++ b/clang/test/Sema/attr-availability-zippered.c
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 "-triple" "x86_64-apple-macos10.14" -darwin-target-variant-triple x86_64-apple-ios12-macabi -fsyntax-only -verify %s
 // RUN: %clang_cc1 "-triple" x86_64-apple-ios12-macabi -darwin-target-variant-triple "x86_64-apple-macos10.14"  -fsyntax-only -verify -D INVERTED %s
-
 // XFAIL: *
+
 __attribute__((availability(macos, introduced=10.10, deprecated=10.14), availability(ios, introduced=9, deprecated=12)))
 void bothDeprecated() { // expected-note {{'bothDeprecated' has been explicitly marked deprecated here}}
 }
diff --git a/clang/test/SemaObjC/unguarded-availability-zippered.m b/clang/test/SemaObjC/unguarded-availability-zippered.m
index 49449541729d4..1afbf6caf0d7e 100644
--- a/clang/test/SemaObjC/unguarded-availability-zippered.m
+++ b/clang/test/SemaObjC/unguarded-availability-zippered.m
@@ -1,8 +1,8 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macos10.14 -darwin-target-variant-triple x86_64-apple-ios12-macabi -fblocks -fsyntax-only -verify %s
 // RUN: %clang_cc1 -triple x86_64-apple-ios12-macabi -darwin-target-variant-triple x86_64-apple-macos10.14 -fblocks -fsyntax-only -verify -D INVERTED %s
 
-
 // XFAIL: *
+
 #define AVAILABLE_PREV_MAC __attribute__((availability(macos, introduced = 10.13)))
 #define AVAILABLE_CURRENT_MAC __attribute__((availability(macos, introduced = 10.14)))
 #define AVAILABLE_NEXT_MAC __attribute__((availability(macos, introduced = 10.15)))

>From a65d8d273436f3fead407c41c07283ff05f9599d Mon Sep 17 00:00:00 2001
From: Alex Lorenz <arphaman at gmail.com>
Date: Wed, 20 Mar 2019 17:27:53 -0700
Subject: [PATCH 09/21] Migrate to the new availability checking compiler-rt
 builtins

<rdar://problem/36080874> Marzipan: Add Clang support for working runtime @available checks in zippered TUs

apple-llvm-split-commit: 90b1d6f295500b5108c0f1ac2eb5e96d7f50b7b5
apple-llvm-split-dir: clang/
---
 clang/lib/CodeGen/CGExprScalar.cpp            |  6 +-
 clang/lib/CodeGen/CGObjC.cpp                  | 94 +++++--------------
 clang/lib/CodeGen/CodeGenFunction.h           |  3 +-
 clang/lib/CodeGen/CodeGenModule.h             |  5 +-
 .../CodeGenObjC/availability-check-zippered.m | 38 +++-----
 5 files changed, 41 insertions(+), 105 deletions(-)

diff --git a/clang/lib/CodeGen/CGExprScalar.cpp b/clang/lib/CodeGen/CGExprScalar.cpp
index 5cbf5dce6691f..5be65e13a34f9 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -648,11 +648,7 @@ class ScalarExprEmitter
                CGF.CGM.getTarget().getTargetVariantPlatformMinVersion()))))
       return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
 
-    return CGF.EmitBuiltinAvailable(
-        Version, VariantVersion,
-        /*UseTargetVariantCheck=*/CGF.CGM.getTarget().getTriple().getOS() ==
-                llvm::Triple::IOS &&
-            CGF.CGM.getTarget().getTriple().isMacCatalystEnvironment());
+    return CGF.EmitBuiltinAvailable(Version, VariantVersion);
   }
 
   Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
diff --git a/clang/lib/CodeGen/CGObjC.cpp b/clang/lib/CodeGen/CGObjC.cpp
index 250a6712b4704..969ae90d03339 100644
--- a/clang/lib/CodeGen/CGObjC.cpp
+++ b/clang/lib/CodeGen/CGObjC.cpp
@@ -4013,8 +4013,9 @@ static unsigned getBaseMachOPlatformID(const llvm::Triple &TT) {
   }
 }
 
-static llvm::Value *emitIsPlatformVersionAtLeast(CodeGenFunction &CGF,
-                                                 const VersionTuple &Version) {
+static llvm::Value *
+emitIsPlatformVersionAtLeast(CodeGenFunction &CGF, const VersionTuple &Version,
+                             const VersionTuple &VariantVersion) {
   CodeGenModule &CGM = CGF.CGM;
   // Note: we intend to support multi-platform version checks, so reserve
   // the room for a dual platform checking invocation that will be
@@ -4031,8 +4032,10 @@ static llvm::Value *emitIsPlatformVersionAtLeast(CodeGenFunction &CGF,
     Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, SMin.value_or(0)));
   };
 
-  assert(!Version.empty() && "unexpected empty version");
-  EmitArgs(Version, CGM.getTarget().getTriple());
+  if (!Version.empty())
+    EmitArgs(Version, CGM.getTarget().getTriple());
+  if (!VariantVersion.empty())
+    EmitArgs(VariantVersion, *CGM.getTarget().getDarwinTargetVariantTriple());
 
   if (!CGM.IsPlatformVersionAtLeastFn) {
     llvm::FunctionType *FTy = llvm::FunctionType::get(
@@ -4040,82 +4043,29 @@ static llvm::Value *emitIsPlatformVersionAtLeast(CodeGenFunction &CGF,
         false);
     CGM.IsPlatformVersionAtLeastFn =
         CGM.CreateRuntimeFunction(FTy, "__isPlatformVersionAtLeast");
+    llvm::FunctionType *FTy2 = llvm::FunctionType::get(
+        CGM.Int32Ty,
+        {CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty,
+         CGM.Int32Ty, CGM.Int32Ty, CGM.Int32Ty},
+        false);
+    CGM.IsPlatformOrVariantPlatformVersionAtLeastFn = CGM.CreateRuntimeFunction(
+        FTy2, "__isPlatformOrVariantPlatformVersionAtLeast");
   }
 
-  llvm::Value *Check =
-      CGF.EmitNounwindRuntimeCall(CGM.IsPlatformVersionAtLeastFn, Args);
+  assert((Args.size() == 4 || Args.size() == 8) &&
+         "Expected 4 or 8 argument here!");
+  llvm::Value *Check = CGF.EmitNounwindRuntimeCall(
+      Args.size() == 4 ? CGM.IsPlatformVersionAtLeastFn
+                       : CGM.IsPlatformOrVariantPlatformVersionAtLeastFn,
+      Args);
   return CGF.Builder.CreateICmpNE(Check,
                                   llvm::Constant::getNullValue(CGM.Int32Ty));
 }
 
 llvm::Value *
 CodeGenFunction::EmitBuiltinAvailable(const VersionTuple &Version,
-                                      const VersionTuple &VariantVersion,
-                                      bool UseTargetVariantCheck) {
-  // Darwin uses the new __isPlatformVersionAtLeast family of routines.
-  if (CGM.getTarget().getTriple().isOSDarwin() &&
-      !CGM.getTarget().hasTargetVariantPlatform())
-    return emitIsPlatformVersionAtLeast(*this, Version);
-
-  if (!CGM.IsOSVersionAtLeastFn) {
-    llvm::FunctionType *FTy =
-        llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
-    CGM.IsOSVersionAtLeastFn =
-        CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
-    llvm::FunctionType *FTy2 = llvm::FunctionType::get(Int32Ty, {}, false);
-    CGM.IsTargetPlatformNativeFn =
-        CGM.CreateRuntimeFunction(FTy2, "__isTargetPlatformNative");
-    CGM.IsTargetVariantOSVersionAtLeastFn =
-        CGM.CreateRuntimeFunction(FTy, "__isTargetVariantOSVersionAtLeast");
-  }
-
-  auto EmitVersionArgs = [&](const VersionTuple &V,
-                             llvm::SmallVectorImpl<llvm::Value *> &Args) {
-    if (V.empty())
-      return;
-    std::optional<unsigned> Min = V.getMinor(), SMin = V.getSubminor();
-    Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, V.getMajor()));
-    Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, Min.value_or(0)));
-    Args.push_back(llvm::ConstantInt::get(CGM.Int32Ty, SMin.value_or(0)));
-  };
-
-  llvm::SmallVector<llvm::Value *, 3> Args;
-  llvm::SmallVector<llvm::Value *, 3> VariantArgs;
-  EmitVersionArgs(Version, Args);
-  EmitVersionArgs(VariantVersion, VariantArgs);
-
-  llvm::Value *Check = nullptr;
-  if (!Args.empty()) {
-    Check = EmitNounwindRuntimeCall(UseTargetVariantCheck
-                                        ? CGM.IsTargetVariantOSVersionAtLeastFn
-                                        : CGM.IsOSVersionAtLeastFn,
-                                    Args);
-  }
-  llvm::Value *VariantCheck = nullptr;
-  if (!VariantArgs.empty()) {
-    VariantCheck = EmitNounwindRuntimeCall(
-        UseTargetVariantCheck ? CGM.IsOSVersionAtLeastFn
-                              : CGM.IsTargetVariantOSVersionAtLeastFn,
-        VariantArgs);
-  }
-  llvm::Value *IsNativeCheck = nullptr;
-  if (CGM.getTarget().hasTargetVariantPlatform()) {
-    IsNativeCheck = EmitNounwindRuntimeCall(CGM.IsTargetPlatformNativeFn);
-    IsNativeCheck = Builder.CreateICmpNE(IsNativeCheck,
-                                         llvm::Constant::getNullValue(Int32Ty));
-    if (!Check)
-      Check = llvm::ConstantInt::get(Int32Ty, 1);
-    if (!VariantCheck)
-      VariantCheck = llvm::ConstantInt::get(Int32Ty, 1);
-    // When macOS is the target variant, we should swap the check and the
-    // variant check to ensure that our condition which always checks if the
-    // process is macOS still works.
-    if (UseTargetVariantCheck)
-      std::swap(Check, VariantCheck);
-    Check = Builder.CreateSelect(IsNativeCheck, Check, VariantCheck);
-  }
-
-  return Builder.CreateICmpNE(Check, llvm::Constant::getNullValue(Int32Ty));
+                                      const VersionTuple &VariantVersion) {
+  return emitIsPlatformVersionAtLeast(*this, Version, VariantVersion);
 }
 
 static bool isFoundationNeededForDarwinAvailabilityCheck(
diff --git a/clang/lib/CodeGen/CodeGenFunction.h b/clang/lib/CodeGen/CodeGenFunction.h
index 60ff69ba614b8..3bf62755ac270 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -5029,8 +5029,7 @@ class CodeGenFunction : public CodeGenTypeCache {
   llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
 
   llvm::Value *EmitBuiltinAvailable(const VersionTuple &Version,
-                                    const VersionTuple &VariantVersion,
-                                    bool UseTargetVariantCheck);
+                                    const VersionTuple &VariantVersion);
 
   llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
   llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
diff --git a/clang/lib/CodeGen/CodeGenModule.h b/clang/lib/CodeGen/CodeGenModule.h
index ffca028f65709..a38e9e809797f 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -832,8 +832,9 @@ class CodeGenModule : public CodeGenTypeCache {
   llvm::FunctionCallee IsOSVersionAtLeastFn = nullptr;
   // i32 @__isPlatformVersionAtLeast(i32, i32, i32, i32)
   llvm::FunctionCallee IsPlatformVersionAtLeastFn = nullptr;
-  llvm::FunctionCallee IsTargetPlatformNativeFn = nullptr;
-  llvm::FunctionCallee IsTargetVariantOSVersionAtLeastFn = nullptr;
+  // i32 @__isPlatformOrVariantPlatformVersionAtLeast(i32, i32, i32, i32, i32,
+  // i32, i32, i32)
+  llvm::FunctionCallee IsPlatformOrVariantPlatformVersionAtLeastFn = nullptr;
 
   InstrProfStats &getPGOStats() { return PGOStats; }
   llvm::IndexedInstrProfReader *getPGOReader() const { return PGOReader.get(); }
diff --git a/clang/test/CodeGenObjC/availability-check-zippered.m b/clang/test/CodeGenObjC/availability-check-zippered.m
index 5e164e52ca7b9..05969845052d1 100644
--- a/clang/test/CodeGenObjC/availability-check-zippered.m
+++ b/clang/test/CodeGenObjC/availability-check-zippered.m
@@ -1,42 +1,32 @@
-// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14 -darwin-target-variant-triple x86_64-apple-ios12-macabi -emit-llvm -o - %s | FileCheck %s
-// RUN: %clang_cc1 -triple x86_64-apple-ios12-macabi -darwin-target-variant-triple x86_64-apple-macosx10.14 -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14 -darwin-target-variant-triple x86_64-apple-ios13-macabi -emit-llvm -o - %s | FileCheck --check-prefixes=CHECK,MAC %s
+// RUN: %clang_cc1 -triple x86_64-apple-ios13-macabi -darwin-target-variant-triple x86_64-apple-macosx10.14 -emit-llvm -o - %s | FileCheck --check-prefixes=CHECK,IOS %s
 
-// XFAIL: *
 void use_at_available() {
 
-  // CHECK: call i32 @__isOSVersionAtLeast(i32 10, i32 15, i32 0)
-  // CHECK-NEXT: call i32 @__isTargetPlatformNative()
-  // CHECK-NEXT: icmp ne
-  // CHECK-NEXT: select i1 %{{[0-9]+}}, i32 %{{[0-9]+}}, i32 1
+  // CHECK: call i32 @__isPlatformVersionAtLeast(i32 1, i32 10, i32 15, i32 0)
   // CHECK-NEXT: icmp ne
   if (@available(macos 10.15, *))
     ;
 
-  // CHECK-DAG: call i32 @__isOSVersionAtLeast(i32 10, i32 15, i32 0)
-  // CHECK-DAG: call i32 @__isTargetVariantOSVersionAtLeast(i32 13, i32 0, i32 0)
-  // CHECK: call i32 @__isTargetPlatformNative()
-  // CHECK-NEXT: icmp ne
-  // CHECK-NEXT: select i1 %{{[0-9]+}}, i32 %{{[0-9]+}}, i32 %{{[0-9]+}}
-  // CHECK-NEXT: icmp ne
-  if (@available(macos 10.15, iosmac 13, *))
+  // MAC: call i32 @__isPlatformOrVariantPlatformVersionAtLeast(i32 1, i32 10, i32 15, i32 0, i32 2, i32 13, i32 1, i32 0)
+  // MAC-NEXT: icmp ne
+  // IOS: call i32 @__isPlatformOrVariantPlatformVersionAtLeast(i32 2, i32 13, i32 1, i32 0, i32 1, i32 10, i32 15, i32 0)
+  // IOS-NEXT: icmp ne
+  if (@available(macos 10.15, macCatalyst 13.1, *))
    ;
 
-  // CHECK: call i32 @__isTargetVariantOSVersionAtLeast(i32 13, i32 0, i32 0)
-  // CHECK-NEXT: call i32 @__isTargetPlatformNative()
-  // CHECK-NEXT: icmp ne
-  // CHECK-NEXT: select i1 %{{[0-9]+}}, i32 1, i32 %{{[0-9]+}}
+  // CHECK: call i32 @__isPlatformVersionAtLeast(i32 2, i32 13, i32 1, i32 0)
   // CHECK-NEXT: icmp ne
-  if (@available(ios 13, *))
+  if (@available(ios 13.1, *))
    ;
 
   // This check should be folded: our deployment target is 10.11.
-  // CHECK-NOT: call i32 @__isOSVersionAtLeast
-  // CHECK-NOT: call i32 @__isTargetVariantOSVersionAtLeast
+  // CHECK-NOT: call i32 @__isPlatformVersionAtLeast
+  // CHECK-NOT: call i32 @__isPlatformOrVariantPlatformVersionAtLeast
   // CHECK: br i1 true
   if (__builtin_available(macos 10.11, ios 11, *))
     ;
 }
 
-// CHECK: declare i32 @__isOSVersionAtLeast(i32, i32, i32)
-// CHECK: declare i32 @__isTargetPlatformNative
-// CHECK: declare i32 @__isTargetVariantOSVersionAtLeast(i32, i32, i32)
+// CHECK: declare i32 @__isPlatformVersionAtLeast(i32, i32, i32, i32)
+// CHECK: declare i32 @__isPlatformOrVariantPlatformVersionAtLeast(i32, i32, i32, i32, i32, i32, i32, i32)

>From fc3e47fa3f38100be3b175d80cfddfa6dc26791d Mon Sep 17 00:00:00 2001
From: Alex Lorenz <arphaman at gmail.com>
Date: Fri, 19 Apr 2019 15:53:35 -0700
Subject: [PATCH 10/21] Rename the iOS (for macOS) availability description to
 UIKit for macOS

apple-llvm-split-commit: 805d32d9975ca563959b8ea1e0a7aaeee3c42606
apple-llvm-split-dir: clang/
---
 clang/test/Sema/attr-availability-zippered.c  | 40 +++++++++----------
 .../unguarded-availability-zippered.m         | 24 +++++------
 2 files changed, 32 insertions(+), 32 deletions(-)

diff --git a/clang/test/Sema/attr-availability-zippered.c b/clang/test/Sema/attr-availability-zippered.c
index 1373434eaf979..fd097f78186e9 100644
--- a/clang/test/Sema/attr-availability-zippered.c
+++ b/clang/test/Sema/attr-availability-zippered.c
@@ -22,12 +22,12 @@ void checkDeprecated() {
   // The compiler may warn here if the deployment target is older than the version introduced
   bothDeprecated();
 #ifndef INVERTED
-  // expected-warning at -2 {{'bothDeprecated' is deprecated: first deprecated in macOS 10.14 and first deprecated in iOS (on macOS) 12}}
+  // expected-warning at -2 {{'bothDeprecated' is deprecated: first deprecated in macOS 10.14 and first deprecated in UIKit for macOS 12}}
 #else
-  // expected-warning at -4 {{'bothDeprecated' is deprecated: first deprecated in iOS (on macOS) 12 and first deprecated in macOS 10.14}}
+  // expected-warning at -4 {{'bothDeprecated' is deprecated: first deprecated in UIKit for macOS 12 and first deprecated in macOS 10.14}}
 #endif
   macOSDeprecated(); // expected-warning {{'macOSDeprecated' is deprecated: first deprecated in macOS 10.14}}
-  iOSDeprecated();   // expected-warning {{'iOSDeprecated' is deprecated: first deprecated in iOS (on macOS) 12}}
+  iOSDeprecated();   // expected-warning {{'iOSDeprecated' is deprecated: first deprecated in UIKit for macOS 12}}
   bothNotDeprecated();
 }
 
@@ -53,25 +53,25 @@ void bothObsoleted() { // expected-note {{'bothObsoleted' has been explicitly ma
 void checkUnavailable() {
   bothUnavailable();
 #ifndef INVERTED
-  // expected-error at -2 {{'bothUnavailable' is unavailable: not available on macOS and not available on iOS (on macOS)}}
+  // expected-error at -2 {{'bothUnavailable' is unavailable: not available on macOS and not available on UIKit for macOS}}
 #else
-  // expected-error at -4 {{'bothUnavailable' is unavailable: not available on iOS (on macOS) and not available on macOS}}
+  // expected-error at -4 {{'bothUnavailable' is unavailable: not available on UIKit for macOS and not available on macOS}}
 #endif
-  iosUnavailable(); // expected-error {{'iosUnavailable' is unavailable: not available on iOS (on macOS)}}
+  iosUnavailable(); // expected-error {{'iosUnavailable' is unavailable: not available on UIKit for macOS}}
   macOSUnavailable(); // expected-error {{'macOSUnavailable' is unavailable: not available on macOS}}
   bothAvailable();
   
   bothObsoleted();
 #ifndef INVERTED
-  // expected-error at -2 {{'bothObsoleted' is unavailable: obsoleted in macOS 10.14 and obsoleted in iOS (on macOS) 12}}
+  // expected-error at -2 {{'bothObsoleted' is unavailable: obsoleted in macOS 10.14 and obsoleted in UIKit for macOS 12}}
 #else
-  // expected-error at -4 {{'bothObsoleted' is unavailable: obsoleted in iOS (on macOS) 12 and obsoleted in macOS 10.14}}
+  // expected-error at -4 {{'bothObsoleted' is unavailable: obsoleted in UIKit for macOS 12 and obsoleted in macOS 10.14}}
 #endif
 }
 
 __attribute__((availability(macos, introduced=10.10, deprecated=10.14)))
 typedef struct ZipperedTypedefDifferentOffendingDecl { // expected-note {{'ZipperedTypedefDifferentOffendingDecl' has been explicitly marked deprecated here}}
-// expected-warning at -1 {{'ZipperedTypedefDifferentOffendingDecl' is deprecated: first deprecated in iOS (on macOS) 12}}
+// expected-warning at -1 {{'ZipperedTypedefDifferentOffendingDecl' is deprecated: first deprecated in UIKit for macOS 12}}
 // expected-note at -2 {{'ZipperedTypedefDifferentOffendingDecl' has been explicitly marked deprecated here}}
   int x;
 } __attribute__((availability(ios, introduced=9, deprecated=12))) ZipperedTypedefDifferentOffendingDecl_t; // expected-note {{'ZipperedTypedefDifferentOffendingDecl_t' has been explicitly marked deprecated here}}
@@ -79,9 +79,9 @@ typedef struct ZipperedTypedefDifferentOffendingDecl { // expected-note {{'Zippe
 void checkZipperDiffOffendingDecl() {
   ZipperedTypedefDifferentOffendingDecl_t tt;
 #ifndef INVERTED
-  // expected-warning at -2 {{'ZipperedTypedefDifferentOffendingDecl_t' is deprecated: first deprecated in macOS 10.14 and first deprecated in iOS (on macOS) 12}}
+  // expected-warning at -2 {{'ZipperedTypedefDifferentOffendingDecl_t' is deprecated: first deprecated in macOS 10.14 and first deprecated in UIKit for macOS 12}}
 #else
-  // expected-warning at -4 {{'ZipperedTypedefDifferentOffendingDecl_t' is deprecated: first deprecated in iOS (on macOS) 12 and first deprecated in macOS 10.14}}
+  // expected-warning at -4 {{'ZipperedTypedefDifferentOffendingDecl_t' is deprecated: first deprecated in UIKit for macOS 12 and first deprecated in macOS 10.14}}
 #endif
 }
 
@@ -119,30 +119,30 @@ void justMacOSDeprecated() { // expected-note {{'justMacOSDeprecated' has been e
 
 void checkMix() {
   mixUnavailableAndDeprecated();
-  // expected-error at -1 {{'mixUnavailableAndDeprecated' is unavailable: not available on iOS (on macOS)}}
+  // expected-error at -1 {{'mixUnavailableAndDeprecated' is unavailable: not available on UIKit for macOS}}
   // expected-warning at -2 {{'mixUnavailableAndDeprecated' is deprecated: first deprecated in macOS 10.14}}
   
   iOSUnavailableMacGood();
-  // expected-error at -1 {{'iOSUnavailableMacGood' is unavailable: not available on iOS (on macOS)}}
+  // expected-error at -1 {{'iOSUnavailableMacGood' is unavailable: not available on UIKit for macOS}}
   
   macOSDeprecatedIOSGood();
   // expected-warning at -1 {{'macOSDeprecatedIOSGood' is deprecated: first deprecated in macOS 10.14}}
 
   bothDeprecatedDiffReplacement();
 #ifndef INVERTED
-  // expected-warning at -2 {{'bothDeprecatedDiffReplacement' is deprecated: first deprecated in macOS 10.14 and first deprecated in iOS (on macOS) 12}}
+  // expected-warning at -2 {{'bothDeprecatedDiffReplacement' is deprecated: first deprecated in macOS 10.14 and first deprecated in UIKit for macOS 12}}
 #else
-  // expected-warning at -4 {{'bothDeprecatedDiffReplacement' is deprecated: first deprecated in iOS (on macOS) 12 and first deprecated in macOS 10.14}}
+  // expected-warning at -4 {{'bothDeprecatedDiffReplacement' is deprecated: first deprecated in UIKit for macOS 12 and first deprecated in macOS 10.14}}
 #endif
 
   bothUnavailableSameReplacement();
 #ifndef INVERTED
-  // expected-error at -2 {{'bothUnavailableSameReplacement' is unavailable: not available on macOS and not available on iOS (on macOS)}}
+  // expected-error at -2 {{'bothUnavailableSameReplacement' is unavailable: not available on macOS and not available on UIKit for macOS}}
 #else
-  // expected-error at -4 {{'bothUnavailableSameReplacement' is unavailable: not available on iOS (on macOS) and not available on macOS}}
+  // expected-error at -4 {{'bothUnavailableSameReplacement' is unavailable: not available on UIKit for macOS and not available on macOS}}
 #endif
 
-  justIosUnavailable(); // expected-error {{'justIosUnavailable' is unavailable: not available on iOS (on macOS)}}
+  justIosUnavailable(); // expected-error {{'justIosUnavailable' is unavailable: not available on UIKit for macOS}}
 
   justMacOSDeprecated(); // expected-warning {{'justMacOSDeprecated' is deprecated: first deprecated in macOS 10.14}}
 }
@@ -166,8 +166,8 @@ struct IntroducedLaterBoth { } __attribute__((availability(macos, introduced=10.
 struct NotYetIntroduced { // expected-note {{annotate 'NotYetIntroduced' with an availability attribute to silence this warning}}
   struct IntroducedLaterBoth x;
 #ifndef INVERTED
-  // expected-warning at -2 {{'IntroducedLaterBoth' is only available on macOS 10.15 and iOS (on macOS) 13 or newer}}
+  // expected-warning at -2 {{'IntroducedLaterBoth' is only available on macOS 10.15 and UIKit for macOS 13 or newer}}
 #else
-  // expected-warning at -4 {{'IntroducedLaterBoth' is only available on iOS (on macOS) 13 and macOS 10.15 or newer}}
+  // expected-warning at -4 {{'IntroducedLaterBoth' is only available on UIKit for macOS 13 and macOS 10.15 or newer}}
 #endif
 };
diff --git a/clang/test/SemaObjC/unguarded-availability-zippered.m b/clang/test/SemaObjC/unguarded-availability-zippered.m
index 1afbf6caf0d7e..e3c6cb39dd4af 100644
--- a/clang/test/SemaObjC/unguarded-availability-zippered.m
+++ b/clang/test/SemaObjC/unguarded-availability-zippered.m
@@ -16,15 +16,15 @@
 void bothWillBeAvailable() AVAILABLE_NEXT_MAC AVAILABLE_NEXT_IOS;
 #ifndef INVERTED
 // expected-note at -2 3 {{'bothWillBeAvailable' has been marked as being introduced in macOS 10.15 here, but the deployment target is macOS 10.14.0}}
-// expected-note at -3 {{'bothWillBeAvailable' has been marked as being introduced in iOS (on macOS) 14 here, but the deployment target is iOS (on macOS) 13.0.0}}
+// expected-note at -3 {{'bothWillBeAvailable' has been marked as being introduced in UIKit for macOS 14 here, but the deployment target is UIKit for macOS 13.0.0}}
 #else
-// expected-note at -5 3 {{'bothWillBeAvailable' has been marked as being introduced in iOS (on macOS) 14 here, but the deployment target is iOS (on macOS) 13.0.0}}
+// expected-note at -5 3 {{'bothWillBeAvailable' has been marked as being introduced in UIKit for macOS 14 here, but the deployment target is UIKit for macOS 13.0.0}}
 // expected-note at -6 {{'bothWillBeAvailable' has been marked as being introduced in macOS 10.15 here, but the deployment target is macOS 10.14.0}}
 #endif
 
 void macOSCurrentlyAvailable() AVAILABLE_CURRENT_MAC AVAILABLE_NEXT_IOS;
 // #ifndef INVERTED
-// expected-note at -2 2 {{'macOSCurrentlyAvailable' has been marked as being introduced in iOS (on macOS) 14 here, but the deployment target is iOS (on macOS) 13.0.0}}
+// expected-note at -2 2 {{'macOSCurrentlyAvailable' has been marked as being introduced in UIKit for macOS 14 here, but the deployment target is UIKit for macOS 13.0.0}}
 // #else
 // #endif
 
@@ -37,13 +37,13 @@ void test() {
   bothCurrentlyAvailable();
   bothWillBeAvailable(); // expected-note{{enclose 'bothWillBeAvailable' in an @available check to silence this warning}}
 #ifndef INVERTED
-  // expected-warning at -2 {{'bothWillBeAvailable' is only available on macOS 10.15 and iOS (on macOS) 13 or newer}}
+  // expected-warning at -2 {{'bothWillBeAvailable' is only available on macOS 10.15 and UIKit for macOS 13 or newer}}
 #else
-  // expected-warning at -4 {{'bothWillBeAvailable' is only available on iOS (on macOS) 13 and macOS 10.15 or newer}}
+  // expected-warning at -4 {{'bothWillBeAvailable' is only available on UIKit for macOS 13 and macOS 10.15 or newer}}
 #endif
   
   
-  macOSCurrentlyAvailable(); // expected-warning {{'macOSCurrentlyAvailable' is only available on iOS (on macOS) 13 or newer}}
+  macOSCurrentlyAvailable(); // expected-warning {{'macOSCurrentlyAvailable' is only available on UIKit for macOS 13 or newer}}
   // expected-note at -1 {{enclose 'macOSCurrentlyAvailable' in an @available check to silence this warning}}
 
   if (@available(ios 13, macos 10.15, *))
@@ -54,25 +54,25 @@ void test() {
   if (@available(ios 12, *))
     bothWillBeAvailable(); // expected-note {{enclose}}
 #ifndef INVERTED
-  // expected-warning at -2 {{'bothWillBeAvailable' is only available on macOS 10.15 and iOS (on macOS) 13 or newer}}
+  // expected-warning at -2 {{'bothWillBeAvailable' is only available on macOS 10.15 and UIKit for macOS 13 or newer}}
 #else
-  // expected-warning at -4 {{'bothWillBeAvailable' is only available on iOS (on macOS) 13 and macOS 10.15 or newer}}
+  // expected-warning at -4 {{'bothWillBeAvailable' is only available on UIKit for macOS 13 and macOS 10.15 or newer}}
 #endif
   if (@available(macos 10.15, *))
-    bothWillBeAvailable(); // expected-warning {{'bothWillBeAvailable' is only available on iOS (on macOS) 13 or newer}}
+    bothWillBeAvailable(); // expected-warning {{'bothWillBeAvailable' is only available on UIKit for macOS 13 or newer}}
   // expected-note at -1 {{enclose}}
 
   if (@available(macos 10.15, *))
-    macOSCurrentlyAvailable(); // expected-warning {{'macOSCurrentlyAvailable' is only available on iOS (on macOS) 13 or newer}}
+    macOSCurrentlyAvailable(); // expected-warning {{'macOSCurrentlyAvailable' is only available on UIKit for macOS 13 or newer}}
   // expected-note at -1 {{enclose}}
   if (@available(ios 13, *))
     macOSCurrentlyAvailable();
 
   macOSNextAvailableiOSNotAvailable();
-  // expected-error at -1 {{'macOSNextAvailableiOSNotAvailable' is unavailable: not available on iOS (on macOS)}}
+  // expected-error at -1 {{'macOSNextAvailableiOSNotAvailable' is unavailable: not available on UIKit for macOS}}
   // expected-warning at -2 {{'macOSNextAvailableiOSNotAvailable' is only available on macOS 10.15 or newer}}
   // expected-note at -3 {{enclose}}
 
   if (@available(macos 10.15, *))
-    macOSNextAvailableiOSNotAvailable(); // expected-error {{'macOSNextAvailableiOSNotAvailable' is unavailable: not available on iOS (on macOS)}}
+    macOSNextAvailableiOSNotAvailable(); // expected-error {{'macOSNextAvailableiOSNotAvailable' is unavailable: not available on UIKit for macOS}}
 }

>From 941da4a5ab276b2304c18fe7c00c064a97025378 Mon Sep 17 00:00:00 2001
From: Alex Lorenz <arphaman at gmail.com>
Date: Mon, 22 Apr 2019 16:07:26 -0700
Subject: [PATCH 11/21] Disable zippered checks for
 __attribute__((unavailable)) and __attribute__((deprecated))

<rdar://problem/45654463> Clang complains that there's no call to a designated initializer even though a noreturn function is provably called
<rdar://problem/49500719> Reenable clang zippered availability checks

apple-llvm-split-commit: a642e9f053d1699f0052ac832de1b7b308f4fb8c
apple-llvm-split-dir: clang/
---
 clang/lib/AST/DeclBase.cpp | 12 ++----------
 1 file changed, 2 insertions(+), 10 deletions(-)

diff --git a/clang/lib/AST/DeclBase.cpp b/clang/lib/AST/DeclBase.cpp
index 1a5a764acffae..8515092e46300 100644
--- a/clang/lib/AST/DeclBase.cpp
+++ b/clang/lib/AST/DeclBase.cpp
@@ -860,21 +860,13 @@ VersionTuple Decl::getVersionIntroduced() const {
 bool Decl::isDeprecatedInAnyTargetPlatform(std::string *Message) const {
   const TargetInfo &TI = getASTContext().getTargetInfo();
   return getAvailability(TI.getPlatformName(), TI.getPlatformMinVersion()) ==
-             AR_Deprecated ||
-         (TI.hasTargetVariantPlatform() &&
-          getAvailability(TI.getTargetVariantPlatform(),
-                          TI.getTargetVariantPlatformMinVersion()) ==
-              AR_Deprecated);
+         AR_Deprecated;
 }
 
 bool Decl::isUnavailableForAllTargetPlatforms() const {
   const TargetInfo &TI = getASTContext().getTargetInfo();
   return getAvailability(TI.getPlatformName(), TI.getPlatformMinVersion()) ==
-             AR_Unavailable &&
-         (!getASTContext().getTargetInfo().hasTargetVariantPlatform() ||
-          getAvailability(TI.getTargetVariantPlatform(),
-                          TI.getTargetVariantPlatformMinVersion()) ==
-              AR_Unavailable);
+         AR_Unavailable;
 }
 
 bool Decl::canBeWeakImported(bool &IsDefinition) const {

>From 19bde182abd9bf92842f1a086cfc911e6b033d8e Mon Sep 17 00:00:00 2001
From: Alex Lorenz <arphaman at gmail.com>
Date: Wed, 1 May 2019 11:20:05 -0700
Subject: [PATCH 12/21] Improve IRGen check folding for zippered availability
 checks

rdar://50375346

apple-llvm-split-commit: b44e25f5d44343e33e24319811ef2714d8d5d06b
apple-llvm-split-dir: clang/
---
 clang/lib/CodeGen/CGExprScalar.cpp            | 16 +++++++-------
 .../CodeGenObjC/availability-check-zippered.m | 21 ++++++++++++++++++-
 2 files changed, 29 insertions(+), 8 deletions(-)

diff --git a/clang/lib/CodeGen/CGExprScalar.cpp b/clang/lib/CodeGen/CGExprScalar.cpp
index 5be65e13a34f9..ac19c58dbc684 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -639,13 +639,15 @@ class ScalarExprEmitter
 
     // If we're checking for a platform older than our minimum deployment
     // target, we can fold the check away.
-    if ((Version.empty() && VariantVersion.empty()) ||
-        (!Version.empty() &&
-         Version <= CGF.CGM.getTarget().getPlatformMinVersion() &&
-         (!CGF.CGM.getTarget().hasTargetVariantPlatform() ||
-          (!VariantVersion.empty() &&
-           VariantVersion <=
-               CGF.CGM.getTarget().getTargetVariantPlatformMinVersion()))))
+    if (!Version.empty() &&
+        Version <= CGF.CGM.getTarget().getPlatformMinVersion())
+      Version = VersionTuple();
+    if (!VariantVersion.empty() &&
+        VariantVersion <=
+            CGF.CGM.getTarget().getTargetVariantPlatformMinVersion())
+      VariantVersion = VersionTuple();
+
+    if (Version.empty() && VariantVersion.empty())
       return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
 
     return CGF.EmitBuiltinAvailable(Version, VariantVersion);
diff --git a/clang/test/CodeGenObjC/availability-check-zippered.m b/clang/test/CodeGenObjC/availability-check-zippered.m
index 05969845052d1..f6ccb2fe1d55d 100644
--- a/clang/test/CodeGenObjC/availability-check-zippered.m
+++ b/clang/test/CodeGenObjC/availability-check-zippered.m
@@ -20,12 +20,31 @@ void use_at_available() {
   if (@available(ios 13.1, *))
    ;
 
-  // This check should be folded: our deployment target is 10.11.
+  // These checks should be partially folded
+  // CHECK: call i32 @__isPlatformVersionAtLeast(i32 2, i32 13, i32 1, i32 0)
+  // CHECK-NEXT: icmp ne
+  if (@available(macos 10.11, macCatalyst 13.1, *))
+    ;
+
+  // CHECK: call i32 @__isPlatformVersionAtLeast(i32 1, i32 10, i32 15, i32 0)
+  // CHECK-NEXT: icmp ne
+  if (@available(macos 10.15, ios 11, *))
+    ;
+
+  // These checks should be folded: our deployment target is higher.
   // CHECK-NOT: call i32 @__isPlatformVersionAtLeast
   // CHECK-NOT: call i32 @__isPlatformOrVariantPlatformVersionAtLeast
   // CHECK: br i1 true
   if (__builtin_available(macos 10.11, ios 11, *))
     ;
+
+  // CHECK: br i1 true
+  if (@available(ios 11, *))
+    ;
+
+  // CHECK: br i1 true
+  if (@available(macos 10.11, *))
+    ;
 }
 
 // CHECK: declare i32 @__isPlatformVersionAtLeast(i32, i32, i32, i32)

>From 53880d5768240b2ab2e749053a19d422c4572bf3 Mon Sep 17 00:00:00 2001
From: Alex Lorenz <arphaman at gmail.com>
Date: Wed, 15 May 2019 15:27:11 -0700
Subject: [PATCH 13/21] Revert "Disable zippered availability checking"

This reverts commit 74611f47917501fe700465ee3f2da8938411f6c2.

apple-llvm-split-commit: 6e0cac80b3f8cc1f428838b08ef2a1950981379b
apple-llvm-split-dir: clang/
---
 clang/lib/AST/DeclBase.cpp                      | 17 ++++++++++-------
 clang/test/FixIt/fixit-availability-zippered.m  |  6 +++---
 clang/test/Sema/attr-availability-zippered.c    |  2 +-
 .../SemaObjC/unguarded-availability-zippered.m  |  2 +-
 4 files changed, 15 insertions(+), 12 deletions(-)

diff --git a/clang/lib/AST/DeclBase.cpp b/clang/lib/AST/DeclBase.cpp
index 8515092e46300..4e9773f53eaac 100644
--- a/clang/lib/AST/DeclBase.cpp
+++ b/clang/lib/AST/DeclBase.cpp
@@ -791,11 +791,6 @@ AvailabilityResult Decl::getAvailability(StringRef Platform,
     return FTD->getTemplatedDecl()->getAvailability(
         Platform, PlatformMinVersion, Message, RealizedPlatform);
 
-  if (getASTContext().getTargetInfo().hasTargetVariantPlatform() &&
-      getASTContext().getTargetInfo().getTargetVariantPlatform() == Platform) {
-    return AR_Available;
-  }
-
   AvailabilityResult Result = AR_Available;
   std::string ResultMessage;
 
@@ -860,13 +855,21 @@ VersionTuple Decl::getVersionIntroduced() const {
 bool Decl::isDeprecatedInAnyTargetPlatform(std::string *Message) const {
   const TargetInfo &TI = getASTContext().getTargetInfo();
   return getAvailability(TI.getPlatformName(), TI.getPlatformMinVersion()) ==
-         AR_Deprecated;
+             AR_Deprecated ||
+         (TI.hasTargetVariantPlatform() &&
+          getAvailability(TI.getTargetVariantPlatform(),
+                          TI.getTargetVariantPlatformMinVersion()) ==
+              AR_Deprecated);
 }
 
 bool Decl::isUnavailableForAllTargetPlatforms() const {
   const TargetInfo &TI = getASTContext().getTargetInfo();
   return getAvailability(TI.getPlatformName(), TI.getPlatformMinVersion()) ==
-         AR_Unavailable;
+             AR_Unavailable &&
+         (!getASTContext().getTargetInfo().hasTargetVariantPlatform() ||
+          getAvailability(TI.getTargetVariantPlatform(),
+                          TI.getTargetVariantPlatformMinVersion()) ==
+              AR_Unavailable);
 }
 
 bool Decl::canBeWeakImported(bool &IsDefinition) const {
diff --git a/clang/test/FixIt/fixit-availability-zippered.m b/clang/test/FixIt/fixit-availability-zippered.m
index 87fa48a95d4e7..e27636a1e388a 100644
--- a/clang/test/FixIt/fixit-availability-zippered.m
+++ b/clang/test/FixIt/fixit-availability-zippered.m
@@ -1,12 +1,12 @@
 // RUN: %clang_cc1 -fsyntax-only -Wunguarded-availability -fdiagnostics-parseable-fixits -triple x86_64-apple-macos10.14 -darwin-target-variant-triple x86_64-apple-ios12-macabi %s 2>&1 | FileCheck %s
-// XFAIL: *
 
+// XFAIL: *
 __attribute__((availability(macOS, introduced=10.15))) __attribute__((availability(ios, introduced=13)))
 int function(void);
 
 int use() {
   function();
-// CHECK: fix-it:{{.*}}:{[[@LINE-1]]:3-[[@LINE-1]]:3}:"if (@available(macOS 10.15, iOSMac 13, *)) {\n      "
+// CHECK: fix-it:{{.*}}:{[[@LINE-1]]:3-[[@LINE-1]]:3}:"if (@available(macOS 10.15, uikitformac 13, *)) {\n      "
 // CHECK-NEXT: fix-it:{{.*}}:{[[@LINE-2]]:14-[[@LINE-2]]:14}:"\n  } else {\n      // Fallback on earlier versions\n  }"
 }
 
@@ -18,6 +18,6 @@ @interface NewClass
 
 @interface OldButOfferFixit
 @property(copy) NewClass *prop;
-// CHECK: fix-it:{{.*}}:{[[@LINE-2]]:1-[[@LINE-2]]:1}:"API_AVAILABLE(macos(10.15), iosmac(13))\n"
+// CHECK: fix-it:{{.*}}:{[[@LINE-2]]:1-[[@LINE-2]]:1}:"API_AVAILABLE(macos(10.15), uikitformac(13))\n"
 
 @end
diff --git a/clang/test/Sema/attr-availability-zippered.c b/clang/test/Sema/attr-availability-zippered.c
index fd097f78186e9..223b15b17cd19 100644
--- a/clang/test/Sema/attr-availability-zippered.c
+++ b/clang/test/Sema/attr-availability-zippered.c
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 "-triple" "x86_64-apple-macos10.14" -darwin-target-variant-triple x86_64-apple-ios12-macabi -fsyntax-only -verify %s
 // RUN: %clang_cc1 "-triple" x86_64-apple-ios12-macabi -darwin-target-variant-triple "x86_64-apple-macos10.14"  -fsyntax-only -verify -D INVERTED %s
-// XFAIL: *
 
+// XFAIL: *
 __attribute__((availability(macos, introduced=10.10, deprecated=10.14), availability(ios, introduced=9, deprecated=12)))
 void bothDeprecated() { // expected-note {{'bothDeprecated' has been explicitly marked deprecated here}}
 }
diff --git a/clang/test/SemaObjC/unguarded-availability-zippered.m b/clang/test/SemaObjC/unguarded-availability-zippered.m
index e3c6cb39dd4af..bc35654d69e0c 100644
--- a/clang/test/SemaObjC/unguarded-availability-zippered.m
+++ b/clang/test/SemaObjC/unguarded-availability-zippered.m
@@ -1,8 +1,8 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macos10.14 -darwin-target-variant-triple x86_64-apple-ios12-macabi -fblocks -fsyntax-only -verify %s
 // RUN: %clang_cc1 -triple x86_64-apple-ios12-macabi -darwin-target-variant-triple x86_64-apple-macos10.14 -fblocks -fsyntax-only -verify -D INVERTED %s
 
-// XFAIL: *
 
+// XFAIL: *
 #define AVAILABLE_PREV_MAC __attribute__((availability(macos, introduced = 10.13)))
 #define AVAILABLE_CURRENT_MAC __attribute__((availability(macos, introduced = 10.14)))
 #define AVAILABLE_NEXT_MAC __attribute__((availability(macos, introduced = 10.15)))

>From e5b290c2308ad7bb33b8ed7faae8af32e8fca714 Mon Sep 17 00:00:00 2001
From: Alex Lorenz <arphaman at gmail.com>
Date: Wed, 15 May 2019 17:00:49 -0700
Subject: [PATCH 14/21] Turn on zippered availability checks only when
 -ftarget-variant-availability-checks is enabled

apple-llvm-split-commit: 6fcf59c2b3fadaf63100d3e1a2e3a975c6e7e26e
apple-llvm-split-dir: clang/
---
 clang/include/clang/Basic/LangOptions.def           |  1 +
 clang/include/clang/Options/Options.td              |  6 ++++++
 clang/lib/AST/DeclBase.cpp                          | 13 +++++++++++--
 clang/lib/Driver/ToolChains/Clang.cpp               |  5 +++++
 .../darwin-target-variant-availability-checks.c     | 10 ++++++++++
 clang/test/FixIt/fixit-availability-zippered.m      |  2 +-
 clang/test/Sema/attr-availability-zippered.c        |  4 ++--
 .../unguarded-availability-zippered-disabled.m      | 12 ++++++++++++
 .../test/SemaObjC/unguarded-availability-zippered.m |  4 ++--
 9 files changed, 50 insertions(+), 7 deletions(-)
 create mode 100644 clang/test/Driver/darwin-target-variant-availability-checks.c
 create mode 100644 clang/test/SemaObjC/unguarded-availability-zippered-disabled.m

diff --git a/clang/include/clang/Basic/LangOptions.def b/clang/include/clang/Basic/LangOptions.def
index f945b60b6966d..8cb0ccbf140ea 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -297,6 +297,7 @@ LANGOPT(ConstantNSNumberLiterals , 1, 0, NotCompatible, "constant number literal
 LANGOPT(ConstantNSArrayLiterals , 1, 0, NotCompatible, "constant array literals")
 LANGOPT(ConstantNSDictionaryLiterals , 1, 0, NotCompatible, "constant dictionary literals")
 LANGOPT(InlineVisibilityHidden , 1, 0, Benign, "hidden visibility for inline C++ methods")
+LANGOPT(ZipperedAvailabilityChecks , 1, 0, NotCompatible, "check availability for target variant platform")
 ENUM_LANGOPT(DefaultVisibilityExportMapping, DefaultVisiblityExportMapping, 2, DefaultVisiblityExportMapping::None, Benign, "controls mapping of default visibility to dllexport")
 LANGOPT(IgnoreXCOFFVisibility, 1, 0, Benign, "All the visibility attributes that are specified in the source code are ignored in aix XCOFF.")
 LANGOPT(VisibilityInlinesHiddenStaticLocalVar, 1, 0, Benign,
diff --git a/clang/include/clang/Options/Options.td b/clang/include/clang/Options/Options.td
index eb5a009b5628c..c4de349f2ffa9 100644
--- a/clang/include/clang/Options/Options.td
+++ b/clang/include/clang/Options/Options.td
@@ -2071,6 +2071,12 @@ def fapinotes_swift_version : Joined<["-"], "fapinotes-swift-version=">,
   MetaVarName<"<version>">,
   HelpText<"Specify the Swift version to use when filtering API notes">;
 
+defm target_variant_availability_checks : BoolOption<"f", "target-variant-availability-checks",
+  LangOpts<"ZipperedAvailabilityChecks">, DefaultFalse,
+  PosFlag<SetTrue, [], [ClangOption, CC1Option],
+          "Enable availability checks for the target variant platform">,
+  NegFlag<SetFalse>>, Group<f_clang_Group>;
+
 defm bounds_safety : BoolFOption<
   "experimental-bounds-safety",
   LangOpts<"BoundsSafety">, DefaultFalse,
diff --git a/clang/lib/AST/DeclBase.cpp b/clang/lib/AST/DeclBase.cpp
index 4e9773f53eaac..c8974880b1442 100644
--- a/clang/lib/AST/DeclBase.cpp
+++ b/clang/lib/AST/DeclBase.cpp
@@ -791,6 +791,13 @@ AvailabilityResult Decl::getAvailability(StringRef Platform,
     return FTD->getTemplatedDecl()->getAvailability(
         Platform, PlatformMinVersion, Message, RealizedPlatform);
 
+  const auto &Ctx = getASTContext();
+  if (!Ctx.getLangOpts().ZipperedAvailabilityChecks &&
+      Ctx.getTargetInfo().hasTargetVariantPlatform() &&
+      Ctx.getTargetInfo().getTargetVariantPlatform() == Platform) {
+    return AR_Available;
+  }
+
   AvailabilityResult Result = AR_Available;
   std::string ResultMessage;
 
@@ -856,7 +863,8 @@ bool Decl::isDeprecatedInAnyTargetPlatform(std::string *Message) const {
   const TargetInfo &TI = getASTContext().getTargetInfo();
   return getAvailability(TI.getPlatformName(), TI.getPlatformMinVersion()) ==
              AR_Deprecated ||
-         (TI.hasTargetVariantPlatform() &&
+         (getASTContext().getLangOpts().ZipperedAvailabilityChecks &&
+          TI.hasTargetVariantPlatform() &&
           getAvailability(TI.getTargetVariantPlatform(),
                           TI.getTargetVariantPlatformMinVersion()) ==
               AR_Deprecated);
@@ -866,7 +874,8 @@ bool Decl::isUnavailableForAllTargetPlatforms() const {
   const TargetInfo &TI = getASTContext().getTargetInfo();
   return getAvailability(TI.getPlatformName(), TI.getPlatformMinVersion()) ==
              AR_Unavailable &&
-         (!getASTContext().getTargetInfo().hasTargetVariantPlatform() ||
+         (!(getASTContext().getLangOpts().ZipperedAvailabilityChecks &&
+            getASTContext().getTargetInfo().hasTargetVariantPlatform()) ||
           getAvailability(TI.getTargetVariantPlatform(),
                           TI.getTargetVariantPlatformMinVersion()) ==
               AR_Unavailable);
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp
index b081265412752..885d028abc078 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6905,6 +6905,11 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
       A->render(Args, CmdArgs);
   }
 
+  if (Args.hasFlag(options::OPT_ftarget_variant_availability_checks,
+                   options::OPT_fno_target_variant_availability_checks,
+                   /*Default=*/false))
+    CmdArgs.push_back("-ftarget-variant-availability-checks");
+
   if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
     CmdArgs.push_back("-fconstant-string-class");
     CmdArgs.push_back(A->getValue());
diff --git a/clang/test/Driver/darwin-target-variant-availability-checks.c b/clang/test/Driver/darwin-target-variant-availability-checks.c
new file mode 100644
index 0000000000000..ace433f788a59
--- /dev/null
+++ b/clang/test/Driver/darwin-target-variant-availability-checks.c
@@ -0,0 +1,10 @@
+// RUN: %clang -target x86_64-apple-macosx10.13 -target-variant x86_64-apple-ios13.1-macabi -ftarget-variant-availability-checks -c -### %s 2>&1 \
+// RUN:   | FileCheck %s
+// RUN: %clang -target x86_64-apple-macosx10.13 -target-variant x86_64-apple-ios13.1-macabi -fno-target-variant-availability-checks -c -### %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=NO_ARG %s
+// RUN: %clang -target x86_64-apple-macosx10.13 -target-variant x86_64-apple-ios13.1-macabi -c -### %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=NO_ARG %s
+
+// NO_ARG-NOT: -ftarget-variant-availability-checks
+// CHECK: -ftarget-variant-availability-checks
+
diff --git a/clang/test/FixIt/fixit-availability-zippered.m b/clang/test/FixIt/fixit-availability-zippered.m
index e27636a1e388a..7b07eb2541762 100644
--- a/clang/test/FixIt/fixit-availability-zippered.m
+++ b/clang/test/FixIt/fixit-availability-zippered.m
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -Wunguarded-availability -fdiagnostics-parseable-fixits -triple x86_64-apple-macos10.14 -darwin-target-variant-triple x86_64-apple-ios12-macabi %s 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -ftarget-variant-availability-checks -fsyntax-only -Wunguarded-availability -fdiagnostics-parseable-fixits -triple x86_64-apple-macos10.14 -darwin-target-variant-triple x86_64-apple-ios12-macabi %s 2>&1 | FileCheck %s
 
 // XFAIL: *
 __attribute__((availability(macOS, introduced=10.15))) __attribute__((availability(ios, introduced=13)))
diff --git a/clang/test/Sema/attr-availability-zippered.c b/clang/test/Sema/attr-availability-zippered.c
index 223b15b17cd19..ac145aeaf1c3e 100644
--- a/clang/test/Sema/attr-availability-zippered.c
+++ b/clang/test/Sema/attr-availability-zippered.c
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 "-triple" "x86_64-apple-macos10.14" -darwin-target-variant-triple x86_64-apple-ios12-macabi -fsyntax-only -verify %s
-// RUN: %clang_cc1 "-triple" x86_64-apple-ios12-macabi -darwin-target-variant-triple "x86_64-apple-macos10.14"  -fsyntax-only -verify -D INVERTED %s
+// RUN: %clang_cc1 -ftarget-variant-availability-checks "-triple" "x86_64-apple-macos10.14" -darwin-target-variant-triple x86_64-apple-ios12-macabi -fsyntax-only -verify %s
+// RUN: %clang_cc1 -ftarget-variant-availability-checks "-triple" x86_64-apple-ios12-macabi -darwin-target-variant-triple "x86_64-apple-macos10.14"  -fsyntax-only -verify -D INVERTED %s
 
 // XFAIL: *
 __attribute__((availability(macos, introduced=10.10, deprecated=10.14), availability(ios, introduced=9, deprecated=12)))
diff --git a/clang/test/SemaObjC/unguarded-availability-zippered-disabled.m b/clang/test/SemaObjC/unguarded-availability-zippered-disabled.m
new file mode 100644
index 0000000000000..cb999eed3f432
--- /dev/null
+++ b/clang/test/SemaObjC/unguarded-availability-zippered-disabled.m
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -triple x86_64-apple-macos10.14 -darwin-target-variant-triple x86_64-apple-ios13.1-macabi -fblocks -fsyntax-only -verify %s
+
+#define AVAILABLE_CUR_MAC __attribute__((availability(macos, introduced = 10.14)))
+#define AVAILABLE_NEXT_IOS __attribute__((availability(ios, introduced = 14)))
+
+void uikitformacIntroducedLater() AVAILABLE_CUR_MAC AVAILABLE_NEXT_IOS;
+// expected-warning at -1 {{macOS availability is ignored without a valid 'SDKSettings.json' in the SDK}}
+
+void test() {
+  uikitformacIntroducedLater();
+}
+
diff --git a/clang/test/SemaObjC/unguarded-availability-zippered.m b/clang/test/SemaObjC/unguarded-availability-zippered.m
index bc35654d69e0c..93b4768dd1158 100644
--- a/clang/test/SemaObjC/unguarded-availability-zippered.m
+++ b/clang/test/SemaObjC/unguarded-availability-zippered.m
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -triple x86_64-apple-macos10.14 -darwin-target-variant-triple x86_64-apple-ios12-macabi -fblocks -fsyntax-only -verify %s
-// RUN: %clang_cc1 -triple x86_64-apple-ios12-macabi -darwin-target-variant-triple x86_64-apple-macos10.14 -fblocks -fsyntax-only -verify -D INVERTED %s
+// RUN: %clang_cc1 -triple x86_64-apple-macos10.14 -darwin-target-variant-triple x86_64-apple-ios12-macabi -fblocks -fsyntax-only -ftarget-variant-availability-checks -verify %s
+// RUN: %clang_cc1 -triple x86_64-apple-ios12-macabi -darwin-target-variant-triple x86_64-apple-macos10.14 -fblocks -fsyntax-only -ftarget-variant-availability-checks -verify -D INVERTED %s
 
 
 // XFAIL: *

>From 07ef75c3be630f298eb64a2df92de52454e7e43d Mon Sep 17 00:00:00 2001
From: Alex Lorenz <arphaman at gmail.com>
Date: Fri, 28 Jun 2019 12:51:35 -0700
Subject: [PATCH 15/21] [clang] rename uikitformac to maccatalyst

The old 'uikitformac' aliases for the availability are preserved.

<rdar://problem/52124997> Add "macCatalyst" as a synonym for "uikitformac"
<rdar://problem/44963038> Marzipan: Add Clang support for the final marketing name for Marzipan (to replace "iOSMac")

apple-llvm-split-commit: af13efc7c68ad1f845091467b56d1d98973d32ad
apple-llvm-split-dir: clang/
---
 .../test/FixIt/fixit-availability-zippered.m  |  4 +-
 clang/test/Sema/attr-availability-zippered.c  | 40 +++++++++----------
 .../unguarded-availability-zippered.m         | 24 +++++------
 3 files changed, 34 insertions(+), 34 deletions(-)

diff --git a/clang/test/FixIt/fixit-availability-zippered.m b/clang/test/FixIt/fixit-availability-zippered.m
index 7b07eb2541762..31f99e44d70dd 100644
--- a/clang/test/FixIt/fixit-availability-zippered.m
+++ b/clang/test/FixIt/fixit-availability-zippered.m
@@ -6,7 +6,7 @@
 
 int use() {
   function();
-// CHECK: fix-it:{{.*}}:{[[@LINE-1]]:3-[[@LINE-1]]:3}:"if (@available(macOS 10.15, uikitformac 13, *)) {\n      "
+// CHECK: fix-it:{{.*}}:{[[@LINE-1]]:3-[[@LINE-1]]:3}:"if (@available(macOS 10.15, macCatalyst 13, *)) {\n      "
 // CHECK-NEXT: fix-it:{{.*}}:{[[@LINE-2]]:14-[[@LINE-2]]:14}:"\n  } else {\n      // Fallback on earlier versions\n  }"
 }
 
@@ -18,6 +18,6 @@ @interface NewClass
 
 @interface OldButOfferFixit
 @property(copy) NewClass *prop;
-// CHECK: fix-it:{{.*}}:{[[@LINE-2]]:1-[[@LINE-2]]:1}:"API_AVAILABLE(macos(10.15), uikitformac(13))\n"
+// CHECK: fix-it:{{.*}}:{[[@LINE-2]]:1-[[@LINE-2]]:1}:"API_AVAILABLE(macos(10.15), maccatalyst(13))\n"
 
 @end
diff --git a/clang/test/Sema/attr-availability-zippered.c b/clang/test/Sema/attr-availability-zippered.c
index ac145aeaf1c3e..c2035f7bc29c2 100644
--- a/clang/test/Sema/attr-availability-zippered.c
+++ b/clang/test/Sema/attr-availability-zippered.c
@@ -22,12 +22,12 @@ void checkDeprecated() {
   // The compiler may warn here if the deployment target is older than the version introduced
   bothDeprecated();
 #ifndef INVERTED
-  // expected-warning at -2 {{'bothDeprecated' is deprecated: first deprecated in macOS 10.14 and first deprecated in UIKit for macOS 12}}
+  // expected-warning at -2 {{'bothDeprecated' is deprecated: first deprecated in macOS 10.14 and first deprecated in macCatalyst 12}}
 #else
-  // expected-warning at -4 {{'bothDeprecated' is deprecated: first deprecated in UIKit for macOS 12 and first deprecated in macOS 10.14}}
+  // expected-warning at -4 {{'bothDeprecated' is deprecated: first deprecated in macCatalyst 12 and first deprecated in macOS 10.14}}
 #endif
   macOSDeprecated(); // expected-warning {{'macOSDeprecated' is deprecated: first deprecated in macOS 10.14}}
-  iOSDeprecated();   // expected-warning {{'iOSDeprecated' is deprecated: first deprecated in UIKit for macOS 12}}
+  iOSDeprecated();   // expected-warning {{'iOSDeprecated' is deprecated: first deprecated in macCatalyst 12}}
   bothNotDeprecated();
 }
 
@@ -53,25 +53,25 @@ void bothObsoleted() { // expected-note {{'bothObsoleted' has been explicitly ma
 void checkUnavailable() {
   bothUnavailable();
 #ifndef INVERTED
-  // expected-error at -2 {{'bothUnavailable' is unavailable: not available on macOS and not available on UIKit for macOS}}
+  // expected-error at -2 {{'bothUnavailable' is unavailable: not available on macOS and not available on macCatalyst}}
 #else
-  // expected-error at -4 {{'bothUnavailable' is unavailable: not available on UIKit for macOS and not available on macOS}}
+  // expected-error at -4 {{'bothUnavailable' is unavailable: not available on macCatalyst and not available on macOS}}
 #endif
-  iosUnavailable(); // expected-error {{'iosUnavailable' is unavailable: not available on UIKit for macOS}}
+  iosUnavailable(); // expected-error {{'iosUnavailable' is unavailable: not available on macCatalyst}}
   macOSUnavailable(); // expected-error {{'macOSUnavailable' is unavailable: not available on macOS}}
   bothAvailable();
   
   bothObsoleted();
 #ifndef INVERTED
-  // expected-error at -2 {{'bothObsoleted' is unavailable: obsoleted in macOS 10.14 and obsoleted in UIKit for macOS 12}}
+  // expected-error at -2 {{'bothObsoleted' is unavailable: obsoleted in macOS 10.14 and obsoleted in macCatalyst 12}}
 #else
-  // expected-error at -4 {{'bothObsoleted' is unavailable: obsoleted in UIKit for macOS 12 and obsoleted in macOS 10.14}}
+  // expected-error at -4 {{'bothObsoleted' is unavailable: obsoleted in macCatalyst 12 and obsoleted in macOS 10.14}}
 #endif
 }
 
 __attribute__((availability(macos, introduced=10.10, deprecated=10.14)))
 typedef struct ZipperedTypedefDifferentOffendingDecl { // expected-note {{'ZipperedTypedefDifferentOffendingDecl' has been explicitly marked deprecated here}}
-// expected-warning at -1 {{'ZipperedTypedefDifferentOffendingDecl' is deprecated: first deprecated in UIKit for macOS 12}}
+// expected-warning at -1 {{'ZipperedTypedefDifferentOffendingDecl' is deprecated: first deprecated in macCatalyst 12}}
 // expected-note at -2 {{'ZipperedTypedefDifferentOffendingDecl' has been explicitly marked deprecated here}}
   int x;
 } __attribute__((availability(ios, introduced=9, deprecated=12))) ZipperedTypedefDifferentOffendingDecl_t; // expected-note {{'ZipperedTypedefDifferentOffendingDecl_t' has been explicitly marked deprecated here}}
@@ -79,9 +79,9 @@ typedef struct ZipperedTypedefDifferentOffendingDecl { // expected-note {{'Zippe
 void checkZipperDiffOffendingDecl() {
   ZipperedTypedefDifferentOffendingDecl_t tt;
 #ifndef INVERTED
-  // expected-warning at -2 {{'ZipperedTypedefDifferentOffendingDecl_t' is deprecated: first deprecated in macOS 10.14 and first deprecated in UIKit for macOS 12}}
+  // expected-warning at -2 {{'ZipperedTypedefDifferentOffendingDecl_t' is deprecated: first deprecated in macOS 10.14 and first deprecated in macCatalyst 12}}
 #else
-  // expected-warning at -4 {{'ZipperedTypedefDifferentOffendingDecl_t' is deprecated: first deprecated in UIKit for macOS 12 and first deprecated in macOS 10.14}}
+  // expected-warning at -4 {{'ZipperedTypedefDifferentOffendingDecl_t' is deprecated: first deprecated in macCatalyst 12 and first deprecated in macOS 10.14}}
 #endif
 }
 
@@ -119,30 +119,30 @@ void justMacOSDeprecated() { // expected-note {{'justMacOSDeprecated' has been e
 
 void checkMix() {
   mixUnavailableAndDeprecated();
-  // expected-error at -1 {{'mixUnavailableAndDeprecated' is unavailable: not available on UIKit for macOS}}
+  // expected-error at -1 {{'mixUnavailableAndDeprecated' is unavailable: not available on macCatalyst}}
   // expected-warning at -2 {{'mixUnavailableAndDeprecated' is deprecated: first deprecated in macOS 10.14}}
   
   iOSUnavailableMacGood();
-  // expected-error at -1 {{'iOSUnavailableMacGood' is unavailable: not available on UIKit for macOS}}
+  // expected-error at -1 {{'iOSUnavailableMacGood' is unavailable: not available on macCatalyst}}
   
   macOSDeprecatedIOSGood();
   // expected-warning at -1 {{'macOSDeprecatedIOSGood' is deprecated: first deprecated in macOS 10.14}}
 
   bothDeprecatedDiffReplacement();
 #ifndef INVERTED
-  // expected-warning at -2 {{'bothDeprecatedDiffReplacement' is deprecated: first deprecated in macOS 10.14 and first deprecated in UIKit for macOS 12}}
+  // expected-warning at -2 {{'bothDeprecatedDiffReplacement' is deprecated: first deprecated in macOS 10.14 and first deprecated in macCatalyst 12}}
 #else
-  // expected-warning at -4 {{'bothDeprecatedDiffReplacement' is deprecated: first deprecated in UIKit for macOS 12 and first deprecated in macOS 10.14}}
+  // expected-warning at -4 {{'bothDeprecatedDiffReplacement' is deprecated: first deprecated in macCatalyst 12 and first deprecated in macOS 10.14}}
 #endif
 
   bothUnavailableSameReplacement();
 #ifndef INVERTED
-  // expected-error at -2 {{'bothUnavailableSameReplacement' is unavailable: not available on macOS and not available on UIKit for macOS}}
+  // expected-error at -2 {{'bothUnavailableSameReplacement' is unavailable: not available on macOS and not available on macCatalyst}}
 #else
-  // expected-error at -4 {{'bothUnavailableSameReplacement' is unavailable: not available on UIKit for macOS and not available on macOS}}
+  // expected-error at -4 {{'bothUnavailableSameReplacement' is unavailable: not available on macCatalyst and not available on macOS}}
 #endif
 
-  justIosUnavailable(); // expected-error {{'justIosUnavailable' is unavailable: not available on UIKit for macOS}}
+  justIosUnavailable(); // expected-error {{'justIosUnavailable' is unavailable: not available on macCatalyst}}
 
   justMacOSDeprecated(); // expected-warning {{'justMacOSDeprecated' is deprecated: first deprecated in macOS 10.14}}
 }
@@ -166,8 +166,8 @@ struct IntroducedLaterBoth { } __attribute__((availability(macos, introduced=10.
 struct NotYetIntroduced { // expected-note {{annotate 'NotYetIntroduced' with an availability attribute to silence this warning}}
   struct IntroducedLaterBoth x;
 #ifndef INVERTED
-  // expected-warning at -2 {{'IntroducedLaterBoth' is only available on macOS 10.15 and UIKit for macOS 13 or newer}}
+  // expected-warning at -2 {{'IntroducedLaterBoth' is only available on macOS 10.15 and macCatalyst 13 or newer}}
 #else
-  // expected-warning at -4 {{'IntroducedLaterBoth' is only available on UIKit for macOS 13 and macOS 10.15 or newer}}
+  // expected-warning at -4 {{'IntroducedLaterBoth' is only available on macCatalyst 13 and macOS 10.15 or newer}}
 #endif
 };
diff --git a/clang/test/SemaObjC/unguarded-availability-zippered.m b/clang/test/SemaObjC/unguarded-availability-zippered.m
index 93b4768dd1158..cf720567bdc88 100644
--- a/clang/test/SemaObjC/unguarded-availability-zippered.m
+++ b/clang/test/SemaObjC/unguarded-availability-zippered.m
@@ -16,15 +16,15 @@
 void bothWillBeAvailable() AVAILABLE_NEXT_MAC AVAILABLE_NEXT_IOS;
 #ifndef INVERTED
 // expected-note at -2 3 {{'bothWillBeAvailable' has been marked as being introduced in macOS 10.15 here, but the deployment target is macOS 10.14.0}}
-// expected-note at -3 {{'bothWillBeAvailable' has been marked as being introduced in UIKit for macOS 14 here, but the deployment target is UIKit for macOS 13.0.0}}
+// expected-note at -3 {{'bothWillBeAvailable' has been marked as being introduced in macCatalyst 14 here, but the deployment target is macCatalyst 13.0.0}}
 #else
-// expected-note at -5 3 {{'bothWillBeAvailable' has been marked as being introduced in UIKit for macOS 14 here, but the deployment target is UIKit for macOS 13.0.0}}
+// expected-note at -5 3 {{'bothWillBeAvailable' has been marked as being introduced in macCatalyst 14 here, but the deployment target is macCatalyst 13.0.0}}
 // expected-note at -6 {{'bothWillBeAvailable' has been marked as being introduced in macOS 10.15 here, but the deployment target is macOS 10.14.0}}
 #endif
 
 void macOSCurrentlyAvailable() AVAILABLE_CURRENT_MAC AVAILABLE_NEXT_IOS;
 // #ifndef INVERTED
-// expected-note at -2 2 {{'macOSCurrentlyAvailable' has been marked as being introduced in UIKit for macOS 14 here, but the deployment target is UIKit for macOS 13.0.0}}
+// expected-note at -2 2 {{'macOSCurrentlyAvailable' has been marked as being introduced in macCatalyst 14 here, but the deployment target is macCatalyst 13.0.0}}
 // #else
 // #endif
 
@@ -37,13 +37,13 @@ void test() {
   bothCurrentlyAvailable();
   bothWillBeAvailable(); // expected-note{{enclose 'bothWillBeAvailable' in an @available check to silence this warning}}
 #ifndef INVERTED
-  // expected-warning at -2 {{'bothWillBeAvailable' is only available on macOS 10.15 and UIKit for macOS 13 or newer}}
+  // expected-warning at -2 {{'bothWillBeAvailable' is only available on macOS 10.15 and macCatalyst 13 or newer}}
 #else
-  // expected-warning at -4 {{'bothWillBeAvailable' is only available on UIKit for macOS 13 and macOS 10.15 or newer}}
+  // expected-warning at -4 {{'bothWillBeAvailable' is only available on macCatalyst 13 and macOS 10.15 or newer}}
 #endif
   
   
-  macOSCurrentlyAvailable(); // expected-warning {{'macOSCurrentlyAvailable' is only available on UIKit for macOS 13 or newer}}
+  macOSCurrentlyAvailable(); // expected-warning {{'macOSCurrentlyAvailable' is only available on macCatalyst 13 or newer}}
   // expected-note at -1 {{enclose 'macOSCurrentlyAvailable' in an @available check to silence this warning}}
 
   if (@available(ios 13, macos 10.15, *))
@@ -54,25 +54,25 @@ void test() {
   if (@available(ios 12, *))
     bothWillBeAvailable(); // expected-note {{enclose}}
 #ifndef INVERTED
-  // expected-warning at -2 {{'bothWillBeAvailable' is only available on macOS 10.15 and UIKit for macOS 13 or newer}}
+  // expected-warning at -2 {{'bothWillBeAvailable' is only available on macOS 10.15 and macCatalyst 13 or newer}}
 #else
-  // expected-warning at -4 {{'bothWillBeAvailable' is only available on UIKit for macOS 13 and macOS 10.15 or newer}}
+  // expected-warning at -4 {{'bothWillBeAvailable' is only available on macCatalyst 13 and macOS 10.15 or newer}}
 #endif
   if (@available(macos 10.15, *))
-    bothWillBeAvailable(); // expected-warning {{'bothWillBeAvailable' is only available on UIKit for macOS 13 or newer}}
+    bothWillBeAvailable(); // expected-warning {{'bothWillBeAvailable' is only available on macCatalyst 13 or newer}}
   // expected-note at -1 {{enclose}}
 
   if (@available(macos 10.15, *))
-    macOSCurrentlyAvailable(); // expected-warning {{'macOSCurrentlyAvailable' is only available on UIKit for macOS 13 or newer}}
+    macOSCurrentlyAvailable(); // expected-warning {{'macOSCurrentlyAvailable' is only available on macCatalyst 13 or newer}}
   // expected-note at -1 {{enclose}}
   if (@available(ios 13, *))
     macOSCurrentlyAvailable();
 
   macOSNextAvailableiOSNotAvailable();
-  // expected-error at -1 {{'macOSNextAvailableiOSNotAvailable' is unavailable: not available on UIKit for macOS}}
+  // expected-error at -1 {{'macOSNextAvailableiOSNotAvailable' is unavailable: not available on macCatalyst}}
   // expected-warning at -2 {{'macOSNextAvailableiOSNotAvailable' is only available on macOS 10.15 or newer}}
   // expected-note at -3 {{enclose}}
 
   if (@available(macos 10.15, *))
-    macOSNextAvailableiOSNotAvailable(); // expected-error {{'macOSNextAvailableiOSNotAvailable' is unavailable: not available on UIKit for macOS}}
+    macOSNextAvailableiOSNotAvailable(); // expected-error {{'macOSNextAvailableiOSNotAvailable' is unavailable: not available on macCatalyst}}
 }

>From c92e684f3389e0aa795f02027350507b9578e4fa Mon Sep 17 00:00:00 2001
From: Alex Lorenz <arphaman at gmail.com>
Date: Mon, 1 Jun 2020 22:46:23 -0700
Subject: [PATCH 16/21] [clang] add an as-written version to the @available
 check and use it for codegen

---
 clang/include/clang/AST/ExprObjC.h            | 36 ++++++++++++++-----
 clang/lib/CodeGen/CGExprScalar.cpp            |  4 +--
 clang/lib/Sema/SemaExprObjC.cpp               | 17 ++++-----
 clang/lib/Serialization/ASTReaderStmt.cpp     |  6 ++--
 clang/lib/Serialization/ASTWriterStmt.cpp     |  2 ++
 .../CodeGenObjC/availability-check-zippered.m |  8 +++++
 clang/test/CodeGenObjC/availability-check.m   | 10 ++++++
 7 files changed, 63 insertions(+), 20 deletions(-)

diff --git a/clang/include/clang/AST/ExprObjC.h b/clang/include/clang/AST/ExprObjC.h
index 39f22c961ce96..de5b9b63deba7 100644
--- a/clang/include/clang/AST/ExprObjC.h
+++ b/clang/include/clang/AST/ExprObjC.h
@@ -1733,15 +1733,24 @@ class ObjCBridgedCastExpr final
 /// expressions.
 ///
 class ObjCAvailabilityCheckExpr : public Expr {
+public:
+  struct VersionAsWritten {
+    // Platform version canonicalized for use with availability checks.
+    VersionTuple Version;
+    // Platforms version as written in the source.
+    VersionTuple SourceVersion;
+  };
+
+private:
   friend class ASTStmtReader;
 
-  VersionTuple VersionToCheck;
-  VersionTuple VariantVersionToCheck;
+  VersionAsWritten VersionToCheck;
+  VersionAsWritten VariantVersionToCheck;
   SourceLocation AtLoc, RParen;
 
 public:
-  ObjCAvailabilityCheckExpr(VersionTuple VersionToCheck,
-                            VersionTuple VariantVersionToCheck,
+  ObjCAvailabilityCheckExpr(VersionAsWritten VersionToCheck,
+                            VersionAsWritten VariantVersionToCheck,
                             SourceLocation AtLoc, SourceLocation RParen,
                             QualType Ty)
       : Expr(ObjCAvailabilityCheckExprClass, Ty, VK_PRValue, OK_Ordinary),
@@ -1759,12 +1768,23 @@ class ObjCAvailabilityCheckExpr : public Expr {
   SourceRange getSourceRange() const { return {AtLoc, RParen}; }
 
   /// This may be '*', in which case this should fold to true.
-  bool hasVersion() const { return !VersionToCheck.empty(); }
-  VersionTuple getVersion() const { return VersionToCheck; }
+  bool hasVersion() const { return !VersionToCheck.Version.empty(); }
+  VersionTuple getVersion() const { return VersionToCheck.Version; }
+  VersionTuple getVersionAsWritten() const {
+    return VersionToCheck.SourceVersion;
+  }
 
-  bool hasVariantVersion() const { return !VariantVersionToCheck.empty(); }
+  bool hasVariantVersion() const {
+    return !VariantVersionToCheck.Version.empty();
+  }
+
+  VersionTuple getVariantVersion() const {
+    return VariantVersionToCheck.Version;
+  }
 
-  VersionTuple getVariantVersion() const { return VariantVersionToCheck; }
+  VersionTuple getVariantVersionAsWritten() const {
+    return VariantVersionToCheck.SourceVersion;
+  }
 
   child_range children() {
     return child_range(child_iterator(), child_iterator());
diff --git a/clang/lib/CodeGen/CGExprScalar.cpp b/clang/lib/CodeGen/CGExprScalar.cpp
index ac19c58dbc684..f81489f433799 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -634,8 +634,8 @@ class ScalarExprEmitter
   }
 
   Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
-    VersionTuple Version = E->getVersion();
-    VersionTuple VariantVersion = E->getVariantVersion();
+    VersionTuple Version = E->getVersionAsWritten();
+    VersionTuple VariantVersion = E->getVariantVersionAsWritten();
 
     // If we're checking for a platform older than our minimum deployment
     // target, we can fold the check away.
diff --git a/clang/lib/Sema/SemaExprObjC.cpp b/clang/lib/Sema/SemaExprObjC.cpp
index 2de5ee4d2598b..257678f6c3eeb 100644
--- a/clang/lib/Sema/SemaExprObjC.cpp
+++ b/clang/lib/Sema/SemaExprObjC.cpp
@@ -5290,9 +5290,8 @@ ExprResult SemaObjC::ActOnObjCAvailabilityCheckExpr(
     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
     SourceLocation RParen) {
   ASTContext &Context = getASTContext();
-  auto FindSpecVersion =
-      [&](StringRef Platform,
-          const llvm::Triple::OSType &OS) -> std::optional<VersionTuple> {
+  auto FindSpecVersion = [&](StringRef Platform, const llvm::Triple::OSType &OS)
+      -> std::optional<ObjCAvailabilityCheckExpr::VersionAsWritten> {
     auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
       return Spec.getPlatform() == Platform;
     });
@@ -5317,18 +5316,20 @@ ExprResult SemaObjC::ActOnObjCAvailabilityCheckExpr(
     if (Spec == AvailSpecs.end())
       return std::nullopt;
 
-    return llvm::Triple::getCanonicalVersionForOS(
-        OS, Spec->getVersion(),
-        llvm::Triple::isValidVersionForOS(OS, Spec->getVersion()));
+    return ObjCAvailabilityCheckExpr::VersionAsWritten{
+        llvm::Triple::getCanonicalVersionForOS(
+            OS, Spec->getVersion(),
+            llvm::Triple::isValidVersionForOS(OS, Spec->getVersion())),
+        Spec->getVersion()};
   };
 
-  VersionTuple Version;
+  ObjCAvailabilityCheckExpr::VersionAsWritten Version;
   if (auto MaybeVersion =
           FindSpecVersion(Context.getTargetInfo().getPlatformName(),
                           Context.getTargetInfo().getTriple().getOS()))
     Version = *MaybeVersion;
 
-  VersionTuple VariantVersion;
+  ObjCAvailabilityCheckExpr::VersionAsWritten VariantVersion;
   if (Context.getTargetInfo().hasTargetVariantPlatform()) {
     const llvm::Triple *VariantTriple =
         Context.getTargetInfo().getDarwinTargetVariantTriple();
diff --git a/clang/lib/Serialization/ASTReaderStmt.cpp b/clang/lib/Serialization/ASTReaderStmt.cpp
index 8fb690d800143..95e2db852e0e7 100644
--- a/clang/lib/Serialization/ASTReaderStmt.cpp
+++ b/clang/lib/Serialization/ASTReaderStmt.cpp
@@ -1742,8 +1742,10 @@ void ASTStmtReader::VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E)
   SourceRange R = Record.readSourceRange();
   E->AtLoc = R.getBegin();
   E->RParen = R.getEnd();
-  E->VersionToCheck = Record.readVersionTuple();
-  E->VariantVersionToCheck = Record.readVersionTuple();
+  E->VersionToCheck.Version = Record.readVersionTuple();
+  E->VersionToCheck.SourceVersion = Record.readVersionTuple();
+  E->VariantVersionToCheck.Version = Record.readVersionTuple();
+  E->VariantVersionToCheck.SourceVersion = Record.readVersionTuple();
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/clang/lib/Serialization/ASTWriterStmt.cpp b/clang/lib/Serialization/ASTWriterStmt.cpp
index c1c9cf77feddd..393f76312259c 100644
--- a/clang/lib/Serialization/ASTWriterStmt.cpp
+++ b/clang/lib/Serialization/ASTWriterStmt.cpp
@@ -1716,7 +1716,9 @@ void ASTStmtWriter::VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E)
   VisitExpr(E);
   Record.AddSourceRange(E->getSourceRange());
   Record.AddVersionTuple(E->getVersion());
+  Record.AddVersionTuple(E->getVersionAsWritten());
   Record.AddVersionTuple(E->getVariantVersion());
+  Record.AddVersionTuple(E->getVariantVersionAsWritten());
   Code = serialization::EXPR_OBJC_AVAILABILITY_CHECK;
 }
 
diff --git a/clang/test/CodeGenObjC/availability-check-zippered.m b/clang/test/CodeGenObjC/availability-check-zippered.m
index f6ccb2fe1d55d..4642a3f4ba86c 100644
--- a/clang/test/CodeGenObjC/availability-check-zippered.m
+++ b/clang/test/CodeGenObjC/availability-check-zippered.m
@@ -1,6 +1,7 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14 -darwin-target-variant-triple x86_64-apple-ios13-macabi -emit-llvm -o - %s | FileCheck --check-prefixes=CHECK,MAC %s
 // RUN: %clang_cc1 -triple x86_64-apple-ios13-macabi -darwin-target-variant-triple x86_64-apple-macosx10.14 -emit-llvm -o - %s | FileCheck --check-prefixes=CHECK,IOS %s
 
+// XFAIL: *
 void use_at_available() {
 
   // CHECK: call i32 @__isPlatformVersionAtLeast(i32 1, i32 10, i32 15, i32 0)
@@ -15,6 +16,13 @@ void use_at_available() {
   if (@available(macos 10.15, macCatalyst 13.1, *))
    ;
 
+  // MAC: call i32 @__isPlatformOrVariantPlatformVersionAtLeast(i32 1, i32 10, i32 16, i32 0, i32 2, i32 13, i32 1, i32 0)
+  // MAC-NEXT: icmp ne
+  // IOS: call i32 @__isPlatformOrVariantPlatformVersionAtLeast(i32 2, i32 13, i32 1, i32 0, i32 1, i32 10, i32 16, i32 0)
+  // IOS-NEXT: icmp ne
+  if (@available(macos 10.16, iosmac 13.1, *))
+   ;
+
   // CHECK: call i32 @__isPlatformVersionAtLeast(i32 2, i32 13, i32 1, i32 0)
   // CHECK-NEXT: icmp ne
   if (@available(ios 13.1, *))
diff --git a/clang/test/CodeGenObjC/availability-check.m b/clang/test/CodeGenObjC/availability-check.m
index eceaf973119fb..ffcce52f44212 100644
--- a/clang/test/CodeGenObjC/availability-check.m
+++ b/clang/test/CodeGenObjC/availability-check.m
@@ -26,6 +26,16 @@ void use_at_available(void) {
   // CHECK: br i1 true
   if (__builtin_available(macos 10.11, *))
     ;
+
+  // CHECK: call i32 @__isPlatformVersionAtLeast(i32 1, i32 10, i32 16, i32 0)
+  // CHECK-NEXT: icmp ne
+  if (__builtin_available(macos 10.16, *))
+    ;
+
+  // CHECK: call i32 @__isPlatformVersionAtLeast(i32 1, i32 11, i32 0, i32 0)
+  // CHECK-NEXT: icmp ne
+  if (__builtin_available(macos 11.0, *))
+    ;
 }
 
 // CHECK: declare i32 @__isPlatformVersionAtLeast(i32, i32, i32, i32)

>From 865915f94a6350c4f67a71265320f9df28dec6f0 Mon Sep 17 00:00:00 2001
From: Alex Lorenz <arphaman at gmail.com>
Date: Mon, 29 Jun 2020 22:08:28 -0700
Subject: [PATCH 17/21] canonicalize macOS 10.16 availability to macOS 11 while
 preserving uses of if @available macOS 10.16

This patch canonicalizes the macOS versions in the availability, so that clang can treat macOS 10.16 availability as macOS 11 availability. The if (@available (macOS 10.16, *) checks still preserve their original version in the generated code to ensure that the software running on macOS Big Sur Beta 1 can still exhibits the expected runtime behavior for the 10.16 availability checks.
---
 clang/test/CodeGen/attr-availability-new.c    |  25 ++++
 clang/test/Sema/attr-availability-macos-new.c | 116 ++++++++++++++++++
 2 files changed, 141 insertions(+)
 create mode 100644 clang/test/CodeGen/attr-availability-new.c
 create mode 100644 clang/test/Sema/attr-availability-macos-new.c

diff --git a/clang/test/CodeGen/attr-availability-new.c b/clang/test/CodeGen/attr-availability-new.c
new file mode 100644
index 0000000000000..2fa50fd84ea8c
--- /dev/null
+++ b/clang/test/CodeGen/attr-availability-new.c
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -fvisibility=hidden "-triple" "x86_64-apple-macos11.0" -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -fvisibility=hidden "-triple" "x86_64-apple-macos10.15" -emit-llvm -o - %s | FileCheck -check-prefix=CHECK-OLD %s
+
+__attribute__((availability(macos,introduced=10.16)))
+void f0(void);
+
+__attribute__((availability(macos,introduced=11.0)))
+void f1(void);
+
+__attribute__((availability(macos,introduced=12.0)))
+void f2(void);
+
+// CHECK-OLD: declare extern_weak void @f0
+// CHECK-OLD: declare extern_weak void @f1
+// CHECK-OLD: declare extern_weak void @f2
+
+// CHECK: declare void @f0
+// CHECK: declare void @f1
+// CHECK: declare extern_weak void @f2
+
+void test() {
+  f0();
+  f1();
+  f2();
+}
diff --git a/clang/test/Sema/attr-availability-macos-new.c b/clang/test/Sema/attr-availability-macos-new.c
new file mode 100644
index 0000000000000..20d7d0cf75bf1
--- /dev/null
+++ b/clang/test/Sema/attr-availability-macos-new.c
@@ -0,0 +1,116 @@
+// RUN: %clang_cc1 "-triple" "x86_64-apple-macos10.15" -fsyntax-only -verify %s
+// RUN: %clang_cc1 "-triple" "x86_64-apple-macos11" -DNEW -fsyntax-only -verify %s
+// RUN: %clang_cc1 "-triple" "x86_64-apple-darwin20" -DNEW -fsyntax-only -verify %s
+// RUN: %clang_cc1 "-triple" "x86_64-apple-macos10.15" -fsyntax-only -verify -fapplication-extension -DAPP_EXT %s
+
+__attribute__((availability(macos,strict,introduced=10.16)))
+void fNew1();
+#ifndef NEW
+// expected-note at -2 {{here}}
+#endif
+
+__attribute__((availability(macosx,strict,introduced=10.16)))
+void fNew();
+
+__attribute__((availability(macos,strict,introduced=11)))
+void fNew() { }
+#ifndef NEW
+// expected-note at -2 {{here}}
+#endif
+
+__attribute__((availability(macosx,strict,deprecated=10.16)))
+void fDep();
+
+__attribute__((availability(macos,strict,deprecated=11)))
+void fDep() { }
+#ifdef NEW
+// expected-note at -2 {{here}}
+#endif
+
+__attribute__((availability(macosx,strict,obsoleted=10.16)))
+void fObs();
+
+__attribute__((availability(macos,strict,obsoleted=11)))
+void fObs() { }
+#ifdef NEW
+// expected-note at -2 {{here}}
+#endif
+
+__attribute__((availability(macosx_app_extension,strict,introduced=10.16)))
+void fAppExt();
+
+__attribute__((availability(macos_app_extension,strict,introduced=11)))
+void fAppExt() { }
+#ifdef APP_EXT
+// expected-note at -2 {{here}}
+#endif
+
+void testVersionRemapping() {
+  fNew1();
+#ifndef NEW
+  // expected-error at -2 {{'fNew1' is unavailable: introduced in macOS 11.0}}
+#endif
+  fNew();
+#ifndef NEW
+  // expected-error at -2 {{'fNew' is unavailable: introduced in macOS 11}}
+#endif
+  fDep();
+#ifdef NEW
+  // expected-warning at -2 {{'fDep' is deprecated: first deprecated in macOS 11}}
+#endif
+  fObs();
+#ifdef NEW
+  // expected-error at -2 {{'fObs' is unavailable: obsoleted in macOS 11}}
+#endif
+
+  fAppExt();
+#ifdef APP_EXT
+  // expected-error at -2 {{'fAppExt' is unavailable: introduced in macOS (App Extension) 11}}
+#endif
+}
+
+__attribute__((availability(macosx,strict,introduced=10.16.1))) // expected-note {{here}}
+void fMatchErr();
+
+__attribute__((availability(macos,strict,introduced=11))) // expected-warning {{availability does not match previous declaration}}
+void fMatchErr() { }
+
+__attribute__((availability(macosx_app_extension,strict,introduced=10.16))) // expected-note {{here}}
+void fAppExtErr();
+
+__attribute__((availability(macos_app_extension,strict,introduced=11.1))) // expected-warning {{availability does not match previous declaration}}
+void fAppExtErr() { }
+
+__attribute__((availability(macos,introduced=11)))
+void fNew2();
+#ifndef NEW
+  // expected-note at -2 {{'fNew2' has been marked as being introduced in macOS 11 here, but the deployment target is macOS 10.15}}
+#endif
+__attribute__((availability(macos,introduced=10.16)))
+void fNew3();
+
+__attribute__((availability(macos,introduced=12)))
+void evenNewer();
+#ifdef NEW
+  // expected-note at -2 {{'evenNewer' has been marked as being introduced in macOS 12 here, but the deployment target is macOS 11}}
+#endif
+
+void testAvailabilityCheck() {
+  if (__builtin_available(macOS 10.16, *)) {
+    fNew2();
+    fNew3();
+  }
+  if (__builtin_available(macOS 11, *)) {
+    fNew2();
+    fNew3();
+  }
+  fNew2();
+#ifndef NEW
+  // expected-warning at -2 {{'fNew2' is only available on macOS 11 or newer}} expected-note at -2 {{enclose}}
+#endif
+#ifdef NEW
+  evenNewer(); // expected-warning {{'evenNewer' is only available on macOS 12 or newer}} expected-note {{enclose}}
+#endif
+}
+
+

>From a36bbcfbe6cedf8a11e858a5b2f4de79789df4e5 Mon Sep 17 00:00:00 2001
From: Alex Lorenz <arphaman at gmail.com>
Date: Fri, 23 Jul 2021 08:16:32 -0700
Subject: [PATCH 18/21] [clang] Fix internal tests after merging Mac Catalyst
 upstream support

---
 .../CodeGenObjC/availability-check-zippered.m |  3 +-
 clang/test/Sema/attr-availability-zippered.c  | 65 +++++++++----------
 ...unguarded-availability-zippered-disabled.m | 10 +--
 .../unguarded-availability-zippered.m         | 58 ++++++++---------
 4 files changed, 67 insertions(+), 69 deletions(-)

diff --git a/clang/test/CodeGenObjC/availability-check-zippered.m b/clang/test/CodeGenObjC/availability-check-zippered.m
index 4642a3f4ba86c..5d40081e497f3 100644
--- a/clang/test/CodeGenObjC/availability-check-zippered.m
+++ b/clang/test/CodeGenObjC/availability-check-zippered.m
@@ -1,7 +1,6 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14 -darwin-target-variant-triple x86_64-apple-ios13-macabi -emit-llvm -o - %s | FileCheck --check-prefixes=CHECK,MAC %s
 // RUN: %clang_cc1 -triple x86_64-apple-ios13-macabi -darwin-target-variant-triple x86_64-apple-macosx10.14 -emit-llvm -o - %s | FileCheck --check-prefixes=CHECK,IOS %s
 
-// XFAIL: *
 void use_at_available() {
 
   // CHECK: call i32 @__isPlatformVersionAtLeast(i32 1, i32 10, i32 15, i32 0)
@@ -20,7 +19,7 @@ void use_at_available() {
   // MAC-NEXT: icmp ne
   // IOS: call i32 @__isPlatformOrVariantPlatformVersionAtLeast(i32 2, i32 13, i32 1, i32 0, i32 1, i32 10, i32 16, i32 0)
   // IOS-NEXT: icmp ne
-  if (@available(macos 10.16, iosmac 13.1, *))
+  if (@available(macos 10.16, macCatalyst 13.1, *))
    ;
 
   // CHECK: call i32 @__isPlatformVersionAtLeast(i32 2, i32 13, i32 1, i32 0)
diff --git a/clang/test/Sema/attr-availability-zippered.c b/clang/test/Sema/attr-availability-zippered.c
index c2035f7bc29c2..f2e8cd703f602 100644
--- a/clang/test/Sema/attr-availability-zippered.c
+++ b/clang/test/Sema/attr-availability-zippered.c
@@ -1,20 +1,19 @@
-// RUN: %clang_cc1 -ftarget-variant-availability-checks "-triple" "x86_64-apple-macos10.14" -darwin-target-variant-triple x86_64-apple-ios12-macabi -fsyntax-only -verify %s
-// RUN: %clang_cc1 -ftarget-variant-availability-checks "-triple" x86_64-apple-ios12-macabi -darwin-target-variant-triple "x86_64-apple-macos10.14"  -fsyntax-only -verify -D INVERTED %s
+// RUN: %clang_cc1 "-triple" "x86_64-apple-macos10.15" -darwin-target-variant-triple x86_64-apple-ios13.1-macabi -fsyntax-only -ftarget-variant-availability-checks -verify %s
+// RUN: %clang_cc1 "-triple" x86_64-apple-ios13.1-macabi -darwin-target-variant-triple "x86_64-apple-macos10.15"  -fsyntax-only -ftarget-variant-availability-checks -verify -D INVERTED %s
 
-// XFAIL: *
-__attribute__((availability(macos, introduced=10.10, deprecated=10.14), availability(ios, introduced=9, deprecated=12)))
+__attribute__((availability(macos, introduced=10.10, deprecated=10.15), availability(ios, introduced=9, deprecated=12))) // expected-warning {{macOS availability is ignored without a valid 'SDKSettings.json' in the SDK}}
 void bothDeprecated() { // expected-note {{'bothDeprecated' has been explicitly marked deprecated here}}
 }
 
-__attribute__((availability(macos, introduced=10.10, deprecated=10.14), availability(ios, introduced=9, deprecated=13)))
+__attribute__((availability(macos, introduced=10.10, deprecated=10.15), availability(ios, introduced=9, deprecated=14)))
 void macOSDeprecated() { // expected-note {{'macOSDeprecated' has been explicitly marked deprecated here}}
 }
 
-__attribute__((availability(macos, introduced=10.10, deprecated=10.15), availability(ios, introduced=9, deprecated=12)))
+__attribute__((availability(macos, introduced=10.10, deprecated=11), availability(ios, introduced=9, deprecated=12)))
 void iOSDeprecated() { // expected-note {{'iOSDeprecated' has been explicitly marked deprecated here}}
 }
 
-__attribute__((availability(macos, introduced=10.10, deprecated=10.15), availability(ios, introduced=9, deprecated=13)))
+__attribute__((availability(macos, introduced=10.10, deprecated=11), availability(ios, introduced=13.0, deprecated=14.0)))
 void bothNotDeprecated() {
 }
 
@@ -22,12 +21,12 @@ void checkDeprecated() {
   // The compiler may warn here if the deployment target is older than the version introduced
   bothDeprecated();
 #ifndef INVERTED
-  // expected-warning at -2 {{'bothDeprecated' is deprecated: first deprecated in macOS 10.14 and first deprecated in macCatalyst 12}}
+  // expected-warning at -2 {{'bothDeprecated' is deprecated: first deprecated in macOS 10.15 and first deprecated in macCatalyst 13.1}}
 #else
-  // expected-warning at -4 {{'bothDeprecated' is deprecated: first deprecated in macCatalyst 12 and first deprecated in macOS 10.14}}
+  // expected-warning at -4 {{'bothDeprecated' is deprecated: first deprecated in macCatalyst 13.1 and first deprecated in macOS 10.15}}
 #endif
-  macOSDeprecated(); // expected-warning {{'macOSDeprecated' is deprecated: first deprecated in macOS 10.14}}
-  iOSDeprecated();   // expected-warning {{'iOSDeprecated' is deprecated: first deprecated in macCatalyst 12}}
+  macOSDeprecated(); // expected-warning {{'macOSDeprecated' is deprecated: first deprecated in macOS 10.15}}
+  iOSDeprecated();   // expected-warning {{'iOSDeprecated' is deprecated: first deprecated in macCatalyst 13.1}}
   bothNotDeprecated();
 }
 
@@ -46,7 +45,7 @@ void macOSUnavailable() { // expected-note {{'macOSUnavailable' has been explici
 __attribute__((availability(macos, introduced=10.10), availability(ios, introduced=11)))
 void bothAvailable() { }
 
-__attribute__((availability(macos, introduced=10.10, obsoleted=10.14), availability(ios, introduced=9, obsoleted=12)))
+__attribute__((availability(macos, introduced=10.10, obsoleted=10.15), availability(ios, introduced=9, obsoleted=12)))
 void bothObsoleted() { // expected-note {{'bothObsoleted' has been explicitly marked unavailable here}}
 }
 
@@ -63,15 +62,15 @@ void checkUnavailable() {
   
   bothObsoleted();
 #ifndef INVERTED
-  // expected-error at -2 {{'bothObsoleted' is unavailable: obsoleted in macOS 10.14 and obsoleted in macCatalyst 12}}
+  // expected-error at -2 {{'bothObsoleted' is unavailable: obsoleted in macOS 10.15 and obsoleted in macCatalyst 13.1}}
 #else
-  // expected-error at -4 {{'bothObsoleted' is unavailable: obsoleted in macCatalyst 12 and obsoleted in macOS 10.14}}
+  // expected-error at -4 {{'bothObsoleted' is unavailable: obsoleted in macCatalyst 13.1 and obsoleted in macOS 10.15}}
 #endif
 }
 
-__attribute__((availability(macos, introduced=10.10, deprecated=10.14)))
+__attribute__((availability(macos, introduced=10.10, deprecated=10.15)))
 typedef struct ZipperedTypedefDifferentOffendingDecl { // expected-note {{'ZipperedTypedefDifferentOffendingDecl' has been explicitly marked deprecated here}}
-// expected-warning at -1 {{'ZipperedTypedefDifferentOffendingDecl' is deprecated: first deprecated in macCatalyst 12}}
+// expected-warning at -1 {{'ZipperedTypedefDifferentOffendingDecl' is deprecated: first deprecated in macCatalyst 13}}
 // expected-note at -2 {{'ZipperedTypedefDifferentOffendingDecl' has been explicitly marked deprecated here}}
   int x;
 } __attribute__((availability(ios, introduced=9, deprecated=12))) ZipperedTypedefDifferentOffendingDecl_t; // expected-note {{'ZipperedTypedefDifferentOffendingDecl_t' has been explicitly marked deprecated here}}
@@ -79,29 +78,29 @@ typedef struct ZipperedTypedefDifferentOffendingDecl { // expected-note {{'Zippe
 void checkZipperDiffOffendingDecl() {
   ZipperedTypedefDifferentOffendingDecl_t tt;
 #ifndef INVERTED
-  // expected-warning at -2 {{'ZipperedTypedefDifferentOffendingDecl_t' is deprecated: first deprecated in macOS 10.14 and first deprecated in macCatalyst 12}}
+  // expected-warning at -2 {{'ZipperedTypedefDifferentOffendingDecl_t' is deprecated: first deprecated in macOS 10.15 and first deprecated in macCatalyst 13.1}}
 #else
-  // expected-warning at -4 {{'ZipperedTypedefDifferentOffendingDecl_t' is deprecated: first deprecated in macCatalyst 12 and first deprecated in macOS 10.14}}
+  // expected-warning at -4 {{'ZipperedTypedefDifferentOffendingDecl_t' is deprecated: first deprecated in macCatalyst 13.1 and first deprecated in macOS 10.15}}
 #endif
 }
 
-__attribute__((availability(macos, introduced=10.10, deprecated=10.14), availability(ios, unavailable)))
+__attribute__((availability(macos, introduced=10.10, deprecated=10.15), availability(ios, unavailable)))
 void mixUnavailableAndDeprecated() {
   // expected-note at -1 {{'mixUnavailableAndDeprecated' has been explicitly marked unavailable here}}
   // expected-note at -2 {{'mixUnavailableAndDeprecated' has been explicitly marked deprecated here}}
 }
 
-__attribute__((availability(macos, introduced=10.10, deprecated=10.15), availability(ios, unavailable)))
+__attribute__((availability(macos, introduced=10.10, deprecated=11), availability(ios, unavailable)))
 void iOSUnavailableMacGood() {
   // expected-note at -1 {{'iOSUnavailableMacGood' has been explicitly marked unavailable here}}
 }
 
-__attribute__((availability(macos, introduced=10.10, deprecated=10.14), availability(ios, introduced=11)))
+__attribute__((availability(macos, introduced=10.10, deprecated=10.15), availability(ios, introduced=11)))
 void macOSDeprecatedIOSGood() {
   // expected-note at -1 {{'macOSDeprecatedIOSGood' has been explicitly marked deprecated here}}
 }
 
-__attribute__((availability(macos, introduced=10.10, deprecated=10.14, replacement="foo"), availability(ios, introduced=9, deprecated=12, replacement="bar")))
+__attribute__((availability(macos, introduced=10.10, deprecated=10.15, replacement="foo"), availability(ios, introduced=9, deprecated=12, replacement="bar")))
 void bothDeprecatedDiffReplacement() { // expected-note {{'bothDeprecatedDiffReplacement' has been explicitly marked deprecated here}}
 }
 
@@ -113,26 +112,26 @@ __attribute__((availability(ios, unavailable)))
 void justIosUnavailable() { // expected-note {{'justIosUnavailable' has been explicitly marked unavailable here}}
 }
 
-__attribute__((availability(macos, introduced=10.10, deprecated=10.14)))
+__attribute__((availability(macos, introduced=10.10, deprecated=10.15)))
 void justMacOSDeprecated() { // expected-note {{'justMacOSDeprecated' has been explicitly marked deprecated here}}
 }
 
 void checkMix() {
   mixUnavailableAndDeprecated();
   // expected-error at -1 {{'mixUnavailableAndDeprecated' is unavailable: not available on macCatalyst}}
-  // expected-warning at -2 {{'mixUnavailableAndDeprecated' is deprecated: first deprecated in macOS 10.14}}
+  // expected-warning at -2 {{'mixUnavailableAndDeprecated' is deprecated: first deprecated in macOS 10.15}}
   
   iOSUnavailableMacGood();
   // expected-error at -1 {{'iOSUnavailableMacGood' is unavailable: not available on macCatalyst}}
   
   macOSDeprecatedIOSGood();
-  // expected-warning at -1 {{'macOSDeprecatedIOSGood' is deprecated: first deprecated in macOS 10.14}}
+  // expected-warning at -1 {{'macOSDeprecatedIOSGood' is deprecated: first deprecated in macOS 10.15}}
 
   bothDeprecatedDiffReplacement();
 #ifndef INVERTED
-  // expected-warning at -2 {{'bothDeprecatedDiffReplacement' is deprecated: first deprecated in macOS 10.14 and first deprecated in macCatalyst 12}}
+  // expected-warning at -2 {{'bothDeprecatedDiffReplacement' is deprecated: first deprecated in macOS 10.15 and first deprecated in macCatalyst 13.1}}
 #else
-  // expected-warning at -4 {{'bothDeprecatedDiffReplacement' is deprecated: first deprecated in macCatalyst 12 and first deprecated in macOS 10.14}}
+  // expected-warning at -4 {{'bothDeprecatedDiffReplacement' is deprecated: first deprecated in macCatalyst 13.1 and first deprecated in macOS 10.15}}
 #endif
 
   bothUnavailableSameReplacement();
@@ -144,7 +143,7 @@ void checkMix() {
 
   justIosUnavailable(); // expected-error {{'justIosUnavailable' is unavailable: not available on macCatalyst}}
 
-  justMacOSDeprecated(); // expected-warning {{'justMacOSDeprecated' is deprecated: first deprecated in macOS 10.14}}
+  justMacOSDeprecated(); // expected-warning {{'justMacOSDeprecated' is deprecated: first deprecated in macOS 10.15}}
 }
 
 int deprecatedFunc() __attribute__((deprecated)); // expected-note {{'deprecatedFunc' has been explicitly marked deprecated here}}
@@ -156,18 +155,18 @@ void a() {
 }
 
 
-struct IntroducedLaterBoth { } __attribute__((availability(macos, introduced=10.15), availability(ios, introduced=14)));
+struct IntroducedLaterBoth { } __attribute__((availability(macos, introduced=11), availability(ios, introduced=14)));
 #ifndef INVERTED
-// expected-note at -2 {{'IntroducedLaterBoth' has been marked as being introduced in macOS 10.15 here, but the deployment target is macOS 10.14.0}}
+// expected-note at -2 {{'IntroducedLaterBoth' has been marked as being introduced in macOS 11 here, but the deployment target is macOS 10.15}}
 #else
-// expected-note at -4 {{'IntroducedLaterBoth' has been marked as being introduced in macCatalyst 14 here, but the deployment target is macCatalyst 13.0.0}}
+// expected-note at -4 {{'IntroducedLaterBoth' has been marked as being introduced in macCatalyst 14 here, but the deployment target is macCatalyst 13.1}}
 #endif
 
 struct NotYetIntroduced { // expected-note {{annotate 'NotYetIntroduced' with an availability attribute to silence this warning}}
   struct IntroducedLaterBoth x;
 #ifndef INVERTED
-  // expected-warning at -2 {{'IntroducedLaterBoth' is only available on macOS 10.15 and macCatalyst 13 or newer}}
+  // expected-warning at -2 {{'IntroducedLaterBoth' is only available on macOS 11 and macCatalyst 14 or newer}}
 #else
-  // expected-warning at -4 {{'IntroducedLaterBoth' is only available on macCatalyst 13 and macOS 10.15 or newer}}
+  // expected-warning at -4 {{'IntroducedLaterBoth' is only available on macCatalyst 14 and macOS 11 or newer}}
 #endif
 };
diff --git a/clang/test/SemaObjC/unguarded-availability-zippered-disabled.m b/clang/test/SemaObjC/unguarded-availability-zippered-disabled.m
index cb999eed3f432..c11a2ea219576 100644
--- a/clang/test/SemaObjC/unguarded-availability-zippered-disabled.m
+++ b/clang/test/SemaObjC/unguarded-availability-zippered-disabled.m
@@ -1,12 +1,12 @@
-// RUN: %clang_cc1 -triple x86_64-apple-macos10.14 -darwin-target-variant-triple x86_64-apple-ios13.1-macabi -fblocks -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple x86_64-apple-macos10.15 -darwin-target-variant-triple x86_64-apple-ios13.1-macabi -fblocks -fsyntax-only -Wno-ignored-availability-without-sdk-settings -verify %s
 
-#define AVAILABLE_CUR_MAC __attribute__((availability(macos, introduced = 10.14)))
+#define AVAILABLE_CUR_MAC __attribute__((availability(macos, introduced = 10.15)))
 #define AVAILABLE_NEXT_IOS __attribute__((availability(ios, introduced = 14)))
 
-void uikitformacIntroducedLater() AVAILABLE_CUR_MAC AVAILABLE_NEXT_IOS;
-// expected-warning at -1 {{macOS availability is ignored without a valid 'SDKSettings.json' in the SDK}}
+void macCatalystIntroducedLater() AVAILABLE_CUR_MAC AVAILABLE_NEXT_IOS;
 
 void test() {
-  uikitformacIntroducedLater();
+  macCatalystIntroducedLater();
 }
 
+// expected-no-diagnostics
diff --git a/clang/test/SemaObjC/unguarded-availability-zippered.m b/clang/test/SemaObjC/unguarded-availability-zippered.m
index cf720567bdc88..74bd0ca24b5ef 100644
--- a/clang/test/SemaObjC/unguarded-availability-zippered.m
+++ b/clang/test/SemaObjC/unguarded-availability-zippered.m
@@ -1,78 +1,78 @@
-// RUN: %clang_cc1 -triple x86_64-apple-macos10.14 -darwin-target-variant-triple x86_64-apple-ios12-macabi -fblocks -fsyntax-only -ftarget-variant-availability-checks -verify %s
-// RUN: %clang_cc1 -triple x86_64-apple-ios12-macabi -darwin-target-variant-triple x86_64-apple-macos10.14 -fblocks -fsyntax-only -ftarget-variant-availability-checks -verify -D INVERTED %s
+// RUN: %clang_cc1 -triple x86_64-apple-macos10.15 -darwin-target-variant-triple x86_64-apple-ios13.1-macabi -fblocks -fsyntax-only -ftarget-variant-availability-checks -Wno-ignored-availability-without-sdk-settings -verify %s
+// RUN: %clang_cc1 -triple x86_64-apple-ios13.1-macabi -darwin-target-variant-triple x86_64-apple-macos10.15 -fblocks -fsyntax-only -ftarget-variant-availability-checks -Wno-ignored-availability-without-sdk-settings -verify -D INVERTED %s
 
 
 // XFAIL: *
 #define AVAILABLE_PREV_MAC __attribute__((availability(macos, introduced = 10.13)))
-#define AVAILABLE_CURRENT_MAC __attribute__((availability(macos, introduced = 10.14)))
-#define AVAILABLE_NEXT_MAC __attribute__((availability(macos, introduced = 10.15)))
+#define AVAILABLE_CURRENT_MAC __attribute__((availability(macos, introduced = 10.15)))
+#define AVAILABLE_NEXT_MAC __attribute__((availability(macos, introduced = 11.0)))
 
-#define AVAILABLE_PREV_IOS __attribute__((availability(ios, introduced = 11)))
-#define AVAILABLE_CURRENT_IOS __attribute__((availability(iOSMac, introduced = 12)))
-#define AVAILABLE_NEXT_IOS __attribute__((availability(ios, introduced = 13)))
+#define AVAILABLE_PREV_IOS __attribute__((availability(macCatalyst, introduced = 11)))
+#define AVAILABLE_CURRENT_IOS __attribute__((availability(macCatalyst, introduced = 13.1)))
+#define AVAILABLE_NEXT_IOS __attribute__((availability(macCatalyst, introduced = 14)))
 
 void bothPreviouslyAvailable() AVAILABLE_PREV_MAC AVAILABLE_PREV_IOS;
 void bothCurrentlyAvailable() AVAILABLE_CURRENT_MAC AVAILABLE_CURRENT_IOS;
 void bothWillBeAvailable() AVAILABLE_NEXT_MAC AVAILABLE_NEXT_IOS;
 #ifndef INVERTED
-// expected-note at -2 3 {{'bothWillBeAvailable' has been marked as being introduced in macOS 10.15 here, but the deployment target is macOS 10.14.0}}
-// expected-note at -3 {{'bothWillBeAvailable' has been marked as being introduced in macCatalyst 14 here, but the deployment target is macCatalyst 13.0.0}}
+// expected-note at -2 3 {{'bothWillBeAvailable' has been marked as being introduced in macOS 11.0 here, but the deployment target is macOS 10.15}}
+// expected-note at -3 {{'bothWillBeAvailable' has been marked as being introduced in macCatalyst 14 here, but the deployment target is macCatalyst 13.1}}
 #else
-// expected-note at -5 3 {{'bothWillBeAvailable' has been marked as being introduced in macCatalyst 14 here, but the deployment target is macCatalyst 13.0.0}}
-// expected-note at -6 {{'bothWillBeAvailable' has been marked as being introduced in macOS 10.15 here, but the deployment target is macOS 10.14.0}}
+// expected-note at -5 3 {{'bothWillBeAvailable' has been marked as being introduced in macCatalyst 14 here, but the deployment target is macCatalyst 13.1}}
+// expected-note at -6 {{'bothWillBeAvailable' has been marked as being introduced in macOS 11.0 here, but the deployment target is macOS 10.15}}
 #endif
 
 void macOSCurrentlyAvailable() AVAILABLE_CURRENT_MAC AVAILABLE_NEXT_IOS;
 // #ifndef INVERTED
-// expected-note at -2 2 {{'macOSCurrentlyAvailable' has been marked as being introduced in macCatalyst 14 here, but the deployment target is macCatalyst 13.0.0}}
+// expected-note at -2 2 {{'macOSCurrentlyAvailable' has been marked as being introduced in macCatalyst 14 here, but the deployment target is macCatalyst 13.1}}
 // #else
 // #endif
 
 void macOSNextAvailableiOSNotAvailable() AVAILABLE_NEXT_MAC __attribute__((availability(ios, unavailable)));
 // expected-note at -1 2 {{'macOSNextAvailableiOSNotAvailable' has been explicitly marked unavailable here}}
-// expected-note at -2 {{'macOSNextAvailableiOSNotAvailable' has been marked as being introduced in macOS 10.15 here, but the deployment target is macOS 10.14.0}}
+// expected-note at -2 {{'macOSNextAvailableiOSNotAvailable' has been marked as being introduced in macOS 11.0 here, but the deployment target is macOS 10.15}}
 
 void test() {
   bothPreviouslyAvailable();
   bothCurrentlyAvailable();
   bothWillBeAvailable(); // expected-note{{enclose 'bothWillBeAvailable' in an @available check to silence this warning}}
 #ifndef INVERTED
-  // expected-warning at -2 {{'bothWillBeAvailable' is only available on macOS 10.15 and macCatalyst 13 or newer}}
+  // expected-warning at -2 {{'bothWillBeAvailable' is only available on macOS 11.0 and macCatalyst 14 or newer}}
 #else
-  // expected-warning at -4 {{'bothWillBeAvailable' is only available on macCatalyst 13 and macOS 10.15 or newer}}
+  // expected-warning at -4 {{'bothWillBeAvailable' is only available on macCatalyst 14 and macOS 11.0 or newer}}
 #endif
   
   
-  macOSCurrentlyAvailable(); // expected-warning {{'macOSCurrentlyAvailable' is only available on macCatalyst 13 or newer}}
+  macOSCurrentlyAvailable(); // expected-warning {{'macOSCurrentlyAvailable' is only available on macCatalyst 14 or newer}}
   // expected-note at -1 {{enclose 'macOSCurrentlyAvailable' in an @available check to silence this warning}}
 
-  if (@available(ios 13, macos 10.15, *))
+  if (@available(ios 14, macos 11.0, *))
     bothWillBeAvailable();
-  if (@available(ios 13, *))
-    bothWillBeAvailable(); // expected-warning {{'bothWillBeAvailable' is only available on macOS 10.15 or newer}}
+  if (@available(ios 14, *))
+    bothWillBeAvailable(); // expected-warning {{'bothWillBeAvailable' is only available on macOS 11.0 or newer}}
   // expected-note at -1 {{enclose}}
-  if (@available(ios 12, *))
+  if (@available(ios 13, *))
     bothWillBeAvailable(); // expected-note {{enclose}}
 #ifndef INVERTED
-  // expected-warning at -2 {{'bothWillBeAvailable' is only available on macOS 10.15 and macCatalyst 13 or newer}}
+  // expected-warning at -2 {{'bothWillBeAvailable' is only available on macOS 11.0 and macCatalyst 14 or newer}}
 #else
-  // expected-warning at -4 {{'bothWillBeAvailable' is only available on macCatalyst 13 and macOS 10.15 or newer}}
+  // expected-warning at -4 {{'bothWillBeAvailable' is only available on macCatalyst 14 and macOS 11.0 or newer}}
 #endif
-  if (@available(macos 10.15, *))
-    bothWillBeAvailable(); // expected-warning {{'bothWillBeAvailable' is only available on macCatalyst 13 or newer}}
+  if (@available(macos 11.0, *))
+    bothWillBeAvailable(); // expected-warning {{'bothWillBeAvailable' is only available on macCatalyst 14 or newer}}
   // expected-note at -1 {{enclose}}
 
-  if (@available(macos 10.15, *))
-    macOSCurrentlyAvailable(); // expected-warning {{'macOSCurrentlyAvailable' is only available on macCatalyst 13 or newer}}
+  if (@available(macos 11.0, *))
+    macOSCurrentlyAvailable(); // expected-warning {{'macOSCurrentlyAvailable' is only available on macCatalyst 14 or newer}}
   // expected-note at -1 {{enclose}}
-  if (@available(ios 13, *))
+  if (@available(ios 14, *))
     macOSCurrentlyAvailable();
 
   macOSNextAvailableiOSNotAvailable();
   // expected-error at -1 {{'macOSNextAvailableiOSNotAvailable' is unavailable: not available on macCatalyst}}
-  // expected-warning at -2 {{'macOSNextAvailableiOSNotAvailable' is only available on macOS 10.15 or newer}}
+  // expected-warning at -2 {{'macOSNextAvailableiOSNotAvailable' is only available on macOS 11.0 or newer}}
   // expected-note at -3 {{enclose}}
 
-  if (@available(macos 10.15, *))
+  if (@available(macos 11.0, *))
     macOSNextAvailableiOSNotAvailable(); // expected-error {{'macOSNextAvailableiOSNotAvailable' is unavailable: not available on macCatalyst}}
 }

>From 625f9c44a5488acd7915035902f1f641eca8dfe2 Mon Sep 17 00:00:00 2001
From: Alex Lorenz <arphaman at gmail.com>
Date: Thu, 29 Jul 2021 14:45:35 -0700
Subject: [PATCH 19/21] [internal] restore iosmac availability name for now
 until CarbonHeaders is updated in rdar://81291410 (Carbon header's
 API_UNAVAILABLE(macCatalyst) translates into 'iosmac' availability)

---
 clang/include/clang/Basic/Attr.td               | 4 ++++
 clang/test/Sema/attr-availability-maccatalyst.c | 4 ++--
 2 files changed, 6 insertions(+), 2 deletions(-)

diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td
index 252b53e25e5c8..41c7813281911 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1179,6 +1179,10 @@ static llvm::StringRef canonicalizePlatformName(llvm::StringRef Platform) {
              .Case("visionos_app_extension", "xros_app_extension")
              .Case("anyAppleOS", "anyappleos")
              .Case("ShaderModel", "shadermodel")
+             .Case("iosmac", "maccatalyst")
+             .Case("iosmac_app_extension", "maccatalyst_app_extension")
+             .Case("iOSMac", "maccatalyst")
+             .Case("iOSMacApplicationExtension", "maccatalyst_app_extension")
              .Default(Platform);
 }
 static std::vector<llvm::StringRef> equivalentPlatformNames(llvm::StringRef Platform) {
diff --git a/clang/test/Sema/attr-availability-maccatalyst.c b/clang/test/Sema/attr-availability-maccatalyst.c
index 4e6caca7d72ec..e225f5199331f 100644
--- a/clang/test/Sema/attr-availability-maccatalyst.c
+++ b/clang/test/Sema/attr-availability-maccatalyst.c
@@ -17,8 +17,8 @@ void f32(int) __attribute__((availability(maccatalyst,introduced=3.0, obsoleted=
 
 
 void f5(int) __attribute__((availability(maccatalyst,introduced=2.0))) __attribute__((availability(maccatalyst,deprecated=9.0))); // expected-note {{'f5' has been explicitly marked deprecated here}}
-void f6(int) __attribute__((availability(maccatalyst,deprecated=9.0))); // expected-note {{'f6' has been explicitly marked deprecated here}}
-void f6(int) __attribute__((availability(macCatalyst,introduced=2.0)));
+void f6(int) __attribute__((availability(iosmac,deprecated=9.0))); // expected-note {{'f6' has been explicitly marked deprecated here}}
+void f6(int) __attribute__((availability(iOSMac,introduced=2.0)));
 
 void f7(void) // expected-note {{'f7' has been explicitly marked deprecated here}}
 __attribute__((availability(maccatalyst,introduced=3.0, deprecated=4.0)))

>From 6bc724c0765511c412e7aa2f5e877aaa87909732 Mon Sep 17 00:00:00 2001
From: Akira Hatanaka <ahatanaka at apple.com>
Date: Fri, 24 Jan 2025 19:11:55 -0800
Subject: [PATCH 20/21] Check target variant too when diagnosing unguarded
 availability

Fixes SemaObjC/unguarded-availability-zippered.m.

rdar://142437215
---
 clang/lib/Sema/SemaAvailability.cpp                   | 6 +++++-
 clang/test/SemaObjC/unguarded-availability-zippered.m | 1 -
 2 files changed, 5 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaAvailability.cpp b/clang/lib/Sema/SemaAvailability.cpp
index 2c736015c20ca..332533a0b98f0 100644
--- a/clang/lib/Sema/SemaAvailability.cpp
+++ b/clang/lib/Sema/SemaAvailability.cpp
@@ -1458,9 +1458,13 @@ bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
     return DynamicRecursiveASTVisitor::TraverseIfStmt(If);
   }
   CondVersion = IfCond.E->getVersion();
+  VariantCondVersion = IfCond.E->getVariantVersion();
   // If we're using the '*' case here or if this check is redundant, then we
   // use the enclosing version to check both branches.
-  if (CondVersion.empty() || CondVersion <= AvailabilityStack.back().Version) {
+  if ((CondVersion.empty() ||
+       CondVersion <= AvailabilityStack.back().Version) &&
+      (VariantCondVersion.empty() ||
+       VariantCondVersion <= AvailabilityStack.back().VariantVersion)) {
     return TraverseStmt(If->getThen()) && TraverseStmt(If->getElse());
   }
 
diff --git a/clang/test/SemaObjC/unguarded-availability-zippered.m b/clang/test/SemaObjC/unguarded-availability-zippered.m
index 74bd0ca24b5ef..8ef84d11819cb 100644
--- a/clang/test/SemaObjC/unguarded-availability-zippered.m
+++ b/clang/test/SemaObjC/unguarded-availability-zippered.m
@@ -2,7 +2,6 @@
 // RUN: %clang_cc1 -triple x86_64-apple-ios13.1-macabi -darwin-target-variant-triple x86_64-apple-macos10.15 -fblocks -fsyntax-only -ftarget-variant-availability-checks -Wno-ignored-availability-without-sdk-settings -verify -D INVERTED %s
 
 
-// XFAIL: *
 #define AVAILABLE_PREV_MAC __attribute__((availability(macos, introduced = 10.13)))
 #define AVAILABLE_CURRENT_MAC __attribute__((availability(macos, introduced = 10.15)))
 #define AVAILABLE_NEXT_MAC __attribute__((availability(macos, introduced = 11.0)))

>From 3bdbb87727b00fc0a9281a85f914ae5744743a47 Mon Sep 17 00:00:00 2001
From: Ian Anderson <iana at apple.com>
Date: Tue, 28 Jan 2025 17:33:57 -0800
Subject: [PATCH 21/21] [test][Clang][Sema] Fix the zippered availability test

We never fixed the internal-only availability tests after <rdar://134475028>. Do that now.

rdar://142437215
---
 clang/test/FixIt/fixit-availability-zippered.m | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/clang/test/FixIt/fixit-availability-zippered.m b/clang/test/FixIt/fixit-availability-zippered.m
index 31f99e44d70dd..b16cbee5316af 100644
--- a/clang/test/FixIt/fixit-availability-zippered.m
+++ b/clang/test/FixIt/fixit-availability-zippered.m
@@ -1,6 +1,5 @@
 // RUN: %clang_cc1 -ftarget-variant-availability-checks -fsyntax-only -Wunguarded-availability -fdiagnostics-parseable-fixits -triple x86_64-apple-macos10.14 -darwin-target-variant-triple x86_64-apple-ios12-macabi %s 2>&1 | FileCheck %s
 
-// XFAIL: *
 __attribute__((availability(macOS, introduced=10.15))) __attribute__((availability(ios, introduced=13)))
 int function(void);
 
@@ -10,7 +9,10 @@ int use() {
 // CHECK-NEXT: fix-it:{{.*}}:{[[@LINE-2]]:14-[[@LINE-2]]:14}:"\n  } else {\n      // Fallback on earlier versions\n  }"
 }
 
-#define API_AVAILABLE(...) __attribute__((availability(macOS, introduced=10.15))) __attribute__((availability(ios, introduced=13))) // dummy macro
+#define API_AVAILABLE(x, y) __attribute__((availability(__API_AVAILABLE_PLATFORM_##x))) __attribute__((availability(__API_AVAILABLE_PLATFORM_##y)))
+#define __API_AVAILABLE_PLATFORM_macos(x) macos,introduced=x
+#define __API_AVAILABLE_PLATFORM_ios(x) ios,introduced=x
+#define __API_AVAILABLE_PLATFORM_macCatalyst(x) macCatalyst,introduced=x
 
 API_AVAILABLE(macos(10.15), ios(13))
 @interface NewClass
@@ -18,6 +20,6 @@ @interface NewClass
 
 @interface OldButOfferFixit
 @property(copy) NewClass *prop;
-// CHECK: fix-it:{{.*}}:{[[@LINE-2]]:1-[[@LINE-2]]:1}:"API_AVAILABLE(macos(10.15), maccatalyst(13))\n"
+// CHECK: fix-it:{{.*}}:{[[@LINE-2]]:1-[[@LINE-2]]:1}:"API_AVAILABLE(macos(10.15), macCatalyst(13))\n"
 
 @end



More information about the cfe-commits mailing list