[clang] Introduce paged vector (PR #66430)

2023-09-18 Thread Giulio Eulisse via cfe-commits

https://github.com/ktf updated https://github.com/llvm/llvm-project/pull/66430

>From b952f0577dfe8112f394bd5392212f843c0cc86e Mon Sep 17 00:00:00 2001
From: Giulio Eulisse <10544+...@users.noreply.github.com>
Date: Thu, 14 Sep 2023 21:58:21 +0200
Subject: [PATCH 01/16] Introduce PagedVector class

The goal of the class is to be an (almost) drop in replacement for
SmallVector and std::vector when those are presized and filled later,
as it happens in SourceManager and ASTReader.

By splitting the actual vector in pages of the same size and allocating
the pages only when they are needed, using this containers reduces the
memory usage by a factor 4 for the cases relevant to the ALICE
experiment ROOT / cling usage.
---
 llvm/include/llvm/ADT/PagedVector.h | 96 +
 1 file changed, 96 insertions(+)
 create mode 100644 llvm/include/llvm/ADT/PagedVector.h

diff --git a/llvm/include/llvm/ADT/PagedVector.h 
b/llvm/include/llvm/ADT/PagedVector.h
new file mode 100644
index 000..dab0d249aa706e4
--- /dev/null
+++ b/llvm/include/llvm/ADT/PagedVector.h
@@ -0,0 +1,96 @@
+//===- llvm/ADT/PagedVector.h - 'Lazyly allocated' vectors *- C++
+//-*-===//
+//
+// 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
+//
+//===--===//
+//
+// This file defines the PagedVector class.
+//
+//===--===//
+#ifndef LLVM_ADT_PAGEDVECTOR_H
+#define LLVM_ADT_PAGEDVECTOR_H
+
+#include 
+
+// Notice that this does not have iterators, because if you
+// have iterators it probably means you are going to touch
+// all the memory in any case, so better use a std::vector in
+// the first place.
+template  class PagedVector {
+  size_t Size = 0;
+  // Index of where to find a given page in the data
+  mutable std::vector Lookup;
+  // Actual data
+  mutable std::vector Data;
+
+public:
+  // Add a range to the vector.
+  // When vector is accessed, it will call the callback to fill the range
+  // with data.
+
+  // Lookup an element at position i.
+  // If the given range is not filled, it will be filled.
+  // If the given range is filled, return the element.
+  T [](int Index) const { return at(Index); }
+
+  T (int Index) const {
+auto  = Lookup[Index / PAGE_SIZE];
+// If the range is not filled, fill it
+if (PageId == -1) {
+  int OldSize = Data.size();
+  PageId = OldSize / PAGE_SIZE;
+  // Allocate the memory
+  Data.resize(OldSize + PAGE_SIZE);
+  // Fill the whole capacity with empty elements
+  for (int I = 0; I < PAGE_SIZE; ++I) {
+Data[I + OldSize] = T();
+  }
+}
+// Return the element
+return Data[Index % PAGE_SIZE + PAGE_SIZE * PageId];
+  }
+
+  // Return the size of the vector
+  size_t capacity() const { return Lookup.size() * PAGE_SIZE; }
+
+  size_t size() const { return Size; }
+
+  // Expands the vector to the given size.
+  // If the vector is already bigger, does nothing.
+  void expand(size_t NewSize) {
+// You cannot shrink the vector, otherwise
+// you would have to invalidate
+assert(NewSize >= Size);
+if (NewSize <= Size) {
+  return;
+}
+if (NewSize <= capacity()) {
+  Size = NewSize;
+  return;
+}
+auto Pages = NewSize / PAGE_SIZE;
+auto Remainder = NewSize % PAGE_SIZE;
+if (Remainder) {
+  Pages += 1;
+}
+assert(Pages > Lookup.size());
+Lookup.resize(Pages, -1);
+Size = NewSize;
+  }
+
+  // Return true if the vector is empty
+  bool empty() const { return Size == 0; }
+  /// Clear the vector
+  void clear() {
+Size = 0;
+Lookup.clear();
+Data.clear();
+  }
+
+  std::vector const () const { return Data; }
+};
+
+#endif // LLVM_ADT_PAGEDVECTOR_H

>From f0c75c8af0fea27b5b758e2e5775787f33595de3 Mon Sep 17 00:00:00 2001
From: Giulio Eulisse <10544+...@users.noreply.github.com>
Date: Thu, 14 Sep 2023 22:20:29 +0200
Subject: [PATCH 02/16] Use PagedVector to reduce memory usage of sparsely
 populated vectors

---
 clang/include/clang/Basic/SourceManager.h |  3 ++-
 clang/include/clang/Serialization/ASTReader.h |  5 +++--
 clang/lib/Basic/SourceManager.cpp | 12 ++--
 clang/lib/Serialization/ASTReader.cpp |  9 +
 4 files changed, 16 insertions(+), 13 deletions(-)

diff --git a/clang/include/clang/Basic/SourceManager.h 
b/clang/include/clang/Basic/SourceManager.h
index 2f846502d6f3327..b1942a3d86afc37 100644
--- a/clang/include/clang/Basic/SourceManager.h
+++ b/clang/include/clang/Basic/SourceManager.h
@@ -43,6 +43,7 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/PagedVector.h"
 #include "llvm/ADT/PointerIntPair.h"
 #include 

[clang-tools-extra] [clang-tidy] Update llvmlibc-implementation-in-namespace to new rules (PR #66504)

2023-09-18 Thread Guillaume Chatelet via cfe-commits

https://github.com/gchatelet updated 
https://github.com/llvm/llvm-project/pull/66504

>From f1427a81c4a3425c1a574316fc26d2c74297b34b Mon Sep 17 00:00:00 2001
From: Guillaume Chatelet 
Date: Fri, 15 Sep 2023 12:34:17 +
Subject: [PATCH 1/3] [clang-tidy] Update llvmlibc-implementation-in-namespace
 to new rules

This is the implementation of step 3 of
https://discourse.llvm.org/t/rfc-customizable-namespace-to-allow-testing-the-libc-when-the-system-libc-is-also-llvms-libc/73079.
---
 .../ImplementationInNamespaceCheck.cpp| 21 -
 .../llvmlibc/implementation-in-namespace.rst  | 23 +-
 .../llvmlibc/implementation-in-namespace.cpp  | 31 +--
 3 files changed, 50 insertions(+), 25 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/llvmlibc/ImplementationInNamespaceCheck.cpp 
b/clang-tools-extra/clang-tidy/llvmlibc/ImplementationInNamespaceCheck.cpp
index d05310f09ef773a..69a385f5be9807f 100644
--- a/clang-tools-extra/clang-tidy/llvmlibc/ImplementationInNamespaceCheck.cpp
+++ b/clang-tools-extra/clang-tidy/llvmlibc/ImplementationInNamespaceCheck.cpp
@@ -14,7 +14,9 @@ using namespace clang::ast_matchers;
 
 namespace clang::tidy::llvm_libc {
 
-const static StringRef RequiredNamespace = "__llvm_libc";
+const static StringRef RequiredNamespaceStart = "__llvm_libc";
+const static StringRef RequiredNamespaceMacroName = "LIBC_NAMESPACE";
+
 void ImplementationInNamespaceCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   decl(hasParent(translationUnitDecl()), unless(linkageSpecDecl()))
@@ -29,16 +31,19 @@ void ImplementationInNamespaceCheck::check(
   if (!Result.SourceManager->isInMainFile(MatchedDecl->getLocation()))
 return;
 
-  if (const auto *NS = dyn_cast(MatchedDecl)) {
-if (NS->getName() != RequiredNamespace) {
-  diag(NS->getLocation(), "'%0' needs to be the outermost namespace")
-  << RequiredNamespace;
-}
+  if (auto *NS = dyn_cast(MatchedDecl)) {
+if (!Result.SourceManager->isMacroBodyExpansion(NS->getLocation()))
+  diag(NS->getLocation(),
+   "the outermost namespace should be the '%0' macro")
+  << RequiredNamespaceMacroName;
+else if (!NS->getName().starts_with(RequiredNamespaceStart))
+  diag(NS->getLocation(), "the outermost namespace should start with '%0'")
+  << RequiredNamespaceStart;
 return;
   }
   diag(MatchedDecl->getLocation(),
-   "declaration must be declared within the '%0' namespace")
-  << RequiredNamespace;
+   "declaration must be declared within a namespace starting with '%0'")
+  << RequiredNamespaceStart;
 }
 
 } // namespace clang::tidy::llvm_libc
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/llvmlibc/implementation-in-namespace.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/llvmlibc/implementation-in-namespace.rst
index 33d6dc8ff125c84..47ea2b866a93404 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/llvmlibc/implementation-in-namespace.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/llvmlibc/implementation-in-namespace.rst
@@ -8,21 +8,30 @@ correct namespace.
 
 .. code-block:: c++
 
-// Correct: implementation inside the correct namespace.
-namespace __llvm_libc {
+// Implementation inside the LIBC_NAMESPACE namespace.
+// Correct if:
+// - LIBC_NAMESPACE is a macro
+// - LIBC_NAMESPACE expansion starts with `__llvm_libc`
+namespace LIBC_NAMESPACE {
 void LLVM_LIBC_ENTRYPOINT(strcpy)(char *dest, const char *src) {}
-// Namespaces within __llvm_libc namespace are allowed.
-namespace inner{
+// Namespaces within LIBC_NAMESPACE namespace are allowed.
+namespace inner {
 int localVar = 0;
 }
 // Functions with C linkage are allowed.
-extern "C" void str_fuzz(){}
+extern "C" void str_fuzz() {}
 }
 
-// Incorrect: implementation not in a namespace.
+// Incorrect: implementation not in the LIBC_NAMESPACE namespace.
 void LLVM_LIBC_ENTRYPOINT(strcpy)(char *dest, const char *src) {}
 
-// Incorrect: outer most namespace is not correct.
+// Incorrect: outer most namespace is not the LIBC_NAMESPACE macro.
 namespace something_else {
 void LLVM_LIBC_ENTRYPOINT(strcpy)(char *dest, const char *src) {}
 }
+
+// Incorrect: outer most namespace expansion does not start with 
`__llvm_libc`.
+#define LIBC_NAMESPACE custom_namespace
+namespace LIBC_NAMESPACE {
+void LLVM_LIBC_ENTRYPOINT(strcpy)(char *dest, const char *src) {}
+}
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/llvmlibc/implementation-in-namespace.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/llvmlibc/implementation-in-namespace.cpp
index e75556a623b655c..16c5f9ca1067ec5 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/llvmlibc/implementation-in-namespace.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/llvmlibc/implementation-in-namespace.cpp
@@ 

[clang] [InstCombine] Simplify the pattern `a ne/eq (zext (a ne/eq c))` (PR #65852)

2023-09-18 Thread Yingwei Zheng via cfe-commits

https://github.com/dtcxzyw updated 
https://github.com/llvm/llvm-project/pull/65852

>From d9d8bcbb98e8f5aecb9733329389d61a489bd731 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng 
Date: Sat, 9 Sep 2023 23:07:29 +0800
Subject: [PATCH 1/3] [InstCombine] Simplify the pattern `a ne/eq (zext (a
 ne/eq c))`

---
 .../InstCombine/InstCombineCompares.cpp   |  62 ++
 .../test/Transforms/InstCombine/icmp-range.ll | 181 ++
 2 files changed, 243 insertions(+)

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp 
b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
index 9fdc46fec631679..837b8e6d2619989 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
@@ -6309,7 +6309,69 @@ Instruction 
*InstCombinerImpl::foldICmpUsingBoolRange(ICmpInst ) {
   Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
 
+  ICmpInst::Predicate Pred1, Pred2;
   const APInt *C;
+  // icmp eq/ne X, (zext (icmp eq/ne X, C))
+  if (match(, m_c_ICmp(Pred1, m_Value(X),
+ m_ZExt(m_ICmp(Pred2, m_Deferred(X), m_APInt(C) &&
+  ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
+if (C->isZero()) {
+  if (Pred2 == ICmpInst::ICMP_EQ) {
+// icmp eq X, (zext (icmp eq X, 0)) --> false
+// icmp ne X, (zext (icmp eq X, 0)) --> true
+return replaceInstUsesWith(
+I,
+Constant::getIntegerValue(
+I.getType(),
+APInt(1U, static_cast(Pred1 == ICmpInst::ICMP_NE;
+  } else {
+// icmp eq X, (zext (icmp ne X, 0)) --> icmp ult X, 2
+// icmp ne X, (zext (icmp ne X, 0)) --> icmp ugt X, 1
+return ICmpInst::Create(
+Instruction::ICmp,
+Pred1 == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGT
+   : ICmpInst::ICMP_ULT,
+X,
+Constant::getIntegerValue(
+X->getType(), APInt(X->getType()->getScalarSizeInBits(),
+Pred1 == ICmpInst::ICMP_NE ? 1 : 2)));
+  }
+} else if (C->isOne()) {
+  if (Pred2 == ICmpInst::ICMP_NE) {
+// icmp eq X, (zext (icmp ne X, 1)) --> false
+// icmp ne X, (zext (icmp ne X, 1)) --> true
+return replaceInstUsesWith(
+I,
+Constant::getIntegerValue(
+I.getType(),
+APInt(1U, static_cast(Pred1 == ICmpInst::ICMP_NE;
+  } else {
+// icmp eq X, (zext (icmp eq X, 1)) --> icmp ult X, 2
+// icmp ne X, (zext (icmp eq X, 1)) --> icmp ugt X, 1
+return ICmpInst::Create(
+Instruction::ICmp,
+Pred1 == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGT
+   : ICmpInst::ICMP_ULT,
+X,
+Constant::getIntegerValue(
+X->getType(), APInt(X->getType()->getScalarSizeInBits(),
+Pred1 == ICmpInst::ICMP_NE ? 1 : 2)));
+  }
+} else {
+  // C != 0 && C != 1
+  // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
+  // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
+  // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
+  // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
+  return ICmpInst::Create(
+  Instruction::ICmp, Pred1, X,
+  Constant::getIntegerValue(
+  X->getType(),
+  APInt(X->getType()->getScalarSizeInBits(),
+static_cast(Pred2 == ICmpInst::ICMP_NE;
+}
+  }
+
   if (match(I.getOperand(0), m_c_Add(m_ZExt(m_Value(X)), m_SExt(m_Value(Y 
&&
   match(I.getOperand(1), m_APInt(C)) &&
   X->getType()->isIntOrIntVectorTy(1) &&
diff --git a/llvm/test/Transforms/InstCombine/icmp-range.ll 
b/llvm/test/Transforms/InstCombine/icmp-range.ll
index 4281e09cb0309c8..15424fce33fdeea 100644
--- a/llvm/test/Transforms/InstCombine/icmp-range.ll
+++ b/llvm/test/Transforms/InstCombine/icmp-range.ll
@@ -1034,6 +1034,187 @@ define i1 @icmp_ne_bool_1(ptr %ptr) {
   ret i1 %cmp
 }
 
+define i1 @icmp_ne_zext_eq_zero(i32 %a) {
+; CHECK-LABEL: @icmp_ne_zext_eq_zero(
+; CHECK-NEXT:ret i1 true
+;
+  %cmp = icmp eq i32 %a, 0
+  %conv = zext i1 %cmp to i32
+  %cmp1 = icmp ne i32 %conv, %a
+  ret i1 %cmp1
+}
+
+define i1 @icmp_ne_zext_ne_zero(i32 %a) {
+; CHECK-LABEL: @icmp_ne_zext_ne_zero(
+; CHECK-NEXT:[[CMP1:%.*]] = icmp ugt i32 [[A:%.*]], 1
+; CHECK-NEXT:ret i1 [[CMP1]]
+;
+  %cmp = icmp ne i32 %a, 0
+  %conv = zext i1 %cmp to i32
+  %cmp1 = icmp ne i32 %conv, %a
+  ret i1 %cmp1
+}
+
+define i1 @icmp_eq_zext_eq_zero(i32 %a) {
+; CHECK-LABEL: @icmp_eq_zext_eq_zero(
+; CHECK-NEXT:ret i1 false
+;
+  %cmp = icmp eq i32 %a, 0
+  %conv = zext i1 %cmp to i32
+  %cmp1 = icmp eq i32 %conv, %a
+  ret i1 %cmp1
+}
+
+define i1 @icmp_eq_zext_ne_zero(i32 %a) 

[PATCH] D155688: [PATCH] [llvm] [InstCombine] Reassociate loop invariant GEP index calculations.

2023-09-18 Thread Dmitriy Smirnov via Phabricator via cfe-commits
d-smirnov added a comment.

@nikic Could you check out the updated code to make sure we're on the right 
track before I try to fix the rest of the unit tests?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D155688/new/

https://reviews.llvm.org/D155688

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [InstCombine] Simplify the pattern `a ne/eq (zext (a ne/eq c))` (PR #65852)

2023-09-18 Thread Yingwei Zheng via cfe-commits

https://github.com/dtcxzyw resolved 
https://github.com/llvm/llvm-project/pull/65852
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [InstCombine] Simplify the pattern `a ne/eq (zext (a ne/eq c))` (PR #65852)

2023-09-18 Thread Yingwei Zheng via cfe-commits

https://github.com/dtcxzyw updated 
https://github.com/llvm/llvm-project/pull/65852

>From d9d8bcbb98e8f5aecb9733329389d61a489bd731 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng 
Date: Sat, 9 Sep 2023 23:07:29 +0800
Subject: [PATCH 1/2] [InstCombine] Simplify the pattern `a ne/eq (zext (a
 ne/eq c))`

---
 .../InstCombine/InstCombineCompares.cpp   |  62 ++
 .../test/Transforms/InstCombine/icmp-range.ll | 181 ++
 2 files changed, 243 insertions(+)

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp 
b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
index 9fdc46fec631679..837b8e6d2619989 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
@@ -6309,7 +6309,69 @@ Instruction 
*InstCombinerImpl::foldICmpUsingBoolRange(ICmpInst ) {
   Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
 
+  ICmpInst::Predicate Pred1, Pred2;
   const APInt *C;
+  // icmp eq/ne X, (zext (icmp eq/ne X, C))
+  if (match(, m_c_ICmp(Pred1, m_Value(X),
+ m_ZExt(m_ICmp(Pred2, m_Deferred(X), m_APInt(C) &&
+  ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
+if (C->isZero()) {
+  if (Pred2 == ICmpInst::ICMP_EQ) {
+// icmp eq X, (zext (icmp eq X, 0)) --> false
+// icmp ne X, (zext (icmp eq X, 0)) --> true
+return replaceInstUsesWith(
+I,
+Constant::getIntegerValue(
+I.getType(),
+APInt(1U, static_cast(Pred1 == ICmpInst::ICMP_NE;
+  } else {
+// icmp eq X, (zext (icmp ne X, 0)) --> icmp ult X, 2
+// icmp ne X, (zext (icmp ne X, 0)) --> icmp ugt X, 1
+return ICmpInst::Create(
+Instruction::ICmp,
+Pred1 == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGT
+   : ICmpInst::ICMP_ULT,
+X,
+Constant::getIntegerValue(
+X->getType(), APInt(X->getType()->getScalarSizeInBits(),
+Pred1 == ICmpInst::ICMP_NE ? 1 : 2)));
+  }
+} else if (C->isOne()) {
+  if (Pred2 == ICmpInst::ICMP_NE) {
+// icmp eq X, (zext (icmp ne X, 1)) --> false
+// icmp ne X, (zext (icmp ne X, 1)) --> true
+return replaceInstUsesWith(
+I,
+Constant::getIntegerValue(
+I.getType(),
+APInt(1U, static_cast(Pred1 == ICmpInst::ICMP_NE;
+  } else {
+// icmp eq X, (zext (icmp eq X, 1)) --> icmp ult X, 2
+// icmp ne X, (zext (icmp eq X, 1)) --> icmp ugt X, 1
+return ICmpInst::Create(
+Instruction::ICmp,
+Pred1 == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGT
+   : ICmpInst::ICMP_ULT,
+X,
+Constant::getIntegerValue(
+X->getType(), APInt(X->getType()->getScalarSizeInBits(),
+Pred1 == ICmpInst::ICMP_NE ? 1 : 2)));
+  }
+} else {
+  // C != 0 && C != 1
+  // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
+  // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
+  // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
+  // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
+  return ICmpInst::Create(
+  Instruction::ICmp, Pred1, X,
+  Constant::getIntegerValue(
+  X->getType(),
+  APInt(X->getType()->getScalarSizeInBits(),
+static_cast(Pred2 == ICmpInst::ICMP_NE;
+}
+  }
+
   if (match(I.getOperand(0), m_c_Add(m_ZExt(m_Value(X)), m_SExt(m_Value(Y 
&&
   match(I.getOperand(1), m_APInt(C)) &&
   X->getType()->isIntOrIntVectorTy(1) &&
diff --git a/llvm/test/Transforms/InstCombine/icmp-range.ll 
b/llvm/test/Transforms/InstCombine/icmp-range.ll
index 4281e09cb0309c8..15424fce33fdeea 100644
--- a/llvm/test/Transforms/InstCombine/icmp-range.ll
+++ b/llvm/test/Transforms/InstCombine/icmp-range.ll
@@ -1034,6 +1034,187 @@ define i1 @icmp_ne_bool_1(ptr %ptr) {
   ret i1 %cmp
 }
 
+define i1 @icmp_ne_zext_eq_zero(i32 %a) {
+; CHECK-LABEL: @icmp_ne_zext_eq_zero(
+; CHECK-NEXT:ret i1 true
+;
+  %cmp = icmp eq i32 %a, 0
+  %conv = zext i1 %cmp to i32
+  %cmp1 = icmp ne i32 %conv, %a
+  ret i1 %cmp1
+}
+
+define i1 @icmp_ne_zext_ne_zero(i32 %a) {
+; CHECK-LABEL: @icmp_ne_zext_ne_zero(
+; CHECK-NEXT:[[CMP1:%.*]] = icmp ugt i32 [[A:%.*]], 1
+; CHECK-NEXT:ret i1 [[CMP1]]
+;
+  %cmp = icmp ne i32 %a, 0
+  %conv = zext i1 %cmp to i32
+  %cmp1 = icmp ne i32 %conv, %a
+  ret i1 %cmp1
+}
+
+define i1 @icmp_eq_zext_eq_zero(i32 %a) {
+; CHECK-LABEL: @icmp_eq_zext_eq_zero(
+; CHECK-NEXT:ret i1 false
+;
+  %cmp = icmp eq i32 %a, 0
+  %conv = zext i1 %cmp to i32
+  %cmp1 = icmp eq i32 %conv, %a
+  ret i1 %cmp1
+}
+
+define i1 @icmp_eq_zext_ne_zero(i32 %a) 

[clang] [clang-cl] Fix for __FUNCTION__ in c++. (PR #66120)

2023-09-18 Thread Zahira Ammarguellat via cfe-commits

https://github.com/zahiraam updated 
https://github.com/llvm/llvm-project/pull/66120

>From 3fcfa303bd211f9a3382657012968cd3f7269db8 Mon Sep 17 00:00:00 2001
From: Ammarguellat 
Date: Tue, 12 Sep 2023 11:25:19 -0700
Subject: [PATCH 1/2] [clang-cl] Fix for __FUNCTION__ in c++.

---
 clang/lib/AST/Expr.cpp| 20 
 clang/lib/AST/TypePrinter.cpp |  4 
 2 files changed, 24 insertions(+)

diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 4f3837371b3fc5e..55b6e2968487b86 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -727,6 +727,26 @@ StringRef 
PredefinedExpr::getIdentKindName(PredefinedExpr::IdentKind IK) {
 std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) 
{
   ASTContext  = CurrentDecl->getASTContext();
 
+  if (CurrentDecl->getASTContext().getTargetInfo().getCXXABI().isMicrosoft() &&
+  IK == PredefinedExpr::Function) {
+if (const FunctionDecl *FD = dyn_cast(CurrentDecl)) {
+  SmallString<256> Name;
+  llvm::raw_svector_ostream Out(Name);
+  PrintingPolicy Policy(Context.getLangOpts());
+  Policy.AlwaysIncludeTypeForTemplateArgument = true;
+  std::string Proto;
+  llvm::raw_string_ostream POut(Proto);
+  const FunctionDecl *Decl = FD;
+  if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
+Decl = Pattern;
+  const FunctionType *AFT = Decl->getType()->getAs();
+  const FunctionProtoType *FT = nullptr;
+  if (FD->hasWrittenPrototype())
+FT = dyn_cast(AFT);
+  FD->printQualifiedName(POut, Policy);
+  return std::string(POut.str());
+}
+  }
   if (IK == PredefinedExpr::FuncDName) {
 if (const NamedDecl *ND = dyn_cast(CurrentDecl)) {
   std::unique_ptr MC;
diff --git a/clang/lib/AST/TypePrinter.cpp b/clang/lib/AST/TypePrinter.cpp
index eb69d0bb8755b48..676ce166312adf4 100644
--- a/clang/lib/AST/TypePrinter.cpp
+++ b/clang/lib/AST/TypePrinter.cpp
@@ -2218,6 +2218,10 @@ printTo(raw_ostream , ArrayRef Args, const 
PrintingPolicy ,
 } else {
   if (!FirstArg)
 OS << Comma;
+  // zahira
+  //if (Argument.getKind() == TemplateArgument::Type)
+  //  OS << "class ";
+
   // Tries to print the argument with location info if exists.
   printArgument(Arg, Policy, ArgOS,
 TemplateParameterList::shouldIncludeTypeForArgument(

>From f2c2d9ca4120d61e8cf75165693ead19890be0e0 Mon Sep 17 00:00:00 2001
From: Ammarguellat 
Date: Wed, 13 Sep 2023 06:45:03 -0700
Subject: [PATCH 2/2] Testing.

---
 clang/lib/AST/TypePrinter.cpp | 1 -
 1 file changed, 1 deletion(-)

diff --git a/clang/lib/AST/TypePrinter.cpp b/clang/lib/AST/TypePrinter.cpp
index 676ce166312adf4..e4abf4b2160682a 100644
--- a/clang/lib/AST/TypePrinter.cpp
+++ b/clang/lib/AST/TypePrinter.cpp
@@ -2218,7 +2218,6 @@ printTo(raw_ostream , ArrayRef Args, const 
PrintingPolicy ,
 } else {
   if (!FirstArg)
 OS << Comma;
-  // zahira
   //if (Argument.getKind() == TemplateArgument::Type)
   //  OS << "class ";
 

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libunwind] [libunwind][AIX] Fix up TOC register if unw_getcontext is called from a different module (PR #66549)

2023-09-18 Thread via cfe-commits


@@ -305,9 +305,22 @@ DEFINE_LIBUNWIND_FUNCTION(__unw_getcontext)
   mflr  0
   std   0, PPC64_OFFS_SRR0(3) // store lr as ssr0
   PPC64_STR(1)
+  PPC64_STR(4)  // Save r4 first since it will be used for fixing r2.
+#if defined(_AIX)
+  // The TOC register (r2) was changed by the glue code if unw_getcontext
+  // is called from a different module. Save the original TOC register
+  // in the context if this is the case.
+  mflr  4

stephenpeckham wrote:

Either way is fine with me.

https://github.com/llvm/llvm-project/pull/66549
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libunwind] [libunwind][AIX] Fix up TOC register if unw_getcontext is called from a different module (PR #66549)

2023-09-18 Thread via cfe-commits


@@ -305,9 +305,22 @@ DEFINE_LIBUNWIND_FUNCTION(__unw_getcontext)
   mflr  0
   std   0, PPC64_OFFS_SRR0(3) // store lr as ssr0
   PPC64_STR(1)
+  PPC64_STR(4)  // Save r4 first since it will be used for fixing r2.
+#if defined(_AIX)
+  // The TOC register (r2) was changed by the glue code if unw_getcontext
+  // is called from a different module. Save the original TOC register
+  // in the context if this is the case.
+  mflr  4
+  lwz   4, 0(4) // Get the first instruction at the return address.
+  lis   0, 0xe841   // Is it reloading the TOC register "ld 2,40(1)"?

stephenpeckham wrote:

The legacy compiler uses xoris/cmplwi for both 32-bit and 64-bit.

https://github.com/llvm/llvm-project/pull/66549
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Fix null dereference on return in lambda attribute statement expr (PR #66643)

2023-09-18 Thread Piotr Fusik via cfe-commits

pfusik wrote:

> I'd be inclined to move the test to clang/test/Parser/ because even though 
> the fix is in Sema, it's testing a wrong parse.

It's an ICE in Sema. The test is identical to the bug report, but it doesn't 
mean the issue is limited to syntax errors.

```cpp
int main() {
[]()__attribute__((b(({ return 0; }{};
}
```

g++ accepts the above while Clang crashes. I'll add this as a second test.

https://github.com/llvm/llvm-project/pull/66643
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [InstCombine] Simplify the pattern `a ne/eq (zext (a ne/eq c))` (PR #65852)

2023-09-18 Thread Yingwei Zheng via cfe-commits

https://github.com/dtcxzyw resolved 
https://github.com/llvm/llvm-project/pull/65852
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [InstCombine] Simplify the pattern `a ne/eq (zext (a ne/eq c))` (PR #65852)

2023-09-18 Thread Yingwei Zheng via cfe-commits

https://github.com/dtcxzyw resolved 
https://github.com/llvm/llvm-project/pull/65852
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Introduce paged vector (PR #66430)

2023-09-18 Thread Jakub Kuderski via cfe-commits


@@ -1625,6 +1625,35 @@ SmallVector has grown a few other minor advantages over 
std::vector, causing
and is no longer "private to the implementation". A name like
``SmallVectorHeader`` might be more appropriate.
 
+.. _dss_pagedvector:
+
+llvm/ADT/PagedVector.h
+^^
+
+``PagedVector`` is a random access container that allocates 
(PageSize) elements
+of type Type when the first element of a page is accessed via the 
``operator[]`` or the ``at()``
+method.  This is useful for the case in which the number of elements is known 
in advance and 
+their actual initialization is expensive and sparse so that it's only done 
lazily when the element is 
+accessed. When the number of used pages is small significant memory savings 
can be achieved.
+
+The main advantage is that a PagedVector allows to delay the actual allocation 
of the page until it's needed,
+at the extra cost of one integer per page and one extra indirection when 
accessing elements with their positional
+index. 

kuhar wrote:

Please reflow this section to fit the column limit. Your editor should be able 
to do this automatically (either built-in or via a plugin).

https://github.com/llvm/llvm-project/pull/66430
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [InstCombine] Simplify the pattern `a ne/eq (zext (a ne/eq c))` (PR #65852)

2023-09-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-llvm-transforms


Changes

This patch folds the pattern `a ne/eq (zext (a ne/eq c))` into a boolean 
constant or a compare.
Clang vs GCC: https://godbolt.org/z/4ro817WE8
Alive2: https://alive2.llvm.org/ce/z/6z9NRF
Fixes #65073.


---
Full diff: https://github.com/llvm/llvm-project/pull/65852.diff


2 Files Affected:

- (modified) llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp (+62) 
- (modified) llvm/test/Transforms/InstCombine/icmp-range.ll (+18-58) 


``diff
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp 
b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
index a219dac7acfbe16..d0b62c17ec94358 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
@@ -6380,7 +6380,69 @@ Instruction 
*InstCombinerImpl::foldICmpUsingBoolRange(ICmpInst ) {
   Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
 
+  ICmpInst::Predicate Pred1, Pred2;
   const APInt *C;
+  // icmp eq/ne X, (zext (icmp eq/ne X, C))
+  if (match(, m_c_ICmp(Pred1, m_Value(X),
+ m_ZExt(m_ICmp(Pred2, m_Deferred(X), m_APInt(C) &&
+  ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
+if (C->isZero()) {
+  if (Pred2 == ICmpInst::ICMP_EQ) {
+// icmp eq X, (zext (icmp eq X, 0)) --> false
+// icmp ne X, (zext (icmp eq X, 0)) --> true
+return replaceInstUsesWith(
+I,
+Constant::getIntegerValue(
+I.getType(),
+APInt(1U, static_cast(Pred1 == ICmpInst::ICMP_NE;
+  } else {
+// icmp eq X, (zext (icmp ne X, 0)) --> icmp ult X, 2
+// icmp ne X, (zext (icmp ne X, 0)) --> icmp ugt X, 1
+return ICmpInst::Create(
+Instruction::ICmp,
+Pred1 == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGT
+   : ICmpInst::ICMP_ULT,
+X,
+Constant::getIntegerValue(
+X->getType(), APInt(X->getType()->getScalarSizeInBits(),
+Pred1 == ICmpInst::ICMP_NE ? 1 : 2)));
+  }
+} else if (C->isOne()) {
+  if (Pred2 == ICmpInst::ICMP_NE) {
+// icmp eq X, (zext (icmp ne X, 1)) --> false
+// icmp ne X, (zext (icmp ne X, 1)) --> true
+return replaceInstUsesWith(
+I,
+Constant::getIntegerValue(
+I.getType(),
+APInt(1U, static_cast(Pred1 == ICmpInst::ICMP_NE;
+  } else {
+// icmp eq X, (zext (icmp eq X, 1)) --> icmp ult X, 2
+// icmp ne X, (zext (icmp eq X, 1)) --> icmp ugt X, 1
+return ICmpInst::Create(
+Instruction::ICmp,
+Pred1 == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGT
+   : ICmpInst::ICMP_ULT,
+X,
+Constant::getIntegerValue(
+X->getType(), APInt(X->getType()->getScalarSizeInBits(),
+Pred1 == ICmpInst::ICMP_NE ? 1 : 2)));
+  }
+} else {
+  // C != 0 && C != 1
+  // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
+  // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
+  // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
+  // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
+  return ICmpInst::Create(
+  Instruction::ICmp, Pred1, X,
+  Constant::getIntegerValue(
+  X->getType(),
+  APInt(X->getType()->getScalarSizeInBits(),
+static_cast(Pred2 == ICmpInst::ICMP_NE;
+}
+  }
+
   if (match(I.getOperand(0), m_c_Add(m_ZExt(m_Value(X)), m_SExt(m_Value(Y 
&&
   match(I.getOperand(1), m_APInt(C)) &&
   X->getType()->isIntOrIntVectorTy(1) &&
diff --git a/llvm/test/Transforms/InstCombine/icmp-range.ll 
b/llvm/test/Transforms/InstCombine/icmp-range.ll
index a26e760059b43fe..88d5a723747ad5f 100644
--- a/llvm/test/Transforms/InstCombine/icmp-range.ll
+++ b/llvm/test/Transforms/InstCombine/icmp-range.ll
@@ -1037,10 +1037,7 @@ define i1 @icmp_ne_bool_1(ptr %ptr) {
 ; Tests from PR65073
 define i1 @icmp_ne_zext_eq_zero(i32 %a) {
 ; CHECK-LABEL: @icmp_ne_zext_eq_zero(
-; CHECK-NEXT:[[CMP:%.*]] = icmp eq i32 [[A:%.*]], 0
-; CHECK-NEXT:[[CONV:%.*]] = zext i1 [[CMP]] to i32
-; CHECK-NEXT:[[CMP1:%.*]] = icmp ne i32 [[CONV]], [[A]]
-; CHECK-NEXT:ret i1 [[CMP1]]
+; CHECK-NEXT:ret i1 true
 ;
   %cmp = icmp eq i32 %a, 0
   %conv = zext i1 %cmp to i32
@@ -1050,9 +1047,7 @@ define i1 @icmp_ne_zext_eq_zero(i32 %a) {
 
 define i1 @icmp_ne_zext_ne_zero(i32 %a) {
 ; CHECK-LABEL: @icmp_ne_zext_ne_zero(
-; CHECK-NEXT:[[CMP:%.*]] = icmp ne i32 [[A:%.*]], 0
-; CHECK-NEXT:[[CONV:%.*]] = zext i1 [[CMP]] to i32
-; CHECK-NEXT:[[CMP1:%.*]] = icmp ne i32 [[CONV]], [[A]]
+; CHECK-NEXT:[[CMP1:%.*]] = icmp 

[clang-tools-extra] [InstCombine] Simplify the pattern `a ne/eq (zext (a ne/eq c))` (PR #65852)

2023-09-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-llvm-transforms


Changes

This patch folds the pattern `a ne/eq (zext (a ne/eq c))` into a boolean 
constant or a compare.
Clang vs GCC: https://godbolt.org/z/4ro817WE8
Alive2: https://alive2.llvm.org/ce/z/6z9NRF
Fixes #65073.


---
Full diff: https://github.com/llvm/llvm-project/pull/65852.diff


2 Files Affected:

- (modified) llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp (+62) 
- (modified) llvm/test/Transforms/InstCombine/icmp-range.ll (+18-58) 


``diff
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp 
b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
index a219dac7acfbe16..d0b62c17ec94358 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
@@ -6380,7 +6380,69 @@ Instruction 
*InstCombinerImpl::foldICmpUsingBoolRange(ICmpInst ) {
   Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
 
+  ICmpInst::Predicate Pred1, Pred2;
   const APInt *C;
+  // icmp eq/ne X, (zext (icmp eq/ne X, C))
+  if (match(, m_c_ICmp(Pred1, m_Value(X),
+ m_ZExt(m_ICmp(Pred2, m_Deferred(X), m_APInt(C) &&
+  ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
+if (C->isZero()) {
+  if (Pred2 == ICmpInst::ICMP_EQ) {
+// icmp eq X, (zext (icmp eq X, 0)) --> false
+// icmp ne X, (zext (icmp eq X, 0)) --> true
+return replaceInstUsesWith(
+I,
+Constant::getIntegerValue(
+I.getType(),
+APInt(1U, static_cast(Pred1 == ICmpInst::ICMP_NE;
+  } else {
+// icmp eq X, (zext (icmp ne X, 0)) --> icmp ult X, 2
+// icmp ne X, (zext (icmp ne X, 0)) --> icmp ugt X, 1
+return ICmpInst::Create(
+Instruction::ICmp,
+Pred1 == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGT
+   : ICmpInst::ICMP_ULT,
+X,
+Constant::getIntegerValue(
+X->getType(), APInt(X->getType()->getScalarSizeInBits(),
+Pred1 == ICmpInst::ICMP_NE ? 1 : 2)));
+  }
+} else if (C->isOne()) {
+  if (Pred2 == ICmpInst::ICMP_NE) {
+// icmp eq X, (zext (icmp ne X, 1)) --> false
+// icmp ne X, (zext (icmp ne X, 1)) --> true
+return replaceInstUsesWith(
+I,
+Constant::getIntegerValue(
+I.getType(),
+APInt(1U, static_cast(Pred1 == ICmpInst::ICMP_NE;
+  } else {
+// icmp eq X, (zext (icmp eq X, 1)) --> icmp ult X, 2
+// icmp ne X, (zext (icmp eq X, 1)) --> icmp ugt X, 1
+return ICmpInst::Create(
+Instruction::ICmp,
+Pred1 == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGT
+   : ICmpInst::ICMP_ULT,
+X,
+Constant::getIntegerValue(
+X->getType(), APInt(X->getType()->getScalarSizeInBits(),
+Pred1 == ICmpInst::ICMP_NE ? 1 : 2)));
+  }
+} else {
+  // C != 0 && C != 1
+  // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
+  // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
+  // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
+  // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
+  return ICmpInst::Create(
+  Instruction::ICmp, Pred1, X,
+  Constant::getIntegerValue(
+  X->getType(),
+  APInt(X->getType()->getScalarSizeInBits(),
+static_cast(Pred2 == ICmpInst::ICMP_NE;
+}
+  }
+
   if (match(I.getOperand(0), m_c_Add(m_ZExt(m_Value(X)), m_SExt(m_Value(Y 
&&
   match(I.getOperand(1), m_APInt(C)) &&
   X->getType()->isIntOrIntVectorTy(1) &&
diff --git a/llvm/test/Transforms/InstCombine/icmp-range.ll 
b/llvm/test/Transforms/InstCombine/icmp-range.ll
index a26e760059b43fe..88d5a723747ad5f 100644
--- a/llvm/test/Transforms/InstCombine/icmp-range.ll
+++ b/llvm/test/Transforms/InstCombine/icmp-range.ll
@@ -1037,10 +1037,7 @@ define i1 @icmp_ne_bool_1(ptr %ptr) {
 ; Tests from PR65073
 define i1 @icmp_ne_zext_eq_zero(i32 %a) {
 ; CHECK-LABEL: @icmp_ne_zext_eq_zero(
-; CHECK-NEXT:[[CMP:%.*]] = icmp eq i32 [[A:%.*]], 0
-; CHECK-NEXT:[[CONV:%.*]] = zext i1 [[CMP]] to i32
-; CHECK-NEXT:[[CMP1:%.*]] = icmp ne i32 [[CONV]], [[A]]
-; CHECK-NEXT:ret i1 [[CMP1]]
+; CHECK-NEXT:ret i1 true
 ;
   %cmp = icmp eq i32 %a, 0
   %conv = zext i1 %cmp to i32
@@ -1050,9 +1047,7 @@ define i1 @icmp_ne_zext_eq_zero(i32 %a) {
 
 define i1 @icmp_ne_zext_ne_zero(i32 %a) {
 ; CHECK-LABEL: @icmp_ne_zext_ne_zero(
-; CHECK-NEXT:[[CMP:%.*]] = icmp ne i32 [[A:%.*]], 0
-; CHECK-NEXT:[[CONV:%.*]] = zext i1 [[CMP]] to i32
-; CHECK-NEXT:[[CMP1:%.*]] = icmp ne i32 [[CONV]], [[A]]
+; CHECK-NEXT:[[CMP1:%.*]] = icmp 

[clang] [InstCombine] Simplify the pattern `a ne/eq (zext (a ne/eq c))` (PR #65852)

2023-09-18 Thread Yingwei Zheng via cfe-commits

https://github.com/dtcxzyw updated 
https://github.com/llvm/llvm-project/pull/65852

>From d9d8bcbb98e8f5aecb9733329389d61a489bd731 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng 
Date: Sat, 9 Sep 2023 23:07:29 +0800
Subject: [PATCH] [InstCombine] Simplify the pattern `a ne/eq (zext (a ne/eq
 c))`

---
 .../InstCombine/InstCombineCompares.cpp   |  62 ++
 .../test/Transforms/InstCombine/icmp-range.ll | 181 ++
 2 files changed, 243 insertions(+)

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp 
b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
index 9fdc46fec631679..837b8e6d2619989 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
@@ -6309,7 +6309,69 @@ Instruction 
*InstCombinerImpl::foldICmpUsingBoolRange(ICmpInst ) {
   Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
 
+  ICmpInst::Predicate Pred1, Pred2;
   const APInt *C;
+  // icmp eq/ne X, (zext (icmp eq/ne X, C))
+  if (match(, m_c_ICmp(Pred1, m_Value(X),
+ m_ZExt(m_ICmp(Pred2, m_Deferred(X), m_APInt(C) &&
+  ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
+if (C->isZero()) {
+  if (Pred2 == ICmpInst::ICMP_EQ) {
+// icmp eq X, (zext (icmp eq X, 0)) --> false
+// icmp ne X, (zext (icmp eq X, 0)) --> true
+return replaceInstUsesWith(
+I,
+Constant::getIntegerValue(
+I.getType(),
+APInt(1U, static_cast(Pred1 == ICmpInst::ICMP_NE;
+  } else {
+// icmp eq X, (zext (icmp ne X, 0)) --> icmp ult X, 2
+// icmp ne X, (zext (icmp ne X, 0)) --> icmp ugt X, 1
+return ICmpInst::Create(
+Instruction::ICmp,
+Pred1 == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGT
+   : ICmpInst::ICMP_ULT,
+X,
+Constant::getIntegerValue(
+X->getType(), APInt(X->getType()->getScalarSizeInBits(),
+Pred1 == ICmpInst::ICMP_NE ? 1 : 2)));
+  }
+} else if (C->isOne()) {
+  if (Pred2 == ICmpInst::ICMP_NE) {
+// icmp eq X, (zext (icmp ne X, 1)) --> false
+// icmp ne X, (zext (icmp ne X, 1)) --> true
+return replaceInstUsesWith(
+I,
+Constant::getIntegerValue(
+I.getType(),
+APInt(1U, static_cast(Pred1 == ICmpInst::ICMP_NE;
+  } else {
+// icmp eq X, (zext (icmp eq X, 1)) --> icmp ult X, 2
+// icmp ne X, (zext (icmp eq X, 1)) --> icmp ugt X, 1
+return ICmpInst::Create(
+Instruction::ICmp,
+Pred1 == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGT
+   : ICmpInst::ICMP_ULT,
+X,
+Constant::getIntegerValue(
+X->getType(), APInt(X->getType()->getScalarSizeInBits(),
+Pred1 == ICmpInst::ICMP_NE ? 1 : 2)));
+  }
+} else {
+  // C != 0 && C != 1
+  // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
+  // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
+  // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
+  // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
+  return ICmpInst::Create(
+  Instruction::ICmp, Pred1, X,
+  Constant::getIntegerValue(
+  X->getType(),
+  APInt(X->getType()->getScalarSizeInBits(),
+static_cast(Pred2 == ICmpInst::ICMP_NE;
+}
+  }
+
   if (match(I.getOperand(0), m_c_Add(m_ZExt(m_Value(X)), m_SExt(m_Value(Y 
&&
   match(I.getOperand(1), m_APInt(C)) &&
   X->getType()->isIntOrIntVectorTy(1) &&
diff --git a/llvm/test/Transforms/InstCombine/icmp-range.ll 
b/llvm/test/Transforms/InstCombine/icmp-range.ll
index 4281e09cb0309c8..15424fce33fdeea 100644
--- a/llvm/test/Transforms/InstCombine/icmp-range.ll
+++ b/llvm/test/Transforms/InstCombine/icmp-range.ll
@@ -1034,6 +1034,187 @@ define i1 @icmp_ne_bool_1(ptr %ptr) {
   ret i1 %cmp
 }
 
+define i1 @icmp_ne_zext_eq_zero(i32 %a) {
+; CHECK-LABEL: @icmp_ne_zext_eq_zero(
+; CHECK-NEXT:ret i1 true
+;
+  %cmp = icmp eq i32 %a, 0
+  %conv = zext i1 %cmp to i32
+  %cmp1 = icmp ne i32 %conv, %a
+  ret i1 %cmp1
+}
+
+define i1 @icmp_ne_zext_ne_zero(i32 %a) {
+; CHECK-LABEL: @icmp_ne_zext_ne_zero(
+; CHECK-NEXT:[[CMP1:%.*]] = icmp ugt i32 [[A:%.*]], 1
+; CHECK-NEXT:ret i1 [[CMP1]]
+;
+  %cmp = icmp ne i32 %a, 0
+  %conv = zext i1 %cmp to i32
+  %cmp1 = icmp ne i32 %conv, %a
+  ret i1 %cmp1
+}
+
+define i1 @icmp_eq_zext_eq_zero(i32 %a) {
+; CHECK-LABEL: @icmp_eq_zext_eq_zero(
+; CHECK-NEXT:ret i1 false
+;
+  %cmp = icmp eq i32 %a, 0
+  %conv = zext i1 %cmp to i32
+  %cmp1 = icmp eq i32 %conv, %a
+  ret i1 %cmp1
+}
+
+define i1 @icmp_eq_zext_ne_zero(i32 %a) {
+; 

[clang-tools-extra] [InstCombine] Simplify the pattern `a ne/eq (zext (a ne/eq c))` (PR #65852)

2023-09-18 Thread Yingwei Zheng via cfe-commits

https://github.com/dtcxzyw updated 
https://github.com/llvm/llvm-project/pull/65852

>From d9d8bcbb98e8f5aecb9733329389d61a489bd731 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng 
Date: Sat, 9 Sep 2023 23:07:29 +0800
Subject: [PATCH] [InstCombine] Simplify the pattern `a ne/eq (zext (a ne/eq
 c))`

---
 .../InstCombine/InstCombineCompares.cpp   |  62 ++
 .../test/Transforms/InstCombine/icmp-range.ll | 181 ++
 2 files changed, 243 insertions(+)

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp 
b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
index 9fdc46fec631679..837b8e6d2619989 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
@@ -6309,7 +6309,69 @@ Instruction 
*InstCombinerImpl::foldICmpUsingBoolRange(ICmpInst ) {
   Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
 
+  ICmpInst::Predicate Pred1, Pred2;
   const APInt *C;
+  // icmp eq/ne X, (zext (icmp eq/ne X, C))
+  if (match(, m_c_ICmp(Pred1, m_Value(X),
+ m_ZExt(m_ICmp(Pred2, m_Deferred(X), m_APInt(C) &&
+  ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
+if (C->isZero()) {
+  if (Pred2 == ICmpInst::ICMP_EQ) {
+// icmp eq X, (zext (icmp eq X, 0)) --> false
+// icmp ne X, (zext (icmp eq X, 0)) --> true
+return replaceInstUsesWith(
+I,
+Constant::getIntegerValue(
+I.getType(),
+APInt(1U, static_cast(Pred1 == ICmpInst::ICMP_NE;
+  } else {
+// icmp eq X, (zext (icmp ne X, 0)) --> icmp ult X, 2
+// icmp ne X, (zext (icmp ne X, 0)) --> icmp ugt X, 1
+return ICmpInst::Create(
+Instruction::ICmp,
+Pred1 == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGT
+   : ICmpInst::ICMP_ULT,
+X,
+Constant::getIntegerValue(
+X->getType(), APInt(X->getType()->getScalarSizeInBits(),
+Pred1 == ICmpInst::ICMP_NE ? 1 : 2)));
+  }
+} else if (C->isOne()) {
+  if (Pred2 == ICmpInst::ICMP_NE) {
+// icmp eq X, (zext (icmp ne X, 1)) --> false
+// icmp ne X, (zext (icmp ne X, 1)) --> true
+return replaceInstUsesWith(
+I,
+Constant::getIntegerValue(
+I.getType(),
+APInt(1U, static_cast(Pred1 == ICmpInst::ICMP_NE;
+  } else {
+// icmp eq X, (zext (icmp eq X, 1)) --> icmp ult X, 2
+// icmp ne X, (zext (icmp eq X, 1)) --> icmp ugt X, 1
+return ICmpInst::Create(
+Instruction::ICmp,
+Pred1 == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGT
+   : ICmpInst::ICMP_ULT,
+X,
+Constant::getIntegerValue(
+X->getType(), APInt(X->getType()->getScalarSizeInBits(),
+Pred1 == ICmpInst::ICMP_NE ? 1 : 2)));
+  }
+} else {
+  // C != 0 && C != 1
+  // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
+  // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
+  // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
+  // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
+  return ICmpInst::Create(
+  Instruction::ICmp, Pred1, X,
+  Constant::getIntegerValue(
+  X->getType(),
+  APInt(X->getType()->getScalarSizeInBits(),
+static_cast(Pred2 == ICmpInst::ICMP_NE;
+}
+  }
+
   if (match(I.getOperand(0), m_c_Add(m_ZExt(m_Value(X)), m_SExt(m_Value(Y 
&&
   match(I.getOperand(1), m_APInt(C)) &&
   X->getType()->isIntOrIntVectorTy(1) &&
diff --git a/llvm/test/Transforms/InstCombine/icmp-range.ll 
b/llvm/test/Transforms/InstCombine/icmp-range.ll
index 4281e09cb0309c8..15424fce33fdeea 100644
--- a/llvm/test/Transforms/InstCombine/icmp-range.ll
+++ b/llvm/test/Transforms/InstCombine/icmp-range.ll
@@ -1034,6 +1034,187 @@ define i1 @icmp_ne_bool_1(ptr %ptr) {
   ret i1 %cmp
 }
 
+define i1 @icmp_ne_zext_eq_zero(i32 %a) {
+; CHECK-LABEL: @icmp_ne_zext_eq_zero(
+; CHECK-NEXT:ret i1 true
+;
+  %cmp = icmp eq i32 %a, 0
+  %conv = zext i1 %cmp to i32
+  %cmp1 = icmp ne i32 %conv, %a
+  ret i1 %cmp1
+}
+
+define i1 @icmp_ne_zext_ne_zero(i32 %a) {
+; CHECK-LABEL: @icmp_ne_zext_ne_zero(
+; CHECK-NEXT:[[CMP1:%.*]] = icmp ugt i32 [[A:%.*]], 1
+; CHECK-NEXT:ret i1 [[CMP1]]
+;
+  %cmp = icmp ne i32 %a, 0
+  %conv = zext i1 %cmp to i32
+  %cmp1 = icmp ne i32 %conv, %a
+  ret i1 %cmp1
+}
+
+define i1 @icmp_eq_zext_eq_zero(i32 %a) {
+; CHECK-LABEL: @icmp_eq_zext_eq_zero(
+; CHECK-NEXT:ret i1 false
+;
+  %cmp = icmp eq i32 %a, 0
+  %conv = zext i1 %cmp to i32
+  %cmp1 = icmp eq i32 %conv, %a
+  ret i1 %cmp1
+}
+
+define i1 @icmp_eq_zext_ne_zero(i32 %a) {
+; 

[clang-tools-extra] [clang] remove ClassScopeFunctionSpecializationDecl (PR #66636)

2023-09-18 Thread Erich Keane via cfe-commits


@@ -2613,70 +2579,6 @@ class TypeAliasTemplateDecl : public 
RedeclarableTemplateDecl {
   static bool classofKind(Kind K) { return K == TypeAliasTemplate; }
 };
 
-/// Declaration of a function specialization at template class scope.
-///
-/// For example:
-/// \code
-/// template 
-/// class A {
-///template  void foo(U a) { }
-///template<> void foo(int a) { }
-/// }
-/// \endcode
-///
-/// "template<> foo(int a)" will be saved in Specialization as a normal
-/// CXXMethodDecl. Then during an instantiation of class A, it will be
-/// transformed into an actual function specialization.
-///
-/// FIXME: This is redundant; we could store the same information directly on
-/// the CXXMethodDecl as a DependentFunctionTemplateSpecializationInfo.

erichkeane wrote:

I see this fixme here as perhaps some of the 'why'?  

https://github.com/llvm/llvm-project/pull/66636
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang] remove ClassScopeFunctionSpecializationDecl (PR #66636)

2023-09-18 Thread Erich Keane via cfe-commits

https://github.com/erichkeane commented:

I guess my first question is 'why'?  My second is 'if this is unnecessary, why 
was it here in the first place?`.  I'd like some level of historical analysis 
here/perhaps the knowledge of @zygoloid.

https://github.com/llvm/llvm-project/pull/66636
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang] remove ClassScopeFunctionSpecializationDecl (PR #66636)

2023-09-18 Thread Erich Keane via cfe-commits

https://github.com/erichkeane edited 
https://github.com/llvm/llvm-project/pull/66636
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Introduce paged vector (PR #66430)

2023-09-18 Thread Jakub Kuderski via cfe-commits


@@ -0,0 +1,132 @@
+//===- llvm/ADT/PagedVector.h - 'Lazyly allocated' vectors *- C++
+//-*-===//
+//
+// 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
+//
+//===--===//
+//
+// This file defines the PagedVector class.
+//
+//===--===//
+#ifndef LLVM_ADT_PAGEDVECTOR_H
+#define LLVM_ADT_PAGEDVECTOR_H
+
+#include 
+#include 
+
+namespace llvm {
+// A vector that allocates memory in pages.
+// Order is kept, but memory is allocated only when one element of the page is
+// accessed. This introduces a level of indirection, but it is useful when you
+// have a sparsely initialised vector where the full size is allocated upfront
+// with the default constructor and elements are initialised later, on first
+// access.
+//
+// Notice that this does not have iterators, because if you
+// have iterators it probably means you are going to touch
+// all the memory in any case, so better use a std::vector in
+// the first place.
+template 
+class PagedVector {
+  static_assert(PAGE_SIZE > 0, "PAGE_SIZE must be greater than 0. Most likely 
you want it to be greater than 16.");

kuhar wrote:

Please run this through clang-format

https://github.com/llvm/llvm-project/pull/66430
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Introduce paged vector (PR #66430)

2023-09-18 Thread Jakub Kuderski via cfe-commits


@@ -0,0 +1,133 @@
+//===- llvm/ADT/PagedVector.h - 'Lazyly allocated' vectors *- C++
+//-*-===//
+//
+// 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
+//
+//===--===//
+//
+// This file defines the PagedVector class.
+//
+//===--===//
+#ifndef LLVM_ADT_PAGEDVECTOR_H
+#define LLVM_ADT_PAGEDVECTOR_H
+
+#include 
+#include 
+
+namespace llvm {
+// A vector that allocates memory in pages.
+// Order is kept, but memory is allocated only when one element of the page is
+// accessed. This introduces a level of indirection, but it is useful when you
+// have a sparsely initialised vector where the full size is allocated upfront
+// with the default constructor and elements are initialised later, on first
+// access.
+//
+// Notice that this does not have iterators, because if you
+// have iterators it probably means you are going to touch
+// all the memory in any case, so better use a std::vector in
+// the first place.
+template  class PagedVector {
+  // The actual number of element in the vector which can be accessed.
+  std::size_t Size = 0;
+  // The position of the initial element of the page in the Data vector.
+  // Pages are allocated contiguously in the Data vector.
+  mutable std::vector Lookup;
+  // Actual page data. All the page elements are added to this vector on the
+  // first access of any of the elements of the page. Elements default
+  // constructed and elements of the page are stored contiguously. The oder of
+  // the elements however depends on the order of access of the pages.
+  mutable std::vector Data;
+
+public:
+  // Lookup an element at position Index.
+  T [](std::size_t Index) const { return at(Index); }
+
+  // Lookup an element at position i.
+  // If the associated page is not filled, it will be filled with default
+  // constructed elements. If the associated page is filled, return the 
element.
+  T (std::size_t Index) const {
+assert(Index < Size);
+assert(Index / PAGE_SIZE < Lookup.size());
+auto  = Lookup[Index / PAGE_SIZE];
+// If the range is not filled, fill it
+if (PageId == -1) {
+  int OldSize = Data.size();
+  PageId = OldSize / PAGE_SIZE;
+  // Allocate the memory
+  Data.resize(OldSize + PAGE_SIZE);
+  // Fill the whole capacity with empty elements
+  for (int I = 0; I < PAGE_SIZE; ++I) {
+Data[I + OldSize] = T();
+  }
+}
+// Calculate the actual position in the Data vector
+// by taking the start of the page and adding the offset
+// in the page.
+std::size_t StoreIndex = Index % PAGE_SIZE + PAGE_SIZE * PageId;
+// Return the element
+assert(StoreIndex < Data.size());
+return Data[StoreIndex];
+  }
+
+  // Return the capacity of the vector. I.e. the maximum size it can be 
expanded
+  // to with the expand method without allocating more pages.
+  std::size_t capacity() const { return Lookup.size() * PAGE_SIZE; }
+
+  // Return the size of the vector. I.e. the maximum index that can be
+  // accessed, i.e. the maximum value which was used as argument of the
+  // expand method.
+  std::size_t size() const { return Size; }
+
+  // Expands the vector to the given NewSize number of elements.
+  // If the vector was smaller, allocates new pages as needed.
+  // It should be called only with NewSize >= Size.
+  void expand(std::size_t NewSize) {
+// You cannot shrink the vector, otherwise
+// one would have to invalidate contents which is expensive and
+// while giving the false hope that the resize is cheap.
+if (NewSize <= Size) {
+  return;
+}
+// If the capacity is enough, just update the size and continue
+// with the currently allocated pages.
+if (NewSize <= capacity()) {
+  Size = NewSize;
+  return;
+}
+// The number of pages to allocate. The Remainder is calculated
+// for the case in which the NewSize is not a multiple of PAGE_SIZE.
+// In that case we need one more page.
+auto Pages = NewSize / PAGE_SIZE;
+auto Remainder = NewSize % PAGE_SIZE;
+if (Remainder) {
+  Pages += 1;
+}
+assert(Pages > Lookup.size());
+// We use -1 to indicate that a page has not been allocated yet.
+// This cannot be 0, because 0 is a valid page id.
+// We use -1 instead of a separate bool to avoid wasting space.
+Lookup.resize(Pages, -1);
+Size = NewSize;
+  }
+
+  // Return true if the vector is empty
+  bool empty() const { return Size == 0; }
+
+  /// Clear the vector, i.e. clear the allocated pages, the whole page
+  /// lookup index and reset the size.
+  void clear() {
+Size = 0;
+Lookup.clear();
+Data.clear();
+  }
+
+  /// Return the materialised vector. 

[clang] [clang] remove ClassScopeFunctionSpecializationDecl (PR #66636)

2023-09-18 Thread via cfe-commits

cor3ntin wrote:

@erichkeane Opinions?

https://github.com/llvm/llvm-project/pull/66636
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Sema] add cast from IncompleteArrayType to ConstantArrayType in TryReferenceListInitialization (PR #65918)

2023-09-18 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 edited 
https://github.com/llvm/llvm-project/pull/65918
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Fix null dereference on return in lambda attribute statement expr (PR #66643)

2023-09-18 Thread via cfe-commits

cor3ntin wrote:

@Fznamznon I think so too, although I'd be inclined to move the test to 
`clang/test/Parser/` because even though the fix is in Sema, it's testing a 
wrong parse.

The commit message also could do with a longer description.

Otherwise LGTM

https://github.com/llvm/llvm-project/pull/66643
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D148381: [Clang] Implement the 'counted_by' attribute

2023-09-18 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

I've got no further comments/concerns.




Comment at: clang/include/clang/AST/Decl.h:4272-4275
+FieldDecl *FD = nullptr;
+for (FieldDecl *Field : fields())
+  FD = Field;
+return FD;

aaron.ballman wrote:
> void wrote:
> > aaron.ballman wrote:
> > > Could this be implemented as: `return !field_empty() ? 
> > > *std::prev(field_end()) : nullptr;` ? Then maybe someday we'll get better 
> > > iterator support that isn't forward-only and this code will automagically 
> > > get faster.
> > Using `std::prev` on a forward iterator won't work:
> > 
> > https://stackoverflow.com/questions/23868378/why-stdprev-does-not-fire-an-error-with-an-iterator-of-stdunordered-set
> > 
> > `std::prev` itself is defined only for bidirectional iterators:
> > 
> > ```
> >  template
> > _GLIBCXX_NODISCARD
> > inline _GLIBCXX17_CONSTEXPR _BidirectionalIterator
> > prev(_BidirectionalIterator __x, typename
> >  iterator_traits<_BidirectionalIterator>::difference_type __n = 1)
> > {
> > ...
> > ```
> > 
> Drat! Oh well, it was a lovely thought.
something like `!field_empty() ? *std::advance(field_begin(), 
std::distance(field_begin(), field_end() - 1) : nullptr`

would do what Aaron would like, though perhaps with an extra run through the 
fields list until then.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:6371
+def err_flexible_array_counted_by_attr_refers_to_self : Error<
+  "counted_by field %0 cannot refer to the flexible array">;
+def err_flexible_array_counted_by_attr_field_not_integral : Error<

void wrote:
> erichkeane wrote:
> > aaron.ballman wrote:
> > > We try to wrap syntax elements in single quotes in our diagnostics so 
> > > it's more visually distinct
> > This one isn't clear... something more specifically about 'cannot point to 
> > itself' is perhaps more useful/explainatory.
> > 
> > Also, the beginning of all of these is really quite awkward as well, 
> > perhaps something like:
> > 
> > `field %0 referenced by 'counted_by' attribute ...` ?
> I reworded them a bit.
> 
> As for referring to itself, it could be a bit confusing to say that it 
> 'cannot point to itself' because the 'itself' in that is the attribute, not 
> the flexible array member. I think it's more-or-less clear what the error's 
> referring to. The user can use this attribute only with a flexible array 
> member. So they should know what what's meant by the message.
I think the reword helps, I am less confident that referring to the 'flexible 
array member' is clear. One of the things I've noticed in the past is users 
'trying' attributes without looking them up to see what they do.  Frankly, I 
think that should be a supported strategy, and one that we manage by making 
clear diagnostics.

I'm up for suggestions/hopeful someone else will come up with something better, 
but I can hold my nose at this if we don't have anything better (and in fact, 
my attempts to put a strawman up were at least as bad).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D148381/new/

https://reviews.llvm.org/D148381

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Sema] add cast from IncompleteArrayType to ConstantArrayType in TryReferenceListInitialization (PR #65918)

2023-09-18 Thread Congcong Cai via cfe-commits


@@ -4532,6 +4532,15 @@ static void TryReferenceListInitialization(Sema ,
   if (T1Quals.hasAddressSpace())
 Sequence.AddQualificationConversionStep(
 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
+  else if (S.getLangOpts().CPlusPlus20 &&
+   isa(T1->getUnqualifiedDesugaredType()) &&
+   DestType->isRValueReferenceType()) {
+// [dcl.init.list] p3.10
+// unless T is “reference to array of unknown bound of U”, in which 
case
+// the type of the prvalue is the type of x in the declaration U x[] H,
+// where H is the initializer list.
+Sequence.AddQualificationConversionStep(cv1T1, VK_XValue);

HerrCai0907 wrote:

Yes, int[1] to int[] in above example

https://github.com/llvm/llvm-project/pull/65918
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] clang/OpenCL: set sqrt fp accuracy on call to Z4sqrt (PR #66651)

2023-09-18 Thread Romaric Jodin via cfe-commits

rjodinchr wrote:

@alan-baker @arsenm @AnastasiaStulova 
Could you review this PR please?
Thank you

https://github.com/llvm/llvm-project/pull/66651
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] clang/OpenCL: set sqrt fp accuracy on call to Z4sqrt (PR #66651)

2023-09-18 Thread Romaric Jodin via cfe-commits

https://github.com/rjodinchr created 
https://github.com/llvm/llvm-project/pull/66651

This is reverting the previous implementation to avoid adding inline function 
in opencl headers.
This was breaking clspv flow google/clspv#1231, while 
https://reviews.llvm.org/D156743 mentioned that just decoring the call node 
with `!pfmath` was enough.
This PR is implementing this idea.
The test has been updated with this implementation.


>From b6df142239256e979a70896f324f9ed3547c640c Mon Sep 17 00:00:00 2001
From: Romaric Jodin 
Date: Mon, 18 Sep 2023 09:34:56 +0200
Subject: [PATCH 1/2] Revert "clang/OpenCL: Add inline implementations of sqrt
 in builtin header"

This reverts commit 15e0fe0b6122e32657b98daf74a1fce028d2e5bf.
---
 clang/lib/Headers/opencl-c-base.h   |  58 ---
 clang/lib/Headers/opencl-c.h|  26 +++
 clang/lib/Sema/OpenCLBuiltins.td|   5 +-
 clang/test/CodeGenOpenCL/sqrt-fpmath.cl | 201 
 4 files changed, 27 insertions(+), 263 deletions(-)
 delete mode 100644 clang/test/CodeGenOpenCL/sqrt-fpmath.cl

diff --git a/clang/lib/Headers/opencl-c-base.h 
b/clang/lib/Headers/opencl-c-base.h
index d56e5ceae652ad5..2494f6213fc5695 100644
--- a/clang/lib/Headers/opencl-c-base.h
+++ b/clang/lib/Headers/opencl-c-base.h
@@ -819,64 +819,6 @@ int printf(__constant const char* st, ...) 
__attribute__((format(printf, 1, 2)))
 
 #endif // cl_intel_device_side_avc_motion_estimation
 
-/**
- * Compute square root.
- *
- * Provide inline implementations using the builtin so that we get appropriate
- * !fpmath based on -cl-fp32-correctly-rounded-divide-sqrt, attached to
- * llvm.sqrt. The implementation should still provide an external definition.
- */
-#define __ovld __attribute__((overloadable))
-#define __cnfn __attribute__((const))
-
-inline float __ovld __cnfn sqrt(float __x) {
-  return __builtin_elementwise_sqrt(__x);
-}
-
-inline float2 __ovld __cnfn sqrt(float2 __x) {
-  return __builtin_elementwise_sqrt(__x);
-}
-
-inline float3 __ovld __cnfn sqrt(float3 __x) {
-  return __builtin_elementwise_sqrt(__x);
-}
-
-inline float4 __ovld __cnfn sqrt(float4 __x) {
-  return __builtin_elementwise_sqrt(__x);
-}
-
-inline float8 __ovld __cnfn sqrt(float8 __x) {
-  return __builtin_elementwise_sqrt(__x);
-}
-
-inline float16 __ovld __cnfn sqrt(float16 __x) {
-  return __builtin_elementwise_sqrt(__x);
-}
-
-// We only really want to define the float variants here. However
-// -fdeclare-opencl-builtins will not work if some overloads are already
- // provided in the base header, so provide all overloads here.
-
-#ifdef cl_khr_fp64
-double __ovld __cnfn sqrt(double);
-double2 __ovld __cnfn sqrt(double2);
-double3 __ovld __cnfn sqrt(double3);
-double4 __ovld __cnfn sqrt(double4);
-double8 __ovld __cnfn sqrt(double8);
-double16 __ovld __cnfn sqrt(double16);
-#endif //cl_khr_fp64
-#ifdef cl_khr_fp16
-half __ovld __cnfn sqrt(half);
-half2 __ovld __cnfn sqrt(half2);
-half3 __ovld __cnfn sqrt(half3);
-half4 __ovld __cnfn sqrt(half4);
-half8 __ovld __cnfn sqrt(half8);
-half16 __ovld __cnfn sqrt(half16);
-#endif //cl_khr_fp16
-
-#undef __cnfn
-#undef __ovld
-
 // Disable any extensions we may have enabled previously.
 #pragma OPENCL EXTENSION all : disable
 
diff --git a/clang/lib/Headers/opencl-c.h b/clang/lib/Headers/opencl-c.h
index 1efbbf8f8ee6a01..288bb18bc654ebc 100644
--- a/clang/lib/Headers/opencl-c.h
+++ b/clang/lib/Headers/opencl-c.h
@@ -8496,6 +8496,32 @@ half8 __ovld __cnfn sinpi(half8);
 half16 __ovld __cnfn sinpi(half16);
 #endif //cl_khr_fp16
 
+/**
+ * Compute square root.
+ */
+float __ovld __cnfn sqrt(float);
+float2 __ovld __cnfn sqrt(float2);
+float3 __ovld __cnfn sqrt(float3);
+float4 __ovld __cnfn sqrt(float4);
+float8 __ovld __cnfn sqrt(float8);
+float16 __ovld __cnfn sqrt(float16);
+#ifdef cl_khr_fp64
+double __ovld __cnfn sqrt(double);
+double2 __ovld __cnfn sqrt(double2);
+double3 __ovld __cnfn sqrt(double3);
+double4 __ovld __cnfn sqrt(double4);
+double8 __ovld __cnfn sqrt(double8);
+double16 __ovld __cnfn sqrt(double16);
+#endif //cl_khr_fp64
+#ifdef cl_khr_fp16
+half __ovld __cnfn sqrt(half);
+half2 __ovld __cnfn sqrt(half2);
+half3 __ovld __cnfn sqrt(half3);
+half4 __ovld __cnfn sqrt(half4);
+half8 __ovld __cnfn sqrt(half8);
+half16 __ovld __cnfn sqrt(half16);
+#endif //cl_khr_fp16
+
 /**
  * Compute tangent.
  */
diff --git a/clang/lib/Sema/OpenCLBuiltins.td b/clang/lib/Sema/OpenCLBuiltins.td
index 9db450281912d2f..0cceba090bd8f26 100644
--- a/clang/lib/Sema/OpenCLBuiltins.td
+++ b/clang/lib/Sema/OpenCLBuiltins.td
@@ -563,15 +563,12 @@ foreach name = ["acos", "acosh", "acospi",
 "log", "log2", "log10", "log1p", "logb",
 "rint", "round", "rsqrt",
 "sin", "sinh", "sinpi",
+"sqrt",
 "tan", "tanh", "tanpi",
 "tgamma", "trunc",
 "lgamma"] in {
 def : Builtin;
 }
-
-// sqrt is handled in opencl-c-base.h to handle
-// 

[clang] [LLD][AARCH64] lld incorrectly handles .eh_frame when it has a non-zero offset within its output section. (PR #65966)

2023-09-18 Thread via cfe-commits

https://github.com/simpal01 updated 
https://github.com/llvm/llvm-project/pull/65966

>From eb4d99345cbe9aba6b909ccbc7ce932dcaef3f7d Mon Sep 17 00:00:00 2001
From: Simi Pallipurath 
Date: Mon, 11 Sep 2023 14:42:27 +0100
Subject: [PATCH] [LLD][AARCH64] lld incorrectly handles .eh_frame when it has
 a non-zero offset within its output section.

When the .eh_frame section is placed at a non-zero
offset within its output section, the relocation
value within .eh_frame are computed incorrectly.

We had similar issue in AArch32 and it has been
fixed already in https://reviews.llvm.org/D148033.

While applying the relocation using S+A-P, the value
of P (the location of the relocation) is getting wrong.
P is:
  P = SecAddr + rel.offset, But SecAddr points to the
starting address of the outputsection rather than the
starting address of the eh frame section within that
output section.
---
 lld/ELF/Arch/AArch64.cpp   |  3 ++
 lld/test/ELF/eh-frame-nonzero-offset.s | 55 ++
 2 files changed, 58 insertions(+)
 create mode 100644 lld/test/ELF/eh-frame-nonzero-offset.s

diff --git a/lld/ELF/Arch/AArch64.cpp b/lld/ELF/Arch/AArch64.cpp
index 174a0a3624f7765..09477141c777948 100644
--- a/lld/ELF/Arch/AArch64.cpp
+++ b/lld/ELF/Arch/AArch64.cpp
@@ -770,6 +770,9 @@ void AArch64::relocateAlloc(InputSectionBase , uint8_t 
*buf) const {
   uint64_t secAddr = sec.getOutputSection()->addr;
   if (auto *s = dyn_cast())
 secAddr += s->outSecOff;
+  else if (auto *eh = dyn_cast())
+if (InputSection *isec = eh->getParent())
+  secAddr += isec->outSecOff;
   AArch64Relaxer relaxer(sec.relocs());
   for (size_t i = 0, size = sec.relocs().size(); i != size; ++i) {
 const Relocation  = sec.relocs()[i];
diff --git a/lld/test/ELF/eh-frame-nonzero-offset.s 
b/lld/test/ELF/eh-frame-nonzero-offset.s
new file mode 100644
index 000..ef086fcf670d81b
--- /dev/null
+++ b/lld/test/ELF/eh-frame-nonzero-offset.s
@@ -0,0 +1,55 @@
+// REQUIRES: aarch64
+// RUN: rm -rf %t && split-file %s %t
+
+// RUN: llvm-mc -filetype=obj -triple=aarch64 %t/a.s -o %t/a.o
+// RUN: ld.lld %t/a.o -T %t/eh-frame-non-zero-offset.t -o %t/non-zero
+// RUN: llvm-readelf --program-headers --unwind --symbols -x .eh_frame 
%t/non-zero | FileCheck --check-prefix=NONZERO %s
+// RUN: ld.lld %t/a.o -T %t/eh-frame-zero-offset.t -o %t/zero
+// RUN: llvm-readelf --program-headers --unwind --symbols -x .eh_frame %t/zero 
| FileCheck --check-prefix=ZERO %s
+
+// NONZERO:  {{[0-9]+}}: 0080 {{.*}} __eh_frame_start
+// NONZERO-NEXT: {{[0-9]+}}: 00ac {{.*}} __eh_frame_end
+
+// NONZERO:  0x0078   1000 
+// NONZERO-NEXT: 0x0088 017a5200 017c1e01 1b0c1f00 1000
+// NONZERO-NEXT: 0x0098 1800 64ff 0800 
+// NONZERO-NEXT: 0x00a8 
+
+// ZERO:  {{[0-9]+}}: 0080 {{.*}} __eh_frame_start
+// ZERO-NEXT: {{[0-9]+}}: 00ac {{.*}} __eh_frame_end
+
+// ZERO:  0x0080 1000  017a5200 017c1e01
+// ZERO-NEXT: 0x0090 1b0c1f00 1000 1800 64ff
+// ZERO-NEXT: 0x00a0 0800  
+
+//--- eh-frame-non-zero-offset.t
+SECTIONS {
+  .text : { *(.text .text.*) }
+  .eh_frame : {
+  /* Alignment padding within .eh_frame */
+  . = ALIGN(128);
+  __eh_frame_start = .;
+  *(.eh_frame .eh_frame.*) ;
+  __eh_frame_end = .;
+  }
+}
+
+//--- eh-frame-zero-offset.t
+SECTIONS {
+  .text : { *(.text .text.*) }
+  .eh_frame : ALIGN(128) {
+  __eh_frame_start = .;
+  *(.eh_frame .eh_frame.*) ;
+  __eh_frame_end = .;
+  }
+}
+
+//--- a.s
+.section .text.01, "ax",%progbits
+.global f1
+.type f1, %function
+f1:
+.cfi_startproc
+   nop
+   nop
+.cfi_endproc

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [libc++] Prevent calling the projection more than three times (PR #66315)

2023-09-18 Thread Louis Dionne via cfe-commits


@@ -108,7 +108,34 @@ constexpr bool test() {
 auto prvalue_proj = [](const CheckDoubleMove& x) -> CheckDoubleMove { 
return x; };
 assert(::ranges::clamp(val, low, high, moving_comp, prvalue_proj) == 
);
   }
+  { // Make sure we don't call the projection more than three times per 
[alg.clamp], see #64717
+int counter = 0;
+auto projection_function = [](const int value) -> int {
+  counter++;
+  return value;
+};
+assert(std::ranges::clamp(3, 2, 4, std::ranges::less{}, 
projection_function) == 3);
+assert(counter <= 3);
+  }
+  {
+struct Foo {
+  std::string s;
+};
+
+// taking by value is important here
+auto comparator = [](std::string a, std::string b) {
+  return std::atoi(a.c_str()) < std::atoi(b.c_str());
+};
+
+auto projection = [](Foo const& foo) {
+  return foo.s;
+};
 
+Foo foo{"12"};
+Foo high{"10"};
+Foo low{"1"};
+assert(std::ranges::clamp(foo, low, high, comparator, projection).s == 
"10");
+  }

ldionne wrote:

Let's add the test case from https://gcc.godbolt.org/z/a8ne6e487.

In this case it means that we also need to use `std::forward` like you did 
previously, thanks @timsong-cpp for clarifying.

https://github.com/llvm/llvm-project/pull/66315
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [libc++] Prevent calling the projection more than three times (PR #66315)

2023-09-18 Thread Louis Dionne via cfe-commits


@@ -108,7 +108,34 @@ constexpr bool test() {
 auto prvalue_proj = [](const CheckDoubleMove& x) -> CheckDoubleMove { 
return x; };
 assert(::ranges::clamp(val, low, high, moving_comp, prvalue_proj) == 
);
   }
+  { // Make sure we don't call the projection more than three times per 
[alg.clamp], see #64717
+int counter = 0;
+auto projection_function = [](const int value) -> int {
+  counter++;
+  return value;
+};
+assert(std::ranges::clamp(3, 2, 4, std::ranges::less{}, 
projection_function) == 3);
+assert(counter <= 3);
+  }
+  {
+struct Foo {
+  std::string s;
+};
+
+// taking by value is important here
+auto comparator = [](std::string a, std::string b) {
+  return std::atoi(a.c_str()) < std::atoi(b.c_str());
+};
+
+auto projection = [](Foo const& foo) {
+  return foo.s;
+};
 
+Foo foo{"12"};
+Foo high{"10"};
+Foo low{"1"};
+assert(std::ranges::clamp(foo, low, high, comparator, projection).s == 
"10");
+  }

ldionne wrote:

Let's add the test case from https://gcc.godbolt.org/z/a8ne6e487.

In this case it means that we also need to use `std::forward` like you did 
previously, thanks @timsong-cpp for clarifying.

https://github.com/llvm/llvm-project/pull/66315
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [libc++] Prevent calling the projection more than three times (PR #66315)

2023-09-18 Thread Louis Dionne via cfe-commits


@@ -37,9 +37,10 @@ struct __fn {
 _LIBCPP_ASSERT_UNCATEGORIZED(!bool(std::invoke(__comp, std::invoke(__proj, 
__high), std::invoke(__proj, __low))),
  "Bad bounds passed to std::ranges::clamp");
 
-if (std::invoke(__comp, std::invoke(__proj, __value), std::invoke(__proj, 
__low)))
+auto&& __projected = std::invoke(__proj, __value);
+if (std::invoke(__comp, std::forward(__projected), 
std::invoke(__proj, __low)))
   return __low;
-else if (std::invoke(__comp, std::invoke(__proj, __high), 
std::invoke(__proj, __value)))
+else if (std::invoke(__comp, std::invoke(__proj, __high), 
std::forward(__projected))

ldionne wrote:

Ah, thanks a lot! Like I said in the other comment, @pandaninjas let's add a 
test for that and go back to `std::forward`. Then I think this patch will be 
good to go.

https://github.com/llvm/llvm-project/pull/66315
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [libc++] Prevent calling the projection more than three times (PR #66315)

2023-09-18 Thread Louis Dionne via cfe-commits

ldionne wrote:

> Any idea why the CI is failing? It mentions line 86 not being constexpr 
> because of assert, but it doesn't seem like I've done anything which should 
> affect that...

I looked into it a bit and I think the CI is failing because of the 
`std::forward` problem. The assertion on line 86 fails because we don't respect 
the value category returned by the projection, which is basically that problem.

https://github.com/llvm/llvm-project/pull/66315
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [libc++] Prevent calling the projection more than three times (PR #66315)

2023-09-18 Thread Louis Dionne via cfe-commits

ldionne wrote:

> Any idea why the CI is failing? It mentions line 86 not being constexpr 
> because of assert, but it doesn't seem like I've done anything which should 
> affect that...

I looked into it a bit and I think the CI is failing because of the 
`std::forward` problem. The assertion on line 86 fails because we don't respect 
the value category returned by the projection, which is basically that problem.

https://github.com/llvm/llvm-project/pull/66315
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [analyzer] Do not use APInt methods on _BitInt() Types (PR #65887)

2023-09-18 Thread via cfe-commits

https://github.com/DonatNagyE approved this pull request.

Don't forget to update the commit message!

https://github.com/llvm/llvm-project/pull/65887
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [libc++] Prevent calling the projection more than three times (PR #66315)

2023-09-18 Thread Louis Dionne via cfe-commits

https://github.com/ldionne resolved 
https://github.com/llvm/llvm-project/pull/66315
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [libc++] Prevent calling the projection more than three times (PR #66315)

2023-09-18 Thread Louis Dionne via cfe-commits

https://github.com/ldionne resolved 
https://github.com/llvm/llvm-project/pull/66315
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang] [C23] Fix crash with _BitInt running clang-tidy (PR #65889)

2023-09-18 Thread via cfe-commits


@@ -1333,7 +1333,14 @@ void StmtProfiler::VisitPredefinedExpr(const 
PredefinedExpr *S) {
 void StmtProfiler::VisitIntegerLiteral(const IntegerLiteral *S) {
   VisitExpr(S);
   S->getValue().Profile(ID);
-  ID.AddInteger(S->getType()->castAs()->getKind());
+
+  QualType T = S->getType();
+  if (auto BitIntT = T->getAs()) {
+BitIntT->Profile(ID, BitIntT->isSigned(), BitIntT->getNumBits());

DonatNagyE wrote:

```suggestion
ID.AddBoolean(true);
BitIntT->Profile(ID);
```
(1) Add a boolean true to guarantee a difference from the other branch 
(otherwise we could theoretically get a hash collision in the case when the 
number of bits in an unsigned BitInt type happens to be equal to the kind of a 
builtin integer type).
(2) `BitIntType` has two methods named `Profile`; use the non-static one.

https://github.com/llvm/llvm-project/pull/65889
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D155064: [clang][SemaCXX] Diagnose tautological uses of consteval if and is_constant_evaluated

2023-09-18 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet updated this revision to Diff 556946.
hazohelet added a comment.

After discussion in https://github.com/llvm/llvm-project/pull/66222, I noticed 
I had misunderstood the recursiveness of constant-evaluated context.
I was pushing constant-evaluating on the lambda body when it appears inside 
constant-evaluated context. This was causing false positive in

  constexpr auto cexpr_lambda = []() {
    return __builtin_is_constant_evaluated();
  }

I fixed this by stopping pushing constant-evaluated context (See 
`SemaLambda.cpp`). Instead, I am pushing immediate-function context when the 
outer evaluation context is immediate function context as well as when it's 
consteval lambda so that we can warn on

  consteval void f() {
auto lam = []() { return __builtin_is_constant_evaluated(); };
  }

@cor3ntin
Should this patch wait for https://github.com/llvm/llvm-project/pull/66222?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D155064/new/

https://reviews.llvm.org/D155064

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticASTKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ExprConstant.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/AST/Interp/builtins.cpp
  clang/test/AST/Interp/if.cpp
  clang/test/AST/Interp/literals.cpp
  clang/test/CXX/expr/expr.const/p2-0x.cpp
  clang/test/CXX/expr/expr.const/p6-2a.cpp
  clang/test/CXX/expr/expr.prim/expr.prim.lambda/p3.cpp
  clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p4.cpp
  clang/test/Parser/pragma-fenv_access.c
  clang/test/SemaCXX/constant-conversion.cpp
  clang/test/SemaCXX/constant-expression-cxx11.cpp
  clang/test/SemaCXX/cxx2a-consteval.cpp
  clang/test/SemaCXX/cxx2b-consteval-if.cpp
  clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
  clang/test/SemaCXX/fixit-tautological-meta-constant.cpp
  clang/test/SemaCXX/vartemplate-lambda.cpp
  clang/test/SemaCXX/warn-constant-evaluated-constexpr.cpp
  clang/test/SemaCXX/warn-tautological-meta-constant.cpp
  clang/test/SemaTemplate/concepts.cpp
  clang/unittests/Support/TimeProfilerTest.cpp
  libcxx/include/__type_traits/is_constant_evaluated.h
  
libcxx/test/std/algorithms/alg.modifying.operations/alg.copy/ranges.copy.segmented.pass.cpp
  
libcxx/test/std/utilities/meta/meta.const.eval/is_constant_evaluated.verify.cpp

Index: libcxx/test/std/utilities/meta/meta.const.eval/is_constant_evaluated.verify.cpp
===
--- libcxx/test/std/utilities/meta/meta.const.eval/is_constant_evaluated.verify.cpp
+++ libcxx/test/std/utilities/meta/meta.const.eval/is_constant_evaluated.verify.cpp
@@ -24,7 +24,7 @@
 #else
   // expected-error-re@+1 (static_assert|static assertion)}} failed}}
   static_assert(!std::is_constant_evaluated(), "");
-  // expected-warning@-1 0-1 {{'std::is_constant_evaluated' will always evaluate to 'true' in a manifestly constant-evaluated expression}}
+  // expected-warning-re@-1 0-1 {{'std::is_constant_evaluated' will always evaluate to {{('true' in a manifestly constant-evaluated expression|true in this context)
 #endif
   return 0;
 }
Index: libcxx/test/std/algorithms/alg.modifying.operations/alg.copy/ranges.copy.segmented.pass.cpp
===
--- libcxx/test/std/algorithms/alg.modifying.operations/alg.copy/ranges.copy.segmented.pass.cpp
+++ libcxx/test/std/algorithms/alg.modifying.operations/alg.copy/ranges.copy.segmented.pass.cpp
@@ -93,12 +93,10 @@
 }
 
 int main(int, char**) {
-  if (!std::is_constant_evaluated()) {
-test_containers, std::deque>();
-test_containers, std::vector>();
-test_containers, std::deque>();
-test_containers, std::vector>();
-  }
+  test_containers, std::deque>();
+  test_containers, std::vector>();
+  test_containers, std::deque>();
+  test_containers, std::vector>();
 
   types::for_each(types::forward_iterator_list{}, [] {
 test_join_view();
Index: libcxx/include/__type_traits/is_constant_evaluated.h
===
--- libcxx/include/__type_traits/is_constant_evaluated.h
+++ libcxx/include/__type_traits/is_constant_evaluated.h
@@ -24,7 +24,14 @@
 #endif
 
 _LIBCPP_HIDE_FROM_ABI inline _LIBCPP_CONSTEXPR bool __libcpp_is_constant_evaluated() _NOEXCEPT {
+// __builtin_is_constant_evaluated() in this function always evaluates to false in pre-C++11 mode
+// because this function is not constexpr-qualified.
+// The following macro use clarifies this and avoids warnings from 

[clang] [clang][doc] Add documentation for the ASTs used to represent C++ templates (PR #66436)

2023-09-18 Thread Erich Keane via cfe-commits

erichkeane wrote:

> TBH, not sure if the UML diagrams would really help anyone understand what's 
> going on.

I tend to agree with this, the documentation via these diagrams is confusing me 
as well, it doesn't really seem to add anything (and in fact, seem to be 
'subtracting' in my case).

That said, if we DO decide to do this, we shouldn't commit the PNG, we need to 
add building of these from the script(.ded file) to cmake.

https://github.com/llvm/llvm-project/pull/66436
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Improve CI output when trailing whitespace is found (PR #66649)

2023-09-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

Fixes #66468
---
Full diff: https://github.com/llvm/llvm-project/pull/66649.diff


1 Files Affected:

- (modified) clang/utils/ci/run-buildbot (+5-1) 


``diff
diff --git a/clang/utils/ci/run-buildbot b/clang/utils/ci/run-buildbot
index d117fccc7e3fbd8..f47ffb5cbd38dcd 100755
--- a/clang/utils/ci/run-buildbot
+++ b/clang/utils/ci/run-buildbot
@@ -70,7 +70,11 @@ ninja --version
 
 case "${BUILDER}" in
 check-format)
-! grep -rnI '[[:blank:]]$' clang/lib clang/include clang/docs
+echo "*** Checking for trailing whitespace left in Clang source files ***"
+if grep -rnI '[[:blank:]]$' clang/lib clang/include clang/docs; then
+echo "*** Trailing whitespace has been found in Clang source files as 
described above ***"
+exit 1
+fi
 ;;
 build-clang)
 mkdir install

``




https://github.com/llvm/llvm-project/pull/66649
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Improve CI output when trailing whitespace is found (PR #66649)

2023-09-18 Thread Louis Dionne via cfe-commits

ldionne wrote:

@asl This should make it a bit more explicit. I see this now when running 
locally:

```
+ echo '*** Checking for trailing whitespace left in Clang source files ***'
*** Checking for trailing whitespace left in Clang source files ***
+ grep -rnI '[[:blank:]]$' clang/lib clang/include clang/docs
clang/include/clang-c/Index.h:38:
+ echo '*** Trailing whitespace has been found in Clang source files as 
described above ***'
*** Trailing whitespace has been found in Clang source files as described above 
***
+ exit 1
```

WDYT? It's still a bit cluttered by the fact that we run with `set -x` but I 
think it might be good enough.

https://github.com/llvm/llvm-project/pull/66649
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Improve CI output when trailing whitespace is found (PR #66649)

2023-09-18 Thread Louis Dionne via cfe-commits

https://github.com/ldionne created 
https://github.com/llvm/llvm-project/pull/66649

Fixes #66468

>From df20b6321bf9332571fc4e45ae370793876f7773 Mon Sep 17 00:00:00 2001
From: Louis Dionne 
Date: Mon, 18 Sep 2023 09:58:29 -0400
Subject: [PATCH] [clang] Improve CI output when trailing whitespace is found

Fixes #66468
---
 clang/utils/ci/run-buildbot | 6 +-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/clang/utils/ci/run-buildbot b/clang/utils/ci/run-buildbot
index d117fccc7e3fbd8..f47ffb5cbd38dcd 100755
--- a/clang/utils/ci/run-buildbot
+++ b/clang/utils/ci/run-buildbot
@@ -70,7 +70,11 @@ ninja --version
 
 case "${BUILDER}" in
 check-format)
-! grep -rnI '[[:blank:]]$' clang/lib clang/include clang/docs
+echo "*** Checking for trailing whitespace left in Clang source files ***"
+if grep -rnI '[[:blank:]]$' clang/lib clang/include clang/docs; then
+echo "*** Trailing whitespace has been found in Clang source files as 
described above ***"
+exit 1
+fi
 ;;
 build-clang)
 mkdir install

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Fix null dereference on return in lambda attribute statement expr (PR #66643)

2023-09-18 Thread Mariya Podchishchaeva via cfe-commits

https://github.com/Fznamznon commented:

The change needs a release note, otherwise looks good.
Right, @cor3ntin  ?

https://github.com/llvm/llvm-project/pull/66643
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [analyzer] Remove inaccurate legacy handling of bad bitwise shifts (PR #66647)

2023-09-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-static-analyzer-1


Changes

Previously, bitwise shifts with constant operands were validated by the checker 
`core.UndefinedBinaryOperatorResult`. However, this logic was unreliable, and 
commit 25b9696b61e53a958e217bb3d0eab66350dc187f added the dedicated checker 
`core.BitwiseShift` which validated the preconditions of all bitwise shifts 
with a more accurate logic (that uses the real types from the AST instead of 
the unreliable type information encoded in `APSInt` objects).

This commit disables the inaccurate logic that could mark bitwise shifts as 
'undefined' and removes the redundant shift-related warning messages from 
core.UndefinedBinaryOperatorResult. The tests that were validating this logic 
are also deleted by this commit; but I verified that those testcases trigger 
the expected bug reports from `core.BitwiseShift`. (I didn't convert them to 
tests of `core.BitwiseShift`, because that checker already has its own 
extensive test suite with many analogous testcases.)

I hope that there will be a time when the constant folding will be reliable, 
but until then we need hacky solutions like this improve the quality of results.
---
Full diff: https://github.com/llvm/llvm-project/pull/66647.diff


8 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp (+3-53) 
- (modified) clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp (-8) 
- (modified) clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp (+14-1) 
- (removed) clang/test/Analysis/bitwise-ops-nocrash.c (-28) 
- (removed) clang/test/Analysis/bitwise-ops.c (-60) 
- (modified) clang/test/Analysis/bitwise-shift-sanity-checks.c (+19-3) 
- (removed) clang/test/Analysis/left-shift-cxx2a.cpp (-22) 
- (modified) clang/test/Analysis/svalbuilder-simplify-no-crash.c (+3-1) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
index a2b5e2987db5959..5f37b915deb8a02 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
@@ -115,59 +115,9 @@ void UndefResultChecker::checkPostStmt(const 
BinaryOperator *B,
 OS << " due to array index out of bounds";
 } else {
   // Neither operand was undefined, but the result is undefined.
-  if ((B->getOpcode() == BinaryOperatorKind::BO_Shl ||
-   B->getOpcode() == BinaryOperatorKind::BO_Shr) &&
-  C.isNegative(B->getRHS())) {
-OS << "The result of the "
-   << ((B->getOpcode() == BinaryOperatorKind::BO_Shl) ? "left"
-  : "right")
-   << " shift is undefined because the right operand is negative";
-Ex = B->getRHS();
-  } else if ((B->getOpcode() == BinaryOperatorKind::BO_Shl ||
-  B->getOpcode() == BinaryOperatorKind::BO_Shr) &&
- isShiftOverflow(B, C)) {
-
-OS << "The result of the "
-   << ((B->getOpcode() == BinaryOperatorKind::BO_Shl) ? "left"
-  : "right")
-   << " shift is undefined due to shifting by ";
-Ex = B->getRHS();
-
-SValBuilder  = C.getSValBuilder();
-const llvm::APSInt *I =
-SB.getKnownValue(C.getState(), C.getSVal(B->getRHS()));
-if (!I)
-  OS << "a value that is";
-else if (I->isUnsigned())
-  OS << '\'' << I->getZExtValue() << "\', which is";
-else
-  OS << '\'' << I->getSExtValue() << "\', which is";
-
-OS << " greater or equal to the width of type '"
-   << B->getLHS()->getType() << "'.";
-  } else if (B->getOpcode() == BinaryOperatorKind::BO_Shl &&
- C.isNegative(B->getLHS())) {
-OS << "The result of the left shift is undefined because the left "
-  "operand is negative";
-Ex = B->getLHS();
-  } else if (B->getOpcode() == BinaryOperatorKind::BO_Shl &&
- isLeftShiftResultUnrepresentable(B, C)) {
-ProgramStateRef State = C.getState();
-SValBuilder  = C.getSValBuilder();
-const llvm::APSInt *LHS =
-SB.getKnownValue(State, C.getSVal(B->getLHS()));
-const llvm::APSInt *RHS =
-SB.getKnownValue(State, C.getSVal(B->getRHS()));
-OS << "The result of the left shift is undefined due to shifting \'"
-   << LHS->getSExtValue() << "\' by \'" << RHS->getZExtValue()
-   << "\', which is unrepresentable in the unsigned version of "
-   << "the return type \'" << B->getLHS()->getType() << "\'";
-Ex = B->getLHS();
-  } else {
-OS << "The result of the '"
-   << BinaryOperator::getOpcodeStr(B->getOpcode())
-   << "' expression is undefined";
-  }
+  OS << "The result of the '"
+ << BinaryOperator::getOpcodeStr(B->getOpcode())
+ 

[clang] [analyzer] Remove inaccurate legacy handling of bad bitwise shifts (PR #66647)

2023-09-18 Thread via cfe-commits

https://github.com/DonatNagyE created 
https://github.com/llvm/llvm-project/pull/66647

Previously, bitwise shifts with constant operands were validated by the checker 
`core.UndefinedBinaryOperatorResult`. However, this logic was unreliable, and 
commit 25b9696b61e53a958e217bb3d0eab66350dc187f added the dedicated checker 
`core.BitwiseShift` which validated the preconditions of all bitwise shifts 
with a more accurate logic (that uses the real types from the AST instead of 
the unreliable type information encoded in `APSInt` objects).

This commit disables the inaccurate logic that could mark bitwise shifts as 
'undefined' and removes the redundant shift-related warning messages from 
core.UndefinedBinaryOperatorResult. The tests that were validating this logic 
are also deleted by this commit; but I verified that those testcases trigger 
the expected bug reports from `core.BitwiseShift`. (I didn't convert them to 
tests of `core.BitwiseShift`, because that checker already has its own 
extensive test suite with many analogous testcases.)

I hope that there will be a time when the constant folding will be reliable, 
but until then we need hacky solutions like this improve the quality of results.

>From f5adc9b2a86266641d046ff83ed65c25a2419948 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Don=C3=A1t=20Nagy?= 
Date: Mon, 18 Sep 2023 13:06:33 +0200
Subject: [PATCH] [analyzer] Remove inaccurate legacy handling of bad bitwise
 shifts

Previously, bitwise shifts with constant operands were validated by
the checker `core.UndefinedBinaryOperatorResult`. However, this logic was
unreliable, and commit 25b9696b61e53a958e217bb3d0eab66350dc187f added
the dedicated checker `core.BitwiseShift` which validated the
preconditions of all bitwise shifts with a more accurate logic (that
uses the real types from the AST instead of the unreliable type
information encoded in `APSInt` objects).

This commit disables the inaccurate logic that could mark bitwise shifts
as 'undefined' and removes the redundant shift-related warning messages
from core.UndefinedBinaryOperatorResult. The tests that were validating
this logic are also deleted by this commit; but I verified that those
testcases trigger the expected bug reports from `core.BitwiseShift`.
(I didn't convert them to tests of `core.BitwiseShift`, because that
checker already has its own extensive test suite with many analogous
testcases.)

I hope that there will be a time when the constant folding will be
reliable, but until then we need hacky solutions like this improve the
quality of results.
---
 .../Checkers/UndefResultChecker.cpp   | 56 +
 .../StaticAnalyzer/Core/BasicValueFactory.cpp |  8 ---
 .../StaticAnalyzer/Core/SimpleSValBuilder.cpp | 15 -
 clang/test/Analysis/bitwise-ops-nocrash.c | 28 -
 clang/test/Analysis/bitwise-ops.c | 60 ---
 .../Analysis/bitwise-shift-sanity-checks.c| 22 ++-
 clang/test/Analysis/left-shift-cxx2a.cpp  | 22 ---
 .../Analysis/svalbuilder-simplify-no-crash.c  |  4 +-
 8 files changed, 39 insertions(+), 176 deletions(-)
 delete mode 100644 clang/test/Analysis/bitwise-ops-nocrash.c
 delete mode 100644 clang/test/Analysis/bitwise-ops.c
 delete mode 100644 clang/test/Analysis/left-shift-cxx2a.cpp

diff --git a/clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
index a2b5e2987db5959..5f37b915deb8a02 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
@@ -115,59 +115,9 @@ void UndefResultChecker::checkPostStmt(const 
BinaryOperator *B,
 OS << " due to array index out of bounds";
 } else {
   // Neither operand was undefined, but the result is undefined.
-  if ((B->getOpcode() == BinaryOperatorKind::BO_Shl ||
-   B->getOpcode() == BinaryOperatorKind::BO_Shr) &&
-  C.isNegative(B->getRHS())) {
-OS << "The result of the "
-   << ((B->getOpcode() == BinaryOperatorKind::BO_Shl) ? "left"
-  : "right")
-   << " shift is undefined because the right operand is negative";
-Ex = B->getRHS();
-  } else if ((B->getOpcode() == BinaryOperatorKind::BO_Shl ||
-  B->getOpcode() == BinaryOperatorKind::BO_Shr) &&
- isShiftOverflow(B, C)) {
-
-OS << "The result of the "
-   << ((B->getOpcode() == BinaryOperatorKind::BO_Shl) ? "left"
-  : "right")
-   << " shift is undefined due to shifting by ";
-Ex = B->getRHS();
-
-SValBuilder  = C.getSValBuilder();
-const llvm::APSInt *I =
-SB.getKnownValue(C.getState(), C.getSVal(B->getRHS()));
-if (!I)
-  OS << "a value that is";
-else if (I->isUnsigned())
-  OS << '\'' << I->getZExtValue() << "\', 

[clang-tools-extra] [InstSimplify] Fold icmp of `X and/or C1` and `X and/or C2` into constant (PR #65905)

2023-09-18 Thread Yingwei Zheng via cfe-commits

https://github.com/dtcxzyw closed 
https://github.com/llvm/llvm-project/pull/65905
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [InstSimplify] Fold icmp of `X and/or C1` and `X and/or C2` into constant (PR #65905)

2023-09-18 Thread Yingwei Zheng via cfe-commits

dtcxzyw wrote:

> LGTM, but please cleanup commits.

GitHub will squash commits into a single commit.


https://github.com/llvm/llvm-project/pull/65905
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [InstSimplify] Fold icmp of `X and/or C1` and `X and/or C2` into constant (PR #65905)

2023-09-18 Thread Yingwei Zheng via cfe-commits

dtcxzyw wrote:

> LGTM, but please cleanup commits.

GitHub will squash commits into a single commit.


https://github.com/llvm/llvm-project/pull/65905
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D134654: [clang] Detect header loops

2023-09-18 Thread Nathan Sidwell via Phabricator via cfe-commits
urnathan added a comment.

In D134654#4645969 , @cor3ntin wrote:

> @aaron.ballman @urnathan What is the status of this PR?

I'd kind of forgotten about it. Did get a query from, I think, boost about how 
I detected the loops  I reported -- which was by hacking the compiler and a bit 
of scripting.  But it seems there might be users desiring the knowledge of this.

And personally I noticed that if you write your headers as:

  #ifndef MACRO
  // body of header goes here
  #define MACRO
  #endif // MACRO

the current technology shouts at you -- pity that idiom is not a thing :(


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D134654/new/

https://reviews.llvm.org/D134654

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libunwind] [libunwind][AIX] Fix up TOC register if unw_getcontext is called from a different module (PR #66549)

2023-09-18 Thread via cfe-commits


@@ -305,9 +305,22 @@ DEFINE_LIBUNWIND_FUNCTION(__unw_getcontext)
   mflr  0
   std   0, PPC64_OFFS_SRR0(3) // store lr as ssr0
   PPC64_STR(1)
+  PPC64_STR(4)  // Save r4 first since it will be used for fixing r2.
+#if defined(_AIX)
+  // The TOC register (r2) was changed by the glue code if unw_getcontext
+  // is called from a different module. Save the original TOC register
+  // in the context if this is the case.
+  mflr  4

xingxue-ibm wrote:

Yes, `r0` has `LR` at this point and `mflr 4` has the same effect as `mr 4, 0` 
here. FWIW, I thought using `mflr 4` directly in the same new code block might 
make it a little easier for readers. If you think `mr 4, 0` is better, I can 
make the change.

https://github.com/llvm/llvm-project/pull/66549
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libunwind] [libunwind][AIX] Fix up TOC register if unw_getcontext is called from a different module (PR #66549)

2023-09-18 Thread via cfe-commits


@@ -305,9 +305,22 @@ DEFINE_LIBUNWIND_FUNCTION(__unw_getcontext)
   mflr  0
   std   0, PPC64_OFFS_SRR0(3) // store lr as ssr0
   PPC64_STR(1)
+  PPC64_STR(4)  // Save r4 first since it will be used for fixing r2.
+#if defined(_AIX)
+  // The TOC register (r2) was changed by the glue code if unw_getcontext
+  // is called from a different module. Save the original TOC register
+  // in the context if this is the case.
+  mflr  4
+  lwz   4, 0(4) // Get the first instruction at the return address.
+  lis   0, 0xe841   // Is it reloading the TOC register "ld 2,40(1)"?

xingxue-ibm wrote:

It does not work if the 32-bit comparison technique is used for 64-bit, and 
vice versa.

https://github.com/llvm/llvm-project/pull/66549
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Fix null dereference on return in lambda attribute statement expr (PR #66643)

2023-09-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

Fixes https://github.com/llvm/llvm-project/issues/48527
---
Full diff: https://github.com/llvm/llvm-project/pull/66643.diff


2 Files Affected:

- (modified) clang/lib/Sema/SemaStmt.cpp (+2) 
- (added) clang/test/SemaCXX/gh48527.cpp (+10) 


``diff
diff --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 7cc509542d5381d..10adfbc406dfbb5 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -3577,6 +3577,8 @@ StmtResult Sema::ActOnCapScopeReturnStmt(SourceLocation 
ReturnLoc,
   CapturingScopeInfo *CurCap = cast(getCurFunction());
   QualType FnRetType = CurCap->ReturnType;
   LambdaScopeInfo *CurLambda = dyn_cast(CurCap);
+  if (CurLambda && CurLambda->CallOperator->getType().isNull())
+return StmtError();
   bool HasDeducedReturnType =
   CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
 
diff --git a/clang/test/SemaCXX/gh48527.cpp b/clang/test/SemaCXX/gh48527.cpp
new file mode 100644
index 000..420c35be37f5191
--- /dev/null
+++ b/clang/test/SemaCXX/gh48527.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+int main() { // expected-note {{to match this '{'}}
+auto a = [](void)__attribute__((b(({ // expected-note {{to match this '('}}
+return 0;
+} // expected-error 3 {{expected ')'}} \
+  // expected-error {{expected ';' at end of declaration}}
+// expected-error@+2 {{expected ')'}}
+// expected-error@+1 {{expected body of lambda expression}}
+// expected-error {{expected '}'}}

``




https://github.com/llvm/llvm-project/pull/66643
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D159528: [clang] Fix null dereference on return in lambda attribute statement expr

2023-09-18 Thread Piotr Fusik via Phabricator via cfe-commits
pfusik abandoned this revision.
pfusik added a comment.

Moved to https://github.com/llvm/llvm-project/pull/66643


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159528/new/

https://reviews.llvm.org/D159528

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Fix null dereference on return in lambda attribute statement expr (PR #66643)

2023-09-18 Thread Piotr Fusik via cfe-commits

https://github.com/pfusik created 
https://github.com/llvm/llvm-project/pull/66643

Fixes https://github.com/llvm/llvm-project/issues/48527

>From ea731b4d3d553f42cbaaec2079adeec3927b4150 Mon Sep 17 00:00:00 2001
From: Piotr Fusik 
Date: Mon, 18 Sep 2023 15:10:58 +0200
Subject: [PATCH] [clang] Fix null dereference on return in lambda attribute
 statement expr

Fixes https://github.com/llvm/llvm-project/issues/48527
---
 clang/lib/Sema/SemaStmt.cpp|  2 ++
 clang/test/SemaCXX/gh48527.cpp | 10 ++
 2 files changed, 12 insertions(+)
 create mode 100644 clang/test/SemaCXX/gh48527.cpp

diff --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 7cc509542d5381d..10adfbc406dfbb5 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -3577,6 +3577,8 @@ StmtResult Sema::ActOnCapScopeReturnStmt(SourceLocation 
ReturnLoc,
   CapturingScopeInfo *CurCap = cast(getCurFunction());
   QualType FnRetType = CurCap->ReturnType;
   LambdaScopeInfo *CurLambda = dyn_cast(CurCap);
+  if (CurLambda && CurLambda->CallOperator->getType().isNull())
+return StmtError();
   bool HasDeducedReturnType =
   CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
 
diff --git a/clang/test/SemaCXX/gh48527.cpp b/clang/test/SemaCXX/gh48527.cpp
new file mode 100644
index 000..420c35be37f5191
--- /dev/null
+++ b/clang/test/SemaCXX/gh48527.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+int main() { // expected-note {{to match this '{'}}
+auto a = [](void)__attribute__((b(({ // expected-note {{to match this '('}}
+return 0;
+} // expected-error 3 {{expected ')'}} \
+  // expected-error {{expected ';' at end of declaration}}
+// expected-error@+2 {{expected ')'}}
+// expected-error@+1 {{expected body of lambda expression}}
+// expected-error {{expected '}'}}

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [LLVM] Add new attribute `optdebug` to optimize for debugging (PR #66632)

2023-09-18 Thread Paul T Robinson via cfe-commits


@@ -2325,6 +2325,7 @@ void 
CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
   B.addAttribute(llvm::Attribute::Naked);
 
 // OptimizeNone wins over OptimizeForSize and MinSize.
+F->removeFnAttr(llvm::Attribute::OptimizeForDebugging);

pogo59 wrote:

Given that this patch doesn't have any other clang changes, this one can be 
deferred to a later patch where clang actually applies the attribute.

https://github.com/llvm/llvm-project/pull/66632
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Preserve UDL nodes in RemoveNestedImmediateInvocation (PR #66641)

2023-09-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

D63960 performs a tree transformation on AST to prevent evaluating constant 
expressions eagerly by removing recorded immediate consteval invocations from 
subexpressions. (See https://reviews.llvm.org/D63960#inline-600736 for its 
motivation.)

However, the UDL node has been replaced with a CallExpr in the default 
TreeTransform since ca844ab0 (inadvertently?). This confuses clangd as it 
relies on the exact AST node type to decide whether or not to present inlay 
hints for an expression.

With regard to the fix, I think it's enough to return the UDL expression as-is 
during the transformation: We've bound it to temporary in its construction, and 
there's no ConstantExpr to visit under a UDL.

Fixes https://github.com/llvm/llvm-project/issues/63898.
---
Full diff: https://github.com/llvm/llvm-project/pull/66641.diff


2 Files Affected:

- (modified) clang/lib/Sema/SemaExpr.cpp (+4-1) 
- (added) clang/test/AST/ast-dump-udl-consteval.cpp (+17) 


``diff
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 92496b03ecabe54..104da822aae2930 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -18438,7 +18438,10 @@ static void RemoveNestedImmediateInvocation(
   DRSet.erase(cast(E->getCallee()->IgnoreImplicit()));
   return Base::TransformCXXOperatorCallExpr(E);
 }
-/// Base::TransformInitializer skip ConstantExpr so we need to visit them
+/// Base::TransformUserDefinedLiteral doesn't preserve the
+/// UserDefinedLiteral node.
+ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
+/// Base::TransformInitializer skips ConstantExpr so we need to visit them
 /// here.
 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
   if (!Init)
diff --git a/clang/test/AST/ast-dump-udl-consteval.cpp 
b/clang/test/AST/ast-dump-udl-consteval.cpp
new file mode 100644
index 000..9da53f725172aba
--- /dev/null
+++ b/clang/test/AST/ast-dump-udl-consteval.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -xc++ -std=c++23 -ast-dump %s | FileCheck %s
+
+int inline consteval operator""_u32(unsigned long long val) {
+  return val;
+}
+
+void udl() {
+  (void)(0_u32 + 1_u32);
+}
+
+// CHECK: `-BinaryOperator {{.+}}  'int' '+'
+// CHECK-NEXT: |-ConstantExpr {{.+}}  'int'
+// CHECK-NEXT: | |-value: Int 0
+// CHECK-NEXT: | `-UserDefinedLiteral {{.+}}  'int'
+// CHECK: `-ConstantExpr {{.+}}  'int'
+// CHECK-NEXT:   |-value: Int 1
+// CHECK-NEXT:   `-UserDefinedLiteral {{.+}}  'int'

``




https://github.com/llvm/llvm-project/pull/66641
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Preserve UDL nodes in RemoveNestedImmediateInvocation (PR #66641)

2023-09-18 Thread via cfe-commits

https://github.com/zyn0217 created 
https://github.com/llvm/llvm-project/pull/66641

D63960 performs a tree transformation on AST to prevent evaluating constant 
expressions eagerly by removing recorded immediate consteval invocations from 
subexpressions. (See https://reviews.llvm.org/D63960#inline-600736 for its 
motivation.)

However, the UDL node has been replaced with a CallExpr in the default 
TreeTransform since ca844ab0 (inadvertently?). This confuses clangd as it 
relies on the exact AST node type to decide whether or not to present inlay 
hints for an expression.

With regard to the fix, I think it's enough to return the UDL expression as-is 
during the transformation: We've bound it to temporary in its construction, and 
there's no ConstantExpr to visit under a UDL.

Fixes https://github.com/llvm/llvm-project/issues/63898.

>From ba9aa0ffe006ecdd8685c7e62be8c4c776391ec2 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Mon, 18 Sep 2023 19:55:45 +0800
Subject: [PATCH] [clang] Preserve UDL nodes in RemoveNestedImmediateInvocation

D63960 performs a tree transformation on AST to prevent evaluating
constant expressions eagerly by removing recorded immediate consteval
invocations from subexpressions. (See 
https://reviews.llvm.org/D63960#inline-600736
for its motivation.)

However, the UDL node has been replaced with a CallExpr in the default
TreeTransform since ca844ab0 (inadvertently?). This confuses clangd
as it relies on the exact AST node type to decide whether or not to
present inlay hints for an expression.

With regard to the fix, I think it's enough to return the UDL expression
as-is during the transformation: We've bound it to temporary
in its construction, and there's no ConstantExpr to visit under a UDL.

Fixes https://github.com/llvm/llvm-project/issues/63898.
---
 clang/lib/Sema/SemaExpr.cpp   |  5 -
 clang/test/AST/ast-dump-udl-consteval.cpp | 17 +
 2 files changed, 21 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/AST/ast-dump-udl-consteval.cpp

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 92496b03ecabe54..104da822aae2930 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -18438,7 +18438,10 @@ static void RemoveNestedImmediateInvocation(
   DRSet.erase(cast(E->getCallee()->IgnoreImplicit()));
   return Base::TransformCXXOperatorCallExpr(E);
 }
-/// Base::TransformInitializer skip ConstantExpr so we need to visit them
+/// Base::TransformUserDefinedLiteral doesn't preserve the
+/// UserDefinedLiteral node.
+ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
+/// Base::TransformInitializer skips ConstantExpr so we need to visit them
 /// here.
 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
   if (!Init)
diff --git a/clang/test/AST/ast-dump-udl-consteval.cpp 
b/clang/test/AST/ast-dump-udl-consteval.cpp
new file mode 100644
index 000..9da53f725172aba
--- /dev/null
+++ b/clang/test/AST/ast-dump-udl-consteval.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -xc++ -std=c++23 -ast-dump %s | FileCheck %s
+
+int inline consteval operator""_u32(unsigned long long val) {
+  return val;
+}
+
+void udl() {
+  (void)(0_u32 + 1_u32);
+}
+
+// CHECK: `-BinaryOperator {{.+}}  'int' '+'
+// CHECK-NEXT: |-ConstantExpr {{.+}}  'int'
+// CHECK-NEXT: | |-value: Int 0
+// CHECK-NEXT: | `-UserDefinedLiteral {{.+}}  'int'
+// CHECK: `-ConstantExpr {{.+}}  'int'
+// CHECK-NEXT:   |-value: Int 1
+// CHECK-NEXT:   `-UserDefinedLiteral {{.+}}  'int'

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][Interp] Add IntegralAP for arbitrary-precision integers (PR #65844)

2023-09-18 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?B=C3=A4der?= ,
Timm =?utf-8?q?B=C3=A4der?= ,
Timm =?utf-8?q?B=C3=A4der?= 
Message-ID:
In-Reply-To: 


tbaederr wrote:

Ping

https://github.com/llvm/llvm-project/pull/65844
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][Interp] Three-way comparisons (PR #65901)

2023-09-18 Thread Timm Baeder via cfe-commits

tbaederr wrote:

Ping

https://github.com/llvm/llvm-project/pull/65901
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D159528: [clang] Fix null dereference on return in lambda attribute statement expr

2023-09-18 Thread Piotr Fusik via Phabricator via cfe-commits
pfusik created this revision.
Herald added a project: All.
pfusik requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Fixes https://github.com/llvm/llvm-project/issues/48527


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D159528

Files:
  clang/lib/Sema/SemaStmt.cpp
  clang/test/SemaCXX/gh48527.cpp


Index: clang/test/SemaCXX/gh48527.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/gh48527.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+int main() { // expected-note {{to match this '{'}}
+auto a = [](void)__attribute__((b(({ // expected-note {{to match this '('}}
+return 0;
+} // expected-error 3 {{expected ')'}} \
+  // expected-error {{expected ';' at end of declaration}}
+// expected-error@+2 {{expected ')'}}
+// expected-error@+1 {{expected body of lambda expression}}
+// expected-error {{expected '}'}}
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -3577,6 +3577,8 @@
   CapturingScopeInfo *CurCap = cast(getCurFunction());
   QualType FnRetType = CurCap->ReturnType;
   LambdaScopeInfo *CurLambda = dyn_cast(CurCap);
+  if (CurLambda && CurLambda->CallOperator->getType().isNull())
+return StmtError();
   bool HasDeducedReturnType =
   CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
 


Index: clang/test/SemaCXX/gh48527.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/gh48527.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+int main() { // expected-note {{to match this '{'}}
+auto a = [](void)__attribute__((b(({ // expected-note {{to match this '('}}
+return 0;
+} // expected-error 3 {{expected ')'}} \
+  // expected-error {{expected ';' at end of declaration}}
+// expected-error@+2 {{expected ')'}}
+// expected-error@+1 {{expected body of lambda expression}}
+// expected-error {{expected '}'}}
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -3577,6 +3577,8 @@
   CapturingScopeInfo *CurCap = cast(getCurFunction());
   QualType FnRetType = CurCap->ReturnType;
   LambdaScopeInfo *CurLambda = dyn_cast(CurCap);
+  if (CurLambda && CurLambda->CallOperator->getType().isNull())
+return StmtError();
   bool HasDeducedReturnType =
   CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Fix math-errno issue (PR #66381)

2023-09-18 Thread Zahira Ammarguellat via cfe-commits

https://github.com/zahiraam updated 
https://github.com/llvm/llvm-project/pull/66381

>From 997e3b69ac5c20a9130b957c86c08b16d23af07c Mon Sep 17 00:00:00 2001
From: Zahira Ammarguellat 
Date: Thu, 14 Sep 2023 06:27:35 -0700
Subject: [PATCH 1/7] Fix math-errno issue

---
 clang/lib/CodeGen/CGBuiltin.cpp| 41 +-
 clang/test/CodeGen/math-builtins.c |  2 ++
 clang/test/CodeGen/math-libcalls.c |  2 ++
 3 files changed, 39 insertions(+), 6 deletions(-)

diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 8b19bf85d47a19f..c69ccdb0eb522bf 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -2313,14 +2313,18 @@ RValue CodeGenFunction::EmitBuiltinExpr(const 
GlobalDecl GD, unsigned BuiltinID,
   FD->hasAttr() ? 0 : BuiltinID;
 
   bool ErrnoOverriden = false;
+  bool ErrnoOverrideValue = false;
   // True if math-errno is overriden via the
   // '#pragma float_control(precise, on)'. This pragma disables fast-math,
   // which implies math-errno.
   if (E->hasStoredFPFeatures()) {
 FPOptionsOverride OP = E->getFPFeatures();
-if (OP.hasMathErrnoOverride())
-  ErrnoOverriden = OP.getMathErrnoOverride();
+if (OP.hasMathErrnoOverride()) {
+  ErrnoOverriden = true;
+  ErrnoOverrideValue = OP.getMathErrnoOverride();
+}
   }
+
   // True if 'atttibute__((optnone)) is used. This attibute overrides
   // fast-math which implies math-errno.
   bool OptNone = CurFuncDecl && CurFuncDecl->hasAttr();
@@ -2329,8 +2333,8 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
   // using the '#pragma float_control(precise, off)', and
   // attribute opt-none hasn't been seen.
   bool ErrnoOverridenToFalseWithOpt =
-  !ErrnoOverriden && !OptNone &&
-  CGM.getCodeGenOpts().OptimizationLevel != 0;
+   ErrnoOverriden && !ErrnoOverrideValue && !OptNone &&
+   CGM.getCodeGenOpts().OptimizationLevel != 0;
 
   // There are LLVM math intrinsics/instructions corresponding to math library
   // functions except the LLVM op will never set errno while the math library
@@ -2339,6 +2343,28 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
   // LLVM counterparts if the call is marked 'const' (known to never set 
errno).
   // In case FP exceptions are enabled, the experimental versions of the
   // intrinsics model those.
+  bool ConstAlways =
+  getContext().BuiltinInfo.isConst(BuiltinID);
+
+  // There's a special case with the fma builtins where they are always const
+  // if the target environment is GNU or the target is OS is Windows and we're
+  // targeting the MSVCRT.dll environment.
+  switch (BuiltinID) {
+  case Builtin::BI__builtin_fma:
+  case Builtin::BI__builtin_fmaf:
+  case Builtin::BI__builtin_fmal:
+  case Builtin::BIfma:
+  case Builtin::BIfmaf:
+  case Builtin::BIfmal: {
+auto  = CGM.getTriple();
+if (Trip.isGNUEnvironment() || Trip.isOSMSVCRT())
+  ConstAlways = true;
+break;
+}
+  default:
+break;
+  }  
+
   bool ConstWithoutErrnoAndExceptions =
   getContext().BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
   bool ConstWithoutExceptions =
@@ -2362,14 +2388,17 @@ RValue CodeGenFunction::EmitBuiltinExpr(const 
GlobalDecl GD, unsigned BuiltinID,
   bool ConstWithoutErrnoOrExceptions =
   ConstWithoutErrnoAndExceptions || ConstWithoutExceptions;
   bool GenerateIntrinsics =
-  FD->hasAttr() && !ErrnoOverriden && !OptNone;
+   (ConstAlways && !OptNone) ||
+   (!getLangOpts().MathErrno && !(ErrnoOverriden && ErrnoOverrideValue) &&
+   !OptNone);
   if (!GenerateIntrinsics) {
 GenerateIntrinsics =
 ConstWithoutErrnoOrExceptions && !ConstWithoutErrnoAndExceptions;
 if (!GenerateIntrinsics)
   GenerateIntrinsics =
   ConstWithoutErrnoOrExceptions &&
-  (!getLangOpts().MathErrno && !ErrnoOverriden && !OptNone);
+ (!getLangOpts().MathErrno &&
+   !(ErrnoOverriden && ErrnoOverrideValue) && !OptNone);
 if (!GenerateIntrinsics)
   GenerateIntrinsics =
   ConstWithoutErrnoOrExceptions && ErrnoOverridenToFalseWithOpt;
diff --git a/clang/test/CodeGen/math-builtins.c 
b/clang/test/CodeGen/math-builtins.c
index 962e311698f5755..554c604219957ca 100644
--- a/clang/test/CodeGen/math-builtins.c
+++ b/clang/test/CodeGen/math-builtins.c
@@ -1,5 +1,7 @@
 // RUN: %clang_cc1 -triple x86_64-unknown-unknown -w -S -o - -emit-llvm
  %s | FileCheck %s -check-prefix=NO__ERRNO
 // RUN: %clang_cc1 -triple x86_64-unknown-unknown -w -S -o - -emit-llvm 
-fmath-errno %s | FileCheck %s -check-prefix=HAS_ERRNO
+//  RUN: %clang_cc1 -triple x86_64-unknown-unknown -w -S -o - -emit-llvm 
-disable-llvm-passes -O2  %s | FileCheck %s -check-prefix=NO__ERRNO
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -w -S -o - -emit-llvm 
-disable-llvm-passes -O2 -fmath-errno %s | FileCheck %s -check-prefix=HAS_ERRNO
 // 

[clang] [analyzer] Add std::variant checker (PR #66481)

2023-09-18 Thread Gábor Spaits via cfe-commits

https://github.com/spaits edited https://github.com/llvm/llvm-project/pull/66481
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [analyzer] Add std::variant checker (PR #66481)

2023-09-18 Thread Gábor Spaits via cfe-commits

https://github.com/spaits edited https://github.com/llvm/llvm-project/pull/66481
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [analyzer] Add std::variant checker (PR #66481)

2023-09-18 Thread Gábor Spaits via cfe-commits


@@ -0,0 +1,312 @@
+//===- StdVariantChecker.cpp -*- C++ 
-*-==//
+//
+// 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 "clang/AST/Type.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "llvm/ADT/FoldingSet.h"
+
+#include "TaggedUnionModeling.h"
+
+using namespace clang;
+using namespace ento;
+using namespace variant_modeling;
+
+REGISTER_MAP_WITH_PROGRAMSTATE(VariantHeldTypeMap, const MemRegion *, QualType)
+
+namespace clang {
+namespace ento {
+namespace variant_modeling {
+
+// Returns the CallEvent representing the caller of the function
+// It is needed because the CallEvent class does not contain enough information
+// to tell who called it. Checker context is needed.
+CallEventRef<> getCaller(const CallEvent , const ProgramStateRef ) {
+  const auto *CallLocationContext = Call.getLocationContext();
+  if (!CallLocationContext) {
+return nullptr;
+  }
+
+  if (CallLocationContext->inTopFrame()) {
+return nullptr;
+  }
+  const auto *CallStackFrameContext = CallLocationContext->getStackFrame();
+  if (!CallStackFrameContext) {
+return nullptr;
+  }
+
+  CallEventManager  = State->getStateManager().getCallEventManager();
+  return CEMgr.getCaller(CallStackFrameContext, State);
+}
+
+const CXXConstructorDecl *
+getConstructorDeclarationForCall(const CallEvent ) {
+  const auto *ConstructorCall = dyn_cast();
+  if (!ConstructorCall) {
+return nullptr;
+  }
+  return ConstructorCall->getDecl();
+}
+
+bool isCopyConstructorCall(const CallEvent ) {
+  const CXXConstructorDecl *ConstructorDecl =
+  getConstructorDeclarationForCall(Call);
+  if (!ConstructorDecl) {
+return false;
+  }
+  return ConstructorDecl->isCopyConstructor();
+}
+
+bool isCopyAssignmentCall(const CallEvent ) {
+  const Decl *CopyAssignmentDecl = Call.getDecl();
+  if (!CopyAssignmentDecl) {
+return false;
+  }
+  const auto *AsMethodDecl = dyn_cast(CopyAssignmentDecl);
+  if (!AsMethodDecl) {
+return false;
+  }
+  return AsMethodDecl->isCopyAssignmentOperator();
+}
+
+bool isMoveConstructorCall(const CallEvent ) {
+  const CXXConstructorDecl *ConstructorDecl =
+  getConstructorDeclarationForCall(Call);
+  if (!ConstructorDecl) {
+return false;
+  }
+  return ConstructorDecl->isMoveConstructor();
+}
+
+bool isMoveAssignmentCall(const CallEvent ) {
+  const Decl *CopyAssignmentDecl = Call.getDecl();
+  if (!CopyAssignmentDecl) {
+return false;
+  }
+  const auto *AsMethodDecl = dyn_cast(CopyAssignmentDecl);
+  if (!AsMethodDecl) {
+return false;
+  }
+  return AsMethodDecl->isMoveAssignmentOperator();
+}
+
+const TemplateArgument (const CallEvent ) {
+  const CallExpr *CE = cast(Call.getOriginExpr());
+  const FunctionDecl *FD = CE->getDirectCallee();
+  assert(1 <= FD->getTemplateSpecializationArgs()->asArray().size() &&
+ "std::get should have at least 1 template argument!");
+  return FD->getTemplateSpecializationArgs()->asArray()[0];
+}
+
+bool isStdType(const Type *Type, const std::string ) {
+  auto *Decl = Type->getAsRecordDecl();
+  if (!Decl) {
+return false;
+  }
+
+  return (Decl->getNameAsString() == TypeName) && Decl->isInStdNamespace();
+}
+
+bool isStdVariant(const Type *Type) {
+  return isStdType(Type, std::string("variant"));
+}
+
+bool calledFromSystemHeader(const CallEvent ,
+const ProgramStateRef ) {
+  auto Caller = getCaller(Call, State);
+  if (Caller) {
+return Caller->isInSystemHeader();
+  }
+  return false;
+}
+
+bool calledFromSystemHeader(const CallEvent , CheckerContext ) {
+  return calledFromSystemHeader(Call, C.getState());
+}
+
+} // end of namespace variant_modeling
+} // end of namespace ento
+} // end of namespace clang
+
+static ArrayRef
+getTemplateArgsFromVariant(const Type *VariantType) {
+  const auto *TempSpecType = VariantType->getAs();
+  assert(TempSpecType &&
+ "We are in a variant instance. It must be a template 
specialization!");
+  return TempSpecType->template_arguments();
+}
+
+static QualType getNthTemplateTypeArgFromVariant(const Type *varType,
+ unsigned i) {
+  return getTemplateArgsFromVariant(varType)[i].getAsType();
+}
+
+class StdVariantChecker : public Checker {
+  // Call descriptors to find relevant calls
+  CallDescription 

[clang] [Documentation] Replace recommonmark by myst-parser (PR #65664)

2023-09-18 Thread via cfe-commits

https://github.com/cor3ntin edited 
https://github.com/llvm/llvm-project/pull/65664
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Documentation] Replace recommonmark by myst-parser (PR #65664)

2023-09-18 Thread via cfe-commits

https://github.com/cor3ntin edited 
https://github.com/llvm/llvm-project/pull/65664
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable --print-supported-extensions for all targets (PR #66586)

2023-09-18 Thread Balint Cristian via cfe-commits

https://github.com/cbalint13 closed 
https://github.com/llvm/llvm-project/pull/66586
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-repl] Emit const variables only once (PR #65257)

2023-09-18 Thread Jonas Hahnfeld via cfe-commits

hahnjo wrote:

Ping on the updated patch, which is now also passing downstream testing after I 
realized that we were missing a backport of commit 
e451d552348bc714614d294e32dfbe7ec2cd4005, which explains why some constructors 
were wrongly ordered...

https://github.com/llvm/llvm-project/pull/65257
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Inliner] Improve attribute propagation to callsites when inlining. (PR #66036)

2023-09-18 Thread Nikita Popov via cfe-commits

nikic wrote:

> ```
> define noundef nonnull ptr @foo() {
>%b = call ptr @bar()
>call void @use(ptr %p) willreturn nounwind
>ret ptr %b
> }
> ```
> 
> If we add `nonnull` to `@bar` during inlining it can still make `%p` poison 
> for its use in `@use`. I get it will trigger proper UB at the return b.c the 
> `noundef`, but is it okay to potentially trigger it early at the call to 
> `@use`?

Yes, this is fine, because the UB will be hit anyway. We can move it backwards, 
as long as it's guaranteed to execute.

> > * Just one-use is enough for poison-generating, we don't need 
> > guaranteed-to-transfer, BUT: we need to be careful about an implicit "use" 
> > in the call itself. That is, if the call we're transfering to is noundef 
> > and we only check one-use but not guaranteed-to-transfer, we would convert 
> > poison into UB at that point.
> 
> Oh I see, you mean something like:
> 
> ```
> define nonnull ptr @foo() {
>%b = call noundef ptr @bar()
>ret ptr %b
> }
> ```
> 
> So it would convert `poison` ret to full UB if we transfer `nonnull`. The 
> otherway around too I guess i.e if we have:
> 
> ```
> define noundef ptr @foo() {
>%b = call nonull ptr @bar()
>ret ptr %b
> }
> ```
> 
> We also need to be careful about transferring the `noundef`.
>
> I think with one-use + guranteed to transfer (the latter is a precondition 
> for transferring at all) in the latter we would get UB either way, but we are 
> moving to the point up a tiny bit. I don't understand how this could ever be 
> okay in the former case though? Isn't the former case just straight up 
> converting `poison` to UB which is a no-go?

You are right, the former case isn't correct even with one-use to 
guaranteed-to-transfer. That case would only work if we also had noundef on the 
foo return value.

https://github.com/llvm/llvm-project/pull/66036
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Documentation] Replace recommonmark by myst-parser (PR #65664)

2023-09-18 Thread via cfe-commits

cor3ntin wrote:

@andreil99 Sorry, I missed that.
I'd like to wait a few days for the bots to have the package installed first to 
minimize disruption.

https://github.com/llvm/llvm-project/pull/65664
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable --print-supported-extensions for all targets (PR #66586)

2023-09-18 Thread David Spickett via cfe-commits

DavidSpickett wrote:

> I was only able to check intel's one (w.r.t to -mcpu), without being aware on 
> aarch64 / riscv world's detail.

Yes I wouldn't expect you to right away, that's why we all keep an eye out for 
each other's changes :) . That's what I meant about starting by writing more 
comprehensive testing for the existing supported architectures, it would help 
you fully understand what the existing feature does.

> could be there a lookup within getAllProcessorFeatures() for the 
> human-readable description counterpart ?

Without seeing at least a sketch of what that would look like I can't say. 
Could we for example move some of this "frontend" information back into the 
backends, yes. That's not the unknown there, it's the how. So it's best just to 
try it yourself and maybe put up a draft PR if you think it can be done.

https://github.com/llvm/llvm-project/pull/66586
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Inliner] Improve attribute propagation to callsites when inlining. (PR #66036)

2023-09-18 Thread via cfe-commits

goldsteinn wrote:

> > > It occurs to me that the current return attribute propagation is 
> > > currently buggy for poison-generating attributes: 
> > > https://llvm.godbolt.org/z/x8n18q9Mj
> > > In this case the argument to use() will now be poison as well, while 
> > > before inlining only the return value was poison.
> > > This code needs to distinguish poison and UB generating attributes.
> > 
> > 
> > Good catch. I think this means basically `nonnull`, `noundef`, and `align` 
> > can only be propagated if there are no other uses in to-be-inlined 
> > function. That sound right or do you see any more robust way forward?
> 
> Limiting poison-generating attributes to one-use while keeping the rest of 
> the logic (with guarantee-to-transfer) would be the simplest way to make the 
> existing code correct. There are two additional ways to generalize:
> 
> * If the return is also noundef, we don't need one-use.
Is that right for `nonnull`?

I.e:
```
define noundef nonnull ptr @foo() {
   %b = call ptr @bar()
   call void @use(ptr %p) willreturn nounwind
   ret ptr %b
}
```
If we add `nonnull` to `@bar` during inlining it can still make `%p` poison for 
its use in `@use`. I get it will trigger proper UB at the return b.c the 
`noundef`, but is it okay to potentially trigger it early at the call to `@use`?


> * Just one-use is enough for poison-generating, we don't need 
> guaranteed-to-transfer, BUT: we need to be careful about an implicit "use" in 
> the call itself. That is, if the call we're transfering to is noundef and we 
> only check one-use but not guaranteed-to-transfer, we would convert poison 
> into UB at that point.

Oh I see, you mean something like:
```
define nonnull ptr @foo() {
   %b = call noundef ptr @bar()
   ret ptr %b
}
```

So it would convert `poison` ret to full UB if we transfer `nonnull`.
The otherway around too I guess i.e if we have:
```
define noundef ptr @foo() {
   %b = call nonull ptr @bar()
   ret ptr %b
}
```
We also need to be careful about transferring the `noundef`.

I think with one-use + guranteed to transfer (the latter is a precondition for 
transferring at all)
in the latter we would get UB either way, but we are moving to the point up a 
tiny bit.
I don't understand how this could ever be okay in the former case though? Isn't 
the former case
just straight up converting `poison` to UB which is a no-go?

https://github.com/llvm/llvm-project/pull/66036
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable --print-supported-extensions for all targets (PR #66586)

2023-09-18 Thread Balint Cristian via cfe-commits

cbalint13 wrote:

> Put `-mcpu` aside for now, that's nice, but it's only going to be viable in a 
> world where the backend (tablegen) and frontend (target parsers/ABI info) 
> agree on what is valid and can also be passed to clang.

> So what your patch produces is kinda like `./bin/clang --target  
> -mllvm -mattr=+unknown_name` and getting `Don't understand unknown_name, you 
> could have passed . (and we have had customers ask for exactly that sort of 
> option, but there's a reason some can't be passed to clang)
 
> Unfortunately the information of what is valid to be passed to clang is not 
> in the same tablegen you're pulling from. It would be nice, and it's not as 
> far off a goal as it used to be, but we aren't there yet.

@DavidSpickett ,

I see the point with the curated lists vs tablegen backend, thank you much for 
the explanations.
I was only able to check intel's one (w.r.t to -mcpu), without being aware on 
aarch64 / riscv world's detail.

---

My last (potential) idea that might have a purposeful end out of this effort 
here:

1. For each curated/legit features printed via ```riscvExtensionsHelp()```, 
```AArch64::PrintSupportedExtensions()```,   
```ARM::PrintSupportedExtensions()``` could be there a lookup  within 
getAllProcessorFeatures() for the human-readable description counterpart ?

---

Thanks a lot for your time !







https://github.com/llvm/llvm-project/pull/66586
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] remove ClassScopeFunctionSpecializationDecl (PR #66636)

2023-09-18 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian created 
https://github.com/llvm/llvm-project/pull/66636

This removes the `ClassScopeFunctionSpecializationDecl` `Decl` node, and 
instead uses `DependentFunctionTemplateSpecializationInfo` to handle such 
declarations. `DependentFunctionTemplateSpecializationInfo` is also changed to 
store a `const ASTTemplateArgumentListInfo*` to be more in line with 
`FunctionTemplateSpecializationInfo`. 

This also changes `FunctionDecl::isFunctionTemplateSpecialization` to return 
`true` for dependent specializations, and 
`FunctionDecl::getTemplateSpecializationKind`/`FunctionDecl::getTemplateSpecializationKindForInstantiation`
 to return `TSK_ExplicitSpecialization` for non-friend dependent 
specializations (the same behavior as dependent class scope 
`ClassTemplateSepcializationDecl` & `VarTemplateSepcializationDecl`).

>From d11d546f3190936ba45c57b4825073026d817878 Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Fri, 25 Aug 2023 14:07:32 -0400
Subject: [PATCH] [clang] remove ClassScopeFunctionSpecializationDecl

---
 .../clang-tidy/modernize/UseEmplaceCheck.cpp  |   2 +-
 .../clangd/SemanticHighlighting.cpp   |   9 --
 clang/include/clang/AST/ASTNodeTraverser.h|   7 +-
 clang/include/clang/AST/Decl.h|  10 +-
 clang/include/clang/AST/DeclTemplate.h| 150 +++---
 clang/include/clang/AST/RecursiveASTVisitor.h |  19 ++-
 clang/include/clang/Basic/DeclNodes.td|   1 -
 .../clang/Basic/DiagnosticSemaKinds.td|   8 +-
 clang/include/clang/Sema/Sema.h   |   6 +-
 clang/include/clang/Sema/Template.h   |   2 -
 .../include/clang/Serialization/ASTBitCodes.h |   4 -
 .../clang/Serialization/ASTRecordReader.h |   2 +
 clang/lib/AST/ASTImporter.cpp |  26 ++-
 clang/lib/AST/Decl.cpp|  71 ++---
 clang/lib/AST/DeclBase.cpp|   2 -
 clang/lib/AST/DeclTemplate.cpp|  13 --
 clang/lib/AST/ODRHash.cpp |   4 +
 clang/lib/CodeGen/CGDecl.cpp  |   1 -
 clang/lib/Index/IndexSymbol.cpp   |   1 -
 clang/lib/Sema/SemaDecl.cpp   | 112 ++---
 clang/lib/Sema/SemaTemplate.cpp   |  14 +-
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 121 +++---
 clang/lib/Serialization/ASTCommon.cpp |   1 -
 clang/lib/Serialization/ASTReader.cpp |  19 ++-
 clang/lib/Serialization/ASTReaderDecl.cpp |  59 ++-
 clang/lib/Serialization/ASTWriter.cpp |   1 -
 clang/lib/Serialization/ASTWriterDecl.cpp |  42 ++---
 .../Checkers/SmartPtrModeling.cpp |   2 +-
 clang/test/AST/ast-dump-decl.cpp  |   9 +-
 clang/test/CXX/drs/dr7xx.cpp  |   5 +
 .../test/SemaTemplate/instantiate-method.cpp  |   7 +-
 clang/tools/libclang/CIndex.cpp   |   1 -
 32 files changed, 290 insertions(+), 441 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
index 554abcd900e329c..06ae1f4e257528f 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
@@ -67,7 +67,7 @@ AST_MATCHER_P(CallExpr, hasLastArgument,
 // function had parameters defined (this is useful to check if there is only 
one
 // variadic argument).
 AST_MATCHER(CXXMemberCallExpr, hasSameNumArgsAsDeclNumParams) {
-  if (Node.getMethodDecl()->isFunctionTemplateSpecialization())
+  if (Node.getMethodDecl()->getPrimaryTemplate())
 return Node.getNumArgs() == Node.getMethodDecl()
 ->getPrimaryTemplate()
 ->getTemplatedDecl()
diff --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp 
b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index 45c01634e2e38d1..7649e37e1f96663 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -715,13 +715,6 @@ class CollectExtraHighlightings
 return true;
   }
 
-  bool VisitClassScopeFunctionSpecializationDecl(
-  ClassScopeFunctionSpecializationDecl *D) {
-if (auto *Args = D->getTemplateArgsAsWritten())
-  H.addAngleBracketTokens(Args->getLAngleLoc(), Args->getRAngleLoc());
-return true;
-  }
-
   bool VisitDeclRefExpr(DeclRefExpr *E) {
 H.addAngleBracketTokens(E->getLAngleLoc(), E->getRAngleLoc());
 return true;
@@ -752,8 +745,6 @@ class CollectExtraHighlightings
 }
 if (auto *Args = D->getTemplateSpecializationArgsAsWritten())
   H.addAngleBracketTokens(Args->getLAngleLoc(), Args->getRAngleLoc());
-if (auto *I = D->getDependentSpecializationInfo())
-  H.addAngleBracketTokens(I->getLAngleLoc(), I->getRAngleLoc());
 return true;
   }
 
diff --git a/clang/include/clang/AST/ASTNodeTraverser.h 
b/clang/include/clang/AST/ASTNodeTraverser.h
index 

[PATCH] D153131: [clang analysis][thread-safety] Handle return-by-reference...

2023-09-18 Thread Clement Courbet via Phabricator via cfe-commits
courbet added a comment.

> I think we should use the expected exit set instead of the entry set.

Indeed, I've added  a few tests to check this. Let me know if you see any other 
tests that might be valuable.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153131/new/

https://reviews.llvm.org/D153131

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153131: [clang analysis][thread-safety] Handle return-by-reference...

2023-09-18 Thread Clement Courbet via Phabricator via cfe-commits
courbet updated this revision to Diff 556940.
courbet marked 7 inline comments as done.
courbet added a comment.

- Check return values against the exit set rather than the entry set, add unit 
tests.
- Address other cosmetic review comments


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153131/new/

https://reviews.llvm.org/D153131

Files:
  clang/include/clang/Analysis/Analyses/ThreadSafety.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Analysis/ThreadSafety.cpp
  clang/lib/Sema/AnalysisBasedWarnings.cpp
  clang/test/SemaCXX/warn-thread-safety-analysis.cpp

Index: clang/test/SemaCXX/warn-thread-safety-analysis.cpp
===
--- clang/test/SemaCXX/warn-thread-safety-analysis.cpp
+++ clang/test/SemaCXX/warn-thread-safety-analysis.cpp
@@ -5580,6 +5580,85 @@
   }
 };
 
+class Return {
+  Mutex mu;
+  Foo foo GUARDED_BY(mu);
+  Foo* foo_ptr PT_GUARDED_BY(mu);
+
+  Foo returns_value_locked() {
+MutexLock lock();
+return foo;
+  }
+
+  Foo returns_value_locks_required() EXCLUSIVE_LOCKS_REQUIRED(mu) {
+return foo;
+  }
+
+  Foo returns_value_releases_lock_after_return() UNLOCK_FUNCTION(mu) {
+MutexLock lock(, true);
+return foo;
+  }
+
+  Foo returns_value_aquires_lock() EXCLUSIVE_LOCK_FUNCTION(mu) {
+mu.Lock();
+return foo;
+  }
+  
+  Foo returns_value_not_locked() {
+return foo;   // expected-warning {{reading variable 'foo' requires holding mutex 'mu'}}
+  }
+  
+  Foo returns_value_releases_lock_before_return() UNLOCK_FUNCTION(mu) {
+mu.Unlock();
+return foo;   // expected-warning {{reading variable 'foo' requires holding mutex 'mu'}}
+  }
+
+  Foo _ref_not_locked() {
+return foo;   // expected-warning {{returning variable 'foo' by reference requires holding mutex 'mu'}}
+  }
+
+  Foo _ref_locked() {
+MutexLock lock();
+return foo;   // expected-warning {{returning variable 'foo' by reference requires holding mutex 'mu'}}
+  }
+
+  Foo _ref_shared_locks_required() SHARED_LOCKS_REQUIRED(mu) {
+return foo;   // expected-warning {{returning variable 'foo' by reference requires holding mutex 'mu' exclusively}}
+  }
+
+  Foo _ref_exclusive_locks_required() EXCLUSIVE_LOCKS_REQUIRED(mu) {
+return foo;
+  }
+
+  Foo _ref_releases_lock_after_return() UNLOCK_FUNCTION(mu) {
+MutexLock lock(, true);
+return foo;   // expected-warning {{returning variable 'foo' by reference requires holding mutex 'mu' exclusively}}
+  }
+
+  Foo& returns_ref_releases_lock_before_return() UNLOCK_FUNCTION(mu) {
+mu.Unlock();
+return foo;   // // expected-warning {{returning variable 'foo' by reference requires holding mutex 'mu' exclusively}}
+  }
+  
+  Foo _ref_aquires_lock() EXCLUSIVE_LOCK_FUNCTION(mu) {
+mu.Lock();
+return foo;
+  }
+  
+  const Foo _constref_shared_locks_required() SHARED_LOCKS_REQUIRED(mu) {
+return foo;
+  }
+  
+  Foo *returns_ptr() {
+return   // FIXME -- Do we want to warn on this ?
+  }
+
+  Foo _ref2() {
+return *foo_ptr;  // expected-warning {{returning the value that 'foo_ptr' points to by reference requires holding mutex 'mu' exclusively}}
+  }
+
+};
+
 
 }  // end namespace PassByRefTest
 
Index: clang/lib/Sema/AnalysisBasedWarnings.cpp
===
--- clang/lib/Sema/AnalysisBasedWarnings.cpp
+++ clang/lib/Sema/AnalysisBasedWarnings.cpp
@@ -1983,6 +1983,12 @@
 case POK_PtPassByRef:
   DiagID = diag::warn_pt_guarded_pass_by_reference;
   break;
+case POK_ReturnByRef:
+  DiagID = diag::warn_guarded_return_by_reference;
+  break;
+case POK_PtReturnByRef:
+  DiagID = diag::warn_pt_guarded_return_by_reference;
+  break;
   }
   PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
<< D
@@ -2013,6 +2019,12 @@
 case POK_PtPassByRef:
   DiagID = diag::warn_pt_guarded_pass_by_reference;
   break;
+case POK_ReturnByRef:
+  DiagID = diag::warn_guarded_return_by_reference;
+  break;
+case POK_PtReturnByRef:
+  DiagID = diag::warn_pt_guarded_return_by_reference;
+  break;
   }
   PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
<< D
Index: clang/lib/Analysis/ThreadSafety.cpp
===
--- clang/lib/Analysis/ThreadSafety.cpp
+++ clang/lib/Analysis/ThreadSafety.cpp
@@ -1008,7 +1008,7 @@
   threadSafety::SExprBuilder SxBuilder;
 
   ThreadSafetyHandler 
-  const CXXMethodDecl *CurrentMethod = nullptr;
+  const FunctionDecl *CurrentFunction;
   LocalVariableMap LocalVarMap;
   FactManager FactMan;
   std::vector 

[PATCH] D159212: [MLIR] Allow dialects to disable CSE for certain operations

2023-09-18 Thread Sergio Afonso via Phabricator via cfe-commits
skatrak abandoned this revision.
skatrak added a comment.

I'll close this patch now, since the agreed approach has been to try using the 
`IsolatedFromAbove` trait and not to add an interface modifying the CSE pass 
behavior.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159212/new/

https://reviews.llvm.org/D159212

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [LLVM] Add new attribute `optdebug` to optimize for debugging (PR #66632)

2023-09-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-debuginfo


Changes

This patch adds a new fn attribute, `optdebug`, that specifies that 
optimizations should make decisions that prioritize debug info quality, 
potentially at the cost of runtime performance.

This patch does not add any functional changes triggered by this attribute, 
only the attribute itself. A subsequent patch will use this flag to disable the 
post-RA scheduler.

I've added the reviewers of the original patch (D157615), i.e. debug info 
codeowners and the others who left comments; as far as I'm aware there isn't a 
codeowner for "attributes", but if there's some owned category that applies 
then lmk and I'll add the relevant reviewer.
---
Full diff: https://github.com/llvm/llvm-project/pull/66632.diff


12 Files Affected:

- (modified) clang/lib/CodeGen/CodeGenModule.cpp (+1) 
- (modified) llvm/docs/BitCodeFormat.rst (+1) 
- (modified) llvm/docs/LangRef.rst (+4) 
- (modified) llvm/include/llvm/Bitcode/LLVMBitCodes.h (+1) 
- (modified) llvm/include/llvm/IR/Attributes.td (+3) 
- (modified) llvm/lib/Bitcode/Reader/BitcodeReader.cpp (+2) 
- (modified) llvm/lib/Bitcode/Writer/BitcodeWriter.cpp (+2) 
- (modified) llvm/lib/Transforms/Utils/CodeExtractor.cpp (+1) 
- (modified) llvm/test/Bitcode/attributes.ll (+7) 
- (modified) llvm/utils/emacs/llvm-mode.el (+1-1) 
- (modified) llvm/utils/kate/llvm.xml (+1) 
- (modified) llvm/utils/vim/syntax/llvm.vim (+1) 


``diff
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 8b0c9340775cbe9..96d053a6aa8f9e5 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -2325,6 +2325,7 @@ void 
CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
   B.addAttribute(llvm::Attribute::Naked);
 
 // OptimizeNone wins over OptimizeForSize and MinSize.
+F->removeFnAttr(llvm::Attribute::OptimizeForDebugging);
 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
 F->removeFnAttr(llvm::Attribute::MinSize);
   } else if (D->hasAttr()) {
diff --git a/llvm/docs/BitCodeFormat.rst b/llvm/docs/BitCodeFormat.rst
index 70be73abef19d6d..ce0e29fb6b928a7 100644
--- a/llvm/docs/BitCodeFormat.rst
+++ b/llvm/docs/BitCodeFormat.rst
@@ -1085,6 +1085,7 @@ The integer codes are mapped to well-known attributes as 
follows.
 * code 77: ``elementtype``
 * code 78: ``disable_sanitizer_instrumentation``
 * code 79: ``nosanitize_bounds``
+* code 88: ``optdebug``
 
 .. note::
   The ``allocsize`` attribute has a special encoding for its arguments. Its two
diff --git a/llvm/docs/LangRef.rst b/llvm/docs/LangRef.rst
index f542e70bcfee810..fa274fdb66a5047 100644
--- a/llvm/docs/LangRef.rst
+++ b/llvm/docs/LangRef.rst
@@ -2024,6 +2024,10 @@ example:
Note: Comparing address of a global variable to ``null`` may still
evaluate to false because of a limitation in querying this attribute inside
constant expressions.
+``optdebug``
+This attribute suggests that optimization passes and code generator passes
+should make choices that try to preserve debug info without significantly
+degrading runtime performance.
 ``optforfuzzing``
 This attribute indicates that this function should be optimized
 for maximum fuzzing signal.
diff --git a/llvm/include/llvm/Bitcode/LLVMBitCodes.h 
b/llvm/include/llvm/Bitcode/LLVMBitCodes.h
index 52e76356a892e45..5d7be5ca936ad37 100644
--- a/llvm/include/llvm/Bitcode/LLVMBitCodes.h
+++ b/llvm/include/llvm/Bitcode/LLVMBitCodes.h
@@ -713,6 +713,7 @@ enum AttributeKindCodes {
   ATTR_KIND_SKIP_PROFILE = 85,
   ATTR_KIND_MEMORY = 86,
   ATTR_KIND_NOFPCLASS = 87,
+  ATTR_KIND_OPTIMIZE_FOR_DEBUGGING = 88,
 };
 
 enum ComdatSelectionKindCodes {
diff --git a/llvm/include/llvm/IR/Attributes.td 
b/llvm/include/llvm/IR/Attributes.td
index aba1d718f7f72f9..fda79f5f24495fb 100644
--- a/llvm/include/llvm/IR/Attributes.td
+++ b/llvm/include/llvm/IR/Attributes.td
@@ -200,6 +200,9 @@ def NoSanitizeCoverage : EnumAttr<"nosanitize_coverage", 
[FnAttr]>;
 /// Null pointer in address space zero is valid.
 def NullPointerIsValid : EnumAttr<"null_pointer_is_valid", [FnAttr]>;
 
+/// Select optimizations that give decent debug info.
+def OptimizeForDebugging : EnumAttr<"optdebug", [FnAttr]>;
+
 /// Select optimizations for best fuzzing signal.
 def OptForFuzzing : EnumAttr<"optforfuzzing", [FnAttr]>;
 
diff --git a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp 
b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
index 1d1ec988a93d847..16eafa6e18f5d59 100644
--- a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
+++ b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
@@ -1980,6 +1980,8 @@ static Attribute::AttrKind getAttrFromCode(uint64_t Code) 
{
 return Attribute::NoSanitizeCoverage;
   case bitc::ATTR_KIND_NULL_POINTER_IS_VALID:
 return Attribute::NullPointerIsValid;
+  case bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING:
+return Attribute::OptimizeForDebugging;
   case bitc::ATTR_KIND_OPT_FOR_FUZZING:
 return 

[clang] [LLVM] Add new attribute `optdebug` to optimize for debugging (PR #66632)

2023-09-18 Thread Stephen Tozer via cfe-commits

https://github.com/SLTozer created 
https://github.com/llvm/llvm-project/pull/66632

This patch adds a new fn attribute, `optdebug`, that specifies that 
optimizations should make decisions that prioritize debug info quality, 
potentially at the cost of runtime performance.

This patch does not add any functional changes triggered by this attribute, 
only the attribute itself. A subsequent patch will use this flag to disable the 
post-RA scheduler.

I've added the reviewers of the original patch (D157615), i.e. debug info 
codeowners and the others who left comments; as far as I'm aware there isn't a 
codeowner for "attributes", but if there's some owned category that applies 
then lmk and I'll add the relevant reviewer.

>From 18f494a4006b4c21b364a91107d4a07ceaf88213 Mon Sep 17 00:00:00 2001
From: Stephen Tozer 
Date: Mon, 18 Sep 2023 09:59:11 +0100
Subject: [PATCH] [LLVM] Add new attribute `optdebug` to optimize for debugging

This patch adds a new fn attribute, `optdebug`, that specifies that
optimizations should make decisions that prioritize debug info quality,
potentially at the cost of runtime performance.

This patch does not add any functional changes triggered by this attribute,
only the attribute itself.
---
 clang/lib/CodeGen/CodeGenModule.cpp | 1 +
 llvm/docs/BitCodeFormat.rst | 1 +
 llvm/docs/LangRef.rst   | 4 
 llvm/include/llvm/Bitcode/LLVMBitCodes.h| 1 +
 llvm/include/llvm/IR/Attributes.td  | 3 +++
 llvm/lib/Bitcode/Reader/BitcodeReader.cpp   | 2 ++
 llvm/lib/Bitcode/Writer/BitcodeWriter.cpp   | 2 ++
 llvm/lib/Transforms/Utils/CodeExtractor.cpp | 1 +
 llvm/test/Bitcode/attributes.ll | 7 +++
 llvm/utils/emacs/llvm-mode.el   | 2 +-
 llvm/utils/kate/llvm.xml| 1 +
 llvm/utils/vim/syntax/llvm.vim  | 1 +
 12 files changed, 25 insertions(+), 1 deletion(-)

diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 8b0c9340775cbe9..96d053a6aa8f9e5 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -2325,6 +2325,7 @@ void 
CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
   B.addAttribute(llvm::Attribute::Naked);
 
 // OptimizeNone wins over OptimizeForSize and MinSize.
+F->removeFnAttr(llvm::Attribute::OptimizeForDebugging);
 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
 F->removeFnAttr(llvm::Attribute::MinSize);
   } else if (D->hasAttr()) {
diff --git a/llvm/docs/BitCodeFormat.rst b/llvm/docs/BitCodeFormat.rst
index 70be73abef19d6d..ce0e29fb6b928a7 100644
--- a/llvm/docs/BitCodeFormat.rst
+++ b/llvm/docs/BitCodeFormat.rst
@@ -1085,6 +1085,7 @@ The integer codes are mapped to well-known attributes as 
follows.
 * code 77: ``elementtype``
 * code 78: ``disable_sanitizer_instrumentation``
 * code 79: ``nosanitize_bounds``
+* code 88: ``optdebug``
 
 .. note::
   The ``allocsize`` attribute has a special encoding for its arguments. Its two
diff --git a/llvm/docs/LangRef.rst b/llvm/docs/LangRef.rst
index f542e70bcfee810..fa274fdb66a5047 100644
--- a/llvm/docs/LangRef.rst
+++ b/llvm/docs/LangRef.rst
@@ -2024,6 +2024,10 @@ example:
Note: Comparing address of a global variable to ``null`` may still
evaluate to false because of a limitation in querying this attribute inside
constant expressions.
+``optdebug``
+This attribute suggests that optimization passes and code generator passes
+should make choices that try to preserve debug info without significantly
+degrading runtime performance.
 ``optforfuzzing``
 This attribute indicates that this function should be optimized
 for maximum fuzzing signal.
diff --git a/llvm/include/llvm/Bitcode/LLVMBitCodes.h 
b/llvm/include/llvm/Bitcode/LLVMBitCodes.h
index 52e76356a892e45..5d7be5ca936ad37 100644
--- a/llvm/include/llvm/Bitcode/LLVMBitCodes.h
+++ b/llvm/include/llvm/Bitcode/LLVMBitCodes.h
@@ -713,6 +713,7 @@ enum AttributeKindCodes {
   ATTR_KIND_SKIP_PROFILE = 85,
   ATTR_KIND_MEMORY = 86,
   ATTR_KIND_NOFPCLASS = 87,
+  ATTR_KIND_OPTIMIZE_FOR_DEBUGGING = 88,
 };
 
 enum ComdatSelectionKindCodes {
diff --git a/llvm/include/llvm/IR/Attributes.td 
b/llvm/include/llvm/IR/Attributes.td
index aba1d718f7f72f9..fda79f5f24495fb 100644
--- a/llvm/include/llvm/IR/Attributes.td
+++ b/llvm/include/llvm/IR/Attributes.td
@@ -200,6 +200,9 @@ def NoSanitizeCoverage : EnumAttr<"nosanitize_coverage", 
[FnAttr]>;
 /// Null pointer in address space zero is valid.
 def NullPointerIsValid : EnumAttr<"null_pointer_is_valid", [FnAttr]>;
 
+/// Select optimizations that give decent debug info.
+def OptimizeForDebugging : EnumAttr<"optdebug", [FnAttr]>;
+
 /// Select optimizations for best fuzzing signal.
 def OptForFuzzing : EnumAttr<"optforfuzzing", [FnAttr]>;
 
diff --git a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp 
b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
index 1d1ec988a93d847..16eafa6e18f5d59 100644
--- 

[clang] [clang] Enable --print-supported-extensions for all targets (PR #66586)

2023-09-18 Thread David Spickett via cfe-commits

DavidSpickett wrote:

Put `-mcpu` aside for now, that's nice, but it's only going to be viable in a 
world where the backend (tablegen) and frontend (target parsers/ABI info) agree 
on what is valid and can also be passed to clang.

> The file with the full log outputs is here: 
> [sample-outputs.log.gz](https://github.com/llvm/llvm-project/files/12646975/sample-outputs.log.gz)

This is problem 1 right now. RISC-V is currently printing more kinds of 
information than what your sample outputs are with this patch. Currently it 
prints:
```
$ ./bin/clang --target=riscv64-unknown-linux-gnu  --print-supported-extensions
<...>
All available -march extensions for RISC-V

NameVersion
i   2.1
e   2.0
<...>
xperimental extensions
zicfilp 0.2
```
So you will have to either get the RISC-V folks to agree that that extra 
information is not required, or pipe that info through 
`getAllProcessorFeatures` and have the higher level code know to split 
extensions into sections.

I believe RISC-V is the only backend to have versions and status (at least 
explicitly), but given it motivated the feature in the first place, it should 
be catered for. If we can't handle what RISC-V needs, we've done something 
wrong.

Problem 2 is that this patch is listing backend flags that are never meant to 
be passed in `march` or `mcpu` to clang. For example it's listing 
`call-saved-x10`.
```
$ ./bin/clang --target=aarch64-unknown-linux-gnu -march=armv8-a+call-saved-x10 
/tmp/test.c
clang: error: unsupported argument 'armv8-a+call-saved-x10' to option '-march='
```
It also includes feature names like `apple-a10` which if anything should go in 
`mcpu`, they clearly shouldn't be listed in an option that is showing valid 
options for `-march`.

For AArch64, look at 
https://github.com/llvm/llvm-project/blob/102838d3f6e15a5c510257c2c70fe7faca5b59d6/llvm/include/llvm/TargetParser/AArch64TargetParser.h#L190.
 You cannot pass `+bti` to `-march=` (in this case because we want you to use 
other compiler options to generate these instructions, but that's beside the 
point).

So what your patch produces is kinda like `./bin/clang --target  
-mllvm -mattr=+unknown_name` and getting `Don't understand unknown_name, you 
could have passed .
(and we have had customers ask for exactly that sort of option, but there's a 
reason some can't be passed to clang)

Unfortunately the information of what is valid to be passed to clang is not in 
the same tablegen you're pulling from. It would be nice, and it's not as far 
off a goal as it used to be, but we aren't there yet.

I applaud the instinct to generalise and use a single source of information, 
but one has to consider the current state of affairs and what might be lost by 
moving forward with this.

https://github.com/llvm/llvm-project/pull/66586
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable --print-supported-extensions for all targets (PR #66586)

2023-09-18 Thread Balint Cristian via cfe-commits

cbalint13 wrote:


@DavidSpickett 

Hi David, 

> Thankyou for looking into this, if it can work it's much cleaner than an ever 
> expanding if.
> 
> I think that `getAllProcessorFeatures` may include things that are rejected 
> by `-march`. I will check that for Arm and AArch64. Since the list of 
> features in the target parser may be different than the backend (it's not 
> good but it is what it is).


* I see the important point of ```-march```. 

   To be accurate , we can filter/validate through llvm 
```MCInfo->checkFeatures()``` with respect to the -mcpu (if user provides it, 
otherwise return a full list just like now).

   Something like:
   ```
   $ zcat sample-outputs.log.gz | grep print
   $ ./bin/clang --target=riscv64-unknown-linux-gnu  
--print-supported-extensions
   $ ./bin/clang --target=riscv64-unknown-linux-gnu -mcpu=sifive-x280 
--print-supported-extensions
   $ ./bin/clang --target=x86_64-unknown-linux-gnu --print-supported-extensions
   $ ./bin/clang --target=x86_64-unknown-linux-gnu -mcpu=sandybridge 
--print-supported-extensions
   $ ./bin/clang --target=x86_64-unknown-linux-gnu -mcpu=cascadelake 
--print-supported-extensions
   $ ./bin/clang --target=aarch64-unknown-linux-gnu --print-supported-extensions
   $ ./bin/clang --target=aarch64-unknown-linux-gnu  -mcpu=cortex-a55 
--print-supported-extensions
   ```
   The file with the full log outputs is here: 
[sample-outputs.log.gz](https://github.com/llvm/llvm-project/files/12646975/sample-outputs.log.gz)



> Does this change RISC-V's output? They are (I assume) unique in printing 
> version numbers and ratification status, etc. Assuming it doesn't (which it 
> probably does), it would likely make a few methods in RSIC-V ABI info unused, 
> but deal with that later if so.

* If user provides ```-mcpu``` we can narrow the flags the only to validated 
ones for that target+mcpu, see:

```
$ ./bin/clang --target=riscv64-unknown-linux-gnu -mcpu=sifive-x280 
--print-supported-extensions
All available -march extensions for riscv64 and -mcpu sifive-x280

  64bitImplements RV64
  a'A' (Atomic Instructions)
  c'C' (Compressed Instructions)
  d'D' (Double-Precision Floating-Point)
  dlen-factor-2Vector unit DLEN(data path width) is 
half of VLEN
  f'F' (Single-Precision Floating-Point)
  m'M' (Integer Multiplication and 
Division)
  no-default-unrollDisable default unroll preference.
  short-forward-branch-opt Enable short forward branch 
optimization
  sifive7  SiFive 7-Series processors
  v'V' (Vector Extension for 
Application Processors)
  zba  'Zba' (Address Generation 
Instructions)
  zbb  'Zbb' (Basic Bit-Manipulation)
  zfh  'Zfh' (Half-Precision Floating-Point)
  zfhmin   'Zfhmin' (Half-Precision 
Floating-Point Minimal)
  zicsr'zicsr' (CSRs)
  zifencei 'Zifencei' (fence.i)
  zve32f   'Zve32f' (Vector Extensions for 
Embedded Processors with maximal 32 EEW and F extension)
  zve32x   'Zve32x' (Vector Extensions for 
Embedded Processors with maximal 32 EEW)
  zve64d   'Zve64d' (Vector Extensions for 
Embedded Processors with maximal 64 EEW, F and D extension)
  zve64f   'Zve64f' (Vector Extensions for 
Embedded Processors with maximal 64 EEW and F extension)
  zve64x   'Zve64x' (Vector Extensions for 
Embedded Processors with maximal 64 EEW)
  zvfh 'Zvfh' (Vector Half-Precision 
Floating-Point)
  zvl128b  'Zvl' (Minimum Vector Length) 128
  zvl256b  'Zvl' (Minimum Vector Length) 256
  zvl32b   'Zvl' (Minimum Vector Length) 32
  zvl512b  'Zvl' (Minimum Vector Length) 512
  zvl64b   'Zvl' (Minimum Vector Length) 64

```





In current state this PR prints _all_ flags of target, it is not mcpu aware.
I don't know how to drag into 
[cc1_main()](https://github.com/llvm/llvm-project/blob/08d2ea372ff63156939a439dfb30766d83686764/clang/tools/driver/cc1_main.cpp#L218)
 the user's -mcpu flag from clang's main().

An attempt to do it is here, but propagading down the ```-mcpu``` fails many 
unittests: 

[clang-tools-extra] [llvm][documentation] Fix coroutines documentation (PR #66420)

2023-09-18 Thread Tobias Hieta via cfe-commits

tru wrote:

ping @tstellar - guess it can be a wrong team name / label name?

https://github.com/llvm/llvm-project/pull/66420
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Inliner] Improve attribute propagation to callsites when inlining. (PR #66036)

2023-09-18 Thread Nikita Popov via cfe-commits

nikic wrote:

> > It occurs to me that the current return attribute propagation is currently 
> > buggy for poison-generating attributes: https://llvm.godbolt.org/z/x8n18q9Mj
> > In this case the argument to use() will now be poison as well, while before 
> > inlining only the return value was poison.
> > This code needs to distinguish poison and UB generating attributes.
> 
> Good catch. I think this means basically `nonnull`, `noundef`, and `align` 
> can only be propagated if there are no other uses in to-be-inlined function. 
> That sound right or do you see any more robust way forward?

Limiting poison-generating attributes to one-use while keeping the rest of the 
logic (with guarantee-to-transfer) would be the simplest way to make the 
existing code correct. There are two additional ways to generalize:

 * If the return is also noundef, we don't need one-use.
 * Just one-use is enough for poison-generating, we don't need 
guaranteed-to-transfer, BUT: we need to be careful about an implicit "use" in 
the call itself. That is, if the call we're transfering to is noundef and we 
only check one-use but not guaranteed-to-transfer, we would convert poison into 
UB at that point.

https://github.com/llvm/llvm-project/pull/66036
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable --print-supported-extensions for all targets (PR #66586)

2023-09-18 Thread David Spickett via cfe-commits

DavidSpickett wrote:

One way to check the formats is to add checks for the column titles (if any) 
and first extension listed in `clang/test/Driver/print-supported-extensions.c`, 
to document the existing behaviour. RISC-V calls into it's own ABI info class 
which only has unit tests so if you change things here we won't notice with the 
current tests.

Then you can build this change on top of that, and potentially change RISC-Vs 
format if there is agreement there.

https://github.com/llvm/llvm-project/pull/66586
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [analyzer] Do not use APInt methods on _BitInt() Types (PR #65887)

2023-09-18 Thread via cfe-commits

vabridgers wrote:

The status above shows 1 change requested, but I believe I've resolved the 
requested changes. Please review at your convenience. Thank you.

https://github.com/llvm/llvm-project/pull/65887
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [llvm][documentation] Fix coroutines documentation (PR #66420)

2023-09-18 Thread Chuanqi Xu via cfe-commits

https://github.com/ChuanqiXu9 closed 
https://github.com/llvm/llvm-project/pull/66420
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable --print-supported-extensions for all targets (PR #66586)

2023-09-18 Thread David Spickett via cfe-commits

DavidSpickett wrote:

Thankyou for looking into this, if it can work it's much cleaner than an ever 
expanding if.

I think that `getAllProcessorFeatures` my include things that are rejected by 
`-march`. I will check that for Arm and AArch64. Since the list of features in 
the target parser may be different than the backend (it's not good but it is 
what it is).

Does this change RISC-V's output? They are (I assume) unique in printing 
version numbers and ratification status, etc. Assuming it doesn't (which it 
probably does), it would likely make a few methods in RSIC-V ABI info unused, 
but deal with that later if so.

https://github.com/llvm/llvm-project/pull/66586
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [llvm][documentation] Fix coroutines documentation (PR #66420)

2023-09-18 Thread Chuanqi Xu via cfe-commits

https://github.com/ChuanqiXu9 updated 
https://github.com/llvm/llvm-project/pull/66420

>From 71c5d851d2b14022434fb6533ec7418ee00751c2 Mon Sep 17 00:00:00 2001
From: NoodleSugar 
Date: Tue, 12 Sep 2023 12:39:13 +0200
Subject: [PATCH] [llvm][documentation] Fix coroutines documentation

---
 llvm/docs/Coroutines.rst | 25 +++--
 1 file changed, 15 insertions(+), 10 deletions(-)

diff --git a/llvm/docs/Coroutines.rst b/llvm/docs/Coroutines.rst
index 46dc2dcbee18276..96bc7003b68e984 100644
--- a/llvm/docs/Coroutines.rst
+++ b/llvm/docs/Coroutines.rst
@@ -372,7 +372,7 @@ execution of the coroutine until a suspend point is reached:
 store void (%f.frame*)* @f.destroy, void (%f.frame*)** %2
 
 %inc = add nsw i32 %n, 1
-%inc.spill.addr = getelementptr inbounds %f.Frame, %f.Frame* %FramePtr, 
i32 0, i32 2
+%inc.spill.addr = getelementptr inbounds %f.frame, %f.frame* %frame, i32 
0, i32 2
 store i32 %inc, i32* %inc.spill.addr
 call void @print(i32 %n)
 
@@ -387,7 +387,7 @@ Outlined resume part of the coroutine will reside in 
function `f.resume`:
   entry:
 %inc.spill.addr = getelementptr %f.frame, %f.frame* %frame.ptr.resume, i64 
0, i32 2
 %inc.spill = load i32, i32* %inc.spill.addr, align 4
-%inc = add i32 %n.val, 1
+%inc = add i32 %inc.spill, 1
 store i32 %inc, i32* %inc.spill.addr, align 4
 tail call void @print(i32 %inc)
 ret void
@@ -497,23 +497,28 @@ as the code in the previous section):
   i8 1, label %cleanup]
 
 In this case, the coroutine frame would include a suspend index that will
-indicate at which suspend point the coroutine needs to resume. The resume
-function will use an index to jump to an appropriate basic block and will look
+indicate at which suspend point the coroutine needs to resume.
+
+.. code-block:: llvm
+
+  %f.frame = type { ptr, ptr, i32, i32 }
+
+The resume function will use an index to jump to an appropriate basic block 
and will look
 as follows:
 
 .. code-block:: llvm
 
-  define internal fastcc void @f.Resume(%f.Frame* %FramePtr) {
-  entry.Resume:
-%index.addr = getelementptr inbounds %f.Frame, %f.Frame* %FramePtr, i64 0, 
i32 2
+  define internal fastcc void @f.resume(%f.frame* %FramePtr) {
+  entry.resume:
+%index.addr = getelementptr inbounds %f.frame, %f.frame* %FramePtr, i64 0, 
i32 2
 %index = load i8, i8* %index.addr, align 1
 %switch = icmp eq i8 %index, 0
-%n.addr = getelementptr inbounds %f.Frame, %f.Frame* %FramePtr, i64 0, i32 
3
+%n.addr = getelementptr inbounds %f.frame, %f.frame* %FramePtr, i64 0, i32 
3
 %n = load i32, i32* %n.addr, align 4
 br i1 %switch, label %loop.resume, label %loop
 
   loop.resume:
-%sub = xor i32 %n, -1
+%sub = sub nsw i32 0, %n
 call void @print(i32 %sub)
 br label %suspend
   loop:
@@ -589,7 +594,7 @@ correct resume point):
 %save2 = call token @llvm.coro.save(i8* %hdl)
 call void @async_op2(i8* %hdl)
 %suspend2 = call i1 @llvm.coro.suspend(token %save2, i1 false)
-switch i8 %suspend1, label %suspend [i8 0, label %resume2
+switch i8 %suspend2, label %suspend [i8 0, label %resume2
  i8 1, label %cleanup]
 
 .. _coroutine promise:

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang] [C23] Fix crash with _BitInt running clang-tidy (PR #65889)

2023-09-18 Thread via cfe-commits

vabridgers wrote:

The status above is showing 1 change requested, but I think I've addressed all 
comments. Please review at your convenience. Thank you.

https://github.com/llvm/llvm-project/pull/65889
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [analyzer] Do not use APInt methods on _BitInt() Types (PR #65887)

2023-09-18 Thread via cfe-commits

https://github.com/vabridgers resolved 
https://github.com/llvm/llvm-project/pull/65887
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Update llvmlibc-implementation-in-namespace to new rules (PR #66504)

2023-09-18 Thread Piotr Zegar via cfe-commits

PiotrZSL wrote:

> Where would that be? `clang-tools-extra/docs/ReleaseNotes.rst`? I can't find 
> what the current release notes look like for head.

Yes, it's deployed here: https://clang.llvm.org/extra/ReleaseNotes.html



https://github.com/llvm/llvm-project/pull/66504
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157526: [clang][Sema] Remove irrelevant diagnostics from constraint satisfaction failure

2023-09-18 Thread Takuya Shimizu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb2cd9db58933: [clang][Sema] Remove irrelevant diagnostics 
from constraint satisfaction failure (authored by hazohelet).

Changed prior to commit:
  https://reviews.llvm.org/D157526?vs=556227=556936#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D157526/new/

https://reviews.llvm.org/D157526

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaConcept.cpp
  clang/test/SemaTemplate/concepts.cpp


Index: clang/test/SemaTemplate/concepts.cpp
===
--- clang/test/SemaTemplate/concepts.cpp
+++ clang/test/SemaTemplate/concepts.cpp
@@ -994,3 +994,40 @@
 }
 
 }
+
+namespace GH54678 {
+template
+concept True = true;
+
+template
+concept False = false; // expected-note 9 {{'false' evaluated to false}}
+
+template
+concept Irrelevant = false;
+
+template 
+concept ErrorRequires = requires(ErrorRequires auto x) { x; }; // 
expected-error {{unknown type name 'ErrorRequires'}}
+
+template void aaa(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (False || False) || False {} // expected-note 3 {{'int' does 
not satisfy 'False'}}
+template void bbb(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (False || False) && True {} // expected-note 2 {{'long' does 
not satisfy 'False'}}
+template void ccc(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (True || Irrelevant) && False {} // expected-note 
{{'unsigned long' does not satisfy 'False'}}
+template void ddd(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (Irrelevant || True) && False {} // expected-note {{'int' 
does not satisfy 'False'}}
+template void eee(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (Irrelevant || Irrelevant || True) && False {} // 
expected-note {{'long' does not satisfy 'False'}}
+
+template void fff(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires((ErrorRequires || False || True) && False) {} // 
expected-note {{'unsigned long' does not satisfy 'False'}}
+
+void test() {
+aaa(42); // expected-error {{no matching function}}
+bbb(42L); // expected-error{{no matching function}}
+ccc(42UL); // expected-error {{no matching function}}
+ddd(42); // expected-error {{no matching function}}
+eee(42L); // expected-error {{no matching function}}
+fff(42UL); // expected-error {{no matching function}}
+}
+}
Index: clang/lib/Sema/SemaConcept.cpp
===
--- clang/lib/Sema/SemaConcept.cpp
+++ clang/lib/Sema/SemaConcept.cpp
@@ -185,6 +185,7 @@
   ConstraintExpr = ConstraintExpr->IgnoreParenImpCasts();
 
   if (LogicalBinOp BO = ConstraintExpr) {
+auto EffectiveDetailEnd = Satisfaction.Details.end();
 ExprResult LHSRes = calculateConstraintSatisfaction(
 S, BO.getLHS(), Satisfaction, Evaluator);
 
@@ -218,6 +219,19 @@
 if (RHSRes.isInvalid())
   return ExprError();
 
+bool IsRHSSatisfied = Satisfaction.IsSatisfied;
+// Current implementation adds diagnostic information about the falsity
+// of each false atomic constraint expression when it evaluates them.
+// When the evaluation results to `false || true`, the information
+// generated during the evaluation of left-hand side is meaningless
+// because the whole expression evaluates to true.
+// The following code removes the irrelevant diagnostic information.
+// FIXME: We should probably delay the addition of diagnostic information
+// until we know the entire expression is false.
+if (BO.isOr() && IsRHSSatisfied)
+  Satisfaction.Details.erase(EffectiveDetailEnd,
+ Satisfaction.Details.end());
+
 return BO.recreateBinOp(S, LHSRes, RHSRes);
   }
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -169,6 +169,9 @@
   Also clang no longer emits false positive warnings about the output length of
   ``%g`` format specifier and about ``%o, %x, %X`` with ``#`` flag.
 - Clang now emits ``-Wcast-qual`` for functional-style cast expressions.
+- Clang no longer emits irrelevant notes about unsatisfied constraint 
expressions
+  on the left-hand side of ``||`` when the right-hand side constraint is 
satisfied.
+  (`#54678: `_).
 
 Bug Fixes in This Version
 -


Index: clang/test/SemaTemplate/concepts.cpp
===
--- clang/test/SemaTemplate/concepts.cpp
+++ 

[clang] b2cd9db - [clang][Sema] Remove irrelevant diagnostics from constraint satisfaction failure

2023-09-18 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-09-18T18:14:44+09:00
New Revision: b2cd9db589335d5885c04df83003a623cf2f05ff

URL: 
https://github.com/llvm/llvm-project/commit/b2cd9db589335d5885c04df83003a623cf2f05ff
DIFF: 
https://github.com/llvm/llvm-project/commit/b2cd9db589335d5885c04df83003a623cf2f05ff.diff

LOG: [clang][Sema] Remove irrelevant diagnostics from constraint satisfaction 
failure

BEFORE this patch, when clang handles constraints like C1 || C2 where C1 
evaluates to false and C2 evaluates to true, it emitted irrelevant diagnostics 
about the falsity of C1.
This patch removes the irrelevant diagnostic information generated during the 
evaluation of C1 if C2 evaluates to true.

Fixes https://github.com/llvm/llvm-project/issues/54678

Reviewed By: erichkeane
Differential Revision: https://reviews.llvm.org/D157526

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaConcept.cpp
clang/test/SemaTemplate/concepts.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d47d664c062c204..500f9c9a0cda741 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -169,6 +169,9 @@ Improvements to Clang's diagnostics
   Also clang no longer emits false positive warnings about the output length of
   ``%g`` format specifier and about ``%o, %x, %X`` with ``#`` flag.
 - Clang now emits ``-Wcast-qual`` for functional-style cast expressions.
+- Clang no longer emits irrelevant notes about unsatisfied constraint 
expressions
+  on the left-hand side of ``||`` when the right-hand side constraint is 
satisfied.
+  (`#54678: `_).
 
 Bug Fixes in This Version
 -

diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index d1fa8e7831225b7..dacdd07c8069950 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -185,6 +185,7 @@ calculateConstraintSatisfaction(Sema , const Expr 
*ConstraintExpr,
   ConstraintExpr = ConstraintExpr->IgnoreParenImpCasts();
 
   if (LogicalBinOp BO = ConstraintExpr) {
+auto EffectiveDetailEnd = Satisfaction.Details.end();
 ExprResult LHSRes = calculateConstraintSatisfaction(
 S, BO.getLHS(), Satisfaction, Evaluator);
 
@@ -218,6 +219,19 @@ calculateConstraintSatisfaction(Sema , const Expr 
*ConstraintExpr,
 if (RHSRes.isInvalid())
   return ExprError();
 
+bool IsRHSSatisfied = Satisfaction.IsSatisfied;
+// Current implementation adds diagnostic information about the falsity
+// of each false atomic constraint expression when it evaluates them.
+// When the evaluation results to `false || true`, the information
+// generated during the evaluation of left-hand side is meaningless
+// because the whole expression evaluates to true.
+// The following code removes the irrelevant diagnostic information.
+// FIXME: We should probably delay the addition of diagnostic information
+// until we know the entire expression is false.
+if (BO.isOr() && IsRHSSatisfied)
+  Satisfaction.Details.erase(EffectiveDetailEnd,
+ Satisfaction.Details.end());
+
 return BO.recreateBinOp(S, LHSRes, RHSRes);
   }
 

diff  --git a/clang/test/SemaTemplate/concepts.cpp 
b/clang/test/SemaTemplate/concepts.cpp
index 9776ddbb372991e..891b45aa5789296 100644
--- a/clang/test/SemaTemplate/concepts.cpp
+++ b/clang/test/SemaTemplate/concepts.cpp
@@ -994,3 +994,40 @@ void test_params() {
 }
 
 }
+
+namespace GH54678 {
+template
+concept True = true;
+
+template
+concept False = false; // expected-note 9 {{'false' evaluated to false}}
+
+template
+concept Irrelevant = false;
+
+template 
+concept ErrorRequires = requires(ErrorRequires auto x) { x; }; // 
expected-error {{unknown type name 'ErrorRequires'}}
+
+template void aaa(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (False || False) || False {} // expected-note 3 {{'int' does 
not satisfy 'False'}}
+template void bbb(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (False || False) && True {} // expected-note 2 {{'long' does 
not satisfy 'False'}}
+template void ccc(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (True || Irrelevant) && False {} // expected-note 
{{'unsigned long' does not satisfy 'False'}}
+template void ddd(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (Irrelevant || True) && False {} // expected-note {{'int' 
does not satisfy 'False'}}
+template void eee(T t) // expected-note {{candidate template ignored: 
constraints not satisfied}}
+requires (Irrelevant || Irrelevant || True) && False {} // 
expected-note {{'long' does not satisfy 'False'}}
+
+template void fff(T t) // expected-note 

[PATCH] D158595: [clang][Interp] Allow zero-init of primitives with an empty init list

2023-09-18 Thread Timm Bäder via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG52a55a717838: [clang][Interp] Allow zero-init of primitives 
with an empty init list (authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158595/new/

https://reviews.llvm.org/D158595

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/test/AST/Interp/literals.cpp


Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -91,6 +91,15 @@
// ref-error {{not an integral constant 
expression}} \
// ref-note {{outside the range of 
representable values}} \
 
+namespace PrimitiveEmptyInitList {
+  constexpr int a = {};
+  static_assert(a == 0, "");
+  constexpr bool b = {};
+  static_assert(!b, "");
+  constexpr double d = {};
+  static_assert(d == 0.0, "");
+}
+
 
 enum E {};
 constexpr E e = static_cast(0);
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -571,8 +571,10 @@
 
   // Primitive values.
   if (std::optional T = classify(E->getType())) {
-assert(E->getNumInits() == 1);
 assert(!DiscardResult);
+if (E->getNumInits() == 0)
+  return this->visitZeroInitializer(E->getType(), E);
+assert(E->getNumInits() == 1);
 return this->delegate(E->inits()[0]);
   }
 


Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -91,6 +91,15 @@
// ref-error {{not an integral constant expression}} \
// ref-note {{outside the range of representable values}} \
 
+namespace PrimitiveEmptyInitList {
+  constexpr int a = {};
+  static_assert(a == 0, "");
+  constexpr bool b = {};
+  static_assert(!b, "");
+  constexpr double d = {};
+  static_assert(d == 0.0, "");
+}
+
 
 enum E {};
 constexpr E e = static_cast(0);
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -571,8 +571,10 @@
 
   // Primitive values.
   if (std::optional T = classify(E->getType())) {
-assert(E->getNumInits() == 1);
 assert(!DiscardResult);
+if (E->getNumInits() == 0)
+  return this->visitZeroInitializer(E->getType(), E);
+assert(E->getNumInits() == 1);
 return this->delegate(E->inits()[0]);
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 52a55a7 - [clang][Interp] Allow zero-init of primitives with an empty init list

2023-09-18 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-09-18T11:09:30+02:00
New Revision: 52a55a7178381c7ac2b46155f2cc000dac48f2d4

URL: 
https://github.com/llvm/llvm-project/commit/52a55a7178381c7ac2b46155f2cc000dac48f2d4
DIFF: 
https://github.com/llvm/llvm-project/commit/52a55a7178381c7ac2b46155f2cc000dac48f2d4.diff

LOG: [clang][Interp] Allow zero-init of primitives with an empty init list

Differential Revision: https://reviews.llvm.org/D158595

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/test/AST/Interp/literals.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 823bef7a8c19e11..c813f9b6d9991c5 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -571,8 +571,10 @@ bool ByteCodeExprGen::VisitInitListExpr(const 
InitListExpr *E) {
 
   // Primitive values.
   if (std::optional T = classify(E->getType())) {
-assert(E->getNumInits() == 1);
 assert(!DiscardResult);
+if (E->getNumInits() == 0)
+  return this->visitZeroInitializer(E->getType(), E);
+assert(E->getNumInits() == 1);
 return this->delegate(E->inits()[0]);
   }
 

diff  --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index 562090d46b094d9..ceda59405ea9105 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -91,6 +91,15 @@ static_assert(-(1 << 31), ""); // expected-error {{not an 
integral constant expr
// ref-error {{not an integral constant 
expression}} \
// ref-note {{outside the range of 
representable values}} \
 
+namespace PrimitiveEmptyInitList {
+  constexpr int a = {};
+  static_assert(a == 0, "");
+  constexpr bool b = {};
+  static_assert(!b, "");
+  constexpr double d = {};
+  static_assert(d == 0.0, "");
+}
+
 
 enum E {};
 constexpr E e = static_cast(0);



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [Sema] add cast from IncompleteArrayType to ConstantArrayType in TryReferenceListInitialization (PR #65918)

2023-09-18 Thread Mariya Podchishchaeva via cfe-commits


@@ -4532,6 +4532,15 @@ static void TryReferenceListInitialization(Sema ,
   if (T1Quals.hasAddressSpace())
 Sequence.AddQualificationConversionStep(
 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
+  else if (S.getLangOpts().CPlusPlus20 &&
+   isa(T1->getUnqualifiedDesugaredType()) &&
+   DestType->isRValueReferenceType()) {
+// [dcl.init.list] p3.10
+// unless T is “reference to array of unknown bound of U”, in which 
case
+// the type of the prvalue is the type of x in the declaration U x[] H,
+// where H is the initializer list.
+Sequence.AddQualificationConversionStep(cv1T1, VK_XValue);

Fznamznon wrote:

@HerrCai0907 I see what you mean and what the patch accomplishes. But my 
confusion was, why in order to do that `AddQualificationConversionStep` is 
called? IMO this is just to convert cv-qualifiers. The goal is to convert one 
array type to another, right?

https://github.com/llvm/llvm-project/pull/65918
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Sema] add cast from IncompleteArrayType to ConstantArrayType in TryReferenceListInitialization (PR #65918)

2023-09-18 Thread Mariya Podchishchaeva via cfe-commits


@@ -4532,6 +4532,15 @@ static void TryReferenceListInitialization(Sema ,
   if (T1Quals.hasAddressSpace())
 Sequence.AddQualificationConversionStep(
 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
+  else if (S.getLangOpts().CPlusPlus20 &&
+   isa(T1->getUnqualifiedDesugaredType()) &&
+   DestType->isRValueReferenceType()) {
+// [dcl.init.list] p3.10
+// unless T is “reference to array of unknown bound of U”, in which 
case
+// the type of the prvalue is the type of x in the declaration U x[] H,
+// where H is the initializer list.
+Sequence.AddQualificationConversionStep(cv1T1, VK_XValue);

Fznamznon wrote:

@HerrCai0907 I see what you mean and what the patch accomplishes. But my 
confusion was, why in order to do that `AddQualificationConversionStep` is 
called? IMO this is just to convert cv-qualifiers. The goal is to convert one 
array type to another, right?

https://github.com/llvm/llvm-project/pull/65918
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Driver][NVPTX] Add a warning that device debug info does not work with optimizations (PR #65327)

2023-09-18 Thread Georgi Mirazchiyski via cfe-commits

GeorgeWeb wrote:

@Artem-B Hi, sorry for the direct ping. I was just wondering if it's okay to 
take a quick look at this patch. 
(Didn't know how to ping folks subscribed to clang-driver).
Thanks!  

https://github.com/llvm/llvm-project/pull/65327
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


<    1   2   3   4   5   >