[clang] 57c8191 - [Clang] Convert update_cc_test_checks tests to opaque pointers (NFC)

2023-02-17 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2023-02-17T09:07:15+01:00
New Revision: 57c81917d3a596f925f1c072ad04425b66bbd80e

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

LOG: [Clang] Convert update_cc_test_checks tests to opaque pointers (NFC)

Added: 


Modified: 
clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp
clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp.expected
clang/test/utils/update_cc_test_checks/Inputs/check-attributes.cpp

clang/test/utils/update_cc_test_checks/Inputs/check-attributes.cpp.funcattrs.expected

clang/test/utils/update_cc_test_checks/Inputs/check-attributes.cpp.plain.expected
clang/test/utils/update_cc_test_checks/Inputs/def-and-decl.c
clang/test/utils/update_cc_test_checks/Inputs/def-and-decl.c.expected
clang/test/utils/update_cc_test_checks/Inputs/exec-all-runlines.c
clang/test/utils/update_cc_test_checks/Inputs/exec-all-runlines.c.expected

clang/test/utils/update_cc_test_checks/Inputs/explicit-template-instantiation.cpp

clang/test/utils/update_cc_test_checks/Inputs/explicit-template-instantiation.cpp.expected
clang/test/utils/update_cc_test_checks/Inputs/generated-funcs-regex.c

clang/test/utils/update_cc_test_checks/Inputs/generated-funcs-regex.c.expected
clang/test/utils/update_cc_test_checks/Inputs/generated-funcs.c

clang/test/utils/update_cc_test_checks/Inputs/generated-funcs.c.generated.expected

clang/test/utils/update_cc_test_checks/Inputs/generated-funcs.c.no-generated.expected
clang/test/utils/update_cc_test_checks/Inputs/mangled_names.c
clang/test/utils/update_cc_test_checks/Inputs/mangled_names.c.expected

clang/test/utils/update_cc_test_checks/Inputs/mangled_names.c.funcsig.expected
clang/test/utils/update_cc_test_checks/Inputs/resolve-tmp-conflict.cpp

clang/test/utils/update_cc_test_checks/Inputs/resolve-tmp-conflict.cpp.expected

Removed: 




diff  --git a/clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp 
b/clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp
index d1931edb2e0aa..98be350b39377 100644
--- a/clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp
+++ b/clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp
@@ -1,5 +1,5 @@
 // Basic C++ test for update_cc_test_checks
-// RUN: %clang_cc1 -no-opaque-pointers -triple=x86_64-unknown-linux-gnu 
-emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple=x86_64-unknown-linux-gnu -emit-llvm -o - %s | 
FileCheck %s
 
 class Foo {
   int x;

diff  --git 
a/clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp.expected 
b/clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp.expected
index 6c7dd730e5439..c916e3395a91c 100644
--- a/clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp.expected
+++ b/clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp.expected
@@ -1,6 +1,6 @@
 // NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
 // Basic C++ test for update_cc_test_checks
-// RUN: %clang_cc1 -no-opaque-pointers -triple=x86_64-unknown-linux-gnu 
-emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple=x86_64-unknown-linux-gnu -emit-llvm -o - %s | 
FileCheck %s
 
 class Foo {
   int x;
@@ -10,14 +10,14 @@ public:
   ~Foo();
 // CHECK-LABEL: @_ZNK3Foo23function_defined_inlineEi(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[THIS_ADDR:%.*]] = alloca %class.Foo*, align 8
+// CHECK-NEXT:[[THIS_ADDR:%.*]] = alloca ptr, align 8
 // CHECK-NEXT:[[ARG_ADDR:%.*]] = alloca i32, align 4
-// CHECK-NEXT:store %class.Foo* [[THIS:%.*]], %class.Foo** [[THIS_ADDR]], 
align 8
-// CHECK-NEXT:store i32 [[ARG:%.*]], i32* [[ARG_ADDR]], align 4
-// CHECK-NEXT:[[THIS1:%.*]] = load %class.Foo*, %class.Foo** 
[[THIS_ADDR]], align 8
-// CHECK-NEXT:[[TMP0:%.*]] = load i32, i32* [[ARG_ADDR]], align 4
-// CHECK-NEXT:[[X:%.*]] = getelementptr inbounds [[CLASS_FOO:%.*]], 
%class.Foo* [[THIS1]], i32 0, i32 0
-// CHECK-NEXT:[[TMP1:%.*]] = load i32, i32* [[X]], align 4
+// CHECK-NEXT:store ptr [[THIS:%.*]], ptr [[THIS_ADDR]], align 8
+// CHECK-NEXT:store i32 [[ARG:%.*]], ptr [[ARG_ADDR]], align 4
+// CHECK-NEXT:[[THIS1:%.*]] = load ptr, ptr [[THIS_ADDR]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = load i32, ptr [[ARG_ADDR]], align 4
+// CHECK-NEXT:[[X:%.*]] = getelementptr inbounds [[CLASS_FOO:%.*]], ptr 
[[THIS1]], i32 0, i32 0
+// CHECK-NEXT:[[TMP1:%.*]] = load i32, ptr [[X]], align 4
 // CHECK-NEXT:[[ADD:%.*]] = add nsw i32 [[TMP0]], [[TMP1]]
 // CHECK-NEXT:ret i32 [[ADD]]
 //
@@ -29,35 +29,35 @@ public:
 
 // CHECK-LABEL: @_ZN3FooC1Ei(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[THIS_ADDR:%.*]] = alloca %class.Foo*, align

[PATCH] D139798: [clang-repl] Support compound statement as a top-level statement.

2023-02-17 Thread Vassil Vassilev via Phabricator via cfe-commits
v.g.vassilev added a comment.

This seems like a good candidate for a post commit review.


Repository:
  rC Clang

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

https://reviews.llvm.org/D139798

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


[clang] 159073b - [clang-repl] Support compound statement as a top-level statement.

2023-02-17 Thread Vassil Vassilev via cfe-commits

Author: Vassil Vassilev
Date: 2023-02-17T09:09:04Z
New Revision: 159073bc0a873b9aa2bc559a8ceba970b049cda2

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

LOG: [clang-repl] Support compound statement as a top-level statement.

This patch teaches our incremental compilation infrastructure to push and pop a
fake function scope making the Parser happy when parsing compound statements as
part of a top-leve statement declaration.

Differential revision: https://reviews.llvm.org/D139798

Added: 


Modified: 
clang/lib/Parse/ParseDecl.cpp
clang/test/Interpreter/execute-stmts.cpp

Removed: 




diff  --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index d32f26b9c32e7..6465d859b1dab 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -5400,7 +5400,9 @@ Parser::DeclGroupPtrTy Parser::ParseTopLevelStmtDecl() {
   // Parse a top-level-stmt.
   Parser::StmtVector Stmts;
   ParsedStmtContext SubStmtCtx = ParsedStmtContext();
+  Actions.PushFunctionScope();
   StmtResult R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
+  Actions.PopFunctionScopeInfo();
   if (!R.isUsable())
 return nullptr;
 

diff  --git a/clang/test/Interpreter/execute-stmts.cpp 
b/clang/test/Interpreter/execute-stmts.cpp
index 567b783ad8cb3..2d4c17e0c91e6 100644
--- a/clang/test/Interpreter/execute-stmts.cpp
+++ b/clang/test/Interpreter/execute-stmts.cpp
@@ -34,5 +34,10 @@ printf("i = %d\n", i);
 for (; i > 4; --i) printf("i = %d\n", i);
 // CHECK-NEXT: i = 5
 
+{++i;}
+
+for (; i > 4; --i) { printf("i = %d\n", i); };
+// CHECK-NEXT: i = 5
+
 int j = i; printf("j = %d\n", j);
 // CHECK-NEXT: j = 4



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


[PATCH] D139798: [clang-repl] Support compound statement as a top-level statement.

2023-02-17 Thread Vassil Vassilev via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rG159073bc0a87: [clang-repl] Support compound statement as a 
top-level statement. (authored by v.g.vassilev).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D139798?vs=481945&id=498279#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139798

Files:
  clang/lib/Parse/ParseDecl.cpp
  clang/test/Interpreter/execute-stmts.cpp


Index: clang/test/Interpreter/execute-stmts.cpp
===
--- clang/test/Interpreter/execute-stmts.cpp
+++ clang/test/Interpreter/execute-stmts.cpp
@@ -34,5 +34,10 @@
 for (; i > 4; --i) printf("i = %d\n", i);
 // CHECK-NEXT: i = 5
 
+{++i;}
+
+for (; i > 4; --i) { printf("i = %d\n", i); };
+// CHECK-NEXT: i = 5
+
 int j = i; printf("j = %d\n", j);
 // CHECK-NEXT: j = 4
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -5400,7 +5400,9 @@
   // Parse a top-level-stmt.
   Parser::StmtVector Stmts;
   ParsedStmtContext SubStmtCtx = ParsedStmtContext();
+  Actions.PushFunctionScope();
   StmtResult R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
+  Actions.PopFunctionScopeInfo();
   if (!R.isUsable())
 return nullptr;
 


Index: clang/test/Interpreter/execute-stmts.cpp
===
--- clang/test/Interpreter/execute-stmts.cpp
+++ clang/test/Interpreter/execute-stmts.cpp
@@ -34,5 +34,10 @@
 for (; i > 4; --i) printf("i = %d\n", i);
 // CHECK-NEXT: i = 5
 
+{++i;}
+
+for (; i > 4; --i) { printf("i = %d\n", i); };
+// CHECK-NEXT: i = 5
+
 int j = i; printf("j = %d\n", j);
 // CHECK-NEXT: j = 4
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -5400,7 +5400,9 @@
   // Parse a top-level-stmt.
   Parser::StmtVector Stmts;
   ParsedStmtContext SubStmtCtx = ParsedStmtContext();
+  Actions.PushFunctionScope();
   StmtResult R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
+  Actions.PopFunctionScopeInfo();
   if (!R.isUsable())
 return nullptr;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D144003: [clang][analyzer] Improve bug reports of StdLibraryFunctionsChecker.

2023-02-17 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

The plan is to bring the checker out of the alpha package, the bug reports 
should be good enough for that. To modify bug report text generation a new 
patch would be better, after the current is finished. Maybe all single numbers 
in all allowed ranges that are 1, 2 (or 3?) long (like the 1,2,4,5,6 in the 
example) can be collected, this makes report generation more complicated than 
the current way.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144003

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


[PATCH] D144216: [clang-tidy] Extract string header from redundant-string-cstr checker

2023-02-17 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added inline comments.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/readability/redundant-string-cstr.cpp:1
-// RUN: %check_clang_tidy %s readability-redundant-string-cstr %t
-
-typedef unsigned __INT16_TYPE__ char16;
-typedef unsigned __INT32_TYPE__ char32;
-typedef __SIZE_TYPE__ size;
-
-namespace std {
-template 
-class allocator {};
-template 
-class char_traits {};
-template 
-struct basic_string {
-  typedef basic_string _Type;
-  basic_string();
-  basic_string(const C *p, const A &a = A());
-
-  ~basic_string();
-
-  const C *c_str() const;
-  const C *data() const;
-
-  _Type& append(const C *s);
-  _Type& append(const C *s, size n);
-  _Type& assign(const C *s);
-  _Type& assign(const C *s, size n);
-
-  int compare(const _Type&) const;
-  int compare(const C* s) const;
-  int compare(size pos, size len, const _Type&) const;
-  int compare(size pos, size len, const C* s) const;
-
-  size find(const _Type& str, size pos = 0) const;
-  size find(const C* s, size pos = 0) const;
-  size find(const C* s, size pos, size n) const;
-
-  _Type& insert(size pos, const _Type& str);
-  _Type& insert(size pos, const C* s);
-  _Type& insert(size pos, const C* s, size n);
-
-  _Type& operator+=(const _Type& str);
-  _Type& operator+=(const C* s);
-  _Type& operator=(const _Type& str);
-  _Type& operator=(const C* s);
-};
-
-typedef basic_string, std::allocator> 
string;
-typedef basic_string, 
std::allocator> wstring;
-typedef basic_string, std::allocator> 
u16string;
-typedef basic_string, std::allocator> 
u32string;
-
-template 
-struct basic_string_view {
-  basic_string_view(const C* s);
-};
-typedef basic_string_view> string_view;
-typedef basic_string_view> wstring_view;
-typedef basic_string_view> u16string_view;
-typedef basic_string_view> u32string_view;
-}
-
-std::string operator+(const std::string&, const std::string&);
-std::string operator+(const std::string&, const char*);
-std::string operator+(const char*, const std::string&);
-
-bool operator==(const std::string&, const std::string&);
-bool operator==(const std::string&, const char*);
-bool operator==(const char*, const std::string&);
+// RUN: %check_clang_tidy %s readability-redundant-string-cstr %t -- -- 
-isystem %clang_tidy_headers
+#include 

Where does this come from? Other tests use the actual path to the folder.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144216

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


[PATCH] D141569: [clang-tidy] Implement CppCoreGuideline F.18

2023-02-17 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp accepted this revision.
carlosgalvezp added a comment.
This revision is now accepted and ready to land.

LGTM thanks! Let's give a couple more days for last reviews. It probably needs 
a rebase since the Release Notes have got a couple more checks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141569

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


[clang] afcf70a - [analyzer] Remove unjustified assert from EquivalenceClass::simplify

2023-02-17 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2023-02-17T11:37:02+01:00
New Revision: afcf70aa6de77a0e99f6cb2d3e3824049203d6e2

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

LOG: [analyzer] Remove unjustified assert from EquivalenceClass::simplify

One might think that by merging the equivalence classes (eqclasses) of
`Sym1` and `Sym2` symbols we would end up with a `State` in which the
eqclass of `Sym1` and `Sym2` should now be the same. Surprisingly, it's
not //always// true.

Such an example triggered the assertion enforcing this _unjustified_
invariant in https://github.com/llvm/llvm-project/issues/58677.
```lang=C++
unsigned a, b;
#define assert(cond) if (!(cond)) return

void f(unsigned c) {
/*(1)*/ assert(c == b);
/*(2)*/ assert((c | a) != a);
/*(3)*/ assert(a);
// a = 0  =>  c | 0 != 0  =>  c != 0  =>  b != 0
}
```

I believe, that this assertion hold for reasonable cases - where both
`MemberSym` and `SimplifiedMemberSym` refer to live symbols.
It can only fail if `SimplifiedMemberSym` refers to an already dead
symbol. See the reasoning at the very end.
In this context, I don't know any way of determining if a symbol is
alive/dead, so I cannot refine the assertion in that way.
So, I'm proposing to drop this unjustified assertion.

---

Let me elaborate on why I think the assertion is wrong in its current
shape.

Here is a quick reminder about equivalence classes in CSA.
We have 4 mappings:
1) `ClassMap`: map, associating `Symbols` with an `EquivalenceClass`.
2) `ClassMembers`: map, associating `EquivalenceClasses` with its
   members - basically an enumeration of the `Symbols` which are known
   to be equal.
3) `ConstraintRange`: map, associating `EquivalenceClasses` with the
   range constraint which should hold for all the members of the
   eqclass.
4) `DisequalityMap`: I'm omitting this, as it's irrelevant for our
   purposes now.

Whenever we encounter/assume that two `SymbolRefs` are equal, we update
the `ClassMap` so that now both `SymbolRefs` are referring to the same
eqclass. This operation is known as `merge` or `union`.
Each eqclass is uniquely identified by the `representative` symbol, but
it could have been just a unique number or anything else - the point
is that an eqclass is identified by something unique.
Initially, all Symbols form - by itself - a trivial eqclass, as there
are no other Symbols to which it is assumed to be equal. A trivial
eqclass has //notionally// exactly one member, the representative symbol.
I'm emphasizing that //notionally// because for such cases we don't store
an entry in the `ClassMap` nor in the `ClassMembers` map, because it
could be deduced.

By `merging` two eqclasses, we essentially do what you would think it
does. An important thing to highlight is that the representative symbol
of the resulting eqclass will be the same as one of the two eqclasses.
This operation should be commutative, so that `merge(eq1,eq2)` and
`merge(eq2,eq1)` should result in the same eqclass - except for the
representative symbol, which is just a unique identifier of the class,
a name if you will. Using the representative symbol of `eq1` or `eq2`
should have no visible effect on the analysis overall.

When merging `eq1` into `eq2`, we take each of the `ClassMembers` of
`eq1` and add them to the `ClassMembers` of `eq2` while we also redirect
all the `Symbol` members of `eq1` to map to the `eq2` eqclass in the
`ClassMap`. This way all members of `eq1` will refer to the correct
eqclass. After these, `eq1` key is unreachable in the `ClassMembers`,
hence we can drop it.

---

Let's get back to the example.
Note that when I refer to symbols `a`, `b`, `c`, I'm referring to the
`SymbolRegionValue{VarRegion{.}}` - the value of that variable.

After `(1)`, we will have a constraint `c == b : [1,1]` and an eqclass
`c,b` with the `c` representative symbol.
After `(2)`, we will have an additional constraint `c|b != a : [1,1]`
with the same eqclass. We will also have disequality info about that
`c|a` is disequal to `a` - and the other way around.
However, after the full-expression, `c` will become dead. This kicks in
the garbage collection, which transforms the state into this:
 - We no longer have any constraints, because only `a` is alive, for
   which we don't have any constraints.
 - We have a single (non-trivial) eqclass with a single element `b` and
   representative symbol `c`. (Dead symbols can be representative
   symbols.)
 - We have the same disequality info as before.

At `(3)` within the false branch, `a` get perfectly constrained to zero.
This kicks in the simplification, so we try to substitute (simplify) the
variable in each SymExpr-tree. In our case, it means that the
`c|a != a : [1,1]` constraint gets re-evaluated as `c|0 != 0 : [1,1]`,
which is `c != 0 : [1,1]`.
Under the hood, it means that we will call `merge(c|a, c)`. where `c` is

[PATCH] D138037: [analyzer] Remove unjustified assertion from EQClass::simplify

2023-02-17 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGafcf70aa6de7: [analyzer] Remove unjustified assert from 
EquivalenceClass::simplify (authored by steakhal).

Changed prior to commit:
  https://reviews.llvm.org/D138037?vs=475480&id=498301#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138037

Files:
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  clang/test/Analysis/symbol-simplification-symplify-results-in-dead-symbol.cpp


Index: 
clang/test/Analysis/symbol-simplification-symplify-results-in-dead-symbol.cpp
===
--- /dev/null
+++ 
clang/test/Analysis/symbol-simplification-symplify-results-in-dead-symbol.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// expected-no-diagnostics
+
+#define assert(cond) if (!(cond)) return
+
+unsigned a, b;
+void f(unsigned c) {
+  assert(c == b);
+  assert((c | a) != a);
+  assert(a); // no-crash
+}
Index: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
@@ -2678,7 +2678,18 @@
   if (OldState == State)
 continue;
 
-  assert(find(State, MemberSym) == find(State, SimplifiedMemberSym));
+  // Be aware that `SimplifiedMemberSym` might refer to an already dead
+  // symbol. In that case, the eqclass of that might not be the same as the
+  // eqclass of `MemberSym`. This is because the dead symbols are not
+  // preserved in the `ClassMap`, hence
+  // `find(State, SimplifiedMemberSym)` will result in a trivial eqclass
+  // compared to the eqclass of `MemberSym`.
+  // These eqclasses should be the same if `SimplifiedMemberSym` is alive.
+  // --> assert(find(State, MemberSym) == find(State, SimplifiedMemberSym))
+  //
+  // Note that `MemberSym` must be alive here since that is from the
+  // `ClassMembers` where all the symbols are alive.
+
   // Remove the old and more complex symbol.
   State = find(State, MemberSym).removeMember(State, MemberSym);
 


Index: clang/test/Analysis/symbol-simplification-symplify-results-in-dead-symbol.cpp
===
--- /dev/null
+++ clang/test/Analysis/symbol-simplification-symplify-results-in-dead-symbol.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// expected-no-diagnostics
+
+#define assert(cond) if (!(cond)) return
+
+unsigned a, b;
+void f(unsigned c) {
+  assert(c == b);
+  assert((c | a) != a);
+  assert(a); // no-crash
+}
Index: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
@@ -2678,7 +2678,18 @@
   if (OldState == State)
 continue;
 
-  assert(find(State, MemberSym) == find(State, SimplifiedMemberSym));
+  // Be aware that `SimplifiedMemberSym` might refer to an already dead
+  // symbol. In that case, the eqclass of that might not be the same as the
+  // eqclass of `MemberSym`. This is because the dead symbols are not
+  // preserved in the `ClassMap`, hence
+  // `find(State, SimplifiedMemberSym)` will result in a trivial eqclass
+  // compared to the eqclass of `MemberSym`.
+  // These eqclasses should be the same if `SimplifiedMemberSym` is alive.
+  // --> assert(find(State, MemberSym) == find(State, SimplifiedMemberSym))
+  //
+  // Note that `MemberSym` must be alive here since that is from the
+  // `ClassMembers` where all the symbols are alive.
+
   // Remove the old and more complex symbol.
   State = find(State, MemberSym).removeMember(State, MemberSym);
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D138037: [analyzer] Remove unjustified assertion from EQClass::simplify

2023-02-17 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

I'm backporting this as #60834 
 to the 16.x branch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138037

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


[clang] f3fa108 - [Clang] Convert some tests to opaque pointers (NFC)

2023-02-17 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2023-02-17T11:56:00+01:00
New Revision: f3fa1086c7f83edcc473724a8ac7d675a9df11d7

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

LOG: [Clang] Convert some tests to opaque pointers (NFC)

Added: 


Modified: 
clang/test/CodeGen/arm64-microsoft-arguments.cpp
clang/test/CodeGen/atomic-ops-libcall.c
clang/test/CodeGen/atomic-ops.c
clang/test/CodeGen/attr-nomerge.cpp
clang/test/CodeGen/attr-target-mv-va-args.c
clang/test/CodeGen/big-atomic-ops.c
clang/test/CodeGen/blocks.c
clang/test/CodeGen/bpf-attr-preserve-access-index-1.c
clang/test/CodeGen/bpf-attr-preserve-access-index-2.c
clang/test/CodeGen/builtin-preserve-access-index-array.c
clang/test/CodeGen/builtin-preserve-access-index-nonptr.c
clang/test/CodeGen/builtin-preserve-access-index-typedef.c
clang/test/CodeGen/builtin-preserve-access-index.c
clang/test/CodeGen/builtins-bpf-preserve-field-info-1.c
clang/test/CodeGen/builtins-bpf-preserve-field-info-2.c
clang/test/CodeGenCXX/microsoft-abi-thread-safe-statics.cpp

Removed: 




diff  --git a/clang/test/CodeGen/arm64-microsoft-arguments.cpp 
b/clang/test/CodeGen/arm64-microsoft-arguments.cpp
index ca1ff2025b74..a9ae6911b16e 100644
--- a/clang/test/CodeGen/arm64-microsoft-arguments.cpp
+++ b/clang/test/CodeGen/arm64-microsoft-arguments.cpp
@@ -1,9 +1,9 @@
-// RUN: %clang_cc1 -no-opaque-pointers -triple aarch64-windows -ffreestanding 
-emit-llvm -O0 \
+// RUN: %clang_cc1 -triple aarch64-windows -ffreestanding -emit-llvm -O0 \
 // RUN: -x c++ -o - %s | FileCheck %s
 
 // Pass and return for type size <= 8 bytes.
 // CHECK: define {{.*}} i64 @{{.*}}f1{{.*}}()
-// CHECK: call i64 {{.*}}func1{{.*}}(i64 %3)
+// CHECK: call i64 {{.*}}func1{{.*}}(i64 %0)
 struct S1 {
   int a[2];
 };
@@ -16,7 +16,7 @@ S1 f1() {
 
 // Pass and return type size <= 16 bytes.
 // CHECK: define {{.*}} [2 x i64] @{{.*}}f2{{.*}}()
-// CHECK: call [2 x i64] {{.*}}func2{{.*}}([2 x i64] %3)
+// CHECK: call [2 x i64] {{.*}}func2{{.*}}([2 x i64] %0)
 struct S2 {
   int a[4];
 };
@@ -28,8 +28,8 @@ S2 f2() {
 }
 
 // Pass and return for type size > 16 bytes.
-// CHECK: define {{.*}} void @{{.*}}f3{{.*}}(%struct.S3* noalias 
sret(%struct.S3) align 4 %agg.result)
-// CHECK: call void {{.*}}func3{{.*}}(%struct.S3* sret(%struct.S3) align 4 
%agg.result, %struct.S3* noundef %agg.tmp)
+// CHECK: define {{.*}} void @{{.*}}f3{{.*}}(ptr noalias sret(%struct.S3) 
align 4 %agg.result)
+// CHECK: call void {{.*}}func3{{.*}}(ptr sret(%struct.S3) align 4 
%agg.result, ptr noundef %agg.tmp)
 struct S3 {
   int a[5];
 };
@@ -42,8 +42,8 @@ S3 f3() {
 
 // Pass and return aggregate (of size < 16 bytes) with non-trivial destructor.
 // Passed directly but returned indirectly.
-// CHECK: define {{.*}} void {{.*}}f4{{.*}}(%struct.S4* inreg noalias 
sret(%struct.S4) align 4 %agg.result)
-// CHECK: call void {{.*}}func4{{.*}}(%struct.S4* inreg sret(%struct.S4) align 
4 %agg.result, [2 x i64] %5)
+// CHECK: define {{.*}} void {{.*}}f4{{.*}}(ptr inreg noalias sret(%struct.S4) 
align 4 %agg.result)
+// CHECK: call void {{.*}}func4{{.*}}(ptr inreg sret(%struct.S4) align 4 
%agg.result, [2 x i64] %0)
 struct S4 {
   int a[3];
   ~S4();
@@ -56,8 +56,8 @@ S4 f4() {
 }
 
 // Pass and return from instance method called from instance method.
-// CHECK: define {{.*}} void @{{.*}}bar@Q1{{.*}}(%class.Q1* {{[^,]*}} %this, 
%class.P1* inreg noalias sret(%class.P1) align 1 %agg.result)
-// CHECK: call void {{.*}}foo@P1{{.*}}(%class.P1* noundef{{[^,]*}} %ref.tmp, 
%class.P1* inreg sret(%class.P1) align 1 %agg.result, i8 %1)
+// CHECK: define {{.*}} void @{{.*}}bar@Q1{{.*}}(ptr {{[^,]*}} %this, ptr 
inreg noalias sret(%class.P1) align 1 %agg.result)
+// CHECK: call void {{.*}}foo@P1{{.*}}(ptr noundef{{[^,]*}} %ref.tmp, ptr 
inreg sret(%class.P1) align 1 %agg.result, i8 %0)
 
 class P1 {
 public:
@@ -76,7 +76,7 @@ P1 Q1::bar() {
 
 // Pass and return from instance method called from free function.
 // CHECK: define {{.*}} void {{.*}}bar{{.*}}()
-// CHECK: call void {{.*}}foo@P2{{.*}}(%class.P2* noundef{{[^,]*}} %ref.tmp, 
%class.P2* inreg sret(%class.P2) align 1 %retval, i8 %0)
+// CHECK: call void {{.*}}foo@P2{{.*}}(ptr noundef{{[^,]*}} %ref.tmp, ptr 
inreg sret(%class.P2) align 1 %retval, i8 %0)
 class P2 {
 public:
   P2 foo(P2 x);
@@ -89,8 +89,8 @@ P2 bar() {
 
 // Pass and return an object with a user-provided constructor (passed directly,
 // returned indirectly)
-// CHECK: define {{.*}} void @{{.*}}f5{{.*}}(%struct.S5* inreg noalias 
sret(%struct.S5) align 4 %agg.result)
-// CHECK: call void {{.*}}func5{{.*}}(%struct.S5* inreg sret(%struct.S5) align 
4 %agg.result, i64 {{.*}})
+// CHECK: define {{.*}} void @{{.*}}f5{{.*}}(ptr inreg noalias 
sret(%struct.S5) align 4

[PATCH] D138037: [analyzer] Remove unjustified assertion from EQClass::simplify

2023-02-17 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D138037#4129160 , @xazax.hun wrote:

> I am ok with committing this to unblock people hitting this assert, but at 
> the same time I wonder if we want to open a ticket on GitHub that we might 
> want to rethink how some of this works.

I created the ticket #60836  
to track this. I don't plan to work on it in the near and far future.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138037

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


[PATCH] D143096: [clangd] Provide patched diagnostics with preamble patch

2023-02-17 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 498308.
kadircet marked 6 inline comments as done.
kadircet added a comment.

- Move patch translation logic to a separate class
- Perform eager copies and use `bool translateX(X&)` type of APIs instead of 
returning optionals.
- Perform multi line content check for each alternative, not just the closest 
match.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143096

Files:
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/unittests/PreambleTests.cpp

Index: clang-tools-extra/clangd/unittests/PreambleTests.cpp
===
--- clang-tools-extra/clangd/unittests/PreambleTests.cpp
+++ clang-tools-extra/clangd/unittests/PreambleTests.cpp
@@ -723,9 +723,8 @@
 #define BAR
 #include [[]])");
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: We should point at the correct coordinates in NewCode.
 EXPECT_THAT(*AST->getDiagnostics(),
-ElementsAre(Diag(Code.range(), "pp_file_not_found")));
+ElementsAre(Diag(NewCode.range(), "pp_file_not_found")));
   }
   {
 // Check with removals from preamble.
@@ -734,18 +733,15 @@
 #include [[]])");
 Annotations NewCode("#include [[]]");
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: We should point at the correct coordinates in NewCode.
 EXPECT_THAT(*AST->getDiagnostics(),
-ElementsAre(Diag(Code.range(), "pp_file_not_found")));
+ElementsAre(Diag(NewCode.range(), "pp_file_not_found")));
   }
   {
 // Drop line with diags.
 Annotations Code("#include [[]]");
 Annotations NewCode("#define BAR\n#define BAZ\n");
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: No diagnostics.
-EXPECT_THAT(*AST->getDiagnostics(),
-ElementsAre(Diag(Code.range(), "pp_file_not_found")));
+EXPECT_THAT(*AST->getDiagnostics(), IsEmpty());
   }
   {
 // Picks closest line in case of multiple alternatives.
@@ -756,18 +752,79 @@
 #define BAR
 #include )");
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: We should point at the correct coordinates in NewCode.
 EXPECT_THAT(*AST->getDiagnostics(),
-ElementsAre(Diag(Code.range(), "pp_file_not_found")));
+ElementsAre(Diag(NewCode.range(), "pp_file_not_found")));
   }
   {
 // Drop diag if line spelling has changed.
 Annotations Code("#include [[]]");
 Annotations NewCode(" # include ");
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: No diags.
+EXPECT_THAT(*AST->getDiagnostics(), IsEmpty());
+  }
+  {
+// Multiple lines.
+Annotations Code(R"(
+#define BAR
+#include [[]])");
+Annotations NewCode(R"(#include [[]])");
+auto AST = createPatchedAST(Code.code(), NewCode.code());
 EXPECT_THAT(*AST->getDiagnostics(),
-ElementsAre(Diag(Code.range(), "pp_file_not_found")));
+ElementsAre(Diag(NewCode.range(), "pp_file_not_found")));
+  }
+  {
+// Multiple lines with change.
+Annotations Code(R"(
+#define BAR
+#include 
+#include [[]])");
+Annotations NewCode(R"(#include )");
+auto AST = createPatchedAST(Code.code(), NewCode.code());
+EXPECT_THAT(*AST->getDiagnostics(), IsEmpty());
+  }
+  {
+// Preserves notes.
+Annotations Code(R"(
+#define $note[[BAR]] 1
+#define $main[[BAR]] 2)");
+Annotations NewCode(R"(
+#define BAZ 0
+#define $note[[BAR]] 1
+#define BAZ 0
+#define $main[[BAR]] 2)");
+auto AST = createPatchedAST(Code.code(), NewCode.code());
+EXPECT_THAT(
+*AST->getDiagnostics(),
+ElementsAre(AllOf(Diag(NewCode.range("main"), "-Wmacro-redefined"),
+  withNote(Diag(NewCode.range("note"));
+  }
+  {
+// Preserves diag without note.
+Annotations Code(R"(
+#define $note[[BAR]] 1
+#define $main[[BAR]] 2)");
+Annotations NewCode(R"(
+#define $main[[BAR]] 2)");
+auto AST = createPatchedAST(Code.code(), NewCode.code());
+EXPECT_THAT(
+*AST->getDiagnostics(),
+ElementsAre(AllOf(Diag(NewCode.range("main"), "-Wmacro-redefined"),
+  Field(&Diag::Notes, IsEmpty();
+  }
+  {
+// Make sure orphaned notes are not promoted to diags.
+Annotations Code(R"(
+#define $note[[BAR]] 1
+#define $main[[BAR]] 2)");
+Annotations NewCode(R"(
+#define BAZ 0
+#define BAR 1)");
+auto AST = createPatchedAST(Code.code(), NewCode.code());
+EXPECT_THAT(*AST->getDiagnostics(), IsEmpty());
   }
 }
 } // namespace
Index: clang-tools-extra/clangd/Preamble.h
===
--- clang-tools-extra/clangd/Preamble.h
+++ clang-tools-extra/clangd/Preamble.h
@@ -34,6

[PATCH] D143096: [clangd] Provide patched diagnostics with preamble patch

2023-02-17 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/Preamble.cpp:625
+// same spelling.
+static std::vector patchDiags(llvm::ArrayRef BaselineDiags,
+const ScannedPreamble &BaselineScan,

sammccall wrote:
> I think this function is too long with too many local lambdas, consider 
> converting it to a class instead (call me old-fashioned!)
well it's gonna be an equally long class, but sure :D



Comment at: clang-tools-extra/clangd/Preamble.cpp:645
+auto ModifiedStartIt =
+ModifiedContentsToLine.find(BaselineScan.Lines[BaselineStart]);
+if (ModifiedStartIt == ModifiedContentsToLine.end())

sammccall wrote:
> we're assuming that the ranges are within the preamble and everyone agrees 
> about the bounds. If not, BaselineStart may not be a valid index into 
> BaselineScan.Lines
> 
> This assumption seems broadly reasonable, but is *very much* not locally 
> enforced. I'd suggest a defensive check or at least an assert.
oops, thanks! both here and also the multi-ine check below.



Comment at: clang-tools-extra/clangd/Preamble.cpp:648
+  return std::nullopt;
+int Closest = ModifiedStartIt->second.front();
+for (auto AlternateLine : ModifiedStartIt->second) {

sammccall wrote:
> this doesn't look right: you're first deciding which possible starting point 
> is closest, and then deciding whether it matches. So a range that matches can 
> be masked by a range where only the first line matches, if the latter is 
> closer.
i thought because this would be rare it's fine to not do that, but the same 
applies in the other direction as well :D
moved the content based matching inside the loop to consider a line as 
alternative only after it matches the contents.



Comment at: clang-tools-extra/clangd/Preamble.cpp:706
+Diag NewDiag;
+// Copy all fields but Notes, Fixes, Name and Tags.
+static_cast(NewDiag) = static_cast(D);

sammccall wrote:
> reasoning about the fields you're *not* rewriting feels fragile. (Here and in 
> TranslateFix).
> 
> Consider copying the whole object and mutating in place (`bool 
> TranslateDiag(Diag&)` together with `erase_if`)
well i am a little worried about copying around notes/fixes just to drop them 
again (which can have quite some strings). but probably rare enough in practice 
to not matter.



Comment at: clang-tools-extra/clangd/unittests/PreambleTests.cpp:820
+  {
+// Note is also dropped if diag is gone.
+Annotations Code(R"(

sammccall wrote:
> i'm confused about what this comment is getting at - a note without a diag is 
> not even representable
well, it is to make sure we're not promoting an orphaned note to a main diag. 
updated the comment but happy to drop if you think it's confusing rather than 
being helpful.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143096

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


[PATCH] D143096: [clangd] Provide patched diagnostics with preamble patch

2023-02-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

LG thanks!




Comment at: clang-tools-extra/clangd/Preamble.cpp:496
+auto CurrentStartIt = CurrentContentsToLine.find(OldLines[OldStart]);
+if (CurrentStartIt == CurrentContentsToLine.end())
+  return false;

up to you, but I find avoiding iterators easier to read

`for (int AlternateLine : CurrentContentsToLine.lookup(OldLines[OldStart]))`

(or with extracted variables)



Comment at: clang-tools-extra/clangd/Preamble.cpp:509
+  // Check if AlternateLine matches all lines in the range.
+  if (llvm::any_of(
+  llvm::zip_equal(RangeContents,

why not just `if (RangeContents != CurrentLines.slice(...))`? I feel like I'm 
missing something subtle :-)

Also if you replace the `slice(a, b)` with `drop_front(a).take_front(b)` then 
you don't need the `CurrentEnd > CurrentLines.size()` check



Comment at: clang-tools-extra/clangd/Preamble.cpp:517
+
+  if (Closest == -1 ||
+  abs(AlternateLine - OldStart) < abs(Closest - OldStart))

if you make `Closest` the delta rather than the line number this gets a bit 
easier to follow IMO:
`abs(Closest) < abs(Delta)` here
`R.start.line += Closest; R.end.line += Closest;` below

You need to make `Closest` an `optional` but that's also clearer than a 
sentinel -1 for me



Comment at: clang-tools-extra/clangd/Preamble.cpp:568
+
+Diag NewD = D;
+NewD.Range = NewRange;

FWIW if we're willing to pay a copy for a successful patch, I don't think it's 
worth any hassle to avoid the copy for a failed patch. Up to you though.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143096

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


[clang] 4901245 - Fix Clang sphinx build

2023-02-17 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2023-02-17T07:57:31-05:00
New Revision: 4901245481b6588056638b8fc38598615039314a

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

LOG: Fix Clang sphinx build

This addresses issues found in:
https://lab.llvm.org/buildbot/#/builders/92/builds/40269

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 70a91bab0cb2..b6d347392955 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -83,7 +83,7 @@ C Language Changes
 --
 - Support for outputs from asm goto statements along indirect edges has been
   added. This fixes
-  `Issue 53562 `_.
 
 C2x Feature Support
 ^^^



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


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

2023-02-17 Thread Whisperity via Phabricator via cfe-commits
whisperity added inline comments.



Comment at: clang-tools-extra/test/clang-tidy/checkers/cert/dcl58-cpp.cpp:3
+// RUN: %check_clang_tidy -std=c++17-or-later %s cert-dcl58-cpp %t -- -- -I 
%clang_tidy_headers -target aarch64
+// RUN: %check_clang_tidy -std=c++17-or-later %s cert-dcl58-cpp %t -- -- -I 
%clang_tidy_headers -target arm
+

balazske wrote:
> I am not sure if these platform specific should be added. A problem was 
> discovered on this platform but this could be true for all other tests.
I agree because there might be a case that some buildbot running the tests 
won't have these targets. If we really need to explicitly test something 
related to these targets, perhaps they should go into a separate file, and have 
a check-prefix. Or the expectation is that things work in the same way across 
all three platforms?



Comment at: clang/docs/ReleaseNotes.rst:63
   `Issue 60344 `_.
+- Fix importing of va_list types and declarations.
 




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142822

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


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

2023-02-17 Thread Whisperity via Phabricator via cfe-commits
whisperity added inline comments.



Comment at: clang-tools-extra/test/clang-tidy/checkers/cert/dcl58-cpp.cpp:5-6
+
+// On arm and arch64 architectures, va_list is within the std namespace.
+// D136886 exposed an issue in the cert-dcl58-cpp checker where
+// implicit namespaces were not ignored.

(Style nits.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142822

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


[PATCH] D140562: [clang][ASTImporter] Improve import of InjectedClassNameType.

2023-02-17 Thread Whisperity via Phabricator via cfe-commits
whisperity added inline comments.



Comment at: clang/lib/AST/ASTContext.cpp:4627
   } else {
-Type *newType =
-  new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
+Type *newType = new (*this, TypeAlignment) InjectedClassNameType(Decl, 
TST);
 Decl->TypeForDecl = newType;

(Potentially unrelated change, only touching the format?)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140562

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


[PATCH] D140562: [clang][ASTImporter] Improve import of InjectedClassNameType.

2023-02-17 Thread Whisperity via Phabricator via cfe-commits
whisperity added a subscriber: vabridgers.
whisperity added a comment.

@vabridgers Please take a look at this, as per off-list discussion, in relation 
to D142822 .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140562

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


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

2023-02-17 Thread Vince Bridgers via Phabricator via cfe-commits
vabridgers planned changes to this revision.
vabridgers added a comment.

Changes are planned. Please do not waste any more time on this for now. This 
will probably be abandoned.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142822

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


[PATCH] D141569: [clang-tidy] Implement CppCoreGuideline F.18

2023-02-17 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL added a comment.

I run this check on project that I work for, here my comments:

False-positives (for me)

  std::optional&& obj + std::move(opj.value());
  std::pair&& obj+ std::forward>(obj);
  Type1&& factory + factory.create() [on initialization list] (create is not && 
method)
  Type&& + member(std:move(obj.member)) [on initialization list]
  Type1&& + member(obj) + when Type1 its POD
  Type&& + x.emplace_back(std::move(obj.x)); y.emplace_back(std::move(obj.y)); 
- as function
  Type&& (unnamed) + throw UnimplementedException in virtual function
  X& operator=(Y&&)  - when we create locally X object and assign it via 
operator=(X&&), Y used only to access other data
  X&& + a = std::move(obj.x), b = std::move(obj.y) (any access to obj member is 
wraped via std::move, but not all members are moved)
  ^ same as above but some members are just used, for example instead of 
move std::optional we just copy value (if initialized)
  ^ same on initialization list
  XYZ&& as lambda argument (explicit) + std::forward(obj) in lambda with 
"using XYZ = std::vector<..>".
  X&& obj as argument + for(auto& v : obj) { something(std::move(v)); }
  X&& obj as argument + for(auto& v : obj) { something(std::move(v.x)); } 
  X&& obj (as function argument)+ lambda called in function [&](auto& v) { v.x 
= std::move(obj.x); }
  std::optional>&& obj + xyz.push_back({other.a, 
other.b, std::move(obj), other.c}); - vector type has no constructor, fields 
initialization
  container&& from + for(auto&& value : from) { if (x) { a = std::move(value); 
} else {dest.emplace_back(std::move(value)); } }
  const Type&& obj + std::move(obj) in function
  FlatMap&& obj + if (const auto it = obj.find(xyz)) { something = 
std::move(it->second); } + obj.clear() at end
  template SomeType serialize(const X&, OtherType&&, bool isSomething); (in 
header, private template function declaration with definition in cpp that also 
got warning)
  templateType& operator=(std::shared_ptr&& u) {  
assign(std::forward(u));   return *this; }
  template void XYZ::swap(XYZ&& other) { something.reset(); 
other.something.reset(); T::swap(other); (T is template parameter, for example 
std::map);
  Map&& xyz, auto&& found = xyz.find(value); if (found != xyz.cend()) { 
something.merge(found->second); }
  Map&& xyz, for(auto& [x,y] : xyz) { something.merge(y); }:
  constructor: explicit Something(T&& value) : value(std::forward(value)) 
{}, where T is class template argument

Overall 167 issues, half false-positive, but I already use other check for 
adding std::move, still had some good finding.
For some of the issues message is wrong, for example it could suggest moving 
some members (that were not moved) or use std::move instead of std::forward.
But for both cases probably other (new) checks could be better.

In summary:

- does not understand std::forward
- does not understand partial std::move
- does not understand ::swap and ::merge
- does not understand unused (unnamed) arguments
- some of use cases are && on purpose, just to hint user that passed value 
should be temporary, with const & it would accept also lvalue, such variables 
usually are created in place via constructor call or just initialization with 
{x, y, z}

I would say, do check more restricted, better is find less issues, than raising 
warnings on correct use-cases.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141569

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


[clang] 06621ec - [Clang] Convert some tests to opaque pointers (NFC)

2023-02-17 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2023-02-17T15:08:50+01:00
New Revision: 06621ecdaf416d87968dcaf57a634c83cf0dc1b8

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

LOG: [Clang] Convert some tests to opaque pointers (NFC)

Added: 


Modified: 
clang/test/CodeGen/math-builtins.c
clang/test/CodeGen/math-libcalls.c
clang/test/CodeGen/mult-alt-generic.c
clang/test/CodeGenCUDA/device-stub.cu
clang/test/CodeGenCUDA/static-device-var-rdc.cu
clang/test/CodeGenCXX/auto-var-init-stop-after.cpp

Removed: 




diff  --git a/clang/test/CodeGen/math-builtins.c 
b/clang/test/CodeGen/math-builtins.c
index 559421a4882c5..04738cce01073 100644
--- a/clang/test/CodeGen/math-builtins.c
+++ b/clang/test/CodeGen/math-builtins.c
@@ -1,7 +1,7 @@
-// RUN: %clang_cc1 -no-opaque-pointers -triple x86_64-unknown-unknown -w -S -o 
- -emit-llvm  %s | FileCheck %s -check-prefix=NO__ERRNO
-// RUN: %clang_cc1 -no-opaque-pointers -triple x86_64-unknown-unknown -w -S -o 
- -emit-llvm -fmath-errno %s | FileCheck %s -check-prefix=HAS_ERRNO
-// RUN: %clang_cc1 -no-opaque-pointers -triple x86_64-unknown-unknown-gnu -w 
-S -o - -emit-llvm -fmath-errno %s | FileCheck %s --check-prefix=HAS_ERRNO_GNU
-// RUN: %clang_cc1 -no-opaque-pointers -triple x86_64-unknown-windows-msvc -w 
-S -o - -emit-llvm -fmath-errno %s | FileCheck %s --check-prefix=HAS_ERRNO_WIN
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -w -S -o - -emit-llvm
  %s | FileCheck %s -check-prefix=NO__ERRNO
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -w -S -o - -emit-llvm 
-fmath-errno %s | FileCheck %s -check-prefix=HAS_ERRNO
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown-gnu -w -S -o - -emit-llvm 
-fmath-errno %s | FileCheck %s --check-prefix=HAS_ERRNO_GNU
+// RUN: %clang_cc1 -triple x86_64-unknown-windows-msvc -w -S -o - -emit-llvm 
-fmath-errno %s | FileCheck %s --check-prefix=HAS_ERRNO_WIN
 
 // Test attributes and codegen of math builtins.
 
@@ -52,14 +52,14 @@ void foo(double *d, float f, float *fp, long double *l, int 
*i, const char *c) {
 
   __builtin_frexp(f,i);__builtin_frexpf(f,i);   __builtin_frexpl(f,i); 
__builtin_frexpf128(f,i);
 
-// NO__ERRNO: declare double @frexp(double noundef, i32* noundef) 
[[NOT_READNONE:#[0-9]+]]
-// NO__ERRNO: declare float @frexpf(float noundef, i32* noundef) 
[[NOT_READNONE]]
-// NO__ERRNO: declare x86_fp80 @frexpl(x86_fp80 noundef, i32* noundef) 
[[NOT_READNONE]]
-// NO__ERRNO: declare fp128 @frexpf128(fp128 noundef, i32* noundef) 
[[NOT_READNONE]]
-// HAS_ERRNO: declare double @frexp(double noundef, i32* noundef) 
[[NOT_READNONE]]
-// HAS_ERRNO: declare float @frexpf(float noundef, i32* noundef) 
[[NOT_READNONE]]
-// HAS_ERRNO: declare x86_fp80 @frexpl(x86_fp80 noundef, i32* noundef) 
[[NOT_READNONE]]
-// HAS_ERRNO: declare fp128 @frexpf128(fp128 noundef, i32* noundef) 
[[NOT_READNONE]]
+// NO__ERRNO: declare double @frexp(double noundef, ptr noundef) 
[[NOT_READNONE:#[0-9]+]]
+// NO__ERRNO: declare float @frexpf(float noundef, ptr noundef) 
[[NOT_READNONE]]
+// NO__ERRNO: declare x86_fp80 @frexpl(x86_fp80 noundef, ptr noundef) 
[[NOT_READNONE]]
+// NO__ERRNO: declare fp128 @frexpf128(fp128 noundef, ptr noundef) 
[[NOT_READNONE]]
+// HAS_ERRNO: declare double @frexp(double noundef, ptr noundef) 
[[NOT_READNONE]]
+// HAS_ERRNO: declare float @frexpf(float noundef, ptr noundef) 
[[NOT_READNONE]]
+// HAS_ERRNO: declare x86_fp80 @frexpl(x86_fp80 noundef, ptr noundef) 
[[NOT_READNONE]]
+// HAS_ERRNO: declare fp128 @frexpf128(fp128 noundef, ptr noundef) 
[[NOT_READNONE]]
 
   __builtin_huge_val();__builtin_huge_valf();   __builtin_huge_vall(); 
__builtin_huge_valf128();
 
@@ -88,36 +88,36 @@ void foo(double *d, float f, float *fp, long double *l, int 
*i, const char *c) {
 
   __builtin_modf(f,d);   __builtin_modff(f,fp);  __builtin_modfl(f,l); 
__builtin_modff128(f,l);
 
-// NO__ERRNO: declare double @modf(double noundef, double* noundef) 
[[NOT_READNONE]]
-// NO__ERRNO: declare float @modff(float noundef, float* noundef) 
[[NOT_READNONE]]
-// NO__ERRNO: declare x86_fp80 @modfl(x86_fp80 noundef, x86_fp80* noundef) 
[[NOT_READNONE]]
-// NO__ERRNO: declare fp128 @modff128(fp128 noundef, fp128* noundef) 
[[NOT_READNONE]]
-// HAS_ERRNO: declare double @modf(double noundef, double* noundef) 
[[NOT_READNONE]]
-// HAS_ERRNO: declare float @modff(float noundef, float* noundef) 
[[NOT_READNONE]]
-// HAS_ERRNO: declare x86_fp80 @modfl(x86_fp80 noundef, x86_fp80* noundef) 
[[NOT_READNONE]]
-// HAS_ERRNO: declare fp128 @modff128(fp128 noundef, fp128* noundef) 
[[NOT_READNONE]]
+// NO__ERRNO: declare double @modf(double noundef, ptr noundef) 
[[NOT_READNONE]]
+// NO__ERRNO: declare float @modff(float noundef, ptr noundef) [[NOT_READNONE]]
+// NO__ERRNO: declare x86

[clang] 4bf6cc6 - GH60642: Fix ICE when checking a lambda defined in a concept definition

2023-02-17 Thread Erich Keane via cfe-commits

Author: Erich Keane
Date: 2023-02-17T06:09:52-08:00
New Revision: 4bf6cc63aa77a7fea7e410f7d45899abcde2b58a

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

LOG: GH60642: Fix ICE when checking a lambda defined in a concept definition

As reported in GH60642, we asserted when there was a lambda defined in a
template arguments inside of a concept, which caused us to not properly
set up the list of instantiation args.  This patch ensures that the
'lambda context decl' correctly falls-through the template argument
instantiation, so that it is available when instantiating the lambda,
and thus, when setting up the lambda instantiation args list.

Added: 


Modified: 
clang/lib/Sema/TreeTransform.h
clang/test/SemaTemplate/concepts-lambda.cpp

Removed: 




diff  --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index cca0383568201..09b4ac814c4d9 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -4569,7 +4569,7 @@ bool TreeTransform::TransformTemplateArgument(
 getSema(),
 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
: Sema::ExpressionEvaluationContext::ConstantEvaluated,
-/*LambdaContextDecl=*/nullptr, /*ExprContext=*/
+Sema::ReuseLambdaContextDecl, /*ExprContext=*/
 Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
 
 Expr *InputExpr = Input.getSourceExpression();

diff  --git a/clang/test/SemaTemplate/concepts-lambda.cpp 
b/clang/test/SemaTemplate/concepts-lambda.cpp
index eace722dd6616..8a184cbf4e9bc 100644
--- a/clang/test/SemaTemplate/concepts-lambda.cpp
+++ b/clang/test/SemaTemplate/concepts-lambda.cpp
@@ -1,6 +1,5 @@
 // RUN: %clang_cc1 -std=c++20 -verify %s
 // RUN: %clang_cc1 -std=c++20 -verify %s -triple powerpc64-ibm-aix
-// expected-no-diagnostics
 
 namespace GH57945 {
   template
@@ -92,3 +91,28 @@ struct Foo {
 static_assert(ConstructibleWithN);
 
 }
+
+// GH60642 reported an assert being hit, make sure we don't assert.
+namespace GH60642 {
+template concept C = requires { Q.template operator()(); };
+template concept D = true;
+static_assert(C<[]{}>);  // ok
+template concept E = C<[]{}>;
+static_assert(E);  // previously Asserted.
+
+// ensure we properly diagnose when "D" is false.
+namespace DIsFalse {
+template concept C = requires { Q.template operator()(); };
+template concept D = false;
+static_assert(C<[]{}>);
+// expected-error@-1{{static assertion failed}}
+// expected-note@-2{{does not satisfy 'C'}}
+// expected-note@-5{{because 'Q.template operator()()' would be 
invalid: no matching member function for call to 'operator()'}}
+template concept E = C<[]{}>;
+static_assert(E);
+// expected-error@-1{{static assertion failed}}
+// expected-note@-2{{because 'int' does not satisfy 'E'}}
+// expected-note@-4{{does not satisfy 'C'}}
+// expected-note@-11{{because 'Q.template operator()()' would be 
invalid: no matching member function for call to 'operator()'}}
+}
+}



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


[PATCH] D144192: GH60642: Fix ICE when checking a lambda defined in a concept definition

2023-02-17 Thread Erich Keane via Phabricator via cfe-commits
erichkeane abandoned this revision.
erichkeane added a comment.

Looks like I have ot abandon this now?  Anyway, fix was committed, but I forgot 
the differential-revision line.


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

https://reviews.llvm.org/D144192

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


[clang] af6c0b6 - [clang][CodeGen] Use base subobject type layout for potentially-overlapping fields

2023-02-17 Thread Vladislav Dzhidzhoev via cfe-commits

Author: Vladislav Dzhidzhoev
Date: 2023-02-17T15:11:42+01:00
New Revision: af6c0b6d8c9dc52485d56e82f79a03de09aa188f

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

LOG: [clang][CodeGen] Use base subobject type layout for 
potentially-overlapping fields

RecordLayoutBuilder assumes the size of a potentially-overlapping
class/struct field with non-zero size as the size of the base subobject
type corresponding to the field type.
Make CGRecordLayoutBuilder to acknowledge that in order to avoid incorrect
padding insertion.

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

Added: 
clang/test/CodeGenCXX/no-unique-address-3.cpp

Modified: 
clang/include/clang/AST/Decl.h
clang/lib/AST/Decl.cpp
clang/lib/AST/RecordLayoutBuilder.cpp
clang/lib/CodeGen/CGRecordLayoutBuilder.cpp

Removed: 




diff  --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index b32d021b1c695..e213c5fe29c68 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -3072,6 +3072,10 @@ class FieldDecl : public DeclaratorDecl, public 
Mergeable {
   /// [[no_unique_address]] attribute.
   bool isZeroSize(const ASTContext &Ctx) const;
 
+  /// Determine if this field is of potentially-overlapping class type, that
+  /// is, subobject with the [[no_unique_address]] attribute
+  bool isPotentiallyOverlapping() const;
+
   /// Get the kind of (C++11) default member initializer that this field has.
   InClassInitStyle getInClassInitStyle() const {
 InitStorageKind storageKind = InitStorage.getInt();

diff  --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index cd09e2fe2b05b..9c72d7a7d928c 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -4347,6 +4347,10 @@ bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
   return true;
 }
 
+bool FieldDecl::isPotentiallyOverlapping() const {
+  return hasAttr() && getType()->getAsCXXRecordDecl();
+}
+
 unsigned FieldDecl::getFieldIndex() const {
   const FieldDecl *Canonical = getCanonicalDecl();
   if (Canonical != this)

diff  --git a/clang/lib/AST/RecordLayoutBuilder.cpp 
b/clang/lib/AST/RecordLayoutBuilder.cpp
index 2f546398338c4..641e9d62149e9 100644
--- a/clang/lib/AST/RecordLayoutBuilder.cpp
+++ b/clang/lib/AST/RecordLayoutBuilder.cpp
@@ -1853,9 +1853,8 @@ void ItaniumRecordLayoutBuilder::LayoutBitField(const 
FieldDecl *D) {
 void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D,
  bool InsertExtraPadding) {
   auto *FieldClass = D->getType()->getAsCXXRecordDecl();
-  bool PotentiallyOverlapping = D->hasAttr() && 
FieldClass;
   bool IsOverlappingEmptyField =
-  PotentiallyOverlapping && FieldClass->isEmpty();
+  D->isPotentiallyOverlapping() && FieldClass->isEmpty();
 
   CharUnits FieldOffset =
   (IsUnion || IsOverlappingEmptyField) ? CharUnits::Zero() : getDataSize();
@@ -1916,7 +1915,7 @@ void ItaniumRecordLayoutBuilder::LayoutField(const 
FieldDecl *D,
 
 // A potentially-overlapping field occupies its dsize or nvsize, whichever
 // is larger.
-if (PotentiallyOverlapping) {
+if (D->isPotentiallyOverlapping()) {
   const ASTRecordLayout &Layout = Context.getASTRecordLayout(FieldClass);
   EffectiveFieldSize =
   std::max(Layout.getNonVirtualSize(), Layout.getDataSize());

diff  --git a/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp 
b/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
index 596f0bd332049..888b7ddcccd32 100644
--- a/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
+++ b/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
@@ -182,7 +182,7 @@ struct CGRecordLowering {
llvm::Type *StorageType);
   /// Lowers an ASTRecordLayout to a llvm type.
   void lower(bool NonVirtualBaseType);
-  void lowerUnion();
+  void lowerUnion(bool isNoUniqueAddress);
   void accumulateFields();
   void accumulateBitFields(RecordDecl::field_iterator Field,
RecordDecl::field_iterator FieldEnd);
@@ -280,7 +280,7 @@ void CGRecordLowering::lower(bool NVBaseType) {
   //CodeGenTypes::ComputeRecordLayout.
   CharUnits Size = NVBaseType ? Layout.getNonVirtualSize() : Layout.getSize();
   if (D->isUnion()) {
-lowerUnion();
+lowerUnion(NVBaseType);
 computeVolatileBitfields();
 return;
   }
@@ -308,8 +308,9 @@ void CGRecordLowering::lower(bool NVBaseType) {
   computeVolatileBitfields();
 }
 
-void CGRecordLowering::lowerUnion() {
-  CharUnits LayoutSize = Layout.getSize();
+void CGRecordLowering::lowerUnion(bool isNoUniqueAddress) {
+  CharUnits LayoutSize =
+  isNoUniqueAddress ? Layout.getDataSize() : Layout.getSize();
   llvm::Type *StorageType = nullptr;
   bool SeenNamedMember = false;
   // Iterate through the fields setting bitFiel

[PATCH] D139741: [clang][CodeGen] Use base subobject type layout for potentially-overlapping fields

2023-02-17 Thread Vladislav Dzhidzhoev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGaf6c0b6d8c9d: [clang][CodeGen] Use base subobject type 
layout for potentially-overlapping… (authored by dzhidzhoev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139741

Files:
  clang/include/clang/AST/Decl.h
  clang/lib/AST/Decl.cpp
  clang/lib/AST/RecordLayoutBuilder.cpp
  clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
  clang/test/CodeGenCXX/no-unique-address-3.cpp

Index: clang/test/CodeGenCXX/no-unique-address-3.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/no-unique-address-3.cpp
@@ -0,0 +1,209 @@
+// RUN: %clang_cc1 -triple aarch64-unknown-linux-gnu -emit-llvm -fdump-record-layouts -std=c++17 %s -o %t | FileCheck %s
+
+// CHECK-LABEL:  0 | class Empty (empty)
+// CHECK-NEXT: | [sizeof=1, dsize=1, align=1,
+// CHECK-NEXT: |  nvsize=1, nvalign=1]
+// CHECK-LABEL:  0 | class Second
+// CHECK-NEXT:   0 |   class Empty (base) (empty)
+// CHECK-NEXT:   0:0-0 |   short A
+// CHECK-NEXT: | [sizeof=2, dsize=1, align=2,
+// CHECK-NEXT: |  nvsize=1, nvalign=2]
+// CHECK-LABEL:  0 | class Foo
+// CHECK-NEXT:   0 |   class Empty (base) (empty)
+// CHECK-NEXT:   2 |   class Second NZNoUnique
+// CHECK-NEXT:   2 | class Empty (base) (empty)
+// CHECK-NEXT:   2:0-0 | short A
+// CHECK-NEXT:   3 |   char B
+// CHECK-NEXT: | [sizeof=4, dsize=4, align=2,
+// CHECK-NEXT: |  nvsize=4, nvalign=2]
+
+class Empty {};
+
+// CHECK-LABEL: LLVMType:%class.Second = type { i8, i8 }
+// CHECK-NEXT:  NonVirtualBaseLLVMType:%class.Second.base = type { i8 }
+class Second : Empty {
+  short A : 1;
+};
+
+// CHECK-LABEL:   LLVMType:%class.Foo = type { [2 x i8], %class.Second.base, i8 }
+// CHECK-NEXT:NonVirtualBaseLLVMType:%class.Foo = type { [2 x i8], %class.Second.base, i8 }
+class Foo : Empty {
+  [[no_unique_address]] Second NZNoUnique;
+  char B;
+};
+Foo I;
+
+// CHECK-LABEL:  0 | class SecondEmpty (empty)
+// CHECK-NEXT:   0 |   class Empty (base) (empty)
+// CHECK-NEXT: | [sizeof=1, dsize=0, align=1,
+// CHECK-NEXT: |  nvsize=1, nvalign=1]
+class SecondEmpty: Empty {
+};
+
+// CHECK-LABEL:  0 | class Bar
+// CHECK-NEXT:   0 |   class Empty (base) (empty)
+// CHECK-NEXT:   1 |   class SecondEmpty ZNoUnique (empty)
+// CHECK-NEXT:   1 | class Empty (base) (empty)
+// CHECK-NEXT:   0 |   char C
+// CHECK-NEXT: | [sizeof=2, dsize=1, align=1,
+// CHECK-NEXT: |  nvsize=2, nvalign=1]
+
+// CHECK-LABEL:  LLVMType:%class.Bar = type { i8, i8 }
+// CHECK-NEXT:   NonVirtualBaseLLVMType:%class.Bar = type { i8, i8 }
+class Bar : Empty {
+  [[no_unique_address]] SecondEmpty ZNoUnique;
+  char C;
+};
+Bar J;
+
+// CHECK-LABEL:  0 | class IntFieldClass
+// CHECK-NEXT:   0 |   class Empty (base) (empty)
+// CHECK-NEXT:   2 |   class Second Field
+// CHECK-NEXT:   2 | class Empty (base) (empty)
+// CHECK-NEXT:   2:0-0 | short A
+// CHECK-NEXT:   4 |   int C
+// CHECK-NEXT: | [sizeof=8, dsize=8, align=4,
+// CHECK-NEXT: |  nvsize=8, nvalign=4]
+
+// CHECK-LABEL:   LLVMType:%class.IntFieldClass = type { [2 x i8], %class.Second.base, i32 }
+// CHECK-NEXT:NonVirtualBaseLLVMType:%class.IntFieldClass = type { [2 x i8], %class.Second.base, i32 }
+class IntFieldClass : Empty {
+  [[no_unique_address]] Second Field;
+  int C;
+};
+IntFieldClass K;
+
+// CHECK-LABEL: 0 | class UnionClass
+// CHECK-NEXT:  0 |   class Empty (base) (empty)
+// CHECK-NEXT:  0 |   union UnionClass
+// CHECK-NEXT:  0 | int I
+// CHECK-NEXT:  0 | char C
+// CHECK-NEXT:  4 |   int C
+// CHECK-NEXT:| [sizeof=8, dsize=8, align=4,
+// CHECK-NEXT:|  nvsize=8, nvalign=4]
+
+// CHECK-LABEL:  LLVMType:%class.UnionClass = type { %union.anon, i32 }
+// CHECK-NEXT:   NonVirtualBaseLLVMType:%class.UnionClass = type { %union.anon, i32 }
+// CHECK-NEXT:   IsZeroInitializable:1
+// CHECK-NEXT:   BitFields:[
+// CHECK-NEXT: ]>
+class UnionClass : Empty {
+  [[no_unique_address]] union {
+int I;
+char C;
+  } U;
+  int C;
+};
+UnionClass L;
+
+// CHECK-LABEL: 0 | class EnumClass
+// CHECK-NEXT:  0 |   class Empty (base) (empty)
+// CHECK-NEXT:  0 |   enum E A
+// CHECK-NEXT:  4 |   int C
+// CHECK-NEXT:| [sizeof=8, dsize=8, align=4,
+// CHECK-NEXT:|  nvsize=8, nvalign=4]
+
+// CHECK-LABEL:  LLVMType:%class.EnumClass = type { i32, i32 }
+// CHECK-NEXT:   NonVirtualBaseLLVMType:%class.EnumClass = type { i32, i32 }
+// CHECK-NEXT:   IsZeroInitializable:1
+// CHECK-NEXT:   BitFie

[PATCH] D144192: GH60642: Fix ICE when checking a lambda defined in a concept definition

2023-02-17 Thread Nikolas Klauser via Phabricator via cfe-commits
philnik added a comment.

In D144192#4134887 , @erichkeane 
wrote:

> Looks like I have ot abandon this now?  Anyway, fix was committed, but I 
> forgot the differential-revision line.

You can also Close the revision instead of abandoning it to make it obvious 
that it has been landed.


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

https://reviews.llvm.org/D144192

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


[PATCH] D144192: GH60642: Fix ICE when checking a lambda defined in a concept definition

2023-02-17 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

In D144192#4134893 , @philnik wrote:

> In D144192#4134887 , @erichkeane 
> wrote:
>
>> Looks like I have ot abandon this now?  Anyway, fix was committed, but I 
>> forgot the differential-revision line.
>
> You can also Close the revision instead of abandoning it to make it obvious 
> that it has been landed.

I didn't actually have that option in the "Add Action" section?  I was looking 
for it, but it seems to have disappeared?


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

https://reviews.llvm.org/D144192

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


[PATCH] D144192: GH60642: Fix ICE when checking a lambda defined in a concept definition

2023-02-17 Thread Nikolas Klauser via Phabricator via cfe-commits
philnik added a comment.

In D144192#4134894 , @erichkeane 
wrote:

> In D144192#4134893 , @philnik wrote:
>
>> In D144192#4134887 , @erichkeane 
>> wrote:
>>
>>> Looks like I have ot abandon this now?  Anyway, fix was committed, but I 
>>> forgot the differential-revision line.
>>
>> You can also Close the revision instead of abandoning it to make it obvious 
>> that it has been landed.
>
> I didn't actually have that option in the "Add Action" section?  I was 
> looking for it, but it seems to have disappeared?

I have it on my open revisions, maybe you just missed it?


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

https://reviews.llvm.org/D144192

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


[PATCH] D144192: GH60642: Fix ICE when checking a lambda defined in a concept definition

2023-02-17 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

In D144192#4134900 , @philnik wrote:

> In D144192#4134894 , @erichkeane 
> wrote:
>
>> In D144192#4134893 , @philnik 
>> wrote:
>>
>>> In D144192#4134887 , @erichkeane 
>>> wrote:
>>>
 Looks like I have ot abandon this now?  Anyway, fix was committed, but I 
 forgot the differential-revision line.
>>>
>>> You can also Close the revision instead of abandoning it to make it obvious 
>>> that it has been landed.
>>
>> I didn't actually have that option in the "Add Action" section?  I was 
>> looking for it, but it seems to have disappeared?
>
> I have it on my open revisions, maybe you just missed it?

This is what I have for options on my open revisions (I went and grabbed a snap 
from a different review): https://imgur.com/a/WYD3uAV

So I don't see 'close' as an option?


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

https://reviews.llvm.org/D144192

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


[PATCH] D143984: [DebugMetadata] Simplify handling subprogram's retainedNodes field. NFCI (1/7)

2023-02-17 Thread Kristina Bessonova via Phabricator via cfe-commits
krisb created this revision.
Herald added a subscriber: hiraditya.
Herald added a project: All.
krisb edited the summary of this revision.
krisb added reviewers: dblaikie, jmmartinez.
krisb added projects: LLVM, debug-info.
krisb published this revision for review.
Herald added a project: clang.
Herald added subscribers: llvm-commits, cfe-commits.

RFC 
https://discourse.llvm.org/t/rfc-dwarfdebug-fix-and-improve-handling-imported-entities-types-and-static-local-in-subprogram-and-lexical-block-scopes/68544

Currently, `retainedNodes` tracks function-local variables and labels.
To support function-local import, types and static variables (which are globals
in LLVM IR), subsequent patches use the same field. So this patch makes
preliminary refactoring of the code tracking local entities to apply future
functional changes lucidly and cleanly.

No functional changes intended.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D143984

Files:
  clang/test/CodeGen/attr-btf_tag-disubprogram-callsite.c
  clang/test/CodeGenCXX/aix-static-init-debug-info.cpp
  clang/test/CodeGenCXX/debug-info-cxx1y.cpp
  clang/test/CodeGenCXX/debug-info-template.cpp
  clang/test/CodeGenObjC/debug-info-category.m
  llvm/include/llvm/IR/DIBuilder.h
  llvm/include/llvm/IR/DebugInfoMetadata.h
  llvm/lib/IR/DIBuilder.cpp

Index: llvm/lib/IR/DIBuilder.cpp
===
--- llvm/lib/IR/DIBuilder.cpp
+++ llvm/lib/IR/DIBuilder.cpp
@@ -57,23 +57,11 @@
 }
 
 void DIBuilder::finalizeSubprogram(DISubprogram *SP) {
-  MDTuple *Temp = SP->getRetainedNodes().get();
-  if (!Temp || !Temp->isTemporary())
-return;
-
-  SmallVector RetainedNodes;
-
-  auto PV = PreservedVariables.find(SP);
-  if (PV != PreservedVariables.end())
-RetainedNodes.append(PV->second.begin(), PV->second.end());
-
-  auto PL = PreservedLabels.find(SP);
-  if (PL != PreservedLabels.end())
-RetainedNodes.append(PL->second.begin(), PL->second.end());
-
-  DINodeArray Node = getOrCreateArray(RetainedNodes);
-
-  TempMDTuple(Temp)->replaceAllUsesWith(Node.get());
+  auto PN = SubprogramTrackedNodes.find(SP);
+  if (PN != SubprogramTrackedNodes.end())
+SP->replaceRetainedNodes(
+MDTuple::get(VMContext, SmallVector(PN->second.begin(),
+PN->second.end(;
 }
 
 void DIBuilder::finalize() {
@@ -772,26 +760,20 @@
 
 static DILocalVariable *createLocalVariable(
 LLVMContext &VMContext,
-DenseMap> &PreservedVariables,
-DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
+SmallVectorImpl &PreservedNodes,
+DIScope *Context, StringRef Name, unsigned ArgNo, DIFile *File,
 unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags,
 uint32_t AlignInBits, DINodeArray Annotations = nullptr) {
-  // FIXME: Why getNonCompileUnitScope()?
-  // FIXME: Why is "!Context" okay here?
   // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT
   // the only valid scopes)?
-  DIScope *Context = getNonCompileUnitScope(Scope);
-
-  auto *Node = DILocalVariable::get(
-  VMContext, cast_or_null(Context), Name, File, LineNo, Ty,
-  ArgNo, Flags, AlignInBits, Annotations);
+  auto *Scope = cast(Context);
+  auto *Node = DILocalVariable::get(VMContext, Scope, Name, File, LineNo, Ty,
+ArgNo, Flags, AlignInBits, Annotations);
   if (AlwaysPreserve) {
 // The optimizer may remove local variables. If there is an interest
 // to preserve variable info in such situation then stash it in a
 // named mdnode.
-DISubprogram *Fn = getDISubprogram(Scope);
-assert(Fn && "Missing subprogram for local variable");
-PreservedVariables[Fn].emplace_back(Node);
+PreservedNodes.emplace_back(Node);
   }
   return Node;
 }
@@ -801,9 +783,11 @@
DIType *Ty, bool AlwaysPreserve,
DINode::DIFlags Flags,
uint32_t AlignInBits) {
-  return createLocalVariable(VMContext, PreservedVariables, Scope, Name,
- /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve,
- Flags, AlignInBits);
+  assert(Scope && isa(Scope) &&
+ "Unexpected scope for a local variable.");
+  return createLocalVariable(
+  VMContext, getSubprogramNodesTrackingVector(Scope), Scope, Name,
+  /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve, Flags, AlignInBits);
 }
 
 DILocalVariable *DIBuilder::createParameterVariable(
@@ -811,25 +795,23 @@
 unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags,
 DINodeArray Annotations) {
   assert(ArgNo && "Expected non-zero argument number for parameter");
-  return createLocalVariable(VMContext, PreservedVariables, Scope, Name, ArgNo,
- File, LineNo, Ty, AlwaysPreserve, Flags,
- 

[PATCH] D144004: [DebugMetadata][DwarfDebug] Fix DWARF emisson of function-local imported entities (3/7)

2023-02-17 Thread Kristina Bessonova via Phabricator via cfe-commits
krisb created this revision.
Herald added subscribers: ormris, steven_wu, hiraditya.
Herald added a reviewer: sscalpone.
Herald added a project: All.
krisb edited the summary of this revision.
krisb added reviewers: dblaikie, jmmartinez, ellis.
krisb added projects: LLVM, debug-info.
krisb published this revision for review.
Herald added a project: clang.
Herald added subscribers: llvm-commits, cfe-commits.

RFC 
https://discourse.llvm.org/t/rfc-dwarfdebug-fix-and-improve-handling-imported-entities-types-and-static-local-in-subprogram-and-lexical-block-scopes/68544

Fixed PR51501 (tests from D112337 ).

This patch proposes two changes that get squashed to this single patch due to
their close dependencies:

1. Reuse of DISubprogram's 'retainedNodes' to track other function-local 
entities together with local variables and labels (this patch cares about 
function-local import while D144006  and 
D144008  use the same approach for local 
types and static variables). So, effectively this patch moves ownership of 
tracking local import from DICompileUnit's 'imports' field to DISubprogram's 
'retainedNodes' and adjusts DWARF emitter for the new layout. The old layout is 
considered unsupported (DwarfDebug would assert on such debug metadata).

  DICompileUnit's 'imports' field is supposed to track global imported 
declarations as it does before.

  This addresses various FIXMEs and simplifies the next part of the patch.

2. Postpone emission of function-local imported entities from 
`DwarfDebug::endFunctionImpl()` to `DwarfDebug::endModule()`. While in 
`DwarfDebug::endFunctionImpl()` we do not have all the information about a 
parent subprogram or a referring subprogram (whether a subprogram inlined or 
not), so we can't guarantee we emit an imported entity correctly and place it 
in a proper subprogram tree. So now, we just gather needed details about the 
import itself and its parent entity (either a Subprogram or a LexicalBlock) 
during processing in `DwarfDebug::endFunctionImpl()`, but all the real work is 
done in `DwarfDebug::endModule()` when we have all the required information to 
make proper emission.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144004

Files:
  clang/test/CodeGenCXX/debug-info-namespace.cpp
  llvm/include/llvm/IR/DIBuilder.h
  llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp
  llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.h
  llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp
  llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h
  llvm/lib/CodeGen/AsmPrinter/DwarfFile.h
  llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
  llvm/lib/CodeGen/AsmPrinter/DwarfUnit.h
  llvm/lib/IR/DIBuilder.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Linker/IRMover.cpp
  llvm/test/CodeGen/Generic/DbgValueAggregate.ll
  llvm/test/DebugInfo/Generic/import-inlined-declaration.ll
  llvm/test/DebugInfo/Generic/imported-name-inlined.ll
  llvm/test/DebugInfo/Generic/namespace.ll
  llvm/test/DebugInfo/Generic/split-dwarf-local-import.ll
  llvm/test/DebugInfo/Generic/split-dwarf-local-import2.ll
  llvm/test/DebugInfo/Generic/split-dwarf-local-import3.ll
  llvm/test/DebugInfo/Generic/verifier-invalid-disubprogram.ll
  llvm/test/DebugInfo/X86/dimodule-external-fortran.ll
  llvm/test/DebugInfo/X86/dwarfdump-DIImportedEntity_elements.ll
  llvm/test/DebugInfo/X86/fission-inline.ll
  llvm/test/DebugInfo/X86/fission-local-import.ll
  llvm/test/DebugInfo/X86/fission-no-inline-gsym.ll
  llvm/test/DebugInfo/X86/lexical-block-file-inline.ll
  llvm/test/DebugInfo/X86/namelist2.ll
  llvm/test/DebugInfo/omit-empty.ll
  llvm/test/ThinLTO/X86/debuginfo-cu-import.ll

Index: llvm/test/ThinLTO/X86/debuginfo-cu-import.ll
===
--- llvm/test/ThinLTO/X86/debuginfo-cu-import.ll
+++ llvm/test/ThinLTO/X86/debuginfo-cu-import.ll
@@ -5,15 +5,13 @@
 ; RUN: opt -module-summary %p/Inputs/debuginfo-cu-import.ll -o %t2.bc
 ; RUN: llvm-lto -thinlto-action=thinlink -o %t.index.bc %t1.bc %t2.bc
 
-; Don't import enums, macros, retainedTypes or globals lists.
-; Only import local scope imported entities.
+; Don't import enums, macros, retainedTypes, globals or imports lists.
 ; RUN: llvm-lto -thinlto-action=import %t2.bc -thinlto-index=%t.index.bc -o - | llvm-dis -o - | FileCheck %s
 ; CHECK-NOT: DICompileUnit{{.*}} enums:
 ; CHECK-NOT: DICompileUnit{{.*}} macros:
 ; CHECK-NOT: DICompileUnit{{.*}} retainedTypes:
 ; CHECK-NOT: DICompileUnit{{.*}} globals:
-; CHECK: DICompileUnit{{.*}} imports: ![[IMP:[0-9]+]]
-; CHECK: ![[IMP]] = !{!{{[0-9]+}}}
+; CHECK-NOT: DICompileUnit{{.*}} imports:
 
 ; ModuleID = 'debuginfo-cu-import.c'
 source_filename = "debuginfo-cu-import.c"
@@ -50,14 +48,14 @@
 !8 = !{!9}
 !9 = !DIGlobalVariableExpression(var: !10, expr: !DIExpression())
 !10 = !DIGlobalVariable(name: "version", scope: !4, file: !1, line: 2, type: !7, isLocal: false, isDefinition: true)
-!11 = !{!12, !1

[PATCH] D144192: GH60642: Fix ICE when checking a lambda defined in a concept definition

2023-02-17 Thread Nikolas Klauser via Phabricator via cfe-commits
philnik added a comment.

In D144192#4134902 , @erichkeane 
wrote:

> In D144192#4134900 , @philnik wrote:
>
>> In D144192#4134894 , @erichkeane 
>> wrote:
>>
>>> In D144192#4134893 , @philnik 
>>> wrote:
>>>
 In D144192#4134887 , @erichkeane 
 wrote:

> Looks like I have ot abandon this now?  Anyway, fix was committed, but I 
> forgot the differential-revision line.

 You can also Close the revision instead of abandoning it to make it 
 obvious that it has been landed.
>>>
>>> I didn't actually have that option in the "Add Action" section?  I was 
>>> looking for it, but it seems to have disappeared?
>>
>> I have it on my open revisions, maybe you just missed it?
>
> This is what I have for options on my open revisions (I went and grabbed a 
> snap from a different review): https://imgur.com/a/WYD3uAV
>
> So I don't see 'close' as an option?

Weird. I see a few more options: F26527345: Bildschirmfoto vom 2023-02-17 
15-30-33.png 


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

https://reviews.llvm.org/D144192

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


[PATCH] D144006: [DebugMetadata][DwarfDebug] Support function-local types in lexical block scopes (5/7)

2023-02-17 Thread Kristina Bessonova via Phabricator via cfe-commits
krisb created this revision.
Herald added a subscriber: hiraditya.
Herald added a project: All.
krisb edited the summary of this revision.
krisb added reviewers: dblaikie, jmmartinez.
krisb added projects: LLVM, debug-info.
krisb published this revision for review.
Herald added a project: clang.
Herald added subscribers: llvm-commits, cfe-commits.

RFC 
https://discourse.llvm.org/t/rfc-dwarfdebug-fix-and-improve-handling-imported-entities-types-and-static-local-in-subprogram-and-lexical-block-scopes/68544

Similar to imported declarations, the patch tracks function-local types in
DISubprogram's 'retainedNodes' field. DwarfDebug is adjusted in accordance with
the aforementioned metadata change and provided a support of function-local
types scoped within a lexical block.

The patch assumes that DICompileUnit's 'enums field' no longer tracks local
types and DwarfDebug would assert if any locally-scoped types get placed there.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144006

Files:
  clang/test/CodeGen/debug-info-codeview-unnamed.c
  clang/test/CodeGen/debug-info-unused-types.c
  clang/test/CodeGen/debug-info-unused-types.cpp
  clang/test/CodeGenCXX/debug-info-access.cpp
  clang/test/CodeGenCXX/debug-info-anon-union-vars.cpp
  clang/test/CodeGenCXX/debug-info-codeview-unnamed.cpp
  clang/test/CodeGenCXX/debug-info-gline-tables-only-codeview.cpp
  clang/test/CodeGenCXX/debug-lambda-this.cpp
  llvm/include/llvm/IR/DIBuilder.h
  llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp
  llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.h
  llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp
  llvm/lib/IR/DIBuilder.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/test/DebugInfo/Generic/inlined-local-type.ll
  llvm/test/DebugInfo/Generic/lexical-block-retained-types.ll
  llvm/test/DebugInfo/Generic/lexical-block-types.ll
  llvm/test/DebugInfo/Generic/local-type-as-template-parameter.ll
  llvm/test/DebugInfo/Generic/verifier-invalid-disubprogram.ll
  llvm/test/DebugInfo/X86/set.ll

Index: llvm/test/DebugInfo/X86/set.ll
===
--- llvm/test/DebugInfo/X86/set.ll
+++ llvm/test/DebugInfo/X86/set.ll
@@ -68,11 +68,11 @@
 !llvm.module.flags = !{!18, !19, !20}
 
 !0 = !{!"versions- cm3: d5.10.0 llvm: 9.0"}
-!1 = distinct !DICompileUnit(language: DW_LANG_Modula3, file: !2, producer: "cm3", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !3)
+!1 = distinct !DICompileUnit(language: DW_LANG_Modula3, file: !2, producer: "cm3", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug)
 !2 = !DIFile(filename: "Main.m3", directory: "/home/cm3/settest/src")
 !3 = !{!4}
 !4 = !DICompositeType(tag: DW_TAG_enumeration_type, name: "Enum", scope: !5, file: !2, line: 11, size: 8, align: 8, elements: !9)
-!5 = distinct !DISubprogram(name: "Test", linkageName: "Main__Test", scope: !2, file: !2, line: 11, type: !6, scopeLine: 11, spFlags: DISPFlagDefinition, unit: !1, retainedNodes: !8)
+!5 = distinct !DISubprogram(name: "Test", linkageName: "Main__Test", scope: !2, file: !2, line: 11, type: !6, scopeLine: 11, spFlags: DISPFlagDefinition, unit: !1, retainedNodes: !3)
 !6 = !DISubroutineType(types: !7)
 !7 = !{null}
 !8 = !{}
Index: llvm/test/DebugInfo/Generic/verifier-invalid-disubprogram.ll
===
--- llvm/test/DebugInfo/Generic/verifier-invalid-disubprogram.ll
+++ llvm/test/DebugInfo/Generic/verifier-invalid-disubprogram.ll
@@ -38,7 +38,7 @@
 define void @invalid_retained_nodes_list() !dbg !10 { ret void }
 !10 = distinct !DISubprogram(retainedNodes: !0)
 
-; CHECK: invalid retained nodes, expected DILocalVariable, DILabel or DIImportedEntity
+; CHECK: invalid retained nodes, expected DILocalVariable, DILabel, DIImportedEntity or DIType
 define void @invalid_retained_nodes_expected() !dbg !11 { ret void }
 !11 = distinct !DISubprogram(retainedNodes: !{!0})
 
Index: llvm/test/DebugInfo/Generic/local-type-as-template-parameter.ll
===
--- /dev/null
+++ llvm/test/DebugInfo/Generic/local-type-as-template-parameter.ll
@@ -0,0 +1,160 @@
+; RUN: %llc_dwarf -O0 -filetype=obj < %s  \
+; RUN:  | llvm-dwarfdump --show-children --name=foo - \
+; RUN:  | FileCheck --implicit-check-not "{{DW_TAG|NULL}}" %s
+
+; The test ensures that AsmPrinter doesn't crashed compiling this.
+; It also demostrates misplacement for a local type (see PR55680 for details).
+
+; The test compiled from:
+
+; template
+; struct A {
+;   A(T &in) : a(in) {}
+;   T a;
+; };
+;
+; __attribute__((always_inline))
+; void foo() {
+;   struct B { int i; };
+;   B objB;
+;   A objA(objB);
+; }
+;
+; int main() {
+;   foo();
+; }
+
+; Concrete out-of-line tree of foo().
+; CHECK: DW_TAG_subprogram
+; CHECK:   DW_AT_abstract_origin {{.*}} "_Z3foov"
+;
+; CHECK:   DW_TAG_variable
+; CHECK: DW_AT_abstract_origin {{.*}} "objB"
+; CHECK:   DW_TAG_variable
+; CHECK: D

[PATCH] D143096: [clangd] Provide patched diagnostics with preamble patch

2023-02-17 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 498351.
kadircet marked 4 inline comments as done.
kadircet added a comment.

- Use direct comparison of ArrayRefs
- optional for closest
- loop over lookup results rather than through iterator


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143096

Files:
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/unittests/PreambleTests.cpp

Index: clang-tools-extra/clangd/unittests/PreambleTests.cpp
===
--- clang-tools-extra/clangd/unittests/PreambleTests.cpp
+++ clang-tools-extra/clangd/unittests/PreambleTests.cpp
@@ -723,9 +723,8 @@
 #define BAR
 #include [[]])");
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: We should point at the correct coordinates in NewCode.
 EXPECT_THAT(*AST->getDiagnostics(),
-ElementsAre(Diag(Code.range(), "pp_file_not_found")));
+ElementsAre(Diag(NewCode.range(), "pp_file_not_found")));
   }
   {
 // Check with removals from preamble.
@@ -734,18 +733,15 @@
 #include [[]])");
 Annotations NewCode("#include [[]]");
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: We should point at the correct coordinates in NewCode.
 EXPECT_THAT(*AST->getDiagnostics(),
-ElementsAre(Diag(Code.range(), "pp_file_not_found")));
+ElementsAre(Diag(NewCode.range(), "pp_file_not_found")));
   }
   {
 // Drop line with diags.
 Annotations Code("#include [[]]");
 Annotations NewCode("#define BAR\n#define BAZ\n");
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: No diagnostics.
-EXPECT_THAT(*AST->getDiagnostics(),
-ElementsAre(Diag(Code.range(), "pp_file_not_found")));
+EXPECT_THAT(*AST->getDiagnostics(), IsEmpty());
   }
   {
 // Picks closest line in case of multiple alternatives.
@@ -756,18 +752,79 @@
 #define BAR
 #include )");
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: We should point at the correct coordinates in NewCode.
 EXPECT_THAT(*AST->getDiagnostics(),
-ElementsAre(Diag(Code.range(), "pp_file_not_found")));
+ElementsAre(Diag(NewCode.range(), "pp_file_not_found")));
   }
   {
 // Drop diag if line spelling has changed.
 Annotations Code("#include [[]]");
 Annotations NewCode(" # include ");
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: No diags.
+EXPECT_THAT(*AST->getDiagnostics(), IsEmpty());
+  }
+  {
+// Multiple lines.
+Annotations Code(R"(
+#define BAR
+#include [[]])");
+Annotations NewCode(R"(#include [[]])");
+auto AST = createPatchedAST(Code.code(), NewCode.code());
 EXPECT_THAT(*AST->getDiagnostics(),
-ElementsAre(Diag(Code.range(), "pp_file_not_found")));
+ElementsAre(Diag(NewCode.range(), "pp_file_not_found")));
+  }
+  {
+// Multiple lines with change.
+Annotations Code(R"(
+#define BAR
+#include 
+#include [[]])");
+Annotations NewCode(R"(#include )");
+auto AST = createPatchedAST(Code.code(), NewCode.code());
+EXPECT_THAT(*AST->getDiagnostics(), IsEmpty());
+  }
+  {
+// Preserves notes.
+Annotations Code(R"(
+#define $note[[BAR]] 1
+#define $main[[BAR]] 2)");
+Annotations NewCode(R"(
+#define BAZ 0
+#define $note[[BAR]] 1
+#define BAZ 0
+#define $main[[BAR]] 2)");
+auto AST = createPatchedAST(Code.code(), NewCode.code());
+EXPECT_THAT(
+*AST->getDiagnostics(),
+ElementsAre(AllOf(Diag(NewCode.range("main"), "-Wmacro-redefined"),
+  withNote(Diag(NewCode.range("note"));
+  }
+  {
+// Preserves diag without note.
+Annotations Code(R"(
+#define $note[[BAR]] 1
+#define $main[[BAR]] 2)");
+Annotations NewCode(R"(
+#define $main[[BAR]] 2)");
+auto AST = createPatchedAST(Code.code(), NewCode.code());
+EXPECT_THAT(
+*AST->getDiagnostics(),
+ElementsAre(AllOf(Diag(NewCode.range("main"), "-Wmacro-redefined"),
+  Field(&Diag::Notes, IsEmpty();
+  }
+  {
+// Make sure orphaned notes are not promoted to diags.
+Annotations Code(R"(
+#define $note[[BAR]] 1
+#define $main[[BAR]] 2)");
+Annotations NewCode(R"(
+#define BAZ 0
+#define BAR 1)");
+auto AST = createPatchedAST(Code.code(), NewCode.code());
+EXPECT_THAT(*AST->getDiagnostics(), IsEmpty());
   }
 }
 } // namespace
Index: clang-tools-extra/clangd/Preamble.h
===
--- clang-tools-extra/clangd/Preamble.h
+++ clang-tools-extra/clangd/Preamble.h
@@ -34,6 +34,7 @@
 #include "clang/Frontend/PrecompiledPreamble.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Compil

[PATCH] D143096: [clangd] Provide patched diagnostics with preamble patch

2023-02-17 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

thanks for the review!




Comment at: clang-tools-extra/clangd/Preamble.cpp:509
+  // Check if AlternateLine matches all lines in the range.
+  if (llvm::any_of(
+  llvm::zip_equal(RangeContents,

sammccall wrote:
> why not just `if (RangeContents != CurrentLines.slice(...))`? I feel like I'm 
> missing something subtle :-)
> 
> Also if you replace the `slice(a, b)` with `drop_front(a).take_front(b)` then 
> you don't need the `CurrentEnd > CurrentLines.size()` check
> why not just if (RangeContents != CurrentLines.slice(...))? I feel like I'm 
> missing something subtle :-)

no that's absolutely right, i guess i had a brain fart 😂 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143096

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


[clang] 17a90f1 - Tighten up a modules test

2023-02-17 Thread Paul Robinson via cfe-commits

Author: Paul Robinson
Date: 2023-02-17T06:35:01-08:00
New Revision: 17a90f1196c1a4b48b8d02c055497565ce5c785d

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

LOG: Tighten up a modules test

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

Added: 


Modified: 
clang/test/CXX/module/basic/basic.def.odr/p4.cppm

Removed: 




diff  --git a/clang/test/CXX/module/basic/basic.def.odr/p4.cppm 
b/clang/test/CXX/module/basic/basic.def.odr/p4.cppm
index a07913c1e08e1..b8f24d3ed5c8a 100644
--- a/clang/test/CXX/module/basic/basic.def.odr/p4.cppm
+++ b/clang/test/CXX/module/basic/basic.def.odr/p4.cppm
@@ -2,7 +2,7 @@
 // RUN: mkdir %t
 // RUN: split-file %s %t
 //
-// RUN: %clang_cc1 -std=c++20 %t/Module.cppm -triple %itanium_abi_triple 
-emit-llvm -o - | FileCheck %t/Module.cppm --implicit-check-not unused_inline 
--implicit-check-not unused_stastic_global_module
+// RUN: %clang_cc1 -std=c++20 %t/Module.cppm -triple %itanium_abi_triple 
-emit-llvm -o - | FileCheck %t/Module.cppm --implicit-check-not unused
 //
 // RUN: %clang_cc1 -std=c++20 %t/Module.cppm -triple %itanium_abi_triple 
-emit-module-interface -o %t/Module.pcm
 // RUN: %clang_cc1 -std=c++20 %t/module.cpp -triple %itanium_abi_triple 
-fmodule-file=%t/Module.pcm -emit-llvm -o - | FileCheck %t/module.cpp 
--implicit-check-not=unused --implicit-check-not=global_module
@@ -33,8 +33,6 @@
 // CHECK-DAG: @_ZL24const_var_module_linkage = internal
 //
 // CHECK-DAG: @_ZW6Module25unused_var_module_linkage = {{(dso_local )?}}global 
i32 4
-// CHECK-NOT: @_ZW6Module32unused_static_var_module_linkage =
-// CHECK-NOT: @_ZW6Module31unused_const_var_module_linkage =
 
 module;
 
@@ -85,7 +83,6 @@ export {
   }
 }
 
-// CHECK-NOT: define {{(dso_local )?}}void 
{{.*}}@_ZW6Module28unused_static_module_linkagev
 static void unused_static_module_linkage() {}
 
 static void used_static_module_linkage() {}



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


[PATCH] D144188: Tighten up a modules test

2023-02-17 Thread Paul Robinson via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG17a90f1196c1: Tighten up a modules test (authored by 
probinson).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144188

Files:
  clang/test/CXX/module/basic/basic.def.odr/p4.cppm


Index: clang/test/CXX/module/basic/basic.def.odr/p4.cppm
===
--- clang/test/CXX/module/basic/basic.def.odr/p4.cppm
+++ clang/test/CXX/module/basic/basic.def.odr/p4.cppm
@@ -2,7 +2,7 @@
 // RUN: mkdir %t
 // RUN: split-file %s %t
 //
-// RUN: %clang_cc1 -std=c++20 %t/Module.cppm -triple %itanium_abi_triple 
-emit-llvm -o - | FileCheck %t/Module.cppm --implicit-check-not unused_inline 
--implicit-check-not unused_stastic_global_module
+// RUN: %clang_cc1 -std=c++20 %t/Module.cppm -triple %itanium_abi_triple 
-emit-llvm -o - | FileCheck %t/Module.cppm --implicit-check-not unused
 //
 // RUN: %clang_cc1 -std=c++20 %t/Module.cppm -triple %itanium_abi_triple 
-emit-module-interface -o %t/Module.pcm
 // RUN: %clang_cc1 -std=c++20 %t/module.cpp -triple %itanium_abi_triple 
-fmodule-file=%t/Module.pcm -emit-llvm -o - | FileCheck %t/module.cpp 
--implicit-check-not=unused --implicit-check-not=global_module
@@ -33,8 +33,6 @@
 // CHECK-DAG: @_ZL24const_var_module_linkage = internal
 //
 // CHECK-DAG: @_ZW6Module25unused_var_module_linkage = {{(dso_local )?}}global 
i32 4
-// CHECK-NOT: @_ZW6Module32unused_static_var_module_linkage =
-// CHECK-NOT: @_ZW6Module31unused_const_var_module_linkage =
 
 module;
 
@@ -85,7 +83,6 @@
   }
 }
 
-// CHECK-NOT: define {{(dso_local )?}}void 
{{.*}}@_ZW6Module28unused_static_module_linkagev
 static void unused_static_module_linkage() {}
 
 static void used_static_module_linkage() {}


Index: clang/test/CXX/module/basic/basic.def.odr/p4.cppm
===
--- clang/test/CXX/module/basic/basic.def.odr/p4.cppm
+++ clang/test/CXX/module/basic/basic.def.odr/p4.cppm
@@ -2,7 +2,7 @@
 // RUN: mkdir %t
 // RUN: split-file %s %t
 //
-// RUN: %clang_cc1 -std=c++20 %t/Module.cppm -triple %itanium_abi_triple -emit-llvm -o - | FileCheck %t/Module.cppm --implicit-check-not unused_inline --implicit-check-not unused_stastic_global_module
+// RUN: %clang_cc1 -std=c++20 %t/Module.cppm -triple %itanium_abi_triple -emit-llvm -o - | FileCheck %t/Module.cppm --implicit-check-not unused
 //
 // RUN: %clang_cc1 -std=c++20 %t/Module.cppm -triple %itanium_abi_triple -emit-module-interface -o %t/Module.pcm
 // RUN: %clang_cc1 -std=c++20 %t/module.cpp -triple %itanium_abi_triple -fmodule-file=%t/Module.pcm -emit-llvm -o - | FileCheck %t/module.cpp --implicit-check-not=unused --implicit-check-not=global_module
@@ -33,8 +33,6 @@
 // CHECK-DAG: @_ZL24const_var_module_linkage = internal
 //
 // CHECK-DAG: @_ZW6Module25unused_var_module_linkage = {{(dso_local )?}}global i32 4
-// CHECK-NOT: @_ZW6Module32unused_static_var_module_linkage =
-// CHECK-NOT: @_ZW6Module31unused_const_var_module_linkage =
 
 module;
 
@@ -85,7 +83,6 @@
   }
 }
 
-// CHECK-NOT: define {{(dso_local )?}}void {{.*}}@_ZW6Module28unused_static_module_linkagev
 static void unused_static_module_linkage() {}
 
 static void used_static_module_linkage() {}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D125693: [DebugInfo] Support types, imports and static locals declared in a lexical block (3/5)

2023-02-17 Thread Kristina Bessonova via Phabricator via cfe-commits
krisb abandoned this revision.
krisb added a comment.

Abandon in favor of 
https://discourse.llvm.org/t/rfc-dwarfdebug-fix-and-improve-handling-imported-entities-types-and-static-local-in-subprogram-and-lexical-block-scopes/68544.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125693

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


[PATCH] D144269: [Analyzer] Show "taint originated here" note of alpha.security.taint.TaintPropagation checker at the correct place

2023-02-17 Thread Daniel Krupp via Phabricator via cfe-commits
dkrupp created this revision.
dkrupp added a reviewer: Szelethus.
dkrupp added a project: clang.
Herald added subscribers: steakhal, manas, ASDenysPetrov, martong, gamesh411, 
donat.nagy, mikhail.ramalho, a.sidorin, JDevlieghere, rnkovacs, szepet, 
baloghadamsoftware, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
dkrupp requested review of this revision.
Herald added a subscriber: cfe-commits.

This patch improves the diagnostics of the 
alpha.security.taint.TaintPropagation and taint related checkers by showing the 
"Taint originated here" note at the correct place, where the attacker may 
inject it. This greatly improves the understandability of the taint reports.

Taint Analysis: The attacker injects the malicious data at the taint source 
(e.g. getenv() call) which is then propagated and used at taint sink (e.g. 
exec() call) causing a security vulnerability (e.g. shell injection 
vulnerability), without data sanitation.

The goal of the checker is to discover and show to the user these potential 
taint source, sink pairs and the propagation call chain.

In the baseline the taint source was pointing to an invalid location, typically 
somewhere between the real taint source and sink.

After the fix, the "Taint originated here" tag is correctly shown at the taint 
source. This is the function call where the attacker can inject a malicious 
data (e.g. reading from environment variable, reading from file, reading from 
standard input etc.).

Before the patch the clang static analyzer puts the taint origin note wrongly 
to the `strtol(..)` call.

  c
  int main(){
char *pathbuf;
char *user_data=getenv("USER_INPUT"); 
char *end;  
long size=strtol(user_data, &end, 10); // note: Taint originated here. 
if (size > 0){
  pathbuf=(char*) malloc(size+1);//note: Untrusted data is used to specify 
the buffer size ...
  // ... 
  free(pathbuf);
}
return 0;
  }

After the fix, the taint origin point is correctly annotated at `getenv()` 
where the attacker really injects the value.

  c
  int main(){
char *pathbuf;
char *user_data=getenv("USER_INPUT");  // note: Taint originated here. 
char *end;
long size=strtol(user_data, &end, 10); 
if (size > 0){
  pathbuf=(char*) malloc(size+1);//note: Untrusted data is used to specify 
the buffer size ...
  // ... 
  free(pathbuf);
}
return 0;
  }

The BugVisitor placing the note was wrongly going back only until introduction 
of the tainted SVal in the sink.

This patch creates a new uniquely identified taint flow for each taint source 
(e.g.getenv()) it traverses and places a NoteTag ("Taint originated here") with 
the new id. Then, when the bug report is generated, the taint flow id is 
propagated back (in the new TainBugReport) along the bug path and the correct 
"Taint originated here." annotation is generated (matching the flow id).

You can find the new improved reports

here 


And the old reports (look out for "Taint originated here" notes. They are at 
the wrong place, close to the end of the reports)

here 



Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144269

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Taint.h
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
  clang/include/clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h
  clang/include/clang/StaticAnalyzer/Core/BugReporter/TaintBugType.h
  clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
  clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/Taint.cpp
  clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporter.cpp
  clang/lib/StaticAnalyzer/Core/CommonBugCategories.cpp
  
clang/test/Analysis/diagnostics/Inputs/expected-sarif/sarif-diagnostics-taint-test.c.sarif
  
clang/test/Analysis/diagnostics/Inputs/expected-sarif/sarif-multi-diagnostic-test.c.sarif
  clang/test/Analysis/diagnostics/sarif-diagnostics-taint-test.c
  clang/test/Analysis/taint-checker-callback-order-has-definition.c
  clang/test/Analysis/taint-checker-callback-order-without-definition.c
  clang/test/Analysis/taint-diagnostic-visitor.c
  clang/test/Analysis/taint-dumps.c

Index: clang/test/Analysis/taint-dumps.c
=

[PATCH] D143825: [clang-format] Put ports on separate lines in Verilog module headers

2023-02-17 Thread sstwcw via Phabricator via cfe-commits
sstwcw marked 3 inline comments as done.
sstwcw added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:2836
+  Tok = Tok->getNextNonComment();
+  } else if (Tok->is(tok::hashhash)) {
+// Concatenation. Skip.

MyDeveloperDay wrote:
> are we covering these cases in the unit tests
I added a test on line 432.



Comment at: clang/lib/Format/TokenAnnotator.cpp:2846
+// The name may have dots like `interface_foo.modport_foo`.
+while (Tok != nullptr && Tok->isOneOf(tok::period, tok::coloncolon) &&
+   (Tok = Tok->getNextNonComment())) {

MyDeveloperDay wrote:
> are we covering these cases in the unit tests
I added a test on line 374.



Comment at: clang/lib/Format/TokenAnnotator.cpp:4365
+if (Right.is(tok::l_paren) && Right.is(TT_VerilogStrength))
+  return true;
   }

MyDeveloperDay wrote:
> Is this an unrelated change? if not can you add an test
I added a test on line 255.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143825

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


[PATCH] D143825: [clang-format] Put ports on separate lines in Verilog module headers

2023-02-17 Thread sstwcw via Phabricator via cfe-commits
sstwcw updated this revision to Diff 498376.
sstwcw marked 3 inline comments as done.
sstwcw added a comment.

- add tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143825

Files:
  clang/lib/Format/FormatToken.h
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTestVerilog.cpp

Index: clang/unittests/Format/FormatTestVerilog.cpp
===
--- clang/unittests/Format/FormatTestVerilog.cpp
+++ clang/unittests/Format/FormatTestVerilog.cpp
@@ -252,6 +252,34 @@
Style);
 }
 
+TEST_F(FormatTestVerilog, Declaration) {
+  verifyFormat("wire mynet;");
+  verifyFormat("wire mynet, mynet1;");
+  verifyFormat("wire mynet, //\n"
+   " mynet1;");
+  verifyFormat("wire mynet = enable;");
+  verifyFormat("wire mynet = enable, mynet1;");
+  verifyFormat("wire mynet = enable, //\n"
+   " mynet1;");
+  verifyFormat("wire mynet, mynet1 = enable;");
+  verifyFormat("wire mynet, //\n"
+   " mynet1 = enable;");
+  verifyFormat("wire mynet = enable, mynet1 = enable;");
+  verifyFormat("wire mynet = enable, //\n"
+   " mynet1 = enable;");
+  verifyFormat("wire (strong1, pull0) mynet;");
+  verifyFormat("wire (strong1, pull0) mynet, mynet1;");
+  verifyFormat("wire (strong1, pull0) mynet, //\n"
+   "  mynet1;");
+  verifyFormat("wire (strong1, pull0) mynet = enable;");
+  verifyFormat("wire (strong1, pull0) mynet = enable, mynet1;");
+  verifyFormat("wire (strong1, pull0) mynet = enable, //\n"
+   "  mynet1;");
+  verifyFormat("wire (strong1, pull0) mynet, mynet1 = enable;");
+  verifyFormat("wire (strong1, pull0) mynet, //\n"
+   "  mynet1 = enable;");
+}
+
 TEST_F(FormatTestVerilog, Delay) {
   // Delay by the default unit.
   verifyFormat("#0;");
@@ -275,6 +303,155 @@
 "x = x;"));
 }
 
+TEST_F(FormatTestVerilog, Headers) {
+  // Test headers with multiple ports.
+  verifyFormat("module mh1\n"
+   "(input var int in1,\n"
+   " input var shortreal in2,\n"
+   " output tagged_st out);\n"
+   "endmodule");
+  // Ports should be grouped by types.
+  verifyFormat("module test\n"
+   "(input [7 : 0] a,\n"
+   " input signed [7 : 0] b, c, d);\n"
+   "endmodule");
+  verifyFormat("module test\n"
+   "(input [7 : 0] a,\n"
+   " (* x = x *) input signed [7 : 0] b, c, d);\n"
+   "endmodule");
+  verifyFormat("module test\n"
+   "(input [7 : 0] a = 0,\n"
+   " input signed [7 : 0] b = 0, c = 0, d = 0);\n"
+   "endmodule");
+  verifyFormat("module test\n"
+   "#(parameter x)\n"
+   "(input [7 : 0] a,\n"
+   " input signed [7 : 0] b, c, d);\n"
+   "endmodule");
+  // When a line needs to be broken, ports of the same type should be aligned to
+  // the same column.
+  verifyFormat("module test\n"
+   "(input signed [7 : 0] b, c, //\n"
+   "  d);\n"
+   "endmodule");
+  verifyFormat("module test\n"
+   "((* x = x *) input signed [7 : 0] b, c, //\n"
+   "  d);\n"
+   "endmodule");
+  verifyFormat("module test\n"
+   "(input signed [7 : 0] b = 0, c, //\n"
+   "  d);\n"
+   "endmodule");
+  verifyFormat("module test\n"
+   "(input signed [7 : 0] b, c = 0, //\n"
+   "  d);\n"
+   "endmodule");
+  verifyFormat("module test\n"
+   "(input signed [7 : 0] b, c, //\n"
+   "  d = 0);\n"
+   "endmodule");
+  verifyFormat("module test\n"
+   "(input wire logic signed [7 : 0][0 : 1] b, c, //\n"
+   "d);\n"
+   "endmodule");
+  verifyFormat("module test\n"
+   "(input signed [7 : 0] b, //\n"
+   "  c, //\n"
+   "  d);\n"
+   "endmodule");
+  verifyFormat("module test\n"
+   "(input [7 : 0] a,\n"
+   " input signed [7 : 0] b, //\n"
+   "  c, //\n"
+   "  d);\n"
+   "endmodule");
+  verifyFormat("module test\n"
+   "(input signed [7 : 0] b, //\n"
+   "  c, //\n"
+   "  d,\n"
+   " output signed [7 : 0] h);\n"
+ 

[PATCH] D144232: [PowerPC] Correctly use ELFv2 ABI on FreeBSD/powerpc64

2023-02-17 Thread Piotr Kubaj via Phabricator via cfe-commits
pkubaj updated this revision to Diff 498378.
pkubaj added a comment.

Addres adalava's review.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144232

Files:
  clang/lib/Basic/Targets/PPC.h
  llvm/lib/Target/PowerPC/PPCTargetMachine.cpp


Index: llvm/lib/Target/PowerPC/PPCTargetMachine.cpp
===
--- llvm/lib/Target/PowerPC/PPCTargetMachine.cpp
+++ llvm/lib/Target/PowerPC/PPCTargetMachine.cpp
@@ -233,6 +233,11 @@
   assert(Options.MCOptions.getABIName().empty() &&
  "Unknown target-abi option!");
 
+  if (TT.isOSFreeBSD() && TT.getArch() == Triple::ppc64 &&
+  (TT.getOSVersion().empty() || TT.getOSMajorVersion() >= 13)) {
+return PPCTargetMachine::PPC_ABI_ELFv2;
+  }
+
   switch (TT.getArch()) {
   case Triple::ppc64le:
 return PPCTargetMachine::PPC_ABI_ELFv2;
Index: clang/lib/Basic/Targets/PPC.h
===
--- clang/lib/Basic/Targets/PPC.h
+++ clang/lib/Basic/Targets/PPC.h
@@ -425,6 +425,10 @@
 } else if ((Triple.getArch() == llvm::Triple::ppc64le)) {
   DataLayout = "e-m:e-i64:64-n32:64";
   ABI = "elfv2";
+} else if (Triple.isOSFreeBSD() && (Triple.getOSVersion().empty() ||
+Triple.getOSMajorVersion() >= 13)) {
+  DataLayout = "E-m:e-i64:64-n32:64";
+  ABI = "elfv2";
 } else {
   DataLayout = "E-m:e-i64:64-n32:64";
   ABI = "elfv1";


Index: llvm/lib/Target/PowerPC/PPCTargetMachine.cpp
===
--- llvm/lib/Target/PowerPC/PPCTargetMachine.cpp
+++ llvm/lib/Target/PowerPC/PPCTargetMachine.cpp
@@ -233,6 +233,11 @@
   assert(Options.MCOptions.getABIName().empty() &&
  "Unknown target-abi option!");
 
+  if (TT.isOSFreeBSD() && TT.getArch() == Triple::ppc64 &&
+  (TT.getOSVersion().empty() || TT.getOSMajorVersion() >= 13)) {
+return PPCTargetMachine::PPC_ABI_ELFv2;
+  }
+
   switch (TT.getArch()) {
   case Triple::ppc64le:
 return PPCTargetMachine::PPC_ABI_ELFv2;
Index: clang/lib/Basic/Targets/PPC.h
===
--- clang/lib/Basic/Targets/PPC.h
+++ clang/lib/Basic/Targets/PPC.h
@@ -425,6 +425,10 @@
 } else if ((Triple.getArch() == llvm::Triple::ppc64le)) {
   DataLayout = "e-m:e-i64:64-n32:64";
   ABI = "elfv2";
+} else if (Triple.isOSFreeBSD() && (Triple.getOSVersion().empty() ||
+Triple.getOSMajorVersion() >= 13)) {
+  DataLayout = "E-m:e-i64:64-n32:64";
+  ABI = "elfv2";
 } else {
   DataLayout = "E-m:e-i64:64-n32:64";
   ABI = "elfv1";
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D144272: [clang][Interp] Ignore StaticAssertDecls

2023-02-17 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: aaron.ballman, tahonermann, erichkeane, shafik.
Herald added a project: All.
tbaeder requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

  They have already been handled before, but we can't just return false
  when we encounter one.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144272

Files:
  clang/lib/AST/Interp/ByteCodeStmtGen.cpp
  clang/test/AST/Interp/functions.cpp


Index: clang/test/AST/Interp/functions.cpp
===
--- clang/test/AST/Interp/functions.cpp
+++ clang/test/AST/Interp/functions.cpp
@@ -9,11 +9,28 @@
 static_assert(gimme5() == 5, "");
 
 
-template constexpr T identity(T t) { return t; }
+template constexpr T identity(T t) {
+  static_assert(true);
+  return t;
+}
 static_assert(identity(true), "");
 static_assert(identity(true), ""); /// Compiled bytecode should be cached
 static_assert(!identity(false), "");
 
+template
+constexpr bool sameSize() {
+  static_assert(sizeof(A) == sizeof(B), ""); // expected-error {{static 
assertion failed}} \
+ // ref-error {{static assertion 
failed}} \
+ // expected-note {{evaluates to}} 
\
+ // ref-note {{evaluates to}}
+  return true;
+}
+static_assert(sameSize(), "");
+static_assert(sameSize(), "");
+static_assert(sameSize(), ""); // expected-note {{in instantiation 
of function template specialization}} \
+   // ref-note {{in instantiation of 
function template specialization}}
+
+
 constexpr auto add(int a, int b) -> int {
   return identity(a) + identity(b);
 }
Index: clang/lib/AST/Interp/ByteCodeStmtGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -210,6 +210,9 @@
 template 
 bool ByteCodeStmtGen::visitDeclStmt(const DeclStmt *DS) {
   for (auto *D : DS->decls()) {
+if (isa(D))
+  continue;
+
 const auto *VD = dyn_cast(D);
 if (!VD)
   return false;


Index: clang/test/AST/Interp/functions.cpp
===
--- clang/test/AST/Interp/functions.cpp
+++ clang/test/AST/Interp/functions.cpp
@@ -9,11 +9,28 @@
 static_assert(gimme5() == 5, "");
 
 
-template constexpr T identity(T t) { return t; }
+template constexpr T identity(T t) {
+  static_assert(true);
+  return t;
+}
 static_assert(identity(true), "");
 static_assert(identity(true), ""); /// Compiled bytecode should be cached
 static_assert(!identity(false), "");
 
+template
+constexpr bool sameSize() {
+  static_assert(sizeof(A) == sizeof(B), ""); // expected-error {{static assertion failed}} \
+ // ref-error {{static assertion failed}} \
+ // expected-note {{evaluates to}} \
+ // ref-note {{evaluates to}}
+  return true;
+}
+static_assert(sameSize(), "");
+static_assert(sameSize(), "");
+static_assert(sameSize(), ""); // expected-note {{in instantiation of function template specialization}} \
+   // ref-note {{in instantiation of function template specialization}}
+
+
 constexpr auto add(int a, int b) -> int {
   return identity(a) + identity(b);
 }
Index: clang/lib/AST/Interp/ByteCodeStmtGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -210,6 +210,9 @@
 template 
 bool ByteCodeStmtGen::visitDeclStmt(const DeclStmt *DS) {
   for (auto *D : DS->decls()) {
+if (isa(D))
+  continue;
+
 const auto *VD = dyn_cast(D);
 if (!VD)
   return false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D144216: [clang-tidy] Extract string header from redundant-string-cstr checker

2023-02-17 Thread Mike Crowe via Phabricator via cfe-commits
mikecrowe added a comment.

In D144216#4133671 , @Eugene.Zelenko 
wrote:

> May be you could use heard in other test in same patch?

I'm not quite sure what you mean by "heard". Searching for "heard" in the LLVM 
code and Googling "llvm heard" reveal nothing useful. Please can you explain 
what you mean?

If you're suggesting that I could use the new `` header to replace 
declarations of `basic_string` etc. in other tests then I think that would be 
possible with some careful checking to make sure it include the necessary 
functionality. I think that would easier to review separately rather than in a 
single patch though.




Comment at: 
clang-tools-extra/test/clang-tidy/checkers/readability/redundant-string-cstr.cpp:1
-// RUN: %check_clang_tidy %s readability-redundant-string-cstr %t
-
-typedef unsigned __INT16_TYPE__ char16;
-typedef unsigned __INT32_TYPE__ char32;
-typedef __SIZE_TYPE__ size;
-
-namespace std {
-template 
-class allocator {};
-template 
-class char_traits {};
-template 
-struct basic_string {
-  typedef basic_string _Type;
-  basic_string();
-  basic_string(const C *p, const A &a = A());
-
-  ~basic_string();
-
-  const C *c_str() const;
-  const C *data() const;
-
-  _Type& append(const C *s);
-  _Type& append(const C *s, size n);
-  _Type& assign(const C *s);
-  _Type& assign(const C *s, size n);
-
-  int compare(const _Type&) const;
-  int compare(const C* s) const;
-  int compare(size pos, size len, const _Type&) const;
-  int compare(size pos, size len, const C* s) const;
-
-  size find(const _Type& str, size pos = 0) const;
-  size find(const C* s, size pos = 0) const;
-  size find(const C* s, size pos, size n) const;
-
-  _Type& insert(size pos, const _Type& str);
-  _Type& insert(size pos, const C* s);
-  _Type& insert(size pos, const C* s, size n);
-
-  _Type& operator+=(const _Type& str);
-  _Type& operator+=(const C* s);
-  _Type& operator=(const _Type& str);
-  _Type& operator=(const C* s);
-};
-
-typedef basic_string, std::allocator> 
string;
-typedef basic_string, 
std::allocator> wstring;
-typedef basic_string, std::allocator> 
u16string;
-typedef basic_string, std::allocator> 
u32string;
-
-template 
-struct basic_string_view {
-  basic_string_view(const C* s);
-};
-typedef basic_string_view> string_view;
-typedef basic_string_view> wstring_view;
-typedef basic_string_view> u16string_view;
-typedef basic_string_view> u32string_view;
-}
-
-std::string operator+(const std::string&, const std::string&);
-std::string operator+(const std::string&, const char*);
-std::string operator+(const char*, const std::string&);
-
-bool operator==(const std::string&, const std::string&);
-bool operator==(const std::string&, const char*);
-bool operator==(const char*, const std::string&);
+// RUN: %check_clang_tidy %s readability-redundant-string-cstr %t -- -- 
-isystem %clang_tidy_headers
+#include 

carlosgalvezp wrote:
> Where does this come from? Other tests use the actual path to the folder.
I copied it from other checks:
```
clang-tools-extra/test/clang-tidy/checkers/bugprone/signal-handler-minimal.c:// 
RUN: -- -isystem %clang_tidy_headers
clang-tools-extra/test/clang-tidy/checkers/bugprone/signal-handler-posix.c:// 
RUN: -- -isystem %clang_tidy_headers
clang-tools-extra/test/clang-tidy/checkers/bugprone/signal-handler.c:// RUN: 
%check_clang_tidy %s bugprone-signal-handler %t -- -- -isystem 
%clang_tidy_headers
clang-tools-extra/test/clang-tidy/checkers/bugprone/signal-handler.cpp:// RUN: 
%check_clang_tidy -std=c++14 %s bugprone-signal-handler %t -- -- -isystem 
%clang_tidy_headers -isystem %S/Inputs/signal-handler -target 
x86_64-unknown-unknown
clang-tools-extra/test/clang-tidy/checkers/bugprone/suspicious-include.cpp:// 
RUN: %check_clang_tidy %s bugprone-suspicious-include %t -- -- -isystem 
%clang_tidy_headers -fmodules
clang-tools-extra/test/clang-tidy/checkers/google/objc-function-naming.m:// 
RUN: %check_clang_tidy %s google-objc-function-naming %t -- -- -isystem 
%clang_tidy_headers
clang-tools-extra/test/clang-tidy/checkers/llvm/include-order.cpp:// RUN: 
%check_clang_tidy %s llvm-include-order %t -- -- -isystem %clang_tidy_headers
clang-tools-extra/test/clang-tidy/checkers/modernize/pass-by-value-macro-header.cpp://
 RUN: %check_clang_tidy %s modernize-pass-by-value %t -- -- -isystem 
%clang_tidy_headers
clang-tools-extra/test/clang-tidy/checkers/performance/move-constructor-init.cpp://
 RUN: -- -isystem %clang_tidy_headers
clang-tools-extra/test/clang-tidy/checkers/readability/redundant-string-cstr-format.cpp://
 RUN: %check_clang_tidy -check-suffix=STDFORMAT -std=c++20 %s 
readability-redundant-string-cstr %t -- --  -isystem %clang_tidy_headers 
-DTEST_STDFORMAT
clang-tools-extra/test/clang-tidy/checkers/readability/redundant-string-cstr-format.cpp://
 RUN: %check_clang_tidy -check-suffixes=STDFORMAT,STDPRINT -std=c++2b %s 
readability-redundant-string-cstr %t -- --  -isystem %clang_tidy_heade

[PATCH] D143825: [clang-format] Put ports on separate lines in Verilog module headers

2023-02-17 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.
This revision is now accepted and ready to land.

Thank you for adding the tests, as I don't know Verilog then I can't really 
comment on the correctness, as you are mostly in your own scoped verilog 
functions, I'm fine with you improving the Verilog support, I don't personally 
see anything wrong with the touch points with other languages. I'm not sure if 
others have comments or if they have expertise in this area.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143825

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


[PATCH] D143917: [clang-tidy] Clarify bugprone-branch-clone diagnostic message

2023-02-17 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2b51c8cd2ac6: [clang-tidy] Clarify bugprone-branch-clone 
diagnostic message (authored by donat.nagy, committed by Donát Nagy 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143917

Files:
  clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone-if-constexpr-template.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone-macro-crash.c
  clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp
@@ -388,7 +388,7 @@
 
 void test_chain1(int in, int &out) {
   if (in > 77)
-// CHECK-MESSAGES: :[[@LINE+1]]:5: warning: repeated branch in conditional chain [bugprone-branch-clone]
+// CHECK-MESSAGES: :[[@LINE+1]]:5: warning: repeated branch body in conditional chain [bugprone-branch-clone]
 out++;
 // CHECK-MESSAGES: :[[@LINE-1]]:10: note: end of the original
   else if (in > 55)
@@ -400,7 +400,7 @@
 
 void test_chain2(int in, int &out) {
   if (in > 77)
-// CHECK-MESSAGES: :[[@LINE+1]]:5: warning: repeated branch in conditional chain [bugprone-branch-clone]
+// CHECK-MESSAGES: :[[@LINE+1]]:5: warning: repeated branch body in conditional chain [bugprone-branch-clone]
 out++;
 // CHECK-MESSAGES: :[[@LINE-1]]:10: note: end of the original
   else if (in > 55)
@@ -422,7 +422,7 @@
 
 void test_chain3(int in, int &out) {
   if (in > 77) {
-// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: repeated branch in conditional chain [bugprone-branch-clone]
+// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: repeated branch body in conditional chain [bugprone-branch-clone]
 out++;
 out++;
 // CHECK-MESSAGES: :[[@LINE+1]]:4: note: end of the original
@@ -452,7 +452,7 @@
 // describes all branches of the first one before mentioning the second one.
 void test_chain4(int in, int &out) {
   if (in > 77) {
-// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: repeated branch in conditional chain [bugprone-branch-clone]
+// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: repeated branch body in conditional chain [bugprone-branch-clone]
 out++;
 out++;
 // CHECK-MESSAGES: :[[@LINE+1]]:4: note: end of the original
@@ -463,7 +463,7 @@
 out++;
 out++;
   } else if (in > 42)
-// CHECK-MESSAGES: :[[@LINE+1]]:5: warning: repeated branch in conditional chain [bugprone-branch-clone]
+// CHECK-MESSAGES: :[[@LINE+1]]:5: warning: repeated branch body in conditional chain [bugprone-branch-clone]
 out--;
 // CHECK-MESSAGES: :[[@LINE-1]]:10: note: end of the original
   else if (in > 28) {
@@ -485,7 +485,7 @@
 
 void test_chain5(int in, int &out) {
   if (in > 77)
-// CHECK-MESSAGES: :[[@LINE+1]]:5: warning: repeated branch in conditional chain [bugprone-branch-clone]
+// CHECK-MESSAGES: :[[@LINE+1]]:5: warning: repeated branch body in conditional chain [bugprone-branch-clone]
 out++;
 // CHECK-MESSAGES: :[[@LINE-1]]:10: note: end of the original
   else if (in > 55)
@@ -507,7 +507,7 @@
 
 void test_chain6(int in, int &out) {
   if (in > 77) {
-// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: repeated branch in conditional chain [bugprone-branch-clone]
+// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: repeated branch body in conditional chain [bugprone-branch-clone]
 out++;
 out++;
 // CHECK-MESSAGES: :[[@LINE+1]]:4: note: end of the original
@@ -538,7 +538,7 @@
 // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: if with identical then and else branches [bugprone-branch-clone]
 // CHECK-MESSAGES: :[[@LINE+27]]:5: note: else branch starts here
 if (b > 5) {
-// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: repeated branch in conditional chain [bugprone-branch-clone]
+// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: repeated branch body in conditional chain [bugprone-branch-clone]
 // CHECK-MESSAGES: :[[@LINE+9]]:6: note: end of the original
 // CHECK-MESSAGES: :[[@LINE+8]]:24: note: clone 1 starts here
 // CHECK-MESSAGES: :[[@LINE+14]]:12: note: clone 2 starts here
@@ -565,7 +565,7 @@
 }
   } else {
 if (b > 5) {
-// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: repeated branch in conditional chain [bugprone-branch-clone]
+// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: repeated branch body in conditional chain [bugprone-branch-clone]
 // CHECK-MESSAGES: :[[@LINE+9]]:6: note: end of the original
 // CHECK-MESSAGES: :[[@LINE+8]]:24: note: clone 1 starts here
 // CHECK-MESSAGES: :[[@LINE+14]]:12: note: clone 2 starts here
@@ -948,7 +948,7 @@
 return 'A';
 
   if (in > 77)
-// CHECK-MESSAGES: :[[@LINE+1]]:5: warning: repeated branch in conditional chain [bugp

[clang-tools-extra] 2b51c8c - [clang-tidy] Clarify bugprone-branch-clone diagnostic message

2023-02-17 Thread Donát Nagy via cfe-commits

Author: Donát Nagy
Date: 2023-02-17T17:05:19+01:00
New Revision: 2b51c8cd2ac6b9a6a5b713700c8299954980242d

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

LOG: [clang-tidy] Clarify bugprone-branch-clone diagnostic message

This simple commit inserts "body" into the message "repeated branch _body_ in
conditional chain". This is motivated by feedback from a user who (at first
glance) thought that clang-tidy complained about a repeated branch _condition_.

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp

clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone-if-constexpr-template.cpp

clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone-macro-crash.c
clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp
index 41b8d32500cdb..df232e9a64cd0 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp
@@ -141,7 +141,7 @@ void BranchCloneCheck::check(const MatchFinder::MatchResult 
&Result) {
 if (NumCopies == 2) {
   // We report the first occurrence only when we find the second one.
   diag(Branches[I]->getBeginLoc(),
-   "repeated branch in conditional chain");
+   "repeated branch body in conditional chain");
   SourceLocation End =
   Lexer::getLocForEndOfToken(Branches[I]->getEndLoc(), 0,
  *Result.SourceManager, getLangOpts());

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone-if-constexpr-template.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone-if-constexpr-template.cpp
index 382330139c8c5..10cf06e8d9cc8 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone-if-constexpr-template.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone-if-constexpr-template.cpp
@@ -5,7 +5,7 @@ void handle(int);
 template 
 void shouldFail() {
   if constexpr (Index == 0) {
-// CHECK-MESSAGES: :[[@LINE-1]]:29: warning: repeated branch in 
conditional chain [bugprone-branch-clone]
+// CHECK-MESSAGES: :[[@LINE-1]]:29: warning: repeated branch body in 
conditional chain [bugprone-branch-clone]
 handle(0);
   } else if constexpr (Index == 1) {
 handle(1);
@@ -28,7 +28,7 @@ void shouldPass() {
 void shouldFailNonTemplate() {
   constexpr unsigned Index = 1;
   if constexpr (Index == 0) {
-// CHECK-MESSAGES: :[[@LINE-1]]:29: warning: repeated branch in 
conditional chain [bugprone-branch-clone]
+// CHECK-MESSAGES: :[[@LINE-1]]:29: warning: repeated branch body in 
conditional chain [bugprone-branch-clone]
 handle(0);
   } else if constexpr (Index == 1) {
 handle(1);

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone-macro-crash.c
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone-macro-crash.c
index a51069828b3eb..a4cb7347f88c6 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone-macro-crash.c
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone-macro-crash.c
@@ -9,6 +9,6 @@ int y = 1;
 d = b;
 
 void f(void) {
-  // CHECK-MESSAGES: warning: repeated branch in conditional chain 
[bugprone-branch-clone]
+  // CHECK-MESSAGES: warning: repeated branch body in conditional chain 
[bugprone-branch-clone]
   a(x, y)
 }

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp
index 09f87cedfceb6..1525ba2802d16 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp
@@ -388,7 +388,7 @@ void test_macro13(int in, int &out) {
 
 void test_chain1(int in, int &out) {
   if (in > 77)
-// CHECK-MESSAGES: :[[@LINE+1]]:5: warning: repeated branch in conditional 
chain [bugprone-branch-clone]
+// CHECK-MESSAGES: :[[@LINE+1]]:5: warning: repeated branch body in 
conditional chain [bugprone-branch-clone]
 out++;
 // CHECK-MESSAGES: :[[@LINE-1]]:10: note: end of the original
   else if (in > 55)
@@ -400,7 +400,7 @@ void test_chain1(int in, int &out) {
 
 void test_chain2(int in, int &out) {
   if (in > 77)
-// CHECK-MESSAGES: :[[@LINE+1]]:5: warning: repeated branch in conditional 
chain [bugprone-branch-clone]
+// CHECK-MESSAGES: :[[@LINE+1]]:5: warning: repeated branch body in 
conditional chain [bugprone-branch-clone]
 out++;
 

[PATCH] D144273: [clang][ASTImporter] Add VaList declaration to lookup table.

2023-02-17 Thread Balázs Kéri via Phabricator via cfe-commits
balazske created this revision.
Herald added subscribers: steakhal, martong, gamesh411, Szelethus, dkrupp.
Herald added a reviewer: a.sidorin.
Herald added a reviewer: shafik.
Herald added a project: All.
balazske requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The declaration of __builtin_va_list seems to be handled specially
by ASTContext and/or Sema. The normal AST traversal probably can
not find it, therefore it is not added to ASTImporterLookupTable.
If it is not added, errors can occur because a duplicated
VaList declaration is created at import. To fix the problem the
VaList declaration is added manually to ASTImporterLookupTable
at construction.
In special cases this declaration is inside a "invisible" 'std'
namespace that behaves the same way. This namespace must be added
to the table too.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144273

Files:
  clang/lib/AST/ASTImporterLookupTable.cpp
  clang/unittests/AST/ASTImporterTest.cpp


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -8137,6 +8137,42 @@
   EXPECT_FALSE(SharedStatePtr->isNewDecl(ToBar));
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, VaListC) {
+  Decl *FromTU = getTuDecl(R"(typedef __builtin_va_list va_list;)", Lang_C99);
+
+  auto *FromVaList = FirstDeclMatcher().match(
+  FromTU, typedefDecl(hasName("va_list")));
+  ASSERT_TRUE(FromVaList);
+
+  auto *ToVaList = Import(FromVaList, Lang_C99);
+  ASSERT_TRUE(ToVaList);
+
+  auto *ToBuiltinVaList = FirstDeclMatcher().match(
+  ToAST->getASTContext().getTranslationUnitDecl(),
+  typedefDecl(hasName("__builtin_va_list")));
+
+  ASSERT_TRUE(ToAST->getASTContext().hasSameType(
+  ToVaList->getUnderlyingType(), ToBuiltinVaList->getUnderlyingType()));
+}
+
+TEST_P(ASTImporterOptionSpecificTestBase, VaListCpp) {
+  Decl *FromTU = getTuDecl(R"(typedef __builtin_va_list va_list;)", 
Lang_CXX03);
+
+  auto *FromVaList = FirstDeclMatcher().match(
+  FromTU, typedefDecl(hasName("va_list")));
+  ASSERT_TRUE(FromVaList);
+
+  auto *ToVaList = Import(FromVaList, Lang_CXX03);
+  ASSERT_TRUE(ToVaList);
+
+  auto *ToBuiltinVaList = FirstDeclMatcher().match(
+  ToAST->getASTContext().getTranslationUnitDecl(),
+  typedefDecl(hasName("__builtin_va_list")));
+
+  ASSERT_TRUE(ToAST->getASTContext().hasSameType(
+  ToVaList->getUnderlyingType(), ToBuiltinVaList->getUnderlyingType()));
+}
+
 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ASTImporterLookupTableTest,
  DefaultTestValuesForRunOptions);
 
Index: clang/lib/AST/ASTImporterLookupTable.cpp
===
--- clang/lib/AST/ASTImporterLookupTable.cpp
+++ clang/lib/AST/ASTImporterLookupTable.cpp
@@ -85,8 +85,21 @@
 } // anonymous namespace
 
 ASTImporterLookupTable::ASTImporterLookupTable(TranslationUnitDecl &TU) {
+  (void)TU.getASTContext().getVaListTagDecl();
   Builder B(*this);
   B.TraverseDecl(&TU);
+  // The VaList declaration may be created on demand only or not traversed.
+  // To ensure it is present and found during import, add it to the table now.
+  if (auto *D =
+  dyn_cast_or_null(TU.getASTContext().getVaListTagDecl())) {
+// On some platforms (AArch64) the VaList declaration can be inside a 'std'
+// namespace. This is handled specially and not visible by AST traversal.
+// ASTImporter must be able to find this namespace to import the VaList
+// declaration (and the namespace) correctly.
+if (auto *Ns = dyn_cast(D->getDeclContext()))
+  add(&TU, Ns);
+add(D->getDeclContext(), D);
+  }
 }
 
 void ASTImporterLookupTable::add(DeclContext *DC, NamedDecl *ND) {


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -8137,6 +8137,42 @@
   EXPECT_FALSE(SharedStatePtr->isNewDecl(ToBar));
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, VaListC) {
+  Decl *FromTU = getTuDecl(R"(typedef __builtin_va_list va_list;)", Lang_C99);
+
+  auto *FromVaList = FirstDeclMatcher().match(
+  FromTU, typedefDecl(hasName("va_list")));
+  ASSERT_TRUE(FromVaList);
+
+  auto *ToVaList = Import(FromVaList, Lang_C99);
+  ASSERT_TRUE(ToVaList);
+
+  auto *ToBuiltinVaList = FirstDeclMatcher().match(
+  ToAST->getASTContext().getTranslationUnitDecl(),
+  typedefDecl(hasName("__builtin_va_list")));
+
+  ASSERT_TRUE(ToAST->getASTContext().hasSameType(
+  ToVaList->getUnderlyingType(), ToBuiltinVaList->getUnderlyingType()));
+}
+
+TEST_P(ASTImporterOptionSpecificTestBase, VaListCpp) {
+  Decl *FromTU = getTuDecl(R"(typedef __builtin_va_list va_list;)", Lang_CXX03);
+
+  auto *FromVaList = FirstDeclMatcher().match(
+  FromTU, ty

[PATCH] D143301: [flang] Handle unsupported warning flags

2023-02-17 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

@elmcdonough , let me rephrase this (should've been clearer before, sorry):

> One thing that's not clear to me - how come "-Wextra" is not treated as an 
> error and "-Wblah" is?

Where's the logic that makes sure that `-Wextra` (and other flags that you 
redefine here) is reported as unused? That's not clear from this definition:

  multiclass FlangIgnoredDiagOpt {
def unsupported_warning_w#NAME : Flag<["-", "--"], "W"#name>, 
Group;
  }

In particular, I don't see anything that would check whether a particular 
option is in this group: `flang_ignored_w_Group`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143301

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


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

2023-02-17 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

I have created the new patch D144273  that 
should fix the same AST import problems as this patch, without change of `Sema`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142822

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


[PATCH] D144273: [clang][ASTImporter] Add VaList declaration to lookup table.

2023-02-17 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 498392.
balazske added a comment.

removed a not needed line


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144273

Files:
  clang/lib/AST/ASTImporterLookupTable.cpp
  clang/unittests/AST/ASTImporterTest.cpp


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -8137,6 +8137,42 @@
   EXPECT_FALSE(SharedStatePtr->isNewDecl(ToBar));
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, VaListC) {
+  Decl *FromTU = getTuDecl(R"(typedef __builtin_va_list va_list;)", Lang_C99);
+
+  auto *FromVaList = FirstDeclMatcher().match(
+  FromTU, typedefDecl(hasName("va_list")));
+  ASSERT_TRUE(FromVaList);
+
+  auto *ToVaList = Import(FromVaList, Lang_C99);
+  ASSERT_TRUE(ToVaList);
+
+  auto *ToBuiltinVaList = FirstDeclMatcher().match(
+  ToAST->getASTContext().getTranslationUnitDecl(),
+  typedefDecl(hasName("__builtin_va_list")));
+
+  ASSERT_TRUE(ToAST->getASTContext().hasSameType(
+  ToVaList->getUnderlyingType(), ToBuiltinVaList->getUnderlyingType()));
+}
+
+TEST_P(ASTImporterOptionSpecificTestBase, VaListCpp) {
+  Decl *FromTU = getTuDecl(R"(typedef __builtin_va_list va_list;)", 
Lang_CXX03);
+
+  auto *FromVaList = FirstDeclMatcher().match(
+  FromTU, typedefDecl(hasName("va_list")));
+  ASSERT_TRUE(FromVaList);
+
+  auto *ToVaList = Import(FromVaList, Lang_CXX03);
+  ASSERT_TRUE(ToVaList);
+
+  auto *ToBuiltinVaList = FirstDeclMatcher().match(
+  ToAST->getASTContext().getTranslationUnitDecl(),
+  typedefDecl(hasName("__builtin_va_list")));
+
+  ASSERT_TRUE(ToAST->getASTContext().hasSameType(
+  ToVaList->getUnderlyingType(), ToBuiltinVaList->getUnderlyingType()));
+}
+
 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ASTImporterLookupTableTest,
  DefaultTestValuesForRunOptions);
 
Index: clang/lib/AST/ASTImporterLookupTable.cpp
===
--- clang/lib/AST/ASTImporterLookupTable.cpp
+++ clang/lib/AST/ASTImporterLookupTable.cpp
@@ -87,6 +87,18 @@
 ASTImporterLookupTable::ASTImporterLookupTable(TranslationUnitDecl &TU) {
   Builder B(*this);
   B.TraverseDecl(&TU);
+  // The VaList declaration may be created on demand only or not traversed.
+  // To ensure it is present and found during import, add it to the table now.
+  if (auto *D =
+  dyn_cast_or_null(TU.getASTContext().getVaListTagDecl())) {
+// On some platforms (AArch64) the VaList declaration can be inside a 'std'
+// namespace. This is handled specially and not visible by AST traversal.
+// ASTImporter must be able to find this namespace to import the VaList
+// declaration (and the namespace) correctly.
+if (auto *Ns = dyn_cast(D->getDeclContext()))
+  add(&TU, Ns);
+add(D->getDeclContext(), D);
+  }
 }
 
 void ASTImporterLookupTable::add(DeclContext *DC, NamedDecl *ND) {


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -8137,6 +8137,42 @@
   EXPECT_FALSE(SharedStatePtr->isNewDecl(ToBar));
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, VaListC) {
+  Decl *FromTU = getTuDecl(R"(typedef __builtin_va_list va_list;)", Lang_C99);
+
+  auto *FromVaList = FirstDeclMatcher().match(
+  FromTU, typedefDecl(hasName("va_list")));
+  ASSERT_TRUE(FromVaList);
+
+  auto *ToVaList = Import(FromVaList, Lang_C99);
+  ASSERT_TRUE(ToVaList);
+
+  auto *ToBuiltinVaList = FirstDeclMatcher().match(
+  ToAST->getASTContext().getTranslationUnitDecl(),
+  typedefDecl(hasName("__builtin_va_list")));
+
+  ASSERT_TRUE(ToAST->getASTContext().hasSameType(
+  ToVaList->getUnderlyingType(), ToBuiltinVaList->getUnderlyingType()));
+}
+
+TEST_P(ASTImporterOptionSpecificTestBase, VaListCpp) {
+  Decl *FromTU = getTuDecl(R"(typedef __builtin_va_list va_list;)", Lang_CXX03);
+
+  auto *FromVaList = FirstDeclMatcher().match(
+  FromTU, typedefDecl(hasName("va_list")));
+  ASSERT_TRUE(FromVaList);
+
+  auto *ToVaList = Import(FromVaList, Lang_CXX03);
+  ASSERT_TRUE(ToVaList);
+
+  auto *ToBuiltinVaList = FirstDeclMatcher().match(
+  ToAST->getASTContext().getTranslationUnitDecl(),
+  typedefDecl(hasName("__builtin_va_list")));
+
+  ASSERT_TRUE(ToAST->getASTContext().hasSameType(
+  ToVaList->getUnderlyingType(), ToBuiltinVaList->getUnderlyingType()));
+}
+
 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ASTImporterLookupTableTest,
  DefaultTestValuesForRunOptions);
 
Index: clang/lib/AST/ASTImporterLookupTable.cpp
===
--- clang/lib/AST/ASTImporterLookupTable.cpp
+++ clang/lib/AST/ASTImporterLookupTable.cpp

[PATCH] D141569: [clang-tidy] Implement CppCoreGuideline F.18

2023-02-17 Thread Chris Cotter via Phabricator via cfe-commits
ccotter added a comment.

Some of the examples you mentioned are indeed not compliant with guideline 
F.18. I have a test for at least one of the examples you gave 
(`moves_deref_optional` matches your first example). The guideline is fairly 
strict IMO, and I asked about this in 
https://github.com/isocpp/CppCoreGuidelines/issues/2026, but the response was 
that the guideline will remain with the requirement that the whole object needs 
to be moved. This would imply that the fix for cases like 
`moves_deref_optional` would be to change the parameter to be a value rather 
than rvalue reference of the type (and move the individual parts as desired). 
Example `X&& obj as argument + for(auto& v : obj) { something(std::move(v.x)); 
}` also violates F.18 since the whole object is not moved (just a subobject, 
although I'm a little confused about the loop also).

One example (second, `std::pair&& obj+ 
std::forward>(obj);`) seems invalid or incomplete, 
since `std::pair` is not a universal reference and shouldn't be 
forwarded. I couldn't follow the other `forward` examples. In your `swap` 
example, this code also confused me - could you clarify it (it looks like the 
tool would be correct since I don't see any `move` of the parameter `other`).

`const Type&& obj + std::move(obj) in function` - this is a good catch, I don't 
have a test for this, but my tool incorrectly flags this. I will fix this.

All that said, I did consider but not implement an option to the tool which 
would allow a less strict version of F.18 which considered `move`s of any 
expression containing the parameter to be considered a move of the object. 
E.g., both of my tests `moves_member_of_parameter` and `moves_deref_optional` 
violate F.18, although I can reasonably see code written this way with the 
author not desiring this check to flag such code (of course, it could be 
compliant with the guideline by accepting a value rather than rvalue ref of the 
object). I recall seeing discussion elsewhere on a phab that clang-tidy tends 
to add options to allow less strict interpretations of the guidelines. I think 
it'd be worth adding this specific option. Should I add it as default enabled 
or disabled (i.e., should the default be strict adherence or not)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141569

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


[PATCH] D144216: [clang-tidy] Extract string header from redundant-string-cstr checker

2023-02-17 Thread Mike Crowe via Phabricator via cfe-commits
mikecrowe marked an inline comment as done.
mikecrowe added a comment.

> If you're suggesting that I could use the new  header to replace 
> declarations of basic_string etc. in other tests then I think that would be 
> possible with some careful checking to make sure it include the necessary 
> functionality. I think that would easier to review separately rather than in 
> a single patch though.

I had a quick look at likely candidates:

- `abseil/redundant-strcat-calls.cpp` appears to declare `basic_string` outside 
the `std` namespace and inside it, and does some strange stuff with a base 
class. If I rip all that out, and replace uses of `string` with `std::string` 
then the tests pass using ``.
- `readability/string-compare.cpp` and `readability/container-data-pointer.cpp` 
require some tweaks to `` but are straightforward.
- There may be complications if MSVC differs in its `std::basic_string` 
implementation in ways that the `-msvc` tests care about, but I didn't spot any.

So, it looks like the use of this new `` header could be extended. Do 
you have a preference for one big patch, one patch per directory (abseil, 
readability), or one patch per check? Do you require all to be complete before 
even this patch can be accepted?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144216

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


[PATCH] D143496: [clangd] Add support for missing includes analysis.

2023-02-17 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 498401.
VitaNuo marked 14 inline comments as done.
VitaNuo added a comment.
Herald added a subscriber: ChuanqiXu.

Address review comments. Make diagnostics symref-centered and attach them to 
each reference.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143496

Files:
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
  clang-tools-extra/include-cleaner/lib/Analysis.cpp

Index: clang-tools-extra/include-cleaner/lib/Analysis.cpp
===
--- clang-tools-extra/include-cleaner/lib/Analysis.cpp
+++ clang-tools-extra/include-cleaner/lib/Analysis.cpp
@@ -49,8 +49,8 @@
   }
 }
 
-static std::string spellHeader(const Header &H, HeaderSearch &HS,
-   const FileEntry *Main) {
+std::string spellHeader(const Header &H, HeaderSearch &HS,
+const FileEntry *Main) {
   switch (H.kind()) {
   case Header::Physical: {
 bool IsSystem = false;
Index: clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
===
--- clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
+++ clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
@@ -73,6 +73,8 @@
 std::string fixIncludes(const AnalysisResults &Results, llvm::StringRef Code,
 const format::FormatStyle &IncludeStyle);
 
+std::string spellHeader(const Header &H, HeaderSearch &HS,
+const FileEntry *Main);
 } // namespace include_cleaner
 } // namespace clang
 
Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -9,11 +9,19 @@
 #include "Annotations.h"
 #include "Config.h"
 #include "IncludeCleaner.h"
+#include "ParsedAST.h"
 #include "SourceCode.h"
 #include "TestFS.h"
 #include "TestTU.h"
+#include "clang-include-cleaner/Analysis.h"
+#include "clang-include-cleaner/Types.h"
 #include "support/Context.h"
+#include "clang/AST/DeclBase.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/ScopeExit.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
 #include "llvm/Testing/Support/SupportHelpers.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
@@ -342,7 +350,8 @@
   auto AST = TU.build();
   EXPECT_THAT(computeUnusedIncludes(AST),
   ElementsAre(Pointee(writtenInclusion("";
-  EXPECT_THAT(computeUnusedIncludesExperimental(AST),
+  IncludeCleanerFindings Findings = computeIncludeCleanerFindings(AST);
+  EXPECT_THAT(Findings.UnusedIncludes,
   ElementsAre(Pointee(writtenInclusion("";
 }
 
@@ -379,12 +388,69 @@
   computeUnusedIncludes(AST),
   UnorderedElementsAre(Pointee(writtenInclusion("\"unused.h\"")),
Pointee(writtenInclusion("\"dir/unused.h\"";
+
+  IncludeCleanerFindings Findings = computeIncludeCleanerFindings(AST);
   EXPECT_THAT(
-  computeUnusedIncludesExperimental(AST),
+  Findings.UnusedIncludes,
   UnorderedElementsAre(Pointee(writtenInclusion("\"unused.h\"")),
Pointee(writtenInclusion("\"dir/unused.h\"";
 }
 
+TEST(IncludeCleaner, GetMissingHeaders) {
+  llvm::StringLiteral MainFile = R"cpp(
+#include "a.h"
+#include "dir/c.h"
+#include 
+
+void foo() {
+  b();
+  d();
+  f();
+})cpp";
+  // Build expected ast with symbols coming from headers.
+  TestTU TU;
+  TU.Filename = "foo.cpp";
+  TU.AdditionalFiles["foo.h"] = guard("void foo();");
+  TU.AdditionalFiles["a.h"] = guard("#include \"b.h\"");
+  TU.AdditionalFiles["b.h"] = guard("void b();");
+
+  TU.AdditionalFiles["dir/c.h"] = guard("#include \"d.h\"");
+  TU.AdditionalFiles["dir/d.h"] = guard("void d();");
+
+  TU.AdditionalFiles["system/e.h"] = guard("#include ");
+  TU.AdditionalFiles["system/f.h"] = guard("void f();");
+  TU.ExtraArgs.push_back("-isystem" + testPath("system"));
+
+  TU.Code = MainFile.str();
+  ParsedAST AST = TU.build();
+
+  IncludeCleanerFindings Findings = computeIncludeCleanerFindings(AST);
+  const SourceManager &SM = AST.getSo

[PATCH] D141569: [clang-tidy] Implement CppCoreGuideline F.18

2023-02-17 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added a comment.

I think we aim at having it strict as default (so someone wanting to comply 
with the rule "as-is" can just enable the check), and then add options to relax 
it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141569

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


[PATCH] D144216: [clang-tidy] Extract string header from redundant-string-cstr checker

2023-02-17 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp accepted this revision.
carlosgalvezp added a comment.
This revision is now accepted and ready to land.

Fair enough! I think we should merge this patch as is first, so that people can 
benefit from it already, and work through the technical debt afterwards.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144216

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


[PATCH] D143496: [clangd] Add support for missing includes analysis.

2023-02-17 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo added a comment.

Thanks for the extensive explanations! See the updated version, it should also 
take the discussions on the document into account.




Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:512
+include_cleaner::Includes
+convertIncludes(const SourceManager &SM,
+const std::vector &MainFileIncludes) {

kadircet wrote:
> since this is a local symbol, either mark it as `static` or move it to 
> anonymous namespace above so that it won't be visible to other translation 
> units.
Oh yeah makes sense.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:513
+convertIncludes(const SourceManager &SM,
+const std::vector &MainFileIncludes) {
+  include_cleaner::Includes Includes;

kadircet wrote:
> nit: you can use `llvm::ArrayRef` instead of a `const std::vector &`. 
> `ArrayRef` is a trivially copyable/constructible type for providing views 
> into a consecutive set of elements.
Ok.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:521
+SM.getComposedLoc(SM.getMainFileID(), Inc.HashOffset);
+TransformedInc.Line = Inc.HashLine;
+TransformedInc.Angled = WrittenRef.starts_with("<");

kadircet wrote:
> include_cleaner::Includes::Line is 1-based, whereas 
> clang::clangd::Inclusion::HashLine is 0-based. so we need to have a `+1` on 
> the RHS. we are probably missing some test coverage if this didn't fail
Ok, got it. We only use the include conversion for matching, and matching seems 
not to use line numbers. I guess it's the reason nothing fails.
I can't write a test for this function directly since it's in an anonymous 
namespace.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:523
+TransformedInc.Angled = WrittenRef.starts_with("<");
+if (auto FE = SM.getFileManager().getFile(Inc.Resolved))
+  TransformedInc.Resolved = *FE;

kadircet wrote:
> i don't think we should convert any unresolved includes. it usually means 
> header wasn't found, so we can't perform any reliable analysis on them. 
> anything i am missing?
Ok I will skip unresolved includes. But I am not sure I fully understand. We do 
the following:
1. Convert clangd includes to include-cleaner includes.
2. Match include-cleaner includes with symbol providers.
3. If match found, symbol reference is satisfied.

How does it matter in this scenario if the include is resolved? AFAIU as long 
as the header is spelled in the main file + it's matched with a symbol 
provider, we should say that the symbol reference is satisfied.

Otherwise, it seems like we'll say that the header is missing, although it's 
there in the main file and unresolved.

I don't know if this is in any way a realistic scenario. I am just approaching 
it with general logic, and in this sense having more "satisfied" symbols seems 
better than having less => leads to less false positives. It can lead to false 
negatives, too, but AFAIU false negatives are much less of a risk for missing 
include management. 



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:535
+  Diag D;
+  D.Message = llvm::formatv("header {0} is missing", Spelling);
+  D.Name = "missing-includes";

kadircet wrote:
> i think the symbol name should also be part of the diagnostic. as editors can 
> show these diagnostics without context (e.g. you've got a big file open, 
> there's a diagnostic panel displaying messages/fixes for all of the file. you 
> should be able to reason about the diagnostics and fixes without jumping all 
> over the file). so maybe something like:
> 
> `formatv("{0} providing '{1}' is not directly included", Header, Symbol)`
Sure. The new design does this, as well as skipping the header name.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:549
+  bool Angled = HeaderRef.starts_with("<");
+  std::optional Replacement = HeaderIncludes.insert(
+  HeaderRef.trim("\"<>"), Angled, tooling::IncludeDirective::Include);

kadircet wrote:
> this returns nullopt only if Header is already included in the main file. our 
> analysis should never suggest such a header for include, unless the include 
> is coming from a PP-disabled region.
> 
> so i think if Replacement generation fails, we should drop the diagnostic 
> completely rather than just dropping the fix. WDYT?
Ok, sure. What's a PP-disabled region? Are you talking about #ifdef's and such?



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:590
+ include_cleaner::Header Provider) {
+  std::string SpelledHeader;
+  if (Provider.kind() == include_cleaner::Header::Physical) {

kadircet wrote:
> nit: you can rewrite this as:
> ```
> // Give URI schemes a chance to customize header spellings
> if(Provider.kind() == Physical) {
>if(auto CanPath = getCanonicalPath(Provid

[PATCH] D142584: [CodeGen] Add a boolean flag to `Address::getPointer` and `Lvalue::getPointer` that indicates whether the pointer is known not to be null

2023-02-17 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks added inline comments.



Comment at: clang/lib/CodeGen/Address.h:67
   return;
-// Currently the max supported alignment is much less than 1 << 63 and is
+// Currently the max supported alignment is much less than 1 << 32 and is
 // guaranteed to be a power of 2, so we can store the log of the alignment

ahatanak wrote:
> ahatanak wrote:
> > efriedma wrote:
> > > ahatanak wrote:
> > > > efriedma wrote:
> > > > > ahatanak wrote:
> > > > > > efriedma wrote:
> > > > > > > This comment isn't right.  The max alignment is, as far as I can 
> > > > > > > tell, 1<<32 exactly.  (But there's something weird going on with 
> > > > > > > very large values... somehow `int a[1LL<<32] 
> > > > > > > __attribute((aligned(1ULL<<32))) = {};` ignores the alignment.)
> > > > > > The following function generated by tablegen (and a few others 
> > > > > > directly or indirectly calling the function) returns a 32-bit int, 
> > > > > > but it should be returning a 64-bit int.
> > > > > > 
> > > > > > https://github.com/llvm/llvm-project/blob/main/clang/utils/TableGen/ClangAttrEmitter.cpp#L532
> > > > > Filed https://github.com/llvm/llvm-project/issues/60752 so we don't 
> > > > > lose track of this.
> > > > I just realized we can't reduce the number of bits used for alignment 
> > > > here as we need 6 bits for alignment of `1 << 32`.
> > > > 
> > > > Should we allocate additional memory when `AlignLog` is either 31 or 
> > > > 32? If the 5-bit alignment is equal to `0b1`, it would mean that 
> > > > there is an out-of-line storage large enough to hold the alignment and 
> > > > any other extra information that is needed. I think 
> > > > https://reviews.llvm.org/D117262#3267899 proposes a similar idea.
> > > How much does `sizeof(Address)` actually matter, anyway?  If it's going 
> > > to get that nasty to implement the packing, I'm not sure it's worth the 
> > > effort to optimize.
> > I'm not sure, but apparently https://reviews.llvm.org/D117262 was needed to 
> > reduce the memory usage.
> > 
> > I don't see a significant increase in stack usage (a little over 1%) in the 
> > files in `clang/lib/CodeGen` when I build clang with `-fstack-usage`.
> @aeubanks do we have to use the specialization `AddressImpl`?
> 
> https://github.com/llvm/llvm-project/blob/main/clang/lib/CodeGen/Address.h#L31
looking back at the internal bug motivating the patch, it was because some we 
had to lower some thresholds in a stress test, so that in it of itself isn't 
super important. but `Address` is used a lot and it's nice to keep resource 
usage down (1% isn't trivial). does this noticeably affect max RSS? could run a 
potential patch through llvm-compile-time-tracker (I can help with that) to see 
the impact


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142584

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


[PATCH] D144216: [clang-tidy] Extract string header from redundant-string-cstr checker

2023-02-17 Thread Mike Crowe via Phabricator via cfe-commits
mikecrowe added a comment.

In D144216#4135431 , @carlosgalvezp 
wrote:

> Fair enough! I think we should merge this patch as is first, so that people 
> can benefit from it already, and work through the technical debt afterwards.

Great. Thank you. I'm still interested in answers to the questions in my 
comment since I have the necessary changes to migrate the tests I mentioned to 
using `` ready and I'd be happy to have a go at migrating more.

Thanks.

Mike.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144216

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


[PATCH] D143509: Move the BySpelling map to IncludeStructure.

2023-02-17 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 498419.
VitaNuo added a comment.

Address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143509

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/Headers.h
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/unittests/HeadersTests.cpp

Index: clang-tools-extra/clangd/unittests/HeadersTests.cpp
===
--- clang-tools-extra/clangd/unittests/HeadersTests.cpp
+++ clang-tools-extra/clangd/unittests/HeadersTests.cpp
@@ -197,6 +197,36 @@
Distance(getID(BazHeader, Includes), 1u)));
 }
 
+TEST_F(HeadersTest, CacheBySpellingIsBuiltForMainInclusions) {
+  std::string FooHeader = testPath("foo.h");
+  FS.Files[FooHeader] = R"cpp(
+  void foo();
+)cpp";
+  std::string BarHeader = testPath("bar.h");
+  FS.Files[BarHeader] = R"cpp(
+  void bar();
+)cpp";
+  std::string BazHeader = testPath("baz.h");
+  FS.Files[BazHeader] = R"cpp(
+  void baz();
+)cpp";
+  FS.Files[MainFile] = R"cpp(
+#include "foo.h"
+#include "bar.h"
+#include "baz.h"
+)cpp";
+  auto Includes = collectIncludes();
+  EXPECT_THAT(Includes.MainFileIncludes,
+  UnorderedElementsAre(written("\"foo.h\""), written("\"bar.h\""),
+   written("\"baz.h\"")));
+  EXPECT_THAT(Includes.mainFileIncludesWithSpelling("\"foo.h\""),
+  UnorderedElementsAre(Includes.MainFileIncludes[0]));
+  EXPECT_THAT(Includes.mainFileIncludesWithSpelling("\"bar.h\""),
+  UnorderedElementsAre(Includes.MainFileIncludes[1]));
+  EXPECT_THAT(Includes.mainFileIncludesWithSpelling("\"baz.h\""),
+  UnorderedElementsAre(Includes.MainFileIncludes[2]));
+}
+
 TEST_F(HeadersTest, PreambleIncludesPresentOnce) {
   // We use TestTU here, to ensure we use the preamble replay logic.
   // We're testing that the logic doesn't crash, and doesn't result in duplicate
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -85,7 +85,7 @@
 // Using templateName case is handled by the override TraverseTemplateName.
 if (TST->getTemplateName().getKind() == TemplateName::UsingTemplate)
   return true;
-add(TST->getAsCXXRecordDecl());  // Specialization
+add(TST->getAsCXXRecordDecl()); // Specialization
 return true;
   }
 
@@ -474,22 +474,16 @@
   translateToHeaderIDs(ReferencedFiles, AST.getIncludeStructure(), SM);
   return getUnused(AST, ReferencedHeaders, ReferencedFiles.SpelledUmbrellas);
 }
-std::vector computeUnusedIncludesExperimental(ParsedAST &AST) {
-   const auto &SM = AST.getSourceManager();
-   const auto &Includes = AST.getIncludeStructure();
-   // FIXME: this map should probably be in IncludeStructure.
-   llvm::StringMap> BySpelling;
-   for (const auto &Inc : Includes.MainFileIncludes) {
-if (Inc.HeaderID)
-  BySpelling.try_emplace(Inc.Written)
-  .first->second.push_back(
-  static_cast(*Inc.HeaderID));
-   }
-   // FIXME: !!this is a hacky way to collect macro references.
-   std::vector Macros;
-auto& PP = AST.getPreprocessor();
-   for (const syntax::Token &Tok :
-AST.getTokens().spelledTokens(SM.getMainFileID())) {
+std::vector
+computeUnusedIncludesExperimental(ParsedAST &AST) {
+  const auto &SM = AST.getSourceManager();
+  const auto &Includes = AST.getIncludeStructure();
+
+  // FIXME: !!this is a hacky way to collect macro references.
+  std::vector Macros;
+  auto &PP = AST.getPreprocessor();
+  for (const syntax::Token &Tok :
+   AST.getTokens().spelledTokens(SM.getMainFileID())) {
 auto Macro = locateMacroAt(Tok, PP);
 if (!Macro)
   continue;
@@ -499,31 +493,38 @@
include_cleaner::Macro{/*Name=*/PP.getIdentifierInfo(Tok.text(SM)),
   DefLoc},
include_cleaner::RefType::Explicit});
-   }
-   llvm::DenseSet Used;
-   include_cleaner::walkUsed(
-   AST.getLocalTopLevelDecls(), /*MacroRefs=*/Macros,
-   AST.getPragmaIncludes(), SM,
-   [&](const include_cleaner::SymbolReference &Ref,
-   llvm::ArrayRef Providers) {
- for (const auto &H : Providers) {
-   switch (H.kind()) {
-   case include_cleaner::Header::Physical:
- if (auto HeaderID = Includes.getID(H.physical()))
-   Used.insert(*HeaderID);
- break;
-   case include_cleaner::Header::Standard:
- for (auto HeaderID : Includes.StdlibHeaders.lookup(H.standard()))
-   Used.insert(HeaderID);
- break;
-   case include_cleaner::Header::Verbatim:
- for (auto HeaderID : BySpelling.lookup(H.verbatim()))
-   Used.insert(Head

[PATCH] D143509: Move the BySpelling map to IncludeStructure.

2023-02-17 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo marked an inline comment as done.
VitaNuo added a comment.

Thanks for the comments!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143509

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


[PATCH] D143509: Move the BySpelling map to IncludeStructure.

2023-02-17 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 498428.
VitaNuo added a comment.

Move to source file.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143509

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/Headers.h
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/unittests/HeadersTests.cpp

Index: clang-tools-extra/clangd/unittests/HeadersTests.cpp
===
--- clang-tools-extra/clangd/unittests/HeadersTests.cpp
+++ clang-tools-extra/clangd/unittests/HeadersTests.cpp
@@ -197,6 +197,36 @@
Distance(getID(BazHeader, Includes), 1u)));
 }
 
+TEST_F(HeadersTest, CacheBySpellingIsBuiltForMainInclusions) {
+  std::string FooHeader = testPath("foo.h");
+  FS.Files[FooHeader] = R"cpp(
+  void foo();
+)cpp";
+  std::string BarHeader = testPath("bar.h");
+  FS.Files[BarHeader] = R"cpp(
+  void bar();
+)cpp";
+  std::string BazHeader = testPath("baz.h");
+  FS.Files[BazHeader] = R"cpp(
+  void baz();
+)cpp";
+  FS.Files[MainFile] = R"cpp(
+#include "foo.h"
+#include "bar.h"
+#include "baz.h"
+)cpp";
+  auto Includes = collectIncludes();
+  EXPECT_THAT(Includes.MainFileIncludes,
+  UnorderedElementsAre(written("\"foo.h\""), written("\"bar.h\""),
+   written("\"baz.h\"")));
+  EXPECT_THAT(Includes.mainFileIncludesWithSpelling("\"foo.h\""),
+  UnorderedElementsAre(Includes.MainFileIncludes[0]));
+  EXPECT_THAT(Includes.mainFileIncludesWithSpelling("\"bar.h\""),
+  UnorderedElementsAre(Includes.MainFileIncludes[1]));
+  EXPECT_THAT(Includes.mainFileIncludesWithSpelling("\"baz.h\""),
+  UnorderedElementsAre(Includes.MainFileIncludes[2]));
+}
+
 TEST_F(HeadersTest, PreambleIncludesPresentOnce) {
   // We use TestTU here, to ensure we use the preamble replay logic.
   // We're testing that the logic doesn't crash, and doesn't result in duplicate
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -85,7 +85,7 @@
 // Using templateName case is handled by the override TraverseTemplateName.
 if (TST->getTemplateName().getKind() == TemplateName::UsingTemplate)
   return true;
-add(TST->getAsCXXRecordDecl());  // Specialization
+add(TST->getAsCXXRecordDecl()); // Specialization
 return true;
   }
 
@@ -474,22 +474,16 @@
   translateToHeaderIDs(ReferencedFiles, AST.getIncludeStructure(), SM);
   return getUnused(AST, ReferencedHeaders, ReferencedFiles.SpelledUmbrellas);
 }
-std::vector computeUnusedIncludesExperimental(ParsedAST &AST) {
-   const auto &SM = AST.getSourceManager();
-   const auto &Includes = AST.getIncludeStructure();
-   // FIXME: this map should probably be in IncludeStructure.
-   llvm::StringMap> BySpelling;
-   for (const auto &Inc : Includes.MainFileIncludes) {
-if (Inc.HeaderID)
-  BySpelling.try_emplace(Inc.Written)
-  .first->second.push_back(
-  static_cast(*Inc.HeaderID));
-   }
-   // FIXME: !!this is a hacky way to collect macro references.
-   std::vector Macros;
-auto& PP = AST.getPreprocessor();
-   for (const syntax::Token &Tok :
-AST.getTokens().spelledTokens(SM.getMainFileID())) {
+std::vector
+computeUnusedIncludesExperimental(ParsedAST &AST) {
+  const auto &SM = AST.getSourceManager();
+  const auto &Includes = AST.getIncludeStructure();
+
+  // FIXME: !!this is a hacky way to collect macro references.
+  std::vector Macros;
+  auto &PP = AST.getPreprocessor();
+  for (const syntax::Token &Tok :
+   AST.getTokens().spelledTokens(SM.getMainFileID())) {
 auto Macro = locateMacroAt(Tok, PP);
 if (!Macro)
   continue;
@@ -499,31 +493,38 @@
include_cleaner::Macro{/*Name=*/PP.getIdentifierInfo(Tok.text(SM)),
   DefLoc},
include_cleaner::RefType::Explicit});
-   }
-   llvm::DenseSet Used;
-   include_cleaner::walkUsed(
-   AST.getLocalTopLevelDecls(), /*MacroRefs=*/Macros,
-   AST.getPragmaIncludes(), SM,
-   [&](const include_cleaner::SymbolReference &Ref,
-   llvm::ArrayRef Providers) {
- for (const auto &H : Providers) {
-   switch (H.kind()) {
-   case include_cleaner::Header::Physical:
- if (auto HeaderID = Includes.getID(H.physical()))
-   Used.insert(*HeaderID);
- break;
-   case include_cleaner::Header::Standard:
- for (auto HeaderID : Includes.StdlibHeaders.lookup(H.standard()))
-   Used.insert(HeaderID);
- break;
-   case include_cleaner::Header::Verbatim:
- for (auto HeaderID : BySpelling.lookup(H.verbatim()))
-   Used.insert(

[PATCH] D144285: [Clang] Implement CWG2518 - static_assert(false)

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

This allows `static_assert(false)` to not be ill-formed
in template definitions.

This change is applied as a DR in all C++ modes.

Of notes, a couple of tests were relying of the eager nature
of static_assert

- test/SemaTemplate/instantiation-dependence.cpp
- test/SemaTemplate/instantiate-var-template.cpp

I don't know if the changes to `static_assert`
still allow that sort of tests to be expressed.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144285

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/CXX/drs/dr25xx.cpp
  clang/test/SemaCXX/access-base-class.cpp
  clang/test/SemaCXX/coroutines-exp-namespace.cpp
  clang/test/SemaCXX/coroutines.cpp
  clang/test/SemaCXX/static-assert.cpp
  clang/test/SemaTemplate/instantiate-var-template.cpp
  clang/test/SemaTemplate/instantiation-dependence.cpp
  clang/www/cxx_dr_status.html

Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -14915,7 +14915,7 @@
 https://wg21.link/cwg2518";>2518
 review
 Conformance requirements and #error/#warning
-Not resolved
+Clang 17
   
   
 https://wg21.link/cwg2519";>2519
Index: clang/test/SemaTemplate/instantiation-dependence.cpp
===
--- clang/test/SemaTemplate/instantiation-dependence.cpp
+++ clang/test/SemaTemplate/instantiation-dependence.cpp
@@ -38,7 +38,7 @@
 
   template void foo() {
 static_assert(!__is_void(indirect_void_t)); // "ok", dependent
-static_assert(!__is_void(void_t)); // expected-error {{failed}}
+static_assert(!__is_void(void_t)); // fixme: can we check a type is dependant?
   }
 }
 
Index: clang/test/SemaTemplate/instantiate-var-template.cpp
===
--- clang/test/SemaTemplate/instantiate-var-template.cpp
+++ clang/test/SemaTemplate/instantiate-var-template.cpp
@@ -31,9 +31,9 @@
   static_assert(b == 1, ""); // expected-note {{in instantiation of}}
 
   template void f() {
-static_assert(a == 0, ""); // expected-error {{static assertion failed due to requirement 'a == 0'}} \
-   // expected-note {{evaluates to '1 == 0'}}
+static_assert(a == 0, ""); // fixme: can we check a var is dependant?
   }
+
 }
 
 namespace PR24483 {
Index: clang/test/SemaCXX/static-assert.cpp
===
--- clang/test/SemaCXX/static-assert.cpp
+++ clang/test/SemaCXX/static-assert.cpp
@@ -54,7 +54,7 @@
   // Only give one error here.
   static_assert(false, ""); // expected-error {{static assertion failed}}
 };
-AlwaysFails alwaysFails;
+AlwaysFails alwaysFails; // expected-note {{instantiation}}
 
 template struct StaticAssertProtected {
   static_assert(__is_literal(T), ""); // expected-error {{static assertion failed}}
Index: clang/test/SemaCXX/coroutines.cpp
===
--- clang/test/SemaCXX/coroutines.cpp
+++ clang/test/SemaCXX/coroutines.cpp
@@ -1309,7 +1309,7 @@
   }
 };
 
-template struct DepTestType; // expected-note {{requested here}}
+template struct DepTestType; // expected-note 2{{requested here}}
 template CoroMemberTag DepTestType::test_member_template(long, const char *) const &&;
 
 template CoroMemberTag DepTestType::test_static_template(const char *volatile &, unsigned);
Index: clang/test/SemaCXX/coroutines-exp-namespace.cpp
===
--- clang/test/SemaCXX/coroutines-exp-namespace.cpp
+++ clang/test/SemaCXX/coroutines-exp-namespace.cpp
@@ -1288,7 +1288,7 @@
   }
 };
 
-template struct DepTestType; // expected-note {{requested here}}
+template struct DepTestType; // expected-note 2{{requested here}}
 template CoroMemberTag DepTestType::test_member_template(long, const char *) const &&;
 
 template CoroMemberTag DepTestType::test_static_template(const char *volatile &, unsigned);
Index: clang/test/SemaCXX/access-base-class.cpp
===
--- clang/test/SemaCXX/access-base-class.cpp
+++ clang/test/SemaCXX/access-base-class.cpp
@@ -96,14 +96,14 @@
 };
 
 template 
-struct trait : flag {};
+struct trait : flag {}; // expected-note 2{{here}}
 
-template ::value>
+template ::value> // expected-note {{here}}
 struct a {};
 
 template 
 class b {
-  a x;
+  a x; // expected-note {{here}}
   using U = a;
 };
 
@@ -113,5 +113,5 @@
 };
 
 // verify "no member named 'value'" bogus diagnostic is not emitted.
-trait>>::value;
+trait>>::value; // expected-note {{here}}
 } // namespace T8
Index: clang/test/CXX/drs/dr25xx.cpp
=

[PATCH] D144285: [Clang] Implement CWG2518 - static_assert(false)

2023-02-17 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 498448.
cor3ntin added a comment.

Forgot to run clang-format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144285

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/CXX/drs/dr25xx.cpp
  clang/test/SemaCXX/access-base-class.cpp
  clang/test/SemaCXX/coroutines-exp-namespace.cpp
  clang/test/SemaCXX/coroutines.cpp
  clang/test/SemaCXX/static-assert.cpp
  clang/test/SemaTemplate/instantiate-var-template.cpp
  clang/test/SemaTemplate/instantiation-dependence.cpp
  clang/www/cxx_dr_status.html

Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -14915,7 +14915,7 @@
 https://wg21.link/cwg2518";>2518
 review
 Conformance requirements and #error/#warning
-Not resolved
+Clang 17
   
   
 https://wg21.link/cwg2519";>2519
Index: clang/test/SemaTemplate/instantiation-dependence.cpp
===
--- clang/test/SemaTemplate/instantiation-dependence.cpp
+++ clang/test/SemaTemplate/instantiation-dependence.cpp
@@ -38,7 +38,7 @@
 
   template void foo() {
 static_assert(!__is_void(indirect_void_t)); // "ok", dependent
-static_assert(!__is_void(void_t)); // expected-error {{failed}}
+static_assert(!__is_void(void_t)); // fixme: can we check a type is dependant?
   }
 }
 
Index: clang/test/SemaTemplate/instantiate-var-template.cpp
===
--- clang/test/SemaTemplate/instantiate-var-template.cpp
+++ clang/test/SemaTemplate/instantiate-var-template.cpp
@@ -31,9 +31,9 @@
   static_assert(b == 1, ""); // expected-note {{in instantiation of}}
 
   template void f() {
-static_assert(a == 0, ""); // expected-error {{static assertion failed due to requirement 'a == 0'}} \
-   // expected-note {{evaluates to '1 == 0'}}
+static_assert(a == 0, ""); // fixme: can we check a var is dependant?
   }
+
 }
 
 namespace PR24483 {
Index: clang/test/SemaCXX/static-assert.cpp
===
--- clang/test/SemaCXX/static-assert.cpp
+++ clang/test/SemaCXX/static-assert.cpp
@@ -54,7 +54,7 @@
   // Only give one error here.
   static_assert(false, ""); // expected-error {{static assertion failed}}
 };
-AlwaysFails alwaysFails;
+AlwaysFails alwaysFails; // expected-note {{instantiation}}
 
 template struct StaticAssertProtected {
   static_assert(__is_literal(T), ""); // expected-error {{static assertion failed}}
Index: clang/test/SemaCXX/coroutines.cpp
===
--- clang/test/SemaCXX/coroutines.cpp
+++ clang/test/SemaCXX/coroutines.cpp
@@ -1309,7 +1309,7 @@
   }
 };
 
-template struct DepTestType; // expected-note {{requested here}}
+template struct DepTestType; // expected-note 2{{requested here}}
 template CoroMemberTag DepTestType::test_member_template(long, const char *) const &&;
 
 template CoroMemberTag DepTestType::test_static_template(const char *volatile &, unsigned);
Index: clang/test/SemaCXX/coroutines-exp-namespace.cpp
===
--- clang/test/SemaCXX/coroutines-exp-namespace.cpp
+++ clang/test/SemaCXX/coroutines-exp-namespace.cpp
@@ -1288,7 +1288,7 @@
   }
 };
 
-template struct DepTestType; // expected-note {{requested here}}
+template struct DepTestType; // expected-note 2{{requested here}}
 template CoroMemberTag DepTestType::test_member_template(long, const char *) const &&;
 
 template CoroMemberTag DepTestType::test_static_template(const char *volatile &, unsigned);
Index: clang/test/SemaCXX/access-base-class.cpp
===
--- clang/test/SemaCXX/access-base-class.cpp
+++ clang/test/SemaCXX/access-base-class.cpp
@@ -96,14 +96,14 @@
 };
 
 template 
-struct trait : flag {};
+struct trait : flag {}; // expected-note 2{{here}}
 
-template ::value>
+template ::value> // expected-note {{here}}
 struct a {};
 
 template 
 class b {
-  a x;
+  a x; // expected-note {{here}}
   using U = a;
 };
 
@@ -113,5 +113,5 @@
 };
 
 // verify "no member named 'value'" bogus diagnostic is not emitted.
-trait>>::value;
+trait>>::value; // expected-note {{here}}
 } // namespace T8
Index: clang/test/CXX/drs/dr25xx.cpp
===
--- clang/test/CXX/drs/dr25xx.cpp
+++ clang/test/CXX/drs/dr25xx.cpp
@@ -1,5 +1,33 @@
 // RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-unknown %s -verify
 
+namespace dr2518 { // dr2518: 17 review
+
+#error one
+// expected-error@-1 {{one}}
+#if 0
+#error skip
+#warning skip // expected-error {{skip}}
+#endif
+#error two
+// expected-error@-1 {{two}}
+#warning 

[PATCH] D144285: [Clang] Implement CWG2518 - static_assert(false)

2023-02-17 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:16805
+// definition, the declaration has no effect.
+bool InTemplateDefinition = getLangOpts().CPlusPlus && 
getTemplateDepth(getCurScope()) != 0;
+

Hmm... interesting way to calculate template depth, I wasn't aware of that one. 
 Does this cause problems in 'a template caused another template to 
instantiate' sorta thing? 

Also, is the "CPlusPlus" test here necessary?



Comment at: clang/test/SemaTemplate/instantiate-var-template.cpp:34
   template void f() {
-static_assert(a == 0, ""); // expected-error 
{{static assertion failed due to requirement 'a == 0'}} \
-   // expected-note 
{{evaluates to '1 == 0'}}
+static_assert(a == 0, ""); // fixme: can we check 
a var is dependant?
   }

You should be able to instantiate this template later, and probably what we now 
have to do.  Also, 'dependent' is the spelling in this case, 'dependant' is 
something different :)



Comment at: clang/test/SemaTemplate/instantiation-dependence.cpp:41
 static_assert(!__is_void(indirect_void_t)); // "ok", dependent
-static_assert(!__is_void(void_t)); // expected-error {{failed}}
+static_assert(!__is_void(void_t)); // fixme: can we check a type is 
dependant?
   }

This one is probably a bigger pain to test, and I don't have a good idea.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144285

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


[PATCH] D144285: [Clang] Implement CWG2518 - static_assert(false)

2023-02-17 Thread Vlad Serebrennikov via Phabricator via cfe-commits
Endill added a comment.

Thank you for the patch.
Any plans to backport this to 16.x branch?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144285

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


[PATCH] D144285: [Clang] Implement CWG2518 - static_assert(false)

2023-02-17 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:16805
+// definition, the declaration has no effect.
+bool InTemplateDefinition = getLangOpts().CPlusPlus && 
getTemplateDepth(getCurScope()) != 0;
+

erichkeane wrote:
> Hmm... interesting way to calculate template depth, I wasn't aware of that 
> one.  Does this cause problems in 'a template caused another template to 
> instantiate' sorta thing? 
> 
> Also, is the "CPlusPlus" test here necessary?
It's what I came up with. Do you think there is a better way?
If you have suggestions for additional tests, I'm all ears!

The  CplusPlus tests is just there to avoid unnecessary cycles in C mode. It 
probably doesn't do much of a difference.



Comment at: clang/test/SemaTemplate/instantiate-var-template.cpp:34
   template void f() {
-static_assert(a == 0, ""); // expected-error 
{{static assertion failed due to requirement 'a == 0'}} \
-   // expected-note 
{{evaluates to '1 == 0'}}
+static_assert(a == 0, ""); // fixme: can we check 
a var is dependant?
   }

erichkeane wrote:
> You should be able to instantiate this template later, and probably what we 
> now have to do.  Also, 'dependent' is the spelling in this case, 'dependant' 
> is something different :)
I'm afraid doing though would defeat the intent of the test - it is after all 
named "InstantiationDependent"


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144285

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


[PATCH] D144285: [Clang] Implement CWG2518 - static_assert(false)

2023-02-17 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

In D144285#4135775 , @Endill wrote:

> Thank you for the patch.
> Any plans to backport this to 16.x branch?

I think that's something we'd need to discuss with more folks but maybe a bit 
of time to see how this behaves on real code wouldn't hurt - even if I 
understand people have a keen interest in getting access to that sooner rather 
than later.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144285

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


[PATCH] D144285: [Clang] Implement CWG2518 - static_assert(false)

2023-02-17 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

In D144285#4135775 , @Endill wrote:

> Thank you for the patch.
> Any plans to backport this to 16.x branch?

I would not really want us to do that, the breaking change here is concerning, 
and I'd like this to spend time in trunk 'baking' a while.




Comment at: clang/lib/Sema/SemaDeclCXX.cpp:16805
+// definition, the declaration has no effect.
+bool InTemplateDefinition = getLangOpts().CPlusPlus && 
getTemplateDepth(getCurScope()) != 0;
+

cor3ntin wrote:
> erichkeane wrote:
> > Hmm... interesting way to calculate template depth, I wasn't aware of that 
> > one.  Does this cause problems in 'a template caused another template to 
> > instantiate' sorta thing? 
> > 
> > Also, is the "CPlusPlus" test here necessary?
> It's what I came up with. Do you think there is a better way?
> If you have suggestions for additional tests, I'm all ears!
> 
> The  CplusPlus tests is just there to avoid unnecessary cycles in C mode. It 
> probably doesn't do much of a difference.
For "Zero" I usually would just check if the current decl-context is dependent. 
 I'm not positive if that is 'correct' without more thought, though I would 
expect it to be?  I think we make sure that is set up correctly everywhere.  it 
would at least be a good check to see where we mess that up :)



Comment at: clang/test/SemaTemplate/instantiate-var-template.cpp:34
   template void f() {
-static_assert(a == 0, ""); // expected-error 
{{static assertion failed due to requirement 'a == 0'}} \
-   // expected-note 
{{evaluates to '1 == 0'}}
+static_assert(a == 0, ""); // fixme: can we check 
a var is dependant?
   }

cor3ntin wrote:
> erichkeane wrote:
> > You should be able to instantiate this template later, and probably what we 
> > now have to do.  Also, 'dependent' is the spelling in this case, 
> > 'dependant' is something different :)
> I'm afraid doing though would defeat the intent of the test - it is after all 
> named "InstantiationDependent"
Ah, yeah, you're right, it isn't clear what this is trying to test to me 
unfortunately.  It might require some history digging.  Same comment as below 
on the spelling.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144285

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


[PATCH] D141008: [Clang][SPIR-V] Emit target extension types for OpenCL types on SPIR-V.

2023-02-17 Thread Joshua Cranmer via Phabricator via cfe-commits
jcranmer-intel updated this revision to Diff 498453.
jcranmer-intel marked 5 inline comments as done.
jcranmer-intel added a comment.

Mostly test fixes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141008

Files:
  clang/include/clang-c/Index.h
  clang/include/clang/Basic/OpenCLExtensionTypes.def
  clang/lib/CodeGen/CGOpenCLRuntime.cpp
  clang/lib/CodeGen/CGOpenCLRuntime.h
  clang/lib/CodeGen/TargetInfo.cpp
  clang/lib/CodeGen/TargetInfo.h
  clang/test/CodeGenOpenCL/cast_image.cl
  clang/test/CodeGenOpenCL/cl20-device-side-enqueue-attributes.cl
  clang/test/CodeGenOpenCL/cl20-device-side-enqueue.cl
  clang/test/CodeGenOpenCL/intel-subgroups-avc-ext-types.cl
  clang/test/CodeGenOpenCL/opencl_types.cl
  clang/test/CodeGenOpenCL/sampler.cl
  clang/test/Index/pipe-size.cl
  llvm/docs/SPIRVUsage.rst

Index: llvm/docs/SPIRVUsage.rst
===
--- llvm/docs/SPIRVUsage.rst
+++ llvm/docs/SPIRVUsage.rst
@@ -75,3 +75,36 @@
 Example:
 
 ``-target spirv64v1.0`` can be used to compile for SPIR-V version 1.0 with 64-bit pointer width.
+
+.. _spirv-types:
+
+Representing special types in SPIR-V
+
+
+SPIR-V specifies several kinds of opaque types. These types are represented
+using target extension types. These types are represented as follows:
+
+  .. table:: SPIR-V Opaque Types
+
+ == == =
+ SPIR-V TypeLLVM type name LLVM type arguments
+ == == =
+ OpTypeImage``spirv.Image``sampled type, dimensionality, depth, arrayed, MS, sampled, image format, access qualifier
+ OpTypeSampler  ``spirv.Sampler``  (none)
+ OpTypeSampledImage ``spirv.SampledImage`` sampled type, dimensionality, depth, arrayed, MS, sampled, image format, access qualifier
+ OpTypeEvent``spirv.Event``(none)
+ OpTypeDeviceEvent  ``spirv.DeviceEvent``  (none)
+ OpTypeReserveId``spirv.ReserveId``(none)
+ OpTypeQueue``spirv.Queue``(none)
+ OpTypePipe ``spirv.Pipe`` access qualifier
+ OpTypePipeStorage  ``spirv.PipeStorage``  (none)
+ == == =
+
+All integer arguments take the same value as they do in their `corresponding
+SPIR-V instruction `_.
+For example, the OpenCL type ``image2d_depth_ro_t`` would be represented in
+SPIR-V IR as ``target("spirv.Image", void, 1, 1, 0, 0, 0, 0, 0)``, with its
+dimensionality parameter as ``1`` meaning 2D. Sampled image types include the
+parameters of its underlying image type, so that a sampled image for the
+previous type has the representation
+``target("spirv.SampledImage, void, 1, 1, 0, 0, 0, 0, 0)``.
Index: clang/test/Index/pipe-size.cl
===
--- clang/test/Index/pipe-size.cl
+++ clang/test/Index/pipe-size.cl
@@ -7,9 +7,9 @@
 int s = sizeof(test);
 // X86: store ptr %test, ptr %test.addr, align 8
 // X86: store i32 8, ptr %s, align 4
-// SPIR: store ptr addrspace(1) %test, ptr %test.addr, align 4
+// SPIR: store target("spirv.Pipe", 0) %test, ptr %test.addr, align 4
 // SPIR: store i32 4, ptr %s, align 4
-// SPIR64: store ptr addrspace(1) %test, ptr %test.addr, align 8
+// SPIR64: store target("spirv.Pipe", 0) %test, ptr %test.addr, align 8
 // SPIR64: store i32 8, ptr %s, align 4
 // AMDGCN: store ptr addrspace(1) %test, ptr addrspace(5) %test.addr, align 8
 // AMDGCN: store i32 8, ptr addrspace(5) %s, align 4
Index: clang/test/CodeGenOpenCL/sampler.cl
===
--- clang/test/CodeGenOpenCL/sampler.cl
+++ clang/test/CodeGenOpenCL/sampler.cl
@@ -1,6 +1,9 @@
-// RUN: %clang_cc1 -no-opaque-pointers %s -emit-llvm -triple spir-unknown-unknown -o - -O0 | FileCheck %s
-// RUN: %clang_cc1 -no-opaque-pointers %s -cl-std=CL2.0 -emit-llvm -triple spir-unknown-unknown -o - -O0 | FileCheck %s
-// RUN: %clang_cc1 -no-opaque-pointers %s -cl-std=clc++ -emit-llvm -triple spir-unknown-unknown -o - -O0 | FileCheck %s
+// RUN: %clang_cc1 %s -emit-llvm -triple spir-unknown-unknown -o - -O0 | FileCheck --check-prefixes=CHECK-COMMON,CHECK-SPIR %s
+// RUN: %clang_cc1 %s -cl-std=CL2.0 -emit-llvm -triple spir-unknown-unknown -o - -O0 | FileCheck --check-prefixes=CHECK-COMMON,CHECK-SPIR %s
+// RUN: %clang_cc1 %s -cl-std=clc++ -emit-llvm -triple spir-unknown-unknown -o - -O0 | FileCheck --check-prefixes=

[PATCH] D141008: [Clang][SPIR-V] Emit target extension types for OpenCL types on SPIR-V.

2023-02-17 Thread Joshua Cranmer via Phabricator via cfe-commits
jcranmer-intel added inline comments.



Comment at: clang/test/CodeGenOpenCL/opencl_types.cl:2
 // RUN: %clang_cc1 -no-opaque-pointers -cl-std=CL2.0 %s -triple 
"spir-unknown-unknown" -emit-llvm -o - -O0 | FileCheck %s 
--check-prefixes=CHECK-COM,CHECK-SPIR
 // RUN: %clang_cc1 -no-opaque-pointers -cl-std=CL2.0 %s -triple 
"amdgcn--amdhsa" -emit-llvm -o - -O0 | FileCheck %s 
--check-prefixes=CHECK-COM,CHECK-AMDGCN
 

yaxunl wrote:
> need a non-spir target
This file checks AMD already.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141008

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


[PATCH] D144285: [Clang] Implement CWG2518 - static_assert(false)

2023-02-17 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 498455.
cor3ntin added a comment.

- Simplify how we check we are in a dependent context
- Fix typos


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144285

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/CXX/drs/dr25xx.cpp
  clang/test/SemaCXX/access-base-class.cpp
  clang/test/SemaCXX/coroutines-exp-namespace.cpp
  clang/test/SemaCXX/coroutines.cpp
  clang/test/SemaCXX/static-assert.cpp
  clang/test/SemaTemplate/instantiate-var-template.cpp
  clang/test/SemaTemplate/instantiation-dependence.cpp
  clang/www/cxx_dr_status.html

Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -14915,7 +14915,7 @@
 https://wg21.link/cwg2518";>2518
 review
 Conformance requirements and #error/#warning
-Not resolved
+Clang 17
   
   
 https://wg21.link/cwg2519";>2519
Index: clang/test/SemaTemplate/instantiation-dependence.cpp
===
--- clang/test/SemaTemplate/instantiation-dependence.cpp
+++ clang/test/SemaTemplate/instantiation-dependence.cpp
@@ -38,7 +38,7 @@
 
   template void foo() {
 static_assert(!__is_void(indirect_void_t)); // "ok", dependent
-static_assert(!__is_void(void_t)); // expected-error {{failed}}
+static_assert(!__is_void(void_t)); // fixme: can we check a type is dependent?
   }
 }
 
Index: clang/test/SemaTemplate/instantiate-var-template.cpp
===
--- clang/test/SemaTemplate/instantiate-var-template.cpp
+++ clang/test/SemaTemplate/instantiate-var-template.cpp
@@ -31,9 +31,9 @@
   static_assert(b == 1, ""); // expected-note {{in instantiation of}}
 
   template void f() {
-static_assert(a == 0, ""); // expected-error {{static assertion failed due to requirement 'a == 0'}} \
-   // expected-note {{evaluates to '1 == 0'}}
+static_assert(a == 0, ""); // fixme: can we check a var is dependent?
   }
+
 }
 
 namespace PR24483 {
Index: clang/test/SemaCXX/static-assert.cpp
===
--- clang/test/SemaCXX/static-assert.cpp
+++ clang/test/SemaCXX/static-assert.cpp
@@ -54,7 +54,7 @@
   // Only give one error here.
   static_assert(false, ""); // expected-error {{static assertion failed}}
 };
-AlwaysFails alwaysFails;
+AlwaysFails alwaysFails; // expected-note {{instantiation}}
 
 template struct StaticAssertProtected {
   static_assert(__is_literal(T), ""); // expected-error {{static assertion failed}}
Index: clang/test/SemaCXX/coroutines.cpp
===
--- clang/test/SemaCXX/coroutines.cpp
+++ clang/test/SemaCXX/coroutines.cpp
@@ -1309,7 +1309,7 @@
   }
 };
 
-template struct DepTestType; // expected-note {{requested here}}
+template struct DepTestType; // expected-note 2{{requested here}}
 template CoroMemberTag DepTestType::test_member_template(long, const char *) const &&;
 
 template CoroMemberTag DepTestType::test_static_template(const char *volatile &, unsigned);
Index: clang/test/SemaCXX/coroutines-exp-namespace.cpp
===
--- clang/test/SemaCXX/coroutines-exp-namespace.cpp
+++ clang/test/SemaCXX/coroutines-exp-namespace.cpp
@@ -1288,7 +1288,7 @@
   }
 };
 
-template struct DepTestType; // expected-note {{requested here}}
+template struct DepTestType; // expected-note 2{{requested here}}
 template CoroMemberTag DepTestType::test_member_template(long, const char *) const &&;
 
 template CoroMemberTag DepTestType::test_static_template(const char *volatile &, unsigned);
Index: clang/test/SemaCXX/access-base-class.cpp
===
--- clang/test/SemaCXX/access-base-class.cpp
+++ clang/test/SemaCXX/access-base-class.cpp
@@ -96,14 +96,14 @@
 };
 
 template 
-struct trait : flag {};
+struct trait : flag {}; // expected-note 2{{here}}
 
-template ::value>
+template ::value> // expected-note {{here}}
 struct a {};
 
 template 
 class b {
-  a x;
+  a x; // expected-note {{here}}
   using U = a;
 };
 
@@ -113,5 +113,5 @@
 };
 
 // verify "no member named 'value'" bogus diagnostic is not emitted.
-trait>>::value;
+trait>>::value; // expected-note {{here}}
 } // namespace T8
Index: clang/test/CXX/drs/dr25xx.cpp
===
--- clang/test/CXX/drs/dr25xx.cpp
+++ clang/test/CXX/drs/dr25xx.cpp
@@ -1,5 +1,33 @@
 // RUN: %clang_cc1 -std=c++20 -triple x86_64-unknown-unknown %s -verify
 
+namespace dr2518 { // dr2518: 17 review
+
+#error one
+// expected-error@-1 {{one}}
+#if 0
+#error skip
+#warning skip // expected-error {{skip}}
+#endif
+#error two
+

[PATCH] D144285: [Clang] Implement CWG2518 - static_assert(false)

2023-02-17 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin marked 2 inline comments as done.
cor3ntin added inline comments.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:16805
+// definition, the declaration has no effect.
+bool InTemplateDefinition = getLangOpts().CPlusPlus && 
getTemplateDepth(getCurScope()) != 0;
+

erichkeane wrote:
> cor3ntin wrote:
> > erichkeane wrote:
> > > Hmm... interesting way to calculate template depth, I wasn't aware of 
> > > that one.  Does this cause problems in 'a template caused another 
> > > template to instantiate' sorta thing? 
> > > 
> > > Also, is the "CPlusPlus" test here necessary?
> > It's what I came up with. Do you think there is a better way?
> > If you have suggestions for additional tests, I'm all ears!
> > 
> > The  CplusPlus tests is just there to avoid unnecessary cycles in C mode. 
> > It probably doesn't do much of a difference.
> For "Zero" I usually would just check if the current decl-context is 
> dependent.  I'm not positive if that is 'correct' without more thought, 
> though I would expect it to be?  I think we make sure that is set up 
> correctly everywhere.  it would at least be a good check to see where we mess 
> that up :)
Yes, i feel stupid now, that was the obvious solution! Thanks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144285

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


[PATCH] D143919: [Clang] Copy strictfp attribute from pattern to instantiation

2023-02-17 Thread Eli Friedman via Phabricator via cfe-commits
efriedma accepted this revision.
efriedma 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/D143919/new/

https://reviews.llvm.org/D143919

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


[PATCH] D144288: [RISCV] Add missing plumbing and tests for zfa

2023-02-17 Thread Philip Reames via Phabricator via cfe-commits
reames created this revision.
reames added reviewers: craig.topper, asb, Joshua-401, kito-cheng, lbenes, 
jrtc27.
Herald added subscribers: luke, VincentWu, vkmr, frasercrmck, jdoerfert, 
evandro, luismarques, apazos, sameer.abuasal, s.egerton, Jim, benna, psnobl, 
jocewei, PkmX, the_o, brucehoult, MartinMosbeck, rogfer01, edward-jones, 
zzheng, shiva0217, niosHD, sabuasal, bollu, simoncook, johnrusso, rbar, 
hiraditya, arichardson, mcrosier.
Herald added a project: All.
reames requested review of this revision.
Herald added subscribers: cfe-commits, pcwang-thead, eopXD, MaskRay.
Herald added projects: clang, LLVM.

Experimental support for the zfa extension was recently added in 
https://reviews.llvm.org/D141984.  A couple of the normal test changes and 
clang plumbing got missed in that change.  This commit updates the usual 
suspects.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144288

Files:
  clang/test/Preprocessor/riscv-target-features.c
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/test/CodeGen/RISCV/attributes.ll
  llvm/test/MC/RISCV/attribute-arch.s


Index: llvm/test/MC/RISCV/attribute-arch.s
===
--- llvm/test/MC/RISCV/attribute-arch.s
+++ llvm/test/MC/RISCV/attribute-arch.s
@@ -199,3 +199,6 @@
 
 .attribute arch, "rv32izifencei2p0"
 # CHECK: attribute  5, "rv32i2p0_zifencei2p0"
+
+.attribute arch, "rv32izfa0p1"
+# CHECK: attribute  5, "rv32i2p0_zfa0p1"
Index: llvm/test/CodeGen/RISCV/attributes.ll
===
--- llvm/test/CodeGen/RISCV/attributes.ll
+++ llvm/test/CodeGen/RISCV/attributes.ll
@@ -48,6 +48,7 @@
 ; RUN: llc -mtriple=riscv32 -mattr=+experimental-zcf %s -o - | FileCheck 
--check-prefixes=CHECK,RV32ZCF %s
 ; RUN: llc -mtriple=riscv32 -mattr=+zicsr %s -o - | FileCheck 
--check-prefixes=CHECK,RV32ZICSR %s
 ; RUN: llc -mtriple=riscv32 -mattr=+zifencei %s -o - | FileCheck 
--check-prefixes=CHECK,RV32ZIFENCEI %s
+; RUN: llc -mtriple=riscv32 -mattr=+experimental-zfa %s -o - | FileCheck 
--check-prefixes=CHECK,RV32ZFA %s
 
 ; RUN: llc -mtriple=riscv64 %s -o - | FileCheck %s
 ; RUN: llc -mtriple=riscv64 -mattr=+m %s -o - | FileCheck 
--check-prefixes=CHECK,RV64M %s
@@ -103,6 +104,7 @@
 ; RUN: llc -mtriple=riscv64 -mattr=+experimental-zcd %s -o - | FileCheck 
--check-prefixes=CHECK,RV64ZCD %s
 ; RUN: llc -mtriple=riscv64 -mattr=+zicsr %s -o - | FileCheck 
--check-prefixes=CHECK,RV64ZICSR %s
 ; RUN: llc -mtriple=riscv64 -mattr=+zifencei %s -o - | FileCheck 
--check-prefixes=CHECK,RV64ZIFENCEI %s
+; RUN: llc -mtriple=riscv64 -mattr=+experimental-zfa %s -o - | FileCheck 
--check-prefixes=CHECK,RV64ZFA %s
 
 ; CHECK: .attribute 4, 16
 
@@ -153,6 +155,7 @@
 ; RV32ZCF: .attribute 5, "rv32i2p0_zcf1p0"
 ; RV32ZICSR: .attribute 5, "rv32i2p0_zicsr2p0"
 ; RV32ZIFENCEI: .attribute 5, "rv32i2p0_zifencei2p0"
+; RV32ZFA: .attribute 5, "rv32i2p0_f2p0_zfa0p1"
 
 ; RV64M: .attribute 5, "rv64i2p0_m2p0"
 ; RV64ZMMUL: .attribute 5, "rv64i2p0_zmmul1p0"
@@ -207,6 +210,7 @@
 ; RV64ZCD: .attribute 5, "rv64i2p0_zcd1p0"
 ; RV64ZICSR: .attribute 5, "rv64i2p0_zicsr2p0"
 ; RV64ZIFENCEI: .attribute 5, "rv64i2p0_zifencei2p0"
+; RV64ZFA: .attribute 5, "rv64i2p0_f2p0_zfa0p1"
 
 define i32 @addi(i32 %a) {
   %1 = add i32 %a, 1
Index: llvm/lib/Support/RISCVISAInfo.cpp
===
--- llvm/lib/Support/RISCVISAInfo.cpp
+++ llvm/lib/Support/RISCVISAInfo.cpp
@@ -126,6 +126,7 @@
 {"zcb", RISCVExtensionVersion{1, 0}},
 {"zcd", RISCVExtensionVersion{1, 0}},
 {"zcf", RISCVExtensionVersion{1, 0}},
+{"zfa", RISCVExtensionVersion{0, 1}},
 {"zvfh", RISCVExtensionVersion{0, 1}},
 {"zawrs", RISCVExtensionVersion{1, 0}},
 {"ztso", RISCVExtensionVersion{0, 1}},
Index: clang/test/Preprocessor/riscv-target-features.c
===
--- clang/test/Preprocessor/riscv-target-features.c
+++ clang/test/Preprocessor/riscv-target-features.c
@@ -506,3 +506,11 @@
 // RUN: %clang -target riscv64-unknown-linux-gnu -march=rv64izifencei2p0 -x c 
-E -dM %s \
 // RUN: -o - | FileCheck --check-prefix=CHECK-ZIFENCEI-EXT %s
 // CHECK-ZIFENCEI-EXT: __riscv_zifencei 200{{$}}
+
+// RUN: %clang -target riscv32-unknown-linux-gnu 
-menable-experimental-extensions \
+// RUN: -march=rv32izfa0p1 -x c -E -dM %s \
+// RUN: -o - | FileCheck --check-prefix=CHECK-ZFA-EXT %s
+// RUN: %clang -target riscv64-unknown-linux-gnu 
-menable-experimental-extensions \
+// RUN: -march=rv64izfa0p1 -x c -E -dM %s \
+// RUN: -o - | FileCheck --check-prefix=CHECK-ZFA-EXT %s
+// CHECK-ZFA-EXT: __riscv_zfa 1000{{$}}


Index: llvm/test/MC/RISCV/attribute-arch.s
===
--- llvm/test/MC/RISCV/attribute-arch.s
+++ llvm/test/MC/RISCV/attribute-arch.s
@@ -199,3 +199,6 @@
 
 .attribute arch, "rv32izifencei2p0"
 # CHECK: attribute  5, "rv32i2p0_zifencei2p

[PATCH] D144288: [RISCV] Add missing plumbing and tests for zfa

2023-02-17 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: llvm/lib/Support/RISCVISAInfo.cpp:853
 // Note: The table needs to be sorted by name.
 static constexpr ImpliedExtsEntry ImpliedExts[] = {
 {{"v"}, {ImpliedExtsV}},

I think zfa should imply F here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144288

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


[PATCH] D144285: [Clang] Implement CWG2518 - static_assert(false)

2023-02-17 Thread Erich Keane via Phabricator via cfe-commits
erichkeane accepted this revision.
erichkeane added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:16806
+bool InTemplateDefinition =
+getLangOpts().CPlusPlus && CurContext->isDependentContext();
+

CplusPlus check is now not really beneficial?  I'm not sure how much it matters 
now though that these are both just bit-loads.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144285

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


[PATCH] D144135: [clang-tidy] Add performance-enum-size check

2023-02-17 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL updated this revision to Diff 498471.
PiotrZSL added a comment.

Updated documentation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144135

Files:
  clang-tools-extra/clang-tidy/performance/CMakeLists.txt
  clang-tools-extra/clang-tidy/performance/EnumSizeCheck.cpp
  clang-tools-extra/clang-tidy/performance/EnumSizeCheck.h
  clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/performance/enum-size.rst
  clang-tools-extra/test/clang-tidy/checkers/performance/enum-size.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance/enum-size.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/performance/enum-size.cpp
@@ -0,0 +1,94 @@
+// RUN: %check_clang_tidy -std=c++17-or-later %s performance-enum-size %t -- \
+// RUN:   -config="{CheckOptions: [{key: performance-enum-size.EnumIgnoreRegexp, value: '^::IgnoredEnum$'}]}"
+
+namespace std
+{
+using uint8_t = unsigned char;
+using int8_t = signed char;
+using uint16_t = unsigned short;
+using int16_t = signed short;
+using uint32_t = unsigned int;
+using int32_t = signed int;
+}
+
+enum class Value
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: enum 'Value' derive from 'int' of size 4 bytes, derive from 'std::uint8_t' to reduce it size to 1 [performance-enum-size]
+{
+supported
+};
+
+
+enum class EnumClass : std::int16_t
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: enum 'EnumClass' derive from 'std::int16_t' (aka 'short') of size 2 bytes, derive from 'std::uint8_t' to reduce it size to 1 [performance-enum-size]
+{
+supported
+};
+
+enum EnumWithType : std::uint16_t
+// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: enum 'EnumWithType' derive from 'std::uint16_t' (aka 'unsigned short') of size 2 bytes, derive from 'std::uint8_t' to reduce it size to 1 [performance-enum-size]
+{
+supported,
+supported2
+};
+
+enum EnumWithNegative
+// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: enum 'EnumWithNegative' derive from 'int' of size 4 bytes, derive from 'std::int8_t' to reduce it size to 1 [performance-enum-size]
+{
+s1 = -128,
+s2 = -100,
+s3 = 100,
+s4 = 127
+};
+
+enum EnumThatCanBeReducedTo2Bytes
+// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: enum 'EnumThatCanBeReducedTo2Bytes' derive from 'int' of size 4 bytes, derive from 'std::int16_t' to reduce it size to 2 [performance-enum-size]
+{
+a1 = -128,
+a2 = 0x6EEE
+};
+
+enum EnumOnlyNegative
+// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: enum 'EnumOnlyNegative' derive from 'int' of size 4 bytes, derive from 'std::int8_t' to reduce it size to 1 [performance-enum-size]
+{
+b1 = -125,
+b2 = -50,
+b3 = -10
+};
+
+enum CorrectU8 : std::uint8_t
+{
+c01 = 10,
+c02 = 11
+};
+
+enum CorrectU16 : std::uint16_t
+{
+c11 = 10,
+c12 = 0x
+};
+
+constexpr int getValue()
+{
+return 256;
+}
+
+
+enum CalculatedDueToUnknown1 : unsigned int
+// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: enum 'CalculatedDueToUnknown1' derive from 'unsigned int' of size 4 bytes, derive from 'std::uint16_t' to reduce it size to 2 [performance-enum-size]
+{
+c21 = 10,
+c22 = getValue()
+};
+
+enum CalculatedDueToUnknown2 : unsigned int
+// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: enum 'CalculatedDueToUnknown2' derive from 'unsigned int' of size 4 bytes, derive from 'std::uint16_t' to reduce it size to 2 [performance-enum-size]
+{
+c31 = 10,
+c32 = c31 + 246
+};
+
+enum class IgnoredEnum : std::uint32_t
+{
+unused1 = 1,
+unused2 = 2
+};
Index: clang-tools-extra/docs/clang-tidy/checks/performance/enum-size.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/performance/enum-size.rst
@@ -0,0 +1,72 @@
+.. title:: clang-tidy - performance-enum-size
+
+performance-enum-size
+=
+
+Recommends the smallest possible underlying type for an ``enum`` or ``enum``
+class based on the range of its enumerators. Analyzes the values of the
+enumerators in an ``enum`` or ``enum`` class, including signed values, to
+recommend the smallest possible underlying type that can represent all the
+values of the ``enum``. The suggested underlying types are the integral types
+``std::uint8_t``, ``std::uint16_t``, and ``std::uint32_t`` for unsigned types,
+and ``std::int8_t``, ``std::int16_t``, and ``std::int32_t`` for signed types.
+Using the suggested underlying types can help reduce the memory footprint of
+the program and improve performance in some cases.
+
+For example:
+
+.. code-block:: c++
+
+// BEFORE
+enum Color {
+RED = -1,
+GREEN = 0,
+BLUE = 1
+};
+
+std::optional color_opt;
+
+The `Color` ``enum`` uses the default under

[PATCH] D144285: [Clang] Implement CWG2518 - static_assert(false)

2023-02-17 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:16806
+bool InTemplateDefinition =
+getLangOpts().CPlusPlus && CurContext->isDependentContext();
+

erichkeane wrote:
> CplusPlus check is now not really beneficial?  I'm not sure how much it 
> matters now though that these are both just bit-loads.
isDependentContext still does a bunch of work, recursively. I think we should 
keep it!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144285

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


[PATCH] D144135: [clang-tidy] Add performance-enum-size check

2023-02-17 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL updated this revision to Diff 498472.
PiotrZSL added a comment.

Typo in doc


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144135

Files:
  clang-tools-extra/clang-tidy/performance/CMakeLists.txt
  clang-tools-extra/clang-tidy/performance/EnumSizeCheck.cpp
  clang-tools-extra/clang-tidy/performance/EnumSizeCheck.h
  clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/performance/enum-size.rst
  clang-tools-extra/test/clang-tidy/checkers/performance/enum-size.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance/enum-size.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/performance/enum-size.cpp
@@ -0,0 +1,94 @@
+// RUN: %check_clang_tidy -std=c++17-or-later %s performance-enum-size %t -- \
+// RUN:   -config="{CheckOptions: [{key: performance-enum-size.EnumIgnoreRegexp, value: '^::IgnoredEnum$'}]}"
+
+namespace std
+{
+using uint8_t = unsigned char;
+using int8_t = signed char;
+using uint16_t = unsigned short;
+using int16_t = signed short;
+using uint32_t = unsigned int;
+using int32_t = signed int;
+}
+
+enum class Value
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: enum 'Value' derive from 'int' of size 4 bytes, derive from 'std::uint8_t' to reduce it size to 1 [performance-enum-size]
+{
+supported
+};
+
+
+enum class EnumClass : std::int16_t
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: enum 'EnumClass' derive from 'std::int16_t' (aka 'short') of size 2 bytes, derive from 'std::uint8_t' to reduce it size to 1 [performance-enum-size]
+{
+supported
+};
+
+enum EnumWithType : std::uint16_t
+// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: enum 'EnumWithType' derive from 'std::uint16_t' (aka 'unsigned short') of size 2 bytes, derive from 'std::uint8_t' to reduce it size to 1 [performance-enum-size]
+{
+supported,
+supported2
+};
+
+enum EnumWithNegative
+// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: enum 'EnumWithNegative' derive from 'int' of size 4 bytes, derive from 'std::int8_t' to reduce it size to 1 [performance-enum-size]
+{
+s1 = -128,
+s2 = -100,
+s3 = 100,
+s4 = 127
+};
+
+enum EnumThatCanBeReducedTo2Bytes
+// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: enum 'EnumThatCanBeReducedTo2Bytes' derive from 'int' of size 4 bytes, derive from 'std::int16_t' to reduce it size to 2 [performance-enum-size]
+{
+a1 = -128,
+a2 = 0x6EEE
+};
+
+enum EnumOnlyNegative
+// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: enum 'EnumOnlyNegative' derive from 'int' of size 4 bytes, derive from 'std::int8_t' to reduce it size to 1 [performance-enum-size]
+{
+b1 = -125,
+b2 = -50,
+b3 = -10
+};
+
+enum CorrectU8 : std::uint8_t
+{
+c01 = 10,
+c02 = 11
+};
+
+enum CorrectU16 : std::uint16_t
+{
+c11 = 10,
+c12 = 0x
+};
+
+constexpr int getValue()
+{
+return 256;
+}
+
+
+enum CalculatedDueToUnknown1 : unsigned int
+// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: enum 'CalculatedDueToUnknown1' derive from 'unsigned int' of size 4 bytes, derive from 'std::uint16_t' to reduce it size to 2 [performance-enum-size]
+{
+c21 = 10,
+c22 = getValue()
+};
+
+enum CalculatedDueToUnknown2 : unsigned int
+// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: enum 'CalculatedDueToUnknown2' derive from 'unsigned int' of size 4 bytes, derive from 'std::uint16_t' to reduce it size to 2 [performance-enum-size]
+{
+c31 = 10,
+c32 = c31 + 246
+};
+
+enum class IgnoredEnum : std::uint32_t
+{
+unused1 = 1,
+unused2 = 2
+};
Index: clang-tools-extra/docs/clang-tidy/checks/performance/enum-size.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/performance/enum-size.rst
@@ -0,0 +1,72 @@
+.. title:: clang-tidy - performance-enum-size
+
+performance-enum-size
+=
+
+Recommends the smallest possible underlying type for an ``enum`` or ``enum``
+class based on the range of its enumerators. Analyzes the values of the
+enumerators in an ``enum`` or ``enum`` class, including signed values, to
+recommend the smallest possible underlying type that can represent all the
+values of the ``enum``. The suggested underlying types are the integral types
+``std::uint8_t``, ``std::uint16_t``, and ``std::uint32_t`` for unsigned types,
+and ``std::int8_t``, ``std::int16_t``, and ``std::int32_t`` for signed types.
+Using the suggested underlying types can help reduce the memory footprint of
+the program and improve performance in some cases.
+
+For example:
+
+.. code-block:: c++
+
+// BEFORE
+enum Color {
+RED = -1,
+GREEN = 0,
+BLUE = 1
+};
+
+std::optional color_opt;
+
+The `Color` ``enum`` uses the default underlying type,

[PATCH] D144217: [clang-tidy] Fix false-positive in readability-container-size-empty

2023-02-17 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL created this revision.
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a reviewer: njames93.
Herald added a project: All.
PiotrZSL added a comment.
Eugene.Zelenko added reviewers: aaron.ballman, carlosgalvezp.
PiotrZSL updated this revision to Diff 498450.
PiotrZSL published this revision for review.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

I may consider tomorrow moving `std::array` into into some dedicated option, 
like IgnoredContainersInComparisonRegexp


PiotrZSL added a comment.

Add configuration option. Release Notes + documentation for new option powered 
by ChatGPT.


PiotrZSL added a comment.

Ready for review


Ignoring std::array type when matching 'std:array == std::array()'.
In such case we shouldn't propose to use empty().

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144217

Files:
  clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
  clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/readability/container-size-empty.rst
  
clang-tools-extra/test/clang-tidy/checkers/readability/container-size-empty.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability/container-size-empty.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability/container-size-empty.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability/container-size-empty.cpp
@@ -724,10 +724,37 @@
   size_type size() const;
   bool empty() const;
 };
-void test() {
+
+void testTypedefSize() {
   TypedefSize ts;
   if (ts.size() == 0)
 ;
   // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used
   // CHECK-FIXES: {{^  }}if (ts.empty()){{$}}
 }
+
+namespace std {
+
+template  struct array {
+  bool operator==(const array& other) const;
+  bool operator!=(const array& other) const;
+  unsigned long size() const { return N; }
+  bool empty() const { return N != 0U; }
+
+  T data[N];
+};
+
+}
+
+typedef std::array Array;
+
+bool testArraySize(const Array& value) {
+  return value.size() == 0U;
+// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+// CHECK-FIXES: {{^  }}return value.empty();{{$}}
+// CHECK-MESSAGES: :742:8: note: method 'array'::empty() defined here
+}
+
+bool testArrayCompareToEmptye(const Array& value) {
+  return value == std::array();
+}
Index: clang-tools-extra/docs/clang-tidy/checks/readability/container-size-empty.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/readability/container-size-empty.rst
+++ clang-tools-extra/docs/clang-tidy/checks/readability/container-size-empty.rst
@@ -24,3 +24,11 @@
   bool empty() const;
 
 `size_type` can be any kind of integer type.
+
+.. option:: IgnoreComparisonForTypesRegexp
+
+Excludes certain classes from the check using a regular expression of ERE
+syntax. If excluded, the check won't suggest replacing the comparison of
+an object with a default constructed object of the same type using
+``empty()``. This option is useful if the check incorrectly flags such
+comparisons for certain classes. Default value is `^::std::array`.
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -130,6 +130,11 @@
 Changes in existing checks
 ^^
 
+- Fixed a false positive in :doc:`readability-container-size-empty
+  ` check when comparing
+  ``std::array`` objects to default constructed ones. The behavior for this and
+  other relevant classes can now be configured with a new option.
+
 Removed checks
 ^^
 
Index: clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.h
===
--- clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.h
+++ clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.h
@@ -10,6 +10,7 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_CONTAINERSIZEEMPTYCHECK_H
 
 #include "../ClangTidyCheck.h"
+#include 
 
 namespace clang::tidy::readability {
 
@@ -31,9 +32,13 @@
   }
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+  void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
   std::optional getCheckTraversalKind() const override {
 return TK_IgnoreUnlessSpelledInSource;
   }
+
+private:
+  std::string IgnoreComparisonForTypesRegexp;
 };
 
 } // namespace clang::tidy::readability
Index: clang-tools-extra/clang-tidy

[PATCH] D144285: [Clang] Implement CWG2518 - static_assert(false)

2023-02-17 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:16806
+bool InTemplateDefinition =
+getLangOpts().CPlusPlus && CurContext->isDependentContext();
+

cor3ntin wrote:
> erichkeane wrote:
> > CplusPlus check is now not really beneficial?  I'm not sure how much it 
> > matters now though that these are both just bit-loads.
> isDependentContext still does a bunch of work, recursively. I think we should 
> keep it!
Ah, Oh! You're right!  It is the Expr class where this is free/just checking a 
bit.  Disregard.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144285

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


[PATCH] D141569: [clang-tidy] Implement CppCoreGuideline F.18

2023-02-17 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL added a comment.

You right swap case can also be invalid (rvalue not needed, there).
Anyway it it has too be script then this can be strict.

But message could be better, for example if we don't move all fields of class, 
then this could warn that its not fully moved, or that some members are 
accessed without move., or at least is not moved as whole.
Because not it could be confusing...

  void Class:set(Obj&& obj) // warning: rvalue reference parameter 'obj' is 
never moved from inside the function body 
[cppcoreguidelines-rvalue-reference-param-not-moved]
  {
  this->a = std::move(obj.a);
  this->b = std::move(obj.b);
  this->c = std::move(obj.c);
  }

And then when you read "is never moved" you tap your forehead, about whats 
going on, you did move everything you wanted.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141569

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


[PATCH] D144291: [clang-format-diff] Correctly parse start-of-file diffs

2023-02-17 Thread Tamir Duberstein via Phabricator via cfe-commits
tamird created this revision.
tamird added a reviewer: hans.
Herald added a project: All.
tamird requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Handle the case where the diff is a pure removal of lines. Before this
change start_line would end up as 0 which is rejected by clang-format.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144291

Files:
  clang/tools/clang-format/clang-format-diff.py


Index: clang/tools/clang-format/clang-format-diff.py
===
--- clang/tools/clang-format/clang-format-diff.py
+++ clang/tools/clang-format/clang-format-diff.py
@@ -84,12 +84,19 @@
   if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
 continue
 
-match = re.search(r'^@@.*\+(\d+)(,(\d+))?', line)
+match = re.search(r'^@@.*\+(\d+)(?:,(\d+))?', line)
 if match:
   start_line = int(match.group(1))
   line_count = 1
-  if match.group(3):
-line_count = int(match.group(3))
+  if match.group(2):
+line_count = int(match.group(2))
+# The input is something like
+#
+# @@ -1, +0,0 @@
+#
+# which means no lines were added.
+if line_count == 0:
+  continue
   # Also format lines range if line_count is 0 in case of deleting
   # surrounding statements.
   end_line = start_line


Index: clang/tools/clang-format/clang-format-diff.py
===
--- clang/tools/clang-format/clang-format-diff.py
+++ clang/tools/clang-format/clang-format-diff.py
@@ -84,12 +84,19 @@
   if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
 continue
 
-match = re.search(r'^@@.*\+(\d+)(,(\d+))?', line)
+match = re.search(r'^@@.*\+(\d+)(?:,(\d+))?', line)
 if match:
   start_line = int(match.group(1))
   line_count = 1
-  if match.group(3):
-line_count = int(match.group(3))
+  if match.group(2):
+line_count = int(match.group(2))
+# The input is something like
+#
+# @@ -1, +0,0 @@
+#
+# which means no lines were added.
+if line_count == 0:
+  continue
   # Also format lines range if line_count is 0 in case of deleting
   # surrounding statements.
   end_line = start_line
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D144293: [PowerPC] Fix the implicit casting for the emulated intrinsics

2023-02-17 Thread Maryam Moghadas via Phabricator via cfe-commits
maryammo created this revision.
Herald added subscribers: shchenz, kbarton, nemanjai.
Herald added a project: All.
maryammo requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch is to fix some implicit castings for emulated intrinsics
so that there are no lax-vector-conversions errors and warnings.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144293

Files:
  clang/lib/Headers/ppc_wrappers/emmintrin.h
  clang/lib/Headers/ppc_wrappers/smmintrin.h
  clang/test/CodeGen/PowerPC/ppc-smmintrin.c


Index: clang/test/CodeGen/PowerPC/ppc-smmintrin.c
===
--- clang/test/CodeGen/PowerPC/ppc-smmintrin.c
+++ clang/test/CodeGen/PowerPC/ppc-smmintrin.c
@@ -73,7 +73,7 @@
 
 // CHECK-LABEL: define available_externally <2 x i64> @_mm_blend_epi16(<2 x 
i64> noundef %{{[0-9a-zA-Z_.]+}}, <2 x i64> noundef %{{[0-9a-zA-Z_.]+}}, i32 
noundef signext %{{[0-9a-zA-Z_.]+}})
 // CHECK: %[[TRUNC:[0-9a-zA-Z_.]+]] = trunc i32 %{{[0-9a-zA-Z_.]+}} to i8
-// CHECK: call <16 x i8> @vec_splats(signed char)(i8 noundef signext 
%[[TRUNC]])
+// CHECK: call <16 x i8> @vec_splats(unsigned char)(i8 noundef zeroext 
%[[TRUNC]])
 // CHECK: call <16 x i8> @llvm.ppc.altivec.vgbbd(<16 x i8> %{{[0-9a-zA-Z_.]+}})
 // CHECK: %[[PACK:[0-9a-zA-Z_.]+]] = call <8 x i16> @vec_unpackh(signed char 
vector[16])
 // CHECK: store <8 x i16> %[[PACK]], ptr %{{[0-9a-zA-Z_.]+}}, align 16
@@ -232,8 +232,8 @@
 test_round() {
   _mm_round_ps(mn1, 0);
   _mm_round_ss(mn1, mn2, 0);
-  _mm_round_pd(mn1, 0);
-  _mm_round_sd(mn1, mn2, 0);
+  _mm_round_pd(md1, 0);
+  _mm_round_sd(md1, md2, 0);
 }
 
 // CHECK-LABEL: @test_round
Index: clang/lib/Headers/ppc_wrappers/smmintrin.h
===
--- clang/lib/Headers/ppc_wrappers/smmintrin.h
+++ clang/lib/Headers/ppc_wrappers/smmintrin.h
@@ -305,9 +305,9 @@
 extern __inline __m128i
 __attribute__((__gnu_inline__, __always_inline__, __artificial__))
 _mm_blend_epi16(__m128i __A, __m128i __B, const int __imm8) {
-  __v16qi __charmask = vec_splats((signed char)__imm8);
+  __v16qu __charmask = vec_splats((unsigned char)__imm8);
   __charmask = vec_gb(__charmask);
-  __v8hu __shortmask = (__v8hu)vec_unpackh(__charmask);
+  __v8hu __shortmask = (__v8hu)vec_unpackh((__v16qi)__charmask);
 #ifdef __BIG_ENDIAN__
   __shortmask = vec_reve(__shortmask);
 #endif
Index: clang/lib/Headers/ppc_wrappers/emmintrin.h
===
--- clang/lib/Headers/ppc_wrappers/emmintrin.h
+++ clang/lib/Headers/ppc_wrappers/emmintrin.h
@@ -54,6 +54,7 @@
 typedef __vector unsigned short __v8hu;
 typedef __vector signed char __v16qi;
 typedef __vector unsigned char __v16qu;
+typedef __vector float __v2f;
 
 /* The Intel API is flexible enough that we must allow aliasing with other
vector types, and their scalar components.  */
@@ -951,7 +952,7 @@
 _mm_cvtpi32_pd(__m64 __A) {
   __v4si __temp;
   __v2di __tmp2;
-  __v2df __result;
+  __v2f __result;
 
   __temp = (__v4si)vec_splats(__A);
   __tmp2 = (__v2di)vec_unpackl(__temp);


Index: clang/test/CodeGen/PowerPC/ppc-smmintrin.c
===
--- clang/test/CodeGen/PowerPC/ppc-smmintrin.c
+++ clang/test/CodeGen/PowerPC/ppc-smmintrin.c
@@ -73,7 +73,7 @@
 
 // CHECK-LABEL: define available_externally <2 x i64> @_mm_blend_epi16(<2 x i64> noundef %{{[0-9a-zA-Z_.]+}}, <2 x i64> noundef %{{[0-9a-zA-Z_.]+}}, i32 noundef signext %{{[0-9a-zA-Z_.]+}})
 // CHECK: %[[TRUNC:[0-9a-zA-Z_.]+]] = trunc i32 %{{[0-9a-zA-Z_.]+}} to i8
-// CHECK: call <16 x i8> @vec_splats(signed char)(i8 noundef signext %[[TRUNC]])
+// CHECK: call <16 x i8> @vec_splats(unsigned char)(i8 noundef zeroext %[[TRUNC]])
 // CHECK: call <16 x i8> @llvm.ppc.altivec.vgbbd(<16 x i8> %{{[0-9a-zA-Z_.]+}})
 // CHECK: %[[PACK:[0-9a-zA-Z_.]+]] = call <8 x i16> @vec_unpackh(signed char vector[16])
 // CHECK: store <8 x i16> %[[PACK]], ptr %{{[0-9a-zA-Z_.]+}}, align 16
@@ -232,8 +232,8 @@
 test_round() {
   _mm_round_ps(mn1, 0);
   _mm_round_ss(mn1, mn2, 0);
-  _mm_round_pd(mn1, 0);
-  _mm_round_sd(mn1, mn2, 0);
+  _mm_round_pd(md1, 0);
+  _mm_round_sd(md1, md2, 0);
 }
 
 // CHECK-LABEL: @test_round
Index: clang/lib/Headers/ppc_wrappers/smmintrin.h
===
--- clang/lib/Headers/ppc_wrappers/smmintrin.h
+++ clang/lib/Headers/ppc_wrappers/smmintrin.h
@@ -305,9 +305,9 @@
 extern __inline __m128i
 __attribute__((__gnu_inline__, __always_inline__, __artificial__))
 _mm_blend_epi16(__m128i __A, __m128i __B, const int __imm8) {
-  __v16qi __charmask = vec_splats((signed char)__imm8);
+  __v16qu __charmask = vec_splats((unsigned char)__imm8);
   __charmask = vec_gb(__charmask);
-  __v8hu __shortmask = (__v8hu)vec_unpackh(__charmask);
+  __v8hu __shortmask = (__v8hu)vec_unpackh((__v16qi)__char

[clang] 4eadd19 - [Fuchsia] Enable llvm-driver build

2023-02-17 Thread Alex Brachet via cfe-commits

Author: Alex Brachet
Date: 2023-02-17T21:02:18Z
New Revision: 4eadd19cc423b860f7ce0217000276da769b7809

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

LOG: [Fuchsia] Enable llvm-driver build

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

Added: 


Modified: 
clang/cmake/caches/Fuchsia-stage2.cmake

Removed: 




diff  --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index 5a7cf6cf2c88..3369b42d17bd 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -22,6 +22,7 @@ set(LLVM_ENABLE_ZLIB ON CACHE BOOL "")
 set(LLVM_INCLUDE_DOCS OFF CACHE BOOL "")
 set(LLVM_INCLUDE_EXAMPLES OFF CACHE BOOL "")
 set(LLVM_STATIC_LINK_CXX_STDLIB ON CACHE BOOL "")
+set(LLVM_TOOL_LLVM_DRIVER_BUILD ON CACHE BOOL "")
 set(LLVM_USE_RELATIVE_PATHS_IN_FILES ON CACHE BOOL "")
 
 if(WIN32)
@@ -292,6 +293,7 @@ set(LLVM_TOOLCHAIN_TOOLS
   llvm-cxxfilt
   llvm-debuginfod-find
   llvm-dlltool
+  llvm-driver
   llvm-dwarfdump
   llvm-dwp
   llvm-ifs



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


[PATCH] D144287: [Fuchsia] Enable llvm-driver build

2023-02-17 Thread Alex Brachet 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 rG4eadd19cc423: [Fuchsia] Enable llvm-driver build (authored 
by abrachet).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D144287?vs=498461&id=498486#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144287

Files:
  clang/cmake/caches/Fuchsia-stage2.cmake


Index: clang/cmake/caches/Fuchsia-stage2.cmake
===
--- clang/cmake/caches/Fuchsia-stage2.cmake
+++ clang/cmake/caches/Fuchsia-stage2.cmake
@@ -22,6 +22,7 @@
 set(LLVM_INCLUDE_DOCS OFF CACHE BOOL "")
 set(LLVM_INCLUDE_EXAMPLES OFF CACHE BOOL "")
 set(LLVM_STATIC_LINK_CXX_STDLIB ON CACHE BOOL "")
+set(LLVM_TOOL_LLVM_DRIVER_BUILD ON CACHE BOOL "")
 set(LLVM_USE_RELATIVE_PATHS_IN_FILES ON CACHE BOOL "")
 
 if(WIN32)
@@ -292,6 +293,7 @@
   llvm-cxxfilt
   llvm-debuginfod-find
   llvm-dlltool
+  llvm-driver
   llvm-dwarfdump
   llvm-dwp
   llvm-ifs


Index: clang/cmake/caches/Fuchsia-stage2.cmake
===
--- clang/cmake/caches/Fuchsia-stage2.cmake
+++ clang/cmake/caches/Fuchsia-stage2.cmake
@@ -22,6 +22,7 @@
 set(LLVM_INCLUDE_DOCS OFF CACHE BOOL "")
 set(LLVM_INCLUDE_EXAMPLES OFF CACHE BOOL "")
 set(LLVM_STATIC_LINK_CXX_STDLIB ON CACHE BOOL "")
+set(LLVM_TOOL_LLVM_DRIVER_BUILD ON CACHE BOOL "")
 set(LLVM_USE_RELATIVE_PATHS_IN_FILES ON CACHE BOOL "")
 
 if(WIN32)
@@ -292,6 +293,7 @@
   llvm-cxxfilt
   llvm-debuginfod-find
   llvm-dlltool
+  llvm-driver
   llvm-dwarfdump
   llvm-dwp
   llvm-ifs
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D144287: [Fuchsia] Enable llvm-driver build

2023-02-17 Thread Alex Brachet via Phabricator via cfe-commits
abrachet marked an inline comment as done.
abrachet added inline comments.



Comment at: clang/cmake/caches/Fuchsia-stage2.cmake:26
 set(LLVM_USE_RELATIVE_PATHS_IN_FILES ON CACHE BOOL "")
+set(LLVM_TOOL_LLVM_DRIVER_BUILD ON CACHE BOOL "")
 

phosek wrote:
> Nit: can you move it one line up so it's alphabetically sorted?
Done in commit


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144287

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


[PATCH] D144296: [clang-format] Rewrite how indent is reduced for compacted namespaces

2023-02-17 Thread Emilia Dreamer via Phabricator via cfe-commits
rymiel created this revision.
rymiel added a project: clang-format.
rymiel added reviewers: owenpan, MyDeveloperDay, HazardyKnusperkeks.
Herald added a project: All.
rymiel requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The previous version set the indentation directly using IndentForLevel,
however, this has a few caveats, namely:

- IndentForLevel applies to all scopes of the entire program being

formatted, but this indentation should only be adjusted for scopes of
namespaces.

- The method it used only set the correct indent amount if one wasn't

already set for a given level, meaning it didn't work correctly if
anything with indentation preceded a namespace keyword. This includes
preprocessing directives if using IndentPPDirectives.

This patch instead reduces the Level of all lines within namespaces
which are compacted by CompactNamespaces. This means they will get
correct indentation using the normal process.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144296

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


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -4431,6 +4431,24 @@
"int k; }} // namespace out::mid",
Style));
 
+  verifyFormat("namespace A { namespace B { namespace C {\n"
+   "  int i;\n"
+   "}}} // namespace A::B::C\n"
+   "int main() {\n"
+   "  if (true)\n"
+   "return 0;\n"
+   "}",
+   "namespace A { namespace B {\n"
+   "namespace C {\n"
+   "  int i;\n"
+   "}} // namespace B::C\n"
+   "} // namespace A\n"
+   "int main() {\n"
+   "  if (true)\n"
+   "return 0;\n"
+   "}",
+   Style);
+
   Style.NamespaceIndentation = FormatStyle::NI_Inner;
   EXPECT_EQ("namespace out { namespace in {\n"
 "  int i;\n"
Index: clang/lib/Format/UnwrappedLineFormatter.cpp
===
--- clang/lib/Format/UnwrappedLineFormatter.cpp
+++ clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -366,20 +366,28 @@
 // instead of TheLine->First.
 
 if (Style.CompactNamespaces) {
-  if (auto nsToken = TheLine->First->getNamespaceToken()) {
-int i = 0;
-unsigned closingLine = TheLine->MatchingClosingBlockLineIndex - 1;
-for (; I + 1 + i != E &&
-   nsToken->TokenText == getNamespaceTokenText(I[i + 1]) &&
-   closingLine == I[i + 1]->MatchingClosingBlockLineIndex &&
-   I[i + 1]->Last->TotalLength < Limit;
- i++, --closingLine) {
-  // No extra indent for compacted namespaces.
-  IndentTracker.skipLine(*I[i + 1]);
+  if (auto *nsToken = TheLine->First->getNamespaceToken()) {
+int j = 1;
+unsigned closingLineIndex = TheLine->MatchingClosingBlockLineIndex - 1;
 
-  Limit -= I[i + 1]->Last->TotalLength;
+for (; I + j != E &&
+   nsToken->TokenText == getNamespaceTokenText(I[j]) &&
+   closingLineIndex == I[j]->MatchingClosingBlockLineIndex &&
+   I[j]->Last->TotalLength < Limit;
+ j++, --closingLineIndex) {
+  Limit -= I[j]->Last->TotalLength;
+
+  // Reduce indent level for bodies of namespaces which were compacted,
+  // but only if their content was indented in the first place
+  auto *closingLine = AnnotatedLines.begin() + closingLineIndex + 1;
+  auto dedentBy = I[j]->Level - TheLine->Level;
+  for (auto *compactedLine = I + j; compactedLine <= closingLine;
+   compactedLine++) {
+if (!(*compactedLine)->InPPDirective)
+  (*compactedLine)->Level-= dedentBy;
+  }
 }
-return i;
+return j - 1;
   }
 
   if (auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) {


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -4431,6 +4431,24 @@
"int k; }} // namespace out::mid",
Style));
 
+  verifyFormat("namespace A { namespace B { namespace C {\n"
+   "  int i;\n"
+   "}}} // namespace A::B::C\n"
+   "int main() {\n"
+   "  if (true)\n"
+   "return 0;\n"
+   "}",
+   "namespace A { namespace B {\n"
+   "namespace C {\n"
+   "  int i;\n"
+   "}} // namespace B::C\n"
+   

[PATCH] D144296: [clang-format] Rewrite how indent is reduced for compacted namespaces

2023-02-17 Thread Emilia Dreamer via Phabricator via cfe-commits
rymiel added a comment.

Note: this patch also makes `LevelIndentTracker::skipLine` obsolete. I suppose 
I could clean that up in a following patch


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144296

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


[PATCH] D142569: [OpenMP] Introduce kernel environment

2023-02-17 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 updated this revision to Diff 498492.
tianshilei1992 marked 7 inline comments as done.
tianshilei1992 added a comment.

rebase and fix comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142569

Files:
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
  llvm/lib/Transforms/IPO/OpenMPOpt.cpp
  openmp/libomptarget/DeviceRTL/CMakeLists.txt
  openmp/libomptarget/DeviceRTL/include/Debug.h
  openmp/libomptarget/DeviceRTL/include/Interface.h
  openmp/libomptarget/DeviceRTL/include/State.h
  openmp/libomptarget/DeviceRTL/src/Configuration.cpp
  openmp/libomptarget/DeviceRTL/src/Debug.cpp
  openmp/libomptarget/DeviceRTL/src/Kernel.cpp
  openmp/libomptarget/DeviceRTL/src/State.cpp
  openmp/libomptarget/include/DeviceEnvironment.h
  openmp/libomptarget/include/Environment.h
  openmp/libomptarget/plugins-nextgen/amdgpu/src/rtl.cpp
  openmp/libomptarget/plugins-nextgen/common/PluginInterface/PluginInterface.cpp
  openmp/libomptarget/plugins-nextgen/common/PluginInterface/PluginInterface.h
  openmp/libomptarget/plugins-nextgen/cuda/src/rtl.cpp
  openmp/libomptarget/plugins-nextgen/generic-elf-64bit/src/rtl.cpp
  openmp/libomptarget/plugins/amdgpu/src/rtl.cpp
  openmp/libomptarget/plugins/cuda/src/rtl.cpp

Index: openmp/libomptarget/plugins/cuda/src/rtl.cpp
===
--- openmp/libomptarget/plugins/cuda/src/rtl.cpp
+++ openmp/libomptarget/plugins/cuda/src/rtl.cpp
@@ -23,7 +23,7 @@
 #include 
 
 #include "Debug.h"
-#include "DeviceEnvironment.h"
+#include "Environment.h"
 #include "omptarget.h"
 #include "omptargetplugin.h"
 
Index: openmp/libomptarget/plugins/amdgpu/src/rtl.cpp
===
--- openmp/libomptarget/plugins/amdgpu/src/rtl.cpp
+++ openmp/libomptarget/plugins/amdgpu/src/rtl.cpp
@@ -37,7 +37,7 @@
 #include "internal.h"
 #include "rt.h"
 
-#include "DeviceEnvironment.h"
+#include "Environment.h"
 #include "get_elf_mach_gfx_name.h"
 #include "omptargetplugin.h"
 #include "print_tracing.h"
Index: openmp/libomptarget/plugins-nextgen/generic-elf-64bit/src/rtl.cpp
===
--- openmp/libomptarget/plugins-nextgen/generic-elf-64bit/src/rtl.cpp
+++ openmp/libomptarget/plugins-nextgen/generic-elf-64bit/src/rtl.cpp
@@ -17,7 +17,7 @@
 #include 
 
 #include "Debug.h"
-#include "DeviceEnvironment.h"
+#include "Environment.h"
 #include "GlobalHandler.h"
 #include "PluginInterface.h"
 #include "omptarget.h"
Index: openmp/libomptarget/plugins-nextgen/cuda/src/rtl.cpp
===
--- openmp/libomptarget/plugins-nextgen/cuda/src/rtl.cpp
+++ openmp/libomptarget/plugins-nextgen/cuda/src/rtl.cpp
@@ -17,7 +17,7 @@
 #include 
 
 #include "Debug.h"
-#include "DeviceEnvironment.h"
+#include "Environment.h"
 #include "GlobalHandler.h"
 #include "PluginInterface.h"
 
Index: openmp/libomptarget/plugins-nextgen/common/PluginInterface/PluginInterface.h
===
--- openmp/libomptarget/plugins-nextgen/common/PluginInterface/PluginInterface.h
+++ openmp/libomptarget/plugins-nextgen/common/PluginInterface/PluginInterface.h
@@ -19,7 +19,7 @@
 #include 
 
 #include "Debug.h"
-#include "DeviceEnvironment.h"
+#include "Environment.h"
 #include "GlobalHandler.h"
 #include "JIT.h"
 #include "MemoryManager.h"
@@ -732,6 +732,11 @@
 
   /// Map of host pinned allocations used for optimize device transfers.
   PinnedAllocationMapTy PinnedAllocs;
+
+private:
+  /// Return the kernel environment object for kernel \p Name.
+  Expected
+  getKernelEnvironmentForKernel(StringRef Name, DeviceImageTy &Image);
 };
 
 /// Class implementing common functionalities of offload plugins. Each plugin
Index: openmp/libomptarget/plugins-nextgen/common/PluginInterface/PluginInterface.cpp
===
--- openmp/libomptarget/plugins-nextgen/common/PluginInterface/PluginInterface.cpp
+++ openmp/libomptarget/plugins-nextgen/common/PluginInterface/PluginInterface.cpp
@@ -554,32 +554,43 @@
   return Plugin::success();
 }
 
-Expected
-GenericDeviceTy::getExecutionModeForKernel(StringRef Name,
-   DeviceImageTy &Image) {
-  // Create a metadata object for the exec mode global (auto-generated).
-  StaticGlobalTy ExecModeGlobal(Name.data(),
-"_exec_mode");
+Expected
+GenericDeviceTy::getKernelEnvironmentForKernel(StringRef Name,
+   DeviceImageTy &Image) {
+  // Create a metadata object for the kernel environment object.
+  StaticGlobalTy KernelEnv(Name.data()

[PATCH] D142569: [OpenMP] Introduce kernel environment

2023-02-17 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 added inline comments.



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:3910
+  // proper method.
+  if (Kernel->hasLocalLinkage()) {
+assert(Kernel->hasOneUse() && "Unexpected use of debug kernel wrapper.");

This doesn't work as expected. Need to figure it out.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142569

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


[PATCH] D143680: [WIP][-Wunsafe-buffer-usage] Improve fix-its for local variable declarations with null pointer initializers

2023-02-17 Thread Ziqing Luo via Phabricator via cfe-commits
ziqingluo-90 updated this revision to Diff 498493.
ziqingluo-90 marked 3 inline comments as done.

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

https://reviews.llvm.org/D143680

Files:
  clang/lib/Analysis/UnsafeBufferUsage.cpp
  clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-local-var-span.cpp

Index: clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-local-var-span.cpp
===
--- clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-local-var-span.cpp
+++ clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-local-var-span.cpp
@@ -131,6 +131,38 @@
   tmp = (int) s[5];
 }
 
+void null_init() {
+#define NULL 0
+  int tmp;
+  int * my_null = 0;
+  int * p = 0;
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:12}:"std::span p"
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-2]]:{{^3}}
+  int * g = NULL; // cannot handle fix-its involving macros for now
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:
+  int * f = nullptr;
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:12}:"std::span f"
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-2]]:{{^3}}
+
+  // In case of value dependencies, we give up
+  int * q = my_null;
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:12}:"std::span q"
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-2]]:13-[[@LINE-2]]:13}:"{"
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-3]]:20-[[@LINE-3]]:20}:", <# placeholder #>}"
+  int * r = my_null + 0;
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:12}:"std::span r"
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-2]]:13-[[@LINE-2]]:13}:"{"
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-3]]:24-[[@LINE-3]]:24}:", <# placeholder #>}"
+
+  tmp = p[5]; // `p[5]` will cause crash after `p` being transformed to be a `std::span`
+  tmp = q[5]; // Similar for the rests.
+  tmp = r[5];
+  tmp = g[5];
+  tmp = f[5];
+#undef NULL
+}
+
+
 void unsupported_multi_decl(int * x) {
   int * p = x, * q = new int[10];
   // CHECK-NOT: fix-it:"{{.*}}":[[@LINE-1]]
Index: clang/lib/Analysis/UnsafeBufferUsage.cpp
===
--- clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -1068,14 +1068,30 @@
 template 
 static SourceLocation getEndCharLoc(const NodeTy *Node, const SourceManager &SM,
 const LangOptions &LangOpts) {
-  return Lexer::getLocForEndOfToken(Node->getEndLoc(), 1, SM, LangOpts);
+  unsigned TkLen = Lexer::MeasureTokenLength(Node->getEndLoc(), SM, LangOpts);
+  SourceLocation Loc = Node->getEndLoc().getLocWithOffset(TkLen - 1);
+
+  // We expect `Loc` to be valid. The location is obtained by moving forward
+  // from the beginning of the token 'len(token)-1' characters. The file ID of
+  // the locations within a token must be consistent.
+  assert(Loc.isValid() && "Expected the source location of the last"
+  "character of an AST Node to be always valid");
+  return Loc;
 }
 
 // Return the source location just past the last character of the AST `Node`.
 template 
 static SourceLocation getPastLoc(const NodeTy *Node, const SourceManager &SM,
  const LangOptions &LangOpts) {
-  return Lexer::getLocForEndOfToken(Node->getEndLoc(), 0, SM, LangOpts);
+  SourceLocation Loc =
+  Lexer::getLocForEndOfToken(Node->getEndLoc(), 0, SM, LangOpts);
+
+  // We expect `Loc` to be valid as it is either associated to a file ID or
+  //   it must be the end of a macro expansion. (see
+  //   `Lexer::getLocForEndOfToken`)
+  assert(Loc.isValid() && "Expected the source location just past the last "
+  "character of an AST Node to be always valid");
+  return Loc;
 }
 
 // Return text representation of an `Expr`.
@@ -1180,9 +1196,25 @@
 static FixItList
 populateInitializerFixItWithSpan(const Expr *Init, const ASTContext &Ctx,
  const StringRef UserFillPlaceHolder) {
-  FixItList FixIts{};
   const SourceManager &SM = Ctx.getSourceManager();
   const LangOptions &LangOpts = Ctx.getLangOpts();
+
+  // If `Init` has a constant value that is (or equivalent to) a
+  // NULL pointer, we use the default constructor to initialize the span
+  // object, i.e., a `std:span` variable declaration with no initializer.
+  // So the fix-it is just to remove the initializer.
+  if (Init->isNullPointerConstant(
+  std::remove_const_t(Ctx),
+  // FIXME: Why does this function not ask for `const ASTContext
+  // &`? It should. Maybe worth an NFC patch later.
+  Expr::NullPointerConstantValueDependence::
+  NPC_ValueDependentIsNotNull)) {
+SourceRange SR(Init->getBeginLoc(), getEndCharLoc(Init, SM, LangOpts));
+
+return {FixItHint::CreateRemoval(SR)};
+  }
+
+  FixItList FixIts{};
   std::string ExtentText = UserFillPlaceHolder.data();
   StringRef One = "1";
 
@@ -1255,8 +1287,8 @@
 FixItList InitFixIts =
 

[PATCH] D143680: [WIP][-Wunsafe-buffer-usage] Improve fix-its for local variable declarations with null pointer initializers

2023-02-17 Thread Ziqing Luo via Phabricator via cfe-commits
ziqingluo-90 updated this revision to Diff 498494.

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

https://reviews.llvm.org/D143680

Files:
  clang/lib/Analysis/UnsafeBufferUsage.cpp
  clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-local-var-span.cpp

Index: clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-local-var-span.cpp
===
--- clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-local-var-span.cpp
+++ clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-local-var-span.cpp
@@ -131,6 +131,38 @@
   tmp = (int) s[5];
 }
 
+void null_init() {
+#define NULL 0
+  int tmp;
+  int * my_null = 0;
+  int * p = 0;
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:12}:"std::span p"
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-2]]:{{^3}}
+  int * g = NULL; // cannot handle fix-its involving macros for now
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:
+  int * f = nullptr;
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:12}:"std::span f"
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-2]]:{{^3}}
+
+  // In case of value dependencies, we give up
+  int * q = my_null;
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:12}:"std::span q"
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-2]]:13-[[@LINE-2]]:13}:"{"
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-3]]:20-[[@LINE-3]]:20}:", <# placeholder #>}"
+  int * r = my_null + 0;
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:12}:"std::span r"
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-2]]:13-[[@LINE-2]]:13}:"{"
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-3]]:24-[[@LINE-3]]:24}:", <# placeholder #>}"
+
+  tmp = p[5]; // `p[5]` will cause crash after `p` being transformed to be a `std::span`
+  tmp = q[5]; // Similar for the rests.
+  tmp = r[5];
+  tmp = g[5];
+  tmp = f[5];
+#undef NULL
+}
+
+
 void unsupported_multi_decl(int * x) {
   int * p = x, * q = new int[10];
   // CHECK-NOT: fix-it:"{{.*}}":[[@LINE-1]]
Index: clang/lib/Analysis/UnsafeBufferUsage.cpp
===
--- clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -1068,14 +1068,30 @@
 template 
 static SourceLocation getEndCharLoc(const NodeTy *Node, const SourceManager &SM,
 const LangOptions &LangOpts) {
-  return Lexer::getLocForEndOfToken(Node->getEndLoc(), 1, SM, LangOpts);
+  unsigned TkLen = Lexer::MeasureTokenLength(Node->getEndLoc(), SM, LangOpts);
+  SourceLocation Loc = Node->getEndLoc().getLocWithOffset(TkLen - 1);
+
+  // We expect `Loc` to be valid. The location is obtained by moving forward
+  // from the beginning of the token 'len(token)-1' characters. The file ID of
+  // the locations within a token must be consistent.
+  assert(Loc.isValid() && "Expected the source location of the last"
+  "character of an AST Node to be always valid");
+  return Loc;
 }
 
 // Return the source location just past the last character of the AST `Node`.
 template 
 static SourceLocation getPastLoc(const NodeTy *Node, const SourceManager &SM,
  const LangOptions &LangOpts) {
-  return Lexer::getLocForEndOfToken(Node->getEndLoc(), 0, SM, LangOpts);
+  SourceLocation Loc =
+  Lexer::getLocForEndOfToken(Node->getEndLoc(), 0, SM, LangOpts);
+
+  // We expect `Loc` to be valid as it is either associated to a file ID or
+  //   it must be the end of a macro expansion. (see
+  //   `Lexer::getLocForEndOfToken`)
+  assert(Loc.isValid() && "Expected the source location just past the last "
+  "character of an AST Node to be always valid");
+  return Loc;
 }
 
 // Return text representation of an `Expr`.
@@ -1180,9 +1196,25 @@
 static FixItList
 populateInitializerFixItWithSpan(const Expr *Init, const ASTContext &Ctx,
  const StringRef UserFillPlaceHolder) {
-  FixItList FixIts{};
   const SourceManager &SM = Ctx.getSourceManager();
   const LangOptions &LangOpts = Ctx.getLangOpts();
+
+  // If `Init` has a constant value that is (or equivalent to) a
+  // NULL pointer, we use the default constructor to initialize the span
+  // object, i.e., a `std:span` variable declaration with no initializer.
+  // So the fix-it is just to remove the initializer.
+  if (Init->isNullPointerConstant(
+  std::remove_const_t(Ctx),
+  // FIXME: Why does this function not ask for `const ASTContext
+  // &`? It should. Maybe worth an NFC patch later.
+  Expr::NullPointerConstantValueDependence::
+  NPC_ValueDependentIsNotNull)) {
+SourceRange SR(Init->getBeginLoc(), getEndCharLoc(Init, SM, LangOpts));
+
+return {FixItHint::CreateRemoval(SR)};
+  }
+
+  FixItList FixIts{};
   std::string ExtentText = UserFillPlaceHolder.data();
   StringRef One = "1";
 
@@ -1255,8 +1287,8 @@
 FixItList InitFixIts =
 populateInitializerFixItWithSpan(Init, 

[clang] c0f3ac1 - Revert "[Fuchsia] Enable llvm-driver build"

2023-02-17 Thread Alex Brachet via cfe-commits

Author: Alex Brachet
Date: 2023-02-17T21:29:14Z
New Revision: c0f3ac1d0015fd051144a987ff500b888a32be86

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

LOG: Revert "[Fuchsia] Enable llvm-driver build"

This reverts commit 4eadd19cc423b860f7ce0217000276da769b7809.

Doesn't work on macos. I'll investigate more

Added: 


Modified: 
clang/cmake/caches/Fuchsia-stage2.cmake

Removed: 




diff  --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index 3369b42d17bd7..5a7cf6cf2c887 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -22,7 +22,6 @@ set(LLVM_ENABLE_ZLIB ON CACHE BOOL "")
 set(LLVM_INCLUDE_DOCS OFF CACHE BOOL "")
 set(LLVM_INCLUDE_EXAMPLES OFF CACHE BOOL "")
 set(LLVM_STATIC_LINK_CXX_STDLIB ON CACHE BOOL "")
-set(LLVM_TOOL_LLVM_DRIVER_BUILD ON CACHE BOOL "")
 set(LLVM_USE_RELATIVE_PATHS_IN_FILES ON CACHE BOOL "")
 
 if(WIN32)
@@ -293,7 +292,6 @@ set(LLVM_TOOLCHAIN_TOOLS
   llvm-cxxfilt
   llvm-debuginfod-find
   llvm-dlltool
-  llvm-driver
   llvm-dwarfdump
   llvm-dwp
   llvm-ifs



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


[PATCH] D143128: [-Wunsafe-buffer-usage] Fix-Its transforming `&DRE[any]` to `(DRE.data() + any)`

2023-02-17 Thread Ziqing Luo via Phabricator via cfe-commits
ziqingluo-90 updated this revision to Diff 498498.
ziqingluo-90 added a comment.

Now we have different `FixableGadget`s that may match the same `Stmt` 
(representing a context).  
So in order to discover all "Fixable"s, we can no longer match `anyOf` 
`FixableGadget`s' matchers.  Instead, we match `eachOf` them.


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

https://reviews.llvm.org/D143128

Files:
  clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h
  clang/include/clang/Analysis/Analyses/UnsafeBufferUsageGadgets.def
  clang/lib/Analysis/UnsafeBufferUsage.cpp
  
clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-addressof-arraysubscript.cpp

Index: clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-addressof-arraysubscript.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-addressof-arraysubscript.cpp
@@ -0,0 +1,74 @@
+// RUN: %clang_cc1 -std=c++20 -Wunsafe-buffer-usage -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s
+
+int f(unsigned long, void *);
+
+[[clang::unsafe_buffer_usage]]
+int unsafe_f(unsigned long, void *);
+
+void address_to_integer(int x) {
+  int * p = new int[10];
+  unsigned long n = (unsigned long) &p[5];
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:37-[[@LINE-1]]:42}:"(p.data() + 5)"
+  unsigned long m = (unsigned long) &p[x];
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:37-[[@LINE-1]]:42}:"(p.data() + x)"
+}
+
+void call_argument(int x) {
+  int * p = new int[10];
+
+  f((unsigned long) &p[5], &p[x]);
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:21-[[@LINE-1]]:26}:"(p.data() + 5)"
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-2]]:28-[[@LINE-2]]:33}:"(p.data() + x)"
+}
+
+void ignore_unsafe_calls(int x) {
+  // Cannot fix `&p[x]` for now as it is an argument of an unsafe
+  // call. So no fix for variable `p`.
+  int * p = new int[10];
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]
+  unsafe_f((unsigned long) &p[5],
+	   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]
+	   &p[x]);
+
+  int * q = new int[10];
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:12}:"std::span q"
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:13-[[@LINE-2]]:13}:"{"
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:24-[[@LINE-3]]:24}:", 10}"
+  unsafe_f((unsigned long) &q[5],
+	   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:28-[[@LINE-1]]:33}:"(q.data() + 5)"
+	   (void*)0);
+}
+
+void odd_subscript_form() {
+  int * p = new int[10];
+  unsigned long n = (unsigned long) &5[p];
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:37-[[@LINE-1]]:42}:"(p.data() + 5)"
+}
+
+// To test multiple function declarations, each of which carries
+// different incomplete informations:
+[[clang::unsafe_buffer_usage]]
+void unsafe_g(void*);
+
+void unsafe_g(void*);
+
+void multiple_unsafe_fundecls() {
+  int * p = new int[10];
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]
+  unsafe_g(&p[5]);
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]
+}
+
+void unsafe_h(void*);
+
+[[clang::unsafe_buffer_usage]]
+void unsafe_h(void*);
+
+void unsafe_h(void* p) { ((char*)p)[10]; }
+
+void multiple_unsafe_fundecls2() {
+  int * p = new int[10];
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]
+  unsafe_h(&p[5]);
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]
+}
Index: clang/lib/Analysis/UnsafeBufferUsage.cpp
===
--- clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -117,6 +117,15 @@
   bool Matches;
 };
 
+// Because we're dealing with raw pointers, let's define what we mean by that.
+static auto hasPointerType() {
+return hasType(hasCanonicalType(pointerType()));
+}
+
+static auto hasArrayType() {
+return hasType(hasCanonicalType(arrayType()));
+}
+
 AST_MATCHER_P(Stmt, forEveryDescendant, internal::Matcher, innerMatcher) {
   const DynTypedMatcher &DTM = static_cast(innerMatcher);
   
@@ -149,6 +158,29 @@
 ));
 // clang-format off
 }
+
+// Returns a matcher that matches any expression `e` such that `InnerMatcher`
+// matches `e` and `e` is in an Unspecified Pointer Context (UPC).
+static internal::Matcher
+isInUnspecifiedPointerContext(internal::Matcher InnerMatcher) {
+  // A UPC can be
+  // 1. an argument of a function call (except the callee has [[unsafe_...]]
+  // attribute), or
+  // 2. the operand of a cast operation; or
+  // ...
+  auto CallArgMatcher =
+  callExpr(hasAnyArgument(allOf(
+   hasPointerType() /* array also decays to pointer type*/,
+   InnerMatcher)),
+   unless(callee(functionDecl(hasAttr(attr::UnsafeBufferUsage);
+  auto CastOperandMatcher =
+  explicitCastExpr(hasCastKind(CastKind::CK_PointerToIntegral),
+   castSubExpr(allOf(hasPointerType(), InnerMatcher)));
+
+ return stmt(anyOf(CallArgMatcher, CastOperandMatcher));
+  // FIXME: any more cases? (UPC excludes the RHS of an assignment.  For now we
+  // don't have to check that.)
+}
 } // 

[PATCH] D143128: [-Wunsafe-buffer-usage] Fix-Its transforming `&DRE[any]` to `(DRE.data() + any)`

2023-02-17 Thread Ziqing Luo via Phabricator via cfe-commits
ziqingluo-90 added inline comments.



Comment at: clang/lib/Analysis/UnsafeBufferUsage.cpp:849
   // in one `anyOf` group (for better performance via short-circuiting).
-  stmt(anyOf(
+  stmt(eachOf(
 #define FIXABLE_GADGET(x)  
\

Change from `anyOf` to `eachOf`


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

https://reviews.llvm.org/D143128

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


[PATCH] D144285: [Clang] Implement CWG2518 - static_assert(false)

2023-02-17 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:62
   directly rather than instantiating the definition from the standard library.
+- Implemented `CWG2518 `_ which allows 
``static_assert(false)``
+  not to be ill-formed when its condition is evaluated in a non-instantiated 
templates.

I am assuming this will be updated eventually but that version is not the final 
one and the one that was approved can be found from: 
https://github.com/cplusplus/papers/issues/1251

and it here: https://cplusplus.github.io/CWG/issues/2518.html

I think a better wording would be `would not be ill-formed when evaluated in 
the context of a template definition`



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:16806
+bool InTemplateDefinition =
+getLangOpts().CPlusPlus && CurContext->isDependentContext();
+

erichkeane wrote:
> cor3ntin wrote:
> > erichkeane wrote:
> > > CplusPlus check is now not really beneficial?  I'm not sure how much it 
> > > matters now though that these are both just bit-loads.
> > isDependentContext still does a bunch of work, recursively. I think we 
> > should keep it!
> Ah, Oh! You're right!  It is the Expr class where this is free/just checking 
> a bit.  Disregard.
So `isDependentContext()` strictly means we are in a definition context? I 
think it makes sense after reading the implementation but not obvious at first. 
Maybe that would to document someplace?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144285

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


  1   2   >