[PATCH] D140086: [analyzer][solver] Improve reasoning for not equal to operator

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

About spellings. In the summary you used 'lesser', I think as a synonym for 
'smaller' or something like that. Anyway, not important.
Great stuff.




Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1642
+if (LHS.isUnsigned() != RHS.isUnsigned()) {
+  auto SignedHS = LHS.isUnsigned() ? RHS : LHS;
+

Interesting. I like it. I'd however recommend to move this and the other 
variable to the beginning of this guarded block. That way it would be easier to 
see that the guard condition relates to this ternary condition.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1642
+if (LHS.isUnsigned() ^ RHS.isUnsigned()) {
+  if (LHS.isUnsigned() && (LHS.getBitWidth() >= RHS.getBitWidth())) {
+

manas wrote:
> steakhal wrote:
> > Why do we need this additional condition?
> > If I remove these, I get no test failures, which suggests to me that we 
> > have some undertested code paths here.
> > Why do we need this additional condition?
> 
> Bitwidth was important because we should ideally cast smaller bitwidth type 
> to bigger bitwidth type.
> 
> Consider if we have `LHS(u8), RHS(i32)`, then without checking for bitwidth, 
> we would be casting RHS's maxValue to LHS's type, which will result in lose 
> of information and will not serve our purpose.
> 
> 
If you think we need that bitwidth check, why did you remove it?
I'd like to see test cases demonstrating what we are talking about and see if 
we want that behavior or not.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140086

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


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

2022-12-17 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 483802.
tbaeder marked 2 inline comments as done.

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

https://reviews.llvm.org/D134859

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

Index: clang/test/SemaCXX/rounding-math.cpp
===
--- clang/test/SemaCXX/rounding-math.cpp
+++ clang/test/SemaCXX/rounding-math.cpp
@@ -1,5 +1,6 @@
 // RUN: %clang_cc1 -triple x86_64-linux -verify=norounding -Wno-unknown-pragmas %s
 // RUN: %clang_cc1 -triple x86_64-linux -verify=rounding %s -frounding-math -Wno-unknown-pragmas
+// RUN: %clang_cc1 -triple x86_64-linux -verify=rounding %s -frounding-math -fexperimental-new-constant-interpreter -Wno-unknown-pragmas
 // rounding-no-diagnostics
 
 #define fold(x) (__builtin_constant_p(x) ? (x) : (x))
Index: clang/test/AST/Interp/floats.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/floats.cpp
@@ -0,0 +1,56 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify %s
+// RUN: %clang_cc1 -verify=ref %s
+
+constexpr int i = 2;
+constexpr float f = 1.0f;
+static_assert(f == 1.0f, "");
+
+constexpr float f2 = 1u * f;
+static_assert(f2 == 1.0f, "");
+
+constexpr float f3 = 1.5;
+constexpr int i3 = f3;
+static_assert(i3 == 1);
+
+constexpr bool b3 = f3;
+static_assert(b3);
+
+
+static_assert(1.0f + 3u == 4, "");
+static_assert(4.0f / 1.0f == 4, "");
+static_assert(10.0f * false == 0, "");
+
+constexpr float floats[] = {1.0f, 2.0f, 3.0f, 4.0f};
+
+constexpr float m = 5.0f / 0.0f; // ref-error {{must be initialized by a constant expression}} \
+ // ref-note {{division by zero}} \
+ // expected-error {{must be initialized by a constant expression}} \
+ // expected-note {{division by zero}}
+
+static_assert(~2.0f == 3, ""); // ref-error {{invalid argument type 'float' to unary expression}} \
+   // expected-error {{invalid argument type 'float' to unary expression}}
+
+/// Initialized by a double.
+constexpr float df = 0.0;
+/// The other way around.
+constexpr double fd = 0.0f;
+
+static_assert(0.0f == -0.0f, "");
+
+const int k = 3 * (1.0f / 3.0f);
+static_assert(k == 1, "");
+
+constexpr bool b = 1.0;
+static_assert(b, "");
+
+constexpr double db = true;
+static_assert(db == 1.0, "");
+
+constexpr float fa[] = {1.0f, 2.0, 1, false};
+constexpr float da[] = {1.0f, 2.0, 1, false};
+
+constexpr float fm = __FLT_MAX__;
+constexpr int someInt = fm; // ref-error {{must be initialized by a constant expression}} \
+// ref-note {{is outside the range of representable values}} \
+// expected-error {{must be initialized by a constant expression}} \
+// expected-note {{is outside the range of representable values}}
Index: clang/test/AST/Interp/const-fpfeatures.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/const-fpfeatures.cpp
@@ -0,0 +1,74 @@
+// RUN: %clang_cc1 -S -emit-llvm -triple i386-linux -std=c++2a -Wno-unknown-pragmas %s -o - | FileCheck %s
+// RUN: %clang_cc1 -S -emit-llvm -triple i386-linux -fexperimental-new-constant-interpreter -std=c++2a -Wno-unknown-pragmas %s -o - | FileCheck %s
+
+
+#pragma STDC FENV_ROUND FE_UPWARD
+
+float F1u = 1.0F + 0x0.02p0F;
+float F2u = 1.0F + 0x0.01p0F;
+float F3u = 0x1.01p0;
+// CHECK: @F1u = {{.*}} float 0x3FF02000
+// CHECK: @F2u = {{.*}} float 0x3FF02000
+// CHECK: @F3u = {{.*}} float 0x3FF02000
+
+float FI1u = 0xU;
+// CHECK: @FI1u = {{.*}} float 0x41F0
+
+#pragma STDC FENV_ROUND FE_DOWNWARD
+
+float F1d = 1.0F + 0x0.02p0F;
+float F2d = 1.0F + 0x0.01p0F;
+float F3d = 0x1.01p0;
+
+// CHECK: @F1d = {{.*}} float 0x3FF02000
+// CHECK: @F2d = {{.*}} float 1.00e+00
+// CHECK: @F3d = {{.*}} float 1.00e+00
+
+
+float FI1d = 0xU;
+// CHECK: @FI1d = {{.*}} float 0x41EFE000
+
+// nextUp(1.F) == 0x1.02p0F
+
+constexpr float add_round_down(float x, float y) {
+  #pragma STDC FENV_ROUND FE_DOWNWARD
+  float res = x;
+  res = res + y;
+  return res;
+}
+
+constexpr float add_round_up(float x, float y) {
+  

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

2022-12-17 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder marked 5 inline comments as done.
tbaeder added inline comments.



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:607
+if (*LT == PT_Float) {
+  if (!this->emitAddf(getRoundingMode(E), E))
+return false;

sepavloff wrote:
> As discussed previously, compound assign operator cannot be implemented with 
> the same function as corresponding binary operator in general case.
I left this in so at least one of the test cases in `const-fpfeatures.cpp` 
would work. But it seems like using `res = res + y` instead works as well and 
breaks if the `#pragma` before is commented-out, so I can use that instead.



Comment at: clang/lib/AST/Interp/Interp.h:1243
+// T's bit width.
+if (!T::canRepresent(Result)) {
+  const Expr *E = S.Current->getExpr(OpPC);

sepavloff wrote:
> sepavloff wrote:
> > `Integral::canRepresent` is suitable only for integral-to-intergal 
> > conversions. With loss of precision the floating-point numbers can 
> > represent wider range of integers.
> I was wrong, this is float-to-integer conversion. Would it be easier to 
> detect overflow (as well as other cases, like NaN) by checking that 
> `Status==opInvalidOp && F.isFinite()`? 
That seems to work, yes. I switched to that and added an overflow test case 
to`floats.cpp`.


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

https://reviews.llvm.org/D134859

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


[PATCH] D137343: [clang] add -Wvla-stack-allocation

2022-12-17 Thread Tao Liang via Phabricator via cfe-commits
Origami404 added a subscriber: mizvekov.
Origami404 added a comment.

Hello, I am back now and will be available anytime next week, so if anyone has 
any idea on this topic, please at me!

I haven't found a way that "feels right" to achieve consensus yet. But I do 
have something to share currently.

---

For the semantics of the warning flag, I agree with @uecker that 
`-Wvla-portability` should be changed to `-Wc++-compat`. In my reading of C2x 
standard, using VM type is acceptable and the only reason we need to issue a 
warning is that the C++ standard doesn't allow non-constant array length at 
all. But I have no opinion on the semantics of `-Wvla` and `-Wvla-stack-alloc`.

And should `-Wvla-stack-alloc` fires on static VLAs? (like 
`clang/test/drs/dr3xx.c:164`)

---

For implement details, I add a diag at ``, which will be called after a 
variable declaration. Here we can get the full type of the variable to tell 
whether the variable has a VLA type or just a VM type.

In the GitHub issue 
, 
@mizvekov said:

> A general check about any VLA usage at all should probably happen early when 
> we finished parsing and are building VariableArray types, probably in 
> `Sema::BuildArrayType`.
>
> Otherwise sprinkling around checks for VM types seems messy, so I don't think 
> considering VM for this problem is an efficient approach.

But AFAIK, a VLA type cannot be told just at `Sema::BuildArrayType` level 
because the constructing VLA type may just be a part of another VM type but not 
a VLA type for a VLA. At `Sema::BuildArrayType`, we seem only can detect VM 
type instead of VLA type.

---

In Ballman's summary, the `-Wvla-stack-alloc` should suppress the 
`-Wvla-portability`:

> -Wvla-portability warns on any use of a VM type, except if 
> -Wvla-stack-allocation is also enabled it won't warn on the use of VLA that 
> involves a stack allocation

I failed to achieve the "except" here because, in the current implementation, 
VM type-related warnings are checked directly at `Sema::BuildArrayType`, by 
`checkArraySize` which used `Sema::VerifyIntegerConstantExpression`. But the 
`Sema::VerifyIntegerConstantExpression` requires at least one diag at each 
non-ICE occurrence. I haven't found a way to avoid the diag yet.

---

By the way, I seem to find a bug in the current implementation of VM type 
warning. For VLA at sizeof context, the warning will be issued twice. Github 
issue here . It cause the 
test `clang/test/Sema/warn-vla.c:48` giving two warnings.

---

The reason why I set both `-Wvla-stack-alloc` and `-Wvla-portability` to 
`DefaultIgnore` is that:

- if both of them are not `DefaultIgnore`, 200 tests will fail
- if only `-Wvla-stack-alloc` is not `DefaultIgnore`, 169 tests will fail
- if both of them are `DefaultIgnore`, only 4 tests will fail

Most of the failed tests seem cannot be avoided because they just use VLAs. If 
`DefaultIgnore` is strongly unrecommended, I can go through all the tests and 
add an expected warning diag for them. It's a bit time-consuming, but I am free 
all day now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137343

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


[PATCH] D137343: [clang] add -Wvla-stack-allocation

2022-12-17 Thread Tao Liang via Phabricator via cfe-commits
Origami404 updated this revision to Diff 483796.
Origami404 added a comment.

[clang] add -Wvla-stack-allocation and divide different VLA warning

New behaviors:

-Wvla-stack-allocation

  warns on use of a VLA that involves a stack allocation

-Wvla-portability

  warns on any use of a VM type, even if -Wvla-stack-allocation is
  given.

-Wvla

  groups together -Wvla-stack-allocation and -Wvla-portability

Fixes: https://github.com/llvm/llvm-project/issues/57098
Link: https://reviews.llvm.org/D132952

Co-authored-by: YingChi Long 

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


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137343

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/C/drs/dr3xx.c
  clang/test/Sema/cast.c
  clang/test/Sema/warn-vla.c
  clang/test/SemaCXX/warn-vla.cpp

Index: clang/test/SemaCXX/warn-vla.cpp
===
--- clang/test/SemaCXX/warn-vla.cpp
+++ clang/test/SemaCXX/warn-vla.cpp
@@ -1,7 +1,10 @@
 // RUN: %clang_cc1 -fsyntax-only -verify -Wvla %s
 
 void test1(int n) { // expected-note {{here}}
-  int v[n]; // expected-warning {{variable length array}} expected-note {{parameter 'n'}}
+  int v[n]; /* expected-warning {{variable length array}} 
+   expected-note {{parameter 'n'}}
+   expected-warning {{variable length array that may require stack allocation used}}
+*/
 }
 
 void test2(int n, int v[n]) { // expected-warning {{variable length array}} expected-note {{parameter 'n'}} expected-note {{here}}
@@ -11,7 +14,10 @@
 
 template
 void test4(int n) { // expected-note {{here}}
-  int v[n]; // expected-warning {{variable length array}} expected-note {{parameter 'n'}}
+  int v[n]; /* expected-warning {{variable length array}} 
+   expected-note {{parameter 'n'}}
+   expected-warning {{variable length array that may require stack allocation used}}
+*/
 }
 
 template
Index: clang/test/Sema/warn-vla.c
===
--- clang/test/Sema/warn-vla.c
+++ clang/test/Sema/warn-vla.c
@@ -1,12 +1,59 @@
-// RUN: %clang_cc1 -std=c99 -fsyntax-only -verify -Wvla %s
-// RUN: %clang_cc1 -std=c89 -fsyntax-only -verify -Wvla %s
+// RUN: %clang_cc1 -std=c89 -fsyntax-only -verify=expected,c89 -Wvla %s
+// RUN: %clang_cc1 -std=c99 -fsyntax-only -verify=expected,c99 -Wvla %s
+// RUN: %clang_cc1 -std=c99 -fsyntax-only -verify=expected,only-stack-allocation -Wvla-stack-alloc -Wno-vla-portability %s
 
 void test1(int n) {
-  int v[n]; // expected-warning {{variable length array}}
+  int v[n]; /* 
+c89-warning {{variable length arrays are a C99 feature}}
+c89-warning {{variable length array that may require stack allocation used}}
+c99-warning {{variable length array used}}
+c99-warning {{variable length array that may require stack allocation used}}
+only-stack-allocation-warning {{variable length array that may require stack allocation used}}
+  */
 }
 
-void test2(int n, int v[n]) { // expected-warning {{variable length array}}
+void test2(int n, int v[n]) { /* 
+  c89-warning {{variable length arrays are a C99 feature}}
+  c99-warning {{variable length array used}}
+*/
 }
 
-void test3(int n, int v[n]); // expected-warning {{variable length array}}
+void test3(int n, int v[n]); /* 
+  c89-warning {{variable length arrays are a C99 feature}}
+  c99-warning {{variable length array used}}
+*/
 
+int test4_num;
+typedef int Test4[test4_num]; /* 
+  c89-warning {{variable length arrays are a C99 feature}} 
+  c99-warning {{variable length array used}}
+  expected-error {{variable length array declaration not allowed at file scope}}
+*/
+
+void func() {
+  typedef int test5[test4_num]; /* 
+c89-warning {{variable length arrays are a C99 feature}} 
+c99-warning {{variable length array used}} 
+  */
+
+  int test6[test4_num]; /*  
+c89-warning {{variable length arrays are a C99 feature}}
+c89-warning {{variable length array that may require stack allocation used}}
+c99-warning {{variable length array used}}
+c99-warning {{variable length array that may require stack allocation used}}
+only-stack-allocation-warning {{variable length array that may require stack allocation used}}
+  */
+
+  // FIXME: warn twice
+  (void)sizeof(int[test4_num]); /* 
+c89-warning {{variable length arrays are a C99 feature}}
+c89-warning {{variable length arrays are a C99 feature}}
+c99-warning {{variable length array used}}
+c99-warning {{variable length array used}}
+  */
+
+  int (*test7)[test4_num]; /*
+c89-warning {{variable length arrays are a C99 feature}}
+c99-warning {{variable length array used}}
+  */
+}
Index: 

[PATCH] D140267: [clang-format] Allow line break between template closer and right paren

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

This allows for `AlignAfterOpenBracket: BlockIndent` to work correctly
when using values with type parameters.

Line breaks after any template closer was disallowed 10 years ago, in
90e51fdbab33d43e0d4f932c2d90d0b86e865664, as a fix to 
https://github.com/llvm/llvm-project/issues/15158.
Allowing it again, but only if preceding a specific character, seems to
work out fine.

Note that this change originally caused a test failure in 
`FormatTestJS.NoBreakAfterAsserts`,
which is why there is an explicit negative check against `TT_JsTypeColon`.

Given this, I'm not 100% confident in this change not producing defects,
especially in other languages, but that was the only one in the test
suite.
Perhaps additional restrictions should be used, such as requiring
`BAS_BlockIndent` to be set.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D140267

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


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -24868,6 +24868,12 @@
"(\n"
") = nullptr;",
Style);
+
+  verifyFormat("static_assert(\n"
+   "std::is_base_of_v ||\n"
+   "std::is_base_of_v\n"
+   ");",
+   Style);
 }
 
 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -4952,6 +4952,10 @@
 return false;
   if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
 return true;
+  if (Left.is(TT_TemplateCloser) && Right.is(tok::r_paren) &&
+  (!Right.Next || Right.Next->isNot(TT_JsTypeColon))) {
+return true;
+  }
   if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
   (Left.is(tok::less) && Right.is(tok::less))) {
 return false;


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -24868,6 +24868,12 @@
"(\n"
") = nullptr;",
Style);
+
+  verifyFormat("static_assert(\n"
+   "std::is_base_of_v ||\n"
+   "std::is_base_of_v\n"
+   ");",
+   Style);
 }
 
 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -4952,6 +4952,10 @@
 return false;
   if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
 return true;
+  if (Left.is(TT_TemplateCloser) && Right.is(tok::r_paren) &&
+  (!Right.Next || Right.Next->isNot(TT_JsTypeColon))) {
+return true;
+  }
   if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
   (Left.is(tok::less) && Right.is(tok::less))) {
 return false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D139485: Remove redundant .c_str() and .get() calls

2022-12-17 Thread Fangrui Song 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 rGd22f050e15cb: Remove redundant .c_str() and .get() calls 
(authored by gAlfonso-bit, committed by MaskRay).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D139485?vs=481954=483789#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139485

Files:
  clang-tools-extra/modularize/ModuleAssistant.cpp
  clang/lib/Driver/OffloadBundler.cpp
  clang/lib/Driver/ToolChain.cpp
  lld/ELF/Writer.cpp
  llvm/include/llvm/Analysis/RegionInfoImpl.h
  llvm/include/llvm/MC/MCContext.h
  llvm/include/llvm/ProfileData/InstrProfReader.h
  llvm/include/llvm/Support/YAMLParser.h
  llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp
  llvm/lib/DebugInfo/LogicalView/Core/LVElement.cpp
  llvm/lib/DebugInfo/LogicalView/Core/LVScope.cpp
  llvm/lib/DebugInfo/LogicalView/Readers/LVBinaryReader.cpp
  llvm/lib/ObjCopy/MachO/MachOObjcopy.cpp
  llvm/lib/Target/BPF/BTFDebug.cpp
  llvm/tools/dsymutil/BinaryHolder.cpp
  llvm/tools/llvm-cfi-verify/lib/FileAnalysis.cpp
  llvm/tools/llvm-cov/CodeCoverage.cpp
  llvm/tools/obj2yaml/elf2yaml.cpp
  llvm/tools/obj2yaml/macho2yaml.cpp

Index: llvm/tools/obj2yaml/macho2yaml.cpp
===
--- llvm/tools/obj2yaml/macho2yaml.cpp
+++ llvm/tools/obj2yaml/macho2yaml.cpp
@@ -192,7 +192,7 @@
   if (SecName.startswith("__debug_")) {
 // If the DWARF section cannot be successfully parsed, emit raw content
 // instead of an entry in the DWARF section of the YAML.
-if (Error Err = dumpDebugSection(SecName, *DWARFCtx.get(), Y.DWARF))
+if (Error Err = dumpDebugSection(SecName, *DWARFCtx, Y.DWARF))
   consumeError(std::move(Err));
 else
   S->content.reset();
@@ -326,8 +326,7 @@
   if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
 MachO::swapStruct(LC.Data.load_command_data);
   if (Expected ExpectedEndPtr =
-  processLoadCommandData(LC, LoadCmd,
-  *Y.get()))
+  processLoadCommandData(LC, LoadCmd, *Y))
 EndPtr = *ExpectedEndPtr;
   else
 return ExpectedEndPtr.takeError();
Index: llvm/tools/obj2yaml/elf2yaml.cpp
===
--- llvm/tools/obj2yaml/elf2yaml.cpp
+++ llvm/tools/obj2yaml/elf2yaml.cpp
@@ -402,10 +402,10 @@
   }
 
   llvm::erase_if(Chunks, [this, ](const std::unique_ptr ) {
-if (isa(*C.get()))
+if (isa(*C))
   return false;
 
-const ELFYAML::Section  = cast(*C.get());
+const ELFYAML::Section  = cast(*C);
 return !shouldPrintSection(S, Sections[S.OriginalSecNdx], Y->DWARF);
   });
 
@@ -495,7 +495,7 @@
 // It is not possible to have a non-Section chunk, because
 // obj2yaml does not create Fill chunks.
 for (const std::unique_ptr  : Chunks) {
-  ELFYAML::Section  = cast(*C.get());
+  ELFYAML::Section  = cast(*C);
   if (isInSegment(S, Sections[S.OriginalSecNdx], Phdr)) {
 if (!PH.FirstSec)
   PH.FirstSec = S.Name;
@@ -530,13 +530,13 @@
   cantFail(std::move(Err));
 
   if (RawSec->Name == ".debug_aranges")
-Err = dumpDebugARanges(*DWARFCtx.get(), DWARF);
+Err = dumpDebugARanges(*DWARFCtx, DWARF);
   else if (RawSec->Name == ".debug_str")
-Err = dumpDebugStrings(*DWARFCtx.get(), DWARF);
+Err = dumpDebugStrings(*DWARFCtx, DWARF);
   else if (RawSec->Name == ".debug_ranges")
-Err = dumpDebugRanges(*DWARFCtx.get(), DWARF);
+Err = dumpDebugRanges(*DWARFCtx, DWARF);
   else if (RawSec->Name == ".debug_addr")
-Err = dumpDebugAddr(*DWARFCtx.get(), DWARF);
+Err = dumpDebugAddr(*DWARFCtx, DWARF);
   else
 continue;
 
Index: llvm/tools/llvm-cov/CodeCoverage.cpp
===
--- llvm/tools/llvm-cov/CodeCoverage.cpp
+++ llvm/tools/llvm-cov/CodeCoverage.cpp
@@ -1076,7 +1076,7 @@
 FilenameFunctionMap;
 for (const auto  : SourceFiles)
   for (const auto  : Coverage->getCoveredFunctions(SourceFile))
-if (Filters.matches(*Coverage.get(), Function))
+if (Filters.matches(*Coverage, Function))
   FilenameFunctionMap[SourceFile].push_back();
 
 // Only print filter matching functions for each file.
@@ -1165,7 +1165,7 @@
   if (!Coverage)
 return 1;
 
-  CoverageReport Report(ViewOpts, *Coverage.get());
+  CoverageReport Report(ViewOpts, *Coverage);
   if (!ShowFunctionSummaries) {
 if (SourceFiles.empty())
   Report.renderFileReports(llvm::outs(), IgnoreFilenameFilters);
@@ -1231,16 +1231,16 @@
 
   switch (ViewOpts.Format) {
   case CoverageViewOptions::OutputFormat::Text:
-Exporter = 

[clang-tools-extra] d22f050 - Remove redundant .c_str() and .get() calls

2022-12-17 Thread Fangrui Song via cfe-commits

Author: Gregory Alfonso
Date: 2022-12-18T00:33:53Z
New Revision: d22f050e15cb8c941d488d9674329db320ef1783

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

LOG: Remove redundant .c_str() and .get() calls

Reviewed By: MaskRay

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

Added: 


Modified: 
clang-tools-extra/modularize/ModuleAssistant.cpp
clang/lib/Driver/OffloadBundler.cpp
clang/lib/Driver/ToolChain.cpp
lld/ELF/Writer.cpp
llvm/include/llvm/Analysis/RegionInfoImpl.h
llvm/include/llvm/MC/MCContext.h
llvm/include/llvm/ProfileData/InstrProfReader.h
llvm/include/llvm/Support/YAMLParser.h
llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp
llvm/lib/DebugInfo/LogicalView/Core/LVElement.cpp
llvm/lib/DebugInfo/LogicalView/Core/LVScope.cpp
llvm/lib/DebugInfo/LogicalView/Readers/LVBinaryReader.cpp
llvm/lib/ObjCopy/MachO/MachOObjcopy.cpp
llvm/lib/Target/BPF/BTFDebug.cpp
llvm/tools/dsymutil/BinaryHolder.cpp
llvm/tools/llvm-cfi-verify/lib/FileAnalysis.cpp
llvm/tools/llvm-cov/CodeCoverage.cpp
llvm/tools/obj2yaml/elf2yaml.cpp
llvm/tools/obj2yaml/macho2yaml.cpp

Removed: 




diff  --git a/clang-tools-extra/modularize/ModuleAssistant.cpp 
b/clang-tools-extra/modularize/ModuleAssistant.cpp
index bdce90726e0a..0d4c09987eb1 100644
--- a/clang-tools-extra/modularize/ModuleAssistant.cpp
+++ b/clang-tools-extra/modularize/ModuleAssistant.cpp
@@ -305,7 +305,7 @@ bool createModuleMap(llvm::StringRef ModuleMapPath,
 loadModuleDescriptions(
   RootModuleName, HeaderFileNames, ProblemFileNames, Dependencies,
   HeaderPrefix));
-  if (!RootModule.get())
+  if (!RootModule)
 return false;
 
   // Write module map file.

diff  --git a/clang/lib/Driver/OffloadBundler.cpp 
b/clang/lib/Driver/OffloadBundler.cpp
index 99f962bba7f5..bcc0c320fa47 100644
--- a/clang/lib/Driver/OffloadBundler.cpp
+++ b/clang/lib/Driver/OffloadBundler.cpp
@@ -1183,7 +1183,7 @@ Error OffloadBundler::UnbundleArchive() {
 assert(FileHandler &&
"FileHandle creation failed for file in the archive!");
 
-if (Error ReadErr = FileHandler.get()->ReadHeader(*CodeObjectBuffer))
+if (Error ReadErr = FileHandler->ReadHeader(*CodeObjectBuffer))
   return ReadErr;
 
 Expected> CurBundleIDOrErr =
@@ -1208,8 +1208,7 @@ Error OffloadBundler::UnbundleArchive() {
  BundlerConfig)) {
 std::string BundleData;
 raw_string_ostream DataStream(BundleData);
-if (Error Err =
-FileHandler.get()->ReadBundle(DataStream, *CodeObjectBuffer))
+if (Error Err = FileHandler->ReadBundle(DataStream, *CodeObjectBuffer))
   return Err;
 
 for (auto  : CompatibleTargets) {
@@ -1248,7 +1247,7 @@ Error OffloadBundler::UnbundleArchive() {
 }
   }
 
-  if (Error Err = FileHandler.get()->ReadBundleEnd(*CodeObjectBuffer))
+  if (Error Err = FileHandler->ReadBundleEnd(*CodeObjectBuffer))
 return Err;
 
   Expected> NextTripleOrErr =

diff  --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index 22802b317eaa..7b6de09ee261 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -150,9 +150,9 @@ ToolChain::getSanitizerArgs(const llvm::opt::ArgList 
) const {
 }
 
 const XRayArgs& ToolChain::getXRayArgs() const {
-  if (!XRayArguments.get())
+  if (!XRayArguments)
 XRayArguments.reset(new XRayArgs(*this, Args));
-  return *XRayArguments.get();
+  return *XRayArguments;
 }
 
 namespace {

diff  --git a/lld/ELF/Writer.cpp b/lld/ELF/Writer.cpp
index bde60e230ce8..5904a7b85eda 100644
--- a/lld/ELF/Writer.cpp
+++ b/lld/ELF/Writer.cpp
@@ -1031,8 +1031,8 @@ template  void 
Writer::setReservedSymbolSections() {
 // to the start of the .got or .got.plt section.
 InputSection *sec = in.gotPlt.get();
 if (!target->gotBaseSymInGotPlt)
-  sec = in.mipsGot.get() ? cast(in.mipsGot.get())
- : cast(in.got.get());
+  sec = in.mipsGot ? cast(in.mipsGot.get())
+   : cast(in.got.get());
 ElfSym::globalOffsetTable->section = sec;
   }
 

diff  --git a/llvm/include/llvm/Analysis/RegionInfoImpl.h 
b/llvm/include/llvm/Analysis/RegionInfoImpl.h
index 7fdfdd0efba8..74591ee25ae5 100644
--- a/llvm/include/llvm/Analysis/RegionInfoImpl.h
+++ b/llvm/include/llvm/Analysis/RegionInfoImpl.h
@@ -778,12 +778,12 @@ template 
 void RegionInfoBase::dump() const { print(dbgs()); }
 #endif
 
-template 
-void RegionInfoBase::releaseMemory() {
+template  void RegionInfoBase::releaseMemory() {
   BBtoRegion.clear();
-  if (TopLevelRegion)
+  if (TopLevelRegion) {
 delete TopLevelRegion;
-  TopLevelRegion = nullptr;
+TopLevelRegion = nullptr;

[PATCH] D140086: [analyzer][solver] Improve reasoning for not equal to operator

2022-12-17 Thread Manas Gupta via Phabricator via cfe-commits
manas updated this revision to Diff 483786.
manas added a comment.

Remove redundant branches


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140086

Files:
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  clang/test/Analysis/constant-folding.c


Index: clang/test/Analysis/constant-folding.c
===
--- clang/test/Analysis/constant-folding.c
+++ clang/test/Analysis/constant-folding.c
@@ -303,7 +303,8 @@
 
   if (s1 < 0 && s1 > -4 && u1 > UINT_MAX - 4 && u1 < UINT_MAX - 1) {
 // s1: [-3, -1], u1: [UINT_MAX - 3, UINT_MAX - 2]
-clang_analyzer_eval(u1 != s1); // expected-warning{{UNKNOWN}}
+clang_analyzer_eval(u1 != s1); // expected-warning{{TRUE}}
+clang_analyzer_eval(s1 != u1); // expected-warning{{TRUE}}
   }
 
   if (s1 < 1 && s1 > -6 && s1 != -4 && s1 != -3 &&
@@ -400,12 +401,10 @@
 clang_analyzer_eval(uch != sch); // expected-warning{{UNKNOWN}}
   }
 
-  // FIXME: Casting smaller signed types to unsigned one may leave us with
-  // overlapping values, falsely indicating UNKNOWN, where it is possible to
-  // assert TRUE.
   if (uch > 1 && sch < 1) {
 // uch: [2, UCHAR_MAX], sch: [SCHAR_MIN, 0]
-clang_analyzer_eval(uch != sch); // expected-warning{{UNKNOWN}}
+clang_analyzer_eval(uch != sch); // expected-warning{{TRUE}}
+clang_analyzer_eval(sch != uch); // expected-warning{{TRUE}}
   }
 
   if (uch <= 1 && uch >= 1 && sch <= 1 && sch >= 1) {
@@ -419,10 +418,9 @@
 clang_analyzer_eval(ush != ssh); // expected-warning{{UNKNOWN}}
   }
 
-  // FIXME: Casting leave us with overlapping values. Should be TRUE.
   if (ush > 1 && ssh < 1) {
 // ush: [2, USHRT_MAX], ssh: [SHRT_MIN, 0]
-clang_analyzer_eval(ush != ssh); // expected-warning{{UNKNOWN}}
+clang_analyzer_eval(ush != ssh); // expected-warning{{TRUE}}
   }
 
   if (ush <= 1 && ush >= 1 && ssh <= 1 && ssh >= 1) {
Index: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
@@ -1624,7 +1624,37 @@
   if (LHS.getAPSIntType() == RHS.getAPSIntType()) {
 if (intersect(RangeFactory, LHS, RHS).isEmpty())
   return getTrueRange(T);
+
   } else {
+// We can only lose information if we are casting smaller signed type to
+// bigger unsigned type. For e.g.,
+//LHS (unsigned short): [2, USHRT_MAX]
+//RHS   (signed short): [SHRT_MIN, 0]
+//
+// Casting RHS to LHS type will leave us with overlapping values
+//CastedRHS : [0, 0] U [SHRT_MAX + 1, USHRT_MAX]
+//
+// We can avoid this by checking if signed type's maximum value is lesser
+// than unsigned type's minimum value.
+
+// If both have different signs then only we can get more information.
+if (LHS.isUnsigned() != RHS.isUnsigned()) {
+  auto SignedHS = LHS.isUnsigned() ? RHS : LHS;
+
+  // If signed range is =Zero, then maximum value of signed
+  // type should be lesser than minimum value of unsigned type.
+  if (UnsignedHS.getAPSIntType().convert(SignedHS.getMaxValue()) <
+  UnsignedHS.getMinValue())
+return getTrueRange(T);
+}
+
 // Both RangeSets should be casted to bigger unsigned type.
 APSIntType CastingType(std::max(LHS.getBitWidth(), RHS.getBitWidth()),
LHS.isUnsigned() || RHS.isUnsigned());
@@ -2147,7 +2177,6 @@
   RangeSet::Factory 
 };
 
-
 bool ConstraintAssignor::assignSymExprToConst(const SymExpr *Sym,
   const llvm::APSInt ) {
   llvm::SmallSet SimplifiedClasses;


Index: clang/test/Analysis/constant-folding.c
===
--- clang/test/Analysis/constant-folding.c
+++ clang/test/Analysis/constant-folding.c
@@ -303,7 +303,8 @@
 
   if (s1 < 0 && s1 > -4 && u1 > UINT_MAX - 4 && u1 < UINT_MAX - 1) {
 // s1: [-3, -1], u1: [UINT_MAX - 3, UINT_MAX - 2]
-clang_analyzer_eval(u1 != s1); // expected-warning{{UNKNOWN}}
+clang_analyzer_eval(u1 != s1); // expected-warning{{TRUE}}
+clang_analyzer_eval(s1 != u1); // expected-warning{{TRUE}}
   }
 
   if (s1 < 1 && s1 > -6 && s1 != -4 && s1 != -3 &&
@@ -400,12 +401,10 @@
 clang_analyzer_eval(uch != sch); // expected-warning{{UNKNOWN}}
   }
 
-  // FIXME: Casting smaller signed types to unsigned one may leave us with
-  // overlapping values, falsely indicating UNKNOWN, where it is possible to
-  // assert TRUE.
   if (uch > 1 && sch < 1) {
 // uch: [2, UCHAR_MAX], sch: [SCHAR_MIN, 0]
-clang_analyzer_eval(uch != sch); // expected-warning{{UNKNOWN}}
+clang_analyzer_eval(uch != sch); // expected-warning{{TRUE}}
+clang_analyzer_eval(sch != uch); // expected-warning{{TRUE}}
   }
 
   if (uch <= 1 && uch >= 1 

[PATCH] D140086: [analyzer][solver] Improve reasoning for not equal to operator

2022-12-17 Thread Manas Gupta via Phabricator via cfe-commits
manas marked 2 inline comments as done.
manas added a comment.

In D140086#3998426 , @steakhal wrote:

> Thanks for going the extra mile to address this last thing. I really 
> appreciate it.
> I've got only a few minor comments and suggestions.
>
> I'd recommend spell-checking the comments and the summary of this revision.
> See my technical comments inline.

Thank you once again for reviewing @steakhal :)

I did the spell-checking.




Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1641-1642
+// If both have different signs then only we can get more information.
+if (LHS.isUnsigned() ^ RHS.isUnsigned()) {
+  if (LHS.isUnsigned() && (LHS.getBitWidth() >= RHS.getBitWidth())) {
+

steakhal wrote:
> steakhal wrote:
> > I think in this context `!=` should achieve the same, and we usually prefer 
> > this operator for this.
> I was thinking that maybe `if (LHS.isUnsigned() && RHS.isSigned()) {} ... 
> else if (LHS.isSigned() && RHS.isUnsigned())` results in cleaner code, as it 
> would require one level fewer indentations.
> The control-flow looks complicated already enough.
> I was thinking that maybe if (LHS.isUnsigned() && RHS.isSigned()) {} ... else 
> if (LHS.isSigned() && RHS.isUnsigned()) results in cleaner code

I did this, and I also combined both blocks into one to remove redundant code.




Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1642
+if (LHS.isUnsigned() ^ RHS.isUnsigned()) {
+  if (LHS.isUnsigned() && (LHS.getBitWidth() >= RHS.getBitWidth())) {
+

steakhal wrote:
> Why do we need this additional condition?
> If I remove these, I get no test failures, which suggests to me that we have 
> some undertested code paths here.
> Why do we need this additional condition?

Bitwidth was important because we should ideally cast smaller bitwidth type to 
bigger bitwidth type.

Consider if we have `LHS(u8), RHS(i32)`, then without checking for bitwidth, we 
would be casting RHS's maxValue to LHS's type, which will result in lose of 
information and will not serve our purpose.





Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1666-1669
+const llvm::APSInt CastedLHSMax =
+RHS.getAPSIntType().convert(LHS.getMaxValue());
+if (CastedLHSMax < RHS.getMinValue())
+  return getTrueRange(T);

steakhal wrote:
> I was thinking of using init-ifs, but on second thought I'm not sure if 
> that's more readable.
> ```lang=c++
> if (RHS.getAPSIntType().convert(LHS.getMaxValue()) < RHS.getMinValue())
>   return getTrueRange(T);
> ```
> Shouldn't be too bad.
I think its readable. But to combine two blocks into one, I had to use 
different variable names, which makes this expression bigger. Should we still 
go with init-ifs?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140086

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


[clang-tools-extra] b57533d - [clang-tools-extra] llvm::Optional::value => operator*/operator->

2022-12-17 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2022-12-17T20:03:01Z
New Revision: b57533d1d5a2fa6b9402aa6255cb67b2dd7529a4

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

LOG: [clang-tools-extra] llvm::Optional::value => operator*/operator->

std::optional::value() has undesired exception checking semantics and is
unavailable in older Xcode (see _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS). The
call sites block std::optional migration.

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
clang-tools-extra/clangd/AST.cpp
clang-tools-extra/clangd/ClangdServer.cpp
clang-tools-extra/unittests/clang-tidy/NamespaceAliaserTest.cpp
clang-tools-extra/unittests/clang-tidy/UsingInserterTest.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
index ea3d64ef700e8..17537f1d1f867 100644
--- a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
@@ -818,7 +818,7 @@ void NotNullTerminatedResultCheck::check(
 }
 
 if (AreSafeFunctionsWanted)
-  UseSafeFunctions = AreSafeFunctionsWanted.value();
+  UseSafeFunctions = *AreSafeFunctionsWanted;
   }
 
   StringRef Name = FunctionExpr->getDirectCallee()->getName();

diff  --git a/clang-tools-extra/clangd/AST.cpp 
b/clang-tools-extra/clangd/AST.cpp
index 6e566fbf91b1e..b9c76076f4907 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -955,7 +955,7 @@ resolveForwardingParameters(const FunctionDecl *D, unsigned 
MaxDepth) {
 break;
   }
   // If we found something: Fill in non-pack parameters
-  auto Info = V.Info.value();
+  auto Info = *V.Info;
   HeadIt = std::copy(Info.Head.begin(), Info.Head.end(), HeadIt);
   TailIt = std::copy(Info.Tail.rbegin(), Info.Tail.rend(), TailIt);
   // Prepare next recursion level

diff  --git a/clang-tools-extra/clangd/ClangdServer.cpp 
b/clang-tools-extra/clangd/ClangdServer.cpp
index b2b6c44744765..9c8803bbfb1ce 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -415,8 +415,7 @@ void ClangdServer::codeComplete(PathRef File, Position Pos,
 }
 if (SpecFuzzyFind && SpecFuzzyFind->NewReq) {
   std::lock_guard Lock(CachedCompletionFuzzyFindRequestMutex);
-  CachedCompletionFuzzyFindRequestByFile[File] =
-  SpecFuzzyFind->NewReq.value();
+  CachedCompletionFuzzyFindRequestByFile[File] = *SpecFuzzyFind->NewReq;
 }
 // SpecFuzzyFind is only destroyed after speculative fuzzy find finishes.
 // We don't want `codeComplete` to wait for the async call if it doesn't 
use

diff  --git a/clang-tools-extra/unittests/clang-tidy/NamespaceAliaserTest.cpp 
b/clang-tools-extra/unittests/clang-tidy/NamespaceAliaserTest.cpp
index c28e89cffac37..dfe04c175b791 100644
--- a/clang-tools-extra/unittests/clang-tidy/NamespaceAliaserTest.cpp
+++ b/clang-tools-extra/unittests/clang-tidy/NamespaceAliaserTest.cpp
@@ -35,7 +35,7 @@ class InsertAliasCheck : public ClangTidyCheck {
 auto Hint = Aliaser->createAlias(*Result.Context, *Call, "::foo::bar",
  {"b", "some_alias"});
 if (Hint)
-  diag(Call->getBeginLoc(), "Fix for testing") << Hint.value();
+  diag(Call->getBeginLoc(), "Fix for testing") << *Hint;
 
 diag(Call->getBeginLoc(), "insert call") << FixItHint::CreateInsertion(
 Call->getBeginLoc(),

diff  --git a/clang-tools-extra/unittests/clang-tidy/UsingInserterTest.cpp 
b/clang-tools-extra/unittests/clang-tidy/UsingInserterTest.cpp
index c27a1f0b132ed..717d2bed15fd1 100644
--- a/clang-tools-extra/unittests/clang-tidy/UsingInserterTest.cpp
+++ b/clang-tools-extra/unittests/clang-tidy/UsingInserterTest.cpp
@@ -38,7 +38,7 @@ class InsertUsingCheck : public clang::tidy::ClangTidyCheck {
 Inserter->createUsingDeclaration(*Result.Context, *Call, 
"::foo::func");
 
 if (Hint)
-  diag(Call->getBeginLoc(), "Fix for testing") << Hint.value();
+  diag(Call->getBeginLoc(), "Fix for testing") << *Hint;
 
 diag(Call->getBeginLoc(), "insert call")
 << clang::FixItHint::CreateReplacement(



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


[clang] d1f4753 - [clang] llvm::Optional::value() && => operator*/operator->

2022-12-17 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2022-12-17T19:47:45Z
New Revision: d1f475347518bdab387f21cda2281c0939a80f70

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

LOG: [clang] llvm::Optional::value() && => operator*/operator->

std::optional::value() has undesired exception checking semantics and is
unavailable in older Xcode (see _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS). The
call sites block std::optional migration.

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
clang/lib/Sema/SemaRISCVVectorLookup.cpp
clang/unittests/Analysis/MacroExpansionContextTest.cpp
clang/unittests/DirectoryWatcher/DirectoryWatcherTest.cpp

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
index 444c317cbbefc..7394a7d32eafb 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
@@ -1017,9 +1017,8 @@ class CXXAllocatorCall : public AnyFunctionCall {
   }
 
   SVal getObjectUnderConstruction() const {
-return ExprEngine::getObjectUnderConstruction(getState(), getOriginExpr(),
-  getLocationContext())
-.value();
+return *ExprEngine::getObjectUnderConstruction(getState(), getOriginExpr(),
+   getLocationContext());
   }
 
   /// Number of non-placement arguments to the call. It is equal to 2 for

diff  --git a/clang/lib/Sema/SemaRISCVVectorLookup.cpp 
b/clang/lib/Sema/SemaRISCVVectorLookup.cpp
index 85bf11e942b96..cf9a8a4f5a228 100644
--- a/clang/lib/Sema/SemaRISCVVectorLookup.cpp
+++ b/clang/lib/Sema/SemaRISCVVectorLookup.cpp
@@ -115,7 +115,7 @@ static QualType RVVType2Qual(ASTContext , const 
RVVType *Type) {
 llvm_unreachable("Unhandled type.");
   }
   if (Type->isVector())
-QT = Context.getScalableVectorType(QT, Type->getScale().value());
+QT = Context.getScalableVectorType(QT, *Type->getScale());
 
   if (Type->isConstant())
 QT = Context.getConstType(QT);

diff  --git a/clang/unittests/Analysis/MacroExpansionContextTest.cpp 
b/clang/unittests/Analysis/MacroExpansionContextTest.cpp
index add3099a5be9a..5c694c836a488 100644
--- a/clang/unittests/Analysis/MacroExpansionContextTest.cpp
+++ b/clang/unittests/Analysis/MacroExpansionContextTest.cpp
@@ -181,14 +181,14 @@ EMPTY zz
   //  A b cd ef gh
   //  zz
 
-  EXPECT_EQ("", Ctx->getExpandedText(at(3, 10)).value());
-  EXPECT_EQ("EMPTY", Ctx->getOriginalText(at(3, 10)).value());
+  EXPECT_EQ("", *Ctx->getExpandedText(at(3, 10)));
+  EXPECT_EQ("EMPTY", *Ctx->getOriginalText(at(3, 10)));
 
-  EXPECT_EQ("", Ctx->getExpandedText(at(3, 19)).value());
-  EXPECT_EQ("EMPTY", Ctx->getOriginalText(at(3, 19)).value());
+  EXPECT_EQ("", *Ctx->getExpandedText(at(3, 19)));
+  EXPECT_EQ("EMPTY", *Ctx->getOriginalText(at(3, 19)));
 
-  EXPECT_EQ("", Ctx->getExpandedText(at(4, 1)).value());
-  EXPECT_EQ("EMPTY", Ctx->getOriginalText(at(4, 1)).value());
+  EXPECT_EQ("", *Ctx->getExpandedText(at(4, 1)));
+  EXPECT_EQ("EMPTY", *Ctx->getOriginalText(at(4, 1)));
 }
 
 TEST_F(MacroExpansionContextTest, TransitiveExpansions) {
@@ -200,10 +200,10 @@ TEST_F(MacroExpansionContextTest, TransitiveExpansions) {
   // After preprocessing:
   //  A b cd ) 1 ef gh
 
-  EXPECT_EQ("WOOF", Ctx->getOriginalText(at(4, 10)).value());
+  EXPECT_EQ("WOOF", *Ctx->getOriginalText(at(4, 10)));
 
-  EXPECT_EQ("", Ctx->getExpandedText(at(4, 18)).value());
-  EXPECT_EQ("EMPTY", Ctx->getOriginalText(at(4, 18)).value());
+  EXPECT_EQ("", *Ctx->getExpandedText(at(4, 18)));
+  EXPECT_EQ("EMPTY", *Ctx->getOriginalText(at(4, 18)));
 }
 
 TEST_F(MacroExpansionContextTest, MacroFunctions) {
@@ -219,17 +219,17 @@ TEST_F(MacroExpansionContextTest, MacroFunctions) {
   //  WOOF( ) ) ) 1
   //  bar barr( ) ) ) 1( ) ) ) 1),,),')
 
-  EXPECT_EQ("$$ ef ()))1", Ctx->getExpandedText(at(4, 10)).value());
-  EXPECT_EQ("WOOF($$ ef)", Ctx->getOriginalText(at(4, 10)).value());
+  EXPECT_EQ("$$ ef ()))1", *Ctx->getExpandedText(at(4, 10)));
+  EXPECT_EQ("WOOF($$ ef)", *Ctx->getOriginalText(at(4, 10)));
 
-  EXPECT_EQ("", Ctx->getExpandedText(at(4, 22)).value());
-  EXPECT_EQ("EMPTY", Ctx->getOriginalText(at(4, 22)).value());
+  EXPECT_EQ("", *Ctx->getExpandedText(at(4, 22)));
+  EXPECT_EQ("EMPTY", *Ctx->getOriginalText(at(4, 22)));
 
-  EXPECT_EQ("WOOF ()))1", Ctx->getExpandedText(at(5, 3)).value());
-  EXPECT_EQ("WOOF(WOOF)", Ctx->getOriginalText(at(5, 3)).value());
+  EXPECT_EQ("WOOF ()))1", *Ctx->getExpandedText(at(5, 3)));
+  EXPECT_EQ("WOOF(WOOF)", *Ctx->getOriginalText(at(5, 3)));
 
-  EXPECT_EQ("bar barr ()))1()))1", 

[PATCH] D134589: [C++20][Modules] Elide unused guard variables in Itanium ABI module initializers.

2022-12-17 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 483770.
iains added a comment.

rebased, amended a comment as suggested


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134589

Files:
  clang/lib/CodeGen/CGDeclCXX.cpp
  clang/test/CodeGenCXX/module-initializer-guard-elision.cpp

Index: clang/test/CodeGenCXX/module-initializer-guard-elision.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/module-initializer-guard-elision.cpp
@@ -0,0 +1,69 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: cd %t
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 O.cpp \
+// RUN:-emit-module-interface -o O.pcm
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 O.pcm -S -emit-llvm \
+// RUN:  -o - | FileCheck %s --check-prefix=CHECK-O
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 P.cpp \
+// RUN:-emit-module-interface -fmodule-file=O.pcm -o P.pcm
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 P.pcm -S -emit-llvm \
+// RUN:  -o - | FileCheck %s --check-prefix=CHECK-P
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 Q.cpp \
+// RUN:-emit-module-interface -fmodule-file=O.pcm -o Q.pcm
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 Q.pcm -S -emit-llvm \
+// RUN:  -o - | FileCheck %s --check-prefix=CHECK-Q
+
+// Testing cases where we can elide the module initializer guard variable.
+
+// This module has no global inits and does not import any other module
+//--- O.cpp
+
+export module O;
+
+export int foo ();
+
+// CHECK-O: define void @_ZGIW1O
+// CHECK-O-LABEL: entry
+// CHECK-O-NEXT: ret void
+// CHECK-O-NOT: @_ZGIW1O__in_chrg
+
+// This has no global inits but imports a module, and therefore needs a guard
+// variable.
+//--- P.cpp
+
+export module P;
+
+export import O;
+export int bar ();
+
+// CHECK-P: define void @_ZGIW1P
+// CHECK-P-LABEL: init
+// CHECK-P: store i8 1, ptr @_ZGIW1P__in_chrg
+// CHECK-P: call void @_ZGIW1O()
+// CHECK-P-NOT: call void @__cxx_global_var_init
+
+// This imports a module and has global inits, so needs a guard.
+//--- Q.cpp
+
+export module Q;
+export import O;
+
+export struct Quack {
+  Quack(){};
+};
+
+export Quack Duck;
+
+export int baz ();
+
+// CHECK-Q: define internal void @__cxx_global_var_init
+// CHECK-Q: call {{.*}} @_ZNW1Q5QuackC1Ev
+// CHECK-Q: define void @_ZGIW1Q
+// CHECK-Q: store i8 1, ptr @_ZGIW1Q__in_chrg
+// CHECK-Q: call void @_ZGIW1O()
+// CHECK-Q: call void @__cxx_global_var_init
+
Index: clang/lib/CodeGen/CGDeclCXX.cpp
===
--- clang/lib/CodeGen/CGDeclCXX.cpp
+++ clang/lib/CodeGen/CGDeclCXX.cpp
@@ -640,7 +640,12 @@
 
 /* Build the initializer for a C++20 module:
This is arranged to be run only once regardless of how many times the module
-   might be included transitively.  This arranged by using a control variable.
+   might be included transitively.  This arranged by using a guard variable.
+
+   If there are no initalizers at all (and also no imported modules) we reduce
+   this to an empty function (since the Itanium ABI requires that this function
+   be available to a caller, which might be produced by a different
+   implementation).
 
First we call any initializers for imported modules.
We then call initializers for the Global Module Fragment (if present)
@@ -652,13 +657,10 @@
   while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
 CXXGlobalInits.pop_back();
 
-  // We create the function, even if it is empty, since an importer of this
-  // module will refer to it unconditionally (for the current implementation
-  // there is no way for the importer to know that an importee does not need
-  // an initializer to be run).
-
+  // As noted above, we create the function, even if it is empty.
   // Module initializers for imported modules are emitted first.
-  // Collect the modules that we import
+
+  // Collect all the modules that we import
   SmallVector AllImports;
   // Ones that we export
   for (auto I : Primary->Exports)
@@ -685,7 +687,6 @@
 FTy, llvm::Function::ExternalLinkage, FnName.str(), ());
 ModuleInits.push_back(Fn);
   }
-  AllImports.clear();
 
   // Add any initializers with specified priority; this uses the same  approach
   // as EmitCXXGlobalInitFunc().
@@ -703,13 +704,11 @@
   for (; I < PrioE; ++I)
 ModuleInits.push_back(I->second);
 }
-PrioritizedCXXGlobalInits.clear();
   }
 
   // Now append the ones without specified priority.
   for (auto *F : CXXGlobalInits)
 ModuleInits.push_back(F);
-  CXXGlobalInits.clear();
 
   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
   const CGFunctionInfo  = getTypes().arrangeNullaryFunction();
@@ -719,7 +718,6 @@
   // each init is run just once (even though a module might be imported
   // multiple times via nested use).
   llvm::Function *Fn;
- 

[PATCH] D139973: [llvm] Make llvm::Any similar to std::any

2022-12-17 Thread Joe Loser via Phabricator via cfe-commits
jloser added a comment.

I'm +1 for the direction here; I took a brief look but will look closely either 
later tonight or tomorrow before I approve.  Thanks for doing this!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139973

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


[PATCH] D139701: [Clang] Don't emit "min-legal-vector-width"="0" for AMDGPU

2022-12-17 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

In D139701#4003209 , @pengfei wrote:

> In D139701#3993131 , @craig.topper 
> wrote:
>
>> I really think only X86 is using this.
>
> I'm still not sure of that. Please see the diff in AArch64/ARM tests.

Most of them were done by me in this commit https://reviews.llvm.org/D52441. I 
either did it for extra coverage or because the tests already checked for `#0` 
and some test cases ended up with #1 due to the different vector lengths.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139701

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


[PATCH] D124351: [Clang][WIP] Implement Change scope of lambda trailing-return-type - Take 2

2022-12-17 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 483757.
cor3ntin added a comment.

Fix fix-it tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124351

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Scope.h
  clang/include/clang/Sema/ScopeInfo.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Sema/Scope.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaCXXScopeSpec.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/TreeTransform.h
  clang/test/CXX/expr/expr.prim/expr.prim.lambda/p11-1y.cpp
  clang/test/CXX/expr/expr.prim/expr.prim.lambda/p4.cpp
  clang/test/SemaCXX/lambda-capture-type-deduction.cpp
  clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1358,7 +1358,7 @@
 
   Change scope of lambda trailing-return-type
   https://wg21.link/P2036R3;>P2036R3
-  No
+  Clang 16
 
 
   https://wg21.link/P2579R0;>P2579R0
Index: clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
===
--- clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
+++ clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
@@ -95,7 +95,7 @@
 #ifdef AVOID
   auto l4 = [var = param] (int param) { ; }; // no warning
 #else
-  auto l4 = [var = param] (int param) { ; }; // expected-warning {{declaration shadows a local variable}}
+  auto l4 = [var = param](int param) { ; }; // expected-warning 2{{declaration shadows a local variable}}
 #endif
 
   // Make sure that inner lambdas work as well.
Index: clang/test/SemaCXX/lambda-capture-type-deduction.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/lambda-capture-type-deduction.cpp
@@ -0,0 +1,248 @@
+// RUN: %clang_cc1 -std=c++2b -verify -fsyntax-only %s
+
+template 
+constexpr bool is_same = false;
+
+template 
+constexpr bool is_same = true;
+
+void f() {
+
+  int y;
+
+  static_assert(is_same decltype((x)) { return x; }())>);
+
+  static_assert(is_same decltype((x)) { return x; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  auto ref = [ = y](
+ decltype([&](decltype(x)) { return 0; }) y) {
+return x;
+  };
+}
+
+void test_noexcept() {
+
+  int y;
+
+  static_assert(noexcept([x = 1] noexcept(is_same) {}()));
+  static_assert(noexcept([x = 1] mutable noexcept(is_same) {}()));
+  static_assert(noexcept([y] noexcept(is_same) {}()));
+  static_assert(noexcept([y] mutable noexcept(is_same) {}()));
+  static_assert(noexcept([=] noexcept(is_same) {}()));
+  static_assert(noexcept([=] mutable noexcept(is_same) {}()));
+  static_assert(noexcept([&] noexcept(is_same) {}()));
+  static_assert(noexcept([&] mutable noexcept(is_same) {}()));
+
+  static_assert(noexcept([&] mutable noexcept(!is_same) {}())); // expected-error {{static_assert failed due}}
+}
+
+void test_requires() {
+
+  int x;
+
+  [x = 1]() requires is_same {}
+  ();
+  [x = 1]() mutable requires is_same {}
+  ();
+  [x]() requires is_same {}
+  ();
+  [x]() mutable requires is_same {}
+  ();
+  [=]() requires is_same {}
+  ();
+  [=]() mutable requires is_same {}
+  ();
+  [&]() requires is_same {}
+  ();
+  [&]() mutable requires is_same {}
+  ();
+  []() requires is_same {}
+  ();
+  []() mutable requires is_same {}
+  ();
+
+  [x = 1]() requires is_same {} (); //expected-error {{no matching function for call to object of type}} \
+   // expected-note {{candidate function not viable}} \
+   // expected-note {{'is_same' evaluated to false}}
+  [x = 1]() mutable requires is_same {} (); // expected-error {{no matching function for call to object of type}} \
+ // expected-note {{candidate function not viable}} \
+ // expected-note {{'is_same' evaluated to false}}
+}
+
+void err() {
+  int y, z; // expected-note 2{{declared here}}
+
+  (void)[x = 1] // expected-note {{variable 'x' is explicitly captured here}}
+  requires(is_same) {}; // expected-error {{captured variable 'x' cannot appear here}}
+
+  (void)[x = 1]{}; // expected-note {{variable 'x' is explicitly captured here}} \
+

[PATCH] D137817: [clangd] Improve action `RemoveUsingNamespace` for user-defined literals

2022-12-17 Thread Vincent Hong via Phabricator via cfe-commits
v1nh1shungry added a comment.

I think this patch is ready for another review now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137817

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


[PATCH] D137817: [clangd] Improve action `RemoveUsingNamespace` for user-defined literals

2022-12-17 Thread Vincent Hong via Phabricator via cfe-commits
v1nh1shungry added a comment.

I think this patch is ready for another review now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137817

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


[PATCH] D140261: [C++20][Modules] Do not allow non-inline external definitions in header units.

2022-12-17 Thread Iain Sandoe via Phabricator via cfe-commits
iains created this revision.
Herald added a project: All.
iains added a reviewer: ChuanqiXu.
iains added a subscriber: clang-modules.
iains published this revision for review.
iains added a comment.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

this came up during discussion of other header unit constraints, we had not 
implemented it yet.
found a test case where we'd accidentally broken this rule too.


[module.import/6] last sentence:
A header unit shall not contain a definition of a non-inline function or
variable whose name has external linkage.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D140261

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDecl.cpp
  clang/test/CXX/module/module.import/p6.cpp
  clang/test/CodeGenCXX/module-initializer-header.cppm

Index: clang/test/CodeGenCXX/module-initializer-header.cppm
===
--- clang/test/CodeGenCXX/module-initializer-header.cppm
+++ clang/test/CodeGenCXX/module-initializer-header.cppm
@@ -8,24 +8,24 @@
 //
 //--- header.h
 int foo();
-int i = foo();
+static int i = foo();
 
 //--- M.cppm
 module;
 import "header.h";
 export module M;
 
-// CHECK: @i = {{.*}}global i32 0
+// CHECK: @_ZL1i = {{.*}}global i32 0
 // CHECK: void @__cxx_global_var_init()
 // CHECK-NEXT: entry:
 // CHECK-NEXT:  %call = call noundef{{.*}} i32 @_Z3foov()
-// CHECK-NEXT:  store i32 %call, ptr @i  
+// CHECK-NEXT:  store i32 %call, ptr @_ZL1i  
 
 //--- Use.cpp
 import "header.h";
 
-// CHECK: @i = {{.*}}global i32 0
+// CHECK: @_ZL1i = {{.*}}global i32 0
 // CHECK: void @__cxx_global_var_init()
 // CHECK-NEXT: entry:
 // CHECK-NEXT:  %call = call noundef{{.*}} i32 @_Z3foov()
-// CHECK-NEXT:  store i32 %call, ptr @i  
+// CHECK-NEXT:  store i32 %call, ptr @_ZL1i  
Index: clang/test/CXX/module/module.import/p6.cpp
===
--- /dev/null
+++ clang/test/CXX/module/module.import/p6.cpp
@@ -0,0 +1,24 @@
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+
+// RUN: %clang_cc1 -std=c++20 -x c++-header %t/bad-header-unit.h \
+// RUN:  -emit-header-unit -o %t/bad-header-unit.pcm -verify
+
+//--- bad-header-unit.h
+
+inline int ok_foo () { return 0;}
+
+static int ok_bar ();
+
+int ok_decl ();
+
+int bad_def () { return 2;}  // expected-error {{non-inline external definitions are not permitted in C++ header units}}
+
+inline int ok_inline_var = 1;
+
+static int ok_static_var;
+
+int ok_var_decl;
+
+int bad_var_definition = 3;  // expected-error {{non-inline external definitions are not permitted in C++ header units}}
+
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -12952,6 +12952,17 @@
   VDecl->setInvalidDecl();
   }
 
+  // C++ [module.import/6] external definitions are not permitted in header
+  // units.
+  if (getLangOpts().CPlusPlus20 && getLangOpts().CPlusPlusModules &&
+  !ModuleScopes.empty() && ModuleScopes.back().Module->isHeaderUnit()) {
+if (VDecl->getFormalLinkage() == Linkage::ExternalLinkage &&
+!VDecl->isInline()) {
+  Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
+  VDecl->setInvalidDecl();
+}
+  }
+
   // If adding the initializer will turn this declaration into a definition,
   // and we already have a definition for this variable, diagnose or otherwise
   // handle the situation.
@@ -15100,6 +15111,17 @@
 }
   }
 
+  // C++ [module.import/6] external definitions are not permitted in header
+  // units.
+  if (getLangOpts().CPlusPlus20 && getLangOpts().CPlusPlusModules &&
+  !ModuleScopes.empty() && ModuleScopes.back().Module->isHeaderUnit()) {
+if (FD->getFormalLinkage() == Linkage::ExternalLinkage &&
+!FD->isInlined()) {
+  Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
+  FD->setInvalidDecl();
+}
+  }
+
   // Ensure that the function's exception specification is instantiated.
   if (const FunctionProtoType *FPT = FD->getType()->getAs())
 ResolveExceptionSpec(D->getLocation(), FPT);
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -11233,6 +11233,8 @@
   "add 'export' here if this is intended to be a module interface unit">;
 def err_invalid_module_name : Error<
   "%0 is %select{an invalid|a reserved}1 name for a module">;
+def err_extern_def_in_header_unit : Error<
+  "non-inline external definitions are not permitted in C++ header units">;
 
 def ext_equivalent_internal_linkage_decl_in_modules : ExtWarn<
   "ambiguous use of internal linkage declaration %0 defined in multiple modules">,
___
cfe-commits mailing list

[PATCH] D139701: [Clang] Don't emit "min-legal-vector-width"="0" for AMDGPU

2022-12-17 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei added a comment.

In D139701#3993446 , @arsenm wrote:

> TargetCodeGenInfo::setTargetAttributes already exists as a place for targets 
> to emit their custom attributes, x86 could emit it there

It's an attractive suggestion. But it's not easy to move it into target code 
because the value is not a static one but calculated during codegen. As I 
explained in LangRef, the value is `max(maxVectorWidthInArgsRet(CurFn), 
maxVectorWidthInArgsRet(Callee0), maxVectorWidthInArgsRet(Callee1), ...)`. We 
may need to copy/paste a lot of codegen code there to achieve the same goal.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139701

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


[PATCH] D137817: [clangd] Improve action `RemoveUsingNamespace` for user-defined literals

2022-12-17 Thread Vincent Hong via Phabricator via cfe-commits
v1nh1shungry updated this revision to Diff 483749.
v1nh1shungry added a comment.

Note:
Currently if there are user-defined literals, this patch will find them and get 
their
`CompoundStmt` parents. If there is one, it will record the parent so that it 
can add the
using-declaration in it later. If there is not, it means the user-defined 
literal is in
the top-level, and it is reasonable to do nothing for it. I choose 
`CompoundStmt` because
it covers many cases, like blocks, functions, lambdas.

Since I failed to find a way to use only `ReferenceLoc` to get the parents, I 
have to
traverse the whole `Decl` again to find out the `DeclRefExpr` and then use 
`ASTContext`
to get its parents. Also this implementation can cause redundance in some cases.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137817

Files:
  clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
  clang-tools-extra/clangd/unittests/tweaks/RemoveUsingNamespaceTests.cpp

Index: clang-tools-extra/clangd/unittests/tweaks/RemoveUsingNamespaceTests.cpp
===
--- clang-tools-extra/clangd/unittests/tweaks/RemoveUsingNamespaceTests.cpp
+++ clang-tools-extra/clangd/unittests/tweaks/RemoveUsingNamespaceTests.cpp
@@ -250,20 +250,33 @@
 foo + 10;
   }
 )cpp"},
-  {// Does not qualify user-defined literals
-   R"cpp(
-  namespace ns {
-  long double operator "" _w(long double);
+  {
+  R"cpp(
+  namespace a {
+  long double operator""_a(long double);
+  inline namespace b {
+  long double operator""_b(long double);
+  } // namespace b
+  } // namespace a
+  using namespace ^a;
+  int main() {
+1.0_a;
+1.0_b;
   }
-  using namespace n^s;
-  int main() { 1.5_w; }
 )cpp",
-   R"cpp(
-  namespace ns {
-  long double operator "" _w(long double);
-  }
+  R"cpp(
+  namespace a {
+  long double operator""_a(long double);
+  inline namespace b {
+  long double operator""_b(long double);
+  } // namespace b
+  } // namespace a
   
-  int main() { 1.5_w; }
+  int main() {using a::operator""_a;
+using a::operator""_b;
+1.0_a;
+1.0_b;
+  }
 )cpp"}};
   for (auto C : Cases)
 EXPECT_EQ(C.second, apply(C.first)) << C.first;
Index: clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp
@@ -13,6 +13,7 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclBase.h"
 #include "clang/AST/DeclCXX.h"
+#include "clang/AST/ParentMapContext.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Tooling/Core/Replacement.h"
@@ -101,6 +102,62 @@
   return D;
 }
 
+using UserDefinedLiteralSet = llvm::SmallPtrSet;
+
+void handleUserDefinedLiterals(
+Decl *D, const UserDefinedLiteralSet ,
+std::map , ASTContext ) {
+  struct Visitor : RecursiveASTVisitor {
+Visitor(const UserDefinedLiteralSet ,
+std::map ,
+ASTContext )
+: Literals{Literals}, Result{Result}, Ctx{Ctx} {}
+
+const UserDefinedLiteralSet 
+std::map 
+ASTContext 
+
+bool VisitDeclRefExpr(DeclRefExpr *DRE) {
+  const NamedDecl *ND = DRE->getFoundDecl();
+  // If DRE references to a user-defined literal
+  if (ND->getDeclName().getNameKind() ==
+  DeclarationName::CXXLiteralOperatorName) {
+for (const NamedDecl *Literal : Literals) {
+  if (ND == Literal) {
+// If the user-defined literal locates in a CompoundStmt,
+// we mark the CompoundStmt so that we can add the using-declaration
+// in it later. If not, the user-defined literal is used in the
+// top-level, it is reasonable to do nothing for it.
+if (const CompoundStmt *CS = getCompoundParent(DRE))
+  Result[CS->getLBracLoc()].insert(ND);
+return true;
+  }
+}
+  }
+  return true;
+}
+
+// Get the closet CompoundStmt parent of DRE
+const CompoundStmt *getCompoundParent(DeclRefExpr *DRE) {
+  DynTypedNodeList Parents = Ctx.getParents(*DRE);
+  llvm::SmallVector NodesToProcess{Parents.begin(),
+Parents.end()};
+  while (!NodesToProcess.empty()) {
+DynTypedNode Node = NodesToProcess.back();
+NodesToProcess.pop_back();
+if (const auto *CS = Node.get())
+  return CS;
+Parents = Ctx.getParents(Node);
+NodesToProcess.append(Parents.begin(), Parents.end());
+  }
+  return nullptr;
+}
+  };
+
+  Visitor V{Literals, Result, 

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

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

In D138037#4003121 , @vabridgers 
wrote:

> Hi @steakhal, thanks for the suggested change.
> How we can help move this forward? From what I'm comprehending from the 
> notes, perhaps we could try running this change through our internal systems 
> level test and fuzzer. Unfortunately, I'd not be able to say more than "trust 
> me, we saw no problems" if we see no problems. But if I do find additional 
> cases I can make simplified reproducers and we can work on addressing those.
> Best!

Well, I totally forgot about this change. I think we could evaluate if keeping 
alive the representatives would help or not.
However, I cannot push this. I dont have the bandwidth.

I'd be interrested to see other crashing cases you mentioned.
Keep me informed.


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] D137944: [ObjC][ARC] Teach the OptimizeSequences step of ObjCARCOpts about WinEH funclet tokens

2022-12-17 Thread Stefan Gränitz via Phabricator via cfe-commits
sgraenitz added a comment.

Thanks for taking a look. That' really useful feedback! Yes, the coloring can 
be expensive and we shouldn't run it more than once.

and there's more places indeed

until it either stops making changes or

  // no retain+release pair nesting is detected




Comment at: llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp:767
+const ColorVector  = BlockColors.find(BB)->second;
+assert(CV.size() == 1 && "non-unique color for block!");
+BasicBlock *EHPadBB = CV.front();

ahatanak wrote:
> sgraenitz wrote:
> > rnk wrote:
> > > I don't think the verifier changes you made guarantee this. I would 
> > > consider strengthening this to `report_fatal_error`, since valid IR 
> > > transforms can probably reach this code.
> > Right, I guess the Verifier change is correct and this should change to 
> > work for multi-color BBs?
> > ```
> >   assert(CV.size() > 0 && "Uncolored block");
> >   for (BasicBlock *EHPadBB : CV)
> > if (auto *EHPad = 
> > dyn_cast(ColorFirstBB->getFirstNonPHI())) {
> >   OpBundles.emplace_back("funclet", EHPad);
> >   break;
> > }
> > ```
> > 
> > There is no test that covers this case, but it appears that the unique 
> > color invariant only holds **after** WinEHPrepare. [The assertion 
> > here](https://github.com/llvm/llvm-project/blob/release/15.x/llvm/lib/CodeGen/WinEHPrepare.cpp#L185)
> >  seems to imply it:
> > ```
> > assert(BBColors.size() == 1 && "multi-color BB not removed by preparation");
> > ```
> > 
> > Since it would be equivalent to the Verifier check, I'd stick with the 
> > assertion and not report a fatal error.
> Is the assertion `assert(CV.size() == 1 && "non-unique color for block!");` 
> in `CloneCallInstForBB` incorrect too?
The code path disappears with the subsequent patch D137945. But yes, it's 
formally incorrect and I adjusted the assertion in the last iteration.



Comment at: llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp:2040-2041
+  DenseMap BlockColors;
+  if (F.hasPersonalityFn() &&
+  isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn(
+BlockColors = colorEHFunclets(F);

ahatanak wrote:
> sgraenitz wrote:
> > rnk wrote:
> > > I think this code snippet probably deserves a Function helper, 
> > > `F->hasScopedEHPersonality()`. Another part of me thinks we should cache 
> > > the personality enum similar to the way we cache intrinsic ids, but I 
> > > wouldn't want to increase Function memory usage, so that seems premature. 
> > > "No action required", I guess.
> > It doesn't really fit the the scope of this patch but I am happy to add the 
> > helper function in a follow-up (for now without personality enum caching).
> `OptimizeIndividualCall` calls `colorEHFunclets` too. Is it possible to just 
> call it once? Or we don't care because it's not expensive?
Good catch! Right, we shouldn't do it multiple times. Having moved funclet 
coloring into `ObjCARCOpt::init()` it now runs only once.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137944

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


[PATCH] D137944: [ObjC][ARC] Teach the OptimizeSequences step of ObjCARCOpts about WinEH funclet tokens

2022-12-17 Thread Stefan Gränitz via Phabricator via cfe-commits
sgraenitz updated this revision to Diff 483745.
sgraenitz marked 2 inline comments as done.
sgraenitz added a comment.

Address feedback


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137944

Files:
  clang/test/CodeGenObjCXX/arc-exceptions-seh.mm
  llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
  llvm/test/Transforms/ObjCARC/funclet-catchpad.ll

Index: llvm/test/Transforms/ObjCARC/funclet-catchpad.ll
===
--- /dev/null
+++ llvm/test/Transforms/ObjCARC/funclet-catchpad.ll
@@ -0,0 +1,40 @@
+; RUN: opt -mtriple=x86_64-windows-msvc -passes=objc-arc -S < %s | FileCheck %s
+
+; Check that funclet tokens are preserved
+;
+; CHECK-LABEL:  catch:
+; CHECK:  %1 = catchpad within %0
+; CHECK:  %2 = tail call ptr @llvm.objc.retain(ptr %exn) #0 [ "funclet"(token %1) ]
+; CHECK:  call void @llvm.objc.release(ptr %exn) #0 [ "funclet"(token %1) ]
+; CHECK:  catchret from %1 to label %eh.cont
+
+define void @try_catch_with_objc_intrinsic() personality ptr @__CxxFrameHandler3 {
+entry:
+  %exn.slot = alloca ptr, align 8
+  invoke void @may_throw(ptr null) to label %eh.cont unwind label %catch.dispatch
+
+catch.dispatch:   ; preds = %entry
+  %0 = catchswitch within none [label %catch] unwind to caller
+
+eh.cont:  ; preds = %catch, %entry
+  ret void
+
+catch:; preds = %catch.dispatch
+  %1 = catchpad within %0 [ptr null, i32 0, ptr %exn.slot]
+  br label %if.then
+
+if.then:  ; preds = %catch
+  %exn = load ptr, ptr null, align 8
+  %2 = call ptr @llvm.objc.retain(ptr %exn) [ "funclet"(token %1) ]
+  call void @may_throw(ptr %exn)
+  call void @llvm.objc.release(ptr %exn) [ "funclet"(token %1) ]
+  catchret from %1 to label %eh.cont
+}
+
+declare void @may_throw(ptr)
+declare i32 @__CxxFrameHandler3(...)
+
+declare ptr @llvm.objc.retain(ptr) #0
+declare void @llvm.objc.release(ptr) #0
+
+attributes #0 = { nounwind }
Index: llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
===
--- llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
+++ llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
@@ -502,6 +502,8 @@
   /// is in fact used in the current function.
   unsigned UsedInThisFunction;
 
+  DenseMap BlockEHColors;
+
   bool OptimizeRetainRVCall(Function , Instruction *RetainRV);
   void OptimizeAutoreleaseRVCall(Function , Instruction *AutoreleaseRV,
  ARCInstKind );
@@ -509,17 +511,16 @@
 
   /// Optimize an individual call, optionally passing the
   /// GetArgRCIdentityRoot if it has already been computed.
-  void OptimizeIndividualCallImpl(
-  Function , DenseMap ,
-  Instruction *Inst, ARCInstKind Class, const Value *Arg);
+  void OptimizeIndividualCallImpl(Function , Instruction *Inst,
+  ARCInstKind Class, const Value *Arg);
 
   /// Try to optimize an AutoreleaseRV with a RetainRV or UnsafeClaimRV.  If the
   /// optimization occurs, returns true to indicate that the caller should
   /// assume the instructions are dead.
-  bool OptimizeInlinedAutoreleaseRVCall(
-  Function , DenseMap ,
-  Instruction *Inst, const Value *, ARCInstKind Class,
-  Instruction *AutoreleaseRV, const Value *);
+  bool OptimizeInlinedAutoreleaseRVCall(Function , Instruction *Inst,
+const Value *, ARCInstKind Class,
+Instruction *AutoreleaseRV,
+const Value *);
 
   void CheckForCFGHazards(const BasicBlock *BB,
   DenseMap ,
@@ -567,12 +568,46 @@
 
   void OptimizeReturns(Function );
 
+  Instruction *cloneCallInstForBB(CallInst , BasicBlock ) {
+SmallVector OpBundles;
+for (unsigned I = 0, E = CI.getNumOperandBundles(); I != E; ++I) {
+  auto Bundle = CI.getOperandBundleAt(I);
+  // Funclets will be reassociated in the future.
+  if (Bundle.getTagID() == LLVMContext::OB_funclet)
+continue;
+  OpBundles.emplace_back(Bundle);
+}
+
+if (!BlockEHColors.empty()) {
+  const ColorVector  = BlockEHColors.find()->second;
+  assert(CV.size() > 0 && "non-unique color for block!");
+  Instruction *EHPad = CV.front()->getFirstNonPHI();
+  if (EHPad->isEHPad())
+OpBundles.emplace_back("funclet", EHPad);
+}
+
+return CallInst::Create(, OpBundles);
+  }
+
+  void addOpBundleForFunclet(BasicBlock *BB,
+ SmallVectorImpl ) {
+if (!BlockEHColors.empty()) {
+  const ColorVector  = BlockEHColors.find(BB)->second;
+  assert(CV.size() > 0 && "Uncolored block");
+  for (BasicBlock *EHPadBB : CV)
+if (auto *EHPad = 

[PATCH] D139073: [X86] AMD Zen 4 Initial enablement

2022-12-17 Thread Ganesh Gopalasubramanian 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 rG1f057e365f1f: [X86] AMD Zen 4 Initial enablement (authored 
by GGanesh).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139073

Files:
  clang/lib/Basic/Targets/X86.cpp
  clang/test/CodeGen/target-builtin-noerror.c
  clang/test/Driver/x86-march.c
  clang/test/Frontend/x86-target-cpu.c
  clang/test/Misc/target-invalid-cpu-note.c
  clang/test/Preprocessor/predefined-arch-macros.c
  compiler-rt/lib/builtins/cpu_model.c
  llvm/include/llvm/Support/X86TargetParser.h
  llvm/lib/Support/Host.cpp
  llvm/lib/Support/X86TargetParser.cpp
  llvm/lib/Target/X86/X86.td
  llvm/lib/Target/X86/X86PfmCounters.td
  llvm/test/CodeGen/X86/cpus-amd.ll
  llvm/test/CodeGen/X86/rdpru.ll
  llvm/test/CodeGen/X86/slow-unaligned-mem.ll
  llvm/test/CodeGen/X86/sqrt-fastmath-tune.ll
  llvm/test/CodeGen/X86/vector-shuffle-fast-per-lane.ll
  llvm/test/CodeGen/X86/x86-64-double-shifts-var.ll
  llvm/test/MC/X86/x86_long_nop.s

Index: llvm/test/MC/X86/x86_long_nop.s
===
--- llvm/test/MC/X86/x86_long_nop.s
+++ llvm/test/MC/X86/x86_long_nop.s
@@ -17,6 +17,8 @@
 # RUN: llvm-mc -filetype=obj -arch=x86 -triple=i686-pc-linux-gnu %s -mcpu=znver2 | llvm-objdump -d --no-show-raw-insn - | FileCheck %s --check-prefix=LNOP15
 # RUN: llvm-mc -filetype=obj -arch=x86 -triple=x86_64-pc-linux-gnu -mcpu=znver3 %s | llvm-objdump -d --no-show-raw-insn - | FileCheck %s --check-prefix=LNOP15
 # RUN: llvm-mc -filetype=obj -arch=x86 -triple=i686-pc-linux-gnu %s -mcpu=znver3 | llvm-objdump -d --no-show-raw-insn - | FileCheck %s --check-prefix=LNOP15
+# RUN: llvm-mc -filetype=obj -arch=x86 -triple=x86_64-pc-linux-gnu -mcpu=znver4 %s | llvm-objdump -d --no-show-raw-insn - | FileCheck %s --check-prefix=LNOP15
+# RUN: llvm-mc -filetype=obj -arch=x86 -triple=i686-pc-linux-gnu %s -mcpu=znver4 | llvm-objdump -d --no-show-raw-insn - | FileCheck %s --check-prefix=LNOP15
 # RUN: llvm-mc -filetype=obj -arch=x86 -triple=i686-pc-linux-gnu -mcpu=nehalem %s | llvm-objdump -d --no-show-raw-insn - | FileCheck --check-prefix=LNOP10 %s
 # RUN: llvm-mc -filetype=obj -arch=x86 -triple=i686-pc-linux-gnu -mcpu=westmere %s | llvm-objdump -d --no-show-raw-insn - | FileCheck --check-prefix=LNOP10 %s
 # RUN: llvm-mc -filetype=obj -arch=x86 -triple=i686-pc-linux-gnu -mcpu=sandybridge %s | llvm-objdump -d --no-show-raw-insn - | FileCheck --check-prefix=LNOP15 %s
Index: llvm/test/CodeGen/X86/x86-64-double-shifts-var.ll
===
--- llvm/test/CodeGen/X86/x86-64-double-shifts-var.ll
+++ llvm/test/CodeGen/X86/x86-64-double-shifts-var.ll
@@ -15,6 +15,7 @@
 ; RUN: llc < %s -mtriple=x86_64-- -mcpu=znver1 | FileCheck %s
 ; RUN: llc < %s -mtriple=x86_64-- -mcpu=znver2 | FileCheck %s
 ; RUN: llc < %s -mtriple=x86_64-- -mcpu=znver3 | FileCheck %s
+; RUN: llc < %s -mtriple=x86_64-- -mcpu=znver4 | FileCheck %s
 
 ; Verify that for the X86_64 processors that are known to have poor latency
 ; double precision shift instructions we do not generate 'shld' or 'shrd'
Index: llvm/test/CodeGen/X86/vector-shuffle-fast-per-lane.ll
===
--- llvm/test/CodeGen/X86/vector-shuffle-fast-per-lane.ll
+++ llvm/test/CodeGen/X86/vector-shuffle-fast-per-lane.ll
@@ -7,6 +7,7 @@
 ; RUN: llc < %s -mtriple=x86_64-unknown -mcpu=znver1 | FileCheck %s --check-prefixes=FAST
 ; RUN: llc < %s -mtriple=x86_64-unknown -mcpu=znver2 | FileCheck %s --check-prefixes=FAST
 ; RUN: llc < %s -mtriple=x86_64-unknown -mcpu=znver3 | FileCheck %s --check-prefixes=FAST
+; RUN: llc < %s -mtriple=x86_64-unknown -mcpu=znver4 | FileCheck %s --check-prefixes=FAST
 ; RUN: llc < %s -mtriple=x86_64-unknown -mcpu=haswell | FileCheck %s --check-prefixes=FAST
 ; RUN: llc < %s -mtriple=x86_64-unknown -mcpu=skx | FileCheck %s --check-prefixes=FAST
 
Index: llvm/test/CodeGen/X86/sqrt-fastmath-tune.ll
===
--- llvm/test/CodeGen/X86/sqrt-fastmath-tune.ll
+++ llvm/test/CodeGen/X86/sqrt-fastmath-tune.ll
@@ -5,6 +5,7 @@
 ; RUN: llc < %s -mtriple=x86_64-- -mcpu=skylake | FileCheck %s --check-prefixes=FAST-SCALAR,FAST-VECTOR
 ; RUN: llc < %s -mtriple=x86_64-- -mcpu=znver1  | FileCheck %s --check-prefixes=FAST-SCALAR,FAST-VECTOR
 ; RUN: llc < %s -mtriple=x86_64-- -mcpu=znver3  | FileCheck %s --check-prefixes=FAST-SCALAR,FAST-VECTOR
+; RUN: llc < %s -mtriple=x86_64-- -mcpu=znver4  | FileCheck %s --check-prefixes=FAST-SCALAR,FAST-VECTOR
 ; RUN: llc < %s -mtriple=x86_64-- -mcpu=x86-64  | FileCheck %s --check-prefixes=X86-64
 
 define float @f32_no_daz(float %f) #0 {
Index: llvm/test/CodeGen/X86/slow-unaligned-mem.ll
===

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

2022-12-17 Thread Vince Bridgers via Phabricator via cfe-commits
vabridgers added a comment.

Hi @steakhal, thanks for the suggested change.
How we can help move this forward? From what I'm comprehending from the notes, 
perhaps we could try running this change through our internal systems level 
test and fuzzer. Unfortunately, I'd not be able to say more than "trust me, we 
saw no problems" if we see no problems. But if I do find additional cases I can 
make simplified reproducers and we can work on addressing those.
Best!


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] D139837: [Clang] Implements CTAD for aggregates P1816R0 and P2082R1

2022-12-17 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen updated this revision to Diff 483735.
ychen added a comment.

- update cxx_status.html


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139837

Files:
  clang/include/clang/AST/DeclBase.h
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Sema/TemplateDeduction.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/Decl.cpp
  clang/lib/Sema/SemaInit.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/test/SemaTemplate/aggregate-deduction-candidate.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1241,7 +1241,7 @@
 
   Class template argument deduction for aggregates
   https://wg21.link/p1816r0;>P1816R0
-  No
+  Clang 16
 

 https://wg21.link/p2082r1;>P2082R1
Index: clang/test/SemaTemplate/aggregate-deduction-candidate.cpp
===
--- /dev/null
+++ clang/test/SemaTemplate/aggregate-deduction-candidate.cpp
@@ -0,0 +1,297 @@
+// RUN: %clang_cc1 -std=c++20 -verify -ast-dump -ast-dump-decl-types -ast-dump-filter "deduction guide" %s | FileCheck %s --strict-whitespace
+
+namespace Basic {
+  template struct A {
+T x;
+T y;
+  };
+
+  A a1{3.0, 4.0};
+  A a2{.x = 3.0, .y = 4.0};
+
+  // CHECK-LABEL: Dumping Basic:::
+  // CHECK: FunctionTemplateDecl {{.*}} implicit 
+  // CHECK: |-TemplateTypeParmDecl {{.*}} referenced class depth 0 index 0 T
+  // CHECK: |-CXXDeductionGuideDecl {{.*}} implicit  'auto (T, T) -> A'
+  // CHECK: | |-ParmVarDecl {{.*}} 'T'
+  // CHECK: | `-ParmVarDecl {{.*}} 'T'
+  // CHECK: `-CXXDeductionGuideDecl {{.*}} implicit used  'auto (double, double) -> Basic::A'
+  // CHECK:   |-TemplateArgument type 'double'
+  // CHECK:   | `-BuiltinType {{.*}} 'double'
+  // CHECK:   |-ParmVarDecl {{.*}} 'double':'double'
+  // CHECK:   `-ParmVarDecl {{.*}} 'double':'double'
+  // CHECK: FunctionProtoType {{.*}} 'auto (T, T) -> A' dependent trailing_return cdecl
+  // CHECK: |-InjectedClassNameType {{.*}} 'A' dependent
+  // CHECK: | `-CXXRecord {{.*}} 'A'
+  // CHECK: |-TemplateTypeParmType {{.*}} 'T' dependent depth 0 index 0
+  // CHECK: | `-TemplateTypeParm {{.*}} 'T'
+  // CHECK: `-TemplateTypeParmType {{.*}} 'T' dependent depth 0 index 0
+  // CHECK:   `-TemplateTypeParm {{.*}} 'T'
+
+  template  struct S {
+T x;
+T y;
+  };
+
+  template  struct C { // expected-note 5 {{candidate}}
+S s;
+T t;
+  };
+
+  template  struct D { // expected-note 3 {{candidate}}
+S s;
+T t;
+  };
+
+  C c1 = {1, 2}; // expected-error {{no viable}}
+  C c2 = {1, 2, 3}; // expected-error {{no viable}}
+  C c3 = {{1u, 2u}, 3};
+
+  D d1 = {1, 2}; // expected-error {{no viable}}
+  D d2 = {1, 2, 3};
+
+  // CHECK-LABEL: Dumping Basic:::
+  // CHECK: FunctionTemplateDecl {{.*}} implicit 
+  // CHECK: |-TemplateTypeParmDecl {{.*}} referenced typename depth 0 index 0 T
+  // CHECK: |-CXXDeductionGuideDecl {{.*}} implicit  'auto (S, T) -> C'
+  // CHECK: | |-ParmVarDecl {{.*}} 'S':'S'
+  // CHECK: | `-ParmVarDecl {{.*}} 'T'
+  // CHECK: `-CXXDeductionGuideDecl {{.*}} implicit used  'auto (S, int) -> Basic::C'
+  // CHECK:   |-TemplateArgument type 'int'
+  // CHECK:   | `-BuiltinType {{.*}} 'int'
+  // CHECK:   |-ParmVarDecl {{.*}} 'S':'Basic::S'
+  // CHECK:   `-ParmVarDecl {{.*}} 'int':'int'
+  // CHECK: FunctionProtoType {{.*}} 'auto (S, T) -> C' dependent trailing_return cdecl
+  // CHECK: |-InjectedClassNameType {{.*}} 'C' dependent
+  // CHECK: | `-CXXRecord {{.*}} 'C'
+  // CHECK: |-ElaboratedType {{.*}} 'S' sugar dependent
+  // CHECK: | `-TemplateSpecializationType {{.*}} 'S' dependent S
+  // CHECK: |   `-TemplateArgument type 'T'
+  // CHECK: | `-TemplateTypeParmType {{.*}} 'T' dependent depth 0 index 0
+  // CHECK: |   `-TemplateTypeParm {{.*}} 'T'
+  // CHECK: `-TemplateTypeParmType {{.*}} 'T' dependent depth 0 index 0
+  // CHECK:   `-TemplateTypeParm {{.*}} 'T'
+
+  // CHECK-LABEL: Dumping Basic:::
+  // CHECK: FunctionTemplateDecl {{.*}} implicit 
+  // CHECK: |-TemplateTypeParmDecl {{.*}} referenced typename depth 0 index 0 T
+  // CHECK: `-CXXDeductionGuideDecl {{.*}} implicit  'auto (int, int) -> D'
+  // CHECK:   |-ParmVarDecl {{.*}} 'int':'int'
+  // CHECK:   `-ParmVarDecl {{.*}} 'int':'int'
+  // CHECK: FunctionProtoType {{.*}} 'auto (int, int) -> D' dependent trailing_return cdecl
+  // CHECK: |-InjectedClassNameType {{.*}} 'D' dependent
+  // CHECK: | `-CXXRecord {{.*}} 'D'
+  // CHECK: |-SubstTemplateTypeParmType {{.*}} 'int' sugar typename depth 0 index 0 T
+  // CHECK: | 

[PATCH] D140218: [update_cc_test_checks] Default to --function-signature for new tests

2022-12-17 Thread Alexander Richardson via Phabricator via cfe-commits
arichardson added a comment.

In D140218#4001835 , @jdoerfert wrote:

> I don't understand why we would remove the flag for _cc_. I feel all these 
> patches are going exactly in the opposite direction I would think one would 
> go.

The flag is not being removed it's just inside common.py now (see D140212 
) and defaults to on for new tests without 
the auto-generated note.




Comment at: 
clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp.expected:3
 // 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
 

arsenm wrote:
> Why do we still have generated tests using -no-opaque-pointers? Surely that's 
> the lowest hanging fruit?
Good question, I can update this as a separate NFC change on Monday.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140218

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


[clang] 1e6adba - [clang] llvm::Optional::value => operator*/operator->

2022-12-17 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2022-12-17T08:10:45Z
New Revision: 1e6adbadc77517037cb0723df26510fb7a8457ec

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

LOG: [clang] llvm::Optional::value => operator*/operator->

std::optional::value() has undesired exception checking semantics and is
unavailable in older Xcode (see _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS). The
call sites block std::optional migration.

This makes `ninja check-clang` work in the absence of llvm::Optional::value.

Added: 


Modified: 
clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
clang/tools/libclang/CIndex.cpp
clang/unittests/Lex/HeaderSearchTest.cpp

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp 
b/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
index b112059693e85..2bdb1cdcc9534 100644
--- a/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
+++ b/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
@@ -36,7 +36,7 @@ buildStmtToBasicBlockMap(const CFG ) {
   if (!Stmt)
 continue;
 
-  StmtToBlock[Stmt.value().getStmt()] = Block;
+  StmtToBlock[Stmt->getStmt()] = Block;
 }
 if (const Stmt *TerminatorStmt = Block->getTerminatorStmt())
   StmtToBlock[TerminatorStmt] = Block;

diff  --git a/clang/lib/Analysis/FlowSensitive/DebugSupport.cpp 
b/clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
index 1e3ecf46e3112..d4886f154b339 100644
--- a/clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
@@ -185,7 +185,7 @@ Constraints
 
 auto StatusString = clang::dataflow::debugString(Result.getStatus());
 auto Solution = Result.getSolution();
-auto SolutionString = Solution ? "\n" + debugString(Solution.value()) : "";
+auto SolutionString = Solution ? "\n" + debugString(*Solution) : "";
 
 return formatv(
 Template,

diff  --git a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp 
b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
index 5c885680207d7..ced016f1be035 100644
--- a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -262,7 +262,7 @@ computeBlockInputState(const CFGBlock , 
AnalysisContext ) {
 if (!MaybePredState)
   continue;
 
-TypeErasedDataflowAnalysisState PredState = MaybePredState.value();
+TypeErasedDataflowAnalysisState PredState = *MaybePredState;
 if (BuiltinTransferOpts) {
   if (const Stmt *PredTerminatorStmt = Pred->getTerminatorStmt()) {
 const StmtToEnvMapImpl StmtToEnv(AC.CFCtx, AC.BlockStates);

diff  --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp
index f99275e4f243c..9958671e03a18 100644
--- a/clang/tools/libclang/CIndex.cpp
+++ b/clang/tools/libclang/CIndex.cpp
@@ -538,7 +538,7 @@ bool CursorVisitor::VisitChildren(CXCursor Cursor) {
 const Optional V = handleDeclForVisitation(*TL);
 if (!V)
   continue;
-return V.value();
+return *V;
   }
 } else if (VisitDeclContext(
CXXUnit->getASTContext().getTranslationUnitDecl()))
@@ -643,7 +643,7 @@ bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
 const Optional V = handleDeclForVisitation(D);
 if (!V)
   continue;
-return V.value();
+return *V;
   }
   return false;
 }
@@ -677,7 +677,7 @@ Optional CursorVisitor::handleDeclForVisitation(const 
Decl *D) {
   const Optional V = shouldVisitCursor(Cursor);
   if (!V)
 return std::nullopt;
-  if (!V.value())
+  if (!*V)
 return false;
   if (Visit(Cursor, true))
 return true;
@@ -1076,7 +1076,7 @@ bool 
CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
 const Optional  = shouldVisitCursor(Cursor);
 if (!V)
   continue;
-if (!V.value())
+if (!*V)
   return false;
 if (Visit(Cursor, true))
   return true;

diff  --git a/clang/unittests/Lex/HeaderSearchTest.cpp 
b/clang/unittests/Lex/HeaderSearchTest.cpp
index e67445f1aeadc..b0f4221ad335b 100644
--- a/clang/unittests/Lex/HeaderSearchTest.cpp
+++ b/clang/unittests/Lex/HeaderSearchTest.cpp
@@ -214,7 +214,7 @@ TEST_F(HeaderSearchTest, HeaderFrameworkLookup) {
 
   EXPECT_TRUE(FoundFile.has_value());
   EXPECT_TRUE(IsFrameworkFound);
-  auto  = FoundFile.value();
+  auto  = *FoundFile;
   auto FI = Search.getExistingFileInfo(FE);
   EXPECT_TRUE(FI);
   EXPECT_TRUE(FI->IsValid);
@@ -284,7 +284,7 @@ TEST_F(HeaderSearchTest, HeaderMapFrameworkLookup) {
 
   EXPECT_TRUE(FoundFile.has_value());