[PATCH] D131685: [clang][AST] RecursiveASTVisitor should visit owned TagDecl of friend type.

2022-08-23 Thread Balázs Kéri via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG23fbfb3f725b: [clang][AST] RecursiveASTVisitor should visit 
owned TagDecl of friend type. (authored by balazske).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131685

Files:
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/unittests/AST/ASTContextParentMapTest.cpp


Index: clang/unittests/AST/ASTContextParentMapTest.cpp
===
--- clang/unittests/AST/ASTContextParentMapTest.cpp
+++ clang/unittests/AST/ASTContextParentMapTest.cpp
@@ -119,5 +119,34 @@
   Lang_CXX11));
 }
 
+TEST(GetParents, FriendTypeLoc) {
+  auto AST = tooling::buildASTFromCode("struct A { friend struct Fr; };"
+   "struct B { friend struct Fr; };"
+   "struct Fr;");
+  auto &Ctx = AST->getASTContext();
+  auto &TU = *Ctx.getTranslationUnitDecl();
+  auto &A = *TU.lookup(&Ctx.Idents.get("A")).front();
+  auto &B = *TU.lookup(&Ctx.Idents.get("B")).front();
+  auto &FrA = *cast(*++(cast(A).decls_begin()));
+  auto &FrB = *cast(*++(cast(B).decls_begin()));
+  TypeLoc FrALoc = FrA.getFriendType()->getTypeLoc();
+  TypeLoc FrBLoc = FrB.getFriendType()->getTypeLoc();
+  TagDecl *FrATagDecl =
+  FrALoc.getTypePtr()->getAs()->getOwnedTagDecl();
+  TagDecl *FrBTagDecl =
+  FrBLoc.getTypePtr()->getAs()->getOwnedTagDecl();
+
+  EXPECT_THAT(Ctx.getParents(A), ElementsAre(DynTypedNode::create(TU)));
+  EXPECT_THAT(Ctx.getParents(B), ElementsAre(DynTypedNode::create(TU)));
+  EXPECT_THAT(Ctx.getParents(FrA), ElementsAre(DynTypedNode::create(A)));
+  EXPECT_THAT(Ctx.getParents(FrB), ElementsAre(DynTypedNode::create(B)));
+  EXPECT_THAT(Ctx.getParents(FrALoc), ElementsAre(DynTypedNode::create(FrA)));
+  EXPECT_THAT(Ctx.getParents(FrBLoc), ElementsAre(DynTypedNode::create(FrB)));
+  EXPECT_TRUE(FrATagDecl);
+  EXPECT_FALSE(FrBTagDecl);
+  EXPECT_THAT(Ctx.getParents(*FrATagDecl),
+  ElementsAre(DynTypedNode::create(FrA)));
+}
+
 } // end namespace ast_matchers
 } // end namespace clang
Index: clang/include/clang/AST/RecursiveASTVisitor.h
===
--- clang/include/clang/AST/RecursiveASTVisitor.h
+++ clang/include/clang/AST/RecursiveASTVisitor.h
@@ -1549,10 +1549,15 @@
 
 DEF_TRAVERSE_DECL(FriendDecl, {
   // Friend is either decl or a type.
-  if (D->getFriendType())
+  if (D->getFriendType()) {
 TRY_TO(TraverseTypeLoc(D->getFriendType()->getTypeLoc()));
-  else
+// Traverse any CXXRecordDecl owned by this type, since
+// it will not be in the parent context:
+if (auto *ET = D->getFriendType()->getType()->getAs())
+  TRY_TO(TraverseDecl(ET->getOwnedTagDecl()));
+  } else {
 TRY_TO(TraverseDecl(D->getFriendDecl()));
+  }
 })
 
 DEF_TRAVERSE_DECL(FriendTemplateDecl, {


Index: clang/unittests/AST/ASTContextParentMapTest.cpp
===
--- clang/unittests/AST/ASTContextParentMapTest.cpp
+++ clang/unittests/AST/ASTContextParentMapTest.cpp
@@ -119,5 +119,34 @@
   Lang_CXX11));
 }
 
+TEST(GetParents, FriendTypeLoc) {
+  auto AST = tooling::buildASTFromCode("struct A { friend struct Fr; };"
+   "struct B { friend struct Fr; };"
+   "struct Fr;");
+  auto &Ctx = AST->getASTContext();
+  auto &TU = *Ctx.getTranslationUnitDecl();
+  auto &A = *TU.lookup(&Ctx.Idents.get("A")).front();
+  auto &B = *TU.lookup(&Ctx.Idents.get("B")).front();
+  auto &FrA = *cast(*++(cast(A).decls_begin()));
+  auto &FrB = *cast(*++(cast(B).decls_begin()));
+  TypeLoc FrALoc = FrA.getFriendType()->getTypeLoc();
+  TypeLoc FrBLoc = FrB.getFriendType()->getTypeLoc();
+  TagDecl *FrATagDecl =
+  FrALoc.getTypePtr()->getAs()->getOwnedTagDecl();
+  TagDecl *FrBTagDecl =
+  FrBLoc.getTypePtr()->getAs()->getOwnedTagDecl();
+
+  EXPECT_THAT(Ctx.getParents(A), ElementsAre(DynTypedNode::create(TU)));
+  EXPECT_THAT(Ctx.getParents(B), ElementsAre(DynTypedNode::create(TU)));
+  EXPECT_THAT(Ctx.getParents(FrA), ElementsAre(DynTypedNode::create(A)));
+  EXPECT_THAT(Ctx.getParents(FrB), ElementsAre(DynTypedNode::create(B)));
+  EXPECT_THAT(Ctx.getParents(FrALoc), ElementsAre(DynTypedNode::create(FrA)));
+  EXPECT_THAT(Ctx.getParents(FrBLoc), ElementsAre(DynTypedNode::create(FrB)));
+  EXPECT_TRUE(FrATagDecl);
+  EXPECT_FALSE(FrBTagDecl);
+  EXPECT_THAT(Ctx.getParents(*FrATagDecl),
+  ElementsAre(DynTypedNode::create(FrA)));
+}
+
 } // end namespace ast_matchers
 } // end namespace clang
Index: clang/include/clang/AST/RecursiveASTVisitor.h
===
--- clang/include/clang/AST/RecursiveASTVisitor.h
+++ clang/include/clang/AST/RecursiveASTVisitor.h
@@ -1549,10 +1549,15 @@
 
 DE

[clang] 23fbfb3 - [clang][AST] RecursiveASTVisitor should visit owned TagDecl of friend type.

2022-08-23 Thread Balázs Kéri via cfe-commits

Author: Balázs Kéri
Date: 2022-08-23T09:15:55+02:00
New Revision: 23fbfb3f725ba3afca65bec04d81826d60cf7fbc

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

LOG: [clang][AST] RecursiveASTVisitor should visit owned TagDecl of friend type.

A FriendDecl node can have a friend record type that owns a RecordDecl
object. This object is different than the one got from TypeSourceInfo
object of the FriendDecl. When building a ParentMapContext this owned
tag decaration has to be encountered to have the parent set for it.

Reviewed By: sammccall

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

Added: 


Modified: 
clang/include/clang/AST/RecursiveASTVisitor.h
clang/unittests/AST/ASTContextParentMapTest.cpp

Removed: 




diff  --git a/clang/include/clang/AST/RecursiveASTVisitor.h 
b/clang/include/clang/AST/RecursiveASTVisitor.h
index bd7fadb87c5fe..054a7436ff749 100644
--- a/clang/include/clang/AST/RecursiveASTVisitor.h
+++ b/clang/include/clang/AST/RecursiveASTVisitor.h
@@ -1549,10 +1549,15 @@ DEF_TRAVERSE_DECL(ImportDecl, {})
 
 DEF_TRAVERSE_DECL(FriendDecl, {
   // Friend is either decl or a type.
-  if (D->getFriendType())
+  if (D->getFriendType()) {
 TRY_TO(TraverseTypeLoc(D->getFriendType()->getTypeLoc()));
-  else
+// Traverse any CXXRecordDecl owned by this type, since
+// it will not be in the parent context:
+if (auto *ET = D->getFriendType()->getType()->getAs())
+  TRY_TO(TraverseDecl(ET->getOwnedTagDecl()));
+  } else {
 TRY_TO(TraverseDecl(D->getFriendDecl()));
+  }
 })
 
 DEF_TRAVERSE_DECL(FriendTemplateDecl, {

diff  --git a/clang/unittests/AST/ASTContextParentMapTest.cpp 
b/clang/unittests/AST/ASTContextParentMapTest.cpp
index 4d11ef0b796a5..515dfb99e1126 100644
--- a/clang/unittests/AST/ASTContextParentMapTest.cpp
+++ b/clang/unittests/AST/ASTContextParentMapTest.cpp
@@ -119,5 +119,34 @@ TEST(GetParents, ImplicitLambdaNodes) {
   Lang_CXX11));
 }
 
+TEST(GetParents, FriendTypeLoc) {
+  auto AST = tooling::buildASTFromCode("struct A { friend struct Fr; };"
+   "struct B { friend struct Fr; };"
+   "struct Fr;");
+  auto &Ctx = AST->getASTContext();
+  auto &TU = *Ctx.getTranslationUnitDecl();
+  auto &A = *TU.lookup(&Ctx.Idents.get("A")).front();
+  auto &B = *TU.lookup(&Ctx.Idents.get("B")).front();
+  auto &FrA = *cast(*++(cast(A).decls_begin()));
+  auto &FrB = *cast(*++(cast(B).decls_begin()));
+  TypeLoc FrALoc = FrA.getFriendType()->getTypeLoc();
+  TypeLoc FrBLoc = FrB.getFriendType()->getTypeLoc();
+  TagDecl *FrATagDecl =
+  FrALoc.getTypePtr()->getAs()->getOwnedTagDecl();
+  TagDecl *FrBTagDecl =
+  FrBLoc.getTypePtr()->getAs()->getOwnedTagDecl();
+
+  EXPECT_THAT(Ctx.getParents(A), ElementsAre(DynTypedNode::create(TU)));
+  EXPECT_THAT(Ctx.getParents(B), ElementsAre(DynTypedNode::create(TU)));
+  EXPECT_THAT(Ctx.getParents(FrA), ElementsAre(DynTypedNode::create(A)));
+  EXPECT_THAT(Ctx.getParents(FrB), ElementsAre(DynTypedNode::create(B)));
+  EXPECT_THAT(Ctx.getParents(FrALoc), ElementsAre(DynTypedNode::create(FrA)));
+  EXPECT_THAT(Ctx.getParents(FrBLoc), ElementsAre(DynTypedNode::create(FrB)));
+  EXPECT_TRUE(FrATagDecl);
+  EXPECT_FALSE(FrBTagDecl);
+  EXPECT_THAT(Ctx.getParents(*FrATagDecl),
+  ElementsAre(DynTypedNode::create(FrA)));
+}
+
 } // end namespace ast_matchers
 } // end namespace clang



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


[PATCH] D132440: [Clang] Avoid using unwind library in the MSVC environment

2022-08-23 Thread Petr Hosek via Phabricator via cfe-commits
phosek created this revision.
phosek added a reviewer: mstorsjo.
Herald added a project: All.
phosek requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

We're seeing the following warnings with --rtlib=compiler-rt:


  lld-link: warning: ignoring unknown argument '--as-needed'
  lld-link: warning: ignoring unknown argument '-lunwind'
  lld-link: warning: ignoring unknown argument '--no-as-needed'


MSVC doesn't use the unwind library, so just omit it.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132440

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp


Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1510,7 +1510,7 @@
   // Targets that don't use unwind libraries.
   if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) ||
   TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() ||
-  UNW == ToolChain::UNW_None)
+  TC.getTriple().isWindowsMSVCEnvironment() || UNW == ToolChain::UNW_None)
 return;
 
   LibGccType LGT = getLibGccType(TC, D, Args);


Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1510,7 +1510,7 @@
   // Targets that don't use unwind libraries.
   if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) ||
   TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() ||
-  UNW == ToolChain::UNW_None)
+  TC.getTriple().isWindowsMSVCEnvironment() || UNW == ToolChain::UNW_None)
 return;
 
   LibGccType LGT = getLibGccType(TC, D, Args);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132440: [Clang] Avoid using unwind library in the MSVC environment

2022-08-23 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo accepted this revision.
mstorsjo added a comment.
This revision is now accepted and ready to land.

LGTM.

(Should we have a testcase for this, or is it trivial enough to just go as is?)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132440

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


[PATCH] D132294: [clang-tidy] Add check of sprintf with fixed size buffer

2022-08-23 Thread 方程 via Phabricator via cfe-commits
Yoorkin updated this revision to Diff 454722.
Yoorkin added a comment.

Now it can find usage of both `sprintf` and `vsprintf`, and then change a small 
piece of code. Here is an option `PreferSafe`, when value is true, the check 
prefers `snprintf_s` `vsnprintf_s` over `snprintf` `vsnprintf`.


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

https://reviews.llvm.org/D132294

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/PrintfWithFixedSizeBufferCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/PrintfWithFixedSizeBufferCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone/printf-with-fixed-size-buffer.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/printf-with-fixed-size-buffer.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/printf-with-fixed-size-buffer.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/printf-with-fixed-size-buffer.cpp
@@ -0,0 +1,33 @@
+// RUN: %check_clang_tidy %s bugprone-printf-with-fixed-size-buffer %t
+
+#include 
+
+void f(){
+  char buff[80];
+  sprintf(buff, "Hello, %s!\n", "world");
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: string to be written may exceeds the size of buffer; use snprintf instead [bugprone-printf-with-fixed-size-buffer]
+  // CHECK-FIXES: snprintf(buff, sizeof(buff), "Hello, %s!\n", "world");
+}
+
+char sbuff[80];
+
+void f2(){
+  sprintf(sbuff, "Hello, %s!\n", "world");
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: string to be written may exceeds the size of buffer; use snprintf instead [bugprone-printf-with-fixed-size-buffer]
+  // CHECK-FIXES: snprintf(sbuff, sizeof(sbuff), "Hello, %s!\n", "world");
+}
+
+void f3(){
+char *dynamic_sized_buff = nullptr;
+sprintf(dynamic_sized_buff, "Hello, %s!\n", "world");
+}
+
+void f4(const char * format, ... ){
+  char buff[100];
+  va_list args;
+  va_start(args, format);
+  vsprintf(buff, format, args);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: string to be written may exceeds the size of buffer; use vsnprintf instead [bugprone-printf-with-fixed-size-buffer]
+  // CHECK-FIXES: vsnprintf(buff, sizeof(buff), format, args);
+  va_end(args);
+}
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -107,6 +107,7 @@
`bugprone-not-null-terminated-result `_, "Yes"
`bugprone-parent-virtual-call `_, "Yes"
`bugprone-posix-return `_, "Yes"
+   `bugprone-printf-with-fixed-size-buffer `_, "Yes"
`bugprone-redundant-branch-condition `_, "Yes"
`bugprone-reserved-identifier `_, "Yes"
`bugprone-shared-ptr-array-mismatch `_, "Yes"
Index: clang-tools-extra/docs/clang-tidy/checks/bugprone/printf-with-fixed-size-buffer.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/bugprone/printf-with-fixed-size-buffer.rst
@@ -0,0 +1,36 @@
+.. title:: clang-tidy - bugprone-printf-with-fixed-size-buffer
+
+
+bugprone-printf-with-fixed-size-buffer
+===
+
+Finds usage of ``sprintf`` or ``vsprintf``, which write output string into a fixed-size array. 
+It will suggest the counted versions instead.
+
+It's a common idiom to have a fixed-size buffer of characters allocated on 
+the stack and then to printf into the buffer. It may be leading to errors if the 
+string to be written exceeds the size of the array pointed to by buffer.
+
+Example:
+.. code-block:: c++
+
+void f(){
+  char buff[80];
+  sprintf(buff, "Hello, %s!\n", "world");
+}
+
+Becomes:
+.. code-block:: c++
+
+void f(){
+  char buff[80];
+  snprintf(buff, sizeof(buff), "Hello, %s!\n", "world");
+}
+
+Options
+---
+
+.. option:: PreferSafe
+
+  When `true`, prefer to use ``snprintf_s`` ``vsnprintf_s`` over ``snprintf`` ``vsnprintf``.
+  Default is `false`.
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -99,6 +99,11 @@
 New checks
 ^^
 
+- New :doc:`bugprone-printf-with-fixed-size-buffer
+  ` check.
+
+  Finds usage of ``sprintf`` or ``vsprintf``, which write output string into a fixed-size array.
+
 - New :doc:`cppcoreguidelines-avoid-const-or-ref-data-members
   ` check.
 
Index: clang-tools-extra/clang-tidy/bugprone/PrintfWithFixedSizeBufferCheck.h
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/bugprone/PrintfWithFixedSizeBufferCheck.h
@@ -0,0 +

[PATCH] D132286: [clang][Interp] Implement function calls

2022-08-23 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 454723.
tbaeder marked 3 inline comments as done.
tbaeder added a comment.

I noticed two problems:

1. Calls returning void didn't work. That needed another new opcode
2. When creating a new stackframe and running `Intepret()`... there's nothing 
actually stopping the interpreter after that stack frame. This triggered the 
`assert(VoidResult.isAbsent())` assert I added. I modified the opcode generator 
to return from the enclosing function if `CanReturn = 1`.


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

https://reviews.llvm.org/D132286

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/EvalEmitter.cpp
  clang/lib/AST/Interp/Function.h
  clang/lib/AST/Interp/Interp.cpp
  clang/lib/AST/Interp/InterpFrame.h
  clang/lib/AST/Interp/Opcodes.td
  clang/lib/AST/Interp/PrimType.h
  clang/test/AST/Interp/functions.cpp
  clang/utils/TableGen/ClangOpcodesEmitter.cpp

Index: clang/utils/TableGen/ClangOpcodesEmitter.cpp
===
--- clang/utils/TableGen/ClangOpcodesEmitter.cpp
+++ clang/utils/TableGen/ClangOpcodesEmitter.cpp
@@ -120,6 +120,9 @@
 
 OS << "case OP_" << ID << ": {\n";
 
+if (CanReturn)
+  OS << "  bool DoReturn = (S.Current == StartFrame);\n";
+
 // Emit calls to read arguments.
 for (size_t I = 0, N = Args.size(); I < N; ++I) {
   OS << "  auto V" << I;
@@ -146,6 +149,9 @@
 if (CanReturn) {
   OS << "  if (!S.Current || S.Current->isRoot())\n";
   OS << "return true;\n";
+
+  OS << "  if (DoReturn)\n";
+  OS << "return true;\n";
 }
 
 OS << "  continue;\n";
Index: clang/test/AST/Interp/functions.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/functions.cpp
@@ -0,0 +1,67 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify %s
+// RUN: %clang_cc1 -verify=ref %s
+
+// expected-no-diagnostics
+// ref-no-diagnostics
+
+constexpr void doNothing() {}
+constexpr int gimme5() {
+  doNothing();
+  return 5;
+}
+static_assert(gimme5() == 5, "");
+
+
+template constexpr T identity(T t) { return t; }
+static_assert(identity(true), "");
+static_assert(identity(true), "");
+static_assert(!identity(false), "");
+
+constexpr auto add(int a, int b) -> int {
+  return identity(a) + identity(b);
+}
+
+constexpr int sub(int a, int b) {
+  return a - b;
+}
+static_assert(sub(5, 2) == 3, "");
+static_assert(sub(0, 5) == -5, "");
+
+constexpr int norm(int n) {
+  if (n >= 0) {
+return identity(n);
+  }
+  return -identity(n);
+}
+static_assert(norm(5) == norm(-5), "");
+
+constexpr int square(int n) {
+  return norm(n) * norm(n);
+}
+static_assert(square(2) == 4, "");
+
+constexpr int add_second(int a, int b, bool doAdd = true) {
+  if (doAdd)
+return a + b;
+  return a;
+}
+static_assert(add_second(10, 3, true) == 13, "");
+static_assert(add_second(10, 3) == 13, "");
+static_assert(add_second(300, -20, false) == 300, "");
+
+
+constexpr int sub(int a, int b, int c) {
+  return a - b - c;
+}
+static_assert(sub(10, 8, 2) == 0, "");
+
+
+constexpr int recursion(int i) {
+  doNothing();
+  i = i - 1;
+  if (i == 0)
+return identity(0);
+
+  return recursion(i);
+}
+static_assert(recursion(10) == 0, "");
Index: clang/lib/AST/Interp/PrimType.h
===
--- clang/lib/AST/Interp/PrimType.h
+++ clang/lib/AST/Interp/PrimType.h
@@ -82,6 +82,7 @@
 /// The macro implicitly exposes a type T in the scope of the inner block.
 #define TYPE_SWITCH_CASE(Name, B) \
   case Name: { using T = PrimConv::T; B; break; }
+
 #define TYPE_SWITCH(Expr, B)   \
   do { \
 switch (Expr) {\
Index: clang/lib/AST/Interp/Opcodes.td
===
--- clang/lib/AST/Interp/Opcodes.td
+++ clang/lib/AST/Interp/Opcodes.td
@@ -42,7 +42,7 @@
 def ArgUint64 : ArgType { let Name = "uint64_t"; }
 def ArgBool : ArgType { let Name = "bool"; }
 
-def ArgFunction : ArgType { let Name = "Function *"; }
+def ArgFunction : ArgType { let Name = "const Function *"; }
 def ArgRecord : ArgType { let Name = "Record *"; }
 
 def ArgSema : ArgType { let Name = "const fltSemantics *"; }
@@ -153,6 +153,22 @@
 // [] -> EXIT
 def NoRet : Opcode {}
 
+
+def Call : Opcode {
+  let Args = [ArgFunction];
+  let Types = [AllTypeClass];
+  let ChangesPC = 1;
+  let HasCustomEval = 1;
+  let HasGroup = 1;
+}
+
+def CallVoid : Opcode {
+  let Args = [ArgFunction];
+  let Types = [];
+  let ChangesPC = 1;
+  let HasCustomEval = 1;
+}
+
 //===--===//
 // Frame management
 //===-

[PATCH] D132294: [clang-tidy] Add check of sprintf with fixed size buffer

2022-08-23 Thread 方程 via Phabricator via cfe-commits
Yoorkin updated this revision to Diff 454724.
Yoorkin added a comment.

I forgot to update comments in `PrintfWithFixedSizeBufferCheck.h`, sorry


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

https://reviews.llvm.org/D132294

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/PrintfWithFixedSizeBufferCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/PrintfWithFixedSizeBufferCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone/printf-with-fixed-size-buffer.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/printf-with-fixed-size-buffer.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/printf-with-fixed-size-buffer.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/printf-with-fixed-size-buffer.cpp
@@ -0,0 +1,33 @@
+// RUN: %check_clang_tidy %s bugprone-printf-with-fixed-size-buffer %t
+
+#include 
+
+void f(){
+  char buff[80];
+  sprintf(buff, "Hello, %s!\n", "world");
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: string to be written may exceeds the size of buffer; use snprintf instead [bugprone-printf-with-fixed-size-buffer]
+  // CHECK-FIXES: snprintf(buff, sizeof(buff), "Hello, %s!\n", "world");
+}
+
+char sbuff[80];
+
+void f2(){
+  sprintf(sbuff, "Hello, %s!\n", "world");
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: string to be written may exceeds the size of buffer; use snprintf instead [bugprone-printf-with-fixed-size-buffer]
+  // CHECK-FIXES: snprintf(sbuff, sizeof(sbuff), "Hello, %s!\n", "world");
+}
+
+void f3(){
+char *dynamic_sized_buff = nullptr;
+sprintf(dynamic_sized_buff, "Hello, %s!\n", "world");
+}
+
+void f4(const char * format, ... ){
+  char buff[100];
+  va_list args;
+  va_start(args, format);
+  vsprintf(buff, format, args);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: string to be written may exceeds the size of buffer; use vsnprintf instead [bugprone-printf-with-fixed-size-buffer]
+  // CHECK-FIXES: vsnprintf(buff, sizeof(buff), format, args);
+  va_end(args);
+}
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -107,6 +107,7 @@
`bugprone-not-null-terminated-result `_, "Yes"
`bugprone-parent-virtual-call `_, "Yes"
`bugprone-posix-return `_, "Yes"
+   `bugprone-printf-with-fixed-size-buffer `_, "Yes"
`bugprone-redundant-branch-condition `_, "Yes"
`bugprone-reserved-identifier `_, "Yes"
`bugprone-shared-ptr-array-mismatch `_, "Yes"
Index: clang-tools-extra/docs/clang-tidy/checks/bugprone/printf-with-fixed-size-buffer.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/bugprone/printf-with-fixed-size-buffer.rst
@@ -0,0 +1,36 @@
+.. title:: clang-tidy - bugprone-printf-with-fixed-size-buffer
+
+
+bugprone-printf-with-fixed-size-buffer
+===
+
+Finds usage of ``sprintf`` or ``vsprintf``, which write output string into a fixed-size array. 
+It will suggest the counted versions instead.
+
+It's a common idiom to have a fixed-size buffer of characters allocated on 
+the stack and then to printf into the buffer. It may be leading to errors if the 
+string to be written exceeds the size of the array pointed to by buffer.
+
+Example:
+.. code-block:: c++
+
+void f(){
+  char buff[80];
+  sprintf(buff, "Hello, %s!\n", "world");
+}
+
+Becomes:
+.. code-block:: c++
+
+void f(){
+  char buff[80];
+  snprintf(buff, sizeof(buff), "Hello, %s!\n", "world");
+}
+
+Options
+---
+
+.. option:: PreferSafe
+
+  When `true`, prefer to use ``snprintf_s`` ``vsnprintf_s`` over ``snprintf`` ``vsnprintf``.
+  Default is `false`.
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -99,6 +99,11 @@
 New checks
 ^^
 
+- New :doc:`bugprone-printf-with-fixed-size-buffer
+  ` check.
+
+  Finds usage of ``sprintf`` or ``vsprintf``, which write output string into a fixed-size array.
+
 - New :doc:`cppcoreguidelines-avoid-const-or-ref-data-members
   ` check.
 
Index: clang-tools-extra/clang-tidy/bugprone/PrintfWithFixedSizeBufferCheck.h
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/bugprone/PrintfWithFixedSizeBufferCheck.h
@@ -0,0 +1,47 @@
+//===--- PrintfWithFixedSizeBufferCheck.h - clang-tidy --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v

[PATCH] D132286: [clang][Interp] Implement function calls

2022-08-23 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 454726.

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

https://reviews.llvm.org/D132286

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/EvalEmitter.cpp
  clang/lib/AST/Interp/Function.h
  clang/lib/AST/Interp/Interp.cpp
  clang/lib/AST/Interp/InterpFrame.h
  clang/lib/AST/Interp/Opcodes.td
  clang/lib/AST/Interp/PrimType.h
  clang/test/AST/Interp/functions.cpp
  clang/utils/TableGen/ClangOpcodesEmitter.cpp

Index: clang/utils/TableGen/ClangOpcodesEmitter.cpp
===
--- clang/utils/TableGen/ClangOpcodesEmitter.cpp
+++ clang/utils/TableGen/ClangOpcodesEmitter.cpp
@@ -120,6 +120,9 @@
 
 OS << "case OP_" << ID << ": {\n";
 
+if (CanReturn)
+  OS << "  bool DoReturn = (S.Current == StartFrame);\n";
+
 // Emit calls to read arguments.
 for (size_t I = 0, N = Args.size(); I < N; ++I) {
   OS << "  auto V" << I;
@@ -146,6 +149,9 @@
 if (CanReturn) {
   OS << "  if (!S.Current || S.Current->isRoot())\n";
   OS << "return true;\n";
+
+  OS << "  if (DoReturn)\n";
+  OS << "return true;\n";
 }
 
 OS << "  continue;\n";
Index: clang/test/AST/Interp/functions.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/functions.cpp
@@ -0,0 +1,67 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify %s
+// RUN: %clang_cc1 -verify=ref %s
+
+// expected-no-diagnostics
+// ref-no-diagnostics
+
+constexpr void doNothing() {}
+constexpr int gimme5() {
+  doNothing();
+  return 5;
+}
+static_assert(gimme5() == 5, "");
+
+
+template constexpr T identity(T t) { return t; }
+static_assert(identity(true), "");
+static_assert(identity(true), "");
+static_assert(!identity(false), "");
+
+constexpr auto add(int a, int b) -> int {
+  return identity(a) + identity(b);
+}
+
+constexpr int sub(int a, int b) {
+  return a - b;
+}
+static_assert(sub(5, 2) == 3, "");
+static_assert(sub(0, 5) == -5, "");
+
+constexpr int norm(int n) {
+  if (n >= 0) {
+return identity(n);
+  }
+  return -identity(n);
+}
+static_assert(norm(5) == norm(-5), "");
+
+constexpr int square(int n) {
+  return norm(n) * norm(n);
+}
+static_assert(square(2) == 4, "");
+
+constexpr int add_second(int a, int b, bool doAdd = true) {
+  if (doAdd)
+return a + b;
+  return a;
+}
+static_assert(add_second(10, 3, true) == 13, "");
+static_assert(add_second(10, 3) == 13, "");
+static_assert(add_second(300, -20, false) == 300, "");
+
+
+constexpr int sub(int a, int b, int c) {
+  return a - b - c;
+}
+static_assert(sub(10, 8, 2) == 0, "");
+
+
+constexpr int recursion(int i) {
+  doNothing();
+  i = i - 1;
+  if (i == 0)
+return identity(0);
+
+  return recursion(i);
+}
+static_assert(recursion(10) == 0, "");
Index: clang/lib/AST/Interp/PrimType.h
===
--- clang/lib/AST/Interp/PrimType.h
+++ clang/lib/AST/Interp/PrimType.h
@@ -82,6 +82,7 @@
 /// The macro implicitly exposes a type T in the scope of the inner block.
 #define TYPE_SWITCH_CASE(Name, B) \
   case Name: { using T = PrimConv::T; B; break; }
+
 #define TYPE_SWITCH(Expr, B)   \
   do { \
 switch (Expr) {\
Index: clang/lib/AST/Interp/Opcodes.td
===
--- clang/lib/AST/Interp/Opcodes.td
+++ clang/lib/AST/Interp/Opcodes.td
@@ -42,7 +42,7 @@
 def ArgUint64 : ArgType { let Name = "uint64_t"; }
 def ArgBool : ArgType { let Name = "bool"; }
 
-def ArgFunction : ArgType { let Name = "Function *"; }
+def ArgFunction : ArgType { let Name = "const Function *"; }
 def ArgRecord : ArgType { let Name = "Record *"; }
 
 def ArgSema : ArgType { let Name = "const fltSemantics *"; }
@@ -153,6 +153,22 @@
 // [] -> EXIT
 def NoRet : Opcode {}
 
+
+def Call : Opcode {
+  let Args = [ArgFunction];
+  let Types = [AllTypeClass];
+  let ChangesPC = 1;
+  let HasCustomEval = 1;
+  let HasGroup = 1;
+}
+
+def CallVoid : Opcode {
+  let Args = [ArgFunction];
+  let Types = [];
+  let ChangesPC = 1;
+  let HasCustomEval = 1;
+}
+
 //===--===//
 // Frame management
 //===--===//
Index: clang/lib/AST/Interp/InterpFrame.h
===
--- clang/lib/AST/Interp/InterpFrame.h
+++ clang/lib/AST/Interp/InterpFrame.h
@@ -113,6 +113,7 @@
 private:
   /// Returns an original argument from the stack.
   template  const T &stackRef(unsigned Offset) {
+assert(Args);
 return *reinterpret_cast(Args - ArgSize + Offset);
   }
 
Index: clang/

[PATCH] D132415: [LLDB] Add data formatter for std::coroutine_handle

2022-08-23 Thread Adrian Vogelsgesang via Phabricator via cfe-commits
avogelsgesang updated this revision to Diff 454728.
avogelsgesang added a comment.

remove unrelated changes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132415

Files:
  clang/docs/tools/clang-formatted-files.txt
  lldb/packages/Python/lldbsuite/test/lldbtest.py
  lldb/source/Plugins/Language/CPlusPlus/CMakeLists.txt
  lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
  lldb/source/Plugins/Language/CPlusPlus/Coroutines.cpp
  lldb/source/Plugins/Language/CPlusPlus/Coroutines.h
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/coroutine_handle/Makefile
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/coroutine_handle/TestCoroutineHandle.py
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/coroutine_handle/main.cpp

Index: lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/coroutine_handle/main.cpp
===
--- /dev/null
+++ lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/coroutine_handle/main.cpp
@@ -0,0 +1,36 @@
+#include 
+
+// `int_generator` is a stripped down, minimal coroutine generator
+// type.
+struct int_generator {
+  struct promise_type {
+int current_value = -1;
+
+auto get_return_object() {
+  return std::coroutine_handle::from_promise(*this);
+}
+auto initial_suspend() { return std::suspend_always(); }
+auto final_suspend() noexcept { return std::suspend_always(); }
+auto return_void() { return std::suspend_always(); }
+void unhandled_exception() { __builtin_unreachable(); }
+auto yield_value(int v) {
+  current_value = v;
+  return std::suspend_always();
+}
+  };
+
+  std::coroutine_handle hdl;
+
+  int_generator(std::coroutine_handle h) : hdl(h) {}
+  ~int_generator() { hdl.destroy(); }
+};
+
+int_generator my_generator_func() { co_yield 42; }
+
+int main() {
+  int_generator gen = my_generator_func();
+  std::coroutine_handle<> type_erased_hdl = gen.hdl;
+  gen.hdl.resume(); // Break at initial_suspend
+  gen.hdl.resume(); // Break after co_yield
+  // Break at final_suspend
+}
Index: lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/coroutine_handle/TestCoroutineHandle.py
===
--- /dev/null
+++ lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/coroutine_handle/TestCoroutineHandle.py
@@ -0,0 +1,75 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+
+
+import lldb
+from lldbsuite.test.decorators import *
+from lldbsuite.test.lldbtest import *
+from lldbsuite.test import lldbutil
+
+USE_LIBSTDCPP = "USE_LIBSTDCPP"
+USE_LIBCPP = "USE_LIBCPP"
+
+class TestCoroutineHandle(TestBase):
+def do_test(self, stdlib_type):
+"""Test std::coroutine_handle is displayed correctly."""
+self.build(dictionary={stdlib_type: "1"})
+
+test_generator_func_ptr_re = re.compile(
+r"^\(a.out`my_generator_func\(\) at main.cpp:[0-9]*\)$")
+
+lldbutil.run_to_source_breakpoint(self, '// Break at initial_suspend',
+lldb.SBFileSpec("main.cpp", False))
+# Check that we show the correct function pointers and the `promise`. 
+self.expect_expr("gen.hdl",
+result_summary=re.compile("^coro frame = 0x[0-9a-f]*$"),
+result_children=[
+ValueCheck(name="resume", summary = test_generator_func_ptr_re),
+ValueCheck(name="destroy", summary = test_generator_func_ptr_re),
+ValueCheck(name="promise", children=[
+ValueCheck(name="current_value", value = "-1"),
+])
+])
+# For type-erased `coroutine_handle<>` we are missing the `promise`
+# but still show `resume` and `destroy`.
+self.expect_expr("type_erased_hdl",
+result_summary=re.compile("^coro frame = 0x[0-9a-f]*$"),
+result_children=[
+ValueCheck(name="resume", summary = test_generator_func_ptr_re),
+ValueCheck(name="destroy", summary = test_generator_func_ptr_re),
+])
+
+lldbutil.run_to_source_breakpoint(self, '// Break after co_yield',
+lldb.SBFileSpec("main.cpp", False))
+# We correctly show the updated value inside `prommise.current_value`.
+self.expect_expr("gen.hdl",
+result_children=[
+ValueCheck(name="resume", summary = test_generator_func_ptr_re),
+ValueCheck(name="destroy", summary = test_generator_func_ptr_re),
+ValueCheck(name="promise", children=[
+ValueCheck(name="current_value", value = "42"),
+])
+])
+
+lldbutil.run_to_source_breakpoint(self, '// Break at final_suspend',
+lldb.SB

[PATCH] D132444: [clang] Allow using -rtlib=platform to switching to the default rtlib on all targets

2022-08-23 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo created this revision.
mstorsjo added reviewers: phosek, thakis, hans.
Herald added a project: All.
mstorsjo requested review of this revision.
Herald added a subscriber: MaskRay.
Herald added a project: clang.

Normally, passing -rtlib=platform overrides any earlier -rtlib
options, and overrides any hardcoded CLANG_DEFAULT_RTLIB option.
However, some targets, MSVC and Darwin, have custom logic for
disallowing specific -rtlib= option values; amend these checks for
allowing the -rtlib=platform option.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132444

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/Darwin.cpp
  clang/test/Driver/msvc-compiler-rt.c
  clang/test/Driver/rtlib-darwin.c


Index: clang/test/Driver/rtlib-darwin.c
===
--- /dev/null
+++ clang/test/Driver/rtlib-darwin.c
@@ -0,0 +1,6 @@
+// RUN: %clang -target x86_64-apple-darwin 
-resource-dir=%S/Inputs/resource_dir --rtlib=compiler-rt -### %s 2>&1 | 
FileCheck %s -check-prefix DARWIN-COMPILER-RT
+// RUN: %clang -target x86_64-apple-darwin 
-resource-dir=%S/Inputs/resource_dir --rtlib=platform -### %s 2>&1 | FileCheck 
%s -check-prefix DARWIN-COMPILER-RT
+// RUN: not %clang %s -target x86_64-apple-darwin --rtlib=libgcc 2>&1 | 
FileCheck %s -check-prefix CHECK-ERROR
+
+// DARWIN-COMPILER-RT: "{{.*}}clang_rt.osx{{.*}}"
+// CHECK-ERROR: unsupported runtime library 'libgcc' for platform 'darwin'
Index: clang/test/Driver/msvc-compiler-rt.c
===
--- clang/test/Driver/msvc-compiler-rt.c
+++ clang/test/Driver/msvc-compiler-rt.c
@@ -1,5 +1,7 @@
 // RUN: %clang -target x86_64-pc-windows-msvc --rtlib=compiler-rt -### %s 2>&1 
| FileCheck %s -check-prefix MSVC-COMPILER-RT
+// RUN: %clang -target x86_64-pc-windows-msvc --rtlib=compiler-rt 
--rtlib=platform -### %s 2>&1 | FileCheck %s -check-prefix MSVC-DEFAULT
 // RUN: not %clang %s -target x86_64-pc-windows-msvc --rtlib=libgcc 2>&1 | 
FileCheck %s -check-prefix CHECK-ERROR
 
 // MSVC-COMPILER-RT: "{{.*}}clang_rt.builtins{{.*}}"
+// MSVC-DEFAULT-NOT: "{{.*}}clang_rt.builtins{{.*}}"
 // CHECK-ERROR: unsupported runtime library 'libgcc' for platform 'MSVC'
Index: clang/lib/Driver/ToolChains/Darwin.cpp
===
--- clang/lib/Driver/ToolChains/Darwin.cpp
+++ clang/lib/Driver/ToolChains/Darwin.cpp
@@ -1385,7 +1385,7 @@
 const ArgList &Args) const {
   if (Arg* A = Args.getLastArg(options::OPT_rtlib_EQ)) {
 StringRef Value = A->getValue();
-if (Value != "compiler-rt")
+if (Value != "compiler-rt" && Value != "platform")
   getDriver().Diag(clang::diag::err_drv_unsupported_rtlib_for_platform)
   << Value << "darwin";
   }
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1584,9 +1584,10 @@
 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
   // Issue error diagnostic if libgcc is explicitly specified
   // through command line as --rtlib option argument.
-  if (Args.hasArg(options::OPT_rtlib_EQ)) {
+  Arg *A = Args.getLastArg(options::OPT_rtlib_EQ);
+  if (A && A->getValue() != StringRef("platform")) {
 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
-<< Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
+<< A->getValue() << "MSVC";
   }
 } else
   AddLibgcc(TC, D, CmdArgs, Args);


Index: clang/test/Driver/rtlib-darwin.c
===
--- /dev/null
+++ clang/test/Driver/rtlib-darwin.c
@@ -0,0 +1,6 @@
+// RUN: %clang -target x86_64-apple-darwin -resource-dir=%S/Inputs/resource_dir --rtlib=compiler-rt -### %s 2>&1 | FileCheck %s -check-prefix DARWIN-COMPILER-RT
+// RUN: %clang -target x86_64-apple-darwin -resource-dir=%S/Inputs/resource_dir --rtlib=platform -### %s 2>&1 | FileCheck %s -check-prefix DARWIN-COMPILER-RT
+// RUN: not %clang %s -target x86_64-apple-darwin --rtlib=libgcc 2>&1 | FileCheck %s -check-prefix CHECK-ERROR
+
+// DARWIN-COMPILER-RT: "{{.*}}clang_rt.osx{{.*}}"
+// CHECK-ERROR: unsupported runtime library 'libgcc' for platform 'darwin'
Index: clang/test/Driver/msvc-compiler-rt.c
===
--- clang/test/Driver/msvc-compiler-rt.c
+++ clang/test/Driver/msvc-compiler-rt.c
@@ -1,5 +1,7 @@
 // RUN: %clang -target x86_64-pc-windows-msvc --rtlib=compiler-rt -### %s 2>&1 | FileCheck %s -check-prefix MSVC-COMPILER-RT
+// RUN: %clang -target x86_64-pc-windows-msvc --rtlib=compiler-rt --rtlib=platform -### %s 2>&1 | FileCheck %s -check-prefix MSVC-DEFAULT
 // RUN: not %clang %s -target x86_64-pc-windows-msvc --rtlib=libgcc 2>&1 | FileCheck %s -check-prefix CHECK-ERRO

[PATCH] D132141: [X86] Emulate _rdrand64_step with two rdrand32 if it is 32bit

2022-08-23 Thread Bing Yu via Phabricator via cfe-commits
yubing updated this revision to Diff 454738.
yubing added a comment.

Execute the second rdrand32 despite of whether the first one fail or not


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132141

Files:
  clang/lib/Headers/immintrin.h
  clang/test/CodeGen/X86/rdrand-builtins.c

Index: clang/test/CodeGen/X86/rdrand-builtins.c
===
--- clang/test/CodeGen/X86/rdrand-builtins.c
+++ clang/test/CodeGen/X86/rdrand-builtins.c
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -no-opaque-pointers -ffreestanding %s -triple=x86_64-unknown-unknown -target-feature +rdrnd -target-feature +rdseed -emit-llvm -o - -Wall -Werror | FileCheck %s --check-prefixes=CHECK,X64
-// RUN: %clang_cc1 -no-opaque-pointers -ffreestanding %s -triple=i386-unknown-unknown -target-feature +rdrnd -target-feature +rdseed -emit-llvm -o - -Wall -Werror | FileCheck %s --check-prefixes=CHECK
+// RUN: %clang_cc1 -no-opaque-pointers -ffreestanding %s -triple=i386-unknown-unknown -target-feature +rdrnd -target-feature +rdseed -emit-llvm -o - -Wall -Werror | FileCheck %s --check-prefixes=CHECK,X86
 
 #include 
 
@@ -17,14 +17,61 @@
 // CHECK: store i32
 }
 
-#if __x86_64__
 int rdrand64(unsigned long long *p) {
   return _rdrand64_step(p);
 // X64: @rdrand64
 // X64: call { i64, i32 } @llvm.x86.rdrand.64
 // X64: store i64
+
+// X86-LABEL: @rdrand64(
+// X86-NEXT:  entry:
+// X86-NEXT:[[RETVAL_I:%.*]] = alloca i32, align 4
+// X86-NEXT:[[__P_ADDR_I:%.*]] = alloca i64*, align 4
+// X86-NEXT:[[__LO_I:%.*]] = alloca i32, align 4
+// X86-NEXT:[[__HI_I:%.*]] = alloca i32, align 4
+// X86-NEXT:[[__RES_LO_I:%.*]] = alloca i32, align 4
+// X86-NEXT:[[__RES_HI_I:%.*]] = alloca i32, align 4
+// X86-NEXT:[[P_ADDR:%.*]] = alloca i64*, align 4
+// X86-NEXT:store i64* [[P:%.*]], i64** [[P_ADDR]], align 4
+// X86-NEXT:[[TMP0:%.*]] = load i64*, i64** [[P_ADDR]], align 4
+// X86-NEXT:store i64* [[TMP0]], i64** [[__P_ADDR_I]], align 4
+// X86-NEXT:[[TMP1:%.*]] = call { i32, i32 } @llvm.x86.rdrand.32()
+// X86-NEXT:[[TMP2:%.*]] = extractvalue { i32, i32 } [[TMP1]], 0
+// X86-NEXT:store i32 [[TMP2]], i32* [[__LO_I]], align 4
+// X86-NEXT:[[TMP3:%.*]] = extractvalue { i32, i32 } [[TMP1]], 1
+// X86-NEXT:store i32 [[TMP3]], i32* [[__RES_LO_I]], align 4
+// X86-NEXT:[[TMP4:%.*]] = call { i32, i32 } @llvm.x86.rdrand.32()
+// X86-NEXT:[[TMP5:%.*]] = extractvalue { i32, i32 } [[TMP4]], 0
+// X86-NEXT:store i32 [[TMP5]], i32* [[__HI_I]], align 4
+// X86-NEXT:[[TMP6:%.*]] = extractvalue { i32, i32 } [[TMP4]], 1
+// X86-NEXT:store i32 [[TMP6]], i32* [[__RES_HI_I]], align 4
+// X86-NEXT:[[TMP7:%.*]] = load i32, i32* [[__RES_LO_I]], align 4
+// X86-NEXT:[[TOBOOL_I:%.*]] = icmp ne i32 [[TMP7]], 0
+// X86-NEXT:br i1 [[TOBOOL_I]], label [[LAND_LHS_TRUE_I:%.*]], label [[IF_ELSE_I:%.*]]
+// X86:   land.lhs.true.i:
+// X86-NEXT:[[TMP8:%.*]] = load i32, i32* [[__RES_HI_I]], align 4
+// X86-NEXT:[[TOBOOL1_I:%.*]] = icmp ne i32 [[TMP8]], 0
+// X86-NEXT:br i1 [[TOBOOL1_I]], label [[IF_THEN_I:%.*]], label [[IF_ELSE_I]]
+// X86:   if.then.i:
+// X86-NEXT:[[TMP9:%.*]] = load i32, i32* [[__HI_I]], align 4
+// X86-NEXT:[[CONV_I:%.*]] = zext i32 [[TMP9]] to i64
+// X86-NEXT:[[SHL_I:%.*]] = shl i64 [[CONV_I]], 32
+// X86-NEXT:[[TMP10:%.*]] = load i32, i32* [[__LO_I]], align 4
+// X86-NEXT:[[CONV2_I:%.*]] = zext i32 [[TMP10]] to i64
+// X86-NEXT:[[OR_I:%.*]] = or i64 [[SHL_I]], [[CONV2_I]]
+// X86-NEXT:[[TMP11:%.*]] = load i64*, i64** [[__P_ADDR_I]], align 4
+// X86-NEXT:store i64 [[OR_I]], i64* [[TMP11]], align 4
+// X86-NEXT:store i32 1, i32* [[RETVAL_I]], align 4
+// X86-NEXT:br label [[_RDRAND64_STEP_EXIT:%.*]]
+// X86:   if.else.i:
+// X86-NEXT:[[TMP12:%.*]] = load i64*, i64** [[__P_ADDR_I]], align 4
+// X86-NEXT:store i64 0, i64* [[TMP12]], align 4
+// X86-NEXT:store i32 0, i32* [[RETVAL_I]], align 4
+// X86-NEXT:br label [[_RDRAND64_STEP_EXIT]]
+// X86:   _rdrand64_step.exit:
+// X86-NEXT:[[TMP13:%.*]] = load i32, i32* [[RETVAL_I]], align 4
+// X86-NEXT:ret i32 [[TMP13]]
 }
-#endif
 
 int rdseed16(unsigned short *p) {
   return _rdseed16_step(p);
Index: clang/lib/Headers/immintrin.h
===
--- clang/lib/Headers/immintrin.h
+++ clang/lib/Headers/immintrin.h
@@ -291,6 +291,23 @@
 {
   return (int)__builtin_ia32_rdrand64_step(__p);
 }
+#else
+// We need to emulate the functionality of 64-bit rdrand with 2 32-bit
+// rdrand instructions.
+static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("rdrnd")))
+_rdrand64_step(unsigned long long *__p)
+{
+  unsigned int __lo, __hi;
+  int __res_lo = __builtin_ia32_rdrand32_step(&__lo);
+  int __res_hi = __builtin_ia32_rdrand32_step(&__hi);
+  if (__res_lo

[PATCH] D132451: [docs] Add examples for printing asynchronous stack for coroutines

2022-08-23 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu created this revision.
ChuanqiXu added reviewers: avogelsgesang, dblaikie, aprantl, labath, 
JDevlieghere.
ChuanqiXu added a project: debug-info.
Herald added a project: All.
ChuanqiXu requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Previously when I wrote this document, I felt the completed scripts was 
lengthy, redundant and not easy to read. So I didn't add complete examples in 
the previous commit.

However, in the recent discussion with @avogelsgesang, I found people may not 
know how to use debugging scripts to improve their debugging efficiency. So 
now, I feel like it is helpful to put the examples even if they are a little 
bit long.

I understand it may be better to provide debugging scripts for lldb too since 
we are in LLVM community : ) But I never used lldb before... So I put the 
examples for gdb only. I guess this won't be a blocking issue?


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132451

Files:
  clang/docs/DebuggingCoroutines.rst

Index: clang/docs/DebuggingCoroutines.rst
===
--- clang/docs/DebuggingCoroutines.rst
+++ clang/docs/DebuggingCoroutines.rst
@@ -368,6 +368,345 @@
 
 This logic should be quite easily captured in a debugger script.
 
+Examples to printasynchronous stack
+---
+
+Here is an example to print the asynchronous stack for the normal task implementation.
+
+.. code-block:: c++
+
+  // debugging-example.cpp
+  #include 
+  #include 
+  #include 
+
+  struct task {
+struct promise_type {
+  task get_return_object();
+  std::suspend_always initial_suspend() { return {}; }
+  
+  void unhandled_exception() noexcept {}
+
+  struct FinalSuspend {
+std::coroutine_handle<> continuation;
+auto await_ready() noexcept { return false; }
+auto await_suspend(std::coroutine_handle<> handle) noexcept {
+  return continuation;
+}
+void await_resume() noexcept {}
+  };
+  FinalSuspend final_suspend() noexcept { return {continuation}; }
+
+  void return_value(int res) { result = res; }
+
+  std::coroutine_handle<> continuation = std::noop_coroutine();
+  int result = 0;
+};
+
+task(std::coroutine_handle handle) : handle(handle) {}
+~task() {
+  if (handle)
+handle.destroy();
+}
+
+auto operator co_await() {
+  struct Awaiter {
+std::coroutine_handle handle;
+auto await_ready() { return false; }
+auto await_suspend(std::coroutine_handle<> continuation) {
+  handle.promise().continuation = continuation;
+  return handle;
+}
+int await_resume() {
+  int ret = handle.promise().result;
+  handle.destroy();
+  return ret;
+}
+  };
+  return Awaiter{std::exchange(handle, nullptr)};
+}
+
+int syncStart() {
+  handle.resume();
+  return handle.promise().result;
+}
+
+  private:
+std::coroutine_handle handle;
+  };
+
+  task task::promise_type::get_return_object() {
+return std::coroutine_handle::from_promise(*this);
+  }
+
+  namespace detail {
+  template 
+  task chain_fn() {
+co_return N + co_await chain_fn();
+  }
+
+  template <>
+  task chain_fn<0>() {
+// This is the default breakpoint.
+__builtin_debugtrap();
+co_return 0;
+  }
+  }  // namespace detail
+
+  task chain() {
+co_return co_await detail::chain_fn<30>();
+  }
+
+  int main() {
+std::cout << chain().syncStart() << "\n";
+return 0;
+  }
+
+In the example, the ``task`` coroutine holds a ``continuation`` field,
+which would be resumed once the ``task`` completes.
+In another word, the ``continuation`` is the asynchronous caller for the ``task``.
+Just like the normal function returns to its caller when the function completes.
+
+So we can use the ``continuation`` field to construct the asynchronous stack:
+
+.. code-block:: python
+
+  # debugging-helper.py
+  import gdb
+  from gdb.FrameDecorator import FrameDecorator
+
+  class SymValueWrapper():
+  def __init__(self, symbol, value):
+  self.sym = symbol
+  self.val = value
+
+  def __str__(self):
+  return str(self.sym) + " = " + str(self.val)
+
+  def get_long_pointer_size():
+  return gdb.lookup_type('long').pointer().sizeof
+
+  def cast_addr2long_pointer(addr):
+  return gdb.Value(addr).cast(gdb.lookup_type('long').pointer())
+
+  def dereference(addr):
+  return long(cast_addr2long_pointer(addr).dereference())
+
+  class CoroutineFrame(object):
+  def __init__(self, task_addr):
+  self.frame_addr = task_addr
+  self.resume_addr = task_addr
+  self.destroy_addr = task_addr + get_long_pointer_size()
+  self.promise_addr = task_addr + get_long_pointer_size() * 2
+  # In the example, the continuation is the first field member of t

[PATCH] D132451: [docs] Add examples for printing asynchronous stack for coroutines

2022-08-23 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu updated this revision to Diff 454744.
ChuanqiXu edited the summary of this revision.
ChuanqiXu added a comment.

Fix a typo.


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

https://reviews.llvm.org/D132451

Files:
  clang/docs/DebuggingCoroutines.rst

Index: clang/docs/DebuggingCoroutines.rst
===
--- clang/docs/DebuggingCoroutines.rst
+++ clang/docs/DebuggingCoroutines.rst
@@ -368,6 +368,345 @@
 
 This logic should be quite easily captured in a debugger script.
 
+Examples to print asynchronous stack
+
+
+Here is an example to print the asynchronous stack for the normal task implementation.
+
+.. code-block:: c++
+
+  // debugging-example.cpp
+  #include 
+  #include 
+  #include 
+
+  struct task {
+struct promise_type {
+  task get_return_object();
+  std::suspend_always initial_suspend() { return {}; }
+  
+  void unhandled_exception() noexcept {}
+
+  struct FinalSuspend {
+std::coroutine_handle<> continuation;
+auto await_ready() noexcept { return false; }
+auto await_suspend(std::coroutine_handle<> handle) noexcept {
+  return continuation;
+}
+void await_resume() noexcept {}
+  };
+  FinalSuspend final_suspend() noexcept { return {continuation}; }
+
+  void return_value(int res) { result = res; }
+
+  std::coroutine_handle<> continuation = std::noop_coroutine();
+  int result = 0;
+};
+
+task(std::coroutine_handle handle) : handle(handle) {}
+~task() {
+  if (handle)
+handle.destroy();
+}
+
+auto operator co_await() {
+  struct Awaiter {
+std::coroutine_handle handle;
+auto await_ready() { return false; }
+auto await_suspend(std::coroutine_handle<> continuation) {
+  handle.promise().continuation = continuation;
+  return handle;
+}
+int await_resume() {
+  int ret = handle.promise().result;
+  handle.destroy();
+  return ret;
+}
+  };
+  return Awaiter{std::exchange(handle, nullptr)};
+}
+
+int syncStart() {
+  handle.resume();
+  return handle.promise().result;
+}
+
+  private:
+std::coroutine_handle handle;
+  };
+
+  task task::promise_type::get_return_object() {
+return std::coroutine_handle::from_promise(*this);
+  }
+
+  namespace detail {
+  template 
+  task chain_fn() {
+co_return N + co_await chain_fn();
+  }
+
+  template <>
+  task chain_fn<0>() {
+// This is the default breakpoint.
+__builtin_debugtrap();
+co_return 0;
+  }
+  }  // namespace detail
+
+  task chain() {
+co_return co_await detail::chain_fn<30>();
+  }
+
+  int main() {
+std::cout << chain().syncStart() << "\n";
+return 0;
+  }
+
+In the example, the ``task`` coroutine holds a ``continuation`` field,
+which would be resumed once the ``task`` completes.
+In another word, the ``continuation`` is the asynchronous caller for the ``task``.
+Just like the normal function returns to its caller when the function completes.
+
+So we can use the ``continuation`` field to construct the asynchronous stack:
+
+.. code-block:: python
+
+  # debugging-helper.py
+  import gdb
+  from gdb.FrameDecorator import FrameDecorator
+
+  class SymValueWrapper():
+  def __init__(self, symbol, value):
+  self.sym = symbol
+  self.val = value
+
+  def __str__(self):
+  return str(self.sym) + " = " + str(self.val)
+
+  def get_long_pointer_size():
+  return gdb.lookup_type('long').pointer().sizeof
+
+  def cast_addr2long_pointer(addr):
+  return gdb.Value(addr).cast(gdb.lookup_type('long').pointer())
+
+  def dereference(addr):
+  return long(cast_addr2long_pointer(addr).dereference())
+
+  class CoroutineFrame(object):
+  def __init__(self, task_addr):
+  self.frame_addr = task_addr
+  self.resume_addr = task_addr
+  self.destroy_addr = task_addr + get_long_pointer_size()
+  self.promise_addr = task_addr + get_long_pointer_size() * 2
+  # In the example, the continuation is the first field member of the promise_type.
+  # So they have the same addresses.
+  # If we want to generalize the scripts to other coroutine types, we need to be sure
+  # the continuation field is the first memeber of promise_type.
+  self.continuation_addr = self.promise_addr
+
+  def next_task_addr(self):
+  return dereference(self.continuation_addr)
+
+  class CoroutineFrameDecorator(FrameDecorator):
+  def __init__(self, coro_frame):
+  super(CoroutineFrameDecorator, self).__init__(None)
+  self.coro_frame = coro_frame
+  self.resume_func = dereference(self.coro_frame.resume_addr)
+  self.resume_func_block = gdb.block_for_pc(self.resume_func)
+  if self.resume_func_block == None:
+  r

[PATCH] D132451: [docs] Add examples for printing asynchronous stack for coroutines

2022-08-23 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu updated this revision to Diff 454745.
ChuanqiXu added a comment.

Fix a typo.


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

https://reviews.llvm.org/D132451

Files:
  clang/docs/DebuggingCoroutines.rst

Index: clang/docs/DebuggingCoroutines.rst
===
--- clang/docs/DebuggingCoroutines.rst
+++ clang/docs/DebuggingCoroutines.rst
@@ -368,6 +368,345 @@
 
 This logic should be quite easily captured in a debugger script.
 
+Examples to print asynchronous stack
+
+
+Here is an example to print the asynchronous stack for the normal task implementation.
+
+.. code-block:: c++
+
+  // debugging-example.cpp
+  #include 
+  #include 
+  #include 
+
+  struct task {
+struct promise_type {
+  task get_return_object();
+  std::suspend_always initial_suspend() { return {}; }
+  
+  void unhandled_exception() noexcept {}
+
+  struct FinalSuspend {
+std::coroutine_handle<> continuation;
+auto await_ready() noexcept { return false; }
+auto await_suspend(std::coroutine_handle<> handle) noexcept {
+  return continuation;
+}
+void await_resume() noexcept {}
+  };
+  FinalSuspend final_suspend() noexcept { return {continuation}; }
+
+  void return_value(int res) { result = res; }
+
+  std::coroutine_handle<> continuation = std::noop_coroutine();
+  int result = 0;
+};
+
+task(std::coroutine_handle handle) : handle(handle) {}
+~task() {
+  if (handle)
+handle.destroy();
+}
+
+auto operator co_await() {
+  struct Awaiter {
+std::coroutine_handle handle;
+auto await_ready() { return false; }
+auto await_suspend(std::coroutine_handle<> continuation) {
+  handle.promise().continuation = continuation;
+  return handle;
+}
+int await_resume() {
+  int ret = handle.promise().result;
+  handle.destroy();
+  return ret;
+}
+  };
+  return Awaiter{std::exchange(handle, nullptr)};
+}
+
+int syncStart() {
+  handle.resume();
+  return handle.promise().result;
+}
+
+  private:
+std::coroutine_handle handle;
+  };
+
+  task task::promise_type::get_return_object() {
+return std::coroutine_handle::from_promise(*this);
+  }
+
+  namespace detail {
+  template 
+  task chain_fn() {
+co_return N + co_await chain_fn();
+  }
+
+  template <>
+  task chain_fn<0>() {
+// This is the default breakpoint.
+__builtin_debugtrap();
+co_return 0;
+  }
+  }  // namespace detail
+
+  task chain() {
+co_return co_await detail::chain_fn<30>();
+  }
+
+  int main() {
+std::cout << chain().syncStart() << "\n";
+return 0;
+  }
+
+In the example, the ``task`` coroutine holds a ``continuation`` field,
+which would be resumed once the ``task`` completes.
+In another word, the ``continuation`` is the asynchronous caller for the ``task``.
+Just like the normal function returns to its caller when the function completes.
+
+So we can use the ``continuation`` field to construct the asynchronous stack:
+
+.. code-block:: python
+
+  # debugging-helper.py
+  import gdb
+  from gdb.FrameDecorator import FrameDecorator
+
+  class SymValueWrapper():
+  def __init__(self, symbol, value):
+  self.sym = symbol
+  self.val = value
+
+  def __str__(self):
+  return str(self.sym) + " = " + str(self.val)
+
+  def get_long_pointer_size():
+  return gdb.lookup_type('long').pointer().sizeof
+
+  def cast_addr2long_pointer(addr):
+  return gdb.Value(addr).cast(gdb.lookup_type('long').pointer())
+
+  def dereference(addr):
+  return long(cast_addr2long_pointer(addr).dereference())
+
+  class CoroutineFrame(object):
+  def __init__(self, task_addr):
+  self.frame_addr = task_addr
+  self.resume_addr = task_addr
+  self.destroy_addr = task_addr + get_long_pointer_size()
+  self.promise_addr = task_addr + get_long_pointer_size() * 2
+  # In the example, the continuation is the first field member of the promise_type.
+  # So they have the same addresses.
+  # If we want to generalize the scripts to other coroutine types, we need to be sure
+  # the continuation field is the first memeber of promise_type.
+  self.continuation_addr = self.promise_addr
+
+  def next_task_addr(self):
+  return dereference(self.continuation_addr)
+
+  class CoroutineFrameDecorator(FrameDecorator):
+  def __init__(self, coro_frame):
+  super(CoroutineFrameDecorator, self).__init__(None)
+  self.coro_frame = coro_frame
+  self.resume_func = dereference(self.coro_frame.resume_addr)
+  self.resume_func_block = gdb.block_for_pc(self.resume_func)
+  if self.resume_func_block == None:
+  raise Exception('Not stackless coroutine.')
+   

[PATCH] D132451: [docs] Add examples for printing asynchronous stack for coroutines

2022-08-23 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/docs/DebuggingCoroutines.rst:619
+
+.. code-block:: text
+

Here we can't use `.. code-block:: console` since it will meet some parsing 
problems.


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

https://reviews.llvm.org/D132451

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


[PATCH] D132141: [X86] Emulate _rdrand64_step with two rdrand32 if it is 32bit

2022-08-23 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon accepted this revision.
RKSimon added a comment.
This revision is now accepted and ready to land.

LGTM - cheers


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132141

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


[PATCH] D131616: [clang][dataflow] Generalise match switch utility to other AST types and add a `CFGMatchSwitch` which currently handles `CFGStmt` and `CFGInitializer`.

2022-08-23 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev added inline comments.



Comment at: clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h:24-25
+#include "clang/AST/Stmt.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Analysis/CFG.h"

These seem unnecessary.



Comment at: clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h:28
+#include "clang/Analysis/FlowSensitive/MatchSwitch.h"
+#include "llvm/ADT/StringRef.h"
+#include 

This seems unnecessary.



Comment at: clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h:30
+#include 
+#include 
+#include 

This seems unnecessary.



Comment at: clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h:32
+#include 
+#include 
+

This seems unnecessary.



Comment at: clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h:55
+MSActionT A) && {
+std::move(std::move(StmtBuilder).template CaseOf(M, A));
+return std::move(*this);

Is the outer move necessary? Also, aren't we supposed to assign the result back 
to `StmtBuilder`? Same comment for `InitBuilder` below.



Comment at: clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h:1
 //=== MatchSwitch.h -*- C++ 
-*-===//
 //

Let's add a FIXME to rename the file to ASTMatchSwitch.h and update the comment 
below.



Comment at: clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h:47-51
+template  using MSMatcherT = ast_matchers::internal::Matcher;
+
+template 
+using MSActionT = std::function;

What do you think about calling these `MatchSwitchMatcher` and 
`MatchSwitchAction`?



Comment at: clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h:64
+/// callbacks, which together define a switch that can be applied to a node
+/// whose type can be derived from `BaseT`. This structure can simplify the
+/// definition of `transfer` functions that rely on pattern-matching.





Comment at: clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h:90
   ///
-  ///  `Node` should be a subclass of `Stmt`.
-  template 
-  MatchSwitchBuilder &&
-  CaseOf(ast_matchers::internal::Matcher M,
- std::function
- A) && {
+  ///  `NodeT` should be derivable from `BaseT`.
+  template 

Let's add a static assert.



Comment at: clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h:90
   ///
-  ///  `Node` should be a subclass of `Stmt`.
-  template 
-  MatchSwitchBuilder &&
-  CaseOf(ast_matchers::internal::Matcher M,
- std::function
- A) && {
+  ///  `NodeT` should be derivable from `BaseT`.
+  template 

sgatev wrote:
> Let's add a static assert.




Comment at: clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp:12
+#include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/Stmt.h"

This seems unnecessary.



Comment at: clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp:14-15
+#include "clang/AST/Stmt.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Analysis/CFG.h"

These seem unnecessary.



Comment at: clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp:20-24
+#include 
+#include 
+#include 
+#include 
+#include 

These seem unnecessary.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131616

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


[PATCH] D132377: [clang][dataflow] Add `SetupTest` parameter for `AnalysisInputs`.

2022-08-23 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 454754.
wyt marked 5 inline comments as done.
wyt added a comment.

Address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132377

Files:
  clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h

Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -56,28 +56,6 @@
 
 namespace test {
 
-/// Arguments for building the dataflow analysis.
-template  struct AnalysisInputs {
-  /// Input code that is analyzed.
-  llvm::StringRef Code;
-  /// The body of the function which matches this matcher is analyzed.
-  ast_matchers::internal::Matcher TargetFuncMatcher;
-  /// The analysis to be run is constructed with this function that takes as
-  /// argument the AST generated from the code being analyzed and the
-  /// initial state from which the analysis starts with.
-  std::function MakeAnalysis;
-  /// If provided, this function is applied on each CFG element after the
-  /// analysis has been run.
-  std::function
-  PostVisitCFG = nullptr;
-
-  /// Options for building the AST context.
-  ArrayRef ASTBuildArgs = {};
-  /// Options for building the AST context.
-  const tooling::FileContentMappings &ASTBuildVirtualMappedFiles = {};
-};
-
 /// Contains data structures required and produced by a dataflow analysis run.
 struct AnalysisOutputs {
   /// Input code that is analyzed. Points within the code may be marked with
@@ -106,60 +84,43 @@
   llvm::ArrayRef> BlockStates;
 };
 
+/// Arguments for building the dataflow analysis.
+template  struct AnalysisInputs {
+  /// Input code that is analyzed.
+  llvm::StringRef Code;
+  /// The body of the function which matches this matcher is analyzed.
+  ast_matchers::internal::Matcher TargetFuncMatcher;
+  /// The analysis to be run is constructed with this function that takes as
+  /// argument the AST generated from the code being analyzed and the
+  /// initial state from which the analysis starts with.
+  std::function MakeAnalysis;
+  /// If provided, this function is executed immediately before running the
+  /// dataflow analysis to allow for additional setup. All fields in the
+  /// `AnalysisOutputs` argument will be initialized except for the
+  /// `BlockStates` field which is only computed later during the analysis.
+  std::function SetupTest = nullptr;
+  /// If provided, this function is applied on each CFG element after the
+  /// analysis has been run.
+  std::function
+  PostVisitCFG = nullptr;
+
+  /// Options for building the AST context.
+  ArrayRef ASTBuildArgs = {};
+  /// Options for building the AST context.
+  const tooling::FileContentMappings &ASTBuildVirtualMappedFiles = {};
+};
+
 /// Returns assertions based on annotations that are present after statements in
 /// `AnnotatedCode`.
 llvm::Expected>
 buildStatementToAnnotationMapping(const FunctionDecl *Func,
   llvm::Annotations AnnotatedCode);
 
-/// Returns line numbers and content of the annotations in `AO.Code`.
+/// Returns line numbers and content of the annotations in `AnnotatedCode`.
 llvm::DenseMap
-getAnnotationLinesAndContent(AnalysisOutputs &AO);
-
-// FIXME: Return a string map instead of a vector of pairs.
-//
-/// Returns the analysis states at each annotated statement in `AO.Code`.
-template 
-llvm::Expected>>>
-getAnnotationStates(AnalysisOutputs &AO) {
-  using StateT = DataflowAnalysisState;
-  // FIXME: Extend to annotations on non-statement constructs.
-  // Get annotated statements.
-  llvm::Expected>
-  MaybeStmtToAnnotations =
-  buildStatementToAnnotationMapping(AO.Target, AO.Code);
-  if (!MaybeStmtToAnnotations)
-return MaybeStmtToAnnotations.takeError();
-  auto &StmtToAnnotations = *MaybeStmtToAnnotations;
-
-  // Compute a map from statement annotations to the state computed
-  // for the program point immediately after the annotated statement.
-  std::vector> Results;
-  for (const CFGBlock *Block : AO.CFCtx.getCFG()) {
-// Skip blocks that were not evaluated.
-if (!AO.BlockStates[Block->getBlockID()])
-  continue;
-
-transferBlock(
-AO.CFCtx, AO.BlockStates, *Block, AO.InitEnv, AO.Analysis,
-[&Results,
- &StmtToAnnotations](const clang::CFGElement &Element,
- const TypeErasedDataflowAnalysisState &State) {
-  auto Stmt = Element.getAs();
-  if (!Stmt)
-return;
-  auto It = StmtToAnnotations.find(Stmt->getStmt());
-  if (It == StmtToAnnotations.end())
-return;
-  auto *Lattice =
-  llvm::any_cast(&State.Lattice.Value);
-  Results.emplace_back(It->second, StateT{*Lattice, Stat

[PATCH] D113107: Support of expression granularity for _Float16.

2022-08-23 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei added inline comments.



Comment at: clang/test/CodeGen/X86/Float16-arithmetic.c:207
+// CHECK-NEXT:[[EXT:%.*]] = fpext half [[TMP0]] to float
+// CHECK-NEXT:store float [[EXT]], ptr [[RETVAL]], align 2
+// CHECK-NEXT:[[TMP1:%.*]] = load half, ptr [[RETVAL]], align 2

rjmccall wrote:
> pengfei wrote:
> > rjmccall wrote:
> > > zahiraam wrote:
> > > > zahiraam wrote:
> > > > > pengfei wrote:
> > > > > > Not sure if we need a fptrunc and store the half value. The 
> > > > > > following tests have the same problem.
> > > > > I think that's what we want?
> > > > > // CHECK-LABEL: @RealOp(
> > > > > // CHECK-NEXT:  entry:
> > > > > // CHECK-NEXT:[[A_ADDR:%.*]] = alloca half, align 2
> > > > > // CHECK-NEXT:store half [[A:%.*]], ptr [[A_ADDR]], align 2
> > > > > // CHECK-NEXT:[[TMP0:%.*]] = load half, ptr [[A_ADDR]], align 2
> > > > > // CHECK-NEXT:[[EXT:%.*]] = fpext half [[TMP0]] to float
> > > > > // CHECK-NEXT:[[UNPROMOTION:%.*]] = fptrunc float [[EXT]] to half
> > > > > // CHECK-NEXT:ret half [[UNPROMOTION]]
> > > > > 
> > > > > Do you agree? If this is correct, I will make the change the other 
> > > > > operators.
> > > > But I feel like we should be returning a float no?  In which case it 
> > > > will be more tricky (need to calculate the Address with the promoted 
> > > > elementype)? @rmjccall?
> > > The function is declared as returning `_Float16`, not `float`.  This is 
> > > therefore a question about when we're allowed to return a value in 
> > > greater precision than the declared return type, which raises three 
> > > sub-questions: one about ABI, one about language semantics, and one about 
> > > our handling in the implementation.
> > > 
> > > The first is about ABI.  This mode is not supposed to be ABI-breaking, so 
> > > whenever the ABI is in doubt, and the target makes a `_Float16` return 
> > > incompatible with the ABI of a `float` return, we must use the former.  
> > > That means, at the very least, returning from a function with unknown 
> > > call sites or calling a function with an unknown implementation.  We 
> > > could potentially eliminate extra truncations here when we fully 
> > > understand a call; for example, we could change the return type to 
> > > `float` when the function is internal to a TU and not address-taken, or 
> > > we could eliminate a trunc+extend pair after inlining.  It is fair to ask 
> > > whether that's a good idea, however.
> > > 
> > > Anyway, concretely we're talking about two ABIs here:
> > > - On x86_64, `_Float16` and `float` are not returned compatibly: they're 
> > > both returned in `xmm0`, but the bit patterns are different, and the 
> > > caller and callee must agree in order to preserve the value.
> > > - On i386, `_Float16` and `float` *are* returned compatibly: they're both 
> > > returned in `%st0`, promoted to the 80-bit format.
> > > 
> > > Let's assume for a second that we're interested in avoiding truncations 
> > > in situations where the ABI doesn't limit us.  Then we have a question of 
> > > language semantics, which is principally about this: does C's 
> > > authorization of excess precision in intermediate results allows return 
> > > values to propagate the excess precision?  The answer that appears to be 
> > > yes, it does, per the explicit footnote at the end of the standard's 
> > > description of the `return` statement:
> > > 
> > > > The return statement is not an assignment. The overlap restriction of 
> > > > 6.5.16.1 does not apply to the case of function return. The 
> > > > representation of floating-point values can have wider range or 
> > > > precision than implied by the type; a cast can be used to remove this 
> > > > extra range and precision.
> > > 
> > > Okay.  So the third question is about implementation: how should we take 
> > > advantage of this flexibility, assuming we actually want to?  A major 
> > > part of the reason we're doing explicit promoted emission in the frontend 
> > > in this patch is that only the frontend has the required knowledge of 
> > > when to force truncation; and a big part of *that* is that explicit casts 
> > > and assignments both force truncation, and neither has a persistent 
> > > semantic representation in LLVM IR.  We cannot distinguish between a 
> > > truncation that was only done to satisfy the ABI and a truncation that 
> > > was required by the language semantics.  Once we have a value as an 
> > > `fp16` in IR, it's entirely possible that it underwent an operation that 
> > > required excess precision to be discarded, one which no longer has any 
> > > representation in IR.  I think the only reasonable way to avoid this 
> > > would be to allow functions to directly return `float` (and receive 
> > > `float`s as returns) with some sort of annotation that it actually has to 
> > > be returned as an `fp16` to satisfy the ABI.  And within Clang, we would 
> > > handle that by making the call/retu

[PATCH] D132451: [docs] Add examples for printing asynchronous stack for coroutines

2022-08-23 Thread Adrian Vogelsgesang via Phabricator via cfe-commits
avogelsgesang accepted this revision.
avogelsgesang added a comment.
This revision is now accepted and ready to land.

LGTM, thanks!

I guess I will update this documentation with LLDB examples, as soon as 
https://reviews.llvm.org/D132415 and a couple of follow-up improvements landed.
As soon as that happened, we will also have LLDB covered here. I see no problem 
with covering mostly gdb for the time being, given that lldb debugging is 
currently subject to change, anyway


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

https://reviews.llvm.org/D132451

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


[PATCH] D132451: [docs] Add examples for printing asynchronous stack for coroutines

2022-08-23 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

In D132451#3742064 , @avogelsgesang 
wrote:

> LGTM, thanks!
>
> I guess I will update this documentation with LLDB examples, as soon as 
> https://reviews.llvm.org/D132415 and a couple of follow-up improvements 
> landed.
> As soon as that happened, we will also have LLDB covered here. I see no 
> problem with covering mostly gdb for the time being, given that lldb 
> debugging is currently subject to change, anyway

Got it. I feel better to add LLDB support too : )


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

https://reviews.llvm.org/D132451

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


[clang] 4332b04 - [docs] Add examples for printing asynchronous stack for coroutines

2022-08-23 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2022-08-23T17:37:12+08:00
New Revision: 4332b049edf6ccf98c9e31dcc983760a89f01d40

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

LOG: [docs] Add examples for printing asynchronous stack for coroutines

Previously when I wrote this document, I felt the completed scripts was
lengthy, redundant and not easy to read. So I didn't add complete
examples in the previous commit.

However, in the recent discussion with @avogelsgesang, I found people
may not know how to use debugging scripts to improve their debugging
efficiency. So now, I feel like it is helpful to put the examples even
if they are a little bit long.

Test Plan: make docs-clang-html

Reviewed By: avogelsgesang

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

Added: 


Modified: 
clang/docs/DebuggingCoroutines.rst

Removed: 




diff  --git a/clang/docs/DebuggingCoroutines.rst 
b/clang/docs/DebuggingCoroutines.rst
index 828822f52bd61..ae5359117775b 100644
--- a/clang/docs/DebuggingCoroutines.rst
+++ b/clang/docs/DebuggingCoroutines.rst
@@ -368,6 +368,345 @@ contains the corresponding continuation (which itself is 
a coroutine with a
 
 This logic should be quite easily captured in a debugger script.
 
+Examples to print asynchronous stack
+
+
+Here is an example to print the asynchronous stack for the normal task 
implementation.
+
+.. code-block:: c++
+
+  // debugging-example.cpp
+  #include 
+  #include 
+  #include 
+
+  struct task {
+struct promise_type {
+  task get_return_object();
+  std::suspend_always initial_suspend() { return {}; }
+  
+  void unhandled_exception() noexcept {}
+
+  struct FinalSuspend {
+std::coroutine_handle<> continuation;
+auto await_ready() noexcept { return false; }
+auto await_suspend(std::coroutine_handle<> handle) noexcept {
+  return continuation;
+}
+void await_resume() noexcept {}
+  };
+  FinalSuspend final_suspend() noexcept { return {continuation}; }
+
+  void return_value(int res) { result = res; }
+
+  std::coroutine_handle<> continuation = std::noop_coroutine();
+  int result = 0;
+};
+
+task(std::coroutine_handle handle) : handle(handle) {}
+~task() {
+  if (handle)
+handle.destroy();
+}
+
+auto operator co_await() {
+  struct Awaiter {
+std::coroutine_handle handle;
+auto await_ready() { return false; }
+auto await_suspend(std::coroutine_handle<> continuation) {
+  handle.promise().continuation = continuation;
+  return handle;
+}
+int await_resume() {
+  int ret = handle.promise().result;
+  handle.destroy();
+  return ret;
+}
+  };
+  return Awaiter{std::exchange(handle, nullptr)};
+}
+
+int syncStart() {
+  handle.resume();
+  return handle.promise().result;
+}
+
+  private:
+std::coroutine_handle handle;
+  };
+
+  task task::promise_type::get_return_object() {
+return std::coroutine_handle::from_promise(*this);
+  }
+
+  namespace detail {
+  template 
+  task chain_fn() {
+co_return N + co_await chain_fn();
+  }
+
+  template <>
+  task chain_fn<0>() {
+// This is the default breakpoint.
+__builtin_debugtrap();
+co_return 0;
+  }
+  }  // namespace detail
+
+  task chain() {
+co_return co_await detail::chain_fn<30>();
+  }
+
+  int main() {
+std::cout << chain().syncStart() << "\n";
+return 0;
+  }
+
+In the example, the ``task`` coroutine holds a ``continuation`` field,
+which would be resumed once the ``task`` completes.
+In another word, the ``continuation`` is the asynchronous caller for the 
``task``.
+Just like the normal function returns to its caller when the function 
completes.
+
+So we can use the ``continuation`` field to construct the asynchronous stack:
+
+.. code-block:: python
+
+  # debugging-helper.py
+  import gdb
+  from gdb.FrameDecorator import FrameDecorator
+
+  class SymValueWrapper():
+  def __init__(self, symbol, value):
+  self.sym = symbol
+  self.val = value
+
+  def __str__(self):
+  return str(self.sym) + " = " + str(self.val)
+
+  def get_long_pointer_size():
+  return gdb.lookup_type('long').pointer().sizeof
+
+  def cast_addr2long_pointer(addr):
+  return gdb.Value(addr).cast(gdb.lookup_type('long').pointer())
+
+  def dereference(addr):
+  return long(cast_addr2long_pointer(addr).dereference())
+
+  class CoroutineFrame(object):
+  def __init__(self, task_addr):
+  self.frame_addr = task_addr
+  self.resume_addr = task_addr
+  self.destroy_addr = task_addr + get_long_pointer_size()
+  self.promise_addr = task

[PATCH] D132451: [docs] Add examples for printing asynchronous stack for coroutines

2022-08-23 Thread Chuanqi Xu 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 rG4332b049edf6: [docs] Add examples for printing asynchronous 
stack for coroutines (authored by ChuanqiXu).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132451

Files:
  clang/docs/DebuggingCoroutines.rst

Index: clang/docs/DebuggingCoroutines.rst
===
--- clang/docs/DebuggingCoroutines.rst
+++ clang/docs/DebuggingCoroutines.rst
@@ -368,6 +368,345 @@
 
 This logic should be quite easily captured in a debugger script.
 
+Examples to print asynchronous stack
+
+
+Here is an example to print the asynchronous stack for the normal task implementation.
+
+.. code-block:: c++
+
+  // debugging-example.cpp
+  #include 
+  #include 
+  #include 
+
+  struct task {
+struct promise_type {
+  task get_return_object();
+  std::suspend_always initial_suspend() { return {}; }
+  
+  void unhandled_exception() noexcept {}
+
+  struct FinalSuspend {
+std::coroutine_handle<> continuation;
+auto await_ready() noexcept { return false; }
+auto await_suspend(std::coroutine_handle<> handle) noexcept {
+  return continuation;
+}
+void await_resume() noexcept {}
+  };
+  FinalSuspend final_suspend() noexcept { return {continuation}; }
+
+  void return_value(int res) { result = res; }
+
+  std::coroutine_handle<> continuation = std::noop_coroutine();
+  int result = 0;
+};
+
+task(std::coroutine_handle handle) : handle(handle) {}
+~task() {
+  if (handle)
+handle.destroy();
+}
+
+auto operator co_await() {
+  struct Awaiter {
+std::coroutine_handle handle;
+auto await_ready() { return false; }
+auto await_suspend(std::coroutine_handle<> continuation) {
+  handle.promise().continuation = continuation;
+  return handle;
+}
+int await_resume() {
+  int ret = handle.promise().result;
+  handle.destroy();
+  return ret;
+}
+  };
+  return Awaiter{std::exchange(handle, nullptr)};
+}
+
+int syncStart() {
+  handle.resume();
+  return handle.promise().result;
+}
+
+  private:
+std::coroutine_handle handle;
+  };
+
+  task task::promise_type::get_return_object() {
+return std::coroutine_handle::from_promise(*this);
+  }
+
+  namespace detail {
+  template 
+  task chain_fn() {
+co_return N + co_await chain_fn();
+  }
+
+  template <>
+  task chain_fn<0>() {
+// This is the default breakpoint.
+__builtin_debugtrap();
+co_return 0;
+  }
+  }  // namespace detail
+
+  task chain() {
+co_return co_await detail::chain_fn<30>();
+  }
+
+  int main() {
+std::cout << chain().syncStart() << "\n";
+return 0;
+  }
+
+In the example, the ``task`` coroutine holds a ``continuation`` field,
+which would be resumed once the ``task`` completes.
+In another word, the ``continuation`` is the asynchronous caller for the ``task``.
+Just like the normal function returns to its caller when the function completes.
+
+So we can use the ``continuation`` field to construct the asynchronous stack:
+
+.. code-block:: python
+
+  # debugging-helper.py
+  import gdb
+  from gdb.FrameDecorator import FrameDecorator
+
+  class SymValueWrapper():
+  def __init__(self, symbol, value):
+  self.sym = symbol
+  self.val = value
+
+  def __str__(self):
+  return str(self.sym) + " = " + str(self.val)
+
+  def get_long_pointer_size():
+  return gdb.lookup_type('long').pointer().sizeof
+
+  def cast_addr2long_pointer(addr):
+  return gdb.Value(addr).cast(gdb.lookup_type('long').pointer())
+
+  def dereference(addr):
+  return long(cast_addr2long_pointer(addr).dereference())
+
+  class CoroutineFrame(object):
+  def __init__(self, task_addr):
+  self.frame_addr = task_addr
+  self.resume_addr = task_addr
+  self.destroy_addr = task_addr + get_long_pointer_size()
+  self.promise_addr = task_addr + get_long_pointer_size() * 2
+  # In the example, the continuation is the first field member of the promise_type.
+  # So they have the same addresses.
+  # If we want to generalize the scripts to other coroutine types, we need to be sure
+  # the continuation field is the first memeber of promise_type.
+  self.continuation_addr = self.promise_addr
+
+  def next_task_addr(self):
+  return dereference(self.continuation_addr)
+
+  class CoroutineFrameDecorator(FrameDecorator):
+  def __init__(self, coro_frame):
+  super(CoroutineFrameDecorator, self).__init__(None)
+  self.coro_frame = coro_frame
+  self.resume_func = dereference(sel

Re: [clang] acaf6b9 - [NFC] Add [[maybe_unused]] to avoid warning in gcc9

2022-08-23 Thread chuanqi.xcq via cfe-commits
Hi David,
 This is the reproduce link from godbolt: https://godbolt.org/z/nEc7WYKnq. It 
is weird that it requries `-Wunused-but-set-parameter` instead of 
`-Wunused-parameter`. The bug exists in all versions of GCC9. And it gets fixed 
in GCC10 and later. Personally, I feel it looks better to suppress the warning 
for GCC9.
Thanks,
Chuanqi
--
From:David Blaikie 
Send Time:2022年8月23日(星期二) 07:22
To:Chuanqi Xu ; Chuanqi Xu 
Cc:cfe-commits 
Subject:Re: [clang] acaf6b9 - [NFC] Add [[maybe_unused]] to avoid warning in 
gcc9
Seems like a bug in the GCC9 warning - any chance we can disable it?
(is it fixed in later versions of GCC?)
I can't seem to reproduce this with godbolt at least with basic
examples - it'd be good to know how bad the thing is we're working
around so we know if we want to keep working around it, or suppress
the warning for certainly compiler versions entirely.
On Thu, Aug 18, 2022 at 11:43 PM Chuanqi Xu via cfe-commits
 wrote:
>
>
> Author: Chuanqi Xu
> Date: 2022-08-19T14:43:22+08:00
> New Revision: acaf6b9dc07de3c12c8a1a55fd8674bca547a917
>
> URL: 
> https://github.com/llvm/llvm-project/commit/acaf6b9dc07de3c12c8a1a55fd8674bca547a917
> DIFF: 
> https://github.com/llvm/llvm-project/commit/acaf6b9dc07de3c12c8a1a55fd8674bca547a917.diff
>
> LOG: [NFC] Add [[maybe_unused]] to avoid warning in gcc9
>
> GCC9 may issue warning for the 'unused' parameters in if constexpr.
> This commit try to fix it by adding the [[maybe_unused]] attribute.
>
> Added:
>
>
> Modified:
> clang/include/clang/AST/RecursiveASTVisitor.h
>
> Removed:
>
>
>
> 
> diff --git a/clang/include/clang/AST/RecursiveASTVisitor.h 
> b/clang/include/clang/AST/RecursiveASTVisitor.h
> index 91baad51b26e..bd7fadb87c5f 100644
> --- a/clang/include/clang/AST/RecursiveASTVisitor.h
> +++ b/clang/include/clang/AST/RecursiveASTVisitor.h
> @@ -73,7 +73,8 @@ struct has_same_member_pointer_type (U::*)(P...)>
> /// are pointers to the same non-static member function.
> template 
> LLVM_ATTRIBUTE_ALWAYS_INLINE LLVM_ATTRIBUTE_NODEBUG auto
> -isSameMethod(FirstMethodPtrTy FirstMethodPtr, SecondMethodPtrTy 
> SecondMethodPtr)
> +isSameMethod([[maybe_unused]] FirstMethodPtrTy FirstMethodPtr,
> + [[maybe_unused]] SecondMethodPtrTy SecondMethodPtr)
> -> bool {
> if constexpr (has_same_member_pointer_type SecondMethodPtrTy>::value)
>
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132444: [clang] Allow using -rtlib=platform to switching to the default rtlib on all targets

2022-08-23 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Do we have precedent for "platform" for this? For fuse-ld=, one is supposed to 
use `-fuse-ld=` (without anything after the `=`) to get the default ld. That's 
not great (...but it can't collide with actual linker names, i suppose).

Using "platform" (or any other self-descriptive name) for this seems easier to 
understand than passing an empty value. But it'd be nice if we could use this 
consistently in our various flags.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132444

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


[PATCH] D132461: [clang-tidy] Add cppcoreguidelines-avoid-do-while check

2022-08-23 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp created this revision.
Herald added subscribers: shchenz, kbarton, xazax.hun, mgorny, nemanjai.
Herald added a project: All.
carlosgalvezp requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Implements rule ES.75 of C++ Core Guidelines.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132461

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidDoWhileCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidDoWhileCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/CMakeLists.txt
  clang-tools-extra/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-do-while.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-do-while.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-do-while.cpp
@@ -0,0 +1,70 @@
+// RUN: %check_clang_tidy -check-suffixes=DEFAULT   %s cppcoreguidelines-avoid-do-while %t
+// RUN: %check_clang_tidy -check-suffixes=ALLOW-WHILE-FALSE %s cppcoreguidelines-avoid-do-while %t -- -config='{CheckOptions: [{key: cppcoreguidelines-avoid-do-while.AllowWhileFalse, value: true}]}'
+
+#define FOO(x) \
+  do { \
+  } while (x != 0)
+
+#define BAR_0(x) \
+  do { \
+bar(x); \
+  } while (0)
+
+#define BAR_FALSE(x) \
+  do { \
+bar(x); \
+  } while (false)
+
+void bar(int);
+int baz();
+
+void foo()
+{
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used [cppcoreguidelines-avoid-do-while]
+do {
+
+} while(0);
+
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used [cppcoreguidelines-avoid-do-while]
+do {
+
+} while(false);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+3]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+int x1{0};
+do {
+  x1 = baz();
+} while (x1 > 0);
+
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+do {
+
+} while (x1 != 0);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+3]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+constexpr int x2{0};
+do {
+
+} while (x2);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+3]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+constexpr bool x3{false};
+do {
+
+} while (x3);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+FOO(x1);
+
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+BAR_0(x1);
+
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+BAR_FALSE(x1);
+}
Index: clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst
@@ -0,0 +1,39 @@
+.. title:: clang-tidy - cppcoreguidelines-avoid-do-while
+
+cppcoreguidelines-avoid-do-while
+
+
+This check warns when using ``do-while`` loops. They are less readable than
+plain ``while`` loops since the termination condition is at the end and the
+condition is not checked prior to the first iteration. This can lead to subtle
+bugs.
+
+Examples:
+
+.. code-block:: c++
+
+  int x;
+  do {
+  std::cin >> x;
+  // ...
+  } while (x < 0);
+
+The check implements
+`rule ES.75 of C++ Core Guidelines `_.
+
+Options
+---
+
+.. option:: AllowWhileFalse
+
+  Allows having ``do-while`` loops where the condition is a literal ``false``
+  or ``0``. This covers the typical use case of safety defining function-like
+  macros:
+
+  .. code-block:: c++
+
+#define FOO_BAR(x) \
+do { \
+  foo(x); \
+  bar(x); \
+} while(0)
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -104,6 +104,11 @@
 
   Warns when a struct or class uses const or reference (lvalue or rvalue) data members.
 
+- New :doc:`cppcoreg

[PATCH] D132444: [clang] Allow using -rtlib=platform to switching to the default rtlib on all targets

2022-08-23 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

In D132444#3742295 , @thakis wrote:

> Do we have precedent for "platform" for this? For fuse-ld=, one is supposed 
> to use `-fuse-ld=` (without anything after the `=`) to get the default ld. 
> That's not great (...but it can't collide with actual linker names, i 
> suppose).
>
> Using "platform" (or any other self-descriptive name) for this seems easier 
> to understand than passing an empty value. But it'd be nice if we could use 
> this consistently in our various flags.

Yes, `"platform"` is an existing option handled in a bunch of places already - 
see e.g. 
https://github.com/llvm/llvm-project/blob/main/clang/lib/Driver/ToolChain.cpp#L832-L838.
 It's just that these cases hadn't been updated to take it into account.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132444

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


[PATCH] D132461: [clang-tidy] Add cppcoreguidelines-avoid-do-while check

2022-08-23 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp updated this revision to Diff 454786.
carlosgalvezp added a comment.

Fix typo


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132461

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidDoWhileCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidDoWhileCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/CMakeLists.txt
  clang-tools-extra/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-do-while.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-do-while.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-do-while.cpp
@@ -0,0 +1,70 @@
+// RUN: %check_clang_tidy -check-suffixes=DEFAULT   %s cppcoreguidelines-avoid-do-while %t
+// RUN: %check_clang_tidy -check-suffixes=ALLOW-WHILE-FALSE %s cppcoreguidelines-avoid-do-while %t -- -config='{CheckOptions: [{key: cppcoreguidelines-avoid-do-while.AllowWhileFalse, value: true}]}'
+
+#define FOO(x) \
+  do { \
+  } while (x != 0)
+
+#define BAR_0(x) \
+  do { \
+bar(x); \
+  } while (0)
+
+#define BAR_FALSE(x) \
+  do { \
+bar(x); \
+  } while (false)
+
+void bar(int);
+int baz();
+
+void foo()
+{
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used [cppcoreguidelines-avoid-do-while]
+do {
+
+} while(0);
+
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used [cppcoreguidelines-avoid-do-while]
+do {
+
+} while(false);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+3]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+int x1{0};
+do {
+  x1 = baz();
+} while (x1 > 0);
+
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+do {
+
+} while (x1 != 0);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+3]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+constexpr int x2{0};
+do {
+
+} while (x2);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+3]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+constexpr bool x3{false};
+do {
+
+} while (x3);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+FOO(x1);
+
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+BAR_0(x1);
+
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+BAR_FALSE(x1);
+}
Index: clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst
@@ -0,0 +1,39 @@
+.. title:: clang-tidy - cppcoreguidelines-avoid-do-while
+
+cppcoreguidelines-avoid-do-while
+
+
+This check warns when using ``do-while`` loops. They are less readable than
+plain ``while`` loops since the termination condition is at the end and the
+condition is not checked prior to the first iteration. This can lead to subtle
+bugs.
+
+Examples:
+
+.. code-block:: c++
+
+  int x;
+  do {
+  std::cin >> x;
+  // ...
+  } while (x < 0);
+
+The check implements
+`rule ES.75 of C++ Core Guidelines `_.
+
+Options
+---
+
+.. option:: AllowWhileFalse
+
+  Allows having ``do-while`` loops where the condition is a literal ``false``
+  or ``0``. This covers the typical use case of safety defining function-like
+  macros:
+
+  .. code-block:: c++
+
+#define FOO_BAR(x) \
+do { \
+  foo(x); \
+  bar(x); \
+} while(0)
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -104,6 +104,11 @@
 
   Warns when a struct or class uses const or reference (lvalue or rvalue) data members.
 
+- New :doc:`cppcoreguidelines-avoid-do-while
+  ` check.
+
+  Warns when using a ``do-while`` loop.
+
 New check aliases
 ^
 
@@ -120,7 +125,7 @@
   ` check. Part

[PATCH] D132461: [clang-tidy] Add cppcoreguidelines-avoid-do-while check

2022-08-23 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp updated this revision to Diff 454787.
carlosgalvezp added a comment.

Document default value


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132461

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidDoWhileCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidDoWhileCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/CMakeLists.txt
  clang-tools-extra/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-do-while.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-do-while.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-do-while.cpp
@@ -0,0 +1,70 @@
+// RUN: %check_clang_tidy -check-suffixes=DEFAULT   %s cppcoreguidelines-avoid-do-while %t
+// RUN: %check_clang_tidy -check-suffixes=ALLOW-WHILE-FALSE %s cppcoreguidelines-avoid-do-while %t -- -config='{CheckOptions: [{key: cppcoreguidelines-avoid-do-while.AllowWhileFalse, value: true}]}'
+
+#define FOO(x) \
+  do { \
+  } while (x != 0)
+
+#define BAR_0(x) \
+  do { \
+bar(x); \
+  } while (0)
+
+#define BAR_FALSE(x) \
+  do { \
+bar(x); \
+  } while (false)
+
+void bar(int);
+int baz();
+
+void foo()
+{
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used [cppcoreguidelines-avoid-do-while]
+do {
+
+} while(0);
+
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used [cppcoreguidelines-avoid-do-while]
+do {
+
+} while(false);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+3]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+int x1{0};
+do {
+  x1 = baz();
+} while (x1 > 0);
+
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+do {
+
+} while (x1 != 0);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+3]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+constexpr int x2{0};
+do {
+
+} while (x2);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+3]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+constexpr bool x3{false};
+do {
+
+} while (x3);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+FOO(x1);
+
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+BAR_0(x1);
+
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+BAR_FALSE(x1);
+}
Index: clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst
@@ -0,0 +1,41 @@
+.. title:: clang-tidy - cppcoreguidelines-avoid-do-while
+
+cppcoreguidelines-avoid-do-while
+
+
+This check warns when using ``do-while`` loops. They are less readable than
+plain ``while`` loops since the termination condition is at the end and the
+condition is not checked prior to the first iteration. This can lead to subtle
+bugs.
+
+Examples:
+
+.. code-block:: c++
+
+  int x;
+  do {
+  std::cin >> x;
+  // ...
+  } while (x < 0);
+
+The check implements
+`rule ES.75 of C++ Core Guidelines `_.
+
+Options
+---
+
+.. option:: AllowWhileFalse
+
+  Allows having ``do-while`` loops where the condition is a literal ``false``
+  or ``0``. This covers the typical use case of safety defining function-like
+  macros:
+
+  .. code-block:: c++
+
+#define FOO_BAR(x) \
+do { \
+  foo(x); \
+  bar(x); \
+} while(0)
+
+  Defaults to ``false``.
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -104,6 +104,11 @@
 
   Warns when a struct or class uses const or reference (lvalue or rvalue) data members.
 
+- New :doc:`cppcoreguidelines-avoid-do-while
+  ` check.
+
+  Warns when using a ``do-while`` loop.
+
 New check aliases
 ^^

[PATCH] D132444: [clang] Allow using -rtlib=platform to switching to the default rtlib on all targets

2022-08-23 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

In D132444#3742305 , @mstorsjo wrote:

> In D132444#3742295 , @thakis wrote:
>
>> Do we have precedent for "platform" for this? For fuse-ld=, one is supposed 
>> to use `-fuse-ld=` (without anything after the `=`) to get the default ld. 
>> That's not great (...but it can't collide with actual linker names, i 
>> suppose).
>>
>> Using "platform" (or any other self-descriptive name) for this seems easier 
>> to understand than passing an empty value. But it'd be nice if we could use 
>> this consistently in our various flags.
>
> Yes, `"platform"` is an existing option handled in a bunch of places already 
> - see e.g. 
> https://github.com/llvm/llvm-project/blob/main/clang/lib/Driver/ToolChain.cpp#L832-L838.
>  It's just that these cases hadn't been updated to take it into account.

Then again, the quoted code comment says that `"platform"` only is meant to be 
used for overriding `CLANG_DEFAULT_RTLIB` in tests, but I don't see why one 
can't use it for overriding `CLANG_DEFAULT_RTLIB` (or an earlier `-rtlib` 
option on the command line) in real world uses too. (I had a user wanting to 
use my builds of clang for MSVC use cases, where it failed due to my Clang 
defaulting to `-rtlib=compiler-rt`, with no way of overriding it back to 
default, see https://github.com/mstorsjo/llvm-mingw/issues/267)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132444

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


[PATCH] D132461: [clang-tidy] Add cppcoreguidelines-avoid-do-while check

2022-08-23 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp updated this revision to Diff 454789.
carlosgalvezp added a comment.

Add check to list of checks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132461

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidDoWhileCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidDoWhileCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/CMakeLists.txt
  clang-tools-extra/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-do-while.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-do-while.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-do-while.cpp
@@ -0,0 +1,70 @@
+// RUN: %check_clang_tidy -check-suffixes=DEFAULT   %s cppcoreguidelines-avoid-do-while %t
+// RUN: %check_clang_tidy -check-suffixes=ALLOW-WHILE-FALSE %s cppcoreguidelines-avoid-do-while %t -- -config='{CheckOptions: [{key: cppcoreguidelines-avoid-do-while.AllowWhileFalse, value: true}]}'
+
+#define FOO(x) \
+  do { \
+  } while (x != 0)
+
+#define BAR_0(x) \
+  do { \
+bar(x); \
+  } while (0)
+
+#define BAR_FALSE(x) \
+  do { \
+bar(x); \
+  } while (false)
+
+void bar(int);
+int baz();
+
+void foo()
+{
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used [cppcoreguidelines-avoid-do-while]
+do {
+
+} while(0);
+
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used [cppcoreguidelines-avoid-do-while]
+do {
+
+} while(false);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+3]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+int x1{0};
+do {
+  x1 = baz();
+} while (x1 > 0);
+
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+do {
+
+} while (x1 != 0);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+3]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+constexpr int x2{0};
+do {
+
+} while (x2);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+3]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+constexpr bool x3{false};
+do {
+
+} while (x3);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+FOO(x1);
+
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+BAR_0(x1);
+
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+BAR_FALSE(x1);
+}
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -177,6 +177,7 @@
`concurrency-mt-unsafe `_,
`concurrency-thread-canceltype-asynchronous `_,
`cppcoreguidelines-avoid-const-or-ref-data-members `_,
+   `cppcoreguidelines-avoid-do-while `_,
`cppcoreguidelines-avoid-goto `_,
`cppcoreguidelines-avoid-non-const-global-variables `_,
`cppcoreguidelines-init-variables `_, "Yes"
Index: clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst
@@ -0,0 +1,41 @@
+.. title:: clang-tidy - cppcoreguidelines-avoid-do-while
+
+cppcoreguidelines-avoid-do-while
+
+
+This check warns when using ``do-while`` loops. They are less readable than
+plain ``while`` loops since the termination condition is at the end and the
+condition is not checked prior to the first iteration. This can lead to subtle
+bugs.
+
+Examples:
+
+.. code-block:: c++
+
+  int x;
+  do {
+  std::cin >> x;
+  // ...
+  } while (x < 0);
+
+The check implements
+`rule ES.75 of C++ Core Guidelines `_.
+
+Options
+---
+
+.. option:: AllowWhileFalse
+
+  Allows having ``do-while`` loops where the condition is a literal ``false``
+  or ``0``. This covers the typical use case 

[PATCH] D132461: [clang-tidy] Add cppcoreguidelines-avoid-do-while check

2022-08-23 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp updated this revision to Diff 454793.
carlosgalvezp added a comment.

Fix typo


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132461

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidDoWhileCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidDoWhileCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/CMakeLists.txt
  clang-tools-extra/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-do-while.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-do-while.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-do-while.cpp
@@ -0,0 +1,70 @@
+// RUN: %check_clang_tidy -check-suffixes=DEFAULT   %s cppcoreguidelines-avoid-do-while %t
+// RUN: %check_clang_tidy -check-suffixes=ALLOW-WHILE-FALSE %s cppcoreguidelines-avoid-do-while %t -- -config='{CheckOptions: [{key: cppcoreguidelines-avoid-do-while.AllowWhileFalse, value: true}]}'
+
+#define FOO(x) \
+  do { \
+  } while (x != 0)
+
+#define BAR_0(x) \
+  do { \
+bar(x); \
+  } while (0)
+
+#define BAR_FALSE(x) \
+  do { \
+bar(x); \
+  } while (false)
+
+void bar(int);
+int baz();
+
+void foo()
+{
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used [cppcoreguidelines-avoid-do-while]
+do {
+
+} while(0);
+
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used [cppcoreguidelines-avoid-do-while]
+do {
+
+} while(false);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+3]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+int x1{0};
+do {
+  x1 = baz();
+} while (x1 > 0);
+
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+do {
+
+} while (x1 != 0);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+3]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+constexpr int x2{0};
+do {
+
+} while (x2);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+3]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+constexpr bool x3{false};
+do {
+
+} while (x3);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+FOO(x1);
+
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+BAR_0(x1);
+
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+BAR_FALSE(x1);
+}
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -177,6 +177,7 @@
`concurrency-mt-unsafe `_,
`concurrency-thread-canceltype-asynchronous `_,
`cppcoreguidelines-avoid-const-or-ref-data-members `_,
+   `cppcoreguidelines-avoid-do-while `_,
`cppcoreguidelines-avoid-goto `_,
`cppcoreguidelines-avoid-non-const-global-variables `_,
`cppcoreguidelines-init-variables `_, "Yes"
Index: clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst
@@ -0,0 +1,41 @@
+.. title:: clang-tidy - cppcoreguidelines-avoid-do-while
+
+cppcoreguidelines-avoid-do-while
+
+
+This check warns when using ``do-while`` loops. They are less readable than
+plain ``while`` loops since the termination condition is at the end and the
+condition is not checked prior to the first iteration. This can lead to subtle
+bugs.
+
+Examples:
+
+.. code-block:: c++
+
+  int x;
+  do {
+  std::cin >> x;
+  // ...
+  } while (x < 0);
+
+The check implements
+`rule ES.75 of C++ Core Guidelines `_.
+
+Options
+---
+
+.. option:: AllowWhileFalse
+
+  Allows having ``do-while`` loops where the condition is a literal ``false``
+  or ``0``. This covers the typical use case of safely defining f

[PATCH] D132302: [clang] Add support for __attribute__((guard(nocf)))

2022-08-23 Thread Alvin Wong via Phabricator via cfe-commits
alvinhochun updated this revision to Diff 454798.
alvinhochun marked an inline comment as done.
alvinhochun added a comment.

Rebased and added a release note entry. @mstorsjo would you mind landing this 
for me? Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132302

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Attr.td
  clang/test/CodeGen/guard_nocf.c
  clang/test/CodeGenCXX/guard_nocf.cpp
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/test/Sema/attr-guard_nocf.c

Index: clang/test/Sema/attr-guard_nocf.c
===
--- clang/test/Sema/attr-guard_nocf.c
+++ clang/test/Sema/attr-guard_nocf.c
@@ -1,10 +1,20 @@
 // RUN: %clang_cc1 -triple %ms_abi_triple -fms-extensions -verify -fsyntax-only %s
 // RUN: %clang_cc1 -triple %ms_abi_triple -fms-extensions -verify -std=c++11 -fsyntax-only -x c++ %s
+// RUN: %clang_cc1 -triple x86_64-w64-windows-gnu -verify -fsyntax-only %s
+// RUN: %clang_cc1 -triple x86_64-w64-windows-gnu -verify -std=c++11 -fsyntax-only -x c++ %s
+
+// The x86_64-w64-windows-gnu version tests mingw target, which relies on
+// __declspec(...) being defined as __attribute__((...)) by compiler built-in.
 
 // Function definition.
 __declspec(guard(nocf)) void testGuardNoCF(void) { // no warning
 }
 
+// Function definition using GNU-style attribute without relying on the
+// __declspec define for mingw.
+__attribute__((guard(nocf))) void testGNUStyleGuardNoCF(void) { // no warning
+}
+
 // Can not be used on variable, parameter, or function pointer declarations.
 int __declspec(guard(nocf)) i;  // expected-warning {{'guard' attribute only applies to functions}}
 void testGuardNoCFFuncParam(double __declspec(guard(nocf)) i) {}// expected-warning {{'guard' attribute only applies to functions}}
Index: clang/test/Misc/pragma-attribute-supported-attributes-list.test
===
--- clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -26,6 +26,7 @@
 // CHECK-NEXT: BuiltinAlias (SubjectMatchRule_function)
 // CHECK-NEXT: CFAuditedTransfer (SubjectMatchRule_function)
 // CHECK-NEXT: CFConsumed (SubjectMatchRule_variable_is_parameter)
+// CHECK-NEXT: CFGuard (SubjectMatchRule_function)
 // CHECK-NEXT: CFICanonicalJumpTable (SubjectMatchRule_function)
 // CHECK-NEXT: CFUnknownTransfer (SubjectMatchRule_function)
 // CHECK-NEXT: CPUDispatch (SubjectMatchRule_function)
Index: clang/test/CodeGenCXX/guard_nocf.cpp
===
--- clang/test/CodeGenCXX/guard_nocf.cpp
+++ clang/test/CodeGenCXX/guard_nocf.cpp
@@ -1,4 +1,8 @@
 // RUN: %clang_cc1 -triple %ms_abi_triple -fms-extensions -std=c++11 -emit-llvm -O2 -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-w64-windows-gnu -std=c++11 -emit-llvm -O2 -o - %s | FileCheck %s
+
+// The x86_64-w64-windows-gnu version tests mingw target, which relies on
+// __declspec(...) being defined as __attribute__((...)) by compiler built-in.
 
 void target_func();
 void (*func_ptr)() = &target_func;
@@ -10,6 +14,23 @@
 // CHECK-LABEL: nocf0
 // CHECK: call{{.*}}[[NOCF:#[0-9]+]]
 
+// Explicitly test using the GNU-style attribute without relying on the
+// __declspec define for mingw.
+// The "guard_nocf" attribute must be added.
+__attribute__((guard(nocf))) void nocf0_gnu_style() {
+  (*func_ptr)();
+}
+// CHECK-LABEL: nocf0_gnu_style
+// CHECK: call{{.*}}[[NOCF:#[0-9]+]]
+
+// Test using the c++-style attribute.
+// The "guard_nocf" attribute must be added.
+[[clang::guard(nocf)]] void nocf0_cxx_style() {
+  (*func_ptr)();
+}
+// CHECK-LABEL: nocf0_cxx_style
+// CHECK: call{{.*}}[[NOCF:#[0-9]+]]
+
 // The "guard_nocf" attribute must *not* be added.
 void cf0() {
   (*func_ptr)();
Index: clang/test/CodeGen/guard_nocf.c
===
--- clang/test/CodeGen/guard_nocf.c
+++ clang/test/CodeGen/guard_nocf.c
@@ -1,4 +1,8 @@
 // RUN: %clang_cc1 -triple %ms_abi_triple -fms-extensions -emit-llvm -O2 -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-w64-windows-gnu -emit-llvm -O2 -o - %s | FileCheck %s
+
+// The x86_64-w64-windows-gnu version tests mingw target, which relies on
+// __declspec(...) being defined as __attribute__((...)) by compiler built-in.
 
 void target_func(void);
 void (*func_ptr)(void) = &target_func;
@@ -10,6 +14,15 @@
 // CHECK-LABEL: nocf0
 // CHECK: call{{.*}}[[NOCF:#[0-9]+]]
 
+// Explicitly test using the GNU-style attribute without relying on the
+// __declspec define for mingw.
+// The "guard_nocf" attribute must be added.
+__attribute__((guard(nocf))) void nocf0_gnu_style(void) {
+  (*func_ptr)();
+}
+// CHECK-LABEL: nocf0_gnu_style
+// CHECK: call{{.*}}[[NOCF:#[0-9

[PATCH] D132324: [RFC] Remove support for building libc++ with `LLVM_ENABLE_PROJECTS`

2022-08-23 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a comment.

Please don't change libc++ things like that without my approval first. This is 
a transition I've been working on for 2+ years, I had a local patch for it 
waiting to be published, and this patch is incomplete in several ways. I 
greatly appreciate the effort and wanting to chime into this transition, 
however concretely this was rushed in.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132324

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


[PATCH] D131979: [clang][UBSan] Fix __builtin_assume_aligned crash

2022-08-23 Thread Wang Yihan via Phabricator via cfe-commits
yihanaa added a comment.

As far as I know, turning on the -fsanitizer=alignment options when calling 
__builtin_assume_aligned in C code, if
the 1st arg has volatile qualifier, Clang will emit "call void 
@__ubsan_handle_alignment_assumption(...)" in CodeGen,
else Clang will emit an warning and ignore "call void 
@__ubsan_handle_alignment_assumption(...)". But the same situation in C++, 
Clang will generate an error in Sema.

So I think, in order to keep this patch consistent with recent version of Clang 
and GCC behavior, when compile C code, Clang
should not directly emit an error and exit in Sema, but should check the 1st 
arg's volatile qualifier in CodeGen and decide 
whether to emit "call void @__ubsan_handle_alignment_assumption(...)".

But, I agree to use other ways to replace use getSubExprAsWritten() in CodeGen 
to check the 1st arg 'isVolatile', what do you all think about?

For more information about UBSan, see 
https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html and search 
'volatile' on this website.

"The null, alignment, object-size, local-bounds, and vptr checks do not apply 
to pointers to types with the volatile qualifier."
C https://godbolt.org/z/xv35fG14r
C++ https://godbolt.org/z/qfje6sErE


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131979

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


[PATCH] D132324: [RFC] Remove support for building libc++ with `LLVM_ENABLE_PROJECTS`

2022-08-23 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D132324#3742394 , @ldionne wrote:

> Please don't change libc++ things like that without my approval first. This 
> is a transition I've been working on for 2+ years, I had a local patch for it 
> waiting to be published, and this patch is incomplete in several ways. I 
> greatly appreciate the effort and wanting to chime into this transition, 
> however concretely this was rushed in.

FWIW, I was also pretty surprised to see something with `[RFC]` in the title be 
proposed on a Saturday night and landed the next morning. While we had 
community agreement on the original deprecation, I think we usually would then 
follow up with an RFC (on Discourse) proposing to remove the deprecated 
functionality so people have more notice before the changes landed. (Just 
something to keep in mind for the future.)

For clarity, @ldionne are you requesting that these changes be reverted due to 
being incomplete, or do you prefer this be fixed forward?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132324

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


[PATCH] D132324: [RFC] Remove support for building libc++ with `LLVM_ENABLE_PROJECTS`

2022-08-23 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a comment.

In D132324#3742406 , @aaron.ballman 
wrote:

> For clarity, @ldionne are you requesting that these changes be reverted due 
> to being incomplete, or do you prefer this be fixed forward?

Sorry, I left no action item on my end after my first comment. I'm wrapping my 
head around this change and the other changes that followed D132298 
 and D132411 
 first, and I'll post here what I think we 
should do. I've also seen some internal fallout of this change and I suspect 
I'm not alone.

Like I said, I greatly appreciate that folks took the lead to push this removal 
forward, however it should have been under review for more than 24h on a 
week-end. Concretely, what I planned on doing was turn the `message(WARNING` 
into `message(ERROR` as a dye test without changing anything else, and then 
turn it back on to `message(WARNING` to give folks a bit of time to fix their 
up/downstream CI systems (to avoid them being red for too long).

I'll post here again when I've wrapped my head around this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132324

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


[PATCH] D131632: [clang] Enable output of SARIF diagnostics

2022-08-23 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Frontend/SARIFDiagnosticPrinter.h:63-65
+  void setSarifWriter(SarifDocumentWriter *SarifWriter) {
+Writer = std::unique_ptr(SarifWriter);
+  }

abrahamcd wrote:
> aaron.ballman wrote:
> > This interface seems dangerous to me -- the caller has no idea that the 
> > pointer will be stashed off as a `unique_ptr` and so the caller might 
> > expect to still be able to use its (now not unique) pointer value.
> Would it be best to store as a regular pointer instead of a unique pointer in 
> this case then?
My preference is to use a `unique_ptr` whenever possible so that ownership 
semantics are clear. So my recommendation is to have the user construct the 
`unique_ptr` and hand it off through this interface with a `move`.



Comment at: clang/lib/Frontend/SARIFDiagnostic.cpp:189
+  // on Windows we can just use llvm::sys::path::remove_dots(), because,
+  // on that system, both aforementioned paths point to the same place.
+#ifdef _WIN32

abrahamcd wrote:
> aaron.ballman wrote:
> > I'm not certain we want a difference in behavior here. For starters, 
> > Windows also has hardlinks and symlinks (they're not exactly the same as on 
> > *nix systems though), so I think the assumption these paths point to the 
> > same place is valid. But also, platform-specific behavior should be 
> > exceedingly rare  in most parts of the compiler. Is there significant harm 
> > in unifying the behavior across platforms?
> There seems to be Windows-specific tests that rely on this behavior, but I'm 
> not too sure what the harm in unifying it would be. There's some discussion 
> on it here: D59415. 
Then let's skip this for now -- if there's something we want to address, we can 
do it in a follow-up.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131632

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


[clang] bf06295 - [OffloadPackager] Add option to extract files from images

2022-08-23 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-08-23T12:57:16Z
New Revision: bf062954364d69e0fb8e3e04ef3a65c432e8bd50

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

LOG: [OffloadPackager] Add option to extract files from images

We use the `clang-offload-packager` too bundle many files into a single
binary format containing metadata. This is used for offloading
compilation which may contain multiple device binaries of different
types and architectures in a single file. We use this special binary
format to store these files along with some necessary metadata around
them. We use this format because of the difficulty of determining the
filesize of the various binary inputs that will be passed to the
offloading toolchain rather than engineering a solution for each input.

Previously we only support packaing many files into a single binary.
This patch adds support for doing the reverse by using the same
`--image=` syntax. To unpackage a binary we now present an input file
instead of an output.

Reviewed By: tra

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

Added: 
clang/test/Driver/offload-packager.c

Modified: 
clang/docs/ClangOffloadPackager.rst
clang/tools/clang-offload-packager/ClangOffloadPackager.cpp

Removed: 




diff  --git a/clang/docs/ClangOffloadPackager.rst 
b/clang/docs/ClangOffloadPackager.rst
index 9b17b5d028d09..295eb48ac0dcb 100644
--- a/clang/docs/ClangOffloadPackager.rst
+++ b/clang/docs/ClangOffloadPackager.rst
@@ -145,8 +145,9 @@ Usage
 =
 
 This tool can be used with the following arguments. Generally information is
-passed as a key-value pair to the ``image=`` argument. The ``file``, 
``triple``,
-and ``arch`` arguments are considered mandatory to make a valid image.
+passed as a key-value pair to the ``image=`` argument. The ``file`` and 
``triple``,
+arguments are considered mandatory to make a valid image. The ``arch`` 
argument 
+is suggested.
 
 .. code-block:: console
 
@@ -179,3 +180,12 @@ single output file with all the images combined.
 .. code-block:: console
 
   clang-offload-packager -o out.bin 
--image=file=input.o,triple=nvptx64,arch=sm_70
+
+The inverse operation can be performed instead by passing the packaged binary 
as 
+input. In this mode the matching images will either be placed in the output 
+specified by the ``file`` option. If no ``file`` argument is provided a name 
+will be generated for each matching image.
+
+.. code-block:: console
+
+  clang-offload-packager in.bin --image=file=output.o,triple=nvptx64,arch=sm_70

diff  --git a/clang/test/Driver/offload-packager.c 
b/clang/test/Driver/offload-packager.c
new file mode 100644
index 0..c4617d06e93d3
--- /dev/null
+++ b/clang/test/Driver/offload-packager.c
@@ -0,0 +1,31 @@
+// REQUIRES: x86-registered-target
+// REQUIRES: nvptx-registered-target
+// REQUIRES: amdgpu-registered-target
+// UNSUPPORTED: system-windows
+
+// Check that we can extract files from the packaged binary.
+// RUN: clang-offload-packager -o %t.out \
+// RUN:   
--image=file=%S/Inputs/dummy-elf.o,kind=openmp,triple=nvptx64-nvidia-cuda,arch=sm_70
 \
+// RUN:   
--image=file=%S/Inputs/dummy-elf.o,kind=openmp,triple=nvptx64-nvidia-cuda,arch=sm_80
 \
+// RUN:   
--image=file=%S/Inputs/dummy-elf.o,kind=openmp,triple=amdgcn-amd-amdhsa,arch=gfx908
 \
+// RUN:   
--image=file=%S/Inputs/dummy-elf.o,kind=openmp,triple=amdgcn-amd-amdhsa,arch=gfx90a
 \
+// RUN:   
--image=file=%S/Inputs/dummy-elf.o,kind=openmp,triple=amdgcn-amd-amdhsa,arch=gfx90c
 
+// RUN: clang-offload-packager %t.out \
+// RUN:   
--image=file=%t-sm_70.o,kind=openmp,triple=nvptx64-nvidia-cuda,arch=sm_70 \
+// RUN:   
--image=file=%t-gfx908.o,kind=openmp,triple=amdgcn-amd-amdhsa,arch=gfx908
+// RUN: 
diff  %t-sm_70.o %S/Inputs/dummy-elf.o
+// RUN: 
diff  %t-gfx908.o %S/Inputs/dummy-elf.o
+
+// Check that we generate a new name if one is not given
+// RUN: clang-offload-packager -o %t \
+// RUN:   
--image=file=%S/Inputs/dummy-elf.o,kind=openmp,triple=nvptx64-nvidia-cuda,arch=sm_70
 \
+// RUN:   
--image=file=%S/Inputs/dummy-elf.o,kind=openmp,triple=nvptx64-nvidia-cuda,arch=sm_80
 \
+// RUN:   
--image=file=%S/Inputs/dummy-elf.o,kind=openmp,triple=amdgcn-amd-amdhsa,arch=gfx908
 \
+// RUN:   
--image=file=%S/Inputs/dummy-elf.o,kind=openmp,triple=amdgcn-amd-amdhsa,arch=gfx90a
 \
+// RUN:   
--image=file=%S/Inputs/dummy-elf.o,kind=hip,triple=amdgcn-amd-amdhsa,arch=gfx90c
 
+// RUN: cd $(dirname "%t") && clang-offload-packager %t --image=kind=openmp
+// RUN: 
diff  *-nvptx64-nvidia-cuda-sm_70.0.o %S/Inputs/dummy-elf.o; rm 
*-nvptx64-nvidia-cuda-sm_70.0.o
+// RUN: 
diff  *-nvptx64-nvidia-cuda-sm_80.1.o %S/Inputs/dummy-elf.o; rm 
*-nvptx64-nvidia-cuda-sm_80.1.o
+// RUN: 
diff  *-amdgcn-amd-amdhsa-gfx908.2.o %S/Inputs/dummy-elf.o; rm 
*-amdgcn

[PATCH] D129507: [OffloadPackager] Add option to extract files from images

2022-08-23 Thread Joseph Huber via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbf062954364d: [OffloadPackager] Add option to extract files 
from images (authored by jhuber6).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129507

Files:
  clang/docs/ClangOffloadPackager.rst
  clang/test/Driver/offload-packager.c
  clang/tools/clang-offload-packager/ClangOffloadPackager.cpp

Index: clang/tools/clang-offload-packager/ClangOffloadPackager.cpp
===
--- clang/tools/clang-offload-packager/ClangOffloadPackager.cpp
+++ clang/tools/clang-offload-packager/ClangOffloadPackager.cpp
@@ -19,6 +19,7 @@
 #include "llvm/Object/OffloadBinary.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FileOutputBuffer.h"
+#include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Signals.h"
@@ -33,11 +34,15 @@
 static cl::OptionCategory
 ClangOffloadPackagerCategory("clang-offload-packager options");
 
-static cl::opt OutputFile("o", cl::Required,
-   cl::desc("Write output to ."),
+static cl::opt OutputFile("o", cl::desc("Write output to ."),
cl::value_desc("file"),
cl::cat(ClangOffloadPackagerCategory));
 
+static cl::opt InputFile(cl::Positional,
+  cl::desc("Extract from ."),
+  cl::value_desc("file"),
+  cl::cat(ClangOffloadPackagerCategory));
+
 static cl::list
 DeviceImages("image",
  cl::desc("List of key and value arguments. Required keywords "
@@ -49,84 +54,192 @@
   OS << clang::getClangToolFullVersion("clang-offload-packager") << '\n';
 }
 
-int main(int argc, const char **argv) {
-  sys::PrintStackTraceOnErrorSignal(argv[0]);
-  cl::HideUnrelatedOptions(ClangOffloadPackagerCategory);
-  cl::SetVersionPrinter(PrintVersion);
-  cl::ParseCommandLineOptions(
-  argc, argv,
-  "A utility for bundling several object files into a single binary.\n"
-  "The output binary can then be embedded into the host section table\n"
-  "to create a fatbinary containing offloading code.\n");
-
-  if (Help) {
-cl::PrintHelpMessage();
-return EXIT_SUCCESS;
+// Get a map containing all the arguments for the image. Repeated arguments will
+// be placed in a comma separated list.
+static DenseMap getImageArguments(StringRef Image,
+StringSaver &Saver) {
+  DenseMap Args;
+  for (StringRef Arg : llvm::split(Image, ",")) {
+auto [Key, Value] = Arg.split("=");
+if (Args.count(Key))
+  Args[Key] = Saver.save(Args[Key] + "," + Value);
+else
+  Args[Key] = Value;
   }
 
-  auto reportError = [argv](Error E) {
-logAllUnhandledErrors(std::move(E), WithColor::error(errs(), argv[0]));
-return EXIT_FAILURE;
-  };
+  return Args;
+}
 
+static Error bundleImages() {
   SmallVector BinaryData;
   raw_svector_ostream OS(BinaryData);
   for (StringRef Image : DeviceImages) {
 BumpPtrAllocator Alloc;
 StringSaver Saver(Alloc);
-
-StringMap Args;
-for (StringRef Arg : llvm::split(Image, ",")) {
-  auto KeyAndValue = Arg.split("=");
-  if (Args.count(KeyAndValue.first))
-Args[KeyAndValue.first] =
-Saver.save(Args[KeyAndValue.first] + "," + KeyAndValue.second);
-  else
-Args[KeyAndValue.first] = KeyAndValue.second;
-}
+DenseMap Args = getImageArguments(Image, Saver);
 
 if (!Args.count("triple") || !Args.count("file"))
-  return reportError(createStringError(
+  return createStringError(
   inconvertibleErrorCode(),
-  "'file' and 'triple' are required image arguments"));
+  "'file' and 'triple' are required image arguments");
 
 OffloadBinary::OffloadingImage ImageBinary{};
 std::unique_ptr DeviceImage;
-for (const auto &KeyAndValue : Args) {
-  StringRef Key = KeyAndValue.getKey();
+for (const auto &[Key, Value] : Args) {
   if (Key == "file") {
 llvm::ErrorOr> ObjectOrErr =
-llvm::MemoryBuffer::getFileOrSTDIN(KeyAndValue.getValue());
+llvm::MemoryBuffer::getFileOrSTDIN(Value);
 if (std::error_code EC = ObjectOrErr.getError())
-  return reportError(errorCodeToError(EC));
+  return errorCodeToError(EC);
 
 // Clang uses the '.o' suffix for LTO bitcode.
 if (identify_magic((*ObjectOrErr)->getBuffer()) == file_magic::bitcode)
   ImageBinary.TheImageKind = object::IMG_Bitcode;
 else
-  ImageBinary.TheImageKind = getImageKind(
-  sys::path::extension(KeyAndValue.getValue()).drop_front());
+  ImageBinary.TheImageKind =
+  getI

[PATCH] D132388: [pseudo] Fix HeadsPartition is not initialized correctly.

2022-08-23 Thread Haojian Wu 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 rGedb8fb265990: [pseudo] Fix HeadsPartition is not initialized 
correctly. (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132388

Files:
  clang-tools-extra/pseudo/lib/GLR.cpp
  clang-tools-extra/pseudo/unittests/GLRTest.cpp


Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -652,6 +652,31 @@
 "[  1, end) └─word := \n");
 }
 
+TEST_F(GLRTest, RecoveryFromStartOfInput) {
+  build(R"bnf(
+_ := start [recover=Fallback] EOF
+
+start := IDENTIFIER
+  )bnf");
+  TestLang.Table = LRTable::buildSLR(TestLang.G);
+  bool fallback_recovered = false;
+  auto fallback = [&](Token::Index Start, const TokenStream & Code) {
+fallback_recovered = true;
+return Code.tokens().size();
+  };
+  TestLang.RecoveryStrategies.try_emplace(
+  extensionID("Fallback"),
+  fallback);
+  clang::LangOptions LOptions;
+  TokenStream Tokens = cook(lex("?", LOptions), LOptions);
+
+  const ForestNode &Parsed =
+  glrParse({Tokens, Arena, GSStack}, id("start"), TestLang);
+  EXPECT_TRUE(fallback_recovered);
+  EXPECT_EQ(Parsed.dumpRecursive(TestLang.G),
+"[  0, end) start := \n");
+}
+
 TEST_F(GLRTest, RepeatedRecovery) {
   // We require multiple steps of recovery at eof and then a reduction in order
   // to successfully parse.
Index: clang-tools-extra/pseudo/lib/GLR.cpp
===
--- clang-tools-extra/pseudo/lib/GLR.cpp
+++ clang-tools-extra/pseudo/lib/GLR.cpp
@@ -31,7 +31,6 @@
   const TokenStream &Tokens,
   const Language &Lang) {
   assert(Strategy != 0);
-  assert(Begin > 0);
   if (auto S = Lang.RecoveryStrategies.lookup(Strategy))
 return S(Begin, Tokens);
   return Token::Invalid;
@@ -614,7 +613,7 @@
   // Invariant: Heads is partitioned by source: {shifted | reduced}.
   // HeadsPartition is the index of the first head formed by reduction.
   // We use this to discard and recreate the reduced heads during recovery.
-  unsigned HeadsPartition = 0;
+  unsigned HeadsPartition = Heads.size();
   std::vector NextHeads;
   auto MaybeGC = [&, Roots(std::vector{}), I(0u)]() mutable 
{
 assert(NextHeads.empty() && "Running GC at the wrong time!");


Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -652,6 +652,31 @@
 "[  1, end) └─word := \n");
 }
 
+TEST_F(GLRTest, RecoveryFromStartOfInput) {
+  build(R"bnf(
+_ := start [recover=Fallback] EOF
+
+start := IDENTIFIER
+  )bnf");
+  TestLang.Table = LRTable::buildSLR(TestLang.G);
+  bool fallback_recovered = false;
+  auto fallback = [&](Token::Index Start, const TokenStream & Code) {
+fallback_recovered = true;
+return Code.tokens().size();
+  };
+  TestLang.RecoveryStrategies.try_emplace(
+  extensionID("Fallback"),
+  fallback);
+  clang::LangOptions LOptions;
+  TokenStream Tokens = cook(lex("?", LOptions), LOptions);
+
+  const ForestNode &Parsed =
+  glrParse({Tokens, Arena, GSStack}, id("start"), TestLang);
+  EXPECT_TRUE(fallback_recovered);
+  EXPECT_EQ(Parsed.dumpRecursive(TestLang.G),
+"[  0, end) start := \n");
+}
+
 TEST_F(GLRTest, RepeatedRecovery) {
   // We require multiple steps of recovery at eof and then a reduction in order
   // to successfully parse.
Index: clang-tools-extra/pseudo/lib/GLR.cpp
===
--- clang-tools-extra/pseudo/lib/GLR.cpp
+++ clang-tools-extra/pseudo/lib/GLR.cpp
@@ -31,7 +31,6 @@
   const TokenStream &Tokens,
   const Language &Lang) {
   assert(Strategy != 0);
-  assert(Begin > 0);
   if (auto S = Lang.RecoveryStrategies.lookup(Strategy))
 return S(Begin, Tokens);
   return Token::Invalid;
@@ -614,7 +613,7 @@
   // Invariant: Heads is partitioned by source: {shifted | reduced}.
   // HeadsPartition is the index of the first head formed by reduction.
   // We use this to discard and recreate the reduced heads during recovery.
-  unsigned HeadsPartition = 0;
+  unsigned HeadsPartition = Heads.size();
   std::vector NextHeads;
   auto MaybeGC = [&, Roots(std::vector{}), I(0u)]() mutable {
 assert(NextHeads.empty() && "Running GC at the wrong time!");
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/lis

[clang-tools-extra] edb8fb2 - [pseudo] Fix HeadsPartition is not initialized correctly.

2022-08-23 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-08-23T15:08:33+02:00
New Revision: edb8fb265990c3c4d0453d6b789554ccb5341123

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

LOG: [pseudo] Fix HeadsPartition is not initialized correctly.

The bug was that if we recover from the token 0, we will make the
Heads empty (Line646), which results no recovery being applied.

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/pseudo/lib/GLR.cpp
clang-tools-extra/pseudo/unittests/GLRTest.cpp

Removed: 




diff  --git a/clang-tools-extra/pseudo/lib/GLR.cpp 
b/clang-tools-extra/pseudo/lib/GLR.cpp
index 8e4e6181eb2a6..3e7d5a5435807 100644
--- a/clang-tools-extra/pseudo/lib/GLR.cpp
+++ b/clang-tools-extra/pseudo/lib/GLR.cpp
@@ -31,7 +31,6 @@ Token::Index findRecoveryEndpoint(ExtensionID Strategy, 
Token::Index Begin,
   const TokenStream &Tokens,
   const Language &Lang) {
   assert(Strategy != 0);
-  assert(Begin > 0);
   if (auto S = Lang.RecoveryStrategies.lookup(Strategy))
 return S(Begin, Tokens);
   return Token::Invalid;
@@ -614,7 +613,7 @@ const ForestNode &glrParse(const ParseParams &Params, 
SymbolID StartSymbol,
   // Invariant: Heads is partitioned by source: {shifted | reduced}.
   // HeadsPartition is the index of the first head formed by reduction.
   // We use this to discard and recreate the reduced heads during recovery.
-  unsigned HeadsPartition = 0;
+  unsigned HeadsPartition = Heads.size();
   std::vector NextHeads;
   auto MaybeGC = [&, Roots(std::vector{}), I(0u)]() mutable 
{
 assert(NextHeads.empty() && "Running GC at the wrong time!");

diff  --git a/clang-tools-extra/pseudo/unittests/GLRTest.cpp 
b/clang-tools-extra/pseudo/unittests/GLRTest.cpp
index 761b2c8db4aac..f361fb78247ac 100644
--- a/clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ b/clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -652,6 +652,31 @@ TEST_F(GLRTest, RecoverUnrestrictedReduce) {
 "[  1, end) └─word := \n");
 }
 
+TEST_F(GLRTest, RecoveryFromStartOfInput) {
+  build(R"bnf(
+_ := start [recover=Fallback] EOF
+
+start := IDENTIFIER
+  )bnf");
+  TestLang.Table = LRTable::buildSLR(TestLang.G);
+  bool fallback_recovered = false;
+  auto fallback = [&](Token::Index Start, const TokenStream & Code) {
+fallback_recovered = true;
+return Code.tokens().size();
+  };
+  TestLang.RecoveryStrategies.try_emplace(
+  extensionID("Fallback"),
+  fallback);
+  clang::LangOptions LOptions;
+  TokenStream Tokens = cook(lex("?", LOptions), LOptions);
+
+  const ForestNode &Parsed =
+  glrParse({Tokens, Arena, GSStack}, id("start"), TestLang);
+  EXPECT_TRUE(fallback_recovered);
+  EXPECT_EQ(Parsed.dumpRecursive(TestLang.G),
+"[  0, end) start := \n");
+}
+
 TEST_F(GLRTest, RepeatedRecovery) {
   // We require multiple steps of recovery at eof and then a reduction in order
   // to successfully parse.



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


[PATCH] D131625: [HLSL] Entry functions require param annotation

2022-08-23 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/AST/Attr.h:193
 
+class HLSLAnnotationAttr : public InheritableAttr {
+protected:

beanz wrote:
> aaron.ballman wrote:
> > beanz wrote:
> > > aaron.ballman wrote:
> > > > Is this intended to be used only for parameters (that's how I read the 
> > > > summary for the patch)? If so, why is this not inheriting from 
> > > > `InheritableParamAttr`?
> > > Sadly these attributes are valid in places that aren’t parameters. For 
> > > example, they can be applied on the members of a struct. When specifying 
> > > an HLSL entry we require semantics for all scalar variables in the 
> > > signature so that the we can match up the parameters from driver and 
> > > user-provided values, but the parameters can be scalars or user defined 
> > > structs. For example:
> > > 
> > > ```
> > > struct Pupper {
> > >   int Legs : SomeAnnotation;
> > >   int Ears : SomeOtherAnnotation;
> > > }
> > > ...
> > > void main(Pupper P) {...} // valid as an entry
> > > ```
> > > 
> > > We also allow these annotations (and require them) on return types for 
> > > entry functions:
> > > 
> > > ```
> > > int main(...) : SomeAnnotation {...}
> > > ```
> > > 
> > > Where this all gets really special is that entry functions as passed to 
> > > drivers have a `void(void)` signature, but entry functions with the 
> > > source-specified signature can be called.
> > > 
> > > I'm trying to handle those cases in D131203 by generating the 
> > > user-written function as is with C++ mangling, and generating a 
> > > non-mangled `void(void)` wrapper that calls the underlying function after 
> > > populating the annotation values. It is an incomplete implementation, but 
> > > a starting point.
> > > 
> > Oh, thank you for the explanation!
> > 
> > > Where this all gets really special is that entry functions as passed to 
> > > drivers have a void(void) signature, but entry functions with the 
> > > source-specified signature can be called.
> > 
> > Well that should be fun if you have code that cares about the address of 
> > the function, depending on which address you happen to get. But you don't 
> > allow pointers IIRC, so maybe you're "safe"?
> I _think_ taking the address of the function should consistently give the 
> address of the mangled function since the AST will resolve using C++ mangling 
> rules. I hope that would be the expected behavior even if we exposed pointers 
> in the future since the `void(void)` entry should only ever be the hardware 
> start point.
> 
> I'm sure I'm wrong about this and will regret this speculation in the 
> future...
Keep in mind that we have things like `__builtin_frame_address()` which exposes 
"this function" and "calling function" to the caller in ways that may be 
surprising. That said, if someone is using those kinds of tricks to inspect the 
identity of a function, I'm not certain how sympathetic I am to their plight in 
this case.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:11635
 def err_hlsl_attribute_param_mismatch : Error<"%0 attribute parameters do not 
match the previous declaration">;
+def err_hlsl_missing_semantic_annotation : Error<"semantic annotations must be 
present for all parameters of an entry function or patch constant function">;
 

I have no idea how close to the 80 col limit I got this, but we do mostly try 
to ensure diagnostics don't go too far over the 80 col limit (we're more lax in 
.td files because clang-format sometimes destroys the formatting rather than 
help it).



Comment at: clang/lib/Sema/SemaDecl.cpp:11876
+if (!Param->hasAttr()) {
+  // FIXME: Handle struct parameters where annotations are on struct 
fields.
+  Diag(FD->getLocation(), diag::err_hlsl_missing_semantic_annotation);

What about checking for the function return type?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131625

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


[PATCH] D132260: [pseudo] Eliminate a false parse of structured binding declaration.

2022-08-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 454816.
hokein marked 3 inline comments as done.
hokein added a comment.

address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132260

Files:
  clang-tools-extra/pseudo/lib/cxx/CXX.cpp
  clang-tools-extra/pseudo/lib/cxx/cxx.bnf
  clang-tools-extra/pseudo/test/cxx/structured-binding.cpp


Index: clang-tools-extra/pseudo/test/cxx/structured-binding.cpp
===
--- /dev/null
+++ clang-tools-extra/pseudo/test/cxx/structured-binding.cpp
@@ -0,0 +1,6 @@
+// RUN: clang-pseudo -grammar=cxx -source=%s --start-symbol=statement-seq 
--print-forest | FileCheck %s
+
+// Verify there is no false parse of the structured binding declaration.
+ABC[post] = abc;
+// CHECK: statement-seq~expression-statement := expression ;
+// CHECK: postfix-expression [ expr-or-braced-init-list ]
Index: clang-tools-extra/pseudo/lib/cxx/cxx.bnf
===
--- clang-tools-extra/pseudo/lib/cxx/cxx.bnf
+++ clang-tools-extra/pseudo/lib/cxx/cxx.bnf
@@ -330,7 +330,7 @@
 nodeclspec-function-declaration := function-declarator ;
 alias-declaration := USING IDENTIFIER = defining-type-id ;
 simple-declaration := decl-specifier-seq init-declarator-list_opt ;
-simple-declaration := decl-specifier-seq ref-qualifier_opt [ identifier-list ] 
initializer ;
+simple-declaration := decl-specifier-seq ref-qualifier_opt [ identifier-list ] 
initializer ; [guard]
 static_assert-declaration := STATIC_ASSERT ( constant-expression ) ;
 static_assert-declaration := STATIC_ASSERT ( constant-expression , 
string-literal ) ;
 empty-declaration := ;
Index: clang-tools-extra/pseudo/lib/cxx/CXX.cpp
===
--- clang-tools-extra/pseudo/lib/cxx/CXX.cpp
+++ clang-tools-extra/pseudo/lib/cxx/CXX.cpp
@@ -161,6 +161,27 @@
   return symbolToToken(P.Lookahead) != tok::kw_else;
 }
 
+bool specifiesStructuredBinding(const GuardParams &P) {
+  const auto DSS = P.RHS[0];
+  assert(DSS->symbol() == Symbol::decl_specifier_seq);
+
+  auto Length = P.RHS[1]->startTokenIndex() - DSS->startTokenIndex();
+  for (const auto &T :
+   P.Tokens.tokens().slice(DSS->startTokenIndex(), Length)) {
+switch (T.Kind) {
+case clang::tok::kw_static:
+case clang::tok::kw_thread_local:
+case clang::tok::kw_auto:
+case clang::tok::kw_const:
+case clang::tok::kw_volatile:
+  break;
+default:
+  return false;
+}
+  }
+  return true;
+}
+
 // Whether this e.g. decl-specifier contains an "exclusive" type such as a 
class
 // name, and thus can't combine with a second exclusive type.
 //
@@ -320,6 +341,18 @@
   {rule::nested_name_specifier::COLONCOLON,
TOKEN_GUARD(coloncolon, Tok.prev().Kind != tok::identifier)},
 
+  // Implement C++ [dcl.pre#6]:
+  //   A simple-declaration with an identifier-list is called a structured
+  //   binding declaration ([dcl.struct.bind]). If the decl-specifier-seq
+  //   contains any decl-specifier other than static, thread_­local, auto,
+  //   or cv-qualifiers, the program is ill-formed.
+  {rule::simple_declaration::
+   
decl_specifier_seq__ref_qualifier__L_SQUARE__identifier_list__R_SQUARE__initializer__SEMI,
+   specifiesStructuredBinding},
+  {rule::simple_declaration::
+   
decl_specifier_seq__L_SQUARE__identifier_list__R_SQUARE__initializer__SEMI,
+   specifiesStructuredBinding},
+
   // The grammar distinguishes (only) user-defined vs plain string 
literals,
   // where the clang lexer distinguishes (only) encoding types.
   {rule::user_defined_string_literal_chunk::STRING_LITERAL,


Index: clang-tools-extra/pseudo/test/cxx/structured-binding.cpp
===
--- /dev/null
+++ clang-tools-extra/pseudo/test/cxx/structured-binding.cpp
@@ -0,0 +1,6 @@
+// RUN: clang-pseudo -grammar=cxx -source=%s --start-symbol=statement-seq --print-forest | FileCheck %s
+
+// Verify there is no false parse of the structured binding declaration.
+ABC[post] = abc;
+// CHECK: statement-seq~expression-statement := expression ;
+// CHECK: postfix-expression [ expr-or-braced-init-list ]
Index: clang-tools-extra/pseudo/lib/cxx/cxx.bnf
===
--- clang-tools-extra/pseudo/lib/cxx/cxx.bnf
+++ clang-tools-extra/pseudo/lib/cxx/cxx.bnf
@@ -330,7 +330,7 @@
 nodeclspec-function-declaration := function-declarator ;
 alias-declaration := USING IDENTIFIER = defining-type-id ;
 simple-declaration := decl-specifier-seq init-declarator-list_opt ;
-simple-declaration := decl-specifier-seq ref-qualifier_opt [ identifier-list ] initializer ;
+simple-declaration := decl-specifier-seq ref-qualifier_opt [ identifier-list ] initializer ; [guard]
 static_assert-declaration := STATI

[clang-tools-extra] f7dc91a - [pseudo] Eliminate a false parse of structured binding declaration.

2022-08-23 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-08-23T15:25:52+02:00
New Revision: f7dc91ad5609fab02cb805861dd232cab492340d

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

LOG: [pseudo] Eliminate a false parse of structured binding declaration.

Using the guard to implement part of the rule https://eel.is/c++draft/dcl.pre#6.

```
void foo() {
  // can be parsed as
  //   - structured-binding declaration (a false parse)
  //   - assignment expression
  array[index] = value;
}
```

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

Added: 
clang-tools-extra/pseudo/test/cxx/structured-binding.cpp

Modified: 
clang-tools-extra/pseudo/lib/cxx/CXX.cpp
clang-tools-extra/pseudo/lib/cxx/cxx.bnf

Removed: 




diff  --git a/clang-tools-extra/pseudo/lib/cxx/CXX.cpp 
b/clang-tools-extra/pseudo/lib/cxx/CXX.cpp
index 668c4d1bfcb6a..46d837aec44ad 100644
--- a/clang-tools-extra/pseudo/lib/cxx/CXX.cpp
+++ b/clang-tools-extra/pseudo/lib/cxx/CXX.cpp
@@ -161,6 +161,27 @@ bool guardNextTokenNotElse(const GuardParams &P) {
   return symbolToToken(P.Lookahead) != tok::kw_else;
 }
 
+bool specifiesStructuredBinding(const GuardParams &P) {
+  const auto DSS = P.RHS[0];
+  assert(DSS->symbol() == Symbol::decl_specifier_seq);
+
+  auto Length = P.RHS[1]->startTokenIndex() - DSS->startTokenIndex();
+  for (const auto &T :
+   P.Tokens.tokens().slice(DSS->startTokenIndex(), Length)) {
+switch (T.Kind) {
+case clang::tok::kw_static:
+case clang::tok::kw_thread_local:
+case clang::tok::kw_auto:
+case clang::tok::kw_const:
+case clang::tok::kw_volatile:
+  break;
+default:
+  return false;
+}
+  }
+  return true;
+}
+
 // Whether this e.g. decl-specifier contains an "exclusive" type such as a 
class
 // name, and thus can't combine with a second exclusive type.
 //
@@ -320,6 +341,18 @@ llvm::DenseMap buildGuards() {
   {rule::nested_name_specifier::COLONCOLON,
TOKEN_GUARD(coloncolon, Tok.prev().Kind != tok::identifier)},
 
+  // Implement C++ [dcl.pre#6]:
+  //   A simple-declaration with an identifier-list is called a structured
+  //   binding declaration ([dcl.struct.bind]). If the decl-specifier-seq
+  //   contains any decl-specifier other than static, thread_­local, auto,
+  //   or cv-qualifiers, the program is ill-formed.
+  {rule::simple_declaration::
+   
decl_specifier_seq__ref_qualifier__L_SQUARE__identifier_list__R_SQUARE__initializer__SEMI,
+   specifiesStructuredBinding},
+  {rule::simple_declaration::
+   
decl_specifier_seq__L_SQUARE__identifier_list__R_SQUARE__initializer__SEMI,
+   specifiesStructuredBinding},
+
   // The grammar distinguishes (only) user-defined vs plain string 
literals,
   // where the clang lexer distinguishes (only) encoding types.
   {rule::user_defined_string_literal_chunk::STRING_LITERAL,

diff  --git a/clang-tools-extra/pseudo/lib/cxx/cxx.bnf 
b/clang-tools-extra/pseudo/lib/cxx/cxx.bnf
index 80c1b54437c07..36caf7b1e6337 100644
--- a/clang-tools-extra/pseudo/lib/cxx/cxx.bnf
+++ b/clang-tools-extra/pseudo/lib/cxx/cxx.bnf
@@ -330,7 +330,7 @@ block-declaration := opaque-enum-declaration
 nodeclspec-function-declaration := function-declarator ;
 alias-declaration := USING IDENTIFIER = defining-type-id ;
 simple-declaration := decl-specifier-seq init-declarator-list_opt ;
-simple-declaration := decl-specifier-seq ref-qualifier_opt [ identifier-list ] 
initializer ;
+simple-declaration := decl-specifier-seq ref-qualifier_opt [ identifier-list ] 
initializer ; [guard]
 static_assert-declaration := STATIC_ASSERT ( constant-expression ) ;
 static_assert-declaration := STATIC_ASSERT ( constant-expression , 
string-literal ) ;
 empty-declaration := ;

diff  --git a/clang-tools-extra/pseudo/test/cxx/structured-binding.cpp 
b/clang-tools-extra/pseudo/test/cxx/structured-binding.cpp
new file mode 100644
index 0..1c68e928ddd62
--- /dev/null
+++ b/clang-tools-extra/pseudo/test/cxx/structured-binding.cpp
@@ -0,0 +1,6 @@
+// RUN: clang-pseudo -grammar=cxx -source=%s --start-symbol=statement-seq 
--print-forest | FileCheck %s
+
+// Verify there is no false parse of the structured binding declaration.
+ABC[post] = abc;
+// CHECK: statement-seq~expression-statement := expression ;
+// CHECK: postfix-expression [ expr-or-braced-init-list ]



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


[PATCH] D132260: [pseudo] Eliminate a false parse of structured binding declaration.

2022-08-23 Thread Haojian Wu 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 rGf7dc91ad5609: [pseudo] Eliminate a false parse of structured 
binding declaration. (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132260

Files:
  clang-tools-extra/pseudo/lib/cxx/CXX.cpp
  clang-tools-extra/pseudo/lib/cxx/cxx.bnf
  clang-tools-extra/pseudo/test/cxx/structured-binding.cpp


Index: clang-tools-extra/pseudo/test/cxx/structured-binding.cpp
===
--- /dev/null
+++ clang-tools-extra/pseudo/test/cxx/structured-binding.cpp
@@ -0,0 +1,6 @@
+// RUN: clang-pseudo -grammar=cxx -source=%s --start-symbol=statement-seq 
--print-forest | FileCheck %s
+
+// Verify there is no false parse of the structured binding declaration.
+ABC[post] = abc;
+// CHECK: statement-seq~expression-statement := expression ;
+// CHECK: postfix-expression [ expr-or-braced-init-list ]
Index: clang-tools-extra/pseudo/lib/cxx/cxx.bnf
===
--- clang-tools-extra/pseudo/lib/cxx/cxx.bnf
+++ clang-tools-extra/pseudo/lib/cxx/cxx.bnf
@@ -330,7 +330,7 @@
 nodeclspec-function-declaration := function-declarator ;
 alias-declaration := USING IDENTIFIER = defining-type-id ;
 simple-declaration := decl-specifier-seq init-declarator-list_opt ;
-simple-declaration := decl-specifier-seq ref-qualifier_opt [ identifier-list ] 
initializer ;
+simple-declaration := decl-specifier-seq ref-qualifier_opt [ identifier-list ] 
initializer ; [guard]
 static_assert-declaration := STATIC_ASSERT ( constant-expression ) ;
 static_assert-declaration := STATIC_ASSERT ( constant-expression , 
string-literal ) ;
 empty-declaration := ;
Index: clang-tools-extra/pseudo/lib/cxx/CXX.cpp
===
--- clang-tools-extra/pseudo/lib/cxx/CXX.cpp
+++ clang-tools-extra/pseudo/lib/cxx/CXX.cpp
@@ -161,6 +161,27 @@
   return symbolToToken(P.Lookahead) != tok::kw_else;
 }
 
+bool specifiesStructuredBinding(const GuardParams &P) {
+  const auto DSS = P.RHS[0];
+  assert(DSS->symbol() == Symbol::decl_specifier_seq);
+
+  auto Length = P.RHS[1]->startTokenIndex() - DSS->startTokenIndex();
+  for (const auto &T :
+   P.Tokens.tokens().slice(DSS->startTokenIndex(), Length)) {
+switch (T.Kind) {
+case clang::tok::kw_static:
+case clang::tok::kw_thread_local:
+case clang::tok::kw_auto:
+case clang::tok::kw_const:
+case clang::tok::kw_volatile:
+  break;
+default:
+  return false;
+}
+  }
+  return true;
+}
+
 // Whether this e.g. decl-specifier contains an "exclusive" type such as a 
class
 // name, and thus can't combine with a second exclusive type.
 //
@@ -320,6 +341,18 @@
   {rule::nested_name_specifier::COLONCOLON,
TOKEN_GUARD(coloncolon, Tok.prev().Kind != tok::identifier)},
 
+  // Implement C++ [dcl.pre#6]:
+  //   A simple-declaration with an identifier-list is called a structured
+  //   binding declaration ([dcl.struct.bind]). If the decl-specifier-seq
+  //   contains any decl-specifier other than static, thread_­local, auto,
+  //   or cv-qualifiers, the program is ill-formed.
+  {rule::simple_declaration::
+   
decl_specifier_seq__ref_qualifier__L_SQUARE__identifier_list__R_SQUARE__initializer__SEMI,
+   specifiesStructuredBinding},
+  {rule::simple_declaration::
+   
decl_specifier_seq__L_SQUARE__identifier_list__R_SQUARE__initializer__SEMI,
+   specifiesStructuredBinding},
+
   // The grammar distinguishes (only) user-defined vs plain string 
literals,
   // where the clang lexer distinguishes (only) encoding types.
   {rule::user_defined_string_literal_chunk::STRING_LITERAL,


Index: clang-tools-extra/pseudo/test/cxx/structured-binding.cpp
===
--- /dev/null
+++ clang-tools-extra/pseudo/test/cxx/structured-binding.cpp
@@ -0,0 +1,6 @@
+// RUN: clang-pseudo -grammar=cxx -source=%s --start-symbol=statement-seq --print-forest | FileCheck %s
+
+// Verify there is no false parse of the structured binding declaration.
+ABC[post] = abc;
+// CHECK: statement-seq~expression-statement := expression ;
+// CHECK: postfix-expression [ expr-or-braced-init-list ]
Index: clang-tools-extra/pseudo/lib/cxx/cxx.bnf
===
--- clang-tools-extra/pseudo/lib/cxx/cxx.bnf
+++ clang-tools-extra/pseudo/lib/cxx/cxx.bnf
@@ -330,7 +330,7 @@
 nodeclspec-function-declaration := function-declarator ;
 alias-declaration := USING IDENTIFIER = defining-type-id ;
 simple-declaration := decl-specifier-seq init-declarator-list_opt ;
-simple-declaration := decl-specifier-seq ref-qualifier_opt [ identifier-list ] initializer ;
+simple-decl

[PATCH] D131203: [HLSL] Initial codegen for SV_GroupIndex

2022-08-23 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131203

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


[PATCH] D132470: [pseudo] add the spurious left-and-upwads recovery case to unittest.

2022-08-23 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added a project: All.
hokein requested review of this revision.
Herald added a subscriber: alextsao1999.
Herald added a project: clang-tools-extra.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132470

Files:
  clang-tools-extra/pseudo/lib/GLR.cpp
  clang-tools-extra/pseudo/unittests/GLRTest.cpp


Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -708,6 +708,57 @@
 "[  1, end) └─body := \n");
 }
 
+TEST_F(GLRTest, SpuriousRecoveryLeftAndUpwardsCase) {
+  build(R"bnf(
+_ := compound-stmt EOF
+
+compound-stmt := { stmt-seq [recover=Braces] }
+
+stmt-seq := stmt
+stmt-seq := stmt-seq stmt
+
+stmt := compound-stmt
+stmt := IF ( expr [recover=Parentheses] ) IDENTIFIER
+stmt := ;
+  )bnf");
+
+  TestLang.Table = LRTable::buildSLR(TestLang.G);
+  TestLang.RecoveryStrategies.try_emplace(extensionID("Braces"), 
recoverBraces);
+  TestLang.RecoveryStrategies.try_emplace(
+  extensionID("Parentheses"),
+  [](Token::Index Start, const TokenStream &Code) {
+assert(Start > 0);
+const Token &Left = Code.tokens()[Start - 1];
+assert(Left.Kind == tok::l_paren);
+if (const auto *Right = Left.pair())
+  return Code.index(*Right);
+return Token::Invalid;
+  });
+  clang::LangOptions LOptions;
+  TokenStream Tokens = cook(lex(R"cpp(
+   { ;
+ { if (id) ? }
+   }
+  )cpp", LOptions), LOptions);
+  pairBrackets(Tokens);
+
+  const ForestNode &Parsed =
+  glrParse({Tokens, Arena, GSStack}, id("compound-stmt"), TestLang);
+  EXPECT_EQ(Parsed.dumpRecursive(TestLang.G),
+"[  0, end) compound-stmt := { stmt-seq [recover=Braces] }\n"
+"[  0,   1) ├─{ := tok[0]\n"
+"[  1,   9) ├─stmt-seq := stmt-seq stmt\n"
+"[  1,   2) │ ├─stmt-seq := stmt\n"
+"[  1,   2) │ │ └─stmt := ;\n"
+"[  1,   2) │ │   └─; := tok[1]\n"
+"[  2,   9) │ └─stmt := compound-stmt\n"
+"[  2,   9) │   └─compound-stmt := { stmt-seq [recover=Braces] }\n"
+"[  2,   3) │ ├─{ := tok[2]\n"
+"[  3,   8) │ ├─stmt-seq := \n"
+"[  8,   9) │ └─} := tok[8]\n"
+"[  9, end) └─} := tok[9]\n");
+}
+
 TEST_F(GLRTest, NoExplicitAccept) {
   build(R"bnf(
 _ := test EOF
Index: clang-tools-extra/pseudo/lib/GLR.cpp
===
--- clang-tools-extra/pseudo/lib/GLR.cpp
+++ clang-tools-extra/pseudo/lib/GLR.cpp
@@ -88,7 +88,6 @@
   // For now, we have to take this into account when defining recovery rules.
   // (e.g. in the expr recovery above, stay inside the parentheses).
   // FIXME: find a more satisfying way to avoid such false recovery.
-  // FIXME: Add a test for spurious recovery once tests can define strategies.
   std::vector Path;
   llvm::DenseSet Seen;
   auto WalkUp = [&](const GSS::Node *N, Token::Index NextTok, auto &WalkUp) {


Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -708,6 +708,57 @@
 "[  1, end) └─body := \n");
 }
 
+TEST_F(GLRTest, SpuriousRecoveryLeftAndUpwardsCase) {
+  build(R"bnf(
+_ := compound-stmt EOF
+
+compound-stmt := { stmt-seq [recover=Braces] }
+
+stmt-seq := stmt
+stmt-seq := stmt-seq stmt
+
+stmt := compound-stmt
+stmt := IF ( expr [recover=Parentheses] ) IDENTIFIER
+stmt := ;
+  )bnf");
+
+  TestLang.Table = LRTable::buildSLR(TestLang.G);
+  TestLang.RecoveryStrategies.try_emplace(extensionID("Braces"), recoverBraces);
+  TestLang.RecoveryStrategies.try_emplace(
+  extensionID("Parentheses"),
+  [](Token::Index Start, const TokenStream &Code) {
+assert(Start > 0);
+const Token &Left = Code.tokens()[Start - 1];
+assert(Left.Kind == tok::l_paren);
+if (const auto *Right = Left.pair())
+  return Code.index(*Right);
+return Token::Invalid;
+  });
+  clang::LangOptions LOptions;
+  TokenStream Tokens = cook(lex(R"cpp(
+   { ;
+ { if (id) ? }
+   }
+  )cpp", LOptions), LOptions);
+  pairBrackets(Tokens);
+
+  const ForestNode &Parsed =
+  glrParse({Tokens, Arena, GSStack}, id("compound-stmt"), TestLang);
+  EXPECT_EQ(Parsed.dumpRecursive(TestLang.G),
+"[  0, end) compound-stmt := { stmt-seq [recover=Braces] }\n"
+"[  0,   1) ├─{ := tok[0]\n"
+"[  1,   9) ├─stmt-seq := stmt-seq stmt\n"
+"[  1,   2) │ ├─stmt-seq := stmt\n"
+"[  1,   2) │ │ └─stmt := ;\n"
+"[  1,   2) │ │   └─; := tok[1]\n"

[PATCH] D129464: [Clang][CodeGen] Set FP options of builder at entry to compound statement

2022-08-23 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff updated this revision to Diff 454822.
sepavloff edited the summary of this revision.
sepavloff added a comment.

Rebase and ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129464

Files:
  clang/include/clang/AST/Stmt.h
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/CodeGen/X86/avx512dq-builtins-constrained.c
  clang/test/CodeGen/aarch64-v8.2a-neon-intrinsics-constrained.c
  clang/test/CodeGen/complex-strictfp.c
  clang/test/CodeGen/pragma-fenv_access.cpp

Index: clang/test/CodeGen/pragma-fenv_access.cpp
===
--- /dev/null
+++ clang/test/CodeGen/pragma-fenv_access.cpp
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 -S -triple x86_64-linux-gnu -emit-llvm %s -o - | FileCheck %s
+
+template 
+T templ_01(T a, T b) {
+  return a * b;
+}
+
+#pragma STDC FENV_ACCESS ON
+
+float func_02(float a, float b) {
+  return 1.0f + templ_01(a, b);
+}
+
+// CHECK-LABEL: define {{.*}} @_Z7func_02ff
+// CHECK: call noundef float @_Z8templ_01IfET_S0_S0_
+// CHECK: call float @llvm.experimental.constrained.fadd.f32({{.*}}, metadata !"round.dynamic", metadata !"fpexcept.strict")
+
+// CHECK-LABEL: define {{.*}} @_Z8templ_01IfET_S0_S0_
+// CHECK: fmul float
+
+
+#pragma STDC FENV_ACCESS OFF
+#pragma STDC FENV_ROUND FE_UPWARD
+
+template 
+T templ_03(T a, T b) {
+  return a * b;
+}
+
+#pragma STDC FENV_ACCESS ON
+
+float func_04(float a, float b) {
+  return 1.0f + templ_03(a, b);
+}
+
+
+// CHECK-LABEL: define {{.*}} @_Z7func_04ff
+// CHECK: call noundef float @_Z8templ_03IfET_S0_S0_
+// CHECK: call float @llvm.experimental.constrained.fadd.f32({{.*}}, metadata !"round.upward", metadata !"fpexcept.strict")
+
+// CHECK-LABEL: define {{.*}} @_Z8templ_03IfET_S0_S0_
+// CHECK: call float @llvm.experimental.constrained.fmul.f32({{.*}}, metadata !"round.upward", metadata !"fpexcept.ignore")
Index: clang/test/CodeGen/complex-strictfp.c
===
--- clang/test/CodeGen/complex-strictfp.c
+++ clang/test/CodeGen/complex-strictfp.c
@@ -5,8 +5,6 @@
 // Test that the constrained intrinsics are picking up the exception
 // metadata from the AST instead of the global default from the command line.
 // Include rounding metadata in the testing.
-// FIXME: All cases of "fpexcept.maytrap" in this test are wrong.
-// FIXME: All cases of "round.tonearest" in this test are wrong.
 
 #pragma float_control(except, on)
 #pragma STDC FENV_ROUND FE_UPWARD
@@ -74,7 +72,7 @@
 // CHECK-NEXT:[[G1_REAL:%.*]] = load double, double* getelementptr inbounds ({ double, double }, { double, double }* @g1, i32 0, i32 0), align 8
 // CHECK-NEXT:[[G1_IMAG:%.*]] = load double, double* getelementptr inbounds ({ double, double }, { double, double }* @g1, i32 0, i32 1), align 8
 // CHECK-NEXT:[[TMP0:%.*]] = load double, double* @D, align 8
-// CHECK-NEXT:[[ADD_R:%.*]] = call double @llvm.experimental.constrained.fadd.f64(double [[G1_REAL]], double [[TMP0]], metadata !"round.tonearest", metadata !"fpexcept.maytrap") #[[ATTR2]]
+// CHECK-NEXT:[[ADD_R:%.*]] = call double @llvm.experimental.constrained.fadd.f64(double [[G1_REAL]], double [[TMP0]], metadata !"round.upward", metadata !"fpexcept.strict") #[[ATTR2]]
 // CHECK-NEXT:store double [[ADD_R]], double* getelementptr inbounds ({ double, double }, { double, double }* @g1, i32 0, i32 0), align 8
 // CHECK-NEXT:store double [[G1_IMAG]], double* getelementptr inbounds ({ double, double }, { double, double }* @g1, i32 0, i32 1), align 8
 // CHECK-NEXT:ret void
@@ -88,7 +86,7 @@
 // CHECK-NEXT:[[TMP0:%.*]] = load double, double* @D, align 8
 // CHECK-NEXT:[[G1_REAL:%.*]] = load double, double* getelementptr inbounds ({ double, double }, { double, double }* @g1, i32 0, i32 0), align 8
 // CHECK-NEXT:[[G1_IMAG:%.*]] = load double, double* getelementptr inbounds ({ double, double }, { double, double }* @g1, i32 0, i32 1), align 8
-// CHECK-NEXT:[[ADD_R:%.*]] = call double @llvm.experimental.constrained.fadd.f64(double [[TMP0]], double [[G1_REAL]], metadata !"round.tonearest", metadata !"fpexcept.maytrap") #[[ATTR2]]
+// CHECK-NEXT:[[ADD_R:%.*]] = call double @llvm.experimental.constrained.fadd.f64(double [[TMP0]], double [[G1_REAL]], metadata !"round.upward", metadata !"fpexcept.strict") #[[ATTR2]]
 // CHECK-NEXT:store double [[ADD_R]], double* getelementptr inbounds ({ double, double }, { double, double }* @g1, i32 0, i32 0), align 8
 // CHECK-NEXT:store double [[G1_IMAG]], double* getelementptr inbounds ({ double, double }, { double, double }* @g1, i32 0, i32 1), align 8
 // CHECK-NEXT:ret void
Index: clang/test/CodeGen/aarch64-v8.2a-neon-intrinsics-constrained.c
===
--- clang/test/CodeGen/aarch64-v8.2a-neon-intrinsics-constrained.c
+++ clang/test/CodeG

[clang] ea0549d - [OffloadPackager] Add necessary move statement on returned value

2022-08-23 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-08-23T08:45:30-05:00
New Revision: ea0549d41bc44f60db6a2fb9e0f32e752d47e177

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

LOG: [OffloadPackager] Add necessary move statement on returned value

Summary:
Some older compilers cannot automatically elide the returned vector of
unique pointers, causing build errors. This patch explicitly moves the
returned value instead which should solve the problem.

Added: 


Modified: 
clang/tools/clang-offload-packager/ClangOffloadPackager.cpp

Removed: 




diff  --git a/clang/tools/clang-offload-packager/ClangOffloadPackager.cpp 
b/clang/tools/clang-offload-packager/ClangOffloadPackager.cpp
index 0f90263d09345..b8d1565689f88 100644
--- a/clang/tools/clang-offload-packager/ClangOffloadPackager.cpp
+++ b/clang/tools/clang-offload-packager/ClangOffloadPackager.cpp
@@ -143,7 +143,7 @@ extractOffloadFiles(MemoryBufferRef Contents) {
 Binaries.emplace_back(std::move(*BinaryOrErr));
   }
 
-  return Binaries;
+  return std::move(Binaries);
 }
 
 static Error unbundleImages() {



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


[PATCH] D132324: [RFC] Remove support for building libc++ with `LLVM_ENABLE_PROJECTS`

2022-08-23 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a comment.

This sucks, but I'm going to revert this series of patches. This is getting 
somewhat out of hands and I feel that we're rushing to fix all kinds of issues 
in various directions. I'm going to revert the following patches, in this order:

1. 952f90b72b35 
 [CMake] 
Weaken 176db3b3ab25ff8a9b2405f50ef5a8bd9304a6d5 

2. e6a0800532bb 
 
[libcxxabi][cmake] Allow building without libcxx again
3. 176db3b3ab25 
 [RFC] 
Remove support for building C++ with `LLVM_ENABLE_PROJECTS`

Otherwise:

- I also think we don't want to move forward with D132411 
 -- it's going against this transition.
- https://reviews.llvm.org/rZORG3a209ca6c1b9 sounds like a good change we'd 
need to make no matter what, so that's great.
- D132454  seems like a good change 
regardless of this series of patches.

I think that's the whole set of changes/reviews associated to this in the past 
few days. If I've missed anything, please let me know ASAP.

This will have been extremely useful as a way to shake out places where the 
deprecated `LLVM_ENABLE_PROJECTS` build is still being used for 
libc++/libc++abi. However, we should take the time to fix these places first 
before landing the actual breaking change, otherwise things become too unstable 
and we're rushed into making potentially poor decisions.

Concretely, as an action item to move this transition forward, I will:

1. Grep for places where we still use `LLVM_ENABLE_PROJECTS` for libc++ and 
libc++abi in the LLVM monorepo
2. Do the same in the llvm-zorg repo
3. Do the same in our downstream bots (if other folks see this because of 
downstream breakage in their forks, be proactive and do this too, or you will 
get broken in the future!)
4. Re-land a patch that turns the `WARNING` into a `FATAL_ERROR`, and just 
that. Watch for more breakage and try fixing it iteratively.
5. Once we have `FATAL_ERROR` in place and things are green, we can land the 
rest of this patch (plus a few other things I had locally) to actually remove 
support for `LLVM_ENABLE_PROJECTS` with libc++/libc++abi.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132324

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


[PATCH] D132399: [clang/test] Correctly specify simulator env in target flag in fsanitize.c

2022-08-23 Thread Hans Wennborg via Phabricator via cfe-commits
hans accepted this revision.
hans added a comment.
This revision is now accepted and ready to land.

lgtm


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

https://reviews.llvm.org/D132399

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


[PATCH] D131683: Diagnosing the Future Keywords

2022-08-23 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticLexKinds.td:85
+  InGroup, DefaultIgnore;
+def warn_c23_keyword : Warning<"'%0' is a keyword in C23">,
+  InGroup, DefaultIgnore;





Comment at: clang/include/clang/Basic/TokenKinds.def:259
 //   KEYC11   - This is a keyword introduced to C in C11
+//   KEYC2X   - This is a keyword introduced to C in C23
 //   KEYCXX   - This is a C++ keyword, or a C++-specific keyword in the





Comment at: clang/include/clang/Basic/TokenKinds.def:384
+C2X_KEYWORD(true, BOOLSUPPORT)
+C2X_KEYWORD(remove_quals, KEYC2X)
+

This is technically correct, but I think we should remove it until we go to 
implement that paper instead of introducing the keyword out of thin air here.

Btw, I think that should be `, 0` instead of `, KEYC2X` given the use of 
`C2X_KEYWORD`, right?



Comment at: clang/lib/Lex/Preprocessor.cpp:789-791
-// char8_t is not modeled as a CXX20_KEYWORD because it's not
-// unconditionally enabled in C++20 mode. (It can be disabled
-// by -fno-char8_t.)

You should be sure to add this comment to the new code so we don't lose the 
useful information.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131683

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


[PATCH] D132400: [clang] Remove a FIXME that we can't fix

2022-08-23 Thread Hans Wennborg via Phabricator via cfe-commits
hans accepted this revision.
hans added a comment.
This revision is now accepted and ready to land.

lgtm

"No behavior change." occurs twice in the change description.


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

https://reviews.llvm.org/D132400

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


[PATCH] D132316: [CMake] `${LLVM_BINARY_DIR}/lib(${LLVM_LIBDIR_SUFFIX})?` -> `${LLVM_LIBRARY_DIR}`

2022-08-23 Thread John Ericson via Phabricator via cfe-commits
Ericson2314 updated this revision to Diff 454829.
Ericson2314 added a comment.

Redo sed mandating ending on word boundary


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132316

Files:
  bolt/lib/Target/AArch64/CMakeLists.txt
  bolt/lib/Target/X86/CMakeLists.txt
  bolt/unittests/Core/CMakeLists.txt
  clang/cmake/modules/CMakeLists.txt
  clang/lib/Tooling/CMakeLists.txt
  flang/cmake/modules/CMakeLists.txt
  lld/cmake/modules/CMakeLists.txt
  lldb/cmake/modules/LLDBConfig.cmake
  llvm/CMakeLists.txt
  llvm/cmake/modules/AddLLVM.cmake
  llvm/cmake/modules/CMakeLists.txt
  llvm/tools/llvm-exegesis/lib/AArch64/CMakeLists.txt
  llvm/tools/llvm-exegesis/lib/Mips/CMakeLists.txt
  llvm/tools/llvm-exegesis/lib/PowerPC/CMakeLists.txt
  llvm/tools/llvm-exegesis/lib/X86/CMakeLists.txt
  llvm/unittests/Target/ARM/CMakeLists.txt
  llvm/unittests/Target/DirectX/CMakeLists.txt
  llvm/unittests/tools/llvm-exegesis/AArch64/CMakeLists.txt
  llvm/unittests/tools/llvm-exegesis/ARM/CMakeLists.txt
  llvm/unittests/tools/llvm-exegesis/Mips/CMakeLists.txt
  llvm/unittests/tools/llvm-exegesis/PowerPC/CMakeLists.txt
  llvm/unittests/tools/llvm-exegesis/X86/CMakeLists.txt
  llvm/unittests/tools/llvm-mca/X86/CMakeLists.txt
  mlir/cmake/modules/CMakeLists.txt
  polly/cmake/CMakeLists.txt
  polly/test/CMakeLists.txt

Index: polly/test/CMakeLists.txt
===
--- polly/test/CMakeLists.txt
+++ polly/test/CMakeLists.txt
@@ -46,7 +46,7 @@
 
 set(LLVM_BINARY_DIR "${LLVM_BINARY_DIR}")
 set(LLVM_TOOLS_DIR "${LLVM_TOOLS_BINARY_DIR}")
-set(LLVM_LIBS_DIR "${LLVM_BINARY_DIR}/lib${LLVM_LIBDIR_SUFFIX}")
+set(LLVM_LIBS_DIR "${LLVM_LIBRARY_DIR}")
 if (CMAKE_LIBRARY_OUTPUT_DIRECTORY)
   set(POLLY_LIB_DIR ${CMAKE_LIBRARY_OUTPUT_DIRECTORY})
 else()
Index: polly/cmake/CMakeLists.txt
===
--- polly/cmake/CMakeLists.txt
+++ polly/cmake/CMakeLists.txt
@@ -12,7 +12,7 @@
 set(LLVM_INSTALL_PACKAGE_DIR "${CMAKE_INSTALL_PACKAGEDIR}/llvm" CACHE STRING
   "Path for CMake subdirectory for LLVM (defaults to '${CMAKE_INSTALL_PACKAGEDIR}/llvm')")
 # CMAKE_INSTALL_PACKAGEDIR might be absolute, so don't reuse below.
-set(llvm_cmake_builddir "${LLVM_BINARY_DIR}/lib${LLVM_LIBDIR_SUFFIX}/cmake/llvm")
+set(llvm_cmake_builddir "${LLVM_LIBRARY_DIR}/cmake/llvm")
 
 if (CMAKE_CONFIGURATION_TYPES)
   set(POLLY_EXPORTS_FILE_NAME "PollyExports-$>.cmake")
Index: mlir/cmake/modules/CMakeLists.txt
===
--- mlir/cmake/modules/CMakeLists.txt
+++ mlir/cmake/modules/CMakeLists.txt
@@ -15,7 +15,7 @@
 set(LLVM_INSTALL_PACKAGE_DIR "${CMAKE_INSTALL_PACKAGEDIR}/llvm" CACHE STRING
   "Path for CMake subdirectory for LLVM (defaults to '${CMAKE_INSTALL_PACKAGEDIR}/llvm')")
 # CMAKE_INSTALL_PACKAGEDIR might be absolute, so don't reuse below.
-set(llvm_cmake_builddir "${LLVM_BINARY_DIR}/lib${LLVM_LIBDIR_SUFFIX}/cmake/llvm")
+set(llvm_cmake_builddir "${LLVM_LIBRARY_DIR}/cmake/llvm")
 
 get_property(MLIR_EXPORTS GLOBAL PROPERTY MLIR_EXPORTS)
 export(TARGETS ${MLIR_EXPORTS} FILE ${mlir_cmake_builddir}/MLIRTargets.cmake)
Index: llvm/unittests/tools/llvm-mca/X86/CMakeLists.txt
===
--- llvm/unittests/tools/llvm-mca/X86/CMakeLists.txt
+++ llvm/unittests/tools/llvm-mca/X86/CMakeLists.txt
@@ -1,6 +1,6 @@
 add_llvm_mca_unittest_includes(
   ${LLVM_MAIN_SRC_DIR}/lib/Target/X86
-  ${LLVM_BINARY_DIR}/lib/Target/X86
+  ${LLVM_LIBRARY_DIR}/Target/X86
   )
 
 add_llvm_mca_unittest_sources(
Index: llvm/unittests/tools/llvm-exegesis/X86/CMakeLists.txt
===
--- llvm/unittests/tools/llvm-exegesis/X86/CMakeLists.txt
+++ llvm/unittests/tools/llvm-exegesis/X86/CMakeLists.txt
@@ -1,6 +1,6 @@
 add_llvm_exegesis_unittest_includes(
   ${LLVM_MAIN_SRC_DIR}/lib/Target/X86
-  ${LLVM_BINARY_DIR}/lib/Target/X86
+  ${LLVM_LIBRARY_DIR}/Target/X86
   ${LLVM_MAIN_SRC_DIR}/tools/llvm-exegesis/lib
   )
 
Index: llvm/unittests/tools/llvm-exegesis/PowerPC/CMakeLists.txt
===
--- llvm/unittests/tools/llvm-exegesis/PowerPC/CMakeLists.txt
+++ llvm/unittests/tools/llvm-exegesis/PowerPC/CMakeLists.txt
@@ -1,6 +1,6 @@
 add_llvm_exegesis_unittest_includes(
   ${LLVM_MAIN_SRC_DIR}/lib/Target/PowerPC
-  ${LLVM_BINARY_DIR}/lib/Target/PowerPC
+  ${LLVM_LIBRARY_DIR}/Target/PowerPC
   ${LLVM_MAIN_SRC_DIR}/tools/llvm-exegesis/lib
   )
 
Index: llvm/unittests/tools/llvm-exegesis/Mips/CMakeLists.txt
===
--- llvm/unittests/tools/llvm-exegesis/Mips/CMakeLists.txt
+++ llvm/unittests/tools/llvm-exegesis/Mips/CMakeLists.txt
@@ -1,6 +1,6 @@
 add_llvm_exegesis_unittest_includes(
   ${LLVM_MAIN_SRC_DIR}/lib/Target/Mips
-  ${LLVM_BINARY_DIR}/lib/

[PATCH] D132415: [LLDB] Add data formatter for std::coroutine_handle

2022-08-23 Thread Adrian Vogelsgesang via Phabricator via cfe-commits
avogelsgesang updated this revision to Diff 454830.
avogelsgesang added a comment.

clang-format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132415

Files:
  clang/docs/tools/clang-formatted-files.txt
  lldb/packages/Python/lldbsuite/test/lldbtest.py
  lldb/source/Plugins/Language/CPlusPlus/CMakeLists.txt
  lldb/source/Plugins/Language/CPlusPlus/CPlusPlusLanguage.cpp
  lldb/source/Plugins/Language/CPlusPlus/Coroutines.cpp
  lldb/source/Plugins/Language/CPlusPlus/Coroutines.h
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/coroutine_handle/Makefile
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/coroutine_handle/TestCoroutineHandle.py
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/coroutine_handle/main.cpp

Index: lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/coroutine_handle/main.cpp
===
--- /dev/null
+++ lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/coroutine_handle/main.cpp
@@ -0,0 +1,36 @@
+#include 
+
+// `int_generator` is a stripped down, minimal coroutine generator
+// type.
+struct int_generator {
+  struct promise_type {
+int current_value = -1;
+
+auto get_return_object() {
+  return std::coroutine_handle::from_promise(*this);
+}
+auto initial_suspend() { return std::suspend_always(); }
+auto final_suspend() noexcept { return std::suspend_always(); }
+auto return_void() { return std::suspend_always(); }
+void unhandled_exception() { __builtin_unreachable(); }
+auto yield_value(int v) {
+  current_value = v;
+  return std::suspend_always();
+}
+  };
+
+  std::coroutine_handle hdl;
+
+  int_generator(std::coroutine_handle h) : hdl(h) {}
+  ~int_generator() { hdl.destroy(); }
+};
+
+int_generator my_generator_func() { co_yield 42; }
+
+int main() {
+  int_generator gen = my_generator_func();
+  std::coroutine_handle<> type_erased_hdl = gen.hdl;
+  gen.hdl.resume(); // Break at initial_suspend
+  gen.hdl.resume(); // Break after co_yield
+  // Break at final_suspend
+}
Index: lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/coroutine_handle/TestCoroutineHandle.py
===
--- /dev/null
+++ lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/coroutine_handle/TestCoroutineHandle.py
@@ -0,0 +1,75 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+
+
+import lldb
+from lldbsuite.test.decorators import *
+from lldbsuite.test.lldbtest import *
+from lldbsuite.test import lldbutil
+
+USE_LIBSTDCPP = "USE_LIBSTDCPP"
+USE_LIBCPP = "USE_LIBCPP"
+
+class TestCoroutineHandle(TestBase):
+def do_test(self, stdlib_type):
+"""Test std::coroutine_handle is displayed correctly."""
+self.build(dictionary={stdlib_type: "1"})
+
+test_generator_func_ptr_re = re.compile(
+r"^\(a.out`my_generator_func\(\) at main.cpp:[0-9]*\)$")
+
+lldbutil.run_to_source_breakpoint(self, '// Break at initial_suspend',
+lldb.SBFileSpec("main.cpp", False))
+# Check that we show the correct function pointers and the `promise`. 
+self.expect_expr("gen.hdl",
+result_summary=re.compile("^coro frame = 0x[0-9a-f]*$"),
+result_children=[
+ValueCheck(name="resume", summary = test_generator_func_ptr_re),
+ValueCheck(name="destroy", summary = test_generator_func_ptr_re),
+ValueCheck(name="promise", children=[
+ValueCheck(name="current_value", value = "-1"),
+])
+])
+# For type-erased `coroutine_handle<>` we are missing the `promise`
+# but still show `resume` and `destroy`.
+self.expect_expr("type_erased_hdl",
+result_summary=re.compile("^coro frame = 0x[0-9a-f]*$"),
+result_children=[
+ValueCheck(name="resume", summary = test_generator_func_ptr_re),
+ValueCheck(name="destroy", summary = test_generator_func_ptr_re),
+])
+
+lldbutil.run_to_source_breakpoint(self, '// Break after co_yield',
+lldb.SBFileSpec("main.cpp", False))
+# We correctly show the updated value inside `prommise.current_value`.
+self.expect_expr("gen.hdl",
+result_children=[
+ValueCheck(name="resume", summary = test_generator_func_ptr_re),
+ValueCheck(name="destroy", summary = test_generator_func_ptr_re),
+ValueCheck(name="promise", children=[
+ValueCheck(name="current_value", value = "42"),
+])
+])
+
+lldbutil.run_to_source_breakpoint(self, '// Break at final_suspend',
+lldb.SBFileSpec("ma

[PATCH] D132324: [RFC] Remove support for building libc++ with `LLVM_ENABLE_PROJECTS`

2022-08-23 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D132324#3742605 , @ldionne wrote:

> This sucks, but I'm going to revert this series of patches. This is getting 
> somewhat out of hands and I feel that we're rushing to fix all kinds of 
> issues in various directions. I'm going to revert the following patches, in 
> this order:
>
> 1. 952f90b72b35 
>  [CMake] 
> Weaken 176db3b3ab25ff8a9b2405f50ef5a8bd9304a6d5 
> 
> 2. e6a0800532bb 
>  
> [libcxxabi][cmake] Allow building without libcxx again
> 3. 176db3b3ab25 
>  [RFC] 
> Remove support for building C++ with `LLVM_ENABLE_PROJECTS`
>
> Otherwise:
>
> - I also think we don't want to move forward with D132411 
>  -- it's going against this transition.
> - https://reviews.llvm.org/rZORG3a209ca6c1b9 sounds like a good change we'd 
> need to make no matter what, so that's great.
> - D132454  seems like a good change 
> regardless of this series of patches.
>
> I think that's the whole set of changes/reviews associated to this in the 
> past few days. If I've missed anything, please let me know ASAP.
>
> This will have been extremely useful as a way to shake out places where the 
> deprecated `LLVM_ENABLE_PROJECTS` build is still being used for 
> libc++/libc++abi. However, we should take the time to fix these places first 
> before landing the actual breaking change, otherwise things become too 
> unstable and we're rushed into making potentially poor decisions.
>
> Concretely, as an action item to move this transition forward, I will:
>
> 1. Grep for places where we still use `LLVM_ENABLE_PROJECTS` for libc++ and 
> libc++abi in the LLVM monorepo
> 2. Do the same in the llvm-zorg repo
> 3. Do the same in our downstream bots (if other folks see this because of 
> downstream breakage in their forks, be proactive and do this too, or you will 
> get broken in the future!)
> 4. Re-land a patch that turns the `WARNING` into a `FATAL_ERROR`, and just 
> that. Watch for more breakage and try fixing it iteratively.
> 5. Once we have `FATAL_ERROR` in place and things are green, we can land the 
> rest of this patch (plus a few other things I had locally) to actually remove 
> support for `LLVM_ENABLE_PROJECTS` with libc++/libc++abi.

Thank you @ldionne -- I think this plan of action makes sense to me. The 
disruption from reverts is unfortunate, but I think it's better to take a clean 
run at this once we have everything lined up and ready in the other projects.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132324

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


[PATCH] D132316: [CMake] `${LLVM_BINARY_DIR}/lib(${LLVM_LIBDIR_SUFFIX})?` -> `${LLVM_LIBRARY_DIR}`

2022-08-23 Thread John Ericson via Phabricator via cfe-commits
Ericson2314 marked an inline comment as done.
Ericson2314 added inline comments.



Comment at: llvm/tools/llvm-shlib/CMakeLists.txt:91
 
   set(LIB_DIR ${LLVM_BINARY_DIR}/${CMAKE_CFG_INTDIR}/lib${LLVM_LIBDIR_SUFFIX})
   set(LIB_NAME ${LIB_DIR}/${CMAKE_SHARED_LIBRARY_PREFIX}LLVM)

sebastian-ne wrote:
> Should this be `set(LIB_DIR ${LLVM_LIBRARY_DIR})`?
I am not sure what is up with `CMAKE_CFG_INTDIR`, so I rather leave that for a 
later revision.



Comment at: llvm/tools/llvm-shlib/CMakeLists.txt:139
   foreach(lib ${LIB_NAMES})
 list(APPEND FULL_LIB_NAMES 
${LLVM_BINARY_DIR}/${CMAKE_CFG_INTDIR}/lib/${lib}.lib)
   endforeach()

sebastian-ne wrote:
> This should probably use LLVM_LIBRARY_DIR as well.
Ditto, rather tackle things with `CMAKE_CFG_INTDIR` separately.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132316

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


[PATCH] D132473: [Docs][OpenCL][SPIR-V] Release 15 notes for Clang

2022-08-23 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia created this revision.
Anastasia added a reviewer: svenvh.
Herald added subscribers: ebevhan, yaxunl.
Herald added a project: All.
Anastasia requested review of this revision.

Added list of functional changes to release notes.


https://reviews.llvm.org/D132473

Files:
  clang/docs/ReleaseNotes.rst


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -566,10 +566,18 @@
 Objective-C Language Changes in Clang
 -
 
-OpenCL C Language Changes in Clang
---
-
-...
+OpenCL Kernel Language Changes in Clang
+---
+
+- Improved/fixed misc issues in the builtin function support and diagnostics.
+- Improved diagnostics for unknown extension pragma, subgroup functions and
+  implicit function prototype.
+- Added `-cl-ext` flag to the Clang driver to toggle extensions/features
+  compiled for.
+- Added `cl_khr_subgroup_rotate` extension.
+- Removed some `printf` and `hostcall` related diagnostics when compiling for
+  AMDGPU.
+- Fixed alignment of pointer types in kernel arguments.
 
 ABI Changes in Clang
 
@@ -660,6 +668,12 @@
   Operations found in the :ref:`Clang Language Extensions `
   document.
 
+SPIR-V Support in Clang
+---
+
+- Added flag `-fintegrated-objemitter` to enable use of experimental integrated
+  LLVM backend when generating SPIR-V binary.
+
 Floating Point Support in Clang
 ---
 


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -566,10 +566,18 @@
 Objective-C Language Changes in Clang
 -
 
-OpenCL C Language Changes in Clang
---
-
-...
+OpenCL Kernel Language Changes in Clang
+---
+
+- Improved/fixed misc issues in the builtin function support and diagnostics.
+- Improved diagnostics for unknown extension pragma, subgroup functions and
+  implicit function prototype.
+- Added `-cl-ext` flag to the Clang driver to toggle extensions/features
+  compiled for.
+- Added `cl_khr_subgroup_rotate` extension.
+- Removed some `printf` and `hostcall` related diagnostics when compiling for
+  AMDGPU.
+- Fixed alignment of pointer types in kernel arguments.
 
 ABI Changes in Clang
 
@@ -660,6 +668,12 @@
   Operations found in the :ref:`Clang Language Extensions `
   document.
 
+SPIR-V Support in Clang
+---
+
+- Added flag `-fintegrated-objemitter` to enable use of experimental integrated
+  LLVM backend when generating SPIR-V binary.
+
 Floating Point Support in Clang
 ---
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132473: [Docs][OpenCL][SPIR-V] Release 15 notes for Clang

2022-08-23 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

@svenvh as you made quite a lot of changes in the headers feel free to expand 
the description if you feel we should document some of those in more detail.


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

https://reviews.llvm.org/D132473

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


[PATCH] D128619: [Clang] Implement P0848 (Conditionally Trivial Special Member Functions)

2022-08-23 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM, thank you for this!!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128619

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


[clang] cd24120 - [clang] Remove a FIXME that we can't fix

2022-08-23 Thread Nico Weber via cfe-commits

Author: Nico Weber
Date: 2022-08-23T10:12:52-04:00
New Revision: cd24120c9d9544b202641fbff46be38175bb2470

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

LOG: [clang] Remove a FIXME that we can't fix

I added this recently, but it looks like several tests very intentionally
check that `-mios-version-min=foo --target=x86_64-apple-ios` does simulator
builds. So we can't easily remove this hack, even though it makes little
sense in an arm mac world. (Here, you _have_ to say
`-mios-simulator-version-min=` or `--target=arm64-apple-ios-simulator`.)

The tests that check this:
  Clang :: Driver/darwin-ld.c
  Clang :: Driver/darwin-simulator-macro.c
  Clang :: Driver/darwin-version.c

No behavior change.

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 2a581a17bd09..c2a344d241a9 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2241,7 +2241,6 @@ void Darwin::AddDeploymentTarget(DerivedArgList &Args) 
const {
 
   DarwinEnvironmentKind Environment = OSTarget->getEnvironment();
   // Recognize iOS targets with an x86 architecture as the iOS simulator.
-  // FIXME: Remove this.
   if (Environment == NativeEnvironment && Platform != MacOS &&
   Platform != DriverKit && OSTarget->canInferSimulatorFromArch() &&
   getTriple().isX86())



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


[PATCH] D132400: [clang] Remove a FIXME that we can't fix

2022-08-23 Thread Nico Weber via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGcd24120c9d95: [clang] Remove a FIXME that we can't fix 
(authored by thakis).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132400

Files:
  clang/lib/Driver/ToolChains/Darwin.cpp


Index: clang/lib/Driver/ToolChains/Darwin.cpp
===
--- clang/lib/Driver/ToolChains/Darwin.cpp
+++ clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2241,7 +2241,6 @@
 
   DarwinEnvironmentKind Environment = OSTarget->getEnvironment();
   // Recognize iOS targets with an x86 architecture as the iOS simulator.
-  // FIXME: Remove this.
   if (Environment == NativeEnvironment && Platform != MacOS &&
   Platform != DriverKit && OSTarget->canInferSimulatorFromArch() &&
   getTriple().isX86())


Index: clang/lib/Driver/ToolChains/Darwin.cpp
===
--- clang/lib/Driver/ToolChains/Darwin.cpp
+++ clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2241,7 +2241,6 @@
 
   DarwinEnvironmentKind Environment = OSTarget->getEnvironment();
   // Recognize iOS targets with an x86 architecture as the iOS simulator.
-  // FIXME: Remove this.
   if (Environment == NativeEnvironment && Platform != MacOS &&
   Platform != DriverKit && OSTarget->canInferSimulatorFromArch() &&
   getTriple().isX86())
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132400: [clang] Remove a FIXME that we can't fix

2022-08-23 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Thanks, fixed commit message.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132400

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


[PATCH] D132316: [CMake] `${LLVM_BINARY_DIR}/lib(${LLVM_LIBDIR_SUFFIX})?` -> `${LLVM_LIBRARY_DIR}`

2022-08-23 Thread Sebastian Neubauer via Phabricator via cfe-commits
sebastian-ne added inline comments.



Comment at: llvm/tools/llvm-shlib/CMakeLists.txt:91
 
   set(LIB_DIR ${LLVM_BINARY_DIR}/${CMAKE_CFG_INTDIR}/lib${LLVM_LIBDIR_SUFFIX})
   set(LIB_NAME ${LIB_DIR}/${CMAKE_SHARED_LIBRARY_PREFIX}LLVM)

Ericson2314 wrote:
> sebastian-ne wrote:
> > Should this be `set(LIB_DIR ${LLVM_LIBRARY_DIR})`?
> I am not sure what is up with `CMAKE_CFG_INTDIR`, so I rather leave that for 
> a later revision.
`LLVM_LIBRARY_DIR` includes `CMAKE_CFG_INTDIR` as it’s set through
```
set(LLVM_LIBRARY_OUTPUT_INTDIR 
${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/lib${LLVM_LIBDIR_SUFFIX})
set(LLVM_LIBRARY_DIR  ${LLVM_LIBRARY_OUTPUT_INTDIR})
```

As far as I understand, `CMAKE_CFG_INTDIR` is set to `.`, unless one does a 
multi-config build, i.e. one build directory for debug and release builds. 
multi-config builds are the default when creating Visual Studio solutions and 
ninja supports multi-config builds since some time (rather recently).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132316

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


[PATCH] D132324: [RFC] Remove support for building libc++ with `LLVM_ENABLE_PROJECTS`

2022-08-23 Thread John Ericson via Phabricator via cfe-commits
Ericson2314 added a comment.

That sounds good to me too.

Sorry I did unquestionably jump the gun here --- I suppose I was surprised to 
get a fairly simple approval when I put on the `[RFC]`, and thought "hmm, maybe 
this isn't so controversial as I feared because indeed the deprecation cycle 
has been so thorough", but then again the simple approval was probably 
predicated on the `[RFC]` indicating I would wait long!

> I also think we don't want to move forward with D132411 
>  -- it's going against this transition.

I would like to discuss some of this sort of thing so more, but better to do 
that on the the discourse than my shoddy commits that need reverting!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132324

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


[clang] 0565e65 - [clang/test] Correctly specify simulator env in target flag in fsanitize.c

2022-08-23 Thread Nico Weber via cfe-commits

Author: Nico Weber
Date: 2022-08-23T10:13:51-04:00
New Revision: 0565e65a69676a75a9da89c35d2ceda2ef4d21f7

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

LOG: [clang/test] Correctly specify simulator env in target flag in fsanitize.c

Putting "simulator" in the `-target` flag requires putting it in the
"environment" part of the triple, which is the 4th `-`-separated component.

Some places in the tests currently use "iossimulator" which puts it in the
OS field. The triple parsing code in llvm::Triple uses startswith("ios")
in parseOS(), so that successfully sets the OS to "iOS", and all these
triples use an intel arch, and iOS + intel triple implicitly make the
driver convert the environment to "simulator", so this happened to work --
but it led to the somewhat strange "simulator-simulator" in the diag
in the test.

No behavior change.

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

Added: 


Modified: 
clang/test/Driver/fsanitize.c

Removed: 




diff  --git a/clang/test/Driver/fsanitize.c b/clang/test/Driver/fsanitize.c
index d7fbeaa8c6f1..d496f48d8560 100644
--- a/clang/test/Driver/fsanitize.c
+++ b/clang/test/Driver/fsanitize.c
@@ -465,10 +465,10 @@
 // RUN: %clang -target arm64-apple-macos -fsanitize=thread %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-TSAN-ARM64-MACOS
 // CHECK-TSAN-ARM64-MACOS-NOT: unsupported option
 
-// RUN: %clang -target x86_64-apple-iossimulator -fsanitize=thread %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-X86-64-IOSSIMULATOR
+// RUN: %clang -target x86_64-apple-ios-simulator -fsanitize=thread %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-X86-64-IOSSIMULATOR
 // CHECK-TSAN-X86-64-IOSSIMULATOR-NOT: unsupported option
 
-// RUN: %clang -target x86_64-apple-tvossimulator -fsanitize=thread %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-X86-64-TVOSSIMULATOR
+// RUN: %clang -target x86_64-apple-tvos-simulator -fsanitize=thread %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-X86-64-TVOSSIMULATOR
 // CHECK-TSAN-X86-64-TVOSSIMULATOR-NOT: unsupported option
 
 // RUN: %clang -target i386-apple-darwin -fsanitize=thread %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-TSAN-I386-DARWIN
@@ -477,11 +477,11 @@
 // RUN: %clang -target arm-apple-ios -fsanitize=thread %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-TSAN-ARM-IOS
 // CHECK-TSAN-ARM-IOS: unsupported option '-fsanitize=thread' for target 
'arm-apple-ios'
 
-// RUN: %clang -target i386-apple-iossimulator -fsanitize=thread %s -### 2>&1 
| FileCheck %s --check-prefix=CHECK-TSAN-I386-IOSSIMULATOR
-// CHECK-TSAN-I386-IOSSIMULATOR: unsupported option '-fsanitize=thread' for 
target 'i386-apple-iossimulator-simulator'
+// RUN: %clang -target i386-apple-ios-simulator -fsanitize=thread %s -### 2>&1 
| FileCheck %s --check-prefix=CHECK-TSAN-I386-IOSSIMULATOR
+// CHECK-TSAN-I386-IOSSIMULATOR: unsupported option '-fsanitize=thread' for 
target 'i386-apple-ios-simulator'
 
-// RUN: %clang -target i386-apple-tvossimulator -fsanitize=thread %s -### 2>&1 
| FileCheck %s --check-prefix=CHECK-TSAN-I386-TVOSSIMULATOR
-// CHECK-TSAN-I386-TVOSSIMULATOR: unsupported option '-fsanitize=thread' for 
target 'i386-apple-tvossimulator-simulator'
+// RUN: %clang -target i386-apple-tvos-simulator -fsanitize=thread %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-I386-TVOSSIMULATOR
+// CHECK-TSAN-I386-TVOSSIMULATOR: unsupported option '-fsanitize=thread' for 
target 'i386-apple-tvos-simulator'
 
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=thread 
-fsanitize-thread-memory-access %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-TSAN-MEMORY-ACCESS
 // CHECK-TSAN-MEMORY-ACCESS-NOT: -cc1{{.*}}tsan-instrument-memory-accesses=0
@@ -552,10 +552,10 @@
 // RUN: %clang -target x86_64-apple-darwin -fsanitize=leak %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-LSAN-X86-64-DARWIN
 // CHECK-LSAN-X86-64-DARWIN-NOT: unsupported option
 
-// RUN: %clang -target x86_64-apple-iossimulator -fsanitize=leak %s -### 2>&1 
| FileCheck %s --check-prefix=CHECK-LSAN-X86-64-IOSSIMULATOR
+// RUN: %clang -target x86_64-apple-ios-simulator -fsanitize=leak %s -### 2>&1 
| FileCheck %s --check-prefix=CHECK-LSAN-X86-64-IOSSIMULATOR
 // CHECK-LSAN-X86-64-IOSSIMULATOR-NOT: unsupported option
 
-// RUN: %clang -target x86_64-apple-tvossimulator -fsanitize=leak %s -### 2>&1 
| FileCheck %s --check-prefix=CHECK-LSAN-X86-64-TVOSSIMULATOR
+// RUN: %clang -target x86_64-apple-tvos-simulator -fsanitize=leak %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-X86-64-TVOSSIMULATOR
 // CHECK-LSAN-X86-64-TVOSSIMULATOR-NOT: unsupported option
 
 // RUN: %clang -target i386-apple-darwin -fsanitize=leak %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-LSAN-I386-DARWIN
@@ -564,10 +564,10 @@
 // RUN: %clang -ta

[PATCH] D132399: [clang/test] Correctly specify simulator env in target flag in fsanitize.c

2022-08-23 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Thanks!


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

https://reviews.llvm.org/D132399

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


[PATCH] D132399: [clang/test] Correctly specify simulator env in target flag in fsanitize.c

2022-08-23 Thread Nico Weber via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0565e65a6967: [clang/test] Correctly specify simulator env 
in target flag in fsanitize.c (authored by thakis).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132399

Files:
  clang/test/Driver/fsanitize.c


Index: clang/test/Driver/fsanitize.c
===
--- clang/test/Driver/fsanitize.c
+++ clang/test/Driver/fsanitize.c
@@ -465,10 +465,10 @@
 // RUN: %clang -target arm64-apple-macos -fsanitize=thread %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-TSAN-ARM64-MACOS
 // CHECK-TSAN-ARM64-MACOS-NOT: unsupported option
 
-// RUN: %clang -target x86_64-apple-iossimulator -fsanitize=thread %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-X86-64-IOSSIMULATOR
+// RUN: %clang -target x86_64-apple-ios-simulator -fsanitize=thread %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-X86-64-IOSSIMULATOR
 // CHECK-TSAN-X86-64-IOSSIMULATOR-NOT: unsupported option
 
-// RUN: %clang -target x86_64-apple-tvossimulator -fsanitize=thread %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-X86-64-TVOSSIMULATOR
+// RUN: %clang -target x86_64-apple-tvos-simulator -fsanitize=thread %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-X86-64-TVOSSIMULATOR
 // CHECK-TSAN-X86-64-TVOSSIMULATOR-NOT: unsupported option
 
 // RUN: %clang -target i386-apple-darwin -fsanitize=thread %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-TSAN-I386-DARWIN
@@ -477,11 +477,11 @@
 // RUN: %clang -target arm-apple-ios -fsanitize=thread %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-TSAN-ARM-IOS
 // CHECK-TSAN-ARM-IOS: unsupported option '-fsanitize=thread' for target 
'arm-apple-ios'
 
-// RUN: %clang -target i386-apple-iossimulator -fsanitize=thread %s -### 2>&1 
| FileCheck %s --check-prefix=CHECK-TSAN-I386-IOSSIMULATOR
-// CHECK-TSAN-I386-IOSSIMULATOR: unsupported option '-fsanitize=thread' for 
target 'i386-apple-iossimulator-simulator'
+// RUN: %clang -target i386-apple-ios-simulator -fsanitize=thread %s -### 2>&1 
| FileCheck %s --check-prefix=CHECK-TSAN-I386-IOSSIMULATOR
+// CHECK-TSAN-I386-IOSSIMULATOR: unsupported option '-fsanitize=thread' for 
target 'i386-apple-ios-simulator'
 
-// RUN: %clang -target i386-apple-tvossimulator -fsanitize=thread %s -### 2>&1 
| FileCheck %s --check-prefix=CHECK-TSAN-I386-TVOSSIMULATOR
-// CHECK-TSAN-I386-TVOSSIMULATOR: unsupported option '-fsanitize=thread' for 
target 'i386-apple-tvossimulator-simulator'
+// RUN: %clang -target i386-apple-tvos-simulator -fsanitize=thread %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-I386-TVOSSIMULATOR
+// CHECK-TSAN-I386-TVOSSIMULATOR: unsupported option '-fsanitize=thread' for 
target 'i386-apple-tvos-simulator'
 
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=thread 
-fsanitize-thread-memory-access %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-TSAN-MEMORY-ACCESS
 // CHECK-TSAN-MEMORY-ACCESS-NOT: -cc1{{.*}}tsan-instrument-memory-accesses=0
@@ -552,10 +552,10 @@
 // RUN: %clang -target x86_64-apple-darwin -fsanitize=leak %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-LSAN-X86-64-DARWIN
 // CHECK-LSAN-X86-64-DARWIN-NOT: unsupported option
 
-// RUN: %clang -target x86_64-apple-iossimulator -fsanitize=leak %s -### 2>&1 
| FileCheck %s --check-prefix=CHECK-LSAN-X86-64-IOSSIMULATOR
+// RUN: %clang -target x86_64-apple-ios-simulator -fsanitize=leak %s -### 2>&1 
| FileCheck %s --check-prefix=CHECK-LSAN-X86-64-IOSSIMULATOR
 // CHECK-LSAN-X86-64-IOSSIMULATOR-NOT: unsupported option
 
-// RUN: %clang -target x86_64-apple-tvossimulator -fsanitize=leak %s -### 2>&1 
| FileCheck %s --check-prefix=CHECK-LSAN-X86-64-TVOSSIMULATOR
+// RUN: %clang -target x86_64-apple-tvos-simulator -fsanitize=leak %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-X86-64-TVOSSIMULATOR
 // CHECK-LSAN-X86-64-TVOSSIMULATOR-NOT: unsupported option
 
 // RUN: %clang -target i386-apple-darwin -fsanitize=leak %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-LSAN-I386-DARWIN
@@ -564,10 +564,10 @@
 // RUN: %clang -target arm-apple-ios -fsanitize=leak %s -### 2>&1 | FileCheck 
%s --check-prefix=CHECK-LSAN-ARM-IOS
 // CHECK-LSAN-ARM-IOS-NOT: unsupported option
 
-// RUN: %clang -target i386-apple-iossimulator -fsanitize=leak %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-LSAN-I386-IOSSIMULATOR
+// RUN: %clang -target i386-apple-ios-simulator -fsanitize=leak %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-LSAN-I386-IOSSIMULATOR
 // CHECK-LSAN-I386-IOSSIMULATOR-NOT: unsupported option
 
-// RUN: %clang -target i386-apple-tvossimulator -fsanitize=leak %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-LSAN-I386-TVOSSIMULATOR
+// RUN: %clang -target i386-apple-tvos-simulator -fsanitize=leak %s -### 2>&1 
| FileCheck %s --check-prefix=CHECK-LSAN-I386-TVOSSIMULATOR
 // CHECK-LSAN-I386-TVOSSIMULATOR-NOT: unsup

[PATCH] D132414: [Clang] follow-up D128745, use ClangABICompat15 instead of ClangABICompat14

2022-08-23 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

Good catch @royjacobson on the ABI version number needing to be bumped! LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132414

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


[PATCH] D132461: [clang-tidy] Add cppcoreguidelines-avoid-do-while check

2022-08-23 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst:6
+
+This check warns when using ``do-while`` loops. They are less readable than
+plain ``while`` loops since the termination condition is at the end and the

Please synchronize first statement with Release Notes. `This check` us usually 
omitted.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst:21
+
+The check implements
+`rule ES.75 of C++ Core Guidelines 
`_.

Links usually placed at the end.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst:41
+
+  Defaults to ``false``.

Please use single back-ticks for options values.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132461

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


[PATCH] D132473: [Docs][OpenCL][SPIR-V] Release 15 notes for Clang

2022-08-23 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia updated this revision to Diff 454838.
Anastasia added a comment.

Minor formatting changes


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

https://reviews.llvm.org/D132473

Files:
  clang/docs/ReleaseNotes.rst


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -566,10 +566,18 @@
 Objective-C Language Changes in Clang
 -
 
-OpenCL C Language Changes in Clang
---
-
-...
+OpenCL Kernel Language Changes in Clang
+---
+
+- Improved/fixed misc issues in the builtin function support and diagnostics.
+- Improved diagnostics for unknown extension pragma, subgroup functions and
+  implicit function prototype.
+- Added ``-cl-ext`` flag to the Clang driver to toggle extensions/features
+  compiled for.
+- Added ``cl_khr_subgroup_rotate`` extension.
+- Removed some ``printf`` and ``hostcall`` related diagnostics when compiling
+  for AMDGPU.
+- Fixed alignment of pointer types in kernel arguments.
 
 ABI Changes in Clang
 
@@ -660,6 +668,12 @@
   Operations found in the :ref:`Clang Language Extensions `
   document.
 
+SPIR-V Support in Clang
+---
+
+- Added flag ``-fintegrated-objemitter`` to enable use of experimental 
integrated
+  LLVM backend when generating SPIR-V binary.
+
 Floating Point Support in Clang
 ---
 


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -566,10 +566,18 @@
 Objective-C Language Changes in Clang
 -
 
-OpenCL C Language Changes in Clang
---
-
-...
+OpenCL Kernel Language Changes in Clang
+---
+
+- Improved/fixed misc issues in the builtin function support and diagnostics.
+- Improved diagnostics for unknown extension pragma, subgroup functions and
+  implicit function prototype.
+- Added ``-cl-ext`` flag to the Clang driver to toggle extensions/features
+  compiled for.
+- Added ``cl_khr_subgroup_rotate`` extension.
+- Removed some ``printf`` and ``hostcall`` related diagnostics when compiling
+  for AMDGPU.
+- Fixed alignment of pointer types in kernel arguments.
 
 ABI Changes in Clang
 
@@ -660,6 +668,12 @@
   Operations found in the :ref:`Clang Language Extensions `
   document.
 
+SPIR-V Support in Clang
+---
+
+- Added flag ``-fintegrated-objemitter`` to enable use of experimental integrated
+  LLVM backend when generating SPIR-V binary.
+
 Floating Point Support in Clang
 ---
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 2c923b8 - [clang-cl] Expose the /volatile:{iso, ms} choice via _ISO_VOLATILE

2022-08-23 Thread David Majnemer via cfe-commits

Author: David Majnemer
Date: 2022-08-23T14:29:52Z
New Revision: 2c923b88631cda41cbddf58a13ccfb5c04a2fc3c

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

LOG: [clang-cl] Expose the /volatile:{iso,ms} choice via _ISO_VOLATILE

MSVC allows interpreting volatile loads and stores, when combined with
/volatile:iso, as having acquire/release semantics. MSVC also exposes a
define, _ISO_VOLATILE, which allows users to enquire if this feature is
enabled or disabled.

Added: 


Modified: 
clang/include/clang/Basic/CodeGenOptions.def
clang/include/clang/Basic/LangOptions.def
clang/include/clang/Driver/Options.td
clang/lib/Basic/Targets/OSTargets.cpp
clang/lib/CodeGen/CGAtomic.cpp
clang/test/Preprocessor/predefined-win-macros.c

Removed: 




diff  --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index 0f35420f43133..87c75bb98d433 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -173,7 +173,6 @@ CODEGENOPT(IncrementalLinkerCompatible, 1, 0) ///< Emit an 
object file which can
   ///< linker.
 CODEGENOPT(MergeAllConstants , 1, 1) ///< Merge identical constants.
 CODEGENOPT(MergeFunctions, 1, 0) ///< Set when -fmerge-functions is 
enabled.
-CODEGENOPT(MSVolatile, 1, 0) ///< Set when /volatile:ms is enabled.
 CODEGENOPT(NoCommon  , 1, 0) ///< Set when -fno-common or C++ is 
enabled.
 CODEGENOPT(NoDwarfDirectoryAsm , 1, 0) ///< Set when -fno-dwarf-directory-asm 
is
///< enabled.

diff  --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index ad366821f3cbf..4f3f6fc9da8c0 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -148,6 +148,7 @@ LANGOPT(TraditionalCPP, 1, 0, "traditional CPP 
emulation")
 LANGOPT(RTTI  , 1, 1, "run-time type information")
 LANGOPT(RTTIData  , 1, 1, "emit run-time type information data")
 LANGOPT(MSBitfields   , 1, 0, "Microsoft-compatible structure layout")
+LANGOPT(MSVolatile, 1, 0, "Microsoft-compatible volatile loads and 
stores")
 LANGOPT(Freestanding, 1, 0, "freestanding implementation")
 LANGOPT(NoBuiltin , 1, 0, "disable builtin functions")
 LANGOPT(NoMathBuiltin , 1, 0, "disable math builtin functions")

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index aadd516cf6209..ec5f553f64584 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2204,7 +2204,7 @@ defm asm_blocks : BoolFOption<"asm-blocks",
   LangOpts<"AsmBlocks">, Default,
   PosFlag, NegFlag>;
 def fms_volatile : Flag<["-"], "fms-volatile">, Group, 
Flags<[CC1Option]>,
-  MarshallingInfoFlag>;
+  MarshallingInfoFlag>;
 def fmsc_version : Joined<["-"], "fmsc-version=">, Group, 
Flags<[NoXarchOption, CoreOption]>,
   HelpText<"Microsoft compiler version number to report in _MSC_VER (0 = don't 
define it (default))">;
 def fms_compatibility_version

diff  --git a/clang/lib/Basic/Targets/OSTargets.cpp 
b/clang/lib/Basic/Targets/OSTargets.cpp
index 5c734024897cb..d11b9f5dbba5a 100644
--- a/clang/lib/Basic/Targets/OSTargets.cpp
+++ b/clang/lib/Basic/Targets/OSTargets.cpp
@@ -263,6 +263,9 @@ static void addVisualCDefines(const LangOptions &Opts, 
MacroBuilder &Builder) {
 }
   }
 
+  if (!Opts.MSVolatile)
+Builder.defineMacro("_ISO_VOLATILE");
+
   if (Opts.Kernel)
 Builder.defineMacro("_KERNEL_MODE");
 

diff  --git a/clang/lib/CodeGen/CGAtomic.cpp b/clang/lib/CodeGen/CGAtomic.cpp
index ccc66bc28605f..8ef95bb808468 100644
--- a/clang/lib/CodeGen/CGAtomic.cpp
+++ b/clang/lib/CodeGen/CGAtomic.cpp
@@ -1594,7 +1594,7 @@ llvm::Value 
*AtomicInfo::EmitAtomicLoadOp(llvm::AtomicOrdering AO,
 /// we are operating under /volatile:ms *and* the LValue itself is volatile and
 /// performing such an operation can be performed without a libcall.
 bool CodeGenFunction::LValueIsSuitableForInlineAtomic(LValue LV) {
-  if (!CGM.getCodeGenOpts().MSVolatile) return false;
+  if (!CGM.getLangOpts().MSVolatile) return false;
   AtomicInfo AI(*this, LV);
   bool IsVolatile = LV.isVolatile() || hasVolatileMember(LV.getType());
   // An atomic is inline if we don't need to use a libcall.

diff  --git a/clang/test/Preprocessor/predefined-win-macros.c 
b/clang/test/Preprocessor/predefined-win-macros.c
index df43ae59cef42..f402ce91838d6 100644
--- a/clang/test/Preprocessor/predefined-win-macros.c
+++ b/clang/test/Preprocessor/predefined-win-macros.c
@@ -5,6 +5,7 @@
 // RUN: %clang_cc1 %s -x c++ -E -dM -triple x86_64-pc-win32 -fms-extensions 
-fms-compati

[PATCH] D132248: [CUDA][OpenMP] Fix the new driver crashing on multiple device-only outputs

2022-08-23 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 454839.
jhuber6 added a comment.

Adding HIP test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132248

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cuda-bindings.cu
  clang/test/Driver/hip-binding.hip

Index: clang/test/Driver/hip-binding.hip
===
--- clang/test/Driver/hip-binding.hip
+++ clang/test/Driver/hip-binding.hip
@@ -51,3 +51,20 @@
 
 // NORDC-NOT: offload bundler
 // NORDC: # "x86_64-unknown-linux-gnu" - "GNU::Linker", inputs: ["{{.*o}}"], output: "a.out"
+
+//
+// Check to make sure we can generate multiple outputs for device-only
+// compilation and fail with '-o'.
+//
+// RUN: %clang -### -target x86_64-linux-gnu --offload-new-driver -ccc-print-bindings \
+// RUN:--offload-arch=gfx90a --offload-arch=gfx908 --offload-device-only -c %s 2>&1 \
+// RUN: | FileCheck -check-prefix=MULTI-D-ONLY %s
+//  MULTI-D-ONLY: # "amdgcn-amd-amdhsa" - "clang", inputs: ["[[INPUT:.+]]"], output: "[[GFX908:.+]]"
+// MULTI-D-ONLY-NEXT: # "amdgcn-amd-amdhsa" - "AMDGCN::Linker", inputs: ["[[GFX908]]"], output: "[[GFX908_OUT:.+]]"
+// MULTI-D-ONLY-NEXT: # "amdgcn-amd-amdhsa" - "clang", inputs: ["[[INPUT]]"], output: "[[GFX90a:.+]]"
+// MULTI-D-ONLY-NEXT: # "amdgcn-amd-amdhsa" - "AMDGCN::Linker", inputs: ["[[GFX90a]]"], output: "[[GFX90a_OUT:.+]]"
+//
+// RUN: %clang -### -target x86_64-linux-gnu --offload-new-driver -ccc-print-bindings \
+// RUN:--offload-arch=gfx90a --offload-arch=gfx908 --offload-device-only -c -o %t %s 2>&1 \
+// RUN: | FileCheck -check-prefix=MULTI-D-ONLY-O %s
+// MULTI-D-ONLY-O: error: cannot specify -o when generating multiple output files
Index: clang/test/Driver/cuda-bindings.cu
===
--- clang/test/Driver/cuda-bindings.cu
+++ clang/test/Driver/cuda-bindings.cu
@@ -146,3 +146,20 @@
 // RUN:--cuda-gpu-arch=sm_52 --cuda-device-only -c -o foo.o %s 2>&1 \
 // RUN: | FileCheck -check-prefix=D_ONLY %s
 // D_ONLY: "foo.o"
+
+//
+// Check to make sure we can generate multiple outputs for device-only
+// compilation and fail with '-o'.
+//
+// RUN: %clang -### -target powerpc64le-ibm-linux-gnu --offload-new-driver -ccc-print-bindings \
+// RUN:--offload-arch=sm_70 --offload-arch=sm_52 --offload-device-only -c %s 2>&1 \
+// RUN: | FileCheck -check-prefix=MULTI-D-ONLY %s
+//  MULTI-D-ONLY: # "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT:.+]]"], output: "[[PTX_70:.+]]"
+// MULTI-D-ONLY-NEXT: # "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX_70]]"], output: "[[CUBIN_70:.+]]"
+// MULTI-D-ONLY-NEXT: # "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]"], output: "[[PTX_52:.+]]"
+// MULTI-D-ONLY-NEXT: # "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX_52]]"], output: "[[CUBIN_52:.+]]"
+//
+// RUN: %clang -### -target powerpc64le-ibm-linux-gnu --offload-new-driver -ccc-print-bindings \
+// RUN:--offload-arch=sm_70 --offload-arch=sm_52 --offload-device-only -c -o %t %s 2>&1 \
+// RUN: | FileCheck -check-prefix=MULTI-D-ONLY-O %s
+// MULTI-D-ONLY-O: error: cannot specify -o when generating multiple output files
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -4716,10 +4716,13 @@
   // we are also generating .o files. So we allow more than one output file in
   // this case as well.
   //
+  // OffloadClass of type TY_Nothing: device-only output will place many outputs
+  // into a single offloading action. We should count all inputs to the action
+  // as outputs.
   if (FinalOutput) {
 unsigned NumOutputs = 0;
 unsigned NumIfsOutputs = 0;
-for (const Action *A : C.getActions())
+for (const Action *A : C.getActions()) {
   if (A->getType() != types::TY_Nothing &&
   !(A->getKind() == Action::IfsMergeJobClass ||
 (A->getType() == clang::driver::types::TY_IFS_CPP &&
@@ -4728,6 +4731,10 @@
 (A->getKind() == Action::BindArchClass && A->getInputs().size() &&
  A->getInputs().front()->getKind() == Action::IfsMergeJobClass)))
 ++NumOutputs;
+  else if (A->getKind() == Action::OffloadClass &&
+   A->getType() == types::TY_Nothing)
+NumOutputs += A->size();
+}
 
 if (NumOutputs > 1) {
   Diag(clang::diag::err_drv_output_argument_with_multiple_files);
@@ -5265,20 +5272,21 @@
 //  \
 //Device Action 1  ---> OffloadAction -> Device Action 2
 //
-// For a) and b), we just return the job generated for the dependence. For
+// For a) and b), we just return the job generated for the dependences. For
 // c) and d) we override the current action with the host/device dependence
 // if the current toolchain is host/device 

[PATCH] D132461: [clang-tidy] Add cppcoreguidelines-avoid-do-while check

2022-08-23 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp updated this revision to Diff 454841.
carlosgalvezp marked 2 inline comments as done.
carlosgalvezp added a comment.

Address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132461

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidDoWhileCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidDoWhileCheck.h
  clang-tools-extra/clang-tidy/cppcoreguidelines/CMakeLists.txt
  clang-tools-extra/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-do-while.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-do-while.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-do-while.cpp
@@ -0,0 +1,70 @@
+// RUN: %check_clang_tidy -check-suffixes=DEFAULT   %s cppcoreguidelines-avoid-do-while %t
+// RUN: %check_clang_tidy -check-suffixes=ALLOW-WHILE-FALSE %s cppcoreguidelines-avoid-do-while %t -- -config='{CheckOptions: [{key: cppcoreguidelines-avoid-do-while.AllowWhileFalse, value: true}]}'
+
+#define FOO(x) \
+  do { \
+  } while (x != 0)
+
+#define BAR_0(x) \
+  do { \
+bar(x); \
+  } while (0)
+
+#define BAR_FALSE(x) \
+  do { \
+bar(x); \
+  } while (false)
+
+void bar(int);
+int baz();
+
+void foo()
+{
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used [cppcoreguidelines-avoid-do-while]
+do {
+
+} while(0);
+
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used [cppcoreguidelines-avoid-do-while]
+do {
+
+} while(false);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+3]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+int x1{0};
+do {
+  x1 = baz();
+} while (x1 > 0);
+
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+do {
+
+} while (x1 != 0);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+3]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+constexpr int x2{0};
+do {
+
+} while (x2);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+3]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+constexpr bool x3{false};
+do {
+
+} while (x3);
+
+// CHECK-MESSAGES-ALLOW-WHILE-FALSE: :[[@LINE+2]]:5: warning: do-while loops shall not be used
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+FOO(x1);
+
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+BAR_0(x1);
+
+// CHECK-MESSAGES-DEFAULT: :[[@LINE+1]]:5: warning: do-while loops shall not be used
+BAR_FALSE(x1);
+}
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -177,6 +177,7 @@
`concurrency-mt-unsafe `_,
`concurrency-thread-canceltype-asynchronous `_,
`cppcoreguidelines-avoid-const-or-ref-data-members `_,
+   `cppcoreguidelines-avoid-do-while `_,
`cppcoreguidelines-avoid-goto `_,
`cppcoreguidelines-avoid-non-const-global-variables `_,
`cppcoreguidelines-init-variables `_, "Yes"
Index: clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst
@@ -0,0 +1,40 @@
+.. title:: clang-tidy - cppcoreguidelines-avoid-do-while
+
+cppcoreguidelines-avoid-do-while
+
+
+Warns when using ``do-while`` loops. They are less readable than plain ``while``
+loops, since the termination condition is at the end and the condition is not
+checked prior to the first iteration. This can lead to subtle bugs.
+
+The check implements
+`rule ES.75 of C++ Core Guidelines `_.
+
+Examples:
+
+.. code-block:: c++
+
+  int x;
+  do {
+  std::cin >> x;
+  // ...
+  } while (x < 0);
+
+Options
+---
+
+.. option:: AllowWhileFalse
+
+  Allows having ``do-while`` loops where the condition is a literal ``false``
+  or ``0``. This cov

[PATCH] D132461: [clang-tidy] Add cppcoreguidelines-avoid-do-while check

2022-08-23 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added inline comments.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst:21
+
+The check implements
+`rule ES.75 of C++ Core Guidelines 
`_.

Eugene.Zelenko wrote:
> Links usually placed at the end.
I think having the link after the options would make it a bit disconnected. 
Instead I typically find Options at the very end, after the description.

See for example: 
https://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines/owning-memory.html

WDYT?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132461

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


[PATCH] D132461: [clang-tidy] Add cppcoreguidelines-avoid-do-while check

2022-08-23 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added a comment.

PS: @aaron.ballman I didn't add you as reviewer since you have expressed in the 
past that you'd prefer not to review C++ Core Guidelines patches. Let me know 
if that has changed :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132461

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


[PATCH] D132461: [clang-tidy] Add cppcoreguidelines-avoid-do-while check

2022-08-23 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added inline comments.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-do-while.rst:21
+
+The check implements
+`rule ES.75 of C++ Core Guidelines 
`_.

carlosgalvezp wrote:
> Eugene.Zelenko wrote:
> > Links usually placed at the end.
> I think having the link after the options would make it a bit disconnected. 
> Instead I typically find Options at the very end, after the description.
> 
> See for example: 
> https://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines/owning-memory.html
> 
> WDYT?
Also:
https://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines/no-malloc.html


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132461

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


[PATCH] D128113: Clang: fix AST representation of expanded template arguments.

2022-08-23 Thread joanahalili via Phabricator via cfe-commits
joanahalili added a comment.

F24241982: reproduction.cpp 

  clang -fsyntax-only -std=c++17  -fproc-stat-report 
-Wno-deprecated-declarations  -fsized-deallocation -Werror 
-Wno-deprecated-declarations  -Wno-inconsistent-missing-override 
-Wno-null-conversion -Wno-ignored-attributes  -Wno-defaulted-function-deleted 
-xc++ reproduction.cpp

This is the reproducer we managed to create for the memory increase.  As 
mentioned above we notice both a difference in memory and execution time. 
Clang version before this patch

- Memory: 8Gb
- Time: 32507 ms

Clang version with this patch:

- Memory: 10.5 Gb (1.5Gb increase)
- Time 63812 (almost double the previous compilation time).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128113

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


[PATCH] D132248: [CUDA][OpenMP] Fix the new driver crashing on multiple device-only outputs

2022-08-23 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl accepted this revision.
yaxunl added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132248

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


[PATCH] D132074: [OpenMP] Add option to assert no nested OpenMP parallelism on the GPU

2022-08-23 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 454845.
jhuber6 added a comment.

Fix missing `()` in assertion and accidentally deleting device libs addition.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132074

Files:
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/OpenMP/target_globals_codegen.cpp
  openmp/libomptarget/DeviceRTL/include/Configuration.h
  openmp/libomptarget/DeviceRTL/src/Configuration.cpp
  openmp/libomptarget/DeviceRTL/src/Parallelism.cpp

Index: openmp/libomptarget/DeviceRTL/src/Parallelism.cpp
===
--- openmp/libomptarget/DeviceRTL/src/Parallelism.cpp
+++ openmp/libomptarget/DeviceRTL/src/Parallelism.cpp
@@ -86,11 +86,16 @@
 
   uint32_t TId = mapping::getThreadIdInBlock();
 
+  // Assert the parallelism level is zero if disabled by the user.
+  ASSERT((config::mayUseNestedParallelism() || icv::Level == 0) &&
+ "nested parallelism while disabled");
+
   // Handle the serialized case first, same for SPMD/non-SPMD:
   // 1) if-clause(0)
-  // 2) nested parallel regions
-  // 3) parallel in task or other thread state inducing construct
-  if (OMP_UNLIKELY(!if_expr || icv::Level || state::HasThreadState)) {
+  // 2) parallel in task or other thread state inducing construct
+  // 3) nested parallel regions
+  if (OMP_UNLIKELY(!if_expr || state::HasThreadState ||
+   (config::mayUseNestedParallelism() && icv::Level))) {
 state::DateEnvironmentRAII DERAII(ident);
 ++icv::Level;
 invokeMicrotask(TId, 0, fn, args, nargs);
Index: openmp/libomptarget/DeviceRTL/src/Configuration.cpp
===
--- openmp/libomptarget/DeviceRTL/src/Configuration.cpp
+++ openmp/libomptarget/DeviceRTL/src/Configuration.cpp
@@ -23,6 +23,7 @@
 // defined by CGOpenMPRuntimeGPU
 extern uint32_t __omp_rtl_debug_kind;
 extern uint32_t __omp_rtl_assume_no_thread_state;
+extern uint32_t __omp_rtl_assume_no_nested_parallelism;
 
 // TODO: We want to change the name as soon as the old runtime is gone.
 // This variable should be visibile to the plugin so we override the default
@@ -52,4 +53,8 @@
 
 bool config::mayUseThreadStates() { return !__omp_rtl_assume_no_thread_state; }
 
+bool config::mayUseNestedParallelism() {
+  return !__omp_rtl_assume_no_nested_parallelism;
+}
+
 #pragma omp end declare target
Index: openmp/libomptarget/DeviceRTL/include/Configuration.h
===
--- openmp/libomptarget/DeviceRTL/include/Configuration.h
+++ openmp/libomptarget/DeviceRTL/include/Configuration.h
@@ -44,6 +44,10 @@
 /// explicitly disabled by the user.
 bool mayUseThreadStates();
 
+/// Indicates if this kernel may require data environments for nested
+/// parallelism, or if it was explicitly disabled by the user.
+bool mayUseNestedParallelism();
+
 } // namespace config
 } // namespace _OMP
 
Index: clang/test/OpenMP/target_globals_codegen.cpp
===
--- clang/test/OpenMP/target_globals_codegen.cpp
+++ clang/test/OpenMP/target_globals_codegen.cpp
@@ -7,6 +7,7 @@
 // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-assume-threads-oversubscription -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix=CHECK-THREADS
 // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-assume-teams-oversubscription -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix=CHECK-TEAMS
 // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-assume-no-thread-state -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix=CHECK-STATE
+// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-assume-no-nested-parallelism -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix=CHECK-NESTED
 // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-device -nogpulib -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix=CHECK-RUNTIME
 // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-assume-teams-oversubscription -fopenmp-is-device -o - | FileCheck %s --check-prefix=CHECK-RUNTIME
 // expected-no-diagnostics
@@ -19,36 +20,49 @@
 

[clang] 2e2caea - [Clang][OpenMP] Make copyin clause on combined and composite construct work (patch by Yuichiro Utsumi (utsumi.yuich...@fujitsu.com))

2022-08-23 Thread Alexey Bataev via cfe-commits

Author: utsumi
Date: 2022-08-23T07:58:35-07:00
New Revision: 2e2caea37f4b70568cec180e5af12ee532aba0af

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

LOG: [Clang][OpenMP] Make copyin clause on combined and composite construct 
work (patch by Yuichiro Utsumi (utsumi.yuich...@fujitsu.com))

Make copyin clause on the following constructs work.

- parallel for
- parallel for simd
- parallel sections

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

Patch by Yuichiro Utsumi (utsumi.yuich...@fujitsu.com)

Reviewed By: ABataev

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

Added: 
clang/test/OpenMP/parallel_copyin_combined_codegen.c
openmp/runtime/test/parallel/omp_parallel_copyin_combined.c

Modified: 
clang/lib/CodeGen/CGStmtOpenMP.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp 
b/clang/lib/CodeGen/CGStmtOpenMP.cpp
index 7398ea98e61b0..1ffee9b94e734 100644
--- a/clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -1593,6 +1593,19 @@ static void emitEmptyBoundParameters(CodeGenFunction &,
  const OMPExecutableDirective &,
  llvm::SmallVectorImpl &) {}
 
+static void emitOMPCopyinClause(CodeGenFunction &CGF,
+const OMPExecutableDirective &S) {
+  bool Copyins = CGF.EmitOMPCopyinClause(S);
+  if (Copyins) {
+// Emit implicit barrier to synchronize threads and avoid data races on
+// propagation master's thread values of threadprivate variables to local
+// instances of that variables of all other implicit threads.
+CGF.CGM.getOpenMPRuntime().emitBarrierCall(
+CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
+/*ForceSimpleCall=*/true);
+  }
+}
+
 Address CodeGenFunction::OMPBuilderCBHelpers::getAddressOfLocalVariable(
 CodeGenFunction &CGF, const VarDecl *VD) {
   CodeGenModule &CGM = CGF.CGM;
@@ -1774,16 +1787,8 @@ void CodeGenFunction::EmitOMPParallelDirective(const 
OMPParallelDirective &S) {
   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
 Action.Enter(CGF);
 OMPPrivateScope PrivateScope(CGF);
-bool Copyins = CGF.EmitOMPCopyinClause(S);
+emitOMPCopyinClause(CGF, S);
 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
-if (Copyins) {
-  // Emit implicit barrier to synchronize threads and avoid data races on
-  // propagation master's thread values of threadprivate variables to local
-  // instances of that variables of all other implicit threads.
-  CGF.CGM.getOpenMPRuntime().emitBarrierCall(
-  CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
-  /*ForceSimpleCall=*/true);
-}
 CGF.EmitOMPPrivateClause(S, PrivateScope);
 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
 (void)PrivateScope.Privatize();
@@ -4352,6 +4357,7 @@ void CodeGenFunction::EmitOMPParallelForDirective(
   // directives: 'parallel' with 'for' directive.
   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
 Action.Enter(CGF);
+emitOMPCopyinClause(CGF, S);
 (void)emitWorksharingDirective(CGF, S, S.hasCancel());
   };
   {
@@ -4385,6 +4391,7 @@ void CodeGenFunction::EmitOMPParallelForSimdDirective(
   // directives: 'parallel' with 'for' directive.
   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
 Action.Enter(CGF);
+emitOMPCopyinClause(CGF, S);
 (void)emitWorksharingDirective(CGF, S, /*HasCancel=*/false);
   };
   {
@@ -4419,16 +4426,8 @@ void CodeGenFunction::EmitOMPParallelMasterDirective(
   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
 Action.Enter(CGF);
 OMPPrivateScope PrivateScope(CGF);
-bool Copyins = CGF.EmitOMPCopyinClause(S);
+emitOMPCopyinClause(CGF, S);
 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
-if (Copyins) {
-  // Emit implicit barrier to synchronize threads and avoid data races on
-  // propagation master's thread values of threadprivate variables to local
-  // instances of that variables of all other implicit threads.
-  CGF.CGM.getOpenMPRuntime().emitBarrierCall(
-  CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
-  /*ForceSimpleCall=*/true);
-}
 CGF.EmitOMPPrivateClause(S, PrivateScope);
 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
 (void)PrivateScope.Privatize();
@@ -4453,6 +4452,7 @@ void CodeGenFunction::EmitOMPParallelSectionsDirective(
   // directives: 'parallel' with 'sections' directive.
   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
 Action.Enter(CGF);
+emitOMPCopyinClause(CGF, S);
 CGF.EmitSections(S);
   };
   {

diff  --git a/cla

[clang] 86bfab2 - [OffloadPackager] Resolve copy elision warnings

2022-08-23 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-08-23T10:01:54-05:00
New Revision: 86bfab2723618772f5c4ffc2a68eedca592c6928

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

LOG: [OffloadPackager] Resolve copy elision warnings

Summary:
The buildbots are giving failures on the explicit move operations here.
Previously I had problems where not perfomring an explicit move would
cause problems with older compilers so we'll see if this works as
expected.

Added: 


Modified: 
clang/tools/clang-offload-packager/ClangOffloadPackager.cpp

Removed: 




diff  --git a/clang/tools/clang-offload-packager/ClangOffloadPackager.cpp 
b/clang/tools/clang-offload-packager/ClangOffloadPackager.cpp
index b8d1565689f8..c9c722e0a5b5 100644
--- a/clang/tools/clang-offload-packager/ClangOffloadPackager.cpp
+++ b/clang/tools/clang-offload-packager/ClangOffloadPackager.cpp
@@ -119,7 +119,7 @@ static Error bundleImages() {
   std::unique_ptr Output = std::move(*OutputOrErr);
   std::copy(BinaryData.begin(), BinaryData.end(), Output->getBufferStart());
   if (Error E = Output->commit())
-return std::move(E);
+return E;
   return Error::success();
 }
 
@@ -200,7 +200,7 @@ static Error unbundleImages() {
   std::unique_ptr Output = std::move(*OutputOrErr);
   llvm::copy(Binary->getImage(), Output->getBufferStart());
   if (Error E = Output->commit())
-return std::move(E);
+return E;
 }
   }
 



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


[PATCH] D132209: [Clang][OpenMP] Make copyin clause on combined and composite construct work

2022-08-23 Thread Alexey Bataev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2e2caea37f4b: [Clang][OpenMP] Make copyin clause on combined 
and composite construct work… (authored by yutsumi, committed by ABataev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132209

Files:
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/test/OpenMP/parallel_copyin_combined_codegen.c
  openmp/runtime/test/parallel/omp_parallel_copyin_combined.c

Index: openmp/runtime/test/parallel/omp_parallel_copyin_combined.c
===
--- /dev/null
+++ openmp/runtime/test/parallel/omp_parallel_copyin_combined.c
@@ -0,0 +1,110 @@
+// RUN: %libomp-compile-and-run
+#include "omp_testsuite.h"
+
+#define N 100
+
+int x1, x2, x3, x4, x5;
+#pragma omp threadprivate(x1, x2, x3, x4, x5)
+
+int test_omp_parallel_copyin() {
+  int a[N];
+  x1 = 1;
+
+#pragma omp parallel copyin(x1)
+#pragma omp for
+  for (int i = 0; i < N; i++)
+a[i] = i + x1;
+
+  int sum = 0;
+
+  for (int i = 0; i < N; i++)
+sum += a[i];
+
+  return (sum == ((99 + 2 * x1) * 100) / 2);
+}
+
+int test_omp_parallel_for_copyin() {
+  int a[N];
+  x2 = 2;
+
+#pragma omp parallel for copyin(x2)
+  for (int i = 0; i < N; i++)
+a[i] = i + x2;
+
+  int sum = 0;
+
+  for (int i = 0; i < N; i++)
+sum += a[i];
+
+  return (sum == ((99 + 2 * x2) * 100) / 2);
+}
+
+int test_omp_parallel_for_simd_copyin() {
+  int a[N];
+  x3 = 3;
+
+#pragma omp parallel for simd copyin(x3)
+  for (int i = 0; i < N; i++)
+a[i] = i + x3;
+
+  int sum = 0;
+
+  for (int i = 0; i < N; i++)
+sum += a[i];
+
+  return (sum == ((99 + 2 * x3) * 100) / 2);
+}
+
+int test_omp_parallel_sections_copyin() {
+  int a = 0;
+  int b = 0;
+  x4 = 4;
+
+#pragma omp parallel sections copyin(x4)
+  {
+#pragma omp section
+{ a = x4; }
+
+#pragma omp section
+{ b = x4; }
+  }
+
+  return (a + b == x4 * 2);
+}
+
+int test_omp_parallel_master_copyin() {
+  int a[N];
+  x5 = 5;
+
+#pragma omp parallel master copyin(x5)
+  for (int i = 0; i < N; i++)
+a[i] = i + x5;
+
+  int sum = 0;
+
+  for (int i = 0; i < N; i++)
+sum += a[i];
+
+  return (sum == ((99 + 2 * x5) * 100) / 2);
+}
+
+int main() {
+  int num_failed = 0;
+
+  if (!test_omp_parallel_copyin())
+num_failed++;
+
+  if (!test_omp_parallel_for_copyin())
+num_failed++;
+
+  if (!test_omp_parallel_for_simd_copyin())
+num_failed++;
+
+  if (!test_omp_parallel_sections_copyin())
+num_failed++;
+
+  if (!test_omp_parallel_master_copyin())
+num_failed++;
+
+  return num_failed;
+}
Index: clang/test/OpenMP/parallel_copyin_combined_codegen.c
===
--- /dev/null
+++ clang/test/OpenMP/parallel_copyin_combined_codegen.c
@@ -0,0 +1,532 @@
+// RUN: %clang_cc1 -no-opaque-pointers -verify -fopenmp -x c -triple x86_64-unknown-linux -emit-llvm %s -o - | FileCheck %s
+// expected-no-diagnostics
+
+#define N 100
+
+int x;
+#pragma omp threadprivate(x)
+
+void test_omp_parallel_copyin(int *a) {
+  x = 1;
+
+#pragma omp parallel copyin(x)
+#pragma omp for
+  for (int i = 0; i < N; i++)
+a[i] = i + x;
+}
+
+void test_omp_parallel_for_copyin(int *a) {
+  x = 2;
+
+#pragma omp parallel for copyin(x)
+  for (int i = 0; i < N; i++)
+a[i] = i + x;
+}
+
+void test_omp_parallel_for_simd_copyin(int *a) {
+  x = 3;
+
+#pragma omp parallel for simd copyin(x)
+  for (int i = 0; i < N; i++)
+a[i] = i + x;
+}
+
+void test_omp_parallel_sections_copyin(int *a, int *b) {
+  x = 4;
+
+#pragma omp parallel sections copyin(x)
+  {
+#pragma omp section
+{ *a = x; }
+
+#pragma omp section
+{ *b = x; }
+  }
+}
+
+void test_omp_parallel_master_copyin(int *a) {
+  x = 5;
+
+#pragma omp parallel master copyin(x)
+  for (int i = 0; i < N; i++)
+a[i] = i + x;
+}
+
+// CHECK-LABEL: define {{[^@]+}}@test_omp_parallel_copyin
+// CHECK-SAME: (i32* noundef [[A:%.*]]) #[[ATTR0:[0-9]+]] {
+// CHECK-NEXT: entry:
+// CHECK-NEXT:   [[A_ADDR:%.*]] = alloca i32*, align 8
+// CHECK-NEXT:   store i32* [[A]], i32** [[A_ADDR]], align 8
+// CHECK-NEXT:   [[TMP0:%.*]] = call i32* @llvm.threadlocal.address.p0i32(i32* @x)
+// CHECK-NEXT:   store i32 1, i32* [[TMP0]], align 4
+// CHECK-NEXT:   [[TMP1:%.*]] = call i32* @llvm.threadlocal.address.p0i32(i32* @x)
+// CHECK-NEXT:   call void (%struct.ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%struct.ident_t* @[[GLOB3:[0-9]+]], i32 2, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i32**, i32*)* @.omp_outlined. to void (i32*, i32*, ...)*), i32** [[A_ADDR]], i32* [[TMP1]])
+// CHECK-NEXT:   ret void
+//
+// CHECK-LABEL: define {{[^@]+}}@.omp_outlined.
+// CHECK-SAME: (i32* noalias noundef [[DOTGLOBAL_TID_:%.*]], i32* noalias noundef [[DOTBOUND_TID_:%.*]], i32** noundef nonnull align 8 dereferenceable(8) [[A:%.*]], i32* noundef nonnull align 4 dereferenceable(4) [[X:%.*]]) #[[ATTR1

[PATCH] D132419: [clang] Pull some utility functions into CompilerInvocation NFC

2022-08-23 Thread Ben Langmuir via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3708a148421f: [clang] Pull some utility functions into 
CompilerInvocation NFC (authored by benlangmuir).

Changed prior to commit:
  https://reviews.llvm.org/D132419?vs=454639&id=454847#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132419

Files:
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp

Index: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
===
--- clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -98,8 +98,8 @@
   // Make a deep copy of the original Clang invocation.
   CompilerInvocation CI(OriginalInvocation);
 
-  CI.getLangOpts()->resetNonModularOptions();
-  CI.getPreprocessorOpts().resetNonModularOptions();
+  CI.resetNonModularOptions();
+  CI.clearImplicitModuleBuildOptions();
 
   // Remove options incompatible with explicit module build or are likely to
   // differ between identical modules discovered from different translation
@@ -120,18 +120,6 @@
   CI.getLangOpts()->ModuleName = Deps.ID.ModuleName;
   CI.getFrontendOpts().IsSystemModule = Deps.IsSystem;
 
-  // Disable implicit modules and canonicalize options that are only used by
-  // implicit modules.
-  CI.getLangOpts()->ImplicitModules = false;
-  CI.getHeaderSearchOpts().ImplicitModuleMaps = false;
-  CI.getHeaderSearchOpts().ModuleCachePath.clear();
-  CI.getHeaderSearchOpts().ModulesValidateOncePerBuildSession = false;
-  CI.getHeaderSearchOpts().BuildSessionTimestamp = 0;
-  // The specific values we canonicalize to for pruning don't affect behaviour,
-  /// so use the default values so they will be dropped from the command-line.
-  CI.getHeaderSearchOpts().ModuleCachePruneInterval = 7 * 24 * 60 * 60;
-  CI.getHeaderSearchOpts().ModuleCachePruneAfter = 31 * 24 * 60 * 60;
-
   // Inputs
   InputKind ModuleMapInputKind(CI.getFrontendOpts().DashX.getLanguage(),
InputKind::Format::ModuleMap);
@@ -182,23 +170,8 @@
   return CI;
 }
 
-static std::vector
-serializeCompilerInvocation(const CompilerInvocation &CI) {
-  // Set up string allocator.
-  llvm::BumpPtrAllocator Alloc;
-  llvm::StringSaver Strings(Alloc);
-  auto SA = [&Strings](const Twine &Arg) { return Strings.save(Arg).data(); };
-
-  // Synthesize full command line from the CompilerInvocation, including "-cc1".
-  SmallVector Args{"-cc1"};
-  CI.generateCC1CommandLine(Args, SA);
-
-  // Convert arguments to the return type.
-  return std::vector{Args.begin(), Args.end()};
-}
-
 std::vector ModuleDeps::getCanonicalCommandLine() const {
-  return serializeCompilerInvocation(BuildInvocation);
+  return BuildInvocation.getCC1CommandLine();
 }
 
 static std::string getModuleContextHash(const ModuleDeps &MD,
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -4672,6 +4672,37 @@
   GenerateDependencyOutputArgs(DependencyOutputOpts, Args, SA);
 }
 
+std::vector CompilerInvocation::getCC1CommandLine() const {
+  // Set up string allocator.
+  llvm::BumpPtrAllocator Alloc;
+  llvm::StringSaver Strings(Alloc);
+  auto SA = [&Strings](const Twine &Arg) { return Strings.save(Arg).data(); };
+
+  // Synthesize full command line from the CompilerInvocation, including "-cc1".
+  SmallVector Args{"-cc1"};
+  generateCC1CommandLine(Args, SA);
+
+  // Convert arguments to the return type.
+  return std::vector{Args.begin(), Args.end()};
+}
+
+void CompilerInvocation::resetNonModularOptions() {
+  getLangOpts()->resetNonModularOptions();
+  getPreprocessorOpts().resetNonModularOptions();
+}
+
+void CompilerInvocation::clearImplicitModuleBuildOptions() {
+  getLangOpts()->ImplicitModules = false;
+  getHeaderSearchOpts().ImplicitModuleMaps = false;
+  getHeaderSearchOpts().ModuleCachePath.clear();
+  getHeaderSearchOpts().ModulesValidateOncePerBuildSession = false;
+  getHeaderSearchOpts().BuildSessionTimestamp = 0;
+  // The specific values we canonicalize to for pruning don't affect behaviour,
+  /// so use the default values so they may be dropped from the command-line.
+  getHeaderSearchOpts().ModuleCachePruneInterval = 7 * 24 * 60 * 60;
+  getHeaderSearchOpts().ModuleCachePruneAfter = 31 * 24 * 60 * 60;
+}
+
 IntrusiveRefCntPtr
 clang::createVFSFromCompilerInvocation(const CompilerInvocation &CI,
DiagnosticsEngine &Diags) {
Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstanc

[clang] 3708a14 - [clang] Pull some utility functions into CompilerInvocation NFC

2022-08-23 Thread Ben Langmuir via cfe-commits

Author: Ben Langmuir
Date: 2022-08-23T08:18:14-07:00
New Revision: 3708a148421fd0449081b9a91fba28f51f1dfb12

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

LOG: [clang] Pull some utility functions into CompilerInvocation NFC

Move copying compiler arguments to a vector and modifying
common module-related options into CompilerInvocation in preparation for
using some of them in more places and to avoid duplicating this code
accidentally in the future.

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

Added: 


Modified: 
clang/include/clang/Frontend/CompilerInvocation.h
clang/lib/Frontend/CompilerInstance.cpp
clang/lib/Frontend/CompilerInvocation.cpp
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp

Removed: 




diff  --git a/clang/include/clang/Frontend/CompilerInvocation.h 
b/clang/include/clang/Frontend/CompilerInvocation.h
index 0753a6632f81..9cf28c52f4d9 100644
--- a/clang/include/clang/Frontend/CompilerInvocation.h
+++ b/clang/include/clang/Frontend/CompilerInvocation.h
@@ -224,7 +224,7 @@ class CompilerInvocation : public CompilerInvocationRefBase,
   std::string getModuleHash() const;
 
   using StringAllocator = llvm::function_ref;
-  /// Generate a cc1-compatible command line arguments from this instance.
+  /// Generate cc1-compatible command line arguments from this instance.
   ///
   /// \param [out] Args - The generated arguments. Note that the caller is
   /// responsible for inserting the path to the clang executable and "-cc1" if
@@ -235,6 +235,20 @@ class CompilerInvocation : public 
CompilerInvocationRefBase,
   void generateCC1CommandLine(llvm::SmallVectorImpl &Args,
   StringAllocator SA) const;
 
+  /// Generate cc1-compatible command line arguments from this instance,
+  /// wrapping the result as a std::vector.
+  ///
+  /// This is a (less-efficient) wrapper over generateCC1CommandLine().
+  std::vector getCC1CommandLine() const;
+
+  /// Reset all of the options that are not considered when building a
+  /// module.
+  void resetNonModularOptions();
+
+  /// Disable implicit modules and canonicalize options that are only used by
+  /// implicit modules.
+  void clearImplicitModuleBuildOptions();
+
 private:
   static bool CreateFromArgsImpl(CompilerInvocation &Res,
  ArrayRef CommandLineArgs,

diff  --git a/clang/lib/Frontend/CompilerInstance.cpp 
b/clang/lib/Frontend/CompilerInstance.cpp
index e3b54478997a..03b5d048c4b8 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -1150,8 +1150,7 @@ compileModuleImpl(CompilerInstance &ImportingInstance, 
SourceLocation ImportLoc,
 
   // For any options that aren't intended to affect how a module is built,
   // reset them to their default values.
-  Invocation->getLangOpts()->resetNonModularOptions();
-  PPOpts.resetNonModularOptions();
+  Invocation->resetNonModularOptions();
 
   // Remove any macro definitions that are explicitly ignored by the module.
   // They aren't supposed to affect how the module is built anyway.

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 9731d4006d1e..7e6d0cd7f504 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -4672,6 +4672,37 @@ void CompilerInvocation::generateCC1CommandLine(
   GenerateDependencyOutputArgs(DependencyOutputOpts, Args, SA);
 }
 
+std::vector CompilerInvocation::getCC1CommandLine() const {
+  // Set up string allocator.
+  llvm::BumpPtrAllocator Alloc;
+  llvm::StringSaver Strings(Alloc);
+  auto SA = [&Strings](const Twine &Arg) { return Strings.save(Arg).data(); };
+
+  // Synthesize full command line from the CompilerInvocation, including 
"-cc1".
+  SmallVector Args{"-cc1"};
+  generateCC1CommandLine(Args, SA);
+
+  // Convert arguments to the return type.
+  return std::vector{Args.begin(), Args.end()};
+}
+
+void CompilerInvocation::resetNonModularOptions() {
+  getLangOpts()->resetNonModularOptions();
+  getPreprocessorOpts().resetNonModularOptions();
+}
+
+void CompilerInvocation::clearImplicitModuleBuildOptions() {
+  getLangOpts()->ImplicitModules = false;
+  getHeaderSearchOpts().ImplicitModuleMaps = false;
+  getHeaderSearchOpts().ModuleCachePath.clear();
+  getHeaderSearchOpts().ModulesValidateOncePerBuildSession = false;
+  getHeaderSearchOpts().BuildSessionTimestamp = 0;
+  // The specific values we canonicalize to for pruning don't affect behaviour,
+  /// so use the default values so they may be dropped from the command-line.
+  getHeaderSearchOpts().ModuleCachePruneInterval = 7 * 24 * 60 * 60;
+  getHeaderSearchOpts().ModuleCachePruneAfter = 31 * 24 * 60 * 60;
+}
+
 IntrusiveRefCntPtr
 

[PATCH] D131939: [clang-tidy] Add performance-expensive-flat-container-operation check

2022-08-23 Thread Nicolas van Kempen via Phabricator via cfe-commits
nicovank added a reviewer: alexfh.
nicovank added a comment.

Ping.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131939

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


[PATCH] D129570: [clang-tidy] Add new clang-tidy check to find implicit conversions from enum to integer.

2022-08-23 Thread Paul Fultz II via Phabricator via cfe-commits
pfultz2 added a comment.

Anymore feedback?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129570

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


[PATCH] D132430: [clang][modules] Track affecting modules

2022-08-23 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir added inline comments.



Comment at: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp:311
+if (!MDC.isPrebuiltModule(M))
+  DirectModularDeps.insert(M);
+

If using eager loading, this will cause us to load the module, right? Does that 
behaviour match the implicit build?



Comment at: clang/test/ClangScanDeps/modules-incomplete-umbrella.c:82
+// CHECK_TU-NEXT:   "command-line": [
+// CHECK_TU:],
+// CHECK_TU-NEXT:   "file-deps": [

The test should probably cover the imports in the command-lines.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132430

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


[PATCH] D132324: [RFC] Remove support for building libc++ with `LLVM_ENABLE_PROJECTS`

2022-08-23 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a comment.

In D132324#3742700 , @Ericson2314 
wrote:

>> I also think we don't want to move forward with D132411 
>>  -- it's going against this transition.
>
> I would like to discuss some of this sort of thing so more, but better to do 
> that on the the discourse than my shoddy commits that need reverting!

Sure, I'd be curious to understand why that's needed.

After some thinking, I created the following stack of patches: D132478 
 => D132479 
 => D132480 
.

The last patch is basically a reboot of this patch, i.e. it's the one that will 
make folks who use `LLVM_ENABLE_PROJECTS=libcxx` start failing. However, I am 
also trying to keep `LLVM_ENABLE_PROJECTS` and `LLVM_ENABLE_RUNTIMES` 
consistent, i.e. it should be possible to use `LLVM_ENABLE_PROJECTS=all` and 
`LLVM_ENABLE_RUNTIMES=all` without ever being broken by any of our changes 
(except `libcxx`, `libcxxabi` and `libunwind` would suddenly start building 
with the bootstrapping build instead of the normal runtimes build).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132324

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


[PATCH] D132142: [analyzer] Prefer wrapping SymbolicRegions by ElementRegions

2022-08-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 454857.
steakhal added a comment.

- Simplify `getApproximatedType()` to `return sym->getType()->getPointeeType();`
- Add doc comments to `getApproximatedType()`
- Removed the "Copied from RegionStoreManager::bind()" FIXME from the 
`ExprEngine::VisitMemberExpr()`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132142

Files:
  clang/include/clang/StaticAnalyzer/Checkers/SValExplainer.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
  clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/lib/StaticAnalyzer/Core/MemRegion.cpp
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/ctor.mm
  clang/test/Analysis/expr-inspection.c
  clang/test/Analysis/memory-model.cpp
  clang/test/Analysis/ptr-arith.c
  clang/test/Analysis/ptr-arith.cpp
  clang/test/Analysis/trivial-copy-struct.cpp

Index: clang/test/Analysis/trivial-copy-struct.cpp
===
--- /dev/null
+++ clang/test/Analysis/trivial-copy-struct.cpp
@@ -0,0 +1,36 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -verify %s
+
+template  void clang_analyzer_dump(T);
+void clang_analyzer_warnIfReached();
+
+struct Node { int* ptr; };
+
+void copy_on_stack(Node* n1) {
+  Node tmp = *n1;
+  Node* n2 = &tmp;
+  clang_analyzer_dump(n1); // expected-warning-re {{&SymRegion{reg_${{[0-9]+}
+  clang_analyzer_dump(n2); // expected-warning {{&tmp}}
+
+  clang_analyzer_dump(n1->ptr); // expected-warning-re {{&SymRegion{reg_${{[0-9]+}}},0 S64b,struct Node}.ptr>}}}
+  clang_analyzer_dump(n2->ptr); // expected-warning-re {{&SymRegion{reg_${{[0-9]+}}},0 S64b,struct Node}.ptr>}}}
+
+  if (n1->ptr != n2->ptr)
+clang_analyzer_warnIfReached(); // unreachable
+  (void)(n1->ptr);
+  (void)(n2->ptr);
+}
+
+void copy_on_heap(Node* n1) {
+  Node* n2 = new Node(*n1);
+
+  clang_analyzer_dump(n1); // expected-warning-re {{&SymRegion{reg_${{[0-9]+}
+  clang_analyzer_dump(n2); // expected-warning-re {{&HeapSymRegion{conj_${{[0-9]+}}{Node *, LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}
+
+  clang_analyzer_dump(n1->ptr); // expected-warning-re {{&SymRegion{reg_${{[0-9]+}}},0 S64b,struct Node}.ptr>}}}
+  clang_analyzer_dump(n2->ptr); // expected-warning {{Unknown}} FIXME: This should be the same as above.
+
+  if (n1->ptr != n2->ptr)
+clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}} FIXME: This should not be reachable.
+  (void)(n1->ptr);
+  (void)(n2->ptr);
+}
Index: clang/test/Analysis/ptr-arith.cpp
===
--- clang/test/Analysis/ptr-arith.cpp
+++ clang/test/Analysis/ptr-arith.cpp
@@ -134,10 +134,10 @@
 int parse(parse_t *p) {
   unsigned copy = p->bits2;
   clang_analyzer_dump(copy);
-  // expected-warning@-1 {{reg_$1}.bits2>}}
+  // expected-warning@-1 {{reg_$1},0 S64b,struct Bug_55934::parse_t}.bits2>}}
   header *bits = (header *)©
   clang_analyzer_dump(bits->b);
-  // expected-warning@-1 {{derived_$2{reg_$1}.bits2>,Element{copy,0 S64b,struct Bug_55934::header}.b}}}
+  // expected-warning@-1 {{derived_$2{reg_$1},0 S64b,struct Bug_55934::parse_t}.bits2>,Element{copy,0 S64b,struct Bug_55934::header}.b}}}
   return bits->b; // no-warning
 }
 } // namespace Bug_55934
Index: clang/test/Analysis/ptr-arith.c
===
--- clang/test/Analysis/ptr-arith.c
+++ clang/test/Analysis/ptr-arith.c
@@ -340,11 +340,11 @@
 void struct_pointer_canon(struct s *ps) {
   struct s ss = *ps;
   clang_analyzer_dump((*ps).v);
-  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}}.v>}}
+  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}},0 S64b,struct s}.v>}}
   clang_analyzer_dump(ps[0].v);
-  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}}.v>}}
+  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}},0 S64b,struct s}.v>}}
   clang_analyzer_dump(ps->v);
-  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}}.v>}}
+  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}},0 S64b,struct s}.v>}}
   clang_analyzer_eval((*ps).v == ps[0].v); // expected-warning{{TRUE}}
   clang_analyzer_eval((*ps).v == ps->v);   // expected-warning{{TRUE}}
   clang_analyzer_eval(ps[0].v == ps->v);   // expected-warning{{TRUE}}
@@ -360,11 +360,11 @@
 void struct_pointer_canon_typedef(T1 *ps) {
   T2 ss = *ps;
   clang_analyzer_dump((*ps).v);
-  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}}.v>}}
+  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}},0 S64b,struct s}.v>}}
   clang_analyzer_dump(ps[0].v);
-  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}}.v>}}
+  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}},0 S64b,struct s}.v>}}
   clang_analyzer_dump(ps->v);
-  // expected-warnin

[PATCH] D132142: [analyzer] Prefer wrapping SymbolicRegions by ElementRegions

2022-08-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 454859.
steakhal added a comment.

upload the same with context


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132142

Files:
  clang/include/clang/StaticAnalyzer/Checkers/SValExplainer.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
  clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/lib/StaticAnalyzer/Core/MemRegion.cpp
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/ctor.mm
  clang/test/Analysis/expr-inspection.c
  clang/test/Analysis/memory-model.cpp
  clang/test/Analysis/ptr-arith.c
  clang/test/Analysis/ptr-arith.cpp
  clang/test/Analysis/trivial-copy-struct.cpp

Index: clang/test/Analysis/trivial-copy-struct.cpp
===
--- /dev/null
+++ clang/test/Analysis/trivial-copy-struct.cpp
@@ -0,0 +1,36 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -verify %s
+
+template  void clang_analyzer_dump(T);
+void clang_analyzer_warnIfReached();
+
+struct Node { int* ptr; };
+
+void copy_on_stack(Node* n1) {
+  Node tmp = *n1;
+  Node* n2 = &tmp;
+  clang_analyzer_dump(n1); // expected-warning-re {{&SymRegion{reg_${{[0-9]+}
+  clang_analyzer_dump(n2); // expected-warning {{&tmp}}
+
+  clang_analyzer_dump(n1->ptr); // expected-warning-re {{&SymRegion{reg_${{[0-9]+}}},0 S64b,struct Node}.ptr>}}}
+  clang_analyzer_dump(n2->ptr); // expected-warning-re {{&SymRegion{reg_${{[0-9]+}}},0 S64b,struct Node}.ptr>}}}
+
+  if (n1->ptr != n2->ptr)
+clang_analyzer_warnIfReached(); // unreachable
+  (void)(n1->ptr);
+  (void)(n2->ptr);
+}
+
+void copy_on_heap(Node* n1) {
+  Node* n2 = new Node(*n1);
+
+  clang_analyzer_dump(n1); // expected-warning-re {{&SymRegion{reg_${{[0-9]+}
+  clang_analyzer_dump(n2); // expected-warning-re {{&HeapSymRegion{conj_${{[0-9]+}}{Node *, LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}
+
+  clang_analyzer_dump(n1->ptr); // expected-warning-re {{&SymRegion{reg_${{[0-9]+}}},0 S64b,struct Node}.ptr>}}}
+  clang_analyzer_dump(n2->ptr); // expected-warning {{Unknown}} FIXME: This should be the same as above.
+
+  if (n1->ptr != n2->ptr)
+clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}} FIXME: This should not be reachable.
+  (void)(n1->ptr);
+  (void)(n2->ptr);
+}
Index: clang/test/Analysis/ptr-arith.cpp
===
--- clang/test/Analysis/ptr-arith.cpp
+++ clang/test/Analysis/ptr-arith.cpp
@@ -134,10 +134,10 @@
 int parse(parse_t *p) {
   unsigned copy = p->bits2;
   clang_analyzer_dump(copy);
-  // expected-warning@-1 {{reg_$1}.bits2>}}
+  // expected-warning@-1 {{reg_$1},0 S64b,struct Bug_55934::parse_t}.bits2>}}
   header *bits = (header *)©
   clang_analyzer_dump(bits->b);
-  // expected-warning@-1 {{derived_$2{reg_$1}.bits2>,Element{copy,0 S64b,struct Bug_55934::header}.b}}}
+  // expected-warning@-1 {{derived_$2{reg_$1},0 S64b,struct Bug_55934::parse_t}.bits2>,Element{copy,0 S64b,struct Bug_55934::header}.b}}}
   return bits->b; // no-warning
 }
 } // namespace Bug_55934
Index: clang/test/Analysis/ptr-arith.c
===
--- clang/test/Analysis/ptr-arith.c
+++ clang/test/Analysis/ptr-arith.c
@@ -340,11 +340,11 @@
 void struct_pointer_canon(struct s *ps) {
   struct s ss = *ps;
   clang_analyzer_dump((*ps).v);
-  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}}.v>}}
+  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}},0 S64b,struct s}.v>}}
   clang_analyzer_dump(ps[0].v);
-  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}}.v>}}
+  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}},0 S64b,struct s}.v>}}
   clang_analyzer_dump(ps->v);
-  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}}.v>}}
+  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}},0 S64b,struct s}.v>}}
   clang_analyzer_eval((*ps).v == ps[0].v); // expected-warning{{TRUE}}
   clang_analyzer_eval((*ps).v == ps->v);   // expected-warning{{TRUE}}
   clang_analyzer_eval(ps[0].v == ps->v);   // expected-warning{{TRUE}}
@@ -360,11 +360,11 @@
 void struct_pointer_canon_typedef(T1 *ps) {
   T2 ss = *ps;
   clang_analyzer_dump((*ps).v);
-  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}}.v>}}
+  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}},0 S64b,struct s}.v>}}
   clang_analyzer_dump(ps[0].v);
-  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}}.v>}}
+  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}},0 S64b,struct s}.v>}}
   clang_analyzer_dump(ps->v);
-  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}}.v>}}
+  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}},0 S64b,struct s}.v>}}
   clang_analyzer_eval((*ps).v == ps[0].v); // expected-warning{{TRUE}}
   clang_analyzer

[PATCH] D132236: [analyzer] Fix liveness of LazyCompoundVals

2022-08-23 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 454861.
steakhal added a comment.

rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132236

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/trivial-copy-struct.cpp


Index: clang/test/Analysis/trivial-copy-struct.cpp
===
--- clang/test/Analysis/trivial-copy-struct.cpp
+++ clang/test/Analysis/trivial-copy-struct.cpp
@@ -34,3 +34,28 @@
   (void)(n1->ptr);
   (void)(n2->ptr);
 }
+
+struct List {
+  List* next;
+};
+
+void ptr1(List* n) {
+  List* n2 = new List(*n); // cctor
+  if (!n->next) {
+if (n2->next) {
+  clang_analyzer_warnIfReached(); // unreachable
+}
+  }
+  delete n2;
+}
+
+void ptr2(List* n) {
+  List* n2 = new List(); // ctor
+  *n2 = *n; // assignment
+  if (!n->next) {
+if (n2->next) {
+  clang_analyzer_warnIfReached(); // unreachable
+}
+  }
+  delete n2;
+}
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -2829,22 +2829,14 @@
 }
 
 void RemoveDeadBindingsWorker::VisitBinding(SVal V) {
-  // Is it a LazyCompoundVal?  All referenced regions are live as well.
-  if (Optional LCS =
-  V.getAs()) {
-
-const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS);
-
-for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(),
-E = Vals.end();
- I != E; ++I)
-  VisitBinding(*I);
+  const MemRegion *R = V.getAsRegion();
 
-return;
-  }
+  // Is it a LazyCompoundVal?  All referenced regions are live as well.
+  if (auto LCS = V.getAs())
+R = LCS->getRegion();
 
   // If V is a region, then add it to the worklist.
-  if (const MemRegion *R = V.getAsRegion()) {
+  if (R) {
 AddToWorkList(R);
 SymReaper.markLive(R);
 


Index: clang/test/Analysis/trivial-copy-struct.cpp
===
--- clang/test/Analysis/trivial-copy-struct.cpp
+++ clang/test/Analysis/trivial-copy-struct.cpp
@@ -34,3 +34,28 @@
   (void)(n1->ptr);
   (void)(n2->ptr);
 }
+
+struct List {
+  List* next;
+};
+
+void ptr1(List* n) {
+  List* n2 = new List(*n); // cctor
+  if (!n->next) {
+if (n2->next) {
+  clang_analyzer_warnIfReached(); // unreachable
+}
+  }
+  delete n2;
+}
+
+void ptr2(List* n) {
+  List* n2 = new List(); // ctor
+  *n2 = *n; // assignment
+  if (!n->next) {
+if (n2->next) {
+  clang_analyzer_warnIfReached(); // unreachable
+}
+  }
+  delete n2;
+}
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -2829,22 +2829,14 @@
 }
 
 void RemoveDeadBindingsWorker::VisitBinding(SVal V) {
-  // Is it a LazyCompoundVal?  All referenced regions are live as well.
-  if (Optional LCS =
-  V.getAs()) {
-
-const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS);
-
-for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(),
-E = Vals.end();
- I != E; ++I)
-  VisitBinding(*I);
+  const MemRegion *R = V.getAsRegion();
 
-return;
-  }
+  // Is it a LazyCompoundVal?  All referenced regions are live as well.
+  if (auto LCS = V.getAs())
+R = LCS->getRegion();
 
   // If V is a region, then add it to the worklist.
-  if (const MemRegion *R = V.getAsRegion()) {
+  if (R) {
 AddToWorkList(R);
 SymReaper.markLive(R);
 
___
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-08-23 Thread Yusuke Kadowaki via Phabricator via cfe-commits
yusuke-kadowaki updated this revision to Diff 454864.
yusuke-kadowaki edited the summary of this revision.
yusuke-kadowaki added a comment.

- [clang-format] Adds a formatter for aligning trailing comments over empty 
lines
- Remove unnecessary style specifications
- Add more tests
- Port AlignTrailingComments to AlignConsecutiveStyle
- Move tests to comments tests
- Remove AlignTrailingCommentsIgnoreEmptyLine
- Removed old AlignTrailingComments
- Add parsing config test
- Add more tests
- Add documentation


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132131

Files:
  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,107 @@
"int a; //\n");
 }
 
+TEST_F(FormatTestComments, AlignTrailingCommentsAcrossEmptyLines) {
+  FormatStyle Style = getLLVMStyle();
+  Style.AlignConsecutiveTrailingComments.AcrossEmptyLines = true;
+  verifyFormat("#include \"a.h\"  //\n"
+   "\n"
+   "#include \"aa.h\" //\n",
+   Style);
+   
+  verifyFormat("#include \"a.h\"   //\n"
+   "\n"
+   "#include \"aa.h\"  //\n"
+   "\n"
+   "#include \"aaa.h\" //\n",   
+   Style);
+   
+  verifyFormat("#include \"a.h\"  //\n"
+   "#include \"aa.h\" //\n"
+   "#include \"aaa.h\"//\n"
+   "\n"
+   "#include \".h\"   //\n"
+   "#include \"a.h\"  //\n"
+   "#include \"aa.h\" //\n",
+   Style);
+
+  verifyFormat("#include \"a.h\"  //\n"
+   "#include \"a.h\"\n"
+   "#include \"aa.h\" //\n",
+   Style);
+
+  verifyFormat("#include \"a.h\"   //\n"
+   "#include \"a.h\"\n"
+   "#include \"aa.h\"  //\n"
+   "#include \"a.h\"\n"
+   "#include \"aaa.h\" //\n",
+   Style);
+   
+  verifyFormat("#include \"a.h\"  //\n"
+   "#include \"aa.h\" //\n"
+   "#include \"aaa.h\"//\n"
+   "#include \"a.h\"\n"
+   "#include \".h\"   //\n"
+   "#include \"a.h\"  //\n"
+   "#include \"aa.h\" //\n",
+   Style);
+  
+  verifyFormat("#include \"a.h\"  //\n"
+   "\n"
+   "#include \"aa.h\" //\n"
+   "#include \"aaa.h\"\n"
+   "#include \"aaa.h\"\n"
+   "#include \"aaa.h\" // Do not align this because there are two lines without comments above\n",
+   Style);
+  
+  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));
+  
+  // FIXME: I think we need to change the implementations to pass tests below.
+  Style.ColumnLimit = 80;
+  EXPECT_EQ("int a; // line about a\n"
+"\n"
+"// line about b\n"
+"long b;",
+format("int a; // line about a\n"
+   "\n"
+   "   // line about b\n"
+   "   long b;",
+   Style));
+  
+  Style.ColumnLimit = 80;
+  EXPECT_EQ("int a; // line about a\n"
+"\n"
+"// line 1 about b\n"
+"// line 2 about b\n"
+"long b;",
+format("int a; // line about a\n"
+   "\n"
+   "   // line 1 about b\n"
+   "   // line 2 about b\n"
+   "   long b;",
+   Style));
+}
+
 TEST_F(FormatTestComments, AlignsBlockCommentDecorations) {
   EXPECT_EQ("/*\n"
 " */",
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -71,7 +71,10 @@
 ScopedTrace t(File, Line, ::testing::Message() << Code.str());
 EXPECT_EQ(Expected.str(), format(Expected, Style))
 << "Expected code is not stable

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

2022-08-23 Thread Yusuke Kadowaki via Phabricator via cfe-commits
yusuke-kadowaki added inline comments.



Comment at: clang/include/clang/Format/Format.h:379
   /// \version 3.7
   bool AlignTrailingComments;
 

HazardyKnusperkeks wrote:
> Maybe you can port this to `AlignConsecutiveStyle`? `AcrossComments` would 
> not affect anything in this context.
I took this approach



Comment at: clang/unittests/Format/FormatTest.cpp:74-77
+
+// FIXME: expectedとCodeをformatしたものがEQ
 EXPECT_EQ(Expected.str(), format(Code, Style));
+

Sorry I will remove these next time I update this patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132131

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


[PATCH] D132111: [clang][Interp] Implement pointer (de)ref operations and DeclRefExprs

2022-08-23 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann added inline comments.



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:662
+  return this->emitGetPtrParam(It->second, E);
+  }
+

tbaeder wrote:
> tahonermann wrote:
> > Perhaps add:
> >   else {
> > assert(0 && "Unhandled declaration kind");
> >   }
> We actually hit this path for non-constexpr-conforming functions, so 
> asserting doesn't work:
> ```
> constexpr void foo(int a) {
>   constexpr int b = a;
> }
> ```
> The initializer for `b` goes through `evaluteAsInitializer()` before the 
> function `foo` is ever registered, so the parameter is not known. This is 
> diagnosed by the current interpreter as well:
> 
> ```
> array.cpp:13:17: error: constexpr variable 'b' must be initialized by a 
> constant expression
>   constexpr int b = a;
> ^   ~
> array.cpp:13:21: note: function parameter 'a' with unknown value cannot be 
> used in a constant expression
>   constexpr int b = a;
> ^
> array.cpp:12:24: note: declared here
> constexpr void foo(int a) {
>^
> ```
> 
> Would be a good future test case, but right now the error message for the new 
> interpreter is just "constexpr variable 'b' must be initialized by a constant 
> expression".
I see, interesting.

I imagine future work will be needed to support references to lambda/block 
captures, data members, and such? And the answer to those right now is, we're 
not there yet?


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

https://reviews.llvm.org/D132111

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


[PATCH] D132111: [clang][Interp] Implement pointer (de)ref operations and DeclRefExprs

2022-08-23 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added inline comments.



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:662
+  return this->emitGetPtrParam(It->second, E);
+  }
+

tahonermann wrote:
> tbaeder wrote:
> > tahonermann wrote:
> > > Perhaps add:
> > >   else {
> > > assert(0 && "Unhandled declaration kind");
> > >   }
> > We actually hit this path for non-constexpr-conforming functions, so 
> > asserting doesn't work:
> > ```
> > constexpr void foo(int a) {
> >   constexpr int b = a;
> > }
> > ```
> > The initializer for `b` goes through `evaluteAsInitializer()` before the 
> > function `foo` is ever registered, so the parameter is not known. This is 
> > diagnosed by the current interpreter as well:
> > 
> > ```
> > array.cpp:13:17: error: constexpr variable 'b' must be initialized by a 
> > constant expression
> >   constexpr int b = a;
> > ^   ~
> > array.cpp:13:21: note: function parameter 'a' with unknown value cannot be 
> > used in a constant expression
> >   constexpr int b = a;
> > ^
> > array.cpp:12:24: note: declared here
> > constexpr void foo(int a) {
> >^
> > ```
> > 
> > Would be a good future test case, but right now the error message for the 
> > new interpreter is just "constexpr variable 'b' must be initialized by a 
> > constant expression".
> I see, interesting.
> 
> I imagine future work will be needed to support references to lambda/block 
> captures, data members, and such? And the answer to those right now is, we're 
> not there yet?
Yes, almost nothing works right now. :)


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

https://reviews.llvm.org/D132111

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


[PATCH] D131616: [clang][dataflow] Generalise match switch utility to other AST types and add a `CFGMatchSwitch` which currently handles `CFGStmt` and `CFGInitializer`.

2022-08-23 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 454868.
wyt marked 13 inline comments as done.
wyt added a comment.

Address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131616

Files:
  clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h
  clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h
  clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
@@ -5,12 +5,6 @@
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===--===//
-//
-//  This file defines a simplistic version of Constant Propagation as an example
-//  of a forward, monotonic dataflow analysis. The analysis tracks all
-//  variables in the scope, but lacks escape analysis.
-//
-//===--===//
 
 #include "clang/Analysis/FlowSensitive/MatchSwitch.h"
 #include "TestingSupport.h"
Index: clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
===
--- clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
+++ clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
@@ -4,6 +4,7 @@
   )
 
 add_clang_unittest(ClangAnalysisFlowSensitiveTests
+  CFGMatchSwitchTest.cpp
   ChromiumCheckModelTest.cpp
   DataflowAnalysisContextTest.cpp
   DataflowEnvironmentTest.cpp
Index: clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp
@@ -0,0 +1,124 @@
+//===- unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Analysis/FlowSensitive/CFGMatchSwitch.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/StringRef.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace dataflow;
+using namespace ast_matchers;
+
+namespace {
+// State for tracking the number of matches on each kind of CFGElement by the
+// CFGMatchSwitch. Currently only tracks CFGStmt and CFGInitializer.
+struct CFGElementMatches {
+  unsigned StmtMatches = 0;
+  unsigned InitializerMatches = 0;
+};
+
+// Returns a match switch that counts the number of local variables
+// (singly-declared) and fields initialized to the integer literal 42.
+auto buildCFGMatchSwitch() {
+  return CFGMatchSwitchBuilder()
+  .CaseOfCFGStmt(
+  declStmt(hasSingleDecl(
+  varDecl(hasInitializer(integerLiteral(equals(42)),
+  [](const DeclStmt *, const MatchFinder::MatchResult &,
+ CFGElementMatches &Counter) { Counter.StmtMatches++; })
+  .CaseOfCFGInit(
+  cxxCtorInitializer(withInitializer(integerLiteral(equals(42,
+  [](const CXXCtorInitializer *, const MatchFinder::MatchResult &,
+ CFGElementMatches &Counter) { Counter.InitializerMatches++; })
+  .Build();
+}
+
+// Runs the match switch `MS` on the control flow graph generated from `Code`,
+// tracking information in state `S`. For simplicity, this test utility is
+// restricted to CFGs with a single control flow block (excluding entry and
+// exit blocks) - generated by `Code` with sequential flow (i.e. no branching).
+//
+// Requirements:
+//
+//  `Code` must contain a function named `f`, the body of this function will be
+//  used to generate the CFG.
+template 
+void applySwitchToCode(CFGMatchSwitch &MS, State &S,
+   llvm::StringRef Code) {
+  auto Unit = tooling::buildASTFromCodeWithArgs(Code, {"-Wno-unused-value"});
+  auto &Ctx = Unit->getASTContext();
+  const auto *F = selectFirst(
+  "f", match(functionDecl(isDefinition(), hasName("f")).bind("f"), Ctx));
+
+  CFG::BuildOptions BO;
+  BO.AddInitializers = true;
+
+  auto CFG = CFG::buildCFG(F, F->getBody(), &Ctx, BO);
+  auto CFGBlock = *CFG->getEntry().succ_begin();
+  for (auto &Elt : CFGBlock->Elements) {
+MS(Elt, Ctx, S);
+  }
+}
+
+TEST(CFGMatchSwitchTest, NoInitializationTo42) {
+  CFGMatchSwitch Switch = buildCFGMatchSwitch();
+  CFGElementMatches Counter;
+  applySwitchToCode(Switch, Co

[PATCH] D131616: [clang][dataflow] Generalise match switch utility to other AST types and add a `CFGMatchSwitch` which currently handles `CFGStmt` and `CFGInitializer`.

2022-08-23 Thread weiyi via Phabricator via cfe-commits
wyt added inline comments.



Comment at: clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h:55
+MSActionT A) && {
+std::move(std::move(StmtBuilder).template CaseOf(M, A));
+return std::move(*this);

sgatev wrote:
> Is the outer move necessary? Also, aren't we supposed to assign the result 
> back to `StmtBuilder`? Same comment for `InitBuilder` below.
> Is the outer move necessary? Also, aren't we supposed to assign the result 
> back to StmtBuilder? Same comment for InitBuilder below.

Yeap the outer move was unnecessary.
The self-assignment wasn't necessary since the CaseOf modifies the object it is 
called on, in fact the self-assignment led to the destroyal of contents inside 
the builder.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131616

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


[PATCH] D131616: [clang][dataflow] Generalise match switch utility to other AST types and add a `CFGMatchSwitch` which currently handles `CFGStmt` and `CFGInitializer`.

2022-08-23 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 454869.
wyt added a comment.

Fix comments for consistency.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131616

Files:
  clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h
  clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h
  clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
@@ -5,12 +5,6 @@
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===--===//
-//
-//  This file defines a simplistic version of Constant Propagation as an example
-//  of a forward, monotonic dataflow analysis. The analysis tracks all
-//  variables in the scope, but lacks escape analysis.
-//
-//===--===//
 
 #include "clang/Analysis/FlowSensitive/MatchSwitch.h"
 #include "TestingSupport.h"
Index: clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
===
--- clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
+++ clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
@@ -4,6 +4,7 @@
   )
 
 add_clang_unittest(ClangAnalysisFlowSensitiveTests
+  CFGMatchSwitchTest.cpp
   ChromiumCheckModelTest.cpp
   DataflowAnalysisContextTest.cpp
   DataflowEnvironmentTest.cpp
Index: clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp
@@ -0,0 +1,124 @@
+//===- unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Analysis/FlowSensitive/CFGMatchSwitch.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/StringRef.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace dataflow;
+using namespace ast_matchers;
+
+namespace {
+// State for tracking the number of matches on each kind of CFGElement by the
+// CFGMatchSwitch. Currently only tracks CFGStmt and CFGInitializer.
+struct CFGElementMatches {
+  unsigned StmtMatches = 0;
+  unsigned InitializerMatches = 0;
+};
+
+// Returns a match switch that counts the number of local variables
+// (singly-declared) and fields initialized to the integer literal 42.
+auto buildCFGMatchSwitch() {
+  return CFGMatchSwitchBuilder()
+  .CaseOfCFGStmt(
+  declStmt(hasSingleDecl(
+  varDecl(hasInitializer(integerLiteral(equals(42)),
+  [](const DeclStmt *, const MatchFinder::MatchResult &,
+ CFGElementMatches &Counter) { Counter.StmtMatches++; })
+  .CaseOfCFGInit(
+  cxxCtorInitializer(withInitializer(integerLiteral(equals(42,
+  [](const CXXCtorInitializer *, const MatchFinder::MatchResult &,
+ CFGElementMatches &Counter) { Counter.InitializerMatches++; })
+  .Build();
+}
+
+// Runs the match switch `MS` on the control flow graph generated from `Code`,
+// tracking information in state `S`. For simplicity, this test utility is
+// restricted to CFGs with a single control flow block (excluding entry and
+// exit blocks) - generated by `Code` with sequential flow (i.e. no branching).
+//
+// Requirements:
+//
+//  `Code` must contain a function named `f`, the body of this function will be
+//  used to generate the CFG.
+template 
+void applySwitchToCode(CFGMatchSwitch &MS, State &S,
+   llvm::StringRef Code) {
+  auto Unit = tooling::buildASTFromCodeWithArgs(Code, {"-Wno-unused-value"});
+  auto &Ctx = Unit->getASTContext();
+  const auto *F = selectFirst(
+  "f", match(functionDecl(isDefinition(), hasName("f")).bind("f"), Ctx));
+
+  CFG::BuildOptions BO;
+  BO.AddInitializers = true;
+
+  auto CFG = CFG::buildCFG(F, F->getBody(), &Ctx, BO);
+  auto CFGBlock = *CFG->getEntry().succ_begin();
+  for (auto &Elt : CFGBlock->Elements) {
+MS(Elt, Ctx, S);
+  }
+}
+
+TEST(CFGMatchSwitchTest, NoInitializationTo42) {
+  CFGMatchSwitch Switch = buildCFGMatchSwitch();
+  CFGElementMatches Counter;
+  applySwitchToCode(Switch, Counter, R"(
+void f() {

  1   2   3   >