[clang] 4b4aaf1 - [clang][Interp] Fix non-initializing CK_VectorSplat casts

2024-06-18 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-06-18T09:05:28+02:00
New Revision: 4b4aaf1e792367b4ce0e24966a7d21e2a83bb979

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

LOG: [clang][Interp] Fix non-initializing CK_VectorSplat casts

Create the usual local variable to fill.

Added: 
clang/test/AST/Interp/hlsl.hlsl

Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index b5e27bfb1a6db..0964ac046e630 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -488,14 +488,25 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
 if (DiscardResult)
   return this->discard(SubExpr);
 
-assert(Initializing); // FIXME: Not always correct.
+if (!Initializing) {
+  std::optional LocalIndex = allocateLocal(CE);
+  if (!LocalIndex)
+return false;
+  if (!this->emitGetPtrLocal(*LocalIndex, CE))
+return false;
+}
+
 const auto *VT = CE->getType()->getAs();
-PrimType ElemT = classifyPrim(SubExpr);
+PrimType ElemT = classifyPrim(SubExpr->getType());
 unsigned ElemOffset = allocateLocalPrimitive(
 SubExpr, ElemT, /*IsConst=*/true, /*IsExtended=*/false);
 
+// Prepare a local variable for the scalar value.
 if (!this->visit(SubExpr))
   return false;
+if (classifyPrim(SubExpr) == PT_Ptr && !this->emitLoadPop(ElemT, CE))
+  return false;
+
 if (!this->emitSetLocal(ElemT, ElemOffset, CE))
   return false;
 
@@ -2778,6 +2789,7 @@ template 
 bool ByteCodeExprGen::VisitExtVectorElementExpr(
 const ExtVectorElementExpr *E) {
   const Expr *Base = E->getBase();
+  assert(Base->getType()->isVectorType());
 
   SmallVector Indices;
   E->getEncodedElementAccess(Indices);

diff  --git a/clang/test/AST/Interp/hlsl.hlsl b/clang/test/AST/Interp/hlsl.hlsl
new file mode 100644
index 0..cb14662c11f39
--- /dev/null
+++ b/clang/test/AST/Interp/hlsl.hlsl
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -std=hlsl2021 -finclude-default-header -x hlsl -triple \
+// RUN:   dxil-pc-shadermodel6.3-library %s -emit-llvm -disable-llvm-passes \
+// RUN:   -o - | FileCheck %s
+
+// RUN: %clang_cc1 -std=hlsl2021 -finclude-default-header -x hlsl -triple \
+// RUN:   dxil-pc-shadermodel6.3-library %s -emit-llvm -disable-llvm-passes \
+// RUN:   -o - -fexperimental-new-constant-interpreter | FileCheck %s
+
+
+/// This test converts V to a 1-element vector and then .xx to a 2-element 
vector.
+// CHECK-LABEL: ToTwoInts
+// CHECK: [[splat:%.*]] = insertelement <1 x i32> poison, i32 {{.*}}, i64 0
+// CHECK: [[vec2:%.*]] = shufflevector <1 x i32> [[splat]], <1 x i32> poison, 
<2 x i32> zeroinitializer
+// CHECK: ret <2 x i32> [[vec2]]
+int2 ToTwoInts(int V){
+  return V.xx;
+}
+
+



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


[clang] [llvm] [AArch64] Add ability to list extensions enabled for a target (PR #95805)

2024-06-18 Thread David Green via cfe-commits


@@ -19,3 +19,19 @@
 // RUN: %clang --target=arm64 -mlittle-endian -march=armv8.1a -### -c %s 2>&1 
| FileCheck -check-prefix=ARM64-GENERICV81A %s
 // RUN: %clang --target=arm64 -mlittle-endian -march=armv8.1-a -### -c %s 2>&1 
| FileCheck -check-prefix=ARM64-GENERICV81A %s
 // ARM64-GENERICV81A: "-cc1"{{.*}} "-triple" "arm64{{.*}}" "-target-cpu" 
"generic"{{.*}} "-target-feature" "+v8.1a"{{.*}} "-target-feature" "+neon"
+
+// = Architecture extensions =
+
+// RUN: %clang -target aarch64 -march=armv8.1-a --print-enabled-extensions 
2>&1 | FileCheck -check-prefix=ARCH-EXTENSION --implicit-check-not FEAT_ %s
+// ARCH-EXTENSION: FEAT_ETE
+// ARCH-EXTENSION: FEAT_LOR
+// ARCH-EXTENSION: FEAT_TRBE
+// ARCH-EXTENSION: FEAT_VHE
+// ARCH-EXTENSION: FEAT_PAN
+// ARCH-EXTENSION: FEAT_CRC32
+// FIXME: FEAT_FP is optional from v8.0a
+// ARCH-EXTENSION: FEAT_FP
+// ARCH-EXTENSION: FEAT_LSE
+// ARCH-EXTENSION: FEAT_RDM
+// FIXME: FEAT_AdvSIMD is optional from v8.0a

davemgreen wrote:

Why do these have FIXMEs?

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


[clang] [llvm] [AArch64] Add ability to list extensions enabled for a target (PR #95805)

2024-06-18 Thread David Green via cfe-commits


@@ -140,89 +152,480 @@ def FeatureAES : Extension<
 // compatibility, and now imply features SHA2 and AES, which was the
 // "traditional" meaning of Crypto.
 let FMVDependencies = "+aes,+sha2" in
-def FeatureCrypto : Extension<"crypto", "Crypto",
+def FeatureCrypto : ExtensionWithMArch<"crypto", "Crypto", "FEAT_Crypto",
   "Enable cryptographic instructions", [FeatureNEON, FeatureSHA2, FeatureAES]>;
 
-def FeatureCRC : Extension<"crc", "CRC",
-  "Enable ARMv8 CRC-32 checksum instructions (FEAT_CRC32)", [],
+def FeatureCRC : ExtensionWithMArch<"crc", "CRC", "FEAT_CRC32",
+  "Enable ARMv8 CRC-32 checksum instructions", [],
   "FEAT_CRC", "+crc", 110>;
 
-def FeatureRAS : Extension<"ras", "RAS",
-  "Enable ARMv8 Reliability, Availability and Serviceability Extensions 
(FEAT_RAS, FEAT_RASv1p1)">;
-
-def FeatureRASv2 : Extension<"rasv2", "RASv2",
-  "Enable ARMv8.9-A Reliability, Availability and Serviceability Extensions 
(FEAT_RASv2)",
-  [FeatureRAS]>;
-
-def FeatureLSE : Extension<"lse", "LSE",
-  "Enable ARMv8.1 Large System Extension (LSE) atomic instructions 
(FEAT_LSE)", [],
-  "FEAT_LSE", "+lse", 80>;
+// This SubtargetFeature is special. It controls only whether codegen will turn
+// `llvm.readcyclecounter()` into an access to a PMUv3 System Register. The
+// `FEAT_PMUv3*` system registers are always available for 
assembly/disassembly.
+let MArchName = "pmuv3" in
+def FeaturePerfMon : ExtensionWithMArch<"perfmon", "PerfMon", "FEAT_PMUv3",
+  "Enable Code Generation for ARMv8 PMUv3 Performance Monitors extension">;
 
-def FeatureLSE2 : SubtargetFeature<"lse2", "HasLSE2", "true",
-  "Enable ARMv8.4 Large System Extension 2 (LSE2) atomicity rules 
(FEAT_LSE2)">;
+def FeatureSpecRestrict : Extension<"specrestrict", "SpecRestrict", 
"FEAT_CSV2_2",
+  "Enable architectural speculation restriction">;
 
-def FeatureOutlineAtomics : SubtargetFeature<"outline-atomics", 
"OutlineAtomics", "true",
-  "Enable out of line atomics to support LSE instructions">;
+//===--===//
+//  Armv8.1 Architecture Extensions
+//===--===//
 
-def FeatureFMV : SubtargetFeature<"fmv", "HasFMV", "true",
-  "Enable Function Multi Versioning support.">;
+def FeatureLSE : ExtensionWithMArch<"lse", "LSE", "FEAT_LSE",
+  "Enable ARMv8.1 Large System Extension (LSE) atomic instructions", [],
+  "FEAT_LSE", "+lse", 80>;
 
 let MArchAlias = "rdma" in
-def FeatureRDM : Extension<"rdm", "RDM",
-  "Enable ARMv8.1 Rounding Double Multiply Add/Subtract instructions 
(FEAT_RDM)",
+def FeatureRDM : ExtensionWithMArch<"rdm", "RDM", "FEAT_RDM",
+  "Enable ARMv8.1 Rounding Double Multiply Add/Subtract instructions",
   [FeatureNEON],
   "FEAT_RDM", "+rdm,+fp-armv8,+neon", 108>;
 
-def FeaturePAN : SubtargetFeature<
-"pan", "HasPAN", "true",
-"Enables ARM v8.1 Privileged Access-Never extension (FEAT_PAN)">;
+def FeaturePAN : Extension<"pan", "PAN", "FEAT_PAN",
+  "Enables ARM v8.1 Privileged Access-Never extension">;
 
-def FeatureLOR : SubtargetFeature<
-"lor", "HasLOR", "true",
-"Enables ARM v8.1 Limited Ordering Regions extension (FEAT_LOR)">;
+def FeatureLOR : Extension<"lor", "LOR", "FEAT_LOR",
+  "Enables ARM v8.1 Limited Ordering Regions extension">;
 
 def FeatureCONTEXTIDREL2 : SubtargetFeature<"CONTEXTIDREL2", 
"HasCONTEXTIDREL2",
 "true", "Enable RW operand CONTEXTIDR_EL2" >;
 
-def FeatureVH : SubtargetFeature<"vh", "HasVH", "true",
-"Enables ARM v8.1 Virtual Host extension (FEAT_VHE)", 
[FeatureCONTEXTIDREL2] >;
+def FeatureVH : Extension<"vh", "VH", "FEAT_VHE",
+  "Enables ARM v8.1 Virtual Host extension", [FeatureCONTEXTIDREL2] >;
 
-// This SubtargetFeature is special. It controls only whether codegen will turn
-// `llvm.readcyclecounter()` into an access to a PMUv3 System Register. The
-// `FEAT_PMUv3*` system registers are always available for 
assembly/disassembly.
-let MArchName = "pmuv3" in
-def FeaturePerfMon : Extension<"perfmon", "PerfMon",
-  "Enable Code Generation for ARMv8 PMUv3 Performance Monitors extension 
(FEAT_PMUv3)">;
+//===--===//
+//  Armv8.2 Architecture Extensions
+//===--===//
+
+def FeatureSM4 : ExtensionWithMArch<"sm4", "SM4", "FEAT_SM4, FEAT_SM3",
+  "Enable SM3 and SM4 support", [FeatureNEON],
+  "FEAT_SM4", "+sm4,+fp-armv8,+neon", 106>;
+
+def FeatureSHA3 : ExtensionWithMArch<"sha3", "SHA3", "FEAT_SHA3, FEAT_SHA512",
+  "Enable SHA512 and SHA3 support", [FeatureNEON, FeatureSHA2],
+  "FEAT_SHA3", "+sha3,+sha2,+fp-armv8,+neon", 140>;
+
+def FeatureRAS : ExtensionWithMArch<"ras", "RAS", "FEAT_RAS, FEAT_RASv1p1",
+  "Enable ARMv8 Reliability, Availability and Serviceability Extensions">;
 
 let ArchExtKindSpelling = "AEK_FP16", MArchName = "fp16" in
-def FeatureFullFP16 : Extension<"fullfp16", "FullF

[clang] [clang][Interp] Implement complex division (PR #94892)

2024-06-18 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr updated 
https://github.com/llvm/llvm-project/pull/94892

>From 7a1c16f2fe0b23ffe49789275ffa66b2ac64c4d7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Sun, 9 Jun 2024 09:25:24 +0200
Subject: [PATCH] [clang][Interp] Implement Complex division

---
 clang/lib/AST/ExprConstShared.h  |  3 +
 clang/lib/AST/ExprConstant.cpp   | 76 ++--
 clang/lib/AST/Interp/ByteCodeExprGen.cpp | 67 ++---
 clang/lib/AST/Interp/Interp.h| 72 ++
 clang/lib/AST/Interp/Opcodes.td  |  4 ++
 clang/test/AST/Interp/complex.cpp| 15 +
 clang/test/SemaCXX/complex-folding.cpp   |  1 +
 7 files changed, 196 insertions(+), 42 deletions(-)

diff --git a/clang/lib/AST/ExprConstShared.h b/clang/lib/AST/ExprConstShared.h
index 9decd47e41767..2a7088e4e371a 100644
--- a/clang/lib/AST/ExprConstShared.h
+++ b/clang/lib/AST/ExprConstShared.h
@@ -62,5 +62,8 @@ GCCTypeClass EvaluateBuiltinClassifyType(QualType T,
 void HandleComplexComplexMul(llvm::APFloat A, llvm::APFloat B, llvm::APFloat C,
  llvm::APFloat D, llvm::APFloat &ResR,
  llvm::APFloat &ResI);
+void HandleComplexComplexDiv(llvm::APFloat A, llvm::APFloat B, llvm::APFloat C,
+ llvm::APFloat D, llvm::APFloat &ResR,
+ llvm::APFloat &ResI);
 
 #endif
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 3a6c8b4f82cca..9ac53438de8e4 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -15189,6 +15189,48 @@ void HandleComplexComplexMul(APFloat A, APFloat B, 
APFloat C, APFloat D,
   }
 }
 
+void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
+ APFloat &ResR, APFloat &ResI) {
+  // This is an implementation of complex division according to the
+  // constraints laid out in C11 Annex G. The implementation uses the
+  // following naming scheme:
+  //   (a + ib) / (c + id)
+
+  int DenomLogB = 0;
+  APFloat MaxCD = maxnum(abs(C), abs(D));
+  if (MaxCD.isFinite()) {
+DenomLogB = ilogb(MaxCD);
+C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
+D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
+  }
+  APFloat Denom = C * C + D * D;
+  ResR =
+  scalbn((A * C + B * D) / Denom, -DenomLogB, 
APFloat::rmNearestTiesToEven);
+  ResI =
+  scalbn((B * C - A * D) / Denom, -DenomLogB, 
APFloat::rmNearestTiesToEven);
+  if (ResR.isNaN() && ResI.isNaN()) {
+if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
+  ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
+  ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
+} else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
+   D.isFinite()) {
+  A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
+A);
+  B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
+B);
+  ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
+  ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
+} else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
+  C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
+C);
+  D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
+D);
+  ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
+  ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
+}
+  }
+}
+
 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
@@ -15326,39 +15368,7 @@ bool ComplexExprEvaluator::VisitBinaryOperator(const 
BinaryOperator *E) {
   // No real optimizations we can do here, stub out with zero.
   B = APFloat::getZero(A.getSemantics());
 }
-int DenomLogB = 0;
-APFloat MaxCD = maxnum(abs(C), abs(D));
-if (MaxCD.isFinite()) {
-  DenomLogB = ilogb(MaxCD);
-  C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
-  D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
-}
-APFloat Denom = C * C + D * D;
-ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
-  APFloat::rmNearestTiesToEven);
-ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
-  APFloat::rmNearestTiesToEven);
-if (ResR.isNaN() && ResI.isNaN()) {
-  if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
-ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
-ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
- 

[clang] [analyzer] Add an ownership change visitor to StreamChecker (PR #94957)

2024-06-18 Thread Kristóf Umann via cfe-commits

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


[clang-tools-extra] [clang][include-cleaner]skip stdlib recogntion only when there are defintion with body in main file. (PR #95797)

2024-06-18 Thread kadir çetinkaya via cfe-commits

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


[clang-tools-extra] [clang][include-cleaner]skip stdlib recogntion only when there are defintion with body in main file. (PR #95797)

2024-06-18 Thread kadir çetinkaya via cfe-commits

https://github.com/kadircet requested changes to this pull request.

hi @HerrCai0907 !

Left some detailed comments in the patch. Due to timezone differences, I highly 
suspect this will be fixed quickly and we have some extra delays for getting 
changes into releases (and I am going to be OOO next week).
Hence while you're addressing the issues here I am going to revert the original 
commit, to make sure include-cleaner doesn't stay with this regression for a 
longer period.

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


[clang-tools-extra] [clang][include-cleaner]skip stdlib recogntion only when there are defintion with body in main file. (PR #95797)

2024-06-18 Thread kadir çetinkaya via cfe-commits


@@ -39,20 +40,24 @@ Hints declHints(const Decl *D) {
 }
 
 std::vector> locateDecl(const Decl &D) {
-  std::vector> Result;
-  // FIXME: Should we also provide physical locations?
-  if (auto SS = tooling::stdlib::Recognizer()(&D)) {
-Result.push_back({*SS, Hints::CompleteSymbol});
-if (!D.hasBody())
-  return Result;
-  }
+  SourceManager &SM = D.getASTContext().getSourceManager();
+  bool HasBodyInMainFile = llvm::any_of(D.redecls(), [&](Decl *Redecl) {
+return Redecl->hasBody() && SM.isInMainFile(Redecl->getLocation());
+  });
+  // if decl has body and in main file, we don't need to do further search.
+  if (!HasBodyInMainFile)

kadircet wrote:

i don't think it's actually "right" layering-wise to perform any 
`sourcelocation <-> fileid` mappings here. it's subtle and expensive, 
especially for every-redecl of stdlib symbols, which might be forward declared 
many times in STL (but also for any other symbol).

Hence we actually have logic down the line that maps sourcelocations to files 
(it's also expensive today, but is in a single place and takes care of edge 
cases, like macros). at least this layering ensures that if we want to 
introduce caching/optimizations one day, we can rely on having certain 
separation between different kinds of mappings.

Moreover, I don't follow the check around a redeclaration having body only in 
the main file. I feel like you're focusing on a very specific issue you have 
and not solving the issue in general. e.g. what if the user only has forward 
declaration of the symbol in the main file? why don't we want to suppress in 
that case? or what if the user has body/declaration in a different header file, 
which also seems pretty common.

I think if you want to improve this case, you really need to address `// FIXME: 
Should we also provide physical locations?`, which is definitely doable, we 
just need to make sure ranking is still done accordingly.

I am still strongly arguing that we should never insert a custom header if 
there's a name-collision with a stdlib symbol. Hence we should make sure all 
physical locations for a stdlib symbol is downranked, i'd recommend stripping 
completesymbol signal from these symbols.

You also need to consider the macro-side of this. you're addressing this 
situation for decls, but the user might as well have `#define assert(X) X` in 
their main file (or some of the other headers). we need to make sure this same 
logic also works for that.

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


[clang] [clang] Fix-it hint for `++this` -> `++*this` when deref is modifiable (PR #94159)

2024-06-18 Thread via cfe-commits

Sirraide wrote:

Having more context would probably help yeah. We should be able to improve that 
a bit even if the fix-it isn’t viable...

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


[clang] Revert "[X86] Add support for MS inp functions." (PR #95890)

2024-06-18 Thread Malay Sanghi via cfe-commits

https://github.com/MalaySanghi created 
https://github.com/llvm/llvm-project/pull/95890

Reverts llvm/llvm-project#93804
Revert commit 089dfeee8a8761c35a3a56e75281275871dd53bc. The original request 
can be fulfilled with alternative __inbyte/__inword/__indword

>From 1d96bd439d4631d0ff9d7005f27b770ce1d80a21 Mon Sep 17 00:00:00 2001
From: Malay Sanghi 
Date: Tue, 18 Jun 2024 12:37:19 +0530
Subject: [PATCH] Revert "[X86] Add support for MS inp functions. (#93804)"

This reverts commit 089dfeee8a8761c35a3a56e75281275871dd53bc.
---
 clang/lib/Headers/intrin.h | 19 
 clang/test/CodeGen/X86/ms-x86-intrinsics.c | 25 --
 2 files changed, 44 deletions(-)

diff --git a/clang/lib/Headers/intrin.h b/clang/lib/Headers/intrin.h
index 1227f45d5432b..5ceb986a1f652 100644
--- a/clang/lib/Headers/intrin.h
+++ b/clang/lib/Headers/intrin.h
@@ -329,25 +329,6 @@ static __inline__ void __DEFAULT_FN_ATTRS __stosq(unsigned 
__int64 *__dst,
 static __inline__ void __DEFAULT_FN_ATTRS __halt(void) {
   __asm__ volatile("hlt");
 }
-
-static inline int _inp(unsigned short port) {
-  int ret;
-  __asm__ volatile("inb %w1, %b0" : "=a"(ret) : "Nd"(port));
-  return ret;
-}
-
-static inline unsigned short _inpw(unsigned short port) {
-  unsigned short ret;
-  __asm__ volatile("inw %w1, %w0" : "=a"(ret) : "Nd"(port));
-  return ret;
-}
-
-static inline unsigned long _inpd(unsigned short port) {
-  unsigned long ret;
-  __asm__ volatile("inl %w1, %k0" : "=a"(ret) : "Nd"(port));
-  return ret;
-}
-
 #endif
 
 #if defined(__i386__) || defined(__x86_64__) || defined(__aarch64__)
diff --git a/clang/test/CodeGen/X86/ms-x86-intrinsics.c 
b/clang/test/CodeGen/X86/ms-x86-intrinsics.c
index 9566951b44d2d..aa557c8e19a83 100644
--- a/clang/test/CodeGen/X86/ms-x86-intrinsics.c
+++ b/clang/test/CodeGen/X86/ms-x86-intrinsics.c
@@ -63,31 +63,6 @@ unsigned __int64 test__emulu(unsigned int a, unsigned int b) 
{
 // CHECK: [[RES:%[0-9]+]] = mul nuw i64 [[Y]], [[X]]
 // CHECK: ret i64 [[RES]]
 
-
-int test_inp(unsigned short port) {
-  return _inp(port);
-}
-// CHECK-LABEL: i32 @test_inp(i16 noundef
-// CHECK-SAME:  [[PORT:%.*]])
-// CHECK:   [[TMP0:%.*]] = tail call i32 asm sideeffect "inb ${1:w}, 
${0:b}", "={ax},N{dx},~{dirflag},~{fpsr},~{flags}"(i16 [[PORT]])
-// CHECK-NEXT:  ret i32 [[TMP0]]
-
-unsigned short test_inpw(unsigned short port) {
-  return _inpw(port);
-}
-// CHECK-LABEL: i16 @test_inpw(i16 noundef
-// CHECK-SAME:  [[PORT:%.*]])
-// CHECK:   [[TMP0:%.*]] = tail call i16 asm sideeffect "inw ${1:w}, 
${0:w}", "={ax},N{dx},~{dirflag},~{fpsr},~{flags}"(i16 [[PORT]])
-// CHECK-NEXT:  ret i16 [[TMP0]]
-
-unsigned long test_inpd(unsigned short port) {
-  return _inpd(port);
-}
-// CHECK-LABEL: i32 @test_inpd(i16 noundef
-// CHECK-SAME:  [[PORT:%.*]])
-// CHECK:   [[TMP0:%.*]] = tail call i32 asm sideeffect "inl ${1:w}, 
${0:k}", "={ax},N{dx},~{dirflag},~{fpsr},~{flags}"(i16 [[PORT]])
-// CHECK-NEXT:  ret i32 [[TMP0]]
-
 #if defined(__x86_64__)
 
 char test__readgsbyte(unsigned long Offset) {

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


[clang] [Clang] [Sema] Ensure noexcept(typeid(E)) checks if E throws when needed (PR #95846)

2024-06-18 Thread via cfe-commits

Sirraide wrote:

Do we already have tests for your most recent commit (i.e. dependent 
expressions)? Because I recall CI passing even when that wasn’t there, but that 
may have been my imagination.

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


[clang] Revert "[X86] Add support for MS inp functions." (PR #95890)

2024-06-18 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-backend-x86

Author: Malay Sanghi (MalaySanghi)


Changes

Reverts llvm/llvm-project#93804
Revert commit 089dfeee8a8761c35a3a56e75281275871dd53bc. The original request 
can be fulfilled with alternative __inbyte/__inword/__indword

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


2 Files Affected:

- (modified) clang/lib/Headers/intrin.h (-19) 
- (modified) clang/test/CodeGen/X86/ms-x86-intrinsics.c (-25) 


``diff
diff --git a/clang/lib/Headers/intrin.h b/clang/lib/Headers/intrin.h
index 1227f45d5432b..5ceb986a1f652 100644
--- a/clang/lib/Headers/intrin.h
+++ b/clang/lib/Headers/intrin.h
@@ -329,25 +329,6 @@ static __inline__ void __DEFAULT_FN_ATTRS __stosq(unsigned 
__int64 *__dst,
 static __inline__ void __DEFAULT_FN_ATTRS __halt(void) {
   __asm__ volatile("hlt");
 }
-
-static inline int _inp(unsigned short port) {
-  int ret;
-  __asm__ volatile("inb %w1, %b0" : "=a"(ret) : "Nd"(port));
-  return ret;
-}
-
-static inline unsigned short _inpw(unsigned short port) {
-  unsigned short ret;
-  __asm__ volatile("inw %w1, %w0" : "=a"(ret) : "Nd"(port));
-  return ret;
-}
-
-static inline unsigned long _inpd(unsigned short port) {
-  unsigned long ret;
-  __asm__ volatile("inl %w1, %k0" : "=a"(ret) : "Nd"(port));
-  return ret;
-}
-
 #endif
 
 #if defined(__i386__) || defined(__x86_64__) || defined(__aarch64__)
diff --git a/clang/test/CodeGen/X86/ms-x86-intrinsics.c 
b/clang/test/CodeGen/X86/ms-x86-intrinsics.c
index 9566951b44d2d..aa557c8e19a83 100644
--- a/clang/test/CodeGen/X86/ms-x86-intrinsics.c
+++ b/clang/test/CodeGen/X86/ms-x86-intrinsics.c
@@ -63,31 +63,6 @@ unsigned __int64 test__emulu(unsigned int a, unsigned int b) 
{
 // CHECK: [[RES:%[0-9]+]] = mul nuw i64 [[Y]], [[X]]
 // CHECK: ret i64 [[RES]]
 
-
-int test_inp(unsigned short port) {
-  return _inp(port);
-}
-// CHECK-LABEL: i32 @test_inp(i16 noundef
-// CHECK-SAME:  [[PORT:%.*]])
-// CHECK:   [[TMP0:%.*]] = tail call i32 asm sideeffect "inb ${1:w}, 
${0:b}", "={ax},N{dx},~{dirflag},~{fpsr},~{flags}"(i16 [[PORT]])
-// CHECK-NEXT:  ret i32 [[TMP0]]
-
-unsigned short test_inpw(unsigned short port) {
-  return _inpw(port);
-}
-// CHECK-LABEL: i16 @test_inpw(i16 noundef
-// CHECK-SAME:  [[PORT:%.*]])
-// CHECK:   [[TMP0:%.*]] = tail call i16 asm sideeffect "inw ${1:w}, 
${0:w}", "={ax},N{dx},~{dirflag},~{fpsr},~{flags}"(i16 [[PORT]])
-// CHECK-NEXT:  ret i16 [[TMP0]]
-
-unsigned long test_inpd(unsigned short port) {
-  return _inpd(port);
-}
-// CHECK-LABEL: i32 @test_inpd(i16 noundef
-// CHECK-SAME:  [[PORT:%.*]])
-// CHECK:   [[TMP0:%.*]] = tail call i32 asm sideeffect "inl ${1:w}, 
${0:k}", "={ax},N{dx},~{dirflag},~{fpsr},~{flags}"(i16 [[PORT]])
-// CHECK-NEXT:  ret i32 [[TMP0]]
-
 #if defined(__x86_64__)
 
 char test__readgsbyte(unsigned long Offset) {

``




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


[clang] Revert "[X86] Add support for MS inp functions." (PR #95890)

2024-06-18 Thread Malay Sanghi via cfe-commits

MalaySanghi wrote:

@phoebewang please review and revert

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


[clang] [clang-cl][AST] Fix auto NTTP MSVC 1920+ mangling for pointer types (PR #92477)

2024-06-18 Thread Eli Friedman via cfe-commits

https://github.com/efriedma-quic approved this pull request.

LGTM

Your commit message mentions variables, function pointers, and member function 
pointers...  is there anything else we need to handle?  Null pointers?  
Integers?

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


[clang] Revert "[X86] Add support for MS inp functions." (PR #95890)

2024-06-18 Thread Phoebe Wang via cfe-commits

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

LGTM.

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


[clang] [X86]Add support for _outp{|w|d} (PR #93774)

2024-06-18 Thread Malay Sanghi via cfe-commits

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


[clang] [X86]Add support for _outp{|w|d} (PR #93774)

2024-06-18 Thread Malay Sanghi via cfe-commits

MalaySanghi wrote:

Closing. The original request can be fulfilled with 
__outbyte/__outword/__outdword

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


[clang] [llvm] [RISCV] Add processor definition for SpacemiT-X60 (PR #94564)

2024-06-18 Thread Shao-Ce SUN via cfe-commits


@@ -381,3 +381,20 @@ def XIANGSHAN_NANHU : 
RISCVProcessorModel<"xiangshan-nanhu",
 TuneZExtHFusion,
 TuneZExtWFusion,
 TuneShiftedZExtWFusion]>;
+
+def SPACEMIT_X60 : RISCVProcessorModel<"spacemit-x60",
+   NoSchedModel,
+   !listconcat(RVA22S64Features,

sunshaoce wrote:

This modification seems to cause the wrong information generated by 
`build/include/llvm/TargetParser/RISCVTargetParserDef.inc`. 

```c++
PROC(SIFIVE_X280, {"sifive-x280"}, 
{"rv64i2p1_m2p0_a2p1_f2p2_d2p2_c2p0_v1p0_zifencei2p0_zfh1p0_zba1p0_zbb1p0_zvfh1p0_zvl512b1p0"},
 0)
PROC(SPACEMIT_X60, {"spacemit-x60"}, 
{"rv0v1p0_zicond1p0_zmmul1p0_zfh1p0_zbc1p0_zbkc1p0_zvfh1p0_zvkt1p0_zvl256b1p0_sscofpmf1p0_sstc1p0_svnapot1p0"},
 0)
PROC(SYNTACORE_SCR1_BASE, {"syntacore-scr1-base"}, 
{"rv32i2p1_c2p0_zicsr2p0_zifencei2p0"}, 0)
```

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


[clang-tools-extra] ae0813f - Revert "[clang-tidy] fix false positives for the functions with the same name as standard library functions in misc-include-cleaner (#94923)"

2024-06-18 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2024-06-18T09:15:30+02:00
New Revision: ae0813f2d7222c4eab7cd3e6099d49f50318d1d5

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

LOG: Revert "[clang-tidy] fix false positives for the functions with the same 
name as standard library functions in misc-include-cleaner (#94923)"

This reverts commit 1bae10879d9183c5edfb709c36b55086ebc772f0. Also add
some test cases to prevent further regressions.

Added: 


Modified: 
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/include-cleaner/lib/LocateSymbol.cpp
clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
clang-tools-extra/test/clang-tidy/checkers/misc/include-cleaner.cpp

Removed: 




diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 3bdd735f7dcf7..16fdc20eafd62 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -341,10 +341,6 @@ Changes in existing checks
   ` check by avoiding crash for 
self
   include cycles.
 
-- Improved :doc:`misc-include-cleaner
-  ` check by avoiding false positives 
for
-  the functions with the same name as standard library functions.
-
 - Improved :doc:`misc-unused-using-decls
   ` check by replacing the local
   option `HeaderFileExtensions` by the global option of the same name.

diff  --git a/clang-tools-extra/include-cleaner/lib/LocateSymbol.cpp 
b/clang-tools-extra/include-cleaner/lib/LocateSymbol.cpp
index 9148d36a5038f..78e783a62eb27 100644
--- a/clang-tools-extra/include-cleaner/lib/LocateSymbol.cpp
+++ b/clang-tools-extra/include-cleaner/lib/LocateSymbol.cpp
@@ -14,7 +14,6 @@
 #include "clang/AST/DeclTemplate.h"
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "llvm/Support/Casting.h"
-#include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 
@@ -41,11 +40,8 @@ Hints declHints(const Decl *D) {
 std::vector> locateDecl(const Decl &D) {
   std::vector> Result;
   // FIXME: Should we also provide physical locations?
-  if (auto SS = tooling::stdlib::Recognizer()(&D)) {
-Result.push_back({*SS, Hints::CompleteSymbol});
-if (!D.hasBody())
-  return Result;
-  }
+  if (auto SS = tooling::stdlib::Recognizer()(&D))
+return {{*SS, Hints::CompleteSymbol}};
   // FIXME: Signal foreign decls, e.g. a forward declaration not owned by a
   // library. Some useful signals could be derived by checking the DeclContext.
   // Most incidental forward decls look like:

diff  --git a/clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp 
b/clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
index fdcbf25fd628c..c5fc465ced7a7 100644
--- a/clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
+++ b/clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
@@ -619,26 +619,23 @@ TEST_F(HeadersForSymbolTest, 
AmbiguousStdSymbolsUsingShadow) {
 
 
 TEST_F(HeadersForSymbolTest, StandardHeaders) {
-  Inputs.Code = "void assert();";
+  Inputs.Code = R"cpp(
+#include "stdlib_internal.h"
+void assert();
+void foo() { assert(); }
+  )cpp";
+  Inputs.ExtraFiles["stdlib_internal.h"] = "void assert();";
   buildAST();
   EXPECT_THAT(
   headersFor("assert"),
   // Respect the ordering from the stdlib mapping.
+  // FIXME: Report physical locations too, stdlib_internal.h and main-file
+  // should also be candidates. But they should be down-ranked compared to
+  // stdlib providers.
   UnorderedElementsAre(tooling::stdlib::Header::named(""),
tooling::stdlib::Header::named("")));
 }
 
-TEST_F(HeadersForSymbolTest, NonStandardHeaders) {
-  Inputs.Code = "void assert() {}";
-  buildAST();
-  EXPECT_THAT(
-  headersFor("assert"),
-  // Respect the ordering from the stdlib mapping.
-  UnorderedElementsAre(physicalHeader("input.mm"),
-   tooling::stdlib::Header::named(""),
-   tooling::stdlib::Header::named("")));
-}
-
 TEST_F(HeadersForSymbolTest, ExporterNoNameMatch) {
   Inputs.Code = R"cpp(
 #include "exporter/foo.h"

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/misc/include-cleaner.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/misc/include-cleaner.cpp
index d5ea96b00254c..e10ac3f46e2e9 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/misc/include-cleaner.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/misc/include-cleaner.cpp
@@ -15,11 +15,3 @@ std::string HelloString;
 // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: no header providing "std::string" 
is directly included [misc-include-cleaner]
 int FooBarResult = foobar();
 // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: no header providing "foobar" is 
directly included [misc-include-cleaner]
-

[clang] [llvm] [analyzer][NFC] Reorganize Z3 report refutation (PR #95128)

2024-06-18 Thread Balazs Benics via cfe-commits

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

>From 6b9a5a6902c3efca6ac7d6a5dabc8950767560cc Mon Sep 17 00:00:00 2001
From: Balazs Benics 
Date: Tue, 11 Jun 2024 16:53:46 +0200
Subject: [PATCH 1/2] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20in?=
 =?UTF-8?q?itial=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.4
---
 .../Core/BugReporter/BugReporterVisitors.h|  23 
 .../Core/BugReporter/Z3CrosscheckVisitor.h|  66 ++
 .../Core/PathSensitive/SMTConstraintManager.h |   5 +-
 clang/lib/StaticAnalyzer/Core/BugReporter.cpp |  28 -
 .../Core/BugReporterVisitors.cpp  |  76 ---
 clang/lib/StaticAnalyzer/Core/CMakeLists.txt  |   1 +
 .../Core/Z3CrosscheckVisitor.cpp  | 118 ++
 .../test/Analysis/z3/crosscheck-statistics.c  |  33 +
 clang/unittests/StaticAnalyzer/CMakeLists.txt |   1 +
 .../StaticAnalyzer/Z3CrosscheckOracleTest.cpp |  59 +
 llvm/include/llvm/Support/SMTAPI.h|  19 +++
 llvm/lib/Support/Z3Solver.cpp | 103 ---
 12 files changed, 408 insertions(+), 124 deletions(-)
 create mode 100644 
clang/include/clang/StaticAnalyzer/Core/BugReporter/Z3CrosscheckVisitor.h
 create mode 100644 clang/lib/StaticAnalyzer/Core/Z3CrosscheckVisitor.cpp
 create mode 100644 clang/test/Analysis/z3/crosscheck-statistics.c
 create mode 100644 clang/unittests/StaticAnalyzer/Z3CrosscheckOracleTest.cpp

diff --git 
a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h 
b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
index cc3d93aabafda..f97514955a591 100644
--- a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
+++ b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
@@ -597,29 +597,6 @@ class SuppressInlineDefensiveChecksVisitor final : public 
BugReporterVisitor {
PathSensitiveBugReport &BR) override;
 };
 
-/// The bug visitor will walk all the nodes in a path and collect all the
-/// constraints. When it reaches the root node, will create a refutation
-/// manager and check if the constraints are satisfiable
-class FalsePositiveRefutationBRVisitor final : public BugReporterVisitor {
-private:
-  /// Holds the constraints in a given path
-  ConstraintMap Constraints;
-
-public:
-  FalsePositiveRefutationBRVisitor();
-
-  void Profile(llvm::FoldingSetNodeID &ID) const override;
-
-  PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
-   BugReporterContext &BRC,
-   PathSensitiveBugReport &BR) override;
-
-  void finalizeVisitor(BugReporterContext &BRC, const ExplodedNode 
*EndPathNode,
-   PathSensitiveBugReport &BR) override;
-  void addConstraints(const ExplodedNode *N,
-  bool OverwriteConstraintsOnExistingSyms);
-};
-
 /// The visitor detects NoteTags and displays the event notes they contain.
 class TagVisitor : public BugReporterVisitor {
 public:
diff --git 
a/clang/include/clang/StaticAnalyzer/Core/BugReporter/Z3CrosscheckVisitor.h 
b/clang/include/clang/StaticAnalyzer/Core/BugReporter/Z3CrosscheckVisitor.h
new file mode 100644
index 0..3ec59e3037363
--- /dev/null
+++ b/clang/include/clang/StaticAnalyzer/Core/BugReporter/Z3CrosscheckVisitor.h
@@ -0,0 +1,66 @@
+//===- Z3CrosscheckVisitor.h - Crosscheck reports with Z3 ---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines the visitor and utilities around it for Z3 report
+//  refutation.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_Z3CROSSCHECKVISITOR_H
+#define LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_Z3CROSSCHECKVISITOR_H
+
+#include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
+
+namespace clang::ento {
+
+/// The bug visitor will walk all the nodes in a path and collect all the
+/// constraints. When it reaches the root node, will create a refutation
+/// manager and check if the constraints are satisfiable.
+class Z3CrosscheckVisitor final : public BugReporterVisitor {
+public:
+  struct Z3Result {
+std::optional IsSAT = std::nullopt;
+  };
+  explicit Z3CrosscheckVisitor(Z3CrosscheckVisitor::Z3Result &Result);
+
+  void Profile(llvm::FoldingSetNodeID &ID) const override;
+
+  PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
+   BugReporterContext &BRC,
+   PathSensitiveBugReport &BR) override;
+
+  void f

[clang] [llvm] [analyzer][NFC] Reorganize Z3 report refutation (PR #95128)

2024-06-18 Thread Balazs Benics via cfe-commits

steakhal wrote:

Implement move-only rule-of-5 for:
 - `Z3Config`
 - `Z3Context`

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


[clang] [llvm] [RISCV] Add processor definition for SpacemiT-X60 (PR #94564)

2024-06-18 Thread Shao-Ce SUN via cfe-commits

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


[clang] [llvm] [DebugInfo][BPF] Add 'btf:type_tag' annotation in DWARF (PR #91423)

2024-06-18 Thread via cfe-commits

https://github.com/eddyz87 updated 
https://github.com/llvm/llvm-project/pull/91423

>From 434c6971332af7dbf80affd9a273e60860e30595 Mon Sep 17 00:00:00 2001
From: Eduard Zingerman 
Date: Tue, 14 Feb 2023 01:19:50 +0200
Subject: [PATCH 1/2] [DebugInfo][BPF] Add 'btf:type_tag' annotation in DWARF

This commit is a follow-up for BPF mailing list discussion at [1].
It changes the way `__attribute__((btf_type_tag("...")))`s are
represented in DWARF.

Prior to this commit type tags could only be attached to pointers.
Such attachments associated the tags with a pointee type.
E.g. for the following C code:

int __attribute__((btf_type_tag("tag1"))) *g;

Generated DWARF looked as follows:

0x001e:   DW_TAG_variable
DW_AT_name  ("g")
DW_AT_type  (0x0029 "int *")

0x0029:   DW_TAG_pointer_type
DW_AT_type  (0x0032 "int")

0x002e: DW_TAG_LLVM_annotation
  DW_AT_name("btf_type_tag")
  DW_AT_const_value ("tag1")

0x0032:   DW_TAG_base_type
DW_AT_name  ("int")

The goal of this commit is to allow attachment of type tags to the
tagged types instead. E.g. for the same example DWARF should look as
follows:

0x001e:   DW_TAG_variable
DW_AT_name  ("g")
DW_AT_type  (0x0029 "int *")

0x0029:   DW_TAG_pointer_type
DW_AT_type  (0x0032 "int")

0x0032:   DW_TAG_base_type
DW_AT_name  ("int")

0x0036: DW_TAG_LLVM_annotation
  DW_AT_name("btf:type_tag")
  DW_AT_const_value ("tag1")

A new tag name, `btf:type_tag`, is used so that DWARF consumers
could distinguish between old and new attachment semantics.

This feature is mostly used by Linux Kernel in combination with tool
named pahole [2]. Reasonably recent versions of pahole generate
errors (1.23, 1.24) or warnings (1.25) when `DW_TAG_LLVM_annotation`
is attached to `DW_TAG_base_type` or `DW_TAG_unspecified_type`.
Hence the `btf:type_tag` generation is controlled by a hidden option
`-mllvm -btf-type-tag-v2`. The goal is to provide a way for tooling to
work on adding support `btf:type_tag` and eventually replace
`btf_type_tag` by `btf:type_tag`, removing the above option.

The commit includes the following changes:
- Changes in debug info generation:
  - New method `DIBuilder::createAnnotationsPlaceholder()` is added,
it creates a temporary `DIDerivedType` that plays as annotations
placeholder while debug info metadata is being constructed;
  - New overload for `CGDebugInfo::CreateType` method is added:

  llvm::DIType *CGDebugInfo::CreateType(const BTFTagAttributedType *Ty,
llvm::DIFile *Unit);

This overload collects BTF type tags in `Ty`, creates annotations
placeholder pointing to the base type of `Ty`, registers the
placeholder in the `CGDebugInfo::AnnotationsPlaceholder` vector.
  - `CGDebugInfo::finalize()` is updated to do the following for each
annotation placeholder:
- clone underlying base type;
- attach annotations the clone using `replaceAnnotations()` call;
- replace all placeholder usages by a clone.
  Such scheme allows to deal with type cycles.

- Changes in AST construction:
  - `ASTContext::getBTFTagAttributedType()` is updated to ensure that
`BTFTagAttributedType` always wraps `QualType` w/o local
constant/volatile/restricted qualifiers. This simplifies debug info
generation.

[1] https://lore.kernel.org/bpf/87r0w9jjoq@oracle.com/
[2] https://git.kernel.org/pub/scm/devel/pahole/pahole.git/

This was previously tracked as differential revision:
https://reviews.llvm.org/D143967
---
 clang/lib/CodeGen/CGDebugInfo.cpp | 204 +++---
 clang/lib/CodeGen/CGDebugInfo.h   |   3 +
 .../test/CodeGen/attr-btf_type_tag-circular.c |  18 ++
 clang/test/CodeGen/attr-btf_type_tag-const.c  |  41 
 .../test/CodeGen/attr-btf_type_tag-func-ptr.c |  19 +-
 clang/test/CodeGen/attr-btf_type_tag-func.c   |  50 +++--
 .../test/CodeGen/attr-btf_type_tag-restrict.c |  21 ++
 .../CodeGen/attr-btf_type_tag-similar-type.c  |  47 ++--
 .../CodeGen/attr-btf_type_tag-typedef-field.c |  66 --
 clang/test/CodeGen/attr-btf_type_tag-var.c|  77 +--
 clang/test/CodeGen/attr-btf_type_tag-void.c   |  12 ++
 .../test/CodeGen/attr-btf_type_tag-volatile.c |  18 ++
 llvm/include/llvm/IR/DIBuilder.h  |   3 +
 llvm/lib/IR/DIBuilder.cpp |  11 +
 14 files changed, 493 insertions(+), 97 deletions(-)
 create mode 100644 clang/test/CodeGen/attr-btf_type_tag-circular.c
 create mode 100644 clang/test/CodeGen/attr-btf_type_tag-const.c
 create mode 100644 clang/test/CodeGen/attr-btf_type_tag-restrict.c
 create mode 100644 clang/test/CodeGen/attr-btf_type_tag-void.c
 cr

[clang] [llvm] [RISCV] Add processor definition for SpacemiT-X60 (PR #94564)

2024-06-18 Thread Craig Topper via cfe-commits


@@ -381,3 +381,20 @@ def XIANGSHAN_NANHU : 
RISCVProcessorModel<"xiangshan-nanhu",
 TuneZExtHFusion,
 TuneZExtWFusion,
 TuneShiftedZExtWFusion]>;
+
+def SPACEMIT_X60 : RISCVProcessorModel<"spacemit-x60",
+   NoSchedModel,
+   !listconcat(RVA22S64Features,
+   [FeatureStdExtV,
+FeatureStdExtSscofpmf,
+FeatureStdExtSstc,
+FeatureStdExtSvnapot,
+FeatureStdExtZbc,
+FeatureStdExtZbkc,
+FeatureStdExtZfh,
+FeatureStdExtZicond,
+FeatureStdExtZmmul,

topperc wrote:

Please don't list Zmmul separate from M.

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


[clang] Revert "[clang] Fix-it hint for `++this` -> `++*this` when deref is modifiable" (PR #95833)

2024-06-18 Thread via cfe-commits

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


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


[clang] [llvm] [RISCV] Add processor definition for SpacemiT-X60 (PR #94564)

2024-06-18 Thread Craig Topper via cfe-commits


@@ -381,3 +381,20 @@ def XIANGSHAN_NANHU : 
RISCVProcessorModel<"xiangshan-nanhu",
 TuneZExtHFusion,
 TuneZExtWFusion,
 TuneShiftedZExtWFusion]>;
+
+def SPACEMIT_X60 : RISCVProcessorModel<"spacemit-x60",
+   NoSchedModel,
+   !listconcat(RVA22S64Features,

topperc wrote:

Need to add `Feature64Bit` and maybe others

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


[clang] 7dd7d57 - Revert "[clang] Fix-it hint for `++this` -> `++*this` when deref is modifiable" (#95833)

2024-06-18 Thread via cfe-commits

Author: Sirraide
Date: 2024-06-18T09:40:17+02:00
New Revision: 7dd7d5749f7d9d98fec50ee88e633e8b85c6502a

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

LOG: Revert "[clang] Fix-it hint for `++this` -> `++*this` when deref is 
modifiable" (#95833)

Reverts llvm/llvm-project#94159

@zygoloid had some concerns about the implementation of this, which make
sense to me, so I’d like to revert this for now so we can have more time
to think about how to best approach this (if at all...)

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaExpr.cpp
clang/test/C/drs/dr1xx.c
clang/test/Sema/exprs.c
clang/test/Sema/va_arg_x86_32.c
clang/test/SemaObjCXX/sel-address.mm

Removed: 
clang/test/Sema/debug-93066.cpp



diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 9b8f5b7e80e7e..8f85371df3b85 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -8778,9 +8778,6 @@ def err_typecheck_incomplete_type_not_modifiable_lvalue : 
Error<
 def err_typecheck_lvalue_casts_not_supported : Error<
   "assignment to cast is illegal, lvalue casts are not supported">;
 
-def note_typecheck_add_deref_star_not_modifiable_lvalue : Note<
-  "add '*' to dereference it">; 
-
 def err_typecheck_duplicate_vector_components_not_mlvalue : Error<
   "vector is not assignable (contains duplicate components)">;
 def err_block_decl_ref_not_modifiable_lvalue : Error<

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 4db8b4130c3c7..453af8f28f946 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -13288,23 +13288,6 @@ enum {
   ConstUnknown,  // Keep as last element
 };
 
-static void MaybeSuggestDerefFixIt(Sema &S, const Expr *E, SourceLocation Loc) 
{
-  ExprResult Deref;
-  Expr *TE = const_cast(E);
-  {
-Sema::TentativeAnalysisScope Trap(S);
-Deref = S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, TE);
-  }
-  if (Deref.isUsable() &&
-  Deref.get()->isModifiableLvalue(S.Context, &Loc) == Expr::MLV_Valid &&
-  !E->getType()->isObjCObjectPointerType()) {
-S.Diag(E->getBeginLoc(),
-   diag::note_typecheck_add_deref_star_not_modifiable_lvalue)
-<< E->getSourceRange()
-<< FixItHint::CreateInsertion(E->getBeginLoc(), "*");
-  }
-}
-
 /// Emit the "read-only variable not assignable" error and print notes to give
 /// more information about why the variable is not assignable, such as pointing
 /// to the declaration of a const variable, showing that a method is const, or
@@ -13399,7 +13382,6 @@ static void DiagnoseConstAssignment(Sema &S, const Expr 
*E,
 if (!DiagnosticEmitted) {
   S.Diag(Loc, diag::err_typecheck_assign_const)
   << ExprRange << ConstVariable << VD << VD->getType();
-  MaybeSuggestDerefFixIt(S, E, Loc);
   DiagnosticEmitted = true;
 }
 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
@@ -13620,12 +13602,10 @@ static bool CheckForModifiableLvalue(Expr *E, 
SourceLocation Loc, Sema &S) {
   SourceRange Assign;
   if (Loc != OrigLoc)
 Assign = SourceRange(OrigLoc, OrigLoc);
-  if (NeedType) {
+  if (NeedType)
 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
-  } else {
+  else
 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
-MaybeSuggestDerefFixIt(S, E, Loc);
-  }
   return true;
 }
 

diff  --git a/clang/test/C/drs/dr1xx.c b/clang/test/C/drs/dr1xx.c
index 20e953b2c20ac..47538e44428c3 100644
--- a/clang/test/C/drs/dr1xx.c
+++ b/clang/test/C/drs/dr1xx.c
@@ -296,7 +296,6 @@ void dr126(void) {
*/
   *object = 12; /* ok */
   ++object; /* expected-error {{cannot assign to variable 'object' with 
const-qualified type 'const IP' (aka 'int *const')}} */
-  /* expected-note@-1 {{add '*' to dereference it}} */
 }
 
 /* WG14 DR128: yes

diff  --git a/clang/test/Sema/debug-93066.cpp b/clang/test/Sema/debug-93066.cpp
deleted file mode 100644
index e64d378e6f90d..0
--- a/clang/test/Sema/debug-93066.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-// RUN: %clang_cc1 -std=c++23 -fsyntax-only -verify %s
-
-struct S {
-  void f() {
-++this; // expected-error {{expression is not assignable}}
-// expected-note@-1 {{add '*' to dereference it}}
-  }
-
-  void g() const {
-++this; // expected-error {{expression is not assignable}}
-  }
-};
-
-void f(int* a, int* const b, const int* const c, __UINTPTR_TYPE__ d) {
-  // expected-note@-1 {{variable 'b' declared const here}}
-  // expected-note@-2 {{variable 'c' declared const here}}
-  (int*)d = 4; // expected-error {{assignment to cast is illegal, lvalue casts 
are not 

[clang] Revert "[clang] Fix-it hint for `++this` -> `++*this` when deref is modifiable" (PR #95833)

2024-06-18 Thread via cfe-commits

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


[clang] [llvm] [RISCV] Add processor definition for SpacemiT-X60 (PR #94564)

2024-06-18 Thread Craig Topper via cfe-commits

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


[clang] 89c26f6 - [analyzer][NFC] Reorganize Z3 report refutation

2024-06-18 Thread via cfe-commits

Author: Balazs Benics
Date: 2024-06-18T09:42:29+02:00
New Revision: 89c26f6c7b0a6dfa257ec090fcf5b6e6e0c89aab

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

LOG: [analyzer][NFC] Reorganize Z3 report refutation

This change keeps existing behavior, namely that if we hit a Z3 timeout
we will accept the report as "satisfiable".

This prepares for the commit "Harden safeguards for Z3 query times".
https://discourse.llvm.org/t/analyzer-rfc-taming-z3-query-times/79520

Reviewers: NagyDonat, haoNoQ, Xazax-hun, mikhailramalho, Szelethus

Reviewed By: NagyDonat

Pull Request: https://github.com/llvm/llvm-project/pull/95128

Added: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/Z3CrosscheckVisitor.h
clang/lib/StaticAnalyzer/Core/Z3CrosscheckVisitor.cpp
clang/test/Analysis/z3/crosscheck-statistics.c
clang/unittests/StaticAnalyzer/Z3CrosscheckOracleTest.cpp

Modified: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
clang/lib/StaticAnalyzer/Core/BugReporter.cpp
clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
clang/lib/StaticAnalyzer/Core/CMakeLists.txt
clang/unittests/StaticAnalyzer/CMakeLists.txt
llvm/include/llvm/Support/SMTAPI.h
llvm/lib/Support/Z3Solver.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h 
b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
index cc3d93aabafda..f97514955a591 100644
--- a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
+++ b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
@@ -597,29 +597,6 @@ class SuppressInlineDefensiveChecksVisitor final : public 
BugReporterVisitor {
PathSensitiveBugReport &BR) override;
 };
 
-/// The bug visitor will walk all the nodes in a path and collect all the
-/// constraints. When it reaches the root node, will create a refutation
-/// manager and check if the constraints are satisfiable
-class FalsePositiveRefutationBRVisitor final : public BugReporterVisitor {
-private:
-  /// Holds the constraints in a given path
-  ConstraintMap Constraints;
-
-public:
-  FalsePositiveRefutationBRVisitor();
-
-  void Profile(llvm::FoldingSetNodeID &ID) const override;
-
-  PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
-   BugReporterContext &BRC,
-   PathSensitiveBugReport &BR) override;
-
-  void finalizeVisitor(BugReporterContext &BRC, const ExplodedNode 
*EndPathNode,
-   PathSensitiveBugReport &BR) override;
-  void addConstraints(const ExplodedNode *N,
-  bool OverwriteConstraintsOnExistingSyms);
-};
-
 /// The visitor detects NoteTags and displays the event notes they contain.
 class TagVisitor : public BugReporterVisitor {
 public:

diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/BugReporter/Z3CrosscheckVisitor.h 
b/clang/include/clang/StaticAnalyzer/Core/BugReporter/Z3CrosscheckVisitor.h
new file mode 100644
index 0..9413fd739f607
--- /dev/null
+++ b/clang/include/clang/StaticAnalyzer/Core/BugReporter/Z3CrosscheckVisitor.h
@@ -0,0 +1,66 @@
+//===- Z3CrosscheckVisitor.h - Crosscheck reports with Z3 ---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines the visitor and utilities around it for Z3 report
+//  refutation.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_Z3CROSSCHECKVISITOR_H
+#define LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_Z3CROSSCHECKVISITOR_H
+
+#include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
+
+namespace clang::ento {
+
+/// The bug visitor will walk all the nodes in a path and collect all the
+/// constraints. When it reaches the root node, will create a refutation
+/// manager and check if the constraints are satisfiable.
+class Z3CrosscheckVisitor final : public BugReporterVisitor {
+public:
+  struct Z3Result {
+std::optional IsSAT = std::nullopt;
+  };
+  explicit Z3CrosscheckVisitor(Z3CrosscheckVisitor::Z3Result &Result);
+
+  void Profile(llvm::FoldingSetNodeID &ID) const override;
+
+  PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
+   BugReporterContext &BRC,
+   PathSensitiveBugRe

[clang] [llvm] [analyzer][NFC] Reorganize Z3 report refutation (PR #95128)

2024-06-18 Thread Balazs Benics via cfe-commits

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


[clang] [llvm] [RISCV] Add processor definition for SpacemiT-X60 (PR #94564)

2024-06-18 Thread Shao-Ce SUN via cfe-commits


@@ -381,3 +381,20 @@ def XIANGSHAN_NANHU : 
RISCVProcessorModel<"xiangshan-nanhu",
 TuneZExtHFusion,
 TuneZExtWFusion,
 TuneShiftedZExtWFusion]>;
+
+def SPACEMIT_X60 : RISCVProcessorModel<"spacemit-x60",
+   NoSchedModel,
+   !listconcat(RVA22S64Features,
+   [FeatureStdExtV,
+FeatureStdExtSscofpmf,
+FeatureStdExtSstc,
+FeatureStdExtSvnapot,
+FeatureStdExtZbc,
+FeatureStdExtZbkc,
+FeatureStdExtZfh,
+FeatureStdExtZicond,
+FeatureStdExtZmmul,

sunshaoce wrote:

Generated `"-target-feature" "-zmmul"` in `clang/test/Driver/riscv-cpus.c`.
It seems that M imply Zmmul is not supported yet.
https://github.com/llvm/llvm-project/pull/95070

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


[clang] [clang-format] Add option to remove leading blank lines (PR #91221)

2024-06-18 Thread Owen Pan via cfe-commits

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


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


[clang] [clang-format] Add option to remove leading blank lines (PR #91221)

2024-06-18 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Add option to remove leading blank lines (PR #91221)

2024-06-18 Thread Owen Pan via cfe-commits


@@ -21947,6 +21950,10 @@ TEST_F(FormatTest, HandlesUTF8BOM) {
   verifyFormat("\xef\xbb\xbf");
   verifyFormat("\xef\xbb\xbf#include ");
   verifyFormat("\xef\xbb\xbf\n#include ");
+  auto Style = getLLVMStyle();

owenca wrote:

Ditto.

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


[clang] [clang-format] Add option to remove leading blank lines (PR #91221)

2024-06-18 Thread Owen Pan via cfe-commits


@@ -45,6 +45,9 @@ TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
   verifyFormat("\nint i;", " \n\t \v \f  int i;");
   verifyFormat("int i;\nint j;", "int i; int j;");
   verifyFormat("int i;\nint j;", "int i;\n  int j;");
+  auto Style = getLLVMStyle();

owenca wrote:

An empty line before `auto Style = ...`?

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


[clang] [clang] Skip auto-init on scalar vars that have a non-constant Init and no self-ref (PR #94642)

2024-06-18 Thread Alexander Potapenko via cfe-commits


@@ -15,7 +15,7 @@ struct Foo {
 
 int foo(unsigned n) {
   bool var_size_1;
-  long var_size_8 = 123;

ramosian-glider wrote:

LGTM

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


[clang] [llvm] [analyzer] Harden safeguards for Z3 query times (PR #95129)

2024-06-18 Thread Balazs Benics via cfe-commits

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


[clang] [llvm] [analyzer] Harden safeguards for Z3 query times (PR #95129)

2024-06-18 Thread Balazs Benics via cfe-commits

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

>From 1b61e227a5ee3bf9646cbb7f1c1fca7490868dbf Mon Sep 17 00:00:00 2001
From: Balazs Benics 
Date: Tue, 11 Jun 2024 16:54:26 +0200
Subject: [PATCH 1/3] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20ch?=
 =?UTF-8?q?anges=20to=20main=20this=20commit=20is=20based=20on?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.4

[skip ci]
---
 .../Core/BugReporter/BugReporterVisitors.h|  23 
 .../Core/BugReporter/Z3CrosscheckVisitor.h|  66 ++
 .../Core/PathSensitive/SMTConstraintManager.h |   5 +-
 clang/lib/StaticAnalyzer/Core/BugReporter.cpp |  28 -
 .../Core/BugReporterVisitors.cpp  |  76 ---
 clang/lib/StaticAnalyzer/Core/CMakeLists.txt  |   1 +
 .../Core/Z3CrosscheckVisitor.cpp  | 118 ++
 .../test/Analysis/z3/crosscheck-statistics.c  |  33 +
 clang/unittests/StaticAnalyzer/CMakeLists.txt |   1 +
 .../StaticAnalyzer/Z3CrosscheckOracleTest.cpp |  59 +
 llvm/include/llvm/Support/SMTAPI.h|  19 +++
 llvm/lib/Support/Z3Solver.cpp | 103 ---
 12 files changed, 408 insertions(+), 124 deletions(-)
 create mode 100644 
clang/include/clang/StaticAnalyzer/Core/BugReporter/Z3CrosscheckVisitor.h
 create mode 100644 clang/lib/StaticAnalyzer/Core/Z3CrosscheckVisitor.cpp
 create mode 100644 clang/test/Analysis/z3/crosscheck-statistics.c
 create mode 100644 clang/unittests/StaticAnalyzer/Z3CrosscheckOracleTest.cpp

diff --git 
a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h 
b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
index cc3d93aabafda..f97514955a591 100644
--- a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
+++ b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
@@ -597,29 +597,6 @@ class SuppressInlineDefensiveChecksVisitor final : public 
BugReporterVisitor {
PathSensitiveBugReport &BR) override;
 };
 
-/// The bug visitor will walk all the nodes in a path and collect all the
-/// constraints. When it reaches the root node, will create a refutation
-/// manager and check if the constraints are satisfiable
-class FalsePositiveRefutationBRVisitor final : public BugReporterVisitor {
-private:
-  /// Holds the constraints in a given path
-  ConstraintMap Constraints;
-
-public:
-  FalsePositiveRefutationBRVisitor();
-
-  void Profile(llvm::FoldingSetNodeID &ID) const override;
-
-  PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
-   BugReporterContext &BRC,
-   PathSensitiveBugReport &BR) override;
-
-  void finalizeVisitor(BugReporterContext &BRC, const ExplodedNode 
*EndPathNode,
-   PathSensitiveBugReport &BR) override;
-  void addConstraints(const ExplodedNode *N,
-  bool OverwriteConstraintsOnExistingSyms);
-};
-
 /// The visitor detects NoteTags and displays the event notes they contain.
 class TagVisitor : public BugReporterVisitor {
 public:
diff --git 
a/clang/include/clang/StaticAnalyzer/Core/BugReporter/Z3CrosscheckVisitor.h 
b/clang/include/clang/StaticAnalyzer/Core/BugReporter/Z3CrosscheckVisitor.h
new file mode 100644
index 0..3ec59e3037363
--- /dev/null
+++ b/clang/include/clang/StaticAnalyzer/Core/BugReporter/Z3CrosscheckVisitor.h
@@ -0,0 +1,66 @@
+//===- Z3CrosscheckVisitor.h - Crosscheck reports with Z3 ---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines the visitor and utilities around it for Z3 report
+//  refutation.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_Z3CROSSCHECKVISITOR_H
+#define LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_Z3CROSSCHECKVISITOR_H
+
+#include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
+
+namespace clang::ento {
+
+/// The bug visitor will walk all the nodes in a path and collect all the
+/// constraints. When it reaches the root node, will create a refutation
+/// manager and check if the constraints are satisfiable.
+class Z3CrosscheckVisitor final : public BugReporterVisitor {
+public:
+  struct Z3Result {
+std::optional IsSAT = std::nullopt;
+  };
+  explicit Z3CrosscheckVisitor(Z3CrosscheckVisitor::Z3Result &Result);
+
+  void Profile(llvm::FoldingSetNodeID &ID) const override;
+
+  PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
+   BugReporterContext &BRC,
+   Pa

[clang] eacc3b3 - [analyzer] Harden safeguards for Z3 query times

2024-06-18 Thread via cfe-commits

Author: Balazs Benics
Date: 2024-06-18T09:48:22+02:00
New Revision: eacc3b3504be061f7334410dd0eb599688ba103a

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

LOG: [analyzer] Harden safeguards for Z3 query times

This patch is a functional change.
https://discourse.llvm.org/t/analyzer-rfc-taming-z3-query-times/79520

As a result of this patch, individual Z3 queries in refutation will be
bound by 300ms. Every report equivalence class will be processed in
at most 1 second.

The heuristic should have only really marginal observable impact -
except for the cases when we had big report eqclasses with long-running
(15s) Z3 queries, where previously CSA effectively halted.
After this patch, CSA will tackle such extreme cases as well.

Reviewers: NagyDonat, haoNoQ, Xazax-hun, Szelethus, mikhailramalho

Reviewed By: NagyDonat

Pull Request: https://github.com/llvm/llvm-project/pull/95129

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
clang/include/clang/StaticAnalyzer/Core/BugReporter/Z3CrosscheckVisitor.h
clang/lib/StaticAnalyzer/Core/BugReporter.cpp
clang/lib/StaticAnalyzer/Core/Z3CrosscheckVisitor.cpp
clang/test/Analysis/analyzer-config.c
clang/unittests/StaticAnalyzer/Z3CrosscheckOracleTest.cpp

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def 
b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
index f008c9c581d95..29aa6a3b8a16e 100644
--- a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
+++ b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
@@ -184,6 +184,26 @@ ANALYZER_OPTION(bool, ShouldCrosscheckWithZ3, 
"crosscheck-with-z3",
 "constraint manager backend.",
 false)
 
+ANALYZER_OPTION(
+unsigned, Z3CrosscheckEQClassTimeoutThreshold,
+"crosscheck-with-z3-eqclass-timeout-threshold",
+"Set a timeout for bug report equivalence classes in milliseconds. "
+"If we exhaust this threshold, we will drop the bug report eqclass "
+"instead of doing more Z3 queries. Set 0 for no timeout.", 700)
+
+ANALYZER_OPTION(
+unsigned, Z3CrosscheckTimeoutThreshold,
+"crosscheck-with-z3-timeout-threshold",
+"Set a timeout for individual Z3 queries in milliseconds. "
+"Set 0 for no timeout.", 300)
+
+ANALYZER_OPTION(
+unsigned, Z3CrosscheckRLimitThreshold,
+"crosscheck-with-z3-rlimit-threshold",
+"Set the Z3 resource limit threshold. This sets a deterministic cutoff "
+"point for Z3 queries, as longer queries usually consume more resources. "
+"Set 0 for unlimited.", 400'000)
+
 ANALYZER_OPTION(bool, ShouldReportIssuesInMainSourceFile,
 "report-in-main-source-file",
 "Whether or not the diagnostic report should be always "

diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/BugReporter/Z3CrosscheckVisitor.h 
b/clang/include/clang/StaticAnalyzer/Core/BugReporter/Z3CrosscheckVisitor.h
index 9413fd739f607..439f37fa8604f 100644
--- a/clang/include/clang/StaticAnalyzer/Core/BugReporter/Z3CrosscheckVisitor.h
+++ b/clang/include/clang/StaticAnalyzer/Core/BugReporter/Z3CrosscheckVisitor.h
@@ -25,8 +25,11 @@ class Z3CrosscheckVisitor final : public BugReporterVisitor {
 public:
   struct Z3Result {
 std::optional IsSAT = std::nullopt;
+unsigned Z3QueryTimeMilliseconds = 0;
+unsigned UsedRLimit = 0;
   };
-  explicit Z3CrosscheckVisitor(Z3CrosscheckVisitor::Z3Result &Result);
+  Z3CrosscheckVisitor(Z3CrosscheckVisitor::Z3Result &Result,
+  const AnalyzerOptions &Opts);
 
   void Profile(llvm::FoldingSetNodeID &ID) const override;
 
@@ -44,21 +47,44 @@ class Z3CrosscheckVisitor final : public BugReporterVisitor 
{
   /// Holds the constraints in a given path.
   ConstraintMap Constraints;
   Z3Result &Result;
+  const AnalyzerOptions &Opts;
 };
 
 /// The oracle will decide if a report should be accepted or rejected based on
-/// the results of the Z3 solver.
+/// the results of the Z3 solver and the statistics of the queries of a report
+/// equivalenece class.
 class Z3CrosscheckOracle {
 public:
+  explicit Z3CrosscheckOracle(const AnalyzerOptions &Opts) : Opts(Opts) {}
+
   enum Z3Decision {
-AcceptReport, // The report was SAT.
-RejectReport, // The report was UNSAT or UNDEF.
+AcceptReport,  // The report was SAT.
+RejectReport,  // The report was UNSAT or UNDEF.
+RejectEQClass, // The heuristic suggests to skip the current eqclass.
   };
 
-  /// Makes a decision for accepting or rejecting the report based on the
-  /// result of the corresponding Z3 query.
-  static Z3Decision
-  interpretQueryResult(const Z3CrosscheckVisitor::Z3Result &Query);
+  /// Updates the internal state with the new Z3Result and makes 

[clang] [llvm] [analyzer] Harden safeguards for Z3 query times (PR #95129)

2024-06-18 Thread Balazs Benics via cfe-commits

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


[clang] Revert "[X86] Add support for MS inp functions." (PR #95890)

2024-06-18 Thread Shengchen Kan via cfe-commits

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

LGTM

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


[clang] [analyzer] Add an ownership change visitor to StreamChecker (PR #94957)

2024-06-18 Thread Kristóf Umann via cfe-commits


@@ -696,6 +730,69 @@ struct StreamOperationEvaluator {
 
 } // end anonymous namespace
 
+//===--===//
+// Definition of NoStreamStateChangeVisitor.
+//===--===//
+
+namespace {
+class NoStreamStateChangeVisitor final : public NoOwnershipChangeVisitor {
+protected:
+  /// Syntactically checks whether the callee is a freeing function. Since
+  /// we have no path-sensitive information on this call (we would need a
+  /// CallEvent instead of a CallExpr for that), its possible that a
+  /// freeing function was called indirectly through a function pointer,
+  /// but we are not able to tell, so this is a best effort analysis.
+  bool isFreeingCallAsWritten(const CallExpr &Call) const {
+const auto *StreamChk = static_cast(&Checker);
+if (StreamChk->FCloseDesc.matchesAsWritten(Call))
+  return true;
+
+return false;

Szelethus wrote:

The retionale behind not inlining this is that we could add more functions that 
could close the stream (annotations, maybe). The checker object is owned by the 
base class, so the static cast is necessary.

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


[clang-tools-extra] [llvm] [llvm] Remove the Legacy PM Hello example (PR #95708)

2024-06-18 Thread Andrzej Warzyński via cfe-commits

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


[clang-tools-extra] 8b0d38b - [llvm] Remove the Legacy PM Hello example (#95708)

2024-06-18 Thread via cfe-commits

Author: Andrzej Warzyński
Date: 2024-06-18T09:01:56+01:00
New Revision: 8b0d38be9ece414dbc7a91dbd8fa506b0e3287e7

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

LOG: [llvm] Remove the Legacy PM Hello example (#95708)

The Legacy PM was deprecated for the optimization pipeline in LLVM 14
[1] (the support was removed altogether in the following release). This
patch removes the original Hello example that was introduced to
illustrate the Legacy PM. The Hello example no longer works and hence is
deleted. The corresponding documentation is also removed.

Note, Hello example for the new PM is located in
  * llvm/lib/Transforms/Utils/HelloWorld.cpp
  
and documented in
  * WritingAnLLVMNewPMPass.rst.

[1]
https://releases.llvm.org/14.0.0/docs/ReleaseNotes.html#changes-to-the-llvm-ir

Added: 


Modified: 
clang-tools-extra/test/CMakeLists.txt
clang-tools-extra/test/clang-tidy/CTTestTidyModule.cpp
llvm/docs/WritingAnLLVMPass.rst
llvm/lib/Transforms/CMakeLists.txt
llvm/test/CMakeLists.txt

Removed: 
llvm/lib/Transforms/Hello/CMakeLists.txt
llvm/lib/Transforms/Hello/Hello.cpp
llvm/lib/Transforms/Hello/Hello.exports



diff  --git a/clang-tools-extra/test/CMakeLists.txt 
b/clang-tools-extra/test/CMakeLists.txt
index 50546f62259ca..0953ff2531e1a 100644
--- a/clang-tools-extra/test/CMakeLists.txt
+++ b/clang-tools-extra/test/CMakeLists.txt
@@ -74,17 +74,8 @@ if (NOT WIN32 OR NOT LLVM_LINK_LLVM_DYLIB)
   PLUGIN_TOOL clang-tidy)
 endif()
 
-if(CLANG_BUILT_STANDALONE)
-  # LLVMHello library is needed below
-  if (EXISTS ${LLVM_MAIN_SRC_DIR}/lib/Transforms/Hello
-  AND NOT TARGET LLVMHello)
-add_subdirectory(${LLVM_MAIN_SRC_DIR}/lib/Transforms/Hello
-  lib/Transforms/Hello)
-  endif()
-endif()
-
 if(TARGET CTTestTidyModule)
-list(APPEND CLANG_TOOLS_TEST_DEPS CTTestTidyModule LLVMHello)
+list(APPEND CLANG_TOOLS_TEST_DEPS CTTestTidyModule)
 target_include_directories(CTTestTidyModule PUBLIC BEFORE 
"${CLANG_TOOLS_SOURCE_DIR}")
 if(CLANG_PLUGIN_SUPPORT AND (WIN32 OR CYGWIN))
   set(LLVM_LINK_COMPONENTS

diff  --git a/clang-tools-extra/test/clang-tidy/CTTestTidyModule.cpp 
b/clang-tools-extra/test/clang-tidy/CTTestTidyModule.cpp
index c66a94f458cf5..19ea46d9b3ded 100644
--- a/clang-tools-extra/test/clang-tidy/CTTestTidyModule.cpp
+++ b/clang-tools-extra/test/clang-tidy/CTTestTidyModule.cpp
@@ -1,5 +1,5 @@
 // REQUIRES: plugins
-// RUN: clang-tidy -checks='-*,mytest*' --list-checks -load 
%llvmshlibdir/CTTestTidyModule%pluginext -load 
%llvmshlibdir/LLVMHello%pluginext | FileCheck --check-prefix=CHECK-LIST %s
+// RUN: clang-tidy -checks='-*,mytest*' --list-checks -load 
%llvmshlibdir/CTTestTidyModule%pluginext | FileCheck --check-prefix=CHECK-LIST 
%s
 // CHECK-LIST: Enabled checks:
 // CHECK-LIST-NEXT:mytest1
 // CHECK-LIST-NEXT:mytest2

diff  --git a/llvm/docs/WritingAnLLVMPass.rst b/llvm/docs/WritingAnLLVMPass.rst
index a3602e7fbc31f..2b5809827f757 100644
--- a/llvm/docs/WritingAnLLVMPass.rst
+++ b/llvm/docs/WritingAnLLVMPass.rst
@@ -37,290 +37,14 @@ passes.  One of the main features of the LLVM Pass 
Framework is that it
 schedules passes to run in an efficient way based on the constraints that your
 pass meets (which are indicated by which class they derive from).
 
-We start by showing you how to construct a pass, everything from setting up the
-code, to compiling, loading, and executing it.  After the basics are down, more
-advanced features are discussed.
-
-Quick Start --- Writing hello world
-===
-
-Here we describe how to write the "hello world" of passes.  The "Hello" pass is
-designed to simply print out the name of non-external functions that exist in
-the program being compiled.  It does not modify the program at all, it just
-inspects it.  The source code and files for this pass are available in the LLVM
-source tree in the ``lib/Transforms/Hello`` directory.
-
-.. _writing-an-llvm-pass-makefile:
-
-Setting up the build environment
-
-
-First, configure and build LLVM.  Next, you need to create a new directory
-somewhere in the LLVM source base.  For this example, we'll assume that you
-made ``lib/Transforms/Hello``.  Finally, you must set up a build script
-that will compile the source code for the new pass.  To do this,
-copy the following into ``CMakeLists.txt``:
-
-.. code-block:: cmake
-
-  add_llvm_library( LLVMHello MODULE
-Hello.cpp
-
-PLUGIN_TOOL
-opt
-)
-
-and the following line into ``lib/Transforms/CMakeLists.txt``:
-
-.. code-block:: cmake
-
-  add_subdirectory(Hello)
-
-(Note that there is already a directory named ``Hello`` with a sample "Hello"
-pass; you may play with it -- in which case you don't need to modify any
-``C

[clang-tools-extra] [llvm] [llvm] Remove the Legacy PM Hello example (PR #95708)

2024-06-18 Thread Andrzej Warzyński via cfe-commits

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


[clang] [clang] Fix-it hint for `++this` -> `++*this` when deref is modifiable (PR #94159)

2024-06-18 Thread Rajveer Singh Bharadwaj via cfe-commits

Rajveer100 wrote:

@Sirraide @zygoloid 
Can I be of any help to improve this?


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


[clang-tools-extra] [clang-tidy] Add `bugprone-pointer-arithmetic-on-polymorphic-object` check (PR #91951)

2024-06-18 Thread via cfe-commits

https://github.com/Discookie updated 
https://github.com/llvm/llvm-project/pull/91951

>From 69cbd3da19eb0f8eb6758782b46daf99b5b79ea4 Mon Sep 17 00:00:00 2001
From: Viktor 
Date: Mon, 6 May 2024 06:11:58 +
Subject: [PATCH 01/15] Add `bugprone-virtual-arithmetic` check

Finds pointer arithmetic on classes that declare a virtual function.
---
 .../bugprone/BugproneTidyModule.cpp   |  3 ++
 .../clang-tidy/bugprone/CMakeLists.txt|  1 +
 .../bugprone/VirtualArithmeticCheck.cpp   | 46 +
 .../bugprone/VirtualArithmeticCheck.h | 30 +++
 .../checks/bugprone/virtual-arithmetic.rst| 50 +++
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../checkers/bugprone/virtual-arithmetic.cpp  | 45 +
 7 files changed, 176 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/VirtualArithmeticCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/VirtualArithmeticCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/virtual-arithmetic.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/virtual-arithmetic.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 1b92d2e60cc17..813f6720074ae 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -91,6 +91,7 @@
 #include "UnusedRaiiCheck.h"
 #include "UnusedReturnValueCheck.h"
 #include "UseAfterMoveCheck.h"
+#include "VirtualArithmeticCheck.h"
 #include "VirtualNearMissCheck.h"
 
 namespace clang::tidy {
@@ -254,6 +255,8 @@ class BugproneModule : public ClangTidyModule {
 CheckFactories.registerCheck(
 "bugprone-unused-return-value");
 CheckFactories.registerCheck("bugprone-use-after-move");
+CheckFactories.registerCheck(
+"bugprone-virtual-arithmetic");
 CheckFactories.registerCheck(
 "bugprone-virtual-near-miss");
   }
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index 2d303191f8865..ec1f3231e7990 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -87,6 +87,7 @@ add_clang_library(clangTidyBugproneModule
   UnusedRaiiCheck.cpp
   UnusedReturnValueCheck.cpp
   UseAfterMoveCheck.cpp
+  VirtualArithmeticCheck.cpp
   VirtualNearMissCheck.cpp
 
   LINK_LIBS
diff --git a/clang-tools-extra/clang-tidy/bugprone/VirtualArithmeticCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/VirtualArithmeticCheck.cpp
new file mode 100644
index 0..57347af2b5881
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/VirtualArithmeticCheck.cpp
@@ -0,0 +1,46 @@
+//===--- VirtualArithmeticCheck.cpp - 
clang-tidy---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "VirtualArithmeticCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+void VirtualArithmeticCheck::registerMatchers(MatchFinder *Finder) {
+  const auto PointerExprWithVirtualMethod =
+  expr(hasType(pointerType(pointee(hasDeclaration(
+   cxxRecordDecl(hasMethod(isVirtualAsWritten(
+  .bind("pointer");
+
+  const auto ArraySubscript =
+  arraySubscriptExpr(hasBase(PointerExprWithVirtualMethod));
+
+  const auto BinaryOperators =
+  binaryOperator(hasAnyOperatorName("+", "-", "+=", "-="),
+ hasEitherOperand(PointerExprWithVirtualMethod));
+
+  const auto UnaryOperators =
+  unaryOperator(hasAnyOperatorName("++", "--"),
+hasUnaryOperand(PointerExprWithVirtualMethod));
+
+  Finder->addMatcher(
+  expr(anyOf(ArraySubscript, BinaryOperators, UnaryOperators)), this);
+}
+
+void VirtualArithmeticCheck::check(const MatchFinder::MatchResult &Result) {
+  const auto *PointerExpr = Result.Nodes.getNodeAs("pointer");
+
+  diag(PointerExpr->getBeginLoc(),
+   "pointer arithmetic on class that declares a virtual function, "
+   "undefined behavior if the pointee is a different class");
+}
+
+} // namespace clang::tidy::bugprone
diff --git a/clang-tools-extra/clang-tidy/bugprone/VirtualArithmeticCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/VirtualArithmeticCheck.h
new file mode 100644
index 0..6a5f86a391747
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/VirtualArithmeticCheck.h
@@ -0,0 +1,30 @@
+//===--- VirtualArithmeticCheck.h - clang-tidy---*- C++ 
-*-===//
+//
+/

[clang] [analyzer] Add an ownership change visitor to StreamChecker (PR #94957)

2024-06-18 Thread Kristóf Umann via cfe-commits


@@ -696,6 +730,69 @@ struct StreamOperationEvaluator {
 
 } // end anonymous namespace
 
+//===--===//
+// Definition of NoStreamStateChangeVisitor.
+//===--===//
+
+namespace {
+class NoStreamStateChangeVisitor final : public NoOwnershipChangeVisitor {
+protected:
+  /// Syntactically checks whether the callee is a freeing function. Since
+  /// we have no path-sensitive information on this call (we would need a
+  /// CallEvent instead of a CallExpr for that), its possible that a
+  /// freeing function was called indirectly through a function pointer,
+  /// but we are not able to tell, so this is a best effort analysis.
+  bool isFreeingCallAsWritten(const CallExpr &Call) const {
+const auto *StreamChk = static_cast(&Checker);
+if (StreamChk->FCloseDesc.matchesAsWritten(Call))
+  return true;
+
+return false;
+  }
+
+  bool doesFnIntendToHandleOwnership(const Decl *Callee,
+ ASTContext &ACtx) override {
+using namespace clang::ast_matchers;
+const FunctionDecl *FD = dyn_cast(Callee);
+
+auto Matches =
+match(findAll(callExpr().bind("call")), *FD->getBody(), ACtx);
+for (BoundNodes Match : Matches) {
+  if (const auto *Call = Match.getNodeAs("call"))
+if (isFreeingCallAsWritten(*Call))
+  return true;
+}
+// TODO: Ownership might change with an attempt to store stream object, not
+// only through freeing it. Check for attempted stores as well.
+return false;
+  }
+
+  virtual bool hasResourceStateChanged(ProgramStateRef CallEnterState,
+   ProgramStateRef CallExitEndState) final 
{
+return CallEnterState->get(Sym) !=
+   CallExitEndState->get(Sym);
+  }
+
+  PathDiagnosticPieceRef emitNote(const ExplodedNode *N) override {
+PathDiagnosticLocation L = PathDiagnosticLocation::create(
+N->getLocation(),
+N->getState()->getStateManager().getContext().getSourceManager());
+return std::make_shared(
+L, "Returning without freeing stream object or storing it for later "
+   "release");
+  }
+
+public:
+  NoStreamStateChangeVisitor(SymbolRef Sym, const StreamChecker *Checker)
+  : NoOwnershipChangeVisitor(Sym, Checker) {}

Szelethus wrote:

It doesn't seem possible, and definitely not worth the trouble.

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


[clang] [llvm] Update ReleaseNotes for MC/DC changes. (PR #95887)

2024-06-18 Thread via cfe-commits

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


[clang] [llvm] Update ReleaseNotes for MC/DC changes. (PR #95887)

2024-06-18 Thread via cfe-commits

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

Looks good to me, I just noticed some minor things.
Thanks for writing release notes!

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


[clang] [llvm] Update ReleaseNotes for MC/DC changes. (PR #95887)

2024-06-18 Thread via cfe-commits


@@ -586,6 +586,20 @@ Improvements to Clang's time-trace
 - Clang now specifies that using ``auto`` in a lambda parameter is a C++14 
extension when
   appropriate. (`#46059: 
`_).
 
+Improvements to Coverage mapping

zmodem wrote:

nit: capital m?

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


[clang] [llvm] Update ReleaseNotes for MC/DC changes. (PR #95887)

2024-06-18 Thread via cfe-commits


@@ -586,6 +586,20 @@ Improvements to Clang's time-trace
 - Clang now specifies that using ``auto`` in a lambda parameter is a C++14 
extension when
   appropriate. (`#46059: 
`_).
 
+Improvements to Coverage mapping
+
+
+- Macros defined in system headers are not expanded in coverage
+  mapping. Conditional expressions in system header macros are no
+  longer taken into account for branch coverage. They can be included
+  with ``-mllvm -system-headers-coverage``. (#78920)
+- MC/DC coverage has been improved. (#82448)
+  - The maximum number of conditions is no longer limited to 6. See
+`this ` for
+more details.
+  - The format of profraw generated by the runtime is not backwards

zmodem wrote:

I don't understand this one. Was it backwards compatible before?

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


[clang] [llvm] Update ReleaseNotes for MC/DC changes. (PR #95887)

2024-06-18 Thread via cfe-commits


@@ -586,6 +586,20 @@ Improvements to Clang's time-trace
 - Clang now specifies that using ``auto`` in a lambda parameter is a C++14 
extension when
   appropriate. (`#46059: 
`_).
 
+Improvements to Coverage mapping
+
+
+- Macros defined in system headers are not expanded in coverage
+  mapping. Conditional expressions in system header macros are no
+  longer taken into account for branch coverage. They can be included
+  with ``-mllvm -system-headers-coverage``. (#78920)

zmodem wrote:

I don't think the PR/issue number will get linked automatically, so it's better 
to do it explicitly (see e.g. 46059 above).

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


[clang] [analyzer] Add an ownership change visitor to StreamChecker (PR #94957)

2024-06-18 Thread Kristóf Umann via cfe-commits

https://github.com/Szelethus updated 
https://github.com/llvm/llvm-project/pull/94957

From faf00d0e1286e053ba9fb457513bd8309eb541ed Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Krist=C3=B3f=20Umann?= 
Date: Fri, 7 Jun 2024 12:07:35 +0200
Subject: [PATCH 1/5] [analyzer] Add an ownership change visitor to
 StreamChecker

This is very similar to https://reviews.llvm.org/D105553, in fact, I
barely made any changes from MallocChecker's ownership visitor to this
one.

The new visitor emits a diagnostic note for function where a change in
stream ownership was expected (for example, it had a fclose() call), but
the ownership remained unchanged. This is similar to messages regarding
ordinary values ("Returning without writing to x").

Change-Id: I7621c178dd35713d860d27bfc644fb56a42b0946
---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 106 ++-
 clang/test/Analysis/stream-visitor.cpp| 179 ++
 2 files changed, 282 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/Analysis/stream-visitor.cpp

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index d4e020f7a72a0..d726ab5eaa599 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -10,6 +10,9 @@
 //
 
//===--===//
 
+#include "NoOwnershipChangeVisitor.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
@@ -74,6 +77,12 @@ struct StreamErrorState {
   /// Returns if the StreamErrorState is a valid object.
   operator bool() const { return NoError || FEof || FError; }
 
+  LLVM_DUMP_METHOD void dump() const { dumpToStream(llvm::errs()); }
+  LLVM_DUMP_METHOD void dumpToStream(llvm::raw_ostream &os) const {
+os << "NoError: " << NoError << ", FEof: " << FEof
+   << ", FError: " << FError;
+  }
+
   void Profile(llvm::FoldingSetNodeID &ID) const {
 ID.AddBoolean(NoError);
 ID.AddBoolean(FEof);
@@ -98,6 +107,19 @@ struct StreamState {
 OpenFailed /// The last open operation has failed.
   } State;
 
+  StringRef getKindStr() const {
+switch (State) {
+case Opened:
+  return "Opened";
+case Closed:
+  return "Closed";
+case OpenFailed:
+  return "OpenFailed";
+default:
+  llvm_unreachable("Unknown StreamState!");
+}
+  }
+
   /// State of the error flags.
   /// Ignored in non-opened stream state but must be NoError.
   StreamErrorState const ErrorState;
@@ -146,6 +168,9 @@ struct StreamState {
 return StreamState{L, OpenFailed, {}, false};
   }
 
+  LLVM_DUMP_METHOD void dump() const { dumpToStream(llvm::errs()); }
+  LLVM_DUMP_METHOD void dumpToStream(llvm::raw_ostream &os) const;
+
   void Profile(llvm::FoldingSetNodeID &ID) const {
 ID.AddPointer(LastOperation);
 ID.AddInteger(State);
@@ -168,8 +193,9 @@ REGISTER_MAP_WITH_PROGRAMSTATE(StreamMap, SymbolRef, 
StreamState)
 namespace {
 
 class StreamChecker;
-using FnCheck = std::function;
+using FnCheckTy = void(const StreamChecker *, const FnDescription *,
+   const CallEvent &, CheckerContext &);
+using FnCheck = std::function;
 
 using ArgNoTy = unsigned int;
 static const ArgNoTy ArgNone = std::numeric_limits::max();
@@ -183,6 +209,14 @@ struct FnDescription {
   ArgNoTy StreamArgNo;
 };
 
+LLVM_DUMP_METHOD void StreamState::dumpToStream(llvm::raw_ostream &os) const {
+  os << "{Kind: " << getKindStr() << ", Last operation: " << LastOperation
+ << ", ErrorState: ";
+  ErrorState.dumpToStream(os);
+  os << ", FilePos: " << (FilePositionIndeterminate ? "Indeterminate" : "OK")
+ << '}';
+}
+
 /// Get the value of the stream argument out of the passed call event.
 /// The call should contain a function that is described by Desc.
 SVal getStreamArg(const FnDescription *Desc, const CallEvent &Call) {
@@ -300,6 +334,8 @@ class StreamChecker : public Checker FnDescriptions = {
   {{CDM::CLibrary, {"fopen"}, 2},
@@ -310,7 +346,7 @@ class StreamChecker : public Checker(&Checker);
+if (StreamChk->FCloseDesc.matchesAsWritten(Call))
+  return true;
+
+return false;
+  }
+
+  bool doesFnIntendToHandleOwnership(const Decl *Callee,
+ ASTContext &ACtx) override {
+using namespace clang::ast_matchers;
+const FunctionDecl *FD = dyn_cast(Callee);
+
+auto Matches =
+match(findAll(callExpr().bind("call")), *FD->getBody(), ACtx);
+for (BoundNodes Match : Matches) {
+  if (const auto *Call = Match.getNodeAs("call"))
+if (isFreeingCallAsWritten(*Call))
+  return true;
+}
+// TODO: Ownership might change with an attempt to store stream object, not
+// only through

[clang] [analyzer] Add an ownership change visitor to StreamChecker (PR #94957)

2024-06-18 Thread Kristóf Umann via cfe-commits

Szelethus wrote:

> I did not find a similar test for `MallocChecker` but there could be one with 
> similar test functions.

I'm not sure what tests you are referring to. I did fix your other observations.

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


[clang] [analyzer] Add an ownership change visitor to StreamChecker (PR #94957)

2024-06-18 Thread Kristóf Umann via cfe-commits


@@ -696,6 +730,69 @@ struct StreamOperationEvaluator {
 
 } // end anonymous namespace
 
+//===--===//
+// Definition of NoStreamStateChangeVisitor.
+//===--===//
+
+namespace {
+class NoStreamStateChangeVisitor final : public NoOwnershipChangeVisitor {
+protected:
+  /// Syntactically checks whether the callee is a freeing function. Since
+  /// we have no path-sensitive information on this call (we would need a
+  /// CallEvent instead of a CallExpr for that), its possible that a
+  /// freeing function was called indirectly through a function pointer,
+  /// but we are not able to tell, so this is a best effort analysis.
+  bool isFreeingCallAsWritten(const CallExpr &Call) const {
+const auto *StreamChk = static_cast(&Checker);
+if (StreamChk->FCloseDesc.matchesAsWritten(Call))
+  return true;
+
+return false;
+  }
+
+  bool doesFnIntendToHandleOwnership(const Decl *Callee,
+ ASTContext &ACtx) override {
+using namespace clang::ast_matchers;
+const FunctionDecl *FD = dyn_cast(Callee);
+
+auto Matches =
+match(findAll(callExpr().bind("call")), *FD->getBody(), ACtx);
+for (BoundNodes Match : Matches) {
+  if (const auto *Call = Match.getNodeAs("call"))
+if (isFreeingCallAsWritten(*Call))
+  return true;
+}

Szelethus wrote:

Showing that a function intended to close a stream already relies on 
heuristics, and its easy to construct dumb counterexamples for it:

```c++
void absolutelyDoesntCloseItsParam(FILE *p) {
  if (coin()) {
FILE *q = fopen(...);
fclose(q); // oh, we saw an fclose, this must've been intended for the 
param...
  }
}
```
We can surely make this smarter, maybe we should, but in finite steps we get to 
the point where we start rewriting the analyzer.

Regarding the CallGraph: if we start to wander of the beaten path (meaning the 
path of execution the analyzer was on), especially if we inspect non-trivial 
functions in the graph, that will lead to a weaker heuristic in my view. 

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


[clang] [Clang] [WIP] Added builtin_alloca support for OpenCL1.2 and below (PR #95750)

2024-06-18 Thread Vikash Gupta via cfe-commits

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


[clang] [Serialization] Use specialized decl hash function for GlobalDeclID (PR #95730)

2024-06-18 Thread Ilya Biryukov via cfe-commits

https://github.com/ilya-biryukov approved this pull request.

LGTM, thanks!

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


[clang] [llvm] Reland "[AArch64] Decouple feature dependency expansion. (#94279)" (PR #95519)

2024-06-18 Thread Tomas Matheson via cfe-commits

https://github.com/tmatheson-arm approved this pull request.

LGTM

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


[clang] [llvm] [SPIRV][HLSL] Add lowering of `rsqrt` to SPIRV (PR #95849)

2024-06-18 Thread Nathan Gauër via cfe-commits

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

Thanks!

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


[clang] [llvm] [RISCV] Add processor definition for SpacemiT-X60 (PR #94564)

2024-06-18 Thread Shao-Ce SUN via cfe-commits

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

>From 363e29385277c049bc91a86e76ff6f6ae70ceaa9 Mon Sep 17 00:00:00 2001
From: Shao-Ce SUN 
Date: Thu, 6 Jun 2024 12:05:33 +0800
Subject: [PATCH 1/8] [RISCV] Add processor definition for Spacemit-K1

---
 clang/test/Driver/riscv-cpus.c| 12 ++
 clang/test/Misc/target-invalid-cpu-note.c |  4 ++--
 llvm/lib/Target/RISCV/RISCVProcessors.td  | 29 +++
 3 files changed, 43 insertions(+), 2 deletions(-)

diff --git a/clang/test/Driver/riscv-cpus.c b/clang/test/Driver/riscv-cpus.c
index ff2bd6f7c8ba3..32d7910ab4daa 100644
--- a/clang/test/Driver/riscv-cpus.c
+++ b/clang/test/Driver/riscv-cpus.c
@@ -31,6 +31,18 @@
 // MCPU-XIANGSHAN-NANHU-SAME: "-target-feature" "+zks" "-target-feature" 
"+zksed" "-target-feature" "+zksh" "-target-feature" "+svinval"
 // MCPU-XIANGSHAN-NANHU-SAME: "-target-abi" "lp64d"
 
+// RUN: %clang --target=riscv64 -### -c %s 2>&1 -mcpu=spacemit-k1 | FileCheck 
-check-prefix=MCPU-SPACEMIT-K1 %s
+// MCPU-SPACEMIT-K1: "-nostdsysteminc" "-target-cpu" "spacemit-k1"
+// MCPU-SPACEMIT-K1-SAME: "-target-feature" "+m" "-target-feature" "+a" 
"-target-feature" "+f" "-target-feature" "+d"
+// MCPU-SPACEMIT-K1-SAME: "-target-feature" "+c" "-target-feature" "+v" 
"-target-feature" "+zicond" "-target-feature" "+zicsr"
+// MCPU-SPACEMIT-K1-SAME: "-target-feature" "+zifencei" "-target-feature" 
"+zmmul" "-target-feature" "+zfh"
+// MCPU-SPACEMIT-K1-SAME: "-target-feature" "+zfhmin" "-target-feature" "+zba" 
"-target-feature" "+zbb" "-target-feature" "+zbc"
+// MCPU-SPACEMIT-K1-SAME: "-target-feature" "+zbkb" "-target-feature" "+zbkc" 
"-target-feature" "+zbs" "-target-feature" "+zve32f"
+// MCPU-SPACEMIT-K1-SAME: "-target-feature" "+zve32x" "-target-feature" 
"+zve64d" "-target-feature" "+zve64f" "-target-feature" "+zve64x"
+// MCPU-SPACEMIT-K1-SAME: "-target-feature" "+zvfh" "-target-feature" 
"+zvfhmin"
+// MCPU-SPACEMIT-K1-SAME: "-target-feature" "+zvl128b" "-target-feature" 
"+zvl256b" "-target-feature" "+zvl32b" "-target-feature" "+zvl64b"
+// MCPU-SPACEMIT-K1-SAME: "-target-abi" "lp64d"
+
 // We cannot check much for -mcpu=native, but it should be replaced by a valid 
CPU string.
 // RUN: %clang --target=riscv64 -### -c %s -mcpu=native 2> %t.err || true
 // RUN: FileCheck --input-file=%t.err -check-prefix=MCPU-NATIVE %s
diff --git a/clang/test/Misc/target-invalid-cpu-note.c 
b/clang/test/Misc/target-invalid-cpu-note.c
index 6558fd753d1d1..04e92360fe665 100644
--- a/clang/test/Misc/target-invalid-cpu-note.c
+++ b/clang/test/Misc/target-invalid-cpu-note.c
@@ -85,7 +85,7 @@
 
 // RUN: not %clang_cc1 -triple riscv64 -target-cpu not-a-cpu -fsyntax-only %s 
2>&1 | FileCheck %s --check-prefix RISCV64
 // RISCV64: error: unknown target CPU 'not-a-cpu'
-// RISCV64-NEXT: note: valid target CPU values are: generic-rv64, rocket-rv64, 
sifive-p450, sifive-p670, sifive-s21, sifive-s51, sifive-s54, sifive-s76, 
sifive-u54, sifive-u74, sifive-x280, veyron-v1, xiangshan-nanhu{{$}}
+// RISCV64-NEXT: note: valid target CPU values are: generic-rv64, rocket-rv64, 
sifive-p450, sifive-p670, sifive-s21, sifive-s51, sifive-s54, sifive-s76, 
sifive-u54, sifive-u74, sifive-x280, spacemit-k1, veyron-v1, 
xiangshan-nanhu{{$}}
 
 // RUN: not %clang_cc1 -triple riscv32 -tune-cpu not-a-cpu -fsyntax-only %s 
2>&1 | FileCheck %s --check-prefix TUNE-RISCV32
 // TUNE-RISCV32: error: unknown target CPU 'not-a-cpu'
@@ -93,4 +93,4 @@
 
 // RUN: not %clang_cc1 -triple riscv64 -tune-cpu not-a-cpu -fsyntax-only %s 
2>&1 | FileCheck %s --check-prefix TUNE-RISCV64
 // TUNE-RISCV64: error: unknown target CPU 'not-a-cpu'
-// TUNE-RISCV64-NEXT: note: valid target CPU values are: generic-rv64, 
rocket-rv64, sifive-p450, sifive-p670, sifive-s21, sifive-s51, sifive-s54, 
sifive-s76, sifive-u54, sifive-u74, sifive-x280, veyron-v1, xiangshan-nanhu, 
generic, rocket, sifive-7-series{{$}}
+// TUNE-RISCV64-NEXT: note: valid target CPU values are: generic-rv64, 
rocket-rv64, sifive-p450, sifive-p670, sifive-s21, sifive-s51, sifive-s54, 
sifive-s76, sifive-u54, sifive-u74, sifive-x280, spacemit-k1, veyron-v1, 
xiangshan-nanhu, generic, rocket, sifive-7-series{{$}}
diff --git a/llvm/lib/Target/RISCV/RISCVProcessors.td 
b/llvm/lib/Target/RISCV/RISCVProcessors.td
index 6ebf9f1eb0452..08602e9d06cc9 100644
--- a/llvm/lib/Target/RISCV/RISCVProcessors.td
+++ b/llvm/lib/Target/RISCV/RISCVProcessors.td
@@ -381,3 +381,32 @@ def XIANGSHAN_NANHU : 
RISCVProcessorModel<"xiangshan-nanhu",
 TuneZExtHFusion,
 TuneZExtWFusion,
 TuneShiftedZExtWFusion]>;
+
+def SPACEMIT_K1 : RISCVProcessorModel<"spacemit-k1",
+   NoSchedModel,
+   [Feature64Bit,
+FeatureStdExtI,
+FeatureStdExtM,
+

[clang] [llvm] [RISCV] Add processor definition for SpacemiT-X60 (PR #94564)

2024-06-18 Thread Shao-Ce SUN via cfe-commits


@@ -381,3 +381,20 @@ def XIANGSHAN_NANHU : 
RISCVProcessorModel<"xiangshan-nanhu",
 TuneZExtHFusion,
 TuneZExtWFusion,
 TuneShiftedZExtWFusion]>;
+
+def SPACEMIT_X60 : RISCVProcessorModel<"spacemit-x60",
+   NoSchedModel,
+   !listconcat(RVA22S64Features,
+   [FeatureStdExtV,
+FeatureStdExtSscofpmf,
+FeatureStdExtSstc,
+FeatureStdExtSvnapot,
+FeatureStdExtZbc,
+FeatureStdExtZbkc,
+FeatureStdExtZfh,
+FeatureStdExtZicond,
+FeatureStdExtZmmul,

sunshaoce wrote:

Addressed. Thanks!

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


[clang] [llvm] [AArch64][TargetParser] move CPUInfo into tablegen [NFC] (PR #92145)

2024-06-18 Thread Tomas Matheson via cfe-commits

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


[clang] [clang-tools-extra] Reland [clang][Sema, Lex, Parse] Preprocessor embed in C and C++ (PR #95802)

2024-06-18 Thread Donát Nagy via cfe-commits


@@ -441,6 +441,7 @@ tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
   CASE( 4, 'e', 's', else);
   CASE( 4, 'l', 'n', line);
   CASE( 4, 's', 'c', sccs);
+  CASE(5, 'e', 'b', embed);

NagyDonat wrote:

```suggestion
  CASE( 5, 'e', 'b', embed);
```
Just drive-by bikeshedding -- consider aligning this like the lines around it.

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


[clang] [llvm] [MC,llvm-readobj,yaml2obj] Support CREL relocation format (PR #91280)

2024-06-18 Thread James Henderson via cfe-commits

jh7370 wrote:

> [jh7370](https://github.com/jh7370) sorry for pinging again. I will be highly 
> grateful if you kindly review this pull request. This change will unblock 
> some of our internal tasks and timely completion of this is crucial for us. 
> Thank you in advance.

I hope to look at this in the next day or two - I've had my head down in some 
local work, so have avoided more complex reviews the past week.

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


[clang] [Serialization] Storing DeclID separately (PR #95897)

2024-06-18 Thread Chuanqi Xu via cfe-commits

https://github.com/ChuanqiXu9 created 
https://github.com/llvm/llvm-project/pull/95897

In https://github.com/llvm/llvm-project/pull/92083, there are some unaddressed 
question about the increased size of PCMs. And I prepared this draft to try to 
address this.

This is patch is not ready for review yet. There are many places to polish. But 
I believe it is functional correct for how sensitive the DeclID is. So this is 
majorly for testing and discussing higher level ideas.

To understand the problem better, we need to understand how we encodes values 
in PCM now. We're using VBR6 format 
(https://llvm.org/docs/BitCodeFormat.html#variable-width-integer) now to record 
values except blobs.

In VBR6 format, the value '1' is stored as `0x1` directly no matter its type. 
And the value `0xFF` will be stored as `0b000111'11`. The first `1` in the 
right hand side of `'` indicates the higher bits still contirbute to the 
current value. And the 12th bit is 0 so that the higher value doesn't relate to 
the current value. Then we can combine the lower 5 bits and the higher 6 bits 
to get the value `0xFF`.

And for my patch, it changes the DeclID from consecutive numbers to 
`` pairs. So that when we record a reference to 
an external declaration, the serialized data in the disk may be much larger. 
But it is not a 100% regression, when we record a reference to a local 
declaration (where `ModuleFileIndex` is `0`), the serialized data in the disk 
may be smaller since the `LocalDeclID` won't be based on the sum of number of 
imported declarations. 

So for the question, the un-strict upper bound in **theory** may be the case 
that we have many modules (more than 2^16) but super less declarations (less 
than 2^5). Then the estimated upper bound may be near 10x. Since we may need 
more than 50 bits to store the index now but previously we can only use 6 bits 
to do that. But I guess this won't be true in practice.

In practice, how the size changes with the last patch should be highly 
dependent to the code bases.

Then for this patch, what I did is, to store the `` pair separately instead of putting them into the one slot. This 
should align to the design more naturally. But from I mentioned above, we can 
see this may not be 100% pure win. Since for local declarations, now we need 
additional 6 bits to present the index. And for my local use cases, since we 
don't have so many modules, I see the size of PCMs increases very slightly 
after this patch.

For landing plans, this patch doesn't have a lot priority in my side, I am 
chasing https://github.com/llvm/llvm-project/pull/92085 
https://github.com/llvm/llvm-project/pull/92511 more now. And from practice, I 
feel the actual increased size  doesn't affect us practically. So I'd like to 
reduce the size more after landing above patches. Also we need to do the 
similar things for source locations, identifier IDs and type IDs. But all of 
them may not have such a strong impact as DeclID has.

>From 9c1755c55509f38c256b7f0191b01d674b7cb619 Mon Sep 17 00:00:00 2001
From: Chuanqi Xu 
Date: Tue, 18 Jun 2024 11:28:03 +0800
Subject: [PATCH] Draft

---
 .../include/clang/Serialization/ASTBitCodes.h |   3 +
 clang/include/clang/Serialization/ASTReader.h |  10 +-
 .../clang/Serialization/ASTRecordReader.h |  15 ++
 .../clang/Serialization/ASTRecordWriter.h |  28 +++
 clang/lib/Serialization/ASTReader.cpp | 159 
 clang/lib/Serialization/ASTReaderDecl.cpp |  29 +--
 clang/lib/Serialization/ASTReaderStmt.cpp |   5 +-
 clang/lib/Serialization/ASTWriter.cpp |  29 ++-
 clang/lib/Serialization/ASTWriterDecl.cpp | 169 --
 clang/utils/TableGen/ClangAttrEmitter.cpp |   4 +-
 10 files changed, 280 insertions(+), 171 deletions(-)

diff --git a/clang/include/clang/Serialization/ASTBitCodes.h 
b/clang/include/clang/Serialization/ASTBitCodes.h
index a4728b1c06b3f..d1f8545052fe8 100644
--- a/clang/include/clang/Serialization/ASTBitCodes.h
+++ b/clang/include/clang/Serialization/ASTBitCodes.h
@@ -261,6 +261,9 @@ using unaligned_decl_id_t =
 serialization::DeclID, llvm::endianness::native,
 llvm::support::unaligned>;
 
+/// The number of slots needed to record a DeclID in bitstreams.
+const unsigned int DeclIDRefSize = 2;
+
 /// The number of predefined preprocessed entity IDs.
 const unsigned int NUM_PREDEF_PP_ENTITY_IDS = 1;
 
diff --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index 08f302c01f538..c6c4a82bcddec 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -599,7 +599,7 @@ class ASTReader
 
   /// An array of lexical contents of a declaration context, as a sequence of
   /// Decl::Kind, DeclID pairs.
-  using LexicalContents = ArrayRef;
+  using LexicalContents = ArrayRef;
 
   /// Map from a DeclContext to its lexical contents.
   llvm::DenseMap>
@@ -960,7 +960,7 @@ class ASTRea

[clang] [Serialization] Storing DeclID separately (PR #95897)

2024-06-18 Thread Chuanqi Xu via cfe-commits

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


[clang] [llvm] [AArch64] Add ability to list extensions enabled for a target (PR #95805)

2024-06-18 Thread David Spickett via cfe-commits


@@ -13,3 +13,57 @@
 // RUN: %clang --target=aarch64_be -mbig-endian -march=armv8.6a -### -c %s 
2>&1 | FileCheck -check-prefix=GENERICV86A-BE %s
 // RUN: %clang --target=aarch64_be -mbig-endian -march=armv8.6-a -### -c %s 
2>&1 | FileCheck -check-prefix=GENERICV86A-BE %s
 // GENERICV86A-BE: "-cc1"{{.*}} "-triple" "aarch64_be{{.*}}" "-target-cpu" 
"generic" "-target-feature" "+v8.6a"{{.*}} "-target-feature" "+neon"
+
+// = Architecture extensions =
+
+// RUN: %clang -target aarch64 -march=armv8.6-a --print-enabled-extensions 
2>&1 | FileCheck -check-prefix=ARCH-EXTENSION --implicit-check-not FEAT_ %s

DavidSpickett wrote:

Ok got it, the CHECK consumes the line so if there was anything left matching 
FEAT_, something was forgotten. Thanks.

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


[clang] [Serialization] Storing DeclID separately (PR #95897)

2024-06-18 Thread Chuanqi Xu via cfe-commits

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


[clang] [clang] Lower _BitInt(129+) to a different type in LLVM IR (PR #91364)

2024-06-18 Thread Mariya Podchishchaeva via cfe-commits


@@ -610,8 +610,26 @@ bool ConstStructBuilder::AppendBytes(CharUnits 
FieldOffsetInChars,
 }
 
 bool ConstStructBuilder::AppendBitField(
-const FieldDecl *Field, uint64_t FieldOffset, llvm::ConstantInt *CI,
+const FieldDecl *Field, uint64_t FieldOffset, llvm::Constant *C,
 bool AllowOverwrite) {
+
+  llvm::ConstantInt *CI = nullptr;
+  if (!isa(C)) {
+// Constants for long _BitInt types are split into individual bytes.
+// Try to fold these back into an integer constant. If that doesn't work
+// out, we We are trying to initialize a bitfield with a non-trivial

Fznamznon wrote:

```suggestion
// out, then we are trying to initialize a bitfield with a non-trivial
```

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


[clang] [clang][analyzer] Add notes to PointerSubChecker (PR #95899)

2024-06-18 Thread Balázs Kéri via cfe-commits

https://github.com/balazske created 
https://github.com/llvm/llvm-project/pull/95899

Notes are added to indicate the array declarations of the arrays in a found 
invalid pointer subtraction.

From 1eb6e7ebde0e97e1cd077dc27ffd3ebd6ed0e93d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bal=C3=A1zs=20K=C3=A9ri?= 
Date: Tue, 18 Jun 2024 10:09:24 +0200
Subject: [PATCH] [clang][analyzer] Add notes to PointerSubChecker

Notes are added to indicate the array declarations of the
arrays in a found invalid pointer subtraction.
---
 .../Checkers/PointerSubChecker.cpp| 45 ---
 clang/test/Analysis/pointer-sub-notes.c   | 34 ++
 2 files changed, 64 insertions(+), 15 deletions(-)
 create mode 100644 clang/test/Analysis/pointer-sub-notes.c

diff --git a/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp
index b73534136fdf0..a983e66df0818 100644
--- a/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp
@@ -43,8 +43,6 @@ class PointerSubChecker
   bool checkArrayBounds(CheckerContext &C, const Expr *E,
 const ElementRegion *ElemReg,
 const MemRegion *Reg) const;
-  void reportBug(CheckerContext &C, const Expr *E,
- const llvm::StringLiteral &Msg) const;
 
 public:
   void checkPreStmt(const BinaryOperator *B, CheckerContext &C) const;
@@ -57,6 +55,14 @@ bool PointerSubChecker::checkArrayBounds(CheckerContext &C, 
const Expr *E,
   if (!ElemReg)
 return true;
 
+  auto ReportBug = [&](const llvm::StringLiteral &Msg) {
+if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
+  auto R = std::make_unique(BT, Msg, N);
+  R->addRange(E->getSourceRange());
+  C.emitReport(std::move(R));
+}
+  };
+
   ProgramStateRef State = C.getState();
   const MemRegion *SuperReg = ElemReg->getSuperRegion();
   SValBuilder &SVB = C.getSValBuilder();
@@ -64,7 +70,7 @@ bool PointerSubChecker::checkArrayBounds(CheckerContext &C, 
const Expr *E,
   if (SuperReg == Reg) {
 if (const llvm::APSInt *I = SVB.getKnownValue(State, ElemReg->getIndex());
 I && (!I->isOne() && !I->isZero()))
-  reportBug(C, E, Msg_BadVarIndex);
+  ReportBug(Msg_BadVarIndex);
 return false;
   }
 
@@ -77,7 +83,7 @@ bool PointerSubChecker::checkArrayBounds(CheckerContext &C, 
const Expr *E,
 ProgramStateRef S1, S2;
 std::tie(S1, S2) = C.getState()->assume(*IndexTooLarge);
 if (S1 && !S2) {
-  reportBug(C, E, Msg_LargeArrayIndex);
+  ReportBug(Msg_LargeArrayIndex);
   return false;
 }
   }
@@ -89,22 +95,13 @@ bool PointerSubChecker::checkArrayBounds(CheckerContext &C, 
const Expr *E,
 ProgramStateRef S1, S2;
 std::tie(S1, S2) = State->assume(*IndexTooSmall);
 if (S1 && !S2) {
-  reportBug(C, E, Msg_NegativeArrayIndex);
+  ReportBug(Msg_NegativeArrayIndex);
   return false;
 }
   }
   return true;
 }
 
-void PointerSubChecker::reportBug(CheckerContext &C, const Expr *E,
-  const llvm::StringLiteral &Msg) const {
-  if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
-auto R = std::make_unique(BT, Msg, N);
-R->addRange(E->getSourceRange());
-C.emitReport(std::move(R));
-  }
-}
-
 void PointerSubChecker::checkPreStmt(const BinaryOperator *B,
  CheckerContext &C) const {
   // When doing pointer subtraction, if the two pointers do not point to the
@@ -136,6 +133,9 @@ void PointerSubChecker::checkPreStmt(const BinaryOperator 
*B,
   if (!checkArrayBounds(C, B->getRHS(), ElemRR, LR))
 return;
 
+  const ValueDecl *DiffDeclL = nullptr;
+  const ValueDecl *DiffDeclR = nullptr;
+
   if (ElemLR && ElemRR) {
 const MemRegion *SuperLR = ElemLR->getSuperRegion();
 const MemRegion *SuperRR = ElemRR->getSuperRegion();
@@ -144,9 +144,24 @@ void PointerSubChecker::checkPreStmt(const BinaryOperator 
*B,
 // Allow arithmetic on different symbolic regions.
 if (isa(SuperLR) || isa(SuperRR))
   return;
+if (const auto *SuperDLR = dyn_cast(SuperLR))
+  DiffDeclL = SuperDLR->getDecl();
+if (const auto *SuperDRR = dyn_cast(SuperRR))
+  DiffDeclR = SuperDRR->getDecl();
   }
 
-  reportBug(C, B, Msg_MemRegionDifferent);
+  if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
+auto R =
+std::make_unique(BT, Msg_MemRegionDifferent, 
N);
+R->addRange(B->getSourceRange());
+if (DiffDeclL)
+  R->addNote("Array at the left-hand side of subtraction",
+ {DiffDeclL, C.getSourceManager()});
+if (DiffDeclR)
+  R->addNote("Array at the right-hand side of subtraction",
+ {DiffDeclR, C.getSourceManager()});
+C.emitReport(std::move(R));
+  }
 }
 
 void ento::registerPointerSubChecker(CheckerManager &mgr) {
diff --git a/clang/test/Analysis/pointer-sub-notes.c 
b/clang/test/Analysis/pointer-sub-notes

[clang] [clang][ExprConst] allow single element access of vector object to be constant expression (PR #72607)

2024-06-18 Thread Vikram Hegde via cfe-commits

vikramRH wrote:

> Hello @vikramRH, please feel free to commandeer this.

Thanks @yuanfang-chen. Also, clang already rejects expressions like &V[0] 
(https://godbolt.org/z/eGcxzGo66), which is also true with constexprs and this 
PR. What's the specific concern here ?

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


[clang] [clang][analyzer] Add notes to PointerSubChecker (PR #95899)

2024-06-18 Thread via cfe-commits

llvmbot wrote:




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

Author: Balázs Kéri (balazske)


Changes

Notes are added to indicate the array declarations of the arrays in a found 
invalid pointer subtraction.

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


2 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp (+30-15) 
- (added) clang/test/Analysis/pointer-sub-notes.c (+34) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp
index b73534136fdf0..a983e66df0818 100644
--- a/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp
@@ -43,8 +43,6 @@ class PointerSubChecker
   bool checkArrayBounds(CheckerContext &C, const Expr *E,
 const ElementRegion *ElemReg,
 const MemRegion *Reg) const;
-  void reportBug(CheckerContext &C, const Expr *E,
- const llvm::StringLiteral &Msg) const;
 
 public:
   void checkPreStmt(const BinaryOperator *B, CheckerContext &C) const;
@@ -57,6 +55,14 @@ bool PointerSubChecker::checkArrayBounds(CheckerContext &C, 
const Expr *E,
   if (!ElemReg)
 return true;
 
+  auto ReportBug = [&](const llvm::StringLiteral &Msg) {
+if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
+  auto R = std::make_unique(BT, Msg, N);
+  R->addRange(E->getSourceRange());
+  C.emitReport(std::move(R));
+}
+  };
+
   ProgramStateRef State = C.getState();
   const MemRegion *SuperReg = ElemReg->getSuperRegion();
   SValBuilder &SVB = C.getSValBuilder();
@@ -64,7 +70,7 @@ bool PointerSubChecker::checkArrayBounds(CheckerContext &C, 
const Expr *E,
   if (SuperReg == Reg) {
 if (const llvm::APSInt *I = SVB.getKnownValue(State, ElemReg->getIndex());
 I && (!I->isOne() && !I->isZero()))
-  reportBug(C, E, Msg_BadVarIndex);
+  ReportBug(Msg_BadVarIndex);
 return false;
   }
 
@@ -77,7 +83,7 @@ bool PointerSubChecker::checkArrayBounds(CheckerContext &C, 
const Expr *E,
 ProgramStateRef S1, S2;
 std::tie(S1, S2) = C.getState()->assume(*IndexTooLarge);
 if (S1 && !S2) {
-  reportBug(C, E, Msg_LargeArrayIndex);
+  ReportBug(Msg_LargeArrayIndex);
   return false;
 }
   }
@@ -89,22 +95,13 @@ bool PointerSubChecker::checkArrayBounds(CheckerContext &C, 
const Expr *E,
 ProgramStateRef S1, S2;
 std::tie(S1, S2) = State->assume(*IndexTooSmall);
 if (S1 && !S2) {
-  reportBug(C, E, Msg_NegativeArrayIndex);
+  ReportBug(Msg_NegativeArrayIndex);
   return false;
 }
   }
   return true;
 }
 
-void PointerSubChecker::reportBug(CheckerContext &C, const Expr *E,
-  const llvm::StringLiteral &Msg) const {
-  if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
-auto R = std::make_unique(BT, Msg, N);
-R->addRange(E->getSourceRange());
-C.emitReport(std::move(R));
-  }
-}
-
 void PointerSubChecker::checkPreStmt(const BinaryOperator *B,
  CheckerContext &C) const {
   // When doing pointer subtraction, if the two pointers do not point to the
@@ -136,6 +133,9 @@ void PointerSubChecker::checkPreStmt(const BinaryOperator 
*B,
   if (!checkArrayBounds(C, B->getRHS(), ElemRR, LR))
 return;
 
+  const ValueDecl *DiffDeclL = nullptr;
+  const ValueDecl *DiffDeclR = nullptr;
+
   if (ElemLR && ElemRR) {
 const MemRegion *SuperLR = ElemLR->getSuperRegion();
 const MemRegion *SuperRR = ElemRR->getSuperRegion();
@@ -144,9 +144,24 @@ void PointerSubChecker::checkPreStmt(const BinaryOperator 
*B,
 // Allow arithmetic on different symbolic regions.
 if (isa(SuperLR) || isa(SuperRR))
   return;
+if (const auto *SuperDLR = dyn_cast(SuperLR))
+  DiffDeclL = SuperDLR->getDecl();
+if (const auto *SuperDRR = dyn_cast(SuperRR))
+  DiffDeclR = SuperDRR->getDecl();
   }
 
-  reportBug(C, B, Msg_MemRegionDifferent);
+  if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
+auto R =
+std::make_unique(BT, Msg_MemRegionDifferent, 
N);
+R->addRange(B->getSourceRange());
+if (DiffDeclL)
+  R->addNote("Array at the left-hand side of subtraction",
+ {DiffDeclL, C.getSourceManager()});
+if (DiffDeclR)
+  R->addNote("Array at the right-hand side of subtraction",
+ {DiffDeclR, C.getSourceManager()});
+C.emitReport(std::move(R));
+  }
 }
 
 void ento::registerPointerSubChecker(CheckerManager &mgr) {
diff --git a/clang/test/Analysis/pointer-sub-notes.c 
b/clang/test/Analysis/pointer-sub-notes.c
new file mode 100644
index 0..dfdace3a58deb
--- /dev/null
+++ b/clang/test/Analysis/pointer-sub-notes.c
@@ -0,0 +1,34 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.core.PointerSub 
-analyzer-output=text -verify %s
+
+void negative_1() {
+  int a[3];
+  int x = -1;
+  // FIXME: should indicate

[clang] [clang][analyzer] Add notes to PointerSubChecker (PR #95899)

2024-06-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Balázs Kéri (balazske)


Changes

Notes are added to indicate the array declarations of the arrays in a found 
invalid pointer subtraction.

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


2 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp (+30-15) 
- (added) clang/test/Analysis/pointer-sub-notes.c (+34) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp
index b73534136fdf0..a983e66df0818 100644
--- a/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/PointerSubChecker.cpp
@@ -43,8 +43,6 @@ class PointerSubChecker
   bool checkArrayBounds(CheckerContext &C, const Expr *E,
 const ElementRegion *ElemReg,
 const MemRegion *Reg) const;
-  void reportBug(CheckerContext &C, const Expr *E,
- const llvm::StringLiteral &Msg) const;
 
 public:
   void checkPreStmt(const BinaryOperator *B, CheckerContext &C) const;
@@ -57,6 +55,14 @@ bool PointerSubChecker::checkArrayBounds(CheckerContext &C, 
const Expr *E,
   if (!ElemReg)
 return true;
 
+  auto ReportBug = [&](const llvm::StringLiteral &Msg) {
+if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
+  auto R = std::make_unique(BT, Msg, N);
+  R->addRange(E->getSourceRange());
+  C.emitReport(std::move(R));
+}
+  };
+
   ProgramStateRef State = C.getState();
   const MemRegion *SuperReg = ElemReg->getSuperRegion();
   SValBuilder &SVB = C.getSValBuilder();
@@ -64,7 +70,7 @@ bool PointerSubChecker::checkArrayBounds(CheckerContext &C, 
const Expr *E,
   if (SuperReg == Reg) {
 if (const llvm::APSInt *I = SVB.getKnownValue(State, ElemReg->getIndex());
 I && (!I->isOne() && !I->isZero()))
-  reportBug(C, E, Msg_BadVarIndex);
+  ReportBug(Msg_BadVarIndex);
 return false;
   }
 
@@ -77,7 +83,7 @@ bool PointerSubChecker::checkArrayBounds(CheckerContext &C, 
const Expr *E,
 ProgramStateRef S1, S2;
 std::tie(S1, S2) = C.getState()->assume(*IndexTooLarge);
 if (S1 && !S2) {
-  reportBug(C, E, Msg_LargeArrayIndex);
+  ReportBug(Msg_LargeArrayIndex);
   return false;
 }
   }
@@ -89,22 +95,13 @@ bool PointerSubChecker::checkArrayBounds(CheckerContext &C, 
const Expr *E,
 ProgramStateRef S1, S2;
 std::tie(S1, S2) = State->assume(*IndexTooSmall);
 if (S1 && !S2) {
-  reportBug(C, E, Msg_NegativeArrayIndex);
+  ReportBug(Msg_NegativeArrayIndex);
   return false;
 }
   }
   return true;
 }
 
-void PointerSubChecker::reportBug(CheckerContext &C, const Expr *E,
-  const llvm::StringLiteral &Msg) const {
-  if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
-auto R = std::make_unique(BT, Msg, N);
-R->addRange(E->getSourceRange());
-C.emitReport(std::move(R));
-  }
-}
-
 void PointerSubChecker::checkPreStmt(const BinaryOperator *B,
  CheckerContext &C) const {
   // When doing pointer subtraction, if the two pointers do not point to the
@@ -136,6 +133,9 @@ void PointerSubChecker::checkPreStmt(const BinaryOperator 
*B,
   if (!checkArrayBounds(C, B->getRHS(), ElemRR, LR))
 return;
 
+  const ValueDecl *DiffDeclL = nullptr;
+  const ValueDecl *DiffDeclR = nullptr;
+
   if (ElemLR && ElemRR) {
 const MemRegion *SuperLR = ElemLR->getSuperRegion();
 const MemRegion *SuperRR = ElemRR->getSuperRegion();
@@ -144,9 +144,24 @@ void PointerSubChecker::checkPreStmt(const BinaryOperator 
*B,
 // Allow arithmetic on different symbolic regions.
 if (isa(SuperLR) || isa(SuperRR))
   return;
+if (const auto *SuperDLR = dyn_cast(SuperLR))
+  DiffDeclL = SuperDLR->getDecl();
+if (const auto *SuperDRR = dyn_cast(SuperRR))
+  DiffDeclR = SuperDRR->getDecl();
   }
 
-  reportBug(C, B, Msg_MemRegionDifferent);
+  if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
+auto R =
+std::make_unique(BT, Msg_MemRegionDifferent, 
N);
+R->addRange(B->getSourceRange());
+if (DiffDeclL)
+  R->addNote("Array at the left-hand side of subtraction",
+ {DiffDeclL, C.getSourceManager()});
+if (DiffDeclR)
+  R->addNote("Array at the right-hand side of subtraction",
+ {DiffDeclR, C.getSourceManager()});
+C.emitReport(std::move(R));
+  }
 }
 
 void ento::registerPointerSubChecker(CheckerManager &mgr) {
diff --git a/clang/test/Analysis/pointer-sub-notes.c 
b/clang/test/Analysis/pointer-sub-notes.c
new file mode 100644
index 0..dfdace3a58deb
--- /dev/null
+++ b/clang/test/Analysis/pointer-sub-notes.c
@@ -0,0 +1,34 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.core.PointerSub 
-analyzer-output=text -verify %s
+
+void negative_1() {
+  int a[3];
+  int x = -1;
+  // FIXME: should indicate that 'x' is -1
+ 

[clang] [clang] Lower _BitInt(129+) to a different type in LLVM IR (PR #91364)

2024-06-18 Thread Nikita Popov via cfe-commits


@@ -118,6 +124,37 @@ llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T, 
bool ForBitField) {
   return R;
 }
 
+bool CodeGenTypes::LLVMTypeLayoutMatchesAST(QualType ASTTy,
+llvm::Type *LLVMTy) {
+  CharUnits ASTSize = Context.getTypeSizeInChars(ASTTy);
+  CharUnits LLVMSize =
+  CharUnits::fromQuantity(getDataLayout().getTypeAllocSize(LLVMTy));
+  return ASTSize == LLVMSize;
+}
+
+llvm::Type *CodeGenTypes::convertTypeForLoadStore(QualType T,
+  llvm::Type *LLVMTy) {
+  if (!LLVMTy)
+LLVMTy = ConvertType(T);
+
+  if (!T->isBitIntType() && LLVMTy->isIntegerTy(1))
+return llvm::IntegerType::get(getLLVMContext(),
+  (unsigned)Context.getTypeSize(T));
+
+  if (T->isBitIntType()) {
+llvm::Type *R = ConvertType(T);
+if (!LLVMTypeLayoutMatchesAST(T, R))
+  return llvm::Type::getIntNTy(
+  getLLVMContext(), Context.getTypeSizeInChars(T).getQuantity() * 8);

nikic wrote:

FWIW, using `[N x i8]` for all types is exactly what Rust does nowadays.

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


[clang] [analyzer] Check the correct first and last elements in cstring.UninitializedRead (PR #95408)

2024-06-18 Thread Donát Nagy via cfe-commits


@@ -393,6 +401,173 @@ ProgramStateRef 
CStringChecker::checkNonNull(CheckerContext &C,
   return stateNonNull;
 }
 
+static std::optional getIndex(ProgramStateRef State,
+  const ElementRegion *ER, CharKind CK) {
+  SValBuilder &SValBuilder = State->getStateManager().getSValBuilder();
+  ASTContext &Ctx = SValBuilder.getContext();
+
+  if (CK == CharKind::Regular) {
+if (ER->getValueType() != Ctx.CharTy)
+  return {};
+return ER->getIndex();
+  }
+
+  if (ER->getValueType() != Ctx.WideCharTy)
+return {};
+
+  QualType SizeTy = Ctx.getSizeType();
+  NonLoc WideSize =
+  SValBuilder
+  .makeIntVal(Ctx.getTypeSizeInChars(Ctx.WideCharTy).getQuantity(),
+  SizeTy)
+  .castAs();
+  SVal Offset =
+  SValBuilder.evalBinOpNN(State, BO_Mul, ER->getIndex(), WideSize, SizeTy);
+  if (Offset.isUnknown())
+return {};
+  return Offset.castAs();
+}
+
+// Try to get hold of the origin regin (e.g. the actual array region from an
+// element region).
+static const TypedValueRegion *getOriginRegion(const ElementRegion *ER) {
+  const MemRegion *MR = ER->getSuperRegion();
+  const MemRegion *Ret = MR;
+  assert(MR);
+  if (const auto *sym = MR->getAs()) {
+SymbolRef sym2 = sym->getSymbol();
+if (!sym2)
+  return nullptr;
+Ret = sym2->getOriginRegion();
+  }
+  if (const auto *element = MR->getAs()) {
+Ret = element->getBaseRegion();
+  }
+  return dyn_cast_or_null(Ret);
+}
+
+// Basically 1 -> 1st, 12 -> 12th, etc.
+static void printIdxWithOrdinalSuffix(llvm::raw_ostream &Os, unsigned Idx) {
+  Os << Idx << llvm::getOrdinalSuffix(Idx);
+}
+
+ProgramStateRef CStringChecker::checkInit(CheckerContext &C,
+  ProgramStateRef State,
+  AnyArgExpr Buffer, SVal Element,
+  SVal Size) const {
+
+  // If a previous check has failed, propagate the failure.
+  if (!State)
+return nullptr;
+
+  const MemRegion *R = Element.getAsRegion();
+  if (!R)
+return State;
+
+  const auto *ER = dyn_cast(R);
+  if (!ER)
+return State;
+
+  const TypedValueRegion *Orig = getOriginRegion(ER);
+  if (!Orig)
+return State;
+
+  SValBuilder &SValBuilder = State->getStateManager().getSValBuilder();

NagyDonat wrote:

I agree with both suggestions, `SVB` is the _right_ name mandated by our _holy 
traditions_.

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


[clang-tools-extra] [clang-tidy] Add `bugprone-pointer-arithmetic-on-polymorphic-object` check (PR #91951)

2024-06-18 Thread via cfe-commits

https://github.com/Discookie updated 
https://github.com/llvm/llvm-project/pull/91951

>From 69cbd3da19eb0f8eb6758782b46daf99b5b79ea4 Mon Sep 17 00:00:00 2001
From: Viktor 
Date: Mon, 6 May 2024 06:11:58 +
Subject: [PATCH 01/15] Add `bugprone-virtual-arithmetic` check

Finds pointer arithmetic on classes that declare a virtual function.
---
 .../bugprone/BugproneTidyModule.cpp   |  3 ++
 .../clang-tidy/bugprone/CMakeLists.txt|  1 +
 .../bugprone/VirtualArithmeticCheck.cpp   | 46 +
 .../bugprone/VirtualArithmeticCheck.h | 30 +++
 .../checks/bugprone/virtual-arithmetic.rst| 50 +++
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../checkers/bugprone/virtual-arithmetic.cpp  | 45 +
 7 files changed, 176 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/VirtualArithmeticCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/VirtualArithmeticCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/virtual-arithmetic.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/virtual-arithmetic.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 1b92d2e60cc17..813f6720074ae 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -91,6 +91,7 @@
 #include "UnusedRaiiCheck.h"
 #include "UnusedReturnValueCheck.h"
 #include "UseAfterMoveCheck.h"
+#include "VirtualArithmeticCheck.h"
 #include "VirtualNearMissCheck.h"
 
 namespace clang::tidy {
@@ -254,6 +255,8 @@ class BugproneModule : public ClangTidyModule {
 CheckFactories.registerCheck(
 "bugprone-unused-return-value");
 CheckFactories.registerCheck("bugprone-use-after-move");
+CheckFactories.registerCheck(
+"bugprone-virtual-arithmetic");
 CheckFactories.registerCheck(
 "bugprone-virtual-near-miss");
   }
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index 2d303191f8865..ec1f3231e7990 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -87,6 +87,7 @@ add_clang_library(clangTidyBugproneModule
   UnusedRaiiCheck.cpp
   UnusedReturnValueCheck.cpp
   UseAfterMoveCheck.cpp
+  VirtualArithmeticCheck.cpp
   VirtualNearMissCheck.cpp
 
   LINK_LIBS
diff --git a/clang-tools-extra/clang-tidy/bugprone/VirtualArithmeticCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/VirtualArithmeticCheck.cpp
new file mode 100644
index 0..57347af2b5881
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/VirtualArithmeticCheck.cpp
@@ -0,0 +1,46 @@
+//===--- VirtualArithmeticCheck.cpp - 
clang-tidy---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "VirtualArithmeticCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+void VirtualArithmeticCheck::registerMatchers(MatchFinder *Finder) {
+  const auto PointerExprWithVirtualMethod =
+  expr(hasType(pointerType(pointee(hasDeclaration(
+   cxxRecordDecl(hasMethod(isVirtualAsWritten(
+  .bind("pointer");
+
+  const auto ArraySubscript =
+  arraySubscriptExpr(hasBase(PointerExprWithVirtualMethod));
+
+  const auto BinaryOperators =
+  binaryOperator(hasAnyOperatorName("+", "-", "+=", "-="),
+ hasEitherOperand(PointerExprWithVirtualMethod));
+
+  const auto UnaryOperators =
+  unaryOperator(hasAnyOperatorName("++", "--"),
+hasUnaryOperand(PointerExprWithVirtualMethod));
+
+  Finder->addMatcher(
+  expr(anyOf(ArraySubscript, BinaryOperators, UnaryOperators)), this);
+}
+
+void VirtualArithmeticCheck::check(const MatchFinder::MatchResult &Result) {
+  const auto *PointerExpr = Result.Nodes.getNodeAs("pointer");
+
+  diag(PointerExpr->getBeginLoc(),
+   "pointer arithmetic on class that declares a virtual function, "
+   "undefined behavior if the pointee is a different class");
+}
+
+} // namespace clang::tidy::bugprone
diff --git a/clang-tools-extra/clang-tidy/bugprone/VirtualArithmeticCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/VirtualArithmeticCheck.h
new file mode 100644
index 0..6a5f86a391747
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/VirtualArithmeticCheck.h
@@ -0,0 +1,30 @@
+//===--- VirtualArithmeticCheck.h - clang-tidy---*- C++ 
-*-===//
+//
+/

[clang] [analyzer] Check the correct first and last elements in cstring.UninitializedRead (PR #95408)

2024-06-18 Thread Kristóf Umann via cfe-commits


@@ -393,6 +401,173 @@ ProgramStateRef 
CStringChecker::checkNonNull(CheckerContext &C,
   return stateNonNull;
 }
 
+static std::optional getIndex(ProgramStateRef State,
+  const ElementRegion *ER, CharKind CK) {
+  SValBuilder &SValBuilder = State->getStateManager().getSValBuilder();
+  ASTContext &Ctx = SValBuilder.getContext();
+
+  if (CK == CharKind::Regular) {
+if (ER->getValueType() != Ctx.CharTy)
+  return {};
+return ER->getIndex();
+  }
+
+  if (ER->getValueType() != Ctx.WideCharTy)
+return {};
+
+  QualType SizeTy = Ctx.getSizeType();
+  NonLoc WideSize =
+  SValBuilder
+  .makeIntVal(Ctx.getTypeSizeInChars(Ctx.WideCharTy).getQuantity(),
+  SizeTy)
+  .castAs();
+  SVal Offset =
+  SValBuilder.evalBinOpNN(State, BO_Mul, ER->getIndex(), WideSize, SizeTy);
+  if (Offset.isUnknown())
+return {};
+  return Offset.castAs();
+}
+
+// Try to get hold of the origin regin (e.g. the actual array region from an
+// element region).
+static const TypedValueRegion *getOriginRegion(const ElementRegion *ER) {
+  const MemRegion *MR = ER->getSuperRegion();
+  const MemRegion *Ret = MR;
+  assert(MR);
+  if (const auto *sym = MR->getAs()) {
+SymbolRef sym2 = sym->getSymbol();
+if (!sym2)
+  return nullptr;
+Ret = sym2->getOriginRegion();
+  }
+  if (const auto *element = MR->getAs()) {
+Ret = element->getBaseRegion();
+  }
+  return dyn_cast_or_null(Ret);
+}
+
+// Basically 1 -> 1st, 12 -> 12th, etc.
+static void printIdxWithOrdinalSuffix(llvm::raw_ostream &Os, unsigned Idx) {
+  Os << Idx << llvm::getOrdinalSuffix(Idx);
+}
+
+ProgramStateRef CStringChecker::checkInit(CheckerContext &C,
+  ProgramStateRef State,
+  AnyArgExpr Buffer, SVal Element,
+  SVal Size) const {
+
+  // If a previous check has failed, propagate the failure.
+  if (!State)
+return nullptr;
+
+  const MemRegion *R = Element.getAsRegion();
+  if (!R)
+return State;
+
+  const auto *ER = dyn_cast(R);
+  if (!ER)
+return State;
+
+  const TypedValueRegion *Orig = getOriginRegion(ER);
+  if (!Orig)
+return State;
+
+  SValBuilder &SValBuilder = State->getStateManager().getSValBuilder();
+  ASTContext &Ctx = SValBuilder.getContext();
+
+  // FIXME: We ought to able to check objects as well. Maybe
+  // UninitializedObjectChecker could help?
+  if (!Orig->getValueType()->isArrayType())
+return State;
+
+  const QualType ElemTy = Ctx.getBaseElementType(Orig->getValueType());
+  const NonLoc Zero = SValBuilder.makeZeroArrayIndex();
+
+  SVal FirstElementVal =
+  State->getLValue(ElemTy, Zero, loc::MemRegionVal(Orig)).castAs();
+  if (!isa(FirstElementVal))
+return State;

Szelethus wrote:

Oh ya, this is  a historical artifact. Though I wonder if the cast is a little 
too brave...

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


[clang] [clang][analyzer] Add notes to PointerSubChecker (PR #95899)

2024-06-18 Thread Donát Nagy via cfe-commits

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


[clang] [clang][analyzer] Add notes to PointerSubChecker (PR #95899)

2024-06-18 Thread Donát Nagy via cfe-commits

https://github.com/NagyDonat commented:

Looks good overall, I have one remark about a rare case that would require some 
specialized code.

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


[clang] [clang][analyzer] Add notes to PointerSubChecker (PR #95899)

2024-06-18 Thread Donát Nagy via cfe-commits


@@ -144,9 +144,24 @@ void PointerSubChecker::checkPreStmt(const BinaryOperator 
*B,
 // Allow arithmetic on different symbolic regions.
 if (isa(SuperLR) || isa(SuperRR))
   return;
+if (const auto *SuperDLR = dyn_cast(SuperLR))
+  DiffDeclL = SuperDLR->getDecl();
+if (const auto *SuperDRR = dyn_cast(SuperRR))
+  DiffDeclR = SuperDRR->getDecl();

NagyDonat wrote:

Note that `FieldRegion`s are `DeclRegion`s, so these declarations may be data 
member declarations within a `struct` or `class`. This is usually not a 
problem, but there is a corner case where `SuperLR != SuperRR`, but the 
corresponding declarations are identical:
```
struct {
  int array[5];
} a, b;
int func(void) {
  return &a.array[3] - &b.array[2];
}
```
In this case the current code would place both notes onto the declaration of 
`field`, which would be confusing for the user.

Consider adding some code that handles this situation explicitly. (Either 
simply skip note creation when `DiffDeclL == DiffDeclR`, or create a 
specialized note for this case.)

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


[clang] [Clang] [Sema] Ensure noexcept(typeid(E)) checks if E throws when needed (PR #95846)

2024-06-18 Thread Mital Ashok via cfe-commits

https://github.com/MitalAshok updated 
https://github.com/llvm/llvm-project/pull/95846

>From 89da8b3bcc678430fe4225c723e87914f2c378cd Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Mon, 17 Jun 2024 21:48:57 +0100
Subject: [PATCH 1/4] [Clang] [Sema] Ensure noexcept(typeid(E)) checks if E
 throws when needed

---
 clang/lib/Sema/SemaExceptionSpec.cpp   |  9 +++--
 .../test/SemaCXX/cxx0x-noexcept-expression.cpp | 18 ++
 2 files changed, 25 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaExceptionSpec.cpp 
b/clang/lib/Sema/SemaExceptionSpec.cpp
index 67e0c7c63909e..ef1128cedf994 100644
--- a/clang/lib/Sema/SemaExceptionSpec.cpp
+++ b/clang/lib/Sema/SemaExceptionSpec.cpp
@@ -,13 +,18 @@ static CanThrowResult canDynamicCastThrow(const 
CXXDynamicCastExpr *DC) {
 }
 
 static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
-  if (DC->isTypeOperand())
+  // Operand is not evaluated, cannot possibly throw
+  if (!DC->isPotentiallyEvaluated())
 return CT_Cannot;
 
   if (DC->isValueDependent())
 return CT_Dependent;
 
-  return DC->hasNullCheck() ? CT_Can : CT_Cannot;
+  // Can throw std::bad_typeid if a nullptr is dereferenced
+  if (DC->hasNullCheck())
+return CT_Can;
+
+  return S.canThrow(DC->getExprOperand());
 }
 
 CanThrowResult Sema::canThrow(const Stmt *S) {
diff --git a/clang/test/SemaCXX/cxx0x-noexcept-expression.cpp 
b/clang/test/SemaCXX/cxx0x-noexcept-expression.cpp
index c2b2244c117a0..1e86a31fffcbf 100644
--- a/clang/test/SemaCXX/cxx0x-noexcept-expression.cpp
+++ b/clang/test/SemaCXX/cxx0x-noexcept-expression.cpp
@@ -1,6 +1,10 @@
 // RUN: %clang_cc1 -fsyntax-only -verify -std=c++2a %s -fexceptions 
-fcxx-exceptions -Wno-unevaluated-expression
 // RUN: %clang_cc1 -fsyntax-only -verify -std=c++2a %s -fexceptions 
-fcxx-exceptions -Wno-unevaluated-expression 
-fexperimental-new-constant-interpreter
 
+namespace std {
+struct type_info;
+}
+
 void f(); // expected-note {{possible target for call}}
 void f(int); // expected-note {{possible target for call}}
 
@@ -97,3 +101,17 @@ void j() noexcept(0);
 void k() noexcept(1);
 void l() noexcept(2); // expected-error {{noexcept specifier argument 
evaluates to 2, which cannot be narrowed to type 'bool'}}
 } // namespace P1401
+
+template
+struct Polymorphic {
+  Polymorphic() noexcept(NoexceptConstructor) {}
+  virtual ~Polymorphic() noexcept(NoexceptDestructor) {}
+};
+
+static_assert(noexcept(typeid(Polymorphic{})));  // Not 
evaluated (not glvalue)
+static_assert(noexcept(typeid((Polymorphic&&) Polymorphic{})));
+static_assert(!noexcept(typeid((Polymorphic&&) Polymorphic{})));
+static_assert(!noexcept(typeid((Polymorphic&&) Polymorphic{})));
+static_assert(!noexcept(typeid(*&(const Polymorphic&) 
Polymorphic{})));
+static_assert(!noexcept(typeid(*&(const Polymorphic&) 
Polymorphic{})));
+static_assert(!noexcept(typeid(*&(const Polymorphic&) 
Polymorphic{})));

>From 1c6c9bf7f30d60a3a69747cd993d49908447d106 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Tue, 18 Jun 2024 06:05:43 +0100
Subject: [PATCH 2/4] Apply suggestions from code review

Co-authored-by: Timm Baeder 
---
 clang/lib/Sema/SemaExceptionSpec.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaExceptionSpec.cpp 
b/clang/lib/Sema/SemaExceptionSpec.cpp
index ef1128cedf994..fcdc39532 100644
--- a/clang/lib/Sema/SemaExceptionSpec.cpp
+++ b/clang/lib/Sema/SemaExceptionSpec.cpp
@@ -,14 +,14 @@ static CanThrowResult canDynamicCastThrow(const 
CXXDynamicCastExpr *DC) {
 }
 
 static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
-  // Operand is not evaluated, cannot possibly throw
+  // Operand is not evaluated, cannot possibly throw.
   if (!DC->isPotentiallyEvaluated())
 return CT_Cannot;
 
   if (DC->isValueDependent())
 return CT_Dependent;
 
-  // Can throw std::bad_typeid if a nullptr is dereferenced
+  // Can throw std::bad_typeid if a nullptr is dereferenced.
   if (DC->hasNullCheck())
 return CT_Can;
 

>From fb7e2debf69235e5c7960353ab497fa159e745f8 Mon Sep 17 00:00:00 2001
From: Mital Ashok 
Date: Tue, 18 Jun 2024 07:11:53 +0100
Subject: [PATCH 3/4] Make sure isPotentiallyEvaluated is not called on a
 dependant expression (which might become potentially evaluated once types are
 known)

---
 clang/lib/Sema/SemaExceptionSpec.cpp | 8 ++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaExceptionSpec.cpp 
b/clang/lib/Sema/SemaExceptionSpec.cpp
index fcdc39532..fb2250d1c98af 100644
--- a/clang/lib/Sema/SemaExceptionSpec.cpp
+++ b/clang/lib/Sema/SemaExceptionSpec.cpp
@@ -,13 +,17 @@ static CanThrowResult canDynamicCastThrow(const 
CXXDynamicCastExpr *DC) {
 }
 
 static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
-  // Operand is not evaluated, cannot possibly throw.
-  if (!DC->isPotentiallyEvaluated())
+  // A typeid of a type is a constant and does not t

[clang] [clang] Emit bad shift warnings (PR #70307)

2024-06-18 Thread Budimir Aranđelović via cfe-commits

https://github.com/budimirarandjelovicsyrmia updated 
https://github.com/llvm/llvm-project/pull/70307

From 69c6fc02cef92c0dd0eda0a30daa82856552ef1c Mon Sep 17 00:00:00 2001
From: budimirarandjelovicsyrmia 
Date: Thu, 26 Oct 2023 10:39:52 +0200
Subject: [PATCH] [clang] Emit bad shift warnings

---
 clang/lib/AST/ExprConstant.cpp |  7 +++
 clang/lib/Sema/SemaExpr.cpp| 17 +
 clang/test/C/drs/dr0xx.c   |  3 ++-
 clang/test/C/drs/dr2xx.c   |  4 +++-
 clang/test/Sema/builtins.c |  6 --
 clang/test/Sema/code_align.c   |  7 ---
 clang/test/Sema/constant-builtins-2.c  |  8 
 clang/test/Sema/shift-count-negative.c | 10 ++
 clang/test/Sema/shift-count-overflow.c |  7 +++
 clang/test/Sema/shift-negative-value.c | 10 ++
 clang/test/Sema/vla-2.c|  6 --
 clang/test/SemaCXX/enum.cpp|  6 --
 clang/test/SemaCXX/shift.cpp   |  2 +-
 13 files changed, 73 insertions(+), 20 deletions(-)
 create mode 100644 clang/test/Sema/shift-count-negative.c
 create mode 100644 clang/test/Sema/shift-count-overflow.c
 create mode 100644 clang/test/Sema/shift-negative-value.c

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index af1f18aa8ef24..0926bcf258f58 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2856,6 +2856,9 @@ static bool handleIntIntBinOp(EvalInfo &Info, const 
BinaryOperator *E,
   else if (LHS.countl_zero() < SA)
 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
 }
+if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
+Info.getLangOpts().CPlusPlus)
+  return false;
 Result = LHS << SA;
 return true;
   }
@@ -2879,6 +2882,10 @@ static bool handleIntIntBinOp(EvalInfo &Info, const 
BinaryOperator *E,
 if (SA != RHS)
   Info.CCEDiag(E, diag::note_constexpr_large_shift)
 << RHS << E->getType() << LHS.getBitWidth();
+
+if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
+Info.getLangOpts().CPlusPlus)
+  return false;
 Result = LHS >> SA;
 return true;
   }
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 44f886bf54e3a..c77a0e511a3a8 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -11246,7 +11246,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
   if (Right.isNegative()) {
 S.DiagRuntimeBehavior(Loc, RHS.get(),
   S.PDiag(diag::warn_shift_negative)
-<< RHS.get()->getSourceRange());
+  << RHS.get()->getSourceRange());
 return;
   }
 
@@ -11261,7 +11261,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
   if (Right.uge(LeftSize)) {
 S.DiagRuntimeBehavior(Loc, RHS.get(),
   S.PDiag(diag::warn_shift_gt_typewidth)
-<< RHS.get()->getSourceRange());
+  << RHS.get()->getSourceRange());
 return;
   }
 
@@ -11294,7 +11294,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
   if (Left.isNegative()) {
 S.DiagRuntimeBehavior(Loc, LHS.get(),
   S.PDiag(diag::warn_shift_lhs_negative)
-<< LHS.get()->getSourceRange());
+  << LHS.get()->getSourceRange());
 return;
   }
 
@@ -17130,11 +17130,20 @@ Sema::VerifyIntegerConstantExpression(Expr *E, 
llvm::APSInt *Result,
   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
   // in the non-ICE case.
   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
+SmallVector Notes;
 if (Result)
-  *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
+  *Result = E->EvaluateKnownConstIntCheckOverflow(Context, &Notes);
 if (!isa(E))
   E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
  : ConstantExpr::Create(Context, E);
+
+if (Notes.size() && !Diagnoser.Suppress) {
+  Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
+  for (const PartialDiagnosticAt &Note : Notes)
+Diag(Note.first, Note.second);
+  return ExprError();
+}
+
 return E;
   }
 
diff --git a/clang/test/C/drs/dr0xx.c b/clang/test/C/drs/dr0xx.c
index 36de32a93da95..530c216722cc3 100644
--- a/clang/test/C/drs/dr0xx.c
+++ b/clang/test/C/drs/dr0xx.c
@@ -430,7 +430,8 @@ void dr081(void) {
   /* Demonstrate that we don't crash when left shifting a signed value; that's
* implementation defined behavior.
*/
- _Static_assert(-1 << 1 == -2, "fail"); /* Didn't shift a zero into the "sign 
bit". */
+ _Static_assert(-1 << 1 == -2, "fail"); /* c89only-error {{static assertion 
expression is not an integral constant expression}}
+ 

[clang] [Clang] [Sema] Ensure noexcept(typeid(E)) checks if E throws when needed (PR #95846)

2024-06-18 Thread Mital Ashok via cfe-commits

MitalAshok wrote:

@Sirraide Yes, the tests did pass because there were no tests for this.

For reference:
 * `llvm:main` currently only handles these two wrong 
https://github.com/llvm/llvm-project/pull/95846/commits/89da8b3bcc678430fe4225c723e87914f2c378cd#diff-c35ff1c0977223e8ef2893fd21f3886c57b26346258850d8c879362fd9222381R113-R114
 (https://godbolt.org/z/1j9Kc187f)
 * The first commit in this PR didn't handle `f1`, `f2` and `f3` properly, 
https://github.com/llvm/llvm-project/pull/95846/commits/77b5b6477f9af79777a35cfdf1fb4659e631be71#diff-c35ff1c0977223e8ef2893fd21f3886c57b26346258850d8c879362fd9222381R124-R141
 (It treated them as `CT_Cannot` since it incorrectly assumed they weren't 
potentially evaluated because the dependent type isn't a polymorphic class type)
 * The third commit fixed that by moving the check afterwards

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


[clang] [clang] Lower _BitInt(129+) to a different type in LLVM IR (PR #91364)

2024-06-18 Thread Mariya Podchishchaeva via cfe-commits


@@ -1533,9 +1533,17 @@ void CodeGenFunction::EmitReturnStmt(const ReturnStmt 
&S) {
 Builder.CreateStore(Result.getScalarVal(), ReturnValue);
   } else {
 switch (getEvaluationKind(RV->getType())) {
-case TEK_Scalar:
-  Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
-  break;
+case TEK_Scalar: {
+  llvm::Value *Ret = EmitScalarExpr(RV);
+  // EmitStoreOfScalar could be used here, but it extends bool which for
+  // some targets is returned as i1 zeroext.

Fznamznon wrote:

@rjmccall if wonder if checking `CurFnInfo->getReturnInfo().getKind()` will 
succeed? 
If so, I'm not really sure where else this needs to be checked, could you give 
a hint?

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


[clang] [clang] Lower _BitInt(129+) to a different type in LLVM IR (PR #91364)

2024-06-18 Thread Mariya Podchishchaeva via cfe-commits


@@ -128,6 +128,15 @@ class CodeGenTypes {
   /// memory representation is usually i8 or i32, depending on the target.
   llvm::Type *ConvertTypeForMem(QualType T, bool ForBitField = false);
 
+  /// Check that size and abi alignment of given LLVM type matches size and
+  /// alignment of given AST type.
+  bool LLVMTypeLayoutMatchesAST(QualType ASTTy, llvm::Type *LLVMTy);

Fznamznon wrote:

Renamed to `typeRequiresSplitIntoByteArray`. Let me know if this is better.

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


[clang] [clang] Lower _BitInt(129+) to a different type in LLVM IR (PR #91364)

2024-06-18 Thread Mariya Podchishchaeva via cfe-commits

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


[clang] [clang][analyzer] Add notes to PointerSubChecker (PR #95899)

2024-06-18 Thread Balázs Kéri via cfe-commits

balazske wrote:

I found difficult results from the checker where it is not obvious what the 
problem is.
One type is this case where a negative index is found (any of these results, or 
check the first one):
https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=curl_curl-7_66_0_pointersub&is-unique=off&diff-type=New&checker-name=alpha.core.PointerSub
This type of problem is not fixed with the patch.

Other problem is when different arrays are found:
https://codechecker-demo.eastus.cloudapp.azure.com/Default/report-detail?run=vim_v8.2.1920_pointersub&is-unique=off&diff-type=New&checker-name=alpha.core.PointerSub&report-id=5494864&report-hash=9a4c8e84e0c5227d61f321ec217e88ec&report-filepath=%2Flocal%2Fpersistent_docker%2FCSA-measurements-driver-2913%2Fmeasurements_workspace%2Fvim%2Fsrc%2Fevalvars.c
This case should improve with the patch (but not tested yet).

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


[clang] [llvm] security check cookie execute only when needed (PR #95904)

2024-06-18 Thread via cfe-commits

https://github.com/mahesh-attarde created 
https://github.com/llvm/llvm-project/pull/95904

For windows __security_check_cookie call gets call everytime function is
return without fixup. Since this function is defined in runtime library, it
incures cost of call in dll which simply does comparison and returns most
time. With Fixup, We selective move to call in DLL only if comparison fails.

>From 6d6619f8f7a37906ac45791487a4d63b51a48ad1 Mon Sep 17 00:00:00 2001
From: mahesh-attarde 
Date: Wed, 12 Jun 2024 06:15:51 -0700
Subject: [PATCH 1/2] added regcall strct by reg support

---
 clang/lib/CodeGen/Targets/X86.cpp | 20 
 clang/test/CodeGen/regcall3.c | 53 +++
 2 files changed, 73 insertions(+)
 create mode 100644 clang/test/CodeGen/regcall3.c

diff --git a/clang/lib/CodeGen/Targets/X86.cpp 
b/clang/lib/CodeGen/Targets/X86.cpp
index 43dadf5e724ac..506d106ad65b0 100644
--- a/clang/lib/CodeGen/Targets/X86.cpp
+++ b/clang/lib/CodeGen/Targets/X86.cpp
@@ -148,6 +148,7 @@ class X86_32ABIInfo : public ABIInfo {
 
   Class classify(QualType Ty) const;
   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
+
   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State,
   unsigned ArgIndex) const;
 
@@ -1306,6 +1307,8 @@ class X86_64ABIInfo : public ABIInfo {
unsigned &NeededSSE,
unsigned &MaxVectorWidth) const;
 
+  bool DoesRegcallStructFitInReg(QualType Ty) const;
+
   bool IsIllegalVectorType(QualType Ty) const;
 
   /// The 0.98 ABI revision clarified a lot of ambiguities,
@@ -2830,6 +2833,20 @@ X86_64ABIInfo::classifyArgumentType(QualType Ty, 
unsigned freeIntRegs,
   return ABIArgInfo::getDirect(ResType);
 }
 
+bool X86_64ABIInfo::DoesRegcallStructFitInReg(QualType Ty) const {
+  auto RT = Ty->castAs();
+  // For Integer class, Max GPR Size is 64
+  if (getContext().getTypeSize(Ty) > 64)
+return false;
+  // Struct At hand must not have other non Builtin types
+  for (const auto *FD : RT->getDecl()->fields()) {
+QualType MTy = FD->getType();
+if (!MTy->isBuiltinType())
+  return false;
+  }
+  return true;
+}
+
 ABIArgInfo
 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
  unsigned &NeededSSE,
@@ -2837,6 +2854,9 @@ X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, 
unsigned &NeededInt,
   auto RT = Ty->getAs();
   assert(RT && "classifyRegCallStructType only valid with struct types");
 
+  if (DoesRegcallStructFitInReg(Ty))
+return classifyArgumentType(Ty, UINT_MAX, NeededInt, NeededSSE, true, 
true);
+
   if (RT->getDecl()->hasFlexibleArrayMember())
 return getIndirectReturnResult(Ty);
 
diff --git a/clang/test/CodeGen/regcall3.c b/clang/test/CodeGen/regcall3.c
new file mode 100644
index 0..1c83407220861
--- /dev/null
+++ b/clang/test/CodeGen/regcall3.c
@@ -0,0 +1,53 @@
+// RUN: %clang_cc1 -S %s -o - -ffreestanding -triple=x86_64-unknown-linux-gnu 
| FileCheck %s --check-prefixes=LINUX64
+
+#include 
+struct struct1 { int x; int y; };
+void __regcall v6(int a, float b, struct struct1 c) {}
+
+void v6_caller(){
+struct struct1 c0;
+c0.x = 0xa0a0; c0.y = 0xb0b0;
+int x= 0xf0f0, y = 0x0f0f;
+v6(x,y,c0);
+}
+
+// LINUX64-LABEL: __regcall3__v6
+// LINUX64: movq   %rcx, -8(%rsp)
+// LINUX64: movl   %eax, -12(%rsp)
+// LINUX64: movss  %xmm0, -16(%rsp)
+
+// LINUX64-LABEL: v6_caller
+// LINUX64: movl   $41120, 16(%rsp)# imm = 0xA0A0
+// LINUX64: movl   $45232, 20(%rsp)# imm = 0xB0B0
+// LINUX64: movl   $61680, 12(%rsp)# imm = 0xF0F0
+// LINUX64: movl   $3855, 8(%rsp)  # imm = 0xF0F
+// LINUX64: movl   12(%rsp), %eax
+// LINUX64: cvtsi2ssl  8(%rsp), %xmm0
+// LINUX64: movq   16(%rsp), %rcx
+// LINUX64: callq  .L__regcall3__v6$local
+
+
+struct struct2 { int x; float y; };
+void __regcall v31(int a, float b, struct struct2 c) {}
+
+void v31_caller(){
+struct struct2 c0;
+c0.x = 0xa0a0; c0.y = 0xb0b0;
+int x= 0xf0f0, y = 0x0f0f;
+v31(x,y,c0);
+}
+
+// LINUX64: __regcall3__v31:# @__regcall3__v31
+// LINUX64:movq%rcx, -8(%rsp)
+// LINUX64:movl%eax, -12(%rsp)
+// LINUX64:movss   %xmm0, -16(%rsp)
+// LINUX64: v31_caller: # @v31_caller
+// LINUX64:movl$41120, 16(%rsp)# imm = 0xA0A0
+// LINUX64:movss   .LCPI3_0(%rip), %xmm0   # xmm0 = 
[4.5232E+4,0.0E+0,0.0E+0,0.0E+0]
+// LINUX64:movss   %xmm0, 20(%rsp)
+// LINUX64:movl$61680, 12(%rsp)# imm = 0xF0F0
+// LINUX64:movl$3855, 8(%rsp)  # imm = 0xF0F
+// LINUX64:movl12(%rsp), %eax
+// LINUX64:cvtsi2ssl   8(%rsp), %xmm0
+// LINUX64:movq16(%rsp), %rcx
+// LINUX64:ca

[clang] [llvm] security check cookie execute only when needed (PR #95904)

2024-06-18 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-backend-x86

@llvm/pr-subscribers-clang-codegen

Author: None (mahesh-attarde)


Changes

For windows __security_check_cookie call gets call everytime function is
return without fixup. Since this function is defined in runtime library, it
incures cost of call in dll which simply does comparison and returns most
time. With Fixup, We selective move to call in DLL only if comparison fails.

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


9 Files Affected:

- (modified) clang/lib/CodeGen/Targets/X86.cpp (+20) 
- (added) clang/test/CodeGen/regcall3.c (+53) 
- (modified) llvm/lib/Target/X86/CMakeLists.txt (+1) 
- (modified) llvm/lib/Target/X86/X86.h (+4) 
- (added) llvm/lib/Target/X86/X86FixupStackProtector.cpp (+249) 
- (modified) llvm/lib/Target/X86/X86TargetMachine.cpp (+1) 
- (modified) llvm/test/CodeGen/X86/opt-pipeline.ll (+1) 
- (modified) llvm/test/CodeGen/X86/stack-protector-msvc.ll (+17-5) 
- (modified) llvm/test/CodeGen/X86/tailcc-ssp.ll (+23-4) 


``diff
diff --git a/clang/lib/CodeGen/Targets/X86.cpp 
b/clang/lib/CodeGen/Targets/X86.cpp
index 43dadf5e724ac..506d106ad65b0 100644
--- a/clang/lib/CodeGen/Targets/X86.cpp
+++ b/clang/lib/CodeGen/Targets/X86.cpp
@@ -148,6 +148,7 @@ class X86_32ABIInfo : public ABIInfo {
 
   Class classify(QualType Ty) const;
   ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
+
   ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State,
   unsigned ArgIndex) const;
 
@@ -1306,6 +1307,8 @@ class X86_64ABIInfo : public ABIInfo {
unsigned &NeededSSE,
unsigned &MaxVectorWidth) const;
 
+  bool DoesRegcallStructFitInReg(QualType Ty) const;
+
   bool IsIllegalVectorType(QualType Ty) const;
 
   /// The 0.98 ABI revision clarified a lot of ambiguities,
@@ -2830,6 +2833,20 @@ X86_64ABIInfo::classifyArgumentType(QualType Ty, 
unsigned freeIntRegs,
   return ABIArgInfo::getDirect(ResType);
 }
 
+bool X86_64ABIInfo::DoesRegcallStructFitInReg(QualType Ty) const {
+  auto RT = Ty->castAs();
+  // For Integer class, Max GPR Size is 64
+  if (getContext().getTypeSize(Ty) > 64)
+return false;
+  // Struct At hand must not have other non Builtin types
+  for (const auto *FD : RT->getDecl()->fields()) {
+QualType MTy = FD->getType();
+if (!MTy->isBuiltinType())
+  return false;
+  }
+  return true;
+}
+
 ABIArgInfo
 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
  unsigned &NeededSSE,
@@ -2837,6 +2854,9 @@ X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, 
unsigned &NeededInt,
   auto RT = Ty->getAs();
   assert(RT && "classifyRegCallStructType only valid with struct types");
 
+  if (DoesRegcallStructFitInReg(Ty))
+return classifyArgumentType(Ty, UINT_MAX, NeededInt, NeededSSE, true, 
true);
+
   if (RT->getDecl()->hasFlexibleArrayMember())
 return getIndirectReturnResult(Ty);
 
diff --git a/clang/test/CodeGen/regcall3.c b/clang/test/CodeGen/regcall3.c
new file mode 100644
index 0..1c83407220861
--- /dev/null
+++ b/clang/test/CodeGen/regcall3.c
@@ -0,0 +1,53 @@
+// RUN: %clang_cc1 -S %s -o - -ffreestanding -triple=x86_64-unknown-linux-gnu 
| FileCheck %s --check-prefixes=LINUX64
+
+#include 
+struct struct1 { int x; int y; };
+void __regcall v6(int a, float b, struct struct1 c) {}
+
+void v6_caller(){
+struct struct1 c0;
+c0.x = 0xa0a0; c0.y = 0xb0b0;
+int x= 0xf0f0, y = 0x0f0f;
+v6(x,y,c0);
+}
+
+// LINUX64-LABEL: __regcall3__v6
+// LINUX64: movq   %rcx, -8(%rsp)
+// LINUX64: movl   %eax, -12(%rsp)
+// LINUX64: movss  %xmm0, -16(%rsp)
+
+// LINUX64-LABEL: v6_caller
+// LINUX64: movl   $41120, 16(%rsp)# imm = 0xA0A0
+// LINUX64: movl   $45232, 20(%rsp)# imm = 0xB0B0
+// LINUX64: movl   $61680, 12(%rsp)# imm = 0xF0F0
+// LINUX64: movl   $3855, 8(%rsp)  # imm = 0xF0F
+// LINUX64: movl   12(%rsp), %eax
+// LINUX64: cvtsi2ssl  8(%rsp), %xmm0
+// LINUX64: movq   16(%rsp), %rcx
+// LINUX64: callq  .L__regcall3__v6$local
+
+
+struct struct2 { int x; float y; };
+void __regcall v31(int a, float b, struct struct2 c) {}
+
+void v31_caller(){
+struct struct2 c0;
+c0.x = 0xa0a0; c0.y = 0xb0b0;
+int x= 0xf0f0, y = 0x0f0f;
+v31(x,y,c0);
+}
+
+// LINUX64: __regcall3__v31:# @__regcall3__v31
+// LINUX64:movq%rcx, -8(%rsp)
+// LINUX64:movl%eax, -12(%rsp)
+// LINUX64:movss   %xmm0, -16(%rsp)
+// LINUX64: v31_caller: # @v31_caller
+// LINUX64:movl$41120, 16(%rsp)# imm = 0xA0A0
+// LINUX64:movss   .LCPI3_0(%rip), %xmm0   # xmm0 = 
[4.5232E+4,0.0E+0,0.0E+0,0.0E+0]
+// LINUX64:movss   %xmm0, 20(%rsp)
+// LINUX64:movl$61680, 12(%r

[clang] [Sema][CTAD] Allow user defined conversion for copy-list-initialization (PR #94752)

2024-06-18 Thread Gábor Spaits via cfe-commits

https://github.com/spaits updated 
https://github.com/llvm/llvm-project/pull/94752

From 8e1f3aa676b891c9566344ad2be046898df34a3a Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Fri, 7 Jun 2024 14:38:08 +0200
Subject: [PATCH 1/4] [CTAD] Allow user defined conversion

---
 clang/include/clang/Sema/Initialization.h |  2 +-
 clang/lib/Sema/SemaInit.cpp   |  6 +-
 .../SemaCXX/ctad-copy-init-list-narrowing.cpp | 90 +++
 3 files changed, 93 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/SemaCXX/ctad-copy-init-list-narrowing.cpp

diff --git a/clang/include/clang/Sema/Initialization.h 
b/clang/include/clang/Sema/Initialization.h
index f443e327eaf32..4b876db436b48 100644
--- a/clang/include/clang/Sema/Initialization.h
+++ b/clang/include/clang/Sema/Initialization.h
@@ -603,7 +603,7 @@ class InitializationKind {
 /// Normal context
 IC_Normal,
 
-/// Normal context, but allows explicit conversion functionss
+/// Normal context, but allows explicit conversion functions
 IC_ExplicitConvs,
 
 /// Implicit context (value initialization)
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index ed8b226a6b39f..211b6887befa3 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -10892,8 +10892,6 @@ QualType 
Sema::DeduceTemplateSpecializationFromInitializer(
 // FIXME: The "second phase of [over.match.list] case can also
 // theoretically happen here, but it's not clear whether we can
 // ever have a parameter of the right type.
-bool SuppressUserConversions = Kind.isCopyInit();
-
 if (TD) {
   SmallVector TmpInits;
   for (Expr *E : Inits)
@@ -10903,12 +10901,12 @@ QualType 
Sema::DeduceTemplateSpecializationFromInitializer(
   TmpInits.push_back(E);
   AddTemplateOverloadCandidate(
   TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates,
-  SuppressUserConversions,
+  /*SuppressUserConversions=*/false,
   /*PartialOverloading=*/false, AllowExplicit, ADLCallKind::NotADL,
   /*PO=*/{}, AllowAggregateDeductionCandidate);
 } else {
   AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,
-   SuppressUserConversions,
+   /*SuppressUserConversions=*/false,
/*PartialOverloading=*/false, AllowExplicit);
 }
   };
diff --git a/clang/test/SemaCXX/ctad-copy-init-list-narrowing.cpp 
b/clang/test/SemaCXX/ctad-copy-init-list-narrowing.cpp
new file mode 100644
index 0..21b1137158d5a
--- /dev/null
+++ b/clang/test/SemaCXX/ctad-copy-init-list-narrowing.cpp
@@ -0,0 +1,90 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wno-unused-value -std=c++20 %s
+namespace std
+{
+  typedef long unsigned int size_t;
+}
+
+namespace std
+{
+  template
+class initializer_list
+{
+public:
+  typedef _E value_type;
+  typedef const _E& reference;
+  typedef const _E& const_reference;
+  typedef size_t size_type;
+  typedef const _E* iterator;
+  typedef const _E* const_iterator;
+
+private:
+  iterator _M_array;
+  size_type _M_len;
+
+
+  constexpr initializer_list(const_iterator __a, size_type __l)
+  : _M_array(__a), _M_len(__l) { }
+
+public:
+  constexpr initializer_list() noexcept
+  : _M_array(0), _M_len(0) { }
+
+
+  constexpr size_type
+  size() const noexcept { return _M_len; }
+
+
+  constexpr const_iterator
+  begin() const noexcept { return _M_array; }
+
+
+  constexpr const_iterator
+  end() const noexcept { return begin() + size(); }
+};
+
+  template
+constexpr const _Tp*
+begin(initializer_list<_Tp> __ils) noexcept
+{ return __ils.begin(); }
+
+  template
+constexpr const _Tp*
+end(initializer_list<_Tp> __ils) noexcept
+{ return __ils.end(); }
+}
+
+template
+class pair{
+private:
+T fst;
+Y snd;
+public:
+pair(T f, Y s) : fst(f), snd(s) {}
+};
+
+template
+class map {
+public:
+map(std::initializer_list>, int a = 4, int b = 5) {}
+};
+
+template
+class Contained {
+  public:
+  Contained(T, Y) {}
+};
+
+template
+class A {
+  public:
+  A(std::initializer_list >, int) {}
+};
+
+int main() {
+map mOk ={pair{5, 'a'}, {6, 'b'}, {7, 'c'}};
+map mNarrow ={pair{5, 'a'}, {6.0f, 'b'}, {7, 'c'}}; // expected-error 
{{type 'float' cannot be narrowed to 'int' in initializer list}} // 
expected-note {{insert an explicit cast to silence this issue}}
+
+A aOk = {{Contained{5, 'c'}, {5, 'c'}}, 5};
+A aNarrowNested = {{Contained{5, 'c'}, {5.0f, 'c'}}, 5}; // expected-error 
{{type 'float' cannot be narrowed to 'int' in initializer list}} // 
expected-note {{insert an explicit cast to silence this issue}}
+A aNarrow = {{Contained{5, 'c'}, {5, 'c'}}, 5.0f}; // expected-error 
{{type 'float' cannot be narrowed to 'int' in initializer list}} // 
expected-note {{insert an explicit cast to sil

[clang] [clang-format] Handle function try block with ctor-initializer (PR #95878)

2024-06-18 Thread via cfe-commits

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


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


[clang] 20d3cab - [clang][NFC] Take const pointers in Sema::DiagnoseAutoDeductionFailure

2024-06-18 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-06-18T12:48:38+02:00
New Revision: 20d3cab85258198d262eea05fae6292a2666d6ae

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

LOG: [clang][NFC] Take const pointers in Sema::DiagnoseAutoDeductionFailure

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaTemplateDeduction.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 4d4579fcfd456..a47aeaa7e6c7f 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -9695,7 +9695,7 @@ class Sema final : public SemaBase {
  bool DependentDeduction = false,
  bool IgnoreConstraints = false,
  TemplateSpecCandidateSet *FailedTSC = nullptr);
-  void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
+  void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init);
   bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
 bool Diagnose = true);
 

diff  --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index befeb38e1fe5b..a432918cbf5e2 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -5418,7 +5418,8 @@ TypeSourceInfo 
*Sema::ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
   .TransformType(TypeWithAuto);
 }
 
-void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
+void Sema::DiagnoseAutoDeductionFailure(const VarDecl *VDecl,
+const Expr *Init) {
   if (isa(Init))
 Diag(VDecl->getLocation(),
  VDecl->isInitCapture()



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


[clang-tools-extra] Enforce SL.con.3: Add check to replace operator[] with at() [Cont.] (PR #95220)

2024-06-18 Thread Paul Heidekrüger via cfe-commits

PBHDK wrote:

> Btw, I realize that this check is part of the [bounds 
> profile](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#SS-bounds)
>  (Bounds.4), so for consistency it should probably be named 
> `cppcoreguidelines-pro-bounds-...`. This becomes then the last remaining 
> check to complete the bounds profile!

Does the fact that this check implements the bounds profile need to be 
mentioned anywhere else? Or is it enough to have it be implicit, e.g., via the 
name.

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


[clang] [clang-format] Handle function try block with ctor-initializer (PR #95878)

2024-06-18 Thread Björn Schäpers via cfe-commits

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


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


[clang] [clang] Lower _BitInt(129+) to a different type in LLVM IR (PR #91364)

2024-06-18 Thread Mariya Podchishchaeva via cfe-commits


@@ -118,6 +124,37 @@ llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T, 
bool ForBitField) {
   return R;
 }
 
+bool CodeGenTypes::LLVMTypeLayoutMatchesAST(QualType ASTTy,
+llvm::Type *LLVMTy) {
+  CharUnits ASTSize = Context.getTypeSizeInChars(ASTTy);
+  CharUnits LLVMSize =
+  CharUnits::fromQuantity(getDataLayout().getTypeAllocSize(LLVMTy));
+  return ASTSize == LLVMSize;
+}
+
+llvm::Type *CodeGenTypes::convertTypeForLoadStore(QualType T,
+  llvm::Type *LLVMTy) {
+  if (!LLVMTy)
+LLVMTy = ConvertType(T);
+
+  if (!T->isBitIntType() && LLVMTy->isIntegerTy(1))
+return llvm::IntegerType::get(getLLVMContext(),
+  (unsigned)Context.getTypeSize(T));
+
+  if (T->isBitIntType()) {
+llvm::Type *R = ConvertType(T);
+if (!LLVMTypeLayoutMatchesAST(T, R))
+  return llvm::Type::getIntNTy(
+  getLLVMContext(), Context.getTypeSizeInChars(T).getQuantity() * 8);

Fznamznon wrote:

I have a concern that this way we will always need to use a different memory 
type for _BitInt (perhaps always `[N x i8]`). I'm not sure it is right for all 
targets?

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


[clang] [clang] Lower _BitInt(129+) to a different type in LLVM IR (PR #91364)

2024-06-18 Thread Mariya Podchishchaeva via cfe-commits

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


[clang] [llvm] [analyzer][NFC] Reorganize Z3 report refutation (PR #95128)

2024-06-18 Thread Mikael Holmén via cfe-commits

mikaelholmen wrote:

Hi @steakhal and @NagyDonat ,

Does this patch have requirements on the Z3 version?

I get
```LLVM ERROR: Z3 error: unknown parameter 'timeout'```
for the following testcases
```
Failed Tests (3):
  Clang-Unit :: StaticAnalyzer/./StaticAnalysisTests/24/188
  Clang-Unit :: StaticAnalyzer/./StaticAnalysisTests/25/188
  Clang-Unit :: StaticAnalyzer/./StaticAnalysisTests/26/188
```


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


[clang] [llvm] [analyzer][NFC] Reorganize Z3 report refutation (PR #95128)

2024-06-18 Thread Balazs Benics via cfe-commits

steakhal wrote:

> Hi @steakhal and @NagyDonat ,
> 
> Does this patch have requirements on the Z3 version?
> 
> I get
> ```LLVM ERROR: Z3 error: unknown parameter 'timeout'```
> for the following testcases
> ```
> Failed Tests (3):
>   Clang-Unit :: StaticAnalyzer/./StaticAnalysisTests/24/188
>   Clang-Unit :: StaticAnalyzer/./StaticAnalysisTests/25/188
>   Clang-Unit :: StaticAnalyzer/./StaticAnalysisTests/26/188
> ```
> 

I'm not aware. I used the latest Z3 when testing. I'll have a look.

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


  1   2   3   4   5   >