[clang] [compiler-rt] [llvm] [AArch64] On-by-default Darwin stack probing via __chkstk_darwin (PR #238571)

Kuba Mracek via cfe-commits cfe-commits at lists.llvm.org
Fri Dec 4 08:57:59 PST 2026


https://github.com/kubamracek updated https://github.com/llvm/llvm-project/pull/238571

>From c4c758f0efbdcb290b72c483851b67dea37a6445 Mon Sep 17 00:00:00 2001
From: Kuba Mracek <mracek at apple.com>
Date: Sat, 31 Oct 2026 15:37:21 +0000
Subject: [PATCH 1/2] [AArch64] On-by-default Darwin stack probing via
 __chkstk_darwin

This is upstreaming of a long-time in-use Apple Clang Darwin-platform
on-by-default security feature, most code on Apple platforms has been compiling
with stack probing and calls to __chkstk_darwin for years already.

Components:
- Clang driver (-fstack-check flag), threshold logic (16k in common cases to
  match 16k pages in arm64 userspace Darwin)
- Clang CodeGen sets probe-stack=__chkstk_darwin function attr
- Backend inserts probe pseudos (StkChkIndirectCall) in prologues and on
  dynamic allocas
- AsmPrinter expands pseudos into GOT-load + BLR
- Special calling convention (x9 = size), almost no clobbers
- compiler-rt's provides a standalone implementation (__chkstk_darwin)
- the OS ships an O(1) version of the probe, ___chkstk_darwin
  (one more underscore), __chkstk_darwin calls it if present
---
 .../clang/Basic/DiagnosticDriverKinds.td      |   4 +
 clang/include/clang/Basic/Features.def        |   1 +
 clang/include/clang/Basic/LangOptions.def     |   1 +
 clang/include/clang/Driver/ToolChain.h        |   5 +
 clang/include/clang/Options/Options.td        |   6 +-
 clang/lib/CodeGen/CodeGenModule.cpp           |   3 +
 clang/lib/CodeGen/TargetInfo.h                |   3 +
 clang/lib/CodeGen/Targets/AArch64.cpp         |  21 ++
 clang/lib/Driver/ToolChains/Clang.cpp         |  25 +++
 clang/lib/Driver/ToolChains/Darwin.cpp        |  28 +++
 clang/lib/Driver/ToolChains/Darwin.h          |   2 +
 clang/test/CodeGen/darwin-stack-probe-size.c  |  45 ++++
 clang/test/CodeGen/stack-check-feature.c      |  10 +
 clang/test/CodeGenObjC/stack-check.m          |  19 ++
 clang/test/Driver/darwin-stack-probe-size.c   |  60 +++++
 clang/test/Driver/generic-stack-check.c       |  42 ++++
 clang/test/Driver/stack-arg-probe.c           |   8 +-
 compiler-rt/CMakeLists.txt                    |   1 +
 compiler-rt/cmake/config-ix.cmake             |   1 +
 compiler-rt/lib/builtins/CMakeLists.txt       |   7 +
 .../lib/builtins/aarch64/chkstk_darwin.S      |  61 ++++++
 .../lib/builtins/aarch64/chkstk_darwin2.S     |  18 ++
 .../SelectionDAG/SelectionDAGBuilder.cpp      |  23 +-
 llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp | 150 ++++++++++++-
 .../AArch64/AArch64CallingConvention.td       |   7 +
 .../Target/AArch64/AArch64ISelLowering.cpp    |  67 +++++-
 llvm/lib/Target/AArch64/AArch64ISelLowering.h |   3 +
 llvm/lib/Target/AArch64/AArch64InstrInfo.cpp  |   4 +
 llvm/lib/Target/AArch64/AArch64InstrInfo.td   |   9 +
 .../AArch64/AArch64MachineFunctionInfo.cpp    |   2 +-
 .../AArch64/AArch64PrologueEpilogue.cpp       | 179 ++++++++++++++-
 .../Target/AArch64/AArch64PrologueEpilogue.h  |   7 +-
 .../Target/AArch64/AArch64RegisterInfo.cpp    |   4 +
 llvm/lib/Target/AArch64/AArch64RegisterInfo.h |   1 +
 .../AArch64/AArch64TargetObjectFile.cpp       |  15 +-
 .../Target/AArch64/AArch64TargetObjectFile.h  |   4 +-
 .../AArch64/GISel/AArch64LegalizerInfo.cpp    |  52 +++++
 .../GlobalISel/legalize-dyn-alloca.mir        |  55 ++++-
 ...rm64-stack-probing-with-shrink-wrapping.ll |  91 ++++++++
 .../CodeGen/AArch64/arm64-stack-probing.ll    | 105 +++++++++
 .../CodeGen/AArch64/arm64_32-stack-probing.ll |  27 +++
 .../CodeGen/AArch64/ptrauth-stack-probing.ll  |  31 +++
 .../shrink-wrap-chkstk-with-x16-clobbered.ll  | 113 ++++++++++
 .../AArch64/stack-check-dwarf-label-crash.ll  | 207 ++++++++++++++++++
 .../AArch64/stack-probe-with-shrink-wrap.mir  | 126 +++++++++++
 45 files changed, 1624 insertions(+), 29 deletions(-)
 create mode 100644 clang/test/CodeGen/darwin-stack-probe-size.c
 create mode 100644 clang/test/CodeGen/stack-check-feature.c
 create mode 100644 clang/test/CodeGenObjC/stack-check.m
 create mode 100644 clang/test/Driver/darwin-stack-probe-size.c
 create mode 100644 clang/test/Driver/generic-stack-check.c
 create mode 100644 compiler-rt/lib/builtins/aarch64/chkstk_darwin.S
 create mode 100644 compiler-rt/lib/builtins/aarch64/chkstk_darwin2.S
 create mode 100644 llvm/test/CodeGen/AArch64/arm64-stack-probing-with-shrink-wrapping.ll
 create mode 100644 llvm/test/CodeGen/AArch64/arm64-stack-probing.ll
 create mode 100644 llvm/test/CodeGen/AArch64/arm64_32-stack-probing.ll
 create mode 100644 llvm/test/CodeGen/AArch64/ptrauth-stack-probing.ll
 create mode 100644 llvm/test/CodeGen/AArch64/shrink-wrap-chkstk-with-x16-clobbered.ll
 create mode 100644 llvm/test/CodeGen/AArch64/stack-check-dwarf-label-crash.ll
 create mode 100644 llvm/test/CodeGen/AArch64/stack-probe-with-shrink-wrap.mir

diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index c7966b295a0b0b..10316a2fba7964 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -1005,4 +1005,8 @@ def warn_drv_gcc_install_dir_libstdcxx : Warning<
 
 def err_drv_reflection_requires_cxx26 : Error<
   "option '%0' is only supported when compiling in C++26 mode">;
+
+def err_stack_probe_unsupported_platform : Error<
+  "stack-arg-probe flags are unsupported on Darwin platforms, use -fstack-check "
+  "or -fno-stack-check instead">;
 }
diff --git a/clang/include/clang/Basic/Features.def b/clang/include/clang/Basic/Features.def
index cfd5bf69f938cf..261567f0c387fb 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -147,6 +147,7 @@ FEATURE(memory_sanitizer,
 FEATURE(type_sanitizer, LangOpts.Sanitize.has(SanitizerKind::Type))
 FEATURE(thread_sanitizer, LangOpts.Sanitize.has(SanitizerKind::Thread))
 FEATURE(dataflow_sanitizer, LangOpts.Sanitize.has(SanitizerKind::DataFlow))
+FEATURE(stack_check, LangOpts.StackCheck)
 FEATURE(scudo, LangOpts.Sanitize.hasOneOf(SanitizerKind::Scudo))
 FEATURE(ptrauth_intrinsics, LangOpts.PointerAuthIntrinsics &&
                             PP.getTargetInfo().getTriple().isOSDarwin())
diff --git a/clang/include/clang/Basic/LangOptions.def b/clang/include/clang/Basic/LangOptions.def
index b11473b4aaafa5..f3378a6f2dbfb5 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -375,6 +375,7 @@ LANGOPT(HalfNoSemanticInterposition, 1, 0, Benign,
         "Like -fno-semantic-interposition but don't use local aliases")
 ENUM_LANGOPT(StackProtector, StackProtectorMode, 2, SSPOff, NotCompatible,
              "stack protector mode")
+LANGOPT(StackCheck, 1, 0, NotCompatible, "stack checking")
 ENUM_LANGOPT(TrivialAutoVarInit, TrivialAutoVarInitKind, 2, TrivialAutoVarInitKind::Uninitialized, Benign,
              "trivial automatic variable initialization")
 VALUE_LANGOPT(TrivialAutoVarInitStopAfter, 32, 0, Benign,
diff --git a/clang/include/clang/Driver/ToolChain.h b/clang/include/clang/Driver/ToolChain.h
index 8a041c8be7ec0a..38e45bfd67d3fe 100644
--- a/clang/include/clang/Driver/ToolChain.h
+++ b/clang/include/clang/Driver/ToolChain.h
@@ -886,6 +886,11 @@ class ToolChain {
     return SanitizerMask();
   }
 
+  /// Return true if stack checking should be enabled by default.
+  virtual bool useStackChecking(const llvm::opt::ArgList &Args) const {
+    return false;
+  }
+
   /// Returns true when it's possible to split LTO unit to use whole
   /// program devirtualization and CFI santiizers.
   virtual bool canSplitThinLTOUnit() const { return true; }
diff --git a/clang/include/clang/Options/Options.td b/clang/include/clang/Options/Options.td
index c4895b584d4067..d7a79284d89397 100644
--- a/clang/include/clang/Options/Options.td
+++ b/clang/include/clang/Options/Options.td
@@ -4697,6 +4697,11 @@ def fstack_protector : Flag<["-"], "fstack-protector">, Group<f_Group>,
            "stack frame such that a buffer overflow from a vulnerable variable will "
            "overwrite the guard value before overwriting the function's return "
            "address. The reference stack guard value is stored in a global variable.">;
+defm stack_check : BoolFOption<"stack-check",
+  LangOpts<"StackCheck">, DefaultFalse,
+  PosFlag<SetTrue, [], [ClangOption], "Enable">,
+  NegFlag<SetFalse, [], [ClangOption], "Disable">,
+  BothFlags<[], [ClangOption, CC1Option], " stack checking">>;
 def ftrivial_auto_var_init : Joined<["-"], "ftrivial-auto-var-init=">, Group<f_Group>,
   Visibility<[ClangOption, CC1Option, CLOption, DXCOption]>,
   HelpText<"Initialize trivial automatic stack variables. Defaults to 'uninitialized'">,
@@ -7924,7 +7929,6 @@ defm signaling_nans : BooleanFFlag<"signaling-nans">, Group<clang_ignored_gcc_op
 defm single_precision_constant : BooleanFFlag<"single-precision-constant">,
     Group<clang_ignored_gcc_optimization_f_Group>;
 defm spec_constr_count : BooleanFFlag<"spec-constr-count">, Group<clang_ignored_f_Group>;
-defm stack_check : BooleanFFlag<"stack-check">, Group<clang_ignored_f_Group>;
 defm strength_reduce :
     BooleanFFlag<"strength-reduce">, Group<clang_ignored_gcc_optimization_f_Group>;
 defm tls_model : BooleanFFlag<"tls-model">, Group<clang_ignored_f_Group>;
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp
index 9ca85831a71b6c..a495853bd89b3e 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -155,6 +155,9 @@ createTargetCodeGenInfo(CodeGenModule &CGM) {
     else if (Target.getABI() == "aapcs-soft")
       Kind = AArch64ABIKind::AAPCSSoft;
 
+    if (Triple.isOSDarwin())
+      return createDarwinAArch64TargetCodeGenInfo(CGM, Kind);
+
     return createAArch64TargetCodeGenInfo(CGM, Kind);
   }
 
diff --git a/clang/lib/CodeGen/TargetInfo.h b/clang/lib/CodeGen/TargetInfo.h
index 178845c5846859..a26a2db181084f 100644
--- a/clang/lib/CodeGen/TargetInfo.h
+++ b/clang/lib/CodeGen/TargetInfo.h
@@ -533,6 +533,9 @@ createAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind Kind);
 std::unique_ptr<TargetCodeGenInfo>
 createWindowsAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind K);
 
+std::unique_ptr<TargetCodeGenInfo>
+createDarwinAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind K);
+
 std::unique_ptr<TargetCodeGenInfo>
 createAMDGPUTargetCodeGenInfo(CodeGenModule &CGM);
 
diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp b/clang/lib/CodeGen/Targets/AArch64.cpp
index e493f717af581d..986a82ad9cd0c9 100644
--- a/clang/lib/CodeGen/Targets/AArch64.cpp
+++ b/clang/lib/CodeGen/Targets/AArch64.cpp
@@ -206,6 +206,21 @@ class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
                                      QualType ReturnType) const;
 };
 
+class DarwinAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
+public:
+  DarwinAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind Kind)
+      : AArch64TargetCodeGenInfo(CGM, Kind) {}
+  void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
+                           CodeGen::CodeGenModule &CGM) const override {
+    AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
+    addStackProbeTargetAttributes(D, GV, CGM);
+    if (!CGM.getLangOpts().StackCheck || !D)
+      return;
+    if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D))
+      cast<llvm::Function>(GV)->addFnAttr("probe-stack", "__chkstk_darwin");
+  }
+};
+
 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
 public:
   WindowsAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind K)
@@ -1346,3 +1361,9 @@ CodeGen::createWindowsAArch64TargetCodeGenInfo(CodeGenModule &CGM,
                                                AArch64ABIKind K) {
   return std::make_unique<WindowsAArch64TargetCodeGenInfo>(CGM, K);
 }
+
+std::unique_ptr<TargetCodeGenInfo>
+CodeGen::createDarwinAArch64TargetCodeGenInfo(CodeGenModule &CGM,
+                                              AArch64ABIKind K) {
+  return std::make_unique<DarwinAArch64TargetCodeGenInfo>(CGM, K);
+}
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp
index c05b0042962836..e301402036138b 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -7484,6 +7484,12 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
       CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + Value));
   }
 
+  bool UseStackChecking =
+      Args.hasFlag(options::OPT_fstack_check, options::OPT_fno_stack_check,
+                   getToolChain().useStackChecking(Args));
+  if (UseStackChecking)
+    CmdArgs.push_back("-fstack-check");
+
   if (Args.hasArg(options::OPT_mstack_probe_size)) {
     StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
 
@@ -7491,8 +7497,27 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
       CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
     else
       CmdArgs.push_back("-mstack-probe-size=0");
+  } else if (UseStackChecking && RawTriple.isOSDarwin() &&
+             RawTriple.getArch() == llvm::Triple::aarch64) {
+    // 16k-page targets only need a probe every 16k to hit the guard page
+    if (RawTriple.isAppleFirmware()) {
+      // Firmware keeps the 4k default
+    } else if (KernelOrKext) {
+      // The kernel and kexts are 16k-paged, even if built with -ffreestanding
+      CmdArgs.push_back("-mstack-probe-size=16384");
+    } else if (Args.hasArg(options::OPT_ffreestanding)) {
+      // Firmware built against a non-firmware triple keeps the 4k default
+    } else {
+      // Darwin userspace is 16k-paged
+      CmdArgs.push_back("-mstack-probe-size=16384");
+    }
   }
 
+  if (TC.getTriple().isOSDarwin() &&
+      (Args.hasArg(options::OPT_mstack_arg_probe) ||
+       Args.hasArg(options::OPT_mno_stack_arg_probe)))
+    D.Diag(diag::err_stack_probe_unsupported_platform);
+
   Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
                      options::OPT_mno_stack_arg_probe);
 
diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp b/clang/lib/Driver/ToolChains/Darwin.cpp
index 1e2e59dab61c8e..7dfaf3ef1914a2 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -3241,6 +3241,34 @@ void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
     CmdArgs.push_back(Args.MakeArgString(P));
 }
 
+bool DarwinClang::useStackChecking(const llvm::opt::ArgList &Args) const {
+  // Only arm64(e) is supported (this also excludes arm64_32).
+  if (getArch() != llvm::Triple::aarch64)
+    return false;
+  if (!isTargetIOSBased() && !isTargetXROS() && !isTargetMacOSBased() &&
+      !isTargetWatchOSBased())
+    return false;
+  if (isTargetIPhoneOS() && isIPhoneOSVersionLT(13, 0))
+    return false;
+  if (isTargetMacOS() && isMacosxVersionLT(10, 15))
+    return false;
+  if (isTargetWatchOSBased() && getTriple().getOSVersion() < VersionTuple(6))
+    return false;
+
+  if (Args.hasArg(options::OPT_nodefaultlibs))
+    return false;
+  const SanitizerArgs &Sanitize = getSanitizerArgs(Args);
+  // We don't enable for firmware using -ffreestanding, unless we're
+  // specifically targeting the kernel.
+  if (Args.hasArg(options::OPT_ffreestanding) &&
+      !Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext))
+    return false;
+  if (Sanitize.needsAsanRt())
+    return false;
+
+  return TargetEnvironment != Simulator;
+}
+
 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args, BoundArch BA,
                                      Action::OffloadKind) const {
   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
diff --git a/clang/lib/Driver/ToolChains/Darwin.h b/clang/lib/Driver/ToolChains/Darwin.h
index 3ca5753f3012cf..4c0d67c32cc34e 100644
--- a/clang/lib/Driver/ToolChains/Darwin.h
+++ b/clang/lib/Driver/ToolChains/Darwin.h
@@ -719,6 +719,8 @@ class LLVM_LIBRARY_VISIBILITY DarwinClang : public Darwin {
 
   bool getDefaultDebugSimpleTemplateNames() const override;
 
+  bool useStackChecking(const llvm::opt::ArgList &Args) const override;
+
   /// }
 
 private:
diff --git a/clang/test/CodeGen/darwin-stack-probe-size.c b/clang/test/CodeGen/darwin-stack-probe-size.c
new file mode 100644
index 00000000000000..24da12e9697ddc
--- /dev/null
+++ b/clang/test/CodeGen/darwin-stack-probe-size.c
@@ -0,0 +1,45 @@
+// REQUIRES: aarch64-registered-target
+
+// Check that the Darwin 16K default stack probe threshold is present in the IR
+
+// (1) arm64 Darwin targets get 16k threshold
+// RUN: %clang -target arm64-apple-macosx15.0 %s -S -emit-llvm -o - | FileCheck %s --check-prefix=ARM64
+// RUN: %clang -target arm64-apple-ios17.0 %s -S -emit-llvm -o - | FileCheck %s --check-prefix=ARM64
+// ARM64: define{{.*}} @large_frame() #0
+// ARM64: attributes #0 = { {{.*}}"probe-stack"="__chkstk_darwin" "stack-probe-size"="16384"
+// ARM64: !{i32 8, !"stack-probe-size", i32 16384}
+
+// (2) manually specified -mstack-probe-size=4096 gets the LLVM default of 4k threshold
+// The 4k threshold is spelled as the *absence* of the attribute and the module
+// flag, so the CHECK-NOT must be anchored to bound its scan region: matching
+// "probe-stack" first starts it inside the attribute list.
+// RUN: %clang -target arm64-apple-macosx15.0 %s -mstack-probe-size=4096 -S -emit-llvm -o - | FileCheck %s --check-prefix=MANUAL-4K
+// MANUAL-4K: attributes #0 = { {{.*}}"probe-stack"="__chkstk_darwin"
+// MANUAL-4K-NOT: "stack-probe-size"
+
+// (3) any other manually specified -mstack-probe-size
+// RUN: %clang -target arm64-apple-macosx15.0 %s -mstack-probe-size=8192 -S -emit-llvm -o - | FileCheck %s --check-prefix=MANUAL-8K
+// MANUAL-8K: attributes #0 = { {{.*}}"probe-stack"="__chkstk_darwin" "stack-probe-size"="8192"
+// MANUAL-8K: !{i32 8, !"stack-probe-size", i32 8192}
+
+// (4) kernel/kext code gets 16k threshold
+// RUN: %clang -target arm64-apple-macosx15.0 %s -mkernel -S -emit-llvm -o - | FileCheck %s --check-prefix=KERNEL
+// RUN: %clang -target arm64-apple-macosx15.0 %s -fapple-kext -S -emit-llvm -o - | FileCheck %s --check-prefix=KERNEL
+// KERNEL: attributes #0 = { {{.*}}"probe-stack"="__chkstk_darwin" "stack-probe-size"="16384"
+// KERNEL: !{i32 8, !"stack-probe-size", i32 16384}
+
+// (5) -ffreestanding disables Darwin stack checking
+// RUN: %clang -target arm64-apple-macosx15.0 %s -ffreestanding -S -emit-llvm -o - | FileCheck %s --check-prefix=FREESTANDING
+// FREESTANDING: define{{.*}} @large_frame() #0
+// FREESTANDING-NOT: "probe-stack"
+// FREESTANDING-NOT: "stack-probe-size"
+
+// (6) -ffreestanding + -fstack-check keeps 4k threshold (LLVM default)
+// RUN: %clang -target arm64-apple-macosx15.0 %s -ffreestanding -fstack-check -S -emit-llvm -o - | FileCheck %s --check-prefix=FREESTANDING-STACK-CHECK
+// FREESTANDING-STACK-CHECK: attributes #0 = { {{.*}}"probe-stack"="__chkstk_darwin"
+// FREESTANDING-STACK-CHECK-NOT: "stack-probe-size"
+
+void large_frame(void) {
+  volatile char buf[8192];
+  buf[0] = 1;
+}
diff --git a/clang/test/CodeGen/stack-check-feature.c b/clang/test/CodeGen/stack-check-feature.c
new file mode 100644
index 00000000000000..0e767a64ef8b1c
--- /dev/null
+++ b/clang/test/CodeGen/stack-check-feature.c
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 %s -E -triple=arm64-- -fstack-check | FileCheck %s --check-prefix=ENABLED
+// RUN: %clang_cc1 %s -E -triple=arm64-- | FileCheck %s --check-prefix=DISABLED
+
+#if __has_feature(stack_check)
+// ENABLED: has_stack_check
+void has_stack_check() {}
+#else
+// DISABLED: not_exists
+void not_exists() {}
+#endif
diff --git a/clang/test/CodeGenObjC/stack-check.m b/clang/test/CodeGenObjC/stack-check.m
new file mode 100644
index 00000000000000..a690768f213a78
--- /dev/null
+++ b/clang/test/CodeGenObjC/stack-check.m
@@ -0,0 +1,19 @@
+// Check that Objective-C functions and methods are protected when stack probing is enabled
+// RUN: %clang_cc1 -triple arm64-apple-darwin -emit-llvm -o- %s -fstack-check -Wno-objc-root-class | FileCheck %s
+
+// Check that Objective-C functions and methods are not protected with stack probing by default
+// RUN: %clang_cc1 -triple arm64-apple-darwin -emit-llvm -o- %s -Wno-objc-root-class | FileCheck %s --check-prefix=CHECK-DEFAULT
+
+void f(void) {}
+
+ at interface C @end
+ at implementation C
++ (void)m1 {}
+- (void)m2 {}
+ at end
+
+// CHECK: define void @f() #[[ATTR_ID:[0-9]+]] {
+// CHECK: define internal void @"\01+[C m1]"({{.*}}) #[[ATTR_ID]] {
+// CHECK: define internal void @"\01-[C m2]"({{.*}}) #[[ATTR_ID]] {
+// CHECK: attributes #[[ATTR_ID]] ={{.*}}"probe-stack"="__chkstk_darwin"
+// CHECK-DEFAULT-NOT: "probe-stack"="__chkstk_darwin"
diff --git a/clang/test/Driver/darwin-stack-probe-size.c b/clang/test/Driver/darwin-stack-probe-size.c
new file mode 100644
index 00000000000000..77330ba601ec6e
--- /dev/null
+++ b/clang/test/Driver/darwin-stack-probe-size.c
@@ -0,0 +1,60 @@
+// Darwin defaults the stack probe threshold to 16K on 16K-page (arm64) targets, and leaves it at the 4K default everywhere else.
+
+// (1) arm64(e) Darwin + kernel/kext targets get 16k threshold
+// RUN: %clang -target arm64-apple-macosx15.0 %s -### 2>&1 | FileCheck %s --check-prefix=PROBE16K
+// RUN: %clang -target arm64e-apple-macosx15.0 %s -### 2>&1 | FileCheck %s --check-prefix=PROBE16K
+// RUN: %clang -target arm64-apple-ios17.0 %s -### 2>&1 | FileCheck %s --check-prefix=PROBE16K
+// RUN: %clang -target arm64-apple-tvos17.0 %s -### 2>&1 | FileCheck %s --check-prefix=PROBE16K
+// RUN: %clang -target arm64-apple-watchos9.0 %s -### 2>&1 | FileCheck %s --check-prefix=PROBE16K
+// RUN: %clang -target arm64-apple-macosx15.0 %s -mkernel -### 2>&1 | FileCheck %s --check-prefix=PROBE16K
+// RUN: %clang -target arm64-apple-macosx15.0 %s -fapple-kext -### 2>&1 | FileCheck %s --check-prefix=PROBE16K
+// PROBE16K: "-mstack-probe-size=16384"
+
+// (2) x86_64 / arm64_32 / simulator / non-darwin keeps the 4k default
+// RUN: %clang -target x86_64-apple-macosx15.0 %s -### 2>&1 | FileCheck %s --check-prefix=NOPROBEARG
+// RUN: %clang -target x86_64-apple-ios17.0-simulator %s -fstack-check -### 2>&1 | FileCheck %s --check-prefix=NOPROBEARG
+// RUN: %clang -target arm64_32-apple-watchos9.0 %s -### 2>&1 | FileCheck %s --check-prefix=NOPROBEARG
+// RUN: %clang -target arm64-apple-ios17.0-simulator %s -### 2>&1 | FileCheck %s --check-prefix=NOPROBEARG
+// RUN: %clang -target aarch64-linux-gnu %s -### 2>&1 | FileCheck %s --check-prefix=NOPROBEARG
+// RUN: %clang -target aarch64-linux-gnu %s -fstack-clash-protection -### 2>&1 | FileCheck %s --check-prefix=NOPROBEARG
+// NOPROBEARG-NOT: "-mstack-probe-size=
+
+// (3) -ffreestanding keeps the 4k default (except for kernel/kext)
+// RUN: %clang -target arm64-apple-macosx15.0 %s -ffreestanding -### 2>&1 | FileCheck %s --check-prefix=FREESTANDING-NOPROBEARG
+// RUN: %clang -target arm64-apple-macosx15.0 %s -ffreestanding -fstack-check -### 2>&1 | FileCheck %s --check-prefix=FREESTANDING-NOPROBEARG
+// RUN: %clang -target arm64-apple-ios17.0 %s -ffreestanding -fstack-check -### 2>&1 | FileCheck %s --check-prefix=FREESTANDING-NOPROBEARG
+// FREESTANDING-NOPROBEARG-NOT: "-mstack-probe-size=
+
+// (4) firmware triples keep the 4k default, with or without -ffreestanding.
+// RUN: %clang -target arm64-apple-firmware %s -### 2>&1 | FileCheck %s --check-prefix=FIRMWARE-NOPROBEARG
+// RUN: %clang -target arm64e-apple-firmware %s -### 2>&1 | FileCheck %s --check-prefix=FIRMWARE-NOPROBEARG
+// RUN: %clang -target arm64-apple-firmware %s -fstack-check -### 2>&1 | FileCheck %s --check-prefix=FIRMWARE-NOPROBEARG
+// RUN: %clang -target arm64-apple-firmware %s -ffreestanding -fstack-check -### 2>&1 | FileCheck %s --check-prefix=FIRMWARE-NOPROBEARG
+// RUN: %clang -target arm64-apple-firmware %s -mkernel -### 2>&1 | FileCheck %s --check-prefix=FIRMWARE-NOPROBEARG
+// FIRMWARE-NOPROBEARG-NOT: "-mstack-probe-size=
+
+// (5) explicit -mstack-probe-size always wins
+// RUN: %clang -target arm64-apple-macosx15.0 %s -mstack-probe-size=4096 -### 2>&1 | FileCheck %s --check-prefix=PROBE4K
+// RUN: %clang -target arm64-apple-ios17.0 %s -mstack-probe-size=4096 -### 2>&1 | FileCheck %s --check-prefix=PROBE4K
+// RUN: %clang -target arm64-apple-macosx15.0 %s -mstack-probe-size=8192 -mstack-probe-size=4096 -### 2>&1 | FileCheck %s --check-prefix=PROBE4K
+// PROBE4K: "-mstack-probe-size=4096"
+// PROBE4K-NOT: "-mstack-probe-size=16384"
+// RUN: %clang -target arm64-apple-macosx15.0 %s -mstack-probe-size=8192 -### 2>&1 | FileCheck %s --check-prefix=PROBE8K
+// PROBE8K: "-mstack-probe-size=8192"
+// PROBE8K-NOT: "-mstack-probe-size=16384"
+// RUN: %clang -target arm64-apple-macosx15.0 %s -mstack-probe-size=65536 -### 2>&1 | FileCheck %s --check-prefix=PROBE64K
+// PROBE64K: "-mstack-probe-size=65536"
+// RUN: %clang -target arm64-apple-macosx15.0 %s -mstack-probe-size=16384 -### 2>&1 | FileCheck %s --check-prefix=PROBE16K-ONCE
+// PROBE16K-ONCE: "-mstack-probe-size=16384"
+// PROBE16K-ONCE-NOT: "-mstack-probe-size=
+
+// (6) explicit value opts in and always wins (kernel/kext, -ffreestanding, firmware)
+// RUN: %clang -target arm64-apple-macosx15.0 %s -mkernel -mstack-probe-size=4096 -### 2>&1 | FileCheck %s --check-prefix=OPT-IN-PROBE4K
+// RUN: %clang -target arm64-apple-macosx15.0 %s -fapple-kext -mstack-probe-size=4096 -### 2>&1 | FileCheck %s --check-prefix=OPT-IN-PROBE4K
+// RUN: %clang -target arm64-apple-macosx15.0 %s -ffreestanding -mstack-probe-size=16384 -### 2>&1 | FileCheck %s --check-prefix=OPT-IN-PROBE16K
+// RUN: %clang -target arm64-apple-firmware %s -mstack-probe-size=16384 -### 2>&1 | FileCheck %s --check-prefix=OPT-IN-PROBE16K
+// OPT-IN-PROBE4K: "-mstack-probe-size=4096"
+// OPT-IN-PROBE4K-NOT: "-mstack-probe-size=16384"
+// OPT-IN-PROBE16K: "-mstack-probe-size=16384"
+
+void f(void) {}
diff --git a/clang/test/Driver/generic-stack-check.c b/clang/test/Driver/generic-stack-check.c
new file mode 100644
index 00000000000000..f1ef9a84c8445d
--- /dev/null
+++ b/clang/test/Driver/generic-stack-check.c
@@ -0,0 +1,42 @@
+// RUN: %clang -target arm64-apple-ios12.0 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-IOS-PRE13
+// CHECK-IOS-PRE13-NOT: "-fstack-check"
+
+// RUN: %clang -target arm64-apple-ios13.0 %s -### 2>&1 | FileCheck %s --check-prefix=IOS13
+// IOS13: "-fstack-check"
+
+// RUN: %clang -target arm64-apple-ios14.0-macabi %s -### 2>&1 | FileCheck %s --check-prefix=IOS14-MACABI
+// IOS14-MACABI: "-fstack-check"
+
+// RUN: %clang -target arm64-apple-macosx11.0 %s -### 2>&1 | FileCheck %s --check-prefix=OSX11
+// OSX11: "-fstack-check"
+
+// Stack checking is only enabled by default on arm64(e).
+// RUN: %clang -target x86_64-apple-macosx15.0 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-X86
+// CHECK-X86-NOT: "-fstack-check"
+
+// RUN: %clang -target arm64-apple-watchos5.0 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-WATCH-PRE6
+// CHECK-WATCH-PRE6-NOT: "-fstack-check"
+
+// RUN: %clang -target arm64_32-apple-watchos6.0 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-WATCH-ARM64-32
+// CHECK-WATCH-ARM64-32-NOT: "-fstack-check"
+
+// RUN: %clang -target arm64-apple-watchos6.0 %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-WATCH-6
+// CHECK-WATCH-6: "-fstack-check"
+
+// RUN: %clang -target arm64-apple-darwin %s -fstack-check -### 2>&1 | FileCheck %s --check-prefix=ENABLE
+// ENABLE: "-fstack-check"
+
+// RUN: %clang -target arm64-apple-darwin %s -fno-stack-check -### 2>&1 | FileCheck %s --check-prefix=DISABLE
+// DISABLE-NOT: "-fno-stack-check"
+
+// RUN: %clang -target arm64-apple-ios12.0 %s -nodefaultlibs -### 2>&1 | FileCheck %s --check-prefix=NODEFAULTLIBS
+// NODEFAULTLIBS-NOT: "-fstack-check"
+
+// RUN: %clang -target arm64-apple-ios12.0 %s -ffreestanding -### 2>&1 | FileCheck %s --check-prefix=FREESTANDING
+// FREESTANDING-NOT: "-fstack-check"
+
+// RUN: %clang -target arm64-apple-ios12.0 %s -fstack-check -ffreestanding -mkernel -### 2>&1 | FileCheck %s --check-prefix=FREESTANDING-KERNEL
+// FREESTANDING-KERNEL: "-fstack-check"
+
+// RUN: %clang -target arm64-apple-ios12.0 %s -fstack-check -ffreestanding -fapple-kext -### 2>&1 | FileCheck %s --check-prefix=FREESTANDING-KEXT
+// FREESTANDING-KEXT: "-fstack-check"
diff --git a/clang/test/Driver/stack-arg-probe.c b/clang/test/Driver/stack-arg-probe.c
index 232d29bc495956..439626272df623 100644
--- a/clang/test/Driver/stack-arg-probe.c
+++ b/clang/test/Driver/stack-arg-probe.c
@@ -1,6 +1,8 @@
-// RUN: %clang -### %s 2>&1 | FileCheck %s -check-prefix=STACKPROBE
-// RUN: %clang -### -mno-stack-arg-probe -mstack-arg-probe %s 2>&1 | FileCheck %s -check-prefix=STACKPROBE
-// RUN: %clang -### -mstack-arg-probe -mno-stack-arg-probe %s 2>&1 | FileCheck %s -check-prefix=NO-STACKPROBE
+// RUN: %clang -### --target=unknown-windows-unknown %s 2>&1 | FileCheck %s -check-prefix=STACKPROBE
+// RUN: %clang -### -mno-stack-arg-probe -mstack-arg-probe --target=unknown-windows-unknown %s 2>&1 | FileCheck %s -check-prefix=STACKPROBE
+// RUN: %clang -### -mstack-arg-probe -mno-stack-arg-probe --target=unknown-windows-unknown %s 2>&1 | FileCheck %s -check-prefix=NO-STACKPROBE
+// RUN: not %clang -mno-stack-arg-probe --target=unknown-apple-darwin %s 2>&1 | FileCheck %s --check-prefix=ERROR
 
 // NO-STACKPROBE: -mno-stack-arg-probe
 // STACKPROBE-NOT: -mno-stack-arg-probe
+// ERROR: stack-arg-probe flags are unsupported on Darwin platforms
\ No newline at end of file
diff --git a/compiler-rt/CMakeLists.txt b/compiler-rt/CMakeLists.txt
index 41940bf648bf7c..a3076c5c5f33b2 100644
--- a/compiler-rt/CMakeLists.txt
+++ b/compiler-rt/CMakeLists.txt
@@ -401,6 +401,7 @@ if(NOT COMPILER_RT_DEBUG AND NOT APPLE)
 endif()
 append_list_if(COMPILER_RT_HAS_FUNWIND_TABLES_FLAG -funwind-tables SANITIZER_COMMON_CFLAGS)
 append_list_if(COMPILER_RT_HAS_FNO_STACK_PROTECTOR_FLAG -fno-stack-protector SANITIZER_COMMON_CFLAGS)
+append_list_if(COMPILER_RT_HAS_FNO_STACK_CHECK_FLAG -fno-stack-check SANITIZER_COMMON_CFLAGS)
 append_list_if(COMPILER_RT_HAS_FNO_SANITIZE_SAFE_STACK_FLAG -fno-sanitize=safe-stack SANITIZER_COMMON_CFLAGS)
 append_list_if(COMPILER_RT_HAS_FVISIBILITY_HIDDEN_FLAG -fvisibility=hidden SANITIZER_COMMON_CFLAGS)
 if(NOT COMPILER_RT_HAS_FVISIBILITY_HIDDEN_FLAG)
diff --git a/compiler-rt/cmake/config-ix.cmake b/compiler-rt/cmake/config-ix.cmake
index 1095279ac1ccd4..67b970f6105e00 100644
--- a/compiler-rt/cmake/config-ix.cmake
+++ b/compiler-rt/cmake/config-ix.cmake
@@ -99,6 +99,7 @@ check_cxx_compiler_flag(-fexceptions         COMPILER_RT_HAS_FEXCEPTIONS_FLAG)
 check_cxx_compiler_flag(-fomit-frame-pointer COMPILER_RT_HAS_FOMIT_FRAME_POINTER_FLAG)
 check_cxx_compiler_flag(-funwind-tables      COMPILER_RT_HAS_FUNWIND_TABLES_FLAG)
 check_cxx_compiler_flag(-fno-stack-protector COMPILER_RT_HAS_FNO_STACK_PROTECTOR_FLAG)
+check_cxx_compiler_flag(-fno-stack-check     COMPILER_RT_HAS_FNO_STACK_CHECK_FLAG)
 check_cxx_compiler_flag(-fno-sanitize=safe-stack COMPILER_RT_HAS_FNO_SANITIZE_SAFE_STACK_FLAG)
 check_cxx_compiler_flag(-fvisibility=hidden  COMPILER_RT_HAS_FVISIBILITY_HIDDEN_FLAG)
 check_cxx_compiler_flag(-frtti               COMPILER_RT_HAS_FRTTI_FLAG)
diff --git a/compiler-rt/lib/builtins/CMakeLists.txt b/compiler-rt/lib/builtins/CMakeLists.txt
index bf96a992032144..65d70940019f23 100644
--- a/compiler-rt/lib/builtins/CMakeLists.txt
+++ b/compiler-rt/lib/builtins/CMakeLists.txt
@@ -880,6 +880,13 @@ if (MINGW)
   )
 endif()
 
+if (APPLE)
+  set(aarch64_SOURCES
+      ${aarch64_SOURCES}
+      aarch64/chkstk_darwin.S
+      aarch64/chkstk_darwin2.S)
+endif()
+
 # Don't build enable_execute_stack on arm64 darwin.
 if (APPLE)
   list(REMOVE_ITEM aarch64_SOURCES enable_execute_stack.c)
diff --git a/compiler-rt/lib/builtins/aarch64/chkstk_darwin.S b/compiler-rt/lib/builtins/aarch64/chkstk_darwin.S
new file mode 100644
index 00000000000000..bd21b26d4e8697
--- /dev/null
+++ b/compiler-rt/lib/builtins/aarch64/chkstk_darwin.S
@@ -0,0 +1,61 @@
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+
+#include "../assembly.h"
+
+#ifdef __aarch64__
+
+.subsections_via_symbols
+
+.p2align 2
+.globl ___chkstk_darwin
+.private_extern ___chkstk_darwin
+___chkstk_darwin:
+// Try to use the faster libSystem implementation (3 underscores) if available.
+#if !__STDC_HOSTED__
+        // In a freestanding environment, it's definitely not available,
+        // don't bother even checking.
+        b       ___chkstk_darwin_probe
+
+#else // __STDC_HOSTED__
+        // Otherwise, use a weak import to support backdeployment.
+        .weak_reference ____chkstk_darwin
+
+Lloh0:
+        adrp    x16, ____chkstk_darwin at GOTPAGE
+Lloh1:
+#if __LP64__
+        ldr     x16, [x16, ____chkstk_darwin at GOTPAGEOFF]
+        cbnz     x16, Lavailable
+#else
+        ldr     w16, [x16, ____chkstk_darwin at GOTPAGEOFF]
+        cbnz    w16, Lavailable
+#endif
+        .loh AdrpLdrGot Lloh0, Lloh1
+        b ___chkstk_darwin_probe
+Lavailable:
+        br      x16
+#endif // __STDC_HOSTED__
+
+.p2align 2
+.globl ___chkstk_darwin_probe
+.private_extern ___chkstk_darwin_probe
+___chkstk_darwin_probe:
+        cmp     x9, #1, lsl #12
+        mov     x10, sp
+        b.lo    Lend
+
+Lloop:
+        sub     x10, x10, #1, lsl #12
+        ldrb    wzr, [x10]
+        sub     x9, x9, #1, lsl #12
+        cmp     x9, #1, lsl #12
+        b.hi    Lloop
+
+Lend:
+        sub     x10, x10, x9
+        ldrb    wzr, [x10]
+        ret
+
+#endif // __aarch64__
diff --git a/compiler-rt/lib/builtins/aarch64/chkstk_darwin2.S b/compiler-rt/lib/builtins/aarch64/chkstk_darwin2.S
new file mode 100644
index 00000000000000..78cfd010fb0a5b
--- /dev/null
+++ b/compiler-rt/lib/builtins/aarch64/chkstk_darwin2.S
@@ -0,0 +1,18 @@
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+
+#include "../assembly.h"
+
+#ifdef __aarch64__
+
+.subsections_via_symbols
+
+.p2align 2
+.globl ____chkstk_darwin
+.private_extern ____chkstk_darwin
+____chkstk_darwin:
+// This is the fallback implementation if we weren't able to link libSystem.
+        b    ___chkstk_darwin_probe
+
+#endif // __aarch64__
diff --git a/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp b/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
index 2e0820e5fb06d3..a5b2692bd2ab84 100644
--- a/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
@@ -4894,14 +4894,21 @@ void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
   // Round the size of the allocation up to the stack alignment size
   // by add SA-1 to the size. This doesn't overflow because we're computing
   // an address inside an alloca.
-  AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
-                          DAG.getConstant(StackAlignMask, dl, IntPtr),
-                          SDNodeFlags::NoUnsignedWrap);
-
-  // Mask out the low bits for alignment purposes.
-  AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
-                          DAG.getSignedConstant(~StackAlignMask, dl, IntPtr));
-
+  // For Darwin with stack checking, we delay this rounding until after the
+  // checking routine is called in order to ensure that adding 0xf doesn't
+  // potentially wrap, and therefore even if the allocation amount is a small
+  // wrapped value, we still do a check of the pre-overflow amount.
+  Triple TT = DAG.getTarget().getTargetTriple();
+  if (!TT.isOSDarwin() || TT.getArch() != Triple::aarch64 ||
+      TLI.getStackProbeSymbolName(*FuncInfo.MF).empty()) {
+    AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
+                            DAG.getConstant(StackAlignMask, dl, IntPtr),
+                            SDNodeFlags::NoUnsignedWrap);
+
+    // Mask out the low bits for alignment purposes.
+    AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
+                            DAG.getSignedConstant(~StackAlignMask, dl, IntPtr));
+  }
   SDValue Ops[] = {
       getRoot(), AllocSize,
       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
diff --git a/llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp b/llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp
index c42c0f3de3580a..dba529477fd2fd 100644
--- a/llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp
+++ b/llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp
@@ -166,6 +166,9 @@ class AArch64AsmPrinter : public AsmPrinter {
   void LowerHWASAN_CHECK_MEMACCESS(const MachineInstr &MI);
   void emitHwasanMemaccessSymbols(Module &M);
 
+  void LowerStkChkIndirectCall(const MachineInstr &MI);
+  void LowerPtrAuthStkChkIndirectCall(const MachineInstr &MI);
+
   void emitSled(const MachineInstr &MI, SledKind Kind);
 
   // Returns whether Reg may be used to store sensitive temporary values when
@@ -398,6 +401,16 @@ class AArch64AsmPrinter : public AsmPrinter {
 
   MInstToMCSymbol LOHInstToLabel;
 
+  // LOHs for instructions emitted directly by the AsmPrinter (e.g. when
+  // lowering StkChkIndirectCall), which aren't in the LOH container.
+  struct LateLOHEntry {
+    MCLOHType Kind;
+    SmallVector<MCSymbol *, 4> Syms;
+    LateLOHEntry(MCLOHType Kind, SmallVectorImpl<MCSymbol *> &Syms)
+        : Kind(Kind), Syms(Syms.begin(), Syms.end()) {}
+  };
+  SmallVector<struct LateLOHEntry> LateLOHs;
+
   bool shouldEmitWeakSwiftAsyncExtendedFramePointerFlags() const override {
     return ShouldEmitWeakSwiftAsyncExtendedFramePointerFlags;
   }
@@ -1042,6 +1055,134 @@ void AArch64AsmPrinter::emitHwasanMemaccessSymbols(Module &M) {
   this->STI = nullptr;
 }
 
+void AArch64AsmPrinter::LowerStkChkIndirectCall(const MachineInstr &MI) {
+  const MachineBasicBlock &MBB = *MI.getParent();
+  const MachineFunction &MF = *MBB.getParent();
+
+  if (MF.getFunction().hasFnAttribute("ptrauth-calls"))
+    return LowerPtrAuthStkChkIndirectCall(MI);
+
+  StringRef TargetFn = "__chkstk_darwin";
+  if (!STI->getTargetLowering()->getStackProbeSymbolName(MF).empty())
+    TargetFn = STI->getTargetLowering()->getStackProbeSymbolName(MF);
+
+  // We emit:
+  // ADRP x16, symbol
+  // LDR x16, x16, sym offset
+  // BLR x16
+  // We also expect x9 as an input to contain the amount of bytes
+  // to check.
+  MCSymbol *TargetFnSym = OutContext.getOrCreateSymbol(
+      Twine(MF.getDataLayout().getGlobalPrefix()) + TargetFn);
+
+  unsigned LDROpcode, LDRDstReg;
+  if (STI->isTargetILP32()) {
+    LDROpcode = AArch64::LDRWui;
+    LDRDstReg = AArch64::W16;
+  } else {
+    LDROpcode = AArch64::LDRXui;
+    LDRDstReg = AArch64::X16;
+  }
+
+  MCSymbol *LOHLabel = createTempSymbol("loh");
+  OutStreamer->emitLabel(LOHLabel);
+
+  OutStreamer->emitInstruction(
+      MCInstBuilder(AArch64::ADRP)
+          .addReg(AArch64::X16)
+          .addExpr(MCSymbolRefExpr::create(
+              TargetFnSym, AArch64::S_MACHO_GOTPAGE, OutContext)),
+      *STI);
+
+  MCSymbol *LOHLabel2 = createTempSymbol("loh");
+  OutStreamer->emitLabel(LOHLabel2);
+
+  OutStreamer->emitInstruction(
+      MCInstBuilder(LDROpcode)
+          .addReg(LDRDstReg)
+          .addReg(AArch64::X16)
+          .addExpr(MCSymbolRefExpr::create(
+              TargetFnSym, AArch64::S_MACHO_GOTPAGEOFF, OutContext)),
+      *STI);
+
+  OutStreamer->emitInstruction(
+      MCInstBuilder(AArch64::BLR).addReg(AArch64::X16).addReg(AArch64::X9),
+      *STI);
+
+  SmallVector<MCSymbol *, 2> MCArgs({LOHLabel, LOHLabel2});
+  LateLOHs.push_back(LateLOHEntry(MCLOH_AdrpLdrGot, MCArgs));
+}
+
+void AArch64AsmPrinter::LowerPtrAuthStkChkIndirectCall(
+    const MachineInstr &MI) {
+  const MachineBasicBlock &MBB = *MI.getParent();
+  const MachineFunction &MF = *MBB.getParent();
+  auto *MachOTLOF =
+    static_cast<AArch64_MachoTargetObjectFile *>(TM.getObjFileLowering());
+
+  StringRef TargetFn = "__chkstk_darwin";
+  if (!STI->getTargetLowering()->getStackProbeSymbolName(MF).empty())
+    TargetFn = STI->getTargetLowering()->getStackProbeSymbolName(MF);
+
+  MCSymbol *TargetFnSym = OutContext.getOrCreateSymbol(
+      Twine(MF.getDataLayout().getGlobalPrefix()) + TargetFn);
+
+  MCSymbol *LOHLabel = createTempSymbol("loh");
+  OutStreamer->emitLabel(LOHLabel);
+
+  // On arm64e with ptrauth-calls we emit:
+  // ADRP X17, l_symbol$auth_ptr$ia$0$addr at PAGE
+  // ADD X17, X17, l_symbol$auth_ptr$ia$0$addr at PAGEOFF
+  // LDR X16, [X17]
+  // BLRAA X16, X17
+  //
+  // Where the $auth_ptr$ symbol is the stub slot containing the signed pointer
+  // to _symbol, with the scheme matching the BLRAA.
+  // We defined the stub ourselves, so we don't need a GOT access.
+  // Note that this isn't beholden to any kind of ABI constraint, so we use
+  // a function-specific scheme.  Address-diversity without a blended constant
+  // discriminator is the cheapest that's still uniquable.
+  //
+  // We also expect x9 as an input to contain the amount of bytes to check.
+
+  TargetFnSym = MachOTLOF->getAuthPtrSlotSymbol(
+      TM, MMI, TargetFnSym, AArch64PACKey::IA,
+      /*Discriminator=*/0, /*HasAddressDiversity=*/true);
+
+  OutStreamer->emitInstruction(
+      MCInstBuilder(AArch64::ADRP)
+          .addReg(AArch64::X17)
+          .addExpr(MCSymbolRefExpr::create(
+              TargetFnSym, AArch64::S_MACHO_PAGE, OutContext)),
+      *STI);
+
+  MCSymbol *LOHLabel2 = createTempSymbol("loh");
+  OutStreamer->emitLabel(LOHLabel2);
+  OutStreamer->emitInstruction(
+      MCInstBuilder(AArch64::ADDXri)
+          .addReg(AArch64::X17)
+          .addReg(AArch64::X17)
+          .addExpr(MCSymbolRefExpr::create(
+              TargetFnSym, AArch64::S_MACHO_PAGEOFF, OutContext))
+          .addImm(0),
+      *STI);
+
+  OutStreamer->emitInstruction(MCInstBuilder(AArch64::LDRXui)
+                                   .addReg(AArch64::X16)
+                                   .addReg(AArch64::X17)
+                                   .addImm(0),
+                               *STI);
+
+  OutStreamer->emitInstruction(MCInstBuilder(AArch64::BLRAA)
+                                   .addReg(AArch64::X16)
+                                   .addReg(AArch64::X17)
+                                   .addReg(AArch64::X9),
+                               *STI);
+
+  SmallVector<MCSymbol *, 2> MCArgs({LOHLabel, LOHLabel2});
+  LateLOHs.push_back(LateLOHEntry(MCLOH_AdrpAdd, MCArgs));
+}
+
 static void emitAuthenticatedPointer(MCStreamer &OutStreamer,
                                      MCSymbol *StubLabel,
                                      const MCExpr *StubAuthPtrRef) {
@@ -1166,6 +1307,9 @@ void AArch64AsmPrinter::emitLOHs() {
     OutStreamer->emitLOHDirective(D.getKind(), MCArgs);
     MCArgs.clear();
   }
+  for (auto &E : LateLOHs)
+    OutStreamer->emitLOHDirective(E.Kind, E.Syms);
+  LateLOHs.clear();
 }
 
 // Unwinding can get confused if the last instruction in an exception-handling
@@ -1200,7 +1344,7 @@ void AArch64AsmPrinter::emitFunctionBodyEnd() {
          "functions. If a function is flagged then it must have explicit "
          "Windows CFI ranges.");
 #endif
-  if (!AArch64FI->getLOHRelated().empty())
+  if (!AArch64FI->getLOHRelated().empty() || !LateLOHs.empty())
     emitLOHs();
 }
 
@@ -4036,6 +4180,10 @@ void AArch64AsmPrinter::emitInstructionImpl(const MachineInstr *MI) {
     OutStreamer->emitWinCFIEndProc();
     return;
 
+  case AArch64::StkChkIndirectCall:
+    LowerStkChkIndirectCall(*MI);
+    return;
+
   case AArch64::SEH_EndC:
     TS->emitARM64WinCFIEndC();
     return;
diff --git a/llvm/lib/Target/AArch64/AArch64CallingConvention.td b/llvm/lib/Target/AArch64/AArch64CallingConvention.td
index 5ad6045c09f509..2c60673043d3b1 100644
--- a/llvm/lib/Target/AArch64/AArch64CallingConvention.td
+++ b/llvm/lib/Target/AArch64/AArch64CallingConvention.td
@@ -830,3 +830,10 @@ def CSR_AArch64_SVE_AAPCS_SCS
     : CalleeSavedRegs<(add CSR_AArch64_SVE_AAPCS, X18)>;
 def CSR_AArch64_AAPCS_SCS
     : CalleeSavedRegs<(add CSR_AArch64_AAPCS, X18)>;
+
+// Darwin stack probing function CSRs. Registers X9-X11 are used, LR since it's
+// a call.
+def CSR_AArch64_StackProbe_Darwin
+    : CalleeSavedRegs<(add (sequence "X%u", 0, 8),
+                           (sequence "X%u", 12, 28), FP, SP,
+                           (sequence "Q%u", 0, 31))>;
diff --git a/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp b/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
index 3ca8e19b2ce07f..9a97db9431a54f 100644
--- a/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
+++ b/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
@@ -18706,6 +18706,8 @@ AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
     return LowerWindowsDYNAMIC_STACKALLOC(Op, DAG);
   else if (hasInlineStackProbe(MF))
     return LowerInlineDYNAMIC_STACKALLOC(Op, DAG);
+  else if (Subtarget->isTargetDarwin())
+    return LowerDarwinDYNAMIC_STACKALLOC(Op, DAG);
   else
     return SDValue();
 }
@@ -18719,6 +18721,59 @@ SDValue AArch64TargetLowering::LowerAVG(SDValue Op, SelectionDAG &DAG,
   return SDValue();
 }
 
+SDValue
+AArch64TargetLowering::LowerDarwinDYNAMIC_STACKALLOC(SDValue Op,
+                                                     SelectionDAG &DAG) const {
+  assert(Subtarget->isTargetDarwin() && "Must be Darwin target");
+  SDLoc DL(Op);
+  // Get the inputs.
+  SDNode *Node = Op.getNode();
+  SDValue Chain = Op.getOperand(0);
+  SDValue Size = Op.getOperand(1);
+
+  MaybeAlign Align =
+      cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
+  EVT VT = Node->getValueType(0);
+
+  MachineFunction &MF = DAG.getMachineFunction();
+  StringRef ProbeSym =
+      MF.getFunction().getFnAttribute("probe-stack").getValueAsString();
+  if (ProbeSym == "")
+    return SDValue();
+
+  Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
+
+  Chain = DAG.getCopyToReg(Chain, DL, AArch64::X9, Size, SDValue());
+  const auto Mask =
+      Subtarget->getRegisterInfo()->getDarwinStackProbePreservedMask();
+  auto CallPseudo =
+      DAG.getMachineNode(AArch64::StkChkIndirectCall, DL, MVT::Other,
+                         DAG.getRegisterMask(Mask), Chain.getValue(0));
+  Chain = SDValue(CallPseudo, 0);
+
+  // For Darwin arm64 we delayed rounding up to stack alignment so we could do
+  // the check before any potential overflow occured. Now we do it here.
+  SDNodeFlags Flags;
+  Flags.setNoUnsignedWrap(true);
+  Size = DAG.getNode(ISD::ADD, DL, Size.getValueType(), Size,
+                     DAG.getConstant(15, DL, MVT::i64), Flags);
+  Size = DAG.getNode(ISD::AND, DL, Size.getValueType(), Size,
+                     DAG.getConstant(~(uint64_t)(15), DL, MVT::i64));
+
+  SDValue SP = DAG.getCopyFromReg(Chain, DL, AArch64::SP, MVT::i64);
+  Chain = SP.getValue(1);
+  SP = DAG.getNode(ISD::SUB, DL, MVT::i64, SP, Size);
+  if (Align)
+    SP = DAG.getNode(ISD::AND, DL, VT, SP.getValue(0),
+                     DAG.getConstant(-(uint64_t)Align->value(), DL, VT));
+  Chain = DAG.getCopyToReg(Chain, DL, AArch64::SP, SP);
+
+  Chain = DAG.getCALLSEQ_END(Chain, 0, 0, SDValue(), DL);
+
+  SDValue Ops[2] = {SP, Chain};
+  return DAG.getMergeValues(Ops, DL);
+}
+
 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
                                            SelectionDAG &DAG) const {
   EVT VT = Op.getValueType();
@@ -34717,6 +34772,14 @@ void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
 // Unlike X86, we let frame lowering assign offsets to all catch objects.
 bool AArch64TargetLowering::needsFixedCatchObjects() const { return true; }
 
+StringRef
+AArch64TargetLowering::getStackProbeSymbolName(const MachineFunction &MF) const {
+  // If the function specifically requests stack probes, emit them.
+  if (MF.getFunction().hasFnAttribute("probe-stack"))
+    return MF.getFunction().getFnAttribute("probe-stack").getValueAsString();
+  return "";
+}
+
 bool AArch64TargetLowering::shouldLocalize(
     const MachineInstr &MI, const TargetTransformInfo *TTI) const {
   auto &MF = *MI.getMF();
@@ -37379,8 +37442,10 @@ unsigned AArch64TargetLowering::getVectorTypeBreakdownForCallingConv(
 
 bool AArch64TargetLowering::hasInlineStackProbe(
     const MachineFunction &MF) const {
+  StringRef ProbeSym = getStackProbeSymbolName(MF);
   return !Subtarget->isTargetWindowsOrUEFI() &&
-         MF.getInfo<AArch64FunctionInfo>()->hasStackProbing();
+         MF.getInfo<AArch64FunctionInfo>()->hasStackProbing() &&
+         (ProbeSym == "inline-asm" || ProbeSym == "");
 }
 
 bool AArch64TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
diff --git a/llvm/lib/Target/AArch64/AArch64ISelLowering.h b/llvm/lib/Target/AArch64/AArch64ISelLowering.h
index a074f76a7e0d8f..33cc534c5fbf8c 100644
--- a/llvm/lib/Target/AArch64/AArch64ISelLowering.h
+++ b/llvm/lib/Target/AArch64/AArch64ISelLowering.h
@@ -546,6 +546,8 @@ class AArch64TargetLowering : public TargetLowering {
   /// Used for exception handling on Win64.
   bool needsFixedCatchObjects() const override;
 
+  StringRef getStackProbeSymbolName(const MachineFunction &MF) const override;
+
   bool fallBackToDAGISel(const Instruction &Inst) const override;
 
   /// SVE code generation for fixed length vectors does not custom lower
@@ -812,6 +814,7 @@ class AArch64TargetLowering : public TargetLowering {
   SDValue LowerVECREDUCE_MUL(SDValue Op, SelectionDAG &DAG) const;
   SDValue LowerWindowsDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const;
   SDValue LowerInlineDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const;
+  SDValue LowerDarwinDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const;
   SDValue LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const;
   SDValue LowerMSTORE(SDValue Op, SelectionDAG &DAG) const;
   SDValue LowerFCANONICALIZE(SDValue Op, SelectionDAG &DAG) const;
diff --git a/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp b/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
index 9542fe85db82e3..0c7ef6f8688c31 100644
--- a/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
+++ b/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
@@ -304,6 +304,10 @@ AArch64InstrInfo::getInstSizeInBytesNoGuard(const MachineInstr &MI) const {
     NumBytes = 24;
     break;
 
+  case AArch64::StkChkIndirectCall:
+    NumBytes = F.hasFnAttribute("ptrauth-calls") ? 16 : 12;
+    break;
+
   case AArch64::SPACE:
     NumBytes = MI.getOperand(1).getImm();
     break;
diff --git a/llvm/lib/Target/AArch64/AArch64InstrInfo.td b/llvm/lib/Target/AArch64/AArch64InstrInfo.td
index 803de33f529538..e415c760b210ab 100644
--- a/llvm/lib/Target/AArch64/AArch64InstrInfo.td
+++ b/llvm/lib/Target/AArch64/AArch64InstrInfo.td
@@ -1593,6 +1593,15 @@ def BR_JumpTable : Pseudo<(outs), (ins i32imm:$jti), []>, Sched<[]> {
   let Size = 44; // 28 fixed + 16 variable, for table size materialization
 }
 
+// In order to prevent the address register of the Darwin stack checking
+// function from being spilled, and thus potentially exposed to corruption,
+// we bundle the addr materialization and branch into this pseudo.
+def StkChkIndirectCall : Pseudo<(outs), (ins), []>, Sched<[]> {
+  let isCall = 1;
+  let Uses = [X9, SP];
+  let Defs = [LR, X16, X17];
+}
+
 // Space-consuming pseudo to aid testing of placement and reachability
 // algorithms. Immediate operand is the number of bytes this "instruction"
 // occupies; register operands can be used to enforce dependency and constrain
diff --git a/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp b/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp
index 94b0bcacd9e11d..552004b4c41770 100644
--- a/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp
+++ b/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp
@@ -174,7 +174,7 @@ AArch64FunctionInfo::AArch64FunctionInfo(const Function &F,
                  F.getParent()->getModuleFlag("probe-stack")))
       ProbeKind = PS->getString();
     if (ProbeKind.size()) {
-      if (ProbeKind != "inline-asm")
+      if (ProbeKind != "inline-asm" && ProbeKind != "__chkstk_darwin")
         report_fatal_error("Unsupported stack probing method");
       StackProbeSize = ProbeSize;
     }
diff --git a/llvm/lib/Target/AArch64/AArch64PrologueEpilogue.cpp b/llvm/lib/Target/AArch64/AArch64PrologueEpilogue.cpp
index 8c755056c205d1..527b220134892c 100644
--- a/llvm/lib/Target/AArch64/AArch64PrologueEpilogue.cpp
+++ b/llvm/lib/Target/AArch64/AArch64PrologueEpilogue.cpp
@@ -483,6 +483,33 @@ void AArch64PrologueEmitter::verifyPrologueClobbers() const {
   // Check if any of the newly instructions clobber any of the live registers.
   for (MachineInstr &MI :
        make_range(MBB.instr_begin(), PrologueEndI->getIterator())) {
+
+    const AArch64FunctionInfo &MFI = *MF.getInfo<AArch64FunctionInfo>();
+    if (MFI.hasStackProbing()) {
+      // Darwin stack probing may spill some live registers and restore them
+      // later. Update their liveness here accordingly.
+      auto StackProbeSpilledReg = [](Register Reg) {
+        return Reg == AArch64::X9 || Reg == AArch64::X10 ||
+               Reg == AArch64::X11 || Reg == AArch64::X12 ||
+               Reg == AArch64::X16 || Reg == AArch64::X17;
+      };
+      if (MI.getOpcode() == AArch64::STPXpre) {
+        Register R1 = MI.getOperand(1).getReg();
+        Register R2 = MI.getOperand(2).getReg();
+        if (StackProbeSpilledReg(R1))
+          LiveRegs.removeReg(R1);
+        if (StackProbeSpilledReg(R2))
+          LiveRegs.removeReg(R2);
+      } else if (MI.getOpcode() == AArch64::LDPXpre) {
+        Register R1 = MI.getOperand(1).getReg();
+        Register R2 = MI.getOperand(2).getReg();
+        if (StackProbeSpilledReg(R1))
+          LiveRegs.addReg(R1);
+        if (StackProbeSpilledReg(R2))
+          LiveRegs.addReg(R2);
+      }
+    }
+
     for (auto &Op : MI.operands())
       if (Op.isReg() && Op.isDef())
         assert(!LiveRegs.contains(Op.getReg()) &&
@@ -712,6 +739,14 @@ void AArch64PrologueEmitter::emitPrologue() {
   else
     AFI->setTaggedBasePointerOffset(MFI.getStackSize());
 
+  int StackProbeSize = 4096;
+  if (F.hasFnAttribute("stack-probe-size"))
+    F.getFnAttribute("stack-probe-size")
+        .getValueAsString()
+        .getAsInteger(0, StackProbeSize);
+  StringRef ProbeSym =
+      Subtarget.getTargetLowering()->getStackProbeSymbolName(MF);
+
   // getStackSize() includes all the locals in its size calculation. We don't
   // include these locals when computing the stack size of a funclet, as they
   // are allocated in the parent's stack frame and accessed via the frame
@@ -721,7 +756,8 @@ void AArch64PrologueEmitter::emitPrologue() {
   int64_t NumBytes =
       IsFunclet ? AFL.getWinEHFuncletFrameSize(MF) : MFI.getStackSize();
   if (!AFI->hasStackFrame() && !AFL.windowsRequiresStackProbe(MF, NumBytes))
-    return emitEmptyStackFramePrologue(NumBytes, PrologueBeginI, DL);
+    return emitEmptyStackFramePrologue(NumBytes, PrologueBeginI, DL,
+                                       StackProbeSize, ProbeSym);
 
   bool IsWin64 = Subtarget.isCallingConvWin64(F.getCallingConv(), F.isVarArg());
   unsigned FixedObject = AFL.getFixedObjectSize(MF, AFI, IsWin64, IsFunclet);
@@ -848,7 +884,15 @@ void AArch64PrologueEmitter::emitPrologue() {
   // stack as necessary.
   assert(!(AFL.canUseRedZone(MF) && NeedsRealignment) &&
          "Cannot use redzone with stack realignment");
-  if (!AFL.canUseRedZone(MF)) {
+  if (NumBytes >= StackProbeSize && ProbeSym != "" &&
+      ProbeSym != "inline-asm") {
+    // We need to emit a call to the stack probe function. Note that we still
+    // need to adjust SP, the probing doesn't modify it.
+    emitDarwinStackProbe(AfterSVESavesI, DL, NumBytes);
+    allocateStackSpace(AfterSVESavesI, RealignmentPadding, SVEAllocs.AfterZPRs,
+                       EmitAsyncCFI && !HasFP, CFAOffset,
+                       MFI.hasVarSizedObjects());
+  } else if (!AFL.canUseRedZone(MF)) {
     // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have the
     // correct value here, as NumBytes also includes padding bytes, which
     // shouldn't be counted here.
@@ -994,7 +1038,7 @@ void AArch64PrologueEmitter::emitSwiftAsyncContextFramePointer(
 
 void AArch64PrologueEmitter::emitEmptyStackFramePrologue(
     int64_t NumBytes, MachineBasicBlock::iterator MBBI,
-    const DebugLoc &DL) const {
+    const DebugLoc &DL, int StackProbeSize, StringRef ProbeSym) const {
   assert(!HasFP && "unexpected function without stack frame but with FP");
   assert(!AFL.getSVEStackSize(MF) &&
          "unexpected function without stack frame but with SVE objects");
@@ -1013,6 +1057,10 @@ void AArch64PrologueEmitter::emitEmptyStackFramePrologue(
     AFI->setHasRedZone(true);
     ++NumRedZoneFunctions;
   } else {
+    if (NumBytes >= StackProbeSize && ProbeSym != "" &&
+        ProbeSym != "inline-asm")
+      emitDarwinStackProbe(MBBI, DL, NumBytes);
+
     emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
                     StackOffset::getFixed(-NumBytes), TII,
                     MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI);
@@ -1099,6 +1147,131 @@ void AArch64PrologueEmitter::emitDefineCFAWithFP(
       .buildDefCFA(FramePtr, FixedObject - OffsetToFirstCalleeSaveFromFP);
 }
 
+static bool isRegLiveIn(MachineBasicBlock &MBB, unsigned PhysReg) {
+  for (MachineBasicBlock::RegisterMaskPair RegMask : MBB.liveins()) {
+    unsigned Reg = RegMask.PhysReg;
+    if (Reg == PhysReg)
+      return true;
+  }
+  return false;
+}
+
+// Emit a stack probing function call at the specified location.
+void AArch64PrologueEmitter::emitDarwinStackProbe(
+    MachineBasicBlock::iterator MBBI, DebugLoc DL, unsigned NumBytes) const {
+  const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
+  const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
+
+  // If the LR has already been saved we don't need to save it before calling
+  // the probe function. However if it hasn't then the probe will clobber it.
+  bool LRIsSaved =
+      std::any_of(CSI.begin(), CSI.end(), [](const CalleeSavedInfo &SI) {
+        return SI.getReg() == AArch64::LR;
+      });
+  if (!LRIsSaved) {
+    // LR wasn't saved as a CSR, so we need to save it ourselves. We don't
+    // bother updating SP, as we know the probe function won't modify any
+    // memory.
+    BuildMI(MBB, MBBI, DL, TII->get(AArch64::STRXpre))
+        .addReg(AArch64::SP, RegState::Define)
+        .addReg(AArch64::LR)
+        .addReg(AArch64::SP)
+        .addImm(-16) // Keep SP 16 byte aligned.
+        .setMIFlags(MachineInstr::FrameSetup);
+  }
+
+  bool SaveScratchRegs = false;
+  // Shrink wrapping may change our insertion block for the prolog code, so the
+  // X9, X10, X11, X12, X16 or X17 registers may be live at this point.
+  bool X16Live = false;
+  bool X17Live = false;
+  if (&MBB != &MF.front()) {
+    bool X9Live =
+        isRegLiveIn(MBB, AArch64::W9) || isRegLiveIn(MBB, AArch64::X9);
+    bool X10Live =
+        isRegLiveIn(MBB, AArch64::W10) || isRegLiveIn(MBB, AArch64::X10);
+    bool X11Live =
+        isRegLiveIn(MBB, AArch64::W11) || isRegLiveIn(MBB, AArch64::X11);
+    bool X12Live =
+        isRegLiveIn(MBB, AArch64::W12) || isRegLiveIn(MBB, AArch64::X12);
+    X16Live = isRegLiveIn(MBB, AArch64::W16) || isRegLiveIn(MBB, AArch64::X16);
+    X17Live = isRegLiveIn(MBB, AArch64::W17) || isRegLiveIn(MBB, AArch64::X17);
+    SaveScratchRegs = true;
+    BuildMI(MBB, MBBI, DL, TII->get(AArch64::STPXpre))
+        .addReg(AArch64::SP, RegState::Define)
+        .addReg(AArch64::X9, X9Live ? RegState::NoFlags : RegState::Undef)
+        .addReg(AArch64::X10, X10Live ? RegState::NoFlags : RegState::Undef)
+        .addReg(AArch64::SP)
+        .addImm(-2)
+        .setMIFlags(MachineInstr::FrameSetup);
+    BuildMI(MBB, MBBI, DL, TII->get(AArch64::STPXpre))
+        .addReg(AArch64::SP, RegState::Define)
+        .addReg(AArch64::X11, X11Live ? RegState::NoFlags : RegState::Undef)
+        .addReg(AArch64::X12, X12Live ? RegState::NoFlags : RegState::Undef)
+        .addReg(AArch64::SP)
+        .addImm(-2)
+        .setMIFlags(MachineInstr::FrameSetup);
+    if (X16Live || X17Live)
+      BuildMI(MBB, MBBI, DL, TII->get(AArch64::STPXpre))
+          .addReg(AArch64::SP, RegState::Define)
+          .addReg(AArch64::X16, X16Live ? RegState::NoFlags : RegState::Undef)
+          .addReg(AArch64::X17, X17Live ? RegState::NoFlags : RegState::Undef)
+          .addReg(AArch64::SP)
+          .addImm(-2)
+          .setMIFlags(MachineInstr::FrameSetup);
+  }
+
+  // We pass the number of bytes to check to the probe function in register
+  // W9, a temporary register that we can use in places like the prolog. The
+  // probe function should preserve all registers except X9, X10, X11 and LR.
+
+  // To materalize the probe size, we emit a MOVi32imm pseudo-instruction which
+  // will later get expanded into either an ORR Wd, Wzr, #bimm32 or into a
+  // sequence of MOV instructions depending on the value.
+  BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi32imm))
+      .addReg(AArch64::W9, RegState::Define)
+      .addImm(NumBytes)
+      .setMIFlags(MachineInstr::FrameSetup);
+
+  BuildMI(MBB, MBBI, DL, TII->get(AArch64::StkChkIndirectCall))
+    .addRegMask(RegInfo->getDarwinStackProbePreservedMask())
+    .setMIFlags(MachineInstr::FrameSetup);
+
+  if (SaveScratchRegs) {
+    if (X16Live || X17Live)
+      BuildMI(MBB, MBBI, DL, TII->get(AArch64::LDPXpost))
+          .addReg(AArch64::SP, RegState::Define)
+          .addReg(AArch64::X16, RegState::Define)
+          .addReg(AArch64::X17, RegState::Define)
+          .addReg(AArch64::SP)
+          .addImm(2)
+          .setMIFlags(MachineInstr::FrameSetup);
+    BuildMI(MBB, MBBI, DL, TII->get(AArch64::LDPXpost))
+        .addReg(AArch64::SP, RegState::Define)
+        .addReg(AArch64::X11, RegState::Define)
+        .addReg(AArch64::X12, RegState::Define)
+        .addReg(AArch64::SP)
+        .addImm(2)
+        .setMIFlags(MachineInstr::FrameSetup);
+    BuildMI(MBB, MBBI, DL, TII->get(AArch64::LDPXpost))
+        .addReg(AArch64::SP, RegState::Define)
+        .addReg(AArch64::X9, RegState::Define)
+        .addReg(AArch64::X10, RegState::Define)
+        .addReg(AArch64::SP)
+        .addImm(2)
+        .setMIFlags(MachineInstr::FrameSetup);
+  }
+  if (!LRIsSaved) {
+    // Restore LR.
+    BuildMI(MBB, MBBI, DL, TII->get(AArch64::LDRXpost))
+        .addReg(AArch64::SP, RegState::Define)
+        .addReg(AArch64::LR, RegState::Define)
+        .addReg(AArch64::SP)
+        .addImm(16)
+        .setMIFlags(MachineInstr::FrameSetup);
+  }
+}
+
 void AArch64PrologueEmitter::emitWindowsStackProbe(
     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, int64_t &NumBytes,
     int64_t RealignmentPadding) const {
diff --git a/llvm/lib/Target/AArch64/AArch64PrologueEpilogue.h b/llvm/lib/Target/AArch64/AArch64PrologueEpilogue.h
index 78e113c32e7af8..da4ba996123b13 100644
--- a/llvm/lib/Target/AArch64/AArch64PrologueEpilogue.h
+++ b/llvm/lib/Target/AArch64/AArch64PrologueEpilogue.h
@@ -131,7 +131,9 @@ class AArch64PrologueEmitter final : public AArch64PrologueEpilogueCommon {
 
   void emitEmptyStackFramePrologue(int64_t NumBytes,
                                    MachineBasicBlock::iterator MBBI,
-                                   const DebugLoc &DL) const;
+                                   const DebugLoc &DL,
+                                   int StackProbeSize,
+                                   StringRef ProbeSym) const;
 
   void emitFramePointerSetup(MachineBasicBlock::iterator MBBI,
                              const DebugLoc &DL, unsigned FixedObject);
@@ -143,6 +145,9 @@ class AArch64PrologueEmitter final : public AArch64PrologueEpilogueCommon {
                              const DebugLoc &DL, int64_t &NumBytes,
                              int64_t RealignmentPadding) const;
 
+  void emitDarwinStackProbe(MachineBasicBlock::iterator MBBI, DebugLoc DL,
+                            unsigned NumBytes) const;
+
   void emitCalleeSavedGPRLocations(MachineBasicBlock::iterator MBBI) const;
   void emitCalleeSavedSVELocations(MachineBasicBlock::iterator MBBI) const;
 
diff --git a/llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp b/llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp
index 9bbd7e0e4eabe0..614643838e25db 100644
--- a/llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp
+++ b/llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp
@@ -388,6 +388,10 @@ const uint32_t *AArch64RegisterInfo::getWindowsStackProbePreservedMask() const {
   return CSR_AArch64_StackProbe_Windows_RegMask;
 }
 
+const uint32_t *AArch64RegisterInfo::getDarwinStackProbePreservedMask() const {
+  return CSR_AArch64_StackProbe_Darwin_RegMask;
+}
+
 std::optional<std::string>
 AArch64RegisterInfo::explainReservedReg(const MachineFunction &MF,
                                         MCRegister PhysReg) const {
diff --git a/llvm/lib/Target/AArch64/AArch64RegisterInfo.h b/llvm/lib/Target/AArch64/AArch64RegisterInfo.h
index 4b577e7206f2f3..1247a65fddaa90 100644
--- a/llvm/lib/Target/AArch64/AArch64RegisterInfo.h
+++ b/llvm/lib/Target/AArch64/AArch64RegisterInfo.h
@@ -96,6 +96,7 @@ class AArch64RegisterInfo final : public AArch64GenRegisterInfo {
 
   /// Stack probing calls preserve different CSRs to the normal CC.
   const uint32_t *getWindowsStackProbePreservedMask() const;
+  const uint32_t *getDarwinStackProbePreservedMask() const;
 
   BitVector getStrictlyReservedRegs(const MachineFunction &MF) const;
   BitVector getUserReservedRegs(const MachineFunction &MF) const;
diff --git a/llvm/lib/Target/AArch64/AArch64TargetObjectFile.cpp b/llvm/lib/Target/AArch64/AArch64TargetObjectFile.cpp
index 8acf29159bc797..931bf8b69f00a7 100644
--- a/llvm/lib/Target/AArch64/AArch64TargetObjectFile.cpp
+++ b/llvm/lib/Target/AArch64/AArch64TargetObjectFile.cpp
@@ -126,13 +126,14 @@ template <typename MachineModuleInfoTarget>
 static MCSymbol *getAuthPtrSlotSymbolHelper(
     MCContext &Ctx, const TargetMachine &TM, MachineModuleInfo *MMI,
     MachineModuleInfoTarget &TargetMMI, const MCSymbol *RawSym,
-    AArch64PACKey::ID Key, uint16_t Discriminator) {
+    AArch64PACKey::ID Key, uint16_t Discriminator,
+    bool HasAddressDiversity = false) {
   const DataLayout &DL = MMI->getModule()->getDataLayout();
 
   MCSymbol *StubSym = Ctx.getOrCreateSymbol(
       DL.getLinkerPrivateGlobalPrefix() + RawSym->getName() +
       Twine("$auth_ptr$") + AArch64PACKeyIDToString(Key) + Twine('$') +
-      Twine(Discriminator));
+      Twine(Discriminator) + (HasAddressDiversity ? "$addr" : ""));
 
   const MCExpr *&StubAuthPtrRef = TargetMMI.getAuthPtrStubEntry(StubSym);
 
@@ -141,9 +142,8 @@ static MCSymbol *getAuthPtrSlotSymbolHelper(
 
   const MCExpr *Sym = MCSymbolRefExpr::create(RawSym, Ctx);
 
-  StubAuthPtrRef =
-      AArch64AuthMCExpr::create(Sym, Discriminator, Key,
-                                /*HasAddressDiversity=*/false, Ctx);
+  StubAuthPtrRef = AArch64AuthMCExpr::create(Sym, Discriminator, Key,
+                                             HasAddressDiversity, Ctx);
   return StubSym;
 }
 
@@ -157,10 +157,11 @@ MCSymbol *AArch64_ELFTargetObjectFile::getAuthPtrSlotSymbol(
 
 MCSymbol *AArch64_MachoTargetObjectFile::getAuthPtrSlotSymbol(
     const TargetMachine &TM, MachineModuleInfo *MMI, const MCSymbol *RawSym,
-    AArch64PACKey::ID Key, uint16_t Discriminator) const {
+    AArch64PACKey::ID Key, uint16_t Discriminator,
+    bool HasAddressDiversity) const {
   auto &MachOMMI = MMI->getObjFileInfo<MachineModuleInfoMachO>();
   return getAuthPtrSlotSymbolHelper(getContext(), TM, MMI, MachOMMI, RawSym,
-                                    Key, Discriminator);
+                                    Key, Discriminator, HasAddressDiversity);
 }
 
 static bool isExecuteOnlyFunction(const GlobalObject *GO, SectionKind Kind,
diff --git a/llvm/lib/Target/AArch64/AArch64TargetObjectFile.h b/llvm/lib/Target/AArch64/AArch64TargetObjectFile.h
index 3b3abf3a6017f9..95727d6304366a 100644
--- a/llvm/lib/Target/AArch64/AArch64TargetObjectFile.h
+++ b/llvm/lib/Target/AArch64/AArch64TargetObjectFile.h
@@ -72,8 +72,8 @@ class AArch64_MachoTargetObjectFile : public TargetLoweringObjectFileMachO {
 
   MCSymbol *getAuthPtrSlotSymbol(const TargetMachine &TM,
                                  MachineModuleInfo *MMI, const MCSymbol *RawSym,
-                                 AArch64PACKey::ID Key,
-                                 uint16_t Discriminator) const;
+                                 AArch64PACKey::ID Key, uint16_t Discriminator,
+                                 bool HasAddressDiversity = false) const;
 };
 
 /// This implementation is used for AArch64 COFF targets.
diff --git a/llvm/lib/Target/AArch64/GISel/AArch64LegalizerInfo.cpp b/llvm/lib/Target/AArch64/GISel/AArch64LegalizerInfo.cpp
index 4b63c0ee4f98b4..b15fd18824929f 100644
--- a/llvm/lib/Target/AArch64/GISel/AArch64LegalizerInfo.cpp
+++ b/llvm/lib/Target/AArch64/GISel/AArch64LegalizerInfo.cpp
@@ -2655,10 +2655,62 @@ bool AArch64LegalizerInfo::legalizeExtractVectorElt(
 
 bool AArch64LegalizerInfo::legalizeDynStackAlloc(
     MachineInstr &MI, LegalizerHelper &Helper) const {
+  assert(MI.getOpcode() == TargetOpcode::G_DYN_STACKALLOC);
+
   MachineFunction &MF = *MI.getParent()->getParent();
   MachineIRBuilder &MIRBuilder = Helper.MIRBuilder;
   MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
 
+  // The "probe-stack" attribute either holds the symbol to call, or the
+  // special string "inline-asm".
+  StringRef ProbeStackAttr =
+    MF.getFunction().getFnAttribute("probe-stack").getValueAsString();
+
+  // FIXME: "inline-asm" isn't supported on darwin here, fallback to the
+  // generic implementation.
+  if (ST->isTargetDarwin() && ProbeStackAttr != "inline-asm") {
+    Register Dst = MI.getOperand(0).getReg();
+    Register AllocSize = MI.getOperand(1).getReg();
+    Align Alignment = assumeAligned(MI.getOperand(2).getImm());
+
+    const auto &MF = *MI.getMF();
+    const auto &TLI = *MF.getSubtarget().getTargetLowering();
+
+    MIRBuilder.setInstr(MI);
+
+    if (ProbeStackAttr != "") {
+      MIRBuilder.buildCopy(AArch64::X9, AllocSize);
+      auto ChkInst = MIRBuilder.buildInstr(AArch64::StkChkIndirectCall, {}, {});
+      auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
+      const auto Mask =
+          Subtarget.getRegisterInfo()->getDarwinStackProbePreservedMask();
+      ChkInst.addRegMask(Mask);
+    }
+
+    // Now lower it as a normal alloca.
+    LLT PtrTy = MRI.getType(Dst);
+    LLT IntPtrTy = LLT::integer(PtrTy.getSizeInBits());
+
+    Register SPReg = TLI.getStackPointerRegisterToSaveRestore();
+    auto SPTmp = MIRBuilder.buildCopy(PtrTy, SPReg);
+    SPTmp = MIRBuilder.buildCast(IntPtrTy, SPTmp);
+
+    auto Alloc = MIRBuilder.buildSub(IntPtrTy, SPTmp, AllocSize);
+    if (Alignment > Align(1)) {
+      APInt AlignMask(IntPtrTy.getSizeInBits(), Alignment.value(), true);
+      AlignMask.negate();
+      auto AlignCst = MIRBuilder.buildConstant(IntPtrTy, AlignMask);
+      Alloc = MIRBuilder.buildAnd(IntPtrTy, Alloc, AlignCst);
+    }
+
+    SPTmp = MIRBuilder.buildCast(PtrTy, Alloc);
+    MIRBuilder.buildCopy(SPReg, SPTmp);
+    MIRBuilder.buildCopy(Dst, SPTmp);
+
+    MI.eraseFromParent();
+    return true;
+  }
+
   // If stack probing is not enabled for this function, use the default
   // lowering.
   if (!MF.getFunction().hasFnAttribute("probe-stack") ||
diff --git a/llvm/test/CodeGen/AArch64/GlobalISel/legalize-dyn-alloca.mir b/llvm/test/CodeGen/AArch64/GlobalISel/legalize-dyn-alloca.mir
index 3884b3169ba3e4..4021f86fad7821 100644
--- a/llvm/test/CodeGen/AArch64/GlobalISel/legalize-dyn-alloca.mir
+++ b/llvm/test/CodeGen/AArch64/GlobalISel/legalize-dyn-alloca.mir
@@ -1,5 +1,5 @@
 # NOTE: Assertions have been autogenerated by utils/update_mir_test_checks.py
-# RUN: llc -mtriple=arm64-unknown-unknown -global-isel -global-isel-abort=1 -O0 -run-pass=legalizer %s -o - | FileCheck %s
+# RUN: llc -mtriple=arm64-apple-darwin -global-isel -global-isel-abort=1 -O0 -run-pass=legalizer %s -o - | FileCheck %s
 --- |
   target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
   target triple = "aarch64"
@@ -19,6 +19,11 @@
     ret ptr %addr
   }
 
+  define ptr @test_stack_check_alloca_regmask(i32 %numelts) "probe-stack"="__chkstk_darwin" {
+    %addr = alloca i8, i32 %numelts
+    ret ptr %addr
+  }
+
   define ptr @test_simple_alloca_stack_probing(i32 %numelts) "probe-stack"="inline-asm" {
     %addr = alloca i8, i32 %numelts
     ret ptr %addr
@@ -174,6 +179,54 @@ body:             |
     $x0 = COPY %8(p0)
     RET_ReallyLR implicit $x0
 
+...
+---
+name:            test_stack_check_alloca_regmask
+alignment:       4
+tracksRegLiveness: true
+liveins:
+  - { reg: '$w0' }
+frameInfo:
+  maxAlignment:    1
+stack:
+  - { id: 0, name: addr, type: variable-sized, alignment: 1 }
+machineFunctionInfo: {}
+body:             |
+  bb.1 (%ir-block.0):
+    liveins: $w0
+
+    ; CHECK-LABEL: name: test_stack_check_alloca_regmask
+    ; CHECK: liveins: $w0
+    ; CHECK: [[COPY:%[0-9]+]]:_(s32) = COPY $w0
+    ; CHECK: [[C:%[0-9]+]]:_(s64) = G_CONSTANT i64 1
+    ; CHECK: [[ZEXT:%[0-9]+]]:_(s64) = G_ZEXT [[COPY]](s32)
+    ; CHECK: [[MUL:%[0-9]+]]:_(s64) = G_MUL [[ZEXT]], [[C]]
+    ; CHECK: [[C1:%[0-9]+]]:_(s64) = G_CONSTANT i64 15
+    ; CHECK: [[ADD:%[0-9]+]]:_(s64) = nuw G_ADD [[MUL]], [[C1]]
+    ; CHECK: [[C2:%[0-9]+]]:_(s64) = G_CONSTANT i64 -16
+    ; CHECK: [[AND:%[0-9]+]]:_(s64) = G_AND [[ADD]], [[C2]]
+    ; CHECK: $x9 = COPY [[AND]](s64)
+    ; CHECK: StkChkIndirectCall csr_aarch64_stackprobe_darwin, implicit-def $lr, implicit-def $x16, implicit-def $x17, implicit $x9, implicit $sp
+    ; CHECK: [[COPY1:%[0-9]+]]:_(p0) = COPY $sp
+    ; CHECK: [[PTRTOINT:%[0-9]+]]:_(i64) = G_PTRTOINT [[COPY1]](p0)
+    ; CHECK: [[SUB:%[0-9]+]]:_(i64) = G_SUB [[PTRTOINT]], [[AND]]
+    ; CHECK: [[INTTOPTR:%[0-9]+]]:_(p0) = G_INTTOPTR [[SUB]](i64)
+    ; CHECK: $sp = COPY [[INTTOPTR]](p0)
+    ; CHECK: [[COPY2:%[0-9]+]]:_(p0) = COPY [[INTTOPTR]](p0)
+    ; CHECK: $x0 = COPY [[COPY2]](p0)
+    ; CHECK: RET_ReallyLR implicit $x0
+    %0:_(s32) = COPY $w0
+    %3:_(s64) = G_CONSTANT i64 1
+    %1:_(s64) = G_ZEXT %0(s32)
+    %2:_(s64) = G_MUL %1, %3
+    %4:_(s64) = G_CONSTANT i64 15
+    %5:_(s64) = nuw G_ADD %2, %4
+    %6:_(s64) = G_CONSTANT i64 -16
+    %7:_(s64) = G_AND %5, %6
+    %8:_(p0) = G_DYN_STACKALLOC %7(s64), 0
+    $x0 = COPY %8(p0)
+    RET_ReallyLR implicit $x0
+
 ...
 ---
 name:            test_simple_alloca_stack_probing
diff --git a/llvm/test/CodeGen/AArch64/arm64-stack-probing-with-shrink-wrapping.ll b/llvm/test/CodeGen/AArch64/arm64-stack-probing-with-shrink-wrapping.ll
new file mode 100644
index 00000000000000..5da5c84f302405
--- /dev/null
+++ b/llvm/test/CodeGen/AArch64/arm64-stack-probing-with-shrink-wrapping.ll
@@ -0,0 +1,91 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py UTC_ARGS: --version 4
+; RUN: llc -o - %s | FileCheck %s
+
+target datalayout = "e-m:o-i64:64-i128:128-n32:64-S128"
+target triple = "arm64-apple-macosx14.0.0"
+
+declare i64 @foo(ptr)
+
+define i64 @test(ptr %0) #0 {
+; CHECK-LABEL: test:
+; CHECK:       ; %bb.0:
+; CHECK-NEXT:    ldrb w8, [x0]
+; CHECK-NEXT:    tbz w8, #0, LBB0_4
+; CHECK-NEXT:  ; %bb.1:
+; CHECK-NEXT:    stp x28, x27, [sp, #-32]! ; 16-byte Folded Spill
+; CHECK-NEXT:    stp x29, x30, [sp, #16] ; 16-byte Folded Spill
+; CHECK-NEXT:    stp x9, x10, [sp, #-16]!
+; CHECK-NEXT:    stp x11, x12, [sp, #-16]!
+; CHECK-NEXT:    mov w9, #6000 ; =0x1770
+; CHECK-NEXT:  Lloh0:
+; CHECK-NEXT:    adrp x16, ___chkstk_darwin at GOTPAGE
+; CHECK-NEXT:  Lloh1:
+; CHECK-NEXT:    ldr x16, [x16, ___chkstk_darwin at GOTPAGEOFF]
+; CHECK-NEXT:    blr x16
+; CHECK-NEXT:    ldp x11, x12, [sp], #16
+; CHECK-NEXT:    ldp x9, x10, [sp], #16
+; CHECK-NEXT:    sub sp, sp, #1, lsl #12 ; =4096
+; CHECK-NEXT:    sub sp, sp, #1904
+; CHECK-NEXT:    .cfi_def_cfa_offset 6032
+; CHECK-NEXT:    .cfi_offset w30, -8
+; CHECK-NEXT:    .cfi_offset w29, -16
+; CHECK-NEXT:    .cfi_offset w27, -24
+; CHECK-NEXT:    .cfi_offset w28, -32
+; CHECK-NEXT:    cbz w8, LBB0_5
+; CHECK-NEXT:  LBB0_2:
+; CHECK-NEXT:    bl _foo
+; CHECK-NEXT:  LBB0_3:
+; CHECK-NEXT:    add sp, sp, #1, lsl #12 ; =4096
+; CHECK-NEXT:    add sp, sp, #1904
+; CHECK-NEXT:    ldp x29, x30, [sp, #16] ; 16-byte Folded Reload
+; CHECK-NEXT:    ldp x28, x27, [sp], #32 ; 16-byte Folded Reload
+; CHECK-NEXT:  LBB0_4: ; %common.ret
+; CHECK-NEXT:    mov x0, xzr
+; CHECK-NEXT:    ret
+; CHECK-NEXT:  LBB0_5:
+; CHECK-NEXT:    mov x8, xzr
+; CHECK-NEXT:    ldr x8, [x8]
+; CHECK-NEXT:    ldr w9, [x8]
+; CHECK-NEXT:    cbz w9, LBB0_2
+; CHECK-NEXT:  ; %bb.6:
+; CHECK-NEXT:    mov w9, #1 ; =0x1
+; CHECK-NEXT:    cbnz w9, LBB0_3
+; CHECK-NEXT:  ; %bb.7:
+; CHECK-NEXT:    mov x0, x8
+; CHECK-NEXT:    b LBB0_2
+; CHECK-NEXT:    .loh AdrpLdrGot Lloh0, Lloh1
+  %2 = alloca [6000 x i8], align 8
+  %3 = load i8, ptr %0, align 8
+  %4 = and i8 %3, 1
+  %5 = icmp eq i8 %4, 0
+  br i1 %5, label %common.ret, label %6
+
+6:                                                ; preds = %1
+  %7 = icmp eq i8 %3, 0
+  br i1 %7, label %8, label %18
+
+8:                                                ; preds = %6
+  %9 = load ptr, ptr null, align 8
+  %10 = load i32, ptr %9, align 4
+  %11 = icmp eq i32 %10, 0
+  br i1 %11, label %18, label %12
+
+12:                                               ; preds = %8
+  %13 = and i64 1, 1
+  %14 = icmp eq i64 %13, 0
+  %15 = or i1 false, %14
+  br i1 %15, label %16, label %common.ret
+
+16:                                               ; preds = %12
+  %17 = tail call ptr @foo(ptr %9)
+  br label %common.ret
+
+common.ret:                                       ; preds = %18, %16, %12, %1
+  ret i64 0
+
+18:                                               ; preds = %8, %6
+  %19 = tail call i64 @foo(ptr %0)
+  br label %common.ret
+}
+
+attributes #0 = { "probe-stack"="__chkstk_darwin" }
diff --git a/llvm/test/CodeGen/AArch64/arm64-stack-probing.ll b/llvm/test/CodeGen/AArch64/arm64-stack-probing.ll
new file mode 100644
index 00000000000000..64d30862e763f5
--- /dev/null
+++ b/llvm/test/CodeGen/AArch64/arm64-stack-probing.ll
@@ -0,0 +1,105 @@
+; RUN: llc < %s -mtriple=arm64-apple-darwin -verify-machineinstrs | FileCheck %s
+; RUN: llc < %s -mtriple=arm64-apple-darwin -verify-machineinstrs -O0 -global-isel | FileCheck %s --check-prefix=O0
+target datalayout = "e-m:o-i64:64-i128:128-n32:64-S128"
+target triple = "arm64-apple-darwin"
+
+declare i32 @use_ptr(i32*) #1
+
+; Expect a probe here due to static object size > 4096.
+; Function Attrs: noinline nounwind optnone uwtable
+define void @static_test1_probe() #0 {
+; CHECK-LABEL: static_test1_probe
+; CHECK:  mov	w9, #16384
+; CHECK:  adrp    x16, ___chkstk_darwin at GOTPAGE
+; CHECK:  ldr     x16, [x16, ___chkstk_darwin at GOTPAGEOFF]
+; CHECK:  blr x16
+; CHECK-NEXT:  sub sp, sp, #4, lsl #12
+; O0:  mov	w9, #16384
+; O0:  adrp    x16, ___chkstk_darwin at GOTPAGE
+; O0:  ldr     x16, [x16, ___chkstk_darwin at GOTPAGEOFF]
+; O0:  blr x16
+; O0-NEXT:  sub sp, sp, #4, lsl #12
+  %1 = alloca [4096 x i32], align 4
+  %2 = getelementptr inbounds [4096 x i32], [4096 x i32]* %1, i32 0, i32 0
+  %3 = call i32 @use_ptr(i32* %2)
+  ret void
+}
+
+; No probe without the function attribute present..
+; Function Attrs: noinline nounwind optnone uwtable
+define void @static_test1_no_attr() {
+; CHECK-LABEL: static_test1_no_attr
+; CHECK-NOT: bl ___chkstk_darwin
+; O0-NOT: bl ___chkstk_darwin
+  %1 = alloca [4096 x i32], align 4
+  %2 = getelementptr inbounds [4096 x i32], [4096 x i32]* %1, i32 0, i32 0
+  %3 = call i32 @use_ptr(i32* %2)
+  ret void
+}
+
+; Stack size should be less than 4k, no probe.
+; Function Attrs: noinline nounwind optnone uwtable
+define void @static_test2_small() #0 {
+; CHECK-LABEL: static_test2_small
+; CHECK-NOT: bl ___chkstk_darwin
+; O0-NOT: bl ___chkstk_darwin
+  %1 = alloca [64 x i32], align 4
+  %2 = getelementptr inbounds [64 x i32], [64 x i32]* %1, i32 0, i32 0
+  %3 = call i32 @use_ptr(i32* %2)
+  ret void
+}
+
+ at g = common local_unnamed_addr global i32* null, align 8
+
+; Check that the LR is saved in the prolog for static allocas when it isn't
+; otherwise saved as a normal callee-save reg.
+; Function Attrs: nounwind optsize ssp uwtable
+define void @test_static_oversize_nocsr(i32* nocapture readnone) local_unnamed_addr #0 {
+; CHECK-LABEL: test_static_oversize_nocsr
+; CHECK:         stp     x28, x27, [sp, #-16]!
+; CHECK:    str x30, [sp, #-16]!
+; CHECK:  mov w9, #8000
+; CHECK:  adrp    x16, ___chkstk_darwin at GOTPAGE
+; CHECK:  ldr     x16, [x16, ___chkstk_darwin at GOTPAGEOFF]
+; CHECK:  blr x16
+; O0:         stp     x28, x27, [sp, #-16]!
+; O0:    str x30, [sp, #-16]!
+; O0:  mov w9, #8000
+; O0:  adrp    x16, ___chkstk_darwin at GOTPAGE
+; O0:  ldr     x16, [x16, ___chkstk_darwin at GOTPAGEOFF]
+; O0:  blr x16
+  %2 = alloca [2000 x i32], align 4
+  %3 = bitcast [2000 x i32]* %2 to i32*
+  store i32* %3, i32** @g, align 8
+  ret void
+}
+
+; Test dynamic sized allocas.
+; Function Attrs: nounwind optsize ssp uwtable
+define void @test_dynamic(i32* nocapture readnone, i64 %num) local_unnamed_addr #0 {
+; CHECK-LABEL: test_dynamic
+; CHECK:       mov x9, x1
+; CHECK:       adrp    x16, ___chkstk_darwin at GOTPAGE
+; CHECK:       ldr     x16, [x16, ___chkstk_darwin at GOTPAGEOFF]
+; CHECK-NEXT:  blr x16
+; CHECK:       add [[AMOUNT:x[0-9]+]], x{{[0-9]+}}, #15
+; CHECK-NEXT:  mov x8, sp
+; CHECK-NEXT:  and [[AMOUNT]], [[AMOUNT]], #0xfffffffffffffff0
+; CHECK-NEXT:  sub x8, x8, x9
+; CHECK-NEXT:  mov sp, x8
+; O0:       add [[AMOUNT:x[0-9]+]], x{{[0-9]+}}, #15
+; O0-NEXT:  and x9, [[AMOUNT]], #0xfffffffffffffff0
+; O0:       adrp    x16, ___chkstk_darwin at GOTPAGE
+; O0:       ldr     x16, [x16, ___chkstk_darwin at GOTPAGEOFF]
+; O0-NEXT:  blr x16
+; O0:  mov [[SPCOPY:x[0-9]+]], sp
+; O0:  subs [[ALLOC:x[0-9]+]], [[SPCOPY]], x{{[0-9]+}}
+; O0-NEXT:  mov sp, [[ALLOC]]
+  %2 = alloca i8, i64 %num, align 16
+  %3 = bitcast i8* %2 to i32*
+  store i32* %3, i32** @g, align 8
+  ret void
+}
+
+
+attributes #0 = { "probe-stack"="__chkstk_darwin" }
diff --git a/llvm/test/CodeGen/AArch64/arm64_32-stack-probing.ll b/llvm/test/CodeGen/AArch64/arm64_32-stack-probing.ll
new file mode 100644
index 00000000000000..41e41adbd5b1b7
--- /dev/null
+++ b/llvm/test/CodeGen/AArch64/arm64_32-stack-probing.ll
@@ -0,0 +1,27 @@
+; RUN: llc < %s -mtriple=arm64_32-apple-darwin -verify-machineinstrs | FileCheck %s
+; RUN: llc < %s -O0 -mtriple=arm64_32-apple-darwin -verify-machineinstrs | FileCheck %s --check-prefixes=O0
+
+declare i32 @use_ptr(i32*) #1
+
+; Expect a probe here due to static object size > 4096.
+; Function Attrs: noinline nounwind optnone uwtable
+define void @static_test1_probe() #0 {
+; CHECK-LABEL: static_test1_probe
+; CHECK:  mov	w9, #16384
+; CHECK:  adrp    x16, ___chkstk_darwin at GOTPAGE
+; CHECK:  ldr     w16, [x16, ___chkstk_darwin at GOTPAGEOFF]
+; CHECK:  blr x16
+; CHECK-NEXT:  sub sp, sp, #4, lsl #12
+; O0:  mov	w9, #16384
+; O0:  adrp    x16, ___chkstk_darwin at GOTPAGE
+; O0:  ldr     w16, [x16, ___chkstk_darwin at GOTPAGEOFF]
+; O0:  blr x16
+; O0-NEXT:  sub sp, sp, #4, lsl #12
+  %1 = alloca [4096 x i32], align 4
+  %2 = getelementptr inbounds [4096 x i32], [4096 x i32]* %1, i32 0, i32 0
+  %3 = call i32 @use_ptr(i32* %2)
+  ret void
+}
+
+
+attributes #0 = { "probe-stack"="__chkstk_darwin" nounwind }
diff --git a/llvm/test/CodeGen/AArch64/ptrauth-stack-probing.ll b/llvm/test/CodeGen/AArch64/ptrauth-stack-probing.ll
new file mode 100644
index 00000000000000..8e6a58b02a81b2
--- /dev/null
+++ b/llvm/test/CodeGen/AArch64/ptrauth-stack-probing.ll
@@ -0,0 +1,31 @@
+; RUN: llc < %s -mtriple=arm64e-apple-darwin -verify-machineinstrs | FileCheck %s
+; RUN: llc < %s -mtriple=arm64e-apple-darwin -verify-machineinstrs -O0 -global-isel | FileCheck %s
+
+target datalayout = "e-m:o-i64:64-i128:128-n32:64-S128"
+target triple = "arm64e-apple-darwin"
+
+declare i32 @use_ptr(i32*)
+
+define void @test_chkstk_ptrauth() #0 {
+; CHECK-LABEL: _test_chkstk_ptrauth
+; CHECK:  mov	w9, #16384
+; CHECK:  adrp    x17, l___chkstk_darwin$auth_ptr$ia$0$addr at PAGE
+; CHECK:  add     x17, x17, l___chkstk_darwin$auth_ptr$ia$0$addr at PAGEOFF
+; CHECK:  ldr     x16, [x17]
+; CHECK:  blraa   x16, x17
+; CHECK-NEXT:  sub sp, sp, #4, lsl #12
+  %1 = alloca [4096 x i32], align 4
+  %2 = getelementptr inbounds [4096 x i32], [4096 x i32]* %1, i32 0, i32 0
+  %3 = call i32 @use_ptr(i32* %2)
+  ret void
+}
+
+
+
+attributes #0 = { "ptrauth-calls" "probe-stack"="__chkstk_darwin" }
+
+
+; CHECK: .section  __DATA,__auth_ptr
+; CHECK: .p2align  3
+; CHECK: l___chkstk_darwin$auth_ptr$ia$0$addr:
+; CHECK: .quad ___chkstk_darwin at AUTH(ia,0,addr)
diff --git a/llvm/test/CodeGen/AArch64/shrink-wrap-chkstk-with-x16-clobbered.ll b/llvm/test/CodeGen/AArch64/shrink-wrap-chkstk-with-x16-clobbered.ll
new file mode 100644
index 00000000000000..0602289530bed9
--- /dev/null
+++ b/llvm/test/CodeGen/AArch64/shrink-wrap-chkstk-with-x16-clobbered.ll
@@ -0,0 +1,113 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py UTC_ARGS: --version 4
+; RUN: llc -O3 -aarch64-enable-gep-opt -o - %s | FileCheck %s
+
+target triple = "arm64-apple-macosx"
+
+define i8 @chkstk_with_x16_clobbered([2 x i64] %arg, [2 x i64] %arg1, i8 zeroext %arg2, i1 %arg3, ptr %arg4, i8 %arg5, ptr %arg6, i8 %arg7, i1 %arg8, i1 %arg9, i64 %arg10) #0 {
+; CHECK-LABEL: chkstk_with_x16_clobbered:
+; CHECK:       ; %bb.0: ; %bb
+; CHECK-NEXT:    cmp w4, #1
+; CHECK-NEXT:    csinc w16, w4, wzr, lo
+; CHECK-NEXT:    tbnz w5, #0, LBB0_5
+; CHECK-NEXT:  ; %bb.1: ; %bb11
+; CHECK-NEXT:    stp x28, x27, [sp, #-16]! ; 16-byte Folded Spill
+; CHECK-NEXT:    str x30, [sp, #-16]!
+; CHECK-NEXT:    stp x9, x10, [sp, #-16]!
+; CHECK-NEXT:    stp x11, x12, [sp, #-16]!
+; CHECK-NEXT:    stp x16, x17, [sp, #-16]!
+; CHECK-NEXT:    mov w9, #10416 ; =0x28b0
+; CHECK-NEXT:  Lloh0:
+; CHECK-NEXT:    adrp x16, ___chkstk_darwin at GOTPAGE
+; CHECK-NEXT:  Lloh1:
+; CHECK-NEXT:    ldr x16, [x16, ___chkstk_darwin at GOTPAGEOFF]
+; CHECK-NEXT:    blr x16
+; CHECK-NEXT:    ldp x16, x17, [sp], #16
+; CHECK-NEXT:    ldp x11, x12, [sp], #16
+; CHECK-NEXT:    ldp x9, x10, [sp], #16
+; CHECK-NEXT:    ldr x30, [sp], #16
+; CHECK-NEXT:    sub sp, sp, #2, lsl #12 ; =8192
+; CHECK-NEXT:    sub sp, sp, #2224
+; CHECK-NEXT:    .cfi_def_cfa_offset 10432
+; CHECK-NEXT:    .cfi_offset w27, -8
+; CHECK-NEXT:    .cfi_offset w28, -16
+; CHECK-NEXT:    add x8, sp, #2, lsl #12 ; =8192
+; CHECK-NEXT:    add x9, sp, #2, lsl #12 ; =8192
+; CHECK-NEXT:    add x11, sp, #2, lsl #12 ; =8192
+; CHECK-NEXT:    ldrb w8, [x8, #2250]
+; CHECK-NEXT:    ldrb w9, [x9, #2249]
+; CHECK-NEXT:    ldrb w11, [x11, #2248]
+; CHECK-NEXT:    ldr x12, [sp, #10432]
+; CHECK-NEXT:    cmp w4, #1
+; CHECK-NEXT:    mov w13, #1 ; =0x1
+; CHECK-NEXT:    and w10, w7, #0xff
+; CHECK-NEXT:    neg x14, x16
+; CHECK-NEXT:    csinc w15, w4, wzr, lo
+; CHECK-NEXT:    sub x16, x13, x16
+; CHECK-NEXT:    add sp, sp, #2, lsl #12 ; =8192
+; CHECK-NEXT:    add sp, sp, #2224
+; CHECK-NEXT:    ldp x28, x27, [sp], #16 ; 16-byte Folded Reload
+; CHECK-NEXT:  LBB0_2: ; %bb12
+; CHECK-NEXT:    ; =>This Loop Header: Depth=1
+; CHECK-NEXT:    ; Child Loop BB0_3 Depth 2
+; CHECK-NEXT:    mov x17, x14
+; CHECK-NEXT:    strb w13, [x6]
+; CHECK-NEXT:  LBB0_3: ; %bb13
+; CHECK-NEXT:    ; Parent Loop BB0_2 Depth=1
+; CHECK-NEXT:    ; => This Inner Loop Header: Depth=2
+; CHECK-NEXT:    ldrb w0, [x12, x17]
+; CHECK-NEXT:    mov x17, x16
+; CHECK-NEXT:    cmp w10, w0
+; CHECK-NEXT:    cset w0, ne
+; CHECK-NEXT:    orr w0, w11, w0
+; CHECK-NEXT:    and w0, w0, #0xff
+; CHECK-NEXT:    cmp w0, w15
+; CHECK-NEXT:    csel w0, w0, w15, lo
+; CHECK-NEXT:    strb w0, [x6]
+; CHECK-NEXT:    tbz w9, #0, LBB0_3
+; CHECK-NEXT:  ; %bb.4: ; %bb18
+; CHECK-NEXT:    ; in Loop: Header=BB0_2 Depth=1
+; CHECK-NEXT:    tbnz w8, #0, LBB0_2
+; CHECK-NEXT:  LBB0_5: ; %bb19
+; CHECK-NEXT:    mov w0, wzr
+; CHECK-NEXT:    ret
+; CHECK-NEXT:    .loh AdrpLdrGot Lloh0, Lloh1
+bb:
+  %alloca = alloca { [102 x [102 x i8] ] }, align 1
+  %call = tail call i8 @llvm.umin.i8(i8 %arg2, i8 1)
+  br i1 %arg3, label %bb19, label %bb11
+
+bb11:                                             ; preds = %bb
+  %zext = zext i8 %call to i64
+  br label %bb12
+
+bb12:                                             ; preds = %bb18, %bb11
+  %sub = sub i64 0, %zext
+  store i8 1, ptr %arg4, align 1
+  br label %bb13
+
+bb13:                                             ; preds = %bb13, %bb12
+  %phi = phi i64 [ %add, %bb13 ], [ %sub, %bb12 ]
+  %getelementptr = getelementptr i8, ptr %arg6, i64 %phi
+  %load = load i8, ptr %getelementptr, align 1
+  %icmp = icmp ne i8 %arg5, %load
+  %zext14 = zext i1 %icmp to i8
+  %or = or i8 %arg7, %zext14
+  %call15 = call i8 @llvm.umin.i8(i8 %arg2, i8 1)
+  %call16 = call i8 @llvm.umin.i8(i8 %or, i8 %call15)
+  %getelementptr17 = getelementptr [102 x i8], ptr %alloca, i64 0, i64 %arg10
+  store i8 %call16, ptr %arg4, align 1
+  %add = add i64 %sub, 1
+  br i1 %arg8, label %bb18, label %bb13
+
+bb18:                                             ; preds = %bb13
+  br i1 %arg9, label %bb12, label %bb19
+
+bb19:                                             ; preds = %bb18, %bb
+  ret i8 0
+}
+
+; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn memory(none)
+declare i8 @llvm.umin.i8(i8, i8) #1
+
+attributes #0 = { "probe-stack"="__chkstk_darwin" }
+attributes #1 = { nocallback nofree nosync nounwind speculatable willreturn memory(none) }
diff --git a/llvm/test/CodeGen/AArch64/stack-check-dwarf-label-crash.ll b/llvm/test/CodeGen/AArch64/stack-check-dwarf-label-crash.ll
new file mode 100644
index 00000000000000..8018a2cf8f2529
--- /dev/null
+++ b/llvm/test/CodeGen/AArch64/stack-check-dwarf-label-crash.ll
@@ -0,0 +1,207 @@
+; RUN: llc < %s -mtriple=arm64-apple-darwin -verify-machineinstrs | FileCheck %s
+target datalayout = "e-m:o-i64:64-i128:128-n32:64-S128"
+target triple = "arm64-apple-darwin"
+
+%struct.foo = type { %struct.pluto }
+%struct.pluto = type { i8*, i8*, %struct.wombat, %struct.wombat, %struct.widget, %struct.hoge, i8, i8, i8, %struct.barney.1 }
+%struct.wombat = type { %struct.barney**, %struct.barney**, %struct.barney**, [32 x %struct.barney*] }
+%struct.barney = type <{ i32 (...)**, i8, i8, i8, i8, [4 x i8] }>
+%struct.widget = type { %struct.barney**, %struct.barney**, %struct.barney**, [8 x %struct.barney*] }
+%struct.hoge = type { %struct.pluto.0**, %struct.pluto.0**, %struct.pluto.0**, [4 x %struct.pluto.0*] }
+%struct.pluto.0 = type <{ %struct.spam, [4 x i8], i64, %struct.barney*, i8, [7 x i8] }>
+%struct.spam = type <{ i32 (...)**, i8, i8, i8, i8 }>
+%struct.barney.1 = type { %struct.ham }
+%struct.ham = type { [4096 x i8], %struct.bar* }
+%struct.bar = type { %struct.bar*, i64 }
+
+; Check we don't crash on this.
+; CHECK-LABEL: barney
+define void @barney() local_unnamed_addr #0 !dbg !3 {
+bb:
+  %tmp = alloca %struct.foo, align 8
+  br i1 undef, label %bb2, label %bb1, !dbg !7
+
+bb1:                                              ; preds = %bb
+  br i1 undef, label %bb2, label %bb4, !dbg !8
+
+bb2:                                              ; preds = %bb1, %bb
+  br i1 undef, label %bb34, label %bb3, !dbg !9
+
+bb3:                                              ; preds = %bb2
+  br label %bb34, !dbg !10
+
+bb4:                                              ; preds = %bb1
+  br i1 undef, label %bb18, label %bb5, !dbg !11
+
+bb5:                                              ; preds = %bb4
+  br i1 undef, label %bb6, label %bb7, !dbg !12
+
+bb6:                                              ; preds = %bb5
+  br i1 undef, label %bb18, label %bb8, !dbg !16
+
+bb7:                                              ; preds = %bb5
+  br label %bb8
+
+bb8:                                              ; preds = %bb7, %bb6
+  br i1 undef, label %bb10, label %bb9, !dbg !17
+
+bb9:                                              ; preds = %bb8
+  br label %bb10, !dbg !21
+
+bb10:                                             ; preds = %bb9, %bb8
+  br i1 undef, label %bb11, label %bb12, !dbg !22
+
+bb11:                                             ; preds = %bb10
+  br label %bb15, !dbg !22
+
+bb12:                                             ; preds = %bb10
+  br i1 undef, label %bb14, label %bb13, !dbg !27
+
+bb13:                                             ; preds = %bb12
+  br label %bb15, !dbg !27
+
+bb14:                                             ; preds = %bb12
+  unreachable, !dbg !28
+
+bb15:                                             ; preds = %bb13, %bb11
+  br i1 undef, label %bb17, label %bb16, !dbg !29
+
+bb16:                                             ; preds = %bb15
+  br label %bb17, !dbg !30
+
+bb17:                                             ; preds = %bb16, %bb15
+  br label %bb18
+
+bb18:                                             ; preds = %bb17, %bb6, %bb4
+  br i1 undef, label %bb20, label %bb19, !dbg !31
+
+bb19:                                             ; preds = %bb18
+  br label %bb20, !dbg !32
+
+bb20:                                             ; preds = %bb19, %bb18
+  br i1 undef, label %bb25, label %bb21, !dbg !33
+
+bb21:                                             ; preds = %bb20
+  br label %bb22, !dbg !33
+
+bb22:                                             ; preds = %bb24, %bb21
+  br i1 undef, label %bb24, label %bb23, !dbg !50
+
+bb23:                                             ; preds = %bb22
+  br label %bb24, !dbg !51
+
+bb24:                                             ; preds = %bb23, %bb22
+  br i1 undef, label %bb25, label %bb22, !dbg !33, !llvm.loop !52
+
+bb25:                                             ; preds = %bb24, %bb20
+  br i1 undef, label %bb27, label %bb26, !dbg !54
+
+bb26:                                             ; preds = %bb25
+  br label %bb27, !dbg !59
+
+bb27:                                             ; preds = %bb26, %bb25
+  br i1 undef, label %bb29, label %bb28, !dbg !60
+
+bb28:                                             ; preds = %bb27
+  br label %bb29, !dbg !65
+
+bb29:                                             ; preds = %bb28, %bb27
+  br i1 undef, label %bb31, label %bb30, !dbg !66
+
+bb30:                                             ; preds = %bb29
+  br label %bb31, !dbg !71
+
+bb31:                                             ; preds = %bb30, %bb29
+  br i1 undef, label %bb33, label %bb32, !dbg !72
+
+bb32:                                             ; preds = %bb31
+  br label %bb33, !dbg !75
+
+bb33:                                             ; preds = %bb32, %bb31
+  br label %bb34
+
+bb34:                                             ; preds = %bb33, %bb3, %bb2
+  ret void
+}
+
+attributes #0 = { "probe-stack"="__chkstk_darwin" }
+
+!llvm.module.flags = !{!0}
+!llvm.dbg.cu = !{!1}
+
+!0 = !{i32 2, !"Debug Info Version", i32 3}
+!1 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !2, producer: "clang", isOptimized: true, runtimeVersion: 0, emissionKind: LineTablesOnly, nameTableKind: GNU)
+!2 = !DIFile(filename: "foo", directory: "/")
+!3 = distinct !DISubprogram(name: "foo", scope: !4, file: !4, line: 326, type: !5, scopeLine: 327, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!4 = !DIFile(filename: "foo", directory: "")
+!5 = !DISubroutineType(types: !6)
+!6 = !{}
+!7 = !DILocation(line: 328, column: 30, scope: !3)
+!8 = !DILocation(line: 328, column: 49, scope: !3)
+!9 = !DILocation(line: 329, column: 9, scope: !3)
+!10 = !DILocation(line: 330, column: 7, scope: !3)
+!11 = !DILocation(line: 340, column: 7, scope: !3)
+!12 = !DILocation(line: 177, column: 7, scope: !13, inlinedAt: !15)
+!13 = distinct !DISubprogram(name: "foo", scope: !14, file: !14, line: 174, type: !5, scopeLine: 175, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!14 = !DIFile(filename: "foo", directory: "")
+!15 = distinct !DILocation(line: 342, column: 13, scope: !3)
+!16 = !DILocation(line: 179, column: 9, scope: !13, inlinedAt: !15)
+!17 = !DILocation(line: 182, column: 9, scope: !18, inlinedAt: !20)
+!18 = distinct !DISubprogram(name: "print", scope: !19, file: !19, line: 180, type: !5, scopeLine: 180, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!19 = !DIFile(filename: "foo", directory: "")
+!20 = distinct !DILocation(line: 346, column: 10, scope: !3)
+!21 = !DILocation(line: 183, column: 7, scope: !18, inlinedAt: !20)
+!22 = !DILocation(line: 34, column: 9, scope: !23, inlinedAt: !24)
+!23 = distinct !DISubprogram(name: "grow", scope: !14, file: !14, line: 33, type: !5, scopeLine: 33, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!24 = distinct !DILocation(line: 91, column: 5, scope: !25, inlinedAt: !26)
+!25 = distinct !DISubprogram(name: "operator+=", scope: !14, file: !14, line: 90, type: !5, scopeLine: 90, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!26 = distinct !DILocation(line: 347, column: 7, scope: !3)
+!27 = !DILocation(line: 39, column: 11, scope: !23, inlinedAt: !24)
+!28 = !DILocation(line: 40, column: 9, scope: !23, inlinedAt: !24)
+!29 = !DILocation(line: 348, column: 9, scope: !3)
+!30 = !DILocation(line: 349, column: 7, scope: !3)
+!31 = !DILocation(line: 353, column: 7, scope: !3)
+!32 = !DILocation(line: 354, column: 5, scope: !3)
+!33 = !DILocation(line: 291, column: 5, scope: !34, inlinedAt: !35)
+!34 = distinct !DISubprogram(name: "reset", scope: !4, file: !4, line: 290, type: !5, scopeLine: 290, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagLocalToUnit | DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!35 = distinct !DILocation(line: 300, column: 29, scope: !36, inlinedAt: !37)
+!36 = distinct !DISubprogram(name: "~foo", scope: !4, file: !4, line: 300, type: !5, scopeLine: 300, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagLocalToUnit | DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!37 = distinct !DILocation(line: 300, column: 27, scope: !38, inlinedAt: !39)
+!38 = distinct !DISubprogram(name: "~foo", scope: !4, file: !4, line: 300, type: !5, scopeLine: 300, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagLocalToUnit | DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!39 = distinct !DILocation(line: 303, column: 7, scope: !40, inlinedAt: !41)
+!40 = distinct !DISubprogram(name: "~foo", scope: !4, file: !4, line: 303, type: !5, scopeLine: 303, flags: DIFlagArtificial | DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagLocalToUnit | DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!41 = distinct !DILocation(line: 303, column: 7, scope: !42, inlinedAt: !43)
+!42 = distinct !DISubprogram(name: "~foo", scope: !4, file: !4, line: 303, type: !5, scopeLine: 303, flags: DIFlagArtificial | DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagLocalToUnit | DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!43 = distinct !DILocation(line: 2156, column: 52, scope: !44, inlinedAt: !45)
+!44 = distinct !DISubprogram(name: "~foo", scope: !19, file: !19, line: 2156, type: !5, scopeLine: 2156, flags: DIFlagArtificial | DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagLocalToUnit | DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!45 = distinct !DILocation(line: 5227, column: 8, scope: !46, inlinedAt: !47)
+!46 = distinct !DISubprogram(name: "~foo", scope: !19, file: !19, line: 5227, type: !5, scopeLine: 5227, flags: DIFlagArtificial | DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagLocalToUnit | DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!47 = distinct !DILocation(line: 5227, column: 8, scope: !48, inlinedAt: !49)
+!48 = distinct !DISubprogram(name: "~foo", scope: !19, file: !19, line: 5227, type: !5, scopeLine: 5227, flags: DIFlagArtificial | DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagLocalToUnit | DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!49 = distinct !DILocation(line: 356, column: 1, scope: !3)
+!50 = !DILocation(line: 294, column: 11, scope: !34, inlinedAt: !35)
+!51 = !DILocation(line: 295, column: 9, scope: !34, inlinedAt: !35)
+!52 = distinct !{!52, !33, !53}
+!53 = !DILocation(line: 296, column: 5, scope: !34, inlinedAt: !35)
+!54 = !DILocation(line: 2151, column: 9, scope: !55, inlinedAt: !56)
+!55 = distinct !DISubprogram(name: "~foo", scope: !19, file: !19, line: 2150, type: !5, scopeLine: 2150, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!56 = distinct !DILocation(line: 2150, column: 21, scope: !57, inlinedAt: !58)
+!57 = distinct !DISubprogram(name: "~foo", scope: !19, file: !19, line: 2150, type: !5, scopeLine: 2150, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!58 = distinct !DILocation(line: 2156, column: 52, scope: !44, inlinedAt: !45)
+!59 = !DILocation(line: 2152, column: 7, scope: !55, inlinedAt: !56)
+!60 = !DILocation(line: 2151, column: 9, scope: !61, inlinedAt: !62)
+!61 = distinct !DISubprogram(name: "~foo", scope: !19, file: !19, line: 2150, type: !5, scopeLine: 2150, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!62 = distinct !DILocation(line: 2150, column: 21, scope: !63, inlinedAt: !64)
+!63 = distinct !DISubprogram(name: "~foo", scope: !19, file: !19, line: 2150, type: !5, scopeLine: 2150, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!64 = distinct !DILocation(line: 2156, column: 52, scope: !44, inlinedAt: !45)
+!65 = !DILocation(line: 2152, column: 7, scope: !61, inlinedAt: !62)
+!66 = !DILocation(line: 2151, column: 9, scope: !67, inlinedAt: !68)
+!67 = distinct !DISubprogram(name: "~foo", scope: !19, file: !19, line: 2150, type: !5, scopeLine: 2150, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!68 = distinct !DILocation(line: 2150, column: 21, scope: !69, inlinedAt: !70)
+!69 = distinct !DISubprogram(name: "~foo", scope: !19, file: !19, line: 2150, type: !5, scopeLine: 2150, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !1)
+!70 = distinct !DILocation(line: 2156, column: 52, scope: !44, inlinedAt: !45)
+!71 = !DILocation(line: 2152, column: 7, scope: !67, inlinedAt: !68)
+!72 = !DILocation(line: 2151, column: 9, scope: !67, inlinedAt: !73)
+!73 = distinct !DILocation(line: 2150, column: 21, scope: !69, inlinedAt: !74)
+!74 = distinct !DILocation(line: 2156, column: 52, scope: !44, inlinedAt: !45)
+!75 = !DILocation(line: 2152, column: 7, scope: !67, inlinedAt: !73)
diff --git a/llvm/test/CodeGen/AArch64/stack-probe-with-shrink-wrap.mir b/llvm/test/CodeGen/AArch64/stack-probe-with-shrink-wrap.mir
new file mode 100644
index 00000000000000..1495f8e73d9b3f
--- /dev/null
+++ b/llvm/test/CodeGen/AArch64/stack-probe-with-shrink-wrap.mir
@@ -0,0 +1,126 @@
+# NOTE: Assertions have been autogenerated by utils/update_mir_test_checks.py
+# RUN: llc -O0 -run-pass=prolog-epilog -verify-machineinstrs %s -o - | FileCheck %s
+
+# This test checks that if X9 or X10 is live after shrink wrapping changes the prolog insertion
+# point, then we save the registers before calling the probing routine.
+--- |
+  target datalayout = "e-m:o-i64:64-i128:128-n32:64-S128"
+  target triple = "aarch64-apple-darwin"
+
+  define i32 @foo(i32 %a, i32 %b) #0 {
+    %tmp = alloca i32, align 4
+    %bigalloc = alloca [4096 x i32], align 4
+    %tmp2 = icmp slt i32 %a, %b
+    br i1 %tmp2, label %true, label %false
+
+  true:                                             ; preds = %0
+    store i32 %a, ptr %tmp, align 4
+    %tmp4 = call i32 @doSomething(i32 0, ptr %tmp, ptr %bigalloc)
+    br label %false
+
+  false:                                            ; preds = %true, %0
+    %tmp.0 = phi i32 [ %tmp4, %true ], [ %a, %0 ]
+    ret i32 %tmp.0
+  }
+
+  declare i32 @doSomething(i32, ptr, ptr)
+
+  attributes #0 = { "probe-stack"="__chkstk_darwin" }
+
+...
+---
+name:            foo
+alignment:       2
+tracksRegLiveness: true
+liveins:
+  - { reg: '$w0' }
+  - { reg: '$w1' }
+  - { reg: '$w0' }
+  - { reg: '$w1' }
+frameInfo:
+  maxAlignment:    4
+  adjustsStack:    true
+  hasCalls:        true
+  maxCallFrameSize: 0
+  savePoint:
+    - point:           '%bb.1'
+  restorePoint:
+    - point:           '%bb.1'
+stack:
+  - { id: 0, name: tmp, size: 4, alignment: 4, stack-id: default, local-offset: -4 }
+  - { id: 1, name: bigalloc, size: 16384, alignment: 4, stack-id: default, local-offset: -16388 }
+  - { id: 2, name: tmp, size: 4, alignment: 4, stack-id: default, local-offset: -16392 }
+  - { id: 3, name: bigalloc, size: 16384, alignment: 4, stack-id: default, local-offset: -32776 }
+body:             |
+  ; CHECK-LABEL: name: foo
+  ; CHECK: bb.0 (%ir-block.0):
+  ; CHECK-NEXT:   successors: %bb.1(0x40000000), %bb.2(0x40000000)
+  ; CHECK-NEXT:   liveins: $w0, $w1, $lr, $x27, $x28
+  ; CHECK-NEXT: {{  $}}
+  ; CHECK-NEXT:   dead $wzr = SUBSWrr renamable $w0, renamable $w1, implicit-def $nzcv
+  ; CHECK-NEXT:   $w9 = ADDWri $w0, 0, 0
+  ; CHECK-NEXT:   Bcc 11, %bb.1, implicit killed $nzcv
+  ; CHECK-NEXT:   B %bb.2
+  ; CHECK-NEXT: {{  $}}
+  ; CHECK-NEXT: bb.1.true:
+  ; CHECK-NEXT:   successors: %bb.2(0x80000000)
+  ; CHECK-NEXT:   liveins: $w0, $w9, $x27, $x28, $lr
+  ; CHECK-NEXT: {{  $}}
+  ; CHECK-NEXT:   early-clobber $sp = frame-setup STPXpre killed $x28, killed $x27, $sp, -4 :: (store (s64) into %stack.7), (store (s64) into %stack.6)
+  ; CHECK-NEXT:   frame-setup STPXi killed $fp, killed $lr, $sp, 2 :: (store (s64) into %stack.5), (store (s64) into %stack.4)
+  ; CHECK-NEXT:   early-clobber $sp = frame-setup STPXpre $x9, undef $x10, $sp, -2
+  ; CHECK-NEXT:   early-clobber $sp = frame-setup STPXpre undef $x11, undef $x12, $sp, -2
+  ; CHECK-NEXT:   $w9 = frame-setup MOVi32imm 32784
+  ; CHECK-NEXT:   frame-setup StkChkIndirectCall csr_aarch64_stackprobe_darwin, implicit-def $lr, implicit-def $x16, implicit-def $x17, implicit $x9, implicit $sp
+  ; CHECK-NEXT:   early-clobber $sp, $x11, $x12 = frame-setup LDPXpost $sp, 2
+  ; CHECK-NEXT:   early-clobber $sp, $x9, $x10 = frame-setup LDPXpost $sp, 2
+  ; CHECK-NEXT:   $sp = frame-setup SUBXri $sp, 8, 12
+  ; CHECK-NEXT:   $sp = frame-setup SUBXri $sp, 16, 0
+  ; CHECK-NEXT:   frame-setup CFI_INSTRUCTION def_cfa_offset 32816
+  ; CHECK-NEXT:   frame-setup CFI_INSTRUCTION offset $w30, -8
+  ; CHECK-NEXT:   frame-setup CFI_INSTRUCTION offset $w29, -16
+  ; CHECK-NEXT:   frame-setup CFI_INSTRUCTION offset $w27, -24
+  ; CHECK-NEXT:   frame-setup CFI_INSTRUCTION offset $w28, -32
+  ; CHECK-NEXT:   $x8 = ADDXri $sp, 8, 12
+  ; CHECK-NEXT:   STRWui renamable $w0, killed $x8, 3 :: (store (s32) into %ir.tmp)
+  ; CHECK-NEXT:   $x1 = ADDXri $sp, 8, 12
+  ; CHECK-NEXT:   $x1 = ADDXri $x1, 12, 0
+  ; CHECK-NEXT:   $x2 = ADDXri $sp, 4, 12
+  ; CHECK-NEXT:   $x2 = ADDXri $x2, 12, 0
+  ; CHECK-NEXT:   $w0 = COPY $wzr
+  ; CHECK-NEXT:   BL @doSomething, csr_aarch64_aapcs, implicit-def dead $lr, implicit $sp, implicit $w0, implicit $x1, implicit killed $x2, implicit-def $sp, implicit-def dead $w0
+  ; CHECK-NEXT:   $sp = frame-destroy ADDXri $sp, 8, 12
+  ; CHECK-NEXT:   $sp = frame-destroy ADDXri $sp, 16, 0
+  ; CHECK-NEXT:   $fp, $lr = frame-destroy LDPXi $sp, 2 :: (load (s64) from %stack.5), (load (s64) from %stack.4)
+  ; CHECK-NEXT:   early-clobber $sp, $x28, $x27 = frame-destroy LDPXpost $sp, 4 :: (load (s64) from %stack.7), (load (s64) from %stack.6)
+  ; CHECK-NEXT: {{  $}}
+  ; CHECK-NEXT: bb.2.false:
+  ; CHECK-NEXT:   liveins: $w0, $w9, $lr, $x27, $x28
+  ; CHECK-NEXT: {{  $}}
+  ; CHECK-NEXT:   $w0 = ADDWrs $w0, $w9, 0
+  ; CHECK-NEXT:   RET_ReallyLR implicit $w0
+  bb.0 (%ir-block.0):
+    liveins: $w0, $w1
+
+    dead $wzr = SUBSWrr renamable $w0, renamable $w1, implicit-def $nzcv
+    $w9 = ADDWri $w0, 0, 0
+    Bcc 11, %bb.1, implicit killed $nzcv
+    B %bb.2
+
+  bb.1.true:
+    liveins: $w0, $w9
+
+    STRWui renamable $w0, %stack.0.tmp, 0 :: (store 4 into %ir.tmp)
+    ADJCALLSTACKDOWN 0, 0, implicit-def dead $sp, implicit $sp
+    $x1 = ADDXri %stack.0.tmp, 0, 0
+    $x2 = ADDXri %stack.1.bigalloc, 0, 0
+    $w0 = COPY $wzr
+    BL @doSomething, csr_aarch64_aapcs, implicit-def dead $lr, implicit $sp, implicit $w0, implicit $x1, implicit killed $x2, implicit-def $sp, implicit-def dead $w0
+    ADJCALLSTACKUP 0, 0, implicit-def dead $sp, implicit $sp
+
+  bb.2.false:
+    liveins: $w0, $w9
+    $w0 = ADDWrs $w0, $w9, 0
+    RET_ReallyLR implicit $w0
+
+...

>From 38ad773bb2a3db34e236dc9d535f0e50e4c70bd4 Mon Sep 17 00:00:00 2001
From: Kuba Mracek <mracek at apple.com>
Date: Fri, 4 Dec 2026 16:53:17 +0000
Subject: [PATCH 2/2] [clang][Driver] Alias -fstack-clash-protection to
 -fstack-check on Darwin

On Darwin, stack probing via __chkstk_darwin (-fstack-check) is the
mechanism that provides stack clash protection, so treat
-f[no-]stack-clash-protection as an alias of -f[no-]stack-check there.
The last of the four flags wins. Previously -fstack-clash-protection was
ignored on Darwin with an "argument unused" warning.

Non-Darwin targets are unchanged.
---
 clang/lib/Driver/ToolChains/Clang.cpp         | 19 ++++++++++++---
 .../Driver/darwin-stack-clash-protection.c    | 24 +++++++++++++++++++
 2 files changed, 40 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/Driver/darwin-stack-clash-protection.c

diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp
index e301402036138b..c6a88519d863bd 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -7484,9 +7484,22 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
       CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + Value));
   }
 
-  bool UseStackChecking =
-      Args.hasFlag(options::OPT_fstack_check, options::OPT_fno_stack_check,
-                   getToolChain().useStackChecking(Args));
+  bool UseStackChecking = getToolChain().useStackChecking(Args);
+  if (RawTriple.isOSDarwin()) {
+    // On Darwin, -f[no-]stack-clash-protection is an alias for
+    // -f[no-]stack-check: both mean probing the stack via __chkstk_darwin.
+    if (Arg *A = Args.getLastArg(options::OPT_fstack_check,
+                                 options::OPT_fno_stack_check,
+                                 options::OPT_fstack_clash_protection,
+                                 options::OPT_fno_stack_clash_protection))
+      UseStackChecking =
+          A->getOption().matches(options::OPT_fstack_check) ||
+          A->getOption().matches(options::OPT_fstack_clash_protection);
+  } else {
+    UseStackChecking = Args.hasFlag(options::OPT_fstack_check,
+                                    options::OPT_fno_stack_check,
+                                    UseStackChecking);
+  }
   if (UseStackChecking)
     CmdArgs.push_back("-fstack-check");
 
diff --git a/clang/test/Driver/darwin-stack-clash-protection.c b/clang/test/Driver/darwin-stack-clash-protection.c
new file mode 100644
index 00000000000000..69ed4f8d129d8c
--- /dev/null
+++ b/clang/test/Driver/darwin-stack-clash-protection.c
@@ -0,0 +1,24 @@
+// On Darwin, -f[no-]stack-clash-protection is an alias for -f[no-]stack-check.
+
+// RUN: %clang -target arm64-apple-macosx15.0 %s -fstack-clash-protection -### 2>&1 | FileCheck %s --check-prefix=ENABLE
+// RUN: %clang -target arm64-apple-ios12.0 %s -fstack-clash-protection -### 2>&1 | FileCheck %s --check-prefix=ENABLE
+// RUN: %clang -target arm64-apple-macosx15.0 %s -fno-stack-check -fstack-clash-protection -### 2>&1 | FileCheck %s --check-prefix=ENABLE
+// RUN: %clang -target arm64-apple-macosx15.0 %s -fno-stack-clash-protection -fstack-check -### 2>&1 | FileCheck %s --check-prefix=ENABLE
+// ENABLE-NOT: argument unused
+// ENABLE: "-cc1"
+// ENABLE-SAME: "-fstack-check"
+// ENABLE-NOT: "-fstack-clash-protection"
+
+// RUN: %clang -target arm64-apple-macosx15.0 %s -fno-stack-clash-protection -### 2>&1 | FileCheck %s --check-prefix=DISABLE
+// RUN: %clang -target arm64-apple-macosx15.0 %s -fstack-check -fno-stack-clash-protection -### 2>&1 | FileCheck %s --check-prefix=DISABLE
+// RUN: %clang -target arm64-apple-macosx15.0 %s -fstack-clash-protection -fno-stack-check -### 2>&1 | FileCheck %s --check-prefix=DISABLE
+// DISABLE-NOT: argument unused
+// DISABLE: "-cc1"
+// DISABLE-NOT: "-fstack-check"
+// DISABLE-NOT: "-fstack-clash-protection"
+
+// Non-Darwin targets are unaffected: -fstack-clash-protection doesn't imply
+// -fstack-check.
+// RUN: %clang -target aarch64-linux-gnu %s -fstack-clash-protection -### 2>&1 | FileCheck %s --check-prefix=LINUX
+// LINUX: "-fstack-clash-protection"
+// LINUX-NOT: "-fstack-check"



More information about the cfe-commits mailing list