[PATCH] D133941: [clang][Interp] Record item types in InterpStack

2022-09-15 Thread Jun Zhang via Phabricator via cfe-commits
junaire added a comment.

Do you think `std::is_same_v` will be even better?


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

https://reviews.llvm.org/D133941

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


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

2022-09-15 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added a comment.

In D132461#3793634 , @njames93 wrote:

> In D132461#3773792 , @carlosgalvezp 
> wrote:
>
>> @njames93 Friendly ping. The patch has addressed all comments and remained 
>> unchanged for 2 weeks. I would like to land it latest next week. If you are 
>> happy with the patch, please accept the review. Alternatively, please let me 
>> know if you intend to continue reviewing.
>
> I do intend, but I'm currently between 2 jobs and accommodation atm, once 
> life settles down next week, I should have more time.

Totally understandable, thanks for the response! Are there other reviewers that 
could review the patch instead, to remove some load off you?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132461

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


[PATCH] D133941: [clang][Interp] Record item types in InterpStack

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

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

https://reviews.llvm.org/D133941

Files:
  clang/lib/AST/Interp/InterpStack.h


Index: clang/lib/AST/Interp/InterpStack.h
===
--- clang/lib/AST/Interp/InterpStack.h
+++ clang/lib/AST/Interp/InterpStack.h
@@ -13,7 +13,9 @@
 #ifndef LLVM_CLANG_AST_INTERP_INTERPSTACK_H
 #define LLVM_CLANG_AST_INTERP_INTERPSTACK_H
 
+#include "PrimType.h"
 #include 
+#include 
 
 namespace clang {
 namespace interp {
@@ -29,10 +31,17 @@
   /// Constructs a value in place on the top of the stack.
   template  void push(Tys &&... Args) {
 new (grow(aligned_size())) T(std::forward(Args)...);
+#ifndef NDEBUG
+ItemTypes.push_back(toPrimType());
+#endif
   }
 
   /// Returns the value from the top of the stack and removes it.
   template  T pop() {
+#ifndef NDEBUG
+assert(ItemTypes.back() == toPrimType());
+ItemTypes.pop_back();
+#endif
 auto *Ptr = &peek();
 auto Value = std::move(*Ptr);
 Ptr->~T();
@@ -42,6 +51,10 @@
 
   /// Discards the top value from the stack.
   template  void discard() {
+#ifndef NDEBUG
+assert(ItemTypes.back() == toPrimType());
+ItemTypes.pop_back();
+#endif
 auto *Ptr = &peek();
 Ptr->~T();
 shrink(aligned_size());
@@ -111,6 +124,45 @@
   StackChunk *Chunk = nullptr;
   /// Total size of the stack.
   size_t StackSize = 0;
+
+#ifndef NDEBUG
+  /// vector recording the type of data we pushed into the stack.
+  std::vector ItemTypes;
+
+  template  static constexpr PrimType toPrimType() {
+if constexpr (std::is_same::value)
+  return PT_Ptr;
+else if constexpr (std::is_same::value ||
+   std::is_same::value)
+  return PT_Bool;
+else if constexpr (std::is_same::value ||
+   std::is_same>::value)
+  return PT_Sint8;
+else if constexpr (std::is_same::value ||
+   std::is_same>::value)
+  return PT_Uint8;
+else if constexpr (std::is_same::value ||
+   std::is_same>::value)
+  return PT_Sint16;
+else if constexpr (std::is_same::value ||
+   std::is_same>::value)
+  return PT_Uint16;
+else if constexpr (std::is_same::value ||
+   std::is_same>::value)
+  return PT_Sint32;
+else if constexpr (std::is_same::value ||
+   std::is_same>::value)
+  return PT_Uint32;
+else if constexpr (std::is_same::value ||
+   std::is_same>::value)
+  return PT_Sint64;
+else if constexpr (std::is_same::value ||
+   std::is_same>::value)
+  return PT_Uint64;
+
+llvm_unreachable("unknown type push()'ed into InterpStack");
+  }
+#endif
 };
 
 } // namespace interp


Index: clang/lib/AST/Interp/InterpStack.h
===
--- clang/lib/AST/Interp/InterpStack.h
+++ clang/lib/AST/Interp/InterpStack.h
@@ -13,7 +13,9 @@
 #ifndef LLVM_CLANG_AST_INTERP_INTERPSTACK_H
 #define LLVM_CLANG_AST_INTERP_INTERPSTACK_H
 
+#include "PrimType.h"
 #include 
+#include 
 
 namespace clang {
 namespace interp {
@@ -29,10 +31,17 @@
   /// Constructs a value in place on the top of the stack.
   template  void push(Tys &&... Args) {
 new (grow(aligned_size())) T(std::forward(Args)...);
+#ifndef NDEBUG
+ItemTypes.push_back(toPrimType());
+#endif
   }
 
   /// Returns the value from the top of the stack and removes it.
   template  T pop() {
+#ifndef NDEBUG
+assert(ItemTypes.back() == toPrimType());
+ItemTypes.pop_back();
+#endif
 auto *Ptr = &peek();
 auto Value = std::move(*Ptr);
 Ptr->~T();
@@ -42,6 +51,10 @@
 
   /// Discards the top value from the stack.
   template  void discard() {
+#ifndef NDEBUG
+assert(ItemTypes.back() == toPrimType());
+ItemTypes.pop_back();
+#endif
 auto *Ptr = &peek();
 Ptr->~T();
 shrink(aligned_size());
@@ -111,6 +124,45 @@
   StackChunk *Chunk = nullptr;
   /// Total size of the stack.
   size_t StackSize = 0;
+
+#ifndef NDEBUG
+  /// vector recording the type of data we pushed into the stack.
+  std::vector ItemTypes;
+
+  template  static constexpr PrimType toPrimType() {
+if constexpr (std::is_same::value)
+  return PT_Ptr;
+else if constexpr (std::is_same::value ||
+   std::is_same::value)
+  return PT_Bool;
+else if constexpr (std::is_same::value ||
+   std::is_same>::value)
+  return PT_Sint8;
+else if constexpr (std::is_same::value ||
+   std::is_same>::value)
+  return PT_Uint8;
+else if constexpr (std::is_same::value ||
+   std::is_same>::value)
+  return PT_Sint16;
+else if constexpr (std::is_same::value ||
+   std::is_same>::value)
+  return PT_Uint16;
+

[PATCH] D133817: MSVC ABI: Looks like even non-aarch64 uses the MSVC/14 definition for pod/aggregate passing

2022-09-15 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a subscriber: majnemer.
dblaikie added a comment.

In D133817#3790057 , @rnk wrote:

> Thanks!
>
>> But I had
>> trouble figuring out how to exercise this functionality properly to add
>> test coverage and then compare that to MSVC itself... - I got very
>> confused/turned around trying to test this, so I've given up enough to
>> send what I have out for review, but happy to look further into this
>> with help.
>
> I think I would take the three cases you found (protected, nsdmi, defaulted 
> copy ctor), add each to this file, and check for the IR prototypes here in 
> this test file. Either sret is used, or it is not.

OK, done that. Removed the other attempt I'd made at the 
protected-field-in-field test case in favor of the one at the end with the 
other two cases, since that seemed clearer.

> Regarding HFAs, I believe that logic is only used on x86/x64 for the 
> __vectorcall calling convention.

Oooh.. hmm, that should help. I'll look around.

> I believe it is well-tested with respect to C-like structs, but the C++ 
> aspects that you are changing are not well tested. I think I managed to 
> construct a case using NSDMIs (Richard used to prefer the terminology 
> "default member initializers" which is simpler): 
> https://godbolt.org/z/daPzKxj3h It looks like we don't match arm64 MSVC's 
> behavior exactly here, but your change to remove the "!isAArch64" test would 
> probably cause us to change behavior in this case, right?

It would change the behavior, but I think in the wrong direction... making 
non-AArch64 behave like the buggy AArch64... hrm.

So I think https://godbolt.org/z/Md91eE8KM demonstrates that the homogenous 
aggregate rules are different for AArch64 from x86_64 - so we aren't going 
to/shouldn't lose the AArch64 check in `isPermittedToBeHomogeneousAggregate`.

But it's also true that the rules are different again from the 
`isTrivialForMSVC` - as per your test with "default member initializers", this 
doesn't seem to change the return ABI, but it does make the (only the AArch64, 
not the x86_64) consider the type non-homogenous-aggregate.

(even though the ways that homogenous aggregate rules are inconsistent with 
`isTrivialForMSVC`, `isTrivialForMSVC` does agree between x86 and AArch64... so 
it suggests that generalizing that function across x86 and AArch64 is correct, 
but if someone wants to fix the AArch64 vectorcall ABI, they will need to do so 
by introducing a separate function, `isHomogenousAggregateForAArch64MSVC` or 
the like)

So, I could leave a test case and some comments, or follow-up with a separate 
fix for the homogenous aggregate issue? I guess it comes down to writing that 
separate function to do the tests. (would be great to throw some of this at the 
ABI fuzzer @majnemer had back in the day, at least I think he had an ABI fuzzer 
of some sort, yeah?)




Comment at: clang/test/CodeGenCXX/microsoft-abi-sret-and-byval.cpp:77
 
+struct SmallWithSmallWithPrivate {
+  SmallWithPrivate p;

rnk wrote:
> I'm amused that this class is passed directly, but if you pass the field by 
> itself, it is passed indirectly. :shrug:
> 
Yeah, isn't that... neat?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133817

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


[PATCH] D133924: add clang_CXXMethod_isDeleted function

2022-09-15 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

Looks like the new version you uploaded is //only// the changes to the last 
version. You need to merge that into your previous commit and upload a patch of 
that. (e.g. using `git rebase -i` or even just `git commit --amend`).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133924

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


[PATCH] D133991: add new function to release notes

2022-09-15 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

In D133991#3793762 , @anderslanglands 
wrote:

> Sorry, this was supposed to update https://reviews.llvm.org/D13392. How do I 
> delete this?

At the bottom of the page, there's a drop-down right above the comment 
textview. Select "Abandon Revision" in it and submit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133991

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


[PATCH] D133934: [clang][Interp] Handle sizeof() expressions

2022-09-15 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 460648.

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

https://reviews.llvm.org/D133934

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

Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -72,10 +72,41 @@
 constexpr const int* getIntPointer() {
   return &m;
 }
-//static_assert(getIntPointer() == &m, ""); TODO
-//static_assert(*getIntPointer() == 10, ""); TODO
+static_assert(getIntPointer() == &m, "");
+static_assert(*getIntPointer() == 10, "");
 
 constexpr int gimme(int k) {
   return k;
 }
-// static_assert(gimme(5) == 5, ""); TODO
+static_assert(gimme(5) == 5, "");
+
+namespace SizeOf {
+  constexpr int soint = sizeof(int);
+  constexpr int souint = sizeof(unsigned int);
+  static_assert(soint == souint, "");
+
+  static_assert(sizeof(&soint) == sizeof(void*), "");
+  static_assert(sizeof(&soint) == sizeof(nullptr), "");
+
+  static_assert(sizeof(long) == sizeof(unsigned long), "");
+  static_assert(sizeof(char) == sizeof(unsigned char), "");
+
+  constexpr int N = 4;
+  constexpr int arr[N] = {1,2,3,4};
+  static_assert(sizeof(arr) == N * sizeof(int), "");
+  static_assert(sizeof(arr) == N * sizeof(arr[0]), "");
+
+  constexpr bool arrB[N] = {true, true, true, true};
+  static_assert(sizeof(arrB) == N * sizeof(bool), "");
+
+  static_assert(sizeof(bool) == 1, "");
+  static_assert(sizeof(char) == 1, "");
+
+  constexpr int F = sizeof(void); // expected-error{{incomplete type 'void'}} \
+  // ref-error{{incomplete type 'void'}}
+
+  constexpr int F2 = sizeof(gimme); // expected-error{{to a function type}} \
+// ref-error{{to a function type}}
+
+
+};
Index: clang/lib/AST/Interp/Opcodes.td
===
--- clang/lib/AST/Interp/Opcodes.td
+++ clang/lib/AST/Interp/Opcodes.td
@@ -427,11 +427,11 @@
 // TODO: Expand this to handle casts between more types.
 
 def FromCastTypeClass : TypeClass {
-  let Types = [Uint32, Sint32, Bool];
+  let Types = [Uint8, Sint8, Uint16, Sint16, Uint32, Sint32, Uint64, Sint64, Bool];
 }
 
 def ToCastTypeClass : TypeClass {
-  let Types = [Uint32, Sint32, Bool];
+  let Types = [Uint8, Sint8, Uint16, Sint16, Uint32, Sint32, Uint64, Sint64, Bool];
 }
 
 def Cast: Opcode {
Index: clang/lib/AST/Interp/ByteCodeExprGen.h
===
--- clang/lib/AST/Interp/ByteCodeExprGen.h
+++ clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -80,6 +80,7 @@
   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
   bool VisitInitListExpr(const InitListExpr *E);
   bool VisitConstantExpr(const ConstantExpr *E);
+  bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
 
 protected:
   bool visitExpr(const Expr *E) override;
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -281,7 +281,24 @@
 }
 
 template 
-bool ByteCodeExprGen::discard(const Expr *E) {
+bool ByteCodeExprGen::VisitUnaryExprOrTypeTraitExpr(
+const UnaryExprOrTypeTraitExpr *E) {
+
+  if (E->getKind() == UETT_SizeOf) {
+QualType ArgType = E->getTypeOfArgument();
+
+if (!ArgType->isConstantSizeType() ||
+ArgType->isDependentType())
+  return false;
+
+return this->emitConst(
+E, Ctx.getASTContext().getTypeSizeInChars(ArgType).getQuantity());
+  }
+
+  return false;
+}
+
+template  bool ByteCodeExprGen::discard(const Expr *E) {
   OptionScope Scope(this, /*NewDiscardResult=*/true);
   return this->Visit(E);
 }
Index: clang/lib/AST/Interp/Boolean.h
===
--- clang/lib/AST/Interp/Boolean.h
+++ clang/lib/AST/Interp/Boolean.h
@@ -48,6 +48,10 @@
   Boolean operator~() const { return Boolean(true); }
 
   explicit operator unsigned() const { return V; }
+  explicit operator int8_t() const { return V; }
+  explicit operator uint8_t() const { return V; }
+  explicit operator int16_t() const { return V; }
+  explicit operator uint16_t() const { return V; }
   explicit operator int64_t() const { return V; }
   explicit operator uint64_t() const { return V; }
   explicit operator int() const { return V; }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D133934: [clang][Interp] Handle sizeof() expressions

2022-09-15 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

I can see that `HandleSizeOf()` uses 1 for void and function types as a gcc 
extension, but I can't reproduce that: https://godbolt.org/z/njG9zh6PM




Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:290
+return this->emitConst(
+E, Ctx.getASTContext().getTypeSizeInChars(ArgType).getQuantity());
+  }

shafik wrote:
> aaron.ballman wrote:
> > erichkeane wrote:
> > > shafik wrote:
> > > > I notice that `HandleSizeof` special cases `void` and function types. 
> > > OOOH, DEFINITELY make sure you test function types here, and figure out 
> > > how HandleSizeof does it.
> > > 
> > > BUT, I think 'void' should error/be an invalid before we get here?
> > > 
> > > ALSO, now that I think further, I'm sure @aaron.ballman has a bunch of 
> > > runtime-evaluated sizeof examples to share around vlas.
> > I was just about to comment about everyone's favorite horrible C++ 
> > extension. :-D We should make sure we properly reject code like:
> > ```
> > void func() {
> >   int n = 12;
> >   constexpr int oofda = sizeof(int[n++]);
> > }
> > ```
> > while accepting code like:
> > ```
> > consteval int foo(int n) {
> >   return sizeof(int[n]);
> > }
> > constinit int var = foo(5);
> > ```
> Note, that clang currently treats that as ill-formed and there is divergence 
> with how gcc and clang treat the `constexpr` case as well.
> 
> So if we are going to say we want this to work then we should file a bug 
> against clang. 
Right, the second example doesn't seem to be accepted by current clang.


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

https://reviews.llvm.org/D133934

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


[PATCH] D133817: MSVC ABI: Looks like even non-aarch64 uses the MSVC/14 definition for pod/aggregate passing

2022-09-15 Thread David Blaikie via Phabricator via cfe-commits
dblaikie updated this revision to Diff 460637.
dblaikie marked an inline comment as done.
dblaikie added a comment.

Add the three test cases. Verified they failed without the patch and pass with 
it. Testing them across all the Windows ABI variants, since they seem to apply 
equally.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133817

Files:
  clang/lib/CodeGen/MicrosoftCXXABI.cpp
  clang/test/CodeGenCXX/microsoft-abi-sret-and-byval.cpp

Index: clang/test/CodeGenCXX/microsoft-abi-sret-and-byval.cpp
===
--- clang/test/CodeGenCXX/microsoft-abi-sret-and-byval.cpp
+++ clang/test/CodeGenCXX/microsoft-abi-sret-and-byval.cpp
@@ -1,8 +1,8 @@
 // RUN: %clang_cc1 -no-opaque-pointers -std=c++11 -emit-llvm %s -o - -triple=i386-pc-linux | FileCheck -check-prefix LINUX %s
-// RUN: %clang_cc1 -no-opaque-pointers -std=c++11 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fno-rtti | FileCheck -check-prefix WIN32 %s
-// RUN: %clang_cc1 -no-opaque-pointers -std=c++11 -emit-llvm %s -o - -triple=thumb-pc-win32 -mconstructor-aliases -fno-rtti | FileCheck -check-prefix WOA %s
-// RUN: %clang_cc1 -no-opaque-pointers -std=c++11 -emit-llvm %s -o - -triple=x86_64-pc-win32 -mconstructor-aliases -fno-rtti | FileCheck -check-prefix WIN64 %s
-// RUN: %clang_cc1 -no-opaque-pointers -std=c++11 -emit-llvm %s -o - -triple=aarch64-windows-msvc -mconstructor-aliases -fno-rtti | FileCheck -check-prefix WOA64 %s
+// RUN: %clang_cc1 -no-opaque-pointers -std=c++11 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fno-rtti | FileCheck -check-prefix WIN32 --check-prefix WIN %s
+// RUN: %clang_cc1 -no-opaque-pointers -std=c++11 -emit-llvm %s -o - -triple=thumb-pc-win32 -mconstructor-aliases -fno-rtti | FileCheck -check-prefix WOA --check-prefix WIN %s
+// RUN: %clang_cc1 -no-opaque-pointers -std=c++11 -emit-llvm %s -o - -triple=x86_64-pc-win32 -mconstructor-aliases -fno-rtti | FileCheck -check-prefix WIN64 --check-prefix WIN %s
+// RUN: %clang_cc1 -no-opaque-pointers -std=c++11 -emit-llvm %s -o - -triple=aarch64-windows-msvc -mconstructor-aliases -fno-rtti | FileCheck -check-prefix WOA64 --check-prefix WIN %s
 
 struct Empty {};
 
@@ -74,6 +74,10 @@
  int i;
 };
 
+struct SmallWithSmallWithPrivate {
+  SmallWithPrivate p;
+};
+
 // WIN32: declare dso_local void @"{{.*take_bools_and_chars.*}}"
 // WIN32:   (<{ i8, [3 x i8], i8, [3 x i8], %struct.SmallWithDtor,
 // WIN32:   i8, [3 x i8], i8, [3 x i8], i32, i8, [3 x i8] }>* inalloca(<{ i8, [3 x i8], i8, [3 x i8], %struct.SmallWithDtor, i8, [3 x i8], i8, [3 x i8], i32, i8, [3 x i8] }>)
@@ -197,6 +201,10 @@
 // WOA64: define dso_local void @"?small_arg_with_private_member@@YA?AUSmallWithPrivate@@U1@@Z"(%struct.SmallWithPrivate* inreg noalias sret(%struct.SmallWithPrivate) align 4 %agg.result, i64 %s.coerce) {{.*}} {
 SmallWithPrivate small_arg_with_private_member(SmallWithPrivate s) { return s; }
 
+// WOA64: define dso_local i32 @"?small_arg_with_small_struct_with_private_member@@YA?AUSmallWithSmallWithPrivate@@U1@@Z"(i64 %s.coerce) {{.*}} {
+// WIN64: define dso_local i32 @"?small_arg_with_small_struct_with_private_member@@YA?AUSmallWithSmallWithPrivate@@U1@@Z"(i32 %s.coerce) {{.*}} {
+SmallWithSmallWithPrivate small_arg_with_small_struct_with_private_member(SmallWithSmallWithPrivate s) { return s; }
+
 void call_small_arg_with_dtor() {
   small_arg_with_dtor(SmallWithDtor());
 }
@@ -468,3 +476,32 @@
 // WIN64-LABEL: define dso_local void @"?g@C@pr30293@@QEAAXXZ"(%"struct.pr30293::C"* {{[^,]*}} %this)
 // WIN64: declare dso_local void @"?h@C@pr30293@@UEAAXUSmallWithDtor@@@Z"(i8* noundef, i32)
 }
+
+namespace protected_member_of_member {
+struct field { protected: int i; };
+struct t1 {
+  field f;
+};
+extern const t1& v1;
+t1 f1() { return v1; }
+// WIN: define dso_local {{.*}}i32 @"?f1@protected_member_of_member@@YA?AUt1@1@XZ"()
+}
+
+namespace default_member_initializer {
+struct t1 {
+  int i = 3;
+};
+extern const t1& v1;
+t1 f1() { return v1; }
+// WIN: define dso_local {{.*}}i32 @"?f1@default_member_initializer@@YA?AUt1@1@XZ"()
+}
+
+namespace defaulted_copy_ctor {
+struct t1 {
+  int i;
+  t1(const t1&) = default;
+};
+extern const t1& v1;
+t1 f1() { return v1; }
+// WIN: define dso_local {{.*}}i32 @"?f1@defaulted_copy_ctor@@YA?AUt1@1@XZ"()
+}
Index: clang/lib/CodeGen/MicrosoftCXXABI.cpp
===
--- clang/lib/CodeGen/MicrosoftCXXABI.cpp
+++ clang/lib/CodeGen/MicrosoftCXXABI.cpp
@@ -1086,8 +1086,8 @@
   return isDeletingDtor(GD);
 }
 
-static bool isTrivialForAArch64MSVC(const CXXRecordDecl *RD) {
-  // For AArch64, we use the C++14 definition of an aggregate, so we also
+static bool isTrivialForMSVC(const CXXRecordDecl *RD) {
+  // We use the C++14 definition of an aggregate, so we also
   // check for:
   //   No private or protected non sta

[PATCH] D133341: [C++] [Coroutines] Prefer aligned (de)allocation for coroutines - implement the option2 of P2014R0

2022-09-15 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/test/SemaCXX/coroutine-alloc-4.cpp:49
+void return_value(int) {}
+void *operator new(std::size_t, std::align_val_t) noexcept;
+void *operator new(std::size_t) noexcept;

ychen wrote:
> ChuanqiXu wrote:
> > ychen wrote:
> > > ChuanqiXu wrote:
> > > > ychen wrote:
> > > > > Like this test case, please add additional test cases to check the 
> > > > > expected look-up order, one test for each consecutive pair should be 
> > > > > good.
> > > > > 
> > > > > ```
> > > > > void* T::operator new  ( std::size_t count, std::align_val_t al, 
> > > > > user-defined-args... );
> > > > > void* T::operator new  ( std::size_t count, std::align_val_t al);
> > > > > void* T::operator new  ( std::size_t count, user-defined-args... );
> > > > > void* T::operator new  ( std::size_t count);
> > > > > void* operator new  ( std::size_t count, std::align_val_t al );
> > > > > ```
> > > > > 
> > > > > 
> > > > Yeah, I'm testing this in CodeGenCoroutines. (It is hard to test the 
> > > > selection in Sema Test)
> > > Thanks for adding the overload. I think the `noexcept` on operator new is 
> > > not necessary. Strictly speaking, it is not a conforming API.
> > The noexcept here is necessary. The specs says the allocation function 
> > should have a noexcept specifier if get_return_object_on_allocation_failure 
> > presents.
> I see. I didn't realize that, before P2014, the way class-specific operator 
> new/delete are looked up is already different between coroutine and regular 
> routine. Basically, with the normal operator new/delete lookup rules, the 
> no-throw and potentially-throw allocation functions may overload, so the 
> throw function type must have `std::throw_t` parameter; with the coroutine 
> operator new/delete lookup rules, the no-throw and potentially-throw 
> allocation functions do not overload since 
> `get_return_object_on_allocation_failure` is either found or not found, thus 
> the `std::throw_t` parameter is not necessary for the potentially-throw 
> allocation function.
> 
Yeah, thanks for the explanation.


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

https://reviews.llvm.org/D133341

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


[clang] 45b85ae - [Driver][test] Disable hip-link-bc-to-bc.hip

2022-09-15 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2022-09-15T21:41:18-07:00
New Revision: 45b85aebdbb08fed26cb5976401cddcf51625533

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

LOG: [Driver][test] Disable hip-link-bc-to-bc.hip

As it was disabled due to unsupported feature "clang-driver" before.

Added: 


Modified: 
clang/test/Driver/hip-link-bc-to-bc.hip

Removed: 




diff  --git a/clang/test/Driver/hip-link-bc-to-bc.hip 
b/clang/test/Driver/hip-link-bc-to-bc.hip
index b331bacf99ed..df858cf15852 100644
--- a/clang/test/Driver/hip-link-bc-to-bc.hip
+++ b/clang/test/Driver/hip-link-bc-to-bc.hip
@@ -1,4 +1,4 @@
-// REQUIRES: x86-registered-target, amdgpu-registered-target
+// REQUIRES: clang-driver, x86-registered-target, amdgpu-registered-target
 
 // Check that clang unbundles the two bitcodes and links via llvm-link
 // RUN: rm -rf %t && mkdir %t



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


[PATCH] D133341: [C++] [Coroutines] Prefer aligned (de)allocation for coroutines - implement the option2 of P2014R0

2022-09-15 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen accepted this revision.
ychen added a comment.
This revision is now accepted and ready to land.

LGTM. Give it a few days in case @rjmccall have comments.




Comment at: clang/test/SemaCXX/coroutine-alloc-4.cpp:49
+void return_value(int) {}
+void *operator new(std::size_t, std::align_val_t) noexcept;
+void *operator new(std::size_t) noexcept;

ChuanqiXu wrote:
> ychen wrote:
> > ChuanqiXu wrote:
> > > ychen wrote:
> > > > Like this test case, please add additional test cases to check the 
> > > > expected look-up order, one test for each consecutive pair should be 
> > > > good.
> > > > 
> > > > ```
> > > > void* T::operator new  ( std::size_t count, std::align_val_t al, 
> > > > user-defined-args... );
> > > > void* T::operator new  ( std::size_t count, std::align_val_t al);
> > > > void* T::operator new  ( std::size_t count, user-defined-args... );
> > > > void* T::operator new  ( std::size_t count);
> > > > void* operator new  ( std::size_t count, std::align_val_t al );
> > > > ```
> > > > 
> > > > 
> > > Yeah, I'm testing this in CodeGenCoroutines. (It is hard to test the 
> > > selection in Sema Test)
> > Thanks for adding the overload. I think the `noexcept` on operator new is 
> > not necessary. Strictly speaking, it is not a conforming API.
> The noexcept here is necessary. The specs says the allocation function should 
> have a noexcept specifier if get_return_object_on_allocation_failure presents.
I see. I didn't realize that, before P2014, the way class-specific operator 
new/delete are looked up is already different between coroutine and regular 
routine. Basically, with the normal operator new/delete lookup rules, the 
no-throw and potentially-throw allocation functions may overload, so the throw 
function type must have `std::throw_t` parameter; with the coroutine operator 
new/delete lookup rules, the no-throw and potentially-throw allocation 
functions do not overload since `get_return_object_on_allocation_failure` is 
either found or not found, thus the `std::throw_t` parameter is not necessary 
for the potentially-throw allocation function.



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

https://reviews.llvm.org/D133341

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


[PATCH] D129824: [RISCV] Set triple based on -march flag which can be deduced in more generic way

2022-09-15 Thread Zixuan Wu via Phabricator via cfe-commits
zixuan-wu added a comment.

AFAIK, --target is clang-specific and transparent for compiler user in RV side. 
-m is also undefined or less used by RV user. It just uses -march to specify 32 
or 64 mode and extensions.
Is the convention specified in RV Spec?


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

https://reviews.llvm.org/D129824

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


[PATCH] D129824: [RISCV] Set triple based on -march flag which can be deduced in more generic way

2022-09-15 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In D129824#3794229 , @jrtc27 wrote:

> In D129824#3794221 , @MaskRay wrote:
>
>> Both D54214  and this look like a 
>> surprising behavior to me. Do we still have time to go back the state before 
>> D54214  and make mismatching --target & 
>> -march= an error?
>
> Then there's no -m32 equivalent; that's what -march currently gives you... 
> also GCC lets you do it. And -target is Clang-specific so you can't write 
> something that works for both compilers.

We can accept `-m32/-m64` as a special case. Other `-m` options

(I edited my previous comment and added a confusing `--target=riscv64 
-march=rv64i -m32` case when you made the comment.)


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

https://reviews.llvm.org/D129824

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


[PATCH] D129824: [RISCV] Set triple based on -march flag which can be deduced in more generic way

2022-09-15 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added a comment.

In D129824#3794221 , @MaskRay wrote:

> Both D54214  and this look like a surprising 
> behavior to me. Do we still have time to go back the state before D54214 
>  and make mismatching --target & -march= an 
> error?

Then there's no -m32 equivalent; that's what -march currently gives you... also 
GCC lets you do it. And -target is Clang-specific so you can't write something 
that works for both compilers.


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

https://reviews.llvm.org/D129824

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


[PATCH] D129824: [RISCV] Set triple based on -march flag which can be deduced in more generic way

2022-09-15 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

Both D54214  and this look like a surprising 
behavior to me. Do we still have time to go back the state before D54214 
 and make mismatching --target & -march= an 
error?

> clang -target=riscv32-- -march=rv64gc

`-target=` => `--target=`


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

https://reviews.llvm.org/D129824

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


[PATCH] D133954: [clang-format] Fix template arguments in macros

2022-09-15 Thread Owen Pan via Phabricator via cfe-commits
owenpan accepted this revision.
owenpan added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:9793-9795
+  verifyFormat("#define FOO(typeName, realClass)   
"
+   "\\\n"
+   "  { #typeName, foo(new foo(#typeName)) }");

And perhaps move it to the end of the test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133954

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


[PATCH] D134007: [Clang][CUDA][NFC] Rename 'addDeviceDepences' to 'addDeviceDependences' in DeviceActionBuilder.

2022-09-15 Thread WangLian via Phabricator via cfe-commits
Jimerlife created this revision.
Jimerlife added reviewers: sfantao, tra, ABataev, benshi001.
Jimerlife added a project: LLVM.
Herald added subscribers: mattd, yaxunl.
Herald added a project: All.
Jimerlife requested review of this revision.
Herald added subscribers: cfe-commits, jacquesguan, MaskRay.
Herald added a project: clang.

I think this method's name maybe `addDeviceDependences` not `addDeviceDepences`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D134007

Files:
  clang/lib/Driver/Driver.cpp


Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -2733,7 +2733,7 @@
 
 /// Update the state to include the provided host action \a HostAction as a
 /// dependency of the current device action. By default it is inactive.
-virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
+virtual ActionBuilderReturnCode addDeviceDependences(Action *HostAction) {
   return ABRT_Inactive;
 }
 
@@ -2821,7 +2821,7 @@
   Action::OffloadKind OFKind)
 : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
 
-ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
+ActionBuilderReturnCode addDeviceDependences(Action *HostAction) override {
   // While generating code for CUDA, we only depend on the host input 
action
   // to trigger the creation of all the CUDA device actions.
 
@@ -3600,7 +3600,7 @@
   if (!SB->isValid())
 continue;
 
-  auto RetCode = SB->addDeviceDepences(HostAction);
+  auto RetCode = SB->addDeviceDependences(HostAction);
 
   // Host dependences for device actions are not compatible with that same
   // action being ignored.


Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -2733,7 +2733,7 @@
 
 /// Update the state to include the provided host action \a HostAction as a
 /// dependency of the current device action. By default it is inactive.
-virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
+virtual ActionBuilderReturnCode addDeviceDependences(Action *HostAction) {
   return ABRT_Inactive;
 }
 
@@ -2821,7 +2821,7 @@
   Action::OffloadKind OFKind)
 : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
 
-ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
+ActionBuilderReturnCode addDeviceDependences(Action *HostAction) override {
   // While generating code for CUDA, we only depend on the host input action
   // to trigger the creation of all the CUDA device actions.
 
@@ -3600,7 +3600,7 @@
   if (!SB->isValid())
 continue;
 
-  auto RetCode = SB->addDeviceDepences(HostAction);
+  auto RetCode = SB->addDeviceDependences(HostAction);
 
   // Host dependences for device actions are not compatible with that same
   // action being ignored.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132300: [clang][lldb][cmake] Use new `*_INSTALL_LIBDIR_BASENAME` CPP macro

2022-09-15 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In the long term we should just remove the `CLANG_INSTALL_LIBDIR_BASENAME` 
customization. This is supposed for GCC multilib lib32 lib64 names but we don't 
necessarily use it for Clang + compiler-rt files.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132300

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


[PATCH] D133998: [HIP][test] Avoid %T

2022-09-15 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 rG9e1c1ecb148e: [HIP][test] Avoid %T (authored by MaskRay).

Changed prior to commit:
  https://reviews.llvm.org/D133998?vs=460569&id=460608#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133998

Files:
  clang/test/Driver/hip-link-bc-to-bc.hip
  clang/test/Driver/hip-link-bundle-archive.hip
  clang/test/Driver/hip-link-save-temps.hip
  clang/test/Driver/hip-phases.hip
  clang/test/Driver/hip-runtime-libs-linux.hip
  clang/test/Driver/hip-toolchain-no-rdc.hip
  clang/test/Driver/hip-toolchain-rdc-separate.hip

Index: clang/test/Driver/hip-toolchain-rdc-separate.hip
===
--- clang/test/Driver/hip-toolchain-rdc-separate.hip
+++ clang/test/Driver/hip-toolchain-rdc-separate.hip
@@ -1,6 +1,7 @@
 // REQUIRES: x86-registered-target
 // REQUIRES: amdgpu-registered-target
 
+// RUN: rm -rf %t && mkdir %t
 // RUN: %clang -c -### --target=x86_64-linux-gnu \
 // RUN:   -x hip --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
 // RUN:   --hip-device-lib=lib1.bc --hip-device-lib=lib2.bc \
@@ -81,24 +82,23 @@
 // CHECK-SAME: "-targets=hip-amdgcn-amd-amdhsa-gfx803,hip-amdgcn-amd-amdhsa-gfx900,host-x86_64-unknown-linux-gnu"
 // CHECK-SAME: "-output=[[B_O:.*b.o]]" "-input=[[B_BC1]]" "-input=[[B_BC2]]" "-input=[[B_OBJ_HOST]]"
 
-// RUN: touch %T/a.o
-// RUN: touch %T/b.o
+// RUN: touch %t/a.o %t/b.o
 // RUN: %clang --hip-link -### --target=x86_64-linux-gnu \
 // RUN:   --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
 // RUN:   -fuse-ld=lld -fgpu-rdc -nogpuinc \
-// RUN:   %T/a.o %T/b.o \
+// RUN:   %t/a.o %t/b.o \
 // RUN: 2>&1 | FileCheck -check-prefixes=LINK,LINK-HOST-UNBUNDLE,LLD-TMP,LINK-BUNDLE,LINK-EMBED %s
 
 // RUN: %clang --hip-link -### --target=x86_64-linux-gnu \
 // RUN:   --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
 // RUN:   -fuse-ld=lld -fgpu-rdc -nogpuinc \
-// RUN:   %T/a.o %T/b.o --cuda-device-only \
+// RUN:   %t/a.o %t/b.o --cuda-device-only \
 // RUN: 2>&1 | FileCheck -check-prefixes=LINK,LLD-TMP,LINK-BUNDLE,LINK-NOEMBED %s
 
 // RUN: %clang --hip-link -### --target=x86_64-linux-gnu \
 // RUN:   --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
 // RUN:   -fuse-ld=lld -fgpu-rdc -nogpuinc \
-// RUN:   %T/a.o %T/b.o --cuda-device-only --no-gpu-bundle-output \
+// RUN:   %t/a.o %t/b.o --cuda-device-only --no-gpu-bundle-output \
 // RUN: 2>&1 | FileCheck -check-prefixes=LINK,LLD-FIN,LINK-NOBUNDLE,LINK-NOEMBED %s
 
 // LINK-HOST-UNBUNDLE: [[BUNDLER:".*clang-offload-bundler"]] "-type=o"
Index: clang/test/Driver/hip-toolchain-no-rdc.hip
===
--- clang/test/Driver/hip-toolchain-no-rdc.hip
+++ clang/test/Driver/hip-toolchain-no-rdc.hip
@@ -1,6 +1,7 @@
 // REQUIRES: x86-registered-target
 // REQUIRES: amdgpu-registered-target
 
+// RUN: rm -rf %t && mkdir %t
 // RUN: %clang -### --target=x86_64-linux-gnu -fno-gpu-rdc \
 // RUN:   -x hip --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
 // RUN:   --hip-device-lib=lib1.bc --hip-device-lib=lib2.bc \
@@ -31,12 +32,11 @@
 // RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
 // RUN: 2>&1 | FileCheck -check-prefixes=CHECK %s
 
-// RUN: touch %T/a.o
-// RUN: touch %T/b.o
+// RUN: touch %t/a.o %t/b.o
 // RUN: %clang -### --target=x86_64-linux-gnu \
 // RUN:   --hip-link --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
 // RUN:   -fuse-ld=lld -nogpuinc \
-// RUN:   %T/a.o %T/b.o \
+// RUN:   %t/a.o %t/b.o \
 // RUN: 2>&1 | FileCheck -check-prefixes=LKONLY %s
 
 //
Index: clang/test/Driver/hip-runtime-libs-linux.hip
===
--- clang/test/Driver/hip-runtime-libs-linux.hip
+++ clang/test/Driver/hip-runtime-libs-linux.hip
@@ -13,12 +13,11 @@
 // RUN:   | FileCheck -check-prefixes=ROCM-PATH %s
 
 // Test detecting latest /opt/rocm-{release} directory.
-// RUN: rm -rf %T/opt
-// RUN: mkdir -p %T/opt
-// RUN: cp -r %S/Inputs/rocm %T/opt/rocm-3.9.0-1234
-// RUN: cp -r %S/Inputs/rocm %T/opt/rocm-3.10.0
+// RUN: rm -rf %t && mkdir -p %t/opt
+// RUN: cp -r %S/Inputs/rocm %t/opt/rocm-3.9.0-1234
+// RUN: cp -r %S/Inputs/rocm %t/opt/rocm-3.10.0
 // RUN: %clang -### --hip-link --target=x86_64-linux-gnu \
-// RUN:   --sysroot=%T %t.o 2>&1 \
+// RUN:   --sysroot=%t %t.o 2>&1 \
 // RUN:   | FileCheck -check-prefixes=ROCM-REL %s
 
 // Test HIP runtime lib is not linked without --hip-link.
Index: clang/test/Driver/hip-phases.hip
===
--- clang/test/Driver/hip-phases.hip
+++ clang/test/Driver/hip-phases.hip
@@ -305,23 +305,23 @@
 //
 // Test linking two objects with two gpu architectures.
 //
-// RUN: touch %T/obj1.o
-// RUN: touch %T/obj2.o
-//
+// RUN: rm -rf %t && mkdir %t
+// RUN: touch %t/obj1.o %t/obj2.o
+
 // RUN: %c

[clang] 9e1c1ec - [HIP][test] Avoid %T

2022-09-15 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2022-09-15T19:58:42-07:00
New Revision: 9e1c1ecb148eb4e530467e178973e870945e6602

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

LOG: [HIP][test] Avoid %T

%T is a deprecated lit feature. It refers to the parent directory.
When two tests in test/Driver refer to the same `%T/foo`, they are racy with 
each other.
%t includes the test name and is safe for use.

Reviewed By: tra

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

Added: 


Modified: 
clang/test/Driver/hip-link-bc-to-bc.hip
clang/test/Driver/hip-link-bundle-archive.hip
clang/test/Driver/hip-link-save-temps.hip
clang/test/Driver/hip-phases.hip
clang/test/Driver/hip-runtime-libs-linux.hip
clang/test/Driver/hip-toolchain-no-rdc.hip
clang/test/Driver/hip-toolchain-rdc-separate.hip

Removed: 




diff  --git a/clang/test/Driver/hip-link-bc-to-bc.hip 
b/clang/test/Driver/hip-link-bc-to-bc.hip
index 42a539bd3cdd8..b331bacf99edf 100644
--- a/clang/test/Driver/hip-link-bc-to-bc.hip
+++ b/clang/test/Driver/hip-link-bc-to-bc.hip
@@ -1,12 +1,13 @@
-// REQUIRES: clang-driver, x86-registered-target, amdgpu-registered-target
+// REQUIRES: x86-registered-target, amdgpu-registered-target
 
 // Check that clang unbundles the two bitcodes and links via llvm-link
-// RUN: touch %T/bundle1.bc
-// RUN: touch %T/bundle2.bc
+// RUN: rm -rf %t && mkdir %t
+// RUN: touch %t/bundle1.bc
+// RUN: touch %t/bundle2.bc
 
-// RUN: %clang -### --offload-arch=gfx906 --hip-link \
+// RUN: %clang -### --target=x86_64-unknown-linux-gnu --offload-arch=gfx906 
--hip-link \
 // RUN:   -emit-llvm -fgpu-rdc --cuda-device-only \
-// RUN:   %T/bundle1.bc %T/bundle2.bc \
+// RUN:   %t/bundle1.bc %t/bundle2.bc \
 // RUN:   2>&1 | FileCheck -check-prefix=BITCODE %s
 
 // BITCODE: "{{.*}}clang-offload-bundler" "-type=bc" 
"-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx906" 
"-input={{.*}}bundle1.bc" "-output=[[B1HOST:.*\.bc]]" 
"-output=[[B1DEV1:.*\.bc]]" "-unbundle" "-allow-missing-bundles"
@@ -18,12 +19,12 @@
 // BITCODE: "{{.*}}llvm-link" "-o" "bundle1-hip-amdgcn-amd-amdhsa-gfx906.bc" 
"[[B1DEV2]]" "[[B2DEV2]]"
 
 // Check that clang unbundles the bitcode and archive and links via llvm-link
-// RUN: touch %T/libhipbundle.a
-// RUN: touch %T/bundle.bc
+// RUN: touch %t/libhipbundle.a
+// RUN: touch %t/bundle.bc
 
-// RUN: %clang -### --offload-arch=gfx906 --hip-link \
+// RUN: %clang -### --target=x86_64-unknown-linux-gnu --offload-arch=gfx906 
--hip-link \
 // RUN:   -emit-llvm -fgpu-rdc --cuda-device-only \
-// RUN:   %T/bundle.bc -L%T -lhipbundle \
+// RUN:   %t/bundle.bc -L%t -lhipbundle \
 // RUN:   2>&1 | FileCheck -check-prefix=ARCHIVE %s
 
 // ARCHIVE: "{{.*}}clang-offload-bundler" "-type=bc" 
"-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx906" 
"-input={{.*}}bundle.bc" "-output=[[HOST:.*\.bc]]" "-output=[[DEV1:.*\.bc]]" 
"-unbundle" "-allow-missing-bundles"

diff  --git a/clang/test/Driver/hip-link-bundle-archive.hip 
b/clang/test/Driver/hip-link-bundle-archive.hip
index bb912d6e57c55..32cec5fab9def 100644
--- a/clang/test/Driver/hip-link-bundle-archive.hip
+++ b/clang/test/Driver/hip-link-bundle-archive.hip
@@ -3,16 +3,17 @@
 
 // Check clang unbundle the archive and link them by lld.
 
-// RUN: touch %T/libhipBundled.a
+// RUN: rm -rf %t && mkdir %t
+// RUN: touch %t/libhipBundled.a
 // RUN: %clang -### --offload-arch=gfx906 --offload-arch=gfx1030 \
 // RUN:   --target=x86_64-unknown-linux-gnu \
-// RUN:   -nogpulib %s -fgpu-rdc -L%T -lhipBundled \
+// RUN:   -nogpulib %s -fgpu-rdc -L%t -lhipBundled \
 // RUN:   2>&1 | FileCheck -check-prefix=GNU %s
 
-// RUN: touch %T/hipBundled2.lib
+// RUN: touch %t/hipBundled2.lib
 // RUN: %clang -### --offload-arch=gfx906 --offload-arch=gfx1030 \
 // RUN:   --target=x86_64-pc-windows-msvc \
-// RUN:   -nogpulib %s -fgpu-rdc -L%T -lhipBundled2 \
+// RUN:   -nogpulib %s -fgpu-rdc -L%t -lhipBundled2 \
 // RUN:   2>&1 | FileCheck -check-prefix=MSVC %s
 
 // GNU: "{{.*}}clang-offload-bundler" "-unbundle" "-type=a" 
"-input={{.*}}libhipBundled.a" "-targets=hip-amdgcn-amd-amdhsa-gfx1030" 
"-output=[[A1030:.*\.a]]" "-allow-missing-bundles"

diff  --git a/clang/test/Driver/hip-link-save-temps.hip 
b/clang/test/Driver/hip-link-save-temps.hip
index 735c8e884ebd3..b8a5dcefb8cf0 100644
--- a/clang/test/Driver/hip-link-save-temps.hip
+++ b/clang/test/Driver/hip-link-save-temps.hip
@@ -2,37 +2,38 @@
 // REQUIRES: amdgpu-registered-target
 
 // -fgpu-rdc link with output
-// RUN: touch %T/obj1.o
-// RUN: touch %T/obj2.o
+// RUN: rm -rf %t && mkdir %t
+// RUN: touch %t/obj1.o
+// RUN: touch %t/obj2.o
 // RUN: %clang -### --target=x86_64-linux-gnu -nogpulib -save-temps \
 // RUN:   --hip-link -o executable -fgpu-rdc --cuda-gpu-arch=gfx90

[PATCH] D133244: [clang-tidy] Readability-container-data-pointer adds new option to ignore Containers

2022-09-15 Thread Félix-Antoine Constantin via Phabricator via cfe-commits
felix642 added a comment.

Ping.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133244

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


[clang] d6aed77 - [InstrProfiling] No runtime hook for unused funcs

2022-09-15 Thread Gulfem Savrun Yeniceri via cfe-commits

Author: Gulfem Savrun Yeniceri
Date: 2022-09-16T02:05:09Z
New Revision: d6aed77f0d19664be48d531552692520ae2a6f1a

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

LOG: [InstrProfiling] No runtime hook for unused funcs

This is a reland of https://reviews.llvm.org/D122336.
Original patch caused a problem in collecting coverage in
Fuchsia because it was returning early without putting unused
function names into __llvm_prf_names section. This patch
fixes that issue.

The original commit message is as the following:
CoverageMappingModuleGen generates a coverage mapping record
even for unused functions with internal linkage, e.g.
static int foo() { return 100; }
Clang frontend eliminates such functions, but InstrProfiling pass
still emits runtime hook since there is a coverage record.
Fuchsia uses runtime counter relocation, and pulling in profile
runtime for unused functions causes a linker error:
undefined hidden symbol: __llvm_profile_counter_bias.
Since https://reviews.llvm.org/D98061, we do not hook profile
runtime for the binaries that none of its translation units
have been instrumented in Fuchsia. This patch extends that for
the instrumented binaries that consist of only unused functions.

Reviewed By: phosek

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

Added: 
clang/test/CoverageMapping/unused_function_no_runtime_hook.cpp

Modified: 
llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp

Removed: 




diff  --git a/clang/test/CoverageMapping/unused_function_no_runtime_hook.cpp 
b/clang/test/CoverageMapping/unused_function_no_runtime_hook.cpp
new file mode 100644
index ..5a835ae31169
--- /dev/null
+++ b/clang/test/CoverageMapping/unused_function_no_runtime_hook.cpp
@@ -0,0 +1,6 @@
+// RUN: %clang -target x86_64-unknown-fuchsia -fprofile-instr-generate 
-fcoverage-mapping -emit-llvm -S %s -o - | FileCheck %s
+
+// CHECK-NOT: @__llvm_profile_runtime
+static int f0() {
+  return 100;
+}

diff  --git a/llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp 
b/llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
index 64043151a830..ce9972888e89 100644
--- a/llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
+++ b/llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
@@ -525,9 +525,8 @@ bool InstrProfiling::run(
   TT = Triple(M.getTargetTriple());
 
   bool MadeChange = false;
-
-  // Emit the runtime hook even if no counters are present.
-  if (needsRuntimeHookUnconditionally(TT))
+  bool NeedsRuntimeHook = needsRuntimeHookUnconditionally(TT);
+  if (NeedsRuntimeHook)
 MadeChange = emitRuntimeHook();
 
   // Improve compile time by avoiding linear scans when there is no work.
@@ -567,7 +566,14 @@ bool InstrProfiling::run(
 
   emitVNodes();
   emitNameData();
-  emitRuntimeHook();
+
+  // Emit runtime hook except for the cases where coverage is enabled on
+  // code that is eliminated by the front-end, e.g. unused functions with
+  // internal linkage, and the target does not require pulling in profile
+  // runtime.
+  if (containsProfilingIntrinsics(M) || !CoverageNamesVar || NeedsRuntimeHook)
+emitRuntimeHook();
+
   emitRegistration();
   emitUses();
   emitInitialization();



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


[clang] 3eca0b3 - [lit] Set shlibpath_var on OpenBSD

2022-09-15 Thread Brad Smith via cfe-commits

Author: Brad Smith
Date: 2022-09-15T21:43:54-04:00
New Revision: 3eca0b395ff07d0428f4179e33a6ae295e608f47

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

LOG: [lit] Set shlibpath_var on OpenBSD

Added: 


Modified: 
clang/test/Unit/lit.cfg.py

Removed: 




diff  --git a/clang/test/Unit/lit.cfg.py b/clang/test/Unit/lit.cfg.py
index 60a1e79e9330..8e3e6f2e862d 100644
--- a/clang/test/Unit/lit.cfg.py
+++ b/clang/test/Unit/lit.cfg.py
@@ -50,7 +50,7 @@
 config.environment[var] = os.environ[var]
 
 def find_shlibpath_var():
-if platform.system() in ['Linux', 'FreeBSD', 'NetBSD', 'SunOS']:
+if platform.system() in ['Linux', 'FreeBSD', 'NetBSD', 'OpenBSD', 'SunOS']:
 yield 'LD_LIBRARY_PATH'
 elif platform.system() == 'Darwin':
 yield 'DYLD_LIBRARY_PATH'



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


[PATCH] D133574: [C2x] reject type definitions in offsetof

2022-09-15 Thread YingChi Long via Phabricator via cfe-commits
inclyc added inline comments.



Comment at: clang/test/Sema/offsetof.c:79
+int a;
+struct B // no-error, struct B is not defined within __builtin_offsetof 
directly
+{

aaron.ballman wrote:
> inclyc wrote:
> > inclyc wrote:
> > > aaron.ballman wrote:
> > > > inclyc wrote:
> > > > > aaron.ballman wrote:
> > > > > > I think this is defensible. The wording in the standard is "If the 
> > > > > > specified type defines a new type or if the specified member is a 
> > > > > > bit-field, the behavior is undefined." and the specified type in 
> > > > > > this case is `struct A`; that `struct A` happens to also define 
> > > > > > `struct B` is immaterial.
> > > > > > 
> > > > > > However, the intent behind the change to the rule is to support 
> > > > > > older implementations of `offsetof` to protect them from having to 
> > > > > > deal with a case like: `offsetof(struct S { int a, b }, b);` where 
> > > > > > `offsetof` is a macro and thus the comma between `a` and `b` is 
> > > > > > treated as a separator. So there's a part of me that wonders if we 
> > > > > > want to also support diagnosing this case. But then we'd have to 
> > > > > > look at the declarator context more recursively to see whether any 
> > > > > > of the contexts on the stack are an `offsetof` context and that 
> > > > > > might be tricky.
> > > > > > 
> > > > > > Thoughts?
> > > > > FWIW, gcc seems just rejects all definitions in this context. 
> > > > > (Perhaps during Parsing the statements). If we add a bool state to 
> > > > > the Parser (just using RAII object as before) struct B will trigger 
> > > > > diagnostic error because the state "ParsingOffsetof" is passed into 
> > > > > inner declaration.
> > > > GCC accepts currently: https://godbolt.org/z/oEvzjW6Ee but you're 
> > > > correct regarding switching back to an RAII object being an easier way 
> > > > to address the nested declarations.
> > > > 
> > > > Let me think on this situation a bit
> > > > GCC accepts currently
> > > 
> > > C++: https://godbolt.org/z/fon8e7dzf 
> > ```
> > : In function 'int main()':
> > :3:3: error: types may not be defined within '__builtin_offsetof'
> > 3 |   {
> >   |   ^
> > :6:5: error: types may not be defined within '__builtin_offsetof'
> > 6 | {
> >   | ^
> > Compiler returned: 1
> > ```
> C++ is a different language in this case though. In C, you can generally 
> define types anywhere you can spell a type, and in C++ you cannot. e.g., 
> `void func(struct S { int x, y; } s);` is valid in C and invalid in C++.
GCC explicitly reject type definitions since GCC 8 (in C++ mode). I guess the 
logic here in GCC may also add a boolean state parameter to parser.

Interestingly, in C++ we treat the first parameter of `__builtin_offsetof` as a 
type specifier, rejecting the definition of `struct A`, but not rejecting 
nested definition `struct B`

https://godbolt.org/z/PqWjzqqYn

Emm, so, how about switch back to RAIIObject to support diagnosing nested 
definitions?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133574

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


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

2022-09-15 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov updated this revision to Diff 460595.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128113

Files:
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/Type.h
  clang/include/clang/AST/TypeProperties.td
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/ASTStructuralEquivalence.cpp
  clang/lib/AST/JSONNodeDumper.cpp
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/AST/Type.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/TreeTransform.h
  clang/test/AST/ast-dump-template-decls.cpp
  clang/test/SemaTemplate/type_pack_element.cpp
  clang/unittests/AST/ASTImporterTest.cpp

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -4793,6 +4793,44 @@
   ToD2->getDeclContext(), ToD2->getTemplateParameters()->getParam(0)));
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, ImportSubstTemplateTypeParmType) {
+  constexpr auto Code = R"(
+template  struct A {
+  using B = A1(A2...);
+};
+template struct A;
+)";
+  Decl *FromTU = getTuDecl(Code, Lang_CXX11, "input.cpp");
+  auto *FromClass = FirstDeclMatcher().match(
+  FromTU, classTemplateSpecializationDecl());
+
+  auto testType = [&](ASTContext &Ctx, const char *Name,
+  llvm::Optional PackIndex) {
+const auto *Subst = selectFirst(
+"sttp", match(substTemplateTypeParmType(
+  hasReplacementType(hasCanonicalType(asString(Name
+  .bind("sttp"),
+  Ctx));
+const char *ExpectedTemplateParamName = PackIndex ? "A2" : "A1";
+ASSERT_TRUE(Subst);
+ASSERT_EQ(Subst->getReplacedParameter()->getIdentifier()->getName(),
+  ExpectedTemplateParamName);
+ASSERT_EQ(Subst->getPackIndex(), PackIndex);
+  };
+  auto tests = [&](ASTContext &Ctx) {
+testType(Ctx, "void", None);
+testType(Ctx, "char", 3);
+testType(Ctx, "float", 2);
+testType(Ctx, "int", 1);
+testType(Ctx, "short", 0);
+  };
+
+  tests(FromTU->getASTContext());
+
+  ClassTemplateSpecializationDecl *ToClass = Import(FromClass, Lang_CXX11);
+  tests(ToClass->getASTContext());
+}
+
 const AstTypeMatcher
 substTemplateTypeParmPackType;
 
Index: clang/test/SemaTemplate/type_pack_element.cpp
===
--- clang/test/SemaTemplate/type_pack_element.cpp
+++ clang/test/SemaTemplate/type_pack_element.cpp
@@ -11,7 +11,7 @@
 // CHECK-NEXT:   | `-IntegerLiteral 0x{{[0-9A-Fa-f]+}}  'int' 0
 // CHECK-NEXT:   |-TemplateArgument type 'int'
 // CHECK-NEXT:   | `-BuiltinType 0x{{[0-9A-Fa-f]+}} 'int'
-// CHECK-NEXT:   `-SubstTemplateTypeParmType 0x{{[0-9A-Fa-f]+}} 'int' sugar typename depth 0 index 1 ...
+// CHECK-NEXT:   `-SubstTemplateTypeParmType 0x{{[0-9A-Fa-f]+}} 'int' sugar typename depth 0 index 1 ... pack_index 0
 // CHECK-NEXT: |-BuiltinTemplate 0x{{[0-9A-Fa-f]+}} '__type_pack_element'
 // CHECK-NEXT: `-BuiltinType 0x{{[0-9A-Fa-f]+}} 'int'
 
Index: clang/test/AST/ast-dump-template-decls.cpp
===
--- clang/test/AST/ast-dump-template-decls.cpp
+++ clang/test/AST/ast-dump-template-decls.cpp
@@ -136,13 +136,13 @@
 };
 using t1 = foo::bind;
 // CHECK:  TemplateSpecializationType 0x{{[^ ]*}} 'Y' sugar Y
-// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'char' sugar typename depth 0 index 0 ... Bs
+// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'char' sugar typename depth 0 index 0 ... Bs pack_index 3
 // CHECK-NEXT: TypeAliasTemplate 0x{{[^ ]*}} 'Z'
-// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'float' sugar typename depth 0 index 0 ... Bs
+// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'float' sugar typename depth 0 index 0 ... Bs pack_index 2
 // CHECK-NEXT: TypeAliasTemplate 0x{{[^ ]*}} 'Z'
-// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'int' sugar typename depth 0 index 0 ... Bs
+// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'int' sugar typename depth 0 index 0 ... Bs pack_index 1
 // CHECK-NEXT: TypeAliasTemplate 0x{{[^ ]*}} 'Z'
-// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'short' sugar typename depth 0 index 0 ... Bs
+// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 'short' sugar typename depth 0 index 0 ... Bs pack_index 0
 // CHECK-NEXT: TypeAliasTemplate 0x{{[^ ]*}} 'Z'
 
 template  struct D {
@@ -152,13 +152,13 @@
 // CHECK:  TemplateSpecializationType 0x{{[^ ]*}} 'B' sugar alias B
 // CHECK:  FunctionProtoType 0x{{[^ ]*}} 'int (int (*)(float, int), int (*)(char, short))' cdecl
 // CHECK:  FunctionProtoType 0x{{[^ ]*}} 'int (float, int)' cdecl
-// CHECK:  SubstTemplateTypeParmType 0x{{[^ ]*}} 

[PATCH] D133874: [clang] Implement sugar retention for converted template arguments

2022-09-15 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov updated this revision to Diff 460594.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133874

Files:
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Sema/TemplateDeduction.h
  clang/lib/Sema/SemaLookup.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/SemaCXX/ppc-pair-mma-types.cpp
  clang/test/SemaTemplate/make_integer_seq.cpp
  libcxx/DELETE.ME

Index: libcxx/DELETE.ME
===
--- libcxx/DELETE.ME
+++ libcxx/DELETE.ME
@@ -2,3 +2,4 @@
 D130308
 D133262
 D131858
+D133874
Index: clang/test/SemaTemplate/make_integer_seq.cpp
===
--- clang/test/SemaTemplate/make_integer_seq.cpp
+++ clang/test/SemaTemplate/make_integer_seq.cpp
@@ -53,7 +53,9 @@
 // CHECK-NEXT: |-TemplateArgument type 'int':'int'
 // CHECK-NEXT: | `-SubstTemplateTypeParmType 0x{{[0-9A-Fa-f]+}} 'int' sugar typename depth 0 index 1
 // CHECK-NEXT: |   |-BuiltinTemplate 0x{{[0-9A-Fa-f]+}} '__make_integer_seq'
-// CHECK-NEXT: |   `-BuiltinType 0x{{[0-9A-Fa-f]+}} 'int'
+// CHECK-NEXT: |   `-SubstTemplateTypeParmType 0x{{[0-9A-Fa-f]+}} 'int' sugar class depth 0 index 0 B1
+// CHECK-NEXT: | |-TypeAliasTemplate 0x{{[0-9A-Fa-f]+}} 'B'
+// CHECK-NEXT: | `-BuiltinType 0x{{[0-9A-Fa-f]+}} 'int'
 // CHECK-NEXT: |-TemplateArgument expr
 // CHECK-NEXT: | `-ConstantExpr 0x{{[0-9A-Fa-f]+}}  'int'
 // CHECK-NEXT: |   |-value: Int 0
@@ -63,7 +65,7 @@
 
 template  class S, class T, int N> struct C {
   using test3 = __make_integer_seq;
-//  CHECK: |-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test3 '__make_integer_seq':'__make_integer_seq'
+//  CHECK: |-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test3 '__make_integer_seq':'__make_integer_seq'
 // CHECK-NEXT:   `-ElaboratedType 0x{{[0-9A-Fa-f]+}} '__make_integer_seq' sugar dependent
 // CHECK-NEXT: `-TemplateSpecializationType 0x{{[0-9A-Fa-f]+}} '__make_integer_seq' sugar dependent alias __make_integer_seq
 // CHECK-NEXT:   |-TemplateArgument template S
@@ -82,7 +84,7 @@
 // CHECK-NEXT: `-DeclRefExpr 0x{{[0-9A-Fa-f]+}}  'int' NonTypeTemplateParm 0x{{[0-9A-Fa-f]+}} 'N' 'int'
 
   using test4 = __make_integer_seq;
-//  CHECK: |-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test4 '__make_integer_seq':'__make_integer_seq'
+//  CHECK: |-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test4 '__make_integer_seq':'__make_integer_seq'
 // CHECK-NEXT:   `-ElaboratedType 0x{{[0-9A-Fa-f]+}} '__make_integer_seq' sugar dependent
 // CHECK-NEXT: `-TemplateSpecializationType 0x{{[0-9A-Fa-f]+}} '__make_integer_seq' sugar dependent alias __make_integer_seq
 // CHECK-NEXT:   |-TemplateArgument template A
@@ -101,7 +103,7 @@
 // CHECK-NEXT: `-IntegerLiteral 0x{{[0-9A-Fa-f]+}}  'int' 1
 
   using test5 = __make_integer_seq;
-//  CHECK: `-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test5 '__make_integer_seq':'__make_integer_seq'
+//  CHECK: `-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test5 '__make_integer_seq':'__make_integer_seq'
 // CHECK-NEXT:   `-ElaboratedType 0x{{[0-9A-Fa-f]+}} '__make_integer_seq' sugar dependent
 // CHECK-NEXT: `-TemplateSpecializationType 0x{{[0-9A-Fa-f]+}} '__make_integer_seq' sugar dependent alias __make_integer_seq
 // CHECK-NEXT:   |-TemplateArgument template A
Index: clang/test/SemaCXX/ppc-pair-mma-types.cpp
===
--- clang/test/SemaCXX/ppc-pair-mma-types.cpp
+++ clang/test/SemaCXX/ppc-pair-mma-types.cpp
@@ -85,8 +85,8 @@
 
   // template argument
   template 
-  void testVQTemplate(T v, T *p) { // expected-note {{candidate template ignored: substitution failure [with T = __vector_quad]: invalid use of PPC MMA type}} \
- expected-note {{candidate template ignored: substitution failure [with T = __vector_quad]: invalid use of PPC MMA type}}
+  void testVQTemplate(T v, T *p) { // expected-note {{candidate template ignored: substitution failure [with T = vq_t]: invalid use of PPC MMA type}} \
+  expected-note {{candidate template ignored: substitution failure [with T = __vector_quad]: invalid use of PPC MMA type}}
 *(p + 1) = v;
   }
 
@@ -276,8 +276,8 @@
 
   // template argument
   template 
-  void testVPTemplate(T v, T *p) { // expected-note {{candidate template ignored: substitution failure [with T = __vector_pair]: invalid use of PPC MMA type}} \
- expected-note {{candidate template ignored: substitution failure [with T = __vector_pair]: invalid use of PPC MMA type}}

[PATCH] D133468: [clang] Implement divergence for TypedefType and UsingType

2022-09-15 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov updated this revision to Diff 460593.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133468

Files:
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/JSONNodeDumper.h
  clang/include/clang/AST/Type.h
  clang/include/clang/AST/TypeProperties.td
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/ASTStructuralEquivalence.cpp
  clang/lib/AST/JSONNodeDumper.cpp
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/AST/Type.cpp
  clang/test/SemaCXX/sugar-common-types.cpp

Index: clang/test/SemaCXX/sugar-common-types.cpp
===
--- clang/test/SemaCXX/sugar-common-types.cpp
+++ clang/test/SemaCXX/sugar-common-types.cpp
@@ -112,3 +112,22 @@
 C2 auto t26_3 = (::SB1){};
 N t26 = 0 ? t26_1 : t26_2; // expected-error {{from 'SB1' (aka 'SS1')}}
 N t27 = 0 ? t26_1 : t26_3; // expected-error {{from 'SB1' (aka 'SS1')}}
+
+using RPB1 = X1*;
+using RPX1 = RPB1;
+using RPB1 = Y1*; // redeclared
+using RPY1 = RPB1;
+N t28 = *(RPB1){}; // expected-error {{lvalue of type 'Y1' (aka 'int')}}
+auto t29 = 0 ? (RPX1){} : (RPY1){};
+N t30 = t29;  // expected-error {{lvalue of type 'RPB1' (aka 'int *')}}
+N t31 = *t29; // expected-error {{lvalue of type 'B1' (aka 'int')}}
+
+namespace A { using type1 = X1*; };
+namespace C { using A::type1; };
+using UPX1 = C::type1;
+namespace A { using type1 = Y1*; };  // redeclared
+namespace C { using A::type1; }; // redeclared
+using UPY1 = C::type1;
+auto t32 = 0 ? (UPX1){} : (UPY1){};
+N t33 = t32;  // expected-error {{lvalue of type 'C::type1' (aka 'int *')}}
+N t34 = *t32; // expected-error {{lvalue of type 'B1' (aka 'int')}}
Index: clang/lib/AST/Type.cpp
===
--- clang/lib/AST/Type.cpp
+++ clang/lib/AST/Type.cpp
@@ -3434,25 +3434,34 @@
 }
 
 TypedefType::TypedefType(TypeClass tc, const TypedefNameDecl *D,
- QualType underlying, QualType can)
-: Type(tc, can, toSemanticDependence(underlying->getDependence())),
+ QualType Underlying, QualType can)
+: Type(tc, can, toSemanticDependence(can->getDependence())),
   Decl(const_cast(D)) {
   assert(!isa(can) && "Invalid canonical type");
+  TypedefBits.isDivergent = !Underlying.isNull();
+  if (isDivergent())
+*reinterpret_cast(this + 1) = Underlying;
 }
 
 QualType TypedefType::desugar() const {
-  return getDecl()->getUnderlyingType();
+  return isDivergent() ? *getTrailingObjects()
+   : Decl->getUnderlyingType();
 }
 
 UsingType::UsingType(const UsingShadowDecl *Found, QualType Underlying,
  QualType Canon)
-: Type(Using, Canon, toSemanticDependence(Underlying->getDependence())),
+: Type(Using, Canon, toSemanticDependence(Canon->getDependence())),
   Found(const_cast(Found)) {
-  assert(Underlying == getUnderlyingType());
+  UsingBits.isDivergent = !Underlying.isNull();
+  if (isDivergent())
+*reinterpret_cast(this + 1) = Underlying;
 }
 
 QualType UsingType::getUnderlyingType() const {
-  return QualType(cast(Found->getTargetDecl())->getTypeForDecl(), 0);
+  return isDivergent()
+ ? *getTrailingObjects()
+ : QualType(
+   cast(Found->getTargetDecl())->getTypeForDecl(), 0);
 }
 
 QualType MacroQualifiedType::desugar() const { return getUnderlyingType(); }
Index: clang/lib/AST/TextNodeDumper.cpp
===
--- clang/lib/AST/TextNodeDumper.cpp
+++ clang/lib/AST/TextNodeDumper.cpp
@@ -1543,10 +1543,14 @@
 
 void TextNodeDumper::VisitUsingType(const UsingType *T) {
   dumpDeclRef(T->getFoundDecl());
+  if (T->isDivergent())
+OS << " divergent";
 }
 
 void TextNodeDumper::VisitTypedefType(const TypedefType *T) {
   dumpDeclRef(T->getDecl());
+  if (T->isDivergent())
+OS << " divergent";
 }
 
 void TextNodeDumper::VisitUnaryTransformType(const UnaryTransformType *T) {
Index: clang/lib/AST/JSONNodeDumper.cpp
===
--- clang/lib/AST/JSONNodeDumper.cpp
+++ clang/lib/AST/JSONNodeDumper.cpp
@@ -531,6 +531,14 @@
 
 void JSONNodeDumper::VisitTypedefType(const TypedefType *TT) {
   JOS.attribute("decl", createBareDeclRef(TT->getDecl()));
+  if (TT->isDivergent())
+JOS.attribute("type", createQualType(TT->desugar()));
+}
+
+void JSONNodeDumper::VisitUsingType(const UsingType *TT) {
+  JOS.attribute("decl", createBareDeclRef(TT->getFoundDecl()));
+  if (TT->isDivergent())
+JOS.attribute("type", createQualType(TT->desugar()));
 }
 
 void JSONNodeDumper::VisitFunctionType(const FunctionType *T) {
Index: clang/lib/AST/ASTStructuralEquivalence.cpp
===
--- clang/lib/AST/ASTStructuralEquivalence.cpp
+++ clang/lib/AST/ASTStructuralEquivalence.cpp
@@ -957,11 +957,

[PATCH] D132816: [clang] AST: SubstTemplateTypeParmType support for non-canonical underlying type

2022-09-15 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov updated this revision to Diff 460592.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132816

Files:
  clang/include/clang/AST/Type.h
  clang/include/clang/AST/TypeProperties.td
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/Type.cpp
  clang/lib/Sema/SemaTemplate.cpp

Index: clang/lib/Sema/SemaTemplate.cpp
===
--- clang/lib/Sema/SemaTemplate.cpp
+++ clang/lib/Sema/SemaTemplate.cpp
@@ -3506,8 +3506,8 @@
 
   // Wrap the type in substitution sugar.
   auto getSubstType = [&](unsigned IndexReplaced, QualType Replacement) {
-return SemaRef.Context.getSubstTemplateTypeParmType(
-Replacement.getCanonicalType(), BTD, IndexReplaced);
+return SemaRef.Context.getSubstTemplateTypeParmType(Replacement, BTD,
+IndexReplaced);
   };
 
   switch (BTD->getBuiltinTemplateKind()) {
Index: clang/lib/AST/Type.cpp
===
--- clang/lib/AST/Type.cpp
+++ clang/lib/AST/Type.cpp
@@ -3718,6 +3718,11 @@
 : Type(SubstTemplateTypeParm, Replacement.getCanonicalType(),
Replacement->getDependence()),
   ReplacedDecl(ReplacedDecl) {
+  SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType =
+  Replacement != getCanonicalTypeInternal();
+  if (SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType)
+*getTrailingObjects() = Replacement;
+
   SubstTemplateTypeParmTypeBits.Index = Index;
   assert(ReplacedDecl != nullptr);
   assert(getReplacedParameter() != nullptr);
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -1529,8 +1529,7 @@
 return ToReplacementTypeOrErr.takeError();
 
   return Importer.getToContext().getSubstTemplateTypeParmType(
-  ToReplacementTypeOrErr->getCanonicalType(), *ReplacedOrErr,
-  T->getIndex());
+  *ToReplacementTypeOrErr, *ReplacedOrErr, T->getIndex());
 }
 
 ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmPackType(
Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -4755,9 +4755,6 @@
 QualType ASTContext::getSubstTemplateTypeParmType(QualType Replacement,
   Decl *ReplacedDecl,
   unsigned Index) const {
-  assert(Replacement.isCanonical()
- && "replacement types must always be canonical");
-
   llvm::FoldingSetNodeID ID;
   SubstTemplateTypeParmType::Profile(ID, Replacement, ReplacedDecl, Index);
   void *InsertPos = nullptr;
@@ -4765,8 +4762,11 @@
   SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
 
   if (!SubstParm) {
-SubstParm = new (*this, TypeAlignment)
-SubstTemplateTypeParmType(Replacement, ReplacedDecl, Index);
+void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc(
+ !Replacement.isCanonical()),
+ TypeAlignment);
+SubstParm =
+new (Mem) SubstTemplateTypeParmType(Replacement, ReplacedDecl, Index);
 Types.push_back(SubstParm);
 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
   }
Index: clang/include/clang/AST/TypeProperties.td
===
--- clang/include/clang/AST/TypeProperties.td
+++ clang/include/clang/AST/TypeProperties.td
@@ -741,7 +741,7 @@
   // The call to getCanonicalType here existed in ASTReader.cpp, too.
   def : Creator<[{
 return ctx.getSubstTemplateTypeParmType(
-ctx.getCanonicalType(replacementType), replacedDecl, Index);
+replacementType, replacedDecl, Index);
   }]>;
 }
 
Index: clang/include/clang/AST/Type.h
===
--- clang/include/clang/AST/Type.h
+++ clang/include/clang/AST/Type.h
@@ -1798,8 +1798,10 @@
 
 unsigned : NumTypeBits;
 
+unsigned HasNonCanonicalUnderlyingType : 1;
+
 // The index of the template parameter this substitution represents.
-unsigned Index;
+unsigned Index : 16;
   };
 
   class SubstTemplateTypeParmPackTypeBitfields {
@@ -4981,8 +4983,12 @@
 /// been replaced with these.  They are used solely to record that a
 /// type was originally written as a template type parameter;
 /// therefore they are never canonical.
-class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
+class SubstTemplateTypeParmType final
+: public Type,
+  public llvm::FoldingSetNode,
+  private llvm::TrailingObjects {
   friend class ASTContext;
+  friend class llvm::TrailingObjects;
 
   Decl *ReplacedDecl;
 
@@ -4992,7 +4998,11 @@
 public:
   /// 

[PATCH] D131858: [clang] Track the templated entity in type substitution.

2022-09-15 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov updated this revision to Diff 460591.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131858

Files:
  clang-tools-extra/clang-tidy/hicpp/ExceptionBaseclassCheck.cpp
  clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
  clang-tools-extra/clangd/AST.cpp
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/ASTNodeTraverser.h
  clang/include/clang/AST/JSONNodeDumper.h
  clang/include/clang/AST/TextNodeDumper.h
  clang/include/clang/AST/Type.h
  clang/include/clang/AST/TypeProperties.td
  clang/include/clang/Sema/Template.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/ASTStructuralEquivalence.cpp
  clang/lib/AST/JSONNodeDumper.cpp
  clang/lib/AST/ODRHash.cpp
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/AST/Type.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/Sema/SemaConcept.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Sema/SemaTemplateVariadic.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/lib/StaticAnalyzer/Checkers/MismatchedIteratorChecker.cpp
  clang/test/AST/ast-dump-openmp-begin-declare-variant_reference.cpp
  clang/test/AST/ast-dump-template-decls.cpp
  clang/test/AST/deduction-guides.cpp
  clang/test/SemaTemplate/deduction-guide.cpp
  clang/test/SemaTemplate/make_integer_seq.cpp
  clang/test/SemaTemplate/type_pack_element.cpp
  libcxx/DELETE.ME

Index: libcxx/DELETE.ME
===
--- libcxx/DELETE.ME
+++ libcxx/DELETE.ME
@@ -1,3 +1,4 @@
 D111509
 D130308
 D133262
+D131858
Index: clang/test/SemaTemplate/type_pack_element.cpp
===
--- clang/test/SemaTemplate/type_pack_element.cpp
+++ clang/test/SemaTemplate/type_pack_element.cpp
@@ -11,14 +11,13 @@
 // CHECK-NEXT:   | `-IntegerLiteral 0x{{[0-9A-Fa-f]+}}  'int' 0
 // CHECK-NEXT:   |-TemplateArgument type 'int'
 // CHECK-NEXT:   | `-BuiltinType 0x{{[0-9A-Fa-f]+}} 'int'
-// CHECK-NEXT:   `-SubstTemplateTypeParmType 0x{{[0-9A-Fa-f]+}} 'int' sugar
-// CHECK-NEXT: |-TemplateTypeParmType 0x{{[0-9A-Fa-f]+}} 'auto' dependent depth 0 index 1
-// CHECK-NEXT: | `-TemplateTypeParm 0x{{[0-9A-Fa-f]+}} ''
+// CHECK-NEXT:   `-SubstTemplateTypeParmType 0x{{[0-9A-Fa-f]+}} 'int' sugar typename depth 0 index 1 ...
+// CHECK-NEXT: |-BuiltinTemplate 0x{{[0-9A-Fa-f]+}} '__type_pack_element'
 // CHECK-NEXT: `-BuiltinType 0x{{[0-9A-Fa-f]+}} 'int'
 
 template struct A {
   using test2 = __type_pack_element;
-//  CHECK: |-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test2 '__type_pack_element':'__type_pack_element'
+//  CHECK: |-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test2 '__type_pack_element':'__type_pack_element'
 // CHECK-NEXT:   `-ElaboratedType 0x{{[0-9A-Fa-f]+}} '__type_pack_element' sugar dependent
 // CHECK-NEXT: `-TemplateSpecializationType 0x{{[0-9A-Fa-f]+}} '__type_pack_element' sugar dependent alias __type_pack_element
 // CHECK-NEXT:   |-TemplateArgument expr
@@ -38,7 +37,7 @@
 // CHECK-NEXT:   `-TemplateTypeParmType 0x{{[0-9A-Fa-f]+}} 'type-parameter-0-1' dependent contains_unexpanded_pack depth 0 index 1 pack
 
   using test3 = __type_pack_element<0, Ts...>;
-//  CHECK: |-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test3 '__type_pack_element<0, Ts...>':'__type_pack_element<0, type-parameter-0-1...>'
+//  CHECK: |-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test3 '__type_pack_element<0, Ts...>':'__type_pack_element<0, type-parameter-0-1...>'
 // CHECK-NEXT:   `-ElaboratedType 0x{{[0-9A-Fa-f]+}} '__type_pack_element<0, Ts...>' sugar dependent
 // CHECK-NEXT: `-TemplateSpecializationType 0x{{[0-9A-Fa-f]+}} '__type_pack_element<0, Ts...>' sugar dependent alias __type_pack_element
 // CHECK-NEXT:   |-TemplateArgument expr
@@ -58,7 +57,7 @@
 // CHECK-NEXT:   `-TemplateTypeParmType 0x{{[0-9A-Fa-f]+}} 'type-parameter-0-1' dependent contains_unexpanded_pack depth 0 index 1 pack
 
   using test4 = __type_pack_element;
-//  CHECK: `-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test4 '__type_pack_element':'__type_pack_element'
+//  CHECK: `-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test4 '__type_pack_element':'__type_pack_element'
 // CHECK-NEXT:   `-ElaboratedType 0x{{[0-9A-Fa-f]+}} '__type_pack_element' sugar dependent
 // CHECK-NEXT: `-TemplateSpecializationType 0x{{[0-9A-Fa-f]+}} '__type_pack_element' sugar dependent alias __type_pack_element
 // CHECK-NEXT:   |-TemplateArgument expr
Index: clang/test/SemaTemplate/make_integer_seq.cpp
===
--- clang/test/SemaTemplate

[PATCH] D133262: [clang] Fixes how we represent / emulate builtin templates

2022-09-15 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov updated this revision to Diff 460590.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133262

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/DeclTemplate.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/DeclTemplate.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/test/SemaTemplate/make_integer_seq.cpp
  clang/test/SemaTemplate/type_pack_element.cpp
  libcxx/DELETE.ME

Index: libcxx/DELETE.ME
===
--- libcxx/DELETE.ME
+++ libcxx/DELETE.ME
@@ -1,2 +1,3 @@
 D111509
 D130308
+D133262
Index: clang/test/SemaTemplate/type_pack_element.cpp
===
--- clang/test/SemaTemplate/type_pack_element.cpp
+++ clang/test/SemaTemplate/type_pack_element.cpp
@@ -3,7 +3,7 @@
 using test1 = __type_pack_element<0, int>;
 //  CHECK: |-TypeAliasDecl 0x{{[0-9A-Fa-f]+}} <:3:1, col:41> col:7 test1 '__type_pack_element<0, int>':'int'
 // CHECK-NEXT:   `-ElaboratedType 0x{{[0-9A-Fa-f]+}} '__type_pack_element<0, int>' sugar
-// CHECK-NEXT: `-TemplateSpecializationType 0x{{[0-9A-Fa-f]+}} '__type_pack_element<0, int>' sugar __type_pack_element
+// CHECK-NEXT: `-TemplateSpecializationType 0x{{[0-9A-Fa-f]+}} '__type_pack_element<0, int>' sugar alias __type_pack_element
 // CHECK-NEXT:   |-TemplateArgument expr
 // CHECK-NEXT:   | `-ConstantExpr 0x{{[0-9A-Fa-f]+}}  'unsigned long'
 // CHECK-NEXT:   |   |-value: Int 0
@@ -11,53 +11,79 @@
 // CHECK-NEXT:   | `-IntegerLiteral 0x{{[0-9A-Fa-f]+}}  'int' 0
 // CHECK-NEXT:   |-TemplateArgument type 'int'
 // CHECK-NEXT:   | `-BuiltinType 0x{{[0-9A-Fa-f]+}} 'int'
-// CHECK-NEXT:   `-BuiltinType 0x{{[0-9A-Fa-f]+}} 'int'
+// CHECK-NEXT:   `-SubstTemplateTypeParmType 0x{{[0-9A-Fa-f]+}} 'int' sugar
+// CHECK-NEXT: |-TemplateTypeParmType 0x{{[0-9A-Fa-f]+}} 'auto' dependent depth 0 index 1
+// CHECK-NEXT: | `-TemplateTypeParm 0x{{[0-9A-Fa-f]+}} ''
+// CHECK-NEXT: `-BuiltinType 0x{{[0-9A-Fa-f]+}} 'int'
 
 template struct A {
   using test2 = __type_pack_element;
-//  CHECK: |-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test2 '__type_pack_element':'__type_pack_element'
+//  CHECK: |-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test2 '__type_pack_element':'__type_pack_element'
 // CHECK-NEXT:   `-ElaboratedType 0x{{[0-9A-Fa-f]+}} '__type_pack_element' sugar dependent
-// CHECK-NEXT: `-TemplateSpecializationType 0x{{[0-9A-Fa-f]+}} '__type_pack_element' dependent __type_pack_element
+// CHECK-NEXT: `-TemplateSpecializationType 0x{{[0-9A-Fa-f]+}} '__type_pack_element' sugar dependent alias __type_pack_element
 // CHECK-NEXT:   |-TemplateArgument expr
 // CHECK-NEXT:   | `-ImplicitCastExpr 0x{{[0-9A-Fa-f]+}}  'unsigned long' 
 // CHECK-NEXT:   |   `-DeclRefExpr 0x{{[0-9A-Fa-f]+}}  'int' NonTypeTemplateParm 0x{{[0-9A-Fa-f]+}} 'N' 'int'
-// CHECK-NEXT:   `-TemplateArgument type 'Ts...'
-// CHECK-NEXT: `-PackExpansionType 0x{{[0-9A-Fa-f]+}} 'Ts...' dependent
-// CHECK-NEXT:   `-TemplateTypeParmType 0x{{[0-9A-Fa-f]+}} 'Ts' dependent contains_unexpanded_pack depth 0 index 1 pack
-// CHECK-NEXT: `-TemplateTypeParm 0x{{[0-9A-Fa-f]+}} 'Ts'
+// CHECK-NEXT:   |-TemplateArgument type 'Ts...'
+// CHECK-NEXT:   | `-PackExpansionType 0x{{[0-9A-Fa-f]+}} 'Ts...' dependent
+// CHECK-NEXT:   |   `-TemplateTypeParmType 0x{{[0-9A-Fa-f]+}} 'Ts' dependent contains_unexpanded_pack depth 0 index 1 pack
+// CHECK-NEXT:   | `-TemplateTypeParm 0x{{[0-9A-Fa-f]+}} 'Ts'
+// CHECK-NEXT:   `-TemplateSpecializationType 0x{{[0-9A-Fa-f]+}} '__type_pack_element' dependent __type_pack_element
+// CHECK-NEXT: |-TemplateArgument expr
+// CHECK-NEXT: | `-ImplicitCastExpr 0x{{[0-9A-Fa-f]+}}  'unsigned long' 
+// CHECK-NEXT: |   `-DeclRefExpr 0x{{[0-9A-Fa-f]+}}  'int' NonTypeTemplateParm 0x{{[0-9A-Fa-f]+}} 'N' 'int'
+// CHECK-NEXT: `-TemplateArgument pack
+// CHECK-NEXT:   `-TemplateArgument type 'type-parameter-0-1...'
+// CHECK-NEXT: `-PackExpansionType 0x{{[0-9A-Fa-f]+}} 'type-parameter-0-1...' dependent
+// CHECK-NEXT:   `-TemplateTypeParmType 0x{{[0-9A-Fa-f]+}} 'type-parameter-0-1' dependent contains_unexpanded_pack depth 0 index 1 pack
 
   using test3 = __type_pack_element<0, Ts...>;
-//  CHECK: |-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test3 '__type_pack_element<0, Ts...>':'__type_pack_element<0, Ts...>'
+//  CHECK: |-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test3 '__type_pack_element<0, Ts...>':'__type_pack_element<0, type-parameter-0-1...>'
 // CHECK-NEXT:   `-ElaboratedType 0x{{[0-9A-Fa-f]+}} '__type_pack_element<0, Ts...>' sugar dependent
-// CHECK-NEXT: `-TemplateSpecializationType

[PATCH] D133261: NFC: [clang] add template AST test for make_integer_seq and type_pack_element

2022-09-15 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov updated this revision to Diff 460589.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133261

Files:
  clang/test/SemaTemplate/make_integer_seq.cpp
  clang/test/SemaTemplate/type_pack_element.cpp

Index: clang/test/SemaTemplate/type_pack_element.cpp
===
--- /dev/null
+++ clang/test/SemaTemplate/type_pack_element.cpp
@@ -0,0 +1,68 @@
+// RUN: %clang_cc1 -std=c++2b -fsyntax-only -triple x86_64-linux-gnu -ast-dump -verify -xc++ < %s | FileCheck %s
+
+using test1 = __type_pack_element<0, int>;
+//  CHECK: |-TypeAliasDecl 0x{{[0-9A-Fa-f]+}} <:3:1, col:41> col:7 test1 '__type_pack_element<0, int>':'int'
+// CHECK-NEXT:   `-ElaboratedType 0x{{[0-9A-Fa-f]+}} '__type_pack_element<0, int>' sugar
+// CHECK-NEXT: `-TemplateSpecializationType 0x{{[0-9A-Fa-f]+}} '__type_pack_element<0, int>' sugar __type_pack_element
+// CHECK-NEXT:   |-TemplateArgument expr
+// CHECK-NEXT:   | `-ConstantExpr 0x{{[0-9A-Fa-f]+}}  'unsigned long'
+// CHECK-NEXT:   |   |-value: Int 0
+// CHECK-NEXT:   |   `-ImplicitCastExpr 0x{{[0-9A-Fa-f]+}}  'unsigned long' 
+// CHECK-NEXT:   | `-IntegerLiteral 0x{{[0-9A-Fa-f]+}}  'int' 0
+// CHECK-NEXT:   |-TemplateArgument type 'int'
+// CHECK-NEXT:   | `-BuiltinType 0x{{[0-9A-Fa-f]+}} 'int'
+// CHECK-NEXT:   `-BuiltinType 0x{{[0-9A-Fa-f]+}} 'int'
+
+template struct A {
+  using test2 = __type_pack_element;
+//  CHECK: |-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test2 '__type_pack_element':'__type_pack_element'
+// CHECK-NEXT:   `-ElaboratedType 0x{{[0-9A-Fa-f]+}} '__type_pack_element' sugar dependent
+// CHECK-NEXT: `-TemplateSpecializationType 0x{{[0-9A-Fa-f]+}} '__type_pack_element' dependent __type_pack_element
+// CHECK-NEXT:   |-TemplateArgument expr
+// CHECK-NEXT:   | `-ImplicitCastExpr 0x{{[0-9A-Fa-f]+}}  'unsigned long' 
+// CHECK-NEXT:   |   `-DeclRefExpr 0x{{[0-9A-Fa-f]+}}  'int' NonTypeTemplateParm 0x{{[0-9A-Fa-f]+}} 'N' 'int'
+// CHECK-NEXT:   `-TemplateArgument type 'Ts...'
+// CHECK-NEXT: `-PackExpansionType 0x{{[0-9A-Fa-f]+}} 'Ts...' dependent
+// CHECK-NEXT:   `-TemplateTypeParmType 0x{{[0-9A-Fa-f]+}} 'Ts' dependent contains_unexpanded_pack depth 0 index 1 pack
+// CHECK-NEXT: `-TemplateTypeParm 0x{{[0-9A-Fa-f]+}} 'Ts'
+
+  using test3 = __type_pack_element<0, Ts...>;
+//  CHECK: |-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test3 '__type_pack_element<0, Ts...>':'__type_pack_element<0, Ts...>'
+// CHECK-NEXT:   `-ElaboratedType 0x{{[0-9A-Fa-f]+}} '__type_pack_element<0, Ts...>' sugar dependent
+// CHECK-NEXT: `-TemplateSpecializationType 0x{{[0-9A-Fa-f]+}} '__type_pack_element<0, Ts...>' dependent __type_pack_element
+// CHECK-NEXT:   |-TemplateArgument expr
+// CHECK-NEXT:   | `-ConstantExpr 0x{{[0-9A-Fa-f]+}}  'unsigned long'
+// CHECK-NEXT:   |   |-value: Int 0
+// CHECK-NEXT:   |   `-ImplicitCastExpr 0x{{[0-9A-Fa-f]+}}  'unsigned long' 
+// CHECK-NEXT:   | `-IntegerLiteral 0x{{[0-9A-Fa-f]+}}  'int' 0
+// CHECK-NEXT:   `-TemplateArgument type 'Ts...'
+// CHECK-NEXT: `-PackExpansionType 0x{{[0-9A-Fa-f]+}} 'Ts...' dependent
+// CHECK-NEXT:   `-TemplateTypeParmType 0x{{[0-9A-Fa-f]+}} 'Ts' dependent contains_unexpanded_pack depth 0 index 1 pack
+// CHECK-NEXT: `-TemplateTypeParm 0x{{[0-9A-Fa-f]+}} 'Ts'
+
+  using test4 = __type_pack_element;
+//  CHECK: `-TypeAliasDecl 0x{{[0-9A-Fa-f]+}}  col:9 test4 '__type_pack_element':'__type_pack_element'
+// CHECK-NEXT:   `-ElaboratedType 0x{{[0-9A-Fa-f]+}} '__type_pack_element' sugar dependent
+// CHECK-NEXT: `-TemplateSpecializationType 0x{{[0-9A-Fa-f]+}} '__type_pack_element' dependent __type_pack_element
+// CHECK-NEXT:   |-TemplateArgument expr
+// CHECK-NEXT:   | `-ImplicitCastExpr 0x{{[0-9A-Fa-f]+}}  'unsigned long' 
+// CHECK-NEXT:   |   `-DeclRefExpr 0x{{[0-9A-Fa-f]+}}  'int' NonTypeTemplateParm 0x{{[0-9A-Fa-f]+}} 'N' 'int'
+// CHECK-NEXT:   `-TemplateArgument type 'int'
+// CHECK-NEXT: `-BuiltinType 0x{{[0-9A-Fa-f]+}} 'int'
+};
+
+template  struct B; // expected-note {{template is declared here}}
+template  struct B> {};
+template struct B; // expected-error {{explicit instantiation of undefined template}}
+
+template  struct C; // expected-note {{template is declared here}}
+template  struct C> {};
+template struct C; // expected-error {{explicit instantiation of undefined template}}
+
+template  struct D;
+template  struct D<__type_pack_element<0, T, U>> {};
+template  struct D<__type_pack_element<0, U, T>> {};
+
+template  struct E;
+template  struct E<__type_pack_element<0, T>> {};
+template  struct E<__type_pack_element<0, T, U>> {};
Index: clang/test/SemaTemplate/make_integer_seq.cpp
===
--- /dev/null
+++ clang/test/SemaTemplate/m

[PATCH] D130308: [clang] extend getCommonSugaredType to merge sugar nodes

2022-09-15 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov updated this revision to Diff 460588.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130308

Files:
  clang/include/clang/AST/ASTContext.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/test/SemaCXX/sugar-common-types.cpp
  clang/test/SemaTemplate/deduction.cpp
  libcxx/DELETE.ME

Index: libcxx/DELETE.ME
===
--- libcxx/DELETE.ME
+++ libcxx/DELETE.ME
@@ -1 +1,2 @@
 D111509
+D130308
Index: clang/test/SemaTemplate/deduction.cpp
===
--- clang/test/SemaTemplate/deduction.cpp
+++ clang/test/SemaTemplate/deduction.cpp
@@ -190,6 +190,14 @@
 }
 } // namespace test7
 
+namespace test8 {
+template  void foo(T);
+void test(int a) {
+char n[a];
+foo(n);
+}
+} // namespace test8
+
 // Verify that we can deduce enum-typed arguments correctly.
 namespace test14 {
   enum E { E0, E1 };
Index: clang/test/SemaCXX/sugar-common-types.cpp
===
--- clang/test/SemaCXX/sugar-common-types.cpp
+++ clang/test/SemaCXX/sugar-common-types.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++20 -fenable-matrix
+// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++20 -fenable-matrix -triple i686-pc-win32
 
 enum class N {};
 
@@ -38,3 +38,77 @@
 N t7 = X4() + Y4(); // expected-error {{rvalue of type 'B4'}}
 N t8 = X4() * Y4(); // expected-error {{rvalue of type 'B4'}}
 N t9 = X5() * Y5(); // expected-error {{rvalue of type 'A4 __attribute__((matrix_type(3, 3)))'}}
+
+template  struct S1 {
+  template  struct S2 {};
+};
+
+N t10 = 0 ? S1() : S1(); // expected-error {{from 'S1' (aka 'S1')}}
+N t11 = 0 ? S1::S2() : S1::S2(); // expected-error {{from 'S1::S2' (aka 'S2')}}
+
+template  using Al = S1;
+
+N t12 = 0 ? Al() : Al(); // expected-error {{from 'Al' (aka 'S1')}}
+
+#define AS1 __attribute__((address_space(1)))
+#define AS2 __attribute__((address_space(1)))
+using AS1X1 = AS1 B1;
+using AS1Y1 = AS1 B1;
+using AS2Y1 = AS2 B1;
+N t13 = 0 ? (AS1X1){} : (AS1Y1){}; // expected-error {{rvalue of type 'AS1 B1' (aka '__attribute__((address_space(1))) int')}}
+N t14 = 0 ? (AS1X1){} : (AS2Y1){}; // expected-error {{rvalue of type '__attribute__((address_space(1))) B1' (aka '__attribute__((address_space(1))) int')}}
+
+using FX1 = X1 ();
+using FY1 = Y1 ();
+N t15 = 0 ? (FX1*){} : (FY1*){}; // expected-error {{rvalue of type 'B1 (*)()' (aka 'int (*)()')}}
+
+struct SS1 {};
+using SB1 = SS1;
+using SX1 = SB1;
+using SY1 = SB1;
+
+using MFX1 = X1 SX1::*();
+using MFY1 = Y1 SY1::*();
+
+N t16 = 0 ? (MFX1*){} : (MFY1*){}; // expected-error {{rvalue of type 'B1 SB1::*(*)()'}}
+
+N t17 = 0 ? (FX1 SX1::*){} : (FY1 SY1::*){}; // expected-error {{rvalue of type 'B1 (SB1::*)() __attribute__((thiscall))'}}
+
+N t18 = 0 ? (__typeof(X1*)){} : (__typeof(Y1*)){}; // expected-error {{rvalue of type 'typeof(B1 *)' (aka 'int *')}}
+
+struct Enums {
+  enum X : B1;
+  enum Y : ::B1;
+};
+using EnumsB = Enums;
+using EnumsX = EnumsB;
+using EnumsY = EnumsB;
+
+N t19 = 0 ? (__underlying_type(EnumsX::X)){} : (__underlying_type(EnumsY::Y)){};
+// expected-error@-1 {{rvalue of type 'B1' (aka 'int')}}
+
+N t20 = 0 ? (__underlying_type(EnumsX::X)){} : (__underlying_type(EnumsY::X)){};
+// expected-error@-1 {{rvalue of type '__underlying_type(Enums::X)' (aka 'int')}}
+
+using SBTF1 = SS1 [[clang::btf_type_tag("1")]];
+using SBTF2 = ::SS1 [[clang::btf_type_tag("1")]];
+using SBTF3 = ::SS1 [[clang::btf_type_tag("2")]];
+
+N t21 = 0 ? (SBTF1){} : (SBTF3){}; // expected-error {{from 'SS1'}}
+N t22 = 0 ? (SBTF1){} : (SBTF2){}; // expected-error {{from 'SS1 btf_type_tag(1)' (aka 'SS1')}}
+
+using QX = const SB1 *;
+using QY = const ::SB1 *;
+N t23 = 0 ? (QX){} : (QY){}; // expected-error {{rvalue of type 'const SB1 *' (aka 'const SS1 *')}}
+
+template  using Alias = short;
+N t24 = 0 ? (Alias){} : (Alias){}; // expected-error {{rvalue of type 'Alias' (aka 'short')}}
+N t25 = 0 ? (Alias){} : (Alias){}; // expected-error {{rvalue of type 'short'}}
+
+template  concept C1 = true;
+template  concept C2 = true;
+C1 auto t26_1 = (SB1){};
+C1 auto t26_2 = (::SB1){};
+C2 auto t26_3 = (::SB1){};
+N t26 = 0 ? t26_1 : t26_2; // expected-error {{from 'SB1' (aka 'SS1')}}
+N t27 = 0 ? t26_1 : t26_3; // expected-error {{from 'SB1' (aka 'SS1')}}
Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3825,13 +3825,11 @@
 //   - If A is an array type, the pointer type produced by the
 // array-to-pointer standard conversion (4.2) is used in place of
 // A for type deduction; otherwise,
-if (ArgType->isArrayType())
-  ArgType = S.Context.getArr

[PATCH] D111509: [clang] use getCommonSugar in an assortment of places

2022-09-15 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov updated this revision to Diff 460587.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111509

Files:
  clang-tools-extra/clangd/unittests/tweaks/ExtractVariableTests.cpp
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/narrowing-conversions-ignoreconversionfromtypes-option.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/test/AST/ast-dump-fpfeatures.cpp
  clang/test/CodeGen/compound-assign-overflow.c
  clang/test/Sema/complex-int.c
  clang/test/Sema/matrix-type-operators.c
  clang/test/Sema/nullability.c
  clang/test/Sema/sugar-common-types.c
  clang/test/SemaCXX/complex-conversion.cpp
  clang/test/SemaCXX/matrix-type-operators.cpp
  clang/test/SemaCXX/sugar-common-types.cpp
  clang/test/SemaCXX/sugared-auto.cpp
  clang/test/SemaObjC/format-strings-objc.m
  compiler-rt/test/ubsan/TestCases/Integer/add-overflow.cpp
  compiler-rt/test/ubsan/TestCases/Integer/no-recover.cpp
  compiler-rt/test/ubsan/TestCases/Integer/sub-overflow.cpp
  compiler-rt/test/ubsan/TestCases/Integer/uadd-overflow.cpp
  compiler-rt/test/ubsan/TestCases/Integer/umul-overflow.cpp
  compiler-rt/test/ubsan/TestCases/Integer/usub-overflow.cpp
  libcxx/DELETE.ME
  lldb/test/API/commands/expression/rdar42038760/main.c
  lldb/test/API/commands/expression/rdar44436068/main.c

Index: lldb/test/API/commands/expression/rdar44436068/main.c
===
--- lldb/test/API/commands/expression/rdar44436068/main.c
+++ lldb/test/API/commands/expression/rdar44436068/main.c
@@ -3,6 +3,6 @@
 __int128_t n = 1;
 n = n + n;
 return n; //%self.expect("p n", substrs=['(__int128_t) $0 = 2'])
-  //%self.expect("p n + 6", substrs=['(__int128) $1 = 8'])
-  //%self.expect("p n + n", substrs=['(__int128) $2 = 4'])
+  //%self.expect("p n + 6", substrs=['(__int128_t) $1 = 8'])
+  //%self.expect("p n + n", substrs=['(__int128_t) $2 = 4'])
 }
Index: lldb/test/API/commands/expression/rdar42038760/main.c
===
--- lldb/test/API/commands/expression/rdar42038760/main.c
+++ lldb/test/API/commands/expression/rdar42038760/main.c
@@ -10,7 +10,7 @@
   struct S0 l_19;
   l_19.f2 = 419;
   uint32_t l_4037 = 4294967295UL;
-  l_19.f2 = g_463; //%self.expect("expr ((l_4037 % (-(g_463))) | l_19.f2)", substrs=['(unsigned int) $0 = 358717883'])
+  l_19.f2 = g_463; //%self.expect("expr ((l_4037 % (-(g_463))) | l_19.f2)", substrs=['(uint32_t) $0 = 358717883'])
 }
 int main()
 {
Index: libcxx/DELETE.ME
===
--- /dev/null
+++ libcxx/DELETE.ME
@@ -0,0 +1 @@
+D111509
Index: compiler-rt/test/ubsan/TestCases/Integer/usub-overflow.cpp
===
--- compiler-rt/test/ubsan/TestCases/Integer/usub-overflow.cpp
+++ compiler-rt/test/ubsan/TestCases/Integer/usub-overflow.cpp
@@ -12,12 +12,12 @@
 
 #ifdef SUB_I32
   (void)(uint32_t(1) - uint32_t(2));
-  // CHECK-SUB_I32: usub-overflow.cpp:[[@LINE-1]]:22: runtime error: unsigned integer overflow: 1 - 2 cannot be represented in type 'unsigned int'
+  // CHECK-SUB_I32: usub-overflow.cpp:[[@LINE-1]]:22: runtime error: unsigned integer overflow: 1 - 2 cannot be represented in type '{{uint32_t|unsigned int}}'
 #endif
 
 #ifdef SUB_I64
   (void)(uint64_t(800ll) - uint64_t(900ll));
-  // CHECK-SUB_I64: 800 - 900 cannot be represented in type 'unsigned {{long( long)?}}'
+  // CHECK-SUB_I64: 800 - 900 cannot be represented in type '{{uint64_t|unsigned long( long)?}}'
 #endif
 
 #ifdef SUB_I128
@@ -26,6 +26,6 @@
 # else
   puts("__int128 not supported\n");
 # endif
-  // CHECK-SUB_I128: {{0x4000 - 0x8000 cannot be represented in type 'unsigned __int128'|__int128 not supported}}
+  // CHECK-SUB_I128: {{0x4000 - 0x8000 cannot be represented in type '__uint128_t'|__int128 not supported}}
 #endif
 }
Index: compiler-rt/test/ubsan/TestCases/Integer/umul-overflow.cpp
===
--- compiler-rt/test/ubsan/TestCases/Integer/umul-overflow.cpp
+++ compiler-rt/test/ubsan/TestCases/Integer/umul-overflow.cpp
@@ -13,7 +13,7 @@
   (void)(uint16_t(0x) * uint16_t(0x8001));
 
   (void)(uint32_t(0x) * uint32_t(0x2));
-  // CHECK: umul-overflow.cpp:15:31: runtime error: unsigned integer overflow: 4294967295 * 2 cannot be represented in type 'unsigned int'
+  // CHECK: umul-overflow.cpp:15:31: runtime error: unsigned integer overflow: 4294967295 * 2 cannot be represented in type '{{uint32_t|unsigned int}}'
 
   return 0;
 }
Index: compiler-rt/test/ubsan/TestCases/Integer/uadd-overflow.cpp
=

[PATCH] D111283: [clang] template / auto deduction deduces common sugar

2022-09-15 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

In D111283#3786678 , @mizvekov wrote:

> @alexfh This new revision that I just pushed should be good.
>
> Do you want to give it a look / test, or should we go ahead and merge it?

Thanks for the fix! If it fixes the test case I provided, that should be enough 
for now. If it breaks anything else, we'll find this out in a few days after 
you land the patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111283

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


[PATCH] D133705: [HIP] Fix unbundling archive

2022-09-15 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D133705#3793931 , @MaskRay wrote:

> I know very little about HIP, but I am concerned with relying on extensions 
> as well. For example, I've seen `libc++.a.1` (we use this for the real 
> archive while `libc++.a` is a linker script) and `.la` (libtool).
> A `.so` file is sometimes a linker script and it may reference an archive 
> file. For example glibc `libc.so` typically does something like `GROUP ( 
> /lib/x86_64-linux-gnu/libc.so.6 /usr/lib/x86_64-linux-gnu/libc_nonshared.a  
> AS_NEEDED ( /lib64/ld-linux-x86-64.so.2 ) )`
>
> An ELF linker doesn't really care what extensions are used for what kind of 
> input (archive,relocatable file,shared object). `.a` and `.so` are only used 
> for `-lfoo` lookup.

For HIP, we only need to unbundle archive files. We always try to unbundle 
files passed by `-l` options. If it is not archive files, it is OK, since the 
unbundled will generate an empty file. For input files, the current patch only 
tries to unbundle '*.a' or '*.lib' files. If it is a concern that some archive 
files not with extension '*.a' or '*.lib' are missed, one solution might be to 
try to unbundle any files classified as 'Nothing' (which is how clang 
classifies archive files).


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

https://reviews.llvm.org/D133705

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


[PATCH] D133705: [HIP] Fix unbundling archive

2022-09-15 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D133705#3793702 , @tra wrote:

> In D133705#3785470 , @yaxunl wrote:
>
>>> Also, using `lib*.a` as pattern to tell device libraries from the host-ony 
>>> one will be insufficient. There will be libraries with other extensions 
>>> (e.g. `.lo` is fairly common) and there will be libraries that do not have 
>>> `lib` prefix. I.e. nothing stops me from building `mylib.a` and linking 
>>> with it as in the example above.
>>
>> For archives passed as input files, we use the extension ('.a' on Linux and 
>> '.lib' on MSVC) to identify them. We do not restrict the file names to 
>> 'lib*.a', but they need to be '*.a' or '*.lib' to be identified as archives.
>
> As I've pointed above that will create issues.
>
>> For arbitrary file names to be identified as archives, users can pass them 
>> by '-l:', e.g. '-l:file.bin', then clang will treat 'file.bin' as an archive.
>
> It's not always possible. Linking with dependencies is often handled by the 
> build tools that the end user may not control. E.g. TF is built w/ `bazel` 
> which handles virtually all linking under the hood with almost no user 
> controls over the names/extensions it assigns to files or how they are passed 
> to the linker.
>
> @MaskRay - WDYT?

A side note: this patch does not change clang's original behavior about how to 
link archives in host compilation. It only changes how clang determines what 
files to be unbundled as archives. The current patch only treats '*.a' or 
'*.lib' input files as archives and tries to unbundle them.

I think the root issue is that clang lacks a way to mark an arbitrary file name 
as an archive file. One solution might be to introduce a new file type 
'Archive' and a '-x' value 'archive' to represent that. However, there are some 
complications with how currently clang treated '.lib' files. This makes me 
hesitate to introduce such changes. Since such unavoidably will affect how 
clang links archives for host compilation. My current patch does not change 
that. It has a limitation, but that limitation only affects HIP and I think it 
is acceptable.


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

https://reviews.llvm.org/D133705

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


[PATCH] D133732: [clang-doc] Support default args for functions.

2022-09-15 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth accepted this revision.
paulkirth added a comment.
This revision is now accepted and ready to land.

Lgtm


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

https://reviews.llvm.org/D133732

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


[PATCH] D133705: [HIP] Fix unbundling archive

2022-09-15 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

I know very little about HIP, but I am concerned with relying on extensions as 
well. For example, I've seen `libc++.a.1` (we use this for the real archive 
while `libc++.a` is a linker script) and `.la` (libtool).
A `.so` file is sometimes a linker script and it may reference an archive file. 
For example glibc `libc.so` typically does something like `GROUP ( 
/lib/x86_64-linux-gnu/libc.so.6 /usr/lib/x86_64-linux-gnu/libc_nonshared.a  
AS_NEEDED ( /lib64/ld-linux-x86-64.so.2 ) )`


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

https://reviews.llvm.org/D133705

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


[PATCH] D133998: [HIP][test] Avoid %T

2022-09-15 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 460569.
MaskRay added a comment.

fix all hip-*


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133998

Files:
  clang/test/Driver/hip-link-bc-to-bc.hip
  clang/test/Driver/hip-link-bundle-archive.hip
  clang/test/Driver/hip-link-save-temps.hip
  clang/test/Driver/hip-phases.hip
  clang/test/Driver/hip-runtime-libs-linux.hip
  clang/test/Driver/hip-toolchain-no-rdc.hip
  clang/test/Driver/hip-toolchain-rdc-separate.hip

Index: clang/test/Driver/hip-toolchain-rdc-separate.hip
===
--- clang/test/Driver/hip-toolchain-rdc-separate.hip
+++ clang/test/Driver/hip-toolchain-rdc-separate.hip
@@ -1,6 +1,7 @@
 // REQUIRES: x86-registered-target
 // REQUIRES: amdgpu-registered-target
 
+// RUN: rm -rf %t && mkdir %t
 // RUN: %clang -c -### --target=x86_64-linux-gnu \
 // RUN:   -x hip --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
 // RUN:   --hip-device-lib=lib1.bc --hip-device-lib=lib2.bc \
@@ -81,24 +82,23 @@
 // CHECK-SAME: "-targets=hip-amdgcn-amd-amdhsa-gfx803,hip-amdgcn-amd-amdhsa-gfx900,host-x86_64-unknown-linux-gnu"
 // CHECK-SAME: "-output=[[B_O:.*b.o]]" "-input=[[B_BC1]]" "-input=[[B_BC2]]" "-input=[[B_OBJ_HOST]]"
 
-// RUN: touch %T/a.o
-// RUN: touch %T/b.o
+// RUN: touch %t/a.o %t/b.o
 // RUN: %clang --hip-link -### --target=x86_64-linux-gnu \
 // RUN:   --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
 // RUN:   -fuse-ld=lld -fgpu-rdc -nogpuinc \
-// RUN:   %T/a.o %T/b.o \
+// RUN:   %t/a.o %t/b.o \
 // RUN: 2>&1 | FileCheck -check-prefixes=LINK,LINK-HOST-UNBUNDLE,LLD-TMP,LINK-BUNDLE,LINK-EMBED %s
 
 // RUN: %clang --hip-link -### --target=x86_64-linux-gnu \
 // RUN:   --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
 // RUN:   -fuse-ld=lld -fgpu-rdc -nogpuinc \
-// RUN:   %T/a.o %T/b.o --cuda-device-only \
+// RUN:   %t/a.o %t/b.o --cuda-device-only \
 // RUN: 2>&1 | FileCheck -check-prefixes=LINK,LLD-TMP,LINK-BUNDLE,LINK-NOEMBED %s
 
 // RUN: %clang --hip-link -### --target=x86_64-linux-gnu \
 // RUN:   --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
 // RUN:   -fuse-ld=lld -fgpu-rdc -nogpuinc \
-// RUN:   %T/a.o %T/b.o --cuda-device-only --no-gpu-bundle-output \
+// RUN:   %t/a.o %t/b.o --cuda-device-only --no-gpu-bundle-output \
 // RUN: 2>&1 | FileCheck -check-prefixes=LINK,LLD-FIN,LINK-NOBUNDLE,LINK-NOEMBED %s
 
 // LINK-HOST-UNBUNDLE: [[BUNDLER:".*clang-offload-bundler"]] "-type=o"
Index: clang/test/Driver/hip-toolchain-no-rdc.hip
===
--- clang/test/Driver/hip-toolchain-no-rdc.hip
+++ clang/test/Driver/hip-toolchain-no-rdc.hip
@@ -1,6 +1,7 @@
 // REQUIRES: x86-registered-target
 // REQUIRES: amdgpu-registered-target
 
+// RUN: rm -rf %t && mkdir %t
 // RUN: %clang -### --target=x86_64-linux-gnu -fno-gpu-rdc \
 // RUN:   -x hip --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
 // RUN:   --hip-device-lib=lib1.bc --hip-device-lib=lib2.bc \
@@ -31,12 +32,11 @@
 // RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
 // RUN: 2>&1 | FileCheck -check-prefixes=CHECK %s
 
-// RUN: touch %T/a.o
-// RUN: touch %T/b.o
+// RUN: touch %t/a.o %t/b.o
 // RUN: %clang -### --target=x86_64-linux-gnu \
 // RUN:   --hip-link --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
 // RUN:   -fuse-ld=lld -nogpuinc \
-// RUN:   %T/a.o %T/b.o \
+// RUN:   %t/a.o %t/b.o \
 // RUN: 2>&1 | FileCheck -check-prefixes=LKONLY %s
 
 //
Index: clang/test/Driver/hip-runtime-libs-linux.hip
===
--- clang/test/Driver/hip-runtime-libs-linux.hip
+++ clang/test/Driver/hip-runtime-libs-linux.hip
@@ -13,12 +13,11 @@
 // RUN:   | FileCheck -check-prefixes=ROCM-PATH %s
 
 // Test detecting latest /opt/rocm-{release} directory.
-// RUN: rm -rf %T/opt
-// RUN: mkdir -p %T/opt
-// RUN: cp -r %S/Inputs/rocm %T/opt/rocm-3.9.0-1234
-// RUN: cp -r %S/Inputs/rocm %T/opt/rocm-3.10.0
+// RUN: rm -rf %t && mkdir -p %t/opt
+// RUN: cp -r %S/Inputs/rocm %t/opt/rocm-3.9.0-1234
+// RUN: cp -r %S/Inputs/rocm %t/opt/rocm-3.10.0
 // RUN: %clang -### --hip-link --target=x86_64-linux-gnu \
-// RUN:   --sysroot=%T %t.o 2>&1 \
+// RUN:   --sysroot=%t %t.o 2>&1 \
 // RUN:   | FileCheck -check-prefixes=ROCM-REL %s
 
 // Test HIP runtime lib is not linked without --hip-link.
Index: clang/test/Driver/hip-phases.hip
===
--- clang/test/Driver/hip-phases.hip
+++ clang/test/Driver/hip-phases.hip
@@ -305,23 +305,23 @@
 //
 // Test linking two objects with two gpu architectures.
 //
-// RUN: touch %T/obj1.o
-// RUN: touch %T/obj2.o
-//
+// RUN: rm -rf %t && mkdir %t
+// RUN: touch %t/obj1.o %t/obj2.o
+
 // RUN: %clang --target=x86_64-unknown-linux-gnu -ccc-print-phases --hip-link \
-// RUN: --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 %T/obj1.o %T/obj2.o 2>&1 \
+// RUN: --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx90

[PATCH] D133998: [HIP][test] Avoid %T

2022-09-15 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay created this revision.
MaskRay added reviewers: tra, yaxunl.
Herald added a subscriber: StephenFan.
Herald added a project: All.
MaskRay requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

%T is a deprecated lit feature. It refers to the parent directory.
Another test/Driver test may corrupt the %T use of hip-link-bundle-archive.hip


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133998

Files:
  clang/test/Driver/hip-link-bundle-archive.hip


Index: clang/test/Driver/hip-link-bundle-archive.hip
===
--- clang/test/Driver/hip-link-bundle-archive.hip
+++ clang/test/Driver/hip-link-bundle-archive.hip
@@ -3,16 +3,17 @@
 
 // Check clang unbundle the archive and link them by lld.
 
-// RUN: touch %T/libhipBundled.a
+// RUN: rm -rf %t && mkdir %t
+// RUN: touch %t/libhipBundled.a
 // RUN: %clang -### --offload-arch=gfx906 --offload-arch=gfx1030 \
 // RUN:   --target=x86_64-unknown-linux-gnu \
-// RUN:   -nogpulib %s -fgpu-rdc -L%T -lhipBundled \
+// RUN:   -nogpulib %s -fgpu-rdc -L%t -lhipBundled \
 // RUN:   2>&1 | FileCheck -check-prefix=GNU %s
 
-// RUN: touch %T/hipBundled2.lib
+// RUN: touch %t/hipBundled2.lib
 // RUN: %clang -### --offload-arch=gfx906 --offload-arch=gfx1030 \
 // RUN:   --target=x86_64-pc-windows-msvc \
-// RUN:   -nogpulib %s -fgpu-rdc -L%T -lhipBundled2 \
+// RUN:   -nogpulib %s -fgpu-rdc -L%t -lhipBundled2 \
 // RUN:   2>&1 | FileCheck -check-prefix=MSVC %s
 
 // GNU: "{{.*}}clang-offload-bundler" "-unbundle" "-type=a" 
"-input={{.*}}libhipBundled.a" "-targets=hip-amdgcn-amd-amdhsa-gfx1030" 
"-output=[[A1030:.*\.a]]" "-allow-missing-bundles"


Index: clang/test/Driver/hip-link-bundle-archive.hip
===
--- clang/test/Driver/hip-link-bundle-archive.hip
+++ clang/test/Driver/hip-link-bundle-archive.hip
@@ -3,16 +3,17 @@
 
 // Check clang unbundle the archive and link them by lld.
 
-// RUN: touch %T/libhipBundled.a
+// RUN: rm -rf %t && mkdir %t
+// RUN: touch %t/libhipBundled.a
 // RUN: %clang -### --offload-arch=gfx906 --offload-arch=gfx1030 \
 // RUN:   --target=x86_64-unknown-linux-gnu \
-// RUN:   -nogpulib %s -fgpu-rdc -L%T -lhipBundled \
+// RUN:   -nogpulib %s -fgpu-rdc -L%t -lhipBundled \
 // RUN:   2>&1 | FileCheck -check-prefix=GNU %s
 
-// RUN: touch %T/hipBundled2.lib
+// RUN: touch %t/hipBundled2.lib
 // RUN: %clang -### --offload-arch=gfx906 --offload-arch=gfx1030 \
 // RUN:   --target=x86_64-pc-windows-msvc \
-// RUN:   -nogpulib %s -fgpu-rdc -L%T -lhipBundled2 \
+// RUN:   -nogpulib %s -fgpu-rdc -L%t -lhipBundled2 \
 // RUN:   2>&1 | FileCheck -check-prefix=MSVC %s
 
 // GNU: "{{.*}}clang-offload-bundler" "-unbundle" "-type=a" "-input={{.*}}libhipBundled.a" "-targets=hip-amdgcn-amd-amdhsa-gfx1030" "-output=[[A1030:.*\.a]]" "-allow-missing-bundles"
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132984: Set HOME for tests that use module cache path

2022-09-15 Thread Pirama Arumuga Nainar via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7fe475756b26: Set HOME for tests that use module cache path 
(authored by ccross, committed by pirama).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132984

Files:
  clang/test/Driver/modules-cache-path.m
  clang/test/Modules/driver.c
  clang/test/Unit/lit.cfg.py


Index: clang/test/Unit/lit.cfg.py
===
--- clang/test/Unit/lit.cfg.py
+++ clang/test/Unit/lit.cfg.py
@@ -30,6 +30,9 @@
 if 'TEMP' in os.environ:
 config.environment['TEMP'] = os.environ['TEMP']
 
+if 'HOME' in os.environ:
+config.environment['HOME'] = os.environ['HOME']
+
 # Propagate sanitizer options.
 for var in [
 'ASAN_SYMBOLIZER_PATH',
Index: clang/test/Modules/driver.c
===
--- clang/test/Modules/driver.c
+++ clang/test/Modules/driver.c
@@ -1,4 +1,4 @@
-// RUN: %clang -fmodules -fimplicit-module-maps %s -### 2>&1 | FileCheck 
-check-prefix CHECK-NO_MODULE_CACHE %s
+// RUN: env HOME=%t.home %clang -fmodules -fimplicit-module-maps %s -### 2>&1 
| FileCheck -check-prefix CHECK-NO_MODULE_CACHE %s
 // RUN: %clang -fmodules -fimplicit-module-maps -fmodules-cache-path=blarg %s 
-### 2>&1 | FileCheck -check-prefix CHECK-WITH_MODULE_CACHE %s
 
 // CHECK-NO_MODULE_CACHE: {{clang.*"-fmodules-cache-path=.*ModuleCache"}}
Index: clang/test/Driver/modules-cache-path.m
===
--- clang/test/Driver/modules-cache-path.m
+++ clang/test/Driver/modules-cache-path.m
@@ -1,4 +1,4 @@
-// RUN: %clang -fmodules -### %s 2>&1 | FileCheck %s 
-check-prefix=CHECK-DEFAULT
+// RUN: env HOME=%t.home %clang -fmodules -### %s 2>&1 | FileCheck %s 
-check-prefix=CHECK-DEFAULT
 // CHECK-DEFAULT: -fmodules-cache-path={{.*}}clang{{[/\\]+}}ModuleCache
 
 // RUN: env CLANG_MODULE_CACHE_PATH=/dev/null \


Index: clang/test/Unit/lit.cfg.py
===
--- clang/test/Unit/lit.cfg.py
+++ clang/test/Unit/lit.cfg.py
@@ -30,6 +30,9 @@
 if 'TEMP' in os.environ:
 config.environment['TEMP'] = os.environ['TEMP']
 
+if 'HOME' in os.environ:
+config.environment['HOME'] = os.environ['HOME']
+
 # Propagate sanitizer options.
 for var in [
 'ASAN_SYMBOLIZER_PATH',
Index: clang/test/Modules/driver.c
===
--- clang/test/Modules/driver.c
+++ clang/test/Modules/driver.c
@@ -1,4 +1,4 @@
-// RUN: %clang -fmodules -fimplicit-module-maps %s -### 2>&1 | FileCheck -check-prefix CHECK-NO_MODULE_CACHE %s
+// RUN: env HOME=%t.home %clang -fmodules -fimplicit-module-maps %s -### 2>&1 | FileCheck -check-prefix CHECK-NO_MODULE_CACHE %s
 // RUN: %clang -fmodules -fimplicit-module-maps -fmodules-cache-path=blarg %s -### 2>&1 | FileCheck -check-prefix CHECK-WITH_MODULE_CACHE %s
 
 // CHECK-NO_MODULE_CACHE: {{clang.*"-fmodules-cache-path=.*ModuleCache"}}
Index: clang/test/Driver/modules-cache-path.m
===
--- clang/test/Driver/modules-cache-path.m
+++ clang/test/Driver/modules-cache-path.m
@@ -1,4 +1,4 @@
-// RUN: %clang -fmodules -### %s 2>&1 | FileCheck %s -check-prefix=CHECK-DEFAULT
+// RUN: env HOME=%t.home %clang -fmodules -### %s 2>&1 | FileCheck %s -check-prefix=CHECK-DEFAULT
 // CHECK-DEFAULT: -fmodules-cache-path={{.*}}clang{{[/\\]+}}ModuleCache
 
 // RUN: env CLANG_MODULE_CACHE_PATH=/dev/null \
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 7fe4757 - Set HOME for tests that use module cache path

2022-09-15 Thread Pirama Arumuga Nainar via cfe-commits

Author: Colin Cross
Date: 2022-09-15T23:58:57Z
New Revision: 7fe475756b26080fe0bb02e8e317662ccc9a01f1

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

LOG: Set HOME for tests that use module cache path

Getting the default module cache path calls llvm::sys::path::cache_directory,
which calls home_directory, which checks the HOME environment variable
before falling back to getpwuid.  When compiling against musl libc,
which does not support NSS, and running on a machine that doesn't have
the current user in /etc/passwd due to NSS, no home directory can
be found.  Set the HOME environment variable in the tests to avoid
depending on getpwuid.

Reviewed By: pirama, srhines

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

Added: 


Modified: 
clang/test/Driver/modules-cache-path.m
clang/test/Modules/driver.c
clang/test/Unit/lit.cfg.py

Removed: 




diff  --git a/clang/test/Driver/modules-cache-path.m 
b/clang/test/Driver/modules-cache-path.m
index 1da27d2143631..302a8bb1e3b97 100644
--- a/clang/test/Driver/modules-cache-path.m
+++ b/clang/test/Driver/modules-cache-path.m
@@ -1,4 +1,4 @@
-// RUN: %clang -fmodules -### %s 2>&1 | FileCheck %s 
-check-prefix=CHECK-DEFAULT
+// RUN: env HOME=%t.home %clang -fmodules -### %s 2>&1 | FileCheck %s 
-check-prefix=CHECK-DEFAULT
 // CHECK-DEFAULT: -fmodules-cache-path={{.*}}clang{{[/\\]+}}ModuleCache
 
 // RUN: env CLANG_MODULE_CACHE_PATH=/dev/null \

diff  --git a/clang/test/Modules/driver.c b/clang/test/Modules/driver.c
index 34fc163a5ccd4..abd2e70404751 100644
--- a/clang/test/Modules/driver.c
+++ b/clang/test/Modules/driver.c
@@ -1,4 +1,4 @@
-// RUN: %clang -fmodules -fimplicit-module-maps %s -### 2>&1 | FileCheck 
-check-prefix CHECK-NO_MODULE_CACHE %s
+// RUN: env HOME=%t.home %clang -fmodules -fimplicit-module-maps %s -### 2>&1 
| FileCheck -check-prefix CHECK-NO_MODULE_CACHE %s
 // RUN: %clang -fmodules -fimplicit-module-maps -fmodules-cache-path=blarg %s 
-### 2>&1 | FileCheck -check-prefix CHECK-WITH_MODULE_CACHE %s
 
 // CHECK-NO_MODULE_CACHE: {{clang.*"-fmodules-cache-path=.*ModuleCache"}}

diff  --git a/clang/test/Unit/lit.cfg.py b/clang/test/Unit/lit.cfg.py
index 6fddb32f8dd7e..60a1e79e9330e 100644
--- a/clang/test/Unit/lit.cfg.py
+++ b/clang/test/Unit/lit.cfg.py
@@ -30,6 +30,9 @@
 if 'TEMP' in os.environ:
 config.environment['TEMP'] = os.environ['TEMP']
 
+if 'HOME' in os.environ:
+config.environment['HOME'] = os.environ['HOME']
+
 # Propagate sanitizer options.
 for var in [
 'ASAN_SYMBOLIZER_PATH',



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


[PATCH] D131853: [clangd] Add doxygen parsing for Hover

2022-09-15 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

In D131853#3792985 , @logankaser 
wrote:

> Is there anything I can do as a random member of the public that wants this 
> and knows C++?

Maybe apply the patch locally, use it for a bit, and provide feedback?

I haven't forgotten about this review and I hope to get to it as time permits.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131853

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


[PATCH] D133756: [clangd] Introduce CompileCommandsAdjuster

2022-09-15 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added inline comments.



Comment at: clang-tools-extra/clangd/GlobalCompilationDatabase.h:165
+// process a file (possibly different from the one in the command).
+class CompileCommandsAdjuster {
+public:

sammccall wrote:
> I have a couple of concerns with this interface:
>  - we seem to be stretching to cover {mangler, querydriver} with one 
> interface, but there's no particular reason to - we never use it 
> polymorphically.
>  - the contract is very vague. If it's just "mutate flags" then some sort of 
> generic `function` seems sufficient
>  - `File` feels out-of-place - it's purely an input for the mangler. If 
> query-driver needs an extra input, will we add that too?
>  - either `CompileCommand` or filename+argv seems reasonable, providing 
> CompileCommand+argv is confusing. 
>  - the name is hard to distinguish from tooling::ArgumentsAdjuster (which is 
> a bad interface)
> 
> The immediate problem being solved is the type of 
> CommandMangler::SystemIncludeExtractor, right?
> Can that just be `unique_function&, StringRef)>` or so? 
> Possibly behind `using SystemIncludeExtractor = ...`.
It's more that `QueryDriverDatabase` 
[uses](https://searchfox.org/llvm/rev/f213128b292da85f68eeebbb68cba1541e1c39e2/clang-tools-extra/clangd/QueryDriverDatabase.cpp#354)
 the `Directory` field of `tooling::CompileCommand` in addition to the 
arguments.

We could add the directory as another argument to the function, but at that 
point why not group the arguments into `tooling::CompileCommand` which is more 
semantically meaningful?

As for polymorphism vs. `unique_function`, I don't feel strongly about that, 
happy to change that up. (I do find `function` more annoying to debug because 
`step into` at a call site in the debugger steps into some hard-to-read library 
code, but that's probably better solved at the debugger tooling level.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133756

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


[PATCH] D133993: [HLSL] Remove global ctor/dtor variable for non-lib profile.

2022-09-15 Thread Xiang Li via Phabricator via cfe-commits
python3kgae created this revision.
python3kgae added reviewers: beanz, pow2clk, bogner.
Herald added a subscriber: Anastasia.
Herald added a project: All.
python3kgae requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

After generated call for ctor/dtor for entry, global variable for ctor/dtor are 
useless.
Remove them for non-lib profiles.
Lib profile still need these in case export function used the global variable 
which require ctor/dtor.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133993

Files:
  clang/lib/CodeGen/CGHLSLRuntime.cpp
  clang/lib/CodeGen/CGHLSLRuntime.h
  clang/test/CodeGenHLSL/GlobalConstructorFunction.hlsl
  clang/test/CodeGenHLSL/GlobalConstructorLib.hlsl
  clang/test/CodeGenHLSL/GlobalConstructors.hlsl
  clang/test/CodeGenHLSL/GlobalDestructors.hlsl

Index: clang/test/CodeGenHLSL/GlobalDestructors.hlsl
===
--- clang/test/CodeGenHLSL/GlobalDestructors.hlsl
+++ clang/test/CodeGenHLSL/GlobalDestructors.hlsl
@@ -39,6 +39,9 @@
   Wag();
 }
 
+// Make sure global variable for ctors/dtors removed.
+// CHECK-NOT:@llvm.global_ctors
+// CHECK-NOT:@llvm.global_dtors
 //CHECK:  define void @main()
 //CHECK-NEXT: entry:
 //CHECK-NEXT:   call void @_GLOBAL__sub_I_GlobalDestructors.hlsl()
Index: clang/test/CodeGenHLSL/GlobalConstructors.hlsl
===
--- clang/test/CodeGenHLSL/GlobalConstructors.hlsl
+++ clang/test/CodeGenHLSL/GlobalConstructors.hlsl
@@ -5,6 +5,9 @@
 [numthreads(1,1,1)]
 void main(unsigned GI : SV_GroupIndex) {}
 
+// Make sure global variable for ctors/dtors removed.
+// CHECK-NOT:@llvm.global_ctors
+// CHECK-NOT:@llvm.global_dtors
 //CHECK:  define void @main()
 //CHECK-NEXT: entry:
 //CHECK-NEXT:   call void @_GLOBAL__sub_I_GlobalConstructors.hlsl()
Index: clang/test/CodeGenHLSL/GlobalConstructorLib.hlsl
===
--- clang/test/CodeGenHLSL/GlobalConstructorLib.hlsl
+++ clang/test/CodeGenHLSL/GlobalConstructorLib.hlsl
@@ -1,5 +1,8 @@
 // RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library -S -emit-llvm -disable-llvm-passes %s -o - | FileCheck %s
 
+// Make sure global variable for ctors exist for lib profile.
+// CHECK:@llvm.global_ctors
+
 RWBuffer Buffer;
 
 [shader("compute")]
Index: clang/test/CodeGenHLSL/GlobalConstructorFunction.hlsl
===
--- clang/test/CodeGenHLSL/GlobalConstructorFunction.hlsl
+++ clang/test/CodeGenHLSL/GlobalConstructorFunction.hlsl
@@ -17,6 +17,10 @@
 [numthreads(1,1,1)]
 void main(unsigned GI : SV_GroupIndex) {}
 
+// Make sure global variable for ctors/dtors removed.
+// CHECK-NOT:@llvm.global_ctors
+// CHECK-NOT:@llvm.global_dtors
+
 //CHECK: define void @main()
 //CHECK-NEXT: entry:
 //CHECK-NEXT:   call void @"?call_me_first@@YAXXZ"()
Index: clang/lib/CodeGen/CGHLSLRuntime.h
===
--- clang/lib/CodeGen/CGHLSLRuntime.h
+++ clang/lib/CodeGen/CGHLSLRuntime.h
@@ -22,6 +22,7 @@
 namespace llvm {
 class GlobalVariable;
 class Function;
+class Triple;
 } // namespace llvm
 namespace clang {
 class VarDecl;
@@ -46,7 +47,7 @@
   virtual ~CGHLSLRuntime() {}
 
   void annotateHLSLResource(const VarDecl *D, llvm::GlobalVariable *GV);
-  void generateGlobalCtorDtorCalls();
+  void generateGlobalCtorDtorCalls(llvm::Triple &T);
 
   void finishCodeGen();
 
Index: clang/lib/CodeGen/CGHLSLRuntime.cpp
===
--- clang/lib/CodeGen/CGHLSLRuntime.cpp
+++ clang/lib/CodeGen/CGHLSLRuntime.cpp
@@ -60,7 +60,7 @@
   if (T.getArch() == Triple::ArchType::dxil)
 addDxilValVersion(TargetOpts.DxilValidatorVersion, M);
 
-  generateGlobalCtorDtorCalls();
+  generateGlobalCtorDtorCalls(T);
   if (CGM.getCodeGenOpts().OptimizationLevel == 0)
 addDisableOptimizations(M);
 }
@@ -180,7 +180,7 @@
   }
 }
 
-void CGHLSLRuntime::generateGlobalCtorDtorCalls() {
+void CGHLSLRuntime::generateGlobalCtorDtorCalls(Triple &T) {
   llvm::Module &M = CGM.getModule();
   SmallVector CtorFns;
   SmallVector DtorFns;
@@ -202,4 +202,13 @@
 for (auto *Fn : DtorFns)
   B.CreateCall(FunctionCallee(Fn));
   }
+
+  // No need to keep global ctors/dtors for non-lib profile after call to
+  // ctors/dtors added for entry.
+  if (T.getEnvironment() != Triple::EnvironmentType::Library) {
+if (auto *GV = M.getNamedGlobal("llvm.global_ctors"))
+  GV->eraseFromParent();
+if (auto *GV = M.getNamedGlobal("llvm.global_dtors"))
+  GV->eraseFromParent();
+  }
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D133956: Cuda Check for ignored errors after calling a CUDA kernel

2022-09-15 Thread Bartłomiej Cieślar via Phabricator via cfe-commits
barcisz added inline comments.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu:53
+  }
+  auto err = cudaGetLastError();
+

tra wrote:
> barcisz wrote:
> > tra wrote:
> > > Just curious -- is it sufficient to just call `cudaGetLastError();` ? Or 
> > > does the checker require using its result, too? I.e. in practice this 
> > > particular check will not really do anything useful. The tests below look 
> > > somewhat inconsistent. 
> > Technically it does not require the user to actually use the value of 
> > `cudaGetLastError()`, but
> > 
> > 
> >   # If they are calling it then they most likely did not place this call 
> > there randomly and are using it to check for the error returned by the 
> > kernel
> >   # the check being introduced in D133804 can be used to check if the 
> > return value has been used, so checking it here as well would have been a 
> > duplication
> > 
> > 
> > 1. If they are calling it then they most likely did not place this call 
> > there randomly and are using it to check for the error returned by the 
> > kernel
> 
> If that's the case, then why kernel launches on lines 45 and 51 are reported 
> as possibly unchecked? Both are followed by the `cudaGetLastError()` call and 
> are, technically checked, if we're not analyzing the usage of the result of 
> the call. 
> 
> What am I missing?
The idea is that the call should happen directly after the kernel without any 
branching (because branching can often make things much harder to understand in 
case of things like for loop make the error not actually have 
`cudaGetLastError()` called after every kernel call



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu:75
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked 
error after a kernel launch.
+  // Calling an error-checking function after a kernel is not considered safe.
+  errorCheck();

tra wrote:
> barcisz wrote:
> > tra wrote:
> > > WDYM by "is not considered safe" here? How is that different from calling 
> > > `cudaGetLastError()` and checking its value?
> > As in the check does not do inter-procedural analysis short of adding the 
> > handler to AcceptedHandlers, so the check will flag such occurences
> Hmm.. Using a helper function to check for cuda errors is a fairly common 
> pattern. 
> Is there a way to annotate such a helper function as `checks 
> cudaGetLastError`?
There would be an easy way to do that, but it's much more common for projects 
to have those helper functions project-wide (or at least sub-project wide) 
which means they can be just specified explicitly for the project in the 
options for the check (the official documentation for the check will be 
uploaded tomorrow)



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu:80-82
+  b<<<1, 2>>>();; /* The semicolons are here because the
+detection of the macro is done with a lexer */ ;
+  CUDA_CHECK_KERNEL();

tra wrote:
> barcisz wrote:
> > tra wrote:
> > > What would happen with a single `;` as would be seen in the normal user 
> > > code?
> > Nothing, it would work just fine; it's rather that all other kernel calls 
> > in this test use a single `;` so I want to check this case here
> I still do not understand how it all fits together. What does a kernel call, 
> the extra `;`, the macro, and the checker code have to do with each other?
> 
> Is the idea that the checker should see though the empty statement between 
> the kernel call and the checker macro?
> If that's the case I'd make it a bit more prominent. E.g. something like this:
> 
> ```
> b<<<1, 2>>>();
> ; /* Make sure that we see through empty expressions in-between the call 
> and the checker. */ ;
>   CUDA_CHECK_KERNEL();
> ```
> 
> 
The reason we're checking for multiple `;`s here is that due to macros not 
being present in the AST they have to be located on the lexer stage, which 
makes it necessary to search for them based on tokens. The tokens used after 
the kernel call here (semicolons and a comment) are the only allowed token 
between the kernel call and the macro, since any other one would indicate 
another statement being present



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu:112
+  do {
+auto err2 = cudaGetLastError();
+  } while(0);

tra wrote:
> barcisz wrote:
> > tra wrote:
> > > Why does this case produce no warning, while a very similar case above 
> > > does? In both cases result of `cudaGetLastError()` is assigned to an 
> > > unused variable within the loop body.
> > > 
> > > ```
> > >   b<<<1, 2>>>();
> > >   // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked 
> > > error after a kernel launch.
> > >   for(;;)
> > > auto err2 = cudaGetLas

[PATCH] D133988: [clang][deps] Make sure ScanInstance outlives collector

2022-09-15 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 460552.
jansvoboda11 added a comment.

Replace `std::shared_ptr` by `Optional` stored on `DependencyScanningAction`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133988

Files:
  clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp


Index: clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -174,7 +174,8 @@
 Scanned = true;
 
 // Create a compiler instance to handle the actual work.
-CompilerInstance ScanInstance(std::move(PCHContainerOps));
+ScanInstanceStorage.emplace(std::move(PCHContainerOps));
+CompilerInstance &ScanInstance = *ScanInstanceStorage;
 ScanInstance.setInvocation(std::move(Invocation));
 
 // Create the compiler's actual diagnostics engine.
@@ -304,7 +305,8 @@
   bool OptimizeArgs;
   bool EagerLoadModules;
   bool DisableFree;
-  llvm::Optional ModuleName;
+  Optional ModuleName;
+  Optional ScanInstanceStorage;
   std::shared_ptr MDC;
   std::vector LastCC1Arguments;
   bool Scanned = false;


Index: clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -174,7 +174,8 @@
 Scanned = true;
 
 // Create a compiler instance to handle the actual work.
-CompilerInstance ScanInstance(std::move(PCHContainerOps));
+ScanInstanceStorage.emplace(std::move(PCHContainerOps));
+CompilerInstance &ScanInstance = *ScanInstanceStorage;
 ScanInstance.setInvocation(std::move(Invocation));
 
 // Create the compiler's actual diagnostics engine.
@@ -304,7 +305,8 @@
   bool OptimizeArgs;
   bool EagerLoadModules;
   bool DisableFree;
-  llvm::Optional ModuleName;
+  Optional ModuleName;
+  Optional ScanInstanceStorage;
   std::shared_ptr MDC;
   std::vector LastCC1Arguments;
   bool Scanned = false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D133942: Clang tidy utility to generate a fix hint for a subsequent expression to the existing one

2022-09-15 Thread Bartłomiej Cieślar via Phabricator via cfe-commits
barcisz updated this revision to Diff 460551.
barcisz added a comment.

Misplaced diff


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133942

Files:
  clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp
  clang-tools-extra/clang-tidy/utils/FixItHintUtils.h

Index: clang-tools-extra/clang-tidy/utils/FixItHintUtils.h
===
--- clang-tools-extra/clang-tidy/utils/FixItHintUtils.h
+++ clang-tools-extra/clang-tidy/utils/FixItHintUtils.h
@@ -11,7 +11,9 @@
 
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
+#include "clang/Basic/SourceManagerInternals.h"
 #include "clang/Sema/DeclSpec.h"
+#include "clang/Tooling/FixIt.h"
 
 namespace clang {
 namespace tidy {
@@ -46,6 +48,17 @@
   DeclSpec::TQ Qualifier,
   QualifierTarget CT = QualifierTarget::Pointee,
   QualifierPolicy CP = QualifierPolicy::Left);
+
+/// \brief Adds a statement to be executed right after this statement .
+/// Is designed for taking potential comments or statements in the same line
+/// into account. The statement should not be an expression that's part of
+/// another statement. The statement range should include the terminator
+/// (semicolon).
+llvm::SmallVector
+addSubsequentStatement(SourceRange stmtRangeWithTerminator,
+   const Stmt &parentStmt, llvm::StringRef nextStmt,
+   ASTContext &context);
+
 } // namespace fixit
 } // namespace utils
 } // namespace tidy
Index: clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp
===
--- clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp
+++ clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp
@@ -223,6 +223,154 @@
 
   return None;
 }
+
+static unsigned int getLineNumber(SourceLocation Loc, SourceManager& SM) {
+  FileID FID;
+  unsigned int Offset;
+  std::tie(FID, Offset) = SM.getDecomposedLoc(Loc);
+  return SM.getLineNumber(FID, Offset);
+}
+
+static std::string getIndent(SourceLocation sLoc, ASTContext& context) {
+  auto& SM = context.getSourceManager();
+
+  const auto sLocLineNo = getLineNumber(sLoc, SM);
+
+  auto indentation_template = tooling::fixit::internal::getText(
+  CharSourceRange::getCharRange(SourceRange(
+  SM.translateLineCol(SM.getFileID(sLoc), sLocLineNo, 1), sLoc)),
+  context);
+
+  std::string indentation;
+  indentation.reserve(indentation_template.size());
+  std::transform(
+  indentation_template.begin(),
+  indentation_template.end(),
+  std::back_inserter(indentation),
+  [](char c) { return isspace(c) ? c : ' '; });
+  return indentation;
+}
+
+llvm::SmallVector addSubsequentStatement(
+SourceRange stmtRangeWithTerminator,
+const Stmt& parentStmt,
+llvm::StringRef nextStmt,
+ASTContext& context) {
+  auto& SM = context.getSourceManager();
+  auto langOpts = context.getLangOpts();
+
+  const auto stmtEndLineNo =
+  getLineNumber(stmtRangeWithTerminator.getEnd(), SM);
+
+  // Find the first token's data for which the next token is
+  // either a line apart or is not a comment
+  SourceLocation lastTokenEndLoc =
+  stmtRangeWithTerminator.getEnd().getLocWithOffset(1);
+  auto lastTokenLine = stmtEndLineNo;
+  bool insertNewLine = true;
+  while (true) {
+llvm::Optional tokenOption = Lexer::findNextToken(
+lastTokenEndLoc.getLocWithOffset(-1), SM, langOpts, true);
+if (!tokenOption) {
+  return llvm::SmallVector();
+}
+if (tokenOption->is(tok::eof)) {
+  insertNewLine = false;
+  break;
+}
+const auto tokenBeginLineNo = getLineNumber(tokenOption->getLocation(), SM);
+
+if (tokenOption->isNot(tok::comment)) {
+  insertNewLine = tokenBeginLineNo != stmtEndLineNo;
+  break;
+}
+if (tokenBeginLineNo > lastTokenLine) {
+  break;
+}
+
+lastTokenEndLoc = tokenOption->getEndLoc();
+lastTokenLine = getLineNumber(tokenOption->getEndLoc(), SM);
+  }
+
+  bool isEnclosedWithBrackets =
+  parentStmt.getStmtClass() == Stmt::CompoundStmtClass;
+
+  // Generating the FixItHint
+  // There are 5 scenarios that we have to take into account:
+  // 1. The statement is enclosed in brackets but the next statement is
+  //in the same line - insert the new statement right after the previous one
+  // 2. The statement is not enclosed in brackets and the next statement is
+  //in the same line - same as 1. and enclose both statements in brackets
+  //on the same line
+  // 3. The statement is enclosed in brackets and the next statement is
+  //on subsequent lines - skip all the comments in this line
+  // 4. The statement is not enclosed in brackets but the next statement is on
+  //subsequent lines - same as 3. and enclose the statements with
+  //google-style multiline brackets (opening bracket right 

[PATCH] D133956: Cuda Check for ignored errors after calling a CUDA kernel

2022-09-15 Thread Bartłomiej Cieślar via Phabricator via cfe-commits
barcisz updated this revision to Diff 460550.
barcisz added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133956

Files:
  clang-tools-extra/clang-tidy/cuda/CMakeLists.txt
  clang-tools-extra/clang-tidy/cuda/CudaTidyModule.cpp
  clang-tools-extra/clang-tidy/cuda/UnsafeKernelCallCheck.cpp
  clang-tools-extra/clang-tidy/cuda/UnsafeKernelCallCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cuda/unsafe-kernel-call.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/cuda/cuda_runtime.h
  
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-function-handler.cu
  
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu

Index: clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu
@@ -0,0 +1,116 @@
+// RUN: %check_clang_tidy %s cuda-unsafe-kernel-call %t -- \
+// RUN:   -config="{CheckOptions: \
+// RUN: [{key: cuda-unsafe-kernel-call.HandlerName, \
+// RUN:   value: 'CUDA_CHECK_KERNEL'}, \
+// RUN:   {key: cuda-unsafe-kernel-call.AcceptedHandlers, \
+// RUN:value: 'ALTERNATIVE_CUDA_CHECK_KERNEL, cudaCheckKernel, \
+// RUN:alternative::alternativeCudaCheckKernel, \
+// RUN:otherAlternativeCudaCheckKernel'}] \
+// RUN: }" \
+// RUN:   -- -isystem %clang_tidy_headers
+
+#include 
+
+#define CUDA_CHECK_KERNEL() do {} while(0)
+
+#define ALTERNATIVE_CUDA_CHECK_KERNEL() CUDA_CHECK_KERNEL()
+
+void cudaCheckKernel();
+
+namespace alternative {
+
+void alternativeCudaCheckKernel();
+void otherAlternativeCudaCheckKernel();
+
+}
+
+__global__
+void b();
+
+#define KERNEL_CALL() do {b<<<1, 2>>>();} while(0)
+
+void errorCheck() {
+  auto err = cudaGetLastError();
+}
+
+void bad() {
+  b<<<1, 2>>>(); // sample comment
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+
+  KERNEL_CALL(); // sample comment
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+  // There isn't supposed to be a fix here since it's a macro call
+
+  if(true)
+b<<<1, 2>>>()  ; // Brackets omitted purposefully, since they create an additional AST node
+// CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+  else {
+b<<<1, 2>>>();
+// CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+b<<<1, 2>>>();
+// CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+  }
+  auto err = cudaGetLastError();
+
+  b<<<1, 2>>>();
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+  if (true)
+cudaGetLastError();
+
+  b<<<1, 2>>>();
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+  for(;;)
+auto err2 = cudaGetLastError(); // Brackets omitted purposefully, since they create an additional AST node
+
+  b<<<1, 2>>>();
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+  auto err3 = true ? 1 : cudaGetLastError();
+
+  b<<<1, 2>>>();
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+  auto err4 = cudaDeviceReset() + cudaGetLastError();
+
+  b<<<1, 2>>>();
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+  // Calling an error-checking function after a kernel is not considered safe.
+  errorCheck();
+}
+
+void good() {
+  b<<<1, 2>>>();; /* The semicolons are here because the
+detection of the macro is done with a lexer */ ;
+  CUDA_CHECK_KERNEL();
+
+  b<<<1, 2>>>();
+  ALTERNATIVE_CUDA_CHECK_KERNEL();
+
+  b<<<1, 2>>>();
+  alternative::alternativeCudaCheckKernel();
+
+  b<<<1, 2>>>();
+  alternative::otherAlternativeCudaCheckKernel();
+
+  b<<<1, 2>>>();
+  switch(1 + cudaGetLastError()) {
+default:;
+  }
+
+  b<<<1, 2>>>();
+  if(3 < cudaGetLastError()) {
+1;
+  } else {
+2;
+  }
+
+  b<<<1, 2>>>();
+  for(int i = cudaGetLastError();;);
+
+  b<<<1, 2>>>();
+  do {
+  do {
+  do {
+auto err2 = cudaGetLastError();
+  } while(0);
+  } while(0);
+  } while(0);
+}
Index: clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-function-handler.cu
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-function-handler.cu
@@ -0,0 +1,150 @@
+// RUN: 

[PATCH] D133991: add new function to release notes

2022-09-15 Thread Anders Langlands via Phabricator via cfe-commits
anderslanglands added a comment.

Sorry, this was supposed to update https://reviews.llvm.org/D13392. How do I 
delete this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133991

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


[PATCH] D133942: Clang tidy utility to generate a fix hint for a subsequent expression to the existing one

2022-09-15 Thread Bartłomiej Cieślar via Phabricator via cfe-commits
barcisz added a comment.

In D133942#3793618 , @njames93 wrote:

> Would I be correct in assuming you have uploaded the wrong diff here?

Yes, sorry, got mixed up with D133956  (6 
diffs ain't easy to shuffle :-/)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133942

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


[PATCH] D133924: add clang_CXXMethod_isDeleted function

2022-09-15 Thread Anders Langlands via Phabricator via cfe-commits
anderslanglands updated this revision to Diff 460549.
anderslanglands added a comment.

Updating based on review

- Add new function to release notes
- Fix failing test and add a new test specifically for this function


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133924

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang-c/Index.h
  clang/test/Index/availability.cpp
  clang/test/Index/deletion.cpp


Index: clang/test/Index/deletion.cpp
===
--- /dev/null
+++ clang/test/Index/deletion.cpp
@@ -0,0 +1,14 @@
+struct Foo {
+  int foo() = delete;
+  int bar();
+  Foo() = delete;
+  Foo(int);
+};
+
+
+// RUN: c-index-test -test-print-type --std=c++11 %s | FileCheck %s
+// CHECK: StructDecl=Foo:1:8 (Definition) [type=Foo] [typekind=Record] 
[isPOD=1]
+// CHECK: CXXMethod=foo:2:7 (unavailable) (deleted) [type=int (){{.*}}] 
[typekind=FunctionProto] [resulttype=int] [resulttypekind=Int] [isPOD=0]
+// CHECK: CXXMethod=bar:3:7 [type=int (){{.*}}] [typekind=FunctionProto] 
[resulttype=int] [resulttypekind=Int] [isPOD=0]
+// CHECK: CXXConstructor=Foo:4:3 (unavailable) (default constructor) (deleted) 
[type=void (){{.*}}] [typekind=FunctionProto] [resulttype=void] 
[resulttypekind=Void] [isPOD=0]
+// CHECK: CXXConstructor=Foo:5:3 (converting constructor) [type=void 
(int){{.*}}] [typekind=FunctionProto] [resulttype=void] [resulttypekind=Void] 
[args= [int] [Int]] [isPOD=0]
Index: clang/test/Index/availability.cpp
===
--- clang/test/Index/availability.cpp
+++ clang/test/Index/availability.cpp
@@ -9,5 +9,5 @@
 // RUN: c-index-test -test-print-type --std=c++11 %s | FileCheck %s
 // CHECK: FunctionDecl=foo:1:6 (unavailable) [type=void ()] 
[typekind=FunctionProto] [resulttype=void] [resulttypekind=Void] [isPOD=0]
 // CHECK: StructDecl=Foo:3:8 (Definition) [type=Foo] [typekind=Record] 
[isPOD=1]
-// CHECK: CXXMethod=foo:4:7 (unavailable) [type=int (){{.*}}] 
[typekind=FunctionProto] [resulttype=int] [resulttypekind=Int] [isPOD=0]
-// CHECK: CXXConstructor=Foo:5:3 (unavailable) (default constructor) 
[type=void (){{.*}}] [typekind=FunctionProto] [resulttype=void] 
[resulttypekind=Void] [isPOD=0]
+// CHECK: CXXMethod=foo:4:7 (unavailable) (deleted) [type=int (){{.*}}] 
[typekind=FunctionProto] [resulttype=int] [resulttypekind=Int] [isPOD=0]
+// CHECK: CXXConstructor=Foo:5:3 (unavailable) (default constructor) (deleted) 
[type=void (){{.*}}] [typekind=FunctionProto] [resulttype=void] 
[resulttypekind=Void] [isPOD=0]
Index: clang/include/clang-c/Index.h
===
--- clang/include/clang-c/Index.h
+++ clang/include/clang-c/Index.h
@@ -4925,7 +4925,7 @@
 CINDEX_LINKAGE unsigned clang_CXXMethod_isDefaulted(CXCursor C);
 
 /**
- * Determine if a C++ method is declared '= default'.
+ * Determine if a C++ method is declared '= delete'.
  */
 CINDEX_LINKAGE unsigned clang_CXXMethod_isDeleted(CXCursor C);
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -319,6 +319,8 @@
   the behavior of `QualType::getUnqualifiedType` for `CXType`.
 - Introduced the new function `clang_getNonReferenceType`, which mimics
   the behavior of `QualType::getNonReferenceType` for `CXType`.
+- Introduced the new function `clang_CXXMethod_isDeleted`, which queries
+  whether the method is declared `= delete.
 
 Static Analyzer
 ---


Index: clang/test/Index/deletion.cpp
===
--- /dev/null
+++ clang/test/Index/deletion.cpp
@@ -0,0 +1,14 @@
+struct Foo {
+  int foo() = delete;
+  int bar();
+  Foo() = delete;
+  Foo(int);
+};
+
+
+// RUN: c-index-test -test-print-type --std=c++11 %s | FileCheck %s
+// CHECK: StructDecl=Foo:1:8 (Definition) [type=Foo] [typekind=Record] [isPOD=1]
+// CHECK: CXXMethod=foo:2:7 (unavailable) (deleted) [type=int (){{.*}}] [typekind=FunctionProto] [resulttype=int] [resulttypekind=Int] [isPOD=0]
+// CHECK: CXXMethod=bar:3:7 [type=int (){{.*}}] [typekind=FunctionProto] [resulttype=int] [resulttypekind=Int] [isPOD=0]
+// CHECK: CXXConstructor=Foo:4:3 (unavailable) (default constructor) (deleted) [type=void (){{.*}}] [typekind=FunctionProto] [resulttype=void] [resulttypekind=Void] [isPOD=0]
+// CHECK: CXXConstructor=Foo:5:3 (converting constructor) [type=void (int){{.*}}] [typekind=FunctionProto] [resulttype=void] [resulttypekind=Void] [args= [int] [Int]] [isPOD=0]
Index: clang/test/Index/availability.cpp
===
--- clang/test/Index/availability.cpp
+++ clang/test/Index/availability.cpp
@@ -9,5 +9,5 @@
 // RUN: c-index-test -test-print-type --std=c++11 %s | FileCheck %s
 // CHECK: FunctionDecl=foo:1:6 (unavail

[PATCH] D133991: add new function to release notes

2022-09-15 Thread Anders Langlands via Phabricator via cfe-commits
anderslanglands created this revision.
Herald added a subscriber: arphaman.
Herald added a project: All.
anderslanglands requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

fix copy/paste error in doc comment

fix failing test now deleted is supported

add new test for clang_CXXMethod_isDeleted


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133991

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang-c/Index.h
  clang/test/Index/availability.cpp
  clang/test/Index/deletion.cpp


Index: clang/test/Index/deletion.cpp
===
--- /dev/null
+++ clang/test/Index/deletion.cpp
@@ -0,0 +1,14 @@
+struct Foo {
+  int foo() = delete;
+  int bar();
+  Foo() = delete;
+  Foo(int);
+};
+
+
+// RUN: c-index-test -test-print-type --std=c++11 %s | FileCheck %s
+// CHECK: StructDecl=Foo:1:8 (Definition) [type=Foo] [typekind=Record] 
[isPOD=1]
+// CHECK: CXXMethod=foo:2:7 (unavailable) (deleted) [type=int (){{.*}}] 
[typekind=FunctionProto] [resulttype=int] [resulttypekind=Int] [isPOD=0]
+// CHECK: CXXMethod=bar:3:7 [type=int (){{.*}}] [typekind=FunctionProto] 
[resulttype=int] [resulttypekind=Int] [isPOD=0]
+// CHECK: CXXConstructor=Foo:4:3 (unavailable) (default constructor) (deleted) 
[type=void (){{.*}}] [typekind=FunctionProto] [resulttype=void] 
[resulttypekind=Void] [isPOD=0]
+// CHECK: CXXConstructor=Foo:5:3 (converting constructor) [type=void 
(int){{.*}}] [typekind=FunctionProto] [resulttype=void] [resulttypekind=Void] 
[args= [int] [Int]] [isPOD=0]
Index: clang/test/Index/availability.cpp
===
--- clang/test/Index/availability.cpp
+++ clang/test/Index/availability.cpp
@@ -9,5 +9,5 @@
 // RUN: c-index-test -test-print-type --std=c++11 %s | FileCheck %s
 // CHECK: FunctionDecl=foo:1:6 (unavailable) [type=void ()] 
[typekind=FunctionProto] [resulttype=void] [resulttypekind=Void] [isPOD=0]
 // CHECK: StructDecl=Foo:3:8 (Definition) [type=Foo] [typekind=Record] 
[isPOD=1]
-// CHECK: CXXMethod=foo:4:7 (unavailable) [type=int (){{.*}}] 
[typekind=FunctionProto] [resulttype=int] [resulttypekind=Int] [isPOD=0]
-// CHECK: CXXConstructor=Foo:5:3 (unavailable) (default constructor) 
[type=void (){{.*}}] [typekind=FunctionProto] [resulttype=void] 
[resulttypekind=Void] [isPOD=0]
+// CHECK: CXXMethod=foo:4:7 (unavailable) (deleted) [type=int (){{.*}}] 
[typekind=FunctionProto] [resulttype=int] [resulttypekind=Int] [isPOD=0]
+// CHECK: CXXConstructor=Foo:5:3 (unavailable) (default constructor) (deleted) 
[type=void (){{.*}}] [typekind=FunctionProto] [resulttype=void] 
[resulttypekind=Void] [isPOD=0]
Index: clang/include/clang-c/Index.h
===
--- clang/include/clang-c/Index.h
+++ clang/include/clang-c/Index.h
@@ -4925,7 +4925,7 @@
 CINDEX_LINKAGE unsigned clang_CXXMethod_isDefaulted(CXCursor C);
 
 /**
- * Determine if a C++ method is declared '= default'.
+ * Determine if a C++ method is declared '= delete'.
  */
 CINDEX_LINKAGE unsigned clang_CXXMethod_isDeleted(CXCursor C);
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -319,6 +319,8 @@
   the behavior of `QualType::getUnqualifiedType` for `CXType`.
 - Introduced the new function `clang_getNonReferenceType`, which mimics
   the behavior of `QualType::getNonReferenceType` for `CXType`.
+- Introduced the new function `clang_CXXMethod_isDeleted`, which queries
+  whether the method is declared `= delete.
 
 Static Analyzer
 ---


Index: clang/test/Index/deletion.cpp
===
--- /dev/null
+++ clang/test/Index/deletion.cpp
@@ -0,0 +1,14 @@
+struct Foo {
+  int foo() = delete;
+  int bar();
+  Foo() = delete;
+  Foo(int);
+};
+
+
+// RUN: c-index-test -test-print-type --std=c++11 %s | FileCheck %s
+// CHECK: StructDecl=Foo:1:8 (Definition) [type=Foo] [typekind=Record] [isPOD=1]
+// CHECK: CXXMethod=foo:2:7 (unavailable) (deleted) [type=int (){{.*}}] [typekind=FunctionProto] [resulttype=int] [resulttypekind=Int] [isPOD=0]
+// CHECK: CXXMethod=bar:3:7 [type=int (){{.*}}] [typekind=FunctionProto] [resulttype=int] [resulttypekind=Int] [isPOD=0]
+// CHECK: CXXConstructor=Foo:4:3 (unavailable) (default constructor) (deleted) [type=void (){{.*}}] [typekind=FunctionProto] [resulttype=void] [resulttypekind=Void] [isPOD=0]
+// CHECK: CXXConstructor=Foo:5:3 (converting constructor) [type=void (int){{.*}}] [typekind=FunctionProto] [resulttype=void] [resulttypekind=Void] [args= [int] [Int]] [isPOD=0]
Index: clang/test/Index/availability.cpp
===
--- clang/test/Index/availability.cpp
+++ clang/test/Index/availability.cpp
@@ -9,5 +9,5 @@
 // RUN: c-index-test -test-print-type --std

[PATCH] D133983: [HLSL] Add SV_DispatchThreadID

2022-09-15 Thread Xiang Li via Phabricator via cfe-commits
python3kgae updated this revision to Diff 460546.
python3kgae added a comment.

Fix warning.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133983

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CGHLSLRuntime.cpp
  clang/lib/CodeGen/CGHLSLRuntime.h
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGenHLSL/semantics/DispatchThreadID.hlsl

Index: clang/test/CodeGenHLSL/semantics/DispatchThreadID.hlsl
===
--- /dev/null
+++ clang/test/CodeGenHLSL/semantics/DispatchThreadID.hlsl
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library -x hlsl -emit-llvm -finclude-default-header -disable-llvm-passes -o - %s
+
+// Make sure SV_DispatchThreadID translated into dx.thread.id.
+
+const RWBuffer In;
+RWBuffer Out;
+
+// CHECK: define void @foo()
+// CHECK: call i32 @llvm.dx.thread.id(i32 0)
+// CHECK: call void @"?foo@@YAXH@Z"(i32 %{{.*}})
+[shader("compute")]
+[numthreads(8,8,1)]
+void foo(int Idx : SV_DispatchThreadID) {
+  Out[Idx] = In[Idx];
+}
+
+// CHECK: define void @bar()
+// CHECK: call i32 @llvm.dx.thread.id(i32 0)
+// CHECK: call i32 @llvm.dx.thread.id(i32 1)
+// CHECK: call void @"?bar@@YAXT?$__vector@H$01@__clang@@@Z"(<2 x i32> %{{.*}})
+[shader("compute")]
+[numthreads(8,8,1)]
+void bar(int2 Idx : SV_DispatchThreadID) {
+  Out[Idx.y] = In[Idx.x];
+}
+
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -6907,6 +6907,25 @@
   D->addAttr(::new (S.Context) HLSLSV_GroupIndexAttr(S.Context, AL));
 }
 
+static void handleHLSLSV_DispatchThreadIDAttr(Sema &S, Decl *D,
+  const ParsedAttr &AL) {
+  using llvm::Triple;
+  Triple Target = S.Context.getTargetInfo().getTriple();
+  // FIXME: it is OK for a compute shader entry and pixiel shader entry live in
+  // same HLSL file.
+  if (Target.getEnvironment() != Triple::Compute &&
+  Target.getEnvironment() != Triple::Library) {
+uint32_t Pipeline =
+(uint32_t)S.Context.getTargetInfo().getTriple().getEnvironment() -
+(uint32_t)llvm::Triple::Pixel;
+S.Diag(AL.getLoc(), diag::err_hlsl_attr_unsupported_in_stage)
+<< AL << Pipeline << "Compute";
+return;
+  }
+
+  D->addAttr(::new (S.Context) HLSLSV_DispatchThreadIDAttr(S.Context, AL));
+}
+
 static void handleHLSLShaderAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
   StringRef Str;
   SourceLocation ArgLoc;
@@ -8920,6 +8939,9 @@
   case ParsedAttr::AT_HLSLSV_GroupIndex:
 handleHLSLSVGroupIndexAttr(S, D, AL);
 break;
+  case ParsedAttr::AT_HLSLSV_DispatchThreadID:
+handleHLSLSV_DispatchThreadIDAttr(S, D, AL);
+break;
   case ParsedAttr::AT_HLSLShader:
 handleHLSLShaderAttr(S, D, AL);
 break;
Index: clang/lib/CodeGen/CGHLSLRuntime.h
===
--- clang/lib/CodeGen/CGHLSLRuntime.h
+++ clang/lib/CodeGen/CGHLSLRuntime.h
@@ -39,7 +39,8 @@
   uint32_t ResourceCounters[static_cast(
   hlsl::ResourceClass::NumClasses)] = {0};
 
-  llvm::Value *emitInputSemantic(llvm::IRBuilder<> &B, const ParmVarDecl &D);
+  llvm::Value *emitInputSemantic(llvm::IRBuilder<> &B, const ParmVarDecl &D,
+ llvm::Type *Ty);
 
 public:
   CGHLSLRuntime(CodeGenModule &CGM) : CGM(CGM) {}
Index: clang/lib/CodeGen/CGHLSLRuntime.cpp
===
--- clang/lib/CodeGen/CGHLSLRuntime.cpp
+++ clang/lib/CodeGen/CGHLSLRuntime.cpp
@@ -109,14 +109,32 @@
 ShaderAttr->ConvertShaderTypeToStr(ShaderAttr->getType()));
 }
 
+static Value *buildVectorInput(IRBuilder<> &B, Function *F, llvm::Type *Ty) {
+  if (FixedVectorType *VT = dyn_cast(Ty)) {
+Value *Result = PoisonValue::get(Ty);
+for (unsigned I = 0; I < VT->getNumElements(); ++I) {
+  Value *Elt = B.CreateCall(F, {B.getInt32(I)});
+  Result = B.CreateInsertElement(Result, Elt, I);
+}
+return Result;
+  } else
+return B.CreateCall(F, {B.getInt32(0)});
+}
+
 llvm::Value *CGHLSLRuntime::emitInputSemantic(IRBuilder<> &B,
-  const ParmVarDecl &D) {
+  const ParmVarDecl &D,
+  llvm::Type *Ty) {
   assert(D.hasAttrs() && "Entry parameter missing annotation attribute!");
   if (D.hasAttr()) {
 llvm::Function *DxGroupIndex =
 CGM.getIntrinsic(Intrinsic::dx_flattened_thread_id_in_group);
 return B.CreateCall(FunctionCallee(DxGroupIndex));
   }
+  if (D.hasAttr()) {
+llvm::Function *DxThreadID = CGM.getIntrinsic(Intrinsic::dx_thread_id);
+// dx_thread_id
+return buildVectorInput(B, DxThreadID, Ty);
+  }
   assert(false && 

[PATCH] D133988: [clang][deps] Make sure ScanInstance outlives collector

2022-09-15 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

Another option would be to store `ScanInstance` as member of 
`DependencyScanningAction`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133988

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


[PATCH] D133705: [HIP] Fix unbundling archive

2022-09-15 Thread Artem Belevich via Phabricator via cfe-commits
tra added a comment.

In D133705#3785470 , @yaxunl wrote:

>> Also, using `lib*.a` as pattern to tell device libraries from the host-ony 
>> one will be insufficient. There will be libraries with other extensions 
>> (e.g. `.lo` is fairly common) and there will be libraries that do not have 
>> `lib` prefix. I.e. nothing stops me from building `mylib.a` and linking with 
>> it as in the example above.
>
> For archives passed as input files, we use the extension ('.a' on Linux and 
> '.lib' on MSVC) to identify them. We do not restrict the file names to 
> 'lib*.a', but they need to be '*.a' or '*.lib' to be identified as archives.

As I've pointed above that will create issues.

> For arbitrary file names to be identified as archives, users can pass them by 
> '-l:', e.g. '-l:file.bin', then clang will treat 'file.bin' as an archive.

It's not always possible. Linking with dependencies is often handled by the 
build tools that the end user may not control. E.g. TF is built w/ `bazel` 
which handles virtually all linking under the hood with almost no user controls 
over the names/extensions it assigns to files or how they are passed to the 
linker.

@MaskRay - WDYT?


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

https://reviews.llvm.org/D133705

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


[PATCH] D133988: [clang][deps] Make sure ScanInstance outlives collector

2022-09-15 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added a reviewer: benlangmuir.
Herald added a project: All.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The `ScanInstance` is a local variable in 
`DependencyScanningAction::runInvocation()` that is referenced by 
`ModuleDepCollector`. Since D132405 , 
`ModuleDepCollector` can escape the function and can outlive its 
`ScanInstance`. This patch fixes that by reference-counting `ScanInstance`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133988

Files:
  clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
  clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp

Index: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
===
--- clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -261,11 +261,11 @@
   // This has to be delayed as the context hash can change at the start of
   // `CompilerInstance::ExecuteAction`.
   if (MDC.ContextHash.empty()) {
-MDC.ContextHash = MDC.ScanInstance.getInvocation().getModuleHash();
+MDC.ContextHash = MDC.ScanInstance->getInvocation().getModuleHash();
 MDC.Consumer.handleContextHash(MDC.ContextHash);
   }
 
-  SourceManager &SM = MDC.ScanInstance.getSourceManager();
+  SourceManager &SM = MDC.ScanInstance->getSourceManager();
 
   // Dependency generation really does want to go all the way to the
   // file entry for a source location to find out what is depended on.
@@ -308,16 +308,16 @@
 }
 
 void ModuleDepCollectorPP::EndOfMainFile() {
-  FileID MainFileID = MDC.ScanInstance.getSourceManager().getMainFileID();
-  MDC.MainFile = std::string(MDC.ScanInstance.getSourceManager()
+  FileID MainFileID = MDC.ScanInstance->getSourceManager().getMainFileID();
+  MDC.MainFile = std::string(MDC.ScanInstance->getSourceManager()
  .getFileEntryForID(MainFileID)
  ->getName());
 
-  if (!MDC.ScanInstance.getPreprocessorOpts().ImplicitPCHInclude.empty())
-MDC.addFileDep(MDC.ScanInstance.getPreprocessorOpts().ImplicitPCHInclude);
+  if (!MDC.ScanInstance->getPreprocessorOpts().ImplicitPCHInclude.empty())
+MDC.addFileDep(MDC.ScanInstance->getPreprocessorOpts().ImplicitPCHInclude);
 
   for (const Module *M :
-   MDC.ScanInstance.getPreprocessor().getAffectingModules())
+   MDC.ScanInstance->getPreprocessor().getAffectingModules())
 if (!MDC.isPrebuiltModule(M))
   DirectModularDeps.insert(M);
 
@@ -359,7 +359,7 @@
   MD.ImplicitModulePCMPath = std::string(M->getASTFile()->getName());
   MD.IsSystem = M->IsSystem;
 
-  const FileEntry *ModuleMap = MDC.ScanInstance.getPreprocessor()
+  const FileEntry *ModuleMap = MDC.ScanInstance->getPreprocessor()
.getHeaderSearchInfo()
.getModuleMap()
.getModuleMapFileForUniquing(M);
@@ -372,9 +372,9 @@
   }
 
   serialization::ModuleFile *MF =
-  MDC.ScanInstance.getASTReader()->getModuleManager().lookup(
+  MDC.ScanInstance->getASTReader()->getModuleManager().lookup(
   M->getASTFile());
-  MDC.ScanInstance.getASTReader()->visitInputFiles(
+  MDC.ScanInstance->getASTReader()->visitInputFiles(
   *MF, true, true, [&](const serialization::InputFile &IF, bool isSystem) {
 // __inferred_module.map is the result of the way in which an implicit
 // module build handles inferred modules. It adds an overlay VFS with
@@ -412,7 +412,7 @@
 // map). We simply specify all the module maps in the order they were loaded
 // during the implicit build during scan.
 // TODO: Resolve this by serializing and only using Module::UndeclaredUses.
-MDC.ScanInstance.getASTReader()->visitTopLevelModuleMaps(
+MDC.ScanInstance->getASTReader()->visitTopLevelModuleMaps(
 *MF, [&](const FileEntry *FE) {
   if (FE->getName().endswith("__inferred_module.map"))
 return;
@@ -439,7 +439,7 @@
   MD, [&](CompilerInvocation &BuildInvocation) {
 if (MDC.OptimizeArgs)
   optimizeHeaderSearchOpts(BuildInvocation.getHeaderSearchOpts(),
-   *MDC.ScanInstance.getASTReader(), *MF);
+   *MDC.ScanInstance->getASTReader(), *MF);
   });
 
   MDC.associateWithContextHash(CI, MD);
@@ -535,7 +535,7 @@
 
 ModuleDepCollector::ModuleDepCollector(
 std::unique_ptr Opts,
-CompilerInstance &ScanInstance, DependencyConsumer &C,
+std::shared_ptr ScanInstance, DependencyConsumer &C,
 CompilerInvocation OriginalCI, bool OptimizeArgs, bool EagerLoadModules)
 : ScanInstance(ScanInstance), Consumer(C), Opts(std::move(Opt

[PATCH] D133732: [clang-doc] Support default args for functions.

2022-09-15 Thread Brett Wilson via Phabricator via cfe-commits
brettw updated this revision to Diff 460538.
brettw marked 4 inline comments as done.
brettw added a comment.

There is no usage change for this. It just adds another field to the YAML.


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

https://reviews.llvm.org/D133732

Files:
  clang-tools-extra/clang-doc/BitcodeReader.cpp
  clang-tools-extra/clang-doc/BitcodeWriter.cpp
  clang-tools-extra/clang-doc/BitcodeWriter.h
  clang-tools-extra/clang-doc/Representation.h
  clang-tools-extra/clang-doc/Serialize.cpp
  clang-tools-extra/clang-doc/YAMLGenerator.cpp
  clang-tools-extra/unittests/clang-doc/SerializeTest.cpp
  clang-tools-extra/unittests/clang-doc/YAMLGeneratorTest.cpp

Index: clang-tools-extra/unittests/clang-doc/YAMLGeneratorTest.cpp
===
--- clang-tools-extra/unittests/clang-doc/YAMLGeneratorTest.cpp
+++ clang-tools-extra/unittests/clang-doc/YAMLGeneratorTest.cpp
@@ -209,6 +209,8 @@
   I.ReturnType =
   TypeInfo(EmptySID, "void", InfoType::IT_default, "path/to/void");
   I.Params.emplace_back("int", "path/to/int", "P");
+  I.Params.emplace_back("double", "path/to/double", "D");
+  I.Params.back().DefaultValue = "2.0 * M_PI";
   I.IsMethod = true;
   I.Parent = Reference(EmptySID, "Parent", InfoType::IT_record);
 
@@ -240,6 +242,11 @@
   Name:'int'
   Path:'path/to/int'
 Name:'P'
+  - Type:
+  Name:'double'
+  Path:'path/to/double'
+Name:'D'
+DefaultValue:'2.0 * M_PI'
 ReturnType:
   Type:
 Name:'void'
Index: clang-tools-extra/unittests/clang-doc/SerializeTest.cpp
===
--- clang-tools-extra/unittests/clang-doc/SerializeTest.cpp
+++ clang-tools-extra/unittests/clang-doc/SerializeTest.cpp
@@ -511,7 +511,7 @@
   std::vector Args;
   Args.push_back("-fmodules-ts");
   ExtractInfosFromCodeWithArgs(R"raw(export module M;
-int moduleFunction(int x);
+int moduleFunction(int x, double d = 3.2 - 1.0);
 static int staticModuleFunction(int x);
 export double exportedModuleFunction(double y);)raw",
2, /*Public=*/true, Infos, Args);
@@ -523,6 +523,8 @@
   F.ReturnType = TypeInfo(EmptySID, "int", InfoType::IT_default);
   F.Loc.emplace_back(0, llvm::SmallString<16>{"test.cpp"});
   F.Params.emplace_back("int", "x");
+  F.Params.emplace_back("double", "d");
+  F.Params.back().DefaultValue = "3.2 - 1.0";
   F.Access = AccessSpecifier::AS_none;
   ExpectedBWithFunction.ChildFunctions.emplace_back(std::move(F));
   CheckNamespaceInfo(&ExpectedBWithFunction, BWithFunction);
Index: clang-tools-extra/clang-doc/YAMLGenerator.cpp
===
--- clang-tools-extra/clang-doc/YAMLGenerator.cpp
+++ clang-tools-extra/clang-doc/YAMLGenerator.cpp
@@ -109,6 +109,7 @@
 static void FieldTypeInfoMapping(IO &IO, FieldTypeInfo &I) {
   TypeInfoMapping(IO, I);
   IO.mapOptional("Name", I.Name, SmallString<16>());
+  IO.mapOptional("DefaultValue", I.DefaultValue, SmallString<16>());
 }
 
 static void InfoMapping(IO &IO, Info &I) {
@@ -183,6 +184,7 @@
   static void mapping(IO &IO, FieldTypeInfo &I) {
 TypeInfoMapping(IO, I);
 IO.mapOptional("Name", I.Name, SmallString<16>());
+IO.mapOptional("DefaultValue", I.DefaultValue, SmallString<16>());
   }
 };
 
Index: clang-tools-extra/clang-doc/Serialize.cpp
===
--- clang-tools-extra/clang-doc/Serialize.cpp
+++ clang-tools-extra/clang-doc/Serialize.cpp
@@ -10,6 +10,7 @@
 #include "BitcodeWriter.h"
 #include "clang/AST/Comment.h"
 #include "clang/Index/USRGeneration.h"
+#include "clang/Lex/Lexer.h"
 #include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/SHA1.h"
@@ -310,21 +311,31 @@
 
 static void parseParameters(FunctionInfo &I, const FunctionDecl *D) {
   for (const ParmVarDecl *P : D->parameters()) {
+FieldTypeInfo *FieldInfo = nullptr;
 if (const auto *T = getDeclForType(P->getOriginalType())) {
   if (const auto *N = dyn_cast(T)) {
-I.Params.emplace_back(getUSRForDecl(N), N->getNameAsString(),
-  InfoType::IT_enum, getInfoRelativePath(N),
-  P->getNameAsString());
-continue;
+FieldInfo = &I.Params.emplace_back(
+getUSRForDecl(N), N->getNameAsString(), InfoType::IT_enum,
+getInfoRelativePath(N), P->getNameAsString());
   } else if (const auto *N = dyn_cast(T)) {
-I.Params.emplace_back(getUSRForDecl(N), N->getNameAsString(),
-  InfoType::IT_record, getInfoRelativePath(N),
-  P->getNameAsString());
-continue;
+FieldInfo = &I.Params.emplace_back(
+getUSRForDecl(N), N->getNameAsString(), InfoType::IT_record,
+getInfoRelat

[PATCH] D133934: [clang][Interp] Handle sizeof() expressions

2022-09-15 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added inline comments.



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:290
+return this->emitConst(
+E, Ctx.getASTContext().getTypeSizeInChars(ArgType).getQuantity());
+  }

aaron.ballman wrote:
> erichkeane wrote:
> > shafik wrote:
> > > I notice that `HandleSizeof` special cases `void` and function types. 
> > OOOH, DEFINITELY make sure you test function types here, and figure out how 
> > HandleSizeof does it.
> > 
> > BUT, I think 'void' should error/be an invalid before we get here?
> > 
> > ALSO, now that I think further, I'm sure @aaron.ballman has a bunch of 
> > runtime-evaluated sizeof examples to share around vlas.
> I was just about to comment about everyone's favorite horrible C++ extension. 
> :-D We should make sure we properly reject code like:
> ```
> void func() {
>   int n = 12;
>   constexpr int oofda = sizeof(int[n++]);
> }
> ```
> while accepting code like:
> ```
> consteval int foo(int n) {
>   return sizeof(int[n]);
> }
> constinit int var = foo(5);
> ```
Note, that clang currently treats that as ill-formed and there is divergence 
with how gcc and clang treat the `constexpr` case as well.

So if we are going to say we want this to work then we should file a bug 
against clang. 


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

https://reviews.llvm.org/D133934

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


[PATCH] D133634: [clang] Allow vector of BitInt

2022-09-15 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

I think the worst of the backend issues with vectors of non-byte-size integers 
have been resolved?  Work on that has progressed slowly for a very long time.  
There have been a constant stream of issues.  (See, for example, D129164 
.)  But LangRef does define the memory 
layout, and CodeGen does essentially implement that layout.

It's not clear to me we actually want to use that layout for vectors of 
non-power-of-two types.  Load/store for bit-packed vectors isn't efficient.

Maybe we can just enable this specifically for types which are a power of two 
multiple of 8 for now (where there's one obvious layout), and consider the 
other cases later?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133634

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


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

2022-09-15 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D132461#3773792 , @carlosgalvezp 
wrote:

> @njames93 Friendly ping. The patch has addressed all comments and remained 
> unchanged for 2 weeks. I would like to land it latest next week. If you are 
> happy with the patch, please accept the review. Alternatively, please let me 
> know if you intend to continue reviewing.

I do intend, but I'm currently between 2 jobs and accommodation atm, once life 
settles down next week, I should have more time.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132461

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


[PATCH] D133956: Cuda Check for ignored errors after calling a CUDA kernel

2022-09-15 Thread Artem Belevich via Phabricator via cfe-commits
tra added a comment.

> The intention with this check is to work a lot in tandem with the one in 
> D133804 , which therefore prevents most 
> such cases. 
> Thus, the check is optimized for lowering false positives during static 
> checking and for a practice lowering the number of false negatives within the 
> CUDA code.

SGTM. This patch + D133804  should have 
everything covered.




Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu:53
+  }
+  auto err = cudaGetLastError();
+

barcisz wrote:
> tra wrote:
> > Just curious -- is it sufficient to just call `cudaGetLastError();` ? Or 
> > does the checker require using its result, too? I.e. in practice this 
> > particular check will not really do anything useful. The tests below look 
> > somewhat inconsistent. 
> Technically it does not require the user to actually use the value of 
> `cudaGetLastError()`, but
> 
> 
>   # If they are calling it then they most likely did not place this call 
> there randomly and are using it to check for the error returned by the kernel
>   # the check being introduced in D133804 can be used to check if the return 
> value has been used, so checking it here as well would have been a duplication
> 
> 
> 1. If they are calling it then they most likely did not place this call there 
> randomly and are using it to check for the error returned by the kernel

If that's the case, then why kernel launches on lines 45 and 51 are reported as 
possibly unchecked? Both are followed by the `cudaGetLastError()` call and are, 
technically checked, if we're not analyzing the usage of the result of the 
call. 

What am I missing?



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu:75
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked 
error after a kernel launch.
+  // Calling an error-checking function after a kernel is not considered safe.
+  errorCheck();

barcisz wrote:
> tra wrote:
> > WDYM by "is not considered safe" here? How is that different from calling 
> > `cudaGetLastError()` and checking its value?
> As in the check does not do inter-procedural analysis short of adding the 
> handler to AcceptedHandlers, so the check will flag such occurences
Hmm.. Using a helper function to check for cuda errors is a fairly common 
pattern. 
Is there a way to annotate such a helper function as `checks cudaGetLastError`?



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu:80-82
+  b<<<1, 2>>>();; /* The semicolons are here because the
+detection of the macro is done with a lexer */ ;
+  CUDA_CHECK_KERNEL();

barcisz wrote:
> tra wrote:
> > What would happen with a single `;` as would be seen in the normal user 
> > code?
> Nothing, it would work just fine; it's rather that all other kernel calls in 
> this test use a single `;` so I want to check this case here
I still do not understand how it all fits together. What does a kernel call, 
the extra `;`, the macro, and the checker code have to do with each other?

Is the idea that the checker should see though the empty statement between the 
kernel call and the checker macro?
If that's the case I'd make it a bit more prominent. E.g. something like this:

```
b<<<1, 2>>>();
; /* Make sure that we see through empty expressions in-between the call 
and the checker. */ ;
  CUDA_CHECK_KERNEL();
```





Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu:112
+  do {
+auto err2 = cudaGetLastError();
+  } while(0);

barcisz wrote:
> tra wrote:
> > Why does this case produce no warning, while a very similar case above 
> > does? In both cases result of `cudaGetLastError()` is assigned to an unused 
> > variable within the loop body.
> > 
> > ```
> >   b<<<1, 2>>>();
> >   // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked 
> > error after a kernel launch.
> >   for(;;)
> > auto err2 = cudaGetLastError(); // Brackets omitted purposefully, since 
> > they create an additional AST node
> > 
> > ```
> Because often a macro will wrap its error handling code in a do {...} 
> while(0) loop and that's why we check this case and simmilar ones with CFG 
> analysis
The `do/while(0)` wrapping part I understand. I'm puzzled why the checker 
appears to work differently with different loop kinds. 
Why a `cudaGetLastError()` call inside `do {} while()` is detected and 
considered as a cuda result check, but the same call within `for() {}` is not?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133956

___
cfe-commits mailing list
cfe-commits@lists.

[PATCH] D133698: [clang][dataflow] SignAnalysis, edgeTransfer, branchTransfer

2022-09-15 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added inline comments.



Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h:127
+  // Default implementation is a Noop.
+  virtual void branchTransfer(bool Branch, const Stmt *S, Lattice &L,
+  Environment &Env) {}

Please use CRTP (a non-virtual function here), and you'll need SFINAE to detect 
the presence of the overload of branchTransfer in branchTransferTypeErased.



Comment at: 
clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h:86
   Environment &) = 0;
+  virtual void branchTransferTypeErased(bool Branch, const Stmt *,
+TypeErasedLattice &, Environment &) = 
0;

Please add a doc comment. Please add a parameter name for the condition, it is 
not obvious what it is.

Could you think of a more descriptive name for `Branch`? For example, if the 
second parameter is `Cond`, WDYT about `CondValue`?





Comment at: 
clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h:86
   Environment &) = 0;
+  virtual void branchTransferTypeErased(bool Branch, const Stmt *,
+TypeErasedLattice &, Environment &) = 
0;

gribozavr2 wrote:
> Please add a doc comment. Please add a parameter name for the condition, it 
> is not obvious what it is.
> 
> Could you think of a more descriptive name for `Branch`? For example, if the 
> second parameter is `Cond`, WDYT about `CondValue`?
> 
> 
WDYT about calling it `transferBranch...` instead of `branchTransfer...`?



Comment at: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp:78
 public:
-  TerminatorVisitor(const StmtToEnvMap &StmtToEnv, Environment &Env,
+  using RetTy = std::pair;
+  TerminatorVisitor(TypeErasedDataflowAnalysis &Analysis,

Please add a comment to RetTy.



Comment at: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp:148
 
+bool Assumption = true;
 // The condition must be inverted for the successor that encompasses the

`CondValue`?



Comment at: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp:253
+auto [Cond, Assumption] =
+TerminatorVisitor(Analysis, StmtToEnv, PredState.Env,
+  blockIndexInPredecessor(*Pred, Block),

It would be nice to still call `branchTransfer` even when `BuiltinTransferOpts 
== false`. Please leave a TODO if you don't want to implement that.



Comment at: clang/unittests/Analysis/FlowSensitive/SignAnalysisTest.cpp:586
+   HoldsSignLattice(UnorderedElementsAre(Pair(Var("a"), 
Top()));
+}
+

This file is an amazing example of how to use the framework, but could you add 
a more direct unit test with a simpler lattice and analysis that exercises the 
new callback?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133698

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


[PATCH] D133942: Clang tidy utility to generate a fix hint for a subsequent expression to the existing one

2022-09-15 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

Would I be correct in assuming you have uploaded the wrong diff here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133942

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


[PATCH] D133157: Add -fsanitizer-coverage=control-flow

2022-09-15 Thread Vitaly Buka 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 rG3e52c0926c22: Add -fsanitizer-coverage=control-flow 
(authored by Navidem, committed by vitalybuka).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133157

Files:
  clang/docs/SanitizerCoverage.rst
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/Driver/fsanitize-coverage.c
  
compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_control_flow.cpp
  llvm/include/llvm/Transforms/Instrumentation.h
  llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
  llvm/test/Instrumentation/SanitizerCoverage/control-flow.ll

Index: llvm/test/Instrumentation/SanitizerCoverage/control-flow.ll
===
--- /dev/null
+++ llvm/test/Instrumentation/SanitizerCoverage/control-flow.ll
@@ -0,0 +1,22 @@
+; Test -sanitizer-coverage-control-flow.
+; RUN: opt < %s -passes='module(sancov-module)' -sanitizer-coverage-level=3 -sanitizer-coverage-control-flow -S | FileCheck %s
+
+target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64"
+target triple = "x86_64-unknown-linux-gnu"
+define void @foo(ptr %a) sanitize_address {
+entry:
+  %tobool = icmp eq i32* %a, null
+  br i1 %tobool, label %if.end, label %if.then
+
+  if.then:  ; preds = %entry
+  store i32 0, i32* %a, align 4
+  call void @foo(i32* %a)
+  br label %if.end
+
+  if.end:   ; preds = %entry, %if.then
+  ret void
+}
+
+; CHECK: private constant [17 x ptr] [{{.*}}@foo{{.*}}blockaddress{{.*}}blockaddress{{.*}}blockaddress{{.*}}blockaddress{{.*}}blockaddress{{.*}}blockaddress{{.*}}blockaddress{{.*}}@foo{{.*}}null{{.*}}null], section "__sancov_cfs", comdat($foo), align 8
+; CHECK:  @__start___sancov_cfs = extern_weak hidden global
+; CHECK-NEXT: @__stop___sancov_cfs = extern_weak hidden global
Index: llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
===
--- llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
+++ llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
@@ -76,11 +76,13 @@
 const char SanCov8bitCountersInitName[] = "__sanitizer_cov_8bit_counters_init";
 const char SanCovBoolFlagInitName[] = "__sanitizer_cov_bool_flag_init";
 const char SanCovPCsInitName[] = "__sanitizer_cov_pcs_init";
+const char SanCovCFsInitName[] = "__sanitizer_cov_cfs_init";
 
 const char SanCovGuardsSectionName[] = "sancov_guards";
 const char SanCovCountersSectionName[] = "sancov_cntrs";
 const char SanCovBoolFlagSectionName[] = "sancov_bools";
 const char SanCovPCsSectionName[] = "sancov_pcs";
+const char SanCovCFsSectionName[] = "sancov_cfs";
 
 const char SanCovLowestStackName[] = "__sancov_lowest_stack";
 
@@ -148,6 +150,11 @@
   cl::desc("max stack depth tracing"),
   cl::Hidden, cl::init(false));
 
+static cl::opt
+ClCollectCF("sanitizer-coverage-control-flow",
+cl::desc("collect control flow for each function"), cl::Hidden,
+cl::init(false));
+
 namespace {
 
 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
@@ -194,6 +201,7 @@
   !Options.Inline8bitCounters && !Options.StackDepth &&
   !Options.InlineBoolFlag && !Options.TraceLoads && !Options.TraceStores)
 Options.TracePCGuard = true; // TracePCGuard is default.
+  Options.CollectControlFlow |= ClCollectCF;
   return Options;
 }
 
@@ -213,6 +221,7 @@
 PostDomTreeCallback PDTCallback);
 
 private:
+  void createFunctionControlFlow(Function &F);
   void instrumentFunction(Function &F, DomTreeCallback DTCallback,
   PostDomTreeCallback PDTCallback);
   void InjectCoverageForIndirectCalls(Function &F,
@@ -271,6 +280,7 @@
   GlobalVariable *Function8bitCounterArray;  // for inline-8bit-counters.
   GlobalVariable *FunctionBoolArray; // for inline-bool-flag.
   GlobalVariable *FunctionPCsArray;  // for pc-table.
+  GlobalVariable *FunctionCFsArray;  // for control flow table
   SmallVector GlobalsToAppendToUsed;
   SmallVector GlobalsToAppendToCompilerUsed;
 
@@ -385,6 +395,7 @@
   Function8bitCounterArray = nullptr;
   FunctionBoolArray = nullptr;
   FunctionPCsArray = nullptr;
+  FunctionCFsArray = nullptr;
   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
   IntptrPtrTy = PointerType::getUnqual(IntptrTy);
   Type *VoidTy = Type::getVoidTy(*C);
@@ -509,6 +520,15 @@
 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getT

[clang] 3e52c09 - Add -fsanitizer-coverage=control-flow

2022-09-15 Thread Vitaly Buka via cfe-commits

Author: Navid Emamdoost
Date: 2022-09-15T15:56:04-07:00
New Revision: 3e52c0926c22575d918e7ca8369522b986635cd3

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

LOG: Add -fsanitizer-coverage=control-flow

Reviewed By: kcc, vitalybuka, MaskRay

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

Added: 

compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_control_flow.cpp
llvm/test/Instrumentation/SanitizerCoverage/control-flow.ll

Modified: 
clang/docs/SanitizerCoverage.rst
clang/include/clang/Basic/CodeGenOptions.def
clang/include/clang/Basic/CodeGenOptions.h
clang/include/clang/Driver/Options.td
clang/lib/CodeGen/BackendUtil.cpp
clang/lib/Driver/SanitizerArgs.cpp
clang/test/Driver/fsanitize-coverage.c
llvm/include/llvm/Transforms/Instrumentation.h
llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp

Removed: 




diff  --git a/clang/docs/SanitizerCoverage.rst 
b/clang/docs/SanitizerCoverage.rst
index 9d4a32231b60d..c6e77cd7295c2 100644
--- a/clang/docs/SanitizerCoverage.rst
+++ b/clang/docs/SanitizerCoverage.rst
@@ -331,6 +331,60 @@ will not be instrumented.
   void __sanitizer_cov_store8(uint64_t *addr);
   void __sanitizer_cov_store16(__int128 *addr);
 
+
+Tracing control flow
+
+
+With ``-fsanitize-coverage=control-flow`` the compiler will create a table to 
collect
+control flow for each function. More specifically, for each basic block in the 
function,
+two lists are populated. One list for successors of the basic block and 
another list for
+non-intrinsic called functions.
+
+**TODO:** in the current implementation, indirect calls are not tracked
+and are only marked with special value (-1) in the list.
+
+Each table row consists of the basic block address
+followed by ``null``-ended lists of successors and callees.
+The table is encoded in a special section named ``sancov_cfs``
+
+Example:
+
+.. code-block:: c++
+  int foo (int x) {
+if (x > 0)
+  bar(x);
+else
+  x = 0;
+return x;
+  }
+
+The code above contains 4 basic blocks, let's name them A, B, C, D:
+
+.. code-block:: none
+
+A
+|\
+| \
+B  C
+| /
+|/
+D
+
+The collected control flow table is as follows:
+``A, B, C, null, null, B, D, null, @bar, null, C, D, null, null, D, null, 
null.``
+
+Users need to implement a single function to capture the CF table at startup:
+
+.. code-block:: c++
+
+  extern "C"
+  void __sanitizer_cov_cfs_init(const uintptr_t *cfs_beg,
+const uintptr_t *cfs_end) {
+// [cfs_beg,cfs_end) is the array of ptr-sized integers representing
+// the collected control flow.
+  }
+
+
 Disabling instrumentation with ``__attribute__((no_sanitize("coverage")))``
 ===
 

diff  --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index 9c1a23cb17261..c3b6b289fcff8 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -281,6 +281,7 @@ CODEGENOPT(SanitizeCoverageTracePCGuard, 1, 0) ///< Enable 
PC tracing with guard
 CODEGENOPT(SanitizeCoverageInline8bitCounters, 1, 0) ///< Use inline 8bit 
counters.
 CODEGENOPT(SanitizeCoverageInlineBoolFlag, 1, 0) ///< Use inline bool flag.
 CODEGENOPT(SanitizeCoveragePCTable, 1, 0) ///< Create a PC Table.
+CODEGENOPT(SanitizeCoverageControlFlow, 1, 0) ///< Collect control flow
 CODEGENOPT(SanitizeCoverageNoPrune, 1, 0) ///< Disable coverage pruning.
 CODEGENOPT(SanitizeCoverageStackDepth, 1, 0) ///< Enable max stack depth 
tracing
 CODEGENOPT(SanitizeCoverageTraceLoads, 1, 0) ///< Enable tracing of loads.

diff  --git a/clang/include/clang/Basic/CodeGenOptions.h 
b/clang/include/clang/Basic/CodeGenOptions.h
index 0504012badb04..98f537e62b608 100644
--- a/clang/include/clang/Basic/CodeGenOptions.h
+++ b/clang/include/clang/Basic/CodeGenOptions.h
@@ -483,7 +483,7 @@ class CodeGenOptions : public CodeGenOptionsBase {
   bool hasSanitizeCoverage() const {
 return SanitizeCoverageType || SanitizeCoverageIndirectCalls ||
SanitizeCoverageTraceCmp || SanitizeCoverageTraceLoads ||
-   SanitizeCoverageTraceStores;
+   SanitizeCoverageTraceStores || SanitizeCoverageControlFlow;
   }
 
   // Check if any one of SanitizeBinaryMetadata* is enabled.

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 2e0f4c9452d65..a1071294ff6f5 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5486,6 +5486,10 @@ def fsanitize_coverage_pc_table
 : Flag<["-"], "fsanitize-coverage-pc-table">,
   HelpText<"Create a table of cove

[PATCH] D133157: Add -fsanitizer-coverage=control-flow

2022-09-15 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added inline comments.



Comment at: llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp:155
+cl::desc("collect control flow for each function"), cl::Hidden,
+cl::init(false));
+

MaskRay wrote:
> false can be removed
I'll keep it for  consistency with the rest of file


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133157

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


[PATCH] D133157: Add -fsanitizer-coverage=control-flow

2022-09-15 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka updated this revision to Diff 460525.
vitalybuka added a comment.

clang test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133157

Files:
  clang/docs/SanitizerCoverage.rst
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/Driver/fsanitize-coverage.c
  
compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_control_flow.cpp
  llvm/include/llvm/Transforms/Instrumentation.h
  llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
  llvm/test/Instrumentation/SanitizerCoverage/control-flow.ll

Index: llvm/test/Instrumentation/SanitizerCoverage/control-flow.ll
===
--- /dev/null
+++ llvm/test/Instrumentation/SanitizerCoverage/control-flow.ll
@@ -0,0 +1,22 @@
+; Test -sanitizer-coverage-control-flow.
+; RUN: opt < %s -passes='module(sancov-module)' -sanitizer-coverage-level=3 -sanitizer-coverage-control-flow -S | FileCheck %s
+
+target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64"
+target triple = "x86_64-unknown-linux-gnu"
+define void @foo(ptr %a) sanitize_address {
+entry:
+  %tobool = icmp eq i32* %a, null
+  br i1 %tobool, label %if.end, label %if.then
+
+  if.then:  ; preds = %entry
+  store i32 0, i32* %a, align 4
+  call void @foo(i32* %a)
+  br label %if.end
+
+  if.end:   ; preds = %entry, %if.then
+  ret void
+}
+
+; CHECK: private constant [17 x ptr] [{{.*}}@foo{{.*}}blockaddress{{.*}}blockaddress{{.*}}blockaddress{{.*}}blockaddress{{.*}}blockaddress{{.*}}blockaddress{{.*}}blockaddress{{.*}}@foo{{.*}}null{{.*}}null], section "__sancov_cfs", comdat($foo), align 8
+; CHECK:  @__start___sancov_cfs = extern_weak hidden global
+; CHECK-NEXT: @__stop___sancov_cfs = extern_weak hidden global
Index: llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
===
--- llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
+++ llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
@@ -76,11 +76,13 @@
 const char SanCov8bitCountersInitName[] = "__sanitizer_cov_8bit_counters_init";
 const char SanCovBoolFlagInitName[] = "__sanitizer_cov_bool_flag_init";
 const char SanCovPCsInitName[] = "__sanitizer_cov_pcs_init";
+const char SanCovCFsInitName[] = "__sanitizer_cov_cfs_init";
 
 const char SanCovGuardsSectionName[] = "sancov_guards";
 const char SanCovCountersSectionName[] = "sancov_cntrs";
 const char SanCovBoolFlagSectionName[] = "sancov_bools";
 const char SanCovPCsSectionName[] = "sancov_pcs";
+const char SanCovCFsSectionName[] = "sancov_cfs";
 
 const char SanCovLowestStackName[] = "__sancov_lowest_stack";
 
@@ -148,6 +150,11 @@
   cl::desc("max stack depth tracing"),
   cl::Hidden, cl::init(false));
 
+static cl::opt
+ClCollectCF("sanitizer-coverage-control-flow",
+cl::desc("collect control flow for each function"), cl::Hidden,
+cl::init(false));
+
 namespace {
 
 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
@@ -194,6 +201,7 @@
   !Options.Inline8bitCounters && !Options.StackDepth &&
   !Options.InlineBoolFlag && !Options.TraceLoads && !Options.TraceStores)
 Options.TracePCGuard = true; // TracePCGuard is default.
+  Options.CollectControlFlow |= ClCollectCF;
   return Options;
 }
 
@@ -213,6 +221,7 @@
 PostDomTreeCallback PDTCallback);
 
 private:
+  void createFunctionControlFlow(Function &F);
   void instrumentFunction(Function &F, DomTreeCallback DTCallback,
   PostDomTreeCallback PDTCallback);
   void InjectCoverageForIndirectCalls(Function &F,
@@ -271,6 +280,7 @@
   GlobalVariable *Function8bitCounterArray;  // for inline-8bit-counters.
   GlobalVariable *FunctionBoolArray; // for inline-bool-flag.
   GlobalVariable *FunctionPCsArray;  // for pc-table.
+  GlobalVariable *FunctionCFsArray;  // for control flow table
   SmallVector GlobalsToAppendToUsed;
   SmallVector GlobalsToAppendToCompilerUsed;
 
@@ -385,6 +395,7 @@
   Function8bitCounterArray = nullptr;
   FunctionBoolArray = nullptr;
   FunctionPCsArray = nullptr;
+  FunctionCFsArray = nullptr;
   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
   IntptrPtrTy = PointerType::getUnqual(IntptrTy);
   Type *VoidTy = Type::getVoidTy(*C);
@@ -509,6 +520,15 @@
 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
   }
+
+  if (Ctor && Options.CollectControlFlow) {
+auto SecS

[PATCH] D133157: Add -fsanitizer-coverage=control-flow

2022-09-15 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay accepted this revision.
MaskRay added inline comments.
Herald added a subscriber: StephenFan.



Comment at: llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp:155
+cl::desc("collect control flow for each function"), cl::Hidden,
+cl::init(false));
+

false can be removed


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133157

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


[PATCH] D133983: [HLSL] Add SV_DispatchThreadID

2022-09-15 Thread Xiang Li via Phabricator via cfe-commits
python3kgae created this revision.
python3kgae added reviewers: beanz, pow2clk, bogner.
Herald added a reviewer: aaron.ballman.
Herald added a subscriber: Anastasia.
Herald added a project: All.
python3kgae requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Support SV_DispatchThreadID attribute.
Translate it into dx.thread.id in clang codeGen.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133983

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CGHLSLRuntime.cpp
  clang/lib/CodeGen/CGHLSLRuntime.h
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGenHLSL/semantics/DispatchThreadID.hlsl

Index: clang/test/CodeGenHLSL/semantics/DispatchThreadID.hlsl
===
--- /dev/null
+++ clang/test/CodeGenHLSL/semantics/DispatchThreadID.hlsl
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library -x hlsl -emit-llvm -finclude-default-header -disable-llvm-passes -o - %s
+
+// Make sure SV_DispatchThreadID translated into dx.thread.id.
+
+const RWBuffer In;
+RWBuffer Out;
+
+// CHECK: define void @foo()
+// CHECK: call i32 @llvm.dx.thread.id(i32 0)
+// CHECK: call void @"?foo@@YAXH@Z"(i32 %{{.*}})
+[shader("compute")]
+[numthreads(8,8,1)]
+void foo(int Idx : SV_DispatchThreadID) {
+  Out[Idx] = In[Idx];
+}
+
+// CHECK: define void @bar()
+// CHECK: call i32 @llvm.dx.thread.id(i32 0)
+// CHECK: call i32 @llvm.dx.thread.id(i32 1)
+// CHECK: call void @"?bar@@YAXT?$__vector@H$01@__clang@@@Z"(<2 x i32> %{{.*}})
+[shader("compute")]
+[numthreads(8,8,1)]
+void bar(int2 Idx : SV_DispatchThreadID) {
+  Out[Idx.y] = In[Idx.x];
+}
+
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -6907,6 +6907,25 @@
   D->addAttr(::new (S.Context) HLSLSV_GroupIndexAttr(S.Context, AL));
 }
 
+static void handleHLSLSV_DispatchThreadIDAttr(Sema &S, Decl *D,
+  const ParsedAttr &AL) {
+  using llvm::Triple;
+  Triple Target = S.Context.getTargetInfo().getTriple();
+  // FIXME: it is OK for a compute shader entry and pixiel shader entry live in
+  // same HLSL file.
+  if (Target.getEnvironment() != Triple::Compute &&
+  Target.getEnvironment() != Triple::Library) {
+uint32_t Pipeline =
+(uint32_t)S.Context.getTargetInfo().getTriple().getEnvironment() -
+(uint32_t)llvm::Triple::Pixel;
+S.Diag(AL.getLoc(), diag::err_hlsl_attr_unsupported_in_stage)
+<< AL << Pipeline << "Compute";
+return;
+  }
+
+  D->addAttr(::new (S.Context) HLSLSV_DispatchThreadIDAttr(S.Context, AL));
+}
+
 static void handleHLSLShaderAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
   StringRef Str;
   SourceLocation ArgLoc;
@@ -8920,6 +8939,9 @@
   case ParsedAttr::AT_HLSLSV_GroupIndex:
 handleHLSLSVGroupIndexAttr(S, D, AL);
 break;
+  case ParsedAttr::AT_HLSLSV_DispatchThreadID:
+handleHLSLSV_DispatchThreadIDAttr(S, D, AL);
+break;
   case ParsedAttr::AT_HLSLShader:
 handleHLSLShaderAttr(S, D, AL);
 break;
Index: clang/lib/CodeGen/CGHLSLRuntime.h
===
--- clang/lib/CodeGen/CGHLSLRuntime.h
+++ clang/lib/CodeGen/CGHLSLRuntime.h
@@ -39,7 +39,8 @@
   uint32_t ResourceCounters[static_cast(
   hlsl::ResourceClass::NumClasses)] = {0};
 
-  llvm::Value *emitInputSemantic(llvm::IRBuilder<> &B, const ParmVarDecl &D);
+  llvm::Value *emitInputSemantic(llvm::IRBuilder<> &B, const ParmVarDecl &D,
+ llvm::Type *Ty);
 
 public:
   CGHLSLRuntime(CodeGenModule &CGM) : CGM(CGM) {}
Index: clang/lib/CodeGen/CGHLSLRuntime.cpp
===
--- clang/lib/CodeGen/CGHLSLRuntime.cpp
+++ clang/lib/CodeGen/CGHLSLRuntime.cpp
@@ -109,14 +109,32 @@
 ShaderAttr->ConvertShaderTypeToStr(ShaderAttr->getType()));
 }
 
+static Value *buildVectorInput(IRBuilder<> &B, Function *F, llvm::Type *Ty) {
+  if (FixedVectorType *VT = dyn_cast(Ty)) {
+Value *Result = PoisonValue::get(Ty);
+for (unsigned I = 0; I < VT->getNumElements(); ++I) {
+  Value *Elt = B.CreateCall(F, {B.getInt32(I)});
+  Result = B.CreateInsertElement(Result, Elt, I);
+}
+return Result;
+  } else
+return B.CreateCall(F, {B.getInt32(0)});
+}
+
 llvm::Value *CGHLSLRuntime::emitInputSemantic(IRBuilder<> &B,
-  const ParmVarDecl &D) {
+  const ParmVarDecl &D,
+  llvm::Type *Ty) {
   assert(D.hasAttrs() && "Entry parameter missing annotation attribute!");
   if (D.hasAttr()) {
 llvm::Function *DxGroupIndex =
 CGM.getIntrinsic(Intrinsic::dx_flattened_thread_id_in_group);
 return 

[PATCH] D133942: Clang tidy utility to generate a fix hint for a subsequent expression to the existing one

2022-09-15 Thread Bartłomiej Cieślar via Phabricator via cfe-commits
barcisz updated this revision to Diff 460522.
barcisz added a comment.
Herald added a subscriber: mgorny.

rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133942

Files:
  clang-tools-extra/clang-tidy/cuda/CMakeLists.txt
  clang-tools-extra/clang-tidy/cuda/CudaTidyModule.cpp
  clang-tools-extra/clang-tidy/cuda/UnsafeKernelCallCheck.cpp
  clang-tools-extra/clang-tidy/cuda/UnsafeKernelCallCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cuda/unsafe-kernel-call.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/cuda/cuda_runtime.h
  
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-function-handler.cu
  
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu

Index: clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu
@@ -0,0 +1,116 @@
+// RUN: %check_clang_tidy %s cuda-unsafe-kernel-call %t -- \
+// RUN:   -config="{CheckOptions: \
+// RUN: [{key: cuda-unsafe-kernel-call.HandlerName, \
+// RUN:   value: 'CUDA_CHECK_KERNEL'}, \
+// RUN:   {key: cuda-unsafe-kernel-call.AcceptedHandlers, \
+// RUN:value: 'ALTERNATIVE_CUDA_CHECK_KERNEL, cudaCheckKernel, \
+// RUN:alternative::alternativeCudaCheckKernel, \
+// RUN:otherAlternativeCudaCheckKernel'}] \
+// RUN: }" \
+// RUN:   -- -isystem %clang_tidy_headers
+
+#include 
+
+#define CUDA_CHECK_KERNEL() do {} while(0)
+
+#define ALTERNATIVE_CUDA_CHECK_KERNEL() CUDA_CHECK_KERNEL()
+
+void cudaCheckKernel();
+
+namespace alternative {
+
+void alternativeCudaCheckKernel();
+void otherAlternativeCudaCheckKernel();
+
+}
+
+__global__
+void b();
+
+#define KERNEL_CALL() do {b<<<1, 2>>>();} while(0)
+
+void errorCheck() {
+  auto err = cudaGetLastError();
+}
+
+void bad() {
+  b<<<1, 2>>>(); // sample comment
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+
+  KERNEL_CALL(); // sample comment
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+  // There isn't supposed to be a fix here since it's a macro call
+
+  if(true)
+b<<<1, 2>>>()  ; // Brackets omitted purposefully, since they create an additional AST node
+// CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+  else {
+b<<<1, 2>>>();
+// CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+b<<<1, 2>>>();
+// CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+  }
+  auto err = cudaGetLastError();
+
+  b<<<1, 2>>>();
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+  if (true)
+cudaGetLastError();
+
+  b<<<1, 2>>>();
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+  for(;;)
+auto err2 = cudaGetLastError(); // Brackets omitted purposefully, since they create an additional AST node
+
+  b<<<1, 2>>>();
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+  auto err3 = true ? 1 : cudaGetLastError();
+
+  b<<<1, 2>>>();
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+  auto err4 = cudaDeviceReset() + cudaGetLastError();
+
+  b<<<1, 2>>>();
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error after a kernel launch.
+  // Calling an error-checking function after a kernel is not considered safe.
+  errorCheck();
+}
+
+void good() {
+  b<<<1, 2>>>();; /* The semicolons are here because the
+detection of the macro is done with a lexer */ ;
+  CUDA_CHECK_KERNEL();
+
+  b<<<1, 2>>>();
+  ALTERNATIVE_CUDA_CHECK_KERNEL();
+
+  b<<<1, 2>>>();
+  alternative::alternativeCudaCheckKernel();
+
+  b<<<1, 2>>>();
+  alternative::otherAlternativeCudaCheckKernel();
+
+  b<<<1, 2>>>();
+  switch(1 + cudaGetLastError()) {
+default:;
+  }
+
+  b<<<1, 2>>>();
+  if(3 < cudaGetLastError()) {
+1;
+  } else {
+2;
+  }
+
+  b<<<1, 2>>>();
+  for(int i = cudaGetLastError();;);
+
+  b<<<1, 2>>>();
+  do {
+  do {
+  do {
+auto err2 = cudaGetLastError();
+  } while(0);
+  } while(0);
+  } while(0);
+}
Index: clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-function-handler.cu
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-function-han

[PATCH] D133982: [clangd] Improve inlay hints of things expanded from macros

2022-09-15 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: nridge.
Herald added a subscriber: arphaman.
Herald added a project: All.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

When we aim a hint at some expanded tokens, we're only willing to attach it
to spelled tokens that exactly corresponde.

e.g.
int zoom(int x, int y, int z);
int dummy = zoom(NUMBERS);

Here we want to place a hint "x:" on the expanded "1", but we shouldn't
be willing to place it on NUMBERS, because it doesn't *exactly*
correspond (it has more tokens).

Fortunately we don't even have to implement this algorithm from scratch,
TokenBuffer has it.

Fixes https://github.com/clangd/clangd/issues/1289
Fixes https://github.com/clangd/clangd/issues/1118
Fixes https://github.com/clangd/clangd/issues/1018


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133982

Files:
  clang-tools-extra/clangd/InlayHints.cpp
  clang-tools-extra/clangd/unittests/InlayHintTests.cpp

Index: clang-tools-extra/clangd/unittests/InlayHintTests.cpp
===
--- clang-tools-extra/clangd/unittests/InlayHintTests.cpp
+++ clang-tools-extra/clangd/unittests/InlayHintTests.cpp
@@ -820,6 +820,15 @@
 }
   )cpp",
ExpectedHint{"param: ", "param"});
+
+  // If the macro expands to multiple arguments, don't hint it.
+  assertParameterHints(R"cpp(
+void foo(double x, double y);
+#define CONSTANTS 3.14, 2.72
+void bar() {
+  foo(CONSTANTS);
+}
+  )cpp");
 }
 
 TEST(ParameterHints, ConstructorParens) {
Index: clang-tools-extra/clangd/InlayHints.cpp
===
--- clang-tools-extra/clangd/InlayHints.cpp
+++ clang-tools-extra/clangd/InlayHints.cpp
@@ -10,6 +10,7 @@
 #include "Config.h"
 #include "HeuristicResolver.h"
 #include "ParsedAST.h"
+#include "SourceCode.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclarationName.h"
 #include "clang/AST/ExprCXX.h"
@@ -192,8 +193,8 @@
 public:
   InlayHintVisitor(std::vector &Results, ParsedAST &AST,
const Config &Cfg, llvm::Optional RestrictRange)
-  : Results(Results), AST(AST.getASTContext()), Cfg(Cfg),
-RestrictRange(std::move(RestrictRange)),
+  : Results(Results), AST(AST.getASTContext()), Tokens(AST.getTokens()),
+Cfg(Cfg), RestrictRange(std::move(RestrictRange)),
 MainFileID(AST.getSourceManager().getMainFileID()),
 Resolver(AST.getHeuristicResolver()),
 TypeHintPolicy(this->AST.getPrintingPolicy()),
@@ -227,8 +228,7 @@
   return true;
 }
 
-processCall(E->getParenOrBraceRange().getBegin(), E->getConstructor(),
-{E->getArgs(), E->getNumArgs()});
+processCall(E->getConstructor(), {E->getArgs(), E->getNumArgs()});
 return true;
   }
 
@@ -254,7 +254,7 @@
 if (!Callee)
   return true;
 
-processCall(E->getRParenLoc(), Callee, {E->getArgs(), E->getNumArgs()});
+processCall(Callee, {E->getArgs(), E->getNumArgs()});
 return true;
   }
 
@@ -278,11 +278,11 @@
 return true;
   }
 
-  void addReturnTypeHint(FunctionDecl *D, SourceLocation Loc) {
+  void addReturnTypeHint(FunctionDecl *D, SourceRange Range) {
 auto *AT = D->getReturnType()->getContainedAutoType();
 if (!AT || AT->getDeducedType().isNull())
   return;
-addTypeHint(Loc, D->getReturnType(), /*Prefix=*/"-> ");
+addTypeHint(Range, D->getReturnType(), /*Prefix=*/"-> ");
   }
 
   bool VisitVarDecl(VarDecl *D) {
@@ -375,21 +375,11 @@
 private:
   using NameVec = SmallVector;
 
-  // The purpose of Anchor is to deal with macros. It should be the call's
-  // opening or closing parenthesis or brace. (Always using the opening would
-  // make more sense but CallExpr only exposes the closing.) We heuristically
-  // assume that if this location does not come from a macro definition, then
-  // the entire argument list likely appears in the main file and can be hinted.
-  void processCall(SourceLocation Anchor, const FunctionDecl *Callee,
+  void processCall(const FunctionDecl *Callee,
llvm::ArrayRef Args) {
 if (!Cfg.InlayHints.Parameters || Args.size() == 0 || !Callee)
   return;
 
-// If the anchor location comes from a macro definition, there's nowhere to
-// put hints.
-if (!AST.getSourceManager().getTopMacroCallerLoc(Anchor).isFileID())
-  return;
-
 // The parameter name of a move or copy constructor is not very interesting.
 if (auto *Ctor = dyn_cast(Callee))
   if (Ctor->isCopyOrMoveConstructor())
@@ -637,25 +627,33 @@
 #undef CHECK_KIND
 }
 
-auto FileRange =
-toHalfOpenFileRange(AST.getSourceManager(), AST.getLangOpts(), R);
-if (!FileRange)
+auto LSPRange = getHintRange(R);
+if (!LSPRange)
   return;
-Range LSPRange{
-sourceLocToPosition(AS

[PATCH] D133436: Ground work for cuda-related checks in clang-tidy

2022-09-15 Thread Bartłomiej Cieślar via Phabricator via cfe-commits
barcisz updated this revision to Diff 460520.
barcisz added a comment.

moved size_t definition to an stddef.h stub


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133436

Files:
  clang-tools-extra/clang-tidy/CMakeLists.txt
  clang-tools-extra/clang-tidy/ClangTidyForceLinker.h
  clang-tools-extra/clang-tidy/cuda/CMakeLists.txt
  clang-tools-extra/clang-tidy/cuda/CudaTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/index.rst
  clang-tools-extra/test/clang-tidy/check_clang_tidy.py
  clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/cuda/cuda.h
  clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/stddef.h

Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/stddef.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/stddef.h
@@ -0,0 +1,14 @@
+//===--- stddef.h - Stub header for tests ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef _STDDEF_H_
+#define _STDDEF_H_
+
+using size_t = long long unsigned;
+
+#endif // _STDDEF_H_
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/cuda/cuda.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/cuda/cuda.h
@@ -0,0 +1,28 @@
+/* Minimal declarations for CUDA support.  Testing purposes only. */
+
+#include "../stddef.h"
+
+#define __constant__ __attribute__((constant))
+#define __device__ __attribute__((device))
+#define __global__ __attribute__((global))
+#define __host__ __attribute__((host))
+#define __shared__ __attribute__((shared))
+
+struct dim3 {
+  unsigned x, y, z;
+  __host__ __device__ dim3(unsigned x, unsigned y = 1, unsigned z = 1) : x(x), y(y), z(z) {}
+};
+
+typedef struct cudaStream *cudaStream_t;
+typedef enum cudaError {} cudaError_t;
+extern "C" int cudaConfigureCall(dim3 gridSize, dim3 blockSize,
+ size_t sharedSize = 0,
+ cudaStream_t stream = 0);
+extern "C" int __cudaPushCallConfiguration(dim3 gridSize, dim3 blockSize,
+   size_t sharedSize = 0,
+   cudaStream_t stream = 0);
+extern "C" cudaError_t cudaLaunchKernel(const void *func, dim3 gridDim,
+dim3 blockDim, void **args,
+size_t sharedMem, cudaStream_t stream);
+
+extern "C" __device__ int printf(const char*, ...);
Index: clang-tools-extra/test/clang-tidy/check_clang_tidy.py
===
--- clang-tools-extra/test/clang-tidy/check_clang_tidy.py
+++ clang-tools-extra/test/clang-tidy/check_clang_tidy.py
@@ -93,7 +93,7 @@
 
 file_name_with_extension = self.assume_file_name or self.input_file_name
 _, extension = os.path.splitext(file_name_with_extension)
-if extension not in ['.c', '.hpp', '.m', '.mm']:
+if extension not in ['.c', '.cu', '.hpp', '.m', '.mm']:
   extension = '.cpp'
 self.temp_file_name = self.temp_file_name + extension
 
@@ -115,9 +115,14 @@
   self.clang_extra_args = ['-fobjc-abi-version=2', '-fobjc-arc', '-fblocks'] + \
   self.clang_extra_args
 
-if extension in ['.cpp', '.hpp', '.mm']:
+if extension in ['.cpp', '.cu', '.hpp', '.mm']:
   self.clang_extra_args.append('-std=' + self.std)
 
+# Tests should not rely on a certain cuda headers and library version
+# being available on the machine
+if extension == '.cu':
+  self.clang_extra_args.extend(["--no-cuda-version-check", "-nocudalib", "-nocudainc"])
+
 # Tests should not rely on STL being available, and instead provide mock
 # implementations of relevant APIs.
 self.clang_extra_args.append('-nostdinc++')
Index: clang-tools-extra/docs/clang-tidy/index.rst
===
--- clang-tools-extra/docs/clang-tidy/index.rst
+++ clang-tools-extra/docs/clang-tidy/index.rst
@@ -67,6 +67,7 @@
 ``concurrency-``   Checks related to concurrent programming (including
threads, fibers, coroutines, etc.).
 ``cppcoreguidelines-`` Checks related to C++ Core Guidelines.
+``cuda-``  Checks related to CUDA best practices.
 ``darwin-``Checks related to Darwin coding conventions.
 ``fuchsia-``   Checks related to Fuchsia coding conventions.
 ``google-``Checks related to Google coding conve

[PATCH] D130096: [Clang][AMDGPU] Emit AMDGPU library control constants in clang

2022-09-15 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: clang/lib/CodeGen/TargetInfo.cpp:9449-9450
+  !(Features & llvm::AMDGPU::FEATURE_WAVE32) ||
+  llvm::is_contained(CGM.getTarget().getTargetOpts().FeaturesAsWritten,
+ "+wavefrontsize64");
+

Do we really have to scan through the features too? This seems broken



Comment at: clang/lib/CodeGen/TargetInfo.cpp:9455
+  bool UnsafeMath = CGM.getLangOpts().UnsafeFPMath;
+  bool DenormAtZero = CGM.getCodeGenOpts().FP32DenormalMode ==
+  llvm::DenormalMode::getPreserveSign();

s/DenormAtZero/DenormAreZero/?



Comment at: clang/lib/CodeGen/TargetInfo.cpp:9458
+  bool FiniteOnly =
+  CGM.getLangOpts().NoHonorInfs || CGM.getLangOpts().NoHonorNaNs;
+

or doesn't look right. finite only is no infinities and no nans (not sure why 
the library control merges the two)



Comment at: clang/lib/CodeGen/TargetInfo.cpp:9473-9475
+  AddGlobal("__oclc_ISA_version", Minor + Major * 1000, /*Size=*/32);
+  AddGlobal("__oclc_ABI_version",
+CGM.getTarget().getTargetOpts().CodeObjectVersion, /*Size=*/32);

These probably should use linkonce_odr


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130096

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


[PATCH] D133436: Ground work for cuda-related checks in clang-tidy

2022-09-15 Thread Bartłomiej Cieślar via Phabricator via cfe-commits
barcisz updated this revision to Diff 460519.
barcisz added a comment.

Dummy definition for size_t


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133436

Files:
  clang-tools-extra/clang-tidy/CMakeLists.txt
  clang-tools-extra/clang-tidy/ClangTidyForceLinker.h
  clang-tools-extra/clang-tidy/cuda/CMakeLists.txt
  clang-tools-extra/clang-tidy/cuda/CudaTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/index.rst
  clang-tools-extra/test/clang-tidy/check_clang_tidy.py
  clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/cuda/cuda.h

Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/cuda/cuda.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/cuda/cuda.h
@@ -0,0 +1,28 @@
+/* Minimal declarations for CUDA support.  Testing purposes only. */
+
+using size_t = long long unsigned;
+
+#define __constant__ __attribute__((constant))
+#define __device__ __attribute__((device))
+#define __global__ __attribute__((global))
+#define __host__ __attribute__((host))
+#define __shared__ __attribute__((shared))
+
+struct dim3 {
+  unsigned x, y, z;
+  __host__ __device__ dim3(unsigned x, unsigned y = 1, unsigned z = 1) : x(x), y(y), z(z) {}
+};
+
+typedef struct cudaStream *cudaStream_t;
+typedef enum cudaError {} cudaError_t;
+extern "C" int cudaConfigureCall(dim3 gridSize, dim3 blockSize,
+ size_t sharedSize = 0,
+ cudaStream_t stream = 0);
+extern "C" int __cudaPushCallConfiguration(dim3 gridSize, dim3 blockSize,
+   size_t sharedSize = 0,
+   cudaStream_t stream = 0);
+extern "C" cudaError_t cudaLaunchKernel(const void *func, dim3 gridDim,
+dim3 blockDim, void **args,
+size_t sharedMem, cudaStream_t stream);
+
+extern "C" __device__ int printf(const char*, ...);
Index: clang-tools-extra/test/clang-tidy/check_clang_tidy.py
===
--- clang-tools-extra/test/clang-tidy/check_clang_tidy.py
+++ clang-tools-extra/test/clang-tidy/check_clang_tidy.py
@@ -93,7 +93,7 @@
 
 file_name_with_extension = self.assume_file_name or self.input_file_name
 _, extension = os.path.splitext(file_name_with_extension)
-if extension not in ['.c', '.hpp', '.m', '.mm']:
+if extension not in ['.c', '.cu', '.hpp', '.m', '.mm']:
   extension = '.cpp'
 self.temp_file_name = self.temp_file_name + extension
 
@@ -115,9 +115,14 @@
   self.clang_extra_args = ['-fobjc-abi-version=2', '-fobjc-arc', '-fblocks'] + \
   self.clang_extra_args
 
-if extension in ['.cpp', '.hpp', '.mm']:
+if extension in ['.cpp', '.cu', '.hpp', '.mm']:
   self.clang_extra_args.append('-std=' + self.std)
 
+# Tests should not rely on a certain cuda headers and library version
+# being available on the machine
+if extension == '.cu':
+  self.clang_extra_args.extend(["--no-cuda-version-check", "-nocudalib", "-nocudainc"])
+
 # Tests should not rely on STL being available, and instead provide mock
 # implementations of relevant APIs.
 self.clang_extra_args.append('-nostdinc++')
Index: clang-tools-extra/docs/clang-tidy/index.rst
===
--- clang-tools-extra/docs/clang-tidy/index.rst
+++ clang-tools-extra/docs/clang-tidy/index.rst
@@ -67,6 +67,7 @@
 ``concurrency-``   Checks related to concurrent programming (including
threads, fibers, coroutines, etc.).
 ``cppcoreguidelines-`` Checks related to C++ Core Guidelines.
+``cuda-``  Checks related to CUDA best practices.
 ``darwin-``Checks related to Darwin coding conventions.
 ``fuchsia-``   Checks related to Fuchsia coding conventions.
 ``google-``Checks related to Google coding conventions.
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -16,6 +16,7 @@
clang-analyzer/*
concurrency/*
cppcoreguidelines/*
+   cuda/*
darwin/*
fuchsia/*
google/*
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -96,6 +96,8 @@
 Improvements to clang-tidy
 --
 
+- Introduce the cuda module for checks specific to CUDA code.
+
 New checks
 ^^
 
Index: clang-tools-extra/clang-tidy/cuda/CudaTidyModul

[PATCH] D133157: Add -fsanitizer-coverage=control-flow

2022-09-15 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka updated this revision to Diff 460518.
vitalybuka added a comment.

clang-format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133157

Files:
  clang/docs/SanitizerCoverage.rst
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/SanitizerArgs.cpp
  
compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_control_flow.cpp
  llvm/include/llvm/Transforms/Instrumentation.h
  llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
  llvm/test/Instrumentation/SanitizerCoverage/control-flow.ll

Index: llvm/test/Instrumentation/SanitizerCoverage/control-flow.ll
===
--- /dev/null
+++ llvm/test/Instrumentation/SanitizerCoverage/control-flow.ll
@@ -0,0 +1,22 @@
+; Test -sanitizer-coverage-control-flow.
+; RUN: opt < %s -passes='module(sancov-module)' -sanitizer-coverage-level=3 -sanitizer-coverage-control-flow -S | FileCheck %s
+
+target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64"
+target triple = "x86_64-unknown-linux-gnu"
+define void @foo(ptr %a) sanitize_address {
+entry:
+  %tobool = icmp eq i32* %a, null
+  br i1 %tobool, label %if.end, label %if.then
+
+  if.then:  ; preds = %entry
+  store i32 0, i32* %a, align 4
+  call void @foo(i32* %a)
+  br label %if.end
+
+  if.end:   ; preds = %entry, %if.then
+  ret void
+}
+
+; CHECK: private constant [17 x ptr] [{{.*}}@foo{{.*}}blockaddress{{.*}}blockaddress{{.*}}blockaddress{{.*}}blockaddress{{.*}}blockaddress{{.*}}blockaddress{{.*}}blockaddress{{.*}}@foo{{.*}}null{{.*}}null], section "__sancov_cfs", comdat($foo), align 8
+; CHECK:  @__start___sancov_cfs = extern_weak hidden global
+; CHECK-NEXT: @__stop___sancov_cfs = extern_weak hidden global
Index: llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
===
--- llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
+++ llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
@@ -75,11 +75,13 @@
 const char SanCov8bitCountersInitName[] = "__sanitizer_cov_8bit_counters_init";
 const char SanCovBoolFlagInitName[] = "__sanitizer_cov_bool_flag_init";
 const char SanCovPCsInitName[] = "__sanitizer_cov_pcs_init";
+const char SanCovCFsInitName[] = "__sanitizer_cov_cfs_init";
 
 const char SanCovGuardsSectionName[] = "sancov_guards";
 const char SanCovCountersSectionName[] = "sancov_cntrs";
 const char SanCovBoolFlagSectionName[] = "sancov_bools";
 const char SanCovPCsSectionName[] = "sancov_pcs";
+const char SanCovCFsSectionName[] = "sancov_cfs";
 
 const char SanCovLowestStackName[] = "__sancov_lowest_stack";
 
@@ -147,6 +149,11 @@
   cl::desc("max stack depth tracing"),
   cl::Hidden, cl::init(false));
 
+static cl::opt
+ClCollectCF("sanitizer-coverage-control-flow",
+cl::desc("collect control flow for each function"), cl::Hidden,
+cl::init(false));
+
 namespace {
 
 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
@@ -193,6 +200,7 @@
   !Options.Inline8bitCounters && !Options.StackDepth &&
   !Options.InlineBoolFlag && !Options.TraceLoads && !Options.TraceStores)
 Options.TracePCGuard = true; // TracePCGuard is default.
+  Options.CollectControlFlow |= ClCollectCF;
   return Options;
 }
 
@@ -212,6 +220,7 @@
 PostDomTreeCallback PDTCallback);
 
 private:
+  void createFunctionControlFlow(Function &F);
   void instrumentFunction(Function &F, DomTreeCallback DTCallback,
   PostDomTreeCallback PDTCallback);
   void InjectCoverageForIndirectCalls(Function &F,
@@ -270,6 +279,7 @@
   GlobalVariable *Function8bitCounterArray;  // for inline-8bit-counters.
   GlobalVariable *FunctionBoolArray; // for inline-bool-flag.
   GlobalVariable *FunctionPCsArray;  // for pc-table.
+  GlobalVariable *FunctionCFsArray;  // for control flow table
   SmallVector GlobalsToAppendToUsed;
   SmallVector GlobalsToAppendToCompilerUsed;
 
@@ -378,6 +388,7 @@
   Function8bitCounterArray = nullptr;
   FunctionBoolArray = nullptr;
   FunctionPCsArray = nullptr;
+  FunctionCFsArray = nullptr;
   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
   IntptrPtrTy = PointerType::getUnqual(IntptrTy);
   Type *VoidTy = Type::getVoidTy(*C);
@@ -502,6 +513,15 @@
 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
   }
+
+  if (Ctor && Options.CollectControlFlow) {
+auto SecStartEnd = CreateSecStartEnd(M, SanCovCF

[PATCH] D133157: Add -fsanitizer-coverage=control-flow

2022-09-15 Thread Navid Emamdoost via Phabricator via cfe-commits
Navidem added a comment.

Thanks @kcc @vitalybuka, I do not have commit access.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133157

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


[PATCH] D53847: [C++2a] P0634r3: Down with typename!

2022-09-15 Thread Alan Zhao via Phabricator via cfe-commits
ayzhao updated this revision to Diff 460514.
ayzhao added a comment.

hacky fix for the test CXX/module/module.interface/p2-2.cpp

If anyone has a better idea on how to fix this test, feedback is **very** 
welcome.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D53847

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/DeclSpec.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Parse/ParseTemplate.cpp
  clang/lib/Parse/ParseTentative.cpp
  clang/lib/Parse/Parser.cpp
  clang/lib/Sema/DeclSpec.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/test/CXX/basic/basic.lookup/basic.lookup.qual/class.qual/p2.cpp
  clang/test/CXX/drs/dr1xx.cpp
  clang/test/CXX/drs/dr2xx.cpp
  clang/test/CXX/drs/dr4xx.cpp
  clang/test/CXX/drs/dr5xx.cpp
  clang/test/CXX/temp/temp.res/p3.cpp
  clang/test/CXX/temp/temp.res/p4.cpp
  clang/test/CXX/temp/temp.res/temp.dep/temp.dep.type/p1.cpp
  clang/test/FixIt/fixit.cpp
  clang/test/Parser/cxx-member-initializers.cpp
  clang/test/SemaCXX/MicrosoftCompatibility.cpp
  clang/test/SemaCXX/MicrosoftExtensions.cpp
  clang/test/SemaCXX/MicrosoftSuper.cpp
  clang/test/SemaCXX/rounding-math-crash.cpp
  clang/test/SemaCXX/typo-correction.cpp
  clang/test/SemaCXX/unknown-type-name.cpp
  clang/test/SemaTemplate/alias-templates.cpp
  clang/test/SemaTemplate/typename-specifier-3.cpp

Index: clang/test/SemaTemplate/typename-specifier-3.cpp
===
--- clang/test/SemaTemplate/typename-specifier-3.cpp
+++ clang/test/SemaTemplate/typename-specifier-3.cpp
@@ -28,7 +28,7 @@
   typedef int arg;
 };
 struct C {
-  typedef B::X x; // expected-error {{missing 'typename'}}
+  typedef B::X x; // precxx17-warning{{missing 'typename' prior to dependent type name B::X; implicit 'typename' is a C++20 extension}}
 };
   };
 
Index: clang/test/SemaTemplate/alias-templates.cpp
===
--- clang/test/SemaTemplate/alias-templates.cpp
+++ clang/test/SemaTemplate/alias-templates.cpp
@@ -193,11 +193,10 @@
   struct base {
 template  struct derived;
   };
-  // FIXME: The diagnostics here are terrible.
   template 
-  using derived = base::template derived; // expected-error {{expected a type}} expected-error {{expected ';'}}
+  using derived = base::template derived; // expected-warning {{missing 'typename'}}
   template 
-  using derived2 = ::PR16904::base::template derived; // expected-error {{expected a type}} expected-error {{expected ';'}}
+  using derived2 = ::PR16904::base::template derived; // expected-warning {{missing 'typename'}}
 }
 
 namespace PR14858 {
Index: clang/test/SemaCXX/unknown-type-name.cpp
===
--- clang/test/SemaCXX/unknown-type-name.cpp
+++ clang/test/SemaCXX/unknown-type-name.cpp
@@ -36,15 +36,15 @@
 
   static int n;
   static type m;
-  static int h(T::type, int); // expected-error{{missing 'typename'}}
-  static int h(T::type x, char); // expected-error{{missing 'typename'}}
+  static int h(T::type, int); // expected-warning{{implicit 'typename' is a C++20 extension}}
+  static int h(T::type x, char); // expected-warning{{implicit 'typename' is a C++20 extension}}
 };
 
 template
-A::type g(T t) { return t; } // expected-error{{missing 'typename'}}
+A::type g(T t) { return t; } // expected-warning{{implicit 'typename' is a C++20 extension}}
 
 template
-A::type A::f() { return type(); } // expected-error{{missing 'typename'}}
+A::type A::f() { return type(); } // expected-warning{{implicit 'typename' is a C++20 extension}}
 
 template
 void f(T::type) { } // expected-error{{missing 'typename'}}
@@ -84,11 +84,11 @@
 
 template int A::n(T::value); // ok
 template
-A::type // expected-error{{missing 'typename'}}
+A::type // expected-warning {{implicit 'typename' is a C++20 extension}}
 A::m(T::value, 0); // ok
 
-template int A::h(T::type, int) {} // expected-error{{missing 'typename'}}
-template int A::h(T::type x, char) {} // expected-error{{missing 'typename'}}
+template int A::h(T::type, int) {} // expected-warning{{implicit 'typename' is a C++20 extension}}
+template int A::h(T::type x, char) {} // expected-warning{{implicit 'typename' is a C++20 extension}}
 
 template int h(T::type, int); // expected-error{{missing 'typename'}}
 template int h(T::type x, char); // expected-error{{missing 'typename'}}
@@ -116,4 +116,5 @@
 // FIXME: We know which type specifier should have been specified here. Provide
 //a fix-it to add 'typename A::type'
 template
-A::g() { } // expected-error{{a type specifier is required}}
+A::g() { } // expected-error{{expecte

[PATCH] D53847: [C++2a] P0634r3: Down with typename!

2022-09-15 Thread Alan Zhao via Phabricator via cfe-commits
ayzhao added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:362
+// allow this as an extension.
+if (AllowImplicitTypename == ImplicitTypenameContext::No &&
+!isClassName && !IsCtorOrDtorName)

ayzhao wrote:
> Status update:
> 
> This line is currently causing 
> [p2-2.cpp](https://github.com/llvm/llvm-project/blob/main/clang/test/CXX/module/module.interface/p2-2.cpp)
>  to fail with the following error:
> 
> ```
> FAIL: Clang :: CXX/module/module.interface/p2-2.cpp (2 of 17555)
>  TEST 'Clang :: CXX/module/module.interface/p2-2.cpp' 
> FAILED 
> Script:
> --
> : 'RUN: at line 3';   /dev/shm/ayzhao_llvm/llvm-project/build/bin/clang -cc1 
> -internal-isystem 
> /dev/shm/ayzhao_llvm/llvm-project/build/lib/clang/16.0.0/include 
> -nostdsysteminc -std=c++20 
> /dev/shm/ayzhao_llvm/llvm-project/clang/test/CXX/module/module.interface/p2-2.cpp
>  -verify
> --
> Exit Code: 1
>  
> Command Output (stderr):
> --
> error: 'error' diagnostics expected but not seen:
>   File 
> /dev/shm/ayzhao_llvm/llvm-project/clang/test/CXX/module/module.interface/p2-2.cpp
>  Line 17: cannot export 'iterator' as it is not at namespace scope
>   File 
> /dev/shm/ayzhao_llvm/llvm-project/clang/test/CXX/module/module.interface/p2-2.cpp
>  Line 35: cannot export 'iterator' as it is not at namespace scope
> error: 'error' diagnostics seen but not expected:
>   File 
> /dev/shm/ayzhao_llvm/llvm-project/clang/test/CXX/module/module.interface/p2-2.cpp
>  Line 17: declaration does not declare anything
>   File 
> /dev/shm/ayzhao_llvm/llvm-project/clang/test/CXX/module/module.interface/p2-2.cpp
>  Line 35: declaration does not declare anything
> 4 errors generated.
>  
> --
>  
> 
> ```
> 
> A reduced repro is here:
> 
> ```
> export module X;
> 
> export template 
> struct X {
>   struct iterator {
> T node;
>   };
> };
> 
> export template  X::iterator;
> ```
> 
> `Sema::getTypeName(...)` is called from [these 
> lines](https://github.com/llvm/llvm-project/blob/ace05124f5494173ae4769259d49f33d75d6f76b/clang/lib/Parse/ParseDecl.cpp#L3391-L3396),
>  with the result being that `TypeRep` is null in main but not null in this 
> patch.
> 
> I'm still in the process of trying to figure out how to resolve this, but any 
> suggestions/insights would be **very** welcome.
I fixed this with the following diff:

```
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 1375431d8998..dacba4d18021 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -362,6 +362,11 @@ ParsedType Sema::getTypeName(const IdentifierInfo &II, 
SourceLocation NameLoc,
 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
 !isClassName && !IsCtorOrDtorName)
   return nullptr;
+// FIXME: This hack is required in order to make the test
+// CXX/module/module.interface/p2-2.cpp pass. Can we get this working
+// with this method returning a non-null ParsedType?
+if (isa(CurContext))
+  return nullptr;
 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
 if (IsImplicitTypename) {
   SourceLocation QualifiedLoc = SS->getRange().getBegin();
```

It's very hacky, but it works (for now)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D53847

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


[PATCH] D133725: Searching for tokens including comments

2022-09-15 Thread Bartłomiej Cieślar via Phabricator via cfe-commits
barcisz added a comment.

In D133725#3792787 , @aaron.ballman 
wrote:

> Can you help me understand the expected use for these change?

Changed the description to answer your question - it's a prerequisite to 
D133942  and D133956 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133725

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


[PATCH] D133956: git push Cuda Check for ignored errors after calling a CUDA kernel

2022-09-15 Thread Bartłomiej Cieślar via Phabricator via cfe-commits
barcisz added a comment.

In D133956#3793022 , @tra wrote:

> I think ultimately the checker should be generalized to flag all unchecked 
> CUDA runtime calls. The problem is that that is going to be exceedingly noisy 
> in practice as a lot of real code does not bother to check for the errors 
> consistently. Limiting the checks to kernel launches may be a reasonable 
> starting point as it would give us the ability to zero in on the culprit 
> kernel by running the app with "CUDA_LAUNCH_BLOCKING".

By that do you mean that the way the check is now it is acceptable or that it 
should be improved to handle intra-procedural analysis? The intention with this 
check is to work a lot in tandem with the one in D133804 
, which therefore prevents most such cases. 
The practice that the check checks for is also commonly used in ML frameworks 
which heavily rely on CUDA, so not catching such cases might still be helpful 
for them just for the sake of preserving code consistency and catching such 
errors (since if there is an error then that means that some part of the code 
was broken anyways). Thus, the check is optimized for lowering false positives 
during static checking and for a practice lowering the number of false 
negatives within the CUDA code.




Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu:53
+  }
+  auto err = cudaGetLastError();
+

tra wrote:
> Just curious -- is it sufficient to just call `cudaGetLastError();` ? Or does 
> the checker require using its result, too? I.e. in practice this particular 
> check will not really do anything useful. The tests below look somewhat 
> inconsistent. 
Technically it does not require the user to actually use the value of 
`cudaGetLastError()`, but


  # If they are calling it then they most likely did not place this call there 
randomly and are using it to check for the error returned by the kernel
  # the check being introduced in D133804 can be used to check if the return 
value has been used, so checking it here as well would have been a duplication





Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu:75
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked 
error after a kernel launch.
+  // Calling an error-checking function after a kernel is not considered safe.
+  errorCheck();

tra wrote:
> WDYM by "is not considered safe" here? How is that different from calling 
> `cudaGetLastError()` and checking its value?
As in the check does not do inter-procedural analysis short of adding the 
handler to AcceptedHandlers, so the check will flag such occurences



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu:80-82
+  b<<<1, 2>>>();; /* The semicolons are here because the
+detection of the macro is done with a lexer */ ;
+  CUDA_CHECK_KERNEL();

tra wrote:
> What would happen with a single `;` as would be seen in the normal user code?
Nothing, it would work just fine; it's rather that all other kernel calls in 
this test use a single `;` so I want to check this case here



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu:112
+  do {
+auto err2 = cudaGetLastError();
+  } while(0);

tra wrote:
> Why does this case produce no warning, while a very similar case above does? 
> In both cases result of `cudaGetLastError()` is assigned to an unused 
> variable within the loop body.
> 
> ```
>   b<<<1, 2>>>();
>   // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked 
> error after a kernel launch.
>   for(;;)
> auto err2 = cudaGetLastError(); // Brackets omitted purposefully, since 
> they create an additional AST node
> 
> ```
Because often a macro will wrap its error handling code in a do {...} while(0) 
loop and that's why we check this case and simmilar ones with CFG analysis


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133956

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


[PATCH] D133732: [clang-doc] Support default args for functions.

2022-09-15 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth added a comment.

Thanks for the patch. This is mostly LGTM modulo a few nits.

My one question is regarding documentation. Do you think this needs to be 
described in the clang-tools-extra/doc/clang-doc.rst? And are there any changes 
in workflow or tool usage that we should document? I assume not, since this 
just changes the YAML format. Is that correct?




Comment at: clang-tools-extra/clang-doc/Serialize.cpp:300
 
-auto& member = I.Members.emplace_back(
+auto &member = I.Members.emplace_back(
 F->getTypeSourceInfo()->getType().getAsString(), F->getNameAsString(),

nit: can we avoid introducing unrelated formatting changes, here and elsewhere 
in the patch?



Comment at: clang-tools-extra/clang-doc/Serialize.cpp:324-329
+  } else {
+FieldInfo = &I.Params.emplace_back(P->getOriginalType().getAsString(),
+   P->getNameAsString());
   }
+} else {
+  FieldInfo = &I.Params.emplace_back(P->getOriginalType().getAsString(),

can we combine these conditions somehow, given that they do the same thing?

Maybe this? WDYT?

```
if(!FieldInfo)
  FieldInfo = &I.Params.emplace_back(P->getOriginalType().getAsString(), ...
```




Comment at: clang-tools-extra/clang-doc/Serialize.cpp:452
 
-  ASTContext& Context = D->getASTContext();
+  ASTContext &Context = D->getASTContext();
   // TODO investigate whether we can use ASTContext::getCommentForDecl instead

nit: same here



Comment at: clang-tools-extra/clang-doc/Serialize.cpp:460
   Comment->setAttached();
-  if (comments::FullComment* fc = Comment->parse(Context, nullptr, D)) {
+  if (comments::FullComment *fc = Comment->parse(Context, nullptr, D)) {
 I.Description.emplace_back();

nit: ditto


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133732

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


[PATCH] D133979: [clangd] XRef functions treat visible class definitions as primary.

2022-09-15 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: kadircet.
Herald added a subscriber: arphaman.
Herald added a project: All.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

This means go-to-type will take us to a class definition in most cases.
As an exception, if the class is declared in a header and defined in a CC file,
then these are treated as a decl/def pair.

This is (fairly) consistent with how the index behaves, though the index
benefits from aggregation across translation units so does a simpler "main file"
check rather than explicitly "is this a header".


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133979

Files:
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp


Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -568,8 +568,8 @@
   )cpp",
 
   R"cpp(// Forward class declaration
-class $decl[[Foo]];
-class $def[[Foo]] {};
+class Foo;
+class [[Foo]] {};
 F^oo* foo();
   )cpp",
 
@@ -1030,6 +1030,33 @@
 }
   }
 }
+
+TEST(LocateSymbol, TypeForwardDeclaredInHeader) {
+  Annotations Code(R"cpp(
+class [[X]] {};
+^X *x;
+  )cpp");
+
+  TestTU TU;
+  TU.HeaderCode = "class X;";
+  TU.Code = Code.code();
+
+  auto AST = TU.build();
+  auto Index = TU.index();
+  LocatedSymbol S = locateSymbolAt(AST, Code.point(), Index.get()).front();
+  EXPECT_EQ(S.Name, "X");
+  auto Filename = [&](const Location &L) {
+return llvm::sys::path::filename(L.uri.file());
+  };
+  EXPECT_EQ(Filename(S.PreferredDeclaration), TU.HeaderFilename);
+  EXPECT_EQ(Filename(*S.Definition), TU.Filename);
+
+  S = findType(AST, Code.point()).front();
+  EXPECT_EQ(S.Name, "X");
+  EXPECT_EQ(Filename(S.PreferredDeclaration), TU.HeaderFilename);
+  EXPECT_EQ(Filename(*S.Definition), TU.Filename);
+}
+
 TEST(LocateSymbol, ValidSymbolID) {
   auto T = Annotations(R"cpp(
 #define MACRO(x, y) ((x) + (y))
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -283,6 +283,30 @@
   // instead of failing.
   D = llvm::cast(D->getCanonicalDecl());
 
+  // Prefer C++ class definitions over a forward declaration.
+  if (const auto *TD = llvm::dyn_cast(D)) {
+if (const auto *Def = TD->getDefinition()) {
+  // Exception: forward decl is exposed in a header, definition is not.
+  // (This exception matches the spirit of our indexing heuristics).
+  if (/*PreferDef=*/[&] {
+if (Def == TD)
+  return true;
+const auto &SM = D->getASTContext().getSourceManager();
+FileID DefFile = 
SM.getDecomposedExpansionLoc(Def->getLocation()).first;
+if (DefFile != SM.getMainFileID())
+  return true; // definition is in a header.
+FileID DeclFile = SM.getDecomposedExpansionLoc(D->getLocation()).first;
+if (DefFile == DeclFile)
+  return true; // def/decl are equally visible.
+// We've established that the definition is in the main file, and the
+// decl is some other header.
+return isHeaderFile(SM.getFileEntryRefForID(DefFile)->getName(),
+D->getASTContext().getLangOpts());
+  }())
+D = Def;
+}
+  }
+
   // Prefer Objective-C class/protocol definitions over the forward 
declaration.
   if (const auto *ID = dyn_cast(D))
 if (const auto *DefinitionID = ID->getDefinition())


Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -568,8 +568,8 @@
   )cpp",
 
   R"cpp(// Forward class declaration
-class $decl[[Foo]];
-class $def[[Foo]] {};
+class Foo;
+class [[Foo]] {};
 F^oo* foo();
   )cpp",
 
@@ -1030,6 +1030,33 @@
 }
   }
 }
+
+TEST(LocateSymbol, TypeForwardDeclaredInHeader) {
+  Annotations Code(R"cpp(
+class [[X]] {};
+^X *x;
+  )cpp");
+
+  TestTU TU;
+  TU.HeaderCode = "class X;";
+  TU.Code = Code.code();
+
+  auto AST = TU.build();
+  auto Index = TU.index();
+  LocatedSymbol S = locateSymbolAt(AST, Code.point(), Index.get()).front();
+  EXPECT_EQ(S.Name, "X");
+  auto Filename = [&](const Location &L) {
+return llvm::sys::path::filename(L.uri.file());
+  };
+  EXPECT_EQ(Filename(S.PreferredDeclaration), TU.HeaderFilename);
+  EXPECT_EQ(Filename(*S.Definition), TU.Filename);
+
+  S = findType(AST, Code.point()).front();
+  EXPECT_EQ(S.Name, "X");
+  EXPECT_EQ(Filename(S.PreferredDeclaration), TU.Hea

[PATCH] D133662: [Clang] Change -ftime-trace storing path and support multiple compilation jobs

2022-09-15 Thread Mészáros Gergely via Phabricator via cfe-commits
Maetveis updated this revision to Diff 460507.
Maetveis retitled this revision from "[Clang] WIP: Change -ftime-trace storing 
path and support multiple compilation jobs" to "[Clang] Change -ftime-trace 
storing path and support multiple compilation jobs".
Maetveis added a comment.

Remove inline elements from the map. Add tests. With the tests I now consider 
this complete, so removed the draft from the title.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133662

Files:
  clang/include/clang/Driver/Compilation.h
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/Tool.h
  clang/include/clang/Frontend/FrontendOptions.h
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Clang.h
  clang/test/Driver/check-time-trace.cpp
  clang/tools/driver/cc1_main.cpp

Index: clang/tools/driver/cc1_main.cpp
===
--- clang/tools/driver/cc1_main.cpp
+++ clang/tools/driver/cc1_main.cpp
@@ -212,9 +212,7 @@
   bool Success = CompilerInvocation::CreateFromArgs(Clang->getInvocation(),
 Argv, Diags, Argv0);
 
-  if (Clang->getFrontendOpts().TimeTrace ||
-  !Clang->getFrontendOpts().TimeTracePath.empty()) {
-Clang->getFrontendOpts().TimeTrace = 1;
+  if (!Clang->getFrontendOpts().TimeTracePath.empty()) {
 llvm::timeTraceProfilerInitialize(
 Clang->getFrontendOpts().TimeTraceGranularity, Argv0);
   }
@@ -256,17 +254,10 @@
   llvm::TimerGroup::clearAll();
 
   if (llvm::timeTraceProfilerEnabled()) {
-SmallString<128> Path(Clang->getFrontendOpts().OutputFile);
-llvm::sys::path::replace_extension(Path, "json");
-if (!Clang->getFrontendOpts().TimeTracePath.empty()) {
-  // replace the suffix to '.json' directly
-  SmallString<128> TracePath(Clang->getFrontendOpts().TimeTracePath);
-  if (llvm::sys::fs::is_directory(TracePath))
-llvm::sys::path::append(TracePath, llvm::sys::path::filename(Path));
-  Path.assign(TracePath);
-}
+const StringRef TracePath = Clang->getFrontendOpts().TimeTracePath;
+assert(!TracePath.empty() && "`-ftime-trace=` is empty");
 if (auto profilerOutput = Clang->createOutputFile(
-Path.str(), /*Binary=*/false, /*RemoveFileOnSignal=*/false,
+TracePath, /*Binary=*/false, /*RemoveFileOnSignal=*/false,
 /*useTemporary=*/false)) {
   llvm::timeTraceProfilerWrite(*profilerOutput);
   profilerOutput.reset();
Index: clang/test/Driver/check-time-trace.cpp
===
--- clang/test/Driver/check-time-trace.cpp
+++ clang/test/Driver/check-time-trace.cpp
@@ -31,6 +31,42 @@
 // CHECK:  "name": "process_name"
 // CHECK:  "name": "thread_name"
 
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: %clangxx -ftime-trace=path/to/trace.json -c -x hip -nogpulib -nogpuinc --offload-arch=gfx803 --offload-arch=gfx900 -### -- %s 2>&1 \
+// RUN:   | FileCheck --check-prefixes=COMMON,FILE %s
+// RUN: %clangxx -ftime-trace=%t -c -x hip -nogpulib -nogpuinc --offload-arch=gfx803 --offload-arch=gfx900 -### -- %s 2>&1 \
+// RUN:   | FileCheck --check-prefixes=COMMON,FOLDER %s
+// RUN: %clangxx -ftime-trace -c -o path/to/output.o -x hip -nogpulib -nogpuinc --offload-arch=gfx803 --offload-arch=gfx900 -### -- %s 2>&1 \
+// RUN:   | FileCheck --check-prefixes=COMMON,OUTPUT %s
+// RUN: %clangxx -ftime-trace -x hip -nogpulib -nogpuinc --offload-arch=gfx803 --offload-arch=gfx900 -### -- %s 2>&1 \
+// RUN:   | FileCheck --check-prefixes=COMMON,NO_OUTPUT %s
+
+// COMMON: "-target-cpu" "gfx803"
+// FILE: "-ftime-trace=path/to/check-time-trace-{{.*}}-gfx803.json"
+// FOLDER: "-ftime-trace=[[BASE:.*]]/check-time-trace-{{.*}}-gfx803.json"
+// OUTPUT: "-ftime-trace=path/to/check-time-trace-{{.*}}-gfx803.json"
+// NO_OUTPUT: "-ftime-trace=check-time-trace-{{.*}}-gfx803.json"
+
+// COMMON: "-target-cpu" "gfx900"
+// FILE: "-ftime-trace=path/to/check-time-trace-{{.*}}-gfx900.json"
+// FOLDER: "-ftime-trace=[[BASE]]/check-time-trace-{{.*}}-gfx900.json"
+// OUTPUT: "-ftime-trace=path/to/check-time-trace-{{.*}}-gfx900.json"
+// NO_OUTPUT: "-ftime-trace=check-time-trace-{{.*}}-gfx900.json"
+
+// COMMON: "-cc1"
+// COMMON-NOT: "-target-cpu" "gfx
+// FILE: "-ftime-trace=path/to/trace.json"
+// FOLDER: "-ftime-trace=[[BASE]]/check-time-trace.json"
+// OUTPUT: "-ftime-trace=path/to/output.json"
+// NO_OUTPUT: "-ftime-trace=check-time-trace-host-{{.*}}.json"
+
+// RUN %clangxx -ftime-trace -save-temps -S -### -- %s 2>&1 | FileCheck --check-prefix=SAVE_TEMPS
+// SAVE_TEMPS: "-E"
+// SAVE_TEMPS: "-ftime-trace=check-time-trace.ii.json"
+// SAVE_TEMPS: "-S"
+// SAVE_TEMPS: "-ftime-trace=check-time-trace.s.json"
+
 template 
 struct Struct {
   T Num;
Index: clang/lib/Driver/ToolChains/Clang.h
===

[PATCH] D133853: [AST] Add msvc-specific C++11 attributes

2022-09-15 Thread Richard Dzenis via Phabricator via cfe-commits
RIscRIpt added a comment.

In D133853#3792518 , @aaron.ballman 
wrote:

> I'm wondering what the goal is for these changes. ... Are you intending to 
> add semantics for these attributes in follow-up patches?

To be honest, I wasn't planning to do any of follow-up patches. I made a patch 
for internal usage at my job, and decided to submit it upstream.
The main reason I (we) need this patch is that we need to be able to parse 
MSVC-specific code (in the current case - detect `constexpr` functions). Since 
Visual Studio 17.3 (MSVC 14.33.31629), Microsoft's STL library added 
`[[msvc::constexpr]]` attribute, which is not documented yet, but makes a 
function to act like a `constexpr` function: see this godbolt sample 
 (i.e. forbids non-constexpr statements 
inside).

To make the patch complete, I decided to browse previous Microsoft's STL 
versions and see which vendor specific (`msvc::`) attributes they added 
previously; in this patch I added all attributes I was able to find.

> We don't typically add attributes to Clang that don't have any effect unless 
> there's a very compelling reason to do so.

Theoretically, I could re-submit (or adjust this) patch, which would add 
support for `[[msvc::constexpr]]` attribute with semantic meaning of 
`constexpr` for functions (for code parsed with `-fms-extensions` flag). 
Regarding other attributes - unfortunately they are either poorly documented, 
or not documented at all, so I can drop commits for these attributes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133853

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


[PATCH] D133959: Add clang flag equivalent to clang-cl /Zl flag

2022-09-15 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

Could the new flag be marked as an Alias in the tablegen, so that we don't need 
to do any code changes for it?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133959

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


[PATCH] D128462: [HLSL] add -I option for dxc mode.

2022-09-15 Thread Chris Bieneman via Phabricator via cfe-commits
beanz added a comment.

I think we had no expectation that DXC-mode would be supported by the tooling 
APIs at this point.

For context, DXC is the HLSL compiler that is based on clang-3.7. The DXC mode 
provides interface compatibility with it. DXC doesn't work with any of the 
clang tooling infrastructure, and clang's HLSL support isn't complete enough 
that people are going to be relying on tooling. I expect that we'll make larger 
investments in the Tooling library as we get further along in the HLSL 
implementation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128462

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


[clang] 9ada3d5 - Fix error in clang /MT equivalent flag patch.

2022-09-15 Thread Amy Huang via cfe-commits

Author: Amy Huang
Date: 2022-09-15T20:24:51Z
New Revision: 9ada3d5a137f5edba7a599ca83e488c76681bbf9

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

LOG: Fix error in clang /MT equivalent flag patch.

This is a followup to reviews.llvm.org/D133457.

Added: 


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

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 9737a0ef33f8..e215dc06379b 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6543,7 +6543,8 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   if (IsMSVCCompat)
 CmdArgs.push_back("-fms-compatibility");
 
-  if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode())
+  if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
+  Args.hasArg(options::OPT_fms_runtime_lib_EQ))
 ProcessVSRuntimeLibrary(Args, CmdArgs);
 
   // Handle -fgcc-version, if present.



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


[PATCH] D133959: Add clang flag equivalent to clang-cl /Zl flag

2022-09-15 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added inline comments.



Comment at: clang/include/clang/Driver/Options.td:
 dll version.}]>;
+def fms_omit_default_lib_name : Joined<["-"], "fms-omit-default-lib-name">,
+  Group, Flags<[NoXarchOption, CoreOption]>,

Initially, I'm not entirely sure about the option name - initially it feels 
weird/clumsy, but after thinking about it, I'm not sure if I can come up with 
something better either. Maybe just `-fms-omit-default-lib`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133959

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


[PATCH] D133968: [clangd] Enable standard library index by default.

2022-09-15 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: kadircet.
Herald added a subscriber: arphaman.
Herald added a project: All.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133968

Files:
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/tool/ClangdMain.cpp


Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -360,6 +360,7 @@
 cat(Misc),
 desc("Abbreviation for -input-style=delimited -pretty -sync "
  "-enable-test-scheme -enable-config=0 -log=verbose -crash-pragmas. "
+ "Also sets config options: Index.StandardLibrary=false. "
  "Intended to simplify lit tests"),
 init(false),
 Hidden,
@@ -697,6 +698,9 @@
 C.Index.Background = *BGPolicy;
   if (AllScopesCompletion.getNumOccurrences())
 C.Completion.AllScopes = AllScopesCompletion;
+
+  if (Test)
+C.Index.StandardLibrary = false;
   return true;
 };
   }
Index: clang-tools-extra/clangd/Config.h
===
--- clang-tools-extra/clangd/Config.h
+++ clang-tools-extra/clangd/Config.h
@@ -85,7 +85,7 @@
 /// Whether this TU should be background-indexed.
 BackgroundPolicy Background = BackgroundPolicy::Build;
 ExternalIndexSpec External;
-bool StandardLibrary = false;
+bool StandardLibrary = true;
   } Index;
 
   enum UnusedIncludesPolicy { Strict, None };


Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -360,6 +360,7 @@
 cat(Misc),
 desc("Abbreviation for -input-style=delimited -pretty -sync "
  "-enable-test-scheme -enable-config=0 -log=verbose -crash-pragmas. "
+ "Also sets config options: Index.StandardLibrary=false. "
  "Intended to simplify lit tests"),
 init(false),
 Hidden,
@@ -697,6 +698,9 @@
 C.Index.Background = *BGPolicy;
   if (AllScopesCompletion.getNumOccurrences())
 C.Completion.AllScopes = AllScopesCompletion;
+
+  if (Test)
+C.Index.StandardLibrary = false;
   return true;
 };
   }
Index: clang-tools-extra/clangd/Config.h
===
--- clang-tools-extra/clangd/Config.h
+++ clang-tools-extra/clangd/Config.h
@@ -85,7 +85,7 @@
 /// Whether this TU should be background-indexed.
 BackgroundPolicy Background = BackgroundPolicy::Build;
 ExternalIndexSpec External;
-bool StandardLibrary = false;
+bool StandardLibrary = true;
   } Index;
 
   enum UnusedIncludesPolicy { Strict, None };
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D133807: Update Unicode to 15.0

2022-09-15 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann added a comment.

> I considered it, and I can add a few if you insist but... I'm not sure adding 
> random tests tell us much except that the specific tested characters are 
> supported.

I wouldn't expect to learn anything from doing so; it would just provide 
regression protection (for example if the code generation scripts are somehow 
broken in the future).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133807

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


[PATCH] D133948: [clang][C++20] Fix clang/clangd assert/crash after compilation errors

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

LGTM! Please add a release note for the fix when you land the changes.




Comment at: clang/test/SemaCXX/remove-nested-immediate-invocation-crash.cpp:4
+
+a, class b {   template < typename c>  
   consteval b(c
+} template  using d = b;

This surely wins an award for "best line noise of the year" or something. :-D


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133948

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


[PATCH] D128462: [HLSL] add -I option for dxc mode.

2022-09-15 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

BTW, I am not sure when the new DXC driver mode was introduced but ATM it isn't 
properly handled by clang-tooling APIs, especially clangd. As the logic there 
wasn't updated accordingly, and it also resulted in regressions for clang-cl 
mode. I've sent out https://reviews.llvm.org/D133962 to remedy the regressions 
at least (which needs to be cherry-picked into next minor release I am afraid).
This is actually probably causing bigger troubles at the moment as a file that 
starts with `/I` will actually be treated as an include search path, rather 
than the input of the compilation, in places where CLDXC flags aren't excluded.

It would be nice to monitor new driver mode introductions to make sure they're 
not making the logic more complicated, as parsing needs to happen in other 
places as well (clangd, lld, lldb and a bunch of other tools parse compile 
flags themselves) and this logic gets duplicated into those places because 
driver doesn't have a public interface that exposes this (mostly because 
`getIncludeExcludeOptionFlagMasks` is complicated, and it's more complicated 
after this new driver mode).
Not supporting new driver modes in those tools, unless explicitly implemented, 
is probably OK, but it's really unfortunate that they'll break silently (due to 
changes similar to this). Because even if we were to test for all of the 
existing flags in those tools, we can't really test for possible flags that 
might be added in the future, which might all of a sudden change a filename to 
a command line option as seen here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128462

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


[clang] 49832b7 - Stop trying to fixup 'overloadable' prototypeless functions.

2022-09-15 Thread Erich Keane via cfe-commits

Author: Erich Keane
Date: 2022-09-15T12:10:54-07:00
New Revision: 49832b7a928d4971417d8dba9aba932d62e447e3

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

LOG: Stop trying to fixup 'overloadable' prototypeless functions.

While investigating something else, I discovered that a prototypeless
function with 'overloadable' was having the attribute left on the
declaration, which caused 'ambiguous' call errors later on. This lead to
some confusion.  This patch removes the 'overloadable' attribute from
the declaration and leaves it as prototypeless, instead of trying to
make it variadic.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaDecl.cpp
clang/test/Sema/overloadable.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 0680aa56db0b7..f897c68b2c87c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -119,6 +119,9 @@ Bug Fixes
   `Issue 57169 `_
 - Clang configuration files are now read through the virtual file system
   rather than the physical one, if these are 
diff erent.
+- Clang will now no longer treat a C 'overloadable' function without a 
prototype as
+  a variadic function with the attribute.  This should make further 
diagnostics more
+  clear.
 
 
 Improvements to Clang's diagnostics

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index e4bd827b38d39..d1e1d8a523925 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -10372,16 +10372,7 @@ Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, 
DeclContext *DC,
 Diag(NewFD->getLocation(),
  diag::err_attribute_overloadable_no_prototype)
   << NewFD;
-
-// Turn this into a variadic function with no parameters.
-const auto *FT = NewFD->getType()->castAs();
-FunctionProtoType::ExtProtoInfo EPI(
-Context.getDefaultCallingConvention(true, false));
-EPI.Variadic = true;
-EPI.ExtInfo = FT->getExtInfo();
-
-QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
-NewFD->setType(R);
+NewFD->dropAttr();
   }
 
   // If there's a #pragma GCC visibility in scope, and this isn't a class

diff  --git a/clang/test/Sema/overloadable.c b/clang/test/Sema/overloadable.c
index ebd9ad1b6d2aa..42d04a52f8c7c 100644
--- a/clang/test/Sema/overloadable.c
+++ b/clang/test/Sema/overloadable.c
@@ -74,6 +74,16 @@ void test() {
   f1();
 }
 
+// Validate that the invalid function doesn't stay overloadable. 
+int __attribute__((overloadable)) invalid(); // expected-error{{'overloadable' 
function 'invalid' must have a prototype}}
+int __attribute__((overloadable)) invalid(int); // 
expected-error{{redeclaration of 'invalid' must not have the 'overloadable' 
attribute}}
+// expected-note@-2{{previous 
unmarked overload of function is here}}
+void use_invalid(void) {
+  invalid(); // expected-error{{too few arguments to function call, expected 
1, have 0}}
+ // expected-note@-4{{'invalid' declared here}}
+  invalid(1);
+}
+
 void before_local_1(int) __attribute__((overloadable));
 void before_local_2(int); // expected-note {{here}}
 void before_local_3(int) __attribute__((overloadable));



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


[PATCH] D133875: [clang] fix generation of .debug_aranges with LTO (resubmit)

2022-09-15 Thread Azat Khuzhin via Phabricator via cfe-commits
azat marked 2 inline comments as done.
azat added inline comments.



Comment at: clang/test/Driver/debug-options-aranges.c:7
+// RUN: %clang -### -g -target x86_64-linux -flto=thin -fuse-ld=lld 
-gdwarf-aranges %s 2>&1 | FileCheck -check-prefix=PLUGIN_GARANGE %s
+// GARANGE: -generate-arange-section
+// PLUGIN_GARANGE: --plugin-opt=-generate-arange-section

probinson wrote:
> I don't see any FileCheck commands that use prefix GARANGE.
Indeed, that was a leftover. Removed.



Comment at: clang/test/Driver/debug-options-aranges.c:15
+// RUN: %clang -g -target x86_64-linux -flto=thin -fuse-ld=lld -gdwarf-aranges 
%s -o - | llvm-dwarfdump --debug-aranges - | FileCheck -check-prefix=ARANGES %s
+// ARANGES: Address Range Header: length = 0x002c, format = DWARF32, 
version = 0x0002, cu_offset = 0x, addr_size = 0x08, seg_size = 0x00
+

dblaikie wrote:
> Generally Clang tests don't test the LLVM behavior - this test should 
> probably just check how -gdwarf-aranges is passed to the linker. Other 
> linker-level tests will test that, given that flag, the linker does the right 
> thing.
Okay, removed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133875

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


[PATCH] D133875: [clang] fix generation of .debug_aranges with LTO (resubmit)

2022-09-15 Thread Azat Khuzhin via Phabricator via cfe-commits
azat updated this revision to Diff 460475.
azat added a comment.

Update the test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133875

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/test/Driver/debug-options-aranges.c


Index: clang/test/Driver/debug-options-aranges.c
===
--- /dev/null
+++ clang/test/Driver/debug-options-aranges.c
@@ -0,0 +1,7 @@
+// REQUIRES: lld
+
+// Check that the linker plugin will get -generate-arange-section
+//
+// RUN: %clang -### -g -target x86_64-linux -flto  -fuse-ld=lld 
-gdwarf-aranges %s 2>&1 | FileCheck %s
+// RUN: %clang -### -g -target x86_64-linux -flto=thin -fuse-ld=lld 
-gdwarf-aranges %s 2>&1 | FileCheck %s
+// CHECK: --plugin-opt=-generate-arange-section
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -508,6 +508,14 @@
 CmdArgs.push_back(Args.MakeArgString(Plugin));
   }
 
+  // Note, this solution is far from perfect, better to encode it into IR
+  // metadata, but this may not be worth it, since it looks like aranges is on
+  // the way out.
+  if (Args.hasArg(options::OPT_gdwarf_aranges)) {
+CmdArgs.push_back(
+Args.MakeArgString("--plugin-opt=-generate-arange-section"));
+  }
+
   // Try to pass driver level flags relevant to LTO code generation down to
   // the plugin.
 


Index: clang/test/Driver/debug-options-aranges.c
===
--- /dev/null
+++ clang/test/Driver/debug-options-aranges.c
@@ -0,0 +1,7 @@
+// REQUIRES: lld
+
+// Check that the linker plugin will get -generate-arange-section
+//
+// RUN: %clang -### -g -target x86_64-linux -flto  -fuse-ld=lld -gdwarf-aranges %s 2>&1 | FileCheck %s
+// RUN: %clang -### -g -target x86_64-linux -flto=thin -fuse-ld=lld -gdwarf-aranges %s 2>&1 | FileCheck %s
+// CHECK: --plugin-opt=-generate-arange-section
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -508,6 +508,14 @@
 CmdArgs.push_back(Args.MakeArgString(Plugin));
   }
 
+  // Note, this solution is far from perfect, better to encode it into IR
+  // metadata, but this may not be worth it, since it looks like aranges is on
+  // the way out.
+  if (Args.hasArg(options::OPT_gdwarf_aranges)) {
+CmdArgs.push_back(
+Args.MakeArgString("--plugin-opt=-generate-arange-section"));
+  }
+
   // Try to pass driver level flags relevant to LTO code generation down to
   // the plugin.
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D133887: [Clang] Support label at end of compound statement

2022-09-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D133887#3790414 , @cor3ntin wrote:

> Thanks for doing that work.
>
> Given that this paper was touted as a C compatibility feature, I think we 
> should implement the C feature at the same time
> https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2508.pdf
>
> If my understanding is correct the change implemented here should just be 
> allowed - without warning in C23
> What do you think @aaron.ballman ?

I don't think the two papers diverge in any way, so I think the implementation 
for one should basically cover the work for the other (aside from test cases, 
etc). It should definitely be without warning in C23 mode and give an extension 
warning in earlier modes.

In D133887#3791243 , @shafik wrote:

> The proposal says:
>
>> A label at the end of a compound statement is treated as if it were followed 
>> by a null statement
>
> Does it make sense to write an AST test to verify this?

I think a test like that would be reasonable, yes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133887

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


[PATCH] D133956: git push Cuda Check for ignored errors after calling a CUDA kernel

2022-09-15 Thread Artem Belevich via Phabricator via cfe-commits
tra added a comment.

> Our linter cannot easily check whether the error was reset

It can not in principle. Many CUDA errors are 'sticky' and can only be cleared 
by resetting the GPU or exiting the application and the former is virtually 
never used beyond toy examples (resetting a GPU would clear a lot of state, 
including memory allocations and restoring it is usually not feasible in 
practice). 
E.g:
https://stackoverflow.com/questions/43659314/how-can-i-reset-the-cuda-error-to-success-with-driver-api-after-a-trap-instructi
https://stackoverflow.com/questions/56329377/reset-cuda-context-after-exception/56330491

The checker has no way to tell whether the returned error is sticky and the 
stickiness can start at any CUDA runtime call, so, generally speaking, all CUDA 
API calls must be checked and any of them may be the one producing sticky 
errors due to preceding calls. At the very minimum, in addition to `<<<...>>>` 
kernel launches, user may also launch kernels via `cudaLaunchKernel()` and, I 
believe, CUDA runtime itself may launch some helper kernels under the hood, so 
I would not be surprised to see other sources of errors.

I think ultimately the checker should be generalized to flag all unchecked CUDA 
runtime calls. The problem is that that is going to be exceedingly noisy in 
practice as a lot of real code does not bother to check for the errors 
consistently. Limiting the checks to kernel launches may be a reasonable 
starting point as it would give us the ability to zero in on the culprit kernel 
by running the app with "CUDA_LAUNCH_BLOCKING".




Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu:53
+  }
+  auto err = cudaGetLastError();
+

Just curious -- is it sufficient to just call `cudaGetLastError();` ? Or does 
the checker require using its result, too? I.e. in practice this particular 
check will not really do anything useful. The tests below look somewhat 
inconsistent. 



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu:75
+  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked 
error after a kernel launch.
+  // Calling an error-checking function after a kernel is not considered safe.
+  errorCheck();

WDYM by "is not considered safe" here? How is that different from calling 
`cudaGetLastError()` and checking its value?



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu:80-82
+  b<<<1, 2>>>();; /* The semicolons are here because the
+detection of the macro is done with a lexer */ ;
+  CUDA_CHECK_KERNEL();

What would happen with a single `;` as would be seen in the normal user code?



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cuda/unsafe-kernel-call-macro-handler.cu:112
+  do {
+auto err2 = cudaGetLastError();
+  } while(0);

Why does this case produce no warning, while a very similar case above does? In 
both cases result of `cudaGetLastError()` is assigned to an unused variable 
within the loop body.

```
  b<<<1, 2>>>();
  // CHECK-MESSAGES: :[[@LINE-1]]:{{[0-9]+}}: warning: Possible unchecked error 
after a kernel launch.
  for(;;)
auto err2 = cudaGetLastError(); // Brackets omitted purposefully, since 
they create an additional AST node

```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133956

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


[PATCH] D133962: [clang(d)] Include/Exclude CLDXC options properly

2022-09-15 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: sammccall.
Herald added a subscriber: arphaman.
Herald added a project: All.
kadircet requested review of this revision.
Herald added subscribers: cfe-commits, ilya-biryukov.
Herald added projects: clang, clang-tools-extra.

This handles the new CLDXC options that was introduced in
https://reviews.llvm.org/D128462 inside clang-tooling to make sure cl driver
mode is not broken.

Fixes https://github.com/clangd/clangd/issues/1292.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133962

Files:
  clang-tools-extra/clangd/CompileCommands.cpp
  clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
  clang/lib/Tooling/InterpolatingCompilationDatabase.cpp


Index: clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
===
--- clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
+++ clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
@@ -165,8 +165,8 @@
   const unsigned OldPos = Pos;
   std::unique_ptr Arg(OptTable.ParseOneArg(
   ArgList, Pos,
-  /* Include */ ClangCLMode ? CoreOption | CLOption : 0,
-  /* Exclude */ ClangCLMode ? 0 : CLOption));
+  /* Include */ ClangCLMode ? CoreOption | CLOption | CLDXCOption : 0,
+  /* Exclude */ ClangCLMode ? 0 : CLOption | CLDXCOption));
 
   if (!Arg)
 continue;
Index: clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
===
--- clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
+++ clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
@@ -415,6 +415,19 @@
   // Make sure we don't crash.
   Mangler.adjust(Args, "foo.cc");
 }
+
+TEST(CommandMangler, PathsAsPositional) {
+  const auto Mangler = CommandMangler::forTests();
+  std::vector Args = {
+  "clang",
+  "--driver-mode=cl",
+  "-I",
+  "foo",
+  };
+  // Make sure we don't crash.
+  Mangler.adjust(Args, "a.cc");
+  EXPECT_THAT(Args, Contains("foo"));
+}
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/CompileCommands.cpp
===
--- clang-tools-extra/clangd/CompileCommands.cpp
+++ clang-tools-extra/clangd/CompileCommands.cpp
@@ -220,10 +220,13 @@
   ArgList = OptTable.ParseArgs(
   llvm::makeArrayRef(OriginalArgs).drop_front(), IgnoredCount, 
IgnoredCount,
   /*FlagsToInclude=*/
-  IsCLMode ? (driver::options::CLOption | driver::options::CoreOption)
+  IsCLMode ? (driver::options::CLOption | driver::options::CoreOption |
+  driver::options::CLDXCOption)
: /*everything*/ 0,
   /*FlagsToExclude=*/driver::options::NoDriverOption |
-  (IsCLMode ? 0 : driver::options::CLOption));
+  (IsCLMode
+   ? 0
+   : (driver::options::CLOption | driver::options::CLDXCOption)));
 
   llvm::SmallVector IndicesToDrop;
   // Having multiple architecture options (e.g. when building fat binaries)


Index: clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
===
--- clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
+++ clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
@@ -165,8 +165,8 @@
   const unsigned OldPos = Pos;
   std::unique_ptr Arg(OptTable.ParseOneArg(
   ArgList, Pos,
-  /* Include */ ClangCLMode ? CoreOption | CLOption : 0,
-  /* Exclude */ ClangCLMode ? 0 : CLOption));
+  /* Include */ ClangCLMode ? CoreOption | CLOption | CLDXCOption : 0,
+  /* Exclude */ ClangCLMode ? 0 : CLOption | CLDXCOption));
 
   if (!Arg)
 continue;
Index: clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
===
--- clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
+++ clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
@@ -415,6 +415,19 @@
   // Make sure we don't crash.
   Mangler.adjust(Args, "foo.cc");
 }
+
+TEST(CommandMangler, PathsAsPositional) {
+  const auto Mangler = CommandMangler::forTests();
+  std::vector Args = {
+  "clang",
+  "--driver-mode=cl",
+  "-I",
+  "foo",
+  };
+  // Make sure we don't crash.
+  Mangler.adjust(Args, "a.cc");
+  EXPECT_THAT(Args, Contains("foo"));
+}
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/CompileCommands.cpp
===
--- clang-tools-extra/clangd/CompileCommands.cpp
+++ clang-tools-extra/clangd/CompileCommands.cpp
@@ -220,10 +220,13 @@
   ArgList = OptTable.ParseArgs(
   llvm::makeArrayRef(OriginalArgs).drop_front(), IgnoredCount, IgnoredCount,
   /*FlagsToInclude=*/
-  IsCLMode ? (driver::options::CLOption | driver::options::CoreOption)
+  IsCLMod

  1   2   3   >