[clang] [SYCL] Basic diagnostics for the sycl_kernel_entry_point attribute. (PR #120327)

2024-12-23 Thread Tom Honermann via cfe-commits


@@ -206,3 +208,124 @@ void SemaSYCL::handleKernelEntryPointAttr(Decl *D, const 
ParsedAttr &AL) {
   D->addAttr(::new (SemaRef.Context)
  SYCLKernelEntryPointAttr(SemaRef.Context, AL, TSI));
 }
+
+static SourceLocation SourceLocationForType(QualType QT) {
+  SourceLocation Loc;
+  const Type *T = QT->getUnqualifiedDesugaredType();
+  if (const TagType *TT = dyn_cast(T))
+Loc = TT->getDecl()->getLocation();
+  else if (const ObjCInterfaceType *ObjCIT = dyn_cast(T))
+Loc = ObjCIT->getDecl()->getLocation();
+  return Loc;

tahonermann wrote:

I renamed the function to `SourceLocationForUserDeclaredType()` and added 
comments to explain its intended purpose.

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


[clang] [SYCL] Basic diagnostics for the sycl_kernel_entry_point attribute. (PR #120327)

2024-12-23 Thread Tom Honermann via cfe-commits


@@ -15978,6 +15988,24 @@ Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt 
*Body,
   CheckCoroutineWrapper(FD);
   }
 
+  // Diagnose invalid SYCL kernel entry point function declarations.
+  if (FD && !FD->isInvalidDecl() && !FD->isTemplated() &&
+  FD->hasAttr()) {
+if (FD->isDeleted()) {
+  Diag(FD->getAttr()->getLocation(),
+   diag::err_sycl_entry_point_invalid)
+  << /*deleted function*/ 2;
+} else if (FD->isDefaulted()) {
+  Diag(FD->getAttr()->getLocation(),
+   diag::err_sycl_entry_point_invalid)
+  << /*defaulted function*/ 3;
+} else if (FSI->isCoroutine()) {
+  Diag(FD->getAttr()->getLocation(),
+   diag::err_sycl_entry_point_invalid)
+  << /*coroutine*/ 7;

tahonermann wrote:

Thanks for pointing me to those examples. For both `AttributeArgumentNType` and 
`AttributeDeclKind`, the production of the diagnostic is more complicated. For 
the first case, the diagnostic is produced in a lambda expression and the 
`%select` index is passed as an argument. For the second case, the `%select` 
index is computed by mapping from another enumeration using a switch statement. 
An enum definitely seems warranted for those cases. Similarly, for 
`Sema::checkTargetVersionAttr`, there are multiple `%select` indices involved 
in each diagnostic and the local enumeration does help with readability.

For simple diagnostics, where the `%select` index doesn't require computation 
and where the same index values are not used in multiple places, I think 
indirection through an enumeration isn't helpful, so I haven't made a change. 
If you still think a change is warranted, perhaps we can get a second opinion.

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


[clang] [Coverage] Introduce the type `CounterPair` for RegionCounterMap. NFC. (PR #112724)

2024-12-23 Thread NAKAMURA Takumi via cfe-commits

https://github.com/chapuni updated 
https://github.com/llvm/llvm-project/pull/112724

>From e4172ca273a6fdfcbfc4662c9e37276ef34c2df4 Mon Sep 17 00:00:00 2001
From: NAKAMURA Takumi 
Date: Thu, 17 Oct 2024 00:32:26 +0900
Subject: [PATCH 1/5] Introduce the type `CounterPair` for RegionCounterMap

`CounterPair` can hold `` instead of current
`unsigned`, to hold also the counter number of SkipPath. For now, this
change provides the skeleton and only `CounterPair::first` is used.

Each counter number can have `None` to suppress emitting counter
increment. `second` is initialized as `None` by default, since most
`Stmt*` don't have a pair of counters.

This change also provides stubs for the verifyer. I'll provide the
impl of verifier for `+Asserts` later.

`markStmtAsUsed(bool, Stmt*)` may be used to inform that other side
counter may not emitted.

`markStmtMaybeUsed(S)` may be used for the `Stmt` and its inner will
be excluded for emission in the case of skipping by constant
folding. I put it into places where I found.

`verifyCounterMap()` will check the coverage map the counter map and
can be used to report inconsistency.

These verifier methods shall be eliminated in `-Asserts`.

https://discourse.llvm.org/t/rfc-integrating-singlebytecoverage-with-branch-coverage/82492
---
 clang/lib/CodeGen/CGDecl.cpp |  9 -
 clang/lib/CodeGen/CGExpr.cpp |  1 +
 clang/lib/CodeGen/CGExprScalar.cpp   |  9 +++--
 clang/lib/CodeGen/CGStmt.cpp |  3 +++
 clang/lib/CodeGen/CodeGenFunction.cpp|  3 +++
 clang/lib/CodeGen/CodeGenFunction.h  |  6 ++
 clang/lib/CodeGen/CodeGenModule.h| 19 +++
 clang/lib/CodeGen/CodeGenPGO.cpp | 14 ++
 clang/lib/CodeGen/CodeGenPGO.h   | 17 +++--
 clang/lib/CodeGen/CoverageMappingGen.cpp |  6 +++---
 clang/lib/CodeGen/CoverageMappingGen.h   |  5 +++--
 11 files changed, 78 insertions(+), 14 deletions(-)

diff --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index 563f728e29d781..ed5f41b624b62b 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -362,6 +362,8 @@ CodeGenFunction::AddInitializerToStaticVarDecl(const 
VarDecl &D,
 return GV;
   }
 
+  PGO.markStmtMaybeUsed(D.getInit()); // FIXME: Too lazy
+
 #ifndef NDEBUG
   CharUnits VarSize = CGM.getContext().getTypeSizeInChars(D.getType()) +
   D.getFlexibleArrayInitChars(getContext());
@@ -1869,7 +1871,10 @@ void CodeGenFunction::EmitAutoVarInit(const 
AutoVarEmission &emission) {
   // If we are at an unreachable point, we don't need to emit the initializer
   // unless it contains a label.
   if (!HaveInsertPoint()) {
-if (!Init || !ContainsLabel(Init)) return;
+if (!Init || !ContainsLabel(Init)) {
+  PGO.markStmtMaybeUsed(Init);
+  return;
+}
 EnsureInsertPoint();
   }
 
@@ -1978,6 +1983,8 @@ void CodeGenFunction::EmitAutoVarInit(const 
AutoVarEmission &emission) {
 return EmitExprAsInit(Init, &D, lv, capturedByInit);
   }
 
+  PGO.markStmtMaybeUsed(Init);
+
   if (!emission.IsConstantAggregate) {
 // For simple scalar/complex initialization, store the value directly.
 LValue lv = MakeAddrLValue(Loc, type);
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 52d2f6d52abf94..2fd6b02a3395ee 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -5134,6 +5134,7 @@ std::optional 
HandleConditionalOperatorLValueSimpleCase(
   // If the true case is live, we need to track its region.
   if (CondExprBool)
 CGF.incrementProfileCounter(E);
+  CGF.markStmtMaybeUsed(Dead);
   // If a throw expression we emit it and return an undefined lvalue
   // because it can't be used.
   if (auto *ThrowExpr = dyn_cast(Live->IgnoreParens())) {
diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index b7f5b932c56b6f..74e93f889f4261 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -4982,8 +4982,10 @@ Value *ScalarExprEmitter::VisitBinLAnd(const 
BinaryOperator *E) {
 }
 
 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
-if (!CGF.ContainsLabel(E->getRHS()))
+if (!CGF.ContainsLabel(E->getRHS())) {
+  CGF.markStmtMaybeUsed(E->getRHS());
   return llvm::Constant::getNullValue(ResTy);
+}
   }
 
   // If the top of the logical operator nest, reset the MCDC temp to 0.
@@ -5122,8 +5124,10 @@ Value *ScalarExprEmitter::VisitBinLOr(const 
BinaryOperator *E) {
 }
 
 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
-if (!CGF.ContainsLabel(E->getRHS()))
+if (!CGF.ContainsLabel(E->getRHS())) {
+  CGF.markStmtMaybeUsed(E->getRHS());
   return llvm::ConstantInt::get(ResTy, 1);
+}
   }
 
   // If the top of the logical operator nest, reset the MCDC temp to 0.
@@ -5247,6 +5251,7 @@ VisitAbstractConditionalOperator

[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-23 Thread Stephen Senran Zhang via cfe-commits

zsrkmyn wrote:

> > I'm thinking if I need to add a new test mode to test the optimal lower 
> > (upper) bound only for AND (OR).
> 
> If you cannot make it optimal for all non-wrapped cases, please just add some 
> special cases (e.g., `[7, 14) & [-1, 0) = [7, 14)`) before 
> `TestBinaryOpExhaustive`.

Ah, I mean, the lower bound by this patch is optimal, but the upper isn't, so 
tests failed. :-D But adding special cases should work.

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


[clang] [clang-format] Skip line splices when sorting C++ includes (PR #120680)

2024-12-23 Thread Owen Pan via cfe-commits


@@ -3246,8 +3246,15 @@ tooling::Replacements sortCppIncludes(const FormatStyle 
&Style, StringRef Code,
   SmallVector RawStringMatches;
   std::string RawStringTermination = ")\"";
 
-  for (;;) {
-auto Pos = Code.find('\n', SearchFrom);
+  for (const auto Size = Code.size(); SearchFrom < Size;) {

owenca wrote:

Because it's used in `SearchFrom < Size`. My previous version using `for (;;)` 
caused a crash in ToolingTests.

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


[clang] [clang][RISCV] Remove unneeded RISCV tuple code (PR #121024)

2024-12-23 Thread Brandon Wu via cfe-commits

https://github.com/4vtomat created 
https://github.com/llvm/llvm-project/pull/121024

These code are no longer needed because we've modeled tuple type using
target extension type rather than structure of scalable vectors.


>From 72401387483dd5839d09f508c1bc988325c5e456 Mon Sep 17 00:00:00 2001
From: Brandon Wu 
Date: Mon, 23 Dec 2024 19:51:16 -0800
Subject: [PATCH] [clang][RISCV] Remove unneeded RISCV tuple code

These code are no longer needed because we've modeled tuple type using
target extension type rather than structure of scalable vectors.
---
 clang/lib/CodeGen/CGCall.cpp| 31 -
 clang/lib/CodeGen/Targets/RISCV.cpp |  8 +---
 2 files changed, 1 insertion(+), 38 deletions(-)

diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 50b9dfbbab083a..f139c30f3dfd44 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -3235,22 +3235,6 @@ void CodeGenFunction::EmitFunctionProlog(const 
CGFunctionInfo &FI,
 
   llvm::StructType *STy =
   dyn_cast(ArgI.getCoerceToType());
-  if (ArgI.isDirect() && !ArgI.getCanBeFlattened() && STy &&
-  STy->getNumElements() > 1) {
-[[maybe_unused]] llvm::TypeSize StructSize =
-CGM.getDataLayout().getTypeAllocSize(STy);
-[[maybe_unused]] llvm::TypeSize PtrElementSize =
-CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(Ty));
-if (STy->containsHomogeneousScalableVectorTypes()) {
-  assert(StructSize == PtrElementSize &&
- "Only allow non-fractional movement of structure with"
- "homogeneous scalable vector type");
-
-  ArgVals.push_back(ParamValue::forDirect(AI));
-  break;
-}
-  }
-
   Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
  Arg->getName());
 
@@ -5414,21 +5398,6 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo 
&CallInfo,
 
   llvm::StructType *STy =
   dyn_cast(ArgInfo.getCoerceToType());
-  if (STy && ArgInfo.isDirect() && !ArgInfo.getCanBeFlattened()) {
-llvm::Type *SrcTy = ConvertTypeForMem(I->Ty);
-[[maybe_unused]] llvm::TypeSize SrcTypeSize =
-CGM.getDataLayout().getTypeAllocSize(SrcTy);
-[[maybe_unused]] llvm::TypeSize DstTypeSize =
-CGM.getDataLayout().getTypeAllocSize(STy);
-if (STy->containsHomogeneousScalableVectorTypes()) {
-  assert(SrcTypeSize == DstTypeSize &&
- "Only allow non-fractional movement of structure with "
- "homogeneous scalable vector type");
-
-  IRCallArgs[FirstIRArg] = I->getKnownRValue().getScalarVal();
-  break;
-}
-  }
 
   // FIXME: Avoid the conversion through memory if possible.
   Address Src = Address::invalid();
diff --git a/clang/lib/CodeGen/Targets/RISCV.cpp 
b/clang/lib/CodeGen/Targets/RISCV.cpp
index b04e436c665f52..873e696e1328f9 100644
--- a/clang/lib/CodeGen/Targets/RISCV.cpp
+++ b/clang/lib/CodeGen/Targets/RISCV.cpp
@@ -495,13 +495,7 @@ ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, 
bool IsFixed,
 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
 }
 
-ABIArgInfo Info = ABIArgInfo::getDirect();
-
-// If it is tuple type, it can't be flattened.
-if (llvm::StructType *STy = 
dyn_cast(CGT.ConvertType(Ty)))
-  Info.setCanBeFlattened(!STy->containsHomogeneousScalableVectorTypes());
-
-return Info;
+return ABIArgInfo::getDirect();
   }
 
   if (const VectorType *VT = Ty->getAs())

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


[clang] [clang-format] extend clang-format directive with options to prevent formatting for one line (PR #118566)

2024-12-23 Thread Owen Pan via cfe-commits

owenca wrote:

> A nice multiline example I stumbled upon is:
> 
> ```c++
> Tree tree[]
> {
> {'D', tree + 1, tree + 2},
> //│
> //┌───┴┐
> //││
> {'B', tree + 3, tree + 4},   {'F', tree + 5, tree + 
> 6},
> //││
> //  ┌─┴─┐  ┌───┴─┐
> //  │   │  │ │
>   {'A'},  {'C'}, {'E'},{'G'}
> };
> ```

Which line(s) do you want clang-format to skip here?

> And [#54334 
> (comment)](https://github.com/llvm/llvm-project/issues/54334#issuecomment-2531049984)
>  makes a good example on why only one line disabling would be desired.

The current way to skip the line in that example is as follows:
```cpp
int foo(Resources *resources, int i, int j, int k) {
  if (i < 0 && j < 0) {
// clang-format off
myproject::detail::LogErrorPrintf( resources->logger, "both i and j can not 
be negative at the same time.\ni = %d, j = %d\n", i, j);
// clang-format on
return -1;
  }

  if (i < 0) {
j *= 10;
  }
  if (j < 0) {
k += 5;
  }
  return i + j * k;
}
```
What's wrong with that other than it may be less convenient? Actually, I prefer 
the current way as it makes the skipped line stand out. If we were to add `// 
clang-format off-next-line`, would "next line" mean the next physical or 
logical/unwrapped line?


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


[clang] [clang][RISCV] Remove unneeded RISCV tuple code (PR #121024)

2024-12-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Brandon Wu (4vtomat)


Changes

These code are no longer needed because we've modeled tuple type using
target extension type rather than structure of scalable vectors.


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


2 Files Affected:

- (modified) clang/lib/CodeGen/CGCall.cpp (-31) 
- (modified) clang/lib/CodeGen/Targets/RISCV.cpp (+1-7) 


``diff
diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 50b9dfbbab083a..f139c30f3dfd44 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -3235,22 +3235,6 @@ void CodeGenFunction::EmitFunctionProlog(const 
CGFunctionInfo &FI,
 
   llvm::StructType *STy =
   dyn_cast(ArgI.getCoerceToType());
-  if (ArgI.isDirect() && !ArgI.getCanBeFlattened() && STy &&
-  STy->getNumElements() > 1) {
-[[maybe_unused]] llvm::TypeSize StructSize =
-CGM.getDataLayout().getTypeAllocSize(STy);
-[[maybe_unused]] llvm::TypeSize PtrElementSize =
-CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(Ty));
-if (STy->containsHomogeneousScalableVectorTypes()) {
-  assert(StructSize == PtrElementSize &&
- "Only allow non-fractional movement of structure with"
- "homogeneous scalable vector type");
-
-  ArgVals.push_back(ParamValue::forDirect(AI));
-  break;
-}
-  }
-
   Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
  Arg->getName());
 
@@ -5414,21 +5398,6 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo 
&CallInfo,
 
   llvm::StructType *STy =
   dyn_cast(ArgInfo.getCoerceToType());
-  if (STy && ArgInfo.isDirect() && !ArgInfo.getCanBeFlattened()) {
-llvm::Type *SrcTy = ConvertTypeForMem(I->Ty);
-[[maybe_unused]] llvm::TypeSize SrcTypeSize =
-CGM.getDataLayout().getTypeAllocSize(SrcTy);
-[[maybe_unused]] llvm::TypeSize DstTypeSize =
-CGM.getDataLayout().getTypeAllocSize(STy);
-if (STy->containsHomogeneousScalableVectorTypes()) {
-  assert(SrcTypeSize == DstTypeSize &&
- "Only allow non-fractional movement of structure with "
- "homogeneous scalable vector type");
-
-  IRCallArgs[FirstIRArg] = I->getKnownRValue().getScalarVal();
-  break;
-}
-  }
 
   // FIXME: Avoid the conversion through memory if possible.
   Address Src = Address::invalid();
diff --git a/clang/lib/CodeGen/Targets/RISCV.cpp 
b/clang/lib/CodeGen/Targets/RISCV.cpp
index b04e436c665f52..873e696e1328f9 100644
--- a/clang/lib/CodeGen/Targets/RISCV.cpp
+++ b/clang/lib/CodeGen/Targets/RISCV.cpp
@@ -495,13 +495,7 @@ ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, 
bool IsFixed,
 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
 }
 
-ABIArgInfo Info = ABIArgInfo::getDirect();
-
-// If it is tuple type, it can't be flattened.
-if (llvm::StructType *STy = 
dyn_cast(CGT.ConvertType(Ty)))
-  Info.setCanBeFlattened(!STy->containsHomogeneousScalableVectorTypes());
-
-return Info;
+return ABIArgInfo::getDirect();
   }
 
   if (const VectorType *VT = Ty->getAs())

``




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


[clang] [clang][RISCV] Remove unneeded RISCV tuple code (PR #121024)

2024-12-23 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-codegen

@llvm/pr-subscribers-backend-risc-v

Author: Brandon Wu (4vtomat)


Changes

These code are no longer needed because we've modeled tuple type using
target extension type rather than structure of scalable vectors.


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


2 Files Affected:

- (modified) clang/lib/CodeGen/CGCall.cpp (-31) 
- (modified) clang/lib/CodeGen/Targets/RISCV.cpp (+1-7) 


``diff
diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 50b9dfbbab083a..f139c30f3dfd44 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -3235,22 +3235,6 @@ void CodeGenFunction::EmitFunctionProlog(const 
CGFunctionInfo &FI,
 
   llvm::StructType *STy =
   dyn_cast(ArgI.getCoerceToType());
-  if (ArgI.isDirect() && !ArgI.getCanBeFlattened() && STy &&
-  STy->getNumElements() > 1) {
-[[maybe_unused]] llvm::TypeSize StructSize =
-CGM.getDataLayout().getTypeAllocSize(STy);
-[[maybe_unused]] llvm::TypeSize PtrElementSize =
-CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(Ty));
-if (STy->containsHomogeneousScalableVectorTypes()) {
-  assert(StructSize == PtrElementSize &&
- "Only allow non-fractional movement of structure with"
- "homogeneous scalable vector type");
-
-  ArgVals.push_back(ParamValue::forDirect(AI));
-  break;
-}
-  }
-
   Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
  Arg->getName());
 
@@ -5414,21 +5398,6 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo 
&CallInfo,
 
   llvm::StructType *STy =
   dyn_cast(ArgInfo.getCoerceToType());
-  if (STy && ArgInfo.isDirect() && !ArgInfo.getCanBeFlattened()) {
-llvm::Type *SrcTy = ConvertTypeForMem(I->Ty);
-[[maybe_unused]] llvm::TypeSize SrcTypeSize =
-CGM.getDataLayout().getTypeAllocSize(SrcTy);
-[[maybe_unused]] llvm::TypeSize DstTypeSize =
-CGM.getDataLayout().getTypeAllocSize(STy);
-if (STy->containsHomogeneousScalableVectorTypes()) {
-  assert(SrcTypeSize == DstTypeSize &&
- "Only allow non-fractional movement of structure with "
- "homogeneous scalable vector type");
-
-  IRCallArgs[FirstIRArg] = I->getKnownRValue().getScalarVal();
-  break;
-}
-  }
 
   // FIXME: Avoid the conversion through memory if possible.
   Address Src = Address::invalid();
diff --git a/clang/lib/CodeGen/Targets/RISCV.cpp 
b/clang/lib/CodeGen/Targets/RISCV.cpp
index b04e436c665f52..873e696e1328f9 100644
--- a/clang/lib/CodeGen/Targets/RISCV.cpp
+++ b/clang/lib/CodeGen/Targets/RISCV.cpp
@@ -495,13 +495,7 @@ ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, 
bool IsFixed,
 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
 }
 
-ABIArgInfo Info = ABIArgInfo::getDirect();
-
-// If it is tuple type, it can't be flattened.
-if (llvm::StructType *STy = 
dyn_cast(CGT.ConvertType(Ty)))
-  Info.setCanBeFlattened(!STy->containsHomogeneousScalableVectorTypes());
-
-return Info;
+return ABIArgInfo::getDirect();
   }
 
   if (const VectorType *VT = Ty->getAs())

``




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


[clang] Add `pragma clang scope [push|pop]` (PR #121025)

2024-12-23 Thread Chris B via cfe-commits

https://github.com/llvm-beanz created 
https://github.com/llvm/llvm-project/pull/121025

Have you ever had that horrible realization that some header you included 
defines a macro that matches a commonly used word that appears throughout your 
codebase? What kind of horrible person would define `max` or `min` as a macro 
and put it into a public header that ships in an SDK?!?!

Well, I have the solution for you!

Enter "Macro Scopes": with this new preprocessor extension you can wrap pesky 
includes with `#pragma clang scope push` and `#pragma clang scope pop` to 
protect your carefully curated source from preprocessor macros that bleed from 
your dependencies.

>From 5433a9134beb8faf1e2b662c96f76d7e8bc814de Mon Sep 17 00:00:00 2001
From: Chris Bieneman 
Date: Mon, 23 Dec 2024 21:22:28 -0600
Subject: [PATCH] Add `pragma clang scope [push|pop]`

Have you ever had that horrible realization that some header you
included defines a macro that matches a commonly used word that appears
throughout your codebase? What kind of horrible person would define
`max` or `min` as a macro and put it into a public header that ships in
an SDK?!?!

Well, I have the solution for you!

Enter "Macro Scopes": with this new preprocessor extension you can wrap
pesky includes with `#pragma clang scope push` and `#pragma clang scope
pop` to protect your carefully curated source from preprocessor macros
that bleed from your dependencies.
---
 clang/docs/LanguageExtensions.rst |  34 ++
 .../include/clang/Basic/DiagnosticLexKinds.td |   4 +-
 clang/include/clang/Lex/Preprocessor.h|   7 +
 clang/lib/Lex/PPMacroExpansion.cpp| 499 ++
 clang/lib/Lex/Pragma.cpp  |  25 +-
 .../Inputs/SomeHeaderThatDefinesAwfulThings.h |   1 +
 clang/test/Lexer/pragma-scope.c   |  36 ++
 7 files changed, 369 insertions(+), 237 deletions(-)
 create mode 100644 clang/test/Lexer/Inputs/SomeHeaderThatDefinesAwfulThings.h
 create mode 100644 clang/test/Lexer/pragma-scope.c

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index cc5f1d4ddf4477..a81fa833eafdc9 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -5738,6 +5738,40 @@ in user headers or code. This is controlled by 
``-Wpedantic-macros``. Final
 macros will always warn on redefinition, including situations with identical
 bodies and in system headers.
 
+Macro Scope
+===
+
+Clang supports the pragma ``#pragma clang scope`` which is provided with an
+argument ``push`` or ``pop`` to denote entering and leaving macro scopes. On
+entering a macro scope all macro definitions and undefinitions are recorded so
+that they can be reverted on leaving the scope.
+
+.. code-block:: c
+
+   #define NUM_DOGGOS 2
+
+   #pragma clang scope push
+   #define NUM_DOGGOS 3
+   #pragma clang scope pop // NUM_DOGGOS is restored to 2
+
+   #pragma clang scope push
+   #undef NUM_DOGGOS
+   #pragma clang scope pop // NUM_DOGGOS is restored to 2
+
+   #undef NUM_DOGGOS
+   #pragma clang scope push
+   #define NUM_DOGGOS 1
+   #pragma clang scope pop // NUM_DOGGOS is restored to undefined
+
+A macro scope can be used to wrap header includes to isolate headers from
+leaking macros to the outer source file.
+
+.. code-block:: c
+
+   #pragma clang scope push
+   #include 
+   #pragma clang scope pop // None of the defines from the included header 
persist.
+
 Line Control
 
 
diff --git a/clang/include/clang/Basic/DiagnosticLexKinds.td 
b/clang/include/clang/Basic/DiagnosticLexKinds.td
index 959376b0847216..a1f57aafb51bf7 100644
--- a/clang/include/clang/Basic/DiagnosticLexKinds.td
+++ b/clang/include/clang/Basic/DiagnosticLexKinds.td
@@ -693,8 +693,8 @@ def warn_pragma_diagnostic_invalid :
ExtWarn<"pragma diagnostic expected 'error', 'warning', 'ignored', 'fatal',"
 " 'push', or 'pop'">,
InGroup;
-def warn_pragma_diagnostic_cannot_pop :
-   ExtWarn<"pragma diagnostic pop could not pop, no matching push">,
+def warn_pragma_cannot_pop :
+   ExtWarn<"pragma %select{diagnostic|scope}0 pop could not pop, no matching 
push">,
InGroup;
 def warn_pragma_diagnostic_invalid_option :
ExtWarn<"pragma diagnostic expected option name (e.g. \"-Wundef\")">,
diff --git a/clang/include/clang/Lex/Preprocessor.h 
b/clang/include/clang/Lex/Preprocessor.h
index 3d223c345ea156..96240533deff5e 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -1059,6 +1059,10 @@ class Preprocessor {
   /// Warning information for macro annotations.
   llvm::DenseMap AnnotationInfos;
 
+  using MacroScopeVec = llvm::SmallVector >;
+  MacroScopeVec *CurScope = nullptr;
+  llvm::SmallVector MacroScopeStack;
+
   /// A "freelist" of MacroArg objects that can be
   /// reused for quick allocation.
   MacroArgs *MacroArgCache = nullptr;
@@ -2896,6 +2900,9 @@ class Preprocessor {
 AnnotationInfos[II].FinalAnnotationLoc = Annotat

[clang] [clang][RISCV] Remove unneeded RISCV tuple code (PR #121024)

2024-12-23 Thread Pengcheng Wang via cfe-commits

https://github.com/wangpc-pp approved this pull request.

LGTM. Nice cleanup.

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


[clang] Add `pragma clang scope [push|pop]` (PR #121025)

2024-12-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Chris B (llvm-beanz)


Changes

Have you ever had that horrible realization that some header you included 
defines a macro that matches a commonly used word that appears throughout your 
codebase? What kind of horrible person would define `max` or `min` as a macro 
and put it into a public header that ships in an SDK?!?!

Well, I have the solution for you!

Enter "Macro Scopes": with this new preprocessor extension you can wrap pesky 
includes with `#pragma clang scope push` and `#pragma clang scope pop` to 
protect your carefully curated source from preprocessor macros that bleed from 
your dependencies.

---

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


7 Files Affected:

- (modified) clang/docs/LanguageExtensions.rst (+34) 
- (modified) clang/include/clang/Basic/DiagnosticLexKinds.td (+2-2) 
- (modified) clang/include/clang/Lex/Preprocessor.h (+7) 
- (modified) clang/lib/Lex/PPMacroExpansion.cpp (+266-233) 
- (modified) clang/lib/Lex/Pragma.cpp (+23-2) 
- (added) clang/test/Lexer/Inputs/SomeHeaderThatDefinesAwfulThings.h (+1) 
- (added) clang/test/Lexer/pragma-scope.c (+36) 


``diff
diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index cc5f1d4ddf4477..a81fa833eafdc9 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -5738,6 +5738,40 @@ in user headers or code. This is controlled by 
``-Wpedantic-macros``. Final
 macros will always warn on redefinition, including situations with identical
 bodies and in system headers.
 
+Macro Scope
+===
+
+Clang supports the pragma ``#pragma clang scope`` which is provided with an
+argument ``push`` or ``pop`` to denote entering and leaving macro scopes. On
+entering a macro scope all macro definitions and undefinitions are recorded so
+that they can be reverted on leaving the scope.
+
+.. code-block:: c
+
+   #define NUM_DOGGOS 2
+
+   #pragma clang scope push
+   #define NUM_DOGGOS 3
+   #pragma clang scope pop // NUM_DOGGOS is restored to 2
+
+   #pragma clang scope push
+   #undef NUM_DOGGOS
+   #pragma clang scope pop // NUM_DOGGOS is restored to 2
+
+   #undef NUM_DOGGOS
+   #pragma clang scope push
+   #define NUM_DOGGOS 1
+   #pragma clang scope pop // NUM_DOGGOS is restored to undefined
+
+A macro scope can be used to wrap header includes to isolate headers from
+leaking macros to the outer source file.
+
+.. code-block:: c
+
+   #pragma clang scope push
+   #include 
+   #pragma clang scope pop // None of the defines from the included header 
persist.
+
 Line Control
 
 
diff --git a/clang/include/clang/Basic/DiagnosticLexKinds.td 
b/clang/include/clang/Basic/DiagnosticLexKinds.td
index 959376b0847216..a1f57aafb51bf7 100644
--- a/clang/include/clang/Basic/DiagnosticLexKinds.td
+++ b/clang/include/clang/Basic/DiagnosticLexKinds.td
@@ -693,8 +693,8 @@ def warn_pragma_diagnostic_invalid :
ExtWarn<"pragma diagnostic expected 'error', 'warning', 'ignored', 'fatal',"
 " 'push', or 'pop'">,
InGroup;
-def warn_pragma_diagnostic_cannot_pop :
-   ExtWarn<"pragma diagnostic pop could not pop, no matching push">,
+def warn_pragma_cannot_pop :
+   ExtWarn<"pragma %select{diagnostic|scope}0 pop could not pop, no matching 
push">,
InGroup;
 def warn_pragma_diagnostic_invalid_option :
ExtWarn<"pragma diagnostic expected option name (e.g. \"-Wundef\")">,
diff --git a/clang/include/clang/Lex/Preprocessor.h 
b/clang/include/clang/Lex/Preprocessor.h
index 3d223c345ea156..96240533deff5e 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -1059,6 +1059,10 @@ class Preprocessor {
   /// Warning information for macro annotations.
   llvm::DenseMap AnnotationInfos;
 
+  using MacroScopeVec = llvm::SmallVector >;
+  MacroScopeVec *CurScope = nullptr;
+  llvm::SmallVector MacroScopeStack;
+
   /// A "freelist" of MacroArg objects that can be
   /// reused for quick allocation.
   MacroArgs *MacroArgCache = nullptr;
@@ -2896,6 +2900,9 @@ class Preprocessor {
 AnnotationInfos[II].FinalAnnotationLoc = AnnotationLoc;
   }
 
+  void pushMacroScope();
+  void popMacroScope(SourceLocation Loc);
+
   const MacroAnnotations &getMacroAnnotations(const IdentifierInfo *II) const {
 return AnnotationInfos.find(II)->second;
   }
diff --git a/clang/lib/Lex/PPMacroExpansion.cpp 
b/clang/lib/Lex/PPMacroExpansion.cpp
index 347c13da0ad215..f47a2eb1a37caf 100644
--- a/clang/lib/Lex/PPMacroExpansion.cpp
+++ b/clang/lib/Lex/PPMacroExpansion.cpp
@@ -66,7 +66,35 @@ Preprocessor::getLocalMacroDirectiveHistory(const 
IdentifierInfo *II) const {
 : Pos->second.getLatest();
 }
 
-void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective 
*MD){
+void Preprocessor::pushMacroScope() {
+  MacroScopeStack.emplace_back(MacroScopeVec());
+  C

[clang] Add `pragma clang scope [push|pop]` (PR #121025)

2024-12-23 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 2c95e60df53ba1a5765b3fad9e8ddaff70f21994 
5433a9134beb8faf1e2b662c96f76d7e8bc814de --extensions h,c,cpp -- 
clang/test/Lexer/Inputs/SomeHeaderThatDefinesAwfulThings.h 
clang/test/Lexer/pragma-scope.c clang/include/clang/Lex/Preprocessor.h 
clang/lib/Lex/PPMacroExpansion.cpp clang/lib/Lex/Pragma.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/include/clang/Lex/Preprocessor.h 
b/clang/include/clang/Lex/Preprocessor.h
index 96240533de..7d9292d072 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -1059,7 +1059,8 @@ private:
   /// Warning information for macro annotations.
   llvm::DenseMap AnnotationInfos;
 
-  using MacroScopeVec = llvm::SmallVector >;
+  using MacroScopeVec =
+  llvm::SmallVector>;
   MacroScopeVec *CurScope = nullptr;
   llvm::SmallVector MacroScopeStack;
 
diff --git a/clang/lib/Lex/PPMacroExpansion.cpp 
b/clang/lib/Lex/PPMacroExpansion.cpp
index f47a2eb1a3..ecc37bbd01 100644
--- a/clang/lib/Lex/PPMacroExpansion.cpp
+++ b/clang/lib/Lex/PPMacroExpansion.cpp
@@ -80,9 +80,9 @@ void Preprocessor::popMacroScope(SourceLocation Loc) {
   for (auto It = CurScope->rbegin(); It != CurScope->rend(); ++It) {
 MacroDirective *Prev = It->second->getPrevious();
 if (Prev && Prev->getKind() == MacroDirective::MD_Define) {
-DefMacroDirective *MD =
-AllocateDefMacroDirective(Prev->getMacroInfo(), Loc);
-appendMacroDirective(It->first, MD);
+  DefMacroDirective *MD =
+  AllocateDefMacroDirective(Prev->getMacroInfo(), Loc);
+  appendMacroDirective(It->first, MD);
 } else {
   UndefMacroDirective *Undef = AllocateUndefMacroDirective(Loc);
   appendMacroDirective(It->first, Undef);
@@ -105,7 +105,7 @@ void Preprocessor::appendMacroDirective(IdentifierInfo *II,
   StoredMD.overrideActiveModuleMacros(*this, II);
 
   if (CurScope)
-CurScope->push_back(std::make_pair(II,MD));
+CurScope->push_back(std::make_pair(II, MD));
 
   if (needModuleMacros()) {
 // Track that we created a new macro directive, so we know we should
@@ -1192,8 +1192,8 @@ static bool HasExtension(const Preprocessor &PP, 
StringRef Extension) {
   Extension.size() >= 4)
 Extension = Extension.substr(2, Extension.size() - 4);
 
-  // Because we inherit the feature list from HasFeature, this string switch
-  // must be less restrictive than HasFeature's.
+// Because we inherit the feature list from HasFeature, this string switch
+// must be less restrictive than HasFeature's.
 #define EXTENSION(Name, Predicate) .Case(#Name, Predicate)
   return llvm::StringSwitch(Extension)
 #include "clang/Basic/Features.def"

``




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


[clang] [SYCL] Basic diagnostics for the sycl_kernel_entry_point attribute. (PR #120327)

2024-12-23 Thread Tom Honermann via cfe-commits


@@ -12408,6 +12408,29 @@ def err_sycl_special_type_num_init_method : Error<
   "types with 'sycl_special_class' attribute must have one and only one 
'__init' "
   "method defined">;
 
+// SYCL kernel entry point diagnostics
+def err_sycl_entry_point_invalid : Error<
+  "'sycl_kernel_entry_point' attribute cannot be applied to a"
+  " %select{non-static member|variadic|deleted|defaulted|constexpr|consteval|"
+   "noreturn|coroutine}0 function">;
+def err_sycl_entry_point_invalid_redeclaration : Error<
+  "'sycl_kernel_entry_point' kernel name argument does not match prior"
+  " declaration%diff{: $ vs $|}0,1">;
+def err_sycl_kernel_name_conflict : Error<
+  "'sycl_kernel_entry_point' kernel name argument conflicts with a previous"
+  " declaration">;
+def warn_sycl_kernel_name_not_a_class_type : Warning<
+  "%0 is not a valid SYCL kernel name type; a class type is required">,

tahonermann wrote:

Done. I stuck with "non-union class" since the SYCL specification just says 
"class". We can revisit if/when the SYCL specification is updated to better 
specify its intent.

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


[clang] [SYCL] Basic diagnostics for the sycl_kernel_entry_point attribute. (PR #120327)

2024-12-23 Thread Tom Honermann via cfe-commits


@@ -206,3 +208,124 @@ void SemaSYCL::handleKernelEntryPointAttr(Decl *D, const 
ParsedAttr &AL) {
   D->addAttr(::new (SemaRef.Context)
  SYCLKernelEntryPointAttr(SemaRef.Context, AL, TSI));
 }
+
+static SourceLocation SourceLocationForType(QualType QT) {
+  SourceLocation Loc;
+  const Type *T = QT->getUnqualifiedDesugaredType();
+  if (const TagType *TT = dyn_cast(T))
+Loc = TT->getDecl()->getLocation();
+  else if (const ObjCInterfaceType *ObjCIT = dyn_cast(T))
+Loc = ObjCIT->getDecl()->getLocation();
+  return Loc;
+}
+
+static bool CheckSYCLKernelName(Sema &S, SourceLocation Loc,
+QualType KernelName) {
+  assert(!KernelName->isDependentType());
+
+  if (!KernelName->isStructureOrClassType()) {
+// SYCL 2020 section 5.2, "Naming of kernels", only requires that the
+// kernel name be a C++ typename. However, the definition of "kernel name"
+// in the glossary states that a kernel name is a class type. Neither
+// section explicitly states whether the kernel name type can be
+// cv-qualified. For now, kernel name types are required to be class types
+// and that they may be cv-qualified. The following issue requests
+// clarification from the SYCL WG.
+//   https://github.com/KhronosGroup/SYCL-Docs/issues/568
+S.Diag(Loc, diag::warn_sycl_kernel_name_not_a_class_type) << KernelName;
+SourceLocation DeclTypeLoc = SourceLocationForType(KernelName);
+if (DeclTypeLoc.isValid())
+  S.Diag(DeclTypeLoc, diag::note_entity_declared_at) << KernelName;
+return true;
+  }
+
+  return false;
+}
+
+void SemaSYCL::CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD) {
+  // Ensure that all attributes present on the declaration are consistent
+  // and warn about any redundant ones.
+  const SYCLKernelEntryPointAttr *SKEPAttr = nullptr;
+  for (auto SAI = FD->specific_attr_begin();

tahonermann wrote:

I swear I had looked for an interface that provided a range of 
specific/filtered attributes and didn't find one. But it is there! I made a 
change to use `Decl::specific_attrs()` and a range-based for loop. That is a 
definite improvement. This still means that `specific_attr_iterator` is used, 
but as implementation detail. It looks like someone so motivated could change 
`Decl::specific_attrs()` to return a filter range as you suggest and 
deprecate/remove the iterator interfaces after transitioning the few uses of 
those. The changes I made should not require any further modifications to work 
with a filter range.

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


[clang] [SYCL] Basic diagnostics for the sycl_kernel_entry_point attribute. (PR #120327)

2024-12-23 Thread Tom Honermann via cfe-commits


@@ -206,3 +208,124 @@ void SemaSYCL::handleKernelEntryPointAttr(Decl *D, const 
ParsedAttr &AL) {
   D->addAttr(::new (SemaRef.Context)
  SYCLKernelEntryPointAttr(SemaRef.Context, AL, TSI));
 }
+
+static SourceLocation SourceLocationForType(QualType QT) {
+  SourceLocation Loc;
+  const Type *T = QT->getUnqualifiedDesugaredType();
+  if (const TagType *TT = dyn_cast(T))
+Loc = TT->getDecl()->getLocation();
+  else if (const ObjCInterfaceType *ObjCIT = dyn_cast(T))
+Loc = ObjCIT->getDecl()->getLocation();
+  return Loc;
+}
+
+static bool CheckSYCLKernelName(Sema &S, SourceLocation Loc,
+QualType KernelName) {
+  assert(!KernelName->isDependentType());
+
+  if (!KernelName->isStructureOrClassType()) {
+// SYCL 2020 section 5.2, "Naming of kernels", only requires that the
+// kernel name be a C++ typename. However, the definition of "kernel name"
+// in the glossary states that a kernel name is a class type. Neither
+// section explicitly states whether the kernel name type can be
+// cv-qualified. For now, kernel name types are required to be class types
+// and that they may be cv-qualified. The following issue requests
+// clarification from the SYCL WG.
+//   https://github.com/KhronosGroup/SYCL-Docs/issues/568
+S.Diag(Loc, diag::warn_sycl_kernel_name_not_a_class_type) << KernelName;
+SourceLocation DeclTypeLoc = SourceLocationForType(KernelName);
+if (DeclTypeLoc.isValid())
+  S.Diag(DeclTypeLoc, diag::note_entity_declared_at) << KernelName;
+return true;
+  }
+
+  return false;
+}
+
+void SemaSYCL::CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD) {
+  // Ensure that all attributes present on the declaration are consistent
+  // and warn about any redundant ones.
+  const SYCLKernelEntryPointAttr *SKEPAttr = nullptr;
+  for (auto SAI = FD->specific_attr_begin();
+   SAI != FD->specific_attr_end(); ++SAI) {
+if (!SKEPAttr) {
+  SKEPAttr = *SAI;
+  continue;
+}
+if (!getASTContext().hasSameType(SAI->getKernelName(),
+ SKEPAttr->getKernelName())) {
+  Diag(SAI->getLocation(), 
diag::err_sycl_entry_point_invalid_redeclaration)
+  << SAI->getKernelName() << SKEPAttr->getKernelName();
+  Diag(SKEPAttr->getLocation(), diag::note_previous_attribute);
+} else {
+  Diag(SAI->getLocation(),
+   diag::warn_sycl_entry_point_redundant_declaration);
+  Diag(SKEPAttr->getLocation(), diag::note_previous_attribute);
+}
+  }
+  assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
+
+  // Ensure the kernel name type is valid.
+  if (!SKEPAttr->getKernelName()->isDependentType()) {
+CheckSYCLKernelName(SemaRef, SKEPAttr->getLocation(),
+SKEPAttr->getKernelName());
+  }
+
+  // Ensure that an attribute present on the previous declaration
+  // matches the one on this declaration.
+  FunctionDecl *PrevFD = FD->getPreviousDecl();
+  if (PrevFD && !PrevFD->isInvalidDecl()) {
+const auto *PrevSKEPAttr = PrevFD->getAttr();
+if (PrevSKEPAttr) {
+  if (!getASTContext().hasSameType(SKEPAttr->getKernelName(),
+   PrevSKEPAttr->getKernelName())) {
+Diag(SKEPAttr->getLocation(),
+ diag::err_sycl_entry_point_invalid_redeclaration)
+<< SKEPAttr->getKernelName() << PrevSKEPAttr->getKernelName();
+Diag(PrevSKEPAttr->getLocation(), diag::note_previous_decl) << PrevFD;
+  }
+}
+  }
+
+  if (auto *MD = dyn_cast(FD)) {

tahonermann wrote:

Done.

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


[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-23 Thread Stephen Senran Zhang via cfe-commits

zsrkmyn wrote:

Ah, by applying the patch below, I just found the lower bound is still not 
optimal for non-wrapped cases. E.g., for 4-bit ints, given 2 ranges,

```
[0011, ]
[1101, ]
```

the optimal lower bound is 1, while the algorithm gives 0.

```diff
diff --git a/llvm/unittests/IR/ConstantRangeTest.cpp 
b/llvm/unittests/IR/ConstantRangeTest.cpp
index e1d9b3e387b2..74a49e6842cb 100644
--- a/llvm/unittests/IR/ConstantRangeTest.cpp
+++ b/llvm/unittests/IR/ConstantRangeTest.cpp
@@ -112,6 +112,10 @@ bool PreferSmallestNonFullSigned(const ConstantRange &CR1,
   return PreferSmallestSigned(CR1, CR2);
 }
 
+bool PreferSmallerLowerBound(const ConstantRange &CR1, const ConstantRange 
&CR2) {
+  return CR1.getLower().ult(CR2.getLower());
+}
+
 testing::AssertionResult rangeContains(const ConstantRange &CR, const APInt &N,
ArrayRef Inputs) {
   if (CR.contains(N))
@@ -2726,6 +2730,13 @@ TEST_F(ConstantRangeTest, binaryAnd) {
   },
   [](const APInt &N1, const APInt &N2) { return N1 & N2; }, PreferSmallest,
   CheckSingleElementsOnly);
+
+  TestBinaryOpExhaustive(
+  [](const ConstantRange &CR1, const ConstantRange &CR2) {
+return CR1.binaryAnd(CR2);
+  },
+  [](const APInt &N1, const APInt &N2) { return N1 & N2; },
+  PreferSmallerLowerBound, CheckNonWrappedOnly);
 }
 
 TEST_F(ConstantRangeTest, binaryOr) {
```

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


[clang] [SYCL] Basic diagnostics for the sycl_kernel_entry_point attribute. (PR #120327)

2024-12-23 Thread Tom Honermann via cfe-commits


@@ -12408,6 +12408,29 @@ def err_sycl_special_type_num_init_method : Error<
   "types with 'sycl_special_class' attribute must have one and only one 
'__init' "
   "method defined">;
 
+// SYCL kernel entry point diagnostics
+def err_sycl_entry_point_invalid : Error<
+  "'sycl_kernel_entry_point' attribute cannot be applied to a"
+  " %select{non-static member|variadic|deleted|defaulted|constexpr|consteval|"
+   "noreturn|coroutine}0 function">;

tahonermann wrote:

Done. I avoided the additional `%select` by duplicating " function" for the 
relevant cases. I also changed the wording for the noreturn case from "no 
return function" to "function declared with the 'noreturn' attribute".

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


[clang] [clang-tools-extra] [libcxx] [llvm] [libc++] implement views::concat (PR #120920)

2024-12-23 Thread Nhat Nguyen via cfe-commits

https://github.com/changkhothuychung updated 
https://github.com/llvm/llvm-project/pull/120920

error: too big or took too long to generate
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [SYCL] Basic diagnostics for the sycl_kernel_entry_point attribute. (PR #120327)

2024-12-23 Thread Tom Honermann via cfe-commits


@@ -206,3 +208,124 @@ void SemaSYCL::handleKernelEntryPointAttr(Decl *D, const 
ParsedAttr &AL) {
   D->addAttr(::new (SemaRef.Context)
  SYCLKernelEntryPointAttr(SemaRef.Context, AL, TSI));
 }
+
+static SourceLocation SourceLocationForType(QualType QT) {
+  SourceLocation Loc;
+  const Type *T = QT->getUnqualifiedDesugaredType();
+  if (const TagType *TT = dyn_cast(T))
+Loc = TT->getDecl()->getLocation();
+  else if (const ObjCInterfaceType *ObjCIT = dyn_cast(T))
+Loc = ObjCIT->getDecl()->getLocation();
+  return Loc;
+}
+
+static bool CheckSYCLKernelName(Sema &S, SourceLocation Loc,
+QualType KernelName) {
+  assert(!KernelName->isDependentType());
+
+  if (!KernelName->isStructureOrClassType()) {
+// SYCL 2020 section 5.2, "Naming of kernels", only requires that the
+// kernel name be a C++ typename. However, the definition of "kernel name"
+// in the glossary states that a kernel name is a class type. Neither
+// section explicitly states whether the kernel name type can be
+// cv-qualified. For now, kernel name types are required to be class types
+// and that they may be cv-qualified. The following issue requests
+// clarification from the SYCL WG.
+//   https://github.com/KhronosGroup/SYCL-Docs/issues/568
+S.Diag(Loc, diag::warn_sycl_kernel_name_not_a_class_type) << KernelName;
+SourceLocation DeclTypeLoc = SourceLocationForType(KernelName);
+if (DeclTypeLoc.isValid())
+  S.Diag(DeclTypeLoc, diag::note_entity_declared_at) << KernelName;
+return true;
+  }
+
+  return false;
+}
+
+void SemaSYCL::CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD) {
+  // Ensure that all attributes present on the declaration are consistent
+  // and warn about any redundant ones.
+  const SYCLKernelEntryPointAttr *SKEPAttr = nullptr;
+  for (auto SAI = FD->specific_attr_begin();
+   SAI != FD->specific_attr_end(); ++SAI) {
+if (!SKEPAttr) {
+  SKEPAttr = *SAI;
+  continue;
+}
+if (!getASTContext().hasSameType(SAI->getKernelName(),
+ SKEPAttr->getKernelName())) {
+  Diag(SAI->getLocation(), 
diag::err_sycl_entry_point_invalid_redeclaration)
+  << SAI->getKernelName() << SKEPAttr->getKernelName();
+  Diag(SKEPAttr->getLocation(), diag::note_previous_attribute);
+} else {
+  Diag(SAI->getLocation(),
+   diag::warn_sycl_entry_point_redundant_declaration);
+  Diag(SKEPAttr->getLocation(), diag::note_previous_attribute);
+}
+  }
+  assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
+
+  // Ensure the kernel name type is valid.
+  if (!SKEPAttr->getKernelName()->isDependentType()) {
+CheckSYCLKernelName(SemaRef, SKEPAttr->getLocation(),
+SKEPAttr->getKernelName());
+  }
+
+  // Ensure that an attribute present on the previous declaration
+  // matches the one on this declaration.
+  FunctionDecl *PrevFD = FD->getPreviousDecl();
+  if (PrevFD && !PrevFD->isInvalidDecl()) {
+const auto *PrevSKEPAttr = PrevFD->getAttr();
+if (PrevSKEPAttr) {
+  if (!getASTContext().hasSameType(SKEPAttr->getKernelName(),
+   PrevSKEPAttr->getKernelName())) {
+Diag(SKEPAttr->getLocation(),
+ diag::err_sycl_entry_point_invalid_redeclaration)
+<< SKEPAttr->getKernelName() << PrevSKEPAttr->getKernelName();
+Diag(PrevSKEPAttr->getLocation(), diag::note_previous_decl) << PrevFD;
+  }
+}
+  }
+
+  if (auto *MD = dyn_cast(FD)) {
+if (!MD->isStatic()) {
+  Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
+  << /*non-static member function*/ 0;
+}

tahonermann wrote:

Done.

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


[clang] [SYCL] Basic diagnostics for the sycl_kernel_entry_point attribute. (PR #120327)

2024-12-23 Thread Tom Honermann via cfe-commits


@@ -1134,8 +1134,18 @@ void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
   // the presence of a sycl_kernel_entry_point attribute, register it so that
   // associated metadata is recreated.
   if (FD->hasAttr()) {
+const auto *SKEPAttr = FD->getAttr();
 ASTContext &C = Reader.getContext();
-C.registerSYCLEntryPointFunction(FD);
+const SYCLKernelInfo *SKI = 
C.findSYCLKernelInfo(SKEPAttr->getKernelName());
+if (SKI) {
+  if (!declaresSameEntity(FD, SKI->getKernelEntryPointDecl())) {
+Reader.Diag(FD->getLocation(), diag::err_sycl_kernel_name_conflict);

tahonermann wrote:

The diagnostic being issued here is specifically for PCH/modules related 
scenarios. See the `sycl-kernel-entry-point-attr-kernel-name-module.cpp` and 
`sycl-kernel-entry-point-attr-kernel-name-pch.cpp` tests in 
`clang/test/SemaSYCL`.

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


[clang] [Coverage] Introduce `getBranchCounterPair()`. NFC. (PR #112702)

2024-12-23 Thread NAKAMURA Takumi via cfe-commits

https://github.com/chapuni updated 
https://github.com/llvm/llvm-project/pull/112702

>From fc697f04fd6c9f3c217ce04e3f1dd082c1f1a705 Mon Sep 17 00:00:00 2001
From: NAKAMURA Takumi 
Date: Wed, 16 Oct 2024 23:16:53 +0900
Subject: [PATCH 1/5] [Coverage] Introduce `getBranchCounterPair()`. NFC.

This aggregates the generation of branch counter pair as `ExecCnt` and
`SkipCnt`, to aggregate `CounterExpr::subtract`. At the moment:

- This change preserves the behavior of
  `llvm::EnableSingleByteCoverage`. Almost of SingleByteCoverage will
  be cleaned up by coming commits.

- `getBranchCounterPair()` is not called in
  `llvm::EnableSingleByteCoverage`. I will implement the new behavior
  of SingleByteCoverage in it.

- `IsCounterEqual(Out, Par)` is introduced instead of
  `Counter::operator==`. Tweaks would be required for the comparison
  for additional counters.

- Braces around `assert()` is intentional. I will add a statement there.

https://discourse.llvm.org/t/rfc-integrating-singlebytecoverage-with-branch-coverage/82492
---
 clang/lib/CodeGen/CoverageMappingGen.cpp | 177 +--
 1 file changed, 102 insertions(+), 75 deletions(-)

diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 07015834bc84f3..0bfad9cbcbe12b 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -941,6 +941,19 @@ struct CounterCoverageMappingBuilder
 return Counter::getCounter(CounterMap[S]);
   }
 
+  std::pair getBranchCounterPair(const Stmt *S,
+   Counter ParentCnt) {
+Counter ExecCnt = getRegionCounter(S);
+return {ExecCnt, Builder.subtract(ParentCnt, ExecCnt)};
+  }
+
+  bool IsCounterEqual(Counter OutCount, Counter ParentCount) {
+if (OutCount == ParentCount)
+  return true;
+
+return false;
+  }
+
   /// Push a region onto the stack.
   ///
   /// Returns the index on the stack where the region was pushed. This can be
@@ -1592,6 +1605,13 @@ struct CounterCoverageMappingBuilder
 llvm::EnableSingleByteCoverage
 ? getRegionCounter(S->getCond())
 : addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
+auto [ExecCount, ExitCount] =
+(llvm::EnableSingleByteCoverage
+ ? std::make_pair(getRegionCounter(S), Counter::getZero())
+ : getBranchCounterPair(S, CondCount));
+if (!llvm::EnableSingleByteCoverage) {
+  assert(ExecCount.isZero() || ExecCount == BodyCount);
+}
 propagateCounts(CondCount, S->getCond());
 adjustForOutOfOrderTraversal(getEnd(S));
 
@@ -1600,13 +1620,11 @@ struct CounterCoverageMappingBuilder
 if (Gap)
   fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
 
-Counter OutCount =
-llvm::EnableSingleByteCoverage
-? getRegionCounter(S)
-: addCounters(BC.BreakCount,
-  subtractCounters(CondCount, BodyCount));
+Counter OutCount = llvm::EnableSingleByteCoverage
+   ? getRegionCounter(S)
+   : addCounters(BC.BreakCount, ExitCount);
 
-if (OutCount != ParentCount) {
+if (!IsCounterEqual(OutCount, ParentCount)) {
   pushRegion(OutCount);
   GapRegionCounter = OutCount;
   if (BodyHasTerminateStmt)
@@ -1615,8 +1633,7 @@ struct CounterCoverageMappingBuilder
 
 // Create Branch Region around condition.
 if (!llvm::EnableSingleByteCoverage)
-  createBranchRegion(S->getCond(), BodyCount,
- subtractCounters(CondCount, BodyCount));
+  createBranchRegion(S->getCond(), BodyCount, ExitCount);
   }
 
   void VisitDoStmt(const DoStmt *S) {
@@ -1645,22 +1662,26 @@ struct CounterCoverageMappingBuilder
 Counter CondCount = llvm::EnableSingleByteCoverage
 ? getRegionCounter(S->getCond())
 : addCounters(BackedgeCount, BC.ContinueCount);
+auto [ExecCount, ExitCount] =
+(llvm::EnableSingleByteCoverage
+ ? std::make_pair(getRegionCounter(S), Counter::getZero())
+ : getBranchCounterPair(S, CondCount));
+if (!llvm::EnableSingleByteCoverage) {
+  assert(ExecCount.isZero() || ExecCount == BodyCount);
+}
 propagateCounts(CondCount, S->getCond());
 
-Counter OutCount =
-llvm::EnableSingleByteCoverage
-? getRegionCounter(S)
-: addCounters(BC.BreakCount,
-  subtractCounters(CondCount, BodyCount));
-if (OutCount != ParentCount) {
+Counter OutCount = llvm::EnableSingleByteCoverage
+   ? getRegionCounter(S)
+   : addCounters(BC.BreakCount, ExitCount);
+if (!IsCounterEqual(OutCount, ParentCount)) {
   pushRegion(OutCount);
   GapRegionCounter = OutCount;
 }
 
 // Create Branch Region around condition.
 if (!llvm::EnableSingleByteCoverage)
-

[clang] [SYCL] Basic diagnostics for the sycl_kernel_entry_point attribute. (PR #120327)

2024-12-23 Thread Tom Honermann via cfe-commits

https://github.com/tahonermann updated 
https://github.com/llvm/llvm-project/pull/120327

>From 6ed96d3bf22c5da5af995ea5ffe083baf91594bb Mon Sep 17 00:00:00 2001
From: Tom Honermann 
Date: Fri, 1 Nov 2024 16:03:24 -0700
Subject: [PATCH 1/6] [SYCL] Basic diagnostics for the sycl_kernel_entry_point
 attribute.

The `sycl_kernel_entry_point` attribute is used to declare a function that
defines a pattern for an offload kernel entry point. The attribute requires
a single type argument that specifies a class type that meets the requirements
for a SYCL kernel name as described in section 5.2, "Naming of kernels", of
the SYCL 2020 specification. A unique kernel name type is required for each
function declared with the attribute. The attribute may not first appear on a
declaration that follows a definition of the function. The function is
required to have a `void` return type. The function must not be a non-static
member function, be deleted or defaulted, be declared with the `constexpr` or
`consteval` specifiers, be declared with the `[[noreturn]]` attribute, be a
coroutine, or accept variadic arguments.

Diagnostics are not yet provided for the following:
- Use of a type as a kernel name that does not satisfy the forward
  declarability requirements specified in section 5.2, "Naming of kernels",
  of the SYCL 2020 specification.
- Use of a type as a parameter of the attributed function that does not
  satisfy the kernel parameter requirements specified in section 4.12.4,
  "Rules for parameter passing to kernels", of the SYCL 2020 specification
  (each such function parameter constitutes a kernel parameter).
- Use of language features that are not permitted in device functions as
  specified in section 5.4, "Language restrictions for device functions",
  of the SYCL 2020 specification.

There are several issues noted by various FIXME comments.
- The diagnostic generated for kernel name conflicts needs additional work
  to better detail the relevant source locations; such as the location of
  each declaration as well as the original source of each kernel name.
- A number of the tests illustrate spurious errors being produced due to
  attributes that appertain to function templates being instantiated too
  early (during overload resolution as opposed to after an overload is
  selected).
---
 clang/include/clang/AST/ASTContext.h  |  10 +
 clang/include/clang/Basic/DiagnosticGroups.td |   1 +
 .../clang/Basic/DiagnosticSemaKinds.td|  23 ++
 clang/include/clang/Sema/SemaSYCL.h   |   2 +
 clang/lib/AST/ASTContext.cpp  |  13 +
 clang/lib/Sema/SemaDecl.cpp   |  30 ++-
 clang/lib/Sema/SemaSYCL.cpp   | 126 +
 clang/lib/Sema/SemaTemplate.cpp   |   2 +
 clang/lib/Serialization/ASTReaderDecl.cpp |  13 +-
 .../ast-dump-sycl-kernel-entry-point.cpp  |  23 +-
 ...-kernel-entry-point-attr-appertainment.cpp | 255 ++
 .../sycl-kernel-entry-point-attr-grammar.cpp  |  15 --
 ...el-entry-point-attr-kernel-name-module.cpp | 104 +++
 ...ernel-entry-point-attr-kernel-name-pch.cpp |  36 +++
 ...cl-kernel-entry-point-attr-kernel-name.cpp |  87 ++
 .../sycl-kernel-entry-point-attr-sfinae.cpp   |  65 +
 16 files changed, 784 insertions(+), 21 deletions(-)
 create mode 100644 
clang/test/SemaSYCL/sycl-kernel-entry-point-attr-appertainment.cpp
 create mode 100644 
clang/test/SemaSYCL/sycl-kernel-entry-point-attr-kernel-name-module.cpp
 create mode 100644 
clang/test/SemaSYCL/sycl-kernel-entry-point-attr-kernel-name-pch.cpp
 create mode 100644 
clang/test/SemaSYCL/sycl-kernel-entry-point-attr-kernel-name.cpp
 create mode 100644 clang/test/SemaSYCL/sycl-kernel-entry-point-attr-sfinae.cpp

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 1e89a6805ce9c6..0e07c5d6ce8fba 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -3360,6 +3360,16 @@ class ASTContext : public RefCountedBase {
   /// this function.
   void registerSYCLEntryPointFunction(FunctionDecl *FD);
 
+  /// Given a type used as a SYCL kernel name, returns a reference to the
+  /// metadata generated from the corresponding SYCL kernel entry point.
+  /// Aborts if the provided type is not a registered SYCL kernel name.
+  const SYCLKernelInfo &getSYCLKernelInfo(QualType T) const;
+
+  /// Returns a pointer to the metadata generated from the corresponding
+  /// SYCLkernel entry point if the provided type corresponds to a registered
+  /// SYCL kernel name. Returns a null pointer otherwise.
+  const SYCLKernelInfo *findSYCLKernelInfo(QualType T) const;
+
   
//======//
   //Statistics
   
//======//
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 3ac490d3

[clang] [SYCL] Basic diagnostics for the sycl_kernel_entry_point attribute. (PR #120327)

2024-12-23 Thread Tom Honermann via cfe-commits


@@ -206,3 +208,124 @@ void SemaSYCL::handleKernelEntryPointAttr(Decl *D, const 
ParsedAttr &AL) {
   D->addAttr(::new (SemaRef.Context)
  SYCLKernelEntryPointAttr(SemaRef.Context, AL, TSI));
 }
+
+static SourceLocation SourceLocationForType(QualType QT) {
+  SourceLocation Loc;
+  const Type *T = QT->getUnqualifiedDesugaredType();
+  if (const TagType *TT = dyn_cast(T))
+Loc = TT->getDecl()->getLocation();
+  else if (const ObjCInterfaceType *ObjCIT = dyn_cast(T))
+Loc = ObjCIT->getDecl()->getLocation();
+  return Loc;
+}
+
+static bool CheckSYCLKernelName(Sema &S, SourceLocation Loc,
+QualType KernelName) {
+  assert(!KernelName->isDependentType());
+
+  if (!KernelName->isStructureOrClassType()) {
+// SYCL 2020 section 5.2, "Naming of kernels", only requires that the
+// kernel name be a C++ typename. However, the definition of "kernel name"
+// in the glossary states that a kernel name is a class type. Neither
+// section explicitly states whether the kernel name type can be
+// cv-qualified. For now, kernel name types are required to be class types
+// and that they may be cv-qualified. The following issue requests
+// clarification from the SYCL WG.
+//   https://github.com/KhronosGroup/SYCL-Docs/issues/568
+S.Diag(Loc, diag::warn_sycl_kernel_name_not_a_class_type) << KernelName;
+SourceLocation DeclTypeLoc = SourceLocationForType(KernelName);
+if (DeclTypeLoc.isValid())
+  S.Diag(DeclTypeLoc, diag::note_entity_declared_at) << KernelName;
+return true;
+  }
+
+  return false;
+}
+
+void SemaSYCL::CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD) {
+  // Ensure that all attributes present on the declaration are consistent
+  // and warn about any redundant ones.
+  const SYCLKernelEntryPointAttr *SKEPAttr = nullptr;
+  for (auto SAI = FD->specific_attr_begin();
+   SAI != FD->specific_attr_end(); ++SAI) {
+if (!SKEPAttr) {
+  SKEPAttr = *SAI;
+  continue;
+}
+if (!getASTContext().hasSameType(SAI->getKernelName(),
+ SKEPAttr->getKernelName())) {
+  Diag(SAI->getLocation(), 
diag::err_sycl_entry_point_invalid_redeclaration)
+  << SAI->getKernelName() << SKEPAttr->getKernelName();
+  Diag(SKEPAttr->getLocation(), diag::note_previous_attribute);
+} else {
+  Diag(SAI->getLocation(),
+   diag::warn_sycl_entry_point_redundant_declaration);
+  Diag(SKEPAttr->getLocation(), diag::note_previous_attribute);
+}
+  }
+  assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
+
+  // Ensure the kernel name type is valid.
+  if (!SKEPAttr->getKernelName()->isDependentType()) {
+CheckSYCLKernelName(SemaRef, SKEPAttr->getLocation(),
+SKEPAttr->getKernelName());
+  }

tahonermann wrote:

Done. This code received additional changes too.

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


[clang] [clang-tools-extra] [libcxx] [llvm] [libc++] implement views::concat (PR #120920)

2024-12-23 Thread Nhat Nguyen via cfe-commits

https://github.com/changkhothuychung updated 
https://github.com/llvm/llvm-project/pull/120920

error: too big or took too long to generate
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-23 Thread Stephen Senran Zhang via cfe-commits

zsrkmyn wrote:

@dtcxzyw, I've updated the patch. It's quite simple. You can forget about the 
previous patch and start a review from scratch.

unittests weren't updated with your patch, since the upper bound wasn't optimal 
(for AND op). I'm thinking if I need to add a new test mode to test the optimal 
lower (upper) bound only for AND (or).

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


[clang] [llvm] [mlir] [NVPTX] Switch front-ends and tests to ptx_kernel cc (PR #120806)

2024-12-23 Thread Guray Ozen via cfe-commits

grypp wrote:

In MLIR, we also have other NVVM metadata such as `reqntid` and `maxntid`, 
among others. What is the plan for these? Will they remain as metadata, or will 
they be expressed differently?  

Could you please elaborate on the compile-time improvements?

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


[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-23 Thread Stephen Senran Zhang via cfe-commits

https://github.com/zsrkmyn updated 
https://github.com/llvm/llvm-project/pull/120352

>From 2cb7f076f4b101ab0503b51e84e3493ae2ba8060 Mon Sep 17 00:00:00 2001
From: Senran Zhang 
Date: Tue, 17 Dec 2024 16:15:25 +0800
Subject: [PATCH] [ConstantRange] Estimate tighter lower (upper) bounds for
 masked binary and (or)

Co-author: Yingwei Zheng (@dtcxzyw)
---
 clang/test/CodeGen/AArch64/fpm-helpers.c  |  18 +--
 llvm/lib/IR/ConstantRange.cpp |  76 ++-
 .../SCCP/range-and-or-bit-masked.ll   | 122 ++
 3 files changed, 201 insertions(+), 15 deletions(-)
 create mode 100644 llvm/test/Transforms/SCCP/range-and-or-bit-masked.ll

diff --git a/clang/test/CodeGen/AArch64/fpm-helpers.c 
b/clang/test/CodeGen/AArch64/fpm-helpers.c
index 4bced01d5c71fa..6264b5caeb4f50 100644
--- a/clang/test/CodeGen/AArch64/fpm-helpers.c
+++ b/clang/test/CodeGen/AArch64/fpm-helpers.c
@@ -35,7 +35,7 @@ extern "C" {
 //
 fpm_t test_init() { return __arm_fpm_init(); }
 
-// CHECK-LABEL: define dso_local noundef i64 @test_src1_1(
+// CHECK-LABEL: define dso_local noundef range(i64 0, -6) i64 @test_src1_1(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 -8
@@ -44,7 +44,7 @@ fpm_t test_src1_1() {
   return __arm_set_fpm_src1_format(INIT_ONES, __ARM_FPM_E5M2);
 }
 
-// CHECK-LABEL: define dso_local noundef i64 @test_src1_2(
+// CHECK-LABEL: define dso_local noundef range(i64 0, -6) i64 @test_src1_2(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 1
@@ -53,7 +53,7 @@ fpm_t test_src1_2() {
   return __arm_set_fpm_src1_format(INIT_ZERO, __ARM_FPM_E4M3);
 }
 
-// CHECK-LABEL: define dso_local noundef i64 @test_src2_1(
+// CHECK-LABEL: define dso_local noundef range(i64 0, -48) i64 @test_src2_1(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 -57
@@ -62,7 +62,7 @@ fpm_t test_src2_1() {
   return __arm_set_fpm_src2_format(INIT_ONES, __ARM_FPM_E5M2);
 }
 
-// CHECK-LABEL: define dso_local noundef i64 @test_src2_2(
+// CHECK-LABEL: define dso_local noundef range(i64 0, -48) i64 @test_src2_2(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 8
@@ -71,7 +71,7 @@ fpm_t test_src2_2() {
   return __arm_set_fpm_src2_format(INIT_ZERO, __ARM_FPM_E4M3);
 }
 
-// CHECK-LABEL: define dso_local noundef i64 @test_dst1_1(
+// CHECK-LABEL: define dso_local noundef range(i64 0, -384) i64 @test_dst1_1(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 -449
@@ -80,7 +80,7 @@ fpm_t test_dst1_1() {
   return __arm_set_fpm_dst_format(INIT_ONES, __ARM_FPM_E5M2);
 }
 
-// CHECK-LABEL: define dso_local noundef i64 @test_dst2_2(
+// CHECK-LABEL: define dso_local noundef range(i64 0, -384) i64 @test_dst2_2(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 64
@@ -139,21 +139,21 @@ fpm_t test_lscale() { return 
__arm_set_fpm_lscale(INIT_ZERO, 127); }
 //
 fpm_t test_lscale2() { return __arm_set_fpm_lscale2(INIT_ZERO, 63); }
 
-// CHECK-LABEL: define dso_local noundef range(i64 0, 4294967296) i64 
@test_nscale_1(
+// CHECK-LABEL: define dso_local noundef range(i64 0, 4278190081) i64 
@test_nscale_1(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 2147483648
 //
 fpm_t test_nscale_1() { return __arm_set_fpm_nscale(INIT_ZERO, -128); }
 
-// CHECK-LABEL: define dso_local noundef range(i64 0, 4294967296) i64 
@test_nscale_2(
+// CHECK-LABEL: define dso_local noundef range(i64 0, 4278190081) i64 
@test_nscale_2(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 2130706432
 //
 fpm_t test_nscale_2() { return __arm_set_fpm_nscale(INIT_ZERO, 127); }
 
-// CHECK-LABEL: define dso_local noundef range(i64 0, 4294967296) i64 
@test_nscale_3(
+// CHECK-LABEL: define dso_local noundef range(i64 0, 4278190081) i64 
@test_nscale_3(
 // CHECK-SAME: ) local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  [[ENTRY:.*:]]
 // CHECK-NEXT:ret i64 4278190080
diff --git a/llvm/lib/IR/ConstantRange.cpp b/llvm/lib/IR/ConstantRange.cpp
index d81a292916fdea..8b36d72b7105b7 100644
--- a/llvm/lib/IR/ConstantRange.cpp
+++ b/llvm/lib/IR/ConstantRange.cpp
@@ -1520,15 +1520,72 @@ ConstantRange ConstantRange::binaryNot() const {
   return ConstantRange(APInt::getAllOnes(getBitWidth())).sub(*this);
 }
 
+/// Estimate the 'bit-masked AND' operation's lower bound.
+///
+/// E.g., given two ranges as follows (single quotes are separators and
+/// have no meaning here),
+///
+///   LHS = [10'00101'1,  ; LLo
+///  10'1'0]  ; LHi
+///   RHS = [10'1'0,  ; RLo
+///  10'1'1]  ; RHi
+///
+/// we know that the higher 2 bits of the result is always 10; and we also
+/// notice that RHS[1:6] a

[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-23 Thread Yingwei Zheng via cfe-commits

dtcxzyw wrote:

> I'm thinking if I need to add a new test mode to test the optimal lower 
> (upper) bound only for AND (OR).

If you cannot make it optimal for all non-wrapped cases, please just add some 
special cases (e.g., `[7, 14) & [-1, 0) = [7, 14)`) before 
`TestBinaryOpExhaustive`.



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


[clang] [X86][AVX10.2] Fix wrong mask bits in cvtpbf8_ph intrinsics (PR #120927)

2024-12-23 Thread Phoebe Wang via cfe-commits

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


[clang] 113177f - [X86][AVX10.2] Fix wrong mask bits in cvtpbf8_ph intrinsics (#120927)

2024-12-23 Thread via cfe-commits

Author: Phoebe Wang
Date: 2024-12-23T17:13:56+08:00
New Revision: 113177f98b9d7ac6edfa833d55ad6ad6fd4a0cbf

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

LOG: [X86][AVX10.2] Fix wrong mask bits in cvtpbf8_ph intrinsics (#120927)

Found during review #120766

Added: 


Modified: 
clang/lib/Headers/avx10_2_512convertintrin.h
clang/lib/Headers/avx10_2convertintrin.h
clang/test/CodeGen/X86/avx10_2_512convert-builtins.c

Removed: 




diff  --git a/clang/lib/Headers/avx10_2_512convertintrin.h 
b/clang/lib/Headers/avx10_2_512convertintrin.h
index a34e135fa30473..60a5b1ef4548d8 100644
--- a/clang/lib/Headers/avx10_2_512convertintrin.h
+++ b/clang/lib/Headers/avx10_2_512convertintrin.h
@@ -308,13 +308,13 @@ static __inline __m512h __DEFAULT_FN_ATTRS512 
_mm512_cvtpbf8_ph(__m256i __A) {
 }
 
 static __inline __m512h __DEFAULT_FN_ATTRS512
-_mm512_mask_cvtpbf8_ph(__m512h __S, __mmask16 __U, __m256i __A) {
+_mm512_mask_cvtpbf8_ph(__m512h __S, __mmask32 __U, __m256i __A) {
   return _mm512_castsi512_ph(
   _mm512_mask_slli_epi16((__m512i)__S, __U, _mm512_cvtepi8_epi16(__A), 8));
 }
 
 static __inline __m512h __DEFAULT_FN_ATTRS512
-_mm512_maskz_cvtpbf8_ph(__mmask16 __U, __m256i __A) {
+_mm512_maskz_cvtpbf8_ph(__mmask32 __U, __m256i __A) {
   return _mm512_castsi512_ph(
   _mm512_slli_epi16(_mm512_maskz_cvtepi8_epi16(__U, __A), 8));
 }

diff  --git a/clang/lib/Headers/avx10_2convertintrin.h 
b/clang/lib/Headers/avx10_2convertintrin.h
index 134adb2850c8de..efe8477cbbf9be 100644
--- a/clang/lib/Headers/avx10_2convertintrin.h
+++ b/clang/lib/Headers/avx10_2convertintrin.h
@@ -580,13 +580,13 @@ static __inline__ __m256h __DEFAULT_FN_ATTRS256 
_mm256_cvtpbf8_ph(__m128i __A) {
 }
 
 static __inline__ __m256h __DEFAULT_FN_ATTRS256
-_mm256_mask_cvtpbf8_ph(__m256h __S, __mmask8 __U, __m128i __A) {
+_mm256_mask_cvtpbf8_ph(__m256h __S, __mmask16 __U, __m128i __A) {
   return _mm256_castsi256_ph(
   _mm256_mask_slli_epi16((__m256i)__S, __U, _mm256_cvtepi8_epi16(__A), 8));
 }
 
 static __inline__ __m256h __DEFAULT_FN_ATTRS256
-_mm256_maskz_cvtpbf8_ph(__mmask8 __U, __m128i __A) {
+_mm256_maskz_cvtpbf8_ph(__mmask16 __U, __m128i __A) {
   return _mm256_castsi256_ph(
   _mm256_slli_epi16(_mm256_maskz_cvtepi8_epi16(__U, __A), 8));
 }

diff  --git a/clang/test/CodeGen/X86/avx10_2_512convert-builtins.c 
b/clang/test/CodeGen/X86/avx10_2_512convert-builtins.c
index e71cc0c9ad6b02..6662e0cbf8a913 100644
--- a/clang/test/CodeGen/X86/avx10_2_512convert-builtins.c
+++ b/clang/test/CodeGen/X86/avx10_2_512convert-builtins.c
@@ -299,7 +299,7 @@ __m512h test_mm512_cvtpbf8_ph(__m256i A) {
   return _mm512_cvtpbf8_ph(A);
 }
 
-__m512h test_mm512_mask_cvtpbf8_ph(__m512h S, __mmask16 M, __m256i A) {
+__m512h test_mm512_mask_cvtpbf8_ph(__m512h S, __mmask32 M, __m256i A) {
   // CHECK-LABEL: @test_mm512_mask_cvtpbf8_ph
   // CHECK: sext <32 x i8> %{{.*}} to <32 x i16>
   // CHECK: @llvm.x86.avx512.pslli.w.512
@@ -308,7 +308,7 @@ __m512h test_mm512_mask_cvtpbf8_ph(__m512h S, __mmask16 M, 
__m256i A) {
   return _mm512_mask_cvtpbf8_ph(S, M, A);
 }
 
-__m512h test_mm512_maskz_cvtpbf8_ph(__mmask16 M, __m256i A) {
+__m512h test_mm512_maskz_cvtpbf8_ph(__mmask32 M, __m256i A) {
   // CHECK-LABEL: @test_mm512_maskz_cvtpbf8_ph
   // CHECK: sext <32 x i8> %{{.*}} to <32 x i16>
   // CHECK: select <32 x i1> %{{.*}}, <32 x i16> %{{.*}}, <32 x i16> %{{.*}}



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


[clang] [analyzer] Don't assume third iteration in loops (PR #119388)

2024-12-23 Thread Donát Nagy via cfe-commits

https://github.com/NagyDonat updated 
https://github.com/llvm/llvm-project/pull/119388

From cb9b5ef4d8b0ed8e67276947525d327c547424fc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Don=C3=A1t=20Nagy?= 
Date: Thu, 28 Nov 2024 17:22:58 +0100
Subject: [PATCH 1/6] [analyzer] Don't assume third iteration in loops

This commit ensures that if the loop condition is opaque (the analyzer
cannot determine whether it's true or false) and there were at least two
iterations, then the analyzer doesn't make the unjustified assumption
that it can enter yet another iteration.

Note that the presence of a loop suggests that the developer thought
that two iterations can happen (otherwise an `if` would've been
sufficient), but it does not imply that the developer expected three or
four iterations -- and in fact there are many false positives where a
loop iterates over a two-element (or three-element) data structure, but
the analyzer cannot understand the loop condition and blindly assumes
that there may be three or more iterations. (In particular, analyzing
the FFMPEG project produces 100+ such false positives.)

Moreover, this provides some performance improvements in the sense that
the analyzer won't waste time on traversing the execution paths with 3
or 4 iterations in a loop (which are very similar to the paths with 2
iterations) and therefore will be able to traverse more branches
elsewhere on the `ExplodedGraph`.

This logic is disabled if the user enables the widen-loops analyzer
option (which is disabled by default), because the "simulate one final
iteration after the invalidation" execution path would be suppressed by
the "exit the loop if the loop condition is opaque and there were at
least two iterations" logic. If we want to support loop widening, we
would need to create a follow-up commit which ensures that it "plays
nicely" with this logic.
---
 .../Core/PathSensitive/CoreEngine.h   |  8 +++
 .../Core/PathSensitive/ExprEngine.h   | 18 +++---
 clang/lib/StaticAnalyzer/Core/CoreEngine.cpp  | 27 -
 clang/lib/StaticAnalyzer/Core/ExprEngine.cpp  | 55 ---
 clang/test/Analysis/loop-unrolling.cpp| 35 +++-
 clang/test/Analysis/misc-ps-region-store.m| 31 ---
 6 files changed, 133 insertions(+), 41 deletions(-)

diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
index a6d05a3ac67b4e..80b79fd4e928f8 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
@@ -126,6 +126,14 @@ class CoreEngine {
   ExplodedNode *generateCallExitBeginNode(ExplodedNode *N,
   const ReturnStmt *RS);
 
+  /// Helper function called by `HandleBranch()`. If the currently handled
+  /// branch corresponds to a loop, this returns the number of already
+  /// completed iterations in that loop, otherwise the return value is
+  /// `std::nullopt`. Note that this counts _all_ earlier iterations, including
+  /// ones that were performed within an earlier iteration of an outer loop.
+  std::optional getCompletedIterationCount(const CFGBlock *B,
+ ExplodedNode *Pred) const;
+
 public:
   /// Construct a CoreEngine object to analyze the provided CFG.
   CoreEngine(ExprEngine &exprengine,
diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
index 8c7493e27fcaa6..20c446e33ef9a5 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -321,14 +321,14 @@ class ExprEngine {
NodeBuilderWithSinks &nodeBuilder,
ExplodedNode *Pred);
 
-  /// ProcessBranch - Called by CoreEngine.  Used to generate successor
-  ///  nodes by processing the 'effects' of a branch condition.
-  void processBranch(const Stmt *Condition,
- NodeBuilderContext& BuilderCtx,
- ExplodedNode *Pred,
- ExplodedNodeSet &Dst,
- const CFGBlock *DstT,
- const CFGBlock *DstF);
+  /// ProcessBranch - Called by CoreEngine. Used to generate successor nodes by
+  /// processing the 'effects' of a branch condition. If the branch condition
+  /// is a loop condition, IterationsCompletedInLoop is the number of completed
+  /// iterations (otherwise it's std::nullopt).
+  void processBranch(const Stmt *Condition, NodeBuilderContext &BuilderCtx,
+ ExplodedNode *Pred, ExplodedNodeSet &Dst,
+ const CFGBlock *DstT, const CFGBlock *DstF,
+ std::optional IterationsCompletedInLoop);
 
   /// Called by CoreEngine.
   /// Used to generate successor nodes for temp

[clang] f70ab7d - [AArch64] Fix argument passing for SVE tuples (#118961)

2024-12-23 Thread via cfe-commits

Author: Momchil Velikov
Date: 2024-12-23T09:26:24Z
New Revision: f70ab7d909d6861c7eec5ab40679bde16ab826c6

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

LOG: [AArch64] Fix argument passing for SVE tuples (#118961)

The fix for passing Pure Scalable Types
(https://github.com/llvm/llvm-project/pull/112747) was incomplete,
it didn't handle correctly tuples of SVE vectors (e.g. `sveboolx2_t`,
`svfloat32x4_t`, etc).

These types are Pure Scalable Types and should be passed either entirely
in vector registers
or indirectly in memory, not split.

Added: 


Modified: 
clang/lib/CodeGen/Targets/AArch64.cpp
clang/test/CodeGen/AArch64/pure-scalable-args.c
clang/test/CodeGenCXX/aarch64-mangle-sve-vectors.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/Targets/AArch64.cpp 
b/clang/lib/CodeGen/Targets/AArch64.cpp
index be33e26f047841..ad7f405cc72550 100644
--- a/clang/lib/CodeGen/Targets/AArch64.cpp
+++ b/clang/lib/CodeGen/Targets/AArch64.cpp
@@ -52,6 +52,7 @@ class AArch64ABIInfo : public ABIInfo {
 
   bool isIllegalVectorType(QualType Ty) const;
 
+  bool passAsAggregateType(QualType Ty) const;
   bool passAsPureScalableType(QualType Ty, unsigned &NV, unsigned &NP,
   SmallVectorImpl &CoerceToSeq) 
const;
 
@@ -337,6 +338,10 @@ ABIArgInfo 
AArch64ABIInfo::coerceAndExpandPureScalableAggregate(
   NSRN += NVec;
   NPRN += NPred;
 
+  // Handle SVE vector tuples.
+  if (Ty->isSVESizelessBuiltinType())
+return ABIArgInfo::getDirect();
+
   llvm::Type *UnpaddedCoerceToType =
   UnpaddedCoerceToSeq.size() == 1
   ? UnpaddedCoerceToSeq[0]
@@ -362,7 +367,7 @@ ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType 
Ty, bool IsVariadicFn,
   if (isIllegalVectorType(Ty))
 return coerceIllegalVector(Ty, NSRN, NPRN);
 
-  if (!isAggregateTypeForABI(Ty)) {
+  if (!passAsAggregateType(Ty)) {
 // Treat an enum type as its underlying type.
 if (const EnumType *EnumTy = Ty->getAs())
   Ty = EnumTy->getDecl()->getIntegerType();
@@ -417,7 +422,7 @@ ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType 
Ty, bool IsVariadicFn,
   // elsewhere for GNU compatibility.
   uint64_t Size = getContext().getTypeSize(Ty);
   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
-  if (IsEmpty || Size == 0) {
+  if (!Ty->isSVESizelessBuiltinType() && (IsEmpty || Size == 0)) {
 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
   return ABIArgInfo::getIgnore();
 
@@ -504,7 +509,7 @@ ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType 
RetTy,
   if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
 return getNaturalAlignIndirect(RetTy);
 
-  if (!isAggregateTypeForABI(RetTy)) {
+  if (!passAsAggregateType(RetTy)) {
 // Treat an enum type as its underlying type.
 if (const EnumType *EnumTy = RetTy->getAs())
   RetTy = EnumTy->getDecl()->getIntegerType();
@@ -519,7 +524,8 @@ ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType 
RetTy,
   }
 
   uint64_t Size = getContext().getTypeSize(RetTy);
-  if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
+  if (!RetTy->isSVESizelessBuiltinType() &&
+  (isEmptyRecord(getContext(), RetTy, true) || Size == 0))
 return ABIArgInfo::getIgnore();
 
   const Type *Base = nullptr;
@@ -654,6 +660,15 @@ bool 
AArch64ABIInfo::isZeroLengthBitfieldPermittedInHomogeneousAggregate()
   return true;
 }
 
+bool AArch64ABIInfo::passAsAggregateType(QualType Ty) const {
+  if (Kind == AArch64ABIKind::AAPCS && Ty->isSVESizelessBuiltinType()) {
+const auto *BT = Ty->getAs();
+return !BT->isSVECount() &&
+   getContext().getBuiltinVectorTypeInfo(BT).NumVectors > 1;
+  }
+  return isAggregateTypeForABI(Ty);
+}
+
 // Check if a type needs to be passed in registers as a Pure Scalable Type (as
 // defined by AAPCS64). Return the number of data vectors and the number of
 // predicate vectors in the type, into `NVec` and `NPred`, respectively. Upon
@@ -719,37 +734,38 @@ bool AArch64ABIInfo::passAsPureScalableType(
 return true;
   }
 
-  const auto *VT = Ty->getAs();
-  if (!VT)
-return false;
+  if (const auto *VT = Ty->getAs()) {
+if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
+  ++NPred;
+  if (CoerceToSeq.size() + 1 > 12)
+return false;
+  CoerceToSeq.push_back(convertFixedToScalableVectorType(VT));
+  return true;
+}
 
-  if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
-++NPred;
-if (CoerceToSeq.size() + 1 > 12)
-  return false;
-CoerceToSeq.push_back(convertFixedToScalableVectorType(VT));
-return true;
-  }
+if (VT->getVectorKind() == VectorKind::SveFixedLengthData) {
+  ++NVec;
+  if (CoerceToSeq.size() + 1 > 12)
+return false;

[clang] [AArch64] Fix argument passing for SVE tuples (PR #118961)

2024-12-23 Thread Momchil Velikov via cfe-commits

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


[clang] [X86][AVX10.2] Fix wrong mask bits in cvtpbf8_ph intrinsics (PR #120927)

2024-12-23 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `lldb-aarch64-ubuntu` 
running on `linaro-lldb-aarch64-ubuntu` while building `clang` at step 6 "test".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/59/builds/10268


Here is the relevant piece of the build log for the reference

```
Step 6 (test) failure: build (failure)
...
PASS: lldb-unit :: Utility/./UtilityTests/1/8 (2060 of 2069)
PASS: lldb-unit :: Utility/./UtilityTests/4/8 (2061 of 2069)
PASS: lldb-unit :: ValueObject/./LLDBValueObjectTests/1/3 (2062 of 2069)
PASS: lldb-unit :: ValueObject/./LLDBValueObjectTests/2/3 (2063 of 2069)
PASS: lldb-unit :: tools/lldb-server/tests/./LLDBServerTests/0/2 (2064 of 2069)
PASS: lldb-unit :: tools/lldb-server/tests/./LLDBServerTests/1/2 (2065 of 2069)
PASS: lldb-unit :: Target/./TargetTests/11/14 (2066 of 2069)
PASS: lldb-unit :: Host/./HostTests/2/13 (2067 of 2069)
PASS: lldb-unit :: Process/gdb-remote/./ProcessGdbRemoteTests/8/9 (2068 of 2069)
UNRESOLVED: lldb-api :: tools/lldb-server/TestLldbGdbServer.py (2069 of 2069)
 TEST 'lldb-api :: tools/lldb-server/TestLldbGdbServer.py' 
FAILED 
Script:
--
/usr/bin/python3.10 
/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/llvm-project/lldb/test/API/dotest.py
 -u CXXFLAGS -u CFLAGS --env 
LLVM_LIBS_DIR=/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./lib --env 
LLVM_INCLUDE_DIR=/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/include 
--env LLVM_TOOLS_DIR=/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./bin 
--arch aarch64 --build-dir 
/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/lldb-test-build.noindex 
--lldb-module-cache-dir 
/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/lldb-test-build.noindex/module-cache-lldb/lldb-api
 --clang-module-cache-dir 
/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/lldb-test-build.noindex/module-cache-clang/lldb-api
 --executable /home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./bin/lldb 
--compiler /home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./bin/clang 
--dsymutil /home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./bin/dsymutil 
--make /usr/bin/gmake --llvm-tools-dir 
/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./bin --lldb-obj-root 
/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/tools/lldb --lldb-libs-dir 
/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/./lib 
/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/llvm-project/lldb/test/API/tools/lldb-server
 -p TestLldbGdbServer.py
--
Exit Code: 1

Command Output (stdout):
--
lldb version 20.0.0git (https://github.com/llvm/llvm-project.git revision 
113177f98b9d7ac6edfa833d55ad6ad6fd4a0cbf)
  clang revision 113177f98b9d7ac6edfa833d55ad6ad6fd4a0cbf
  llvm revision 113177f98b9d7ac6edfa833d55ad6ad6fd4a0cbf
Skipping the following test categories: ['libc++', 'dsym', 'gmodules', 
'debugserver', 'objc']

--
Command Output (stderr):
--
UNSUPPORTED: LLDB 
(/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/bin/clang-aarch64) :: 
test_Hc_then_Csignal_signals_correct_thread_launch_debugserver 
(TestLldbGdbServer.LldbGdbServerTestCase) (test case does not fall in any 
category of interest for this run) 
PASS: LLDB 
(/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/bin/clang-aarch64) :: 
test_Hc_then_Csignal_signals_correct_thread_launch_llgs 
(TestLldbGdbServer.LldbGdbServerTestCase)
PASS: LLDB 
(/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/bin/clang-aarch64) :: 
test_Hg_fails_on_another_pid_llgs (TestLldbGdbServer.LldbGdbServerTestCase)
PASS: LLDB 
(/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/bin/clang-aarch64) :: 
test_Hg_fails_on_minus_one_pid_llgs (TestLldbGdbServer.LldbGdbServerTestCase)
PASS: LLDB 
(/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/bin/clang-aarch64) :: 
test_Hg_fails_on_zero_pid_llgs (TestLldbGdbServer.LldbGdbServerTestCase)
UNSUPPORTED: LLDB 
(/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/bin/clang-aarch64) :: 
test_Hg_switches_to_3_threads_launch_debugserver 
(TestLldbGdbServer.LldbGdbServerTestCase) (test case does not fall in any 
category of interest for this run) 
PASS: LLDB 
(/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/bin/clang-aarch64) :: 
test_Hg_switches_to_3_threads_launch_llgs 
(TestLldbGdbServer.LldbGdbServerTestCase)
UNSUPPORTED: LLDB 
(/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/bin/clang-aarch64) :: 
test_P_and_p_thread_suffix_work_debugserver 
(TestLldbGdbServer.LldbGdbServerTestCase) (test case does not fall in any 
category of interest for this run) 
PASS: LLDB 
(/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/bin/clang-aarch64) :: 
test_P_and_p_thread_suffix_work_llgs (TestLldbGdbServer.LldbGdbServerTestCase)
UNSUPPORTED: LLDB 
(/home/tcwg-buildbot/worker/lldb-aarch64-ubuntu/build/bin/clang-aarch64) :: 
test_P_writes_all_gpr_registers_debugserver 
(TestLldbGdbServer.LldbGdbServerTestCase) (test case does not fall in any 
category of interest for 

[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-23 Thread Stephen Senran Zhang via cfe-commits


@@ -1520,15 +1520,101 @@ ConstantRange ConstantRange::binaryNot() const {
   return ConstantRange(APInt::getAllOnes(getBitWidth())).sub(*this);
 }
 
+/// Estimate the 'bit-masked AND' operation's lower bound.
+///
+/// E.g., given two ranges as follows (single quotes are separators and
+/// have no meaning here),
+///
+///   LHS = [10'001'010,  ; LLo
+///  10'100'000]  ; LHi
+///   RHS = [10'111'010,  ; RLo
+///  10'111'100]  ; RHi
+///
+/// we know that the higher 2 bits of the result is always '10'; and note that
+/// there's at least one bit is 1 in LHS[3:6] (since the range is continuous),
+/// and all bits in RHS[3:6] are 1, so we know the lower bound of the result is
+/// 10'001'000.
+///
+/// The algorithm is as follows,
+/// 1. we first calculate a mask to mask out the higher common bits by
+///   Mask = (LLo ^ LHi) | (LLo ^ LHi) | (LLo ^ RLo);
+///   Mask = set all non-leading-zero bits to 1 for Mask;
+/// 2. find the bit field with at least 1 in LHS (i.e., bit 3:6 in the example)
+///after applying the mask, with
+///   StartBit = BitWidth - (LLo & Mask).clz() - 1;
+///   EndBit = BitWidth - (LHi & Mask).clz();
+/// 3. check if all bits in [StartBit:EndBit] in RHS are 1, and all bits of
+///RLo and RHi in [StartBit:BitWidth] are same, and if so, the lower bound
+///can be updated to
+///   LowerBound = LLo & Keep;
+///where Keep is a mask to mask out trailing bits (the lower 3 bits in the
+///example);
+/// 4. repeat the step 2 and 3 with LHS and RHS swapped, and update the lower
+///bound with the larger one.
+static APInt estimateBitMaskedAndLowerBound(const ConstantRange &LHS,
+const ConstantRange &RHS) {
+  auto BitWidth = LHS.getBitWidth();
+  // If either is full set or unsigned wrapped, then the range must contain '0'
+  // which leads the lower bound to 0.
+  if ((LHS.isFullSet() || RHS.isFullSet()) ||
+  (LHS.isWrappedSet() || RHS.isWrappedSet()))
+return APInt::getZero(BitWidth);
+
+  auto LLo = LHS.getLower();
+  auto LHi = LHS.getUpper() - 1;
+  auto RLo = RHS.getLower();
+  auto RHi = RHS.getUpper() - 1;
+
+  // Calculate the mask that mask out the higher common bits.
+  auto Mask = (LLo ^ LHi) | (RLo ^ RHi) | (LLo ^ RLo);
+  unsigned LeadingZeros = Mask.countLeadingZeros();
+  Mask.setLowBits(BitWidth - LeadingZeros);
+
+  auto estimateBound =
+  [BitWidth, &Mask](const APInt &ALo, const APInt &AHi, const APInt &BLo,
+const APInt &BHi) -> std::optional {
+unsigned LeadingZeros = (ALo & Mask).countLeadingZeros();
+if (LeadingZeros == BitWidth)
+  return std::nullopt;
+
+unsigned StartBit = BitWidth - LeadingZeros - 1;

zsrkmyn wrote:

The whole algorithm is actually extremely simple. I made things complicated... 
You'll see how stupid I am after I update the PR later. Many thanks for the 
review!

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


[clang] [X86][AVX10.2] Fix wrong mask bits in cvtpbf8_ph intrinsics (PR #120927)

2024-12-23 Thread Simon Pilgrim via cfe-commits

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


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


[clang] [llvm] [RISCV] Add support of Sdext, Sdtrig extentions (PR #120936)

2024-12-23 Thread Pengcheng Wang via cfe-commits


@@ -842,6 +842,12 @@ def HasStdExtH : Predicate<"Subtarget->hasStdExtH()">,
  AssemblerPredicate<(all_of FeatureStdExtH),
 "'H' (Hypervisor)">;
 
+// Debugger extensions

wangpc-pp wrote:

They are also `Supervisor` extensions I think since their names start with `S`.

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


[clang] [Clang] Repair the function "rParenEndsCast" to make incorrect judgments in template variable cases (PR #120904)

2024-12-23 Thread via cfe-commits

https://github.com/dty2 updated https://github.com/llvm/llvm-project/pull/120904

From 3f72b657741dc1392e3065a862e3489e800f0782 Mon Sep 17 00:00:00 2001
From: hunter <284050...@qq.com>
Date: Mon, 23 Dec 2024 16:16:47 +0800
Subject: [PATCH] [Clang] Repair the functionrParenEndsCast to make incorrect
 judgments in template variable cases

---
 clang/lib/Format/TokenAnnotator.cpp   | 26 ++-
 clang/unittests/Format/TokenAnnotatorTest.cpp | 14 ++
 2 files changed, 39 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index f2cfa7f49f62f9..3f44b8c18581e1 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -17,6 +17,8 @@
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TokenKinds.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Debug.h"
 
 #define DEBUG_TYPE "format-token-annotator"
@@ -38,6 +40,10 @@ static bool mustBreakAfterAttributes(const FormatToken &Tok,
 
 namespace {
 
+// TODO: Add new Type modifiers
+llvm::SmallVector castIdentifiers{"__type_identity_t",
+   "remove_reference_t"};
+
 /// Returns \c true if the line starts with a token that can start a statement
 /// with an initializer.
 static bool startsWithInitStatement(const AnnotatedLine &Line) {
@@ -2474,6 +2480,11 @@ class AnnotatingParser {
   Current.getNextNonComment()->isOneOf(tok::comma, tok::r_brace)) {
 Current.setType(TT_StringInConcatenation);
   }
+} else if (Style.isCpp() && Current.is(tok::kw_using)) {
+  if (Current.Next && Current.Next->Next && Current.Next->Next->Next) {
+if (Current.Next->Next->Next->isTypeName(LangOpts))
+  castIdentifiers.push_back(Current.Next->TokenText);
+  }
 } else if (Current.is(tok::l_paren)) {
   if (lParenStartsCppCast(Current))
 Current.setType(TT_CppCastLParen);
@@ -2831,8 +2842,21 @@ class AnnotatingParser {
 IsQualifiedPointerOrReference(BeforeRParen, LangOpts);
 bool ParensCouldEndDecl =
 AfterRParen->isOneOf(tok::equal, tok::semi, tok::l_brace, 
tok::greater);
-if (ParensAreType && !ParensCouldEndDecl)
+if (ParensAreType && !ParensCouldEndDecl) {
+  if (BeforeRParen->is(TT_TemplateCloser)) {
+if (determineUnaryOperatorByUsage(*AfterRParen))
+  return true;
+if (AfterRParen->isOneOf(tok::plus, tok::minus, tok::star, 
tok::exclaim,
+ tok::amp)) {
+  auto *Prev = BeforeRParen->MatchingParen->getPreviousNonComment();
+  for (auto &name : castIdentifiers)
+if (Prev->TokenText == name)
+  return true;
+  return false;
+}
+  }
   return true;
+}
 
 // At this point, we heuristically assume that there are no casts at the
 // start of the line. We assume that we have found most cases where there
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index b2fb5227993c3f..e2e94c0588c857 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -752,6 +752,20 @@ TEST_F(TokenAnnotatorTest, UnderstandsCasts) {
   ASSERT_EQ(Tokens.size(), 11u) << Tokens;
   EXPECT_TOKEN(Tokens[7], tok::r_paren, TT_CastRParen);
 
+  Tokens = annotate("(std::__type_identity_t)-2;");
+  ASSERT_EQ(Tokens.size(), 12u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::r_paren, TT_CastRParen);
+
+  Tokens = annotate("template  using type = int;\n"
+"auto = (type)+5;");
+  ASSERT_EQ(Tokens.size(), 21u) << Tokens;
+  EXPECT_TOKEN(Tokens[16], tok::r_paren, TT_CastRParen);
+
+  Tokens = annotate("template  t c;"
+"auto = (c) + 5;");
+  ASSERT_EQ(Tokens.size(), 20u) << Tokens;
+  EXPECT_TOKEN(Tokens[15], tok::r_paren, TT_Unknown);
+
   Tokens = annotate("return (Foo)p;");
   ASSERT_EQ(Tokens.size(), 7u) << Tokens;
   EXPECT_TOKEN(Tokens[3], tok::r_paren, TT_CastRParen);

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


[clang] [llvm] [RISCV] Add support of Sdext, Sdtrig extentions (PR #120936)

2024-12-23 Thread Shao-Ce SUN via cfe-commits

https://github.com/sunshaoce updated 
https://github.com/llvm/llvm-project/pull/120936

>From 4a44a8551cc8e2c790bec2b6b4300e002216bfc0 Mon Sep 17 00:00:00 2001
From: Shao-Ce SUN 
Date: Mon, 23 Dec 2024 14:54:06 +0800
Subject: [PATCH 1/2] [RISCV] Add support of Sdext,Sdtrig extention

The full specification can be found at
https://github.com/riscv/riscv-debug-spec/releases/download/1.0.0-rc4/riscv-debug-specification.pdf
---
 .../Driver/print-supported-extensions-riscv.c |  2 +
 .../test/Preprocessor/riscv-target-features.c | 18 
 llvm/docs/RISCVUsage.rst  |  3 ++
 llvm/docs/ReleaseNotes.md |  1 +
 llvm/lib/Target/RISCV/RISCVFeatures.td|  6 +++
 llvm/lib/Target/RISCV/RISCVSystemOperands.td  |  3 ++
 llvm/test/CodeGen/RISCV/attributes.ll |  4 ++
 llvm/test/CodeGen/RISCV/features-info.ll  |  2 +
 llvm/test/MC/RISCV/attribute-arch.s   |  6 +++
 llvm/test/MC/RISCV/machine-csr-names.s| 42 +++
 .../TargetParser/RISCVISAInfoTest.cpp |  2 +
 11 files changed, 89 insertions(+)

diff --git a/clang/test/Driver/print-supported-extensions-riscv.c 
b/clang/test/Driver/print-supported-extensions-riscv.c
index 8344c1aa399737..df18835e6f3a2a 100644
--- a/clang/test/Driver/print-supported-extensions-riscv.c
+++ b/clang/test/Driver/print-supported-extensions-riscv.c
@@ -185,6 +185,8 @@
 // CHECK-NEXT: zalasr   0.1   'Zalasr' (Load-Acquire and 
Store-Release Instructions)
 // CHECK-NEXT: zvbc32e  0.7   'Zvbc32e' (Vector Carryless 
Multiplication with 32-bits elements)
 // CHECK-NEXT: zvkgs0.7   'Zvkgs' (Vector-Scalar GCM 
instructions for Cryptography)
+// CHECK-NEXT: sdext1.0   'Sdext' (External debugger)
+// CHECK-NEXT: sdtrig   1.0   'Sdtrig' (Debugger triggers)
 // CHECK-NEXT: smctr1.0   'Smctr' (Control Transfer 
Records Machine Level)
 // CHECK-NEXT: ssctr1.0   'Ssctr' (Control Transfer 
Records Supervisor Level)
 // CHECK-NEXT: svukte   0.3   'Svukte' 
(Address-Independent Latency of User-Mode Faults to Supervisor Addresses)
diff --git a/clang/test/Preprocessor/riscv-target-features.c 
b/clang/test/Preprocessor/riscv-target-features.c
index e376821a5517c2..c2197711352757 100644
--- a/clang/test/Preprocessor/riscv-target-features.c
+++ b/clang/test/Preprocessor/riscv-target-features.c
@@ -182,6 +182,8 @@
 
 // Experimental extensions
 
+// CHECK-NOT: __riscv_sdext{{.*$}}
+// CHECK-NOT: __riscv_sdtrig{{.*$}}
 // CHECK-NOT: __riscv_smctr{{.*$}}
 // CHECK-NOT: __riscv_smmpm{{.*$}}
 // CHECK-NOT: __riscv_smnpm{{.*$}}
@@ -1795,6 +1797,22 @@
 // RUN:   -o - | FileCheck --check-prefix=CHECK-SUPM-EXT %s
 // CHECK-SUPM-EXT: __riscv_supm 100{{$}}
 
+// RUN: %clang --target=riscv32 -menable-experimental-extensions \
+// RUN:   -march=rv32i_sdext1p0 -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-SDEXT-EXT %s
+// RUN: %clang --target=riscv64 -menable-experimental-extensions \
+// RUN:   -march=rv64i_sdext1p0 -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-SDEXT-EXT %s
+// CHECK-SDEXT-EXT: __riscv_sdext 100{{$}}
+
+// RUN: %clang --target=riscv32 -menable-experimental-extensions \
+// RUN:   -march=rv32i_sdtrig1p0 -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-SDTRIG-EXT %s
+// RUN: %clang --target=riscv64 -menable-experimental-extensions \
+// RUN:   -march=rv64i_sdtrig1p0 -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-SDTRIG-EXT %s
+// CHECK-SDTRIG-EXT: __riscv_sdtrig 100{{$}}
+
 // RUN: %clang --target=riscv32 -menable-experimental-extensions \
 // RUN:   -march=rv32i_smctr1p0 -E -dM %s \
 // RUN:   -o - | FileCheck --check-prefix=CHECK-SMCTR-EXT %s
diff --git a/llvm/docs/RISCVUsage.rst b/llvm/docs/RISCVUsage.rst
index f6a0dd4bf2383c..9fc6755376ede2 100644
--- a/llvm/docs/RISCVUsage.rst
+++ b/llvm/docs/RISCVUsage.rst
@@ -326,6 +326,9 @@ The primary goal of experimental support is to assist in 
the process of ratifica
 ``experimental-zvbc32e``, ``experimental-zvkgs``
   LLVM implements the `0.7 release specification 
`__.
 
+``experimental-sdext``, ``experimental-sdtrig``
+  LLVM implements the `1.0-rc4 specification 
`__.
+
 ``experimental-smctr``, ``experimental-ssctr``
   LLVM implements the `1.0-rc3 specification 
`__.
 
diff --git a/llvm/docs/ReleaseNotes.md b/llvm/docs/ReleaseNotes.md
index 2835ace34bff83..5a0308944435dc 100644
--- a/llvm/docs/ReleaseNotes.md
+++ b/llvm/docs/ReleaseNotes.md
@@ -226,6 +226,7 @@ Changes to the RISC-V Backend
   extension.
 * Adds experimental assembler support for the Qualcomm uC '

[clang] [llvm] [RISCV] Add support of Sdext, Sdtrig extentions (PR #120936)

2024-12-23 Thread Shao-Ce SUN via cfe-commits


@@ -842,6 +842,12 @@ def HasStdExtH : Predicate<"Subtarget->hasStdExtH()">,
  AssemblerPredicate<(all_of FeatureStdExtH),
 "'H' (Hypervisor)">;
 
+// Debugger extensions

sunshaoce wrote:

Done. Thanks!

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


[clang] [clang][dataflow] Use smart pointer caching in unchecked optional accessor (PR #120249)

2024-12-23 Thread Gábor Horváth via cfe-commits


@@ -555,24 +557,26 @@ void handleConstMemberCall(const CallExpr *CE,
LatticeTransferState &State) {
   // If the const method returns an optional or reference to an optional.
   if (RecordLoc != nullptr && isSupportedOptionalType(CE->getType())) {
-StorageLocation *Loc =
+const FunctionDecl *DirectCallee = CE->getDirectCallee();
+if (DirectCallee == nullptr)
+  return;
+StorageLocation &Loc =
 State.Lattice.getOrCreateConstMethodReturnStorageLocation(
-*RecordLoc, CE, State.Env, [&](StorageLocation &Loc) {
+*RecordLoc, DirectCallee, CE->getType(), State.Env,

Xazax-hun wrote:

Here, we do not actually pass the return type of `DirectCallee`. The return 
type of the callee, and the type of the call expression might differ (I think 
one of differences is when the function returns a reference type). Thus, this 
use contradicts the documentation of this function. Update the documentation or 
the call site. 

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


[clang] [clang][dataflow] Use smart pointer caching in unchecked optional accessor (PR #120249)

2024-12-23 Thread Gábor Horváth via cfe-commits


@@ -71,10 +73,28 @@ template  class CachedConstAccessorsLattice 
: public Base {
   /// Requirements:
   ///
   ///  - `CE` should return a location (GLValue or a record type).
+  ///
+  /// DEPRECATED: switch users to the below overload which takes Callee and 
Type
+  /// directly.
   StorageLocation *getOrCreateConstMethodReturnStorageLocation(
   const RecordStorageLocation &RecordLoc, const CallExpr *CE,
   Environment &Env, llvm::function_ref 
Initialize);
 
+  /// Creates or returns a previously created `StorageLocation` associated with
+  /// a const method call `obj.getFoo()` where `RecordLoc` is the
+  /// `RecordStorageLocation` of `obj`, `Callee` is the decl for `getFoo`,
+  /// and `Type` is the return type of `getFoo`.
+  ///
+  /// The callback `Initialize` runs on the storage location if newly created.
+  ///
+  /// Requirements:
+  ///
+  ///  - `Type` should return a location (GLValue or a record type).
+  StorageLocation &getOrCreateConstMethodReturnStorageLocation(

Xazax-hun wrote:

What is the reason you need to pass in the return type? Couldn't we just query 
it from the `FunctionDecl`? 

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


[clang] [lldb] [lldb] Analyze enum promotion type during parsing (PR #115005)

2024-12-23 Thread Michael Buch via cfe-commits


@@ -2299,11 +2301,103 @@ size_t DWARFASTParserClang::ParseChildEnumerators(
 }
 
 if (name && name[0] && got_value) {
-  m_ast.AddEnumerationValueToEnumerationType(
+  auto ECD = m_ast.AddEnumerationValueToEnumerationType(
   clang_type, decl, name, enum_value, enumerator_byte_size * 8);
   ++enumerators_added;
+
+  llvm::APSInt InitVal = ECD->getInitVal();
+  // Keep track of the size of positive and negative values.
+  if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
+// If the enumerator is zero that should still be counted as a positive
+// bit since we need a bit to store the value zero.
+unsigned ActiveBits = InitVal.getActiveBits();
+NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
+  } else {
+NumNegativeBits =
+std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
+  }
 }
   }
+
+  /// The following code follows the same logic as in Sema::ActOnEnumBody
+  /// clang/lib/Sema/SemaDecl.cpp
+  // If we have an empty set of enumerators we still need one bit.
+  // From [dcl.enum]p8
+  // If the enumerator-list is empty, the values of the enumeration are as if
+  // the enumeration had a single enumerator with value 0
+  if (!NumPositiveBits && !NumNegativeBits)
+NumPositiveBits = 1;
+
+  clang::EnumDecl *enum_decl =
+  ClangUtil::GetQualType(clang_type)->getAs()->getDecl();
+  enum_decl->setNumPositiveBits(NumPositiveBits);
+  enum_decl->setNumNegativeBits(NumNegativeBits);
+
+  // C++0x N3000 [conv.prom]p3:
+  //   An rvalue of an unscoped enumeration type whose underlying
+  //   type is not fixed can be converted to an rvalue of the first
+  //   of the following types that can represent all the values of
+  //   the enumeration: int, unsigned int, long int, unsigned long
+  //   int, long long int, or unsigned long long int.
+  // C99 6.4.4.3p2:
+  //   An identifier declared as an enumeration constant has type int.
+  // The C99 rule is modified by C23.
+  clang::QualType BestPromotionType;
+  unsigned BestWidth;
+
+  auto &Context = m_ast.getASTContext();
+  unsigned LongWidth = Context.getTargetInfo().getLongWidth();
+  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
+  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
+  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
+
+  bool is_cpp = Language::LanguageIsCPlusPlus(
+  SymbolFileDWARF::GetLanguage(*parent_die.GetCU()));
+
+  if (NumNegativeBits) {

Michael137 wrote:

Thanks for trying this out! It doesn't look *aweful* in my opinion (considering 
the code duplication that it prevents). I think the best thing to do here is to 
split the Clang changes out into a separate PR. That would also give you more 
visibility from the Clang maintainers. If you didn't want to have all those 
output parameters you could return a tuple or maybe even a helper structure 
that encapsulates all those arguments. Either way, I'm sure they'll be some 
useful feedback on the Clang PR

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


[clang] [lldb] [lldb] Analyze enum promotion type during parsing (PR #115005)

2024-12-23 Thread Michael Buch via cfe-commits

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


[clang] Introduce virtual interface for lattices and remove dependency on `llvm::Any`. (PR #120967)

2024-12-23 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 11676da80874787a47856da87911234837c53f06 
43385b7341ef6d3bd5f689670ca407f6e5f91949 --extensions h,cpp -- 
clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h 
clang/include/clang/Analysis/FlowSensitive/DataflowLattice.h 
clang/include/clang/Analysis/FlowSensitive/Logger.h 
clang/include/clang/Analysis/FlowSensitive/MapLattice.h 
clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
 clang/include/clang/Analysis/FlowSensitive/NoopAnalysis.h 
clang/include/clang/Analysis/FlowSensitive/NoopLattice.h 
clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h 
clang/lib/Analysis/FlowSensitive/Arena.cpp 
clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp 
clang/lib/Analysis/FlowSensitive/Logger.cpp 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp 
clang/lib/Analysis/FlowSensitive/Transfer.cpp 
clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp 
clang/unittests/Analysis/FlowSensitive/ChromiumCheckModelTest.cpp 
clang/unittests/Analysis/FlowSensitive/LoggerTest.cpp 
clang/unittests/Analysis/FlowSensitive/MapLatticeTest.cpp 
clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp 
clang/unittests/Analysis/FlowSensitive/SignAnalysisTest.cpp 
clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp 
clang/unittests/Analysis/FlowSensitive/TestingSupport.h 
clang/unittests/Analysis/FlowSensitive/TransferBranchTest.cpp 
clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
``





View the diff from clang-format here.


``diff
diff --git 
a/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h 
b/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
index 8dd9cd546b..b8d03f04d7 100644
--- a/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
+++ b/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
@@ -154,11 +154,12 @@ joinConstMethodMap(
 } // namespace internal
 
 template 
-LatticeEffect CachedConstAccessorsLattice::join(
-const DataflowLattice &Other) {
+LatticeEffect
+CachedConstAccessorsLattice::join(const DataflowLattice &Other) {
   LatticeEffect Effect = Base::join(Other);
 
-  const auto &OtherL = llvm::cast>(Other);
+  const auto &OtherL =
+  llvm::cast>(Other);
 
   // For simplicity, we only retain values that are identical, but not ones 
that
   // are non-identical but equivalent. This is likely to be sufficient in
diff --git a/clang/include/clang/Analysis/FlowSensitive/Logger.h 
b/clang/include/clang/Analysis/FlowSensitive/Logger.h
index 34d5865f6b..32719b9170 100644
--- a/clang/include/clang/Analysis/FlowSensitive/Logger.h
+++ b/clang/include/clang/Analysis/FlowSensitive/Logger.h
@@ -40,8 +40,7 @@ public:
 
   /// Called by the framework as we start analyzing a new function or 
statement.
   /// Forms a pair with endAnalysis().
-  virtual void beginAnalysis(const AdornedCFG &, DataflowAnalysis &) {
-  }
+  virtual void beginAnalysis(const AdornedCFG &, DataflowAnalysis &) {}
   virtual void endAnalysis() {}
 
   // At any time during the analysis, we're computing the state for some target
diff --git a/clang/include/clang/Analysis/FlowSensitive/MapLattice.h 
b/clang/include/clang/Analysis/FlowSensitive/MapLattice.h
index 0321d55b98..ec6e97920e 100644
--- a/clang/include/clang/Analysis/FlowSensitive/MapLattice.h
+++ b/clang/include/clang/Analysis/FlowSensitive/MapLattice.h
@@ -93,7 +93,6 @@ public:
 
   mapped_type &operator[](const key_type &K) { return C[K]; }
 
-
   DataflowLatticePtr clone() override {
 return std::make_unique(*this);
   }
diff --git 
a/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
 
b/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
index 654c76efec..d94599ee37 100644
--- 
a/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
+++ 
b/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
@@ -59,8 +59,7 @@ struct UncheckedOptionalAccessLattice
 /// Dataflow analysis that models whether optionals hold values or not.
 ///
 /// Models the `std::optional`, `absl::optional`, and `base::Optional` types.
-class UncheckedOptionalAccessModel
-: public DataflowAnalysis {
+class UncheckedOptionalAccessModel : public DataflowAnalysis {
 public:
   using Lattice = UncheckedOptionalAccessLattice;
 
diff --git 
a/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h 
b/clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
index dbad9d334e..43f2dc8a04 100644
--- a/clang/include/clang/Analysis/FlowSensitive/TypeEr

[clang] Introduce virtual interface for lattices and remove dependency on `llvm::Any`. (PR #120967)

2024-12-23 Thread Yitzhak Mandelbaum via cfe-commits

https://github.com/ymand created 
https://github.com/llvm/llvm-project/pull/120967

This PR has 2 related goals:

*Remove dependency on `llvm::Any`*. For some platforms, use of `llvm::Any`
forces users to explicitly define internal details related to `Any`. Aside from
aesthetics, this places an obscure requirement on lattice implementers. We
prefer to use LLVM's (explicit) RTTI framework instead.

*Introduce virtual interface for lattices*. Currently, we implicitly define the
interface for lattices, because the interface to analyses is fully captured in
templates. This PR moves to an explicit, virtual interface.

We combine these two changes in a single PR because they are closely related: we
use the new lattice interface as the basis of an open type hierarchy that embeds
RTTI for safe interfacing with the dataflow engine.


>From 43385b7341ef6d3bd5f689670ca407f6e5f91949 Mon Sep 17 00:00:00 2001
From: Yitzhak Mandelbaum 
Date: Mon, 23 Dec 2024 13:42:21 +
Subject: [PATCH] Introduce virtual interface for lattices and remove
 dependency on `llvm::Any`.

This PR has 2 related goals:

*Remove dependency on `llvm::Any`*. For some platforms, use of `llvm::Any`
forces users to explicitly define internal details related to `Any`. Aside from
aesthetics, this places an obscure requirement on lattice implementers. We
prefer to use LLVM's (explicit) RTTI framework instead.

*Introduce virtual interface for lattices*. Currently, we implicitly define the
interface for lattices, because the interface to analyses is fully captured in
templates. This PR moves to an explicit, virtual interface.

We combine these two changes in a single PR because they are closely related: we
use the new lattice interface as the basis of an open type hierarchy that embeds
RTTI for safe interfacing with the dataflow engine.
---
 .../CachedConstAccessorsLattice.h |  20 ++-
 .../Analysis/FlowSensitive/DataflowAnalysis.h | 151 +-
 .../Analysis/FlowSensitive/DataflowLattice.h  |  38 +
 .../clang/Analysis/FlowSensitive/Logger.h |   4 +-
 .../clang/Analysis/FlowSensitive/MapLattice.h |  26 ++-
 .../Models/UncheckedOptionalAccessModel.h |  24 ++-
 .../Analysis/FlowSensitive/NoopAnalysis.h |  20 +--
 .../Analysis/FlowSensitive/NoopLattice.h  |  29 ++--
 .../TypeErasedDataflowAnalysis.h  | 144 +
 clang/lib/Analysis/FlowSensitive/Arena.cpp|   4 +-
 .../lib/Analysis/FlowSensitive/HTMLLogger.cpp |   3 +-
 clang/lib/Analysis/FlowSensitive/Logger.cpp   |   4 +-
 .../Models/UncheckedOptionalAccessModel.cpp   |   9 +-
 clang/lib/Analysis/FlowSensitive/Transfer.cpp |   1 +
 .../TypeErasedDataflowAnalysis.cpp|  56 +++
 .../FlowSensitive/ChromiumCheckModelTest.cpp  |  15 +-
 .../Analysis/FlowSensitive/LoggerTest.cpp |  50 --
 .../Analysis/FlowSensitive/MapLatticeTest.cpp |  40 +++--
 .../MultiVarConstantPropagationTest.cpp   |  52 +++---
 .../FlowSensitive/SignAnalysisTest.cpp|  14 +-
 .../SingleVarConstantPropagationTest.cpp  |  52 +++---
 .../Analysis/FlowSensitive/TestingSupport.h   |   8 +-
 .../FlowSensitive/TransferBranchTest.cpp  |  33 ++--
 .../TypeErasedDataflowAnalysisTest.cpp| 116 ++
 24 files changed, 475 insertions(+), 438 deletions(-)

diff --git 
a/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h 
b/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
index 48c5287367739a..8dd9cd546be160 100644
--- a/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
+++ b/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
@@ -20,6 +20,7 @@
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/STLFunctionalExtras.h"
+#include "llvm/Support/ExtensibleRTTI.h"
 
 namespace clang {
 namespace dataflow {
@@ -88,7 +89,15 @@ template  class CachedConstAccessorsLattice : 
public Base {
 return Base::operator==(Other);
   }
 
-  LatticeJoinEffect join(const CachedConstAccessorsLattice &Other);
+  std::unique_ptr clone() override {
+return std::make_unique(*this);
+  }
+
+  bool isEqual(const DataflowLattice &Other) const override {
+return *this == llvm::cast(Other);
+  }
+
+  LatticeEffect join(const DataflowLattice &Other) override;
 
 private:
   // Maps a record storage location and const method to the value to return
@@ -146,22 +155,23 @@ joinConstMethodMap(
 
 template 
 LatticeEffect CachedConstAccessorsLattice::join(
-const CachedConstAccessorsLattice &Other) {
-
+const DataflowLattice &Other) {
   LatticeEffect Effect = Base::join(Other);
 
+  const auto &OtherL = llvm::cast>(Other);
+
   // For simplicity, we only retain values that are identical, but not ones 
that
   // are non-identical but equivalent. This is likely to be sufficient in
   // practice, and it reduces implementation complexity considerably.
 
   ConstMethodReturnValues =
   clang::dataflow::i

[clang] [clang-tools-extra] [clangd] Make clangd run `format::cleanupAroundReplacements()` for all code actions just as clang-tidy does (PR #118569)

2024-12-23 Thread Richard Li via cfe-commits

https://github.com/chomosuke updated 
https://github.com/llvm/llvm-project/pull/118569

>From efc17a803c9c22543de7d5f9e960a7267ade1f2e Mon Sep 17 00:00:00 2001
From: chomosuke 
Date: Wed, 4 Dec 2024 14:42:24 +
Subject: [PATCH 1/3] [clangd][clang-tidy] Make clangd run
 `format::cleanupAroundReplacements()` for all code actions just as clang-tidy
 does

---
 clang-tools-extra/clang-tidy/ClangTidy.cpp| 22 ++--
 clang-tools-extra/clangd/Diagnostics.cpp  | 35 -
 .../clangd/unittests/DiagnosticsTests.cpp | 51 ---
 .../include/clang/Tooling/Core/Replacement.h  |  4 ++
 clang/lib/Tooling/Core/Replacement.cpp| 16 +-
 5 files changed, 99 insertions(+), 29 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/ClangTidy.cpp 
b/clang-tools-extra/clang-tidy/ClangTidy.cpp
index 9c8c93c5d16c72..82331c724eaaf2 100644
--- a/clang-tools-extra/clang-tidy/ClangTidy.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidy.cpp
@@ -149,26 +149,12 @@ class ErrorReporter {
Repl.getLength(), 
Repl.getReplacementText());
 auto &Entry = FileReplacements[R.getFilePath()];
 Replacements &Replacements = Entry.Replaces;
-llvm::Error Err = Replacements.add(R);
+llvm::Error Err = Replacements.addOrMerge(R);
 if (Err) {
   // FIXME: Implement better conflict handling.
-  llvm::errs() << "Trying to resolve conflict: "
-   << llvm::toString(std::move(Err)) << "\n";
-  unsigned NewOffset =
-  Replacements.getShiftedCodePosition(R.getOffset());
-  unsigned NewLength = Replacements.getShiftedCodePosition(
-   R.getOffset() + R.getLength()) -
-   NewOffset;
-  if (NewLength == R.getLength()) {
-R = Replacement(R.getFilePath(), NewOffset, NewLength,
-R.getReplacementText());
-Replacements = Replacements.merge(tooling::Replacements(R));
-CanBeApplied = true;
-++AppliedFixes;
-  } else {
-llvm::errs()
-<< "Can't resolve conflict, skipping the replacement.\n";
-  }
+  llvm::errs()
+  << "Can't resolve conflict, skipping the replacement: "
+  << llvm::toString(std::move(Err)) << '\n';
 } else {
   CanBeApplied = true;
   ++AppliedFixes;
diff --git a/clang-tools-extra/clangd/Diagnostics.cpp 
b/clang-tools-extra/clangd/Diagnostics.cpp
index a59d1e7ac84096..60c6ac7256b58c 100644
--- a/clang-tools-extra/clangd/Diagnostics.cpp
+++ b/clang-tools-extra/clangd/Diagnostics.cpp
@@ -19,6 +19,7 @@
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TokenKinds.h"
+#include "clang/Format/Format.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Lex/Token.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -741,7 +742,7 @@ void StoreDiags::HandleDiagnostic(DiagnosticsEngine::Level 
DiagLevel,
   return false;
 // Copy as we may modify the ranges.
 auto FixIts = Info.getFixItHints().vec();
-llvm::SmallVector Edits;
+auto Replacements = std::make_optional();
 for (auto &FixIt : FixIts) {
   // Allow fixits within a single macro-arg expansion to be applied.
   // This can be incorrect if the argument is expanded multiple times in
@@ -761,7 +762,37 @@ void StoreDiags::HandleDiagnostic(DiagnosticsEngine::Level 
DiagLevel,
 return false;
   if (!isInsideMainFile(FixIt.RemoveRange.getBegin(), SM))
 return false;
-  Edits.push_back(toTextEdit(FixIt, SM, *LangOpts));
+
+  auto R = tooling::Replacement(SM, FixIt.RemoveRange, FixIt.CodeToInsert,
+*LangOpts);
+  auto Err = Replacements->addOrMerge(R);
+  if (Err) {
+log("Skipping formatting the replacement due to conflict: {0}",
+llvm::toString(std::move(Err)));
+Replacements = std::nullopt;
+break;
+  }
+}
+
+llvm::SmallVector Edits;
+
+if (Replacements) {
+  StringRef Code = SM.getBufferData(SM.getMainFileID());
+  auto Repl = format::cleanupAroundReplacements(Code, *Replacements,
+format::getNoStyle());
+  if (!Repl) {
+log("Skipping formatting the replacement due to conflict: {0}",
+llvm::toString(std::move(Repl.takeError(;
+Replacements = std::nullopt;
+  } else {
+auto Es = replacementsToEdits(Code, *Repl);
+Edits.append(Es.begin(), Es.end());
+  }
+}
+if (!Replacements) {
+  for (auto &FixIt : FixIts) {
+Edits.push_back(toTextEdit(FixIt, SM, *LangOpts));
+  }
 }
 
 llvm::SmallString<64> Message;
diff --git a/clang-tools-extra/clangd/unitte

[clang] [Clang][Sema] Process warnings conditionally (PR #120591)

2024-12-23 Thread via cfe-commits

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

We do not use braces for if statements with a single child statement
LGTM otherwise

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


[clang] [Clang][Sema] Process warnings conditionally (PR #120591)

2024-12-23 Thread via cfe-commits


@@ -6591,27 +6591,36 @@ void 
CheckFormatHandler::HandleNonStandardConversionSpecifier(
 
 void CheckFormatHandler::HandlePosition(const char *startPos,
 unsigned posLen) {
-  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
-   getLocationOfByte(startPos),
-   /*IsStringLocation*/true,
-   getSpecifierRange(startPos, posLen));
+  if (!S.getDiagnostics().isIgnored(
+  diag::warn_format_non_standard_positional_arg, SourceLocation())) {
+
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
+ getLocationOfByte(startPos),
+ /*IsStringLocation*/ true,
+ getSpecifierRange(startPos, posLen));
+  }

cor3ntin wrote:

```suggestion
  diag::warn_format_non_standard_positional_arg, SourceLocation()))
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
 getLocationOfByte(startPos),
 /*IsStringLocation*/ true,
 getSpecifierRange(startPos, posLen));
```

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


[clang] [Clang][Sema] Process warnings conditionally (PR #120591)

2024-12-23 Thread via cfe-commits


@@ -6591,27 +6591,36 @@ void 
CheckFormatHandler::HandleNonStandardConversionSpecifier(
 
 void CheckFormatHandler::HandlePosition(const char *startPos,
 unsigned posLen) {
-  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
-   getLocationOfByte(startPos),
-   /*IsStringLocation*/true,
-   getSpecifierRange(startPos, posLen));
+  if (!S.getDiagnostics().isIgnored(
+  diag::warn_format_non_standard_positional_arg, SourceLocation())) {
+
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
+ getLocationOfByte(startPos),
+ /*IsStringLocation*/ true,
+ getSpecifierRange(startPos, posLen));
+  }
 }
 
 void CheckFormatHandler::HandleInvalidPosition(
 const char *startSpecifier, unsigned specifierLen,
 analyze_format_string::PositionContext p) {
-  EmitFormatDiagnostic(
-  S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
-  getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
-  getSpecifierRange(startSpecifier, specifierLen));
+  if (!S.getDiagnostics().isIgnored(
+  diag::warn_format_invalid_positional_specifier, SourceLocation())) {
+EmitFormatDiagnostic(
+S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
+getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
+getSpecifierRange(startSpecifier, specifierLen));
+  }
 }
 
 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
 unsigned posLen) {
-  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
-   getLocationOfByte(startPos),
-   /*IsStringLocation*/true,
-   getSpecifierRange(startPos, posLen));
+  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
+SourceLocation())) {
+EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
+ getLocationOfByte(startPos),
+ /*IsStringLocation*/ true,
+ getSpecifierRange(startPos, posLen));
+  }

cor3ntin wrote:

```suggestion
  if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
SourceLocation()))
EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
 getLocationOfByte(startPos),
 /*IsStringLocation*/ true,
 getSpecifierRange(startPos, posLen));
```

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


[clang] [Clang][Sema] Process warnings conditionally (PR #120591)

2024-12-23 Thread via cfe-commits


@@ -6591,27 +6591,36 @@ void 
CheckFormatHandler::HandleNonStandardConversionSpecifier(
 
 void CheckFormatHandler::HandlePosition(const char *startPos,
 unsigned posLen) {
-  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
-   getLocationOfByte(startPos),
-   /*IsStringLocation*/true,
-   getSpecifierRange(startPos, posLen));
+  if (!S.getDiagnostics().isIgnored(
+  diag::warn_format_non_standard_positional_arg, SourceLocation())) {
+
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
+ getLocationOfByte(startPos),
+ /*IsStringLocation*/ true,
+ getSpecifierRange(startPos, posLen));
+  }
 }
 
 void CheckFormatHandler::HandleInvalidPosition(
 const char *startSpecifier, unsigned specifierLen,
 analyze_format_string::PositionContext p) {
-  EmitFormatDiagnostic(
-  S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
-  getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
-  getSpecifierRange(startSpecifier, specifierLen));
+  if (!S.getDiagnostics().isIgnored(
+  diag::warn_format_invalid_positional_specifier, SourceLocation())) {
+EmitFormatDiagnostic(
+S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
+getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
+getSpecifierRange(startSpecifier, specifierLen));
+  }

cor3ntin wrote:

```suggestion
  if (!S.getDiagnostics().isIgnored(
  diag::warn_format_invalid_positional_specifier, SourceLocation()))
EmitFormatDiagnostic(
S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
getSpecifierRange(startSpecifier, specifierLen));
```

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


[clang] [clang][Sema] Move computing enum width and type to a separate function (PR #120965)

2024-12-23 Thread Ilia Kuklin via cfe-commits

kuilpd wrote:

As of now LLDB doesn't calculate enum's best promotion type when reading it 
from DWARF info. This change would allow to reuse the code from Sema without 
copying it to LLDB, which I'm working on in #115005 
This function however has too many arguments right now, and also needs to 
return 3 results, so I'd be grateful for some advice how to make it look better.

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


[clang] [clang][Sema] Move computing enum width and type to a separate function (PR #120965)

2024-12-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Ilia Kuklin (kuilpd)


Changes

Move the code that calculates BestWidth, BestType and BestPromotionType for an 
enum to a separate function which can be called from outside of Sema.


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


2 Files Affected:

- (modified) clang/include/clang/Sema/Sema.h (+7) 
- (modified) clang/lib/Sema/SemaDecl.cpp (+87-71) 


``diff
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 5ee7ea48cc983c..51a1721fb74f01 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3987,6 +3987,13 @@ class Sema final : public SemaBase {
   SourceLocation IdLoc, IdentifierInfo *Id,
   const ParsedAttributesView &Attrs,
   SourceLocation EqualLoc, Expr *Val);
+
+  bool ComputeBestEnumProperties(ASTContext &Context, EnumDecl *Enum,
+ bool isCpp, bool isPacked,
+ unsigned NumNegativeBits,
+ unsigned NumPositiveBits, unsigned &BestWidth,
+ QualType &BestType,
+ QualType &BestPromotionType);
   void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  Decl *EnumDecl, ArrayRef Elements, Scope *S,
  const ParsedAttributesView &Attr);
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 4001c4d263f1d2..79cbfe3116b26b 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -20008,6 +20008,87 @@ bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const 
llvm::APInt &Val,
   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
 }
 
+bool Sema::ComputeBestEnumProperties(ASTContext &Context, EnumDecl *Enum,
+ bool is_cpp, bool isPacked,
+ unsigned NumNegativeBits,
+ unsigned NumPositiveBits,
+ unsigned &BestWidth, QualType &BestType,
+ QualType &BestPromotionType) {
+  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
+  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
+  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
+  bool enum_too_large = false;
+  if (NumNegativeBits) {
+// If there is a negative value, figure out the smallest integer type (of
+// int/long/longlong) that fits.
+// If it's packed, check also if it fits a char or a short.
+if (isPacked && NumNegativeBits <= CharWidth &&
+NumPositiveBits < CharWidth) {
+  BestType = Context.SignedCharTy;
+  BestWidth = CharWidth;
+} else if (isPacked && NumNegativeBits <= ShortWidth &&
+   NumPositiveBits < ShortWidth) {
+  BestType = Context.ShortTy;
+  BestWidth = ShortWidth;
+} else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
+  BestType = Context.IntTy;
+  BestWidth = IntWidth;
+} else {
+  BestWidth = Context.getTargetInfo().getLongWidth();
+
+  if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
+BestType = Context.LongTy;
+  } else {
+BestWidth = Context.getTargetInfo().getLongLongWidth();
+
+if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
+  enum_too_large = true;
+BestType = Context.LongLongTy;
+  }
+}
+BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
+  } else {
+// If there is no negative value, figure out the smallest type that fits
+// all of the enumerator values.
+// If it's packed, check also if it fits a char or a short.
+if (isPacked && NumPositiveBits <= CharWidth) {
+  BestType = Context.UnsignedCharTy;
+  BestPromotionType = Context.IntTy;
+  BestWidth = CharWidth;
+} else if (isPacked && NumPositiveBits <= ShortWidth) {
+  BestType = Context.UnsignedShortTy;
+  BestPromotionType = Context.IntTy;
+  BestWidth = ShortWidth;
+} else if (NumPositiveBits <= IntWidth) {
+  BestType = Context.UnsignedIntTy;
+  BestWidth = IntWidth;
+  BestPromotionType = (NumPositiveBits == BestWidth || !is_cpp)
+  ? Context.UnsignedIntTy
+  : Context.IntTy;
+} else if (NumPositiveBits <=
+   (BestWidth = Context.getTargetInfo().getLongWidth())) {
+  BestType = Context.UnsignedLongTy;
+  BestPromotionType = (NumPositiveBits == BestWidth || !is_cpp)
+  ? Context.UnsignedLongTy
+  : Context.LongTy;
+} else {
+  BestWidth = Context.getTargetInfo().getLongLongWidth();
+  if (NumPositiveBits > BestWidth) {
+// This can happen with bit-precise integer 

[clang] [clang][Sema] Move computing enum width and type to a separate function (PR #120965)

2024-12-23 Thread Ilia Kuklin via cfe-commits

https://github.com/kuilpd created 
https://github.com/llvm/llvm-project/pull/120965

Move the code that calculates BestWidth, BestType and BestPromotionType for an 
enum to a separate function which can be called from outside of Sema.


>From ab8dcaef120233d0145508aaa4bf45eec22cadf1 Mon Sep 17 00:00:00 2001
From: Ilia Kuklin 
Date: Mon, 23 Dec 2024 17:49:32 +0500
Subject: [PATCH] [clang][Sema] Move calculating enum width and type to a
 separate function

---
 clang/include/clang/Sema/Sema.h |   7 ++
 clang/lib/Sema/SemaDecl.cpp | 158 ++--
 2 files changed, 94 insertions(+), 71 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 5ee7ea48cc983c..51a1721fb74f01 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3987,6 +3987,13 @@ class Sema final : public SemaBase {
   SourceLocation IdLoc, IdentifierInfo *Id,
   const ParsedAttributesView &Attrs,
   SourceLocation EqualLoc, Expr *Val);
+
+  bool ComputeBestEnumProperties(ASTContext &Context, EnumDecl *Enum,
+ bool isCpp, bool isPacked,
+ unsigned NumNegativeBits,
+ unsigned NumPositiveBits, unsigned &BestWidth,
+ QualType &BestType,
+ QualType &BestPromotionType);
   void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  Decl *EnumDecl, ArrayRef Elements, Scope *S,
  const ParsedAttributesView &Attr);
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 4001c4d263f1d2..79cbfe3116b26b 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -20008,6 +20008,87 @@ bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const 
llvm::APInt &Val,
   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
 }
 
+bool Sema::ComputeBestEnumProperties(ASTContext &Context, EnumDecl *Enum,
+ bool is_cpp, bool isPacked,
+ unsigned NumNegativeBits,
+ unsigned NumPositiveBits,
+ unsigned &BestWidth, QualType &BestType,
+ QualType &BestPromotionType) {
+  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
+  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
+  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
+  bool enum_too_large = false;
+  if (NumNegativeBits) {
+// If there is a negative value, figure out the smallest integer type (of
+// int/long/longlong) that fits.
+// If it's packed, check also if it fits a char or a short.
+if (isPacked && NumNegativeBits <= CharWidth &&
+NumPositiveBits < CharWidth) {
+  BestType = Context.SignedCharTy;
+  BestWidth = CharWidth;
+} else if (isPacked && NumNegativeBits <= ShortWidth &&
+   NumPositiveBits < ShortWidth) {
+  BestType = Context.ShortTy;
+  BestWidth = ShortWidth;
+} else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
+  BestType = Context.IntTy;
+  BestWidth = IntWidth;
+} else {
+  BestWidth = Context.getTargetInfo().getLongWidth();
+
+  if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
+BestType = Context.LongTy;
+  } else {
+BestWidth = Context.getTargetInfo().getLongLongWidth();
+
+if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
+  enum_too_large = true;
+BestType = Context.LongLongTy;
+  }
+}
+BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
+  } else {
+// If there is no negative value, figure out the smallest type that fits
+// all of the enumerator values.
+// If it's packed, check also if it fits a char or a short.
+if (isPacked && NumPositiveBits <= CharWidth) {
+  BestType = Context.UnsignedCharTy;
+  BestPromotionType = Context.IntTy;
+  BestWidth = CharWidth;
+} else if (isPacked && NumPositiveBits <= ShortWidth) {
+  BestType = Context.UnsignedShortTy;
+  BestPromotionType = Context.IntTy;
+  BestWidth = ShortWidth;
+} else if (NumPositiveBits <= IntWidth) {
+  BestType = Context.UnsignedIntTy;
+  BestWidth = IntWidth;
+  BestPromotionType = (NumPositiveBits == BestWidth || !is_cpp)
+  ? Context.UnsignedIntTy
+  : Context.IntTy;
+} else if (NumPositiveBits <=
+   (BestWidth = Context.getTargetInfo().getLongWidth())) {
+  BestType = Context.UnsignedLongTy;
+  BestPromotionType = (NumPositiveBits == BestWidth || !is_cpp)
+  ? Context.UnsignedLongTy
+  : Contex

[clang] [analyzer] Don't assume third iteration in loops (PR #119388)

2024-12-23 Thread Gábor Horváth via cfe-commits

Xazax-hun wrote:

Do you expect any changes for less obvious ways of looping?
* Recursion
* `while(true) if (cond) break;`
* Like above but with gotos
?

Would be nice to have some tests for those as well. 



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


[clang] [clang-tools-extra] [clangd] Make clangd run `format::cleanupAroundReplacements()` for all code actions just as clang-tidy does (PR #118569)

2024-12-23 Thread Richard Li via cfe-commits

chomosuke wrote:

Thank you for the review @llvm-beanz, I've fixed the suggestions :).

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


[clang] [clang-tools-extra] [clangd] Make clangd run `format::cleanupAroundReplacements()` for all code actions just as clang-tidy does (PR #118569)

2024-12-23 Thread Richard Li via cfe-commits

https://github.com/chomosuke updated 
https://github.com/llvm/llvm-project/pull/118569

>From efc17a803c9c22543de7d5f9e960a7267ade1f2e Mon Sep 17 00:00:00 2001
From: chomosuke 
Date: Wed, 4 Dec 2024 14:42:24 +
Subject: [PATCH 1/3] [clangd][clang-tidy] Make clangd run
 `format::cleanupAroundReplacements()` for all code actions just as clang-tidy
 does

---
 clang-tools-extra/clang-tidy/ClangTidy.cpp| 22 ++--
 clang-tools-extra/clangd/Diagnostics.cpp  | 35 -
 .../clangd/unittests/DiagnosticsTests.cpp | 51 ---
 .../include/clang/Tooling/Core/Replacement.h  |  4 ++
 clang/lib/Tooling/Core/Replacement.cpp| 16 +-
 5 files changed, 99 insertions(+), 29 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/ClangTidy.cpp 
b/clang-tools-extra/clang-tidy/ClangTidy.cpp
index 9c8c93c5d16c72..82331c724eaaf2 100644
--- a/clang-tools-extra/clang-tidy/ClangTidy.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidy.cpp
@@ -149,26 +149,12 @@ class ErrorReporter {
Repl.getLength(), 
Repl.getReplacementText());
 auto &Entry = FileReplacements[R.getFilePath()];
 Replacements &Replacements = Entry.Replaces;
-llvm::Error Err = Replacements.add(R);
+llvm::Error Err = Replacements.addOrMerge(R);
 if (Err) {
   // FIXME: Implement better conflict handling.
-  llvm::errs() << "Trying to resolve conflict: "
-   << llvm::toString(std::move(Err)) << "\n";
-  unsigned NewOffset =
-  Replacements.getShiftedCodePosition(R.getOffset());
-  unsigned NewLength = Replacements.getShiftedCodePosition(
-   R.getOffset() + R.getLength()) -
-   NewOffset;
-  if (NewLength == R.getLength()) {
-R = Replacement(R.getFilePath(), NewOffset, NewLength,
-R.getReplacementText());
-Replacements = Replacements.merge(tooling::Replacements(R));
-CanBeApplied = true;
-++AppliedFixes;
-  } else {
-llvm::errs()
-<< "Can't resolve conflict, skipping the replacement.\n";
-  }
+  llvm::errs()
+  << "Can't resolve conflict, skipping the replacement: "
+  << llvm::toString(std::move(Err)) << '\n';
 } else {
   CanBeApplied = true;
   ++AppliedFixes;
diff --git a/clang-tools-extra/clangd/Diagnostics.cpp 
b/clang-tools-extra/clangd/Diagnostics.cpp
index a59d1e7ac84096..60c6ac7256b58c 100644
--- a/clang-tools-extra/clangd/Diagnostics.cpp
+++ b/clang-tools-extra/clangd/Diagnostics.cpp
@@ -19,6 +19,7 @@
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TokenKinds.h"
+#include "clang/Format/Format.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Lex/Token.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -741,7 +742,7 @@ void StoreDiags::HandleDiagnostic(DiagnosticsEngine::Level 
DiagLevel,
   return false;
 // Copy as we may modify the ranges.
 auto FixIts = Info.getFixItHints().vec();
-llvm::SmallVector Edits;
+auto Replacements = std::make_optional();
 for (auto &FixIt : FixIts) {
   // Allow fixits within a single macro-arg expansion to be applied.
   // This can be incorrect if the argument is expanded multiple times in
@@ -761,7 +762,37 @@ void StoreDiags::HandleDiagnostic(DiagnosticsEngine::Level 
DiagLevel,
 return false;
   if (!isInsideMainFile(FixIt.RemoveRange.getBegin(), SM))
 return false;
-  Edits.push_back(toTextEdit(FixIt, SM, *LangOpts));
+
+  auto R = tooling::Replacement(SM, FixIt.RemoveRange, FixIt.CodeToInsert,
+*LangOpts);
+  auto Err = Replacements->addOrMerge(R);
+  if (Err) {
+log("Skipping formatting the replacement due to conflict: {0}",
+llvm::toString(std::move(Err)));
+Replacements = std::nullopt;
+break;
+  }
+}
+
+llvm::SmallVector Edits;
+
+if (Replacements) {
+  StringRef Code = SM.getBufferData(SM.getMainFileID());
+  auto Repl = format::cleanupAroundReplacements(Code, *Replacements,
+format::getNoStyle());
+  if (!Repl) {
+log("Skipping formatting the replacement due to conflict: {0}",
+llvm::toString(std::move(Repl.takeError(;
+Replacements = std::nullopt;
+  } else {
+auto Es = replacementsToEdits(Code, *Repl);
+Edits.append(Es.begin(), Es.end());
+  }
+}
+if (!Replacements) {
+  for (auto &FixIt : FixIts) {
+Edits.push_back(toTextEdit(FixIt, SM, *LangOpts));
+  }
 }
 
 llvm::SmallString<64> Message;
diff --git a/clang-tools-extra/clangd/unitte

[clang] [lldb] [clang][RecordLayoutBuilder] Be stricter about inferring packed-ness in ExternalLayouts (PR #97443)

2024-12-23 Thread Michael Buch via cfe-commits

Michael137 wrote:

> > FWIW, I came across another no_unique_address-related crash today:
> > ```
> > $ cat a.cc
> > struct S {
> > private:
> >   int i;
> >   short s;
> > };
> > static_assert(sizeof(S) == 8);
> > 
> > struct T {
> >   [[no_unique_address]] S s;
> >   char c;
> > };
> > static_assert(sizeof(T) == 8);
> > 
> > T t;
> > $ clang++ -c -o /tmp/a.out /tmp/a.cc -g
> > $ lldb /tmp/a.out -o "expr t" -x
> > (lldb) target create "/tmp/a.out"
> > Current executable set to '/tmp/a.out' (x86_64).
> > (lldb) expr t
> > assertion failed at clang/lib/CodeGen/CGRecordLayoutBuilder.cpp:960 in void 
> > (anonymous namespace)::CGRecordLowering::checkBitfieldClipping(bool) const: 
> > M.Offset >= Tail && "Bitfield access unit is not clipped"
> > ...
> > ```
> > 
> > 
> > 
> >   
> > 
> > 
> >   
> > 
> > 
> > 
> >   
> > I was hoping this PR would fix it, but it doesn't appear to help.
> 
> Hmmm interesting, yea that looks more like something that #96422 should've 
> addressed. Though this is a special case where the attribute is applied to a 
> non-empty type. Would need to step through the `CGRecordLayoutBuilder` to see 
> why Clang believes the offsets from DWARF aren't correct.

Yea I took a quick look at this and the problem is the following check: 
https://github.com/llvm/llvm-project/blob/44be5a7fdc20a7f90d63dc18699a470e900bd3ba/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp#L392

`S` is potentially overlapping because it has the `NoUniqueAddress` attribute, 
but that isn't present in the DWARF AST. So when we compute the record layout 
using the DWARF AST we push_back the incorrect MemberInfo here:
```
(lldb) p getStorageType(Field->getType()->getAsCXXRecordDecl())->dump() 

  
%struct.S.base = type <{ i32, i16 }>

  
(lldb) p getStorageType(*Field)->dump() 


  
%struct.S = type <{ i32, i16, [2 x i8] }>   
  
(lldb) n
  
```
In the `isPotentiallyOverlapping` case we would've picked the layout without 
the tail padding.

So we're back to "how do we encode this isPotentiallyOverlapping property 
DWARF". OR, maybe we can get away with removing that dependency on the AST in 
the same way we did with `isZeroSize`..

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


[clang] [lldb] [clang][RecordLayoutBuilder] Be stricter about inferring packed-ness in ExternalLayouts (PR #97443)

2024-12-23 Thread Pavel Labath via cfe-commits

labath wrote:

FWIW, I came across another no_unique_address-related crash today:
```
$ cat a.cc
struct S {
private:
  int i;
  short s;
};
static_assert(sizeof(S) == 8);

struct T {
  [[no_unique_address]] S s;
  char c;
};
static_assert(sizeof(T) == 8);

T t;
$ clang++ -c -o /tmp/a.out /tmp/a.cc -g
$ lldb /tmp/a.out -o "expr t" -x
(lldb) target create "/tmp/a.out"
Current executable set to '/tmp/a.out' (x86_64).
(lldb) expr t
assertion failed at clang/lib/CodeGen/CGRecordLayoutBuilder.cpp:960 in void 
(anonymous namespace)::CGRecordLowering::checkBitfieldClipping(bool) const: 
M.Offset >= Tail && "Bitfield access unit is not clipped"
...
```

I was hoping this PR would fix it, but it doesn't appear to help.

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


[clang] [llvm] [mlir] [NVPTX] Switch front-ends and tests to ptx_kernel cc (PR #120806)

2024-12-23 Thread Durgadoss R via cfe-commits


@@ -556,19 +556,16 @@ llvm.func @kernel_func() attributes {nvvm.kernel} {
   llvm.return
 }
 
-// CHECK: !nvvm.annotations =
-// CHECK-NOT: {ptr @nvvm_special_regs, !"kernel", i32 1}
-// CHECK: {ptr @kernel_func, !"kernel", i32 1}
+// CHECK: ptx_kernel void @kernel_func

durga4github wrote:

So, downstream (non-upstream ones) users should migrate to this cc-based 
instead of kernel-metadata based, right?
I am asking since this does not seem to be an opt-in/optional change.

Alex, Could you please clarify?

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


[clang] [llvm] [openmp] [OpenMP] Use generic IR for the OpenMP DeviceRTL (PR #119091)

2024-12-23 Thread Joseph Huber via cfe-commits

jhuber6 wrote:

> @jhuber6, since I think this PR makes #119006 obsolete, should I merge that 
> one while this one's still in the works, or close it?

I wouldn't say it's high priority. I would've landed this already if it weren't 
for the downstream fork being so divergent this isn't an easy apply.

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


[clang] Introduce virtual interface for lattices and remove dependency on `llvm::Any`. (PR #120967)

2024-12-23 Thread Yitzhak Mandelbaum via cfe-commits

https://github.com/ymand updated 
https://github.com/llvm/llvm-project/pull/120967

>From 27ef09ae6f7a83fa3cf9ee98a46b02880607add8 Mon Sep 17 00:00:00 2001
From: Yitzhak Mandelbaum 
Date: Mon, 23 Dec 2024 13:42:21 +
Subject: [PATCH] Introduce virtual interface for lattices and remove
 dependency on `llvm::Any`.

This PR has 2 related goals:

*Remove dependency on `llvm::Any`*. For some platforms, use of `llvm::Any`
forces users to explicitly define internal details related to `Any`. Aside from
aesthetics, this places an obscure requirement on lattice implementers. We
prefer to use LLVM's (explicit) RTTI framework instead.

*Introduce virtual interface for lattices*. Currently, we implicitly define the
interface for lattices, because the interface to analyses is fully captured in
templates. This PR moves to an explicit, virtual interface.

We combine these two changes in a single PR because they are closely related: we
use the new lattice interface as the basis of an open type hierarchy that embeds
RTTI for safe interfacing with the dataflow engine.

As a side-effect, we are able to greatly simplify the interface of
`DataflowAnalysis` and collapse the distinction between it and
`TypeErasedDataflowAnalysis`.
---
 .../CachedConstAccessorsLattice.h |  20 ++-
 .../Analysis/FlowSensitive/DataflowAnalysis.h | 151 +-
 .../Analysis/FlowSensitive/DataflowLattice.h  |  38 +
 .../clang/Analysis/FlowSensitive/Logger.h |   4 +-
 .../clang/Analysis/FlowSensitive/MapLattice.h |  26 ++-
 .../Models/UncheckedOptionalAccessModel.h |  24 ++-
 .../Analysis/FlowSensitive/NoopAnalysis.h |  20 +--
 .../Analysis/FlowSensitive/NoopLattice.h  |  29 ++--
 .../TypeErasedDataflowAnalysis.h  | 144 +
 clang/lib/Analysis/FlowSensitive/Arena.cpp|   4 +-
 .../lib/Analysis/FlowSensitive/HTMLLogger.cpp |   3 +-
 clang/lib/Analysis/FlowSensitive/Logger.cpp   |   4 +-
 .../Models/UncheckedOptionalAccessModel.cpp   |   9 +-
 clang/lib/Analysis/FlowSensitive/Transfer.cpp |   1 +
 .../TypeErasedDataflowAnalysis.cpp|  56 +++
 .../FlowSensitive/ChromiumCheckModelTest.cpp  |  15 +-
 .../Analysis/FlowSensitive/LoggerTest.cpp |  50 --
 .../Analysis/FlowSensitive/MapLatticeTest.cpp |  40 +++--
 .../MultiVarConstantPropagationTest.cpp   |  52 +++---
 .../FlowSensitive/SignAnalysisTest.cpp|  14 +-
 .../SingleVarConstantPropagationTest.cpp  |  52 +++---
 .../Analysis/FlowSensitive/TestingSupport.h   |   8 +-
 .../FlowSensitive/TransferBranchTest.cpp  |  33 ++--
 .../TypeErasedDataflowAnalysisTest.cpp| 116 ++
 24 files changed, 475 insertions(+), 438 deletions(-)

diff --git 
a/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h 
b/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
index 48c5287367739a..8dd9cd546be160 100644
--- a/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
+++ b/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
@@ -20,6 +20,7 @@
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/STLFunctionalExtras.h"
+#include "llvm/Support/ExtensibleRTTI.h"
 
 namespace clang {
 namespace dataflow {
@@ -88,7 +89,15 @@ template  class CachedConstAccessorsLattice : 
public Base {
 return Base::operator==(Other);
   }
 
-  LatticeJoinEffect join(const CachedConstAccessorsLattice &Other);
+  std::unique_ptr clone() override {
+return std::make_unique(*this);
+  }
+
+  bool isEqual(const DataflowLattice &Other) const override {
+return *this == llvm::cast(Other);
+  }
+
+  LatticeEffect join(const DataflowLattice &Other) override;
 
 private:
   // Maps a record storage location and const method to the value to return
@@ -146,22 +155,23 @@ joinConstMethodMap(
 
 template 
 LatticeEffect CachedConstAccessorsLattice::join(
-const CachedConstAccessorsLattice &Other) {
-
+const DataflowLattice &Other) {
   LatticeEffect Effect = Base::join(Other);
 
+  const auto &OtherL = llvm::cast>(Other);
+
   // For simplicity, we only retain values that are identical, but not ones 
that
   // are non-identical but equivalent. This is likely to be sufficient in
   // practice, and it reduces implementation complexity considerably.
 
   ConstMethodReturnValues =
   clang::dataflow::internal::joinConstMethodMap(
-  ConstMethodReturnValues, Other.ConstMethodReturnValues, Effect);
+  ConstMethodReturnValues, OtherL.ConstMethodReturnValues, Effect);
 
   ConstMethodReturnStorageLocations =
   clang::dataflow::internal::joinConstMethodMap(
   ConstMethodReturnStorageLocations,
-  Other.ConstMethodReturnStorageLocations, Effect);
+  OtherL.ConstMethodReturnStorageLocations, Effect);
 
   return Effect;
 }
diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h 
b/clang/include/clang/Analysis/FlowSensitive/Da

[clang] Introduce virtual interface for lattices and remove dependency on `llvm::Any`. (PR #120967)

2024-12-23 Thread Yitzhak Mandelbaum via cfe-commits

https://github.com/ymand updated 
https://github.com/llvm/llvm-project/pull/120967

>From 3792a385b1ecd2dd029fc6321bacac1de5d8eb46 Mon Sep 17 00:00:00 2001
From: Yitzhak Mandelbaum 
Date: Mon, 23 Dec 2024 13:42:21 +
Subject: [PATCH] Introduce virtual interface for lattices and remove
 dependency on `llvm::Any`.

This PR has 2 related goals:

*Remove dependency on `llvm::Any`*. For some platforms, use of `llvm::Any`
forces users to explicitly define internal details related to `Any`. Aside from
aesthetics, this places an obscure requirement on lattice implementers. We
prefer to use LLVM's (explicit) RTTI framework instead.

*Introduce virtual interface for lattices*. Currently, we implicitly define the
interface for lattices, because the interface to analyses is fully captured in
templates. This PR moves to an explicit, virtual interface.

We combine these two changes in a single PR because they are closely related: we
use the new lattice interface as the basis of an open type hierarchy that embeds
RTTI for safe interfacing with the dataflow engine.

As a side-effect, we are able to greatly simplify the interface of
`DataflowAnalysis` and collapse the distinction between it and
`TypeErasedDataflowAnalysis`.
---
 .../CachedConstAccessorsLattice.h |  27 +++-
 .../Analysis/FlowSensitive/DataflowAnalysis.h | 151 +-
 .../Analysis/FlowSensitive/DataflowLattice.h  |  46 ++
 .../clang/Analysis/FlowSensitive/Logger.h |   4 +-
 .../clang/Analysis/FlowSensitive/MapLattice.h |  27 +++-
 .../Models/UncheckedOptionalAccessModel.h |  18 ++-
 .../Analysis/FlowSensitive/NoopAnalysis.h |  20 +--
 .../Analysis/FlowSensitive/NoopLattice.h  |  30 ++--
 .../TypeErasedDataflowAnalysis.h  | 117 +-
 clang/lib/Analysis/FlowSensitive/Arena.cpp|   4 +-
 .../lib/Analysis/FlowSensitive/HTMLLogger.cpp |   3 +-
 clang/lib/Analysis/FlowSensitive/Logger.cpp   |   4 +-
 .../Models/UncheckedOptionalAccessModel.cpp   |   9 +-
 clang/lib/Analysis/FlowSensitive/Transfer.cpp |   1 +
 .../TypeErasedDataflowAnalysis.cpp|  71 
 .../FlowSensitive/ChromiumCheckModelTest.cpp  |  15 +-
 .../Analysis/FlowSensitive/LoggerTest.cpp |  50 --
 .../Analysis/FlowSensitive/MapLatticeTest.cpp |  40 +++--
 .../MultiVarConstantPropagationTest.cpp   |  52 +++---
 .../FlowSensitive/SignAnalysisTest.cpp|  14 +-
 .../SingleVarConstantPropagationTest.cpp  |  52 +++---
 .../Analysis/FlowSensitive/TestingSupport.h   |   8 +-
 .../FlowSensitive/TransferBranchTest.cpp  |  33 ++--
 .../TypeErasedDataflowAnalysisTest.cpp| 116 ++
 24 files changed, 463 insertions(+), 449 deletions(-)

diff --git 
a/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h 
b/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
index 48c5287367739a..efa173e348e36e 100644
--- a/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
+++ b/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
@@ -20,6 +20,7 @@
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/STLFunctionalExtras.h"
+#include "llvm/Support/ExtensibleRTTI.h"
 
 namespace clang {
 namespace dataflow {
@@ -45,9 +46,15 @@ namespace dataflow {
 /// use(s.getFoo().value()); // unsafe (invalidate cache for s)
 ///   }
 /// }
-template  class CachedConstAccessorsLattice : public Base {
+template 
+class CachedConstAccessorsLattice
+: public llvm::RTTIExtends, Base> {
 public:
-  using Base::Base; // inherit all constructors
+  using Parent = llvm::RTTIExtends;
+  using Parent::Parent; // inherit all constructors
+
+  /// For RTTI.
+  inline static char ID = 0;
 
   /// Creates or returns a previously created `Value` associated with a const
   /// method call `obj.getFoo()` where `RecordLoc` is the
@@ -88,7 +95,16 @@ template  class CachedConstAccessorsLattice : 
public Base {
 return Base::operator==(Other);
   }
 
-  LatticeJoinEffect join(const CachedConstAccessorsLattice &Other);
+  std::unique_ptr clone() override {
+return std::make_unique(*this);
+  }
+
+  bool isEqual(const DataflowLattice &Other) const override {
+return llvm::isa(Other) &&
+   *this == llvm::cast(Other);
+  }
+
+  LatticeEffect join(const DataflowLattice &Other) override;
 
 private:
   // Maps a record storage location and const method to the value to return
@@ -146,9 +162,10 @@ joinConstMethodMap(
 
 template 
 LatticeEffect CachedConstAccessorsLattice::join(
-const CachedConstAccessorsLattice &Other) {
+const DataflowLattice &L) {
+  LatticeEffect Effect = Base::join(L);
 
-  LatticeEffect Effect = Base::join(Other);
+  const auto &Other = llvm::cast>(L);
 
   // For simplicity, we only retain values that are identical, but not ones 
that
   // are non-identical but equivalent. This is likely to be sufficient in
diff --git a/clang/include/clang/Analysis/FlowS

[clang] Introduce virtual interface for lattices and remove dependency on `llvm::Any`. (PR #120967)

2024-12-23 Thread Yitzhak Mandelbaum via cfe-commits

https://github.com/ymand updated 
https://github.com/llvm/llvm-project/pull/120967

>From 2273b56b783b7923108dbb3a5857d256fc4a44ca Mon Sep 17 00:00:00 2001
From: Yitzhak Mandelbaum 
Date: Mon, 23 Dec 2024 13:42:21 +
Subject: [PATCH] Introduce virtual interface for lattices and remove
 dependency on `llvm::Any`.

This PR has 2 related goals:

*Remove dependency on `llvm::Any`*. For some platforms, use of `llvm::Any`
forces users to explicitly define internal details related to `Any`. Aside from
aesthetics, this places an obscure requirement on lattice implementers. We
prefer to use LLVM's (explicit) RTTI framework instead.

*Introduce virtual interface for lattices*. Currently, we implicitly define the
interface for lattices, because the interface to analyses is fully captured in
templates. This PR moves to an explicit, virtual interface.

We combine these two changes in a single PR because they are closely related: we
use the new lattice interface as the basis of an open type hierarchy that embeds
RTTI for safe interfacing with the dataflow engine.

As a side-effect, we are able to greatly simplify the interface of
`DataflowAnalysis` and collapse the distinction between it and
`TypeErasedDataflowAnalysis`.
---
 .../CachedConstAccessorsLattice.h |  29 +++-
 .../Analysis/FlowSensitive/DataflowAnalysis.h | 151 +-
 .../Analysis/FlowSensitive/DataflowLattice.h  |  46 ++
 .../clang/Analysis/FlowSensitive/Logger.h |   5 +-
 .../clang/Analysis/FlowSensitive/MapLattice.h |  26 ++-
 .../Models/UncheckedOptionalAccessModel.h |  19 ++-
 .../Analysis/FlowSensitive/NoopAnalysis.h |  20 +--
 .../Analysis/FlowSensitive/NoopLattice.h  |  30 ++--
 .../TypeErasedDataflowAnalysis.h  |  83 +++---
 clang/lib/Analysis/FlowSensitive/Arena.cpp|   4 +-
 .../lib/Analysis/FlowSensitive/HTMLLogger.cpp |   3 +-
 clang/lib/Analysis/FlowSensitive/Logger.cpp   |   4 +-
 .../Models/UncheckedOptionalAccessModel.cpp   |   9 +-
 clang/lib/Analysis/FlowSensitive/Transfer.cpp |   1 +
 .../TypeErasedDataflowAnalysis.cpp|  71 
 .../FlowSensitive/ChromiumCheckModelTest.cpp  |  15 +-
 .../Analysis/FlowSensitive/LoggerTest.cpp |  50 --
 .../Analysis/FlowSensitive/MapLatticeTest.cpp |  40 +++--
 .../MultiVarConstantPropagationTest.cpp   |  56 ---
 .../FlowSensitive/SignAnalysisTest.cpp|  14 +-
 .../SingleVarConstantPropagationTest.cpp  |  52 +++---
 .../Analysis/FlowSensitive/TestingSupport.h   |   8 +-
 .../FlowSensitive/TransferBranchTest.cpp  |  34 ++--
 .../TypeErasedDataflowAnalysisTest.cpp| 117 +-
 24 files changed, 448 insertions(+), 439 deletions(-)

diff --git 
a/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h 
b/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
index 48c5287367739a..07478d40a42345 100644
--- a/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
+++ b/clang/include/clang/Analysis/FlowSensitive/CachedConstAccessorsLattice.h
@@ -20,6 +20,7 @@
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/STLFunctionalExtras.h"
+#include "llvm/Support/ExtensibleRTTI.h"
 
 namespace clang {
 namespace dataflow {
@@ -45,9 +46,15 @@ namespace dataflow {
 /// use(s.getFoo().value()); // unsafe (invalidate cache for s)
 ///   }
 /// }
-template  class CachedConstAccessorsLattice : public Base {
+template 
+class CachedConstAccessorsLattice
+: public llvm::RTTIExtends, Base> {
 public:
-  using Base::Base; // inherit all constructors
+  using Parent = llvm::RTTIExtends;
+  using Parent::Parent; // inherit all constructors
+
+  /// For RTTI.
+  inline static char ID = 0;
 
   /// Creates or returns a previously created `Value` associated with a const
   /// method call `obj.getFoo()` where `RecordLoc` is the
@@ -88,7 +95,16 @@ template  class CachedConstAccessorsLattice : 
public Base {
 return Base::operator==(Other);
   }
 
-  LatticeJoinEffect join(const CachedConstAccessorsLattice &Other);
+  std::unique_ptr clone() override {
+return std::make_unique(*this);
+  }
+
+  bool isEqual(const DataflowLattice &Other) const override {
+return llvm::isa(Other) &&
+   *this == llvm::cast(Other);
+  }
+
+  LatticeEffect join(const DataflowLattice &Other) override;
 
 private:
   // Maps a record storage location and const method to the value to return
@@ -145,10 +161,11 @@ joinConstMethodMap(
 } // namespace internal
 
 template 
-LatticeEffect CachedConstAccessorsLattice::join(
-const CachedConstAccessorsLattice &Other) {
+LatticeEffect
+CachedConstAccessorsLattice::join(const DataflowLattice &L) {
+  LatticeEffect Effect = Base::join(L);
 
-  LatticeEffect Effect = Base::join(Other);
+  const auto &Other = llvm::cast>(L);
 
   // For simplicity, we only retain values that are identical, but not ones 
that
   // are non-identical but equivalent. This is likely 

[clang] [llvm] [openmp] [OpenMP] Use generic IR for the OpenMP DeviceRTL (PR #119091)

2024-12-23 Thread Michał Górny via cfe-commits

mgorny wrote:

@jhuber6, since I think this PR makes #119006 obsolete, should I merge that one 
while this one's still in the works, or close it?

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


[clang-tools-extra] [clang-tidy] swap cppcoreguidelines-narrowing-conversions and bugprone-narrowing-conversions (PR #120245)

2024-12-23 Thread Carlos Galvez via cfe-commits




carlosgalvezp wrote:

+1

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


[clang] [Clang] raise extension warning for unknown namespaced attributes (PR #120925)

2024-12-23 Thread Oleksandr T. via cfe-commits

a-tarasyuk wrote:

@namandixit it is possible. I'm not confident about the new option., 
@AaronBallman @erichkeane  - should _unknown namespaced attributes_ be 
separated by the new option?

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


[clang] [Clang] raise extension warning for unknown namespaced attributes (PR #120925)

2024-12-23 Thread Oleksandr T. via cfe-commits

https://github.com/a-tarasyuk updated 
https://github.com/llvm/llvm-project/pull/120925

>From bce88b1bb464438828fc177c978ad2b99957530f Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Mon, 23 Dec 2024 02:35:07 +0200
Subject: [PATCH 1/2] [Clang] raise extension warning for unknown namespaced
 attributes

---
 clang/docs/ReleaseNotes.rst|  2 ++
 clang/include/clang/Basic/DiagnosticCommonKinds.td |  2 ++
 clang/lib/Sema/SemaDeclAttr.cpp|  2 ++
 .../CXX/dcl.dcl/dcl.attr/dcl.attr.grammar/p2-1z.cpp|  4 ++--
 clang/test/CXX/module/module.interface/p3.cpp  |  2 +-
 clang/test/Lexer/cxx2a-spaceship.cpp   |  2 +-
 clang/test/OpenMP/openmp_attribute_parsing.cpp |  2 +-
 clang/test/Parser/c2x-attributes.c |  2 +-
 clang/test/Parser/cxx0x-attributes.cpp |  2 +-
 clang/test/Sema/patchable-function-entry-attr.cpp  |  2 +-
 clang/test/Sema/unknown-attributes.c   | 10 ++
 clang/test/SemaCXX/cxx2a-ms-no-unique-address.cpp  |  4 ++--
 12 files changed, 26 insertions(+), 10 deletions(-)
 create mode 100644 clang/test/Sema/unknown-attributes.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6b9e1109f3906e..e2cf90aecf3666 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -552,6 +552,8 @@ Attribute Changes in Clang
 - Clang now permits the usage of the placement new operator in 
``[[msvc::constexpr]]``
   context outside of the std namespace. (#GH74924)
 
+- Clang now raises warnings for unknown namespaced attributes only in pedantic 
mode (#GH120875).
+
 Improvements to Clang's diagnostics
 ---
 
diff --git a/clang/include/clang/Basic/DiagnosticCommonKinds.td 
b/clang/include/clang/Basic/DiagnosticCommonKinds.td
index f4a155bb00bb37..85653429aa5332 100644
--- a/clang/include/clang/Basic/DiagnosticCommonKinds.td
+++ b/clang/include/clang/Basic/DiagnosticCommonKinds.td
@@ -179,6 +179,8 @@ def err_opencl_unknown_type_specifier : Error<
 
 def warn_unknown_attribute_ignored : Warning<
   "unknown attribute %0 ignored">, InGroup;
+def ext_unknown_attribute_ignored : Extension<
+  "unknown attribute %0 ignored">, InGroup;
 def warn_attribute_ignored : Warning<"%0 attribute ignored">,
   InGroup;
 def err_keyword_not_supported_on_target : Error<
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index bb4d33560b93b8..9b1ffebe0804a5 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -6548,6 +6548,8 @@ ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, 
const ParsedAttr &AL,
? (unsigned)diag::err_keyword_not_supported_on_target
: AL.isDeclspecAttribute()
? (unsigned)diag::warn_unhandled_ms_attribute_ignored
+   : AL.getScopeName()
+   ? (unsigned)diag::ext_unknown_attribute_ignored
: (unsigned)diag::warn_unknown_attribute_ignored)
 << AL << AL.getRange();
 return;
diff --git a/clang/test/CXX/dcl.dcl/dcl.attr/dcl.attr.grammar/p2-1z.cpp 
b/clang/test/CXX/dcl.dcl/dcl.attr/dcl.attr.grammar/p2-1z.cpp
index 192fa126109873..c7e66649fb7b22 100644
--- a/clang/test/CXX/dcl.dcl/dcl.attr/dcl.attr.grammar/p2-1z.cpp
+++ b/clang/test/CXX/dcl.dcl/dcl.attr/dcl.attr.grammar/p2-1z.cpp
@@ -12,5 +12,5 @@
 [[using clang:]] extern int n; // ok
 [[using blah: clang::optnone]] extern int n; // expected-error {{attribute 
with scope specifier cannot follow}} expected-warning {{only applies to 
functions}}
 
-[[using clang: unknown_attr]] extern int n; // expected-warning {{unknown 
attribute}}
-[[using unknown_ns: something]] extern int n; // expected-warning {{unknown 
attribute}}
+[[using clang: unknown_attr]] extern int n;
+[[using unknown_ns: something]] extern int n;
diff --git a/clang/test/CXX/module/module.interface/p3.cpp 
b/clang/test/CXX/module/module.interface/p3.cpp
index 32819b2dccb11d..3cde92c1a2cf34 100644
--- a/clang/test/CXX/module/module.interface/p3.cpp
+++ b/clang/test/CXX/module/module.interface/p3.cpp
@@ -40,7 +40,7 @@ export { // No diagnostic after P2615R1 DR
   extern "C++" {} // No diagnostic after P2615R1 DR
 }
 export [[]]; // No diagnostic after P2615R1 DR
-export [[example::attr]]; // expected-warning {{unknown attribute 'attr'}}
+export [[example::attr]]; // expected-error {{unknown attribute 'attr'}}
 
 // [...] shall not declare a name with internal linkage
 export static int a; // expected-error {{declaration of 'a' with internal 
linkage cannot be exported}}
diff --git a/clang/test/Lexer/cxx2a-spaceship.cpp 
b/clang/test/Lexer/cxx2a-spaceship.cpp
index 2163a0bf190f90..505f2f47c8ffb8 100644
--- a/clang/test/Lexer/cxx2a-spaceship.cpp
+++ b/clang/test/Lexer/cxx2a-spaceship.cpp
@@ -61,7 +61,7 @@ static_assert(__builtin_strcmp(b, "<=>") == 0);
 // CXX20: preprocess8: <=>=
 
 #define ID(x) x
-[[some_vendor::some_attribute( // expec

[clang] [lldb] [clang][RecordLayoutBuilder] Be stricter about inferring packed-ness in ExternalLayouts (PR #97443)

2024-12-23 Thread Michael Buch via cfe-commits

Michael137 wrote:

> FWIW, I came across another no_unique_address-related crash today:
> 
> ```
> $ cat a.cc
> struct S {
> private:
>   int i;
>   short s;
> };
> static_assert(sizeof(S) == 8);
> 
> struct T {
>   [[no_unique_address]] S s;
>   char c;
> };
> static_assert(sizeof(T) == 8);
> 
> T t;
> $ clang++ -c -o /tmp/a.out /tmp/a.cc -g
> $ lldb /tmp/a.out -o "expr t" -x
> (lldb) target create "/tmp/a.out"
> Current executable set to '/tmp/a.out' (x86_64).
> (lldb) expr t
> assertion failed at clang/lib/CodeGen/CGRecordLayoutBuilder.cpp:960 in void 
> (anonymous namespace)::CGRecordLowering::checkBitfieldClipping(bool) const: 
> M.Offset >= Tail && "Bitfield access unit is not clipped"
> ...
> ```
> 
> I was hoping this PR would fix it, but it doesn't appear to help.

Hmmm interesting, yea that looks more like something that 
https://github.com/llvm/llvm-project/pull/96422 should've addressed. Though 
this is a special case where the attribute is applied to a non-empty type. 
Would need to step through the `CGRecordLayoutBuilder` to see why Clang 
believes the offsets from DWARF aren't correct.

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


[clang] [SYCL] Allow neon attributes for ARM host (PR #94229)

2024-12-23 Thread Harald van Dijk via cfe-commits

https://github.com/hvdijk updated 
https://github.com/llvm/llvm-project/pull/94229

>From b1a53997e9378954da353ea1f0d8f03a8f19736f Mon Sep 17 00:00:00 2001
From: Harald van Dijk 
Date: Mon, 23 Dec 2024 13:19:56 +
Subject: [PATCH] [SYCL] Allow neon attributes for ARM host

We permit neon attributes in CUDA device code, but this permission was
only for CUDA device code. The same permission makes sense for SYCL
device code as well, especially now that neon attributes are used in
glibc headers.
---
 clang/lib/Sema/SemaType.cpp|  8 
 clang/test/SemaSYCL/neon-attrs.cpp | 10 ++
 2 files changed, 14 insertions(+), 4 deletions(-)
 create mode 100644 clang/test/SemaSYCL/neon-attrs.cpp

diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 83464c50b4b238..266f047b1a6836 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -8287,10 +8287,10 @@ static bool verifyValidIntegerConstantExpr(Sema &S, 
const ParsedAttr &Attr,
 /// match one of the standard Neon vector types.
 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
  Sema &S, VectorKind VecKind) {
-  bool IsTargetCUDAAndHostARM = false;
-  if (S.getLangOpts().CUDAIsDevice) {
+  bool IsTargetDeviceAndHostARM = false;
+  if (S.getLangOpts().CUDAIsDevice || S.getLangOpts().SYCLIsDevice) {
 const TargetInfo *AuxTI = S.getASTContext().getAuxTargetInfo();
-IsTargetCUDAAndHostARM =
+IsTargetDeviceAndHostARM =
 AuxTI && (AuxTI->getTriple().isAArch64() || 
AuxTI->getTriple().isARM());
   }
 
@@ -8327,7 +8327,7 @@ static void HandleNeonVectorTypeAttr(QualType &CurType, 
const ParsedAttr &Attr,
 
   // Only certain element types are supported for Neon vectors.
   if (!isPermittedNeonBaseType(CurType, VecKind, S) &&
-  !IsTargetCUDAAndHostARM) {
+  !IsTargetDeviceAndHostARM) {
 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
 Attr.setInvalid();
 return;
diff --git a/clang/test/SemaSYCL/neon-attrs.cpp 
b/clang/test/SemaSYCL/neon-attrs.cpp
new file mode 100644
index 00..fa9282e08947cf
--- /dev/null
+++ b/clang/test/SemaSYCL/neon-attrs.cpp
@@ -0,0 +1,10 @@
+// Host compilation on ARM with neon enabled (no errors expected).
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -target-feature +neon 
-fsyntax-only -verify=quiet %s
+
+// Device compilation on ARM (no errors expected).
+// RUN: %clang_cc1 -triple spirv64 -aux-triple aarch64-linux-gnu 
-fsycl-is-device -fsyntax-only -verify=quiet %s
+
+// quiet-no-diagnostics
+typedef __attribute__((neon_vector_type(4))) float float32x4_t;
+typedef unsigned char poly8_t;
+typedef __attribute__((neon_polyvector_type(8))) poly8_t poly8x8_t;

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


[clang] [SYCL] Allow neon attributes for ARM host (PR #94229)

2024-12-23 Thread Harald van Dijk via cfe-commits

hvdijk wrote:

The rebase apparently conflicted with #95224. In the test I added, I checked 
that I preserved the existing behaviour with `-target-feature -neon`, but that 
behaviour has since changed. Updated to remove that bit of the test.

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


[clang-tools-extra] [clang-tidy] fix incorrect argument names in documentation for ExtraArgs and ExtraArgsBefore (PR #120963)

2024-12-23 Thread via cfe-commits

https://github.com/float3 created 
https://github.com/llvm/llvm-project/pull/120963

None

>From 5f4415685c116e4b05759b46186c34e210b7b7a3 Mon Sep 17 00:00:00 2001
From: hill 
Date: Mon, 23 Dec 2024 14:21:46 +0100
Subject: [PATCH] [clang-tidy] fix incorrect argument names in documentation
 for ExtraArgs and ExtraArgsBefore

---
 clang-tools-extra/docs/clang-tidy/index.rst | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang-tools-extra/docs/clang-tidy/index.rst 
b/clang-tools-extra/docs/clang-tidy/index.rst
index f053e57e8d4c84..2d23ee57c681ec 100644
--- a/clang-tools-extra/docs/clang-tidy/index.rst
+++ b/clang-tools-extra/docs/clang-tidy/index.rst
@@ -282,8 +282,8 @@ An overview of all the command-line options:
globs can be specified as a list instead of 
a
string.
 ExcludeHeaderFilterRegex - Same as '--exclude-header-filter'.
-ExtraArgs- Same as '--extra-args'.
-ExtraArgsBefore  - Same as '--extra-args-before'.
+ExtraArgs- Same as '--extra-arg'.
+ExtraArgsBefore  - Same as '--extra-arg-before'.
 FormatStyle  - Same as '--format-style'.
 HeaderFileExtensions - File extensions to consider to determine if 
a
given diagnostic is located in a header 
file.

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


[clang-tools-extra] [clang-tidy] fix incorrect argument names in documentation for ExtraArgs and ExtraArgsBefore (PR #120963)

2024-12-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tools-extra

Author: hill (float3)


Changes



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


1 Files Affected:

- (modified) clang-tools-extra/docs/clang-tidy/index.rst (+2-2) 


``diff
diff --git a/clang-tools-extra/docs/clang-tidy/index.rst 
b/clang-tools-extra/docs/clang-tidy/index.rst
index f053e57e8d4c84..2d23ee57c681ec 100644
--- a/clang-tools-extra/docs/clang-tidy/index.rst
+++ b/clang-tools-extra/docs/clang-tidy/index.rst
@@ -282,8 +282,8 @@ An overview of all the command-line options:
globs can be specified as a list instead of 
a
string.
 ExcludeHeaderFilterRegex - Same as '--exclude-header-filter'.
-ExtraArgs- Same as '--extra-args'.
-ExtraArgsBefore  - Same as '--extra-args-before'.
+ExtraArgs- Same as '--extra-arg'.
+ExtraArgsBefore  - Same as '--extra-arg-before'.
 FormatStyle  - Same as '--format-style'.
 HeaderFileExtensions - File extensions to consider to determine if 
a
given diagnostic is located in a header 
file.

``




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


[clang-tools-extra] [clang-tidy] fix incorrect argument names in documentation for ExtraArgs and ExtraArgsBefore (PR #120963)

2024-12-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: hill (float3)


Changes



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


1 Files Affected:

- (modified) clang-tools-extra/docs/clang-tidy/index.rst (+2-2) 


``diff
diff --git a/clang-tools-extra/docs/clang-tidy/index.rst 
b/clang-tools-extra/docs/clang-tidy/index.rst
index f053e57e8d4c84..2d23ee57c681ec 100644
--- a/clang-tools-extra/docs/clang-tidy/index.rst
+++ b/clang-tools-extra/docs/clang-tidy/index.rst
@@ -282,8 +282,8 @@ An overview of all the command-line options:
globs can be specified as a list instead of 
a
string.
 ExcludeHeaderFilterRegex - Same as '--exclude-header-filter'.
-ExtraArgs- Same as '--extra-args'.
-ExtraArgsBefore  - Same as '--extra-args-before'.
+ExtraArgs- Same as '--extra-arg'.
+ExtraArgsBefore  - Same as '--extra-arg-before'.
 FormatStyle  - Same as '--format-style'.
 HeaderFileExtensions - File extensions to consider to determine if 
a
given diagnostic is located in a header 
file.

``




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


[clang] [analyzer] Don't assume third iteration in loops (PR #119388)

2024-12-23 Thread Donát Nagy via cfe-commits

NagyDonat wrote:

The logic that I added only affects the handling of the condition part of loop 
statements, so it has absolutely no effect on the handling of code that 
implements similar looping behavior with different language features. I added a 
testcase to document this (and as an example, show the behavior of `while (1) 
if (cond) break;` which is IMO the least different way of looping).

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


[clang] [Analyzer][CFG] Correctly handle rebuilt default arg and default init expression (PR #117437)

2024-12-23 Thread via cfe-commits

yronglin wrote:

friendly ping~

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


[clang] [analyzer] Don't assume third iteration in loops (PR #119388)

2024-12-23 Thread Donát Nagy via cfe-commits

https://github.com/NagyDonat updated 
https://github.com/llvm/llvm-project/pull/119388

From cb9b5ef4d8b0ed8e67276947525d327c547424fc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Don=C3=A1t=20Nagy?= 
Date: Thu, 28 Nov 2024 17:22:58 +0100
Subject: [PATCH 1/7] [analyzer] Don't assume third iteration in loops

This commit ensures that if the loop condition is opaque (the analyzer
cannot determine whether it's true or false) and there were at least two
iterations, then the analyzer doesn't make the unjustified assumption
that it can enter yet another iteration.

Note that the presence of a loop suggests that the developer thought
that two iterations can happen (otherwise an `if` would've been
sufficient), but it does not imply that the developer expected three or
four iterations -- and in fact there are many false positives where a
loop iterates over a two-element (or three-element) data structure, but
the analyzer cannot understand the loop condition and blindly assumes
that there may be three or more iterations. (In particular, analyzing
the FFMPEG project produces 100+ such false positives.)

Moreover, this provides some performance improvements in the sense that
the analyzer won't waste time on traversing the execution paths with 3
or 4 iterations in a loop (which are very similar to the paths with 2
iterations) and therefore will be able to traverse more branches
elsewhere on the `ExplodedGraph`.

This logic is disabled if the user enables the widen-loops analyzer
option (which is disabled by default), because the "simulate one final
iteration after the invalidation" execution path would be suppressed by
the "exit the loop if the loop condition is opaque and there were at
least two iterations" logic. If we want to support loop widening, we
would need to create a follow-up commit which ensures that it "plays
nicely" with this logic.
---
 .../Core/PathSensitive/CoreEngine.h   |  8 +++
 .../Core/PathSensitive/ExprEngine.h   | 18 +++---
 clang/lib/StaticAnalyzer/Core/CoreEngine.cpp  | 27 -
 clang/lib/StaticAnalyzer/Core/ExprEngine.cpp  | 55 ---
 clang/test/Analysis/loop-unrolling.cpp| 35 +++-
 clang/test/Analysis/misc-ps-region-store.m| 31 ---
 6 files changed, 133 insertions(+), 41 deletions(-)

diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
index a6d05a3ac67b4e..80b79fd4e928f8 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
@@ -126,6 +126,14 @@ class CoreEngine {
   ExplodedNode *generateCallExitBeginNode(ExplodedNode *N,
   const ReturnStmt *RS);
 
+  /// Helper function called by `HandleBranch()`. If the currently handled
+  /// branch corresponds to a loop, this returns the number of already
+  /// completed iterations in that loop, otherwise the return value is
+  /// `std::nullopt`. Note that this counts _all_ earlier iterations, including
+  /// ones that were performed within an earlier iteration of an outer loop.
+  std::optional getCompletedIterationCount(const CFGBlock *B,
+ ExplodedNode *Pred) const;
+
 public:
   /// Construct a CoreEngine object to analyze the provided CFG.
   CoreEngine(ExprEngine &exprengine,
diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
index 8c7493e27fcaa6..20c446e33ef9a5 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -321,14 +321,14 @@ class ExprEngine {
NodeBuilderWithSinks &nodeBuilder,
ExplodedNode *Pred);
 
-  /// ProcessBranch - Called by CoreEngine.  Used to generate successor
-  ///  nodes by processing the 'effects' of a branch condition.
-  void processBranch(const Stmt *Condition,
- NodeBuilderContext& BuilderCtx,
- ExplodedNode *Pred,
- ExplodedNodeSet &Dst,
- const CFGBlock *DstT,
- const CFGBlock *DstF);
+  /// ProcessBranch - Called by CoreEngine. Used to generate successor nodes by
+  /// processing the 'effects' of a branch condition. If the branch condition
+  /// is a loop condition, IterationsCompletedInLoop is the number of completed
+  /// iterations (otherwise it's std::nullopt).
+  void processBranch(const Stmt *Condition, NodeBuilderContext &BuilderCtx,
+ ExplodedNode *Pred, ExplodedNodeSet &Dst,
+ const CFGBlock *DstT, const CFGBlock *DstF,
+ std::optional IterationsCompletedInLoop);
 
   /// Called by CoreEngine.
   /// Used to generate successor nodes for temp

[clang] [analyzer] Simplify CallEvent castArgToParamTypeIfNeeded (PR #120981)

2024-12-23 Thread Balazs Benics via cfe-commits

https://github.com/steakhal created 
https://github.com/llvm/llvm-project/pull/120981

I noticed recently that this code (that I wrote xD) uses the 
`getRuntimeDefinition()` which isn't quite necessary for the simple task this 
function was designed for.

Why would it be better not using this API here?
I'm experimenting with improving how virtual functions are inlined, where 
depending on our ability of deducing the dynamic type of the object we may end 
up with inaccurate type information. Such inaccuracy would mean that we may 
have multiple runtime definitions. After that, this code would become ambiguous.

To resolve this, I decided to refactor this and use a simpler - but equivalent 
approach.

>From 08e384f0827c023bd8e0bf755ce6ea73e6ac6fa2 Mon Sep 17 00:00:00 2001
From: Balazs Benics 
Date: Mon, 23 Dec 2024 17:38:11 +0100
Subject: [PATCH] [analyzer] Simplify CallEvent castArgToParamTypeIfNeeded

I noticed recently that this code (that I wrote xD) uses the
`getRuntimeDefinition()` which isn't quite necessary for the simple task
this function was designed for.

Why would it be better not using this API here?
I'm experimenting with improving how virtual functions are inlined,
where depending on our ability of deducing the dynamic type of the
object we may end up with inaccurate type information.
Such inaccuracy would mean that we may have multiple runtime
definitions. After that, this code would become ambiguous.

To resolve this, I decided to refactor this and use a simpler - but
equivalent approach.
---
 clang/lib/StaticAnalyzer/Core/CallEvent.cpp | 14 +++---
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Core/CallEvent.cpp 
b/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
index 0fdef7487b9814..bb4a39f68280cd 100644
--- a/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -435,27 +435,27 @@ static SVal processArgument(SVal Value, const Expr 
*ArgumentExpr,
 /// runtime definition don't match in terms of argument and parameter count.
 static SVal castArgToParamTypeIfNeeded(const CallEvent &Call, unsigned ArgIdx,
SVal ArgVal, SValBuilder &SVB) {
-  const FunctionDecl *RTDecl =
-  Call.getRuntimeDefinition().getDecl()->getAsFunction();
   const auto *CallExprDecl = dyn_cast_or_null(Call.getDecl());
-
-  if (!RTDecl || !CallExprDecl)
+  if (!CallExprDecl)
 return ArgVal;
 
+  const FunctionDecl *Definition = CallExprDecl;
+  Definition->hasBody(Definition);
+
   // The function decl of the Call (in the AST) will not have any parameter
   // declarations, if it was 'only' declared without a prototype. However, the
   // engine will find the appropriate runtime definition - basically a
   // redeclaration, which has a function body (and a function prototype).
-  if (CallExprDecl->hasPrototype() || !RTDecl->hasPrototype())
+  if (CallExprDecl->hasPrototype() || !Definition->hasPrototype())
 return ArgVal;
 
   // Only do this cast if the number arguments at the callsite matches with
   // the parameters at the runtime definition.
-  if (Call.getNumArgs() != RTDecl->getNumParams())
+  if (Call.getNumArgs() != Definition->getNumParams())
 return UnknownVal();
 
   const Expr *ArgExpr = Call.getArgExpr(ArgIdx);
-  const ParmVarDecl *Param = RTDecl->getParamDecl(ArgIdx);
+  const ParmVarDecl *Param = Definition->getParamDecl(ArgIdx);
   return SVB.evalCast(ArgVal, Param->getType(), ArgExpr->getType());
 }
 

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


[clang] [analyzer] Simplify CallEvent castArgToParamTypeIfNeeded (PR #120981)

2024-12-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Balazs Benics (steakhal)


Changes

I noticed recently that this code (that I wrote xD) uses the 
`getRuntimeDefinition()` which isn't quite necessary for the simple task this 
function was designed for.

Why would it be better not using this API here?
I'm experimenting with improving how virtual functions are inlined, where 
depending on our ability of deducing the dynamic type of the object we may end 
up with inaccurate type information. Such inaccuracy would mean that we may 
have multiple runtime definitions. After that, this code would become ambiguous.

To resolve this, I decided to refactor this and use a simpler - but equivalent 
approach.

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


1 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Core/CallEvent.cpp (+7-7) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Core/CallEvent.cpp 
b/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
index 0fdef7487b9814..bb4a39f68280cd 100644
--- a/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -435,27 +435,27 @@ static SVal processArgument(SVal Value, const Expr 
*ArgumentExpr,
 /// runtime definition don't match in terms of argument and parameter count.
 static SVal castArgToParamTypeIfNeeded(const CallEvent &Call, unsigned ArgIdx,
SVal ArgVal, SValBuilder &SVB) {
-  const FunctionDecl *RTDecl =
-  Call.getRuntimeDefinition().getDecl()->getAsFunction();
   const auto *CallExprDecl = dyn_cast_or_null(Call.getDecl());
-
-  if (!RTDecl || !CallExprDecl)
+  if (!CallExprDecl)
 return ArgVal;
 
+  const FunctionDecl *Definition = CallExprDecl;
+  Definition->hasBody(Definition);
+
   // The function decl of the Call (in the AST) will not have any parameter
   // declarations, if it was 'only' declared without a prototype. However, the
   // engine will find the appropriate runtime definition - basically a
   // redeclaration, which has a function body (and a function prototype).
-  if (CallExprDecl->hasPrototype() || !RTDecl->hasPrototype())
+  if (CallExprDecl->hasPrototype() || !Definition->hasPrototype())
 return ArgVal;
 
   // Only do this cast if the number arguments at the callsite matches with
   // the parameters at the runtime definition.
-  if (Call.getNumArgs() != RTDecl->getNumParams())
+  if (Call.getNumArgs() != Definition->getNumParams())
 return UnknownVal();
 
   const Expr *ArgExpr = Call.getArgExpr(ArgIdx);
-  const ParmVarDecl *Param = RTDecl->getParamDecl(ArgIdx);
+  const ParmVarDecl *Param = Definition->getParamDecl(ArgIdx);
   return SVB.evalCast(ArgVal, Param->getType(), ArgExpr->getType());
 }
 

``




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


[clang] [llvm] [mlir] [NVPTX] Switch front-ends and tests to ptx_kernel cc (PR #120806)

2024-12-23 Thread Alex MacLean via cfe-commits


@@ -556,19 +556,16 @@ llvm.func @kernel_func() attributes {nvvm.kernel} {
   llvm.return
 }
 
-// CHECK: !nvvm.annotations =
-// CHECK-NOT: {ptr @nvvm_special_regs, !"kernel", i32 1}
-// CHECK: {ptr @kernel_func, !"kernel", i32 1}
+// CHECK: ptx_kernel void @kernel_func

AlexMaclean wrote:

This change does not remove support for specifying a kernel via the metadata. 
It simply updates frontends and tests to use a different one of the two already 
supported methods for marking kernels. Long term I hope to remove the support 
for metadata, so downstream users should move the calling-convention, but this 
change does not yet force that. 

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


[clang] [Clang][Sema] Process warnings conditionally (PR #120591)

2024-12-23 Thread via cfe-commits

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


[clang] [Clang][Sema] Process warnings conditionally (PR #120591)

2024-12-23 Thread Dmitry Chestnykh via cfe-commits

https://github.com/chestnykh updated 
https://github.com/llvm/llvm-project/pull/120591

>From 9a0d5d44f70477403a33d2feb3f5518b0d078a66 Mon Sep 17 00:00:00 2001
From: Dmitry Chestnykh 
Date: Thu, 19 Dec 2024 18:35:35 +0300
Subject: [PATCH 1/3] [Clang][Sema] Process warnings conditionally

There are a few functions that emit warnings
related to positional arguments in format strings.
These functions use `getLocationOfByte()` which has O(n)
complexity and may lead to silent hang of compilation in some cases.
But such warnings is not widely used and actually don't emit
if user didn't pass the appropriate `-W...` flag, so
if the flag is not passed dont make the call
to `EmitFormatDiagnostic` for such diags.

Fix #120462
---
 clang/lib/Sema/SemaChecking.cpp | 30 ++
 1 file changed, 18 insertions(+), 12 deletions(-)

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index e703a62ff9cf18..f5c42eba51c252 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -6591,27 +6591,33 @@ void 
CheckFormatHandler::HandleNonStandardConversionSpecifier(
 
 void CheckFormatHandler::HandlePosition(const char *startPos,
 unsigned posLen) {
-  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
-   getLocationOfByte(startPos),
-   /*IsStringLocation*/true,
-   getSpecifierRange(startPos, posLen));
+  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_non_standard_positional_arg, 
SourceLocation())) {
+
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
+getLocationOfByte(startPos),
+/*IsStringLocation*/true,
+getSpecifierRange(startPos, posLen));
+  }
 }
 
 void CheckFormatHandler::HandleInvalidPosition(
 const char *startSpecifier, unsigned specifierLen,
 analyze_format_string::PositionContext p) {
-  EmitFormatDiagnostic(
-  S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
-  getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
-  getSpecifierRange(startSpecifier, specifierLen));
+  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_invalid_positional_specifier, 
SourceLocation())) {
+EmitFormatDiagnostic(
+S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
+getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
+getSpecifierRange(startSpecifier, specifierLen));
+  }
 }
 
 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
 unsigned posLen) {
-  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
-   getLocationOfByte(startPos),
-   /*IsStringLocation*/true,
-   getSpecifierRange(startPos, posLen));
+  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier, 
SourceLocation())) {
+EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
+getLocationOfByte(startPos),
+/*IsStringLocation*/true,
+getSpecifierRange(startPos, posLen));
+  }
 }
 
 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {

>From 7928effc17882139e548adbfe88a52d56f844d3b Mon Sep 17 00:00:00 2001
From: Dmitry Chestnykh 
Date: Thu, 19 Dec 2024 18:50:04 +0300
Subject: [PATCH 2/3] [clang][Sema] Fix code style

---
 clang/lib/Sema/SemaChecking.cpp | 21 -
 1 file changed, 12 insertions(+), 9 deletions(-)

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index f5c42eba51c252..9a05181405cde5 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -6591,18 +6591,20 @@ void 
CheckFormatHandler::HandleNonStandardConversionSpecifier(
 
 void CheckFormatHandler::HandlePosition(const char *startPos,
 unsigned posLen) {
-  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_non_standard_positional_arg, 
SourceLocation())) {
+  if (!S.getDiagnostics().isIgnored(
+  diag::warn_format_non_standard_positional_arg, SourceLocation())) {
 
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
-getLocationOfByte(startPos),
-/*IsStringLocation*/true,
-getSpecifierRange(startPos, posLen));
+ getLocationOfByte(startPos),
+ /*IsStringLocation*/ true,
+ getSpecifierRange(startPos, posLen));
   }
 }
 
 void CheckFormatHandler::HandleInvalidPosition(
 const char *startSpecifier, unsi

[clang] [llvm] [mlir] [NVPTX] Switch front-ends and tests to ptx_kernel cc (PR #120806)

2024-12-23 Thread Durgadoss R via cfe-commits


@@ -556,19 +556,16 @@ llvm.func @kernel_func() attributes {nvvm.kernel} {
   llvm.return
 }
 
-// CHECK: !nvvm.annotations =
-// CHECK-NOT: {ptr @nvvm_special_regs, !"kernel", i32 1}
-// CHECK: {ptr @kernel_func, !"kernel", i32 1}
+// CHECK: ptx_kernel void @kernel_func

durga4github wrote:

ok, thanks for clarifying!

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


[clang] [Clang][Sema] Process warnings conditionally (PR #120591)

2024-12-23 Thread Dmitry Chestnykh via cfe-commits


@@ -6591,27 +6591,36 @@ void 
CheckFormatHandler::HandleNonStandardConversionSpecifier(
 
 void CheckFormatHandler::HandlePosition(const char *startPos,
 unsigned posLen) {
-  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
-   getLocationOfByte(startPos),
-   /*IsStringLocation*/true,
-   getSpecifierRange(startPos, posLen));
+  if (!S.getDiagnostics().isIgnored(
+  diag::warn_format_non_standard_positional_arg, SourceLocation())) {
+
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
+ getLocationOfByte(startPos),
+ /*IsStringLocation*/ true,
+ getSpecifierRange(startPos, posLen));
+  }

chestnykh wrote:

Fixed

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


[clang] [Clang][Sema] Process warnings conditionally (PR #120591)

2024-12-23 Thread Dmitry Chestnykh via cfe-commits


@@ -6591,27 +6591,36 @@ void 
CheckFormatHandler::HandleNonStandardConversionSpecifier(
 
 void CheckFormatHandler::HandlePosition(const char *startPos,
 unsigned posLen) {
-  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
-   getLocationOfByte(startPos),
-   /*IsStringLocation*/true,
-   getSpecifierRange(startPos, posLen));
+  if (!S.getDiagnostics().isIgnored(
+  diag::warn_format_non_standard_positional_arg, SourceLocation())) {
+
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
+ getLocationOfByte(startPos),
+ /*IsStringLocation*/ true,
+ getSpecifierRange(startPos, posLen));
+  }
 }
 
 void CheckFormatHandler::HandleInvalidPosition(
 const char *startSpecifier, unsigned specifierLen,
 analyze_format_string::PositionContext p) {
-  EmitFormatDiagnostic(
-  S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
-  getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
-  getSpecifierRange(startSpecifier, specifierLen));
+  if (!S.getDiagnostics().isIgnored(
+  diag::warn_format_invalid_positional_specifier, SourceLocation())) {
+EmitFormatDiagnostic(
+S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
+getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
+getSpecifierRange(startSpecifier, specifierLen));
+  }

chestnykh wrote:

Fixed

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


[clang] [Clang][Sema] Process warnings conditionally (PR #120591)

2024-12-23 Thread Dmitry Chestnykh via cfe-commits


@@ -6591,27 +6591,36 @@ void 
CheckFormatHandler::HandleNonStandardConversionSpecifier(
 
 void CheckFormatHandler::HandlePosition(const char *startPos,
 unsigned posLen) {
-  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
-   getLocationOfByte(startPos),
-   /*IsStringLocation*/true,
-   getSpecifierRange(startPos, posLen));
+  if (!S.getDiagnostics().isIgnored(
+  diag::warn_format_non_standard_positional_arg, SourceLocation())) {
+
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
+ getLocationOfByte(startPos),
+ /*IsStringLocation*/ true,
+ getSpecifierRange(startPos, posLen));
+  }
 }
 
 void CheckFormatHandler::HandleInvalidPosition(
 const char *startSpecifier, unsigned specifierLen,
 analyze_format_string::PositionContext p) {
-  EmitFormatDiagnostic(
-  S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
-  getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
-  getSpecifierRange(startSpecifier, specifierLen));
+  if (!S.getDiagnostics().isIgnored(
+  diag::warn_format_invalid_positional_specifier, SourceLocation())) {
+EmitFormatDiagnostic(
+S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
+getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
+getSpecifierRange(startSpecifier, specifierLen));
+  }
 }
 
 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
 unsigned posLen) {
-  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
-   getLocationOfByte(startPos),
-   /*IsStringLocation*/true,
-   getSpecifierRange(startPos, posLen));
+  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
+SourceLocation())) {
+EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
+ getLocationOfByte(startPos),
+ /*IsStringLocation*/ true,
+ getSpecifierRange(startPos, posLen));
+  }

chestnykh wrote:

Fixed

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


[clang] [Clang] Prevent assignment to captured structured bindings inside immutable lambda (PR #120849)

2024-12-23 Thread via cfe-commits

https://github.com/cor3ntin commented:

I have a few nits but generally looks good, thanks for the fix

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


[clang] [Clang] Prevent assignment to captured structured bindings inside immutable lambda (PR #120849)

2024-12-23 Thread via cfe-commits

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


[clang] [Clang] Prevent assignment to captured structured bindings inside immutable lambda (PR #120849)

2024-12-23 Thread via cfe-commits


@@ -13299,7 +13293,18 @@ static NonConstCaptureKind 
isReferenceToNonConstCapture(Sema &S, Expr *E) {
 
   // The declaration must be a variable which is not declared 'const'.
   VarDecl *var = dyn_cast(DRE->getDecl());
-  if (!var) return NCCK_None;
+  if (!var) {
+// Bindings also can be captured by lambda in C++
+BindingDecl *binding = dyn_cast(DRE->getDecl());
+if (!binding || binding->getType().isConstQualified())
+  return NCCK_None;
+
+assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
+assert(!isa(binding->getDeclContext()));

cor3ntin wrote:

I would prefer you move the whole code _before_ the cast to Var (L13293)
Alternatively, first cast to ValueDecl, deal with the common const-qualified 
case, then cast to Var

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


[clang] [Clang] Prevent assignment to captured structured bindings inside immutable lambda (PR #120849)

2024-12-23 Thread via cfe-commits


@@ -13299,7 +13293,18 @@ static NonConstCaptureKind 
isReferenceToNonConstCapture(Sema &S, Expr *E) {
 
   // The declaration must be a variable which is not declared 'const'.
   VarDecl *var = dyn_cast(DRE->getDecl());
-  if (!var) return NCCK_None;
+  if (!var) {
+// Bindings also can be captured by lambda in C++
+BindingDecl *binding = dyn_cast(DRE->getDecl());

cor3ntin wrote:

```suggestion
BindingDecl *Binding = dyn_cast(DRE->getDecl());
```

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


[clang] [Clang][Sema] Process warnings conditionally (PR #120591)

2024-12-23 Thread via cfe-commits

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

Thanks!

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


[clang] 99dddef - [Clang][Sema] Process warnings conditionally (#120591)

2024-12-23 Thread via cfe-commits

Author: Dmitry Chestnykh
Date: 2024-12-23T20:02:28+03:00
New Revision: 99dddef340e566e9d303010f1219f7d7d6d37a11

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

LOG: [Clang][Sema] Process warnings conditionally (#120591)

There are a few functions that emit warnings related to positional
arguments in format strings. These functions use `getLocationOfByte()`
which has O(n) complexity and may lead to silent hang of compilation in
some cases. But such warnings is not widely used and actually don't emit
if user didn't pass the appropriate `-W...` flag, so if the flag is not
passed dont make the call to `EmitFormatDiagnostic` for such diags.

Fix #120462

Added: 


Modified: 
clang/lib/Sema/SemaChecking.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index e703a62ff9cf18..ce846ae88c38b4 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -6591,27 +6591,33 @@ void 
CheckFormatHandler::HandleNonStandardConversionSpecifier(
 
 void CheckFormatHandler::HandlePosition(const char *startPos,
 unsigned posLen) {
-  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
-   getLocationOfByte(startPos),
-   /*IsStringLocation*/true,
-   getSpecifierRange(startPos, posLen));
+  if (!S.getDiagnostics().isIgnored(
+  diag::warn_format_non_standard_positional_arg, SourceLocation()))
+
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
+ getLocationOfByte(startPos),
+ /*IsStringLocation*/ true,
+ getSpecifierRange(startPos, posLen));
 }
 
 void CheckFormatHandler::HandleInvalidPosition(
 const char *startSpecifier, unsigned specifierLen,
 analyze_format_string::PositionContext p) {
-  EmitFormatDiagnostic(
-  S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
-  getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
-  getSpecifierRange(startSpecifier, specifierLen));
+  if (!S.getDiagnostics().isIgnored(
+  diag::warn_format_invalid_positional_specifier, SourceLocation()))
+EmitFormatDiagnostic(
+S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
+getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
+getSpecifierRange(startSpecifier, specifierLen));
 }
 
 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
 unsigned posLen) {
-  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
-   getLocationOfByte(startPos),
-   /*IsStringLocation*/true,
-   getSpecifierRange(startPos, posLen));
+  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
+SourceLocation()))
+EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
+ getLocationOfByte(startPos),
+ /*IsStringLocation*/ true,
+ getSpecifierRange(startPos, posLen));
 }
 
 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {



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


[clang] [Clang][Sema] Process warnings conditionally (PR #120591)

2024-12-23 Thread Dmitry Chestnykh via cfe-commits

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


[clang] [llvm] [mlir] [NVPTX] Switch front-ends and tests to ptx_kernel cc (PR #120806)

2024-12-23 Thread Alex MacLean via cfe-commits

AlexMaclean wrote:

> In MLIR, we also have other NVVM metadata such as `reqntid` and `maxntid`, 
> among others. What is the plan for these? Will they remain as metadata, or 
> will they be expressed differently?

Eventually, I hope to migrate all !nvvm.annotations, including `reqntid` and 
`maxntid`, to a more modern mechanism such as attributes, or at least metadata 
attached directly to the function/GV. !nvvm.annotations was added around llvm 3 
when target-specific attributes were not yet present. 

> Could you please elaborate on the compile-time improvements?

Auto-upgrading kernel metadata and no longer traversing !nvvm.annotations lead 
to around a 2% improvement in compile time for several cases in nvcc. This 
change alone won't have the same impact, since we still traverse the metadata 
for functions that do not have the `ptx_kernel` cc but it at least lets up bail 
out early some of the time and lays the foundation for bigger improvements.

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


[clang-tools-extra] [clang-tidy] fix incorrect argument names in documentation for ExtraArgs and ExtraArgsBefore (PR #120963)

2024-12-23 Thread Nicolas van Kempen via cfe-commits

nicovank wrote:

Sync with 
[ClangTidyMain.cpp](https://github.com/llvm/llvm-project/blob/d36836de0183b9b1939cc679d153e3b313e55c76/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp#L57-L58)?

https://github.com/llvm/llvm-project/blob/d36836de0183b9b1939cc679d153e3b313e55c76/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp#L57-L58

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


[clang] [clang][Sema] Move computing enum width and type to a separate function (PR #120965)

2024-12-23 Thread Ilia Kuklin via cfe-commits

https://github.com/kuilpd updated 
https://github.com/llvm/llvm-project/pull/120965

>From ab8dcaef120233d0145508aaa4bf45eec22cadf1 Mon Sep 17 00:00:00 2001
From: Ilia Kuklin 
Date: Mon, 23 Dec 2024 17:49:32 +0500
Subject: [PATCH 1/2] [clang][Sema] Move calculating enum width and type to a
 separate function

---
 clang/include/clang/Sema/Sema.h |   7 ++
 clang/lib/Sema/SemaDecl.cpp | 158 ++--
 2 files changed, 94 insertions(+), 71 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 5ee7ea48cc983c..51a1721fb74f01 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3987,6 +3987,13 @@ class Sema final : public SemaBase {
   SourceLocation IdLoc, IdentifierInfo *Id,
   const ParsedAttributesView &Attrs,
   SourceLocation EqualLoc, Expr *Val);
+
+  bool ComputeBestEnumProperties(ASTContext &Context, EnumDecl *Enum,
+ bool isCpp, bool isPacked,
+ unsigned NumNegativeBits,
+ unsigned NumPositiveBits, unsigned &BestWidth,
+ QualType &BestType,
+ QualType &BestPromotionType);
   void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  Decl *EnumDecl, ArrayRef Elements, Scope *S,
  const ParsedAttributesView &Attr);
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 4001c4d263f1d2..79cbfe3116b26b 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -20008,6 +20008,87 @@ bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const 
llvm::APInt &Val,
   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
 }
 
+bool Sema::ComputeBestEnumProperties(ASTContext &Context, EnumDecl *Enum,
+ bool is_cpp, bool isPacked,
+ unsigned NumNegativeBits,
+ unsigned NumPositiveBits,
+ unsigned &BestWidth, QualType &BestType,
+ QualType &BestPromotionType) {
+  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
+  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
+  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
+  bool enum_too_large = false;
+  if (NumNegativeBits) {
+// If there is a negative value, figure out the smallest integer type (of
+// int/long/longlong) that fits.
+// If it's packed, check also if it fits a char or a short.
+if (isPacked && NumNegativeBits <= CharWidth &&
+NumPositiveBits < CharWidth) {
+  BestType = Context.SignedCharTy;
+  BestWidth = CharWidth;
+} else if (isPacked && NumNegativeBits <= ShortWidth &&
+   NumPositiveBits < ShortWidth) {
+  BestType = Context.ShortTy;
+  BestWidth = ShortWidth;
+} else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
+  BestType = Context.IntTy;
+  BestWidth = IntWidth;
+} else {
+  BestWidth = Context.getTargetInfo().getLongWidth();
+
+  if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
+BestType = Context.LongTy;
+  } else {
+BestWidth = Context.getTargetInfo().getLongLongWidth();
+
+if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
+  enum_too_large = true;
+BestType = Context.LongLongTy;
+  }
+}
+BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
+  } else {
+// If there is no negative value, figure out the smallest type that fits
+// all of the enumerator values.
+// If it's packed, check also if it fits a char or a short.
+if (isPacked && NumPositiveBits <= CharWidth) {
+  BestType = Context.UnsignedCharTy;
+  BestPromotionType = Context.IntTy;
+  BestWidth = CharWidth;
+} else if (isPacked && NumPositiveBits <= ShortWidth) {
+  BestType = Context.UnsignedShortTy;
+  BestPromotionType = Context.IntTy;
+  BestWidth = ShortWidth;
+} else if (NumPositiveBits <= IntWidth) {
+  BestType = Context.UnsignedIntTy;
+  BestWidth = IntWidth;
+  BestPromotionType = (NumPositiveBits == BestWidth || !is_cpp)
+  ? Context.UnsignedIntTy
+  : Context.IntTy;
+} else if (NumPositiveBits <=
+   (BestWidth = Context.getTargetInfo().getLongWidth())) {
+  BestType = Context.UnsignedLongTy;
+  BestPromotionType = (NumPositiveBits == BestWidth || !is_cpp)
+  ? Context.UnsignedLongTy
+  : Context.LongTy;
+} else {
+  BestWidth = Context.getTargetInfo().getLongLongWidth();
+  if (NumPositiveBits > BestWidth) {
+// This ca

[clang] [NFC][Driver] Simplify linking of ubsan_standalone_cxx (PR #120938)

2024-12-23 Thread Kirill Stoimenov via cfe-commits

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


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


[clang] [clang][Sema] Move computing enum width and type to a separate function (PR #120965)

2024-12-23 Thread Ilia Kuklin via cfe-commits

https://github.com/kuilpd updated 
https://github.com/llvm/llvm-project/pull/120965

>From ab8dcaef120233d0145508aaa4bf45eec22cadf1 Mon Sep 17 00:00:00 2001
From: Ilia Kuklin 
Date: Mon, 23 Dec 2024 17:49:32 +0500
Subject: [PATCH 1/2] [clang][Sema] Move calculating enum width and type to a
 separate function

---
 clang/include/clang/Sema/Sema.h |   7 ++
 clang/lib/Sema/SemaDecl.cpp | 158 ++--
 2 files changed, 94 insertions(+), 71 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 5ee7ea48cc983c..51a1721fb74f01 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3987,6 +3987,13 @@ class Sema final : public SemaBase {
   SourceLocation IdLoc, IdentifierInfo *Id,
   const ParsedAttributesView &Attrs,
   SourceLocation EqualLoc, Expr *Val);
+
+  bool ComputeBestEnumProperties(ASTContext &Context, EnumDecl *Enum,
+ bool isCpp, bool isPacked,
+ unsigned NumNegativeBits,
+ unsigned NumPositiveBits, unsigned &BestWidth,
+ QualType &BestType,
+ QualType &BestPromotionType);
   void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  Decl *EnumDecl, ArrayRef Elements, Scope *S,
  const ParsedAttributesView &Attr);
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 4001c4d263f1d2..79cbfe3116b26b 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -20008,6 +20008,87 @@ bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const 
llvm::APInt &Val,
   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
 }
 
+bool Sema::ComputeBestEnumProperties(ASTContext &Context, EnumDecl *Enum,
+ bool is_cpp, bool isPacked,
+ unsigned NumNegativeBits,
+ unsigned NumPositiveBits,
+ unsigned &BestWidth, QualType &BestType,
+ QualType &BestPromotionType) {
+  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
+  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
+  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
+  bool enum_too_large = false;
+  if (NumNegativeBits) {
+// If there is a negative value, figure out the smallest integer type (of
+// int/long/longlong) that fits.
+// If it's packed, check also if it fits a char or a short.
+if (isPacked && NumNegativeBits <= CharWidth &&
+NumPositiveBits < CharWidth) {
+  BestType = Context.SignedCharTy;
+  BestWidth = CharWidth;
+} else if (isPacked && NumNegativeBits <= ShortWidth &&
+   NumPositiveBits < ShortWidth) {
+  BestType = Context.ShortTy;
+  BestWidth = ShortWidth;
+} else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
+  BestType = Context.IntTy;
+  BestWidth = IntWidth;
+} else {
+  BestWidth = Context.getTargetInfo().getLongWidth();
+
+  if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
+BestType = Context.LongTy;
+  } else {
+BestWidth = Context.getTargetInfo().getLongLongWidth();
+
+if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
+  enum_too_large = true;
+BestType = Context.LongLongTy;
+  }
+}
+BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
+  } else {
+// If there is no negative value, figure out the smallest type that fits
+// all of the enumerator values.
+// If it's packed, check also if it fits a char or a short.
+if (isPacked && NumPositiveBits <= CharWidth) {
+  BestType = Context.UnsignedCharTy;
+  BestPromotionType = Context.IntTy;
+  BestWidth = CharWidth;
+} else if (isPacked && NumPositiveBits <= ShortWidth) {
+  BestType = Context.UnsignedShortTy;
+  BestPromotionType = Context.IntTy;
+  BestWidth = ShortWidth;
+} else if (NumPositiveBits <= IntWidth) {
+  BestType = Context.UnsignedIntTy;
+  BestWidth = IntWidth;
+  BestPromotionType = (NumPositiveBits == BestWidth || !is_cpp)
+  ? Context.UnsignedIntTy
+  : Context.IntTy;
+} else if (NumPositiveBits <=
+   (BestWidth = Context.getTargetInfo().getLongWidth())) {
+  BestType = Context.UnsignedLongTy;
+  BestPromotionType = (NumPositiveBits == BestWidth || !is_cpp)
+  ? Context.UnsignedLongTy
+  : Context.LongTy;
+} else {
+  BestWidth = Context.getTargetInfo().getLongLongWidth();
+  if (NumPositiveBits > BestWidth) {
+// This ca

[clang] [clang][Sema] Move computing enum width and type to a separate function (PR #120965)

2024-12-23 Thread Ilia Kuklin via cfe-commits


@@ -20008,6 +20008,87 @@ bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const 
llvm::APInt &Val,
   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
 }
 
+bool Sema::ComputeBestEnumProperties(ASTContext &Context, EnumDecl *Enum,
+ bool is_cpp, bool isPacked,

kuilpd wrote:

Removed `Enum`, `is_cpp` and `BestWidth`, but unfortunately when calling this 
function from LLDB, `Context` in Sema is empty, so it has to be passed as an 
argument.

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


  1   2   >