[clang] [llvm] [OpenMP][CodeGen] Preserve libcalls for declare simd redecls (PR #193881)

via cfe-commits cfe-commits at lists.llvm.org
Fri Nov 27 02:48:41 PST 2026


https://github.com/wpcwzy updated https://github.com/llvm/llvm-project/pull/193881

>From 08becebfc53d69b783b1851cd4bd36d527b39ecf Mon Sep 17 00:00:00 2001
From: Pincheng Wang <pincheng.plct at isrc.iscas.ac.cn>
Date: Sat, 14 Nov 2026 20:56:08 +0800
Subject: [PATCH] [Clang][OpenMP] Preserve libcalls and emit declare simd libm
 mappings

Clang folds libm calls into LLVM intrinsics, which hides the
vector-function-abi-variant mapping of a declare simd redeclaration.
Keep the scalar libcall in that case and emit the VFABI mapping on the
call site from the _ZGV* variant names in the header, filtered by the
features of the function being compiled (CurGD keeps the
MultiVersionIndex of cpu_specific/cpu_dispatch/target_clones versions)
and the preferred vector width.

Skip signatures that cannot have a vector variant: variadic functions,
non-vectorizable return types, and existing symbols whose type does not
match the vector function type. Keep the vector variant declarations in
llvm.compiler.used so they survive GlobalOpt, and keep SimplifyLibCalls
from folding or shrinking mapped calls.
---
 clang/lib/CodeGen/CGBuiltin.cpp               |   5 +
 clang/lib/CodeGen/CGCall.cpp                  |  23 +++
 clang/lib/CodeGen/CGOpenMPRuntime.cpp         | 187 ++++++++++++++++++
 clang/lib/CodeGen/CGOpenMPRuntime.h           |  12 ++
 clang/lib/CodeGen/CodeGenModule.cpp           |   9 +-
 clang/test/OpenMP/Inputs/declare-simd-math.h  |   5 +
 .../OpenMP/declare_simd_math_global_init.cpp  |  16 ++
 clang/test/OpenMP/declare_simd_math_header.c  |  57 ++++++
 clang/test/OpenMP/declare_simd_math_objc.m    |  22 +++
 clang/test/OpenMP/declare_simd_math_redecl.c  |  20 ++
 clang/test/OpenMP/declare_simd_math_target.c  |  40 ++++
 .../OpenMP/declare_simd_math_unsupported.c    |  44 +++++
 .../OpenMP/declare_simd_preserve_builtin.cpp  |  14 ++
 .../lib/Transforms/Utils/SimplifyLibCalls.cpp |  19 +-
 .../Transforms/InstCombine/vfabi-mapping.ll   |  77 ++++++++
 15 files changed, 543 insertions(+), 7 deletions(-)
 create mode 100644 clang/test/OpenMP/Inputs/declare-simd-math.h
 create mode 100644 clang/test/OpenMP/declare_simd_math_global_init.cpp
 create mode 100644 clang/test/OpenMP/declare_simd_math_header.c
 create mode 100644 clang/test/OpenMP/declare_simd_math_objc.m
 create mode 100644 clang/test/OpenMP/declare_simd_math_redecl.c
 create mode 100644 clang/test/OpenMP/declare_simd_math_target.c
 create mode 100644 clang/test/OpenMP/declare_simd_math_unsupported.c
 create mode 100644 clang/test/OpenMP/declare_simd_preserve_builtin.cpp
 create mode 100644 llvm/test/Transforms/InstCombine/vfabi-mapping.ll

diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 0b28bc9f43d5d3..422c88a84ff33d 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -17,6 +17,7 @@
 #include "CGDebugInfo.h"
 #include "CGObjCRuntime.h"
 #include "CGOpenCLRuntime.h"
+#include "CGOpenMPRuntime.h"
 #include "CGRecordLayout.h"
 #include "CGValue.h"
 #include "CodeGenFunction.h"
@@ -2828,6 +2829,10 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
           BuiltinID, CGM.getTriple(), ErrnoOverriden, getLangOpts().MathErrno,
           OptNone, IsOptimizationEnabled);
 
+  if (GenerateFPMathIntrinsics && getLangOpts().OpenMP &&
+      CGOpenMPRuntime::hasLibraryDeclareSimdVariants(FD))
+    GenerateFPMathIntrinsics = false;
+
   if (GenerateFPMathIntrinsics) {
     switch (BuiltinIDIfNoAsmLabel) {
     case Builtin::BIacos:
diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 70747314412a50..d5d1fbc9e1d3ff 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -18,6 +18,7 @@
 #include "CGCXXABI.h"
 #include "CGCleanup.h"
 #include "CGDebugInfo.h"
+#include "CGOpenMPRuntime.h"
 #include "CGRecordLayout.h"
 #include "CodeGenFunction.h"
 #include "CodeGenModule.h"
@@ -52,6 +53,7 @@
 #include "llvm/IR/IntrinsicInst.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/Type.h"
+#include "llvm/IR/VFABIDemangler.h"
 #include "llvm/Transforms/Utils/Local.h"
 #include <optional>
 using namespace clang;
@@ -6572,6 +6574,27 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
     }
   }
 
+  // The mapping goes on the call, so that each caller only gets the vector
+  // variants it can run. Check hasLibraryDeclareSimdVariants() before building
+  // the "no-builtin-<name>" attribute name, since FD may not have a simple
+  // identifier (e.g. a constructor).
+  if (const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
+      getLangOpts().OpenMP && FD && isa<llvm::CallInst>(CI) &&
+      CGOpenMPRuntime::hasLibraryDeclareSimdVariants(FD) &&
+      !Attrs.hasFnAttr(llvm::Attribute::NoBuiltin) &&
+      !CurFn->hasFnAttribute("no-builtins") &&
+      !CurFn->hasFnAttribute(("no-builtin-" + FD->getName()).str())) {
+    if (llvm::Function *F = CI->getCalledFunction();
+        F && !F->hasFnAttribute(llvm::Attribute::NoBuiltin) &&
+        F->getFunctionType() == CI->getFunctionType()) {
+      std::string Mappings =
+          CGM.getOpenMPRuntime().getDeclareSimdVariantMappings(*this, F);
+      if (!Mappings.empty())
+        Attrs = Attrs.addFnAttribute(getLLVMContext(),
+                                     llvm::VFABI::MappingsAttrName, Mappings);
+    }
+  }
+
   // Apply the attributes and calling convention.
   CI->setAttributes(Attrs);
   CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index b828b63592cddd..21ea89ae696eea 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -34,13 +34,16 @@
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringExtras.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Bitcode/BitcodeReader.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/GlobalValue.h"
 #include "llvm/IR/InstrTypes.h"
+#include "llvm/IR/VFABIDemangler.h"
 #include "llvm/IR/Value.h"
+#include "llvm/IR/VectorTypeUtils.h"
 #include "llvm/Support/AtomicOrdering.h"
 #include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
@@ -12405,6 +12408,190 @@ evaluateCDTSize(const FunctionDecl *FD,
   return C.getTypeSize(CDT);
 }
 
+/// Returns true if code built with \p Features can run vector functions of
+/// \p ISA.
+static bool isVFISASupported(llvm::VFISAKind ISA,
+                             const llvm::StringMap<bool> &Features) {
+  switch (ISA) {
+  case llvm::VFISAKind::SSE:
+    return Features.lookup("sse2");
+  case llvm::VFISAKind::AVX:
+    return Features.lookup("avx");
+  case llvm::VFISAKind::AVX2:
+    return Features.lookup("avx2");
+  case llvm::VFISAKind::AVX512:
+    return Features.lookup("avx512f");
+  case llvm::VFISAKind::AdvancedSIMD:
+    return Features.lookup("neon");
+  case llvm::VFISAKind::SVE:
+    return Features.lookup("sve");
+  case llvm::VFISAKind::RVV:
+    return Features.lookup("v");
+  case llvm::VFISAKind::LLVM:
+    // The LLVM ISA is target independent.
+    return true;
+  case llvm::VFISAKind::Unknown:
+    // Unrecognized ISA field; be conservative and drop the variant.
+    return false;
+  }
+  llvm_unreachable("Unhandled VFISAKind");
+}
+
+/// Returns the vector register width used by \p ISA, or 0 if the width is not
+/// fixed by the ISA.
+static unsigned getVFISARegisterWidth(llvm::VFISAKind ISA) {
+  switch (ISA) {
+  case llvm::VFISAKind::SSE:
+  case llvm::VFISAKind::AdvancedSIMD:
+    return 128;
+  case llvm::VFISAKind::AVX:
+  case llvm::VFISAKind::AVX2:
+    return 256;
+  case llvm::VFISAKind::AVX512:
+    return 512;
+  default:
+    return 0;
+  }
+}
+
+/// Returns how capable \p ISA is compared to the other ISA classes.
+static unsigned getVFISARank(llvm::VFISAKind ISA) {
+  switch (ISA) {
+  case llvm::VFISAKind::SSE:
+    return 1;
+  case llvm::VFISAKind::AVX:
+    return 2;
+  case llvm::VFISAKind::AVX2:
+    return 3;
+  case llvm::VFISAKind::AVX512:
+    return 4;
+  default:
+    return 0;
+  }
+}
+
+bool CGOpenMPRuntime::hasLibraryDeclareSimdVariants(const FunctionDecl *FD) {
+  if (!FD || FD->hasAttr<AsmLabelAttr>())
+    return false;
+
+  unsigned BuiltinID = FD->getBuiltinID();
+  if (!BuiltinID ||
+      !FD->getASTContext().BuiltinInfo.isPredefinedLibFunction(BuiltinID))
+    return false;
+
+  return llvm::any_of(FD->redecls(), [](const FunctionDecl *Redecl) {
+    return Redecl->hasAttr<OMPDeclareSimdDeclAttr>();
+  });
+}
+
+std::string
+CGOpenMPRuntime::getDeclareSimdVariantMappings(CodeGenFunction &CGF,
+                                               llvm::Function *Fn) {
+  llvm::FunctionType *ScalarFTy = Fn->getFunctionType();
+  if (ScalarFTy->isVarArg() ||
+      !llvm::canVectorizeTy(ScalarFTy->getReturnType()))
+    return {};
+
+  // Filter by the caller features: a function may have its own target
+  // features, and full LTO keeps a single declaration of the scalar function.
+  // CurGD is used instead of CurCodeDecl to keep the MultiVersionIndex, so
+  // that cpu_specific/cpu_dispatch/target_clones functions get the features of
+  // the version being compiled.
+  const llvm::StringMap<bool> &Features =
+      CGM.getContext().getFunctionFeatureMap(
+          CGF.CurCodeDecl == CGF.CurGD.getDecl() ? CGF.CurGD : GlobalDecl());
+
+  // Respect -mprefer-vector-width, otherwise the vectorizer can pick a variant
+  // wider than the preferred width, e.g. a 512-bit call with
+  // -mprefer-vector-width=256.
+  unsigned PreferWidth = 0;
+  StringRef PreferVectorWidth = CGM.getCodeGenOpts().PreferVectorWidth;
+  if (!PreferVectorWidth.empty() && PreferVectorWidth != "none")
+    (void)PreferVectorWidth.getAsInteger(10, PreferWidth);
+
+  struct Variant {
+    llvm::VFInfo Info;
+    std::string Name;
+  };
+  llvm::SmallVector<Variant, 8> Variants;
+  for (llvm::Attribute Attr : Fn->getAttributes().getFnAttrs()) {
+    if (!Attr.isStringAttribute())
+      continue;
+
+    StringRef VariantName = Attr.getKindAsString();
+    if (!VariantName.starts_with("_ZGV"))
+      continue;
+
+    std::optional<llvm::VFInfo> Info =
+        llvm::VFABI::tryDemangleForVFABI(VariantName, ScalarFTy);
+    if (!Info || !isVFISASupported(Info->ISA, Features))
+      continue;
+
+    if (llvm::any_of(Info->Shape.Parameters, [&](const llvm::VFParameter &P) {
+          return P.ParamKind == llvm::VFParamKind::Vector &&
+                 !llvm::VectorType::isValidElementType(
+                     ScalarFTy->getParamType(P.ParamPos));
+        }))
+      continue;
+
+    unsigned RegisterWidth = getVFISARegisterWidth(Info->ISA);
+    if (PreferWidth && RegisterWidth > PreferWidth)
+      continue;
+
+    Variants.push_back({*Info, std::string(VariantName)});
+  }
+
+  llvm::SmallVector<std::string, 8> Mappings;
+  for (const Variant &Var : Variants) {
+    // Keep only the most capable ISA class for a given vector shape. The
+    // mapping does not imply a preference order.
+    if (llvm::any_of(Variants, [&](const Variant &Other) {
+          return Other.Info.Shape == Var.Info.Shape &&
+                 getVFISARank(Other.Info.ISA) > getVFISARank(Var.Info.ISA);
+        }))
+      continue;
+
+    llvm::FunctionType *VectorTy =
+        llvm::VFABI::createFunctionType(Var.Info, ScalarFTy);
+    llvm::Module &M = CGM.getModule();
+    llvm::Function *VecFn = nullptr;
+    if (llvm::GlobalValue *GV = M.getNamedValue(Var.Info.VectorName)) {
+      VecFn = dyn_cast<llvm::Function>(GV);
+      if (!VecFn || VecFn->getFunctionType() != VectorTy)
+        continue;
+    } else {
+      VecFn = llvm::Function::Create(VectorTy,
+                                     llvm::GlobalValue::ExternalLinkage,
+                                     Var.Info.VectorName, M);
+      for (llvm::Attribute::AttrKind Kind :
+           {llvm::Attribute::NoUnwind, llvm::Attribute::WillReturn,
+            llvm::Attribute::NoFree, llvm::Attribute::NoSync,
+            llvm::Attribute::NoCallback})
+        if (Fn->hasFnAttribute(Kind))
+          VecFn->addFnAttr(Kind);
+
+      // The vector variant computes the same function, so the memory effects
+      // can be copied unless they depend on the argument memory and the
+      // pointer arguments become vector parameters.
+      if (llvm::Attribute Mem = Fn->getFnAttribute(llvm::Attribute::Memory);
+          Mem.isValid() &&
+          (Mem.getMemoryEffects().getModRef(llvm::IRMemLocation::ArgMem) ==
+               llvm::ModRefInfo::NoModRef ||
+           llvm::none_of(VectorTy->params(), [](llvm::Type *Ty) {
+             return Ty->isVectorTy() && Ty->isPtrOrPtrVectorTy();
+           })))
+        VecFn->addFnAttr(Mem);
+    }
+    // The mapping attribute is not a use, so keep the vector function in the
+    // module; otherwise GlobalOpt drops its declaration before vectorization.
+    if (DeclareSimdVariantDecls.insert(VecFn).second)
+      CGM.addCompilerUsedGlobal(VecFn);
+    Mappings.push_back(Var.Name);
+  }
+
+  return llvm::join(Mappings, ",");
+}
+
 // This are the Functions that are needed to mangle the name of the
 // vector functions generated by the compiler, according to the rules
 // defined in the "Vector Function ABI specifications for AArch64",
diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.h b/clang/lib/CodeGen/CGOpenMPRuntime.h
index 00c4488ba97cf1..02968946e0e4a1 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.h
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.h
@@ -309,6 +309,9 @@ class CGOpenMPRuntime {
 protected:
   CodeGenModule &CGM;
 
+  /// Vector variant declarations that have been added to llvm.compiler.used.
+  llvm::SmallPtrSet<llvm::Function *, 8> DeclareSimdVariantDecls;
+
   /// An OpenMP-IR-Builder instance.
   llvm::OpenMPIRBuilder OMPBuilder;
 
@@ -1554,6 +1557,15 @@ class CGOpenMPRuntime {
   virtual void emitDeclareSimdFunction(const FunctionDecl *FD,
                                        llvm::Function *Fn);
 
+  /// Returns true if the vector variants named by the declare simd directives
+  /// of \p FD are provided by the C library.
+  static bool hasLibraryDeclareSimdVariants(const FunctionDecl *FD);
+
+  /// Returns the vector variant mappings of \p Fn that the function emitted by
+  /// \p CGF can call.
+  std::string getDeclareSimdVariantMappings(CodeGenFunction &CGF,
+                                            llvm::Function *Fn);
+
   /// Emit initialization for doacross loop nesting support.
   /// \param D Loop-based construct used in doacross nesting construct.
   virtual void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D,
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp
index 390ca6dbba4616..c515e3550bb283 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3959,7 +3959,10 @@ void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
   if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
     setKCFIType(FD, F);
 
-  if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
+  if (getLangOpts().OpenMP &&
+      llvm::any_of(FD->redecls(), [](const FunctionDecl *Redecl) {
+        return Redecl->hasAttr<OMPDeclareSimdDeclAttr>();
+      }))
     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
 
   if (CodeGenOpts.InlineMaxStackSize != UINT_MAX)
@@ -3990,8 +3993,8 @@ void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
 }
 
 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
-  assert(!GV->isDeclaration() &&
-         "Only globals with definition can force usage.");
+  assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
+         "Only functions can be used without a definition.");
   LLVMCompilerUsed.emplace_back(GV);
 }
 
diff --git a/clang/test/OpenMP/Inputs/declare-simd-math.h b/clang/test/OpenMP/Inputs/declare-simd-math.h
new file mode 100644
index 00000000000000..47972a616d49ed
--- /dev/null
+++ b/clang/test/OpenMP/Inputs/declare-simd-math.h
@@ -0,0 +1,5 @@
+#pragma omp declare simd notinbranch
+double acosh(double);
+
+#pragma omp declare simd notinbranch
+double sin(double);
diff --git a/clang/test/OpenMP/declare_simd_math_global_init.cpp b/clang/test/OpenMP/declare_simd_math_global_init.cpp
new file mode 100644
index 00000000000000..d842e03542806f
--- /dev/null
+++ b/clang/test/OpenMP/declare_simd_math_global_init.cpp
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O2 -disable-llvm-passes \
+// RUN:   -fopenmp -ffast-math -emit-llvm %s -o - | FileCheck %s
+
+extern "C" {
+#pragma omp declare simd notinbranch
+double sin(double);
+}
+
+extern double d;
+double g = sin(d);
+
+// The global initializer has no function of its own, so the mapping must be
+// built from the target features instead of crashing.
+// CHECK-LABEL: define internal void @__cxx_global_var_init(
+// CHECK: call{{.*}} double @sin({{.*}}) #[[MAPPED:[0-9]+]]
+// CHECK-DAG: attributes #[[MAPPED]] = {{.*}}"vector-function-abi-variant"="_ZGVbN2v_sin"
diff --git a/clang/test/OpenMP/declare_simd_math_header.c b/clang/test/OpenMP/declare_simd_math_header.c
new file mode 100644
index 00000000000000..a9ebbb8d44ae44
--- /dev/null
+++ b/clang/test/OpenMP/declare_simd_math_header.c
@@ -0,0 +1,57 @@
+// REQUIRES: x86-registered-target
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O2 -fopenmp -ffast-math \
+// RUN:   -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O2 -fopenmp -ffast-math \
+// RUN:   -target-feature +avx -target-feature +avx2 -emit-llvm %s -o - \
+// RUN:   | FileCheck %s --check-prefix=AVX2
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O2 -fopenmp -ffast-math \
+// RUN:   -target-feature +avx -target-feature +avx2 \
+// RUN:   -target-feature +avx512f -mprefer-vector-width=256 -emit-llvm %s -o - \
+// RUN:   | FileCheck %s --check-prefix=PREFER256
+
+// Check declare-simd libm functions declared in a header: the vector variant
+// mappings are attached to the calls, only for ISAs the caller supports and no
+// wider than -mprefer-vector-width, and the loop uses the variant instead of
+// the intrinsic.
+
+#include "Inputs/declare-simd-math.h"
+
+void loop_acosh(double *restrict d, const double *restrict x, int n) {
+#pragma omp simd
+  for (int i = 0; i < n; i++)
+    d[i] = acosh(x[i]);
+}
+
+void loop_sin(double *restrict d, const double *restrict x, int n) {
+#pragma omp simd
+  for (int i = 0; i < n; i++)
+    d[i] = sin(x[i]);
+}
+
+// The vector functions are kept in llvm.compiler.used so that GlobalOpt does
+// not drop their declarations before vectorization.
+// CHECK: @llvm.compiler.used = appending global [2 x ptr] {{.*}}_ZGVbN2v_acosh{{.*}}_ZGVbN2v_sin
+// Both loops use the SSE variants on the base x86-64 target, and the
+// middle-end must not fold the calls back into intrinsics.
+// CHECK: call{{.*}}<2 x double> @_ZGVbN2v_acosh(
+// CHECK: call{{.*}}<2 x double> @_ZGVbN2v_sin(
+// CHECK-NOT: llvm.acosh
+// CHECK-NOT: llvm.sin
+// CHECK: "vector-function-abi-variant"="_ZGVbN2v_acosh"
+// CHECK: "vector-function-abi-variant"="_ZGVbN2v_sin"
+
+// AVX2 additionally gets the 256-bit variants. The AVX variant is dropped
+// because the AVX2 one has the same shape, and the AVX-512 one is not usable.
+// AVX2: @llvm.compiler.used = appending global [4 x ptr] {{.*}}_ZGVdN4v_sin
+// AVX2-NOT: ptr @_ZGVcN4v
+// AVX2-NOT: ptr @_ZGVeN8v
+// AVX2: call{{.*}}<4 x double> @_ZGVdN4v_acosh(
+// AVX2: "vector-function-abi-variant"="_ZGVbN2v_acosh,_ZGVdN4v_acosh"
+
+// -mprefer-vector-width=256 on an AVX-512 target must not offer or use the
+// 512-bit variants.
+// PREFER256: @llvm.compiler.used = appending global [4 x ptr] {{.*}}_ZGVdN4v_sin
+// PREFER256-NOT: ptr @_ZGVeN8v
+// PREFER256: call{{.*}}<4 x double> @_ZGVdN4v_acosh(
+// PREFER256: "vector-function-abi-variant"="_ZGVbN2v_acosh,_ZGVdN4v_acosh"
diff --git a/clang/test/OpenMP/declare_simd_math_objc.m b/clang/test/OpenMP/declare_simd_math_objc.m
new file mode 100644
index 00000000000000..eb6715374b8c4d
--- /dev/null
+++ b/clang/test/OpenMP/declare_simd_math_objc.m
@@ -0,0 +1,22 @@
+// REQUIRES: x86-registered-target
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -x objective-c -O2 \
+// RUN:   -disable-llvm-passes -fopenmp -ffast-math -emit-llvm %s -o - \
+// RUN:   | FileCheck %s
+
+// The method has no FunctionDecl to take the target features from, so the
+// mapping is built from the TU features.
+#pragma omp declare simd notinbranch
+double sin(double);
+
+ at interface A
+- (double)m:(double)x;
+ at end
+ at implementation A
+- (double)m:(double)x {
+  return sin(x);
+}
+ at end
+
+// CHECK: call{{.*}} double @sin({{.*}}) #[[MAPPED:[0-9]+]]
+// CHECK-DAG: attributes #[[MAPPED]] = {{.*}}"vector-function-abi-variant"="_ZGVbN2v_sin"
diff --git a/clang/test/OpenMP/declare_simd_math_redecl.c b/clang/test/OpenMP/declare_simd_math_redecl.c
new file mode 100644
index 00000000000000..d991a16bb707bd
--- /dev/null
+++ b/clang/test/OpenMP/declare_simd_math_redecl.c
@@ -0,0 +1,20 @@
+// REQUIRES: x86-registered-target
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O2 -fopenmp -ffast-math \
+// RUN:   -emit-llvm %s -o - | FileCheck %s
+
+// The declaration carrying the simd clauses can be followed by another
+// declaration without them. The mapping is built from all redeclarations.
+#pragma omp declare simd notinbranch
+double sin(double);
+double sin(double);
+
+void loop_sin(double *restrict d, const double *restrict x, int n) {
+#pragma omp simd
+  for (int i = 0; i < n; i++)
+    d[i] = sin(x[i]);
+}
+
+// CHECK: @llvm.compiler.used = appending global [1 x ptr] {{.*}}_ZGVbN2v_sin
+// CHECK: call{{.*}}<2 x double> @_ZGVbN2v_sin(
+// CHECK-DAG: attributes #[[MAPPED:[0-9]+]] = {{.*}}"vector-function-abi-variant"="_ZGVbN2v_sin"
diff --git a/clang/test/OpenMP/declare_simd_math_target.c b/clang/test/OpenMP/declare_simd_math_target.c
new file mode 100644
index 00000000000000..ed7fb2fc859b49
--- /dev/null
+++ b/clang/test/OpenMP/declare_simd_math_target.c
@@ -0,0 +1,40 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O2 -disable-llvm-passes \
+// RUN:   -fopenmp -ffast-math -fblocks -emit-llvm %s -o - | FileCheck %s
+
+#include "Inputs/declare-simd-math.h"
+
+double base(double x) { return sin(x); }
+__attribute__((target("avx2"))) double avx2(double x) { return sin(x); }
+__attribute__((target_clones("avx512f", "default"))) double clones(double x) {
+  return acosh(x);
+}
+__attribute__((cpu_specific(ivybridge))) double specific(double x) {
+  return sin(x);
+}
+__attribute__((target("avx2"))) double block_call(double x) {
+  double (^blk)(double) = ^(double y) { return sin(y); };
+  return blk(x);
+}
+
+// CHECK-LABEL: define{{.*}} double @base(
+// CHECK: call{{.*}} double @sin({{.*}}) #[[BASE:[0-9]+]]
+// CHECK: declare <2 x double> @_ZGVbN2v_sin(<2 x double>) #[[VEC_ATTR:[0-9]+]]
+// CHECK-LABEL: define{{.*}} double @avx2(
+// CHECK: call{{.*}} double @sin({{.*}}) #[[AVX2:[0-9]+]]
+// CHECK-LABEL: define{{.*}} double @clones.avx512f
+// CHECK: call{{.*}} double @acosh({{.*}}) #[[CLONES_AVX512:[0-9]+]]
+// CHECK-LABEL: define{{.*}} double @clones.default
+// CHECK: call{{.*}} double @acosh({{.*}}) #[[CLONES_DEFAULT:[0-9]+]]
+// CHECK-LABEL: define{{.*}} double @specific
+// CHECK: call{{.*}} double @sin({{.*}}) #[[SPECIFIC:[0-9]+]]
+// Blocks are compiled with the TU features, not the features of the function
+// they are defined in, so they get the same mapping as the base target.
+// CHECK-LABEL: define internal{{.*}} double @__block_call_block_invoke(
+// CHECK: call{{.*}} double @sin({{.*}}) #[[BASE]]
+// CHECK-DAG: attributes #[[BASE]] = {{.*}}"vector-function-abi-variant"="_ZGVbN2v_sin"
+// CHECK-DAG: attributes #[[AVX2]] = {{.*}}"vector-function-abi-variant"="_ZGVbN2v_sin,_ZGVdN4v_sin"
+// CHECK-DAG: attributes #[[CLONES_AVX512]] = {{.*}}"vector-function-abi-variant"="_ZGVbN2v_acosh,_ZGVdN4v_acosh,_ZGVeN8v_acosh"
+// CHECK-DAG: attributes #[[CLONES_DEFAULT]] = {{.*}}"vector-function-abi-variant"="_ZGVbN2v_acosh"
+// CHECK-DAG: attributes #[[SPECIFIC]] = {{.*}}"vector-function-abi-variant"="_ZGVbN2v_sin,_ZGVcN4v_sin"
+// The variant declarations carry the attributes of the scalar function.
+// CHECK-DAG: attributes #[[VEC_ATTR:[0-9]+]] = { nounwind willreturn memory(none) }
diff --git a/clang/test/OpenMP/declare_simd_math_unsupported.c b/clang/test/OpenMP/declare_simd_math_unsupported.c
new file mode 100644
index 00000000000000..2d097fa4a6a303
--- /dev/null
+++ b/clang/test/OpenMP/declare_simd_math_unsupported.c
@@ -0,0 +1,44 @@
+// REQUIRES: x86-registered-target
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O2 -disable-llvm-passes \
+// RUN:   -fopenmp -ffast-math -emit-llvm %s -o - | FileCheck %s
+
+// Calls whose scalar signature cannot be vectorized must not get a mapping.
+// Clang used to crash on the complex and variadic cases and used to attach
+// mappings that name a variant with a different signature.
+
+// A complex type cannot be a vector element type.
+#pragma omp declare simd notinbranch
+float _Complex cexpf(float _Complex);
+float _Complex complex_call(float _Complex z) { return cexpf(z); }
+
+// Variadic functions have no vector function type.
+#pragma omp declare simd
+int printf(const char *, ...);
+int printf_call(void) { return printf("hi"); }
+
+// The mapped symbol already exists with another signature.
+#pragma omp declare simd notinbranch
+double sin(double);
+float collide(double) __asm__("_ZGVbN2v_sin");
+float collide(double x) { return (float)x; }
+double collision_call(double x) { return sin(x); }
+
+// The call goes through a function pointer with a different signature.
+double mismatch_call(double x) {
+  return ((double (*)(double, double))sin)(x, 0.0);
+}
+
+// no_builtin on the caller disables the mapping.
+__attribute__((no_builtin("sin"))) double no_builtin_sin(double x) {
+  return sin(x);
+}
+__attribute__((no_builtin)) double no_builtin_all(double x) { return sin(x); }
+
+// A function renamed with an asm label is not the C library function.
+#pragma omp declare simd notinbranch
+double cos(double) __asm__("custom_cos");
+double asm_label_call(double x) { return cos(x); }
+
+// CHECK-LABEL: define{{.*}} @complex_call(
+// CHECK-NOT: "vector-function-abi-variant"
diff --git a/clang/test/OpenMP/declare_simd_preserve_builtin.cpp b/clang/test/OpenMP/declare_simd_preserve_builtin.cpp
new file mode 100644
index 00000000000000..7b6a808de13da3
--- /dev/null
+++ b/clang/test/OpenMP/declare_simd_preserve_builtin.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -O2 -ffast-math -fopenmp -emit-llvm %s -o - | FileCheck %s
+
+double sqrt(double);
+
+#pragma omp declare simd notinbranch
+double sqrt(double);
+
+double test(double x) {
+  return sqrt(x);
+}
+
+// CHECK-LABEL: define{{.*}}@_Z4testd(
+// CHECK: call{{.*}}@_Z4sqrtd(
+// CHECK-NOT: llvm.sqrt
diff --git a/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp b/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
index 25b78d40af2e04..22f83774bcb18a 100644
--- a/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
+++ b/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
@@ -32,6 +32,7 @@
 #include "llvm/IR/Module.h"
 #include "llvm/IR/PatternMatch.h"
 #include "llvm/IR/ProfDataUtils.h"
+#include "llvm/IR/VFABIDemangler.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/KnownBits.h"
@@ -2099,7 +2100,8 @@ static Value *optimizeDoubleFP(CallInst *CI, IRBuilderBase &B,
                                bool isBinary, const TargetLibraryInfo *TLI,
                                bool isPrecise = false) {
   Function *CalleeFn = CI->getCalledFunction();
-  if (!CI->getType()->isDoubleTy() || !CalleeFn)
+  if (!CI->getType()->isDoubleTy() || !CalleeFn ||
+      CI->hasFnAttr(VFABI::MappingsAttrName))
     return nullptr;
 
   // If not all the uses of the function are converted to float, then bail out.
@@ -3177,6 +3179,9 @@ static Value *optimizeSymmetricCall(CallInst *CI, bool IsEven,
   if (match(Src, m_OneUse(m_FNegOrFSubNegZero(m_Value(X)))) &&
       (IsEven || !mayFlushDenormalsToPositiveZero(CI))) {
     auto *Call = B.CreateCall(CI->getCalledFunction(), {X}, /*FMFSource=*/CI);
+    if (Attribute A = CI->getAttributes().getFnAttr(VFABI::MappingsAttrName);
+        A.isValid())
+      Call->addFnAttr(A);
     auto *CallInst = copyFlags(*CI, Call);
     if (IsEven) {
       // Even function: f(-x) = f(x)
@@ -3190,6 +3195,9 @@ static Value *optimizeSymmetricCall(CallInst *CI, bool IsEven,
   if (IsEven && (match(Src, m_FAbs(m_Value(X))) ||
                  match(Src, m_CopySign(m_Value(X), m_Value())))) {
     auto *Call = B.CreateCall(CI->getCalledFunction(), {X}, /*FMFSource=*/CI);
+    if (Attribute A = CI->getAttributes().getFnAttr(VFABI::MappingsAttrName);
+        A.isValid())
+      Call->addFnAttr(A);
     return copyFlags(*CI, Call);
   }
 
@@ -4227,6 +4235,9 @@ Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
   if (CI->isStrictFP())
     return nullptr;
 
+  // Replacing the call with an intrinsic would drop its VFABI mappings.
+  bool HasVectorMappings = CI->hasFnAttr(VFABI::MappingsAttrName);
+
   if (Value *V = optimizeSymmetric(CI, Func, Builder))
     return V;
 
@@ -4239,12 +4250,12 @@ Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
     return optimizeSinCosPi(CI, /*IsSin*/false, Builder);
   case LibFunc_sinf:
   case LibFunc_sinl:
-    if (CI->doesNotAccessMemory())
+    if (CI->doesNotAccessMemory() && !HasVectorMappings)
       return replaceUnaryCall(CI, Builder, Intrinsic::sin);
     return nullptr;
   case LibFunc_cosf:
   case LibFunc_cosl:
-    if (CI->doesNotAccessMemory())
+    if (CI->doesNotAccessMemory() && !HasVectorMappings)
       return replaceUnaryCall(CI, Builder, Intrinsic::cos);
     return nullptr;
   case LibFunc_powf:
@@ -4352,7 +4363,7 @@ Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
         hasFloatVersion(M, CI->getCalledFunction()->getName()))
       if (Value *V = optimizeUnaryDoubleFP(CI, Builder, TLI, true))
         return V;
-    if (CI->doesNotAccessMemory())
+    if (CI->doesNotAccessMemory() && !HasVectorMappings)
       return replaceUnaryCall(
           CI, Builder, Func == LibFunc_sin ? Intrinsic::sin : Intrinsic::cos);
     return nullptr;
diff --git a/llvm/test/Transforms/InstCombine/vfabi-mapping.ll b/llvm/test/Transforms/InstCombine/vfabi-mapping.ll
new file mode 100644
index 00000000000000..749cd81011d8fe
--- /dev/null
+++ b/llvm/test/Transforms/InstCombine/vfabi-mapping.ll
@@ -0,0 +1,77 @@
+; RUN: opt -passes=instcombine -S < %s | FileCheck %s
+
+declare double @sin(double) #0
+declare double @cos(double) #0
+declare double @acosh(double) #0
+declare float @acoshf(float)
+
+; A call carrying a VFABI mapping must stay a call, otherwise the loop
+; vectorizer cannot replace it with the vector variant.
+define double @mapped_sin(double %x) {
+; CHECK-LABEL: @mapped_sin(
+; CHECK-NEXT:    [[CALL:%.*]] = call double @sin(double %x) #[[MAPPED:[0-9]+]]
+; CHECK-NEXT:    ret double [[CALL]]
+  %r = call double @sin(double %x) #1
+  ret double %r
+}
+
+; A call without a mapping is folded to the intrinsic as usual.
+define double @plain_cos(double %x) {
+; CHECK-LABEL: @plain_cos(
+; CHECK:         [[CALL:%.*]] = call double @llvm.cos.f64(double %x)
+; CHECK-NEXT:    ret double [[CALL]]
+  %r = call double @cos(double %x)
+  ret double %r
+}
+
+; Rewriting f(-x) to -f(x) must keep the mapping on the new call.
+define double @mapped_sin_neg(double %x) {
+; CHECK-LABEL: @mapped_sin_neg(
+; CHECK-NEXT:    [[CALL:%.*]] = call double @sin(double %x) #[[MAPPED]]
+; CHECK-NEXT:    [[NEG:%.*]] = fneg double [[CALL]]
+; CHECK-NEXT:    ret double [[NEG]]
+  %n = fneg double %x
+  %r = call double @sin(double %n) #1
+  ret double %r
+}
+
+define double @plain_sin_neg(double %x) {
+; CHECK-LABEL: @plain_sin_neg(
+; CHECK-NEXT:    [[CALL:%.*]] = call double @llvm.sin.f64(double %x)
+; CHECK-NEXT:    [[NEG:%.*]] = fneg double [[CALL]]
+; CHECK-NEXT:    ret double [[NEG]]
+  %n = fneg double %x
+  %r = call double @sin(double %n)
+  ret double %r
+}
+
+; Shrinking a mapped call to its float version would lose the mapping.
+define float @mapped_acosh_to_float(float %f) {
+; CHECK-LABEL: @mapped_acosh_to_float(
+; CHECK-NEXT:    [[CONV:%.*]] = fpext float %f to double
+; CHECK-NEXT:    [[CALL:%.*]] = call fast double @acosh(double [[CONV]]) #[[ACOSH_MAPPED:[0-9]+]]
+; CHECK-NEXT:    [[TRUNC:%.*]] = fptrunc double [[CALL]] to float
+; CHECK-NEXT:    ret float [[TRUNC]]
+  %conv = fpext float %f to double
+  %r = call fast double @acosh(double %conv) #2
+  %t = fptrunc double %r to float
+  ret float %t
+}
+
+; Without a mapping the shrink still happens.
+define float @plain_acosh_to_float(float %f) {
+; CHECK-LABEL: @plain_acosh_to_float(
+; CHECK-NEXT:    [[SHRUNK:%.*]] = call fast float @acoshf(float %f)
+; CHECK-NEXT:    ret float [[SHRUNK]]
+  %conv = fpext float %f to double
+  %r = call fast double @acosh(double %conv)
+  %t = fptrunc double %r to float
+  ret float %t
+}
+
+; CHECK-DAG: attributes #[[MAPPED]] = { {{.*}}"vector-function-abi-variant"="_ZGV_LLVM_N2v_sin(vector_sin)"
+; CHECK-DAG: attributes #[[ACOSH_MAPPED]] = { {{.*}}"vector-function-abi-variant"="_ZGV_LLVM_N4v_acosh(vector_acosh)"
+
+attributes #0 = { memory(none) }
+attributes #1 = { "vector-function-abi-variant"="_ZGV_LLVM_N2v_sin(vector_sin)" }
+attributes #2 = { "vector-function-abi-variant"="_ZGV_LLVM_N4v_acosh(vector_acosh)" }



More information about the cfe-commits mailing list