[PATCH] D136545: [Clang] use non-instantiated function declaration for constraints partial ordering

2022-10-30 Thread Yuanfang Chen via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe18c2c5548f6: [Clang] use non-instantiated function 
declaration for constraints partial… (authored by ychen).

Changed prior to commit:
  https://reviews.llvm.org/D136545?vs=470546=471902#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136545

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaConcept.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/test/CXX/over/over.match/over.match.best/p2.cpp
  clang/test/CXX/temp/temp.constr/temp.constr.order/non-template-functions.cpp

Index: clang/test/CXX/temp/temp.constr/temp.constr.order/non-template-functions.cpp
===
--- /dev/null
+++ clang/test/CXX/temp/temp.constr/temp.constr.order/non-template-functions.cpp
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -std=c++2a -x c++ -verify %s
+// expected-no-diagnostics
+
+template
+constexpr static bool is_same_v = false;
+
+template
+constexpr static bool is_same_v = true;
+
+namespace PR56154 {
+  template  concept C0 = (N == 0);
+  template  concept C0x = C0;
+  template  concept C00 = C0x && C0;
+
+  template
+  struct A {
+void f() requires C00;
+void f() requires C0x = delete;
+
+static short g() requires C00;
+static int g() requires C0x;
+  };
+  void h(A<0, 0> a) {
+a.f();
+static_assert(is_same_v::g), short(*)()>);
+  }
+}
Index: clang/test/CXX/over/over.match/over.match.best/p2.cpp
===
--- clang/test/CXX/over/over.match/over.match.best/p2.cpp
+++ clang/test/CXX/over/over.match/over.match.best/p2.cpp
@@ -7,7 +7,11 @@
 bool operator<(const A&) const & requires X; // #1
 int operator<=>(const A&) const & requires X && X = delete; // #2
   };
-  bool k1 = A() < A(); // not ordered by constraints: prefer non-rewritten form
+  bool k1 = A() < A(); // prefer more-constrained 'operator<=>'
+  // expected-error@-1 {{deleted}}
+  // expected-note@#1 {{candidate}}
+  // expected-note@#2 {{candidate function has been explicitly deleted}}
+  // expected-note@#2 {{candidate function (with reversed parameter order) has been explicitly deleted}}
   bool k2 = A() < A(); // prefer more-constrained 'operator<=>'
   // expected-error@-1 {{deleted}}
   // expected-note@#1 {{candidate}}
Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -10039,13 +10039,20 @@
   //  parameter-type-lists, and F1 is more constrained than F2 [...],
   if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
   sameFunctionParameterTypeLists(S, Cand1, Cand2)) {
-const Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
-const Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
+FunctionDecl *Function1 = Cand1.Function;
+FunctionDecl *Function2 = Cand2.Function;
+if (FunctionDecl *MF = Function1->getInstantiatedFromMemberFunction())
+  Function1 = MF;
+if (FunctionDecl *MF = Function2->getInstantiatedFromMemberFunction())
+  Function2 = MF;
+
+const Expr *RC1 = Function1->getTrailingRequiresClause();
+const Expr *RC2 = Function2->getTrailingRequiresClause();
 if (RC1 && RC2) {
   bool AtLeastAsConstrained1, AtLeastAsConstrained2;
-  if (S.IsAtLeastAsConstrained(Cand1.Function, RC1, Cand2.Function, RC2,
+  if (S.IsAtLeastAsConstrained(Function1, RC1, Function2, RC2,
AtLeastAsConstrained1) ||
-  S.IsAtLeastAsConstrained(Cand2.Function, RC2, Cand1.Function, RC1,
+  S.IsAtLeastAsConstrained(Function2, RC2, Function1, RC1,
AtLeastAsConstrained2))
 return false;
   if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
@@ -12630,20 +12637,24 @@
   DeclAccessPair DAP;
   SmallVector AmbiguousDecls;
 
-  auto CheckMoreConstrained =
-  [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional {
-SmallVector AC1, AC2;
-FD1->getAssociatedConstraints(AC1);
-FD2->getAssociatedConstraints(AC2);
-bool AtLeastAsConstrained1, AtLeastAsConstrained2;
-if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
-  return None;
-if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
-  return None;
-if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
-  return None;
-return AtLeastAsConstrained1;
-  };
+  auto CheckMoreConstrained = [&](FunctionDecl *FD1,
+  FunctionDecl *FD2) -> Optional {
+if (FunctionDecl *MF = FD1->getInstantiatedFromMemberFunction())
+  FD1 = MF;
+if (FunctionDecl *MF = FD2->getInstantiatedFromMemberFunction())
+  FD2 = MF;
+

[PATCH] D136744: [Clang] perform "maximum TLS alignment" check for template instantiation

2022-10-30 Thread Yuanfang Chen 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 rG5d086cce8b92: [Clang] perform maximum TLS 
alignment check for template instantiation (authored by ychen).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136744

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/Sema/tls_alignment.cpp

Index: clang/test/Sema/tls_alignment.cpp
===
--- clang/test/Sema/tls_alignment.cpp
+++ clang/test/Sema/tls_alignment.cpp
@@ -58,27 +58,34 @@
bar5.some_data[5];
 }
 
-
-// Verify alignment check where a dependent type is involved.
-// The check is (correctly) not performed on "t", but the check still is
-// performed on the structure as a whole once it has been instantiated.
-
 template struct templated_tls {
 static __thread T t;
 T other_t __attribute__(( aligned(64) ));
 };
-__thread templated_tls blah; // expected-error{{alignment (64) of thread-local variable}}
-
-int blag() {
-return blah.other_t * 2;
-}
+ __thread templated_tls blah; // expected-error{{alignment (64) of thread-local variable}}
 
-
-// Verify alignment check where the alignment is a template parameter.
-// The check is only performed during instantiation.
 template 
 struct S {
+  struct alignas(64) B {};
+  struct alignas(N) C {};
+  static inline void f() {
+thread_local B b; // expected-error{{alignment (64) of thread-local variable}}
+thread_local C c; // expected-error{{alignment (64) of thread-local variable}}
+  }
+  template static inline thread_local int b alignas(J) = J; // expected-error{{alignment (64) of thread-local variable}}
   static int __thread __attribute__((aligned(N))) x; // expected-error{{alignment (64) of thread-local variable}}
 };
 
-S<64> s_instance; // expected-note{{in instantiation of template class 'S<64>' requested here}}
+int blag() {
+// Verify alignment check where the alignment is a template parameter.
+// The check is only performed during instantiation.
+S<64> s_instance; // expected-note{{in instantiation of template class 'S<64>' requested here}}
+
+// Verify alignment for dependent local variables.
+S<64>::f(); // expected-note{{in instantiation of member function 'S<64>::f' requested here}}
+
+// Verify alignment check where a dependent type is involved.
+// The check is (correctly) not performed on "t", but the check still is
+// performed on the structure as a whole once it has been instantiated.
+return blah.other_t * 2 + S<64>::b<64>; // expected-note{{in instantiation of static data member 'S<64>::b' requested here}}
+}
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -1179,6 +1179,9 @@
   if (Var->isStaticLocal())
 SemaRef.CheckStaticLocalForDllExport(Var);
 
+  if (Var->getTLSKind())
+SemaRef.CheckThreadLocalForLargeAlignment(Var);
+
   return Var;
 }
 
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -4341,7 +4341,7 @@
   }
 
   const auto *VD = dyn_cast(D);
-  if (VD && Context.getTargetInfo().isTLSSupported()) {
+  if (VD) {
 unsigned MaxTLSAlign =
 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
 .getQuantity();
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -14032,6 +14032,26 @@
   }
 }
 
+void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
+  assert(VD->getTLSKind());
+
+  // Perform TLS alignment check here after attributes attached to the variable
+  // which may affect the alignment have been processed. Only perform the check
+  // if the target has a maximum TLS alignment (zero means no constraints).
+  if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
+// Protect the check so that it's not performed on dependent types and
+// dependent alignments (we can't determine the alignment in that case).
+if (!VD->hasDependentAlignment()) {
+  CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
+  if (Context.getDeclAlign(VD) > MaxAlignChars) {
+Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
+<< (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
+<< (unsigned)MaxAlignChars.getQuantity();
+  }
+}
+  }
+}
+
 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to 

[clang] e18c2c5 - [Clang] use non-instantiated function declaration for constraints partial ordering

2022-10-30 Thread Yuanfang Chen via cfe-commits

Author: Yuanfang Chen
Date: 2022-10-30T22:39:47-07:00
New Revision: e18c2c5548f6864def4a110239395a18afc195d6

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

LOG: [Clang] use non-instantiated function declaration for constraints partial 
ordering

Per wordings in
- https://eel.is/c++draft/over.match#best.general-2.6
- https://eel.is/c++draft/temp.constr.order
- https://eel.is/c++draft/temp.constr#atomic-1

constraints partial ordering should use the unsubstituted template
parameters of the constrained entity, not the instantiated entity.

Fix #56154

Reviewed By: erichkeane, royjacobson, mizvekov

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

Added: 
clang/test/CXX/temp/temp.constr/temp.constr.order/non-template-functions.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaOverload.cpp
clang/test/CXX/over/over.match/over.match.best/p2.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index bd4c0bf7fa0c0..641f75eeeb64c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -264,6 +264,8 @@ Bug Fixes
   constraint, which re-evaluated the same constraint.
   `Issue 53213 `_
   `Issue 45736 `_
+- Fix an issue when performing constraints partial ordering on non-template
+  functions. `Issue 56154 `_
 
 Improvements to Clang's diagnostics
 ^^^

diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index d3d87c8354aea..54d8a746fa247 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -1300,6 +1300,18 @@ bool Sema::IsAtLeastAsConstrained(NamedDecl *D1,
   NamedDecl *D2,
   MutableArrayRef AC2,
   bool ) {
+  if (const auto *FD1 = dyn_cast(D1)) {
+auto IsExpectedEntity = [](const FunctionDecl *FD) {
+  FunctionDecl::TemplatedKind Kind = FD->getTemplatedKind();
+  return Kind == FunctionDecl::TK_NonTemplate ||
+ Kind == FunctionDecl::TK_FunctionTemplate;
+};
+const auto *FD2 = dyn_cast(D2);
+assert(IsExpectedEntity(FD1) && FD2 && IsExpectedEntity(FD2) &&
+   "use non-instantiated function declaration for constraints partial "
+   "ordering");
+  }
+
   if (AC1.empty()) {
 Result = AC2.empty();
 return false;

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 686a126968e8a..a164d9af8f34a 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -18218,13 +18218,20 @@ static void SetEligibleMethods(Sema , CXXRecordDecl 
*Record,
 if (!SatisfactionStatus[i])
   continue;
 CXXMethodDecl *Method = Methods[i];
-const Expr *Constraints = Method->getTrailingRequiresClause();
+CXXMethodDecl *OrigMethod = Method;
+if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
+  OrigMethod = cast(MF);
+
+const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
 bool AnotherMethodIsMoreConstrained = false;
 for (size_t j = 0; j < Methods.size(); j++) {
   if (i == j || !SatisfactionStatus[j])
 continue;
   CXXMethodDecl *OtherMethod = Methods[j];
-  if (!AreSpecialMemberFunctionsSameKind(S.Context, Method, OtherMethod,
+  if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
+OtherMethod = cast(MF);
+
+  if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, 
OtherMethod,
  CSM))
 continue;
 
@@ -18235,7 +18242,7 @@ static void SetEligibleMethods(Sema , CXXRecordDecl 
*Record,
 AnotherMethodIsMoreConstrained = true;
 break;
   }
-  if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, Method,
+  if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
{Constraints},
AnotherMethodIsMoreConstrained)) {
 // There was an error with the constraints comparison. Exit the loop

diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index d21de7db3f53b..45bca3a31d3a7 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -10039,13 +10039,20 @@ bool clang::isBetterOverloadCandidate(
   //  parameter-type-lists, and F1 is more constrained than F2 [...],
   if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
   sameFunctionParameterTypeLists(S, 

[clang] 5d086cc - [Clang] perform "maximum TLS alignment" check for template instantiation

2022-10-30 Thread Yuanfang Chen via cfe-commits

Author: Yuanfang Chen
Date: 2022-10-30T22:39:47-07:00
New Revision: 5d086cce8b92680a2cdadf1f07d4267cd374122e

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

LOG: [Clang] perform "maximum TLS alignment" check for template instantiation

follow up 
https://github.com/llvm/llvm-project/commit/d30e2eefc3cf8dfd2210aefd62f13a6e7c011b43

Reviewed By: mizvekov

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

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/Sema/tls_alignment.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index b32dfe158c8f3..23b4e3f60cef1 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3013,6 +3013,7 @@ class Sema final {
   void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
   void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
   void CheckStaticLocalForDllExport(VarDecl *VD);
+  void CheckThreadLocalForLargeAlignment(VarDecl *VD);
   void FinalizeDeclaration(Decl *D);
   DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec ,
  ArrayRef Group);

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 19bd670e791bc..686a126968e8a 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -14032,6 +14032,26 @@ void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
   }
 }
 
+void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
+  assert(VD->getTLSKind());
+
+  // Perform TLS alignment check here after attributes attached to the variable
+  // which may affect the alignment have been processed. Only perform the check
+  // if the target has a maximum TLS alignment (zero means no constraints).
+  if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
+// Protect the check so that it's not performed on dependent types and
+// dependent alignments (we can't determine the alignment in that case).
+if (!VD->hasDependentAlignment()) {
+  CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
+  if (Context.getDeclAlign(VD) > MaxAlignChars) {
+Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
+<< (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
+<< (unsigned)MaxAlignChars.getQuantity();
+  }
+}
+  }
+}
+
 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
 /// any semantic actions necessary after any initializer has been attached.
 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
@@ -14075,25 +14095,12 @@ void Sema::FinalizeDeclaration(Decl *ThisDecl) {
 
   checkAttributesAfterMerging(*this, *VD);
 
-  // Perform TLS alignment check here after attributes attached to the variable
-  // which may affect the alignment have been processed. Only perform the check
-  // if the target has a maximum TLS alignment (zero means no constraints).
-  if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
-// Protect the check so that it's not performed on dependent types and
-// dependent alignments (we can't determine the alignment in that case).
-if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
-  CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
-  if (Context.getDeclAlign(VD) > MaxAlignChars) {
-Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
-  << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
-  << (unsigned)MaxAlignChars.getQuantity();
-  }
-}
-  }
-
   if (VD->isStaticLocal())
 CheckStaticLocalForDllExport(VD);
 
+  if (VD->getTLSKind())
+CheckThreadLocalForLargeAlignment(VD);
+
   // Perform check for initializers of device-side global variables.
   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
   // 7.5). We must also apply the same checks to all __shared__

diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index d8dd1ab8e1d17..da9aa611793f9 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -4341,7 +4341,7 @@ void Sema::AddAlignedAttr(Decl *D, const 
AttributeCommonInfo , Expr *E,
   }
 
   const auto *VD = dyn_cast(D);
-  if (VD && Context.getTargetInfo().isTLSSupported()) {
+  if (VD) {
 unsigned MaxTLSAlign =
 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
 .getQuantity();

diff  --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index e034094431bb7..49be412df64c0 100644
--- 

[PATCH] D137020: [clang][AST] Handle variable declaration with unknown typedef in C

2022-10-30 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added subscribers: aaron.ballman, shafik.
shafik added a comment.

CC @aaron.ballman


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137020

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


[PATCH] D136815: [clang][Interp] Unify visiting variable declarations

2022-10-30 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added inline comments.



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:803
+  // Make sure we don't accidentally register the same decl twice.
+  if (const Decl *VD = Src.dyn_cast(); VD && isa(VD)) 
{
+assert(!P.getGlobal(cast(VD)));

Nitpick, I find using `VD` a bit confusing since we don't know if it is a 
`ValueDecl` until after it is initialized. 



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:1154
+
+if (!GlobalIndex)
+  return this->bail(VD);

I wonder if the code in both branches might be better factored out into their 
own functions and perhaps move the ` DeclScope LocalScope(this, VD);` 
out.



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.h:282
+  bool isGlobalDecl(const VarDecl *VD) const {
+return !VD->hasLocalStorage() || VD->isConstexpr();
+  }

Why not `hasGlobalStorage()`?

Also what is the logic behind `isConstexpr()` check?


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

https://reviews.llvm.org/D136815

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


[PATCH] D136925: [clangd] Index scoped enums for code completion

2022-10-30 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added inline comments.



Comment at: clang-tools-extra/clangd/CodeComplete.cpp:2133
   if (const auto *EnumDecl = dyn_cast(ND.getDeclContext()))
-return InTopLevelScope(*EnumDecl) && !EnumDecl->isScoped();
 

tom-anders wrote:
> nridge wrote:
> > Just to make sure I understand:
> > 
> > By also removing the `!isScoped()` condition, in addition to changing the 
> > behaviour for the scenario described in 
> > https://github.com/clangd/clangd/issues/1082 (enum declared at class 
> > scope), you are also changing the behaviour for scenarios like this:
> > 
> > ```
> > enum class Foo { Bar };  // at any scope, including global
> > ```
> > 
> > Completing `Bar` will now offer `Foo::Bar` when previously it didn't.
> > 
> > Is this your intention?
> Ah sorry, that is indeed not what I described in the issue - but yeah this 
> change is intended here,  IMO it's more consistent from a user perspective: 
> Why should **all-scopes**-completion ignore **scoped** enums?
I have no objection to this additional change personally, but to play devil's 
advocate a bit: one could argue that for scoped enums, because the enumeration 
name needs to be mentioned at every use, the enumerator names are more likely 
to be shorter/common words, such that they may appear in multiple enumerations 
across a project, making the completion results more noisy.

Perhaps, it would make sense to split this out into a separate patch, so that 
in case it turns out to be controversial, it can be reverted without affecting 
the other part of the fix?



Comment at: clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp:1334
+  AllOf(qName("Color3"), forCodeCompletion(true)),
+  AllOf(qName("Color3::Blue"), forCodeCompletion(true)),
   AllOf(qName("ns"), forCodeCompletion(true)),

I think it would be nice to add a test case to `CodeCompleteTests.cpp` as well.

(For example, it was not obvious to me that in the scoped enum case, completing 
the enumerator name would correctly insert the enumeration name as part of the 
scope, until I actually tried it in the editor.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136925

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


[PATCH] D137052: [clang-format] Don't skip #else/#elif of #if 0

2022-10-30 Thread sstwcw via Phabricator via cfe-commits
sstwcw added a comment.

This patch fixes the regression caused by 2183fe2 
 while 
introducing a new regression.  But in my opinion the new regression is less of 
a problem than the old one.  Therefore I think it is okay.

Take this piece of code similar to the example in 71814b4.

before

  void SomeFunction(int param1,
template <
  #ifdef A
  #if 0
  #endif
MyType>
  #else
Type1, Type2>
  #endif
param2,
param3) {
f();
  }

after

  void SomeFunction(int param1,
template <
  #ifdef A
  #if 0
  #endif
MyType>
  #else
Type1,
Type2 >
  #endif
param2,
param3) {
f();
  }




Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1150
   }
-  PPChainBranchIndex.push(0);
+  if (!Unreachable)
+PPChainBranchIndex.push(0);

Can you add a comment here saying this line is a nasty hack which breaks the 
assumption that `PPChainBranchIndex` should have as many entries as the number 
of nestings of preprocessor branches and we should probably come up with a 
better way?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137052

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


[PATCH] D136953: [C++20] Diagnose invalid and reserved module names

2022-10-30 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

In D136953#3892578 , @aaron.ballman 
wrote:

> I think the standards wording here is a bit unclear as to what's intended and 
> I had misunderstood the wording around which part of the path needs to be 
> checked. Specifically:
>
> `All module-names either beginning with an identifier consisting of std 
> followed by zero or more digits or containing a reserved identifier 
> ([lex.name]) are reserved and shall not be specified in a module-declaration; 
> no diagnostic is required.`
>
> I took this to mean all identifier components of a module name should check 
> for std followed by zero or more digits, but I now believe it means only the 
> first component in the path and it intends to only catch use of `std[0-9]+` 
> and not `.*std[0-9]+.*`. e.g., `std.foo` is reserved while `foo.std` and 
> `std12Three` are not. I've changed the patch accordingly while addressing the 
> other review feedback.

Oh, yeah, the wording here looks confusing. And I agree with your understanding.




Comment at: clang/lib/Sema/SemaModule.cpp:282
+  StringRef FirstComponentName = Path[0].first->getName();
+  if (!getSourceManager().isInSystemHeader(Path[0].second) &&
+  (FirstComponentName == "std" ||

std modules should be irreverent with system headers; The intuition of the 
wording should be that the users can't declare modules like `std` or 
`std.compat` to avoid possible conflicting. The approach I imaged may be add a 
new compilation flags (call it `-fstd-modules`) now. And if the compiler found 
a `std` module declaration without `-fstd-modules`, emit an error.  

For now, I think we can skip the check for `-fstd-modules` and add it back when 
we starts to support std modules actually.



Comment at: clang/test/Modules/reserved-names-1.cpp:23-24
+ expected-error {{module declaration must occur at the 
start of the translation unit}}
+export module std;// expected-error {{'std' is a reserved name for a 
module}} \
+ expected-error {{module declaration must occur at the 
start of the translation unit}}
+export module std0;   // expected-error {{'std0' is a reserved name for a 
module}} \

or diagnose about `export module std.foo`.


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

https://reviews.llvm.org/D136953

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


[PATCH] D136930: [RISCV] Support -mcpu/mtune=native

2022-10-30 Thread Wang Pengcheng via Phabricator via cfe-commits
pcwang-thead added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:2190
 CmdArgs.push_back("-tune-cpu");
-CmdArgs.push_back(A->getValue());
+if (strcmp(A->getValue(), "native") == 0)
+  CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));

craig.topper wrote:
> Why can't we use A->getValue() == "native" here?
Because newly-changed support of other targets (like PowerPC) are in this form, 
so I think this may benefit from simplification?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136930

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


[PATCH] D136846: [Driver] Add -fsample-profile-use-profi

2022-10-30 Thread Zhang Haoyu via Phabricator via cfe-commits
HaoyuZhang updated this revision to Diff 471895.
HaoyuZhang added a comment.

Remove the prof file uploaded previous for test. No more need.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136846

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGen/pgo-sample-use-profi.c


Index: clang/test/CodeGen/pgo-sample-use-profi.c
===
--- /dev/null
+++ clang/test/CodeGen/pgo-sample-use-profi.c
@@ -0,0 +1,5 @@
+//Test if profi flat is enabled in frontend as user-facing feature.
+//
+//RUN: %clang -c -fsample-profile-use-profi -### %s 2>&1 | FileCheck %s
+
+//CHECK: "-mllvm" "-sample-profile-use-profi"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -5760,6 +5760,11 @@
 
   Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
 
+  if (Args.hasArg(options::OPT_fsample_profile_use_profi)) {
+CmdArgs.push_back("-mllvm");
+CmdArgs.push_back("-sample-profile-use-profi");
+  }
+
   // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are 
enabled.
   if (RawTriple.isPS() &&
   !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1248,6 +1248,14 @@
as cold. Otherwise, treat callsites without profile samples as 
if
we have no profile}]>,
MarshallingInfoFlag>;
+def fsample_profile_use_profi : Flag<["-"], "fsample-profile-use-profi">,
+Flags<[NoXarchOption, CC1Option]>, Group,
+HelpText<"Use profi to infer block and edge counts.">,
+DocBrief<[{Profi - a flow-based profile inference algorithm is an extended
+   and significantly re-engineered classic MCMF (min-cost max-flow)
+   approach. It models profile inference as an optimization problem
+   on a control-flow graph with the objectives and constraints
+   capturing the desired properties on profile data.}]>;
 def fno_profile_sample_accurate : Flag<["-"], "fno-profile-sample-accurate">,
   Group, Flags<[NoXarchOption]>;
 def fauto_profile : Flag<["-"], "fauto-profile">, Group,


Index: clang/test/CodeGen/pgo-sample-use-profi.c
===
--- /dev/null
+++ clang/test/CodeGen/pgo-sample-use-profi.c
@@ -0,0 +1,5 @@
+//Test if profi flat is enabled in frontend as user-facing feature.
+//
+//RUN: %clang -c -fsample-profile-use-profi -### %s 2>&1 | FileCheck %s
+
+//CHECK: "-mllvm" "-sample-profile-use-profi"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -5760,6 +5760,11 @@
 
   Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
 
+  if (Args.hasArg(options::OPT_fsample_profile_use_profi)) {
+CmdArgs.push_back("-mllvm");
+CmdArgs.push_back("-sample-profile-use-profi");
+  }
+
   // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
   if (RawTriple.isPS() &&
   !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1248,6 +1248,14 @@
as cold. Otherwise, treat callsites without profile samples as if
we have no profile}]>,
MarshallingInfoFlag>;
+def fsample_profile_use_profi : Flag<["-"], "fsample-profile-use-profi">,
+Flags<[NoXarchOption, CC1Option]>, Group,
+HelpText<"Use profi to infer block and edge counts.">,
+DocBrief<[{Profi - a flow-based profile inference algorithm is an extended
+   and significantly re-engineered classic MCMF (min-cost max-flow)
+   approach. It models profile inference as an optimization problem
+   on a control-flow graph with the objectives and constraints
+   capturing the desired properties on profile data.}]>;
 def fno_profile_sample_accurate : Flag<["-"], "fno-profile-sample-accurate">,
   Group, Flags<[NoXarchOption]>;
 def fauto_profile : Flag<["-"], "fauto-profile">, Group,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D136846: [Driver] Add -fsample-profile-use-profi

2022-10-30 Thread Zhang Haoyu via Phabricator via cfe-commits
HaoyuZhang added a comment.

Thanks for the comments. The modifications have been finished. PTAL~




Comment at: clang/include/clang/Driver/Options.td:1253
+Flags<[NoXarchOption, CC1Option]>, Group,
+HelpText<"Use profi to infer block and edge counts.">;
 def fno_profile_sample_accurate : Flag<["-"], "fno-profile-sample-accurate">,

hans wrote:
> A user who reads the help message might reasonably ask "what's profi". Can 
> you please add some documentation about it? It would also be nice with a 
> DocBrief (see e.g. -fprofile-sample-accurate above).
Hi Hans, thank you for the comments. The DocBrief may be a good choice. I have 
added it in new commit.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:5763
 
+  // Enable profi in frontend and forward to LLVM invocation
+  if (Args.hasArg(options::OPT_fsample_profile_use_profi)) {

hans wrote:
> Perhaps consider skipping this comment, the code is clear enough.
It has been deleted.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136846

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


[PATCH] D136846: [Driver] Add -fsample-profile-use-profi

2022-10-30 Thread Zhang Haoyu via Phabricator via cfe-commits
HaoyuZhang updated this revision to Diff 471894.
HaoyuZhang added a comment.

[Driver] Add -fsample-profile-use-profi

This patch enable -sample-profile-use-profi in Clang frontend as user-facing
feature. By using this patch, we can use the cflag of -fsample-profile-use-profi
instead of -mllvm -sample-profile-use-profi.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136846

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGen/Inputs/pgo-sample-use-profi.prof
  clang/test/CodeGen/pgo-sample-use-profi.c


Index: clang/test/CodeGen/pgo-sample-use-profi.c
===
--- /dev/null
+++ clang/test/CodeGen/pgo-sample-use-profi.c
@@ -0,0 +1,5 @@
+//Test if profi flat is enabled in frontend as user-facing feature.
+//
+//RUN: %clang -c -fsample-profile-use-profi -### %s 2>&1 | FileCheck %s
+
+//CHECK: "-mllvm" "-sample-profile-use-profi"
\ No newline at end of file
Index: clang/test/CodeGen/Inputs/pgo-sample-use-profi.prof
===
--- /dev/null
+++ clang/test/CodeGen/Inputs/pgo-sample-use-profi.prof
@@ -0,0 +1,8 @@
+_Z11bubble_sortPii:965211:0
+ 0: 0
+ 2: 4
+ 4: 19852
+ 5: 20401
+ 7: 4556
+ 8: 4556
+ 13: 0
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -5760,6 +5760,11 @@
 
   Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
 
+  if (Args.hasArg(options::OPT_fsample_profile_use_profi)) {
+CmdArgs.push_back("-mllvm");
+CmdArgs.push_back("-sample-profile-use-profi");
+  }
+
   // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are 
enabled.
   if (RawTriple.isPS() &&
   !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1248,6 +1248,14 @@
as cold. Otherwise, treat callsites without profile samples as 
if
we have no profile}]>,
MarshallingInfoFlag>;
+def fsample_profile_use_profi : Flag<["-"], "fsample-profile-use-profi">,
+Flags<[NoXarchOption, CC1Option]>, Group,
+HelpText<"Use profi to infer block and edge counts.">,
+DocBrief<[{Profi - a flow-based profile inference algorithm is an extended
+   and significantly re-engineered classic MCMF (min-cost max-flow)
+   approach. It models profile inference as an optimization problem
+   on a control-flow graph with the objectives and constraints
+   capturing the desired properties on profile data.}]>;
 def fno_profile_sample_accurate : Flag<["-"], "fno-profile-sample-accurate">,
   Group, Flags<[NoXarchOption]>;
 def fauto_profile : Flag<["-"], "fauto-profile">, Group,


Index: clang/test/CodeGen/pgo-sample-use-profi.c
===
--- /dev/null
+++ clang/test/CodeGen/pgo-sample-use-profi.c
@@ -0,0 +1,5 @@
+//Test if profi flat is enabled in frontend as user-facing feature.
+//
+//RUN: %clang -c -fsample-profile-use-profi -### %s 2>&1 | FileCheck %s
+
+//CHECK: "-mllvm" "-sample-profile-use-profi"
\ No newline at end of file
Index: clang/test/CodeGen/Inputs/pgo-sample-use-profi.prof
===
--- /dev/null
+++ clang/test/CodeGen/Inputs/pgo-sample-use-profi.prof
@@ -0,0 +1,8 @@
+_Z11bubble_sortPii:965211:0
+ 0: 0
+ 2: 4
+ 4: 19852
+ 5: 20401
+ 7: 4556
+ 8: 4556
+ 13: 0
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -5760,6 +5760,11 @@
 
   Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
 
+  if (Args.hasArg(options::OPT_fsample_profile_use_profi)) {
+CmdArgs.push_back("-mllvm");
+CmdArgs.push_back("-sample-profile-use-profi");
+  }
+
   // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
   if (RawTriple.isPS() &&
   !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1248,6 +1248,14 @@
as cold. Otherwise, treat callsites without profile samples as if
we have no profile}]>,
MarshallingInfoFlag>;
+def fsample_profile_use_profi : Flag<["-"], "fsample-profile-use-profi">,
+Flags<[NoXarchOption, CC1Option]>, Group,
+HelpText<"Use profi to infer block and edge 

[PATCH] D136930: [RISCV] Support -mcpu/mtune=native

2022-10-30 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:2190
 CmdArgs.push_back("-tune-cpu");
-CmdArgs.push_back(A->getValue());
+if (strcmp(A->getValue(), "native") == 0)
+  CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));

Why can't we use A->getValue() == "native" here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136930

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


[PATCH] D137054: [X86][Driver] Remove stale FIXME. NFC

2022-10-30 Thread Craig Topper via Phabricator via cfe-commits
craig.topper created this revision.
craig.topper added reviewers: pengfei, RKSimon.
Herald added a subscriber: StephenFan.
Herald added a project: All.
craig.topper requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

We use getHostCPUFeatures in x86::getX86TargetFeatures so I think
this FIXME is taken care of already.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137054

Files:
  clang/lib/Driver/ToolChains/Arch/X86.cpp


Index: clang/lib/Driver/ToolChains/Arch/X86.cpp
===
--- clang/lib/Driver/ToolChains/Arch/X86.cpp
+++ clang/lib/Driver/ToolChains/Arch/X86.cpp
@@ -30,9 +30,6 @@
 
 // FIXME: Reject attempts to use -march=native unless the target matches
 // the host.
-//
-// FIXME: We should also incorporate the detected target features for use
-// with -native.
 CPU = llvm::sys::getHostCPUName();
 if (!CPU.empty() && CPU != "generic")
   return std::string(CPU);


Index: clang/lib/Driver/ToolChains/Arch/X86.cpp
===
--- clang/lib/Driver/ToolChains/Arch/X86.cpp
+++ clang/lib/Driver/ToolChains/Arch/X86.cpp
@@ -30,9 +30,6 @@
 
 // FIXME: Reject attempts to use -march=native unless the target matches
 // the host.
-//
-// FIXME: We should also incorporate the detected target features for use
-// with -native.
 CPU = llvm::sys::getHostCPUName();
 if (!CPU.empty() && CPU != "generic")
   return std::string(CPU);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D136146: [Clang][LoongArch] Handle -march/-m{single,double,soft}-float/-mfpu options

2022-10-30 Thread WÁNG Xuěruì via Phabricator via cfe-commits
xen0n accepted this revision.
xen0n added a comment.
This revision is now accepted and ready to land.

Looks good LoongArch-wise but I'm not very familiar with Clang internals to 
start with. Might be okay to land since this touches little code outside 
LoongArch and has passed tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136146

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


[PATCH] D136841: [LoongArch] Support inline asm operand modifier 'z'

2022-10-30 Thread Lu Weining 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 rGe415cb1d61e7: [LoongArch] Support inline asm operand 
modifier z (authored by SixWeining).

Changed prior to commit:
  https://reviews.llvm.org/D136841?vs=471730=471892#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136841

Files:
  clang/test/CodeGen/LoongArch/inline-asm-operand-modifiers.c
  llvm/lib/Target/LoongArch/LoongArchAsmPrinter.cpp
  llvm/test/CodeGen/LoongArch/inline-asm-operand-modifiers.ll

Index: llvm/test/CodeGen/LoongArch/inline-asm-operand-modifiers.ll
===
--- /dev/null
+++ llvm/test/CodeGen/LoongArch/inline-asm-operand-modifiers.ll
@@ -0,0 +1,25 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc --mtriple=loongarch32 --verify-machineinstrs < %s | FileCheck %s
+; RUN: llc --mtriple=loongarch64 --verify-machineinstrs < %s | FileCheck %s
+
+define i32 @modifier_z_zero(i32 %a) nounwind {
+; CHECK-LABEL: modifier_z_zero:
+; CHECK:   # %bb.0:
+; CHECK-NEXT:#APP
+; CHECK-NEXT:add.w $a0, $a0, $zero
+; CHECK-NEXT:#NO_APP
+; CHECK-NEXT:ret
+  %1 = tail call i32 asm "add.w $0, $1, ${2:z}", "=r,r,ri"(i32 %a, i32 0)
+  ret i32 %1
+}
+
+define i32 @modifier_z_nonzero(i32 %a) nounwind {
+; CHECK-LABEL: modifier_z_nonzero:
+; CHECK:   # %bb.0:
+; CHECK-NEXT:#APP
+; CHECK-NEXT:addi.w $a0, $a0, 1
+; CHECK-NEXT:#NO_APP
+; CHECK-NEXT:ret
+  %1 = tail call i32 asm "addi.w $0, $1, ${2:z}", "=r,r,ri"(i32 %a, i32 1)
+  ret i32 %1
+}
Index: llvm/lib/Target/LoongArch/LoongArchAsmPrinter.cpp
===
--- llvm/lib/Target/LoongArch/LoongArchAsmPrinter.cpp
+++ llvm/lib/Target/LoongArch/LoongArchAsmPrinter.cpp
@@ -47,24 +47,38 @@
   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, OS))
 return false;
 
-  // TODO: handle other extra codes if we have.
-  if (!ExtraCode) {
-const MachineOperand  = MI->getOperand(OpNo);
-switch (MO.getType()) {
-case MachineOperand::MO_Immediate:
-  OS << MO.getImm();
-  return false;
-case MachineOperand::MO_Register:
-  OS << '$' << LoongArchInstPrinter::getRegisterName(MO.getReg());
-  return false;
-case MachineOperand::MO_GlobalAddress:
-  PrintSymbolOperand(MO, OS);
-  return false;
+  const MachineOperand  = MI->getOperand(OpNo);
+  if (ExtraCode && ExtraCode[0]) {
+if (ExtraCode[1] != 0)
+  return true; // Unknown modifier.
+
+switch (ExtraCode[0]) {
 default:
-  llvm_unreachable("not implemented");
+  return true; // Unknown modifier.
+case 'z':  // Print $zero register if zero, regular printing otherwise.
+  if (MO.isImm() && MO.getImm() == 0) {
+OS << '$' << LoongArchInstPrinter::getRegisterName(LoongArch::R0);
+return false;
+  }
+  break;
+  // TODO: handle other extra codes if any.
 }
   }
 
+  switch (MO.getType()) {
+  case MachineOperand::MO_Immediate:
+OS << MO.getImm();
+return false;
+  case MachineOperand::MO_Register:
+OS << '$' << LoongArchInstPrinter::getRegisterName(MO.getReg());
+return false;
+  case MachineOperand::MO_GlobalAddress:
+PrintSymbolOperand(MO, OS);
+return false;
+  default:
+llvm_unreachable("not implemented");
+  }
+
   return true;
 }
 
Index: clang/test/CodeGen/LoongArch/inline-asm-operand-modifiers.c
===
--- /dev/null
+++ clang/test/CodeGen/LoongArch/inline-asm-operand-modifiers.c
@@ -0,0 +1,25 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -triple loongarch32 -O2 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple loongarch64 -O2 -emit-llvm %s -o - | FileCheck %s
+
+/// Test LoongArch specific operand modifiers (i.e. operand codes).
+
+// CHECK-LABEL: @test_z_zero(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i32 asm sideeffect "add.w $0, $1, ${2:z}", "=r,r,ri"(i32 [[A:%.*]], i32 0) #[[ATTR1:[0-9]+]], !srcloc !2
+// CHECK-NEXT:ret void
+//
+void test_z_zero(int a) {
+  int tmp;
+  asm volatile ("add.w %0, %1, %z2" : "=r" (tmp) : "r" (a), "ri" (0));
+}
+
+// CHECK-LABEL: @test_z_nonzero(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i32 asm sideeffect "add.w $0, $1, ${2:z}", "=r,r,ri"(i32 [[A:%.*]], i32 1) #[[ATTR1]], !srcloc !3
+// CHECK-NEXT:ret void
+//
+void test_z_nonzero(int a) {
+  int tmp;
+  asm volatile ("add.w %0, %1, %z2" : "=r" (tmp) : "r" (a), "ri" (1));
+}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] e415cb1 - [LoongArch] Support inline asm operand modifier 'z'

2022-10-30 Thread Weining Lu via cfe-commits

Author: Weining Lu
Date: 2022-10-31T09:56:41+08:00
New Revision: e415cb1d61e798b6d69b5960a90f00518ca5008f

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

LOG: [LoongArch] Support inline asm operand modifier 'z'

Print $zero register if operand is zero, otherwise print it normally.

Clang is highly compatible [1] with GCC inline assembly extensions,
allowing the same set of constraints, modifiers and operands as GCC
inline assembly. This patch tries to make it compatible regarding
LoongArch specific operand modifiers.

GCC supports many modifiers [2], but it seems that only x86 and msp430
are documented [3][4]. I don't know if any other modifiers are being
used except the 'z' in Linux [5].

[1]: https://clang.llvm.org/compatibility.html#inline-asm
[2]: 
https://github.com/gcc-mirror/gcc/blob/master/gcc/config/loongarch/loongarch.cc#L4884-L4911
[3]: https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#x86Operandmodifiers
[4]: https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#msp430Operandmodifiers
[5]: 
https://github.com/torvalds/linux/blob/master/arch/loongarch/include/asm/cmpxchg.h#L17

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

Added: 
clang/test/CodeGen/LoongArch/inline-asm-operand-modifiers.c
llvm/test/CodeGen/LoongArch/inline-asm-operand-modifiers.ll

Modified: 
llvm/lib/Target/LoongArch/LoongArchAsmPrinter.cpp

Removed: 




diff  --git a/clang/test/CodeGen/LoongArch/inline-asm-operand-modifiers.c 
b/clang/test/CodeGen/LoongArch/inline-asm-operand-modifiers.c
new file mode 100644
index 0..b36fe7a7b69bb
--- /dev/null
+++ b/clang/test/CodeGen/LoongArch/inline-asm-operand-modifiers.c
@@ -0,0 +1,25 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -triple loongarch32 -O2 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple loongarch64 -O2 -emit-llvm %s -o - | FileCheck %s
+
+/// Test LoongArch specific operand modifiers (i.e. operand codes).
+
+// CHECK-LABEL: @test_z_zero(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i32 asm sideeffect "add.w $0, $1, 
${2:z}", "=r,r,ri"(i32 [[A:%.*]], i32 0) #[[ATTR1:[0-9]+]], !srcloc !2
+// CHECK-NEXT:ret void
+//
+void test_z_zero(int a) {
+  int tmp;
+  asm volatile ("add.w %0, %1, %z2" : "=r" (tmp) : "r" (a), "ri" (0));
+}
+
+// CHECK-LABEL: @test_z_nonzero(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i32 asm sideeffect "add.w $0, $1, 
${2:z}", "=r,r,ri"(i32 [[A:%.*]], i32 1) #[[ATTR1]], !srcloc !3
+// CHECK-NEXT:ret void
+//
+void test_z_nonzero(int a) {
+  int tmp;
+  asm volatile ("add.w %0, %1, %z2" : "=r" (tmp) : "r" (a), "ri" (1));
+}

diff  --git a/llvm/lib/Target/LoongArch/LoongArchAsmPrinter.cpp 
b/llvm/lib/Target/LoongArch/LoongArchAsmPrinter.cpp
index 9d69a26e18b13..5ab6bad1e891a 100644
--- a/llvm/lib/Target/LoongArch/LoongArchAsmPrinter.cpp
+++ b/llvm/lib/Target/LoongArch/LoongArchAsmPrinter.cpp
@@ -47,24 +47,38 @@ bool LoongArchAsmPrinter::PrintAsmOperand(const 
MachineInstr *MI, unsigned OpNo,
   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, OS))
 return false;
 
-  // TODO: handle other extra codes if we have.
-  if (!ExtraCode) {
-const MachineOperand  = MI->getOperand(OpNo);
-switch (MO.getType()) {
-case MachineOperand::MO_Immediate:
-  OS << MO.getImm();
-  return false;
-case MachineOperand::MO_Register:
-  OS << '$' << LoongArchInstPrinter::getRegisterName(MO.getReg());
-  return false;
-case MachineOperand::MO_GlobalAddress:
-  PrintSymbolOperand(MO, OS);
-  return false;
+  const MachineOperand  = MI->getOperand(OpNo);
+  if (ExtraCode && ExtraCode[0]) {
+if (ExtraCode[1] != 0)
+  return true; // Unknown modifier.
+
+switch (ExtraCode[0]) {
 default:
-  llvm_unreachable("not implemented");
+  return true; // Unknown modifier.
+case 'z':  // Print $zero register if zero, regular printing otherwise.
+  if (MO.isImm() && MO.getImm() == 0) {
+OS << '$' << LoongArchInstPrinter::getRegisterName(LoongArch::R0);
+return false;
+  }
+  break;
+  // TODO: handle other extra codes if any.
 }
   }
 
+  switch (MO.getType()) {
+  case MachineOperand::MO_Immediate:
+OS << MO.getImm();
+return false;
+  case MachineOperand::MO_Register:
+OS << '$' << LoongArchInstPrinter::getRegisterName(MO.getReg());
+return false;
+  case MachineOperand::MO_GlobalAddress:
+PrintSymbolOperand(MO, OS);
+return false;
+  default:
+llvm_unreachable("not implemented");
+  }
+
   return true;
 }
 

diff  --git a/llvm/test/CodeGen/LoongArch/inline-asm-operand-modifiers.ll 
b/llvm/test/CodeGen/LoongArch/inline-asm-operand-modifiers.ll
new file mode 

[PATCH] D136413: [Clang][LoongArch] Define more LoongArch specific built-in macros

2022-10-30 Thread Lu Weining via Phabricator via cfe-commits
SixWeining added a comment.

In D136413#3895369 , @xen0n wrote:

> Amended the patch summary a little for grammatical fixes and mentioning 
> `__loongarch64` too.

Thanks.

BTW, this patch depends on D136146 . Could 
you help to have a look? :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136413

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


[PATCH] D136413: [Clang][LoongArch] Define more LoongArch specific built-in macros

2022-10-30 Thread WÁNG Xuěruì via Phabricator via cfe-commits
xen0n added a comment.

Amended the patch summary a little for grammatical fixes and mentioning 
`__loongarch64` too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136413

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


[PATCH] D136835: [Clang][LoongArch] Support inline asm constraint 'J'

2022-10-30 Thread Lu Weining via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGcd0174aacb73: [Clang][LoongArch] Support inline asm 
constraint J (authored by SixWeining).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136835

Files:
  clang/lib/Basic/Targets/LoongArch.cpp
  clang/test/CodeGen/LoongArch/inline-asm-constraints.c
  llvm/lib/Target/LoongArch/LoongArchISelLowering.cpp
  llvm/test/CodeGen/LoongArch/inline-asm-constraint-error.ll
  llvm/test/CodeGen/LoongArch/inline-asm-constraint.ll

Index: llvm/test/CodeGen/LoongArch/inline-asm-constraint.ll
===
--- llvm/test/CodeGen/LoongArch/inline-asm-constraint.ll
+++ llvm/test/CodeGen/LoongArch/inline-asm-constraint.ll
@@ -58,6 +58,17 @@
   ret void
 }
 
+define void @constraint_J() nounwind {
+; CHECK-LABEL: constraint_J:
+; CHECK:   # %bb.0:
+; CHECK-NEXT:#APP
+; CHECK-NEXT:addi.w $a0, $a0, 0
+; CHECK-NEXT:#NO_APP
+; CHECK-NEXT:ret
+  tail call void asm sideeffect "addi.w $$a0, $$a0, $0", "J"(i32 0)
+  ret void
+}
+
 define void @constraint_K() nounwind {
 ; CHECK-LABEL: constraint_K:
 ; CHECK:   # %bb.0:
Index: llvm/test/CodeGen/LoongArch/inline-asm-constraint-error.ll
===
--- llvm/test/CodeGen/LoongArch/inline-asm-constraint-error.ll
+++ llvm/test/CodeGen/LoongArch/inline-asm-constraint-error.ll
@@ -17,6 +17,12 @@
   ret void
 }
 
+define void @constraint_J() {
+; CHECK: error: value out of range for constraint 'J'
+  tail call void asm sideeffect "addi.w $$a0, $$a0, $$0", "J"(i32 1)
+  ret void
+}
+
 define void @constraint_K() {
 ; CHECK: error: value out of range for constraint 'K'
   tail call void asm sideeffect "andi.w $$a0, $$a0, $0", "K"(i32 4096)
Index: llvm/lib/Target/LoongArch/LoongArchISelLowering.cpp
===
--- llvm/lib/Target/LoongArch/LoongArchISelLowering.cpp
+++ llvm/lib/Target/LoongArch/LoongArchISelLowering.cpp
@@ -2184,6 +2184,7 @@
   //   offset that is suitable for use in instructions with the same
   //   addressing mode as st.w and ld.w.
   // 'I':  A signed 12-bit constant (for arithmetic instructions).
+  // 'J':  Integer zero.
   // 'K':  An unsigned 12-bit constant (for logic instructions).
   // "ZB": An address that is held in a general-purpose register. The offset is
   //   zero.
@@ -2198,6 +2199,7 @@
   return C_RegisterClass;
 case 'l':
 case 'I':
+case 'J':
 case 'K':
   return C_Immediate;
 case 'k':
@@ -2301,6 +2303,13 @@
   DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getGRLenVT()));
   }
   return;
+case 'J':
+  // Validate & create an integer zero operand.
+  if (auto *C = dyn_cast(Op))
+if (C->getZExtValue() == 0)
+  Ops.push_back(
+  DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getGRLenVT()));
+  return;
 case 'K':
   // Validate & create a 12-bit unsigned immediate operand.
   if (auto *C = dyn_cast(Op)) {
Index: clang/test/CodeGen/LoongArch/inline-asm-constraints.c
===
--- clang/test/CodeGen/LoongArch/inline-asm-constraints.c
+++ clang/test/CodeGen/LoongArch/inline-asm-constraints.c
@@ -43,6 +43,12 @@
   asm volatile ("" :: "I"(-2048));
 }
 
+void test_J(void) {
+// CHECK-LABEL: define{{.*}} void @test_J()
+// CHECK: call void asm sideeffect "", "J"(i32 0)
+  asm volatile ("" :: "J"(0));
+}
+
 void test_K(void) {
 // CHECK-LABEL: define{{.*}} void @test_K()
 // CHECK: call void asm sideeffect "", "K"(i32 4095)
Index: clang/lib/Basic/Targets/LoongArch.cpp
===
--- clang/lib/Basic/Targets/LoongArch.cpp
+++ clang/lib/Basic/Targets/LoongArch.cpp
@@ -88,6 +88,10 @@
 // A signed 12-bit constant (for arithmetic instructions).
 Info.setRequiresImmediate(-2048, 2047);
 return true;
+  case 'J':
+// Integer zero.
+Info.setRequiresImmediate(0);
+return true;
   case 'K':
 // An unsigned 12-bit constant (for logic instructions).
 Info.setRequiresImmediate(0, 4095);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] cd0174a - [Clang][LoongArch] Support inline asm constraint 'J'

2022-10-30 Thread Weining Lu via cfe-commits

Author: Weining Lu
Date: 2022-10-31T09:13:52+08:00
New Revision: cd0174aacb734904205ed7827fb923acda08f79a

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

LOG: [Clang][LoongArch] Support inline asm constraint 'J'

'J' is defined in GCC [1] but not documented [2] while Linux [3] has
already used it in LoongArch port.

[1]: 
https://github.com/gcc-mirror/gcc/blob/master/gcc/config/loongarch/constraints.md#L61
[2]: https://gcc.gnu.org/onlinedocs/gccint/Machine-Constraints.html
[3]: 
https://github.com/torvalds/linux/blob/master/arch/loongarch/include/asm/cmpxchg.h#L19

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

Added: 


Modified: 
clang/lib/Basic/Targets/LoongArch.cpp
clang/test/CodeGen/LoongArch/inline-asm-constraints.c
llvm/lib/Target/LoongArch/LoongArchISelLowering.cpp
llvm/test/CodeGen/LoongArch/inline-asm-constraint-error.ll
llvm/test/CodeGen/LoongArch/inline-asm-constraint.ll

Removed: 




diff  --git a/clang/lib/Basic/Targets/LoongArch.cpp 
b/clang/lib/Basic/Targets/LoongArch.cpp
index 1ad9c0fb8b495..12d53a9aff43b 100644
--- a/clang/lib/Basic/Targets/LoongArch.cpp
+++ b/clang/lib/Basic/Targets/LoongArch.cpp
@@ -88,6 +88,10 @@ bool LoongArchTargetInfo::validateAsmConstraint(
 // A signed 12-bit constant (for arithmetic instructions).
 Info.setRequiresImmediate(-2048, 2047);
 return true;
+  case 'J':
+// Integer zero.
+Info.setRequiresImmediate(0);
+return true;
   case 'K':
 // An unsigned 12-bit constant (for logic instructions).
 Info.setRequiresImmediate(0, 4095);

diff  --git a/clang/test/CodeGen/LoongArch/inline-asm-constraints.c 
b/clang/test/CodeGen/LoongArch/inline-asm-constraints.c
index d7d425ea0766f..b19494284bd99 100644
--- a/clang/test/CodeGen/LoongArch/inline-asm-constraints.c
+++ b/clang/test/CodeGen/LoongArch/inline-asm-constraints.c
@@ -43,6 +43,12 @@ void test_I(void) {
   asm volatile ("" :: "I"(-2048));
 }
 
+void test_J(void) {
+// CHECK-LABEL: define{{.*}} void @test_J()
+// CHECK: call void asm sideeffect "", "J"(i32 0)
+  asm volatile ("" :: "J"(0));
+}
+
 void test_K(void) {
 // CHECK-LABEL: define{{.*}} void @test_K()
 // CHECK: call void asm sideeffect "", "K"(i32 4095)

diff  --git a/llvm/lib/Target/LoongArch/LoongArchISelLowering.cpp 
b/llvm/lib/Target/LoongArch/LoongArchISelLowering.cpp
index f99764fb80225..1c58fa0d1a096 100644
--- a/llvm/lib/Target/LoongArch/LoongArchISelLowering.cpp
+++ b/llvm/lib/Target/LoongArch/LoongArchISelLowering.cpp
@@ -2184,6 +2184,7 @@ LoongArchTargetLowering::getConstraintType(StringRef 
Constraint) const {
   //   offset that is suitable for use in instructions with the same
   //   addressing mode as st.w and ld.w.
   // 'I':  A signed 12-bit constant (for arithmetic instructions).
+  // 'J':  Integer zero.
   // 'K':  An unsigned 12-bit constant (for logic instructions).
   // "ZB": An address that is held in a general-purpose register. The offset is
   //   zero.
@@ -2198,6 +2199,7 @@ LoongArchTargetLowering::getConstraintType(StringRef 
Constraint) const {
   return C_RegisterClass;
 case 'l':
 case 'I':
+case 'J':
 case 'K':
   return C_Immediate;
 case 'k':
@@ -2301,6 +2303,13 @@ void 
LoongArchTargetLowering::LowerAsmOperandForConstraint(
   DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getGRLenVT()));
   }
   return;
+case 'J':
+  // Validate & create an integer zero operand.
+  if (auto *C = dyn_cast(Op))
+if (C->getZExtValue() == 0)
+  Ops.push_back(
+  DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getGRLenVT()));
+  return;
 case 'K':
   // Validate & create a 12-bit unsigned immediate operand.
   if (auto *C = dyn_cast(Op)) {

diff  --git a/llvm/test/CodeGen/LoongArch/inline-asm-constraint-error.ll 
b/llvm/test/CodeGen/LoongArch/inline-asm-constraint-error.ll
index 470581d1faf9d..570fd438be97b 100644
--- a/llvm/test/CodeGen/LoongArch/inline-asm-constraint-error.ll
+++ b/llvm/test/CodeGen/LoongArch/inline-asm-constraint-error.ll
@@ -17,6 +17,12 @@ define void @constraint_I() {
   ret void
 }
 
+define void @constraint_J() {
+; CHECK: error: value out of range for constraint 'J'
+  tail call void asm sideeffect "addi.w $$a0, $$a0, $$0", "J"(i32 1)
+  ret void
+}
+
 define void @constraint_K() {
 ; CHECK: error: value out of range for constraint 'K'
   tail call void asm sideeffect "andi.w $$a0, $$a0, $0", "K"(i32 4096)

diff  --git a/llvm/test/CodeGen/LoongArch/inline-asm-constraint.ll 
b/llvm/test/CodeGen/LoongArch/inline-asm-constraint.ll
index ed2c621bf86a7..4b63d3b0a0a2c 100644
--- a/llvm/test/CodeGen/LoongArch/inline-asm-constraint.ll
+++ b/llvm/test/CodeGen/LoongArch/inline-asm-constraint.ll
@@ -58,6 +58,17 @@ define 

[PATCH] D133647: [clang-format] Parse the else part of `#if 0`

2022-10-30 Thread Owen Pan via Phabricator via cfe-commits
owenpan added a comment.

See D137052 .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133647

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


[PATCH] D137052: [clang-format] Don't skip #else/#elif of #if 0

2022-10-30 Thread Owen Pan via Phabricator via cfe-commits
owenpan created this revision.
owenpan added reviewers: sstwcw, sammccall, HazardyKnusperkeks, MyDeveloperDay, 
rymiel.
owenpan added a project: clang-format.
Herald added a project: All.
owenpan requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137052

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -6119,7 +6119,7 @@
  "#endif");
 
   // Verify that indentation is correct when there is an `#if 0` with an
-  // `#else`.
+  // `#else`/`#elif`.
   verifyFormat("#if 0\n"
"{\n"
"#else\n"
@@ -6127,6 +6127,26 @@
"#endif\n"
"  x;\n"
"}");
+  verifyFormat("#if 0\n"
+   "{\n"
+   "#elif FOO\n"
+   "{\n"
+   "#endif\n"
+   "  x;\n"
+   "}");
+
+  verifyFormat("#if 0\n"
+   "#endif\n"
+   "#if X\n"
+   "int something_fairly_long; // Align here please\n"
+   "#endif // Should be aligned");
+
+  verifyFormat("#if 0\n"
+   "#endif\n"
+   "#if X\n"
+   "#else  // Align\n"
+   ";\n"
+   "#endif // Align");
 }
 
 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1144,12 +1144,11 @@
   ++PPBranchLevel;
   assert(PPBranchLevel >= 0 && PPBranchLevel <= 
(int)PPLevelBranchIndex.size());
   if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
-// If the first branch is unreachable, set the BranchIndex to 1.  This way
-// the next branch will be parsed if there is one.
-PPLevelBranchIndex.push_back(Unreachable ? 1 : 0);
+PPLevelBranchIndex.push_back(0);
 PPLevelBranchCount.push_back(0);
   }
-  PPChainBranchIndex.push(0);
+  if (!Unreachable)
+PPChainBranchIndex.push(0);
   bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
   conditionalCompilationCondition(Unreachable || Skip);
 }


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -6119,7 +6119,7 @@
  "#endif");
 
   // Verify that indentation is correct when there is an `#if 0` with an
-  // `#else`.
+  // `#else`/`#elif`.
   verifyFormat("#if 0\n"
"{\n"
"#else\n"
@@ -6127,6 +6127,26 @@
"#endif\n"
"  x;\n"
"}");
+  verifyFormat("#if 0\n"
+   "{\n"
+   "#elif FOO\n"
+   "{\n"
+   "#endif\n"
+   "  x;\n"
+   "}");
+
+  verifyFormat("#if 0\n"
+   "#endif\n"
+   "#if X\n"
+   "int something_fairly_long; // Align here please\n"
+   "#endif // Should be aligned");
+
+  verifyFormat("#if 0\n"
+   "#endif\n"
+   "#if X\n"
+   "#else  // Align\n"
+   ";\n"
+   "#endif // Align");
 }
 
 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1144,12 +1144,11 @@
   ++PPBranchLevel;
   assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
   if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
-// If the first branch is unreachable, set the BranchIndex to 1.  This way
-// the next branch will be parsed if there is one.
-PPLevelBranchIndex.push_back(Unreachable ? 1 : 0);
+PPLevelBranchIndex.push_back(0);
 PPLevelBranchCount.push_back(0);
   }
-  PPChainBranchIndex.push(0);
+  if (!Unreachable)
+PPChainBranchIndex.push(0);
   bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
   conditionalCompilationCondition(Unreachable || Skip);
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D136568: [Clang] Support constexpr builtin ilogb

2022-10-30 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast requested changes to this revision.
hubert.reinterpretcast added inline comments.
This revision now requires changes to proceed.



Comment at: clang/lib/AST/ExprConstant.cpp:12452
+int Ilogb;
+if (APFloat::opStatus St = ilogb(F, Ilogb); !isConstantOpStatus(St))
+  return false;

Izaron wrote:
> hubert.reinterpretcast wrote:
> > hubert.reinterpretcast wrote:
> > > hubert.reinterpretcast wrote:
> > > > Izaron wrote:
> > > > > majnemer wrote:
> > > > > > Izaron wrote:
> > > > > > > jcranmer-intel wrote:
> > > > > > > > Izaron wrote:
> > > > > > > > > aaron.ballman wrote:
> > > > > > > > > > jcranmer-intel wrote:
> > > > > > > > > > > `long double` is `ppc_fp128` on at least some PPC 
> > > > > > > > > > > targets, and while I'm not entirely certain of what 
> > > > > > > > > > > `ilogb` properly returns in the corner cases of the 
> > > > > > > > > > > `ppc_fp128`, I'm not entirely confident that the 
> > > > > > > > > > > implementation of `APFloat` is correct in those cases. 
> > > > > > > > > > > I'd like someone with PPC background to comment in here.
> > > > > > > > > > Paging @hubert.reinterpretcast for help finding a good 
> > > > > > > > > > person to comment on the PPC questions.
> > > > > > > > > @jcranmer-intel constexpr evaluation is quite 
> > > > > > > > > machine-/target-independent. Clang evaluates it based on its 
> > > > > > > > > **internal** representation of float variables.
> > > > > > > > > 
> > > > > > > > > [[ 
> > > > > > > > > https://github.com/llvm/llvm-project/blob/2e5bf4da99a2f8d3d4bb4f1a4d1ed968a01e8f02/llvm/include/llvm/ADT/APFloat.h#L1256
> > > > > > > > >  | int ilogb ]] uses `Arg.getIEEE()`, that [[ 
> > > > > > > > > https://github.com/llvm/llvm-project/blob/2e5bf4da99a2f8d3d4bb4f1a4d1ed968a01e8f02/llvm/include/llvm/ADT/APFloat.h#L819-L825
> > > > > > > > >  | returns Clang's internal float representation ]].
> > > > > > > > > 
> > > > > > > > > Whichever float semantics is being used, [[ 
> > > > > > > > > https://github.com/llvm/llvm-project/blob/2e5bf4da99a2f8d3d4bb4f1a4d1ed968a01e8f02/llvm/lib/Support/APFloat.cpp#L54-L61
> > > > > > > > >  | minExponent and maxExponent are representable as 
> > > > > > > > > APFloatBase::ExponentType ]], which is `int32_t`:
> > > > > > > > > ```
> > > > > > > > > /// A signed type to represent a floating point numbers 
> > > > > > > > > unbiased exponent.
> > > > > > > > > typedef int32_t ExponentType;
> > > > > > > > > ```
> > > > > > > > > 
> > > > > > > > > We already use `int ilogb` in some constexpr evaluation code: 
> > > > > > > > > [[ 
> > > > > > > > > https://github.com/llvm/llvm-project/blob/2e5bf4da99a2f8d3d4bb4f1a4d1ed968a01e8f02/clang/lib/AST/ExprConstant.cpp#L14592
> > > > > > > > >  | link ]], it is working correct because it is working on 
> > > > > > > > > Clang's float representations.
> > > > > > > > > We already use `int ilogb` in some constexpr evaluation code: 
> > > > > > > > > [[ 
> > > > > > > > > https://github.com/llvm/llvm-project/blob/2e5bf4da99a2f8d3d4bb4f1a4d1ed968a01e8f02/clang/lib/AST/ExprConstant.cpp#L14592
> > > > > > > > >  | link ]], it is working correct because it is working on 
> > > > > > > > > Clang's float representations.
> > > > > > > > 
> > > > > > > > `APFloat::getIEEE()`, if I'm following it correctly, only 
> > > > > > > > returns the details of the high double in `ppc_fp128` floats, 
> > > > > > > > and I'm not sufficiently well-versed in the `ppc_fp128` format 
> > > > > > > > to establish whether or not the low double comes into play 
> > > > > > > > here. glibc seems to think that the low double comes into play 
> > > > > > > > in at least one case: 
> > > > > > > > https://github.com/bminor/glibc/blob/30891f35fa7da832b66d80d0807610df361851f3/sysdeps/ieee754/ldbl-128ibm/e_ilogbl.c
> > > > > > > Thanks for the link to the glibc code! It helped me to understand 
> > > > > > > the IEEE754 standard better.
> > > > > > > 
> > > > > > > I did some research and it seems like AST supports a fixed set of 
> > > > > > > float types, each working good with `ilogb`:
> > > > > > > ```
> > > > > > > half (__fp16, only for OpenCL), float16, float, double, long 
> > > > > > > double, float128
> > > > > > > ```
> > > > > > > [[ 
> > > > > > > https://github.com/llvm/llvm-project/blob/7846d590033e8d661198f4c00f56f46a4993c526/clang/lib/Sema/SemaExpr.cpp#L3911-L3931
> > > > > > >  | link to SemaExpr.cpp ]]
> > > > > > > 
> > > > > > > It means that the constant evaluator doesn't deal with other 
> > > > > > > float types including `ppc_fp128`.
> > > > > > > If `ppc_fp128` was supported on the AST level, it would anyway 
> > > > > > > come through type casting, and `__builtin_ilog` would 
> > > > > > > deal with a value of a known type.
> > > > > > > 
> > > > > > > I checked the list of builtins - each builtin argument of float 
> > > > > > > type also supports only common float types:
> > > > > > > [[ 
> > > > > > > 

[PATCH] D137051: [Clang] Allow additional mathematical symbols in identifiers.

2022-10-30 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 471882.
cor3ntin added a comment.

Remove extra semi colon.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137051

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticLexKinds.td
  clang/lib/Lex/Lexer.cpp
  clang/lib/Lex/UnicodeCharSets.h
  clang/test/Driver/autocomplete.c
  clang/test/Lexer/unicode.c

Index: clang/test/Lexer/unicode.c
===
--- clang/test/Lexer/unicode.c
+++ clang/test/Lexer/unicode.c
@@ -45,7 +45,17 @@
 extern int _\N{TANGSALETTERGA}; // expected-error {{'TANGSALETTERGA' is not a valid Unicode character name}} \
 // expected-note {{characters names in Unicode escape sequences are sensitive to case and whitespace}}
 
+extern int 𝛛; // expected-warning {{mathematical notation character  in identifier is a Clang extension}}
+extern int ₉; // expected-error {{character  not allowed at the start of an identifier}} \\
+ expected-warning {{declaration does not declare anything}}
 
+int a¹b₍₄₂₎∇; // expected-warning 6{{mathematical notation character}}
+
+int \u{221E} = 1; // expected-warning {{mathematical notation character}}
+int \N{MATHEMATICAL SANS-SERIF BOLD ITALIC PARTIAL DIFFERENTIAL} = 1;
+ // expected-warning@-1 {{mathematical notation character}}
+
+int a\N{SUBSCRIPT EQUALS SIGN} = 1; // expected-warning {{mathematical notation character}}
 
 // This character doesn't have the XID_Start property
 extern int  \U00016AC0; // TANGSA DIGIT ZERO  // cxx-error {{expected unqualified-id}} \
Index: clang/test/Driver/autocomplete.c
===
--- clang/test/Driver/autocomplete.c
+++ clang/test/Driver/autocomplete.c
@@ -111,6 +111,7 @@
 // WARNING-NEXT: -Wmain-return-type
 // WARNING-NEXT: -Wmalformed-warning-check
 // WARNING-NEXT: -Wmany-braces-around-scalar-init
+// WARNING-NEXT: -Wmathematical-notation-identifier-extension
 // WARNING-NEXT: -Wmax-tokens
 // WARNING-NEXT: -Wmax-unsigned-zero
 // RUN: %clang --autocomplete=-Wno-invalid-pp- | FileCheck %s -check-prefix=NOWARNING
Index: clang/lib/Lex/UnicodeCharSets.h
===
--- clang/lib/Lex/UnicodeCharSets.h
+++ clang/lib/Lex/UnicodeCharSets.h
@@ -366,6 +366,34 @@
 {0x1E4EC, 0x1E4F9}, {0x1E8D0, 0x1E8D6}, {0x1E944, 0x1E94A},
 {0x1E950, 0x1E959}, {0x1FBF0, 0x1FBF9}, {0xE0100, 0xE01EF}};
 
+// Clang supports the "Mathematical notation profile" as an extension,
+// as described in https://www.unicode.org/L2/L2022/22230-math-profile.pdf
+// Math_Start
+static const llvm::sys::UnicodeCharRange MathematicalNotationProfileIDStartRanges[] = {
+{0x02202, 0x02202}, // ∂
+{0x02207, 0x02207}, // ∇
+{0x0221E, 0x0221E}, // ∞
+{0x1D6C1, 0x1D6C1}, // 𝛁
+{0x1D6DB, 0x1D6DB}, // 𝛛
+{0x1D6FB, 0x1D6FB}, // 𝛻
+{0x1D715, 0x1D715}, // 𝜕
+{0x1D735, 0x1D735}, // 𝜵
+{0x1D74F, 0x1D74F}, // 𝝏
+{0x1D76F, 0x1D76F}, // 𝝯
+{0x1D789, 0x1D789}, // 𝞉
+{0x1D7A9, 0x1D7A9}, // 𝞩
+{0x1D7C3, 0x1D7C3}, // 𝟃
+};
+
+// Math_Continue
+static const llvm::sys::UnicodeCharRange MathematicalNotationProfileIDContinueRanges[] = {
+{0x000B2, 0x000B3}, // ²-³
+{0x000B9, 0x000B9}, // ¹
+{0x02070, 0x02070}, // ⁰
+{0x02074, 0x0207E}, // ⁴-⁾
+{0x02080, 0x0208E}, // ₀-₎
+};
+
 // C11 D.1, C++11 [charname.allowed]
 static const llvm::sys::UnicodeCharRange C11AllowedIDCharRanges[] = {
   // 1
Index: clang/lib/Lex/Lexer.cpp
===
--- clang/lib/Lex/Lexer.cpp
+++ clang/lib/Lex/Lexer.cpp
@@ -1457,7 +1457,30 @@
   return UnicodeWhitespaceChars.contains(Codepoint);
 }
 
-static bool isAllowedIDChar(uint32_t C, const LangOptions ) {
+static llvm::SmallString<5> codepointAsHexString(uint32_t C) {
+  llvm::SmallString<5> CharBuf;
+  llvm::raw_svector_ostream CharOS(CharBuf);
+  llvm::write_hex(CharOS, C, llvm::HexPrintStyle::Upper, 4);
+  return CharBuf;
+}
+
+// To mitigate https://github.com/llvm/llvm-project/issues/54732,
+// we allow "Mathematical Notation Characters" in identifiers.
+// This is a proposed profile that extends the XID_Start/XID_continue
+// with mathematical symbols, superscipts and subscripts digits
+// found in some production software.
+// https://www.unicode.org/L2/L2022/22230-math-profile.pdf
+static bool isMathematicalExtensionID(uint32_t C, const LangOptions , bool IsStart, bool & IsExtension) {
+  static const llvm::sys::UnicodeCharSet MathStartChars(MathematicalNotationProfileIDStartRanges);
+  static const llvm::sys::UnicodeCharSet MathContinueChars(MathematicalNotationProfileIDContinueRanges);
+  if(MathStartChars.contains(C) || (!IsStart && MathContinueChars.contains(C))) {
+

[PATCH] D137051: [Clang] Allow additional mathematical symbols in identifiers.

2022-10-30 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

Note that we should wait end of next week to hear back from the Unicode 
Technical Committee before merging this


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137051

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


[PATCH] D137051: [Clang] Allow additional mathematical symbols in identifiers.

2022-10-30 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin created this revision.
Herald added a project: All.
cor3ntin requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Implement the proposed UAX Profile
"Mathematical notation profile for default identifiers".

This implements a not-yet approved Unicode for a vetted
UAX32 identifier profile
https://www.unicode.org/L2/L2022/22230-math-profile.pdf

This change mitigates the reported disruption caused
by the implementation of UAX32 in C++ and C2x,
as these mathematical symbols are commonly used in the
scientific community.

Fixes #54732


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137051

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticLexKinds.td
  clang/lib/Lex/Lexer.cpp
  clang/lib/Lex/UnicodeCharSets.h
  clang/test/Driver/autocomplete.c
  clang/test/Lexer/unicode.c

Index: clang/test/Lexer/unicode.c
===
--- clang/test/Lexer/unicode.c
+++ clang/test/Lexer/unicode.c
@@ -45,7 +45,17 @@
 extern int _\N{TANGSALETTERGA}; // expected-error {{'TANGSALETTERGA' is not a valid Unicode character name}} \
 // expected-note {{characters names in Unicode escape sequences are sensitive to case and whitespace}}
 
+extern int 𝛛; // expected-warning {{mathematical notation character  in identifier is a Clang extension}}
+extern int ₉; // expected-error {{character  not allowed at the start of an identifier}} \\
+ expected-warning {{declaration does not declare anything}}
 
+int a¹b₍₄₂₎∇; // expected-warning 6{{mathematical notation character}}
+
+int \u{221E} = 1; // expected-warning {{mathematical notation character}}
+int \N{MATHEMATICAL SANS-SERIF BOLD ITALIC PARTIAL DIFFERENTIAL} = 1;
+ // expected-warning@-1 {{mathematical notation character}}
+
+int a\N{SUBSCRIPT EQUALS SIGN} = 1; // expected-warning {{mathematical notation character}}
 
 // This character doesn't have the XID_Start property
 extern int  \U00016AC0; // TANGSA DIGIT ZERO  // cxx-error {{expected unqualified-id}} \
Index: clang/test/Driver/autocomplete.c
===
--- clang/test/Driver/autocomplete.c
+++ clang/test/Driver/autocomplete.c
@@ -111,6 +111,7 @@
 // WARNING-NEXT: -Wmain-return-type
 // WARNING-NEXT: -Wmalformed-warning-check
 // WARNING-NEXT: -Wmany-braces-around-scalar-init
+// WARNING-NEXT: -Wmathematical-notation-identifier-extension
 // WARNING-NEXT: -Wmax-tokens
 // WARNING-NEXT: -Wmax-unsigned-zero
 // RUN: %clang --autocomplete=-Wno-invalid-pp- | FileCheck %s -check-prefix=NOWARNING
Index: clang/lib/Lex/UnicodeCharSets.h
===
--- clang/lib/Lex/UnicodeCharSets.h
+++ clang/lib/Lex/UnicodeCharSets.h
@@ -366,6 +366,34 @@
 {0x1E4EC, 0x1E4F9}, {0x1E8D0, 0x1E8D6}, {0x1E944, 0x1E94A},
 {0x1E950, 0x1E959}, {0x1FBF0, 0x1FBF9}, {0xE0100, 0xE01EF}};
 
+// Clang supports the "Mathematical notation profile" as an extension,
+// as described in https://www.unicode.org/L2/L2022/22230-math-profile.pdf
+// Math_Start
+static const llvm::sys::UnicodeCharRange MathematicalNotationProfileIDStartRanges[] = {
+{0x02202, 0x02202}, // ∂
+{0x02207, 0x02207}, // ∇
+{0x0221E, 0x0221E}, // ∞
+{0x1D6C1, 0x1D6C1}, // 𝛁
+{0x1D6DB, 0x1D6DB}, // 𝛛
+{0x1D6FB, 0x1D6FB}, // 𝛻
+{0x1D715, 0x1D715}, // 𝜕
+{0x1D735, 0x1D735}, // 𝜵
+{0x1D74F, 0x1D74F}, // 𝝏
+{0x1D76F, 0x1D76F}, // 𝝯
+{0x1D789, 0x1D789}, // 𝞉
+{0x1D7A9, 0x1D7A9}, // 𝞩
+{0x1D7C3, 0x1D7C3}, // 𝟃
+};
+
+// Math_Continue
+static const llvm::sys::UnicodeCharRange MathematicalNotationProfileIDContinueRanges[] = {
+{0x000B2, 0x000B3}, // ²-³
+{0x000B9, 0x000B9}, // ¹
+{0x02070, 0x02070}, // ⁰
+{0x02074, 0x0207E}, // ⁴-⁾
+{0x02080, 0x0208E}, // ₀-₎
+};
+
 // C11 D.1, C++11 [charname.allowed]
 static const llvm::sys::UnicodeCharRange C11AllowedIDCharRanges[] = {
   // 1
Index: clang/lib/Lex/Lexer.cpp
===
--- clang/lib/Lex/Lexer.cpp
+++ clang/lib/Lex/Lexer.cpp
@@ -1457,7 +1457,30 @@
   return UnicodeWhitespaceChars.contains(Codepoint);
 }
 
-static bool isAllowedIDChar(uint32_t C, const LangOptions ) {
+static llvm::SmallString<5> codepointAsHexString(uint32_t C) {
+  llvm::SmallString<5> CharBuf;
+  llvm::raw_svector_ostream CharOS(CharBuf);
+  llvm::write_hex(CharOS, C, llvm::HexPrintStyle::Upper, 4);
+  return CharBuf;
+}
+
+// To mitigate https://github.com/llvm/llvm-project/issues/54732,
+// we allow "Mathematical Notation Characters" in identifiers.
+// This is a proposed profile that extends the XID_Start/XID_continue
+// with mathematical symbols, superscipts and subscripts digits
+// found in some production software.
+// 

[PATCH] D134410: [clang][CodeGen] Add noundef metadata to load instructions (preliminary 1 or 2)

2022-10-30 Thread Nuno Lopes via Phabricator via cfe-commits
nlopes added a comment.

In D134410#3895077 , @nikic wrote:

> In D134410#3894995 , @nlopes wrote:
>
>> We wanted this patch to make us switch uninitialized loads to poison at 
>> will, since they become UB. In practice, this helps us fixing bugs in SROA 
>> and etc without perf degradation.
>
> Can you elaborate on this? I don't see how this is necessary for switching 
> uninitialized loads to poison.

It's not mandatory, it's a simple way of achieving it as !noundef already 
exists.

We cannot change the default behavior of load as it would break BC. An 
alternative is to introduce a new !poison_on_unint for loads. Clang could use 
that on all loads except those for bit-fields.
Our suggestion is to jump straight to !noundef.
To fully remove undef, then we need to swtich loads to return `freeze poison` 
rather than undef on uninitialized access, but only after we are able to yield 
poison in the common case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134410

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


[PATCH] D134410: [clang][CodeGen] Add noundef metadata to load instructions (preliminary 1 or 2)

2022-10-30 Thread John McIver via Phabricator via cfe-commits
jmciver updated this revision to Diff 471878.
jmciver added a comment.
Herald added subscribers: kosarev, kerbowa, jvesely.

Updating D134410 : [clang][CodeGen] Add 
noundef metadata to load instructions (preliminary 1 or 2)

Fix AMD-GPU, ARM, PowerPC, and new OpenMP tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134410

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CGExpr.cpp
  clang/test/CodeGen/X86/avx-builtins.c
  clang/test/CodeGen/X86/avx512bw-builtins.c
  clang/test/CodeGen/X86/avx512f-builtins.c
  clang/test/CodeGen/X86/avx512fp16-builtins.c
  clang/test/CodeGen/X86/avx512vl-builtins.c
  clang/test/CodeGen/X86/avx512vlbw-builtins.c
  clang/test/CodeGen/X86/sse-builtins.c
  clang/test/CodeGen/X86/sse2-builtins.c
  clang/test/CodeGen/aarch64-ls64-inline-asm.c
  clang/test/CodeGen/aarch64-ls64.c
  clang/test/CodeGen/aarch64-sve-acle-__ARM_FEATURE_SVE_VECTOR_OPERATORS.c
  clang/test/CodeGen/memcpy-inline-builtin.c
  clang/test/CodeGen/tbaa-array.cpp
  clang/test/CodeGen/tbaa-base.cpp
  clang/test/CodeGen/tbaa.cpp
  clang/test/CodeGen/ubsan-pass-object-size.c
  clang/test/CodeGenCUDA/amdgpu-kernel-arg-pointer-type.cu
  clang/test/CodeGenCXX/attr-likelihood-if-branch-weights.cpp
  clang/test/CodeGenCXX/attr-likelihood-switch-branch-weights.cpp
  clang/test/CodeGenCXX/builtin-bit-cast-no-tbaa.cpp
  clang/test/CodeGenCXX/debug-info-line.cpp
  clang/test/CodeGenCXX/pr12251.cpp
  clang/test/CodeGenCXX/pragma-followup_inner.cpp
  clang/test/OpenMP/cancel_codegen.cpp
  clang/test/OpenMP/cancellation_point_codegen.cpp
  clang/test/OpenMP/distribute_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_reduction_task_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_simd_private_codegen.cpp
  clang/test/OpenMP/distribute_parallel_for_simd_proc_bind_codegen.cpp
  clang/test/OpenMP/distribute_simd_codegen.cpp
  clang/test/OpenMP/distribute_simd_private_codegen.cpp
  clang/test/OpenMP/distribute_simd_reduction_codegen.cpp
  clang/test/OpenMP/for_reduction_task_codegen.cpp
  clang/test/OpenMP/irbuilder_safelen.cpp
  clang/test/OpenMP/irbuilder_safelen_order_concurrent.cpp
  clang/test/OpenMP/irbuilder_simd_aligned.cpp
  clang/test/OpenMP/irbuilder_simdlen.cpp
  clang/test/OpenMP/irbuilder_simdlen_safelen.cpp
  clang/test/OpenMP/master_taskloop_in_reduction_codegen.cpp
  clang/test/OpenMP/master_taskloop_simd_in_reduction_codegen.cpp
  clang/test/OpenMP/nvptx_target_parallel_reduction_codegen_tbaa_PR46146.cpp
  clang/test/OpenMP/ordered_codegen.cpp
  clang/test/OpenMP/parallel_for_reduction_task_codegen.cpp
  clang/test/OpenMP/parallel_for_simd_aligned_codegen.cpp
  clang/test/OpenMP/parallel_for_simd_codegen.cpp
  clang/test/OpenMP/parallel_master_reduction_task_codegen.cpp
  clang/test/OpenMP/parallel_master_taskloop_codegen.cpp
  clang/test/OpenMP/parallel_master_taskloop_lastprivate_codegen.cpp
  clang/test/OpenMP/parallel_master_taskloop_simd_codegen.cpp
  clang/test/OpenMP/parallel_master_taskloop_simd_lastprivate_codegen.cpp
  clang/test/OpenMP/parallel_reduction_task_codegen.cpp
  clang/test/OpenMP/parallel_sections_reduction_task_codegen.cpp
  clang/test/OpenMP/sections_reduction_task_codegen.cpp
  clang/test/OpenMP/target_defaultmap_codegen_01.cpp
  clang/test/OpenMP/target_in_reduction_codegen.cpp
  clang/test/OpenMP/target_is_device_ptr_codegen.cpp
  clang/test/OpenMP/target_map_codegen_00.cpp
  clang/test/OpenMP/target_map_codegen_01.cpp
  clang/test/OpenMP/target_map_codegen_02.cpp
  clang/test/OpenMP/target_map_codegen_04.cpp
  clang/test/OpenMP/target_map_codegen_05.cpp
  clang/test/OpenMP/target_map_codegen_07.cpp
  clang/test/OpenMP/target_map_codegen_11.cpp
  clang/test/OpenMP/target_map_codegen_13.cpp
  clang/test/OpenMP/target_map_codegen_14.cpp
  clang/test/OpenMP/target_map_codegen_15.cpp
  clang/test/OpenMP/target_map_codegen_17.cpp
  clang/test/OpenMP/target_map_codegen_26.cpp
  clang/test/OpenMP/target_map_codegen_27.cpp
  clang/test/OpenMP/target_map_codegen_29.cpp
  clang/test/OpenMP/target_parallel_codegen.cpp
  clang/test/OpenMP/target_parallel_for_codegen.cpp
  clang/test/OpenMP/target_parallel_for_reduction_task_codegen.cpp
  clang/test/OpenMP/target_parallel_for_simd_codegen.cpp
  clang/test/OpenMP/target_parallel_reduction_task_codegen.cpp
  clang/test/OpenMP/target_teams_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_parallel_for_order_codegen.cpp
  
clang/test/OpenMP/target_teams_distribute_parallel_for_reduction_task_codegen.cpp
  
clang/test/OpenMP/target_teams_distribute_parallel_for_simd_collapse_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_parallel_for_simd_if_codegen.cpp
  
clang/test/OpenMP/target_teams_distribute_parallel_for_simd_proc_bind_codegen.cpp
  

[PATCH] D137043: [clang] add implicit include for Linux/gnu compatibility

2022-10-30 Thread Tao Liang via Phabricator via cfe-commits
Origami404 updated this revision to Diff 471865.
Origami404 added a comment.

I'm sorry that my patch can not pass the CI test, but I can not reproduce the CI
failure loaclly, including clang-format related problems. On my machine, 
`ninja check-clang` shows:

  [0/1] Running the Clang regression tests
  llvm-lit: 
/home/origami/llvm/llvm-project/llvm/utils/lit/lit/llvm/config.py:456: note: 
using clang: /home/origami/llvm/llvm-project/build-release/bin/clang
  
  Testing Time: 183.65s
Skipped  :35
Unsupported  :  1681
Passed   : 29839
Expectedly Failed:26

And `git clang-format HEAD~1` show:

  clang-format did not modify any files

I am on Fedora 36, with clang-format 14.0.5 and python 3.10.7. I guess the test
failure maybe lead to incorrect platform setting, so I change the new regression
test in this patch to only run on Linux now by adding `-target` triple.

I am not familiar with the LLVM pybindings, but I will be more than appreciative
if someone can tell me how to fix the CI failure.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137043

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Lex/PreprocessorOptions.h
  clang/lib/Driver/Job.cpp
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/lib/Driver/ToolChains/Linux.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/test/ClangScanDeps/Inputs/has_include_if_elif.json
  clang/test/ClangScanDeps/Inputs/header_stat_before_open_cdb.json
  clang/test/ClangScanDeps/Inputs/headerwithdirname.json
  clang/test/ClangScanDeps/Inputs/headerwithdirnamefollowedbyinclude.json
  clang/test/ClangScanDeps/Inputs/module_fmodule_name_cdb.json
  clang/test/ClangScanDeps/Inputs/modules-context-hash/cdb_a.json.template
  clang/test/ClangScanDeps/Inputs/modules-context-hash/cdb_b.json.template
  clang/test/ClangScanDeps/Inputs/modules-pch-common-submodule/cdb_pch.json
  clang/test/ClangScanDeps/Inputs/modules-pch-common-submodule/cdb_tu.json
  clang/test/ClangScanDeps/Inputs/modules-pch-common-via-submodule/cdb_pch.json
  clang/test/ClangScanDeps/Inputs/modules-pch-common-via-submodule/cdb_tu.json
  clang/test/ClangScanDeps/Inputs/modules-pch/cdb_pch.json
  clang/test/ClangScanDeps/Inputs/modules-pch/cdb_tu.json
  clang/test/ClangScanDeps/Inputs/modules-pch/cdb_tu_with_common.json
  clang/test/ClangScanDeps/Inputs/modules_cdb.json
  clang/test/ClangScanDeps/Inputs/modules_inferred_cdb.json
  clang/test/ClangScanDeps/Inputs/no-werror.json
  clang/test/ClangScanDeps/Inputs/preprocess_minimized_pragmas_cdb.json
  clang/test/ClangScanDeps/Inputs/regular_cdb.json
  clang/test/ClangScanDeps/Inputs/relative_directory.json
  clang/test/ClangScanDeps/Inputs/static-analyzer-cdb.json
  clang/test/ClangScanDeps/Inputs/subframework_header_dir_symlink_cdb.json
  clang/test/ClangScanDeps/Inputs/symlink_cdb.json
  clang/test/ClangScanDeps/Inputs/target-filename-cdb.json
  clang/test/ClangScanDeps/Inputs/vfsoverlay_cdb.json
  clang/test/ClangScanDeps/header-search-pruning-transitive.c
  clang/test/ClangScanDeps/modules-dep-args.c
  clang/test/ClangScanDeps/modules-header-sharing.m
  clang/test/ClangScanDeps/modules-implementation-module-map.c
  clang/test/ClangScanDeps/modules-implicit-dot-private.m
  clang/test/ClangScanDeps/modules-incomplete-umbrella.c
  clang/test/ClangScanDeps/modules-no-undeclared-includes.c
  clang/test/Driver/Inputs/stdc-predef/usr/include/stdc-predef.h
  clang/test/Driver/stdc-predef.c
  clang/test/Driver/stdc-predef.i
  clang/unittests/Tooling/TestVisitor.h
  clang/unittests/libclang/LibclangTest.cpp

Index: clang/unittests/libclang/LibclangTest.cpp
===
--- clang/unittests/libclang/LibclangTest.cpp
+++ clang/unittests/libclang/LibclangTest.cpp
@@ -366,8 +366,11 @@
 "printf(\"mmm!!\");\n"
 "#endif");
 
-  ClangTU = clang_parseTranslationUnit(Index, Main.c_str(), nullptr, 0,
-   nullptr, 0, TUFlags);
+  const char *argv[] = {"-ffreestanding"};
+  const int argc = sizeof(argv) / sizeof(*argv);
+
+  ClangTU = clang_parseTranslationUnit(Index, Main.c_str(), argv, argc, nullptr,
+   0, TUFlags);
 
   CXSourceRangeList *Ranges = clang_getAllSkippedRanges(ClangTU);
   EXPECT_EQ(2U, Ranges->count);
@@ -607,6 +610,9 @@
 "printf(\"mmm!!\");\n"
 "#endif");
 
+  const char *argv[] = {"-ffreestanding"};
+  const int argc = sizeof(argv) / sizeof(*argv);
+
   for (int i = 0; i != 3; ++i) {
 unsigned flags = TUFlags | CXTranslationUnit_PrecompiledPreamble;
 if (i == 2)
@@ -616,7 +622,7 @@
clang_disposeTranslationUnit(ClangTU);  // dispose from previous iter
 
 // parse once
-ClangTU = clang_parseTranslationUnit(Index, Main.c_str(), nullptr, 0,
+ClangTU = clang_parseTranslationUnit(Index, Main.c_str(), argv, argc,
 

[PATCH] D134410: [clang][CodeGen] Add noundef metadata to load instructions (preliminary 1 or 2)

2022-10-30 Thread Thorsten via Phabricator via cfe-commits
tschuett added a comment.

Almost all flags are off by default. That's why they are called flags, i.e., 
`-Weverything`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134410

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


[PATCH] D135858: [clang][Interp] Support pointer arithmetic in binary operators

2022-10-30 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik accepted this revision.
shafik added a comment.
This revision is now accepted and ready to land.

LGTM


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

https://reviews.llvm.org/D135858

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


[PATCH] D134410: [clang][CodeGen] Add noundef metadata to load instructions (preliminary 1 or 2)

2022-10-30 Thread Thorsten via Phabricator via cfe-commits
tschuett added inline comments.



Comment at: clang/lib/CodeGen/CGExpr.cpp:676
+namespace {
+void applyNoundefToLoadInst(bool enable, const clang::QualType ,
+llvm::LoadInst *Load) {

Nit: You meant static.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134410

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


[PATCH] D134410: [clang][CodeGen] Add noundef metadata to load instructions (preliminary 1 or 2)

2022-10-30 Thread Nikita Popov via Phabricator via cfe-commits
nikic added a comment.

In D134410#3894995 , @nlopes wrote:

> We wanted this patch to make us switch uninitialized loads to poison at will, 
> since they become UB. In practice, this helps us fixing bugs in SROA and etc 
> without perf degradation.

Can you elaborate on this? I don't see how this is necessary for switching 
uninitialized loads to poison.

> As long as ubsan/valgrind can detect these uninitialized loads, I think we 
> should be ok to deploy this change.

Valgrind cannot detect uninitialized loads, it only detects branching on 
uninitialized data. Valgrind works on the assembly level, and as such does not 
have the necessary information to tell whether a mov of uninitialized data is 
problematic or not.

The only sanitizer that can detect this is msan (with the patch referenced 
above), which is incidentally also the sanitizer that sees the least use in 
practice, because it is much harder to deploy than ubsan and asan.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134410

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


[PATCH] D137043: [clang] add implicit include for Linux/gnu compatibility

2022-10-30 Thread Sam James via Phabricator via cfe-commits
thesamesam added a comment.

Thanks for the CC. Yep, I had the same adventure with libedit and was very 
confused for a moment until we dug into it and realised: 
https://bugs.gentoo.org/870001.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137043

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


[PATCH] D137043: [clang] add implicit include for Linux/gnu compatibility

2022-10-30 Thread YingChi Long via Phabricator via cfe-commits
inclyc added a comment.

> That is OK for glibc system because glibc includes this file manually. But 
> with other libc (e.g. musl), which does not manually include this, clang will 
> fail but GCC can get it compiled.

FWIW currently we cannot build libedit using clang on x86_64-unknown-linux-musl 
and to fix this issue, they have a workaround here 
https://patchwork.ozlabs.org/project/buildroot/patch/1452127277-9538-1-git-send-email-sergio.pr...@e-labworks.com/
 which manually defined `__STDC_ISO_10646__`

Reproducer:

  #include 
  // #include 
  
  int main() {
  printf("%d", __STDC_ISO_10646__);
  }

GCC accepted this code but clang complained `use of undeclared identifier 
'__STDC_ISO_10646__'`

  test.c:5:15: error: use of undeclared identifier '__STDC_ISO_10646__'
  printf("%d", __STDC_ISO_10646__);
   ^
  1 error generated.

Note that glibc includes `stdc-predefs.h` at the source-code level, so this 
problem cannot be reproduced on the glibc-based systems. (The header `stdio.h` 
actually #includes `stdc-predefs.h` in glibc!)

However if we do not #include `stdio.h`, different behaviors can be seen on 
glibc platforms.

  int main() {
return __STDC_ISO_10646__;
  }

See https://godbolt.org/z/Gd9Kbn766.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137043

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


[PATCH] D137043: [clang] add implicit include for Linux/gnu compatibility

2022-10-30 Thread Tao Liang via Phabricator via cfe-commits
Origami404 created this revision.
Herald added a project: All.
Origami404 added reviewers: aaron.ballman, erichkeane, mgorny, jyknight, 
mibintc, clang-language-wg.
Origami404 published this revision for review.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

On GNU/Linux, GCC will automatically include `stdc-predefs.h`, while clang does
not. That is OK for glibc system because glibc includes this file manually. But
with other libc (e.g. musl), which does not manually include this, clang will
fail but GCC can get it compiled.

In 2017, D34158  try to introduce a new flag 
called `fsystem-include-if-exists`
to fix this, but it was reverted. Nearly, D106577 
 points out that macro
`__STDC_ISO_10646__` was indeed needed, which is defined in `stdc-predefs.h`.
After a discussion, the community reaches a consensus, to make this macro
available with a D34158 -like method.

In this patch, we port the patch in D34158  
into the current clang codebase. The
change is almost the same with D34158 , but we 
change some tests to suit current
codes:

1. c-index-test now does not accept a `-ffreestanding` flag, and it should not.

We choose to disable this pre-include action in Objective-C because it will
cause some c-index-test's tests on Objective-C to fail.

2. Some unit tests about parsing and re-parsing will be affected by this change.

To keep such tests passed, we add `-ffreestanding` flags to them.

3. The new tool, Clang-Scan-Deps, will analyze all header files to find

dependencies. After we add an implicit include, its result will have an extra
`stdc-predefs.h`. Currently, we choose to add `-ffreestanding` flags to all the
affected tests for it. But maybe making it ignore the default header will be a
better choice.

Signed-off-by: Tao Liang 
Co-authored-by: YingChi Long 

Link: https://reviews.llvm.org/D34158
Link: https://gcc.gnu.org/gcc-4.8/porting_to.html
Link: https://reviews.llvm.org/D106577


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137043

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Lex/PreprocessorOptions.h
  clang/lib/Driver/Job.cpp
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/lib/Driver/ToolChains/Linux.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/test/ClangScanDeps/Inputs/has_include_if_elif.json
  clang/test/ClangScanDeps/Inputs/header_stat_before_open_cdb.json
  clang/test/ClangScanDeps/Inputs/headerwithdirname.json
  clang/test/ClangScanDeps/Inputs/headerwithdirnamefollowedbyinclude.json
  clang/test/ClangScanDeps/Inputs/module_fmodule_name_cdb.json
  clang/test/ClangScanDeps/Inputs/modules-context-hash/cdb_a.json.template
  clang/test/ClangScanDeps/Inputs/modules-context-hash/cdb_b.json.template
  clang/test/ClangScanDeps/Inputs/modules-pch-common-submodule/cdb_pch.json
  clang/test/ClangScanDeps/Inputs/modules-pch-common-submodule/cdb_tu.json
  clang/test/ClangScanDeps/Inputs/modules-pch-common-via-submodule/cdb_pch.json
  clang/test/ClangScanDeps/Inputs/modules-pch-common-via-submodule/cdb_tu.json
  clang/test/ClangScanDeps/Inputs/modules-pch/cdb_pch.json
  clang/test/ClangScanDeps/Inputs/modules-pch/cdb_tu.json
  clang/test/ClangScanDeps/Inputs/modules-pch/cdb_tu_with_common.json
  clang/test/ClangScanDeps/Inputs/modules_cdb.json
  clang/test/ClangScanDeps/Inputs/modules_inferred_cdb.json
  clang/test/ClangScanDeps/Inputs/no-werror.json
  clang/test/ClangScanDeps/Inputs/preprocess_minimized_pragmas_cdb.json
  clang/test/ClangScanDeps/Inputs/regular_cdb.json
  clang/test/ClangScanDeps/Inputs/relative_directory.json
  clang/test/ClangScanDeps/Inputs/static-analyzer-cdb.json
  clang/test/ClangScanDeps/Inputs/subframework_header_dir_symlink_cdb.json
  clang/test/ClangScanDeps/Inputs/symlink_cdb.json
  clang/test/ClangScanDeps/Inputs/target-filename-cdb.json
  clang/test/ClangScanDeps/Inputs/vfsoverlay_cdb.json
  clang/test/ClangScanDeps/header-search-pruning-transitive.c
  clang/test/ClangScanDeps/modules-dep-args.c
  clang/test/ClangScanDeps/modules-header-sharing.m
  clang/test/ClangScanDeps/modules-implementation-module-map.c
  clang/test/ClangScanDeps/modules-implicit-dot-private.m
  clang/test/ClangScanDeps/modules-incomplete-umbrella.c
  clang/test/ClangScanDeps/modules-no-undeclared-includes.c
  clang/test/Driver/Inputs/stdc-predef/usr/include/stdc-predef.h
  clang/test/Driver/stdc-predef.c
  clang/test/Driver/stdc-predef.i
  clang/unittests/Tooling/TestVisitor.h
  clang/unittests/libclang/LibclangTest.cpp

Index: clang/unittests/libclang/LibclangTest.cpp
===
--- clang/unittests/libclang/LibclangTest.cpp
+++ clang/unittests/libclang/LibclangTest.cpp
@@ -366,8 +366,11 @@
 "printf(\"mmm!!\");\n"
 "#endif");
 
-  ClangTU = 

[PATCH] D134410: [clang][CodeGen] Add noundef metadata to load instructions (preliminary 1 or 2)

2022-10-30 Thread Nuno Lopes via Phabricator via cfe-commits
nlopes added a comment.

In D134410#3893918 , @nikic wrote:

> I think adding this under a default-disabled flag is fine for evaluation 
> purposes, but I have doubts that we will ever be able to enable this by 
> default. There is a lot of code out there assuming that copying uninitialized 
> data around is fine.

Well, I think that flags that are disabled by default don't exist and they are 
not useful.
We wanted this patch to make us switch uninitialized loads to poison at will, 
since they become UB. In practice, this helps us fixing bugs in SROA and etc 
without perf degradation.
As long as ubsan/valgrind can detect these uninitialized loads, I think we 
should be ok to deploy this change. We are touching memcpys yet, at least, as 
those may be susceptible to handling uninit memory.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134410

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


[PATCH] D137040: [clangd] Add heuristic for dropping snippet when completing member function pointer

2022-10-30 Thread Tom Praschan via Phabricator via cfe-commits
tom-anders created this revision.
Herald added subscribers: kadircet, arphaman.
Herald added a project: All.
tom-anders requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

This implements the 1st heuristic mentioned in 
https://github.com/clangd/clangd/issues/968#issuecomment-1002242704:

When completing a function that names a non-static member of a class, and we 
are not inside that class's scope, assume the reference will not be a call (and 
thus don't add the snippetSuffix)


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137040

Files:
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp

Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -500,6 +500,63 @@
  snippetSuffix("(${1:int i}, ${2:const float f})")));
 }
 
+TEST(CompletionTest, HeuristicsForMemberFunctionCompletion) {
+  clangd::CodeCompleteOptions Opts;
+  Opts.EnableSnippets = true;
+
+  Annotations Code(R"cpp(
+  struct Foo {
+static int staticMethod();
+int method() const;
+Foo() {
+  this->$keepSnippet^
+  $keepSnippet^
+  Foo::$keepSnippet^
+}
+  };
+
+  struct Derived : Foo {
+Derived() {
+  Foo::$keepSnippet^
+}
+  };
+
+  struct OtherClass {
+OtherClass() {
+  Foo f;
+  f.$keepSnippet^
+  ::$noSnippet^
+}
+  };
+
+  int main() {
+Foo f;
+f.$keepSnippet^
+::$noSnippet^
+  }
+  )cpp");
+  auto TU = TestTU::withCode(Code.code());
+
+  for (const auto  : Code.points("noSnippet")) {
+auto Results = completions(TU, P, /*IndexSymbols*/ {}, Opts);
+EXPECT_THAT(Results.Completions,
+Contains(AllOf(named("method"), snippetSuffix("";
+  }
+
+  for (const auto  : Code.points("keepSnippet")) {
+auto Results = completions(TU, P, /*IndexSymbols*/ {}, Opts);
+EXPECT_THAT(Results.Completions,
+Contains(AllOf(named("method"), snippetSuffix("()";
+  }
+
+  // static method will always keep the snippet
+  for (const auto  : Code.points()) {
+auto Results = completions(TU, P, /*IndexSymbols*/ {}, Opts);
+EXPECT_THAT(Results.Completions,
+Contains(AllOf(named("staticMethod"), snippetSuffix("()";
+  }
+}
+
 TEST(CompletionTest, NoSnippetsInUsings) {
   clangd::CodeCompleteOptions Opts;
   Opts.EnableSnippets = true;
Index: clang-tools-extra/clangd/CodeComplete.cpp
===
--- clang-tools-extra/clangd/CodeComplete.cpp
+++ clang-tools-extra/clangd/CodeComplete.cpp
@@ -291,7 +291,8 @@
 // computed from the first candidate, in the constructor.
 // Others vary per candidate, so add() must be called for remaining candidates.
 struct CodeCompletionBuilder {
-  CodeCompletionBuilder(ASTContext *ASTCtx, const CompletionCandidate ,
+  CodeCompletionBuilder(ASTContext *ASTCtx, DeclContext *SemaDeclCtx,
+const CompletionCandidate ,
 CodeCompletionString *SemaCCS,
 llvm::ArrayRef QueryScopes,
 const IncludeInserter ,
@@ -299,13 +300,15 @@
 CodeCompletionContext::Kind ContextKind,
 const CodeCompleteOptions ,
 bool IsUsingDeclaration, tok::TokenKind NextTokenKind)
-  : ASTCtx(ASTCtx),
+  : ASTCtx(ASTCtx), SemaDeclCtx(SemaDeclCtx),
 EnableFunctionArgSnippets(Opts.EnableFunctionArgSnippets),
-IsUsingDeclaration(IsUsingDeclaration), NextTokenKind(NextTokenKind) {
+ContextKind(ContextKind), IsUsingDeclaration(IsUsingDeclaration),
+NextTokenKind(NextTokenKind) {
 Completion.Deprecated = true; // cleared by any non-deprecated overload.
 add(C, SemaCCS);
 if (C.SemaResult) {
   assert(ASTCtx);
+  assert(SemaDeclCtx);
   Completion.Origin |= SymbolOrigin::AST;
   Completion.Name = std::string(llvm::StringRef(SemaCCS->getTypedText()));
   Completion.FilterText = SemaCCS->getAllTypedText();
@@ -412,6 +415,8 @@
   getSignature(*SemaCCS, , ,
, IsPattern);
   S.ReturnType = getReturnType(*SemaCCS);
+  maybeClearSnippetSuffixForMethodFunctionPointer(*C.SemaResult,
+  S.SnippetSuffix);
 } else if (C.IndexResult) {
   S.Signature = std::string(C.IndexResult->Signature);
   S.SnippetSuffix = std::string(C.IndexResult->CompletionSnippetSuffix);
@@ -570,11 +575,57 @@
 return "(…)";
   }
 
+  // Clear snippet when completing a non-static member function (and 

[PATCH] D136533: [clang] Fix missing diagnostic of declaration use when accessing TypeDecls through typename access

2022-10-30 Thread Nico Weber via Phabricator via cfe-commits
thakis added subscribers: aeubanks, hans.
thakis added a comment.

Adding @hans @aeubanks since they were involved over there too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136533

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


[PATCH] D136533: [clang] Fix missing diagnostic of declaration use when accessing TypeDecls through typename access

2022-10-30 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

In D136533#3893032 , @ldionne wrote:

> In D136533#3892949 , @ldionne wrote:
>
>> 2. Shipping this change does mean that anyone building anything with a new 
>> Clang and a not-yet-updated libc++ with a deployment target before 10.15 (or 
>> whatever first version we shipped filesystem in) will fail. IMO that's kind 
>> of annoying, but may be OK if we fix libc++ first.
>
> I guess the interesting question here would be: @thakis, is there a reason 
> why you are using the SDK-provided libc++ but the tip-of-trunk Clang for 
> building Chrome? (I feel like we've talked about this before but I don't 
> remember).

Because that's what you recommended :) We used to use the just-built libc++ but 
that had other issues.

Previous discussions that I found in a hurry: 
https://reviews.llvm.org/D128927#3670288 , and 
https://reviews.llvm.org/D82702#2153627 and onward.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136533

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


[clang-tools-extra] e125e6c - [clang-tools-extra] Use llvm::find (NFC)

2022-10-30 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2022-10-30T09:41:55-07:00
New Revision: e125e6c429e16741b128b2cab3787cdc57e166c6

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

LOG: [clang-tools-extra] Use llvm::find (NFC)

Added: 


Modified: 
clang-tools-extra/clang-doc/Generators.cpp
clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.cpp
clang-tools-extra/clang-tidy/misc/MisleadingBidirectional.cpp
clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
clang-tools-extra/clangd/InlayHints.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-doc/Generators.cpp 
b/clang-tools-extra/clang-doc/Generators.cpp
index 591d43322342f..da19c05ab67b9 100644
--- a/clang-tools-extra/clang-doc/Generators.cpp
+++ b/clang-tools-extra/clang-doc/Generators.cpp
@@ -65,7 +65,7 @@ void Generator::addInfoToIndex(Index , const doc::Info 
*Info) {
   for (const auto  : llvm::reverse(Info->Namespace)) {
 // Look for the current namespace in the children of the index I is
 // pointing.
-auto It = std::find(I->Children.begin(), I->Children.end(), R.USR);
+auto It = llvm::find(I->Children, R.USR);
 if (It != I->Children.end()) {
   // If it is found, just change I to point the namespace reference found.
   I = &*It;
@@ -79,7 +79,7 @@ void Generator::addInfoToIndex(Index , const doc::Info 
*Info) {
   // Look for Info in the vector where it is supposed to be; it could already
   // exist if it is a parent namespace of an Info already passed to this
   // function.
-  auto It = std::find(I->Children.begin(), I->Children.end(), Info->USR);
+  auto It = llvm::find(I->Children, Info->USR);
   if (It == I->Children.end()) {
 // If it is not in the vector it is inserted
 I->Children.emplace_back(Info->USR, Info->extractName(), Info->IT,

diff  --git a/clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.cpp 
b/clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.cpp
index aa8300ced63ac..73e28fb2b6342 100644
--- a/clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/ConfusableIdentifierCheck.cpp
@@ -78,8 +78,7 @@ std::string ConfusableIdentifierCheck::skeleton(StringRef 
Name) {
   UTF8 *BufferStart = std::begin(Buffer);
   UTF8 *IBuffer = BufferStart;
   const UTF32 *ValuesStart = std::begin(Where->values);
-  const UTF32 *ValuesEnd =
-  std::find(std::begin(Where->values), std::end(Where->values), '\0');
+  const UTF32 *ValuesEnd = llvm::find(Where->values, '\0');
   if (ConvertUTF32toUTF8(, ValuesEnd, ,
  std::end(Buffer),
  strictConversion) != conversionOK) {

diff  --git a/clang-tools-extra/clang-tidy/misc/MisleadingBidirectional.cpp 
b/clang-tools-extra/clang-tidy/misc/MisleadingBidirectional.cpp
index 7cd6fc338695c..c2948451ac5f0 100644
--- a/clang-tools-extra/clang-tidy/misc/MisleadingBidirectional.cpp
+++ b/clang-tools-extra/clang-tidy/misc/MisleadingBidirectional.cpp
@@ -75,7 +75,7 @@ static bool containsMisleadingBidi(StringRef Buffer,
   BidiContexts.push_back(PDI);
 // Close a PDI Context.
 else if (CodePoint == PDI) {
-  auto R = std::find(BidiContexts.rbegin(), BidiContexts.rend(), PDI);
+  auto R = llvm::find(llvm::reverse(BidiContexts), PDI);
   if (R != BidiContexts.rend())
 BidiContexts.resize(BidiContexts.rend() - R - 1);
 }

diff  --git 
a/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp 
b/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
index 00f4b00f53819..a8ca761d435f3 100644
--- a/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
+++ b/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
@@ -120,8 +120,7 @@ void UnnecessaryValueParamCheck::check(const 
MatchFinder::MatchResult ) {
 }
   }
 
-  const size_t Index = std::find(Function->parameters().begin(),
- Function->parameters().end(), Param) -
+  const size_t Index = llvm::find(Function->parameters(), Param) -
Function->parameters().begin();
 
   auto Diag =

diff  --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index 16c6b1cecc031..1d13a13521cd1 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -581,9 +581,8 @@ class InlayHintVisitor : public 
RecursiveASTVisitor {
   static const ParmVarDecl *getParamDefinition(const ParmVarDecl *P) {
 if (auto *Callee = dyn_cast(P->getDeclContext())) {
   if (auto *Def = Callee->getDefinition()) {
-auto I = std::distance(
-Callee->param_begin(),
-

[PATCH] D136844: [libclang] Expose completion result kind in `CXCompletionResult`

2022-10-30 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan added inline comments.
Herald added subscribers: Michael137, JDevlieghere.



Comment at: clang/include/clang/Sema/CodeCompleteConsumer.h:755
-  /// Describes the kind of result generated.
-  enum ResultKind {
-/// Refers to a declaration.

kadircet wrote:
> i don't follow the reason for replacing this struct with 
> `CXCompletionResultKind` and renaming occurrences in half of the codebase. 
> can we keep this around, introduce the new enum type into `Index.h` and have 
> `clang/tools/libclang/CIndexCodeCompletion.cpp` do the conversion from Sema 
> type to Index type instead?
> 
> Unless I am missing some other requirement for doing so. i feel like the 
> conceptual dependency from Sema to Index is one we should get rid of, rather 
> than make tighter.
This was mostly done to be consistent with the way `CXCursorKind` and 
`CXAvailabilityKind` are declared in `Index.h` and used as fields of 
`CodeCompletionResult`. I think updating the enum name in a few source files 
shouldn't be a major problem, but I can avoid it if you feel strongly against 
this approach.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136844

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


[PATCH] D136844: [libclang] Expose completion result kind in `CXCompletionResult`

2022-10-30 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan updated this revision to Diff 471838.
egorzhdan added a comment.
Herald added a project: LLDB.
Herald added a subscriber: lldb-commits.

Fix clangd compilation


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136844

Files:
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/CodeCompletionStrings.cpp
  clang-tools-extra/clangd/Quality.cpp
  clang/include/clang-c/Index.h
  clang/include/clang/Sema/CodeCompleteConsumer.h
  clang/lib/Frontend/ASTUnit.cpp
  clang/lib/Sema/CodeCompleteConsumer.cpp
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/Index/arc-complete.m
  clang/test/Index/code-completion.cpp
  clang/test/Index/complete-at-directives.m
  clang/test/Index/complete-at-exprstmt.m
  clang/test/Index/complete-declarators.cpp
  clang/test/Index/complete-declarators.m
  clang/test/Index/complete-exprs.c
  clang/test/Index/complete-exprs.cpp
  clang/test/Index/complete-exprs.m
  clang/test/Index/complete-lambdas.cpp
  clang/test/Index/complete-lambdas.mm
  clang/test/Index/complete-memfunc-cvquals.cpp
  clang/test/Index/complete-method-decls.m
  clang/test/Index/complete-modules.m
  clang/test/Index/complete-preprocessor.m
  clang/test/Index/complete-recovery.m
  clang/test/Index/complete-stmt.c
  clang/test/Index/complete-super.cpp
  clang/test/Index/complete-synthesized.m
  clang/test/Index/complete-type-factors.m
  clang/tools/c-index-test/c-index-test.c
  clang/tools/libclang/CIndex.cpp
  clang/tools/libclang/CIndexCodeCompletion.cpp
  clang/tools/libclang/libclang.map
  lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp

Index: lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
===
--- lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
+++ lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
@@ -859,15 +859,15 @@
CodeCompletionResult Result) override {
 // This code is mostly copied from CodeCompleteConsumer.
 switch (Result.Kind) {
-case CodeCompletionResult::RK_Declaration:
+case CXCompletionResult_Declaration:
   return !(
   Result.Declaration->getIdentifier() &&
   Result.Declaration->getIdentifier()->getName().startswith(Filter));
-case CodeCompletionResult::RK_Keyword:
+case CXCompletionResult_Keyword:
   return !StringRef(Result.Keyword).startswith(Filter);
-case CodeCompletionResult::RK_Macro:
+case CXCompletionResult_Macro:
   return !Result.Macro->getName().startswith(Filter);
-case CodeCompletionResult::RK_Pattern:
+case CXCompletionResult_Pattern:
   return !StringRef(Result.Pattern->getAsString()).startswith(Filter);
 }
 // If we trigger this assert or the above switch yields a warning, then
@@ -894,7 +894,7 @@
 std::string Description;
 // Handle the different completion kinds that come from the Sema.
 switch (R.Kind) {
-case CodeCompletionResult::RK_Declaration: {
+case CXCompletionResult_Declaration: {
   const NamedDecl *D = R.Declaration;
   ToInsert = R.Declaration->getNameAsString();
   // If we have a function decl that has no arguments we want to
@@ -920,13 +920,13 @@
   }
   break;
 }
-case CodeCompletionResult::RK_Keyword:
+case CXCompletionResult_Keyword:
   ToInsert = R.Keyword;
   break;
-case CodeCompletionResult::RK_Macro:
+case CXCompletionResult_Macro:
   ToInsert = R.Macro->getName().str();
   break;
-case CodeCompletionResult::RK_Pattern:
+case CXCompletionResult_Pattern:
   ToInsert = R.Pattern->getTypedText();
   break;
 }
Index: clang/tools/libclang/libclang.map
===
--- clang/tools/libclang/libclang.map
+++ clang/tools/libclang/libclang.map
@@ -4,6 +4,10 @@
 # On platforms where versions scripts are not used, this file will be used to
 # generate a list of exports for libclang.so
 
+LLVM_15 {
+  global:
+clang_getCompletionResultKindSpelling;
+}
 LLVM_13 {
   global:
 clang_BlockCommandComment_getArgText;
Index: clang/tools/libclang/CIndexCodeCompletion.cpp
===
--- clang/tools/libclang/CIndexCodeCompletion.cpp
+++ clang/tools/libclang/CIndexCodeCompletion.cpp
@@ -586,6 +586,7 @@
   includeBriefComments());
 
 CXCompletionResult R;
+R.ResultKind = Results[I].Kind;
 R.CursorKind = Results[I].CursorKind;
 R.CompletionString = StoredCompletion;
 StoredResults.push_back(R);
@@ -666,6 +667,7 @@
 includeBriefComments(), Braced);
 
 CXCompletionResult R;
+R.ResultKind = CXCompletionResult_Declaration;
 R.CursorKind = 

[clang] 63a3a06 - Fix the clang Sphinx build

2022-10-30 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-10-30T08:59:33-04:00
New Revision: 63a3a067d0ad5b243dbd9f993c2515dcc630cce2

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

LOG: Fix the clang Sphinx build

This should address the issue found in:
https://lab.llvm.org/buildbot/#/builders/92/builds/34906

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 1911af6511b0..0416190a2fd5 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -914,6 +914,7 @@ the configuration (without a prefix: ``Auto``).
 
 
   int abcdef; // aligned
+
 And with ``MaxEmptyLinesToKeep`` is 2 and ``OverEmptyLines`` is 1,
 
 .. code-block:: c++



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


[PATCH] D132131: [clang-format] Adds a formatter for aligning trailing comments over empty lines

2022-10-30 Thread MyDeveloperDay 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 rG3edc1210a49d: [clang-format] Adds a formatter for aligning 
trailing comments over empty lines (authored by yusuke-kadowaki, committed by 
MyDeveloperDay).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132131

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/WhitespaceManager.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/FormatTestComments.cpp

Index: clang/unittests/Format/FormatTestComments.cpp
===
--- clang/unittests/Format/FormatTestComments.cpp
+++ clang/unittests/Format/FormatTestComments.cpp
@@ -2858,6 +2858,224 @@
"int a; //\n");
 }
 
+TEST_F(FormatTestComments, AlignTrailingCommentsAcrossEmptyLines) {
+  FormatStyle Style = getLLVMStyle();
+  Style.AlignTrailingComments.Kind = FormatStyle::TCAS_Always;
+  Style.AlignTrailingComments.OverEmptyLines = 1;
+  verifyFormat("#include \"a.h\"  // simple\n"
+   "\n"
+   "#include \"aa.h\" // example case\n",
+   Style);
+
+  verifyFormat("#include \"a.h\"   // align across\n"
+   "\n"
+   "#include \"aa.h\"  // two empty lines\n"
+   "\n"
+   "#include \"aaa.h\" // in a row\n",
+   Style);
+
+  verifyFormat("#include \"a.h\"  // align\n"
+   "#include \"aa.h\" // comment\n"
+   "#include \"aaa.h\"// blocks\n"
+   "\n"
+   "#include \".h\"   // across\n"
+   "#include \"a.h\"  // one\n"
+   "#include \"aa.h\" // empty line\n",
+   Style);
+
+  verifyFormat("#include \"a.h\"  // align trailing comments\n"
+   "#include \"a.h\"\n"
+   "#include \"aa.h\" // across a line without comment\n",
+   Style);
+
+  verifyFormat("#include \"a.h\"   // align across\n"
+   "#include \"a.h\"\n"
+   "#include \"aa.h\"  // two lines without comment\n"
+   "#include \"a.h\"\n"
+   "#include \"aaa.h\" // in a row\n",
+   Style);
+
+  verifyFormat("#include \"a.h\"  // align\n"
+   "#include \"aa.h\" // comment\n"
+   "#include \"aaa.h\"// blocks\n"
+   "#include \"a.h\"\n"
+   "#include \".h\"   // across\n"
+   "#include \"a.h\"  // a line without\n"
+   "#include \"aa.h\" // comment\n",
+   Style);
+
+  // Start of testing OverEmptyLines
+  Style.MaxEmptyLinesToKeep = 3;
+  Style.AlignTrailingComments.OverEmptyLines = 2;
+  // Cannot use verifyFormat here
+  // test::messUp removes all new lines which changes the logic
+  EXPECT_EQ("#include \"a.h\" // comment\n"
+"\n"
+"\n"
+"\n"
+"#include \"ab.h\"  // comment\n"
+"\n"
+"\n"
+"#include \"abcdefg.h\" // comment\n",
+format("#include \"a.h\" // comment\n"
+   "\n"
+   "\n"
+   "\n"
+   "#include \"ab.h\" // comment\n"
+   "\n"
+   "\n"
+   "#include \"abcdefg.h\" // comment\n",
+   Style));
+
+  Style.MaxEmptyLinesToKeep = 1;
+  Style.AlignTrailingComments.OverEmptyLines = 1;
+  // End of testing OverEmptyLines
+
+  Style.ColumnLimit = 15;
+  EXPECT_EQ("int ab; // line\n"
+"int a;  // long\n"
+"// long\n"
+"\n"
+"// long",
+format("int ab; // line\n"
+   "int a; // long long\n"
+   "\n"
+   "// long",
+   Style));
+
+  Style.ColumnLimit = 15;
+  EXPECT_EQ("int ab; // line\n"
+"\n"
+"int a;  // long\n"
+"// long\n",
+format("int ab; // line\n"
+   "\n"
+   "int a; // long long\n",
+   Style));
+
+  Style.ColumnLimit = 30;
+  EXPECT_EQ("int foo = 12345; // comment\n"
+"int bar =\n"
+"1234;  // This is a very\n"
+"   // long comment\n"
+"   // which is wrapped\n"
+"   // arround.\n"
+"\n"
+"int x = 2; // Is this still\n"
+"   // aligned?\n",
+format("int foo = 12345; // comment\n"
+   "int bar = 1234; // This is a very long comment\n"
+   "// which is wrapped arround.\n"
+   "\n"
+   "int x = 2; // Is this still aligned?\n",

[clang] 3edc121 - [clang-format] Adds a formatter for aligning trailing comments over empty lines

2022-10-30 Thread via cfe-commits

Author: Yusuke Kadowaki
Date: 2022-10-30T12:22:39Z
New Revision: 3edc1210a49d4a666b46ace5c592a00ccb2bb350

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

LOG: [clang-format] Adds a formatter for aligning trailing comments over empty 
lines

This patch addresses https://github.com/llvm/llvm-project/issues/19756

Reviewed By: MyDeveloperDay, HazardyKnusperkeks

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/FormatTestComments.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index b52cf49ef5636..1911af6511b0d 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -846,14 +846,85 @@ the configuration (without a prefix: ``Auto``).
 
 
 
-**AlignTrailingComments** (``Boolean``) :versionbadge:`clang-format 3.7`
-  If ``true``, aligns trailing comments.
+**AlignTrailingComments** (``TrailingCommentsAlignmentStyle``) 
:versionbadge:`clang-format 3.7`
+  Control of trailing comments.
 
-  .. code-block:: c++
+  NOTE: As of clang-format 16 this option is not a bool but can be set
+  to the options. Conventional bool options still can be parsed as before.
+
+
+  .. code-block:: yaml
+
+# Example of usage:
+AlignTrailingComments:
+  Kind: Always
+  OverEmptyLines: 2
+
+  Nested configuration flags:
+
+  Alignment options
+
+  * ``TrailingCommentsAlignmentKinds Kind``
+Specifies the way to align trailing comments
+
+Possible values:
+
+* ``TCAS_Leave`` (in configuration: ``Leave``)
+  Leave trailing comments as they are.
+
+  .. code-block:: c++
+
+int a;// comment
+int ab;   // comment
+
+int abc;  // comment
+int abcd; // comment
+
+* ``TCAS_Always`` (in configuration: ``Always``)
+  Align trailing comments.
+
+  .. code-block:: c++
+
+int a;  // comment
+int ab; // comment
+
+int abc;  // comment
+int abcd; // comment
+
+* ``TCAS_Never`` (in configuration: ``Never``)
+  Don't align trailing comments but other formatter applies.
+
+  .. code-block:: c++
+
+int a; // comment
+int ab; // comment
+
+int abc; // comment
+int abcd; // comment
+
+
+  * ``unsigned OverEmptyLines`` How many empty lines to apply alignment
+With ``MaxEmptyLinesToKeep`` is 2 and ``OverEmptyLines`` is 2,
+
+.. code-block:: c++
+
+  int a;  // all these
+
+  int ab; // comments are
+
+
+  int abcdef; // aligned
+And with ``MaxEmptyLinesToKeep`` is 2 and ``OverEmptyLines`` is 1,
+
+.. code-block:: c++
+
+  int a;  // these are
+
+  int ab; // aligned
+
+
+  int abcdef; // but this isn't
 
-true:   false:
-int a; // My comment a  vs. int a; // My comment a
-int b = 2; // comment  bint b = 2; // comment about b
 
 **AllowAllArgumentsOnNextLine** (``Boolean``) :versionbadge:`clang-format 9`
   If a function call or braced initializer list doesn't fit on a

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index b90de05a162c0..6981dc158d241 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -369,14 +369,83 @@ struct FormatStyle {
   /// \version 3.5
   OperandAlignmentStyle AlignOperands;
 
-  /// If ``true``, aligns trailing comments.
-  /// \code
-  ///   true:   false:
-  ///   int a; // My comment a  vs. int a; // My comment a
-  ///   int b = 2; // comment  bint b = 2; // comment about b
+  /// Enums for AlignTrailingComments
+  enum TrailingCommentsAlignmentKinds : int8_t {
+/// Leave trailing comments as they are.
+/// \code
+///   int a;// comment
+///   int ab;   // comment
+///
+///   int abc;  // comment
+///   int abcd; // comment
+/// \endcode
+TCAS_Leave,
+/// Align trailing comments.
+/// \code
+///   int a;  // comment
+///   int ab; // comment
+///
+///   int abc;  // comment
+///   int abcd; // comment
+/// \endcode
+TCAS_Always,
+/// Don't align trailing comments but other formatter applies.
+/// \code
+///   int a; // comment
+///   int ab; // comment
+///
+///   int abc; // comment
+///   int abcd; // comment
+/// \endcode
+TCAS_Never,
+  };
+
+  /// Alignment options
+  struct 

[PATCH] D136886: [clang] ASTImporter: Fix importing of va_list types and declarations

2022-10-30 Thread Vince Bridgers via Phabricator via cfe-commits
vabridgers added a comment.

@mizvekov, thanks for posting a fix. LGTM, but someone else must approve. Best!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136886

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


[PATCH] D136925: [clangd] Index scoped enums for code completion

2022-10-30 Thread Tom Praschan via Phabricator via cfe-commits
tom-anders added inline comments.



Comment at: clang-tools-extra/clangd/CodeComplete.cpp:2133
   if (const auto *EnumDecl = dyn_cast(ND.getDeclContext()))
-return InTopLevelScope(*EnumDecl) && !EnumDecl->isScoped();
 

nridge wrote:
> Just to make sure I understand:
> 
> By also removing the `!isScoped()` condition, in addition to changing the 
> behaviour for the scenario described in 
> https://github.com/clangd/clangd/issues/1082 (enum declared at class scope), 
> you are also changing the behaviour for scenarios like this:
> 
> ```
> enum class Foo { Bar };  // at any scope, including global
> ```
> 
> Completing `Bar` will now offer `Foo::Bar` when previously it didn't.
> 
> Is this your intention?
Ah sorry, that is indeed not what I described in the issue - but yeah this 
change is intended here,  IMO it's more consistent from a user perspective: Why 
should **all-scopes**-completion ignore **scoped** enums?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136925

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


[PATCH] D129531: [clang][C++20] P0960R3: Allow initializing aggregates from a parenthesized list of values

2022-10-30 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

I added a few more comments, mostly nitpicks




Comment at: clang/lib/AST/ExprConstant.cpp:9952-9953
+const FieldDecl *Field;
+if (isa(E)) {
+  Field = cast(E)->getInitializedFieldInUnion();
+} else if (isa(E)) {





Comment at: clang/lib/AST/ExprConstant.cpp:9956
+  assert(InitExprs.size() == 1 &&
+ "Number of expressions in C++ paren list is not 1");
+

Maybe that message could be a bit more clear.

"Union should have exactly 1 initializer in in C++ paren list" or something 
like that.



Comment at: clang/lib/CodeGen/CGExprAgg.cpp:1595
 
+void AggExprEmitter::VisitCXXParenListInitExpr(CXXParenListInitExpr *E) {
+  ArrayRef InitExprs = E->getInitExprs();

There are some overlaps with `VisitInitListExpr`, I wonder if we should try to 
factor out some of the code, especially the base class initialization



Comment at: clang/lib/CodeGen/CGExprAgg.cpp:1600
+  if (const ArrayType *AT = dyn_cast(E->getType())) {
+for (auto Pair : llvm::enumerate(InitExprs)) {
+  // Initialization for every element of the array.

Maybe it would be cleaner to use a structured binding here.



Comment at: clang/lib/CodeGen/CGExprAgg.cpp:1616
+const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
+Address V = CGF.GetAddressOfDirectBaseInCompleteClass(
+Dest.getAddress(), RD, BaseRD,

Should we assert that the base is not virtual?



Comment at: clang/lib/Sema/SemaInit.cpp:5281
+
+  // Unnamed bitfields should not be initialized at all,either with an arg
+  // or by default.





Comment at: clang/lib/Sema/TreeTransform.h:13930
+ InitExprs.size(), true, TransformedInits,
+ ))
+return ExprError();

`ArgumentChanged` is not used, and is defaulted by the function, so you should 
be able to remove it


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129531

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


[PATCH] D136956: [clang][Interp] Implement BitXor opcode

2022-10-30 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 rG74fb770de939: [clang][Interp] Implement bitXor opcode 
(authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D136956?vs=471560=471820#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136956

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/Integral.h
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/Opcodes.td
  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
@@ -279,6 +279,23 @@
   static_assert((12 | true) == 13, "");
 };
 
+namespace bitXor {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wxor-used-as-pow"
+  static_assert((10 ^ 1) == 11, "");
+  static_assert((10 ^ 10) == 0, "");
+
+  enum {
+ONE = 1,
+  };
+
+  static_assert((1337 ^ -1) == -1338, "");
+  static_assert((0 | gimme(12)) == 12, "");
+  static_assert((12 ^ true) == 13, "");
+  static_assert((12 ^ ONE) == 13, "");
+#pragma clang diagnostic pop
+};
+
 #if __cplusplus >= 201402L
 constexpr bool IgnoredUnary() {
   bool bo = true;
Index: clang/lib/AST/Interp/Opcodes.td
===
--- clang/lib/AST/Interp/Opcodes.td
+++ clang/lib/AST/Interp/Opcodes.td
@@ -419,6 +419,7 @@
   let Types = [NumberTypeClass];
   let HasGroup = 1;
 }
+def BitXor : IntegerOpcode;
 
 
//===--===//
 // Unary operators.
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -211,6 +211,23 @@
   return false;
 }
 
+/// 1) Pops the RHS from the stack.
+/// 2) Pops the LHS from the stack.
+/// 3) Pushes 'LHS ^ RHS' on the stack
+template ::T>
+bool BitXor(InterpState , CodePtr OpPC) {
+  const T  = S.Stk.pop();
+  const T  = S.Stk.pop();
+
+  unsigned Bits = RHS.bitWidth();
+  T Result;
+  if (!T::bitXor(LHS, RHS, Bits, )) {
+S.Stk.push(Result);
+return true;
+  }
+  return false;
+}
+
 /// 1) Pops the RHS from the stack.
 /// 2) Pops the LHS from the stack.
 /// 3) Pushes 'LHS % RHS' on the stack (the remainder of dividing LHS by RHS).
Index: clang/lib/AST/Interp/Integral.h
===
--- clang/lib/AST/Interp/Integral.h
+++ clang/lib/AST/Interp/Integral.h
@@ -227,6 +227,11 @@
 return false;
   }
 
+  static bool bitXor(Integral A, Integral B, unsigned OpBits, Integral *R) {
+*R = Integral(A.V ^ B.V);
+return false;
+  }
+
   static bool neg(Integral A, Integral *R) {
 *R = -A;
 return false;
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -241,6 +241,8 @@
   return Discard(this->emitShl(*LT, *RT, BO));
 case BO_Shr:
   return Discard(this->emitShr(*LT, *RT, BO));
+case BO_Xor:
+  return Discard(this->emitBitXor(*T, BO));
 case BO_LAnd:
 case BO_LOr:
 default:


Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -279,6 +279,23 @@
   static_assert((12 | true) == 13, "");
 };
 
+namespace bitXor {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wxor-used-as-pow"
+  static_assert((10 ^ 1) == 11, "");
+  static_assert((10 ^ 10) == 0, "");
+
+  enum {
+ONE = 1,
+  };
+
+  static_assert((1337 ^ -1) == -1338, "");
+  static_assert((0 | gimme(12)) == 12, "");
+  static_assert((12 ^ true) == 13, "");
+  static_assert((12 ^ ONE) == 13, "");
+#pragma clang diagnostic pop
+};
+
 #if __cplusplus >= 201402L
 constexpr bool IgnoredUnary() {
   bool bo = true;
Index: clang/lib/AST/Interp/Opcodes.td
===
--- clang/lib/AST/Interp/Opcodes.td
+++ clang/lib/AST/Interp/Opcodes.td
@@ -419,6 +419,7 @@
   let Types = [NumberTypeClass];
   let HasGroup = 1;
 }
+def BitXor : IntegerOpcode;
 
 //===--===//
 // Unary operators.
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -211,6 +211,23 @@
   return false;
 }
 
+/// 1) Pops the RHS from the stack.
+/// 2) Pops the LHS from the stack.
+/// 3) Pushes 'LHS ^ RHS' on the stack
+template ::T>
+bool BitXor(InterpState , CodePtr OpPC) {
+  const T  

[clang] 74fb770 - [clang][Interp] Implement bitXor opcode

2022-10-30 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2022-10-30T09:23:33+01:00
New Revision: 74fb770de9399d7258a8eda974c93610cfde698e

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

LOG: [clang][Interp] Implement bitXor opcode

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

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/lib/AST/Interp/Integral.h
clang/lib/AST/Interp/Interp.h
clang/lib/AST/Interp/Opcodes.td
clang/test/AST/Interp/literals.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index f13cd7791a6c..516f77cd3d60 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -241,6 +241,8 @@ bool ByteCodeExprGen::VisitBinaryOperator(const 
BinaryOperator *BO) {
   return Discard(this->emitShl(*LT, *RT, BO));
 case BO_Shr:
   return Discard(this->emitShr(*LT, *RT, BO));
+case BO_Xor:
+  return Discard(this->emitBitXor(*T, BO));
 case BO_LAnd:
 case BO_LOr:
 default:

diff  --git a/clang/lib/AST/Interp/Integral.h b/clang/lib/AST/Interp/Integral.h
index 9ee9fd6d7fd8..8a742333ae57 100644
--- a/clang/lib/AST/Interp/Integral.h
+++ b/clang/lib/AST/Interp/Integral.h
@@ -227,6 +227,11 @@ template  class Integral final 
{
 return false;
   }
 
+  static bool bitXor(Integral A, Integral B, unsigned OpBits, Integral *R) {
+*R = Integral(A.V ^ B.V);
+return false;
+  }
+
   static bool neg(Integral A, Integral *R) {
 *R = -A;
 return false;

diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index aacd5209fcfd..23d7b600e1ad 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -211,6 +211,23 @@ bool BitOr(InterpState , CodePtr OpPC) {
   return false;
 }
 
+/// 1) Pops the RHS from the stack.
+/// 2) Pops the LHS from the stack.
+/// 3) Pushes 'LHS ^ RHS' on the stack
+template ::T>
+bool BitXor(InterpState , CodePtr OpPC) {
+  const T  = S.Stk.pop();
+  const T  = S.Stk.pop();
+
+  unsigned Bits = RHS.bitWidth();
+  T Result;
+  if (!T::bitXor(LHS, RHS, Bits, )) {
+S.Stk.push(Result);
+return true;
+  }
+  return false;
+}
+
 /// 1) Pops the RHS from the stack.
 /// 2) Pops the LHS from the stack.
 /// 3) Pushes 'LHS % RHS' on the stack (the remainder of dividing LHS by RHS).

diff  --git a/clang/lib/AST/Interp/Opcodes.td b/clang/lib/AST/Interp/Opcodes.td
index 73f0f6140f6b..9f938a6440ae 100644
--- a/clang/lib/AST/Interp/Opcodes.td
+++ b/clang/lib/AST/Interp/Opcodes.td
@@ -419,6 +419,7 @@ def Div : Opcode {
   let Types = [NumberTypeClass];
   let HasGroup = 1;
 }
+def BitXor : IntegerOpcode;
 
 
//===--===//
 // Unary operators.

diff  --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index afb98e3c1ef9..dc99f83fb1df 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -279,6 +279,23 @@ namespace bitOr {
   static_assert((12 | true) == 13, "");
 };
 
+namespace bitXor {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wxor-used-as-pow"
+  static_assert((10 ^ 1) == 11, "");
+  static_assert((10 ^ 10) == 0, "");
+
+  enum {
+ONE = 1,
+  };
+
+  static_assert((1337 ^ -1) == -1338, "");
+  static_assert((0 | gimme(12)) == 12, "");
+  static_assert((12 ^ true) == 13, "");
+  static_assert((12 ^ ONE) == 13, "");
+#pragma clang diagnostic pop
+};
+
 #if __cplusplus >= 201402L
 constexpr bool IgnoredUnary() {
   bool bo = true;



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


[PATCH] D137036: [X86] Enable EVEX GFNI instructions without avx512bw.

2022-10-30 Thread Craig Topper via Phabricator via cfe-commits
craig.topper created this revision.
craig.topper added reviewers: RKSimon, pengfei.
Herald added subscribers: StephenFan, hiraditya.
Herald added a project: All.
craig.topper requested review of this revision.
Herald added projects: clang, LLVM.

We only really need avx512bw for masking 256 or 512 bit GFNI
instructions due to the need for v32i1 or v64i1.

I wanted to enable 128-bit intrinsics with avx512vl, but the
__builtin_ia32_selectb_128 used in the header file requires avx512bw.
The codegen test for the same is also not using a masked instruction
because vselect with v16i1 mask and v16i8 is not legal so is expanded
before isel. To fix these issues we need a mask specific builtin and a
mask specific ISD opcode.

Fixes PR58687.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137036

Files:
  clang/include/clang/Basic/BuiltinsX86.def
  clang/lib/Headers/gfniintrin.h
  clang/test/CodeGen/X86/gfni-builtins.c
  llvm/lib/Target/X86/X86InstrAVX512.td
  llvm/lib/Target/X86/X86InstrSSE.td
  llvm/test/CodeGen/X86/avx512-gfni-intrinsics.ll

Index: llvm/test/CodeGen/X86/avx512-gfni-intrinsics.ll
===
--- llvm/test/CodeGen/X86/avx512-gfni-intrinsics.ll
+++ llvm/test/CodeGen/X86/avx512-gfni-intrinsics.ll
@@ -1,28 +1,58 @@
 ; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
-; RUN: llc < %s -mtriple=i686-unknown-unknown -mattr=+avx512vl,+gfni,+avx512bw --show-mc-encoding | FileCheck %s --check-prefixes=CHECK,X86
-; RUN: llc < %s -mtriple=x86_64-unknown-unknown -mattr=+avx512vl,+gfni,+avx512bw --show-mc-encoding | FileCheck %s --check-prefixes=CHECK,X64
+; RUN: llc < %s -mtriple=i686-unknown-unknown -mattr=+avx512vl,+gfni,+avx512bw --show-mc-encoding | FileCheck %s --check-prefixes=CHECK,X86BW
+; RUN: llc < %s -mtriple=x86_64-unknown-unknown -mattr=+avx512vl,+gfni,+avx512bw --show-mc-encoding | FileCheck %s --check-prefixes=CHECK,X64BW
+; RUN: llc < %s -mtriple=i686-unknown-unknown -mattr=+avx512vl,+gfni --show-mc-encoding | FileCheck %s --check-prefixes=CHECK,X86NOBW
+; RUN: llc < %s -mtriple=x86_64-unknown-unknown -mattr=+avx512vl,+gfni --show-mc-encoding | FileCheck %s --check-prefixes=CHECK,X64NOBW
 
 declare <16 x i8> @llvm.x86.vgf2p8affineinvqb.128(<16 x i8>, <16 x i8>, i8)
 define { <16 x i8>, <16 x i8>, <16 x i8> } @test_vgf2p8affineinvqb_128(<16 x i8> %src1, <16 x i8> %src2, <16 x i8> %passthru, i16 %mask) {
-; X86-LABEL: test_vgf2p8affineinvqb_128:
-; X86:   # %bb.0:
-; X86-NEXT:kmovw {{[0-9]+}}(%esp), %k1 # encoding: [0xc5,0xf8,0x90,0x4c,0x24,0x04]
-; X86-NEXT:vgf2p8affineinvqb $3, %xmm1, %xmm0, %xmm3 # EVEX TO VEX Compression encoding: [0xc4,0xe3,0xf9,0xcf,0xd9,0x03]
-; X86-NEXT:vgf2p8affineinvqb $4, %xmm1, %xmm0, %xmm4 {%k1} {z} # encoding: [0x62,0xf3,0xfd,0x89,0xcf,0xe1,0x04]
-; X86-NEXT:vgf2p8affineinvqb $5, %xmm1, %xmm0, %xmm2 {%k1} # encoding: [0x62,0xf3,0xfd,0x09,0xcf,0xd1,0x05]
-; X86-NEXT:vmovdqa %xmm3, %xmm0 # EVEX TO VEX Compression encoding: [0xc5,0xf9,0x6f,0xc3]
-; X86-NEXT:vmovdqa %xmm4, %xmm1 # EVEX TO VEX Compression encoding: [0xc5,0xf9,0x6f,0xcc]
-; X86-NEXT:retl # encoding: [0xc3]
-;
-; X64-LABEL: test_vgf2p8affineinvqb_128:
-; X64:   # %bb.0:
-; X64-NEXT:kmovd %edi, %k1 # encoding: [0xc5,0xfb,0x92,0xcf]
-; X64-NEXT:vgf2p8affineinvqb $3, %xmm1, %xmm0, %xmm3 # EVEX TO VEX Compression encoding: [0xc4,0xe3,0xf9,0xcf,0xd9,0x03]
-; X64-NEXT:vgf2p8affineinvqb $4, %xmm1, %xmm0, %xmm4 {%k1} {z} # encoding: [0x62,0xf3,0xfd,0x89,0xcf,0xe1,0x04]
-; X64-NEXT:vgf2p8affineinvqb $5, %xmm1, %xmm0, %xmm2 {%k1} # encoding: [0x62,0xf3,0xfd,0x09,0xcf,0xd1,0x05]
-; X64-NEXT:vmovdqa %xmm3, %xmm0 # EVEX TO VEX Compression encoding: [0xc5,0xf9,0x6f,0xc3]
-; X64-NEXT:vmovdqa %xmm4, %xmm1 # EVEX TO VEX Compression encoding: [0xc5,0xf9,0x6f,0xcc]
-; X64-NEXT:retq # encoding: [0xc3]
+; X86BW-LABEL: test_vgf2p8affineinvqb_128:
+; X86BW:   # %bb.0:
+; X86BW-NEXT:kmovw {{[0-9]+}}(%esp), %k1 # encoding: [0xc5,0xf8,0x90,0x4c,0x24,0x04]
+; X86BW-NEXT:vgf2p8affineinvqb $3, %xmm1, %xmm0, %xmm3 # EVEX TO VEX Compression encoding: [0xc4,0xe3,0xf9,0xcf,0xd9,0x03]
+; X86BW-NEXT:vgf2p8affineinvqb $4, %xmm1, %xmm0, %xmm4 {%k1} {z} # encoding: [0x62,0xf3,0xfd,0x89,0xcf,0xe1,0x04]
+; X86BW-NEXT:vgf2p8affineinvqb $5, %xmm1, %xmm0, %xmm2 {%k1} # encoding: [0x62,0xf3,0xfd,0x09,0xcf,0xd1,0x05]
+; X86BW-NEXT:vmovdqa %xmm3, %xmm0 # EVEX TO VEX Compression encoding: [0xc5,0xf9,0x6f,0xc3]
+; X86BW-NEXT:vmovdqa %xmm4, %xmm1 # EVEX TO VEX Compression encoding: [0xc5,0xf9,0x6f,0xcc]
+; X86BW-NEXT:retl # encoding: [0xc3]
+;
+; X64BW-LABEL: test_vgf2p8affineinvqb_128:
+; X64BW:   # %bb.0:
+; X64BW-NEXT:kmovd %edi, %k1 # encoding: [0xc5,0xfb,0x92,0xcf]
+; X64BW-NEXT:vgf2p8affineinvqb $3, %xmm1, %xmm0, %xmm3 # EVEX TO VEX Compression encoding: [0xc4,0xe3,0xf9,0xcf,0xd9,0x03]
+; X64BW-NEXT:vgf2p8affineinvqb $4, %xmm1, %xmm0, 

[PATCH] D136532: [clang][Interp] Implement left and right shifts

2022-10-30 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 rG6d965c94ba58: [clang][Interp] Implement left and right 
shifts (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D136532?vs=471138=471818#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136532

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/Opcodes.td
  clang/test/AST/Interp/shifts.cpp

Index: clang/test/AST/Interp/shifts.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/shifts.cpp
@@ -0,0 +1,142 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -std=c++20 -verify %s
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -std=c++17 -verify=cxx17 %s
+// RUN: %clang_cc1 -std=c++20 -verify=ref %s
+// RUN: %clang_cc1 -std=c++17 -verify=ref-cxx17 %s
+
+#define INT_MIN (~__INT_MAX__)
+
+
+namespace shifts {
+  constexpr void test() { // ref-error {{constexpr function never produces a constant expression}} \
+  // ref-cxx17-error {{constexpr function never produces a constant expression}}
+
+char c; // cxx17-warning {{uninitialized variable}} \
+// ref-cxx17-warning {{uninitialized variable}}
+
+c = 0 << 0;
+c = 0 << 1;
+c = 1 << 0;
+c = 1 << -0;
+c = 1 >> -0;
+c = 1 << -1; // expected-warning {{shift count is negative}} \
+ // cxx17-warning {{shift count is negative}} \
+ // ref-warning {{shift count is negative}} \
+ // ref-note {{negative shift count -1}} \
+ // ref-cxx17-warning {{shift count is negative}} \
+ // ref-cxx17-note {{negative shift count -1}}
+
+c = 1 >> -1; // expected-warning {{shift count is negative}} \
+ // cxx17-warning {{shift count is negative}} \
+ // ref-warning {{shift count is negative}} \
+ // ref-cxx17-warning {{shift count is negative}}
+c = 1 << (unsigned)-1; // expected-warning {{shift count >= width of type}} \
+   // FIXME: 'implicit conversion' warning missing in the new interpreter. \
+   // cxx17-warning {{shift count >= width of type}} \
+   // ref-warning {{shift count >= width of type}} \
+   // ref-warning {{implicit conversion}} \
+   // ref-cxx17-warning {{shift count >= width of type}} \
+   // ref-cxx17-warning {{implicit conversion}}
+c = 1 >> (unsigned)-1; // expected-warning {{shift count >= width of type}} \
+   // cxx17-warning {{shift count >= width of type}} \
+   // ref-warning {{shift count >= width of type}} \
+   // ref-cxx17-warning {{shift count >= width of type}}
+c = 1 << c;
+c <<= 0;
+c >>= 0;
+c <<= 1;
+c >>= 1;
+c <<= -1; // expected-warning {{shift count is negative}} \
+  // cxx17-warning {{shift count is negative}} \
+  // ref-warning {{shift count is negative}} \
+  // ref-cxx17-warning {{shift count is negative}}
+c >>= -1; // expected-warning {{shift count is negative}} \
+  // cxx17-warning {{shift count is negative}} \
+  // ref-warning {{shift count is negative}} \
+  // ref-cxx17-warning {{shift count is negative}}
+c <<= 99; // expected-warning {{shift count >= width of type}} \
+  // cxx17-warning {{shift count >= width of type}} \
+  // ref-warning {{shift count >= width of type}} \
+  // ref-cxx17-warning {{shift count >= width of type}}
+c >>= 99; // expected-warning {{shift count >= width of type}} \
+  // cxx17-warning {{shift count >= width of type}} \
+  // ref-warning {{shift count >= width of type}} \
+  // ref-cxx17-warning {{shift count >= width of type}}
+c <<= __CHAR_BIT__; // expected-warning {{shift count >= width of type}} \
+// cxx17-warning {{shift count >= width of type}} \
+// ref-warning {{shift count >= width of type}} \
+// ref-cxx17-warning {{shift count >= width of type}}
+c >>= __CHAR_BIT__; // expected-warning {{shift count >= width of type}} \
+// cxx17-warning {{shift count >= width of type}} \
+// ref-warning {{shift count >= width of type}} \
+// ref-cxx17-warning {{shift count >= width of type}}
+c <<= __CHAR_BIT__+1; // expected-warning {{shift count >= width of type}} \
+  // cxx17-warning {{shift count >= width 

[clang] 6d965c9 - [clang][Interp] Implement left and right shifts

2022-10-30 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2022-10-30T08:59:55+01:00
New Revision: 6d965c94ba5806eb18c34cec9a8e9c4cb65c6885

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

LOG: [clang][Interp] Implement left and right shifts

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

Added: 
clang/test/AST/Interp/shifts.cpp

Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/lib/AST/Interp/Interp.h
clang/lib/AST/Interp/Opcodes.td

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 2edd16bc7e6c..f13cd7791a6c 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -237,6 +237,10 @@ bool ByteCodeExprGen::VisitBinaryOperator(const 
BinaryOperator *BO) {
   return Discard(this->emitBitAnd(*T, BO));
 case BO_Or:
   return Discard(this->emitBitOr(*T, BO));
+case BO_Shl:
+  return Discard(this->emitShl(*LT, *RT, BO));
+case BO_Shr:
+  return Discard(this->emitShr(*LT, *RT, BO));
 case BO_LAnd:
 case BO_LOr:
 default:
@@ -451,7 +455,13 @@ bool ByteCodeExprGen::VisitCompoundAssignOperator(
   case BO_DivAssign:
   case BO_RemAssign:
   case BO_ShlAssign:
+if (!this->emitShl(*LT, *RT, E))
+  return false;
+break;
   case BO_ShrAssign:
+if (!this->emitShr(*LT, *RT, E))
+  return false;
+break;
   case BO_AndAssign:
   case BO_XorAssign:
   case BO_OrAssign:

diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 81f833735258..aacd5209fcfd 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1103,84 +1103,63 @@ inline bool This(InterpState , CodePtr OpPC) {
 // Shr, Shl
 
//===--===//
 
-template ::T>
-unsigned Trunc(InterpState , CodePtr OpPC, unsigned Bits, const T ) {
+template 
+inline bool Shr(InterpState , CodePtr OpPC) {
+  using LT = typename PrimConv::T;
+  using RT = typename PrimConv::T;
+  const auto  = S.Stk.pop();
+  const auto  = S.Stk.pop();
+  const unsigned Bits = LHS.bitWidth();
+
+  if (RHS.isNegative()) {
+const SourceInfo  = S.Current->getSource(OpPC);
+S.CCEDiag(Loc, diag::note_constexpr_negative_shift) << RHS.toAPSInt();
+return false;
+  }
+
   // C++11 [expr.shift]p1: Shift width must be less than the bit width of
   // the shifted type.
-  if (Bits > 1 && V >= T::from(Bits, V.bitWidth())) {
+  if (Bits > 1 && RHS >= RT::from(Bits, RHS.bitWidth())) {
 const Expr *E = S.Current->getExpr(OpPC);
-const APSInt Val = V.toAPSInt();
+const APSInt Val = RHS.toAPSInt();
 QualType Ty = E->getType();
 S.CCEDiag(E, diag::note_constexpr_large_shift) << Val << Ty << Bits;
-return Bits;
-  } else {
-return static_cast(V);
-  }
-}
-
-template ::T>
-inline bool ShiftRight(InterpState , CodePtr OpPC, const T , unsigned RHS) 
{
-  if (RHS >= V.bitWidth()) {
-S.Stk.push(T::from(0, V.bitWidth()));
-  } else {
-S.Stk.push(T::from(V >> RHS, V.bitWidth()));
-  }
-  return true;
-}
-
-template ::T>
-inline bool ShiftLeft(InterpState , CodePtr OpPC, const T , unsigned RHS) {
-  if (V.isSigned() && !S.getLangOpts().CPlusPlus20) {
-// C++11 [expr.shift]p2: A signed left shift must have a non-negative
-// operand, and must not overflow the corresponding unsigned type.
-// C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
-// E1 x 2^E2 module 2^N.
-if (V.isNegative()) {
-  const Expr *E = S.Current->getExpr(OpPC);
-  S.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << V.toAPSInt();
-} else if (V.countLeadingZeros() < RHS) {
-  S.CCEDiag(S.Current->getExpr(OpPC), 
diag::note_constexpr_lshift_discards);
-}
+return false;
   }
 
-  if (V.bitWidth() == 1) {
-S.Stk.push(V);
-  } else if (RHS >= V.bitWidth()) {
-S.Stk.push(T::from(0, V.bitWidth()));
-  } else {
-S.Stk.push(T::from(V.toUnsigned() << RHS, V.bitWidth()));
-  }
+  unsigned URHS = static_cast(RHS);
+  S.Stk.push(LT::from(static_cast(LHS) >> URHS, LHS.bitWidth()));
   return true;
 }
 
-template 
-inline bool Shr(InterpState , CodePtr OpPC) {
-  const auto  = S.Stk.pop::T>();
-  const auto  = S.Stk.pop::T>();
+template 
+inline bool Shl(InterpState , CodePtr OpPC) {
+  using LT = typename PrimConv::T;
+  using RT = typename PrimConv::T;
+  const auto  = S.Stk.pop();
+  const auto  = S.Stk.pop();
   const unsigned Bits = LHS.bitWidth();
 
-  if (RHS.isSigned() && RHS.isNegative()) {
+  if (RHS.isNegative()) {
 const SourceInfo  = S.Current->getSource(OpPC);
 S.CCEDiag(Loc, diag::note_constexpr_negative_shift) << RHS.toAPSInt();
-return ShiftLeft(S, OpPC, LHS, Trunc(S, OpPC, Bits, -RHS));
-  } else {
-return 

[PATCH] D134827: [clangd] Avoid recursion on UnresolvedUsingValueDecl during semantic highlighting

2022-10-30 Thread Nathan Ridge via Phabricator via cfe-commits
nridge requested review of this revision.
nridge added a comment.

(I'm going to re-request review since I have an outstanding question about the 
fix approach.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134827

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


[PATCH] D136925: [clangd] Index scoped enums for code completion

2022-10-30 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added inline comments.



Comment at: clang-tools-extra/clangd/CodeComplete.cpp:2133
   if (const auto *EnumDecl = dyn_cast(ND.getDeclContext()))
-return InTopLevelScope(*EnumDecl) && !EnumDecl->isScoped();
 

Just to make sure I understand:

By also removing the `!isScoped()` condition, in addition to changing the 
behaviour for the scenario described in 
https://github.com/clangd/clangd/issues/1082 (enum declared at class scope), 
you are also changing the behaviour for scenarios like this:

```
enum class Foo { Bar };  // at any scope, including global
```

Completing `Bar` will now offer `Foo::Bar` when previously it didn't.

Is this your intention?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136925

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


[PATCH] D136528: [clang][Interp] Implement add and sub compound assign operators

2022-10-30 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 rG881547db03a6: [clang][Interp] Implement add and sub compound 
assign operators (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D136528?vs=470138=471817#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136528

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  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
@@ -415,5 +415,43 @@
  // expected-note {{in call to 'UnderFlow()'}} \
  // ref-error {{not an integral constant expression}} \
  // ref-note {{in call to 'UnderFlow()'}}
+
+  constexpr int getTwo() {
+int i = 1;
+return (i += 1);
+  }
+  static_assert(getTwo() == 2, "");
+
+  constexpr int sub(int a) {
+return (a -= 2);
+  }
+  static_assert(sub(7) == 5, "");
+
+  constexpr int add(int a, int b) {
+a += b; // expected-note {{is outside the range of representable values}} \
+// ref-note {{is outside the range of representable values}} 
+return a;
+  }
+  static_assert(add(1, 2) == 3, "");
+  static_assert(add(INT_MAX, 1) == 0, ""); // expected-error {{not an integral constant expression}} \
+   // expected-note {{in call to 'add}} \
+   // ref-error {{not an integral constant expression}} \
+   // ref-note {{in call to 'add}}
+
+  constexpr int sub(int a, int b) {
+a -= b; // expected-note {{is outside the range of representable values}} \
+// ref-note {{is outside the range of representable values}} 
+return a;
+  }
+  static_assert(sub(10, 20) == -10, "");
+  static_assert(sub(INT_MIN, 1) == 0, ""); // expected-error {{not an integral constant expression}} \
+   // expected-note {{in call to 'sub}} \
+   // ref-error {{not an integral constant expression}} \
+   // ref-note {{in call to 'sub}}
+
+  constexpr int subAll(int a) {
+return (a -= a);
+  }
+  static_assert(subAll(213) == 0, "");
 };
 #endif
Index: clang/lib/AST/Interp/ByteCodeExprGen.h
===
--- clang/lib/AST/Interp/ByteCodeExprGen.h
+++ clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -85,6 +85,7 @@
   bool VisitAbstractConditionalOperator(const AbstractConditionalOperator *E);
   bool VisitStringLiteral(const StringLiteral *E);
   bool VisitCharacterLiteral(const CharacterLiteral *E);
+  bool VisitCompoundAssignOperator(const CompoundAssignOperator *E);
 
 protected:
   bool visitExpr(const Expr *E) override;
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -414,6 +414,57 @@
   return this->emitConst(E, E->getValue());
 }
 
+template 
+bool ByteCodeExprGen::VisitCompoundAssignOperator(
+const CompoundAssignOperator *E) {
+  const Expr *LHS = E->getLHS();
+  const Expr *RHS = E->getRHS();
+  Optional LT = classify(E->getLHS()->getType());
+  Optional RT = classify(E->getRHS()->getType());
+
+  if (!LT || !RT)
+return false;
+
+  assert(!E->getType()->isPointerType() &&
+ "Support pointer arithmethic in compound assignment operators");
+
+  // Get LHS pointer, load its value and get RHS value.
+  if (!visit(LHS))
+return false;
+  if (!this->emitLoad(*LT, E))
+return false;
+  if (!visit(RHS))
+return false;
+
+  // Perform operation.
+  switch (E->getOpcode()) {
+  case BO_AddAssign:
+if (!this->emitAdd(*LT, E))
+  return false;
+break;
+  case BO_SubAssign:
+if (!this->emitSub(*LT, E))
+  return false;
+break;
+
+  case BO_MulAssign:
+  case BO_DivAssign:
+  case BO_RemAssign:
+  case BO_ShlAssign:
+  case BO_ShrAssign:
+  case BO_AndAssign:
+  case BO_XorAssign:
+  case BO_OrAssign:
+  default:
+llvm_unreachable("Unimplemented compound assign operator");
+  }
+
+  // And store the result in LHS.
+  if (DiscardResult)
+return this->emitStorePop(*LT, E);
+  return this->emitStore(*LT, E);
+}
+
 template  bool ByteCodeExprGen::discard(const Expr *E) {
   OptionScope Scope(this, /*NewDiscardResult=*/true);
   return this->Visit(E);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 881547d - [clang][Interp] Implement add and sub compound assign operators

2022-10-30 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2022-10-30T08:11:04+01:00
New Revision: 881547db03a6ea243505a8ccba1547f2f18c05ca

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

LOG: [clang][Interp] Implement add and sub compound assign operators

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

Added: 


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

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 30ae7fbfc637a..2edd16bc7e6cc 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -414,6 +414,57 @@ bool ByteCodeExprGen::VisitCharacterLiteral(
   return this->emitConst(E, E->getValue());
 }
 
+template 
+bool ByteCodeExprGen::VisitCompoundAssignOperator(
+const CompoundAssignOperator *E) {
+  const Expr *LHS = E->getLHS();
+  const Expr *RHS = E->getRHS();
+  Optional LT = classify(E->getLHS()->getType());
+  Optional RT = classify(E->getRHS()->getType());
+
+  if (!LT || !RT)
+return false;
+
+  assert(!E->getType()->isPointerType() &&
+ "Support pointer arithmethic in compound assignment operators");
+
+  // Get LHS pointer, load its value and get RHS value.
+  if (!visit(LHS))
+return false;
+  if (!this->emitLoad(*LT, E))
+return false;
+  if (!visit(RHS))
+return false;
+
+  // Perform operation.
+  switch (E->getOpcode()) {
+  case BO_AddAssign:
+if (!this->emitAdd(*LT, E))
+  return false;
+break;
+  case BO_SubAssign:
+if (!this->emitSub(*LT, E))
+  return false;
+break;
+
+  case BO_MulAssign:
+  case BO_DivAssign:
+  case BO_RemAssign:
+  case BO_ShlAssign:
+  case BO_ShrAssign:
+  case BO_AndAssign:
+  case BO_XorAssign:
+  case BO_OrAssign:
+  default:
+llvm_unreachable("Unimplemented compound assign operator");
+  }
+
+  // And store the result in LHS.
+  if (DiscardResult)
+return this->emitStorePop(*LT, E);
+  return this->emitStore(*LT, E);
+}
+
 template  bool ByteCodeExprGen::discard(const Expr *E) 
{
   OptionScope Scope(this, /*NewDiscardResult=*/true);
   return this->Visit(E);

diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 489e8bdb79ca4..4c7550aa497df 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -85,6 +85,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   bool VisitAbstractConditionalOperator(const AbstractConditionalOperator *E);
   bool VisitStringLiteral(const StringLiteral *E);
   bool VisitCharacterLiteral(const CharacterLiteral *E);
+  bool VisitCompoundAssignOperator(const CompoundAssignOperator *E);
 
 protected:
   bool visitExpr(const Expr *E) override;

diff  --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index 1c6aa4e26979c..afb98e3c1ef99 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -415,5 +415,43 @@ namespace IncDec {
  // expected-note {{in call to 
'UnderFlow()'}} \
  // ref-error {{not an integral 
constant expression}} \
  // ref-note {{in call to 
'UnderFlow()'}}
+
+  constexpr int getTwo() {
+int i = 1;
+return (i += 1);
+  }
+  static_assert(getTwo() == 2, "");
+
+  constexpr int sub(int a) {
+return (a -= 2);
+  }
+  static_assert(sub(7) == 5, "");
+
+  constexpr int add(int a, int b) {
+a += b; // expected-note {{is outside the range of representable values}} \
+// ref-note {{is outside the range of representable values}} 
+return a;
+  }
+  static_assert(add(1, 2) == 3, "");
+  static_assert(add(INT_MAX, 1) == 0, ""); // expected-error {{not an integral 
constant expression}} \
+   // expected-note {{in call to 
'add}} \
+   // ref-error {{not an integral 
constant expression}} \
+   // ref-note {{in call to 'add}}
+
+  constexpr int sub(int a, int b) {
+a -= b; // expected-note {{is outside the range of representable values}} \
+// ref-note {{is outside the range of representable values}} 
+return a;
+  }
+  static_assert(sub(10, 20) == -10, "");
+  static_assert(sub(INT_MIN, 1) == 0, ""); // expected-error {{not an integral 
constant expression}} \
+   // expected-note {{in call to 
'sub}} \
+   // ref-error {{not an integral 
constant expression}} \
+   // ref-note {{in call 

[PATCH] D134859: [clang][Interp] Implement basic support for floating point values

2022-10-30 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 471816.

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

https://reviews.llvm.org/D134859

Files:
  clang/lib/AST/CMakeLists.txt
  clang/lib/AST/Interp/Boolean.h
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/Context.cpp
  clang/lib/AST/Interp/Descriptor.cpp
  clang/lib/AST/Interp/Floating.cpp
  clang/lib/AST/Interp/Floating.h
  clang/lib/AST/Interp/Integral.h
  clang/lib/AST/Interp/Interp.cpp
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/InterpStack.h
  clang/lib/AST/Interp/Opcodes.td
  clang/lib/AST/Interp/PrimType.h
  clang/lib/AST/Interp/Primitives.h
  clang/test/AST/Interp/floats.cpp
  clang/test/SemaCXX/rounding-math.cpp

Index: clang/test/SemaCXX/rounding-math.cpp
===
--- clang/test/SemaCXX/rounding-math.cpp
+++ clang/test/SemaCXX/rounding-math.cpp
@@ -1,5 +1,6 @@
 // RUN: %clang_cc1 -triple x86_64-linux -verify=norounding -Wno-unknown-pragmas %s
 // RUN: %clang_cc1 -triple x86_64-linux -verify=rounding %s -frounding-math -Wno-unknown-pragmas
+// RUN: %clang_cc1 -triple x86_64-linux -verify=rounding %s -frounding-math -fexperimental-new-constant-interpreter -Wno-unknown-pragmas
 // rounding-no-diagnostics
 
 #define fold(x) (__builtin_constant_p(x) ? (x) : (x))
Index: clang/test/AST/Interp/floats.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/floats.cpp
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify %s
+// RUN: %clang_cc1 -verify=ref %s
+
+constexpr int i = 2;
+constexpr float f = 1.0f;
+static_assert(f == 1.0f, "");
+
+constexpr float f2 = 1u * f;
+static_assert(f2 == 1.0f, "");
+
+static_assert(1.0f + 3u == 4, "");
+static_assert(4.0f / 1.0f == 4, "");
+static_assert(10.0f * false == 0, "");
+
+constexpr float floats[] = {1.0f, 2.0f, 3.0f, 4.0f};
+
+constexpr float m = 5.0f / 0.0f; // ref-error {{must be initialized by a constant expression}} \
+ // ref-note {{division by zero}} \
+ // expected-error {{must be initialized by a constant expression}} \
+ // expected-note {{division by zero}}
+
+static_assert(~2.0f == 3, ""); // ref-error {{invalid argument type 'float' to unary expression}} \
+   // expected-error {{invalid argument type 'float' to unary expression}}
+
+/// Initialized by a double.
+constexpr float df = 0.0;
+/// The other way around.
+constexpr double fd = 0.0f;
+
+static_assert(0.0f == -0.0f, "");
+
+const int k = 3 * (1.0f / 3.0f);
+static_assert(k == 1, "");
+
+constexpr bool b = 1.0;
+static_assert(b, "");
+
+constexpr double db = true;
+static_assert(db == 1.0, "");
+
+constexpr float fa[] = {1.0f, 2.0, 1, false};
+constexpr float da[] = {1.0f, 2.0, 1, false};
Index: clang/lib/AST/Interp/Primitives.h
===
--- /dev/null
+++ clang/lib/AST/Interp/Primitives.h
@@ -0,0 +1,36 @@
+//===-- Primitives.h - Types for the constexpr VM ---*- 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
+//
+//===--===//
+//
+// Utilities and helper functions for all primitive types:
+//  - Integral
+//  - Floating
+//  - Boolean
+//
+//===--===//
+
+#ifndef LLVM_CLANG_AST_INTERP_PRIMITIVES_H
+#define LLVM_CLANG_AST_INTERP_PRIMITIVES_H
+
+#include "clang/AST/ComparisonCategories.h"
+
+namespace clang {
+namespace interp {
+
+/// Helper to compare two comparable types.
+template  ComparisonCategoryResult Compare(const T , const T ) {
+  if (X < Y)
+return ComparisonCategoryResult::Less;
+  if (X > Y)
+return ComparisonCategoryResult::Greater;
+  return ComparisonCategoryResult::Equal;
+}
+
+} // namespace interp
+} // namespace clang
+
+#endif
Index: clang/lib/AST/Interp/PrimType.h
===
--- clang/lib/AST/Interp/PrimType.h
+++ clang/lib/AST/Interp/PrimType.h
@@ -13,11 +13,12 @@
 #ifndef LLVM_CLANG_AST_INTERP_TYPE_H
 #define LLVM_CLANG_AST_INTERP_TYPE_H
 
+#include "Boolean.h"
+#include "Floating.h"
+#include "Integral.h"
 #include 
 #include 
 #include 
-#include "Boolean.h"
-#include "Integral.h"
 
 namespace clang {
 namespace interp {
@@ -35,6 +36,7 @@
   PT_Sint64,
   PT_Uint64,
   PT_Bool,
+  PT_Float,
   PT_Ptr,
 };
 
@@ -48,6 +50,7 @@
 template <> struct PrimConv { using T = Integral<32, false>; };
 template <> struct PrimConv { using T = Integral<64, true>; };
 template <> struct PrimConv { using T = Integral<64, false>; };
+template <> 

[PATCH] D134859: [clang][Interp] Implement basic support for floating point values

2022-10-30 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 471814.
tbaeder added a comment.

Moved the tests to their own file and moved the `isConstantContext()` changes 
to `InterpState` to their own NFC commit.


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

https://reviews.llvm.org/D134859

Files:
  clang/lib/AST/CMakeLists.txt
  clang/lib/AST/Interp/Boolean.h
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/Context.cpp
  clang/lib/AST/Interp/Descriptor.cpp
  clang/lib/AST/Interp/Integral.h
  clang/lib/AST/Interp/Interp.cpp
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/InterpStack.h
  clang/lib/AST/Interp/Opcodes.td
  clang/lib/AST/Interp/PrimType.h
  clang/test/SemaCXX/rounding-math.cpp

Index: clang/test/SemaCXX/rounding-math.cpp
===
--- clang/test/SemaCXX/rounding-math.cpp
+++ clang/test/SemaCXX/rounding-math.cpp
@@ -1,5 +1,6 @@
 // RUN: %clang_cc1 -triple x86_64-linux -verify=norounding -Wno-unknown-pragmas %s
 // RUN: %clang_cc1 -triple x86_64-linux -verify=rounding %s -frounding-math -Wno-unknown-pragmas
+// RUN: %clang_cc1 -triple x86_64-linux -verify=rounding %s -frounding-math -fexperimental-new-constant-interpreter -Wno-unknown-pragmas
 // rounding-no-diagnostics
 
 #define fold(x) (__builtin_constant_p(x) ? (x) : (x))
Index: clang/lib/AST/Interp/PrimType.h
===
--- clang/lib/AST/Interp/PrimType.h
+++ clang/lib/AST/Interp/PrimType.h
@@ -13,11 +13,12 @@
 #ifndef LLVM_CLANG_AST_INTERP_TYPE_H
 #define LLVM_CLANG_AST_INTERP_TYPE_H
 
+#include "Boolean.h"
+#include "Floating.h"
+#include "Integral.h"
 #include 
 #include 
 #include 
-#include "Boolean.h"
-#include "Integral.h"
 
 namespace clang {
 namespace interp {
@@ -35,6 +36,7 @@
   PT_Sint64,
   PT_Uint64,
   PT_Bool,
+  PT_Float,
   PT_Ptr,
 };
 
@@ -48,6 +50,7 @@
 template <> struct PrimConv { using T = Integral<32, false>; };
 template <> struct PrimConv { using T = Integral<64, true>; };
 template <> struct PrimConv { using T = Integral<64, false>; };
+template <> struct PrimConv { using T = Floating; };
 template <> struct PrimConv { using T = Boolean; };
 template <> struct PrimConv { using T = Pointer; };
 
@@ -70,6 +73,7 @@
   case PT_Uint32:
   case PT_Sint64:
   case PT_Uint64:
+  case PT_Float:
 return true;
   default:
 return false;
@@ -94,6 +98,7 @@
   TYPE_SWITCH_CASE(PT_Uint32, B)   \
   TYPE_SWITCH_CASE(PT_Sint64, B)   \
   TYPE_SWITCH_CASE(PT_Uint64, B)   \
+  TYPE_SWITCH_CASE(PT_Float, B)\
   TYPE_SWITCH_CASE(PT_Bool, B) \
   TYPE_SWITCH_CASE(PT_Ptr, B)  \
 }  \
Index: clang/lib/AST/Interp/Opcodes.td
===
--- clang/lib/AST/Interp/Opcodes.td
+++ clang/lib/AST/Interp/Opcodes.td
@@ -25,6 +25,7 @@
 def Uint32 : Type;
 def Sint64 : Type;
 def Uint64 : Type;
+def Float : Type;
 def Ptr : Type;
 
 //===--===//
@@ -40,12 +41,15 @@
 def ArgUint32 : ArgType { let Name = "uint32_t"; }
 def ArgSint64 : ArgType { let Name = "int64_t"; }
 def ArgUint64 : ArgType { let Name = "uint64_t"; }
+def ArgFloat : ArgType { let Name = "Floating"; }
 def ArgBool : ArgType { let Name = "bool"; }
 
 def ArgFunction : ArgType { let Name = "const Function *"; }
 def ArgRecordDecl : ArgType { let Name = "const RecordDecl *"; }
 def ArgRecordField : ArgType { let Name = "const Record::Field *"; }
 def ArgLETD: ArgType { let Name = "const LifetimeExtendedTemporaryDecl *"; }
+def ArgFltSemantics : ArgType { let Name = "const llvm::fltSemantics *"; }
+def ArgRoundingMode : ArgType { let Name = "llvm::RoundingMode"; }
 
 //===--===//
 // Classes of types instructions operate on.
@@ -55,18 +59,21 @@
   list Types;
 }
 
-def NumberTypeClass : TypeClass {
+def IntegerTypeClass : TypeClass {
   let Types = [Sint8, Uint8, Sint16, Uint16, Sint32,
Uint32, Sint64, Uint64];
 }
 
-def IntegerTypeClass : TypeClass {
-  let Types = [Sint8, Uint8, Sint16, Uint16, Sint32,
-   Uint32, Sint64, Uint64];
+def NumberTypeClass : TypeClass {
+  let Types = !listconcat(IntegerTypeClass.Types, [Float]);
+}
+
+def FloatTypeClass : TypeClass {
+  let Types = [Float];
 }
 
 def AluTypeClass : TypeClass {
-  let Types = !listconcat(NumberTypeClass.Types, [Bool]);
+  let Types = !listconcat(IntegerTypeClass.Types, [Bool]);
 }
 
 def PtrTypeClass : TypeClass {
@@ -77,12 +84,16 @@
   let Types = [Bool];
 }
 
+def 

[PATCH] D136920: [clang][Interp] Array initialization via CXXConstructExpr

2022-10-30 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 471813.

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

https://reviews.llvm.org/D136920

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


Index: clang/test/AST/Interp/arrays.cpp
===
--- clang/test/AST/Interp/arrays.cpp
+++ clang/test/AST/Interp/arrays.cpp
@@ -185,6 +185,20 @@
   }
 };
 
+class A {
+public:
+  int a;
+  constexpr A(int m = 2) : a(10 + m) {}
+};
+class B {
+public:
+  A a[2];
+  constexpr B() {}
+};
+constexpr B b;
+static_assert(b.a[0].a == 12, "");
+static_assert(b.a[1].a == 12, "");
+
 namespace IncDec {
   // FIXME: Pointer arithmethic needs to be supported in inc/dec
   //   unary operators
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -957,6 +957,36 @@
   assert(false && "default initializer for non-primitive type");
 }
 
+return true;
+  } else if (const auto *Ctor = dyn_cast(Initializer)) {
+const ArrayType *AT = Ctor->getType()->getAsArrayTypeUnsafe();
+const auto *CAT = cast(AT);
+size_t NumElems = CAT->getSize().getZExtValue();
+const Function *Func = getFunction(Ctor->getConstructor());
+if (!Func || !Func->isConstexpr())
+  return false;
+
+// FIXME(perf): We're calling the constructor once per array element here,
+//   in the old intepreter we had a special-case for trivial constructors.
+for (size_t I = 0; I != NumElems; ++I) {
+  if (!this->emitDupPtr(Initializer))
+return false;
+  if (!this->emitConstUint64(I, Initializer))
+return false;
+  if (!this->emitAddOffsetUint64(Initializer))
+return false;
+  if (!this->emitNarrowPtr(Initializer))
+return false;
+
+  // Constructor arguments.
+  for (const auto *Arg : Ctor->arguments()) {
+if (!this->visit(Arg))
+  return false;
+  }
+
+  if (!this->emitCall(Func, Initializer))
+return false;
+}
 return true;
   }
 


Index: clang/test/AST/Interp/arrays.cpp
===
--- clang/test/AST/Interp/arrays.cpp
+++ clang/test/AST/Interp/arrays.cpp
@@ -185,6 +185,20 @@
   }
 };
 
+class A {
+public:
+  int a;
+  constexpr A(int m = 2) : a(10 + m) {}
+};
+class B {
+public:
+  A a[2];
+  constexpr B() {}
+};
+constexpr B b;
+static_assert(b.a[0].a == 12, "");
+static_assert(b.a[1].a == 12, "");
+
 namespace IncDec {
   // FIXME: Pointer arithmethic needs to be supported in inc/dec
   //   unary operators
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -957,6 +957,36 @@
   assert(false && "default initializer for non-primitive type");
 }
 
+return true;
+  } else if (const auto *Ctor = dyn_cast(Initializer)) {
+const ArrayType *AT = Ctor->getType()->getAsArrayTypeUnsafe();
+const auto *CAT = cast(AT);
+size_t NumElems = CAT->getSize().getZExtValue();
+const Function *Func = getFunction(Ctor->getConstructor());
+if (!Func || !Func->isConstexpr())
+  return false;
+
+// FIXME(perf): We're calling the constructor once per array element here,
+//   in the old intepreter we had a special-case for trivial constructors.
+for (size_t I = 0; I != NumElems; ++I) {
+  if (!this->emitDupPtr(Initializer))
+return false;
+  if (!this->emitConstUint64(I, Initializer))
+return false;
+  if (!this->emitAddOffsetUint64(Initializer))
+return false;
+  if (!this->emitNarrowPtr(Initializer))
+return false;
+
+  // Constructor arguments.
+  for (const auto *Arg : Ctor->arguments()) {
+if (!this->visit(Arg))
+  return false;
+  }
+
+  if (!this->emitCall(Func, Initializer))
+return false;
+}
 return true;
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits