[clang] [Clang][Sema] Properly get captured 'this' pointer in lambdas with an explicit object parameter in constant evaluator (PR #81102)

2024-03-13 Thread via cfe-commits

https://github.com/Sirraide updated 
https://github.com/llvm/llvm-project/pull/81102

>From d489acbd3cfb656d203e1f05b74c238351c5428a Mon Sep 17 00:00:00 2001
From: Sirraide 
Date: Thu, 8 Feb 2024 08:33:03 +0100
Subject: [PATCH 1/6] [Clang] Properly get captured 'this' pointer in lambdas
 with an explicit object parameter in constant evaluator

---
 clang/lib/AST/ExprConstant.cpp| 130 ++
 .../constexpr-explicit-object-lambda.cpp  |  34 +
 2 files changed, 109 insertions(+), 55 deletions(-)
 create mode 100644 clang/test/SemaCXX/constexpr-explicit-object-lambda.cpp

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 089bc2094567f7..8dc6348bc7eedb 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8480,6 +8480,54 @@ class LValueExprEvaluator
 };
 } // end anonymous namespace
 
+/// Get an lvalue to a field of a lambda's closure type.
+static bool GetLambdaCaptureAsLValue(EvalInfo &Info, const Expr *E,
+ LValue &Result, const CXXMethodDecl *MD,
+ const FieldDecl *FD,
+ bool LValueToRValueConversion) {
+  // Static lambda function call operators can't have captures. We already
+  // diagnosed this, so bail out here.
+  if (MD->isStatic()) {
+assert(Info.CurrentCall->This == nullptr &&
+   "This should not be set for a static call operator");
+return false;
+  }
+
+  // Start with 'Result' referring to the complete closure object...
+  if (MD->isExplicitObjectMemberFunction()) {
+// Self may be passed by reference or by value.
+auto *Self = MD->getParamDecl(0);
+if (Self->getType()->isReferenceType()) {
+  APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
+  Result.setFrom(Info.Ctx, *RefValue);
+} else {
+  auto *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
+  auto *Frame =
+  Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
+  .first;
+  auto Version = Info.CurrentCall->Arguments.Version;
+  Result.set({VD, Frame->Index, Version});
+}
+  } else
+Result = *Info.CurrentCall->This;
+
+  // ... then update it to refer to the field of the closure object
+  // that represents the capture.
+  if (!HandleLValueMember(Info, E, Result, FD))
+return false;
+
+  // And if the field is of reference type (or if we captured '*this' by
+  // reference if this is a lambda), update 'Result' to refer to what
+  // the field refers to.
+  if (LValueToRValueConversion) {
+APValue RVal;
+if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
+  return false;
+Result.setFrom(Info.Ctx, RVal);
+  }
+  return true;
+}
+
 /// Evaluate an expression as an lvalue. This can be legitimately called on
 /// expressions which are not glvalues, in three cases:
 ///  * function designators in C, and
@@ -8524,37 +8572,8 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
   const auto *MD = cast(Info.CurrentCall->Callee);
-
-  // Static lambda function call operators can't have captures. We already
-  // diagnosed this, so bail out here.
-  if (MD->isStatic()) {
-assert(Info.CurrentCall->This == nullptr &&
-   "This should not be set for a static call operator");
-return false;
-  }
-
-  // Start with 'Result' referring to the complete closure object...
-  if (MD->isExplicitObjectMemberFunction()) {
-APValue *RefValue =
-Info.getParamSlot(Info.CurrentCall->Arguments, 
MD->getParamDecl(0));
-Result.setFrom(Info.Ctx, *RefValue);
-  } else
-Result = *Info.CurrentCall->This;
-
-  // ... then update it to refer to the field of the closure object
-  // that represents the capture.
-  if (!HandleLValueMember(Info, E, Result, FD))
-return false;
-  // And if the field is of reference type, update 'Result' to refer to 
what
-  // the field refers to.
-  if (FD->getType()->isReferenceType()) {
-APValue RVal;
-if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
-RVal))
-  return false;
-Result.setFrom(Info.Ctx, RVal);
-  }
-  return true;
+  return GetLambdaCaptureAsLValue(Info, E, Result, MD, FD,
+  FD->getType()->isReferenceType());
 }
   }
 
@@ -9032,45 +9051,46 @@ class PointerExprEvaluator
 return Error(E);
   }
   bool VisitCXXThisExpr(const CXXThisExpr *E) {
-// Can't look at 'this' when checking a potential constant expression.
-if (Info.checkingPotentialConstantExpression())
-  return false;
-if (!Info.CurrentCall->This) {
+auto DiagnoseInvalidUseOfThis = [&] {
   if (Info.get

[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-13 Thread Sam Clegg via cfe-commits


@@ -198,9 +198,18 @@
 ///
 /// If there are calls to setjmp()
 ///
-/// 2) and 3): The same as 2) and 3) in Emscripten SjLj.
-/// (setjmpTable/setjmpTableSize initialization + setjmp callsite
-/// transformation)
+/// 2) In the function entry that calls setjmp, initialize
+///functionInvocationId as follows:
+///
+///functionInvocationId = alloca()

sbc100 wrote:

Can you include the size that passed to alloca here?  

 (looks like its getInt32Ty() so maybe put 4 here?)

https://github.com/llvm/llvm-project/pull/84137
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-13 Thread Sam Clegg via cfe-commits

https://github.com/sbc100 edited https://github.com/llvm/llvm-project/pull/84137
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-13 Thread Sam Clegg via cfe-commits

https://github.com/sbc100 commented:

Let me know if you want some help testing alsongside the emscripten side.

Alternatively myself or @aheejin could perform the emscripten tests.

https://github.com/llvm/llvm-project/pull/84137
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-13 Thread Sam Clegg via cfe-commits


@@ -198,9 +198,18 @@
 ///
 /// If there are calls to setjmp()
 ///
-/// 2) and 3): The same as 2) and 3) in Emscripten SjLj.
-/// (setjmpTable/setjmpTableSize initialization + setjmp callsite
-/// transformation)
+/// 2) In the function entry that calls setjmp, initialize
+///functionInvocationId as follows:
+///
+///functionInvocationId = alloca()

sbc100 wrote:

Is the same functionInvocationId used even if there are several calls to setjmp 
inside the same function?  

https://github.com/llvm/llvm-project/pull/84137
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] nolock/noalloc attributes (PR #84983)

2024-03-13 Thread via cfe-commits


@@ -4912,3 +4922,279 @@ void AutoType::Profile(llvm::FoldingSetNodeID &ID, 
const ASTContext &Context) {
   Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
   getTypeConstraintConcept(), getTypeConstraintArguments());
 }
+
+FunctionEffect::~FunctionEffect() = default;
+
+bool FunctionEffect::diagnoseConversion(bool Adding, QualType OldType,
+FunctionEffectSet OldFX,
+QualType NewType,
+FunctionEffectSet NewFX) const {
+  return false;
+}
+
+bool FunctionEffect::diagnoseRedeclaration(bool Adding,
+   const FunctionDecl &OldFunction,
+   FunctionEffectSet OldFX,
+   const FunctionDecl &NewFunction,
+   FunctionEffectSet NewFX) const {
+  return false;
+}
+
+bool FunctionEffect::diagnoseMethodOverride(bool Adding,
+const CXXMethodDecl &OldMethod,
+FunctionEffectSet OldFX,
+const CXXMethodDecl &NewMethod,
+FunctionEffectSet NewFX) const {
+  return false;
+}
+
+bool FunctionEffect::canInferOnDecl(const Decl *Caller,
+FunctionEffectSet CallerFX) const {
+  return false;
+}
+
+bool FunctionEffect::diagnoseFunctionCall(bool Direct, const Decl *Caller,
+  FunctionEffectSet CallerFX,
+  CalleeDeclOrType Callee,
+  FunctionEffectSet CalleeFX) const {
+  return false;
+}
+
+const NoLockNoAllocEffect &NoLockNoAllocEffect::nolock_instance() {
+  static NoLockNoAllocEffect global(kNoLockTrue, "nolock");
+  return global;
+}

Sirraide wrote:

With the `[[]]` syntax, attributes that appertain to a function declaration 
come before the return type, and attributes that appertain to the function type 
come after the parameter list, yeah.

Looking at this again, `AttributedType` makes sense for this, I’d say. 
`DeclOrTypeAttr` is probably fine for this, because I don’t think you can put a 
`TypeAttr` *before* a function if you want to be able to do that, but if you 
don’t care about that being possible, then a `TypeAttr` is probably simpler.

So, to get back to what this comment was originally about, if I understand the 
situation correctly, you can attach `nolock`/`noalloc` (optionally w/ an 
expression argument) to function types. This is done using `AttributedType`s, 
which makes sense. The presence/absence of these attributes may affect how 
effects are inferred.

At the same time, we would also like to track effects on the 
`FunctionProtoType`, so what I’m thinking is, it may it be possible to use only 
the attributes for inference, and track effects as a bitmask on the 
`FunctionProtoType` (see also the comment I made about this further down wrt 
one of the questions in your initial pr comment). With all of that in mind, 
it’s not quite clear to me what purpose the `nolock_instance()` serves in all 
of this?

https://github.com/llvm/llvm-project/pull/84983
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][nullability] allow _Nonnull etc on nullable class types (PR #82705)

2024-03-13 Thread Aaron Ballman via cfe-commits


@@ -2156,9 +2156,10 @@ def TypeNonNull : TypeAttr {
   let Documentation = [TypeNonNullDocs];
 }
 
-def TypeNullable : TypeAttr {
+def TypeNullable : DeclOrTypeAttr {
   let Spellings = [CustomKeyword<"_Nullable">];
   let Documentation = [TypeNullableDocs];
+//  let Subjects = SubjectList<[CXXRecord], ErrorDiag>;

AaronBallman wrote:

Ah, I forgot we hadn't yet improved that bit. I thought `DeclOrType` would 
still work with the subject list for declaration attributes but the logic would 
still have to be added manually for types.

Let's leave this in as documentation, hopefully the checking code can be 
improved in the future.

https://github.com/llvm/llvm-project/pull/82705
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] AArch64: add __builtin_arm_trap (PR #85054)

2024-03-13 Thread Jon Roelofs via cfe-commits

https://github.com/jroelofs approved this pull request.


https://github.com/llvm/llvm-project/pull/85054
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] nolock/noalloc attributes (PR #84983)

2024-03-13 Thread Doug Wyatt via cfe-commits


@@ -4912,3 +4922,279 @@ void AutoType::Profile(llvm::FoldingSetNodeID &ID, 
const ASTContext &Context) {
   Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
   getTypeConstraintConcept(), getTypeConstraintArguments());
 }
+
+FunctionEffect::~FunctionEffect() = default;
+
+bool FunctionEffect::diagnoseConversion(bool Adding, QualType OldType,
+FunctionEffectSet OldFX,
+QualType NewType,
+FunctionEffectSet NewFX) const {
+  return false;
+}
+
+bool FunctionEffect::diagnoseRedeclaration(bool Adding,
+   const FunctionDecl &OldFunction,
+   FunctionEffectSet OldFX,
+   const FunctionDecl &NewFunction,
+   FunctionEffectSet NewFX) const {
+  return false;
+}
+
+bool FunctionEffect::diagnoseMethodOverride(bool Adding,
+const CXXMethodDecl &OldMethod,
+FunctionEffectSet OldFX,
+const CXXMethodDecl &NewMethod,
+FunctionEffectSet NewFX) const {
+  return false;
+}
+
+bool FunctionEffect::canInferOnDecl(const Decl *Caller,
+FunctionEffectSet CallerFX) const {
+  return false;
+}
+
+bool FunctionEffect::diagnoseFunctionCall(bool Direct, const Decl *Caller,
+  FunctionEffectSet CallerFX,
+  CalleeDeclOrType Callee,
+  FunctionEffectSet CalleeFX) const {
+  return false;
+}
+
+const NoLockNoAllocEffect &NoLockNoAllocEffect::nolock_instance() {
+  static NoLockNoAllocEffect global(kNoLockTrue, "nolock");
+  return global;
+}
+
+const NoLockNoAllocEffect &NoLockNoAllocEffect::noalloc_instance() {
+  static NoLockNoAllocEffect global(kNoAllocTrue, "noalloc");
+  return global;
+}
+
+// TODO: Separate flags for noalloc
+NoLockNoAllocEffect::NoLockNoAllocEffect(EffectType Ty, const char *Name)
+: FunctionEffect(Ty,
+ kRequiresVerification | kVerifyCalls |
+ kInferrableOnCallees | kExcludeThrow | kExcludeCatch |
+ kExcludeObjCMessageSend | kExcludeStaticLocalVars |
+ kExcludeThreadLocalVars,
+ Name) {}
+
+NoLockNoAllocEffect::~NoLockNoAllocEffect() = default;
+
+std::string NoLockNoAllocEffect::attribute() const {
+  return std::string{"__attribute__((clang_"} + name().str() + "))";
+}
+
+bool NoLockNoAllocEffect::diagnoseConversion(bool Adding, QualType OldType,
+ FunctionEffectSet OldFX,
+ QualType NewType,
+ FunctionEffectSet NewFX) const {
+  // noalloc can't be added (spoofed) during a conversion, unless we have 
nolock
+  if (Adding) {
+if (!isNoLock()) {
+  for (const auto *Effect : OldFX) {
+if (Effect->type() == kNoLockTrue)
+  return false;
+  }
+}
+// nolock can't be added (spoofed) during a conversion.
+return true;
+  }
+  return false;
+}
+
+bool NoLockNoAllocEffect::diagnoseRedeclaration(bool Adding,
+const FunctionDecl 
&OldFunction,
+FunctionEffectSet OldFX,
+const FunctionDecl 
&NewFunction,
+FunctionEffectSet NewFX) const 
{
+  // nolock/noalloc can't be removed in a redeclaration
+  // adding -> false, removing -> true (diagnose)
+  return !Adding;
+}
+
+bool NoLockNoAllocEffect::diagnoseMethodOverride(
+bool Adding, const CXXMethodDecl &OldMethod, FunctionEffectSet OldFX,
+const CXXMethodDecl &NewMethod, FunctionEffectSet NewFX) const {
+  // nolock/noalloc can't be removed from an override
+  return !Adding;
+}
+
+bool NoLockNoAllocEffect::canInferOnDecl(const Decl *Caller,
+ FunctionEffectSet CallerFX) const {
+  // Does the Decl have nolock(false) / noalloc(false) ?
+  QualType QT;
+  if (isa(Caller)) {
+const auto *TSI = cast(Caller)->getSignatureAsWritten();
+QT = TSI->getType();
+  } else if (isa(Caller)) {
+QT = cast(Caller)->getType();
+  } else {
+return false;
+  }
+  if (QT->hasAttr(isNoLock() ? attr::Kind::NoLock : attr::Kind::NoAlloc)) {
+return false;
+  }
+
+  return true;
+}
+
+// TODO: Notice that we don't care about some of the parameters. Is the
+// interface overly general?
+bool NoLockNoAllocEffect::diagnoseFunctionCall(
+bool Direct, const Decl *Caller, FunctionEffectSet CallerFX,
+CalleeD

[clang] nolock/noalloc attributes (PR #84983)

2024-03-13 Thread via cfe-commits


@@ -0,0 +1,84 @@
+// RUN: %clang_cc1 -fsyntax-only -fblocks -verify %s

Sirraide wrote:

It’s usually not required to separate code that errors and code that is 
supposed to compile without errors, but if it is required for something like 
this, then sure, go ahead.

>  -parsing, -sema, -constraints.

Well, *parsing*-related tests should probably go in `test/Parser` (from what 
I’ve seen so far, you also haven’t made any changes in the parser, though).

https://github.com/llvm/llvm-project/pull/84983
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [Clang][BPF] Allow sign/zero extension for call parameters with int/uint types (PR #84874)

2024-03-13 Thread via cfe-commits

eddyz87 wrote:

@yonghong-song , if I understand @efriedma-quic correctly (thank you for 
explanations), the following fragment is not RISC-V ABI conformant:

```
$ cat u.c
void foo(unsigned);
void bar(unsigned a, unsigned b) {
  foo(a + b);
}

   1:   67 02 00 00 20 00 00 00 r2 <<= 0x20
   2:   77 02 00 00 20 00 00 00 r2 >>= 0x20
   3:   bf 21 00 00 00 00 00 00 r1 = r2
   4:   85 10 00 00 ff ff ff ff call -0x1
```

The `r1` would be zero extended, while to be ABI conformant it has to be sign 
extended, as for RV64 the 31-st bit should be the same as upper 32 bits. The 
fact that decision to zero or sign extend the argument depends on the 
architecture means that this extension has to be done at JIT time (meaning that 
BTF is mandatory) or be a part of kfunc.

https://github.com/llvm/llvm-project/pull/84874
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][nullability] allow _Nonnull etc on nullable class types (PR #82705)

2024-03-13 Thread Aaron Ballman via cfe-commits


@@ -1494,6 +1494,15 @@ void 
Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
   }
 }
 
+void Parser::ParseNullabilityClassAttributes(ParsedAttributes &attrs) {
+  while (Tok.is(tok::kw__Nullable)) {

AaronBallman wrote:

With other attributes, accepting multiples in sequence is required per the 
grammar: https://eel.is/c++draft/dcl.attr#nt:attribute-specifier-seq but the 
same is not true for keywords. However, I think it's fine to accept as-is, 
especially when I see: https://godbolt.org/z/YfqWvMf94

https://github.com/llvm/llvm-project/pull/82705
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][nullability] allow _Nonnull etc on nullable class types (PR #82705)

2024-03-13 Thread Aaron Ballman via cfe-commits


@@ -215,6 +215,18 @@ void Sema::inferGslOwnerPointerAttribute(CXXRecordDecl 
*Record) {
   inferGslPointerAttribute(Record, Record);
 }
 
+void Sema::inferNullableClassAttribute(CXXRecordDecl *CRD) {
+  static llvm::StringSet<> Nullable{
+  "auto_ptr", "shared_ptr", "unique_ptr", "exception_ptr",

AaronBallman wrote:

Okay, SGTM! If we want to change our mind here, we can always do so later, too.

https://github.com/llvm/llvm-project/pull/82705
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] nolock/noalloc attributes (PR #84983)

2024-03-13 Thread via cfe-commits


@@ -4912,3 +4922,279 @@ void AutoType::Profile(llvm::FoldingSetNodeID &ID, 
const ASTContext &Context) {
   Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
   getTypeConstraintConcept(), getTypeConstraintArguments());
 }
+
+FunctionEffect::~FunctionEffect() = default;
+
+bool FunctionEffect::diagnoseConversion(bool Adding, QualType OldType,
+FunctionEffectSet OldFX,
+QualType NewType,
+FunctionEffectSet NewFX) const {
+  return false;
+}
+
+bool FunctionEffect::diagnoseRedeclaration(bool Adding,
+   const FunctionDecl &OldFunction,
+   FunctionEffectSet OldFX,
+   const FunctionDecl &NewFunction,
+   FunctionEffectSet NewFX) const {
+  return false;
+}
+
+bool FunctionEffect::diagnoseMethodOverride(bool Adding,
+const CXXMethodDecl &OldMethod,
+FunctionEffectSet OldFX,
+const CXXMethodDecl &NewMethod,
+FunctionEffectSet NewFX) const {
+  return false;
+}
+
+bool FunctionEffect::canInferOnDecl(const Decl *Caller,
+FunctionEffectSet CallerFX) const {
+  return false;
+}
+
+bool FunctionEffect::diagnoseFunctionCall(bool Direct, const Decl *Caller,
+  FunctionEffectSet CallerFX,
+  CalleeDeclOrType Callee,
+  FunctionEffectSet CalleeFX) const {
+  return false;
+}
+
+const NoLockNoAllocEffect &NoLockNoAllocEffect::nolock_instance() {
+  static NoLockNoAllocEffect global(kNoLockTrue, "nolock");
+  return global;
+}
+
+const NoLockNoAllocEffect &NoLockNoAllocEffect::noalloc_instance() {
+  static NoLockNoAllocEffect global(kNoAllocTrue, "noalloc");
+  return global;
+}
+
+// TODO: Separate flags for noalloc
+NoLockNoAllocEffect::NoLockNoAllocEffect(EffectType Ty, const char *Name)
+: FunctionEffect(Ty,
+ kRequiresVerification | kVerifyCalls |
+ kInferrableOnCallees | kExcludeThrow | kExcludeCatch |
+ kExcludeObjCMessageSend | kExcludeStaticLocalVars |
+ kExcludeThreadLocalVars,
+ Name) {}
+
+NoLockNoAllocEffect::~NoLockNoAllocEffect() = default;
+
+std::string NoLockNoAllocEffect::attribute() const {
+  return std::string{"__attribute__((clang_"} + name().str() + "))";
+}
+
+bool NoLockNoAllocEffect::diagnoseConversion(bool Adding, QualType OldType,
+ FunctionEffectSet OldFX,
+ QualType NewType,
+ FunctionEffectSet NewFX) const {
+  // noalloc can't be added (spoofed) during a conversion, unless we have 
nolock
+  if (Adding) {
+if (!isNoLock()) {
+  for (const auto *Effect : OldFX) {
+if (Effect->type() == kNoLockTrue)
+  return false;
+  }
+}
+// nolock can't be added (spoofed) during a conversion.
+return true;
+  }
+  return false;
+}
+
+bool NoLockNoAllocEffect::diagnoseRedeclaration(bool Adding,
+const FunctionDecl 
&OldFunction,
+FunctionEffectSet OldFX,
+const FunctionDecl 
&NewFunction,
+FunctionEffectSet NewFX) const 
{
+  // nolock/noalloc can't be removed in a redeclaration
+  // adding -> false, removing -> true (diagnose)
+  return !Adding;
+}
+
+bool NoLockNoAllocEffect::diagnoseMethodOverride(
+bool Adding, const CXXMethodDecl &OldMethod, FunctionEffectSet OldFX,
+const CXXMethodDecl &NewMethod, FunctionEffectSet NewFX) const {
+  // nolock/noalloc can't be removed from an override
+  return !Adding;
+}
+
+bool NoLockNoAllocEffect::canInferOnDecl(const Decl *Caller,
+ FunctionEffectSet CallerFX) const {
+  // Does the Decl have nolock(false) / noalloc(false) ?
+  QualType QT;
+  if (isa(Caller)) {
+const auto *TSI = cast(Caller)->getSignatureAsWritten();
+QT = TSI->getType();
+  } else if (isa(Caller)) {
+QT = cast(Caller)->getType();
+  } else {
+return false;
+  }
+  if (QT->hasAttr(isNoLock() ? attr::Kind::NoLock : attr::Kind::NoAlloc)) {
+return false;
+  }
+
+  return true;
+}
+
+// TODO: Notice that we don't care about some of the parameters. Is the
+// interface overly general?
+bool NoLockNoAllocEffect::diagnoseFunctionCall(
+bool Direct, const Decl *Caller, FunctionEffectSet CallerFX,
+CalleeD

[clang] [clang][nullability] allow _Nonnull etc on nullable class types (PR #82705)

2024-03-13 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman edited 
https://github.com/llvm/llvm-project/pull/82705
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][nullability] allow _Nonnull etc on nullable class types (PR #82705)

2024-03-13 Thread Aaron Ballman via cfe-commits


@@ -4096,6 +4096,18 @@ non-underscored keywords. For example:
   @property (assign, nullable) NSView *superview;
   @property (readonly, nonnull) NSArray *subviews;
 @end
+
+As well as built-in pointer types, the nullability attributes can be attached
+to C++ classes marked with the ``_Nullable`` attribute.
+
+The following C++ standard library types are considered nullable:
+``unique_ptr``, ``shared_ptr``, ``auto_ptr``, ``exception_ptr``, ``function``,
+``move_only_function`` and ``coroutine_handle``.
+
+Types should be marked nullable only where the type itself leaves nullability
+ambiguous. For example, ``std::optional`` is not marked ``_Nullable``, because

AaronBallman wrote:

Should we mention `std::weak_ptr` here like we do for `std::optional`?

https://github.com/llvm/llvm-project/pull/82705
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][nullability] allow _Nonnull etc on nullable class types (PR #82705)

2024-03-13 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman approved this pull request.

LGTM though there may be a minor change to the docs that could make sense (feel 
free to change when landing if you agree).

https://github.com/llvm/llvm-project/pull/82705
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Headers][X86] Add rounding and exception notes to conversions (PR #83447)

2024-03-13 Thread Paul T Robinson via cfe-commits

https://github.com/pogo59 updated 
https://github.com/llvm/llvm-project/pull/83447

>From 64cdd358d0bf359383a5dd3d1da236a219644c9e Mon Sep 17 00:00:00 2001
From: Paul Robinson 
Date: Thu, 29 Feb 2024 08:59:26 -0800
Subject: [PATCH 1/3] [Headers][X86] Add rounding and exception notes to
 conversions

Consistently describe rounding/truncating on convert intrinsics.
Add notes where an out-of-range result can raise an exception.
---
 clang/lib/Headers/avxintrin.h |  36 +++---
 clang/lib/Headers/emmintrin.h |  91 ++---
 clang/lib/Headers/xmmintrin.h | 125 --
 3 files changed, 182 insertions(+), 70 deletions(-)

diff --git a/clang/lib/Headers/avxintrin.h b/clang/lib/Headers/avxintrin.h
index f116d8bc3a94c7..51c7d76e75ca1a 100644
--- a/clang/lib/Headers/avxintrin.h
+++ b/clang/lib/Headers/avxintrin.h
@@ -2180,7 +2180,8 @@ _mm256_cvtepi32_pd(__m128i __a)
   return (__m256d)__builtin_convertvector((__v4si)__a, __v4df);
 }
 
-/// Converts a vector of [8 x i32] into a vector of [8 x float].
+/// Converts a vector of [8 x i32] into a vector of [8 x float]. Rounds inexact
+///results according to the rounding control bits in the MXCSR register.
 ///
 /// \headerfile 
 ///
@@ -2196,7 +2197,8 @@ _mm256_cvtepi32_ps(__m256i __a)
 }
 
 /// Converts a 256-bit vector of [4 x double] into a 128-bit vector of
-///[4 x float].
+///[4 x float]. Rounds inexact results according to the rounding control
+///bits in the MXCSR register.
 ///
 /// \headerfile 
 ///
@@ -2211,7 +2213,12 @@ _mm256_cvtpd_ps(__m256d __a)
   return (__m128)__builtin_ia32_cvtpd2ps256((__v4df) __a);
 }
 
-/// Converts a vector of [8 x float] into a vector of [8 x i32].
+/// Converts a vector of [8 x float] into a vector of [8 x i32]. Rounds inexact
+///results according to the rounding control bits in the MXCSR register.
+///
+///If a converted value is larger than the maximum possible result,
+///raises a floating-point invalid exception. If the exception is
+///masked, returns the most negative integer.
 ///
 /// \headerfile 
 ///
@@ -2243,8 +2250,11 @@ _mm256_cvtps_pd(__m128 __a)
 }
 
 /// Converts a 256-bit vector of [4 x double] into a 128-bit vector of [4
-///x i32], truncating the result by rounding towards zero when it is
-///inexact.
+///x i32], truncating inexact results.
+///
+///If a converted value is larger than the maximum possible result,
+///raises a floating-point invalid exception. If the exception is
+///masked, returns the most negative integer.
 ///
 /// \headerfile 
 ///
@@ -2259,9 +2269,13 @@ _mm256_cvttpd_epi32(__m256d __a)
   return (__m128i)__builtin_ia32_cvttpd2dq256((__v4df) __a);
 }
 
-/// Converts a 256-bit vector of [4 x double] into a 128-bit vector of [4
-///x i32]. When a conversion is inexact, the value returned is rounded
-///according to the rounding control bits in the MXCSR register.
+/// Converts a 256-bit vector of [4 x double] into a 128-bit vector of
+///[4 x i32]. Rounds inexact results according to the rounding control bits
+///in the MXCSR register.
+///
+///If a converted value is larger than the maximum possible result,
+///raises a floating-point invalid exception. If the exception is
+///masked, returns the most negative integer.
 ///
 /// \headerfile 
 ///
@@ -2277,7 +2291,11 @@ _mm256_cvtpd_epi32(__m256d __a)
 }
 
 /// Converts a vector of [8 x float] into a vector of [8 x i32],
-///truncating the result by rounding towards zero when it is inexact.
+///truncating inexact results.
+///
+///If a converted value is larger than the maximum possible result,
+///raises a floating-point invalid exception. If the exception is
+///masked, returns the most negative integer.
 ///
 /// \headerfile 
 ///
diff --git a/clang/lib/Headers/emmintrin.h b/clang/lib/Headers/emmintrin.h
index 96e3ebdecbdf83..9ae7fe2c809ac6 100644
--- a/clang/lib/Headers/emmintrin.h
+++ b/clang/lib/Headers/emmintrin.h
@@ -1245,7 +1245,8 @@ static __inline__ int __DEFAULT_FN_ATTRS 
_mm_ucomineq_sd(__m128d __a,
 /// Converts the two double-precision floating-point elements of a
 ///128-bit vector of [2 x double] into two single-precision floating-point
 ///values, returned in the lower 64 bits of a 128-bit vector of [4 x 
float].
-///The upper 64 bits of the result vector are set to zero.
+///Rounds inexact results according to the rounding control bits in the
+///MXCSR register. The upper 64 bits of the result vector are set to zero.
 ///
 /// \headerfile 
 ///
@@ -1300,9 +1301,13 @@ static __inline__ __m128d __DEFAULT_FN_ATTRS 
_mm_cvtepi32_pd(__m128i __a) {
 }
 
 /// Converts the two double-precision floating-point elements of a
-///128-bit vector of [2 x double] into two signed 32-bit integer values,
-///returned in the lower 64 bits of a 128-bit vector of [4 x i32]. The 
upper
-///64 bits of the result vector are set to zero.
+///128-bit vector of [2 

[clang] [Headers][X86] Add rounding and exception notes to conversions (PR #83447)

2024-03-13 Thread Paul T Robinson via cfe-commits

pogo59 wrote:

Reworded the parts about truncating results.

https://github.com/llvm/llvm-project/pull/83447
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] AArch64: add __builtin_arm_trap (PR #85054)

2024-03-13 Thread Amara Emerson via cfe-commits

https://github.com/aemerson approved this pull request.

LGTM.

https://github.com/llvm/llvm-project/pull/85054
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [InstallAPI] Add installapi specific options & diagnostics (PR #85100)

2024-03-13 Thread Cyndy Ishida via cfe-commits

https://github.com/cyndyishida created 
https://github.com/llvm/llvm-project/pull/85100

* A lot of `tapi installapi` options are already shared with clang, but not 
all. This patch handles installapi specific options by filtering for them in 
initial argv input, then passing the rest to the clang driver.
* Installapi not only generates a text file but also reports to library 
developers when there are inconsistences between an interface and it's 
implementation. To allow this, add support for reporting installapi 
diagnostics. This will be leveraged in the verifier service.

>From a71d8d338c9a5cc2f21957b7907f676f2f11d4d6 Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Wed, 6 Mar 2024 09:16:20 -0800
Subject: [PATCH] [InstallAPI] Add installapi specific options & diagnostics

* A lot of `tapi installapi` options are already shared with clang, but not all.
  This patch handles installapi specific options by filtering for them in 
initial argv input, then passing the rest to the clang driver.
* Installapi not only generates a text file but also reports to library
  developers when there are inconsistences between an interface and it's
  implementation. To allow this, add support for reporting installapi
  diagnostics. This will be leveraged in the verifier service.
---
 clang/include/clang/Basic/AllDiagnostics.h|   1 +
 clang/include/clang/Basic/CMakeLists.txt  |   1 +
 clang/include/clang/Basic/Diagnostic.td   |   1 +
 clang/include/clang/Basic/DiagnosticIDs.h |   4 +-
 .../clang/Basic/DiagnosticInstallAPI.h|  26 +++
 .../clang/Basic/DiagnosticInstallAPIKinds.td  |  20 ++
 .../include/clang/InstallAPI/DylibVerifier.h  |  27 +++
 .../clang/InstallAPI/InstallAPIDiagnostic.h   |  14 ++
 clang/lib/Basic/DiagnosticIDs.cpp |  10 +-
 .../InstallAPI/driver-invalid-options.test|   7 +-
 clang/test/InstallAPI/functions.test  |   2 +-
 clang/tools/clang-installapi/CMakeLists.txt   |   8 +
 .../clang-installapi/ClangInstallAPI.cpp  |  23 +--
 .../tools/clang-installapi/InstallAPIOpts.td  |  31 +++
 clang/tools/clang-installapi/Options.cpp  | 192 +++---
 clang/tools/clang-installapi/Options.h|  25 ++-
 16 files changed, 342 insertions(+), 50 deletions(-)
 create mode 100644 clang/include/clang/Basic/DiagnosticInstallAPI.h
 create mode 100644 clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
 create mode 100644 clang/include/clang/InstallAPI/DylibVerifier.h
 create mode 100644 clang/include/clang/InstallAPI/InstallAPIDiagnostic.h
 create mode 100644 clang/tools/clang-installapi/InstallAPIOpts.td

diff --git a/clang/include/clang/Basic/AllDiagnostics.h 
b/clang/include/clang/Basic/AllDiagnostics.h
index cc6aa631534a5d..e64634cc138f7f 100644
--- a/clang/include/clang/Basic/AllDiagnostics.h
+++ b/clang/include/clang/Basic/AllDiagnostics.h
@@ -20,6 +20,7 @@
 #include "clang/Basic/DiagnosticCrossTU.h"
 #include "clang/Basic/DiagnosticDriver.h"
 #include "clang/Basic/DiagnosticFrontend.h"
+#include "clang/Basic/DiagnosticInstallAPI.h"
 #include "clang/Basic/DiagnosticLex.h"
 #include "clang/Basic/DiagnosticParse.h"
 #include "clang/Basic/DiagnosticSema.h"
diff --git a/clang/include/clang/Basic/CMakeLists.txt 
b/clang/include/clang/Basic/CMakeLists.txt
index 7785fb430c069b..7d53c751c13ac4 100644
--- a/clang/include/clang/Basic/CMakeLists.txt
+++ b/clang/include/clang/Basic/CMakeLists.txt
@@ -12,6 +12,7 @@ clang_diag_gen(Common)
 clang_diag_gen(CrossTU)
 clang_diag_gen(Driver)
 clang_diag_gen(Frontend)
+clang_diag_gen(InstallAPI)
 clang_diag_gen(Lex)
 clang_diag_gen(Parse)
 clang_diag_gen(Refactoring)
diff --git a/clang/include/clang/Basic/Diagnostic.td 
b/clang/include/clang/Basic/Diagnostic.td
index 8d66e265fbaef0..0b8b3af939ba0e 100644
--- a/clang/include/clang/Basic/Diagnostic.td
+++ b/clang/include/clang/Basic/Diagnostic.td
@@ -162,6 +162,7 @@ include "DiagnosticCommonKinds.td"
 include "DiagnosticCrossTUKinds.td"
 include "DiagnosticDriverKinds.td"
 include "DiagnosticFrontendKinds.td"
+include "DiagnosticInstallAPIKinds.td"
 include "DiagnosticLexKinds.td"
 include "DiagnosticParseKinds.td"
 include "DiagnosticRefactoringKinds.td"
diff --git a/clang/include/clang/Basic/DiagnosticIDs.h 
b/clang/include/clang/Basic/DiagnosticIDs.h
index 0cdda42793f6f0..95b502b1e97ab1 100644
--- a/clang/include/clang/Basic/DiagnosticIDs.h
+++ b/clang/include/clang/Basic/DiagnosticIDs.h
@@ -42,6 +42,7 @@ namespace clang {
   DIAG_SIZE_SEMA  = 4500,
   DIAG_SIZE_ANALYSIS  =  100,
   DIAG_SIZE_REFACTORING   = 1000,
+  DIAG_SIZE_INSTALLAPI=  100,
 };
 // Start position for diagnostics.
 enum {
@@ -57,7 +58,8 @@ namespace clang {
   DIAG_START_SEMA  = DIAG_START_CROSSTU   + 
static_cast(DIAG_SIZE_CROSSTU),
   DIAG_START_ANALYSIS  = DIAG_START_SEMA  + 
static_cast(DIAG_SIZE_SEMA),
   DIAG_START_REFACTORING   = DIAG_START_ANALYSIS  + 
static_cast(DIAG_SIZE_ANALYSIS),
-  DIAG_UPPE

[clang] [InstallAPI] Add installapi specific options & diagnostics (PR #85100)

2024-03-13 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Cyndy Ishida (cyndyishida)


Changes

* A lot of `tapi installapi` options are already shared with clang, but not 
all. This patch handles installapi specific options by filtering for them in 
initial argv input, then passing the rest to the clang driver.
* Installapi not only generates a text file but also reports to library 
developers when there are inconsistences between an interface and it's 
implementation. To allow this, add support for reporting installapi 
diagnostics. This will be leveraged in the verifier service.

---

Patch is 28.47 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/85100.diff


16 Files Affected:

- (modified) clang/include/clang/Basic/AllDiagnostics.h (+1) 
- (modified) clang/include/clang/Basic/CMakeLists.txt (+1) 
- (modified) clang/include/clang/Basic/Diagnostic.td (+1) 
- (modified) clang/include/clang/Basic/DiagnosticIDs.h (+3-1) 
- (added) clang/include/clang/Basic/DiagnosticInstallAPI.h (+26) 
- (added) clang/include/clang/Basic/DiagnosticInstallAPIKinds.td (+20) 
- (added) clang/include/clang/InstallAPI/DylibVerifier.h (+27) 
- (added) clang/include/clang/InstallAPI/InstallAPIDiagnostic.h (+14) 
- (modified) clang/lib/Basic/DiagnosticIDs.cpp (+8-2) 
- (modified) clang/test/InstallAPI/driver-invalid-options.test (+6-1) 
- (modified) clang/test/InstallAPI/functions.test (+1-1) 
- (modified) clang/tools/clang-installapi/CMakeLists.txt (+8) 
- (modified) clang/tools/clang-installapi/ClangInstallAPI.cpp (+5-18) 
- (added) clang/tools/clang-installapi/InstallAPIOpts.td (+31) 
- (modified) clang/tools/clang-installapi/Options.cpp (+166-26) 
- (modified) clang/tools/clang-installapi/Options.h (+24-1) 


``diff
diff --git a/clang/include/clang/Basic/AllDiagnostics.h 
b/clang/include/clang/Basic/AllDiagnostics.h
index cc6aa631534a5d..e64634cc138f7f 100644
--- a/clang/include/clang/Basic/AllDiagnostics.h
+++ b/clang/include/clang/Basic/AllDiagnostics.h
@@ -20,6 +20,7 @@
 #include "clang/Basic/DiagnosticCrossTU.h"
 #include "clang/Basic/DiagnosticDriver.h"
 #include "clang/Basic/DiagnosticFrontend.h"
+#include "clang/Basic/DiagnosticInstallAPI.h"
 #include "clang/Basic/DiagnosticLex.h"
 #include "clang/Basic/DiagnosticParse.h"
 #include "clang/Basic/DiagnosticSema.h"
diff --git a/clang/include/clang/Basic/CMakeLists.txt 
b/clang/include/clang/Basic/CMakeLists.txt
index 7785fb430c069b..7d53c751c13ac4 100644
--- a/clang/include/clang/Basic/CMakeLists.txt
+++ b/clang/include/clang/Basic/CMakeLists.txt
@@ -12,6 +12,7 @@ clang_diag_gen(Common)
 clang_diag_gen(CrossTU)
 clang_diag_gen(Driver)
 clang_diag_gen(Frontend)
+clang_diag_gen(InstallAPI)
 clang_diag_gen(Lex)
 clang_diag_gen(Parse)
 clang_diag_gen(Refactoring)
diff --git a/clang/include/clang/Basic/Diagnostic.td 
b/clang/include/clang/Basic/Diagnostic.td
index 8d66e265fbaef0..0b8b3af939ba0e 100644
--- a/clang/include/clang/Basic/Diagnostic.td
+++ b/clang/include/clang/Basic/Diagnostic.td
@@ -162,6 +162,7 @@ include "DiagnosticCommonKinds.td"
 include "DiagnosticCrossTUKinds.td"
 include "DiagnosticDriverKinds.td"
 include "DiagnosticFrontendKinds.td"
+include "DiagnosticInstallAPIKinds.td"
 include "DiagnosticLexKinds.td"
 include "DiagnosticParseKinds.td"
 include "DiagnosticRefactoringKinds.td"
diff --git a/clang/include/clang/Basic/DiagnosticIDs.h 
b/clang/include/clang/Basic/DiagnosticIDs.h
index 0cdda42793f6f0..95b502b1e97ab1 100644
--- a/clang/include/clang/Basic/DiagnosticIDs.h
+++ b/clang/include/clang/Basic/DiagnosticIDs.h
@@ -42,6 +42,7 @@ namespace clang {
   DIAG_SIZE_SEMA  = 4500,
   DIAG_SIZE_ANALYSIS  =  100,
   DIAG_SIZE_REFACTORING   = 1000,
+  DIAG_SIZE_INSTALLAPI=  100,
 };
 // Start position for diagnostics.
 enum {
@@ -57,7 +58,8 @@ namespace clang {
   DIAG_START_SEMA  = DIAG_START_CROSSTU   + 
static_cast(DIAG_SIZE_CROSSTU),
   DIAG_START_ANALYSIS  = DIAG_START_SEMA  + 
static_cast(DIAG_SIZE_SEMA),
   DIAG_START_REFACTORING   = DIAG_START_ANALYSIS  + 
static_cast(DIAG_SIZE_ANALYSIS),
-  DIAG_UPPER_LIMIT = DIAG_START_REFACTORING   + 
static_cast(DIAG_SIZE_REFACTORING)
+  DIAG_START_INSTALLAPI= DIAG_START_REFACTORING   + 
static_cast(DIAG_SIZE_REFACTORING),
+  DIAG_UPPER_LIMIT = DIAG_START_INSTALLAPI+ 
static_cast(DIAG_SIZE_INSTALLAPI)
 };
 
 class CustomDiagInfo;
diff --git a/clang/include/clang/Basic/DiagnosticInstallAPI.h 
b/clang/include/clang/Basic/DiagnosticInstallAPI.h
new file mode 100644
index 00..a76f6e087a2b0a
--- /dev/null
+++ b/clang/include/clang/Basic/DiagnosticInstallAPI.h
@@ -0,0 +1,26 @@
+//===--- DiagnosticInstallAPI.h - Diagnostics for InstallAPI-*- 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: Apach

[clang] [flang] [flang][cuda] Enable cuda with -x cuda option (PR #84944)

2024-03-13 Thread Valentin Clement バレンタイン クレメン via cfe-commits

https://github.com/clementval edited 
https://github.com/llvm/llvm-project/pull/84944
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [flang] [flang][cuda] Enable cuda with -x cuda option (PR #84944)

2024-03-13 Thread Valentin Clement バレンタイン クレメン via cfe-commits


@@ -0,0 +1,13 @@
+! Test -fcuda option
+! RUN: %flang -fc1 -cpp -fcuda -fdebug-unparse %s -o - | FileCheck %s

clementval wrote:

Added

https://github.com/llvm/llvm-project/pull/84944
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [InstallAPI] Add installapi specific options & diagnostics (PR #85100)

2024-03-13 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff e4edbae0aa6a9739954ee3b494b18f8c599d9d79 
a71d8d338c9a5cc2f21957b7907f676f2f11d4d6 -- 
clang/include/clang/Basic/DiagnosticInstallAPI.h 
clang/include/clang/InstallAPI/DylibVerifier.h 
clang/include/clang/InstallAPI/InstallAPIDiagnostic.h 
clang/include/clang/Basic/AllDiagnostics.h 
clang/include/clang/Basic/DiagnosticIDs.h clang/lib/Basic/DiagnosticIDs.cpp 
clang/tools/clang-installapi/ClangInstallAPI.cpp 
clang/tools/clang-installapi/Options.cpp clang/tools/clang-installapi/Options.h
``





View the diff from clang-format here.


``diff
diff --git a/clang/include/clang/Basic/AllDiagnostics.h 
b/clang/include/clang/Basic/AllDiagnostics.h
index e64634cc13..5c92f4f728 100644
--- a/clang/include/clang/Basic/AllDiagnostics.h
+++ b/clang/include/clang/Basic/AllDiagnostics.h
@@ -23,9 +23,9 @@
 #include "clang/Basic/DiagnosticInstallAPI.h"
 #include "clang/Basic/DiagnosticLex.h"
 #include "clang/Basic/DiagnosticParse.h"
+#include "clang/Basic/DiagnosticRefactoring.h"
 #include "clang/Basic/DiagnosticSema.h"
 #include "clang/Basic/DiagnosticSerialization.h"
-#include "clang/Basic/DiagnosticRefactoring.h"
 
 namespace clang {
 template 
diff --git a/clang/include/clang/Basic/DiagnosticIDs.h 
b/clang/include/clang/Basic/DiagnosticIDs.h
index 95b502b1e9..02396728f5 100644
--- a/clang/include/clang/Basic/DiagnosticIDs.h
+++ b/clang/include/clang/Basic/DiagnosticIDs.h
@@ -30,36 +30,45 @@ namespace clang {
 
 // Size of each of the diagnostic categories.
 enum {
-  DIAG_SIZE_COMMON=  300,
-  DIAG_SIZE_DRIVER=  400,
-  DIAG_SIZE_FRONTEND  =  150,
-  DIAG_SIZE_SERIALIZATION =  120,
-  DIAG_SIZE_LEX   =  400,
-  DIAG_SIZE_PARSE =  700,
-  DIAG_SIZE_AST   =  300,
-  DIAG_SIZE_COMMENT   =  100,
-  DIAG_SIZE_CROSSTU   =  100,
-  DIAG_SIZE_SEMA  = 4500,
-  DIAG_SIZE_ANALYSIS  =  100,
-  DIAG_SIZE_REFACTORING   = 1000,
-  DIAG_SIZE_INSTALLAPI=  100,
+  DIAG_SIZE_COMMON = 300,
+  DIAG_SIZE_DRIVER = 400,
+  DIAG_SIZE_FRONTEND = 150,
+  DIAG_SIZE_SERIALIZATION = 120,
+  DIAG_SIZE_LEX = 400,
+  DIAG_SIZE_PARSE = 700,
+  DIAG_SIZE_AST = 300,
+  DIAG_SIZE_COMMENT = 100,
+  DIAG_SIZE_CROSSTU = 100,
+  DIAG_SIZE_SEMA = 4500,
+  DIAG_SIZE_ANALYSIS = 100,
+  DIAG_SIZE_REFACTORING = 1000,
+  DIAG_SIZE_INSTALLAPI = 100,
 };
 // Start position for diagnostics.
 enum {
-  DIAG_START_COMMON=  0,
-  DIAG_START_DRIVER= DIAG_START_COMMON+ 
static_cast(DIAG_SIZE_COMMON),
-  DIAG_START_FRONTEND  = DIAG_START_DRIVER+ 
static_cast(DIAG_SIZE_DRIVER),
-  DIAG_START_SERIALIZATION = DIAG_START_FRONTEND  + 
static_cast(DIAG_SIZE_FRONTEND),
-  DIAG_START_LEX   = DIAG_START_SERIALIZATION + 
static_cast(DIAG_SIZE_SERIALIZATION),
-  DIAG_START_PARSE = DIAG_START_LEX   + 
static_cast(DIAG_SIZE_LEX),
-  DIAG_START_AST   = DIAG_START_PARSE + 
static_cast(DIAG_SIZE_PARSE),
-  DIAG_START_COMMENT   = DIAG_START_AST   + 
static_cast(DIAG_SIZE_AST),
-  DIAG_START_CROSSTU   = DIAG_START_COMMENT   + 
static_cast(DIAG_SIZE_COMMENT),
-  DIAG_START_SEMA  = DIAG_START_CROSSTU   + 
static_cast(DIAG_SIZE_CROSSTU),
-  DIAG_START_ANALYSIS  = DIAG_START_SEMA  + 
static_cast(DIAG_SIZE_SEMA),
-  DIAG_START_REFACTORING   = DIAG_START_ANALYSIS  + 
static_cast(DIAG_SIZE_ANALYSIS),
-  DIAG_START_INSTALLAPI= DIAG_START_REFACTORING   + 
static_cast(DIAG_SIZE_REFACTORING),
-  DIAG_UPPER_LIMIT = DIAG_START_INSTALLAPI+ 
static_cast(DIAG_SIZE_INSTALLAPI)
+  DIAG_START_COMMON = 0,
+  DIAG_START_DRIVER =
+  DIAG_START_COMMON + static_cast(DIAG_SIZE_COMMON),
+  DIAG_START_FRONTEND =
+  DIAG_START_DRIVER + static_cast(DIAG_SIZE_DRIVER),
+  DIAG_START_SERIALIZATION =
+  DIAG_START_FRONTEND + static_cast(DIAG_SIZE_FRONTEND),
+  DIAG_START_LEX =
+  DIAG_START_SERIALIZATION + static_cast(DIAG_SIZE_SERIALIZATION),
+  DIAG_START_PARSE = DIAG_START_LEX + static_cast(DIAG_SIZE_LEX),
+  DIAG_START_AST = DIAG_START_PARSE + static_cast(DIAG_SIZE_PARSE),
+  DIAG_START_COMMENT = DIAG_START_AST + static_cast(DIAG_SIZE_AST),
+  DIAG_START_CROSSTU =
+  DIAG_START_COMMENT + static_cast(DIAG_SIZE_COMMENT),
+  DIAG_START_SEMA =
+  DIAG_START_CROSSTU + static_cast(DIAG_SIZE_CROSSTU),
+  DIAG_START_ANALYSIS = DIAG_START_SEMA + static_cast(DIAG_SIZE_SEMA),
+  DIAG_START_REFACTORING =
+  DIAG_START_ANALYSIS + static_cast(DIAG_SIZE_ANALYSIS),
+  DIAG_START_INSTALLAPI =
+ 

[clang] [InstallAPI] Add installapi specific options & diagnostics (PR #85100)

2024-03-13 Thread Cyndy Ishida via cfe-commits

https://github.com/cyndyishida edited 
https://github.com/llvm/llvm-project/pull/85100
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Headers][X86] Add rounding and exception notes to conversions (PR #83447)

2024-03-13 Thread Paul T Robinson via cfe-commits

https://github.com/pogo59 updated 
https://github.com/llvm/llvm-project/pull/83447

>From 64cdd358d0bf359383a5dd3d1da236a219644c9e Mon Sep 17 00:00:00 2001
From: Paul Robinson 
Date: Thu, 29 Feb 2024 08:59:26 -0800
Subject: [PATCH 1/4] [Headers][X86] Add rounding and exception notes to
 conversions

Consistently describe rounding/truncating on convert intrinsics.
Add notes where an out-of-range result can raise an exception.
---
 clang/lib/Headers/avxintrin.h |  36 +++---
 clang/lib/Headers/emmintrin.h |  91 ++---
 clang/lib/Headers/xmmintrin.h | 125 --
 3 files changed, 182 insertions(+), 70 deletions(-)

diff --git a/clang/lib/Headers/avxintrin.h b/clang/lib/Headers/avxintrin.h
index f116d8bc3a94c7..51c7d76e75ca1a 100644
--- a/clang/lib/Headers/avxintrin.h
+++ b/clang/lib/Headers/avxintrin.h
@@ -2180,7 +2180,8 @@ _mm256_cvtepi32_pd(__m128i __a)
   return (__m256d)__builtin_convertvector((__v4si)__a, __v4df);
 }
 
-/// Converts a vector of [8 x i32] into a vector of [8 x float].
+/// Converts a vector of [8 x i32] into a vector of [8 x float]. Rounds inexact
+///results according to the rounding control bits in the MXCSR register.
 ///
 /// \headerfile 
 ///
@@ -2196,7 +2197,8 @@ _mm256_cvtepi32_ps(__m256i __a)
 }
 
 /// Converts a 256-bit vector of [4 x double] into a 128-bit vector of
-///[4 x float].
+///[4 x float]. Rounds inexact results according to the rounding control
+///bits in the MXCSR register.
 ///
 /// \headerfile 
 ///
@@ -2211,7 +2213,12 @@ _mm256_cvtpd_ps(__m256d __a)
   return (__m128)__builtin_ia32_cvtpd2ps256((__v4df) __a);
 }
 
-/// Converts a vector of [8 x float] into a vector of [8 x i32].
+/// Converts a vector of [8 x float] into a vector of [8 x i32]. Rounds inexact
+///results according to the rounding control bits in the MXCSR register.
+///
+///If a converted value is larger than the maximum possible result,
+///raises a floating-point invalid exception. If the exception is
+///masked, returns the most negative integer.
 ///
 /// \headerfile 
 ///
@@ -2243,8 +2250,11 @@ _mm256_cvtps_pd(__m128 __a)
 }
 
 /// Converts a 256-bit vector of [4 x double] into a 128-bit vector of [4
-///x i32], truncating the result by rounding towards zero when it is
-///inexact.
+///x i32], truncating inexact results.
+///
+///If a converted value is larger than the maximum possible result,
+///raises a floating-point invalid exception. If the exception is
+///masked, returns the most negative integer.
 ///
 /// \headerfile 
 ///
@@ -2259,9 +2269,13 @@ _mm256_cvttpd_epi32(__m256d __a)
   return (__m128i)__builtin_ia32_cvttpd2dq256((__v4df) __a);
 }
 
-/// Converts a 256-bit vector of [4 x double] into a 128-bit vector of [4
-///x i32]. When a conversion is inexact, the value returned is rounded
-///according to the rounding control bits in the MXCSR register.
+/// Converts a 256-bit vector of [4 x double] into a 128-bit vector of
+///[4 x i32]. Rounds inexact results according to the rounding control bits
+///in the MXCSR register.
+///
+///If a converted value is larger than the maximum possible result,
+///raises a floating-point invalid exception. If the exception is
+///masked, returns the most negative integer.
 ///
 /// \headerfile 
 ///
@@ -2277,7 +2291,11 @@ _mm256_cvtpd_epi32(__m256d __a)
 }
 
 /// Converts a vector of [8 x float] into a vector of [8 x i32],
-///truncating the result by rounding towards zero when it is inexact.
+///truncating inexact results.
+///
+///If a converted value is larger than the maximum possible result,
+///raises a floating-point invalid exception. If the exception is
+///masked, returns the most negative integer.
 ///
 /// \headerfile 
 ///
diff --git a/clang/lib/Headers/emmintrin.h b/clang/lib/Headers/emmintrin.h
index 96e3ebdecbdf83..9ae7fe2c809ac6 100644
--- a/clang/lib/Headers/emmintrin.h
+++ b/clang/lib/Headers/emmintrin.h
@@ -1245,7 +1245,8 @@ static __inline__ int __DEFAULT_FN_ATTRS 
_mm_ucomineq_sd(__m128d __a,
 /// Converts the two double-precision floating-point elements of a
 ///128-bit vector of [2 x double] into two single-precision floating-point
 ///values, returned in the lower 64 bits of a 128-bit vector of [4 x 
float].
-///The upper 64 bits of the result vector are set to zero.
+///Rounds inexact results according to the rounding control bits in the
+///MXCSR register. The upper 64 bits of the result vector are set to zero.
 ///
 /// \headerfile 
 ///
@@ -1300,9 +1301,13 @@ static __inline__ __m128d __DEFAULT_FN_ATTRS 
_mm_cvtepi32_pd(__m128i __a) {
 }
 
 /// Converts the two double-precision floating-point elements of a
-///128-bit vector of [2 x double] into two signed 32-bit integer values,
-///returned in the lower 64 bits of a 128-bit vector of [4 x i32]. The 
upper
-///64 bits of the result vector are set to zero.
+///128-bit vector of [2 

[clang] [InstallAPI] Add installapi specific options & diagnostics (PR #85100)

2024-03-13 Thread Cyndy Ishida via cfe-commits

https://github.com/cyndyishida updated 
https://github.com/llvm/llvm-project/pull/85100

>From 7a7c5103a20b35a00c87fe47f1a4bc4a24dc205e Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Wed, 6 Mar 2024 09:16:20 -0800
Subject: [PATCH] [InstallAPI] Add installapi specific options & diagnostics

* A lot of `tapi installapi` options are already shared with clang, but not all.
  This patch handles installapi specific options by filtering for them in 
initial argv input, then passing the rest to the clang driver.
* Installapi not only generates a text file but also reports to library
  developers when there are inconsistences between an interface and it's
  implementation. To allow this, add support for reporting installapi
  diagnostics. This will be leveraged in the verifier service.
---
 clang/include/clang/Basic/AllDiagnostics.h|   1 +
 clang/include/clang/Basic/CMakeLists.txt  |   1 +
 clang/include/clang/Basic/Diagnostic.td   |   1 +
 clang/include/clang/Basic/DiagnosticIDs.h |   4 +-
 .../clang/Basic/DiagnosticInstallAPI.h|  26 +++
 .../clang/Basic/DiagnosticInstallAPIKinds.td  |  20 ++
 .../include/clang/InstallAPI/DylibVerifier.h  |  27 +++
 .../clang/InstallAPI/InstallAPIDiagnostic.h   |  14 ++
 clang/lib/Basic/DiagnosticIDs.cpp |  10 +-
 .../InstallAPI/driver-invalid-options.test|   7 +-
 clang/test/InstallAPI/functions.test  |   2 +-
 clang/tools/clang-installapi/CMakeLists.txt   |   8 +
 .../clang-installapi/ClangInstallAPI.cpp  |  23 +--
 .../tools/clang-installapi/InstallAPIOpts.td  |  31 +++
 clang/tools/clang-installapi/Options.cpp  | 192 +++---
 clang/tools/clang-installapi/Options.h|  25 ++-
 16 files changed, 342 insertions(+), 50 deletions(-)
 create mode 100644 clang/include/clang/Basic/DiagnosticInstallAPI.h
 create mode 100644 clang/include/clang/Basic/DiagnosticInstallAPIKinds.td
 create mode 100644 clang/include/clang/InstallAPI/DylibVerifier.h
 create mode 100644 clang/include/clang/InstallAPI/InstallAPIDiagnostic.h
 create mode 100644 clang/tools/clang-installapi/InstallAPIOpts.td

diff --git a/clang/include/clang/Basic/AllDiagnostics.h 
b/clang/include/clang/Basic/AllDiagnostics.h
index cc6aa631534a5d..e64634cc138f7f 100644
--- a/clang/include/clang/Basic/AllDiagnostics.h
+++ b/clang/include/clang/Basic/AllDiagnostics.h
@@ -20,6 +20,7 @@
 #include "clang/Basic/DiagnosticCrossTU.h"
 #include "clang/Basic/DiagnosticDriver.h"
 #include "clang/Basic/DiagnosticFrontend.h"
+#include "clang/Basic/DiagnosticInstallAPI.h"
 #include "clang/Basic/DiagnosticLex.h"
 #include "clang/Basic/DiagnosticParse.h"
 #include "clang/Basic/DiagnosticSema.h"
diff --git a/clang/include/clang/Basic/CMakeLists.txt 
b/clang/include/clang/Basic/CMakeLists.txt
index 7785fb430c069b..7d53c751c13ac4 100644
--- a/clang/include/clang/Basic/CMakeLists.txt
+++ b/clang/include/clang/Basic/CMakeLists.txt
@@ -12,6 +12,7 @@ clang_diag_gen(Common)
 clang_diag_gen(CrossTU)
 clang_diag_gen(Driver)
 clang_diag_gen(Frontend)
+clang_diag_gen(InstallAPI)
 clang_diag_gen(Lex)
 clang_diag_gen(Parse)
 clang_diag_gen(Refactoring)
diff --git a/clang/include/clang/Basic/Diagnostic.td 
b/clang/include/clang/Basic/Diagnostic.td
index 8d66e265fbaef0..0b8b3af939ba0e 100644
--- a/clang/include/clang/Basic/Diagnostic.td
+++ b/clang/include/clang/Basic/Diagnostic.td
@@ -162,6 +162,7 @@ include "DiagnosticCommonKinds.td"
 include "DiagnosticCrossTUKinds.td"
 include "DiagnosticDriverKinds.td"
 include "DiagnosticFrontendKinds.td"
+include "DiagnosticInstallAPIKinds.td"
 include "DiagnosticLexKinds.td"
 include "DiagnosticParseKinds.td"
 include "DiagnosticRefactoringKinds.td"
diff --git a/clang/include/clang/Basic/DiagnosticIDs.h 
b/clang/include/clang/Basic/DiagnosticIDs.h
index 0cdda42793f6f0..95b502b1e97ab1 100644
--- a/clang/include/clang/Basic/DiagnosticIDs.h
+++ b/clang/include/clang/Basic/DiagnosticIDs.h
@@ -42,6 +42,7 @@ namespace clang {
   DIAG_SIZE_SEMA  = 4500,
   DIAG_SIZE_ANALYSIS  =  100,
   DIAG_SIZE_REFACTORING   = 1000,
+  DIAG_SIZE_INSTALLAPI=  100,
 };
 // Start position for diagnostics.
 enum {
@@ -57,7 +58,8 @@ namespace clang {
   DIAG_START_SEMA  = DIAG_START_CROSSTU   + 
static_cast(DIAG_SIZE_CROSSTU),
   DIAG_START_ANALYSIS  = DIAG_START_SEMA  + 
static_cast(DIAG_SIZE_SEMA),
   DIAG_START_REFACTORING   = DIAG_START_ANALYSIS  + 
static_cast(DIAG_SIZE_ANALYSIS),
-  DIAG_UPPER_LIMIT = DIAG_START_REFACTORING   + 
static_cast(DIAG_SIZE_REFACTORING)
+  DIAG_START_INSTALLAPI= DIAG_START_REFACTORING   + 
static_cast(DIAG_SIZE_REFACTORING),
+  DIAG_UPPER_LIMIT = DIAG_START_INSTALLAPI+ 
static_cast(DIAG_SIZE_INSTALLAPI)
 };
 
 class CustomDiagInfo;
diff --git a/clang/include/clang/Basic/DiagnosticInstallAPI.h 
b/clang/include/clang/Basic/DiagnosticInstallAPI.h
new file mode 100644
index 00..a76f6e087a2b0a
--- /dev/n

[clang] f15a790 - Remove use of reference lifetime extension introduced in cdde0d9

2024-03-13 Thread David Blaikie via cfe-commits

Author: David Blaikie
Date: 2024-03-13T16:03:16Z
New Revision: f15a790fd383665ec4defa0711e975476fd8b18b

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

LOG: Remove use of reference lifetime extension introduced in cdde0d9

Rather than dealing with which is more readable, the named variable
doesn't seem to add value here - so omit it.

Added: 


Modified: 
clang/lib/AST/Interp/Interp.h

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index bb220657c2dadc..db80e2d59753f8 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -846,8 +846,7 @@ bool CMP3(InterpState &S, CodePtr OpPC, const 
ComparisonCategoryInfo *CmpInfo) {
   CmpInfo->getValueInfo(CmpInfo->makeWeakResult(CmpResult));
   assert(CmpValueInfo);
   assert(CmpValueInfo->hasValidIntValue());
-  const APSInt &IntValue = CmpValueInfo->getIntValue();
-  return SetThreeWayComparisonField(S, OpPC, P, IntValue);
+  return SetThreeWayComparisonField(S, OpPC, P, CmpValueInfo->getIntValue());
 }
 
 template ::T>



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


[clang] nolock/noalloc attributes (PR #84983)

2024-03-13 Thread Doug Wyatt via cfe-commits


@@ -4912,3 +4922,279 @@ void AutoType::Profile(llvm::FoldingSetNodeID &ID, 
const ASTContext &Context) {
   Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
   getTypeConstraintConcept(), getTypeConstraintArguments());
 }
+
+FunctionEffect::~FunctionEffect() = default;
+
+bool FunctionEffect::diagnoseConversion(bool Adding, QualType OldType,
+FunctionEffectSet OldFX,
+QualType NewType,
+FunctionEffectSet NewFX) const {
+  return false;
+}
+
+bool FunctionEffect::diagnoseRedeclaration(bool Adding,
+   const FunctionDecl &OldFunction,
+   FunctionEffectSet OldFX,
+   const FunctionDecl &NewFunction,
+   FunctionEffectSet NewFX) const {
+  return false;
+}
+
+bool FunctionEffect::diagnoseMethodOverride(bool Adding,
+const CXXMethodDecl &OldMethod,
+FunctionEffectSet OldFX,
+const CXXMethodDecl &NewMethod,
+FunctionEffectSet NewFX) const {
+  return false;
+}
+
+bool FunctionEffect::canInferOnDecl(const Decl *Caller,
+FunctionEffectSet CallerFX) const {
+  return false;
+}
+
+bool FunctionEffect::diagnoseFunctionCall(bool Direct, const Decl *Caller,
+  FunctionEffectSet CallerFX,
+  CalleeDeclOrType Callee,
+  FunctionEffectSet CalleeFX) const {
+  return false;
+}
+
+const NoLockNoAllocEffect &NoLockNoAllocEffect::nolock_instance() {
+  static NoLockNoAllocEffect global(kNoLockTrue, "nolock");
+  return global;
+}

dougsonos wrote:

I did one whole implementation with both the true/false forms of the attributes 
as `AttributedType`. Along the way I found and had to hack around two bugs 
where the sugar gets stripped, e.g. on an `auto` lambda.

I got some guidance that the `true` forms of the attributes made sense as part 
of the canonical type, so (confusingly, I know):
- the `true` attribute triggers the addition of a global instance of a 
`NoLockNoAllocEffect` into a `FunctionEffectSet` as an optional part of the 
`FunctionProtoType`. It does not currently put an attribute on the type.
- the `false` attribute uses `AttributedType`. BTW another limitation of 
`AttributedType` is that it doesn't seem to hold anything more than the 
attribute kind, so if we went that way we'd probably need 3 kinds for `nolock` 
(true, false, type-dependent expression) and 3 for `noalloc`. The 
type-dependent expression might end up needing a whole new type-sugar class.

Even if `FunctionEffect` turns out to be just some bits controlling details of 
the behavior, rather than a vtable, it's still attractive to me to encapsulate 
it into a uniqued object with methods, to centralize all those behaviors.

There's a fair amount of code prepared for the possibility of new, unrelated 
effects (e.g. "TCB + types"), anticipating that FunctionEffectSet could hold 
multiple effects. Considering for example a codebase that with several TCB's, 
they would all have the same behaviors about calls within themselves, but need 
to be considered unique effects, e.g. a function in TCB A can't call a function 
that's only part of TCB Z. This is the motivation for the FunctionEffect 
abstraction.

https://github.com/llvm/llvm-project/pull/84983
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] nolock/noalloc attributes (PR #84983)

2024-03-13 Thread Doug Wyatt via cfe-commits

https://github.com/dougsonos edited 
https://github.com/llvm/llvm-project/pull/84983
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] Don't use crtbegin/crtend when building for musl. (PR #85089)

2024-03-13 Thread Alastair Houghton via cfe-commits

https://github.com/al45tair updated 
https://github.com/llvm/llvm-project/pull/85089

>From 8bdd6627e21eaddedfff208eebaa46f1eeb81674 Mon Sep 17 00:00:00 2001
From: Alastair Houghton 
Date: Thu, 22 Feb 2024 11:36:57 +
Subject: [PATCH 1/2] [Clang] Don't use crtbegin/crtend when building for musl.

musl doesn't supply crtbegin/crtend objects, so we don't want to
try to link them there.

rdar://123436174
---
 clang/lib/Driver/ToolChains/Gnu.cpp | 6 --
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index a9c9d2475809d7..7b7d9194a773ec 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -371,13 +371,15 @@ void tools::gnutools::Linker::ConstructJob(Compilation 
&C, const JobAction &JA,
   const llvm::Triple::ArchType Arch = ToolChain.getArch();
   const bool isOHOSFamily = ToolChain.getTriple().isOHOSFamily();
   const bool isAndroid = ToolChain.getTriple().isAndroid();
+  const bool isMusl = ToolChain.getTriple().isMusl();
   const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
   const bool IsVE = ToolChain.getTriple().isVE();
   const bool IsStaticPIE = getStaticPIE(Args, ToolChain);
   const bool IsStatic = getStatic(Args);
   const bool HasCRTBeginEndFiles =
-  ToolChain.getTriple().hasEnvironment() ||
-  (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
+!isMusl && (ToolChain.getTriple().hasEnvironment() ||
+(ToolChain.getTriple().getVendor()
+ != llvm::Triple::MipsTechnologies));
 
   ArgStringList CmdArgs;
 

>From cb13d69df1ff750d9653a76186a8ac4626695470 Mon Sep 17 00:00:00 2001
From: Alastair Houghton 
Date: Wed, 13 Mar 2024 16:05:09 +
Subject: [PATCH 2/2] [Clang] Tweak code formatting.

Tweak code formatting slightly to make clang-format happy.

rdar://123436174
---
 clang/lib/Driver/ToolChains/Gnu.cpp | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index 7b7d9194a773ec..740a160cfa5c22 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -377,9 +377,9 @@ void tools::gnutools::Linker::ConstructJob(Compilation &C, 
const JobAction &JA,
   const bool IsStaticPIE = getStaticPIE(Args, ToolChain);
   const bool IsStatic = getStatic(Args);
   const bool HasCRTBeginEndFiles =
-!isMusl && (ToolChain.getTriple().hasEnvironment() ||
-(ToolChain.getTriple().getVendor()
- != llvm::Triple::MipsTechnologies));
+  !isMusl &&
+  (ToolChain.getTriple().hasEnvironment() ||
+   (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies));
 
   ArgStringList CmdArgs;
 

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


[clang] nolock/noalloc attributes (PR #84983)

2024-03-13 Thread Doug Wyatt via cfe-commits

https://github.com/dougsonos edited 
https://github.com/llvm/llvm-project/pull/84983
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] nolock/noalloc attributes (PR #84983)

2024-03-13 Thread Doug Wyatt via cfe-commits

https://github.com/dougsonos edited 
https://github.com/llvm/llvm-project/pull/84983
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [HLSL] Implement array temporary support (PR #79382)

2024-03-13 Thread Chris B via cfe-commits


@@ -4655,6 +4655,13 @@ void CodeGenFunction::EmitCallArg(CallArgList &args, 
const Expr *E,
 return emitWritebackArg(*this, args, CRE);
   }
 
+  // If an argument is an array paramter expression being passed through. Emit
+  // the argument to a temporary and pass the temporary as the call arg.
+  if (auto AT = dyn_cast(type)) {
+args.add(EmitAnyExprToTemp(E), type);

llvm-beanz wrote:

Ah, yea, I think I need to fix this a different way.

The case where this happens is:

```c++
void fn(float x[2]);

void call(float Arr[2]) {
  fn(Arr);
}
```

In the CallExpr to fn, the argument is an lvalue DeclRefExpr to the ParmVar.

I think the right way to do this is to insert an ImplicitCastExpr for 
CK_HLSLArrayRValue or CK_LValueToRValue.

https://github.com/llvm/llvm-project/pull/79382
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libunwind] [libunwind] Tweak tests for musl support. (PR #85097)

2024-03-13 Thread Alastair Houghton via cfe-commits

https://github.com/al45tair updated 
https://github.com/llvm/llvm-project/pull/85097

>From 6808d20b198bba4f2e062094b89cfc13eac49f85 Mon Sep 17 00:00:00 2001
From: Alastair Houghton 
Date: Thu, 22 Feb 2024 11:59:24 +
Subject: [PATCH 1/2] [libunwind] Tweak tests for musl support.

We can't use `dladdr()` in the tests, because when we're statically
linking with musl that function is a no-op.

Additionally, because musl disables emission of unwind information
in its build, and because its signal trampolines don't include
unwind information, tests that involve unwinding through a signal
handler won't work and need to be disabled for musl.

rdar://123436891
---
 libunwind/test/floatregister.pass.cpp   | 18 +-
 libunwind/test/forceunwind.pass.cpp | 19 +--
 libunwind/test/signal_unwind.pass.cpp   | 26 +++--
 libunwind/test/unwind_leaffunction.pass.cpp | 24 ++-
 4 files changed, 61 insertions(+), 26 deletions(-)

diff --git a/libunwind/test/floatregister.pass.cpp 
b/libunwind/test/floatregister.pass.cpp
index 64107e6d490b70..e4657c63fd1adf 100644
--- a/libunwind/test/floatregister.pass.cpp
+++ b/libunwind/test/floatregister.pass.cpp
@@ -11,20 +11,26 @@
 
 // Basic test for float registers number are accepted.
 
-#include 
 #include 
 #include 
 #include 
 
+// Using __attribute__((section("main_func"))) is Linux specific, but then
+// this entire test is marked as requiring Linux, so we should be good.
+//
+// We don't use dladdr() because on musl it's a no-op when statically linked.
+extern char __start_main_func;
+extern char __stop_main_func;
+
 _Unwind_Reason_Code frame_handler(struct _Unwind_Context *ctx, void *arg) {
   (void)arg;
-  Dl_info info = {0, 0, 0, 0};
 
-  // Unwind util the main is reached, above frames depend on the platform and
+  // Unwind until the main is reached, above frames depend on the platform and
   // architecture.
-  if (dladdr(reinterpret_cast(_Unwind_GetIP(ctx)), &info) &&
-  info.dli_sname && !strcmp("main", info.dli_sname))
+  uintptr_t ip = _Unwind_GetIP(ctx);
+  if (ip >= (uintptr_t)&__start_main_func && ip < 
(uintptr_t)&__stop_main_func) {
 _Exit(0);
+  }
 
   return _URC_NO_REASON;
 }
@@ -45,7 +51,7 @@ __attribute__((noinline)) void foo() {
   _Unwind_Backtrace(frame_handler, NULL);
 }
 
-int main() {
+__attribute__((section("main_func"))) int main() {
   foo();
   return -2;
 }
diff --git a/libunwind/test/forceunwind.pass.cpp 
b/libunwind/test/forceunwind.pass.cpp
index db499d8bc30894..feb71fb769980c 100644
--- a/libunwind/test/forceunwind.pass.cpp
+++ b/libunwind/test/forceunwind.pass.cpp
@@ -17,7 +17,6 @@
 
 #undef NDEBUG
 #include 
-#include 
 #include 
 #include 
 #include 
@@ -27,6 +26,13 @@
 #include 
 #include 
 
+// Using __attribute__((section("main_func"))) is Linux specific, but then
+// this entire test is marked as requiring Linux, so we should be good.
+//
+// We don't use dladdr() because on musl it's a no-op when statically linked.
+extern char __start_main_func;
+extern char __stop_main_func;
+
 void foo();
 _Unwind_Exception ex;
 
@@ -41,14 +47,13 @@ _Unwind_Reason_Code stop(int version, _Unwind_Action 
actions,
   assert(exceptionObject == &ex);
   assert(stop_parameter == &foo);
 
-  Dl_info info = {0, 0, 0, 0};
-
-  // Unwind util the main is reached, above frames depend on the platform and
+  // Unwind until the main is reached, above frames depend on the platform and
   // architecture.
-  if (dladdr(reinterpret_cast(_Unwind_GetIP(context)), &info) &&
-  info.dli_sname && !strcmp("main", info.dli_sname)) {
+  uintptr_t ip = _Unwind_GetIP(context);
+  if (ip >= (uintptr_t)&__start_main_func && ip < 
(uintptr_t)&__stop_main_func) {
 _Exit(0);
   }
+
   return _URC_NO_REASON;
 }
 
@@ -66,7 +71,7 @@ __attribute__((noinline)) void foo() {
   _Unwind_ForcedUnwind(e, stop, (void *)&foo);
 }
 
-int main() {
+__attribute__((section("main_func"))) int main() {
   foo();
   return -2;
 }
diff --git a/libunwind/test/signal_unwind.pass.cpp 
b/libunwind/test/signal_unwind.pass.cpp
index 954a5d4ba3db10..715299e7496efe 100644
--- a/libunwind/test/signal_unwind.pass.cpp
+++ b/libunwind/test/signal_unwind.pass.cpp
@@ -8,14 +8,13 @@
 
//===--===//
 
 // Ensure that the unwinder can cope with the signal handler.
-// REQUIRES: target={{(aarch64|riscv64|s390x|x86_64)-.+linux.*}}
+// REQUIRES: target={{(aarch64|riscv64|s390x|x86_64)-.+}}linux-gnu
 
 // TODO: Figure out why this fails with Memory Sanitizer.
 // XFAIL: msan
 
 #undef NDEBUG
 #include 
-#include 
 #include 
 #include 
 #include 
@@ -24,16 +23,29 @@
 #include 
 #include 
 
+// Note: this test fails on musl because:
+//
+//  (a) musl disables emission of unwind information for its build, and
+//  (b) musl's signal trampolines don't include unwind information
+//
+
+// Using __attribute__((section("main_func"))) is Linux specific, but then
+// this entir

[clang] nolock/noalloc attributes (PR #84983)

2024-03-13 Thread Doug Wyatt via cfe-commits

https://github.com/dougsonos edited 
https://github.com/llvm/llvm-project/pull/84983
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [flang] [flang][cuda] Enable cuda with -x cuda option (PR #84944)

2024-03-13 Thread Andrzej Warzyński via cfe-commits

https://github.com/banach-space approved this pull request.

LGTM, thanks for the updates!

https://github.com/llvm/llvm-project/pull/84944
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] nolock/noalloc attributes (PR #84983)

2024-03-13 Thread Doug Wyatt via cfe-commits


@@ -11100,6 +11136,48 @@ Attr 
*Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
   return nullptr;
 }
 
+// Should only be called when getFunctionEffects() returns a non-empty set.
+// Decl should be a FunctionDecl or BlockDecl.
+void Sema::CheckAddCallableWithEffects(const Decl *D, FunctionEffectSet FX) {
+  if (!D->hasBody()) {
+if (const auto *FD = D->getAsFunction()) {
+  if (!FD->willHaveBody()) {
+return;
+  }
+}
+  }
+
+  if (Diags.getIgnoreAllWarnings() ||
+  (Diags.getSuppressSystemWarnings() &&
+   SourceMgr.isInSystemHeader(D->getLocation(
+return;
+
+  if (hasUncompilableErrorOccurred())
+return;
+
+  // For code in dependent contexts, we'll do this at instantiation time
+  // (??? This was copied from something else in AnalysisBasedWarnings ???)
+  if (cast(D)->isDependentContext()) {
+return;
+  }

dougsonos wrote:

Thanks. For now I've disabled this with a TODO and will see what happens when I 
next try the branch on our codebase.

https://github.com/llvm/llvm-project/pull/84983
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Adapted MemRegion::getDescriptiveName to handle ElementRegions (PR #85104)

2024-03-13 Thread via cfe-commits

https://github.com/T-Gruber created 
https://github.com/llvm/llvm-project/pull/85104

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

Changes:
- Adapted MemRegion::getDescriptiveName
- Added unittest to check name for a given clang::ento::ElementRegion
- Some format changes due to clang-format

>From 0f964127ed91e23f8e969e08ce680535cfeb8906 Mon Sep 17 00:00:00 2001
From: Andreas Steinhausen 
Date: Wed, 13 Mar 2024 17:07:53 +0100
Subject: [PATCH] Adapted MemRegion::getDescriptiveName to handle
 ElementRegions

---
 clang/lib/StaticAnalyzer/Core/MemRegion.cpp   | 244 --
 clang/unittests/StaticAnalyzer/CMakeLists.txt |   1 +
 .../StaticAnalyzer/MemRegionTest.cpp  |  56 
 3 files changed, 167 insertions(+), 134 deletions(-)
 create mode 100644 clang/unittests/StaticAnalyzer/MemRegionTest.cpp

diff --git a/clang/lib/StaticAnalyzer/Core/MemRegion.cpp 
b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
index 16db6b249dc92b..89791bd88001e3 100644
--- a/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
+++ b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
@@ -66,7 +66,7 @@ using namespace ento;
 
//===--===//
 
 template 
-RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1,
+RegionTy *MemRegionManager::getSubRegion(const Arg1Ty arg1,
  const SuperTy *superRegion) {
   llvm::FoldingSetNodeID ID;
   RegionTy::ProfileRegion(ID, arg1, superRegion);
@@ -82,7 +82,7 @@ RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1,
 }
 
 template 
-RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
+RegionTy *MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
  const SuperTy *superRegion) {
   llvm::FoldingSetNodeID ID;
   RegionTy::ProfileRegion(ID, arg1, arg2, superRegion);
@@ -97,9 +97,9 @@ RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, 
const Arg2Ty arg2,
   return R;
 }
 
-template 
-RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
+template 
+RegionTy *MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
  const Arg3Ty arg3,
  const SuperTy *superRegion) {
   llvm::FoldingSetNodeID ID;
@@ -129,8 +129,8 @@ MemRegionManager::~MemRegionManager() = default;
 // Basic methods.
 
//===--===//
 
-bool SubRegion::isSubRegionOf(const MemRegion* R) const {
-  const MemRegion* r = this;
+bool SubRegion::isSubRegionOf(const MemRegion *R) const {
+  const MemRegion *r = this;
   do {
 if (r == R)
   return true;
@@ -143,7 +143,7 @@ bool SubRegion::isSubRegionOf(const MemRegion* R) const {
 }
 
 MemRegionManager &SubRegion::getMemRegionManager() const {
-  const SubRegion* r = this;
+  const SubRegion *r = this;
   do {
 const MemRegion *superRegion = r->getSuperRegion();
 if (const auto *sr = dyn_cast(superRegion)) {
@@ -178,9 +178,7 @@ ObjCIvarRegion::ObjCIvarRegion(const ObjCIvarDecl *ivd, 
const SubRegion *sReg)
 
 const ObjCIvarDecl *ObjCIvarRegion::getDecl() const { return IVD; }
 
-QualType ObjCIvarRegion::getValueType() const {
-  return getDecl()->getType();
-}
+QualType ObjCIvarRegion::getValueType() const { return getDecl()->getType(); }
 
 QualType CXXBaseObjectRegion::getValueType() const {
   return QualType(getDecl()->getTypeForDecl(), 0);
@@ -251,26 +249,25 @@ void 
ObjCStringRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
   ID.AddPointer(superRegion);
 }
 
-void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
- const Expr *Ex, unsigned cnt,
- const MemRegion *superRegion) {
+void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID &ID, const Expr *Ex,
+ unsigned cnt, const MemRegion *superRegion) {
   ID.AddInteger(static_cast(AllocaRegionKind));
   ID.AddPointer(Ex);
   ID.AddInteger(cnt);
   ID.AddPointer(superRegion);
 }
 
-void AllocaRegion::Profile(llvm::FoldingSetNodeID& ID) const {
+void AllocaRegion::Profile(llvm::FoldingSetNodeID &ID) const {
   ProfileRegion(ID, Ex, Cnt, superRegion);
 }
 
-void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID& ID) const {
+void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID &ID) const {
   CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion);
 }
 
-void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
+void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
   const CompoundLiteralExpr *CL,
-  const MemRegion* superRegion) {
+  const MemRegion *superRegion) {
   ID.AddInteger(static_cast(CompoundLiteralRegionKind));
   ID.AddPointer(CL);
   ID.AddPointer(superRegion

[clang] nolock/noalloc attributes (PR #84983)

2024-03-13 Thread Doug Wyatt via cfe-commits


@@ -0,0 +1,84 @@
+// RUN: %clang_cc1 -fsyntax-only -fblocks -verify %s

dougsonos wrote:

OK, maybe "syntax" then...

https://github.com/llvm/llvm-project/pull/84983
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Adapted MemRegion::getDescriptiveName to handle ElementRegions (PR #85104)

2024-03-13 Thread via cfe-commits

github-actions[bot] wrote:



Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be
notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this 
page.

If this is not working for you, it is probably because you do not have write
permissions for the repository. In which case you can instead tag reviewers by
name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review
by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate
is once a week. Please remember that you are asking for valuable time from 
other developers.

If you have further questions, they may be answered by the [LLVM GitHub User 
Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM 
Discord](https://discord.com/invite/xS7Z362) or on the 
[forums](https://discourse.llvm.org/).

https://github.com/llvm/llvm-project/pull/85104
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [flang] [flang][cuda] Enable cuda with -x cuda option (PR #84944)

2024-03-13 Thread Valentin Clement バレンタイン クレメン via cfe-commits

https://github.com/clementval closed 
https://github.com/llvm/llvm-project/pull/84944
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Adapted MemRegion::getDescriptiveName to handle ElementRegions (PR #85104)

2024-03-13 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (T-Gruber)


Changes

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

Changes:
- Adapted MemRegion::getDescriptiveName
- Added unittest to check name for a given clang::ento::ElementRegion
- Some format changes due to clang-format

---

Patch is 28.10 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/85104.diff


3 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Core/MemRegion.cpp (+110-134) 
- (modified) clang/unittests/StaticAnalyzer/CMakeLists.txt (+1) 
- (added) clang/unittests/StaticAnalyzer/MemRegionTest.cpp (+56) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Core/MemRegion.cpp 
b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
index 16db6b249dc92b..89791bd88001e3 100644
--- a/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
+++ b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
@@ -66,7 +66,7 @@ using namespace ento;
 
//===--===//
 
 template 
-RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1,
+RegionTy *MemRegionManager::getSubRegion(const Arg1Ty arg1,
  const SuperTy *superRegion) {
   llvm::FoldingSetNodeID ID;
   RegionTy::ProfileRegion(ID, arg1, superRegion);
@@ -82,7 +82,7 @@ RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1,
 }
 
 template 
-RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
+RegionTy *MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
  const SuperTy *superRegion) {
   llvm::FoldingSetNodeID ID;
   RegionTy::ProfileRegion(ID, arg1, arg2, superRegion);
@@ -97,9 +97,9 @@ RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, 
const Arg2Ty arg2,
   return R;
 }
 
-template 
-RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
+template 
+RegionTy *MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
  const Arg3Ty arg3,
  const SuperTy *superRegion) {
   llvm::FoldingSetNodeID ID;
@@ -129,8 +129,8 @@ MemRegionManager::~MemRegionManager() = default;
 // Basic methods.
 
//===--===//
 
-bool SubRegion::isSubRegionOf(const MemRegion* R) const {
-  const MemRegion* r = this;
+bool SubRegion::isSubRegionOf(const MemRegion *R) const {
+  const MemRegion *r = this;
   do {
 if (r == R)
   return true;
@@ -143,7 +143,7 @@ bool SubRegion::isSubRegionOf(const MemRegion* R) const {
 }
 
 MemRegionManager &SubRegion::getMemRegionManager() const {
-  const SubRegion* r = this;
+  const SubRegion *r = this;
   do {
 const MemRegion *superRegion = r->getSuperRegion();
 if (const auto *sr = dyn_cast(superRegion)) {
@@ -178,9 +178,7 @@ ObjCIvarRegion::ObjCIvarRegion(const ObjCIvarDecl *ivd, 
const SubRegion *sReg)
 
 const ObjCIvarDecl *ObjCIvarRegion::getDecl() const { return IVD; }
 
-QualType ObjCIvarRegion::getValueType() const {
-  return getDecl()->getType();
-}
+QualType ObjCIvarRegion::getValueType() const { return getDecl()->getType(); }
 
 QualType CXXBaseObjectRegion::getValueType() const {
   return QualType(getDecl()->getTypeForDecl(), 0);
@@ -251,26 +249,25 @@ void 
ObjCStringRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
   ID.AddPointer(superRegion);
 }
 
-void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
- const Expr *Ex, unsigned cnt,
- const MemRegion *superRegion) {
+void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID &ID, const Expr *Ex,
+ unsigned cnt, const MemRegion *superRegion) {
   ID.AddInteger(static_cast(AllocaRegionKind));
   ID.AddPointer(Ex);
   ID.AddInteger(cnt);
   ID.AddPointer(superRegion);
 }
 
-void AllocaRegion::Profile(llvm::FoldingSetNodeID& ID) const {
+void AllocaRegion::Profile(llvm::FoldingSetNodeID &ID) const {
   ProfileRegion(ID, Ex, Cnt, superRegion);
 }
 
-void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID& ID) const {
+void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID &ID) const {
   CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion);
 }
 
-void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
+void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
   const CompoundLiteralExpr *CL,
-  const MemRegion* superRegion) {
+  const MemRegion *superRegion) {
   ID.AddInteger(static_cast(CompoundLiteralRegionKind));
   ID.AddPointer(CL);
   ID.AddPointer(superRegion);
@@ -292,9 +289,9 @@ void FieldRegion::Profile(llvm::FoldingSetNodeID &ID) const 
{
   ProfileRegion(ID, getDecl(), superRegion);
 }
 
-void ObjCIvarRegion::ProfileRegion(ll

[clang] Adapted MemRegion::getDescriptiveName to handle ElementRegions (PR #85104)

2024-03-13 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-static-analyzer-1

Author: None (T-Gruber)


Changes

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

Changes:
- Adapted MemRegion::getDescriptiveName
- Added unittest to check name for a given clang::ento::ElementRegion
- Some format changes due to clang-format

---

Patch is 28.10 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/85104.diff


3 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Core/MemRegion.cpp (+110-134) 
- (modified) clang/unittests/StaticAnalyzer/CMakeLists.txt (+1) 
- (added) clang/unittests/StaticAnalyzer/MemRegionTest.cpp (+56) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Core/MemRegion.cpp 
b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
index 16db6b249dc92b..89791bd88001e3 100644
--- a/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
+++ b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
@@ -66,7 +66,7 @@ using namespace ento;
 
//===--===//
 
 template 
-RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1,
+RegionTy *MemRegionManager::getSubRegion(const Arg1Ty arg1,
  const SuperTy *superRegion) {
   llvm::FoldingSetNodeID ID;
   RegionTy::ProfileRegion(ID, arg1, superRegion);
@@ -82,7 +82,7 @@ RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1,
 }
 
 template 
-RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
+RegionTy *MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
  const SuperTy *superRegion) {
   llvm::FoldingSetNodeID ID;
   RegionTy::ProfileRegion(ID, arg1, arg2, superRegion);
@@ -97,9 +97,9 @@ RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, 
const Arg2Ty arg2,
   return R;
 }
 
-template 
-RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
+template 
+RegionTy *MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
  const Arg3Ty arg3,
  const SuperTy *superRegion) {
   llvm::FoldingSetNodeID ID;
@@ -129,8 +129,8 @@ MemRegionManager::~MemRegionManager() = default;
 // Basic methods.
 
//===--===//
 
-bool SubRegion::isSubRegionOf(const MemRegion* R) const {
-  const MemRegion* r = this;
+bool SubRegion::isSubRegionOf(const MemRegion *R) const {
+  const MemRegion *r = this;
   do {
 if (r == R)
   return true;
@@ -143,7 +143,7 @@ bool SubRegion::isSubRegionOf(const MemRegion* R) const {
 }
 
 MemRegionManager &SubRegion::getMemRegionManager() const {
-  const SubRegion* r = this;
+  const SubRegion *r = this;
   do {
 const MemRegion *superRegion = r->getSuperRegion();
 if (const auto *sr = dyn_cast(superRegion)) {
@@ -178,9 +178,7 @@ ObjCIvarRegion::ObjCIvarRegion(const ObjCIvarDecl *ivd, 
const SubRegion *sReg)
 
 const ObjCIvarDecl *ObjCIvarRegion::getDecl() const { return IVD; }
 
-QualType ObjCIvarRegion::getValueType() const {
-  return getDecl()->getType();
-}
+QualType ObjCIvarRegion::getValueType() const { return getDecl()->getType(); }
 
 QualType CXXBaseObjectRegion::getValueType() const {
   return QualType(getDecl()->getTypeForDecl(), 0);
@@ -251,26 +249,25 @@ void 
ObjCStringRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
   ID.AddPointer(superRegion);
 }
 
-void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
- const Expr *Ex, unsigned cnt,
- const MemRegion *superRegion) {
+void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID &ID, const Expr *Ex,
+ unsigned cnt, const MemRegion *superRegion) {
   ID.AddInteger(static_cast(AllocaRegionKind));
   ID.AddPointer(Ex);
   ID.AddInteger(cnt);
   ID.AddPointer(superRegion);
 }
 
-void AllocaRegion::Profile(llvm::FoldingSetNodeID& ID) const {
+void AllocaRegion::Profile(llvm::FoldingSetNodeID &ID) const {
   ProfileRegion(ID, Ex, Cnt, superRegion);
 }
 
-void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID& ID) const {
+void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID &ID) const {
   CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion);
 }
 
-void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
+void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
   const CompoundLiteralExpr *CL,
-  const MemRegion* superRegion) {
+  const MemRegion *superRegion) {
   ID.AddInteger(static_cast(CompoundLiteralRegionKind));
   ID.AddPointer(CL);
   ID.AddPointer(superRegion);
@@ -292,9 +289,9 @@ void FieldRegion::Profile(llvm::FoldingSetNodeID &ID) const 
{
   ProfileRegion(ID, getDecl(), superRegion);
 }
 
-void ObjCIvarRegion

[clang] nolock/noalloc attributes (PR #84983)

2024-03-13 Thread via cfe-commits


@@ -4912,3 +4922,279 @@ void AutoType::Profile(llvm::FoldingSetNodeID &ID, 
const ASTContext &Context) {
   Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
   getTypeConstraintConcept(), getTypeConstraintArguments());
 }
+
+FunctionEffect::~FunctionEffect() = default;
+
+bool FunctionEffect::diagnoseConversion(bool Adding, QualType OldType,
+FunctionEffectSet OldFX,
+QualType NewType,
+FunctionEffectSet NewFX) const {
+  return false;
+}
+
+bool FunctionEffect::diagnoseRedeclaration(bool Adding,
+   const FunctionDecl &OldFunction,
+   FunctionEffectSet OldFX,
+   const FunctionDecl &NewFunction,
+   FunctionEffectSet NewFX) const {
+  return false;
+}
+
+bool FunctionEffect::diagnoseMethodOverride(bool Adding,
+const CXXMethodDecl &OldMethod,
+FunctionEffectSet OldFX,
+const CXXMethodDecl &NewMethod,
+FunctionEffectSet NewFX) const {
+  return false;
+}
+
+bool FunctionEffect::canInferOnDecl(const Decl *Caller,
+FunctionEffectSet CallerFX) const {
+  return false;
+}
+
+bool FunctionEffect::diagnoseFunctionCall(bool Direct, const Decl *Caller,
+  FunctionEffectSet CallerFX,
+  CalleeDeclOrType Callee,
+  FunctionEffectSet CalleeFX) const {
+  return false;
+}
+
+const NoLockNoAllocEffect &NoLockNoAllocEffect::nolock_instance() {
+  static NoLockNoAllocEffect global(kNoLockTrue, "nolock");
+  return global;
+}

Sirraide wrote:

> another limitation of AttributedType is that it doesn't seem to hold anything 
> more than the attribute kind

The attribute itself appears to usually be stored in an `AttributedTypeLoc` 
rather than as part of the type itself. 

> two bugs where the sugar gets stripped, e.g. on an auto lambda

It seems we’re taking care to try and preserve `AttributedType`s in several 
places, so that does sound like it might be a bug; we should probably fix those 
(unless there’s a good reason why we’re stripping the attributes there).

> I got some guidance that the `true` forms of the attributes made sense as 
> part of the canonical type

I agree that that makes sense, yeah.

> Even if FunctionEffect turns out to be just some bits controlling details of 
> the behavior, rather than a vtable, it's still attractive to me to 
> encapsulate it into a uniqued object with methods, to centralize all those 
> behaviors.

I’ll take another look at how it’s currently used; I’d also like to hear what 
other people (for instance Aaron) have to say about this; I already pinged him 
in one of the comments below that’s also about this.

https://github.com/llvm/llvm-project/pull/84983
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] ccd1608 - Diagnose misuse of the cleanup attribute (#80040)

2024-03-13 Thread via cfe-commits

Author: Bhuminjay Soni
Date: 2024-03-13T12:28:25-04:00
New Revision: ccd16085f70105d457f052543d731dd51089945b

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

LOG: Diagnose misuse of the cleanup attribute (#80040)

This pull request fixes #79443 when the cleanup attribute is intended to
be applied to a variable declaration, passing its address to a specified
function. The problem arises when standard functions like free,
closedir, fclose, etc., are used incorrectly with this attribute,
leading to incorrect behavior.

Fixes #79443

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaDeclAttr.cpp
clang/test/Sema/attr-cleanup.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 64a9fe0d8bcc48..7173c1400f53f4 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -237,6 +237,10 @@ Improvements to Clang's diagnostics
 - Clang now diagnoses lambda function expressions being implicitly cast to 
boolean values, under ``-Wpointer-bool-conversion``.
   Fixes #GH82512.
 
+- Clang now provides improved warnings for the ``cleanup`` attribute to detect 
misuse scenarios,
+  such as attempting to call ``free`` on an unallocated object. Fixes
+  `#79443 `_.
+
 Improvements to Clang's time-trace
 --
 

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d6ab2b0c2def99..4a853119a2bb8f 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2152,14 +2152,15 @@ class Sema final {
 
   bool IsLayoutCompatible(QualType T1, QualType T2) const;
 
+  bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
+ const FunctionProtoType *Proto);
+
 private:
   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
 const ArraySubscriptExpr *ASE = nullptr,
 bool AllowOnePastEnd = true, bool IndexNegated = 
false);
   void CheckArrayAccess(const Expr *E);
 
-  bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
- const FunctionProtoType *Proto);
   bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
ArrayRef Args);
   bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,

diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index e3da3e606435f4..ec00fdf3f88d9e 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -3787,6 +3787,30 @@ static void handleCleanupAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   << NI.getName() << ParamTy << Ty;
 return;
   }
+  VarDecl *VD = cast(D);
+  // Create a reference to the variable declaration. This is a fake/dummy
+  // reference.
+  DeclRefExpr *VariableReference = DeclRefExpr::Create(
+  S.Context, NestedNameSpecifierLoc{}, FD->getLocation(), VD, false,
+  DeclarationNameInfo{VD->getDeclName(), VD->getLocation()}, VD->getType(),
+  VK_LValue);
+
+  // Create a unary operator expression that represents taking the address of
+  // the variable. This is a fake/dummy expression.
+  Expr *AddressOfVariable = UnaryOperator::Create(
+  S.Context, VariableReference, UnaryOperatorKind::UO_AddrOf,
+  S.Context.getPointerType(VD->getType()), VK_PRValue, OK_Ordinary, Loc,
+  +false, FPOptionsOverride{});
+
+  // Create a function call expression. This is a fake/dummy call expression.
+  CallExpr *FunctionCallExpression =
+  CallExpr::Create(S.Context, E, ArrayRef{AddressOfVariable},
+   S.Context.VoidTy, VK_PRValue, Loc, FPOptionsOverride{});
+
+  if (S.CheckFunctionCall(FD, FunctionCallExpression,
+  FD->getType()->getAs())) {
+return;
+  }
 
   D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD));
 }

diff  --git a/clang/test/Sema/attr-cleanup.c b/clang/test/Sema/attr-cleanup.c
index 2c38687622c2bb..95baf2e675a086 100644
--- a/clang/test/Sema/attr-cleanup.c
+++ b/clang/test/Sema/attr-cleanup.c
@@ -1,7 +1,7 @@
-// RUN: %clang_cc1 %s -verify -fsyntax-only
+// RUN: %clang_cc1 -Wfree-nonheap-object -fsyntax-only -verify %s
 
 void c1(int *a);
-
+typedef __typeof__(sizeof(0)) size_t;
 extern int g1 __attribute((cleanup(c1))); // expected-warning {{'cleanup' 
attribute only applies to local variables}}
 int g2 __attribute((cleanup(c1))); // expected-warning {{'cleanup' attribute 
only applies to local variables}}
 static int g3 __attribute((cleanup(c1))); // expected-warning {{'cleanup' 
attribute only applies to local variables}}
@@ -48,3 +48,27 @@ void t6(void) {
 }
 
 void t7(__attribute__((c

[clang] Diagnose misuse of the cleanup attribute (PR #80040)

2024-03-13 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman closed 
https://github.com/llvm/llvm-project/pull/80040
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [HLSL] Add -HV option translation to clang-dxc.exe (PR #83938)

2024-03-13 Thread Chris B via cfe-commits

https://github.com/llvm-beanz edited 
https://github.com/llvm/llvm-project/pull/83938
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [HLSL] Add -HV option translation to clang-dxc.exe (PR #83938)

2024-03-13 Thread Chris B via cfe-commits

https://github.com/llvm-beanz commented:

Minor suggestion about the diagnostic.

@MaskRay do you have any thoughts about a follow-up change to add a 
`DriverOptions` structure so that we could use argument marshalling for driver 
options?

https://github.com/llvm/llvm-project/pull/83938
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [HLSL] Add -HV option translation to clang-dxc.exe (PR #83938)

2024-03-13 Thread Chris B via cfe-commits


@@ -8545,6 +8545,11 @@ def dxc_entrypoint : Option<["--", "/", "-"], "E", 
KIND_JOINED_OR_SEPARATE>,
  Group,
  Visibility<[DXCOption]>,
  HelpText<"Entry point name">;
+def dxc_hlsl_version : Option<["/", "-"], "HV", KIND_JOINED_OR_SEPARATE>,
+ Group,
+ Visibility<[DXCOption]>,
+ HelpText<"HLSL Version">,
+ NormalizedValues<["2016", "2017", "2018", "2021", 
"202x"]>;

llvm-beanz wrote:

In the current state of this patch I don't think this does anything. I don't 
think the `Values` or `NormalizedValues` stuff really do anything (other than 
maybe populating the help spew) if you're not using the marshalling 
infrastructure 
(https://clang.llvm.org/docs/InternalsManual.html#option-marshalling-infrastructure).

We don't currently have a `DriverOptions` construct, so driver-only options 
can't use the marshalling stuff, which is unfortunate.

I think for the purposes of this change we should probably go with the 
direction in this PR and revisit marshalling later.

https://github.com/llvm/llvm-project/pull/83938
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [HLSL] Add -HV option translation to clang-dxc.exe (PR #83938)

2024-03-13 Thread Chris B via cfe-commits


@@ -753,6 +753,9 @@ def err_drv_hlsl_bad_shader_required_in_target : Error<
 
 def err_drv_hlsl_bad_shader_unsupported : Error<
   "%select{shader model|Vulkan environment|shader stage}0 '%1' in target '%2' 
is invalid for HLSL code generation">;
+def err_drv_hlsl_dxc_bad_argument_value : Error<

llvm-beanz wrote:

Can we use `err_drv_invalid_value` instead? I don't think there is any reason 
the error needs to say `dxc` in the text.

https://github.com/llvm/llvm-project/pull/83938
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Turn 'counted_by' into a type attribute and parse it into 'CountAttributedType' (PR #78000)

2024-03-13 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman approved this pull request.

Thank you for this, it's exciting to see more bounds safety being added to 
Clang!

I think everything looks good to me (we can clean up any surprises in 
follow-ups at this point). I'm presuming you'll add a release note & docs once 
more of the functionality is place?

https://github.com/llvm/llvm-project/pull/78000
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] [Sema] Fix bug in `_Complex float`+`int` arithmetic (PR #83063)

2024-03-13 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman approved this pull request.

LGTM, thank you for the fix!

https://github.com/llvm/llvm-project/pull/83063
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] AArch64: add __builtin_arm_trap (PR #85054)

2024-03-13 Thread Daniel Kiss via cfe-commits

https://github.com/DanielKristofKiss approved this pull request.

Maybe a line or two in the `clang/docs/LanguageExtensions.rst` would be useful.

https://github.com/llvm/llvm-project/pull/85054
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 69afb9d - [Clang] [Sema] Fix bug in `_Complex float`+`int` arithmetic (#83063)

2024-03-13 Thread via cfe-commits

Author: Sirraide
Date: 2024-03-13T17:39:23+01:00
New Revision: 69afb9d7875d79fdacaaa2f22b5ee3a06faf5373

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

LOG: [Clang] [Sema] Fix bug in `_Complex float`+`int` arithmetic (#83063)

C23 6.3.1.8 ‘Usual arithmetic conversions’ p1 states (emphasis mine): 
> Otherwise, if the corresponding real type of either operand is
`float`, the other operand is converted, *without change of type
domain*, to a type whose corresponding real type is `float`.

‘type domain’ here refers to `_Complex` vs real (i.e. non-`_Complex`);
there is another clause that states the same for `double`.

Consider the following code:
```c++
_Complex float f;
int x;
f / x;
```

After talking this over with @AaronBallman, we came to the conclusion
that `x` should be converted to `float` and *not* `_Complex float` (that
is, we should perform a division of `_Complex float / float`, and *not*
`_Complex float / _Complex float`; the same also applies to `-+*`). This
was already being done correctly for cases where `x` was already a
`float`; it’s just mixed `_Complex float`+`int` operations that
currently suffer from this problem.

This pr removes the extra `FloatingRealToComplex` conversion that we
were erroneously inserting and adds some tests to make sure we’re
actually doing `_Complex float / float` and not `_Complex float /
_Complex float` (and analogously for `double` and `-+*`).

The only exception here is `float / _Complex float`, which calls a
library function (`__divsc3`) that takes 4 `float`s, so we end up having
to convert the `float` to a `_Complex float` after all (and analogously
for `double`); I don’t believe there is a way around this.

Lastly, we were also missing tests for `_Complex` arithmetic at compile
time, so this adds some tests for that as well.

Added: 
clang/test/CodeGen/complex-math-mixed.c
clang/test/Sema/complex-arithmetic.c

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaExpr.cpp
clang/test/CodeGen/volatile.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7173c1400f53f4..c5488e8742f611 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -278,6 +278,13 @@ Bug Fixes in This Version
 - Clang now correctly generates overloads for bit-precise integer types for
   builtin operators in C++. Fixes #GH82998.
 
+- When performing mixed arithmetic between ``_Complex`` floating-point types 
and integers,
+  Clang now correctly promotes the integer to its corresponding real 
floating-point
+  type only rather than to the complex type (e.g. ``_Complex float / int`` is 
now evaluated
+  as ``_Complex float / float`` rather than ``_Complex float / _Complex 
float``), as mandated
+  by the C standard. This significantly improves codegen of `*` and `/` 
especially.
+  Fixes (`#31205 `_).
+
 Bug Fixes to Compiler Builtins
 ^^
 

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 93f82e68ab6440..8725b09f8546cf 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -1099,12 +1099,13 @@ ExprResult Sema::DefaultVariadicArgumentPromotion(Expr 
*E, VariadicCallType CT,
   return E;
 }
 
-/// Converts an integer to complex float type.  Helper function of
+/// Convert complex integers to complex floats and real integers to
+/// real floats as required for complex arithmetic. Helper function of
 /// UsualArithmeticConversions()
 ///
 /// \return false if the integer expression is an integer type and is
-/// successfully converted to the complex type.
-static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
+/// successfully converted to the (complex) float type.
+static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr,
   ExprResult &ComplexExpr,
   QualType IntTy,
   QualType ComplexTy,
@@ -1114,8 +1115,6 @@ static bool handleIntegerToComplexFloatConversion(Sema 
&S, ExprResult &IntExpr,
   if (IntTy->isIntegerType()) {
 QualType fpTy = ComplexTy->castAs()->getElementType();
 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
-IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
-  CK_FloatingRealToComplex);
   } else {
 assert(IntTy->isComplexIntegerType());
 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
@@ -1160,11 +1159,11 @@ static QualType handleComplexFloatConversion(Sema &S, 
ExprResult &Shorter,
 static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
 

[clang] [Clang] [Sema] Fix bug in `_Complex float`+`int` arithmetic (PR #83063)

2024-03-13 Thread via cfe-commits

https://github.com/Sirraide closed 
https://github.com/llvm/llvm-project/pull/83063
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [DXIL] `exp`, `any`, `lerp`, & `rcp` Intrinsic Lowering (PR #84526)

2024-03-13 Thread Farzon Lotfi via cfe-commits


@@ -18015,38 +18015,11 @@ Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned 
BuiltinID,
 Value *X = EmitScalarExpr(E->getArg(0));
 Value *Y = EmitScalarExpr(E->getArg(1));
 Value *S = EmitScalarExpr(E->getArg(2));
-llvm::Type *Xty = X->getType();
-llvm::Type *Yty = Y->getType();
-llvm::Type *Sty = S->getType();
-if (!Xty->isVectorTy() && !Yty->isVectorTy() && !Sty->isVectorTy()) {
-  if (Xty->isFloatingPointTy()) {
-auto V = Builder.CreateFSub(Y, X);
-V = Builder.CreateFMul(S, V);
-return Builder.CreateFAdd(X, V, "dx.lerp");
-  }
-  llvm_unreachable("Scalar Lerp is only supported on floats.");
-}
-// A VectorSplat should have happened
-assert(Xty->isVectorTy() && Yty->isVectorTy() && Sty->isVectorTy() &&
-   "Lerp of vector and scalar is not supported.");
-
-[[maybe_unused]] auto *XVecTy =
-E->getArg(0)->getType()->getAs();
-[[maybe_unused]] auto *YVecTy =
-E->getArg(1)->getType()->getAs();
-[[maybe_unused]] auto *SVecTy =
-E->getArg(2)->getType()->getAs();
-// A HLSLVectorTruncation should have happend
-assert(XVecTy->getNumElements() == YVecTy->getNumElements() &&
-   XVecTy->getNumElements() == SVecTy->getNumElements() &&
-   "Lerp requires vectors to be of the same size.");
-assert(XVecTy->getElementType()->isRealFloatingType() &&
-   XVecTy->getElementType() == YVecTy->getElementType() &&
-   XVecTy->getElementType() == SVecTy->getElementType() &&
-   "Lerp requires float vectors to be of the same type.");
+if (!E->getArg(0)->getType()->hasFloatingRepresentation())

farzonl wrote:

`X->getType()` is a `Type` pointer. `E->getArg(0)->getType()` is a `QualType`. 
Only QualTypes allow us to use `hasFloatingRepresentation`

https://github.com/llvm/llvm-project/pull/84526
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [DXIL] `exp`, `any`, `lerp`, & `rcp` Intrinsic Lowering (PR #84526)

2024-03-13 Thread Farzon Lotfi via cfe-commits

https://github.com/farzonl edited 
https://github.com/llvm/llvm-project/pull/84526
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][modules] giving the __stddef_ headers their own modules can cause redeclaration errors with -fbuiltin-headers-in-system-modules (PR #84127)

2024-03-13 Thread Ben Langmuir via cfe-commits


@@ -301,10 +301,9 @@ bool Module::directlyUses(const Module *Requested) {
 if (Requested->isSubModuleOf(Use))
   return true;
 
-  // Anyone is allowed to use our builtin stdarg.h and stddef.h and their
-  // accompanying modules.
-  if (Requested->getTopLevelModuleName() == "_Builtin_stdarg" ||
-  Requested->getTopLevelModuleName() == "_Builtin_stddef")
+  // Anyone is allowed to use our builtin stddef.h and its accompanying 
modules.
+  if (Requested->fullModuleNameIs({"_Builtin_stddef", "max_align_t"}) ||
+  Requested->fullModuleNameIs({"_Builtin_stddef_wint_t"}))

benlangmuir wrote:

Why was stdarg removed?

https://github.com/llvm/llvm-project/pull/84127
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [DXIL] `exp`, `any`, `lerp`, & `rcp` Intrinsic Lowering (PR #84526)

2024-03-13 Thread Farzon Lotfi via cfe-commits

https://github.com/farzonl edited 
https://github.com/llvm/llvm-project/pull/84526
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][nullability] allow _Nonnull etc on nullable class types (PR #82705)

2024-03-13 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall updated 
https://github.com/llvm/llvm-project/pull/82705

>From eccc46840e343e7ba15200cd4b81316a51c46943 Mon Sep 17 00:00:00 2001
From: Sam McCall 
Date: Thu, 22 Feb 2024 16:00:44 +0100
Subject: [PATCH 1/4] [clang][nullability] allow _Nonnull etc on nullable class
 types

This enables clang and external nullability checkers to make use of
these annotations on nullable C++ class types like unique_ptr.

These types are recognized by the presence of the _Nullable attribute.
Nullable standard library types implicitly receive this attribute.

Existing static warnings for raw pointers are extended to smart pointers:

- nullptr used as return value or argument for non-null functions
  (`-Wnonnull`)
- assigning or initializing nonnull variables with nullable values
  (`-Wnullable-to-nonnull-conversion`)

It doesn't implicitly add these attributes based on the assume_nonnull
pragma, nor warn on missing attributes where the pragma would apply them.
I'm not confident that the pragma's current behavior will work well for
C++ (where type-based metaprogramming is much more common than C/ObjC).
We'd like to revisit this once we have more implementation experience.

Support can be detected as `__has_feature(nullability_on_classes)`.
This is needed for back-compatibility, as previously clang would issue a
hard error when _Nullable appears on a smart pointer.

UBSan's `-fsanitize=nullability` will not check smart-pointer types.
It can be made to do so by synthesizing calls to `operator bool`, but
that's left for future work.
---
 clang/include/clang/Basic/Attr.td  |  3 +-
 clang/include/clang/Basic/AttrDocs.td  | 16 +++
 clang/include/clang/Basic/Features.def |  1 +
 clang/include/clang/Parse/Parser.h |  1 +
 clang/include/clang/Sema/Sema.h|  3 ++
 clang/lib/AST/Type.cpp | 29 +++-
 clang/lib/CodeGen/CGCall.cpp   |  3 +-
 clang/lib/CodeGen/CodeGenFunction.cpp  |  3 +-
 clang/lib/Parse/ParseDeclCXX.cpp   | 33 ++
 clang/lib/Sema/SemaAttr.cpp| 12 +
 clang/lib/Sema/SemaChecking.cpp|  9 
 clang/lib/Sema/SemaDecl.cpp|  4 +-
 clang/lib/Sema/SemaDeclAttr.cpp| 18 
 clang/lib/Sema/SemaInit.cpp|  5 +++
 clang/lib/Sema/SemaOverload.cpp|  7 +++
 clang/lib/Sema/SemaTemplate.cpp|  1 +
 clang/lib/Sema/SemaType.cpp| 18 ++--
 clang/test/SemaCXX/nullability.cpp | 62 +-
 18 files changed, 199 insertions(+), 29 deletions(-)

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index fa191c7378dba4..f75aa126cbb939 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -2156,9 +2156,10 @@ def TypeNonNull : TypeAttr {
   let Documentation = [TypeNonNullDocs];
 }
 
-def TypeNullable : TypeAttr {
+def TypeNullable : DeclOrTypeAttr {
   let Spellings = [CustomKeyword<"_Nullable">];
   let Documentation = [TypeNullableDocs];
+//  let Subjects = SubjectList<[CXXRecord], ErrorDiag>;
 }
 
 def TypeNullableResult : TypeAttr {
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index b96fbddd51154c..8c248fb052f19e 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -4096,6 +4096,11 @@ non-underscored keywords. For example:
   @property (assign, nullable) NSView *superview;
   @property (readonly, nonnull) NSArray *subviews;
 @end
+
+As well as built-in pointer types, ithe nullability attributes can be attached
+to nullable types from the C++ standard library such as ``std::unique_ptr`` and
+``std::function``, as well as C++ classes marked with the ``_Nullable``
+attribute.
   }];
 }
 
@@ -4130,6 +4135,17 @@ The ``_Nullable`` nullability qualifier indicates that a 
value of the
 int fetch_or_zero(int * _Nullable ptr);
 
 a caller of ``fetch_or_zero`` can provide null.
+
+The ``_Nullable`` attribute on classes indicates that the given class can
+represent null values, and so the ``_Nullable``, ``_Nonnull`` etc qualifiers
+make sense for this type. For example:
+
+  .. code-block:: c
+
+class _Nullable ArenaPointer { ... };
+
+ArenaPointer _Nonnull x = ...;
+ArenaPointer _Nullable y = nullptr;
   }];
 }
 
diff --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index 5fad5fc3623cb6..7c0755b7318306 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -94,6 +94,7 @@ EXTENSION(define_target_os_macros,
 FEATURE(enumerator_attributes, true)
 FEATURE(nullability, true)
 FEATURE(nullability_on_arrays, true)
+FEATURE(nullability_on_classes, true)
 FEATURE(nullability_nullable_result, true)
 FEATURE(memory_sanitizer,
 LangOpts.Sanitize.hasOneOf(SanitizerKind::Memory |
diff --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index 071520f535bc95..3d858

[clang] [llvm] [Clang][BPF] Allow sign/zero extension for call parameters with int/uint types (PR #84874)

2024-03-13 Thread via cfe-commits

yonghong-song wrote:

> But **after this patch**, the two numbers get the same result as before this 
> patch. I don't see ld_imm64 becoming a mov instruction, as well as explicit 
> zero extension for 'unsigned int'. Is that expected?

IIUC, we have the same result before and after this patch. So this patch didn't 
make things worse or better. So didn't really solve your problem for 'unsigned 
int'.

https://github.com/llvm/llvm-project/pull/84874
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sema] Properly get captured 'this' pointer in lambdas with an explicit object parameter in constant evaluator (PR #81102)

2024-03-13 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman approved this pull request.

LGTM aside from some coding style guideline nits

https://github.com/llvm/llvm-project/pull/81102
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sema] Properly get captured 'this' pointer in lambdas with an explicit object parameter in constant evaluator (PR #81102)

2024-03-13 Thread Aaron Ballman via cfe-commits


@@ -8485,6 +8485,53 @@ class LValueExprEvaluator
 };
 } // end anonymous namespace
 
+/// Get an lvalue to a field of a lambda's closure type.
+static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
+const CXXMethodDecl *MD, const FieldDecl *FD,
+bool LValueToRValueConversion) {
+  // Static lambda function call operators can't have captures. We already
+  // diagnosed this, so bail out here.
+  if (MD->isStatic()) {
+assert(Info.CurrentCall->This == nullptr &&
+   "This should not be set for a static call operator");
+return false;
+  }
+
+  // Start with 'Result' referring to the complete closure object...
+  if (MD->isExplicitObjectMemberFunction()) {
+// Self may be passed by reference or by value.
+auto *Self = MD->getParamDecl(0);

AaronBallman wrote:

Should spell this type out as well

https://github.com/llvm/llvm-project/pull/81102
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sema] Properly get captured 'this' pointer in lambdas with an explicit object parameter in constant evaluator (PR #81102)

2024-03-13 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman edited 
https://github.com/llvm/llvm-project/pull/81102
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sema] Properly get captured 'this' pointer in lambdas with an explicit object parameter in constant evaluator (PR #81102)

2024-03-13 Thread Aaron Ballman via cfe-commits


@@ -8485,6 +8485,53 @@ class LValueExprEvaluator
 };
 } // end anonymous namespace
 
+/// Get an lvalue to a field of a lambda's closure type.
+static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
+const CXXMethodDecl *MD, const FieldDecl *FD,
+bool LValueToRValueConversion) {
+  // Static lambda function call operators can't have captures. We already
+  // diagnosed this, so bail out here.
+  if (MD->isStatic()) {
+assert(Info.CurrentCall->This == nullptr &&
+   "This should not be set for a static call operator");
+return false;
+  }
+
+  // Start with 'Result' referring to the complete closure object...
+  if (MD->isExplicitObjectMemberFunction()) {
+// Self may be passed by reference or by value.
+auto *Self = MD->getParamDecl(0);
+if (Self->getType()->isReferenceType()) {
+  APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
+  Result.setFrom(Info.Ctx, *RefValue);
+} else {
+  auto *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
+  auto *Frame =
+  Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
+  .first;
+  auto Version = Info.CurrentCall->Arguments.Version;

AaronBallman wrote:

Should spell these types out because they're not spelled out in the 
initialization.

https://github.com/llvm/llvm-project/pull/81102
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sema] Properly get captured 'this' pointer in lambdas with an explicit object parameter in constant evaluator (PR #81102)

2024-03-13 Thread Aaron Ballman via cfe-commits


@@ -9037,45 +9055,46 @@ class PointerExprEvaluator
 return Error(E);
   }
   bool VisitCXXThisExpr(const CXXThisExpr *E) {
-// Can't look at 'this' when checking a potential constant expression.
-if (Info.checkingPotentialConstantExpression())
-  return false;
-if (!Info.CurrentCall->This) {
+auto DiagnoseInvalidUseOfThis = [&] {
   if (Info.getLangOpts().CPlusPlus11)
 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
   else
 Info.FFDiag(E);
+};
+
+// Can't look at 'this' when checking a potential constant expression.
+if (Info.checkingPotentialConstantExpression())
   return false;
+
+const bool IsExplicitLambda =

AaronBallman wrote:

```suggestion
bool IsExplicitLambda =
```

https://github.com/llvm/llvm-project/pull/81102
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][modules] giving the __stddef_ headers their own modules can cause redeclaration errors with -fbuiltin-headers-in-system-modules (PR #84127)

2024-03-13 Thread Ben Langmuir via cfe-commits

benlangmuir wrote:

>> I'm not excited by the complexity we are moving toward with the builtin 
>> headers. But I don't have any alternatives.
> When -fbuiltin-headers-in-system-modules goes away, things become simpler 
> than they were since modules were introduced.

Even for the case with `-fbuiltin-headers-in-system-modules` things aren't any 
more complex than they were before https://reviews.llvm.org/D159064 except for 
the fundamental complexity of having two modes to build in, and hopefully 
-fbuiltin-headers-in-system-modules goes away.

https://github.com/llvm/llvm-project/pull/84127
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][AArch64] Warn when calling streaming/non-streaming about vect… (PR #79842)

2024-03-13 Thread Dinar Temirbulatov via cfe-commits

https://github.com/dtemirbulatov updated 
https://github.com/llvm/llvm-project/pull/79842

>From af323998a63a72f569d543cf5167d5d28e784682 Mon Sep 17 00:00:00 2001
From: Dinar Temirbulatov 
Date: Mon, 29 Jan 2024 14:43:13 +
Subject: [PATCH 1/9] [Clang][AArch64] Warn when calling
 streaming/non-streaming about vector size might be different.

The compiler doesn't know in advance if the streaming and non-streaming
vector-lengths are different, so it should be safe to give a warning diagnostic
to warn the user about possible undefined behaviour. If the user knows
the vector lengths are equal, they can disable the warning separately.
---
 .../clang/Basic/DiagnosticSemaKinds.td| 24 +++
 clang/lib/Sema/SemaChecking.cpp   | 42 
 clang/test/Sema/aarch64-sme-func-attrs.c  | 68 ++-
 3 files changed, 132 insertions(+), 2 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 24d32cb87c89e2..37fea5746936c7 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -3717,6 +3717,30 @@ def err_sme_definition_using_za_in_non_sme_target : 
Error<
   "function using ZA state requires 'sme'">;
 def err_sme_definition_using_zt0_in_non_sme2_target : Error<
   "function using ZT0 state requires 'sme2'">;
+def warn_sme_streaming_caller_pass_args_to_non_streaming : Warning<
+  "streaming caller passes a VL-dependent argument to non-streaming callee, "
+  "the streaming and non-streaming vector lengths may be different">,
+  InGroup;
+def warn_sme_non_streaming_callee_returns_to_streaming : Warning<
+  "non-streaming callee returns a VL-dependent value to streaming caller, "
+  "the streaming and non-streaming vector lengths may be different">,
+  InGroup;
+def warn_sme_non_streaming_caller_pass_args_to_streaming : Warning<
+  "non-streaming caller passes a VL-dependent argument to streaming callee, "
+  "the streaming and non-streaming vector lengths may be different">,
+  InGroup;
+def warn_sme_non_streaming_caller_returns_to_streaming : Warning<
+  "non-streaming callee returns a VL-dependent value to streaming caller, "
+  "the streaming and non-streaming vector lengths may be different">,
+  InGroup;
+def warn_sme_locally_streaming_has_vl_args : Warning<
+  "non-streaming callee receives a VL-dependent argument and the callee has an 
arm_locally_streaming attribute, "
+  "the streaming and non-streaming vector lengths may be different">,
+  InGroup;
+def warn_sme_locally_streaming_returns_vl : Warning<
+  "non-streaming callee returns a VL-dependent value and the callee has an 
arm_locally_streaming attribute, "
+  "the streaming and non-streaming vector lengths may be different">,
+  InGroup;
 def err_conflicting_attributes_arm_state : Error<
   "conflicting attributes for state '%0'">;
 def err_unknown_arm_state : Error<
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 502b24bcdf8b42..e668a45c69e5f9 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -7480,6 +7480,7 @@ void Sema::checkCall(NamedDecl *FDecl, const 
FunctionProtoType *Proto,
 // For variadic functions, we may have more args than parameters.
 // For some K&R functions, we may have less args than parameters.
 const auto N = std::min(Proto->getNumParams(), Args.size());
+bool AnyScalableArgs = false;
 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
   // Args[ArgIdx] can be null in malformed code.
   if (const Expr *Arg = Args[ArgIdx]) {
@@ -7493,6 +7494,8 @@ void Sema::checkCall(NamedDecl *FDecl, const 
FunctionProtoType *Proto,
   checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
 
 QualType ParamTy = Proto->getParamType(ArgIdx);
+if (ParamTy->isSizelessVectorType())
+  AnyScalableArgs = true;
 QualType ArgTy = Arg->getType();
 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
   ArgTy, ParamTy);
@@ -7513,6 +7516,45 @@ void Sema::checkCall(NamedDecl *FDecl, const 
FunctionProtoType *Proto,
   }
 }
 
+auto *CallerFD = dyn_cast(CurContext);
+if (FD && CallerFD && Context.getTargetInfo().hasFeature("sme") &&
+!FD->getBuiltinID()) {
+  // If the callee has an AArch64 SME __arm_locally_streaming attribute
+  // warn if this function returns VL-based value or pass any such 
argument,
+  // the streaming and non-streaming vector lengths may be different.
+  ArmStreamingType CalleeFnType = getArmStreamingFnType(FD);
+  ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
+  if (FD->hasAttr() &&
+  CallerFnType != ArmStreaming) {
+if (AnyScalableArgs)
+  Diag(Loc, diag::warn_sme_locally_streaming_has_vl_args);
+if (FD->getReturnType()->isSizelessVectorType())
+  Diag(Loc, diag::warn

[clang] [llvm] [Clang][BPF] Allow sign/zero extension for call parameters with int/uint types (PR #84874)

2024-03-13 Thread via cfe-commits

yonghong-song wrote:

> @yonghong-song , if I understand @efriedma-quic correctly (thank you for 
> explanations), the following fragment is not RISC-V ABI conformant:
> 
> ```
> $ cat u.c
> void foo(unsigned);
> void bar(unsigned a, unsigned b) {
>   foo(a + b);
> }
> 
>1:   67 02 00 00 20 00 00 00 r2 <<= 0x20
>2:   77 02 00 00 20 00 00 00 r2 >>= 0x20
>3:   bf 21 00 00 00 00 00 00 r1 = r2
>4:   85 10 00 00 ff ff ff ff call -0x1
> ```
> 
> The `r1` would be zero extended, while to be ABI conformant it has to be sign 
> extended, as for RV64 the 31-st bit should be the same as upper 32 bits. The 
> fact that decision to zero or sign extend the argument depends on the 
> architecture means that this extension has to be done at JIT time (meaning 
> that BTF is mandatory) or be a part of kfunc.

If the verifier keeps the same verifier_zext flag for 'r1 = r2', then we should 
be okay. If not, then we have a problem. I need to double check.

I guess I will remove UInt support from this patch since it does not improve 
anything and may risk break something. We can add it back later if needed and 
other issue (with riscv) is clarified/resolved.

https://github.com/llvm/llvm-project/pull/84874
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] nolock/noalloc attributes (PR #84983)

2024-03-13 Thread Andrew Pinski via cfe-commits

pinskia wrote:

One question since the attribute is applied to types is there a way to get the 
nolock/noalloc from type?.
e.g.
```
template [[nolock(T)]] void f(T a) { a(); }
```
Will the above work or is there no way to implement that currently?


Since you mention it is attached to the type, is it mangled then differently. 
e.g.:
```
template [[nolock]] void f(T a) { a(); }
[[nolock(true)]] void g(void);
[[nolock(false)]] void h(void);
void m()
{
  f(g);
  f(h);
}
```
Does the above f calls to 2 different functions?
Or is the nolock/noalloc dropped from function types for templates/auto usage?
What about decltype (or the GNU extension __typeof__) usage is it dropped there 
too?

https://github.com/llvm/llvm-project/pull/84983
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [RISC-V] Add CSR read/write builtins (PR #85091)

2024-03-13 Thread Eli Friedman via cfe-commits


@@ -20,6 +20,12 @@ class RISCVBuiltin : 
TargetBuiltin {
 
 let Attributes = [NoThrow, Const] in {
 
//===--===//
+// Zicsr extension.
+//===--===//
+def csrr : RISCVBuiltin<"unsigned long int(unsigned long int)", "zicsr">;

efriedma-quic wrote:

If you want "size_t" or "uintptr_t", please use that, not "unsigned long".

https://github.com/llvm/llvm-project/pull/85091
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][AArch64] Enable fp128 for aarch64 linux target (PR #85070)

2024-03-13 Thread Matthew Devereau via cfe-commits

https://github.com/MDevereau ready_for_review 
https://github.com/llvm/llvm-project/pull/85070
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][AArch64] Enable fp128 for aarch64 linux target (PR #85070)

2024-03-13 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Matthew Devereau (MDevereau)


Changes



---
Full diff: https://github.com/llvm/llvm-project/pull/85070.diff


2 Files Affected:

- (modified) clang/lib/Basic/Targets/OSTargets.h (+1) 
- (modified) clang/test/CodeGenCXX/float128-declarations.cpp (+24) 


``diff
diff --git a/clang/lib/Basic/Targets/OSTargets.h 
b/clang/lib/Basic/Targets/OSTargets.h
index 4366c1149e4053..ba92604b9bcb9a 100644
--- a/clang/lib/Basic/Targets/OSTargets.h
+++ b/clang/lib/Basic/Targets/OSTargets.h
@@ -359,6 +359,7 @@ class LLVM_LIBRARY_VISIBILITY LinuxTargetInfo : public 
OSTargetInfo {
   break;
 case llvm::Triple::x86:
 case llvm::Triple::x86_64:
+case llvm::Triple::aarch64:
   this->HasFloat128 = true;
   break;
 }
diff --git a/clang/test/CodeGenCXX/float128-declarations.cpp 
b/clang/test/CodeGenCXX/float128-declarations.cpp
index 84b8f7f33036b5..79c99ba2796126 100644
--- a/clang/test/CodeGenCXX/float128-declarations.cpp
+++ b/clang/test/CodeGenCXX/float128-declarations.cpp
@@ -26,6 +26,8 @@
 // RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
 // RUN: %clang_cc1 -emit-llvm -triple x86_64-unknown-haiku -std=c++11 \
 // RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
+// RUN: %clang_cc1 -emit-llvm -triple aarch64-linux-gnu -std=c++11 \
+// RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-AARCH64-DAG
 //
 /*  Various contexts where type __float128 can appear. The different check
 prefixes are due to different mangling on X86.  */
@@ -131,3 +133,25 @@ int main(void) {
 // CHECK-X86-DAG: [[F4L:%[a-z0-9]+]] = load fp128, ptr %f4l
 // CHECK-X86-DAG: [[INC:%[a-z0-9]+]] = fadd fp128 [[F4L]], 
0xL3FFF
 // CHECK-X86-DAG: store fp128 [[INC]], ptr %f4l
+
+// CHECK-AARCH64-DAG: @f1f ={{.*}} global fp128 
0xL
+// CHECK-AARCH64-DAG: @f2f ={{.*}} global fp128 
0xL40040333
+// CHECK-AARCH64-DAG: @arr1f ={{.*}} global [10 x fp128]
+// CHECK-AARCH64-DAG: @arr2f ={{.*}} global [3 x fp128] [fp128 
0xLBFFF, fp128 0xLC0008000, 
fp128 0xLC025176592E0]
+// CHECK-AARCH64-DAG: @__const.main.s1 = private unnamed_addr constant 
%struct.S1 { fp128 0xL40060800 }
+// CHECK-AARCH64-DAG: @_ZN12_GLOBAL__N_13f1nE = internal global fp128 
0xL
+// CHECK-AARCH64-DAG: @_ZN12_GLOBAL__N_13f2nE = internal global fp128 
0xL40040800
+// CHECK-AARCH64-DAG: @_ZN12_GLOBAL__N_15arr1nE = internal global [10 x fp128]
+// CHECK-AARCH64-DAG: @_ZN12_GLOBAL__N_15arr2nE = internal global [3 x fp128] 
[fp128 0xL3FFF, fp128 
0xL40008000, fp128 0xL4025176592E0]
+// CHECK-AARCH64-DAG: store fp128 0xLF0AFD0EBFF292DCE42E0B38CDD83F26F, ptr 
%f1l, align 16
+// CHECK-AARCH64-DAG: store fp128 0xL8000, ptr 
%f2l, align 16
+// CHECK-AARCH64-DAG: store fp128 0xL7FFE, ptr 
%f3l, align 16
+// CHECK-AARCH64-DAG: store fp128 0xLBFFF, ptr 
%f5l, align 16
+// CHECK-AARCH64-DAG: [[F4L:%[a-z0-9]+]] = load fp128, ptr %f4l
+// CHECK-AARCH64-DAG: [[INC:%[a-z0-9]+]] = fadd fp128 [[F4L]], 
0xL3FFF
+// CHECK-AARCH64-DAG: store fp128 [[INC]], ptr %f4l
+// CHECK-AARCH64-DAG: define internal noundef fp128 
@_ZN12_GLOBAL__N_16func1nERKg(ptr
+// CHECK-AARCH64-DAG: declare noundef fp128 @_Z6func1fg(fp128 noundef)
+// CHECK-AARCH64-DAG: define linkonce_odr noundef fp128 @_ZN2C16func2cEg(fp128 
noundef %arg)
+// CHECK-AARCH64-DAG: define linkonce_odr noundef fp128 
@_Z6func1tIgET_S0_(fp128 noundef %arg)
+// CHECK-AARCH64-DAG: define linkonce_odr void @_ZN2C1C2Eg(ptr {{[^,]*}} 
%this, fp128 noundef %arg)

``




https://github.com/llvm/llvm-project/pull/85070
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [HLSL] Add -HV option translation to clang-dxc.exe (PR #83938)

2024-03-13 Thread Joshua Batista via cfe-commits


@@ -8545,6 +8545,11 @@ def dxc_entrypoint : Option<["--", "/", "-"], "E", 
KIND_JOINED_OR_SEPARATE>,
  Group,
  Visibility<[DXCOption]>,
  HelpText<"Entry point name">;
+def dxc_hlsl_version : Option<["/", "-"], "HV", KIND_JOINED_OR_SEPARATE>,
+ Group,
+ Visibility<[DXCOption]>,
+ HelpText<"HLSL Version">,
+ NormalizedValues<["2016", "2017", "2018", "2021", 
"202x"]>;

bob80905 wrote:

Populating the help spew seems helpful! I can remove the marshalling part, but 
it seems helpful to leave the rest as is.

https://github.com/llvm/llvm-project/pull/83938
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sema]: Allow flexible arrays in unions and alone in structs (PR #84428)

2024-03-13 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

Separating out some bits of discussion here.

Standardization of flexible arrays in unions
---
We can dispense with this topic quickly: the standard doesn't allow this, if 
the standard should be relaxed then someone needs to write a paper to propose 
it. I can help shepherd the proposal through WG14, but I don't think I have the 
time or the motivation to write the paper myself.

However, what the standard says doesn't matter too much for our discussion 
because it's conforming to support this as an extension.

Supporting flexible arrays in unions as an extension

Personally, I find flexible arrays to be a pretty weird thing to support in a 
union. Unions have a set of members that all overlap, but flexible array 
members are not really members as such, they're a name used to refer to 
trailing storage after the end of the object and don't contribute to the object 
directly (e.g., don't matter for `sizeof`). However, because we support 
zero-sized unions as an extension (https://godbolt.org/z/GG3odEhev), and we 
support zero-sized arrays as an extension (https://godbolt.org/z/q74EoGTWf), 
including in unions (https://godbolt.org/z/EhvTTb9os)... I don't see a 
compelling reason to disallow using flexible array syntax in unions as they're 
morally equivalent. And the same logic applies to structures where the sole 
member is a flexible array (https://godbolt.org/z/KxsPvqo3v).

https://github.com/llvm/llvm-project/pull/84428
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Avoid overflow when dumping unsigned integer values (PR #85060)

2024-03-13 Thread Piotr Zegar via cfe-commits


@@ -408,17 +408,26 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
 /// Stores an option with the check-local name \p LocalName with
 /// integer value \p Value to \p Options.
 template 
-std::enable_if_t>
+std::enable_if_t && std::is_signed::value>
 store(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
   T Value) const {
   storeInt(Options, LocalName, Value);
 }
 
+/// Stores an option with the check-local name \p LocalName with
+/// unsigned integer value \p Value to \p Options.
+template 
+std::enable_if_t::value>
+store(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
+  T Value) const {
+  storeUnsigned(Options, LocalName, Value);
+}
+
 /// Stores an option with the check-local name \p LocalName with
 /// integer value \p Value to \p Options. If the value is empty
 /// stores ``
 template 
-std::enable_if_t>
+std::enable_if_t && std::is_signed::value>

PiotrZSL wrote:

instead of adding new version for optional, just call in this method `store` 
instead of storeInt,

https://github.com/llvm/llvm-project/pull/85060
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Avoid overflow when dumping unsigned integer values (PR #85060)

2024-03-13 Thread Piotr Zegar via cfe-commits

https://github.com/PiotrZSL edited 
https://github.com/llvm/llvm-project/pull/85060
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Avoid overflow when dumping unsigned integer values (PR #85060)

2024-03-13 Thread Piotr Zegar via cfe-commits

https://github.com/PiotrZSL commented:

Missing test (based on some check).


https://github.com/llvm/llvm-project/pull/85060
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Avoid overflow when dumping unsigned integer values (PR #85060)

2024-03-13 Thread Piotr Zegar via cfe-commits


@@ -470,6 +491,8 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
 void storeInt(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
   int64_t Value) const;
 
+void storeUnsigned(ClangTidyOptions::OptionMap &Options,
+   StringRef LocalName, int64_t Value) const;

PiotrZSL wrote:

value should be uint64_t 

https://github.com/llvm/llvm-project/pull/85060
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Avoid overflow when dumping unsigned integer values (PR #85060)

2024-03-13 Thread Piotr Zegar via cfe-commits


@@ -408,17 +408,26 @@ class ClangTidyCheck : public 
ast_matchers::MatchFinder::MatchCallback {
 /// Stores an option with the check-local name \p LocalName with
 /// integer value \p Value to \p Options.
 template 
-std::enable_if_t>
+std::enable_if_t && std::is_signed::value>
 store(ClangTidyOptions::OptionMap &Options, StringRef LocalName,
   T Value) const {
   storeInt(Options, LocalName, Value);

PiotrZSL wrote:

jinstead of using std::is_signed just use:
```
if constexpr(std::is_signed_v)
   storeInt(Options, LocalName, Value);
else
  storeUnsigned(Options, LocalName, Value);
```

https://github.com/llvm/llvm-project/pull/85060
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Avoid overflow when dumping unsigned integer values (PR #85060)

2024-03-13 Thread Piotr Zegar via cfe-commits

https://github.com/PiotrZSL edited 
https://github.com/llvm/llvm-project/pull/85060
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Avoid overflow when dumping unsigned integer values (PR #85060)

2024-03-13 Thread Piotr Zegar via cfe-commits

https://github.com/PiotrZSL edited 
https://github.com/llvm/llvm-project/pull/85060
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Avoid overflow when dumping unsigned integer values (PR #85060)

2024-03-13 Thread Piotr Zegar via cfe-commits

PiotrZSL wrote:

And just one comment, when this check uses max value as "limit", this behavior 
is also a reason why support for optional values were added. For me in this 
case check & description should be updated to handle this config as an 
optional, instead of mentioning max u64 in documentation. As for support for 
unsigned values, that's welcome too regardless.

https://github.com/llvm/llvm-project/pull/85060
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 13ccaf9 - Revert "Reapply "[analyzer] Accept C library functions from the `std` namespace""

2024-03-13 Thread Philip Reames via cfe-commits

Author: Philip Reames
Date: 2024-03-13T10:19:42-07:00
New Revision: 13ccaf9b9d4400bb128b35ff4ac733e4afc3ad1c

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

LOG: Revert "Reapply "[analyzer] Accept C library functions from the `std` 
namespace""

This reverts commit e48d5a838f69e0a8e0ae95a8aed1a8809f45465a.

Fails to build on x86-64 w/gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04)
with the following message:

../llvm-project/clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp:41:28:
 error: declaration of ‘std::unique_ptr 
IsCLibraryFunctionTest::ASTUnit’ changes meaning of ‘ASTUnit’ [-fpermissive]
   41 |   std::unique_ptr ASTUnit;
  |^~~
In file included from 
../llvm-project/clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp:4:
../llvm-project/clang/include/clang/Frontend/ASTUnit.h:89:7: note: ‘ASTUnit’ 
declared here as ‘class clang::ASTUnit’
   89 | class ASTUnit {
  |   ^~~

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
clang/unittests/StaticAnalyzer/CMakeLists.txt
llvm/utils/gn/secondary/clang/unittests/StaticAnalyzer/BUILD.gn

Removed: 
clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp



diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
index b4e1636130ca7c..3432d2648633c2 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -41,8 +41,12 @@ class CallDescription {
 ///  - We also accept calls where the number of arguments or parameters is
 ///greater than the specified value.
 /// For the exact heuristics, see CheckerContext::isCLibraryFunction().
-/// (This mode only matches functions that are declared either directly
-/// within a TU or in the namespace `std`.)
+/// Note that functions whose declaration context is not a TU (e.g.
+/// methods, functions in namespaces) are not accepted as C library
+/// functions.
+/// FIXME: If I understand it correctly, this discards calls where C++ code
+/// refers a C library function through the namespace `std::` via headers
+/// like .
 CLibrary,
 
 /// Matches "simple" functions that are not methods. (Static methods are

diff  --git a/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp 
b/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
index 1a9bff529e9bb1..d6d4cec9dd3d4d 100644
--- a/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp
@@ -87,11 +87,9 @@ bool CheckerContext::isCLibraryFunction(const FunctionDecl 
*FD,
   if (!II)
 return false;
 
-  // C library functions are either declared directly within a TU (the common
-  // case) or they are accessed through the namespace `std` (when they are used
-  // in C++ via headers like ).
-  const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
-  if (!(DC->isTranslationUnit() || DC->isStdNamespace()))
+  // Look through 'extern "C"' and anything similar invented in the future.
+  // If this function is not in TU directly, it is not a C library function.
+  if (!FD->getDeclContext()->getRedeclContext()->isTranslationUnit())
 return false;
 
   // If this function is not externally visible, it is not a C library 
function.

diff  --git a/clang/unittests/StaticAnalyzer/CMakeLists.txt 
b/clang/unittests/StaticAnalyzer/CMakeLists.txt
index db56e77331b821..775f0f8486b8f9 100644
--- a/clang/unittests/StaticAnalyzer/CMakeLists.txt
+++ b/clang/unittests/StaticAnalyzer/CMakeLists.txt
@@ -11,7 +11,6 @@ add_clang_unittest(StaticAnalysisTests
   CallEventTest.cpp
   ConflictingEvalCallsTest.cpp
   FalsePositiveRefutationBRVisitorTest.cpp
-  IsCLibraryFunctionTest.cpp
   NoStateChangeFuncVisitorTest.cpp
   ParamRegionTest.cpp
   RangeSetTest.cpp

diff  --git a/clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp 
b/clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp
deleted file mode 100644
index 31ff13f428da36..00
--- a/clang/unittests/StaticAnalyzer/IsCLibraryFunctionTest.cpp
+++ /dev/null
@@ -1,84 +0,0 @@
-#include "clang/ASTMatchers/ASTMatchFinder.h"
-#include "clang/ASTMatchers/ASTMatchers.h"
-#include "clang/Analysis/AnalysisDeclContext.h"
-#include "clang/Frontend/ASTUnit.h"
-#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
-#include "clang/Tooling/Tooling.h"
-#include "gtest/gtest.h"
-
-#include 
-
-using namespace clang;
-using namespace ento;
-using namespace ast_matchers;
-
-class IsCLibraryFunctionTest : public testing:

[clang-tools-extra] [clang-tidy]bugprone-unused-return-value ignore `++` and `--` operator overloading (PR #84922)

2024-03-13 Thread Piotr Zegar via cfe-commits

https://github.com/PiotrZSL edited 
https://github.com/llvm/llvm-project/pull/84922
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy]bugprone-unused-return-value ignore `++` and `--` operator overloading (PR #84922)

2024-03-13 Thread Piotr Zegar via cfe-commits


@@ -169,16 +180,14 @@ void UnusedReturnValueCheck::registerMatchers(MatchFinder 
*Finder) {
   callee(functionDecl(
   // Don't match void overloads of checked functions.
   unless(returns(voidType())),
-  // Don't match copy or move assignment operator.
-  unless(cxxMethodDecl(isOperatorOverloading(
-  {OO_Equal, OO_PlusEqual, OO_MinusEqual, OO_StarEqual,
-   OO_SlashEqual, OO_PercentEqual, OO_CaretEqual, OO_AmpEqual,
-   OO_PipeEqual, OO_LessLessEqual, OO_GreaterGreaterEqual}))),
   anyOf(
   isInstantiatedFrom(
   matchers::matchesAnyListedName(CheckedFunctions)),
   returns(hasCanonicalType(hasDeclaration(namedDecl(
-  
matchers::matchesAnyListedName(CheckedReturnTypes)
+  
matchers::matchesAnyListedName(CheckedReturnTypes,
+  // Don't match copy or move assignment operator.
+  unless(cxxOperatorCallExpr(isAssignmentOverloadedOperatorCall())),
+  
unless(callee(cxxMethodDecl(isAssignmentOverloadedOperatorMethod()

PiotrZSL wrote:

try changing this code in a way so callee woudn't be checked if 
cxxOperatorCallExpr were already checked.
you could do it like this:
```
anyOf(cxxOperatorCallExpr(unless(isAssignmentOverloadedOperatorCall()),
   
unless(callee(functionDecl(isAssignmentOverloadedOperatorFunction()
```

You may also consider moving this before all those 
matchers::matchesAnyListedName, so names woudn't be checked for operators at 
all.

https://github.com/llvm/llvm-project/pull/84922
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy]bugprone-unused-return-value ignore `++` and `--` operator overloading (PR #84922)

2024-03-13 Thread Piotr Zegar via cfe-commits


@@ -31,9 +31,20 @@ AST_MATCHER_P(FunctionDecl, isInstantiatedFrom, 
Matcher,
   Finder, Builder);
 }
 
-AST_MATCHER_P(CXXMethodDecl, isOperatorOverloading,
-  llvm::SmallVector, Kinds) {
-  return llvm::is_contained(Kinds, Node.getOverloadedOperator());
+constexpr std::initializer_list
+AssignmentOverloadedOperatorKinds = {
+OO_Equal,  OO_PlusEqual, OO_MinusEqual,  OO_StarEqual,
+OO_SlashEqual, OO_PercentEqual,  OO_CaretEqual,  OO_AmpEqual,
+OO_PipeEqual,  OO_LessLessEqual, OO_GreaterGreaterEqual, OO_PlusPlus,
+OO_MinusMinus};
+
+AST_MATCHER(CXXOperatorCallExpr, isAssignmentOverloadedOperatorCall) {
+  return llvm::is_contained(AssignmentOverloadedOperatorKinds,
+Node.getOperator());
+}
+AST_MATCHER(CXXMethodDecl, isAssignmentOverloadedOperatorMethod) {
+  return llvm::is_contained(AssignmentOverloadedOperatorKinds,

PiotrZSL wrote:

getOverloadedOperator belongs to FunctionDecl, change this from Method to 
Function, and same in calee, in such case you will also cover calls to free 
standing operators called directly.

https://github.com/llvm/llvm-project/pull/84922
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy]bugprone-unused-return-value ignore `++` and `--` operator overloading (PR #84922)

2024-03-13 Thread Piotr Zegar via cfe-commits

https://github.com/PiotrZSL commented:

Few more tests would be also nice, with free standing operators.

https://github.com/llvm/llvm-project/pull/84922
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][modules] giving the __stddef_ headers their own modules can cause redeclaration errors with -fbuiltin-headers-in-system-modules (PR #84127)

2024-03-13 Thread Ian Anderson via cfe-commits


@@ -301,10 +301,9 @@ bool Module::directlyUses(const Module *Requested) {
 if (Requested->isSubModuleOf(Use))
   return true;
 
-  // Anyone is allowed to use our builtin stdarg.h and stddef.h and their
-  // accompanying modules.
-  if (Requested->getTopLevelModuleName() == "_Builtin_stdarg" ||
-  Requested->getTopLevelModuleName() == "_Builtin_stddef")
+  // Anyone is allowed to use our builtin stddef.h and its accompanying 
modules.
+  if (Requested->fullModuleNameIs({"_Builtin_stddef", "max_align_t"}) ||
+  Requested->fullModuleNameIs({"_Builtin_stddef_wint_t"}))

ian-twilightcoder wrote:

We're taking `[no_undeclared_includes]` to imply 
`-fbuiltin-headers-in-system-modules`, where `_Builtin_stdarg` is empty. The 
assumption is that `[no_undeclared_includes]` is a workaround for the C++ 
headers not layering when the C stdlib headers are all in the same module, 
which is also what `-fbuiltin-headers-in-system-modules` is for. If we don't 
think that's a good assumption, then maybe we should add all of the clang C 
stdlib modules here (but it's been fine so far keeping the assumption).

https://github.com/llvm/llvm-project/pull/84127
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [RISCV] Add back SiFive's cdiscard.d.l1, cflush.d.l1, and cease instructions. (PR #83896)

2024-03-13 Thread Yingwei Zheng via cfe-commits

https://github.com/dtcxzyw approved this pull request.


https://github.com/llvm/llvm-project/pull/83896
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sema] Properly get captured 'this' pointer in lambdas with an explicit object parameter in constant evaluator (PR #81102)

2024-03-13 Thread via cfe-commits

https://github.com/Sirraide updated 
https://github.com/llvm/llvm-project/pull/81102

>From d489acbd3cfb656d203e1f05b74c238351c5428a Mon Sep 17 00:00:00 2001
From: Sirraide 
Date: Thu, 8 Feb 2024 08:33:03 +0100
Subject: [PATCH 1/7] [Clang] Properly get captured 'this' pointer in lambdas
 with an explicit object parameter in constant evaluator

---
 clang/lib/AST/ExprConstant.cpp| 130 ++
 .../constexpr-explicit-object-lambda.cpp  |  34 +
 2 files changed, 109 insertions(+), 55 deletions(-)
 create mode 100644 clang/test/SemaCXX/constexpr-explicit-object-lambda.cpp

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 089bc2094567f7..8dc6348bc7eedb 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8480,6 +8480,54 @@ class LValueExprEvaluator
 };
 } // end anonymous namespace
 
+/// Get an lvalue to a field of a lambda's closure type.
+static bool GetLambdaCaptureAsLValue(EvalInfo &Info, const Expr *E,
+ LValue &Result, const CXXMethodDecl *MD,
+ const FieldDecl *FD,
+ bool LValueToRValueConversion) {
+  // Static lambda function call operators can't have captures. We already
+  // diagnosed this, so bail out here.
+  if (MD->isStatic()) {
+assert(Info.CurrentCall->This == nullptr &&
+   "This should not be set for a static call operator");
+return false;
+  }
+
+  // Start with 'Result' referring to the complete closure object...
+  if (MD->isExplicitObjectMemberFunction()) {
+// Self may be passed by reference or by value.
+auto *Self = MD->getParamDecl(0);
+if (Self->getType()->isReferenceType()) {
+  APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
+  Result.setFrom(Info.Ctx, *RefValue);
+} else {
+  auto *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
+  auto *Frame =
+  Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
+  .first;
+  auto Version = Info.CurrentCall->Arguments.Version;
+  Result.set({VD, Frame->Index, Version});
+}
+  } else
+Result = *Info.CurrentCall->This;
+
+  // ... then update it to refer to the field of the closure object
+  // that represents the capture.
+  if (!HandleLValueMember(Info, E, Result, FD))
+return false;
+
+  // And if the field is of reference type (or if we captured '*this' by
+  // reference if this is a lambda), update 'Result' to refer to what
+  // the field refers to.
+  if (LValueToRValueConversion) {
+APValue RVal;
+if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
+  return false;
+Result.setFrom(Info.Ctx, RVal);
+  }
+  return true;
+}
+
 /// Evaluate an expression as an lvalue. This can be legitimately called on
 /// expressions which are not glvalues, in three cases:
 ///  * function designators in C, and
@@ -8524,37 +8572,8 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
   const auto *MD = cast(Info.CurrentCall->Callee);
-
-  // Static lambda function call operators can't have captures. We already
-  // diagnosed this, so bail out here.
-  if (MD->isStatic()) {
-assert(Info.CurrentCall->This == nullptr &&
-   "This should not be set for a static call operator");
-return false;
-  }
-
-  // Start with 'Result' referring to the complete closure object...
-  if (MD->isExplicitObjectMemberFunction()) {
-APValue *RefValue =
-Info.getParamSlot(Info.CurrentCall->Arguments, 
MD->getParamDecl(0));
-Result.setFrom(Info.Ctx, *RefValue);
-  } else
-Result = *Info.CurrentCall->This;
-
-  // ... then update it to refer to the field of the closure object
-  // that represents the capture.
-  if (!HandleLValueMember(Info, E, Result, FD))
-return false;
-  // And if the field is of reference type, update 'Result' to refer to 
what
-  // the field refers to.
-  if (FD->getType()->isReferenceType()) {
-APValue RVal;
-if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
-RVal))
-  return false;
-Result.setFrom(Info.Ctx, RVal);
-  }
-  return true;
+  return GetLambdaCaptureAsLValue(Info, E, Result, MD, FD,
+  FD->getType()->isReferenceType());
 }
   }
 
@@ -9032,45 +9051,46 @@ class PointerExprEvaluator
 return Error(E);
   }
   bool VisitCXXThisExpr(const CXXThisExpr *E) {
-// Can't look at 'this' when checking a potential constant expression.
-if (Info.checkingPotentialConstantExpression())
-  return false;
-if (!Info.CurrentCall->This) {
+auto DiagnoseInvalidUseOfThis = [&] {
   if (Info.get

[clang] [Clang][Sema] Properly get captured 'this' pointer in lambdas with an explicit object parameter in constant evaluator (PR #81102)

2024-03-13 Thread via cfe-commits


@@ -8485,6 +8485,53 @@ class LValueExprEvaluator
 };
 } // end anonymous namespace
 
+/// Get an lvalue to a field of a lambda's closure type.
+static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
+const CXXMethodDecl *MD, const FieldDecl *FD,
+bool LValueToRValueConversion) {
+  // Static lambda function call operators can't have captures. We already
+  // diagnosed this, so bail out here.
+  if (MD->isStatic()) {
+assert(Info.CurrentCall->This == nullptr &&
+   "This should not be set for a static call operator");
+return false;
+  }
+
+  // Start with 'Result' referring to the complete closure object...
+  if (MD->isExplicitObjectMemberFunction()) {
+// Self may be passed by reference or by value.
+auto *Self = MD->getParamDecl(0);
+if (Self->getType()->isReferenceType()) {
+  APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
+  Result.setFrom(Info.Ctx, *RefValue);
+} else {
+  auto *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
+  auto *Frame =
+  Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
+  .first;
+  auto Version = Info.CurrentCall->Arguments.Version;

Sirraide wrote:

I probably intended to come back later because I sort of expected there to be a 
helper that I missed.

https://github.com/llvm/llvm-project/pull/81102
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sema] Properly get captured 'this' pointer in lambdas with an explicit object parameter in constant evaluator (PR #81102)

2024-03-13 Thread via cfe-commits

https://github.com/Sirraide updated 
https://github.com/llvm/llvm-project/pull/81102

>From d489acbd3cfb656d203e1f05b74c238351c5428a Mon Sep 17 00:00:00 2001
From: Sirraide 
Date: Thu, 8 Feb 2024 08:33:03 +0100
Subject: [PATCH 1/8] [Clang] Properly get captured 'this' pointer in lambdas
 with an explicit object parameter in constant evaluator

---
 clang/lib/AST/ExprConstant.cpp| 130 ++
 .../constexpr-explicit-object-lambda.cpp  |  34 +
 2 files changed, 109 insertions(+), 55 deletions(-)
 create mode 100644 clang/test/SemaCXX/constexpr-explicit-object-lambda.cpp

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 089bc2094567f7..8dc6348bc7eedb 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8480,6 +8480,54 @@ class LValueExprEvaluator
 };
 } // end anonymous namespace
 
+/// Get an lvalue to a field of a lambda's closure type.
+static bool GetLambdaCaptureAsLValue(EvalInfo &Info, const Expr *E,
+ LValue &Result, const CXXMethodDecl *MD,
+ const FieldDecl *FD,
+ bool LValueToRValueConversion) {
+  // Static lambda function call operators can't have captures. We already
+  // diagnosed this, so bail out here.
+  if (MD->isStatic()) {
+assert(Info.CurrentCall->This == nullptr &&
+   "This should not be set for a static call operator");
+return false;
+  }
+
+  // Start with 'Result' referring to the complete closure object...
+  if (MD->isExplicitObjectMemberFunction()) {
+// Self may be passed by reference or by value.
+auto *Self = MD->getParamDecl(0);
+if (Self->getType()->isReferenceType()) {
+  APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
+  Result.setFrom(Info.Ctx, *RefValue);
+} else {
+  auto *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
+  auto *Frame =
+  Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
+  .first;
+  auto Version = Info.CurrentCall->Arguments.Version;
+  Result.set({VD, Frame->Index, Version});
+}
+  } else
+Result = *Info.CurrentCall->This;
+
+  // ... then update it to refer to the field of the closure object
+  // that represents the capture.
+  if (!HandleLValueMember(Info, E, Result, FD))
+return false;
+
+  // And if the field is of reference type (or if we captured '*this' by
+  // reference if this is a lambda), update 'Result' to refer to what
+  // the field refers to.
+  if (LValueToRValueConversion) {
+APValue RVal;
+if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
+  return false;
+Result.setFrom(Info.Ctx, RVal);
+  }
+  return true;
+}
+
 /// Evaluate an expression as an lvalue. This can be legitimately called on
 /// expressions which are not glvalues, in three cases:
 ///  * function designators in C, and
@@ -8524,37 +8572,8 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
   const auto *MD = cast(Info.CurrentCall->Callee);
-
-  // Static lambda function call operators can't have captures. We already
-  // diagnosed this, so bail out here.
-  if (MD->isStatic()) {
-assert(Info.CurrentCall->This == nullptr &&
-   "This should not be set for a static call operator");
-return false;
-  }
-
-  // Start with 'Result' referring to the complete closure object...
-  if (MD->isExplicitObjectMemberFunction()) {
-APValue *RefValue =
-Info.getParamSlot(Info.CurrentCall->Arguments, 
MD->getParamDecl(0));
-Result.setFrom(Info.Ctx, *RefValue);
-  } else
-Result = *Info.CurrentCall->This;
-
-  // ... then update it to refer to the field of the closure object
-  // that represents the capture.
-  if (!HandleLValueMember(Info, E, Result, FD))
-return false;
-  // And if the field is of reference type, update 'Result' to refer to 
what
-  // the field refers to.
-  if (FD->getType()->isReferenceType()) {
-APValue RVal;
-if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
-RVal))
-  return false;
-Result.setFrom(Info.Ctx, RVal);
-  }
-  return true;
+  return GetLambdaCaptureAsLValue(Info, E, Result, MD, FD,
+  FD->getType()->isReferenceType());
 }
   }
 
@@ -9032,45 +9051,46 @@ class PointerExprEvaluator
 return Error(E);
   }
   bool VisitCXXThisExpr(const CXXThisExpr *E) {
-// Can't look at 'this' when checking a potential constant expression.
-if (Info.checkingPotentialConstantExpression())
-  return false;
-if (!Info.CurrentCall->This) {
+auto DiagnoseInvalidUseOfThis = [&] {
   if (Info.get

[clang] [llvm] [RISCV] Support RISC-V Profiles in -march option (PR #76357)

2024-03-13 Thread Philip Reames via cfe-commits


@@ -36,6 +36,11 @@ struct RISCVSupportedExtension {
   }
 };
 
+struct RISCVProfile {

preames wrote:

Very minor, but I believe you can use std::pair here instead.  

https://github.com/llvm/llvm-project/pull/76357
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Sema] Properly get captured 'this' pointer in lambdas with an explicit object parameter in constant evaluator (PR #81102)

2024-03-13 Thread via cfe-commits

https://github.com/Sirraide updated 
https://github.com/llvm/llvm-project/pull/81102

>From d489acbd3cfb656d203e1f05b74c238351c5428a Mon Sep 17 00:00:00 2001
From: Sirraide 
Date: Thu, 8 Feb 2024 08:33:03 +0100
Subject: [PATCH 1/8] [Clang] Properly get captured 'this' pointer in lambdas
 with an explicit object parameter in constant evaluator

---
 clang/lib/AST/ExprConstant.cpp| 130 ++
 .../constexpr-explicit-object-lambda.cpp  |  34 +
 2 files changed, 109 insertions(+), 55 deletions(-)
 create mode 100644 clang/test/SemaCXX/constexpr-explicit-object-lambda.cpp

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 089bc2094567f7..8dc6348bc7eedb 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8480,6 +8480,54 @@ class LValueExprEvaluator
 };
 } // end anonymous namespace
 
+/// Get an lvalue to a field of a lambda's closure type.
+static bool GetLambdaCaptureAsLValue(EvalInfo &Info, const Expr *E,
+ LValue &Result, const CXXMethodDecl *MD,
+ const FieldDecl *FD,
+ bool LValueToRValueConversion) {
+  // Static lambda function call operators can't have captures. We already
+  // diagnosed this, so bail out here.
+  if (MD->isStatic()) {
+assert(Info.CurrentCall->This == nullptr &&
+   "This should not be set for a static call operator");
+return false;
+  }
+
+  // Start with 'Result' referring to the complete closure object...
+  if (MD->isExplicitObjectMemberFunction()) {
+// Self may be passed by reference or by value.
+auto *Self = MD->getParamDecl(0);
+if (Self->getType()->isReferenceType()) {
+  APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
+  Result.setFrom(Info.Ctx, *RefValue);
+} else {
+  auto *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
+  auto *Frame =
+  Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
+  .first;
+  auto Version = Info.CurrentCall->Arguments.Version;
+  Result.set({VD, Frame->Index, Version});
+}
+  } else
+Result = *Info.CurrentCall->This;
+
+  // ... then update it to refer to the field of the closure object
+  // that represents the capture.
+  if (!HandleLValueMember(Info, E, Result, FD))
+return false;
+
+  // And if the field is of reference type (or if we captured '*this' by
+  // reference if this is a lambda), update 'Result' to refer to what
+  // the field refers to.
+  if (LValueToRValueConversion) {
+APValue RVal;
+if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
+  return false;
+Result.setFrom(Info.Ctx, RVal);
+  }
+  return true;
+}
+
 /// Evaluate an expression as an lvalue. This can be legitimately called on
 /// expressions which are not glvalues, in three cases:
 ///  * function designators in C, and
@@ -8524,37 +8572,8 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
   const auto *MD = cast(Info.CurrentCall->Callee);
-
-  // Static lambda function call operators can't have captures. We already
-  // diagnosed this, so bail out here.
-  if (MD->isStatic()) {
-assert(Info.CurrentCall->This == nullptr &&
-   "This should not be set for a static call operator");
-return false;
-  }
-
-  // Start with 'Result' referring to the complete closure object...
-  if (MD->isExplicitObjectMemberFunction()) {
-APValue *RefValue =
-Info.getParamSlot(Info.CurrentCall->Arguments, 
MD->getParamDecl(0));
-Result.setFrom(Info.Ctx, *RefValue);
-  } else
-Result = *Info.CurrentCall->This;
-
-  // ... then update it to refer to the field of the closure object
-  // that represents the capture.
-  if (!HandleLValueMember(Info, E, Result, FD))
-return false;
-  // And if the field is of reference type, update 'Result' to refer to 
what
-  // the field refers to.
-  if (FD->getType()->isReferenceType()) {
-APValue RVal;
-if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
-RVal))
-  return false;
-Result.setFrom(Info.Ctx, RVal);
-  }
-  return true;
+  return GetLambdaCaptureAsLValue(Info, E, Result, MD, FD,
+  FD->getType()->isReferenceType());
 }
   }
 
@@ -9032,45 +9051,46 @@ class PointerExprEvaluator
 return Error(E);
   }
   bool VisitCXXThisExpr(const CXXThisExpr *E) {
-// Can't look at 'this' when checking a potential constant expression.
-if (Info.checkingPotentialConstantExpression())
-  return false;
-if (!Info.CurrentCall->This) {
+auto DiagnoseInvalidUseOfThis = [&] {
   if (Info.get

[clang] bd77a26 - [Clang][Sema] Properly get captured 'this' pointer in lambdas with an explicit object parameter in constant evaluator (#81102)

2024-03-13 Thread via cfe-commits

Author: Sirraide
Date: 2024-03-13T18:49:44+01:00
New Revision: bd77a26e9a15981114e9802d83047f42631125a2

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

LOG: [Clang][Sema] Properly get captured 'this' pointer in lambdas with an 
explicit object parameter in constant evaluator (#81102)

There were some bugs wrt explicit object parameters in lambdas in the
constant evaluator:
- The code evaluating a `CXXThisExpr` wasn’t checking for explicit
object parameters at all and thus assumed that there was no `this` in
the current context because the lambda didn’t have one, even though we
were in a member function and had captured its `this`.
- The code retrieving captures as lvalues *did* account for explicit
object parameters, but it did not handle the case of the explicit object
parameter being passed by value rather than by reference.

This fixes #80997.

-

Co-authored-by: cor3ntin 
Co-authored-by: Aaron Ballman 

Added: 
clang/test/SemaCXX/constexpr-explicit-object-lambda.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/AST/ExprConstant.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c5488e8742f611..5fe3fd066df235 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -373,6 +373,9 @@ Bug Fixes to C++ Support
   and (`#74494 `_)
 - Allow access to a public template alias declaration that refers to friend's
   private nested type. (#GH25708).
+- Fixed a crash in constant evaluation when trying to access a
+  captured ``this`` pointer in a lambda with an explicit object parameter.
+  Fixes (#GH80997)
 
 Bug Fixes to AST Handling
 ^

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 726415cfbde08a..b154a196e11c7d 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8517,6 +8517,53 @@ class LValueExprEvaluator
 };
 } // end anonymous namespace
 
+/// Get an lvalue to a field of a lambda's closure type.
+static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
+const CXXMethodDecl *MD, const FieldDecl *FD,
+bool LValueToRValueConversion) {
+  // Static lambda function call operators can't have captures. We already
+  // diagnosed this, so bail out here.
+  if (MD->isStatic()) {
+assert(Info.CurrentCall->This == nullptr &&
+   "This should not be set for a static call operator");
+return false;
+  }
+
+  // Start with 'Result' referring to the complete closure object...
+  if (MD->isExplicitObjectMemberFunction()) {
+// Self may be passed by reference or by value.
+const ParmVarDecl *Self = MD->getParamDecl(0);
+if (Self->getType()->isReferenceType()) {
+  APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
+  Result.setFrom(Info.Ctx, *RefValue);
+} else {
+  const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
+  CallStackFrame *Frame =
+  Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
+  .first;
+  unsigned Version = Info.CurrentCall->Arguments.Version;
+  Result.set({VD, Frame->Index, Version});
+}
+  } else
+Result = *Info.CurrentCall->This;
+
+  // ... then update it to refer to the field of the closure object
+  // that represents the capture.
+  if (!HandleLValueMember(Info, E, Result, FD))
+return false;
+
+  // And if the field is of reference type (or if we captured '*this' by
+  // reference), update 'Result' to refer to what
+  // the field refers to.
+  if (LValueToRValueConversion) {
+APValue RVal;
+if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
+  return false;
+Result.setFrom(Info.Ctx, RVal);
+  }
+  return true;
+}
+
 /// Evaluate an expression as an lvalue. This can be legitimately called on
 /// expressions which are not glvalues, in three cases:
 ///  * function designators in C, and
@@ -8561,37 +8608,8 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
   const auto *MD = cast(Info.CurrentCall->Callee);
-
-  // Static lambda function call operators can't have captures. We already
-  // diagnosed this, so bail out here.
-  if (MD->isStatic()) {
-assert(Info.CurrentCall->This == nullptr &&
-   "This should not be set for a static call operator");
-return false;
-  }
-
-  // Start with 'Result' referring to the complete closure object...
-  if (MD->isExplicitObjectMemberFunction()) {
-APValue *RefValue =
-

[clang] [Clang][Sema] Properly get captured 'this' pointer in lambdas with an explicit object parameter in constant evaluator (PR #81102)

2024-03-13 Thread via cfe-commits

https://github.com/Sirraide closed 
https://github.com/llvm/llvm-project/pull/81102
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] Adapted MemRegion::getDescriptiveName to handle ElementRegions (PR #85104)

2024-03-13 Thread Balazs Benics via cfe-commits

https://github.com/steakhal updated 
https://github.com/llvm/llvm-project/pull/85104

>From 0f964127ed91e23f8e969e08ce680535cfeb8906 Mon Sep 17 00:00:00 2001
From: Andreas Steinhausen 
Date: Wed, 13 Mar 2024 17:07:53 +0100
Subject: [PATCH 1/8] Adapted MemRegion::getDescriptiveName to handle
 ElementRegions

---
 clang/lib/StaticAnalyzer/Core/MemRegion.cpp   | 244 --
 clang/unittests/StaticAnalyzer/CMakeLists.txt |   1 +
 .../StaticAnalyzer/MemRegionTest.cpp  |  56 
 3 files changed, 167 insertions(+), 134 deletions(-)
 create mode 100644 clang/unittests/StaticAnalyzer/MemRegionTest.cpp

diff --git a/clang/lib/StaticAnalyzer/Core/MemRegion.cpp 
b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
index 16db6b249dc92b..89791bd88001e3 100644
--- a/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
+++ b/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
@@ -66,7 +66,7 @@ using namespace ento;
 
//===--===//
 
 template 
-RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1,
+RegionTy *MemRegionManager::getSubRegion(const Arg1Ty arg1,
  const SuperTy *superRegion) {
   llvm::FoldingSetNodeID ID;
   RegionTy::ProfileRegion(ID, arg1, superRegion);
@@ -82,7 +82,7 @@ RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1,
 }
 
 template 
-RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
+RegionTy *MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
  const SuperTy *superRegion) {
   llvm::FoldingSetNodeID ID;
   RegionTy::ProfileRegion(ID, arg1, arg2, superRegion);
@@ -97,9 +97,9 @@ RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, 
const Arg2Ty arg2,
   return R;
 }
 
-template 
-RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
+template 
+RegionTy *MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
  const Arg3Ty arg3,
  const SuperTy *superRegion) {
   llvm::FoldingSetNodeID ID;
@@ -129,8 +129,8 @@ MemRegionManager::~MemRegionManager() = default;
 // Basic methods.
 
//===--===//
 
-bool SubRegion::isSubRegionOf(const MemRegion* R) const {
-  const MemRegion* r = this;
+bool SubRegion::isSubRegionOf(const MemRegion *R) const {
+  const MemRegion *r = this;
   do {
 if (r == R)
   return true;
@@ -143,7 +143,7 @@ bool SubRegion::isSubRegionOf(const MemRegion* R) const {
 }
 
 MemRegionManager &SubRegion::getMemRegionManager() const {
-  const SubRegion* r = this;
+  const SubRegion *r = this;
   do {
 const MemRegion *superRegion = r->getSuperRegion();
 if (const auto *sr = dyn_cast(superRegion)) {
@@ -178,9 +178,7 @@ ObjCIvarRegion::ObjCIvarRegion(const ObjCIvarDecl *ivd, 
const SubRegion *sReg)
 
 const ObjCIvarDecl *ObjCIvarRegion::getDecl() const { return IVD; }
 
-QualType ObjCIvarRegion::getValueType() const {
-  return getDecl()->getType();
-}
+QualType ObjCIvarRegion::getValueType() const { return getDecl()->getType(); }
 
 QualType CXXBaseObjectRegion::getValueType() const {
   return QualType(getDecl()->getTypeForDecl(), 0);
@@ -251,26 +249,25 @@ void 
ObjCStringRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
   ID.AddPointer(superRegion);
 }
 
-void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
- const Expr *Ex, unsigned cnt,
- const MemRegion *superRegion) {
+void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID &ID, const Expr *Ex,
+ unsigned cnt, const MemRegion *superRegion) {
   ID.AddInteger(static_cast(AllocaRegionKind));
   ID.AddPointer(Ex);
   ID.AddInteger(cnt);
   ID.AddPointer(superRegion);
 }
 
-void AllocaRegion::Profile(llvm::FoldingSetNodeID& ID) const {
+void AllocaRegion::Profile(llvm::FoldingSetNodeID &ID) const {
   ProfileRegion(ID, Ex, Cnt, superRegion);
 }
 
-void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID& ID) const {
+void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID &ID) const {
   CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion);
 }
 
-void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
+void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
   const CompoundLiteralExpr *CL,
-  const MemRegion* superRegion) {
+  const MemRegion *superRegion) {
   ID.AddInteger(static_cast(CompoundLiteralRegionKind));
   ID.AddPointer(CL);
   ID.AddPointer(superRegion);
@@ -292,9 +289,9 @@ void FieldRegion::Profile(llvm::FoldingSetNodeID &ID) const 
{
   ProfileRegion(ID, getDecl(), superRegion);
 }
 
-void ObjCIvarRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
+void ObjCIvar

  1   2   3   4   5   >