[clang] 0c7a605 - clangCodeGen: [MC/DC] Refactor CoverageGen.

2024-02-25 Thread NAKAMURA Takumi via cfe-commits

Author: NAKAMURA Takumi
Date: 2024-02-26T16:44:19+09:00
New Revision: 0c7a605ada6cb392e6e8c16dbccf2b7e59017399

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

LOG: clangCodeGen: [MC/DC] Refactor CoverageGen.

- Introduce `createDecision(E)` for the root node of `VisitBin`.
- Handle `mcdc::DecisionParameters` for each Decision method.

Added: 


Modified: 
clang/lib/CodeGen/CoverageMappingGen.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index d98ab79eac3aed..e25a92758f32b7 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -852,10 +852,6 @@ struct CounterCoverageMappingBuilder
 return Counter::getCounter(CounterMap[S]);
   }
 
-  auto getBitmapIdx(const Stmt *S) {
-return MCDCState.DecisionByStmt[S].BitmapIdx;
-  }
-
   /// Push a region onto the stack.
   ///
   /// Returns the index on the stack where the region was pushed. This can be
@@ -888,12 +884,11 @@ struct CounterCoverageMappingBuilder
 return RegionStack.size() - 1;
   }
 
-  size_t pushRegion(unsigned BitmapIdx, uint16_t Conditions,
+  size_t pushRegion(const mcdc::DecisionParameters ,
 std::optional StartLoc = std::nullopt,
 std::optional EndLoc = std::nullopt) {
 
-RegionStack.emplace_back(mcdc::DecisionParameters{BitmapIdx, Conditions},
- StartLoc, EndLoc);
+RegionStack.emplace_back(DecisionParams, StartLoc, EndLoc);
 
 return RegionStack.size() - 1;
   }
@@ -1059,8 +1054,9 @@ struct CounterCoverageMappingBuilder
   /// Create a Decision Region with a BitmapIdx and number of Conditions. This
   /// type of region "contains" branch regions, one for each of the conditions.
   /// The visualization tool will group everything together.
-  void createDecisionRegion(const Expr *C, unsigned BitmapIdx, unsigned Conds) 
{
-popRegions(pushRegion(BitmapIdx, Conds, getStart(C), getEnd(C)));
+  void createDecisionRegion(const Expr *C,
+const mcdc::DecisionParameters ) {
+popRegions(pushRegion(DecisionParams, getStart(C), getEnd(C)));
   }
 
   /// Create a Branch Region around a SwitchCase for code coverage
@@ -1312,7 +1308,7 @@ struct CounterCoverageMappingBuilder
   return;
 assert(SpellingRegion(SM, NewStartLoc, EndLoc).isInSourceOrder());
 handleFileExit(NewStartLoc);
-size_t Index = pushRegion({}, NewStartLoc, EndLoc);
+size_t Index = pushRegion(Counter{}, NewStartLoc, EndLoc);
 getRegion().setSkipped(true);
 handleFileExit(EndLoc);
 popRegions(Index);
@@ -1962,6 +1958,20 @@ struct CounterCoverageMappingBuilder
subtractCounters(ParentCount, TrueCount));
   }
 
+  void createDecision(const BinaryOperator *E) {
+unsigned NumConds = MCDCBuilder.getTotalConditionsAndReset(E);
+if (NumConds == 0)
+  return;
+
+auto DecisionParams = mcdc::DecisionParameters{
+MCDCState.DecisionByStmt[E].BitmapIdx,
+NumConds,
+};
+
+// Create MCDC Decision Region.
+createDecisionRegion(E, DecisionParams);
+  }
+
   void VisitBinLAnd(const BinaryOperator *E) {
 bool IsRootNode = MCDCBuilder.isIdle();
 
@@ -1982,11 +1992,6 @@ struct CounterCoverageMappingBuilder
 // Track RHS True/False Decision.
 const auto DecisionRHS = MCDCBuilder.back();
 
-// Create MCDC Decision Region if at top-level (root).
-unsigned NumConds = 0;
-if (IsRootNode && (NumConds = MCDCBuilder.getTotalConditionsAndReset(E)))
-  createDecisionRegion(E, getBitmapIdx(E), NumConds);
-
 // Extract the RHS's Execution Counter.
 Counter RHSExecCnt = getRegionCounter(E);
 
@@ -2003,6 +2008,10 @@ struct CounterCoverageMappingBuilder
 // Create Branch Region around RHS condition.
 createBranchRegion(E->getRHS(), RHSTrueCnt,
subtractCounters(RHSExecCnt, RHSTrueCnt), DecisionRHS);
+
+// Create MCDC Decision Region if at top-level (root).
+if (IsRootNode)
+  createDecision(E);
   }
 
   // Determine whether the right side of OR operation need to be visited.
@@ -2035,11 +2044,6 @@ struct CounterCoverageMappingBuilder
 // Track RHS True/False Decision.
 const auto DecisionRHS = MCDCBuilder.back();
 
-// Create MCDC Decision Region if at top-level (root).
-unsigned NumConds = 0;
-if (IsRootNode && (NumConds = MCDCBuilder.getTotalConditionsAndReset(E)))
-  createDecisionRegion(E, getBitmapIdx(E), NumConds);
-
 // Extract the RHS's Execution Counter.
 Counter RHSExecCnt = getRegionCounter(E);
 
@@ -2060,6 +2064,10 @@ struct CounterCoverageMappingBuilder
 // Create Branch Region around RHS condition.
 

[clang-tools-extra] [clangd] Add support for textDocument/rangesFormatting (LSP 3.18) (PR #80180)

2024-02-25 Thread Tom Praschan via cfe-commits

tom-anders wrote:

(ping)

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


[clang] cace477 - [clang][AArch64] multilib: fix deduction of "-march=" option (#81474)

2024-02-25 Thread via cfe-commits

Author: Dominik Wójt
Date: 2024-02-26T08:09:33+01:00
New Revision: cace477c0b6c3d9494ead66eb725c6e72f27b767

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

LOG: [clang][AArch64] multilib: fix deduction of "-march=" option (#81474)

The deduced "-march=" option always started with aarch64, which is not a
valid value. There was also no way to distinguish between armv8-r and
armv8-a. After this commit, the deduced "-march=" option will start with
greatest available "armv*-a" value or "armv8-r".

Added: 


Modified: 
clang/lib/Driver/ToolChain.cpp
clang/test/Driver/print-multi-selection-flags.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index f8c13c86daf9b0..bd854aae35d4ce 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -200,7 +200,12 @@ static void getAArch64MultilibFlags(const Driver ,
   for (const auto  : AArch64::Extensions)
 if (FeatureSet.contains(Ext.NegFeature))
   MArch.push_back(("no" + Ext.Name).str());
-  MArch.insert(MArch.begin(), ("-march=" + Triple.getArchName()).str());
+  StringRef ArchName;
+  for (const auto  : AArch64::ArchInfos)
+if (FeatureSet.contains(ArchInfo->ArchFeature))
+  ArchName = ArchInfo->Name;
+  assert(!ArchName.empty() && "at least one architecture should be found");
+  MArch.insert(MArch.begin(), ("-march=" + ArchName).str());
   Result.push_back(llvm::join(MArch, "+"));
 }
 

diff  --git a/clang/test/Driver/print-multi-selection-flags.c 
b/clang/test/Driver/print-multi-selection-flags.c
index 248d9a3cdf49b2..06a12db9d97792 100644
--- a/clang/test/Driver/print-multi-selection-flags.c
+++ b/clang/test/Driver/print-multi-selection-flags.c
@@ -51,9 +51,10 @@
 // CHECK-M85_NO_FP_DP: -mfpu=fp-armv8-fullfp16-sp-d16
 
 // RUN: %clang -print-multi-flags-experimental --target=aarch64-none-elf 
-march=armv8-a+lse | FileCheck --check-prefix=CHECK-LSE %s
-// CHECK-LSE: -march=aarch64{{.*}}+lse{{.*}}
+// CHECK-LSE: --target=aarch64-none-unknown-elf
+// CHECK-LSE: -march=armv8-a{{.*}}+lse{{.*}}
 
 // RUN: %clang -print-multi-flags-experimental --target=aarch64-none-elf 
-march=armv8.5-a+sve+sve2 | FileCheck --check-prefix=CHECK-SVE2 %s
 // RUN: %clang -print-multi-flags-experimental --target=aarch64-none-elf 
-march=armv9-a| FileCheck --check-prefix=CHECK-SVE2 %s
 // CHECK-SVE2: --target=aarch64-none-unknown-elf
-// CHECK-SVE2: -march=aarch64{{.*}}+simd{{.*}}+sve{{.*}}+sve2{{.*}}
+// CHECK-SVE2: -march=armv{{.*}}-a{{.*}}+simd{{.*}}+sve{{.*}}+sve2{{.*}}



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


[clang] [clang][AArch64] multilib: fix deduction of "-march=" option (PR #81474)

2024-02-25 Thread Dominik Wójt via cfe-commits

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


[clang] [clang-format] Limit how much work guessLanguage() can do (PR #78925)

2024-02-25 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

> @HighCommander4 I got a better idea. It seems that we don't need to add the 
> parameter! See #82957. I think all you need to do is to call `getStyle()` 
> with the default `""` for the `StringRef Code` argument to skip the 
> Objective-C guesser.

Thanks. That does seem simpler, and seems like it should work just as well 
since the language guesser is the only thing that uses the `Code` argument.

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


[clang-tools-extra] [clang-tidy] bugprone-unused-return-value config now supports regexes (PR #82952)

2024-02-25 Thread Congcong Cai via cfe-commits

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


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


[clang] [OpenMP][Clang] Enable inscan modifier for generic datatypes (PR #82220)

2024-02-25 Thread Animesh Kumar via cfe-commits

https://github.com/animeshk-amd updated 
https://github.com/llvm/llvm-project/pull/82220

>From 26d8d82a3070700dd327337d37c757eb1db6f2cc Mon Sep 17 00:00:00 2001
From: Animesh Kumar 
Date: Mon, 19 Feb 2024 00:28:39 -0600
Subject: [PATCH] [OpenMP][Clang] Enable inscan modifier for generic datatypes

This patch fixes the #67002 ([OpenMP][Clang] Scan Directive not
supported for Generic types). It disables the Sema checks/analysis
that are run on the helper arrays which go into the implementation
of the `omp scan` directive until the template instantiation
happens.
---
 clang/lib/Sema/SemaOpenMP.cpp|  3 ++-
 clang/test/OpenMP/scan_ast_print.cpp | 18 ++
 2 files changed, 20 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp
index 7f75cfc5b54f35..f4364a259ad57f 100644
--- a/clang/lib/Sema/SemaOpenMP.cpp
+++ b/clang/lib/Sema/SemaOpenMP.cpp
@@ -4962,7 +4962,8 @@ StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
   if (RC->getModifier() != OMPC_REDUCTION_inscan)
 continue;
   for (Expr *E : RC->copy_array_temps())
-MarkDeclarationsReferencedInExpr(E);
+if (E)
+  MarkDeclarationsReferencedInExpr(E);
 }
 if (auto *AC = dyn_cast(C)) {
   for (Expr *E : AC->varlists())
diff --git a/clang/test/OpenMP/scan_ast_print.cpp 
b/clang/test/OpenMP/scan_ast_print.cpp
index 3bbd3b60c3e8c4..82cb13eb6e70f7 100644
--- a/clang/test/OpenMP/scan_ast_print.cpp
+++ b/clang/test/OpenMP/scan_ast_print.cpp
@@ -17,6 +17,10 @@ T tmain(T argc) {
   static T a;
 #pragma omp for reduction(inscan, +: a)
   for (int i = 0; i < 10; ++i) {
+#pragma omp scan inclusive(a)
+  }
+#pragma omp parallel for reduction(inscan, +:a)
+  for (int i = 0; i < 10; ++i) {
 #pragma omp scan inclusive(a)
   }
   return a + argc;
@@ -25,15 +29,29 @@ T tmain(T argc) {
 // CHECK-NEXT: #pragma omp for reduction(inscan, +: a)
 // CHECK-NEXT: for (int i = 0; i < 10; ++i) {
 // CHECK-NEXT: #pragma omp scan inclusive(a){{$}}
+
+// CHECK: #pragma omp parallel for reduction(inscan, +: a)
+// CHECK-NEXT: for (int i = 0; i < 10; ++i) {
+// CHECK-NEXT: #pragma omp scan inclusive(a){{$}}
+
 // CHECK:  static int a;
 // CHECK-NEXT: #pragma omp for reduction(inscan, +: a)
 // CHECK-NEXT: for (int i = 0; i < 10; ++i) {
 // CHECK-NEXT: #pragma omp scan inclusive(a)
+
+// CHECK: #pragma omp parallel for reduction(inscan, +: a)
+// CHECK-NEXT: for (int i = 0; i < 10; ++i) {
+// CHECK-NEXT: #pragma omp scan inclusive(a)
+
 // CHECK:  static char a;
 // CHECK-NEXT: #pragma omp for reduction(inscan, +: a)
 // CHECK-NEXT: for (int i = 0; i < 10; ++i) {
 // CHECK-NEXT: #pragma omp scan inclusive(a)
 
+// CHECK: #pragma omp parallel for reduction(inscan, +: a)
+// CHECK-NEXT: for (int i = 0; i < 10; ++i) {
+// CHECK-NEXT: #pragma omp scan inclusive(a)
+
 int main(int argc, char **argv) {
   static int a;
 // CHECK: static int a;

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


[clang] [OpenMP][Clang] Enable inscan modifier for generic datatypes (PR #82220)

2024-02-25 Thread Animesh Kumar via cfe-commits

https://github.com/animeshk-amd updated 
https://github.com/llvm/llvm-project/pull/82220

>From b5de1dd29956ae99ce7990554c4886453b2988e7 Mon Sep 17 00:00:00 2001
From: Animesh Kumar 
Date: Mon, 19 Feb 2024 00:28:39 -0600
Subject: [PATCH] [OpenMP][Clang] Enable inscan modifier for generic datatypes

This patch fixes the #67002 ([OpenMP][Clang] Scan Directive not
supported for Generic types). It disables the Sema checks/analysis
that are run on the helper arrays which go into the implementation
of the `omp scan` directive until the template instantiation
happens.
---
 clang/lib/Sema/SemaOpenMP.cpp|  3 ++-
 clang/test/OpenMP/scan_ast_print.cpp | 18 ++
 2 files changed, 20 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp
index 7f75cfc5b54f35..f4364a259ad57f 100644
--- a/clang/lib/Sema/SemaOpenMP.cpp
+++ b/clang/lib/Sema/SemaOpenMP.cpp
@@ -4962,7 +4962,8 @@ StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
   if (RC->getModifier() != OMPC_REDUCTION_inscan)
 continue;
   for (Expr *E : RC->copy_array_temps())
-MarkDeclarationsReferencedInExpr(E);
+if (E)
+  MarkDeclarationsReferencedInExpr(E);
 }
 if (auto *AC = dyn_cast(C)) {
   for (Expr *E : AC->varlists())
diff --git a/clang/test/OpenMP/scan_ast_print.cpp 
b/clang/test/OpenMP/scan_ast_print.cpp
index 3bbd3b60c3e8c4..82cb13eb6e70f7 100644
--- a/clang/test/OpenMP/scan_ast_print.cpp
+++ b/clang/test/OpenMP/scan_ast_print.cpp
@@ -17,6 +17,10 @@ T tmain(T argc) {
   static T a;
 #pragma omp for reduction(inscan, +: a)
   for (int i = 0; i < 10; ++i) {
+#pragma omp scan inclusive(a)
+  }
+#pragma omp parallel for reduction(inscan, +:a)
+  for (int i = 0; i < 10; ++i) {
 #pragma omp scan inclusive(a)
   }
   return a + argc;
@@ -25,15 +29,29 @@ T tmain(T argc) {
 // CHECK-NEXT: #pragma omp for reduction(inscan, +: a)
 // CHECK-NEXT: for (int i = 0; i < 10; ++i) {
 // CHECK-NEXT: #pragma omp scan inclusive(a){{$}}
+
+// CHECK: #pragma omp parallel for reduction(inscan, +: a)
+// CHECK-NEXT: for (int i = 0; i < 10; ++i) {
+// CHECK-NEXT: #pragma omp scan inclusive(a){{$}}
+
 // CHECK:  static int a;
 // CHECK-NEXT: #pragma omp for reduction(inscan, +: a)
 // CHECK-NEXT: for (int i = 0; i < 10; ++i) {
 // CHECK-NEXT: #pragma omp scan inclusive(a)
+
+// CHECK: #pragma omp parallel for reduction(inscan, +: a)
+// CHECK-NEXT: for (int i = 0; i < 10; ++i) {
+// CHECK-NEXT: #pragma omp scan inclusive(a)
+
 // CHECK:  static char a;
 // CHECK-NEXT: #pragma omp for reduction(inscan, +: a)
 // CHECK-NEXT: for (int i = 0; i < 10; ++i) {
 // CHECK-NEXT: #pragma omp scan inclusive(a)
 
+// CHECK: #pragma omp parallel for reduction(inscan, +: a)
+// CHECK-NEXT: for (int i = 0; i < 10; ++i) {
+// CHECK-NEXT: #pragma omp scan inclusive(a)
+
 int main(int argc, char **argv) {
   static int a;
 // CHECK: static int a;

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


[clang-tools-extra] [clangd] Support outgoing calls in call hierarchy (PR #77556)

2024-02-25 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

@sam-mccall review ping :)

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


[clang] 8c5e9cf - [clang][Interp] Implement nullability argument checking

2024-02-25 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-26T06:19:25+01:00
New Revision: 8c5e9cf737138aba22a4a8f64ef2c5efc80dd7f9

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

LOG: [clang][Interp] Implement nullability argument checking

Implement constexpr checking for null pointers being passed to
arguments annotated as nonnull.

Added: 
clang/lib/AST/Interp/InterpShared.cpp
clang/lib/AST/Interp/InterpShared.h
clang/test/AST/Interp/nullable.cpp

Modified: 
clang/lib/AST/CMakeLists.txt
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/lib/AST/Interp/Function.h
clang/lib/AST/Interp/Interp.cpp
clang/lib/AST/Interp/Interp.h
clang/lib/AST/Interp/Opcodes.td
clang/test/Sema/attr-nonnull.c
clang/test/SemaCXX/attr-nonnull.cpp

Removed: 




diff  --git a/clang/lib/AST/CMakeLists.txt b/clang/lib/AST/CMakeLists.txt
index d793c3ed0410a8..6ea1ca3e76cf33 100644
--- a/clang/lib/AST/CMakeLists.txt
+++ b/clang/lib/AST/CMakeLists.txt
@@ -88,6 +88,7 @@ add_clang_library(clangAST
   Interp/Record.cpp
   Interp/Source.cpp
   Interp/State.cpp
+  Interp/InterpShared.cpp
   ItaniumCXXABI.cpp
   ItaniumMangle.cpp
   JSONNodeDumper.cpp

diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 7f97d8ce9fb804..eb5a1b536b7798 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -13,8 +13,10 @@
 #include "Context.h"
 #include "Floating.h"
 #include "Function.h"
+#include "InterpShared.h"
 #include "PrimType.h"
 #include "Program.h"
+#include "clang/AST/Attr.h"
 
 using namespace clang;
 using namespace clang::interp;
@@ -2656,6 +2658,7 @@ bool ByteCodeExprGen::VisitCallExpr(const 
CallExpr *E) {
   QualType ReturnType = E->getCallReturnType(Ctx.getASTContext());
   std::optional T = classify(ReturnType);
   bool HasRVO = !ReturnType->isVoidType() && !T;
+  const FunctionDecl *FuncDecl = E->getDirectCallee();
 
   if (HasRVO) {
 if (DiscardResult) {
@@ -2673,17 +2676,16 @@ bool ByteCodeExprGen::VisitCallExpr(const 
CallExpr *E) {
 }
   }
 
-  auto Args = E->arguments();
+  auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
   // Calling a static operator will still
   // pass the instance, but we don't need it.
   // Discard it here.
   if (isa(E)) {
-if (const auto *MD =
-dyn_cast_if_present(E->getDirectCallee());
+if (const auto *MD = dyn_cast_if_present(FuncDecl);
 MD && MD->isStatic()) {
   if (!this->discard(E->getArg(0)))
 return false;
-  Args = drop_begin(Args, 1);
+  Args = Args.drop_front();
 }
   }
 
@@ -2693,13 +2695,25 @@ bool ByteCodeExprGen::VisitCallExpr(const 
CallExpr *E) {
   return false;
   }
 
+  llvm::BitVector NonNullArgs = collectNonNullArgs(FuncDecl, Args);
   // Put arguments on the stack.
+  unsigned ArgIndex = 0;
   for (const auto *Arg : Args) {
 if (!this->visit(Arg))
   return false;
+
+// If we know the callee already, check the known parametrs for 
nullability.
+if (FuncDecl && NonNullArgs[ArgIndex]) {
+  PrimType ArgT = classify(Arg).value_or(PT_Ptr);
+  if (ArgT == PT_Ptr || ArgT == PT_FnPtr) {
+if (!this->emitCheckNonNullArg(ArgT, Arg))
+  return false;
+  }
+}
+++ArgIndex;
   }
 
-  if (const FunctionDecl *FuncDecl = E->getDirectCallee()) {
+  if (FuncDecl) {
 const Function *Func = getFunction(FuncDecl);
 if (!Func)
   return false;
@@ -2748,7 +2762,7 @@ bool ByteCodeExprGen::VisitCallExpr(const 
CallExpr *E) {
 if (!this->visit(E->getCallee()))
   return false;
 
-if (!this->emitCallPtr(ArgSize, E))
+if (!this->emitCallPtr(ArgSize, E, E))
   return false;
   }
 

diff  --git a/clang/lib/AST/Interp/Function.h b/clang/lib/AST/Interp/Function.h
index b19d64f9371e3c..0be4564e1e9ec4 100644
--- a/clang/lib/AST/Interp/Function.h
+++ b/clang/lib/AST/Interp/Function.h
@@ -15,9 +15,10 @@
 #ifndef LLVM_CLANG_AST_INTERP_FUNCTION_H
 #define LLVM_CLANG_AST_INTERP_FUNCTION_H
 
-#include "Source.h"
 #include "Descriptor.h"
+#include "Source.h"
 #include "clang/AST/ASTLambda.h"
+#include "clang/AST/Attr.h"
 #include "clang/AST/Decl.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -108,6 +109,8 @@ class Function final {
   /// Checks if the first argument is a RVO pointer.
   bool hasRVO() const { return HasRVO; }
 
+  bool hasNonNullAttr() const { return getDecl()->hasAttr(); }
+
   /// Range over the scope blocks.
   llvm::iterator_range::const_iterator>
   scopes() const {

diff  --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index b2fe70dc14f9d5..5670888c245eb1 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -7,10 +7,9 @@
 

[clang] [clang-format] Add a parameter to getStyle() and guessLanguage() (PR #82911)

2024-02-25 Thread Owen Pan via cfe-commits

owenca wrote:

I will abandon this pull request if #82957 gets approved.

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


[clang] [clang-format] Add a parameter to getStyle() and guessLanguage() (PR #82911)

2024-02-25 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Limit how much work guessLanguage() can do (PR #78925)

2024-02-25 Thread Owen Pan via cfe-commits

owenca wrote:

@HighCommander4 I got a better idea. It seems that we don't need to add the 
parameter! See #82957. I think all you need to do is to call `getStyle()` with 
the default `""` for the `StringRef Code` argument to skip the Objective-C 
guesser.

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


[clang] [llvm] [AMDGPU] Enable OpenCL hostcall printf (WIP) (PR #72556)

2024-02-25 Thread Sameer Sahasrabuddhe via cfe-commits

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


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


[clang] [clang][NFC] constify or staticify some CGRecordLowering fns (PR #82874)

2024-02-25 Thread Eli Friedman via cfe-commits

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

I'm not sure there's really much point to passing around a const reference to a 
CGRecordLowering; all the uses are in one file, so const-correctness doesn't 
seem to help that much.

But if you want to do it this way, that's fine; LGTM

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


[clang] [clang-format][NFC] Skip ObjCHeaderStyleGuesser for empty code (PR #82957)

2024-02-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes



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


1 Files Affected:

- (modified) clang/lib/Format/Format.cpp (+1-1) 


``diff
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 2f6b52510099a7..00ffc6718e052b 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3920,7 +3920,7 @@ FormatStyle::LanguageKind guessLanguage(StringRef 
FileName, StringRef Code) {
 auto Extension = llvm::sys::path::extension(FileName);
 // If there's no file extension (or it's .h), we need to check the contents
 // of the code to see if it contains Objective-C.
-if (Extension.empty() || Extension == ".h") {
+if (!Code.empty() && (Extension.empty() || Extension == ".h")) {
   auto NonEmptyFileName = FileName.empty() ? "guess.h" : FileName;
   Environment Env(Code, NonEmptyFileName, /*Ranges=*/{});
   ObjCHeaderStyleGuesser Guesser(Env, getLLVMStyle());

``




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


[clang] [clang-format][NFC] Skip ObjCHeaderStyleGuesser for empty code (PR #82957)

2024-02-25 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/82957

None

>From 9334d008b4c7ae13fdeb674a6bb9b4dc62c6a1dd Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sun, 25 Feb 2024 20:58:25 -0800
Subject: [PATCH] [clang-format][NFC] Skip ObjCHeaderStyleGuesser for empty
 code

---
 clang/lib/Format/Format.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 2f6b52510099a7..00ffc6718e052b 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3920,7 +3920,7 @@ FormatStyle::LanguageKind guessLanguage(StringRef 
FileName, StringRef Code) {
 auto Extension = llvm::sys::path::extension(FileName);
 // If there's no file extension (or it's .h), we need to check the contents
 // of the code to see if it contains Objective-C.
-if (Extension.empty() || Extension == ".h") {
+if (!Code.empty() && (Extension.empty() || Extension == ".h")) {
   auto NonEmptyFileName = FileName.empty() ? "guess.h" : FileName;
   Environment Env(Code, NonEmptyFileName, /*Ranges=*/{});
   ObjCHeaderStyleGuesser Guesser(Env, getLLVMStyle());

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


[clang] [TBAA] Skip all bitfields when generating !tbaa.struct metadata. (PR #82922)

2024-02-25 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

This seems like it messes up the metadata in a different way: we have no 
representation of the bitfield at all, so it looks like it's padding.

I think we want to treat multiple adjacent bitfields as a single "field".  So 
NamedBitfields from the testcase would have three fields in the LLVM TBAA data: 
one "field" containing both bitfields, followed by a field for the char, 
followed by a field for the double.  You should be able to use CGBitFieldInfo 
for this, I think?

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


[clang] [clang-tools-extra] clangd: Show argument names for function pointer struct fields (PR #69011)

2024-02-25 Thread Nathan Ridge via cfe-commits

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


[clang] [clang-tools-extra] clangd: Show argument names for function pointer struct fields (PR #69011)

2024-02-25 Thread Nathan Ridge via cfe-commits


@@ -6143,6 +6144,13 @@ static FunctionProtoTypeLoc GetPrototypeLoc(Expr *Fn) {
 }
   }
 
+  if (const auto *ME = dyn_cast(Fn)) {

HighCommander4 wrote:

nit: make this an `else if` (i.e. make it part of the chain just above), and 
then the `!Target` condition below becomes unnecessary

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


[clang] [clang-tools-extra] clangd: Show argument names for function pointer struct fields (PR #69011)

2024-02-25 Thread Nathan Ridge via cfe-commits

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

Thanks for the update! Looks good with a final nit.

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


[clang] [HIP] fix host min/max in header (PR #82956)

2024-02-25 Thread Yaxun Liu via cfe-commits


@@ -1306,14 +1306,50 @@ float min(float __x, float __y) { return 
__builtin_fminf(__x, __y); }
 __DEVICE__
 double min(double __x, double __y) { return __builtin_fmin(__x, __y); }
 
+// Define host min/max functions.
+
 #if !defined(__HIPCC_RTC__) && !defined(__OPENMP_AMDGCN__)
-__host__ inline static int min(int __arg1, int __arg2) {
-  return __arg1 < __arg2 ? __arg1 : __arg2;
-}
 
-__host__ inline static int max(int __arg1, int __arg2) {
-  return __arg1 > __arg2 ? __arg1 : __arg2;
-}
+#pragma push_macro("DEFINE_MIN_MAX_FUNCTIONS")
+#define DEFINE_MIN_MAX_FUNCTIONS(type1, type2) \
+static inline auto min(const type1 __a, const type2 __b) \
+  -> typename std::remove_reference::type { \
+  return (__a < __b) ? __a : __b; \
+} \
+static inline auto max(const type1 __a, const type2 __b) \
+  -> typename std::remove_reference __b ? __a : __b)>::type { \
+  return (__a > __b) ? __a : __b; \
+}
+
+// Define min and max functions for same type comparisons
+DEFINE_MIN_MAX_FUNCTIONS(int, int)

yxsamliu wrote:

it will return reference of `__a` or `__b`. that won't work since it is 
reference to stack var

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


[clang] [clang] Better bitfield access units (PR #65742)

2024-02-25 Thread Lu Weining via cfe-commits


@@ -132,6 +132,7 @@ class LLVM_LIBRARY_VISIBILITY LoongArch64TargetInfo
   : LoongArchTargetInfo(Triple, Opts) {
 LongWidth = LongAlign = PointerWidth = PointerAlign = 64;
 IntMaxType = Int64Type = SignedLong;
+HasCheapUnalignedBitfieldAccess = true;

SixWeining wrote:

> you say set to true when -mno-unaligned-access, but I think you mean set to 
> false in that case?

Yes, I think it should be `false`. @wzssyqa 

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


[clang] [HIP] fix host min/max in header (PR #82956)

2024-02-25 Thread Joseph Huber via cfe-commits


@@ -1306,14 +1306,50 @@ float min(float __x, float __y) { return 
__builtin_fminf(__x, __y); }
 __DEVICE__
 double min(double __x, double __y) { return __builtin_fmin(__x, __y); }
 
+// Define host min/max functions.
+
 #if !defined(__HIPCC_RTC__) && !defined(__OPENMP_AMDGCN__)
-__host__ inline static int min(int __arg1, int __arg2) {
-  return __arg1 < __arg2 ? __arg1 : __arg2;
-}
 
-__host__ inline static int max(int __arg1, int __arg2) {
-  return __arg1 > __arg2 ? __arg1 : __arg2;
-}
+#pragma push_macro("DEFINE_MIN_MAX_FUNCTIONS")
+#define DEFINE_MIN_MAX_FUNCTIONS(type1, type2) \
+static inline auto min(const type1 __a, const type2 __b) \
+  -> typename std::remove_reference::type { \
+  return (__a < __b) ? __a : __b; \
+} \
+static inline auto max(const type1 __a, const type2 __b) \
+  -> typename std::remove_reference __b ? __a : __b)>::type { \
+  return (__a > __b) ? __a : __b; \
+}
+
+// Define min and max functions for same type comparisons
+DEFINE_MIN_MAX_FUNCTIONS(int, int)

jhuber6 wrote:

Could we not do something like this w/ the appropriate static assertion? Or is 
there an important restriction on the specific types for this function.
```c
template 
static inline auto min(const T &__a, const U &__b) {
  return (__a < __b) ? __a : __b;
}
```

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


[clang] [HIP] fix host min/max in header (PR #82956)

2024-02-25 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 8be39b3901e3326ceebeaf0381f8cc57fdc0d464 
e36760486cc794dd3dc1604b0969b83f25bdd757 -- clang/lib/Headers/__clang_hip_math.h
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Headers/__clang_hip_math.h 
b/clang/lib/Headers/__clang_hip_math.h
index e87070e41b..dc4df40101 100644
--- a/clang/lib/Headers/__clang_hip_math.h
+++ b/clang/lib/Headers/__clang_hip_math.h
@@ -1311,15 +1311,15 @@ double min(double __x, double __y) { return 
__builtin_fmin(__x, __y); }
 #if !defined(__HIPCC_RTC__) && !defined(__OPENMP_AMDGCN__)
 
 #pragma push_macro("DEFINE_MIN_MAX_FUNCTIONS")
-#define DEFINE_MIN_MAX_FUNCTIONS(type1, type2) \
-static inline auto min(const type1 __a, const type2 __b) \
-  -> typename std::remove_reference::type { \
-  return (__a < __b) ? __a : __b; \
-} \
-static inline auto max(const type1 __a, const type2 __b) \
-  -> typename std::remove_reference __b ? __a : __b)>::type { \
-  return (__a > __b) ? __a : __b; \
-}
+#define DEFINE_MIN_MAX_FUNCTIONS(type1, type2) 
\
+  static inline auto min(const type1 __a, const type2 __b) ->  
\
+  typename std::remove_reference::type {  
\
+return (__a < __b) ? __a : __b;
\
+  }
\
+  static inline auto max(const type1 __a, const type2 __b) ->  
\
+  typename std::remove_reference __b ? __a : __b)>::type {  
\
+return (__a > __b) ? __a : __b;
\
+  }
 
 // Define min and max functions for same type comparisons
 DEFINE_MIN_MAX_FUNCTIONS(int, int)
@@ -1338,15 +1338,31 @@ DEFINE_MIN_MAX_FUNCTIONS(long long, unsigned long long)
 DEFINE_MIN_MAX_FUNCTIONS(unsigned long long, long long)
 
 // Floating-point comparisons using built-in functions
-static inline float min(float const __a, float const __b) { return 
__builtin_fminf(__a, __b); }
-static inline double min(double const __a, double const __b) { return 
__builtin_fmin(__a, __b); }
-static inline double min(float const __a, double const __b) { return 
__builtin_fmin(__a, __b); }
-static inline double min(double const __a, float const __b) { return 
__builtin_fmin(__a, __b); }
-
-static inline float max(float const __a, float const __b) { return 
__builtin_fmaxf(__a, __b); }
-static inline double max(double const __a, double const __b) { return 
__builtin_fmax(__a, __b); }
-static inline double max(float const __a, double const __b) { return 
__builtin_fmax(__a, __b); }
-static inline double max(double const __a, float const __b) { return 
__builtin_fmax(__a, __b); }
+static inline float min(float const __a, float const __b) {
+  return __builtin_fminf(__a, __b);
+}
+static inline double min(double const __a, double const __b) {
+  return __builtin_fmin(__a, __b);
+}
+static inline double min(float const __a, double const __b) {
+  return __builtin_fmin(__a, __b);
+}
+static inline double min(double const __a, float const __b) {
+  return __builtin_fmin(__a, __b);
+}
+
+static inline float max(float const __a, float const __b) {
+  return __builtin_fmaxf(__a, __b);
+}
+static inline double max(double const __a, double const __b) {
+  return __builtin_fmax(__a, __b);
+}
+static inline double max(float const __a, double const __b) {
+  return __builtin_fmax(__a, __b);
+}
+static inline double max(double const __a, float const __b) {
+  return __builtin_fmax(__a, __b);
+}
 
 #pragma pop_macro("DEFINE_MIN_MAX_FUNCTIONS")
 

``




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


[clang] [HIP] fix host min/max in header (PR #82956)

2024-02-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Yaxun (Sam) Liu (yxsamliu)


Changes

CUDA defines min/max functions for host in global namespace. HIP header needs 
to define them too to be compatible. Currently only min/max(int, int) is 
defined. This causes wrong result for arguments that are out of range for int. 
This patch defines host min/max functions to be compatible with CUDA.

Fixes: SWDEV-446564

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


1 Files Affected:

- (modified) clang/lib/Headers/__clang_hip_math.h (+42-6) 


``diff
diff --git a/clang/lib/Headers/__clang_hip_math.h 
b/clang/lib/Headers/__clang_hip_math.h
index 11e1e7d032586f..e87070e41b0ffc 100644
--- a/clang/lib/Headers/__clang_hip_math.h
+++ b/clang/lib/Headers/__clang_hip_math.h
@@ -1306,14 +1306,50 @@ float min(float __x, float __y) { return 
__builtin_fminf(__x, __y); }
 __DEVICE__
 double min(double __x, double __y) { return __builtin_fmin(__x, __y); }
 
+// Define host min/max functions.
+
 #if !defined(__HIPCC_RTC__) && !defined(__OPENMP_AMDGCN__)
-__host__ inline static int min(int __arg1, int __arg2) {
-  return __arg1 < __arg2 ? __arg1 : __arg2;
-}
 
-__host__ inline static int max(int __arg1, int __arg2) {
-  return __arg1 > __arg2 ? __arg1 : __arg2;
-}
+#pragma push_macro("DEFINE_MIN_MAX_FUNCTIONS")
+#define DEFINE_MIN_MAX_FUNCTIONS(type1, type2) \
+static inline auto min(const type1 __a, const type2 __b) \
+  -> typename std::remove_reference::type { \
+  return (__a < __b) ? __a : __b; \
+} \
+static inline auto max(const type1 __a, const type2 __b) \
+  -> typename std::remove_reference __b ? __a : __b)>::type { \
+  return (__a > __b) ? __a : __b; \
+}
+
+// Define min and max functions for same type comparisons
+DEFINE_MIN_MAX_FUNCTIONS(int, int)
+DEFINE_MIN_MAX_FUNCTIONS(unsigned int, unsigned int)
+DEFINE_MIN_MAX_FUNCTIONS(long, long)
+DEFINE_MIN_MAX_FUNCTIONS(unsigned long, unsigned long)
+DEFINE_MIN_MAX_FUNCTIONS(long long, long long)
+DEFINE_MIN_MAX_FUNCTIONS(unsigned long long, unsigned long long)
+
+// Define min and max functions for mixed type comparisons
+DEFINE_MIN_MAX_FUNCTIONS(int, unsigned int)
+DEFINE_MIN_MAX_FUNCTIONS(unsigned int, int)
+DEFINE_MIN_MAX_FUNCTIONS(long, unsigned long)
+DEFINE_MIN_MAX_FUNCTIONS(unsigned long, long)
+DEFINE_MIN_MAX_FUNCTIONS(long long, unsigned long long)
+DEFINE_MIN_MAX_FUNCTIONS(unsigned long long, long long)
+
+// Floating-point comparisons using built-in functions
+static inline float min(float const __a, float const __b) { return 
__builtin_fminf(__a, __b); }
+static inline double min(double const __a, double const __b) { return 
__builtin_fmin(__a, __b); }
+static inline double min(float const __a, double const __b) { return 
__builtin_fmin(__a, __b); }
+static inline double min(double const __a, float const __b) { return 
__builtin_fmin(__a, __b); }
+
+static inline float max(float const __a, float const __b) { return 
__builtin_fmaxf(__a, __b); }
+static inline double max(double const __a, double const __b) { return 
__builtin_fmax(__a, __b); }
+static inline double max(float const __a, double const __b) { return 
__builtin_fmax(__a, __b); }
+static inline double max(double const __a, float const __b) { return 
__builtin_fmax(__a, __b); }
+
+#pragma pop_macro("DEFINE_MIN_MAX_FUNCTIONS")
+
 #endif // !defined(__HIPCC_RTC__) && !defined(__OPENMP_AMDGCN__)
 #endif
 

``




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


[clang] [HIP] fix host min/max in header (PR #82956)

2024-02-25 Thread Yaxun Liu via cfe-commits

https://github.com/yxsamliu created 
https://github.com/llvm/llvm-project/pull/82956

CUDA defines min/max functions for host in global namespace. HIP header needs 
to define them too to be compatible. Currently only min/max(int, int) is 
defined. This causes wrong result for arguments that are out of range for int. 
This patch defines host min/max functions to be compatible with CUDA.

Fixes: SWDEV-446564

>From e36760486cc794dd3dc1604b0969b83f25bdd757 Mon Sep 17 00:00:00 2001
From: "Yaxun (Sam) Liu" 
Date: Sun, 25 Feb 2024 11:13:40 -0500
Subject: [PATCH] [HIP] fix host min/max in header

CUDA defines min/max functions for host in global namespace.
HIP header needs to define them too to be compatible.
Currently only min/max(int, int) is defined. This causes
wrong result for arguments that are out of range for int.
This patch defines host min/max functions to be compatible
with CUDA.

Fixes: SWDEV-446564
---
 clang/lib/Headers/__clang_hip_math.h | 48 
 1 file changed, 42 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Headers/__clang_hip_math.h 
b/clang/lib/Headers/__clang_hip_math.h
index 11e1e7d032586f..e87070e41b0ffc 100644
--- a/clang/lib/Headers/__clang_hip_math.h
+++ b/clang/lib/Headers/__clang_hip_math.h
@@ -1306,14 +1306,50 @@ float min(float __x, float __y) { return 
__builtin_fminf(__x, __y); }
 __DEVICE__
 double min(double __x, double __y) { return __builtin_fmin(__x, __y); }
 
+// Define host min/max functions.
+
 #if !defined(__HIPCC_RTC__) && !defined(__OPENMP_AMDGCN__)
-__host__ inline static int min(int __arg1, int __arg2) {
-  return __arg1 < __arg2 ? __arg1 : __arg2;
-}
 
-__host__ inline static int max(int __arg1, int __arg2) {
-  return __arg1 > __arg2 ? __arg1 : __arg2;
-}
+#pragma push_macro("DEFINE_MIN_MAX_FUNCTIONS")
+#define DEFINE_MIN_MAX_FUNCTIONS(type1, type2) \
+static inline auto min(const type1 __a, const type2 __b) \
+  -> typename std::remove_reference::type { \
+  return (__a < __b) ? __a : __b; \
+} \
+static inline auto max(const type1 __a, const type2 __b) \
+  -> typename std::remove_reference __b ? __a : __b)>::type { \
+  return (__a > __b) ? __a : __b; \
+}
+
+// Define min and max functions for same type comparisons
+DEFINE_MIN_MAX_FUNCTIONS(int, int)
+DEFINE_MIN_MAX_FUNCTIONS(unsigned int, unsigned int)
+DEFINE_MIN_MAX_FUNCTIONS(long, long)
+DEFINE_MIN_MAX_FUNCTIONS(unsigned long, unsigned long)
+DEFINE_MIN_MAX_FUNCTIONS(long long, long long)
+DEFINE_MIN_MAX_FUNCTIONS(unsigned long long, unsigned long long)
+
+// Define min and max functions for mixed type comparisons
+DEFINE_MIN_MAX_FUNCTIONS(int, unsigned int)
+DEFINE_MIN_MAX_FUNCTIONS(unsigned int, int)
+DEFINE_MIN_MAX_FUNCTIONS(long, unsigned long)
+DEFINE_MIN_MAX_FUNCTIONS(unsigned long, long)
+DEFINE_MIN_MAX_FUNCTIONS(long long, unsigned long long)
+DEFINE_MIN_MAX_FUNCTIONS(unsigned long long, long long)
+
+// Floating-point comparisons using built-in functions
+static inline float min(float const __a, float const __b) { return 
__builtin_fminf(__a, __b); }
+static inline double min(double const __a, double const __b) { return 
__builtin_fmin(__a, __b); }
+static inline double min(float const __a, double const __b) { return 
__builtin_fmin(__a, __b); }
+static inline double min(double const __a, float const __b) { return 
__builtin_fmin(__a, __b); }
+
+static inline float max(float const __a, float const __b) { return 
__builtin_fmaxf(__a, __b); }
+static inline double max(double const __a, double const __b) { return 
__builtin_fmax(__a, __b); }
+static inline double max(float const __a, double const __b) { return 
__builtin_fmax(__a, __b); }
+static inline double max(double const __a, float const __b) { return 
__builtin_fmax(__a, __b); }
+
+#pragma pop_macro("DEFINE_MIN_MAX_FUNCTIONS")
+
 #endif // !defined(__HIPCC_RTC__) && !defined(__OPENMP_AMDGCN__)
 #endif
 

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


[clang-tools-extra] [clang-tidy] Improved modernize-use-using by fixing a false-negative (PR #82947)

2024-02-25 Thread Félix-Antoine Constantin via cfe-commits

https://github.com/felix642 updated 
https://github.com/llvm/llvm-project/pull/82947

From d1cbed0e2e83bd3544067fd25d7e811f1ab3f095 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?F=C3=A9lix-Antoine=20Constantin?=
 
Date: Sun, 25 Feb 2024 20:20:59 -0500
Subject: [PATCH 1/2] [clang-tidy] Improved modernize-use-using by fixing a
 false-negative

The check needs a parent decl to match but if the typedef is in a function,
the parent is a declStmt which is not a decl by itself.
Improved the matcher to match on either a decl or a declstmt and extract
the decl from the stmt in the latter case.

fixes #72179
---
 .../clang-tidy/modernize/UseUsingCheck.cpp | 16 +---
 clang-tools-extra/docs/ReleaseNotes.rst|  3 +++
 .../checkers/modernize/use-using.cpp   | 18 ++
 3 files changed, 34 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
index bb05f206c717ce..50a07fc02e31b4 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
@@ -24,6 +24,7 @@ static constexpr llvm::StringLiteral ExternCDeclName = 
"extern-c-decl";
 static constexpr llvm::StringLiteral ParentDeclName = "parent-decl";
 static constexpr llvm::StringLiteral TagDeclName = "tag-decl";
 static constexpr llvm::StringLiteral TypedefName = "typedef";
+static constexpr llvm::StringLiteral DeclStmtName = "decl-stmt";
 
 UseUsingCheck::UseUsingCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
@@ -41,7 +42,8 @@ void UseUsingCheck::registerMatchers(MatchFinder *Finder) {
   unless(isInstantiated()),
   optionally(hasAncestor(
   linkageSpecDecl(isExternCLinkage()).bind(ExternCDeclName))),
-  hasParent(decl().bind(ParentDeclName)))
+  anyOf(hasParent(decl().bind(ParentDeclName)),
+hasParent(declStmt().bind(DeclStmtName
   .bind(TypedefName),
   this);
 
@@ -51,17 +53,25 @@ void UseUsingCheck::registerMatchers(MatchFinder *Finder) {
   tagDecl(
   anyOf(allOf(unless(anyOf(isImplicit(),
classTemplateSpecializationDecl())),
-  hasParent(decl().bind(ParentDeclName))),
+  anyOf(hasParent(decl().bind(ParentDeclName)),
+hasParent(declStmt().bind(DeclStmtName,
 // We want the parent of the ClassTemplateDecl, not the parent
 // of the specialization.
 classTemplateSpecializationDecl(hasAncestor(classTemplateDecl(
-hasParent(decl().bind(ParentDeclName)))
+anyOf(hasParent(decl().bind(ParentDeclName)),
+  hasParent(declStmt().bind(DeclStmtName
   .bind(TagDeclName),
   this);
 }
 
 void UseUsingCheck::check(const MatchFinder::MatchResult ) {
   const auto *ParentDecl = Result.Nodes.getNodeAs(ParentDeclName);
+
+  if (!ParentDecl) {
+const auto *ParentDeclStmt = 
Result.Nodes.getNodeAs(DeclStmtName);
+ParentDecl = ParentDeclStmt->getSingleDecl();
+  }
+
   if (!ParentDecl)
 return;
 
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 6fd01ed9d471c5..2b36ae4acb9f1d 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -183,6 +183,9 @@ Changes in existing checks
   ` check to also remove any trailing
   whitespace when deleting the ``virtual`` keyword.
 
+- Improved :doc:`modernize-use-using `
+  check by fixing false-negative in functions.
+
 - Improved :doc:`readability-implicit-bool-conversion
   ` check to provide
   valid fix suggestions for ``static_cast`` without a preceding space and
diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
index 462bc984fd3ad5..230c7c94cda1cf 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
@@ -342,3 +342,21 @@ typedef int InExternCPP;
 // CHECK-FIXES: using InExternCPP = int;
 
 }
+
+namespace ISSUE_72179
+{  
+  void foo()
+  {
+typedef int a;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use 'using' instead of 
'typedef' [modernize-use-using]
+// CHECK-FIXES: using a = int;
+
+  }
+
+  void foo2()
+  {
+typedef struct { int a; union { int b; }; } c;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use 'using' instead of 
'typedef' [modernize-use-using]
+// CHECK-FIXES: using c = struct { int a; union { int b; }; };
+  }
+}

From 0b5c78508fbf49229d576171d7af6c6bb16b4367 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?F=C3=A9lix-Antoine=20Constantin?=
 
Date: Sun, 25 Feb 2024 22:14:22 -0500
Subject: [PATCH 2/2] fixup! [clang-tidy] 

[clang-tools-extra] [clang-tidy] bugprone-unused-return-value config now supports regexes (PR #82952)

2024-02-25 Thread via cfe-commits

llvmbot wrote:




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

Author: Félix-Antoine Constantin (felix642)


Changes

The parameter `CheckedReturnTypes` now supports regexes

Fixes #63107

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


5 Files Affected:

- (modified) clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp 
(+101-101) 
- (modified) clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h 
(+3-3) 
- (modified) clang-tools-extra/clang-tidy/hicpp/IgnoredRemoveResultCheck.cpp 
(+5-3) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+4) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value-custom.cpp
 (+1-1) 


``diff
diff --git a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
index 05012c7df6a975..b4bf85c912c3ca 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
@@ -33,98 +33,98 @@ AST_MATCHER_P(FunctionDecl, isInstantiatedFrom, 
Matcher,
 UnusedReturnValueCheck::UnusedReturnValueCheck(llvm::StringRef Name,
ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
-  CheckedFunctions(Options.get("CheckedFunctions",
-   "::std::async;"
-   "::std::launder;"
-   "::std::remove;"
-   "::std::remove_if;"
-   "::std::unique;"
-   "::std::unique_ptr::release;"
-   "::std::basic_string::empty;"
-   "::std::vector::empty;"
-   "::std::back_inserter;"
-   "::std::distance;"
-   "::std::find;"
-   "::std::find_if;"
-   "::std::inserter;"
-   "::std::lower_bound;"
-   "::std::make_pair;"
-   "::std::map::count;"
-   "::std::map::find;"
-   "::std::map::lower_bound;"
-   "::std::multimap::equal_range;"
-   "::std::multimap::upper_bound;"
-   "::std::set::count;"
-   "::std::set::find;"
-   "::std::setfill;"
-   "::std::setprecision;"
-   "::std::setw;"
-   "::std::upper_bound;"
-   "::std::vector::at;"
-   // C standard library
-   "::bsearch;"
-   "::ferror;"
-   "::feof;"
-   "::isalnum;"
-   "::isalpha;"
-   "::isblank;"
-   "::iscntrl;"
-   "::isdigit;"
-   "::isgraph;"
-   "::islower;"
-   "::isprint;"
-   "::ispunct;"
-   "::isspace;"
-   "::isupper;"
-   "::iswalnum;"
-   "::iswprint;"
-   "::iswspace;"
-   "::isxdigit;"
-   "::memchr;"
-   "::memcmp;"
-   "::strcmp;"
-   "::strcoll;"
-   "::strncmp;"
-   "::strpbrk;"
-   "::strrchr;"
-   "::strspn;"
-   "::strstr;"
-   "::wcscmp;"
-   // POSIX
-   "::access;"
-   "::bind;"
-   "::connect;"
-   "::difftime;"
-   "::dlsym;"
-   "::fnmatch;"
-   "::getaddrinfo;"
-   "::getopt;"
-   "::htonl;"
-   "::htons;"
-   "::iconv_open;"
-   "::inet_addr;"
- 

[clang-tools-extra] [clang-tidy] bugprone-unused-return-value config now supports regexes (PR #82952)

2024-02-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Félix-Antoine Constantin (felix642)


Changes

The parameter `CheckedReturnTypes` now supports regexes

Fixes #63107

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


5 Files Affected:

- (modified) clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp 
(+101-101) 
- (modified) clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h 
(+3-3) 
- (modified) clang-tools-extra/clang-tidy/hicpp/IgnoredRemoveResultCheck.cpp 
(+5-3) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+4) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value-custom.cpp
 (+1-1) 


``diff
diff --git a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
index 05012c7df6a975..b4bf85c912c3ca 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
@@ -33,98 +33,98 @@ AST_MATCHER_P(FunctionDecl, isInstantiatedFrom, 
Matcher,
 UnusedReturnValueCheck::UnusedReturnValueCheck(llvm::StringRef Name,
ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
-  CheckedFunctions(Options.get("CheckedFunctions",
-   "::std::async;"
-   "::std::launder;"
-   "::std::remove;"
-   "::std::remove_if;"
-   "::std::unique;"
-   "::std::unique_ptr::release;"
-   "::std::basic_string::empty;"
-   "::std::vector::empty;"
-   "::std::back_inserter;"
-   "::std::distance;"
-   "::std::find;"
-   "::std::find_if;"
-   "::std::inserter;"
-   "::std::lower_bound;"
-   "::std::make_pair;"
-   "::std::map::count;"
-   "::std::map::find;"
-   "::std::map::lower_bound;"
-   "::std::multimap::equal_range;"
-   "::std::multimap::upper_bound;"
-   "::std::set::count;"
-   "::std::set::find;"
-   "::std::setfill;"
-   "::std::setprecision;"
-   "::std::setw;"
-   "::std::upper_bound;"
-   "::std::vector::at;"
-   // C standard library
-   "::bsearch;"
-   "::ferror;"
-   "::feof;"
-   "::isalnum;"
-   "::isalpha;"
-   "::isblank;"
-   "::iscntrl;"
-   "::isdigit;"
-   "::isgraph;"
-   "::islower;"
-   "::isprint;"
-   "::ispunct;"
-   "::isspace;"
-   "::isupper;"
-   "::iswalnum;"
-   "::iswprint;"
-   "::iswspace;"
-   "::isxdigit;"
-   "::memchr;"
-   "::memcmp;"
-   "::strcmp;"
-   "::strcoll;"
-   "::strncmp;"
-   "::strpbrk;"
-   "::strrchr;"
-   "::strspn;"
-   "::strstr;"
-   "::wcscmp;"
-   // POSIX
-   "::access;"
-   "::bind;"
-   "::connect;"
-   "::difftime;"
-   "::dlsym;"
-   "::fnmatch;"
-   "::getaddrinfo;"
-   "::getopt;"
-   "::htonl;"
-   "::htons;"
-   "::iconv_open;"
-   "::inet_addr;"
-

[clang-tools-extra] [clang-tidy] bugprone-unused-return-value config now supports regexes (PR #82952)

2024-02-25 Thread Félix-Antoine Constantin via cfe-commits

https://github.com/felix642 created 
https://github.com/llvm/llvm-project/pull/82952

The parameter `CheckedReturnTypes` now supports regexes

Fixes #63107

From 86bc8a57fd56a6b2593af8bcf85d50bbc0ce984e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?F=C3=A9lix-Antoine=20Constantin?=
 
Date: Sun, 25 Feb 2024 22:05:08 -0500
Subject: [PATCH] [clang-tidy] bugprone-unused-return-value config now support
 regexes

Fixes #63107
---
 .../bugprone/UnusedReturnValueCheck.cpp   | 202 +-
 .../bugprone/UnusedReturnValueCheck.h |   6 +-
 .../hicpp/IgnoredRemoveResultCheck.cpp|   8 +-
 clang-tools-extra/docs/ReleaseNotes.rst   |   4 +
 .../bugprone/unused-return-value-custom.cpp   |   2 +-
 5 files changed, 114 insertions(+), 108 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
index 05012c7df6a975..b4bf85c912c3ca 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
@@ -33,98 +33,98 @@ AST_MATCHER_P(FunctionDecl, isInstantiatedFrom, 
Matcher,
 UnusedReturnValueCheck::UnusedReturnValueCheck(llvm::StringRef Name,
ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
-  CheckedFunctions(Options.get("CheckedFunctions",
-   "::std::async;"
-   "::std::launder;"
-   "::std::remove;"
-   "::std::remove_if;"
-   "::std::unique;"
-   "::std::unique_ptr::release;"
-   "::std::basic_string::empty;"
-   "::std::vector::empty;"
-   "::std::back_inserter;"
-   "::std::distance;"
-   "::std::find;"
-   "::std::find_if;"
-   "::std::inserter;"
-   "::std::lower_bound;"
-   "::std::make_pair;"
-   "::std::map::count;"
-   "::std::map::find;"
-   "::std::map::lower_bound;"
-   "::std::multimap::equal_range;"
-   "::std::multimap::upper_bound;"
-   "::std::set::count;"
-   "::std::set::find;"
-   "::std::setfill;"
-   "::std::setprecision;"
-   "::std::setw;"
-   "::std::upper_bound;"
-   "::std::vector::at;"
-   // C standard library
-   "::bsearch;"
-   "::ferror;"
-   "::feof;"
-   "::isalnum;"
-   "::isalpha;"
-   "::isblank;"
-   "::iscntrl;"
-   "::isdigit;"
-   "::isgraph;"
-   "::islower;"
-   "::isprint;"
-   "::ispunct;"
-   "::isspace;"
-   "::isupper;"
-   "::iswalnum;"
-   "::iswprint;"
-   "::iswspace;"
-   "::isxdigit;"
-   "::memchr;"
-   "::memcmp;"
-   "::strcmp;"
-   "::strcoll;"
-   "::strncmp;"
-   "::strpbrk;"
-   "::strrchr;"
-   "::strspn;"
-   "::strstr;"
-   "::wcscmp;"
-   // POSIX
-   "::access;"
-   "::bind;"
-   "::connect;"
-   "::difftime;"
-   "::dlsym;"
-   "::fnmatch;"
-   "::getaddrinfo;"
-   "::getopt;"
-   "::htonl;"
-   "::htons;"
-   "::iconv_open;"
- 

[clang] [clang][dataflow] Factor out built-in boolean model into an explicit module. (PR #82950)

2024-02-25 Thread Yitzhak Mandelbaum via cfe-commits

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

Draft to demo how we can pull out the boolean model. Let's discuss specifics of
namings, location, etc.

The purpose of this refactoring is to enable us to compare the performance of
different boolean models. In particular, we're interested in investigating a
very simple semantic domain of just the booleans (and Top).

In the process, the PR drastically simplifies the handling of terminators. This
cleanup can be pulled out into its own PR, to precede the refactoring work.


>From e0c51969f70079e18b7cacb99c3b9c1a7470b39a Mon Sep 17 00:00:00 2001
From: Yitzhak Mandelbaum 
Date: Fri, 23 Feb 2024 20:15:36 +
Subject: [PATCH] [clang][dataflow] Factor out built-in boolean model into an
 explicit module.

In the process, drastically simplify the handling of terminators.
---
 .../clang/Analysis/FlowSensitive/Transfer.h   |  24 +++
 clang/lib/Analysis/FlowSensitive/Transfer.cpp | 144 --
 .../TypeErasedDataflowAnalysis.cpp| 126 +--
 3 files changed, 161 insertions(+), 133 deletions(-)

diff --git a/clang/include/clang/Analysis/FlowSensitive/Transfer.h 
b/clang/include/clang/Analysis/FlowSensitive/Transfer.h
index 7713df747cb76e..eea0cdd37ff63d 100644
--- a/clang/include/clang/Analysis/FlowSensitive/Transfer.h
+++ b/clang/include/clang/Analysis/FlowSensitive/Transfer.h
@@ -48,6 +48,30 @@ class StmtToEnvMap {
   const TypeErasedDataflowAnalysisState 
 };
 
+namespace bool_model {
+
+BoolValue (Environment );
+
+BoolValue (BoolValue , Environment );
+
+BoolValue (BoolValue , BoolValue , Environment );
+
+BoolValue (BoolValue , BoolValue , Environment );
+
+BoolValue (BoolValue , BoolValue , Environment );
+
+BoolValue (BoolValue , BoolValue , Environment );
+
+BoolValue (BoolValue , Environment );
+
+// Models the transition along a branch edge in the CFG.
+// BranchVal -- the concrete, dynamic branch value -- true for `then` and false
+// for `else`.
+// CondVal -- the abstract value representing the condition.
+void transferBranch(bool BranchVal, BoolValue , Environment );
+
+} // namespace bool_model
+
 /// Evaluates `S` and updates `Env` accordingly.
 ///
 /// Requirements:
diff --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index a098471d0ee905..65072d85d10c69 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -50,21 +50,6 @@ const Environment *StmtToEnvMap::getEnvironment(const Stmt 
) const {
   return >Env;
 }
 
-static BoolValue (const Expr , const Expr ,
-  Environment ) {
-  Value *LHSValue = Env.getValue(LHS);
-  Value *RHSValue = Env.getValue(RHS);
-
-  if (LHSValue == RHSValue)
-return Env.getBoolLiteralValue(true);
-
-  if (auto *LHSBool = dyn_cast_or_null(LHSValue))
-if (auto *RHSBool = dyn_cast_or_null(RHSValue))
-  return Env.makeIff(*LHSBool, *RHSBool);
-
-  return Env.makeAtomicBoolValue();
-}
-
 static BoolValue (BoolValue , Environment ) {
   if (auto *Top = llvm::dyn_cast()) {
 auto  = Env.getDataflowAnalysisContext().arena();
@@ -73,6 +58,68 @@ static BoolValue (BoolValue , Environment 
) {
   return V;
 }
 
+static void propagateValue(const Expr , const Expr , Environment ) 
{
+  if (auto *Val = Env.getValue(From))
+Env.setValue(To, *Val);
+}
+
+static void propagateStorageLocation(const Expr , const Expr ,
+ Environment ) {
+  if (auto *Loc = Env.getStorageLocation(From))
+Env.setStorageLocation(To, *Loc);
+}
+
+// Propagates the value or storage location of `From` to `To` in cases where
+// `From` may be either a glvalue or a prvalue. `To` must be a glvalue iff
+// `From` is a glvalue.
+static void propagateValueOrStorageLocation(const Expr , const Expr ,
+Environment ) {
+  assert(From.isGLValue() == To.isGLValue());
+  if (From.isGLValue())
+propagateStorageLocation(From, To, Env);
+  else
+propagateValue(From, To, Env);
+}
+
+namespace bool_model {
+
+BoolValue (Environment ) {
+  return Env.makeAtomicBoolValue();
+}
+
+BoolValue (BoolValue , Environment ) {
+  return unpackValue(V, Env);
+}
+
+BoolValue (BoolValue , BoolValue , Environment ) {
+  return Env.makeOr(LHS, RHS);
+}
+
+BoolValue (BoolValue , BoolValue , Environment ) {
+  return Env.makeAnd(LHS, RHS);
+}
+
+BoolValue (BoolValue , BoolValue , Environment ) {
+  return Env.makeIff(LHS, RHS);
+}
+
+BoolValue (BoolValue , BoolValue , Environment ) {
+  return Env.makeNot(Env.makeIff(LHS, RHS));
+}
+
+BoolValue (BoolValue , Environment ) { return Env.makeNot(Sub); }
+
+void transferBranch(bool BranchVal, BoolValue , Environment ) {
+  if (BranchVal)
+Env.assume(CondVal.formula());
+  else
+// The condition must be inverted for the successor that encompasses the
+// "else" branch, if such exists.
+

[clang] Revert "[clang][dataflow] Correctly handle `InitListExpr` of union type." (PR #82856)

2024-02-25 Thread Yitzhak Mandelbaum via cfe-commits

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


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


[clang] [ObjC] Defer to the LLVM backend for unaligned atomic load and stores (PR #79191)

2024-02-25 Thread James Y Knight via cfe-commits

jyknight wrote:

> Don't know but everything passed now!

Well, I'm not an expert on the objc codegen...but unless you, or someone else, 
can explain that my concern is invalid, I think this change cannot be made.

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


[clang] clang serialization unittests: fix some leaks (PR #82773)

2024-02-25 Thread Chuanqi Xu via cfe-commits

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


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


[clang] [clang-format] Limit how much work guessLanguage() can do (PR #78925)

2024-02-25 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

> @HighCommander4 see #82911

Thanks. I've prototyped the clangd changes on top of this, and it seem to be 
working (i.e. successfully avoiding the OOM for workflows that don't involve 
formatting the file). I've pushed the changes to my fork at 
https://github.com/HighCommander4/llvm-project/tree/issue-1384-alternate; I 
will submit them for review once the dependent patch merges.

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


[clang-tools-extra] [clangd] Make all calls to format::getStyle() go through getFormatStyleForFile() (PR #82948)

2024-02-25 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

(This patch is in preparation for a fix for 
https://github.com/clangd/clangd/issues/1384, which I haven't posted yet 
because I haven't figured out how to do stacked PRs yet. However, this patch 
seems independently useful and reviewable.)

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


[clang-tools-extra] [clangd] Make all calls to format::getStyle() go through getFormatStyleForFile() (PR #82948)

2024-02-25 Thread via cfe-commits

llvmbot wrote:




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

Author: Nathan Ridge (HighCommander4)


Changes



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


5 Files Affected:

- (modified) clang-tools-extra/clangd/ClangdServer.cpp (+2-7) 
- (modified) clang-tools-extra/clangd/IncludeCleaner.cpp (+5-10) 
- (modified) clang-tools-extra/clangd/IncludeCleaner.h (+1) 
- (modified) clang-tools-extra/clangd/ParsedAST.cpp (+4-3) 
- (modified) clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp (+7-7) 


``diff
diff --git a/clang-tools-extra/clangd/ClangdServer.cpp 
b/clang-tools-extra/clangd/ClangdServer.cpp
index 3f9fd012819428..2907e3ba3c303c 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -551,15 +551,10 @@ void ClangdServer::formatOnType(PathRef File, Position 
Pos,
   auto Action = [File = File.str(), Code = std::move(*Code),
  TriggerText = TriggerText.str(), CursorPos = *CursorPos,
  CB = std::move(CB), this]() mutable {
-auto Style = format::getStyle(format::DefaultFormatStyle, File,
-  format::DefaultFallbackStyle, Code,
-  TFS.view(/*CWD=*/std::nullopt).get());
-if (!Style)
-  return CB(Style.takeError());
-
+auto Style = getFormatStyleForFile(File, Code, TFS);
 std::vector Result;
 for (const tooling::Replacement  :
- formatIncremental(Code, CursorPos, TriggerText, *Style))
+ formatIncremental(Code, CursorPos, TriggerText, Style))
   Result.push_back(replacementToEdit(Code, R));
 return CB(Result);
   };
diff --git a/clang-tools-extra/clangd/IncludeCleaner.cpp 
b/clang-tools-extra/clangd/IncludeCleaner.cpp
index f86a121340f7fb..7375b7b0860917 100644
--- a/clang-tools-extra/clangd/IncludeCleaner.cpp
+++ b/clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -111,21 +111,15 @@ bool mayConsiderUnused(const Inclusion , ParsedAST 
,
 
 std::vector generateMissingIncludeDiagnostics(
 ParsedAST , llvm::ArrayRef MissingIncludes,
-llvm::StringRef Code, HeaderFilter IgnoreHeaders) {
+llvm::StringRef Code, HeaderFilter IgnoreHeaders, const ThreadsafeFS ) 
{
   std::vector Result;
   const SourceManager  = AST.getSourceManager();
   const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID());
 
-  auto FileStyle = format::getStyle(
-  format::DefaultFormatStyle, AST.tuPath(), format::DefaultFallbackStyle,
-  Code, ().getVirtualFileSystem());
-  if (!FileStyle) {
-elog("Couldn't infer style", FileStyle.takeError());
-FileStyle = format::getLLVMStyle();
-  }
+  auto FileStyle = getFormatStyleForFile(AST.tuPath(), Code, TFS);
 
   tooling::HeaderIncludes HeaderIncludes(AST.tuPath(), Code,
- FileStyle->IncludeStyle);
+ FileStyle.IncludeStyle);
   for (const auto  : MissingIncludes) {
 llvm::StringRef ResolvedPath =
 SymbolWithMissingInclude.Providers.front().resolvedPath();
@@ -459,6 +453,7 @@ bool isPreferredProvider(const Inclusion ,
 std::vector
 issueIncludeCleanerDiagnostics(ParsedAST , llvm::StringRef Code,
const IncludeCleanerFindings ,
+   const ThreadsafeFS ,
HeaderFilter IgnoreHeaders) {
   trace::Span Tracer("IncludeCleaner::issueIncludeCleanerDiagnostics");
   std::vector UnusedIncludes = generateUnusedIncludeDiagnostics(
@@ -466,7 +461,7 @@ issueIncludeCleanerDiagnostics(ParsedAST , 
llvm::StringRef Code,
   std::optional RemoveAllUnused = removeAllUnusedIncludes(UnusedIncludes);
 
   std::vector MissingIncludeDiags = generateMissingIncludeDiagnostics(
-  AST, Findings.MissingIncludes, Code, IgnoreHeaders);
+  AST, Findings.MissingIncludes, Code, IgnoreHeaders, TFS);
   std::optional AddAllMissing = 
addAllMissingIncludes(MissingIncludeDiags);
 
   std::optional FixAll;
diff --git a/clang-tools-extra/clangd/IncludeCleaner.h 
b/clang-tools-extra/clangd/IncludeCleaner.h
index b3ba3a716083e8..387763de340767 100644
--- a/clang-tools-extra/clangd/IncludeCleaner.h
+++ b/clang-tools-extra/clangd/IncludeCleaner.h
@@ -59,6 +59,7 @@ using HeaderFilter = 
llvm::ArrayRef>;
 std::vector
 issueIncludeCleanerDiagnostics(ParsedAST , llvm::StringRef Code,
const IncludeCleanerFindings ,
+   const ThreadsafeFS ,
HeaderFilter IgnoreHeader = {});
 
 /// Affects whether standard library includes should be considered for
diff --git a/clang-tools-extra/clangd/ParsedAST.cpp 
b/clang-tools-extra/clangd/ParsedAST.cpp
index bbb0e2c77b3f31..862f06196a7100 100644
--- a/clang-tools-extra/clangd/ParsedAST.cpp
+++ b/clang-tools-extra/clangd/ParsedAST.cpp
@@ -360,7 +360,8 @@ void applyWarningOptions(llvm::ArrayRef 
ExtraArgs,
   }
 }
 
-std::vector getIncludeCleanerDiags(ParsedAST , 

[clang-tools-extra] [clangd] Make all calls to format::getStyle() go through getFormatStyleForFile() (PR #82948)

2024-02-25 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 created 
https://github.com/llvm/llvm-project/pull/82948

None

>From e0cb66c8313c8ff1a934dc222165040de656b71e Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Sun, 25 Feb 2024 19:24:31 -0500
Subject: [PATCH] [clangd] Make all calls to format::getStyle() go through
 getFormatStyleForFile()

---
 clang-tools-extra/clangd/ClangdServer.cpp |  9 ++---
 clang-tools-extra/clangd/IncludeCleaner.cpp   | 15 +--
 clang-tools-extra/clangd/IncludeCleaner.h |  1 +
 clang-tools-extra/clangd/ParsedAST.cpp|  7 ---
 .../clangd/unittests/IncludeCleanerTests.cpp  | 14 +++---
 5 files changed, 19 insertions(+), 27 deletions(-)

diff --git a/clang-tools-extra/clangd/ClangdServer.cpp 
b/clang-tools-extra/clangd/ClangdServer.cpp
index 3f9fd012819428..2907e3ba3c303c 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -551,15 +551,10 @@ void ClangdServer::formatOnType(PathRef File, Position 
Pos,
   auto Action = [File = File.str(), Code = std::move(*Code),
  TriggerText = TriggerText.str(), CursorPos = *CursorPos,
  CB = std::move(CB), this]() mutable {
-auto Style = format::getStyle(format::DefaultFormatStyle, File,
-  format::DefaultFallbackStyle, Code,
-  TFS.view(/*CWD=*/std::nullopt).get());
-if (!Style)
-  return CB(Style.takeError());
-
+auto Style = getFormatStyleForFile(File, Code, TFS);
 std::vector Result;
 for (const tooling::Replacement  :
- formatIncremental(Code, CursorPos, TriggerText, *Style))
+ formatIncremental(Code, CursorPos, TriggerText, Style))
   Result.push_back(replacementToEdit(Code, R));
 return CB(Result);
   };
diff --git a/clang-tools-extra/clangd/IncludeCleaner.cpp 
b/clang-tools-extra/clangd/IncludeCleaner.cpp
index f86a121340f7fb..7375b7b0860917 100644
--- a/clang-tools-extra/clangd/IncludeCleaner.cpp
+++ b/clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -111,21 +111,15 @@ bool mayConsiderUnused(const Inclusion , ParsedAST 
,
 
 std::vector generateMissingIncludeDiagnostics(
 ParsedAST , llvm::ArrayRef MissingIncludes,
-llvm::StringRef Code, HeaderFilter IgnoreHeaders) {
+llvm::StringRef Code, HeaderFilter IgnoreHeaders, const ThreadsafeFS ) 
{
   std::vector Result;
   const SourceManager  = AST.getSourceManager();
   const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID());
 
-  auto FileStyle = format::getStyle(
-  format::DefaultFormatStyle, AST.tuPath(), format::DefaultFallbackStyle,
-  Code, ().getVirtualFileSystem());
-  if (!FileStyle) {
-elog("Couldn't infer style", FileStyle.takeError());
-FileStyle = format::getLLVMStyle();
-  }
+  auto FileStyle = getFormatStyleForFile(AST.tuPath(), Code, TFS);
 
   tooling::HeaderIncludes HeaderIncludes(AST.tuPath(), Code,
- FileStyle->IncludeStyle);
+ FileStyle.IncludeStyle);
   for (const auto  : MissingIncludes) {
 llvm::StringRef ResolvedPath =
 SymbolWithMissingInclude.Providers.front().resolvedPath();
@@ -459,6 +453,7 @@ bool isPreferredProvider(const Inclusion ,
 std::vector
 issueIncludeCleanerDiagnostics(ParsedAST , llvm::StringRef Code,
const IncludeCleanerFindings ,
+   const ThreadsafeFS ,
HeaderFilter IgnoreHeaders) {
   trace::Span Tracer("IncludeCleaner::issueIncludeCleanerDiagnostics");
   std::vector UnusedIncludes = generateUnusedIncludeDiagnostics(
@@ -466,7 +461,7 @@ issueIncludeCleanerDiagnostics(ParsedAST , 
llvm::StringRef Code,
   std::optional RemoveAllUnused = removeAllUnusedIncludes(UnusedIncludes);
 
   std::vector MissingIncludeDiags = generateMissingIncludeDiagnostics(
-  AST, Findings.MissingIncludes, Code, IgnoreHeaders);
+  AST, Findings.MissingIncludes, Code, IgnoreHeaders, TFS);
   std::optional AddAllMissing = 
addAllMissingIncludes(MissingIncludeDiags);
 
   std::optional FixAll;
diff --git a/clang-tools-extra/clangd/IncludeCleaner.h 
b/clang-tools-extra/clangd/IncludeCleaner.h
index b3ba3a716083e8..387763de340767 100644
--- a/clang-tools-extra/clangd/IncludeCleaner.h
+++ b/clang-tools-extra/clangd/IncludeCleaner.h
@@ -59,6 +59,7 @@ using HeaderFilter = 
llvm::ArrayRef>;
 std::vector
 issueIncludeCleanerDiagnostics(ParsedAST , llvm::StringRef Code,
const IncludeCleanerFindings ,
+   const ThreadsafeFS ,
HeaderFilter IgnoreHeader = {});
 
 /// Affects whether standard library includes should be considered for
diff --git a/clang-tools-extra/clangd/ParsedAST.cpp 
b/clang-tools-extra/clangd/ParsedAST.cpp
index bbb0e2c77b3f31..862f06196a7100 100644
--- a/clang-tools-extra/clangd/ParsedAST.cpp
+++ 

[clang-tools-extra] [clang-tidy] Improved modernize-use-using by fixing a false-negative (PR #82947)

2024-02-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Félix-Antoine Constantin (felix642)


Changes

The check needs a parent decl to match but if the typedef is in a function, the 
parent is a declStmt which is not a decl by itself. Improved the matcher to 
match on either a decl or a declstmt and extract the decl from the stmt in the 
latter case.

fixes #72179

CC: @FabianWolff @PiotrZSL @njames93 

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


3 Files Affected:

- (modified) clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp (+13-3) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+3) 
- (modified) clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp 
(+18) 


``diff
diff --git a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
index bb05f206c717ce..50a07fc02e31b4 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
@@ -24,6 +24,7 @@ static constexpr llvm::StringLiteral ExternCDeclName = 
"extern-c-decl";
 static constexpr llvm::StringLiteral ParentDeclName = "parent-decl";
 static constexpr llvm::StringLiteral TagDeclName = "tag-decl";
 static constexpr llvm::StringLiteral TypedefName = "typedef";
+static constexpr llvm::StringLiteral DeclStmtName = "decl-stmt";
 
 UseUsingCheck::UseUsingCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
@@ -41,7 +42,8 @@ void UseUsingCheck::registerMatchers(MatchFinder *Finder) {
   unless(isInstantiated()),
   optionally(hasAncestor(
   linkageSpecDecl(isExternCLinkage()).bind(ExternCDeclName))),
-  hasParent(decl().bind(ParentDeclName)))
+  anyOf(hasParent(decl().bind(ParentDeclName)),
+hasParent(declStmt().bind(DeclStmtName
   .bind(TypedefName),
   this);
 
@@ -51,17 +53,25 @@ void UseUsingCheck::registerMatchers(MatchFinder *Finder) {
   tagDecl(
   anyOf(allOf(unless(anyOf(isImplicit(),
classTemplateSpecializationDecl())),
-  hasParent(decl().bind(ParentDeclName))),
+  anyOf(hasParent(decl().bind(ParentDeclName)),
+hasParent(declStmt().bind(DeclStmtName,
 // We want the parent of the ClassTemplateDecl, not the parent
 // of the specialization.
 classTemplateSpecializationDecl(hasAncestor(classTemplateDecl(
-hasParent(decl().bind(ParentDeclName)))
+anyOf(hasParent(decl().bind(ParentDeclName)),
+  hasParent(declStmt().bind(DeclStmtName
   .bind(TagDeclName),
   this);
 }
 
 void UseUsingCheck::check(const MatchFinder::MatchResult ) {
   const auto *ParentDecl = Result.Nodes.getNodeAs(ParentDeclName);
+
+  if (!ParentDecl) {
+const auto *ParentDeclStmt = 
Result.Nodes.getNodeAs(DeclStmtName);
+ParentDecl = ParentDeclStmt->getSingleDecl();
+  }
+
   if (!ParentDecl)
 return;
 
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 6fd01ed9d471c5..2b36ae4acb9f1d 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -183,6 +183,9 @@ Changes in existing checks
   ` check to also remove any trailing
   whitespace when deleting the ``virtual`` keyword.
 
+- Improved :doc:`modernize-use-using `
+  check by fixing false-negative in functions.
+
 - Improved :doc:`readability-implicit-bool-conversion
   ` check to provide
   valid fix suggestions for ``static_cast`` without a preceding space and
diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
index 462bc984fd3ad5..230c7c94cda1cf 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
@@ -342,3 +342,21 @@ typedef int InExternCPP;
 // CHECK-FIXES: using InExternCPP = int;
 
 }
+
+namespace ISSUE_72179
+{  
+  void foo()
+  {
+typedef int a;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use 'using' instead of 
'typedef' [modernize-use-using]
+// CHECK-FIXES: using a = int;
+
+  }
+
+  void foo2()
+  {
+typedef struct { int a; union { int b; }; } c;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use 'using' instead of 
'typedef' [modernize-use-using]
+// CHECK-FIXES: using c = struct { int a; union { int b; }; };
+  }
+}

``




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


[clang-tools-extra] [clang-tidy] Improved modernize-use-using by fixing a false-negative (PR #82947)

2024-02-25 Thread Félix-Antoine Constantin via cfe-commits

https://github.com/felix642 updated 
https://github.com/llvm/llvm-project/pull/82947

From d1cbed0e2e83bd3544067fd25d7e811f1ab3f095 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?F=C3=A9lix-Antoine=20Constantin?=
 
Date: Sun, 25 Feb 2024 20:20:59 -0500
Subject: [PATCH] [clang-tidy] Improved modernize-use-using by fixing a
 false-negative

The check needs a parent decl to match but if the typedef is in a function,
the parent is a declStmt which is not a decl by itself.
Improved the matcher to match on either a decl or a declstmt and extract
the decl from the stmt in the latter case.

fixes #72179
---
 .../clang-tidy/modernize/UseUsingCheck.cpp | 16 +---
 clang-tools-extra/docs/ReleaseNotes.rst|  3 +++
 .../checkers/modernize/use-using.cpp   | 18 ++
 3 files changed, 34 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
index bb05f206c717ce..50a07fc02e31b4 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
@@ -24,6 +24,7 @@ static constexpr llvm::StringLiteral ExternCDeclName = 
"extern-c-decl";
 static constexpr llvm::StringLiteral ParentDeclName = "parent-decl";
 static constexpr llvm::StringLiteral TagDeclName = "tag-decl";
 static constexpr llvm::StringLiteral TypedefName = "typedef";
+static constexpr llvm::StringLiteral DeclStmtName = "decl-stmt";
 
 UseUsingCheck::UseUsingCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
@@ -41,7 +42,8 @@ void UseUsingCheck::registerMatchers(MatchFinder *Finder) {
   unless(isInstantiated()),
   optionally(hasAncestor(
   linkageSpecDecl(isExternCLinkage()).bind(ExternCDeclName))),
-  hasParent(decl().bind(ParentDeclName)))
+  anyOf(hasParent(decl().bind(ParentDeclName)),
+hasParent(declStmt().bind(DeclStmtName
   .bind(TypedefName),
   this);
 
@@ -51,17 +53,25 @@ void UseUsingCheck::registerMatchers(MatchFinder *Finder) {
   tagDecl(
   anyOf(allOf(unless(anyOf(isImplicit(),
classTemplateSpecializationDecl())),
-  hasParent(decl().bind(ParentDeclName))),
+  anyOf(hasParent(decl().bind(ParentDeclName)),
+hasParent(declStmt().bind(DeclStmtName,
 // We want the parent of the ClassTemplateDecl, not the parent
 // of the specialization.
 classTemplateSpecializationDecl(hasAncestor(classTemplateDecl(
-hasParent(decl().bind(ParentDeclName)))
+anyOf(hasParent(decl().bind(ParentDeclName)),
+  hasParent(declStmt().bind(DeclStmtName
   .bind(TagDeclName),
   this);
 }
 
 void UseUsingCheck::check(const MatchFinder::MatchResult ) {
   const auto *ParentDecl = Result.Nodes.getNodeAs(ParentDeclName);
+
+  if (!ParentDecl) {
+const auto *ParentDeclStmt = 
Result.Nodes.getNodeAs(DeclStmtName);
+ParentDecl = ParentDeclStmt->getSingleDecl();
+  }
+
   if (!ParentDecl)
 return;
 
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 6fd01ed9d471c5..2b36ae4acb9f1d 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -183,6 +183,9 @@ Changes in existing checks
   ` check to also remove any trailing
   whitespace when deleting the ``virtual`` keyword.
 
+- Improved :doc:`modernize-use-using `
+  check by fixing false-negative in functions.
+
 - Improved :doc:`readability-implicit-bool-conversion
   ` check to provide
   valid fix suggestions for ``static_cast`` without a preceding space and
diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
index 462bc984fd3ad5..230c7c94cda1cf 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
@@ -342,3 +342,21 @@ typedef int InExternCPP;
 // CHECK-FIXES: using InExternCPP = int;
 
 }
+
+namespace ISSUE_72179
+{  
+  void foo()
+  {
+typedef int a;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use 'using' instead of 
'typedef' [modernize-use-using]
+// CHECK-FIXES: using a = int;
+
+  }
+
+  void foo2()
+  {
+typedef struct { int a; union { int b; }; } c;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use 'using' instead of 
'typedef' [modernize-use-using]
+// CHECK-FIXES: using c = struct { int a; union { int b; }; };
+  }
+}

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


[clang-tools-extra] [clang-tidy] Improved modernize-use-using by fixing a false-negative (PR #82947)

2024-02-25 Thread Félix-Antoine Constantin via cfe-commits

https://github.com/felix642 created 
https://github.com/llvm/llvm-project/pull/82947

The check needs a parent decl to match but if the typedef is in a function, the 
parent is a declStmt which is not a decl by itself. Improved the matcher to 
match on either a decl or a declstmt and extract the decl from the stmt in the 
latter case.

fixes #72179

CC: @FabianWolff @PiotrZSL @njames93 

From 003ec9d5b75cdf6de3140612e1c4b42322a52413 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?F=C3=A9lix-Antoine=20Constantin?=
 
Date: Sun, 25 Feb 2024 20:20:59 -0500
Subject: [PATCH] [clang-tidy] Improved modernize-use-using by fixing a
 false-positive

The check needs a parent decl to match but if the typedef is in a function,
the parent is a declStmt which is not a decl by itself.
Improved the matcher to match on either a decl or a declstmt and extract
the decl from the stmt in the latter case.

fixes #72179
---
 .../clang-tidy/modernize/UseUsingCheck.cpp | 16 +---
 clang-tools-extra/docs/ReleaseNotes.rst|  3 +++
 .../checkers/modernize/use-using.cpp   | 18 ++
 3 files changed, 34 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
index bb05f206c717ce..50a07fc02e31b4 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
@@ -24,6 +24,7 @@ static constexpr llvm::StringLiteral ExternCDeclName = 
"extern-c-decl";
 static constexpr llvm::StringLiteral ParentDeclName = "parent-decl";
 static constexpr llvm::StringLiteral TagDeclName = "tag-decl";
 static constexpr llvm::StringLiteral TypedefName = "typedef";
+static constexpr llvm::StringLiteral DeclStmtName = "decl-stmt";
 
 UseUsingCheck::UseUsingCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
@@ -41,7 +42,8 @@ void UseUsingCheck::registerMatchers(MatchFinder *Finder) {
   unless(isInstantiated()),
   optionally(hasAncestor(
   linkageSpecDecl(isExternCLinkage()).bind(ExternCDeclName))),
-  hasParent(decl().bind(ParentDeclName)))
+  anyOf(hasParent(decl().bind(ParentDeclName)),
+hasParent(declStmt().bind(DeclStmtName
   .bind(TypedefName),
   this);
 
@@ -51,17 +53,25 @@ void UseUsingCheck::registerMatchers(MatchFinder *Finder) {
   tagDecl(
   anyOf(allOf(unless(anyOf(isImplicit(),
classTemplateSpecializationDecl())),
-  hasParent(decl().bind(ParentDeclName))),
+  anyOf(hasParent(decl().bind(ParentDeclName)),
+hasParent(declStmt().bind(DeclStmtName,
 // We want the parent of the ClassTemplateDecl, not the parent
 // of the specialization.
 classTemplateSpecializationDecl(hasAncestor(classTemplateDecl(
-hasParent(decl().bind(ParentDeclName)))
+anyOf(hasParent(decl().bind(ParentDeclName)),
+  hasParent(declStmt().bind(DeclStmtName
   .bind(TagDeclName),
   this);
 }
 
 void UseUsingCheck::check(const MatchFinder::MatchResult ) {
   const auto *ParentDecl = Result.Nodes.getNodeAs(ParentDeclName);
+
+  if (!ParentDecl) {
+const auto *ParentDeclStmt = 
Result.Nodes.getNodeAs(DeclStmtName);
+ParentDecl = ParentDeclStmt->getSingleDecl();
+  }
+
   if (!ParentDecl)
 return;
 
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 6fd01ed9d471c5..2b36ae4acb9f1d 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -183,6 +183,9 @@ Changes in existing checks
   ` check to also remove any trailing
   whitespace when deleting the ``virtual`` keyword.
 
+- Improved :doc:`modernize-use-using `
+  check by fixing false-negative in functions.
+
 - Improved :doc:`readability-implicit-bool-conversion
   ` check to provide
   valid fix suggestions for ``static_cast`` without a preceding space and
diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
index 462bc984fd3ad5..230c7c94cda1cf 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-using.cpp
@@ -342,3 +342,21 @@ typedef int InExternCPP;
 // CHECK-FIXES: using InExternCPP = int;
 
 }
+
+namespace ISSUE_72179
+{  
+  void foo()
+  {
+typedef int a;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use 'using' instead of 
'typedef' [modernize-use-using]
+// CHECK-FIXES: using a = int;
+
+  }
+
+  void foo2()
+  {
+typedef struct { int a; union { int b; }; } c;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use 'using' instead of 
'typedef' 

[clang] 085f9b0 - [clang-format][doc] Update documentation for RemoveSemicolon

2024-02-25 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2024-02-25T16:08:37-08:00
New Revision: 085f9b0d146fc99bbb0e193593aad696fc50a056

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

LOG: [clang-format][doc] Update documentation for RemoveSemicolon

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index fdf7bfaeaa4ec7..6515b166001910 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -4844,7 +4844,8 @@ the configuration (without a prefix: ``Auto``).
 .. _RemoveSemicolon:
 
 **RemoveSemicolon** (``Boolean``) :versionbadge:`clang-format 16` :ref:`¶ 
`
-  Remove semicolons after the closing brace of a non-empty function.
+  Remove semicolons after the closing braces of functions and
+  constructors/destructors.
 
   .. warning::
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index e9b2160a7b9243..47923e06d2c2d1 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -3771,7 +3771,8 @@ struct FormatStyle {
   /// \version 17
   RemoveParenthesesStyle RemoveParentheses;
 
-  /// Remove semicolons after the closing brace of a non-empty function.
+  /// Remove semicolons after the closing braces of functions and
+  /// constructors/destructors.
   /// \warning
   ///  Setting this option to ``true`` could lead to incorrect code formatting
   ///  due to clang-format's lack of complete semantic information. As such,



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


[clang] [ObjC] Add support for finally blocks (PR #82934)

2024-02-25 Thread via cfe-commits

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


[clang] [ObjC] Add support for finally blocks (PR #82934)

2024-02-25 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/82934

>From 3a4134ff040230e0f0e5054be57e28f779135728 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Sun, 25 Feb 2024 14:52:59 -0500
Subject: [PATCH] [ObjC] Add support for finally blocks

---
 clang/lib/Analysis/CFG.cpp | 71 --
 1 file changed, 61 insertions(+), 10 deletions(-)

diff --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index de70cbbf6cdb38..f8288d17733d87 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -2356,6 +2356,9 @@ CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc,
 case Stmt::ObjCAtTryStmtClass:
   return VisitObjCAtTryStmt(cast(S));
 
+case Stmt::ObjCAtFinallyStmtClass:
+  return VisitObjCAtFinallyStmt(cast(S));
+
 case Stmt::ObjCForCollectionStmtClass:
   return VisitObjCForCollectionStmt(cast(S));
 
@@ -4060,6 +4063,32 @@ CFGBlock 
*CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
   return VisitStmt(S, AddStmtChoice::AlwaysAdd);
 }
 
+CFGBlock *CFGBuilder::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *FS) {
+  // ObjCAtFinallyStmt are treated like labels, so they are the first statement
+  // in a block.
+
+  if (FS->getFinallyBody())
+addStmt(FS->getFinallyBody());
+
+  CFGBlock *FinallyBlock = Block;
+  if (!FinallyBlock)
+FinallyBlock = createBlock();
+
+  appendStmt(FinallyBlock, FS);
+
+  // Also add the ObjCAtFinallyStmt as a label, like with regular labels.
+  FinallyBlock->setLabel(FS);
+
+  // Bail out if the CFG is bad.
+  if (badCFG)
+return nullptr;
+
+  // We set Block to NULL to allow lazy creation of a new block (if necessary).
+  Block = nullptr;
+
+  return FinallyBlock;
+}
+
 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *Terminator) {
   // "@try"/"@catch" is a control-flow statement.  Thus we stop processing the
   // current block.
@@ -4072,17 +4101,27 @@ CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt 
*Terminator) {
   } else
 TrySuccessor = Succ;
 
-  // FIXME: Implement @finally support.
-  if (Terminator->getFinallyStmt())
-return NYS();
-
   CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
-
   // Create a new block that will contain the try statement.
   CFGBlock *NewTryTerminatedBlock = createBlock(false);
   // Add the terminator in the try block.
   NewTryTerminatedBlock->setTerminator(Terminator);
 
+  CFGBlock *FinallyBlock = nullptr;
+
+  if (Terminator->getFinallyStmt()) {
+Succ = TrySuccessor;
+
+Block = nullptr;
+FinallyBlock = VisitObjCAtFinallyStmt(Terminator->getFinallyStmt());
+
+if (!FinallyBlock)
+  return nullptr;
+
+// The code after the finally is the implicit successor.
+addSuccessor(NewTryTerminatedBlock, FinallyBlock);
+  }
+
   bool HasCatchAll = false;
   for (ObjCAtCatchStmt *CS : Terminator->catch_stmts()) {
 // The code after the try is the implicit successor.
@@ -4092,19 +4131,31 @@ CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt 
*Terminator) {
 }
 Block = nullptr;
 CFGBlock *CatchBlock = VisitObjCAtCatchStmt(CS);
+
 if (!CatchBlock)
   return nullptr;
+
 // Add this block to the list of successors for the block with the try
 // statement.
 addSuccessor(NewTryTerminatedBlock, CatchBlock);
+
+// After visiting the catch block, add the @finally block as a successor.
+if (FinallyBlock)
+  addSuccessor(CatchBlock, FinallyBlock);
   }
 
-  // FIXME: This needs updating when @finally support is added.
+  // The @finally block, if it exists, should always be a successor.
+
   if (!HasCatchAll) {
-if (PrevTryTerminatedBlock)
-  addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
-else
-  addSuccessor(NewTryTerminatedBlock, >getExit());
+CFGBlock *endBlock = NewTryTerminatedBlock;
+if (FinallyBlock)
+  endBlock = FinallyBlock;
+
+if (PrevTryTerminatedBlock) {
+  addSuccessor(endBlock, PrevTryTerminatedBlock);
+} else {
+  addSuccessor(endBlock, >getExit());
+}
   }
 
   // The code after the try is the implicit successor.

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


[clang] [ObjC] Add support for finally blocks (PR #82934)

2024-02-25 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 529b5705db2ccefeee2c9b8cb5144e1f5a6420de 
08abfad8feb3c54cc1bb9a8eea94e0e91c3ce678 -- clang/lib/Analysis/CFG.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index 15db6560d1..f8288d1773 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -4117,7 +4117,7 @@ CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt 
*Terminator) {
 
 if (!FinallyBlock)
   return nullptr;
-
+
 // The code after the finally is the implicit successor.
 addSuccessor(NewTryTerminatedBlock, FinallyBlock);
   }
@@ -4131,7 +4131,7 @@ CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt 
*Terminator) {
 }
 Block = nullptr;
 CFGBlock *CatchBlock = VisitObjCAtCatchStmt(CS);
-
+
 if (!CatchBlock)
   return nullptr;
 

``




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


[clang] [ObjC] Add support for finally blocks (PR #82934)

2024-02-25 Thread via cfe-commits

github-actions[bot] wrote:

⚠️ We detected that you are using a GitHub private e-mail address to contribute 
to the repo.
  Please turn off [Keep my email addresses 
private](https://github.com/settings/emails) setting in your account.
  See [LLVM 
Discourse](https://discourse.llvm.org/t/hidden-emails-on-github-should-we-do-something-about-it)
 for more information.


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


[clang] [ObjC] Add support for finally blocks (PR #82934)

2024-02-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: AtariDreams (AtariDreams)


Changes



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


1 Files Affected:

- (modified) clang/lib/Analysis/CFG.cpp (+61-10) 


``diff
diff --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index de70cbbf6cdb38..15db6560d1561f 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -2356,6 +2356,9 @@ CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc,
 case Stmt::ObjCAtTryStmtClass:
   return VisitObjCAtTryStmt(cast(S));
 
+case Stmt::ObjCAtFinallyStmtClass:
+  return VisitObjCAtFinallyStmt(cast(S));
+
 case Stmt::ObjCForCollectionStmtClass:
   return VisitObjCForCollectionStmt(cast(S));
 
@@ -4060,6 +4063,32 @@ CFGBlock 
*CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
   return VisitStmt(S, AddStmtChoice::AlwaysAdd);
 }
 
+CFGBlock *CFGBuilder::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *FS) {
+  // ObjCAtFinallyStmt are treated like labels, so they are the first statement
+  // in a block.
+
+  if (FS->getFinallyBody())
+addStmt(FS->getFinallyBody());
+
+  CFGBlock *FinallyBlock = Block;
+  if (!FinallyBlock)
+FinallyBlock = createBlock();
+
+  appendStmt(FinallyBlock, FS);
+
+  // Also add the ObjCAtFinallyStmt as a label, like with regular labels.
+  FinallyBlock->setLabel(FS);
+
+  // Bail out if the CFG is bad.
+  if (badCFG)
+return nullptr;
+
+  // We set Block to NULL to allow lazy creation of a new block (if necessary).
+  Block = nullptr;
+
+  return FinallyBlock;
+}
+
 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *Terminator) {
   // "@try"/"@catch" is a control-flow statement.  Thus we stop processing the
   // current block.
@@ -4072,17 +4101,27 @@ CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt 
*Terminator) {
   } else
 TrySuccessor = Succ;
 
-  // FIXME: Implement @finally support.
-  if (Terminator->getFinallyStmt())
-return NYS();
-
   CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
-
   // Create a new block that will contain the try statement.
   CFGBlock *NewTryTerminatedBlock = createBlock(false);
   // Add the terminator in the try block.
   NewTryTerminatedBlock->setTerminator(Terminator);
 
+  CFGBlock *FinallyBlock = nullptr;
+
+  if (Terminator->getFinallyStmt()) {
+Succ = TrySuccessor;
+
+Block = nullptr;
+FinallyBlock = VisitObjCAtFinallyStmt(Terminator->getFinallyStmt());
+
+if (!FinallyBlock)
+  return nullptr;
+
+// The code after the finally is the implicit successor.
+addSuccessor(NewTryTerminatedBlock, FinallyBlock);
+  }
+
   bool HasCatchAll = false;
   for (ObjCAtCatchStmt *CS : Terminator->catch_stmts()) {
 // The code after the try is the implicit successor.
@@ -4092,19 +4131,31 @@ CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt 
*Terminator) {
 }
 Block = nullptr;
 CFGBlock *CatchBlock = VisitObjCAtCatchStmt(CS);
+
 if (!CatchBlock)
   return nullptr;
+
 // Add this block to the list of successors for the block with the try
 // statement.
 addSuccessor(NewTryTerminatedBlock, CatchBlock);
+
+// After visiting the catch block, add the @finally block as a successor.
+if (FinallyBlock)
+  addSuccessor(CatchBlock, FinallyBlock);
   }
 
-  // FIXME: This needs updating when @finally support is added.
+  // The @finally block, if it exists, should always be a successor.
+
   if (!HasCatchAll) {
-if (PrevTryTerminatedBlock)
-  addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
-else
-  addSuccessor(NewTryTerminatedBlock, >getExit());
+CFGBlock *endBlock = NewTryTerminatedBlock;
+if (FinallyBlock)
+  endBlock = FinallyBlock;
+
+if (PrevTryTerminatedBlock) {
+  addSuccessor(endBlock, PrevTryTerminatedBlock);
+} else {
+  addSuccessor(endBlock, >getExit());
+}
   }
 
   // The code after the try is the implicit successor.

``




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


[clang] [ObjC] Add support for finally blocks (PR #82934)

2024-02-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-analysis

Author: AtariDreams (AtariDreams)


Changes



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


1 Files Affected:

- (modified) clang/lib/Analysis/CFG.cpp (+61-10) 


``diff
diff --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index de70cbbf6cdb38..15db6560d1561f 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -2356,6 +2356,9 @@ CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc,
 case Stmt::ObjCAtTryStmtClass:
   return VisitObjCAtTryStmt(cast(S));
 
+case Stmt::ObjCAtFinallyStmtClass:
+  return VisitObjCAtFinallyStmt(cast(S));
+
 case Stmt::ObjCForCollectionStmtClass:
   return VisitObjCForCollectionStmt(cast(S));
 
@@ -4060,6 +4063,32 @@ CFGBlock 
*CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
   return VisitStmt(S, AddStmtChoice::AlwaysAdd);
 }
 
+CFGBlock *CFGBuilder::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *FS) {
+  // ObjCAtFinallyStmt are treated like labels, so they are the first statement
+  // in a block.
+
+  if (FS->getFinallyBody())
+addStmt(FS->getFinallyBody());
+
+  CFGBlock *FinallyBlock = Block;
+  if (!FinallyBlock)
+FinallyBlock = createBlock();
+
+  appendStmt(FinallyBlock, FS);
+
+  // Also add the ObjCAtFinallyStmt as a label, like with regular labels.
+  FinallyBlock->setLabel(FS);
+
+  // Bail out if the CFG is bad.
+  if (badCFG)
+return nullptr;
+
+  // We set Block to NULL to allow lazy creation of a new block (if necessary).
+  Block = nullptr;
+
+  return FinallyBlock;
+}
+
 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *Terminator) {
   // "@try"/"@catch" is a control-flow statement.  Thus we stop processing the
   // current block.
@@ -4072,17 +4101,27 @@ CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt 
*Terminator) {
   } else
 TrySuccessor = Succ;
 
-  // FIXME: Implement @finally support.
-  if (Terminator->getFinallyStmt())
-return NYS();
-
   CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
-
   // Create a new block that will contain the try statement.
   CFGBlock *NewTryTerminatedBlock = createBlock(false);
   // Add the terminator in the try block.
   NewTryTerminatedBlock->setTerminator(Terminator);
 
+  CFGBlock *FinallyBlock = nullptr;
+
+  if (Terminator->getFinallyStmt()) {
+Succ = TrySuccessor;
+
+Block = nullptr;
+FinallyBlock = VisitObjCAtFinallyStmt(Terminator->getFinallyStmt());
+
+if (!FinallyBlock)
+  return nullptr;
+
+// The code after the finally is the implicit successor.
+addSuccessor(NewTryTerminatedBlock, FinallyBlock);
+  }
+
   bool HasCatchAll = false;
   for (ObjCAtCatchStmt *CS : Terminator->catch_stmts()) {
 // The code after the try is the implicit successor.
@@ -4092,19 +4131,31 @@ CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt 
*Terminator) {
 }
 Block = nullptr;
 CFGBlock *CatchBlock = VisitObjCAtCatchStmt(CS);
+
 if (!CatchBlock)
   return nullptr;
+
 // Add this block to the list of successors for the block with the try
 // statement.
 addSuccessor(NewTryTerminatedBlock, CatchBlock);
+
+// After visiting the catch block, add the @finally block as a successor.
+if (FinallyBlock)
+  addSuccessor(CatchBlock, FinallyBlock);
   }
 
-  // FIXME: This needs updating when @finally support is added.
+  // The @finally block, if it exists, should always be a successor.
+
   if (!HasCatchAll) {
-if (PrevTryTerminatedBlock)
-  addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
-else
-  addSuccessor(NewTryTerminatedBlock, >getExit());
+CFGBlock *endBlock = NewTryTerminatedBlock;
+if (FinallyBlock)
+  endBlock = FinallyBlock;
+
+if (PrevTryTerminatedBlock) {
+  addSuccessor(endBlock, PrevTryTerminatedBlock);
+} else {
+  addSuccessor(endBlock, >getExit());
+}
   }
 
   // The code after the try is the implicit successor.

``




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


[clang] [ObjC] Add support for finally blocks (PR #82934)

2024-02-25 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/82934

>From 08abfad8feb3c54cc1bb9a8eea94e0e91c3ce678 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Sun, 25 Feb 2024 14:52:59 -0500
Subject: [PATCH] [ObjC] Add support for finally blocks

---
 clang/lib/Analysis/CFG.cpp | 71 --
 1 file changed, 61 insertions(+), 10 deletions(-)

diff --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index de70cbbf6cdb38..15db6560d1561f 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -2356,6 +2356,9 @@ CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc,
 case Stmt::ObjCAtTryStmtClass:
   return VisitObjCAtTryStmt(cast(S));
 
+case Stmt::ObjCAtFinallyStmtClass:
+  return VisitObjCAtFinallyStmt(cast(S));
+
 case Stmt::ObjCForCollectionStmtClass:
   return VisitObjCForCollectionStmt(cast(S));
 
@@ -4060,6 +4063,32 @@ CFGBlock 
*CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
   return VisitStmt(S, AddStmtChoice::AlwaysAdd);
 }
 
+CFGBlock *CFGBuilder::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *FS) {
+  // ObjCAtFinallyStmt are treated like labels, so they are the first statement
+  // in a block.
+
+  if (FS->getFinallyBody())
+addStmt(FS->getFinallyBody());
+
+  CFGBlock *FinallyBlock = Block;
+  if (!FinallyBlock)
+FinallyBlock = createBlock();
+
+  appendStmt(FinallyBlock, FS);
+
+  // Also add the ObjCAtFinallyStmt as a label, like with regular labels.
+  FinallyBlock->setLabel(FS);
+
+  // Bail out if the CFG is bad.
+  if (badCFG)
+return nullptr;
+
+  // We set Block to NULL to allow lazy creation of a new block (if necessary).
+  Block = nullptr;
+
+  return FinallyBlock;
+}
+
 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *Terminator) {
   // "@try"/"@catch" is a control-flow statement.  Thus we stop processing the
   // current block.
@@ -4072,17 +4101,27 @@ CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt 
*Terminator) {
   } else
 TrySuccessor = Succ;
 
-  // FIXME: Implement @finally support.
-  if (Terminator->getFinallyStmt())
-return NYS();
-
   CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
-
   // Create a new block that will contain the try statement.
   CFGBlock *NewTryTerminatedBlock = createBlock(false);
   // Add the terminator in the try block.
   NewTryTerminatedBlock->setTerminator(Terminator);
 
+  CFGBlock *FinallyBlock = nullptr;
+
+  if (Terminator->getFinallyStmt()) {
+Succ = TrySuccessor;
+
+Block = nullptr;
+FinallyBlock = VisitObjCAtFinallyStmt(Terminator->getFinallyStmt());
+
+if (!FinallyBlock)
+  return nullptr;
+
+// The code after the finally is the implicit successor.
+addSuccessor(NewTryTerminatedBlock, FinallyBlock);
+  }
+
   bool HasCatchAll = false;
   for (ObjCAtCatchStmt *CS : Terminator->catch_stmts()) {
 // The code after the try is the implicit successor.
@@ -4092,19 +4131,31 @@ CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt 
*Terminator) {
 }
 Block = nullptr;
 CFGBlock *CatchBlock = VisitObjCAtCatchStmt(CS);
+
 if (!CatchBlock)
   return nullptr;
+
 // Add this block to the list of successors for the block with the try
 // statement.
 addSuccessor(NewTryTerminatedBlock, CatchBlock);
+
+// After visiting the catch block, add the @finally block as a successor.
+if (FinallyBlock)
+  addSuccessor(CatchBlock, FinallyBlock);
   }
 
-  // FIXME: This needs updating when @finally support is added.
+  // The @finally block, if it exists, should always be a successor.
+
   if (!HasCatchAll) {
-if (PrevTryTerminatedBlock)
-  addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
-else
-  addSuccessor(NewTryTerminatedBlock, >getExit());
+CFGBlock *endBlock = NewTryTerminatedBlock;
+if (FinallyBlock)
+  endBlock = FinallyBlock;
+
+if (PrevTryTerminatedBlock) {
+  addSuccessor(endBlock, PrevTryTerminatedBlock);
+} else {
+  addSuccessor(endBlock, >getExit());
+}
   }
 
   // The code after the try is the implicit successor.

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


[clang] [ObjC] Add support for finally blocks (PR #82934)

2024-02-25 Thread via cfe-commits

https://github.com/AtariDreams created 
https://github.com/llvm/llvm-project/pull/82934

None

>From 80d60869a593d59501e14bb673c1bd8938c38028 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Sun, 25 Feb 2024 14:52:59 -0500
Subject: [PATCH] [ObjC] Add support for finally blocks

---
 clang/lib/Analysis/CFG.cpp | 71 --
 1 file changed, 61 insertions(+), 10 deletions(-)

diff --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index de70cbbf6cdb38..15db6560d1561f 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -2356,6 +2356,9 @@ CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc,
 case Stmt::ObjCAtTryStmtClass:
   return VisitObjCAtTryStmt(cast(S));
 
+case Stmt::ObjCAtFinallyStmtClass:
+  return VisitObjCAtFinallyStmt(cast(S));
+
 case Stmt::ObjCForCollectionStmtClass:
   return VisitObjCForCollectionStmt(cast(S));
 
@@ -4060,6 +4063,32 @@ CFGBlock 
*CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
   return VisitStmt(S, AddStmtChoice::AlwaysAdd);
 }
 
+CFGBlock *CFGBuilder::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *FS) {
+  // ObjCAtFinallyStmt are treated like labels, so they are the first statement
+  // in a block.
+
+  if (FS->getFinallyBody())
+addStmt(FS->getFinallyBody());
+
+  CFGBlock *FinallyBlock = Block;
+  if (!FinallyBlock)
+FinallyBlock = createBlock();
+
+  appendStmt(FinallyBlock, FS);
+
+  // Also add the ObjCAtFinallyStmt as a label, like with regular labels.
+  FinallyBlock->setLabel(FS);
+
+  // Bail out if the CFG is bad.
+  if (badCFG)
+return nullptr;
+
+  // We set Block to NULL to allow lazy creation of a new block (if necessary).
+  Block = nullptr;
+
+  return FinallyBlock;
+}
+
 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *Terminator) {
   // "@try"/"@catch" is a control-flow statement.  Thus we stop processing the
   // current block.
@@ -4072,17 +4101,27 @@ CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt 
*Terminator) {
   } else
 TrySuccessor = Succ;
 
-  // FIXME: Implement @finally support.
-  if (Terminator->getFinallyStmt())
-return NYS();
-
   CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
-
   // Create a new block that will contain the try statement.
   CFGBlock *NewTryTerminatedBlock = createBlock(false);
   // Add the terminator in the try block.
   NewTryTerminatedBlock->setTerminator(Terminator);
 
+  CFGBlock *FinallyBlock = nullptr;
+
+  if (Terminator->getFinallyStmt()) {
+Succ = TrySuccessor;
+
+Block = nullptr;
+FinallyBlock = VisitObjCAtFinallyStmt(Terminator->getFinallyStmt());
+
+if (!FinallyBlock)
+  return nullptr;
+
+// The code after the finally is the implicit successor.
+addSuccessor(NewTryTerminatedBlock, FinallyBlock);
+  }
+
   bool HasCatchAll = false;
   for (ObjCAtCatchStmt *CS : Terminator->catch_stmts()) {
 // The code after the try is the implicit successor.
@@ -4092,19 +4131,31 @@ CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt 
*Terminator) {
 }
 Block = nullptr;
 CFGBlock *CatchBlock = VisitObjCAtCatchStmt(CS);
+
 if (!CatchBlock)
   return nullptr;
+
 // Add this block to the list of successors for the block with the try
 // statement.
 addSuccessor(NewTryTerminatedBlock, CatchBlock);
+
+// After visiting the catch block, add the @finally block as a successor.
+if (FinallyBlock)
+  addSuccessor(CatchBlock, FinallyBlock);
   }
 
-  // FIXME: This needs updating when @finally support is added.
+  // The @finally block, if it exists, should always be a successor.
+
   if (!HasCatchAll) {
-if (PrevTryTerminatedBlock)
-  addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
-else
-  addSuccessor(NewTryTerminatedBlock, >getExit());
+CFGBlock *endBlock = NewTryTerminatedBlock;
+if (FinallyBlock)
+  endBlock = FinallyBlock;
+
+if (PrevTryTerminatedBlock) {
+  addSuccessor(endBlock, PrevTryTerminatedBlock);
+} else {
+  addSuccessor(endBlock, >getExit());
+}
   }
 
   // The code after the try is the implicit successor.

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


[clang] [clang-format] Add AlignConsecutiveTableGenCondOperatorColons option. (PR #82878)

2024-02-25 Thread Björn Schäpers via cfe-commits


@@ -849,7 +851,12 @@ void WhitespaceManager::alignConsecutiveAssignments() {
 }
 
 void WhitespaceManager::alignConsecutiveBitFields() {
-  if (!Style.AlignConsecutiveBitFields.Enabled)
+  alignConsecutiveColons(Style.AlignConsecutiveBitFields, TT_BitFieldColon);
+}
+
+void WhitespaceManager::alignConsecutiveColons(
+const FormatStyle::AlignConsecutiveStyle , TokenType Type) {

HazardyKnusperkeks wrote:

You're right. I made the mistake thinking it was just an `enum`.

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


[clang] [clang-format] Add a parameter to getStyle() and guessLanguage() (PR #82911)

2024-02-25 Thread Björn Schäpers via cfe-commits

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


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


[clang] [ObjC] Check entire chain of superclasses to see if class layout is statically known (PR #81335)

2024-02-25 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/81335

>From 6822da9a33e9672cb21a12f006778fce1d1ad194 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Fri, 9 Feb 2024 17:51:15 -0500
Subject: [PATCH 1/2] [ObjC] Add pre-commit tests [NFC]

---
 .../constant-non-fragile-ivar-offset.m| 96 +++
 1 file changed, 96 insertions(+)

diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 788b3220af3067..c4bb1ebc9a80be 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,6 +1,13 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
 
 // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
+// CHECK: @"OBJC_IVAR_$_SuperClass.superClassIvar" = hidden constant i64 20
+// CHECK: @"OBJC_IVAR_$_SuperClass._superClassProperty" = hidden constant i64 
24
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar" = global i64 
32
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar2" = global i64 
40
+// CHECK: @"OBJC_IVAR_$_IntermediateClass._intermediateProperty" = hidden 
global i64 48
+// CHECK: @"OBJC_IVAR_$_SubClass.subClassIvar" = global i64 56
+// CHECK: @"OBJC_IVAR_$_SubClass._subClassProperty" = hidden global i64 64
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +27,95 @@ -(void)meth {
 }
 @end
 
+// Ivars declared in the @interface
+@interface SuperClass : NSObject
+@property (nonatomic, assign) int superClassProperty;
+@end
+
+@implementation SuperClass {
+  int superClassIvar; // Declare an ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[SuperClass superClassMethod]"
+- (void)superClassMethod {
+_superClassProperty = 42;
+superClassIvar = 10;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SuperClass
+// CHECK: getelementptr inbounds i8, ptr %1, i64 20
+}
+
+// implicitly synthesized method here
+// CHECK-LABEL: define internal i32 @"\01-[SuperClass superClassProperty]"
+// CHECK: getelementptr inbounds i8, ptr %0, i64 24
+
+// CHECK-LABEL: define internal void @"\01-[SuperClass setSuperClassProperty:]"
+// CHECK: getelementptr inbounds i8, ptr %1, i64 24
+@end
+
+// Inheritance and Ivars
+@interface IntermediateClass : SuperClass
+{
+double intermediateClassIvar;
+
+@protected
+int intermediateClassIvar2;
+}
+@property (nonatomic, strong) SuperClass *intermediateProperty;
+@end
+
+@implementation IntermediateClass
+@synthesize intermediateProperty = _intermediateProperty;
+- (void)intermediateClassMethod {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[IntermediateClass 
intermediateClassPropertyMethod]"
+- (void)intermediateClassPropertyMethod {
+self.intermediateProperty = 0;
+// CHECK: load ptr, ptr @OBJC_SELECTOR_REFERENCES_
+// CHECK: call void @objc_msgSend(ptr noundef %0, ptr noundef %1, ptr 
noundef null)
+}
+
+// CHECK-LABEL: define internal void @"\01-[IntermediateClass 
intermediateClassPropertyMethodDirect]"
+- (void)intermediateClassPropertyMethodDirect {
+_intermediateProperty = 0;
+// CHECK: load i64, ptr 
@"OBJC_IVAR_$_IntermediateClass._intermediateProperty"
+}
+@end
+
+@interface SubClass : IntermediateClass
+{
+double subClassIvar;
+}
+@property (nonatomic, assign) SubClass *subClassProperty;
+@end
+
+@implementation SubClass
+// CHECK-LABEL: define internal void @"\01-[SubClass subclassVar]"
+- (void)subclassVar {
+
+subClassIvar = 6.28;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[SubClass intermediateSubclassVar]"
+-(void)intermediateSubclassVar {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// implicit synthesized method here:
+// CHECK-LABEL: define internal ptr @"\01-[SubClass subClassProperty]"
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass._subClassProperty"
+
+// CHECK-LABEL: define internal void @"\01-[SubClass setSubClassProperty:]"
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass._subClassProperty"
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

>From c23121c970e765ae90b4abeffa364ca5037a1249 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Tue, 13 Feb 2024 14:52:49 -0500
Subject: [PATCH 2/2] [ObjC] Check entire chain of superclasses to see if class
 layout is statically known

As of now, we only check if a class directly inherits from NSObject to 
determine 

[clang-tools-extra] [clangd] Prevent printing huge initializer lists in hover definitions (PR #79746)

2024-02-25 Thread Raoul Wols via cfe-commits

https://github.com/rwols updated https://github.com/llvm/llvm-project/pull/79746

>From 6d30615ba3fb59163938656827a60a838e160c31 Mon Sep 17 00:00:00 2001
From: Raoul Wols 
Date: Sat, 10 Feb 2024 20:52:03 +0100
Subject: [PATCH] [clangd] Do not render large initializer expressions from the
 preamble

An attempt is made to estimate the size of the initializer expression.
If it has less than 100 (in)direct AST child nodes we'll assume it should
render OK.
---
 clang-tools-extra/clangd/Hover.cpp| 14 -
 .../clangd/unittests/HoverTests.cpp   | 51 +++
 2 files changed, 63 insertions(+), 2 deletions(-)

diff --git a/clang-tools-extra/clangd/Hover.cpp 
b/clang-tools-extra/clangd/Hover.cpp
index 06b949bc4a2b55..c3c5cf2732486d 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -136,6 +136,15 @@ std::string getNamespaceScope(const Decl *D) {
   return "";
 }
 
+/// Compute the number of child statements in this statement. Includes the
+/// statement itself.
+size_t totalChildrenInStmt(const Stmt *Statement) {
+  size_t Count = 1;
+  for (const auto  : Statement->children())
+Count += totalChildrenInStmt(Child);
+  return Count;
+}
+
 std::string printDefinition(const Decl *D, PrintingPolicy PP,
 const syntax::TokenBuffer ) {
   if (auto *VD = llvm::dyn_cast(D)) {
@@ -143,8 +152,9 @@ std::string printDefinition(const Decl *D, PrintingPolicy 
PP,
   // Initializers might be huge and result in lots of memory allocations in
   // some catostrophic cases. Such long lists are not useful in hover cards
   // anyway.
-  if (200 < TB.expandedTokens(IE->getSourceRange()).size())
-PP.SuppressInitializers = true;
+  PP.SuppressInitializers =
+  200 < TB.expandedTokens(IE->getSourceRange()).size() ||
+  100 < totalChildrenInStmt(IE);
 }
   }
   std::string Definition;
diff --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp 
b/clang-tools-extra/clangd/unittests/HoverTests.cpp
index 35db757b9c15b5..9b213da9ec844b 100644
--- a/clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -3956,6 +3956,57 @@ TEST(Hover, HideBigInitializers) {
   EXPECT_EQ(H->Definition, "int arr[]");
 }
 
+TEST(Hover, HideBigInitializersIncludedFromThePreamble) {
+  Annotations T(R"cpp(
+  #include "hugearray.h"
+  auto x = a^rr;
+  )cpp");
+  TestTU TU = TestTU::withCode(T.code());
+  TU.AdditionalFiles["hugearray.h"] = R"cpp(
+#define A(x) x, x, x, x
+#define B(x) A(A(A(A(x
+int arr[256] = {B(0)};
+  )cpp";
+  auto AST = TU.build();
+  auto H = getHover(AST, T.point(), format::getLLVMStyle(), nullptr);
+  ASSERT_TRUE(H);
+  EXPECT_EQ(H->Definition, "int arr[256]");
+}
+
+TEST(Hover, HideBigNestedInitializersIncludedFromThePreamble) {
+  Annotations T(R"cpp(
+  #include "hugearray.h"
+  auto x = a^rr;
+  )cpp");
+  TestTU TU = TestTU::withCode(T.code());
+  TU.AdditionalFiles["hugearray.h"] = R"cpp(
+#define A(x) x, x, x, x
+#define B(x) A(A(A(A(x
+int arr[1][1][256] = {{{B(0)}}};
+  )cpp";
+  auto AST = TU.build();
+  auto H = getHover(AST, T.point(), format::getLLVMStyle(), nullptr);
+  ASSERT_TRUE(H);
+  EXPECT_EQ(H->Definition, "int arr[1][1][256]");
+}
+
+TEST(Hover, DoNotHideSmallInitializersIncludedFromThePreamble) {
+  Annotations T(R"cpp(
+  #include "smallarray.h"
+  auto x = a^rr;
+  )cpp");
+  TestTU TU = TestTU::withCode(T.code());
+  TU.AdditionalFiles["smallarray.h"] = R"cpp(
+#define A(x) x, x
+#define B(x) A(A(x))
+int arr[4] = {B(0)};
+  )cpp";
+  auto AST = TU.build();
+  auto H = getHover(AST, T.point(), format::getLLVMStyle(), nullptr);
+  ASSERT_TRUE(H);
+  EXPECT_EQ(H->Definition, "int arr[4] = {0, 0, 0, 0}");
+}
+
 #if defined(__aarch64__)
 // FIXME: AARCH64 sanitizer buildbots are broken after 72142fbac4.
 #define PREDEFINEMACROS_TEST(x) DISABLED_##x

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


[clang] Thread safety analysis: provide printSCFG definition. (PR #80277)

2024-02-25 Thread Aaron Puchert via cfe-commits

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

Thanks, looks good to me!

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


[clang-tools-extra] [run-clang-tidy.py] Add option to ignore source files from compilation database (PR #82416)

2024-02-25 Thread via cfe-commits

github-actions[bot] wrote:



@duddel Congratulations on having your first Pull Request (PR) merged into the 
LLVM Project!

Your changes will be combined with recent changes from other authors, then 
tested
by our [build bots](https://lab.llvm.org/buildbot/). If there is a problem with 
a build, you may recieve a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as
the builds can include changes from many authors. It is not uncommon for your
change to be included in a build that fails due to someone else's changes, or
infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail 
[here](https://llvm.org/docs/MyFirstTypoFix.html#myfirsttypofix-issues-after-landing-your-pr).

If your change does cause a problem, it may be reverted, or you can revert it 
yourself.
This is a normal part of [LLVM 
development](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy).
 You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are 
working as expected, well done!


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


[clang-tools-extra] [run-clang-tidy.py] Add option to ignore source files from compilation database (PR #82416)

2024-02-25 Thread Piotr Zegar via cfe-commits

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


[clang-tools-extra] 8dfc023 - [run-clang-tidy.py] Add option to ignore source files from compilation database (#82416)

2024-02-25 Thread via cfe-commits

Author: Alexander Scholz
Date: 2024-02-25T17:42:57+01:00
New Revision: 8dfc023e80c35aded33b3e5e4739d3a487b95a7a

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

LOG: [run-clang-tidy.py] Add option to ignore source files from compilation 
database (#82416)

I added the option -source-filter to the
`run-clang-tidy.py` script in the clang-tools-extra.

This option allows for handing over a regex, to filter out source files
from the compilation database (not run `clang-tidy` on them).

Added: 


Modified: 
clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
clang-tools-extra/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py 
b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
index 70f8cbcdcb2f11..1bd4a5b283091c 100755
--- a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -300,6 +300,13 @@ def main():
 "the main file of each translation unit are always "
 "displayed.",
 )
+parser.add_argument(
+"-source-filter",
+default=None,
+help="Regular expression matching the names of the "
+"source files from compilation database to output "
+"diagnostics from.",
+)
 parser.add_argument(
 "-line-filter",
 default=None,
@@ -462,6 +469,19 @@ def main():
 [make_absolute(entry["file"], entry["directory"]) for entry in 
database]
 )
 
+# Filter source files from compilation database.
+if args.source_filter:
+try:
+source_filter_re = re.compile(args.source_filter)
+except:
+print(
+"Error: unable to compile regex from arg -source-filter:",
+file=sys.stderr,
+)
+traceback.print_exc()
+sys.exit(1)
+files = {f for f in files if source_filter_re.match(f)}
+
 max_task = args.j
 if max_task == 0:
 max_task = multiprocessing.cpu_count()

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index a0b9fcfe0d7774..6fd01ed9d471c5 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -97,6 +97,10 @@ The improvements are...
 Improvements to clang-tidy
 --
 
+- Improved :program:`run-clang-tidy.py` script. Added argument `-source-filter`
+  to filter source files from the compilation database, via a RegEx. In a
+  similar fashion to what `-header-filter` does for header files.
+
 New checks
 ^^
 



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


[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-25 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,167 @@
+//===--- UnsafeCrtpCheck.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 "UnsafeCrtpCheck.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+// Finds a node if it's already a bound node.
+AST_MATCHER_P(CXXRecordDecl, isBoundNode, std::string, ID) {
+  return Builder->removeBindings(
+  [&](const ast_matchers::internal::BoundNodesMap ) {
+const auto *BoundRecord = Nodes.getNodeAs(ID);
+return BoundRecord != 
+  });
+}
+
+bool hasPrivateConstructor(const CXXRecordDecl *RD) {
+  for (auto & : RD->ctors()) {
+if (Ctor->getAccess() == AS_private)
+  return true;
+  }
+
+  return false;
+}
+
+bool isDerivedParameterBefriended(const CXXRecordDecl *CRTP,
+  const NamedDecl *Param) {
+  for (auto & : CRTP->friends()) {
+const auto *TTPT =
+dyn_cast(Friend->getFriendType()->getType());
+
+if (TTPT && TTPT->getDecl() == Param)
+  return true;
+  }
+
+  return false;
+}
+
+bool isDerivedClassBefriended(const CXXRecordDecl *CRTP,
+  const CXXRecordDecl *Derived) {
+  for (auto & : CRTP->friends()) {
+if (Friend->getFriendType()->getType()->getAsCXXRecordDecl() == Derived)
+  return true;
+  }
+
+  return false;
+}
+
+std::optional
+getDerivedParameter(const ClassTemplateSpecializationDecl *CRTP,
+const CXXRecordDecl *Derived) {
+  size_t Idx = 0;
+  bool Found = false;
+  for (auto & : CRTP->getTemplateArgs().asArray()) {
+if (TemplateArg.getKind() == TemplateArgument::Type &&
+TemplateArg.getAsType()->getAsCXXRecordDecl() == Derived) {
+  Found = true;
+  break;
+}
+++Idx;
+  }
+
+  if (!Found)
+return std::nullopt;
+
+  return 
CRTP->getSpecializedTemplate()->getTemplateParameters()->getParam(Idx);
+}
+
+std::vector hintMakeCtorPrivate(const CXXConstructorDecl *Ctor,
+   const std::string ,
+   const SourceManager ,
+   const LangOptions ) {
+  std::vector Hints;
+
+  Hints.emplace_back(FixItHint::CreateInsertion(
+  Ctor->getBeginLoc().getLocWithOffset(-1), "private:\n"));
+
+  SourceLocation CtorEndLoc =
+  Ctor->isExplicitlyDefaulted()
+  ? utils::lexer::findNextTerminator(Ctor->getEndLoc(), SM, LangOpts)
+  : Ctor->getEndLoc();
+  Hints.emplace_back(FixItHint::CreateInsertion(
+  CtorEndLoc.getLocWithOffset(1), '\n' + OriginalAccess + ':' + '\n'));
+
+  return Hints;
+}
+} // namespace
+
+void UnsafeCrtpCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  classTemplateSpecializationDecl(
+  decl().bind("crtp"),
+  hasAnyTemplateArgument(refersToType(recordType(hasDeclaration(
+  cxxRecordDecl(isDerivedFrom(cxxRecordDecl(isBoundNode("crtp"
+  .bind("derived")),
+  this);
+}
+
+void UnsafeCrtpCheck::check(const MatchFinder::MatchResult ) {
+  const auto *CRTPInstantiation =
+  Result.Nodes.getNodeAs("crtp");
+  const auto *DerivedRecord = Result.Nodes.getNodeAs("derived");
+  const CXXRecordDecl *CRTPDeclaration =
+  CRTPInstantiation->getSpecializedTemplate()->getTemplatedDecl();
+
+  if (!CRTPDeclaration->hasUserDeclaredConstructor()) {
+bool IsStruct = CRTPDeclaration->isStruct();
+
+diag(CRTPDeclaration->getLocation(),
+ "the implicit default constructor of the CRTP is publicly accessible")
+<< CRTPDeclaration
+<< FixItHint::CreateInsertion(
+   CRTPDeclaration->getBraceRange().getBegin().getLocWithOffset(1),
+   (IsStruct ? "\nprivate:\n" : "\n") +
+   CRTPDeclaration->getNameAsString() + "() = default;\n" +
+   (IsStruct ? "public:\n" : ""));

PiotrZSL wrote:

Main idea should be: do not add something that isn't needed.
It's up to you anyway.

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


[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-25 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,232 @@
+// RUN: %check_clang_tidy %s bugprone-unsafe-crtp %t
+
+namespace class_implicit_ctor {
+template 
+class CRTP {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: the implicit default constructor 
of the CRTP is publicly accessible [bugprone-unsafe-crtp]
+// CHECK-MESSAGES: :[[@LINE-2]]:7: note: consider making it private

PiotrZSL wrote:

Template is about something else, is explicitly point a place in code when 
something could be done.
Usually best is to emit one diagnostic for specific location in code

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


[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-25 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,177 @@
+//===--- CrtpConstructorAccessibilityCheck.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 "CrtpConstructorAccessibilityCheck.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+static bool hasPrivateConstructor(const CXXRecordDecl *RD) {
+  return llvm::any_of(RD->ctors(), [](const CXXConstructorDecl *Ctor) {
+return Ctor->getAccess() == AS_private;
+  });
+}
+
+static bool isDerivedParameterBefriended(const CXXRecordDecl *CRTP,
+ const NamedDecl *Param) {
+  return llvm::any_of(CRTP->friends(), [&](const FriendDecl *Friend) {
+const auto *TTPT =
+dyn_cast(Friend->getFriendType()->getType());
+
+return TTPT && TTPT->getDecl() == Param;
+  });
+}
+
+static bool isDerivedClassBefriended(const CXXRecordDecl *CRTP,
+ const CXXRecordDecl *Derived) {
+  return llvm::any_of(CRTP->friends(), [&](const FriendDecl *Friend) {
+return Friend->getFriendType()->getType()->getAsCXXRecordDecl() == Derived;
+  });
+}
+
+static const NamedDecl *
+getDerivedParameter(const ClassTemplateSpecializationDecl *CRTP,
+const CXXRecordDecl *Derived) {
+  size_t Idx = 0;
+  const bool AnyOf = llvm::any_of(
+  CRTP->getTemplateArgs().asArray(), [&](const TemplateArgument ) {
+++Idx;
+return Arg.getKind() == TemplateArgument::Type &&
+   Arg.getAsType()->getAsCXXRecordDecl() == Derived;
+  });
+
+  return AnyOf ? CRTP->getSpecializedTemplate()
+ ->getTemplateParameters()
+ ->getParam(Idx - 1)
+   : nullptr;
+}
+
+static std::vector
+hintMakeCtorPrivate(const CXXConstructorDecl *Ctor,
+const std::string ) {
+  std::vector Hints;
+
+  Hints.emplace_back(FixItHint::CreateInsertion(
+  Ctor->getBeginLoc().getLocWithOffset(-1), "private:\n"));
+
+  const ASTContext  = Ctor->getASTContext();
+  const SourceLocation CtorEndLoc =
+  Ctor->isExplicitlyDefaulted()
+  ? utils::lexer::findNextTerminator(Ctor->getEndLoc(),
+ ASTCtx.getSourceManager(),
+ ASTCtx.getLangOpts())
+  : Ctor->getEndLoc();
+  Hints.emplace_back(FixItHint::CreateInsertion(
+  CtorEndLoc.getLocWithOffset(1), '\n' + OriginalAccess + ':' + '\n'));
+
+  return Hints;
+}
+
+void CrtpConstructorAccessibilityCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  classTemplateSpecializationDecl(
+  decl().bind("crtp"),
+  hasAnyTemplateArgument(refersToType(recordType(hasDeclaration(
+  cxxRecordDecl(
+  isDerivedFrom(cxxRecordDecl(equalsBoundNode("crtp"
+  .bind("derived")),
+  this);
+}
+
+void CrtpConstructorAccessibilityCheck::check(
+const MatchFinder::MatchResult ) {
+  const auto *CRTPInstantiation =
+  Result.Nodes.getNodeAs("crtp");
+  const auto *DerivedRecord = Result.Nodes.getNodeAs("derived");
+  const CXXRecordDecl *CRTPDeclaration =
+  CRTPInstantiation->getSpecializedTemplate()->getTemplatedDecl();
+
+  const auto *DerivedTemplateParameter =
+  getDerivedParameter(CRTPInstantiation, DerivedRecord);
+
+  assert(DerivedTemplateParameter &&
+ "No template parameter corresponds to the derived class of the 
CRTP.");
+
+  bool NeedsFriend = !isDerivedParameterBefriended(CRTPDeclaration,
+   DerivedTemplateParameter) &&
+ !isDerivedClassBefriended(CRTPDeclaration, DerivedRecord);
+
+  const FixItHint HintFriend = FixItHint::CreateInsertion(
+  CRTPDeclaration->getBraceRange().getEnd(),
+  "friend " + DerivedTemplateParameter->getNameAsString() + ';' + '\n');
+
+  if (hasPrivateConstructor(CRTPDeclaration) && NeedsFriend) {
+diag(CRTPDeclaration->getLocation(),
+ "the CRTP cannot be constructed from the derived class")
+<< CRTPDeclaration << HintFriend;

PiotrZSL wrote:

Remove: " << CRTPDeclaration"

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


[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-25 Thread Piotr Zegar via cfe-commits

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


[clang] 411c5dd - [clang][Interp] Handle null function pointers

2024-02-25 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-25T17:26:36+01:00
New Revision: 411c5dde59fa4c427941143ca0ec8cd8fdaee407

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

LOG: [clang][Interp] Handle null function pointers

We were instead asserting that they are non-null before.

Added: 


Modified: 
clang/lib/AST/Interp/FunctionPointer.h
clang/lib/AST/Interp/Interp.h
clang/test/AST/Interp/functions.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/FunctionPointer.h 
b/clang/lib/AST/Interp/FunctionPointer.h
index 4a3f993d4882e2..bb3da9b50aa552 100644
--- a/clang/lib/AST/Interp/FunctionPointer.h
+++ b/clang/lib/AST/Interp/FunctionPointer.h
@@ -26,6 +26,7 @@ class FunctionPointer final {
   FunctionPointer(const Function *Func) : Func(Func) { assert(Func); }
 
   const Function *getFunction() const { return Func; }
+  bool isZero() const { return !Func; }
 
   APValue toAPValue() const {
 if (!Func)

diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 23a2756a18f690..d885d19ce7064f 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -2087,6 +2087,12 @@ inline bool CallPtr(InterpState , CodePtr OpPC, 
uint32_t ArgSize) {
   const FunctionPointer  = S.Stk.pop();
 
   const Function *F = FuncPtr.getFunction();
+  if (!F) {
+const Expr *E = S.Current->getExpr(OpPC);
+S.FFDiag(E, diag::note_constexpr_null_callee)
+<< const_cast(E) << E->getSourceRange();
+return false;
+  }
   assert(F);
 
   assert(ArgSize >= F->getWrittenArgSize());

diff  --git a/clang/test/AST/Interp/functions.cpp 
b/clang/test/AST/Interp/functions.cpp
index 51269741eb9018..9daf8722050f07 100644
--- a/clang/test/AST/Interp/functions.cpp
+++ b/clang/test/AST/Interp/functions.cpp
@@ -123,9 +123,12 @@ namespace FunctionPointers {
   }
 
   constexpr int applyBinOp(int a, int b, int (*op)(int, int)) {
-return op(a, b);
+return op(a, b); // both-note {{evaluates to a null function pointer}}
   }
   static_assert(applyBinOp(1, 2, add) == 3, "");
+  static_assert(applyBinOp(1, 2, nullptr) == 3, ""); // both-error {{not an 
integral constant expression}} \
+ // both-note {{in call 
to}}
+
 
   constexpr int ignoreReturnValue() {
 int (*foo)(int, int) = add;



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


[clang] [Clang][Sema]: Allow copy constructor side effects (PR #81127)

2024-02-25 Thread Vinayak Dev via cfe-commits

vinayakdsci wrote:

@cor3ntin gentle ping. How exactly should I proceed? copy elision was made 
mandatory in C++17, so wouldn't a warning for C++ < 17 be allowable?

I am very happy to implement any suggestions you have for this PR, but I am 
unable to get the code to work for C++ < 17 because the constructors are not 
marked elidable in the code for these standards.

Specifically in the case where the class object is initialized by an '=' sign 
instead of an explicit argument being passed. As the RHS of the '=' is 
different from a `CXXRecordDecl`, `isTemporaryObject()` returns false and thus 
sets the constructor as non-elidable. This is where I am not sure on how to 
proceed, as changing this behavior breaks a number of assertions in the code 
path followed while compiling the source program. Either I could check if the 
RHS of the assignment is an rvalue, and then add an OR condition to set 
Elidable for the constructor to true. However, _whenever_ the constructor is 
elidable, the codegen emits _directly_, and expects an aggregate type to passed 
in, which is not true for a scalar such as an `int`.

Also, this would involve a conversion process in the code?

I would really appreciate pointers on how to solve this problem, and how to 
improve this PR too.

Thanks!

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


[clang] [Clang][ARM][AArch64] Alway emit protection attributes for functions. (PR #82819)

2024-02-25 Thread via cfe-commits


@@ -138,58 +163,79 @@ void run_foo_tml() {
 // CHECK:   resolver_return1:
 // CHECK-NEXT:ret ptr @_ZN7MyClassIisE7foo_tmlEv._Mfrintts
 // CHECK:   resolver_else2:
-// CHECK-NEXT:ret ptr @_ZN7MyClassIisE7foo_tmlEv
+// CHECK-NEXT:ret ptr @_ZN7MyClassIisE7foo_tmlEv.default
+//
+//
 // CHECK-LABEL: @_ZN7MyClassIfsE7foo_tmlEv(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[THIS_ADDR:%.*]] = alloca ptr, align 8
 // CHECK-NEXT:store ptr [[THIS:%.*]], ptr [[THIS_ADDR]], align 8
 // CHECK-NEXT:[[THIS1:%.*]] = load ptr, ptr [[THIS_ADDR]], align 8
 // CHECK-NEXT:ret i32 3
+//
+//
 // CHECK-LABEL: @_ZN7MyClassIdfE7foo_tmlEv(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[THIS_ADDR:%.*]] = alloca ptr, align 8
 // CHECK-NEXT:store ptr [[THIS:%.*]], ptr [[THIS_ADDR]], align 8
 // CHECK-NEXT:[[THIS1:%.*]] = load ptr, ptr [[THIS_ADDR]], align 8
 // CHECK-NEXT:ret i32 4
+//
+//
 // CHECK-LABEL: @_ZN7MyClassIssE7foo_tmlEv._Mfrintts(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[THIS_ADDR:%.*]] = alloca ptr, align 8
 // CHECK-NEXT:store ptr [[THIS:%.*]], ptr [[THIS_ADDR]], align 8
 // CHECK-NEXT:[[THIS1:%.*]] = load ptr, ptr [[THIS_ADDR]], align 8
 // CHECK-NEXT:ret i32 1
+//
+//
 // CHECK-LABEL: @_ZN7MyClassIssE7foo_tmlEv._MssbsMsme-f64f64(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[THIS_ADDR:%.*]] = alloca ptr, align 8
 // CHECK-NEXT:store ptr [[THIS:%.*]], ptr [[THIS_ADDR]], align 8
 // CHECK-NEXT:[[THIS1:%.*]] = load ptr, ptr [[THIS_ADDR]], align 8
 // CHECK-NEXT:ret i32 1
+//
+//
 // CHECK-LABEL: @_ZN7MyClassIssE7foo_tmlEv.default(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[THIS_ADDR:%.*]] = alloca ptr, align 8
 // CHECK-NEXT:store ptr [[THIS:%.*]], ptr [[THIS_ADDR]], align 8
 // CHECK-NEXT:[[THIS1:%.*]] = load ptr, ptr [[THIS_ADDR]], align 8
 // CHECK-NEXT:ret i32 1
+//
+//
 // CHECK-LABEL: @_ZN7MyClassIisE7foo_tmlEv._Mfrintts(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[THIS_ADDR:%.*]] = alloca ptr, align 8
 // CHECK-NEXT:store ptr [[THIS:%.*]], ptr [[THIS_ADDR]], align 8
 // CHECK-NEXT:[[THIS1:%.*]] = load ptr, ptr [[THIS_ADDR]], align 8
 // CHECK-NEXT:ret i32 2
+//
+//
 // CHECK-LABEL: @_ZN7MyClassIisE7foo_tmlEv._MssbsMsme-f64f64(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[THIS_ADDR:%.*]] = alloca ptr, align 8
 // CHECK-NEXT:store ptr [[THIS:%.*]], ptr [[THIS_ADDR]], align 8
 // CHECK-NEXT:[[THIS1:%.*]] = load ptr, ptr [[THIS_ADDR]], align 8
 // CHECK-NEXT:ret i32 2
+//
+//
 // CHECK-LABEL: @_ZN7MyClassIisE7foo_tmlEv.default(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[THIS_ADDR:%.*]] = alloca ptr, align 8
 // CHECK-NEXT:store ptr [[THIS:%.*]], ptr [[THIS_ADDR]], align 8
 // CHECK-NEXT:[[THIS1:%.*]] = load ptr, ptr [[THIS_ADDR]], align 8
 // CHECK-NEXT:ret i32 2
-
-// CHECK: attributes #0 = { mustprogress noinline nounwind optnone 
"no-trapping-math"="true" "stack-protector-buffer-size"="8" 
"target-features"="+fp-armv8,+fullfp16,+neon" }
-// CHECK: attributes #1 = { mustprogress noinline nounwind optnone 
"no-trapping-math"="true" "stack-protector-buffer-size"="8" }
-// CHECK: attributes #2 = { mustprogress noinline nounwind optnone 
"no-trapping-math"="true" "stack-protector-buffer-size"="8" 
"target-features"="+ls64" }
-// CHECK: attributes #3 = { mustprogress noinline nounwind optnone 
"no-trapping-math"="true" "stack-protector-buffer-size"="8" 
"target-features"="+fptoint" }
-// CHECK: attributes #4 = { mustprogress noinline nounwind optnone 
"no-trapping-math"="true" "stack-protector-buffer-size"="8" 
"target-features"="+bf16,+sme,+sme-f64f64" }
+//
+//.
+// CHECK: attributes #[[ATTR0:[0-9]+]] = { mustprogress noinline nounwind 
optnone "branch-protection-pauth-lr"="false" 
"branch-target-enforcement"="false" "guarded-control-stack"="false" 
"no-trapping-math"="true" "sign-return-address"="none" 
"stack-protector-buffer-size"="8" "target-features"="+fp-armv8,+fullfp16,+neon" 
}
+// CHECK: attributes #[[ATTR1:[0-9]+]] = { mustprogress noinline nounwind 
optnone "branch-protection-pauth-lr"="false" 
"branch-target-enforcement"="false" "guarded-control-stack"="false" 
"no-trapping-math"="true" "sign-return-address"="none" 
"stack-protector-buffer-size"="8" }
+// CHECK: attributes #[[ATTR2:[0-9]+]] = { mustprogress noinline nounwind 
optnone "branch-protection-pauth-lr"="false" 
"branch-target-enforcement"="false" "guarded-control-stack"="false" 
"no-trapping-math"="true" "sign-return-address"="none" 
"stack-protector-buffer-size"="8" "target-features"="+ls64" }
+// CHECK: attributes #[[ATTR3:[0-9]+]] = { mustprogress noinline nounwind 
optnone "branch-protection-pauth-lr"="false" 
"branch-target-enforcement"="false" "guarded-control-stack"="false" 
"no-trapping-math"="true" "sign-return-address"="none" 
"stack-protector-buffer-size"="8" "target-features"="+fptoint" }
+// CHECK: attributes #[[ATTR4:[0-9]+]] = { mustprogress noinline nounwind 
optnone 

[clang] [Clang][ARM][AArch64] Alway emit protection attributes for functions. (PR #82819)

2024-02-25 Thread via cfe-commits


@@ -0,0 +1,16 @@
+// REQUIRES: arm-registered-target
+
+// RUN: %clang -flto -target thumbv7m-unknown-unknown-eabi 
-mbranch-protection=pac-ret %s -S -o - 2>&1 | FileCheck %s

DanielKristofKiss wrote:

Done

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


[clang] [Clang][ARM][AArch64] Alway emit protection attributes for functions. (PR #82819)

2024-02-25 Thread via cfe-commits

https://github.com/DanielKristofKiss updated 
https://github.com/llvm/llvm-project/pull/82819

>From c5c2d720e822624fa7966297087b04e6b2fc2a86 Mon Sep 17 00:00:00 2001
From: Daniel Kiss 
Date: Fri, 23 Feb 2024 17:12:26 +0100
Subject: [PATCH 1/3] [NFC][ARM][AArch64] Deduplicated code.

Add the SignReturnAddressScopeKind to the BranchProtectionInfo class.
---
 clang/include/clang/Basic/TargetInfo.h | 21 ++---
 clang/lib/CodeGen/Targets/AArch64.cpp  |  3 +--
 clang/lib/CodeGen/Targets/ARM.cpp  |  8 +---
 3 files changed, 16 insertions(+), 16 deletions(-)

diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 48e9cec482755c..2eb4f0e2ca42a6 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -1369,13 +1369,20 @@ class TargetInfo : public TransferrableTargetInfo,
   }
 
   struct BranchProtectionInfo {
-LangOptions::SignReturnAddressScopeKind SignReturnAddr =
-LangOptions::SignReturnAddressScopeKind::None;
-LangOptions::SignReturnAddressKeyKind SignKey =
-LangOptions::SignReturnAddressKeyKind::AKey;
-bool BranchTargetEnforcement = false;
-bool BranchProtectionPAuthLR = false;
-bool GuardedControlStack = false;
+LangOptions::SignReturnAddressScopeKind SignReturnAddr;
+LangOptions::SignReturnAddressKeyKind SignKey;
+bool BranchTargetEnforcement;
+bool BranchProtectionPAuthLR;
+bool GuardedControlStack;
+
+BranchProtectionInfo() = default;
+
+const char *getSignReturnAddrStr() const {
+  static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
+  assert(static_cast(SignReturnAddr) <= 2 &&
+ "Unexpected SignReturnAddressScopeKind");
+  return SignReturnAddrStr[static_cast(SignReturnAddr)];
+}
   };
 
   /// Determine if the Architecture in this TargetInfo supports branch
diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp 
b/clang/lib/CodeGen/Targets/AArch64.cpp
index 94f8e7be2ee6eb..f0af87b00b91f4 100644
--- a/clang/lib/CodeGen/Targets/AArch64.cpp
+++ b/clang/lib/CodeGen/Targets/AArch64.cpp
@@ -125,8 +125,7 @@ class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
 assert(Error.empty());
 
 auto *Fn = cast(GV);
-static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
-Fn->addFnAttr("sign-return-address", 
SignReturnAddrStr[static_cast(BPI.SignReturnAddr)]);
+Fn->addFnAttr("sign-return-address", BPI.getSignReturnAddrStr());
 
 if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
   Fn->addFnAttr("sign-return-address-key",
diff --git a/clang/lib/CodeGen/Targets/ARM.cpp 
b/clang/lib/CodeGen/Targets/ARM.cpp
index d7d175ff1724f7..5d42e6286e525b 100644
--- a/clang/lib/CodeGen/Targets/ARM.cpp
+++ b/clang/lib/CodeGen/Targets/ARM.cpp
@@ -152,13 +152,7 @@ class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
   diag::warn_target_unsupported_branch_protection_attribute)
   << Arch;
 } else {
-  static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
-  assert(static_cast(BPI.SignReturnAddr) <= 2 &&
- "Unexpected SignReturnAddressScopeKind");
-  Fn->addFnAttr(
-  "sign-return-address",
-  SignReturnAddrStr[static_cast(BPI.SignReturnAddr)]);
-
+  Fn->addFnAttr("sign-return-address", BPI.getSignReturnAddrStr());
   Fn->addFnAttr("branch-target-enforcement",
 BPI.BranchTargetEnforcement ? "true" : "false");
 }

>From c82cb029dc73130f46df79cf6c1228f690ef71af Mon Sep 17 00:00:00 2001
From: Daniel Kiss 
Date: Mon, 22 Jan 2024 11:33:15 +0100
Subject: [PATCH 2/3] [Clang][ARM][AArch64] Emit attributes for functions
 always.

Branch protection, sign return address, guarded control stack flags are
only emitted as module flags if not specified per function.

The inliner might inline functions with different set of flags as it
doesn't see the flags.

In case of LTO build the module flags get merged with the `min` rule which means
if one of the modules is not build with PAC/BTI then the features will be turned
off on all functions due to the functions takes the branch-protection and
sign-return-address features from the module flags. The sign-return-address is
function level option therefore it is expected functions from files that are
compiled with -mbranch-protection=pac-ret to be protected but in LTO case this
might not happen. This patch adds the flags to functions in case of an LTO build
therefore they don't need to rely on the module flag.
---
 clang/include/clang/Basic/TargetInfo.h| 15 +
 clang/lib/CodeGen/Targets/AArch64.cpp | 27 
 clang/lib/CodeGen/Targets/ARM.cpp |  7 ++
 .../CodeGen/aarch64-cpu-supports-target.c |  6 +-
 .../CodeGen/aarch64-sign-return-address.c | 26 ++--
 .../aarch64-sme-attrs.cpp | 24 +++
 

[clang] [NFC][ARM][AArch64] Deduplicated code. (PR #82785)

2024-02-25 Thread via cfe-commits

https://github.com/DanielKristofKiss updated 
https://github.com/llvm/llvm-project/pull/82785

>From c5c2d720e822624fa7966297087b04e6b2fc2a86 Mon Sep 17 00:00:00 2001
From: Daniel Kiss 
Date: Fri, 23 Feb 2024 17:12:26 +0100
Subject: [PATCH] [NFC][ARM][AArch64] Deduplicated code.

Add the SignReturnAddressScopeKind to the BranchProtectionInfo class.
---
 clang/include/clang/Basic/TargetInfo.h | 21 ++---
 clang/lib/CodeGen/Targets/AArch64.cpp  |  3 +--
 clang/lib/CodeGen/Targets/ARM.cpp  |  8 +---
 3 files changed, 16 insertions(+), 16 deletions(-)

diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 48e9cec482755c..2eb4f0e2ca42a6 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -1369,13 +1369,20 @@ class TargetInfo : public TransferrableTargetInfo,
   }
 
   struct BranchProtectionInfo {
-LangOptions::SignReturnAddressScopeKind SignReturnAddr =
-LangOptions::SignReturnAddressScopeKind::None;
-LangOptions::SignReturnAddressKeyKind SignKey =
-LangOptions::SignReturnAddressKeyKind::AKey;
-bool BranchTargetEnforcement = false;
-bool BranchProtectionPAuthLR = false;
-bool GuardedControlStack = false;
+LangOptions::SignReturnAddressScopeKind SignReturnAddr;
+LangOptions::SignReturnAddressKeyKind SignKey;
+bool BranchTargetEnforcement;
+bool BranchProtectionPAuthLR;
+bool GuardedControlStack;
+
+BranchProtectionInfo() = default;
+
+const char *getSignReturnAddrStr() const {
+  static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
+  assert(static_cast(SignReturnAddr) <= 2 &&
+ "Unexpected SignReturnAddressScopeKind");
+  return SignReturnAddrStr[static_cast(SignReturnAddr)];
+}
   };
 
   /// Determine if the Architecture in this TargetInfo supports branch
diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp 
b/clang/lib/CodeGen/Targets/AArch64.cpp
index 94f8e7be2ee6eb..f0af87b00b91f4 100644
--- a/clang/lib/CodeGen/Targets/AArch64.cpp
+++ b/clang/lib/CodeGen/Targets/AArch64.cpp
@@ -125,8 +125,7 @@ class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
 assert(Error.empty());
 
 auto *Fn = cast(GV);
-static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
-Fn->addFnAttr("sign-return-address", 
SignReturnAddrStr[static_cast(BPI.SignReturnAddr)]);
+Fn->addFnAttr("sign-return-address", BPI.getSignReturnAddrStr());
 
 if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
   Fn->addFnAttr("sign-return-address-key",
diff --git a/clang/lib/CodeGen/Targets/ARM.cpp 
b/clang/lib/CodeGen/Targets/ARM.cpp
index d7d175ff1724f7..5d42e6286e525b 100644
--- a/clang/lib/CodeGen/Targets/ARM.cpp
+++ b/clang/lib/CodeGen/Targets/ARM.cpp
@@ -152,13 +152,7 @@ class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
   diag::warn_target_unsupported_branch_protection_attribute)
   << Arch;
 } else {
-  static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
-  assert(static_cast(BPI.SignReturnAddr) <= 2 &&
- "Unexpected SignReturnAddressScopeKind");
-  Fn->addFnAttr(
-  "sign-return-address",
-  SignReturnAddrStr[static_cast(BPI.SignReturnAddr)]);
-
+  Fn->addFnAttr("sign-return-address", BPI.getSignReturnAddrStr());
   Fn->addFnAttr("branch-target-enforcement",
 BPI.BranchTargetEnforcement ? "true" : "false");
 }

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


[clang-tools-extra] [clangd] Prevent printing huge initializer lists in hover definitions (PR #79746)

2024-02-25 Thread Raoul Wols via cfe-commits

https://github.com/rwols updated https://github.com/llvm/llvm-project/pull/79746

>From 06a84a493646b66a99a9e8e95a64ca09d952be28 Mon Sep 17 00:00:00 2001
From: Raoul Wols 
Date: Sat, 10 Feb 2024 20:52:03 +0100
Subject: [PATCH] [clangd] Do not render large initializer expressions from the
 preamble

An attempt is made to estimate the size of the initializer expression.
If it has less than 100 (in)direct AST child nodes we'll assume it should
render OK.
---
 clang-tools-extra/clangd/Hover.cpp| 14 -
 .../clangd/unittests/HoverTests.cpp   | 51 +++
 2 files changed, 63 insertions(+), 2 deletions(-)

diff --git a/clang-tools-extra/clangd/Hover.cpp 
b/clang-tools-extra/clangd/Hover.cpp
index 06b949bc4a2b55..c3c5cf2732486d 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -136,6 +136,15 @@ std::string getNamespaceScope(const Decl *D) {
   return "";
 }
 
+/// Compute the number of child statements in this statement. Includes the
+/// statement itself.
+size_t totalChildrenInStmt(const Stmt *Statement) {
+  size_t Count = 1;
+  for (const auto  : Statement->children())
+Count += totalChildrenInStmt(Child);
+  return Count;
+}
+
 std::string printDefinition(const Decl *D, PrintingPolicy PP,
 const syntax::TokenBuffer ) {
   if (auto *VD = llvm::dyn_cast(D)) {
@@ -143,8 +152,9 @@ std::string printDefinition(const Decl *D, PrintingPolicy 
PP,
   // Initializers might be huge and result in lots of memory allocations in
   // some catostrophic cases. Such long lists are not useful in hover cards
   // anyway.
-  if (200 < TB.expandedTokens(IE->getSourceRange()).size())
-PP.SuppressInitializers = true;
+  PP.SuppressInitializers =
+  200 < TB.expandedTokens(IE->getSourceRange()).size() ||
+  100 < totalChildrenInStmt(IE);
 }
   }
   std::string Definition;
diff --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp 
b/clang-tools-extra/clangd/unittests/HoverTests.cpp
index 35db757b9c15b5..9b213da9ec844b 100644
--- a/clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -3956,6 +3956,57 @@ TEST(Hover, HideBigInitializers) {
   EXPECT_EQ(H->Definition, "int arr[]");
 }
 
+TEST(Hover, HideBigInitializersIncludedFromThePreamble) {
+  Annotations T(R"cpp(
+  #include "hugearray.h"
+  auto x = a^rr;
+  )cpp");
+  TestTU TU = TestTU::withCode(T.code());
+  TU.AdditionalFiles["hugearray.h"] = R"cpp(
+#define A(x) x, x, x, x
+#define B(x) A(A(A(A(x
+int arr[256] = {B(0)};
+  )cpp";
+  auto AST = TU.build();
+  auto H = getHover(AST, T.point(), format::getLLVMStyle(), nullptr);
+  ASSERT_TRUE(H);
+  EXPECT_EQ(H->Definition, "int arr[256]");
+}
+
+TEST(Hover, HideBigNestedInitializersIncludedFromThePreamble) {
+  Annotations T(R"cpp(
+  #include "hugearray.h"
+  auto x = a^rr;
+  )cpp");
+  TestTU TU = TestTU::withCode(T.code());
+  TU.AdditionalFiles["hugearray.h"] = R"cpp(
+#define A(x) x, x, x, x
+#define B(x) A(A(A(A(x
+int arr[1][1][256] = {{{B(0)}}};
+  )cpp";
+  auto AST = TU.build();
+  auto H = getHover(AST, T.point(), format::getLLVMStyle(), nullptr);
+  ASSERT_TRUE(H);
+  EXPECT_EQ(H->Definition, "int arr[1][1][256]");
+}
+
+TEST(Hover, DoNotHideSmallInitializersIncludedFromThePreamble) {
+  Annotations T(R"cpp(
+  #include "smallarray.h"
+  auto x = a^rr;
+  )cpp");
+  TestTU TU = TestTU::withCode(T.code());
+  TU.AdditionalFiles["smallarray.h"] = R"cpp(
+#define A(x) x, x
+#define B(x) A(A(x))
+int arr[4] = {B(0)};
+  )cpp";
+  auto AST = TU.build();
+  auto H = getHover(AST, T.point(), format::getLLVMStyle(), nullptr);
+  ASSERT_TRUE(H);
+  EXPECT_EQ(H->Definition, "int arr[4] = {0, 0, 0, 0}");
+}
+
 #if defined(__aarch64__)
 // FIXME: AARCH64 sanitizer buildbots are broken after 72142fbac4.
 #define PREDEFINEMACROS_TEST(x) DISABLED_##x

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


[clang] [clang][Sema] Fix for enums overflowing (#24667) (PR #78742)

2024-02-25 Thread via cfe-commits

https://github.com/wheatman updated 
https://github.com/llvm/llvm-project/pull/78742

>From 5a3d785ef4eaa83d8944dedbb4cb1b79914fdacc Mon Sep 17 00:00:00 2001
From: Brian Wheatman 
Date: Fri, 19 Jan 2024 11:13:33 -0500
Subject: [PATCH] [clang][Sema] Fix for overflow in enumerators(#24667)

Enums which do not have a specified type can only grow to bigger types
which contain more bits than the prior types.  This means that the
largest signed integer type cannot grow to the largest unsigned integer types.

In the Process also implements N3029 Improved Normal Enumerations and N3030
Enhancements to Enumerations which brings C enums more inline with C++
enums.

Fixes #24667
---
 clang/docs/ReleaseNotes.rst |  8 +
 clang/lib/Sema/SemaDecl.cpp | 65 -
 clang/test/Sema/enum.c  | 43 +---
 clang/test/SemaCXX/enum.cpp |  2 ++
 4 files changed, 97 insertions(+), 21 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 529dd783ab73825..33a0c2d7d8bb3a4 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -135,6 +135,12 @@ C23 Feature Support
   ``__TYPE_FMTb__`` (e.g., ``__UINT_FAST64_FMTB__``) in C23 mode for use with
   macros typically exposed from , such as ``PRIb8``.
   (`#81896: `_).
+- Enumerations should allow values greater than INT_MAX and smaller than
+  INT_MIN, in order to provide a value-preserved set of integer constants. 
`N3029 Improved Normal Enumerations 
`_
+
+- Enumerations should have the ability to specify the underlying type to aid
+  in portability and usability across platforms, across ABIs, and across
+  languages (for serialization and similar purposes). `N3030 Enhancements to 
Enumerations `_
 
 Non-comprehensive list of changes in this release
 -
@@ -211,6 +217,8 @@ Bug Fixes in This Version
 - Clang now doesn't produce false-positive warning `-Wconstant-logical-operand`
   for logical operators in C23.
   Fixes (`#64356 `_).
+- Fixes miscompilation when an enum has a specified value such that the auto
+  increment overflows a signed long. Fixes (`#24667 
`_)
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 10b5c271f25c10e..d9795589fbe5a38 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -19797,6 +19797,19 @@ EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl 
*Enum,
   // - If an initializer is specified for an enumerator, the
   //   initializing value has the same type as the expression.
   EltTy = Val->getType();
+} else if (getLangOpts().C23) {
+  // C23 6.7.2.2p11 b4
+  // int, if given explicitly with = and the value of the
+  // integer constant expression is representable by an int
+  //
+  // C23 6.7.2.2p11 b5
+  // the type of the integer constant expression, if given
+  // explicitly with = and if the value of the integer
+  // constant expression is not representable by int;
+  if (isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) {
+Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
+  }
+  EltTy = Val->getType();
 } else {
   // C99 6.7.2.2p2:
   //   The expression that defines the value of an enumeration constant
@@ -19806,8 +19819,8 @@ EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl 
*Enum,
   // Complain if the value is not representable in an int.
   if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
 Diag(IdLoc, diag::ext_enum_value_not_int)
-  << toString(EnumVal, 10) << Val->getSourceRange()
-  << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
+<< toString(EnumVal, 10) << Val->getSourceRange()
+<< (EnumVal.isUnsigned() || EnumVal.isNonNegative());
   else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
 // Force the type of the expression to 'int'.
 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
@@ -19855,20 +19868,28 @@ EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl 
*Enum,
 //   sufficient to contain the incremented value. If no such type
 //   exists, the program is ill-formed.
 QualType T = getNextLargerIntegralType(Context, EltTy);
-if (T.isNull() || Enum->isFixed()) {
+if (Enum->isFixed()) {
   // There is no integral type larger enough to represent this
   // value. Complain, 

[clang] [clang] Add __builtin_start_object_lifetime builtin. (PR #82776)

2024-02-25 Thread A. Jiang via cfe-commits


@@ -896,6 +896,12 @@ def Launder : Builtin {
   let Prototype = "void*(void*)";
 }
 
+def StartObjectLifeTime : Builtin {
+  let Spellings = ["__builtin_start_object_lifetime"];

frederick-vs-ja wrote:

IMO if the intent of this intrinsic is to handle polymorphic classes (which is 
not covered by `std::start_lifetime_as`), its name should diverge from "plain" 
`start_lifetime`.

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


[clang] [clang][Sema] Fix for enums overflowing (#24667) (PR #78742)

2024-02-25 Thread via cfe-commits


@@ -18,6 +19,40 @@ enum x  // expected-warning 
{{enumeration values exceed rang
 { y = -9223372036854775807LL-1,  // expected-warning {{ISO C restricts 
enumerator values to range of 'int'}}
 z = 9223372036854775808ULL };// expected-warning {{ISO C restricts 
enumerator values to range of 'int'}}
 
+
+enum GH24667 {   GH24667_x = 9223372036854775807UL, };
+// expected-warning@-1 {{ISO C restricts enumerator values to range of 'int' 
(9223372036854775807 is too large)}}
+
+#else
+enum e {A,
+B = 42LL << 32,
+  C = -4, D = 12456 };
+
+enum g {  // too negative

wheatman wrote:

I have removed those comments, those were copied showing the different behavior 
in different modes, but those comments should only be in the pre C23 version

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


[clang] [clang][Sema] Fix for enums overflowing (#24667) (PR #78742)

2024-02-25 Thread via cfe-commits

https://github.com/wheatman updated 
https://github.com/llvm/llvm-project/pull/78742

>From 294e0995a8e41623e7f82c4f11d2f93c64f4e403 Mon Sep 17 00:00:00 2001
From: Brian Wheatman 
Date: Fri, 19 Jan 2024 11:13:33 -0500
Subject: [PATCH] [clang][Sema] Fix for overflow in enumerators(#24667)

Enums which do not have a specified type can only grow to bigger types
which contain more bits than the prior types.  This means that the
largest signed integer type cannot grow to the largest unsigned integer types.

In the Process also implements N3029 Improved Normal Enumerations and N3030
Enhancements to Enumerations which brings C enums more inline with C++
enums.

Fixes #24667
---
 clang/docs/ReleaseNotes.rst |  8 +
 clang/lib/Sema/SemaDecl.cpp | 65 -
 clang/test/Sema/enum.c  | 43 +---
 clang/test/SemaCXX/enum.cpp |  2 ++
 4 files changed, 97 insertions(+), 21 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 529dd783ab7382..f9a6a3551aa824 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -135,6 +135,12 @@ C23 Feature Support
   ``__TYPE_FMTb__`` (e.g., ``__UINT_FAST64_FMTB__``) in C23 mode for use with
   macros typically exposed from , such as ``PRIb8``.
   (`#81896: `_).
+  - Enumerations should allow values greater than INT_MAX and smaller than
+INT_MIN, in order to provide a value-preserved set of integer constants. 
`N3029 Improved Normal Enumerations 
`_
+
+  - Enumerations should have the ability to specify the underlying type to aid
+in portability and usability across platforms, across ABIs, and across
+languages (for serialization and similar purposes). `N3030 Enhancements to 
Enumerations `_
 
 Non-comprehensive list of changes in this release
 -
@@ -211,6 +217,8 @@ Bug Fixes in This Version
 - Clang now doesn't produce false-positive warning `-Wconstant-logical-operand`
   for logical operators in C23.
   Fixes (`#64356 `_).
+- Fixes miscompilation when an enum has a specified value such that the auto
+  increment overflows a signed long. Fixes (`#24667 
`_)
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 10b5c271f25c10..d9795589fbe5a3 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -19797,6 +19797,19 @@ EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl 
*Enum,
   // - If an initializer is specified for an enumerator, the
   //   initializing value has the same type as the expression.
   EltTy = Val->getType();
+} else if (getLangOpts().C23) {
+  // C23 6.7.2.2p11 b4
+  // int, if given explicitly with = and the value of the
+  // integer constant expression is representable by an int
+  //
+  // C23 6.7.2.2p11 b5
+  // the type of the integer constant expression, if given
+  // explicitly with = and if the value of the integer
+  // constant expression is not representable by int;
+  if (isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) {
+Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
+  }
+  EltTy = Val->getType();
 } else {
   // C99 6.7.2.2p2:
   //   The expression that defines the value of an enumeration constant
@@ -19806,8 +19819,8 @@ EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl 
*Enum,
   // Complain if the value is not representable in an int.
   if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
 Diag(IdLoc, diag::ext_enum_value_not_int)
-  << toString(EnumVal, 10) << Val->getSourceRange()
-  << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
+<< toString(EnumVal, 10) << Val->getSourceRange()
+<< (EnumVal.isUnsigned() || EnumVal.isNonNegative());
   else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
 // Force the type of the expression to 'int'.
 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
@@ -19855,20 +19868,28 @@ EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl 
*Enum,
 //   sufficient to contain the incremented value. If no such type
 //   exists, the program is ill-formed.
 QualType T = getNextLargerIntegralType(Context, EltTy);
-if (T.isNull() || Enum->isFixed()) {
+if (Enum->isFixed()) {
   // There is no integral type larger enough to represent this
   // value. 

[clang] [clang-format] Add AlignConsecutiveTableGenCondOperatorColons option. (PR #82878)

2024-02-25 Thread Hirofumi Nakamura via cfe-commits


@@ -849,7 +851,12 @@ void WhitespaceManager::alignConsecutiveAssignments() {
 }
 
 void WhitespaceManager::alignConsecutiveBitFields() {
-  if (!Style.AlignConsecutiveBitFields.Enabled)
+  alignConsecutiveColons(Style.AlignConsecutiveBitFields, TT_BitFieldColon);
+}
+
+void WhitespaceManager::alignConsecutiveColons(
+const FormatStyle::AlignConsecutiveStyle , TokenType Type) {

hnakamura5 wrote:

Both are OK, but other such functions seems using const reference to pass style.

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


[clang] [DRAFT][analyzer][NFC] clang-format our folders (PR #82599)

2024-02-25 Thread Balazs Benics via cfe-commits

steakhal wrote:

> (In case you do intend to merge changes related to formatting, consider 
> adding the resulting commit hash into the blame-ignore file.)

I dont intend to merge this.

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


[clang] [DRAFT][analyzer][NFC] clang-format our folders (PR #82599)

2024-02-25 Thread via cfe-commits

whisperity wrote:

(In case you do intend to merge changes related to formatting, consider adding 
the resulting commit hash into the blame-ignore file.)

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


[clang] [TBAA] Skip all bitfields when generating !tbaa.struct metadata. (PR #82922)

2024-02-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Florian Hahn (fhahn)


Changes

At the moment, clang generates what I believe are incorrect !tbaa.struct fields 
for named bitfields. At the moment, the base type size is used for named 
bifields (e.g. sizeof(int)) instead of the bifield width per field. This 
results in overalpping fields in !tbaa.struct metadata.

This causes incorrect results when extracting individual copied fields from 
!tbaa.struct as in added in dc85719d5.

This patch fixes that by skipping all bitfields, not only unnamed ones (note 
that CollectFields has a TODO to support bitfields). As bitfields specify their 
widths in bits, while !tbaa metadata uses bytes for sizes and offsets, I don't 
think we would be able to generate correct metadata for them in general.

If this understanding is correct, I can also extend the verifier to check that 
!tbaa.struct fields aren't overlapping.

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

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


2 Files Affected:

- (modified) clang/lib/CodeGen/CodeGenTBAA.cpp (+1-1) 
- (modified) clang/test/CodeGen/tbaa-struct.cpp (+1-1) 


``diff
diff --git a/clang/lib/CodeGen/CodeGenTBAA.cpp 
b/clang/lib/CodeGen/CodeGenTBAA.cpp
index dc288bc3f6157a..43a1aee3d73823 100644
--- a/clang/lib/CodeGen/CodeGenTBAA.cpp
+++ b/clang/lib/CodeGen/CodeGenTBAA.cpp
@@ -298,7 +298,7 @@ CodeGenTBAA::CollectFields(uint64_t BaseOffset,
 unsigned idx = 0;
 for (RecordDecl::field_iterator i = RD->field_begin(),
  e = RD->field_end(); i != e; ++i, ++idx) {
-  if ((*i)->isZeroSize(Context) || (*i)->isUnnamedBitfield())
+  if ((*i)->isZeroSize(Context) || (*i)->isBitField())
 continue;
   uint64_t Offset = BaseOffset +
 Layout.getFieldOffset(idx) / Context.getCharWidth();
diff --git a/clang/test/CodeGen/tbaa-struct.cpp 
b/clang/test/CodeGen/tbaa-struct.cpp
index ff5521fcf3f604..17c9d6bf6a7260 100644
--- a/clang/test/CodeGen/tbaa-struct.cpp
+++ b/clang/test/CodeGen/tbaa-struct.cpp
@@ -130,7 +130,7 @@ void copy8(NamedBitfields *a1, NamedBitfields *a2) {
 // CHECK-OLD: [[TS3]] = !{i64 0, i64 8, !{{.*}}, i64 0, i64 2, !{{.*}}, i64 4, 
i64 8, !{{.*}}}
 // CHECK-OLD: [[TS4]] = !{i64 0, i64 1, [[TAG_CHAR]], i64 1, i64 1, 
[[TAG_CHAR]], i64 2, i64 1, [[TAG_CHAR]]}
 // CHECK-OLD: [[TS5]] = !{i64 0, i64 1, [[TAG_CHAR]], i64 4, i64 1, 
[[TAG_CHAR]], i64 5, i64 1, [[TAG_CHAR]]}
-// CHECK-OLD: [[TS6]] = !{i64 0, i64 4, [[TAG_INT]], i64 1, i64 4, 
[[TAG_INT]], i64 2, i64 1, [[TAG_CHAR]], i64 8, i64 8, [[TAG_DOUBLE:!.+]]}
+// CHECK-OLD: [[TS6]] = !{i64 2, i64 1, [[TAG_CHAR]], i64 8, i64 8, 
[[TAG_DOUBLE:!.+]]}
 // CHECK-OLD: [[TAG_DOUBLE]] = !{[[DOUBLE:!.+]], [[DOUBLE]], i64 0}
 // CHECK-OLD  [[DOUBLE]] = !{!"double", [[CHAR]], i64 0}
 

``




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


[clang] [TBAA] Skip all bitfields when generating !tbaa.struct metadata. (PR #82922)

2024-02-25 Thread Florian Hahn via cfe-commits

https://github.com/fhahn created https://github.com/llvm/llvm-project/pull/82922

At the moment, clang generates what I believe are incorrect !tbaa.struct fields 
for named bitfields. At the moment, the base type size is used for named 
bifields (e.g. sizeof(int)) instead of the bifield width per field. This 
results in overalpping fields in !tbaa.struct metadata.

This causes incorrect results when extracting individual copied fields from 
!tbaa.struct as in added in dc85719d5.

This patch fixes that by skipping all bitfields, not only unnamed ones (note 
that CollectFields has a TODO to support bitfields). As bitfields specify their 
widths in bits, while !tbaa metadata uses bytes for sizes and offsets, I don't 
think we would be able to generate correct metadata for them in general.

If this understanding is correct, I can also extend the verifier to check that 
!tbaa.struct fields aren't overlapping.

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

>From 556fcefed9645aa0a0a965ff8f22d8accdf9eefc Mon Sep 17 00:00:00 2001
From: Florian Hahn 
Date: Sun, 25 Feb 2024 13:23:17 +
Subject: [PATCH] [TBAA] Skip all bitfields when generating !tbaa.struct
 metadata.

At the moment, clang generates what I believe are incorrect !tbaa.struct
fields for named bitfields. At the moment, the base type size is used
for named bifields (e.g. sizeof(int)) instead of the bifield width per
field. This results in overalpping fields in !tbaa.struct metadata.

This causes incorrect results when extracting individual copied fields
from !tbaa.struct as in added in dc85719d5.

This patch fixes that by skipping all bitfields, not only unnamed ones
(note that CollectFields has a TODO to support bitfields). As bitfields
specify their widths in bits, while !tbaa metadata uses bytes for sizes
and offsets, I don't think we would be able to generate correct metadata
for them in general.

If this understanding is correct, I can also extend the verifier to
check that !tbaa.struct fields aren't overlapping.

Fixes https://github.com/llvm/llvm-project/issues/82586
---
 clang/lib/CodeGen/CodeGenTBAA.cpp  | 2 +-
 clang/test/CodeGen/tbaa-struct.cpp | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/lib/CodeGen/CodeGenTBAA.cpp 
b/clang/lib/CodeGen/CodeGenTBAA.cpp
index dc288bc3f6157a..43a1aee3d73823 100644
--- a/clang/lib/CodeGen/CodeGenTBAA.cpp
+++ b/clang/lib/CodeGen/CodeGenTBAA.cpp
@@ -298,7 +298,7 @@ CodeGenTBAA::CollectFields(uint64_t BaseOffset,
 unsigned idx = 0;
 for (RecordDecl::field_iterator i = RD->field_begin(),
  e = RD->field_end(); i != e; ++i, ++idx) {
-  if ((*i)->isZeroSize(Context) || (*i)->isUnnamedBitfield())
+  if ((*i)->isZeroSize(Context) || (*i)->isBitField())
 continue;
   uint64_t Offset = BaseOffset +
 Layout.getFieldOffset(idx) / Context.getCharWidth();
diff --git a/clang/test/CodeGen/tbaa-struct.cpp 
b/clang/test/CodeGen/tbaa-struct.cpp
index ff5521fcf3f604..17c9d6bf6a7260 100644
--- a/clang/test/CodeGen/tbaa-struct.cpp
+++ b/clang/test/CodeGen/tbaa-struct.cpp
@@ -130,7 +130,7 @@ void copy8(NamedBitfields *a1, NamedBitfields *a2) {
 // CHECK-OLD: [[TS3]] = !{i64 0, i64 8, !{{.*}}, i64 0, i64 2, !{{.*}}, i64 4, 
i64 8, !{{.*}}}
 // CHECK-OLD: [[TS4]] = !{i64 0, i64 1, [[TAG_CHAR]], i64 1, i64 1, 
[[TAG_CHAR]], i64 2, i64 1, [[TAG_CHAR]]}
 // CHECK-OLD: [[TS5]] = !{i64 0, i64 1, [[TAG_CHAR]], i64 4, i64 1, 
[[TAG_CHAR]], i64 5, i64 1, [[TAG_CHAR]]}
-// CHECK-OLD: [[TS6]] = !{i64 0, i64 4, [[TAG_INT]], i64 1, i64 4, 
[[TAG_INT]], i64 2, i64 1, [[TAG_CHAR]], i64 8, i64 8, [[TAG_DOUBLE:!.+]]}
+// CHECK-OLD: [[TS6]] = !{i64 2, i64 1, [[TAG_CHAR]], i64 8, i64 8, 
[[TAG_DOUBLE:!.+]]}
 // CHECK-OLD: [[TAG_DOUBLE]] = !{[[DOUBLE:!.+]], [[DOUBLE]], i64 0}
 // CHECK-OLD  [[DOUBLE]] = !{!"double", [[CHAR]], i64 0}
 

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


[clang] [llvm] [openmp] [PGO][OpenMP] Instrumentation for GPU devices (PR #76587)

2024-02-25 Thread Matt Arsenault via cfe-commits


@@ -2067,6 +2067,10 @@ Constant *ConstantExpr::getBitCast(Constant *C, Type 
*DstTy,
 
 Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
  bool OnlyIfReduced) {
+  // Skip cast if types are identical

arsenm wrote:

I guess leave this as it was. The addrspacecast helpers are a mess, we should 
clear out the vestiges of opaque pointers. The cast build helpers should accept 
same same address space and elide the cast, like the other cases. Any changes 
there should be a separate change 

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


[clang] 7110147 - [TBAA] Test for tbaa.struct creation for struct with named bitfields.

2024-02-25 Thread Florian Hahn via cfe-commits

Author: Florian Hahn
Date: 2024-02-25T13:17:08Z
New Revision: 711014714716753f791291ed6a152e00899469a3

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

LOG: [TBAA] Test for tbaa.struct creation for struct with named bitfields.

Add test for tbaa.struct metadata creation for copies of a struct with
named bitfields.

Test for https://github.com/llvm/llvm-project/issues/82586.

Added: 


Modified: 
clang/test/CodeGen/tbaa-struct.cpp

Removed: 




diff  --git a/clang/test/CodeGen/tbaa-struct.cpp 
b/clang/test/CodeGen/tbaa-struct.cpp
index 47ccec3fb4162a..ff5521fcf3f604 100644
--- a/clang/test/CodeGen/tbaa-struct.cpp
+++ b/clang/test/CodeGen/tbaa-struct.cpp
@@ -102,6 +102,23 @@ void copy7(A *a1, AA *a2) {
   *a1 = *a2;
 }
 
+struct NamedBitfields {
+   signed f0 : 9;
+   unsigned f1 : 2;
+   char f2;
+   double f3;
+};
+
+NamedBitfields g;
+
+void copy8(NamedBitfields *a1, NamedBitfields *a2) {
+// CHECK-LABEL: _Z5copy8P14NamedBitfieldsS0_
+// CHECK:   tail call void @llvm.memcpy.p0.p0.i64(ptr noundef nonnull align 8 
dereferenceable(16) %a1, ptr noundef nonnull align 8 dereferenceable(16) %a2, 
i64 16, i1 false),
+// CHECK-OLD-SAME: !tbaa.struct [[TS6:!.*]]
+// CHECK-NEW-SAME: !tbaa [[TAG_NamedBitfields:!.+]], !tbaa.struct
+  *a1 = *a2;
+}
+
 // CHECK-OLD: [[TS]] = !{i64 0, i64 2, !{{.*}}, i64 4, i64 4, !{{.*}}, i64 8, 
i64 1, !{{.*}}, i64 12, i64 4, !{{.*}}}
 // CHECK-OLD: [[CHAR:!.*]] = !{!"omnipotent char", !{{.*}}}
 // CHECK-OLD: [[TAG_INT:!.*]] = !{[[INT:!.*]], [[INT]], i64 0}
@@ -113,6 +130,9 @@ void copy7(A *a1, AA *a2) {
 // CHECK-OLD: [[TS3]] = !{i64 0, i64 8, !{{.*}}, i64 0, i64 2, !{{.*}}, i64 4, 
i64 8, !{{.*}}}
 // CHECK-OLD: [[TS4]] = !{i64 0, i64 1, [[TAG_CHAR]], i64 1, i64 1, 
[[TAG_CHAR]], i64 2, i64 1, [[TAG_CHAR]]}
 // CHECK-OLD: [[TS5]] = !{i64 0, i64 1, [[TAG_CHAR]], i64 4, i64 1, 
[[TAG_CHAR]], i64 5, i64 1, [[TAG_CHAR]]}
+// CHECK-OLD: [[TS6]] = !{i64 0, i64 4, [[TAG_INT]], i64 1, i64 4, 
[[TAG_INT]], i64 2, i64 1, [[TAG_CHAR]], i64 8, i64 8, [[TAG_DOUBLE:!.+]]}
+// CHECK-OLD: [[TAG_DOUBLE]] = !{[[DOUBLE:!.+]], [[DOUBLE]], i64 0}
+// CHECK-OLD  [[DOUBLE]] = !{!"double", [[CHAR]], i64 0}
 
 // CHECK-NEW-DAG: [[TYPE_char:!.*]] = !{{{.*}}, i64 1, !"omnipotent char"}
 // CHECK-NEW-DAG: [[TAG_char]] = !{[[TYPE_char]], [[TYPE_char]], i64 0, i64 0}
@@ -127,3 +147,6 @@ void copy7(A *a1, AA *a2) {
 // CHECK-NEW-DAG: [[TAG_C]] = !{[[TYPE_C]], [[TYPE_C]], i64 0, i64 3}
 // CHECK-NEW-DAG: [[TYPE_D:!.*]] = !{[[TYPE_char]], i64 6, !"_ZTS1D", 
[[TYPE_char]], i64 0, i64 1, [[TYPE_char]], i64 4, i64 1, [[TYPE_char]], i64 5, 
i64 1}
 // CHECK-NEW-DAG: [[TAG_D]] = !{[[TYPE_D]], [[TYPE_D]], i64 0, i64 6}
+// CHECK-NEW-DAG: [[TAG_NamedBitfields]] = !{[[TYPE_NamedBitfields:!.+]], 
[[TYPE_NamedBitfields]], i64 0, i64 16}
+// CHECK-NEW-DAG: [[TYPE_NamedBitfields]] = !{[[TYPE_char]], i64 16, 
!"_ZTS14NamedBitfields", [[TYPE_int]], i64 0, i64 4, [[TYPE_int]], i64 1, i64 
4, [[TYPE_char]], i64 2, i64 1, [[TYPE_double:!.+]], i64 8, i64 8}
+// CHECK-NEW-DAG: [[TYPE_double]] = !{[[TYPE_char]], i64 8, !"double"}



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


[clang] [DRAFT][analyzer][NFC] clang-format our folders (PR #82599)

2024-02-25 Thread Balazs Benics via cfe-commits

steakhal wrote:

I've submitted PRs to resolve the pending formatting issues.

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


[clang] [clang][analyzer][NFC] Prepare for clang-format (PR #82921)

2024-02-25 Thread via cfe-commits

llvmbot wrote:




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

Author: Balazs Benics (steakhal)


Changes

This is the followup PR for #82599 to fix the cases where clang-format 
would regress the flow of the code.

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


13 Files Affected:

- (modified) clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h (+8-4) 
- (modified) clang/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h (+2) 
- (modified) clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
(+4-5) 
- (modified) clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h 
(+1-1) 
- (modified) 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h 
(+1-1) 
- (modified) clang/lib/Analysis/PathDiagnostic.cpp (+1-2) 
- (modified) clang/lib/Analysis/ThreadSafetyCommon.cpp (+2) 
- (modified) clang/lib/Analysis/ThreadSafetyTIL.cpp (+2) 
- (modified) clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp 
(+4-1) 
- (modified) clang/lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp (+9-11) 
- (modified) clang/lib/StaticAnalyzer/Checkers/CheckerDocumentation.cpp 
(+26-24) 
- (modified) clang/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp 
(+2) 
- (modified) clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp (+2) 


``diff
diff --git a/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h 
b/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
index 65dd66ee093fe4..7d26d7439b8830 100644
--- a/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
+++ b/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
@@ -128,6 +128,7 @@ enum TIL_CastOpcode : unsigned char {
   CAST_objToPtr
 };
 
+// clang-format off
 const TIL_Opcode   COP_Min  = COP_Future;
 const TIL_Opcode   COP_Max  = COP_Branch;
 const TIL_UnaryOpcode  UOP_Min  = UOP_Minus;
@@ -136,6 +137,7 @@ const TIL_BinaryOpcode BOP_Min  = BOP_Add;
 const TIL_BinaryOpcode BOP_Max  = BOP_LogicOr;
 const TIL_CastOpcode   CAST_Min = CAST_none;
 const TIL_CastOpcode   CAST_Max = CAST_toInt;
+// clang-format on
 
 /// Return the name of a unary opcode.
 StringRef getUnaryOpcodeString(TIL_UnaryOpcode Op);
@@ -188,12 +190,14 @@ struct ValueType {
 
 inline ValueType::SizeType ValueType::getSizeType(unsigned nbytes) {
   switch (nbytes) {
-case 1: return ST_8;
-case 2: return ST_16;
-case 4: return ST_32;
-case 8: return ST_64;
+// clang-format off
+case  1: return ST_8;
+case  2: return ST_16;
+case  4: return ST_32;
+case  8: return ST_64;
 case 16: return ST_128;
 default: return ST_0;
+// clang-format on
   }
 }
 
diff --git a/clang/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h 
b/clang/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h
index 6fc55130655a29..e4545106915b25 100644
--- a/clang/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h
+++ b/clang/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h
@@ -440,6 +440,7 @@ class PrettyPrinter {
 
   // Return the precedence of a given node, for use in pretty printing.
   unsigned precedence(const SExpr *E) {
+// clang-format off
 switch (E->opcode()) {
   case COP_Future: return Prec_Atom;
   case COP_Undefined:  return Prec_Atom;
@@ -479,6 +480,7 @@ class PrettyPrinter {
   case COP_IfThenElse: return Prec_Other;
   case COP_Let:return Prec_Decl;
 }
+// clang-format on
 return Prec_MAX;
   }
 
diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
index ed5c4adb5e3d56..8c28f4c3a61217 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -393,8 +393,8 @@ class ExprEngine {
   ProgramStateRef processAssume(ProgramStateRef state, SVal cond,
 bool assumption);
 
-  /// processRegionChanges - Called by ProgramStateManager whenever a change 
is made
-  ///  to the store. Used to update checkers that track region values.
+  /// It's called by ProgramStateManager whenever a change is made to the 
store.
+  /// Used to update checkers that track region values.
   ProgramStateRef
   processRegionChanges(ProgramStateRef state,
const InvalidatedSymbols *invalidated,
@@ -587,9 +587,8 @@ class ExprEngine {
 ExplodedNode *Pred,
 ExplodedNodeSet );
 
-  /// evalEagerlyAssumeBinOpBifurcation - Given the nodes in 'Src', eagerly 
assume symbolic
-  ///  expressions of the form 'x != 0' and generate new nodes (stored in Dst)
-  ///  with those assumptions.
+  /// Given the nodes in \p Src, eagerly assume symbolic expressions of the 
form
+  /// `x != 0` and generate new nodes (stored in \p Dst) with those 
assumptions.
   void evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet , ExplodedNodeSet 
,
 

[clang] [clang][analyzer][NFC] Prepare for clang-format (PR #82921)

2024-02-25 Thread Balazs Benics via cfe-commits

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

This is the followup PR for #82599 to fix the cases where clang-format would 
regress the flow of the code.

>From 245de9ea5c33649ff7b3e359cd360361d4dc5ae3 Mon Sep 17 00:00:00 2001
From: Balazs Benics 
Date: Sun, 25 Feb 2024 12:38:28 +0100
Subject: [PATCH] [clang][analyzer][NFC] Prepare for clang-format

---
 .../clang/Analysis/Analyses/ThreadSafetyTIL.h | 12 +++--
 .../Analysis/Analyses/ThreadSafetyTraverse.h  |  2 +
 .../Core/PathSensitive/ExprEngine.h   |  9 ++--
 .../Core/PathSensitive/MemRegion.h|  2 +-
 .../Core/PathSensitive/ProgramStateTrait.h|  2 +-
 clang/lib/Analysis/PathDiagnostic.cpp |  3 +-
 clang/lib/Analysis/ThreadSafetyCommon.cpp |  2 +
 clang/lib/Analysis/ThreadSafetyTIL.cpp|  2 +
 .../Checkers/BasicObjCFoundationChecks.cpp|  5 +-
 .../Checkers/CStringSyntaxChecker.cpp | 20 
 .../Checkers/CheckerDocumentation.cpp | 50 ++-
 .../Checkers/ObjCAutoreleaseWriteChecker.cpp  |  2 +
 clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp |  2 +
 13 files changed, 64 insertions(+), 49 deletions(-)

diff --git a/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h 
b/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
index 65dd66ee093fe4..7d26d7439b8830 100644
--- a/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
+++ b/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
@@ -128,6 +128,7 @@ enum TIL_CastOpcode : unsigned char {
   CAST_objToPtr
 };
 
+// clang-format off
 const TIL_Opcode   COP_Min  = COP_Future;
 const TIL_Opcode   COP_Max  = COP_Branch;
 const TIL_UnaryOpcode  UOP_Min  = UOP_Minus;
@@ -136,6 +137,7 @@ const TIL_BinaryOpcode BOP_Min  = BOP_Add;
 const TIL_BinaryOpcode BOP_Max  = BOP_LogicOr;
 const TIL_CastOpcode   CAST_Min = CAST_none;
 const TIL_CastOpcode   CAST_Max = CAST_toInt;
+// clang-format on
 
 /// Return the name of a unary opcode.
 StringRef getUnaryOpcodeString(TIL_UnaryOpcode Op);
@@ -188,12 +190,14 @@ struct ValueType {
 
 inline ValueType::SizeType ValueType::getSizeType(unsigned nbytes) {
   switch (nbytes) {
-case 1: return ST_8;
-case 2: return ST_16;
-case 4: return ST_32;
-case 8: return ST_64;
+// clang-format off
+case  1: return ST_8;
+case  2: return ST_16;
+case  4: return ST_32;
+case  8: return ST_64;
 case 16: return ST_128;
 default: return ST_0;
+// clang-format on
   }
 }
 
diff --git a/clang/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h 
b/clang/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h
index 6fc55130655a29..e4545106915b25 100644
--- a/clang/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h
+++ b/clang/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h
@@ -440,6 +440,7 @@ class PrettyPrinter {
 
   // Return the precedence of a given node, for use in pretty printing.
   unsigned precedence(const SExpr *E) {
+// clang-format off
 switch (E->opcode()) {
   case COP_Future: return Prec_Atom;
   case COP_Undefined:  return Prec_Atom;
@@ -479,6 +480,7 @@ class PrettyPrinter {
   case COP_IfThenElse: return Prec_Other;
   case COP_Let:return Prec_Decl;
 }
+// clang-format on
 return Prec_MAX;
   }
 
diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
index ed5c4adb5e3d56..8c28f4c3a61217 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -393,8 +393,8 @@ class ExprEngine {
   ProgramStateRef processAssume(ProgramStateRef state, SVal cond,
 bool assumption);
 
-  /// processRegionChanges - Called by ProgramStateManager whenever a change 
is made
-  ///  to the store. Used to update checkers that track region values.
+  /// It's called by ProgramStateManager whenever a change is made to the 
store.
+  /// Used to update checkers that track region values.
   ProgramStateRef
   processRegionChanges(ProgramStateRef state,
const InvalidatedSymbols *invalidated,
@@ -587,9 +587,8 @@ class ExprEngine {
 ExplodedNode *Pred,
 ExplodedNodeSet );
 
-  /// evalEagerlyAssumeBinOpBifurcation - Given the nodes in 'Src', eagerly 
assume symbolic
-  ///  expressions of the form 'x != 0' and generate new nodes (stored in Dst)
-  ///  with those assumptions.
+  /// Given the nodes in \p Src, eagerly assume symbolic expressions of the 
form
+  /// `x != 0` and generate new nodes (stored in \p Dst) with those 
assumptions.
   void evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet , ExplodedNodeSet 
,
  const Expr *Ex);
 
diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h 

[clang] [clang][NFC] Prefer usings over typedefs (PR #82920)

2024-02-25 Thread via cfe-commits

llvmbot wrote:




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

Author: Balazs Benics (steakhal)


Changes



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


1 Files Affected:

- (modified) clang/include/clang/Analysis/FlowSensitive/DataflowValues.h (+6-6) 


``diff
diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h
index 2248bcdf3a512f..8e88f9c4d9c2df 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h
@@ -45,12 +45,12 @@ class DataflowValues {
   
//======//
 
 public:
-  typedef typename ValueTypes::ValTy   ValTy;
-  typedef typename ValueTypes::AnalysisDataTy  AnalysisDataTy;
-  typedef _AnalysisDirTag  AnalysisDirTag;
-  typedef llvm::DenseMap  EdgeDataMapTy;
-  typedef llvm::DenseMap   BlockDataMapTy;
-  typedef llvm::DenseMap   StmtDataMapTy;
+  using ValTy = typename ValueTypes::ValTy;
+  using AnalysisDataTy = typename ValueTypes::AnalysisDataTy;
+  using AnalysisDirTag = _AnalysisDirTag;
+  using EdgeDataMapTy = llvm::DenseMap;
+  using BlockDataMapTy = llvm::DenseMap;
+  using StmtDataMapTy = llvm::DenseMap;
 
   
//======//
   // Predicates.

``




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


[clang] [clang][NFC] Prefer usings over typedefs (PR #82920)

2024-02-25 Thread Balazs Benics via cfe-commits

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

None

>From fd85686af33570f0baf8ba60a0b0b8113e999c4a Mon Sep 17 00:00:00 2001
From: Balazs Benics 
Date: Sun, 25 Feb 2024 12:37:49 +0100
Subject: [PATCH] [clang][NFC] Prefer usings over typedefs

---
 .../clang/Analysis/FlowSensitive/DataflowValues.h| 12 ++--
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h
index 2248bcdf3a512f..8e88f9c4d9c2df 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h
@@ -45,12 +45,12 @@ class DataflowValues {
   
//======//
 
 public:
-  typedef typename ValueTypes::ValTy   ValTy;
-  typedef typename ValueTypes::AnalysisDataTy  AnalysisDataTy;
-  typedef _AnalysisDirTag  AnalysisDirTag;
-  typedef llvm::DenseMap  EdgeDataMapTy;
-  typedef llvm::DenseMap   BlockDataMapTy;
-  typedef llvm::DenseMap   StmtDataMapTy;
+  using ValTy = typename ValueTypes::ValTy;
+  using AnalysisDataTy = typename ValueTypes::AnalysisDataTy;
+  using AnalysisDirTag = _AnalysisDirTag;
+  using EdgeDataMapTy = llvm::DenseMap;
+  using BlockDataMapTy = llvm::DenseMap;
+  using StmtDataMapTy = llvm::DenseMap;
 
   
//======//
   // Predicates.

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


[clang] [clang][NFC] Trim license header comments to 81 characters (PR #82919)

2024-02-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Balazs Benics (steakhal)


Changes

clang-format would format these headers poorly by splitting it into multiple 
lines.

```regex
//=.{78,}
```

---

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


36 Files Affected:

- (modified) clang/include/clang/AST/DeclOpenMP.h (+1-1) 
- (modified) clang/include/clang/AST/ParentMapContext.h (+1-1) 
- (modified) clang/include/clang/Basic/OpenCLExtensionTypes.def (+1-1) 
- (modified) clang/include/clang/Basic/RISCVVTypes.def (+4-4) 
- (modified) clang/include/clang/Basic/arm_neon_incl.td (+1-1) 
- (modified) clang/include/clang/Serialization/PCHContainerOperations.h (+1-1) 
- (modified) clang/include/clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h 
(+1-1) 
- (modified) clang/lib/ARCMigrate/TransGCAttrs.cpp (+1-1) 
- (modified) clang/lib/AST/Interp/ByteCodeEmitter.h (+1-1) 
- (modified) clang/lib/AST/Interp/FunctionPointer.h (+1-1) 
- (modified) clang/lib/AST/Interp/PrimType.h (+1-1) 
- (modified) clang/lib/Driver/ToolChains/Arch/Mips.h (+1-1) 
- (modified) clang/lib/Driver/ToolChains/Arch/Sparc.h (+1-1) 
- (modified) clang/lib/Headers/llvm_libc_wrappers/assert.h (+1-1) 
- (modified) clang/lib/Sema/AnalysisBasedWarnings.cpp (+1-1) 
- (modified) clang/lib/Sema/SemaChecking.cpp (+1-1) 
- (modified) clang/lib/StaticAnalyzer/Checkers/DirectIvarAssignment.cpp (+1-1) 
- (modified) clang/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp 
(+1-1) 
- (modified) clang/lib/StaticAnalyzer/Checkers/STLAlgorithmModeling.cpp (+1-1) 
- (modified) clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp (+1-1) 
- (modified) clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp (+1-1) 
- (modified) clang/lib/Tooling/Refactoring/AtomicChange.cpp (+1-1) 
- (modified) clang/test/Analysis/misc-ps-region-store.mm (+2-2) 
- (modified) clang/test/Rewriter/rewrite-modern-class.mm (+1-1) 
- (modified) clang/tools/clang-fuzzer/proto-to-llvm/loop_proto_to_llvm.h (+1-1) 
- (modified) clang/tools/diagtool/DiagTool.cpp (+1-1) 
- (modified) clang/unittests/AST/ASTImporterODRStrategiesTest.cpp (+1-1) 
- (modified) clang/unittests/ASTMatchers/Dynamic/RegistryTest.cpp (+2-2) 
- (modified) clang/unittests/ASTMatchers/Dynamic/VariantValueTest.cpp (+2-2) 
- (modified) 
clang/unittests/Tooling/RecursiveASTVisitorTests/CXXOperatorCallExprTraverser.cpp
 (+1-1) 
- (modified) 
clang/unittests/Tooling/RecursiveASTVisitorTests/CallbacksBinaryOperator.cpp 
(+2-2) 
- (modified) 
clang/unittests/Tooling/RecursiveASTVisitorTests/CallbacksCompoundAssignOperator.cpp
 (+1-1) 
- (modified) 
clang/unittests/Tooling/RecursiveASTVisitorTests/CallbacksUnaryOperator.cpp 
(+2-2) 
- (modified) 
clang/unittests/Tooling/RecursiveASTVisitorTests/InitListExprPostOrderNoQueue.cpp
 (+1-1) 
- (modified) 
clang/unittests/Tooling/RecursiveASTVisitorTests/InitListExprPreOrderNoQueue.cpp
 (+1-1) 
- (modified) 
clang/unittests/Tooling/RecursiveASTVisitorTests/TemplateArgumentLocTraverser.cpp
 (+1-1) 


``diff
diff --git a/clang/include/clang/AST/DeclOpenMP.h 
b/clang/include/clang/AST/DeclOpenMP.h
index 73725e6e85666a..8fdfddb6c1fd74 100644
--- a/clang/include/clang/AST/DeclOpenMP.h
+++ b/clang/include/clang/AST/DeclOpenMP.h
@@ -1,4 +1,4 @@
-//===- DeclOpenMP.h - Classes for representing OpenMP directives -*- C++ 
-*-===//
+//===- DeclOpenMP.h - Classes for representing OpenMP directives -*- C++ 
-*-==//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
diff --git a/clang/include/clang/AST/ParentMapContext.h 
b/clang/include/clang/AST/ParentMapContext.h
index d3b2e3986a9935..6f79038627d9e1 100644
--- a/clang/include/clang/AST/ParentMapContext.h
+++ b/clang/include/clang/AST/ParentMapContext.h
@@ -1,4 +1,4 @@
-//===- ParentMapContext.h - Map of parents using DynTypedNode ---*- C++ 
-*-===//
+//===- ParentMapContext.h - Map of parents using DynTypedNode ---*- C++ 
-*-===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
diff --git a/clang/include/clang/Basic/OpenCLExtensionTypes.def 
b/clang/include/clang/Basic/OpenCLExtensionTypes.def
index 17c72d69a02065..50ea826c18a77c 100644
--- a/clang/include/clang/Basic/OpenCLExtensionTypes.def
+++ b/clang/include/clang/Basic/OpenCLExtensionTypes.def
@@ -1,4 +1,4 @@
-//===-- OpenCLExtensionTypes.def - Metadata about BuiltinTypes --*- C++ 
-*-===//
+//===-- OpenCLExtensionTypes.def - Metadata about BuiltinTypes --*- C++ 
-*-===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
diff --git a/clang/include/clang/Basic/RISCVVTypes.def 
b/clang/include/clang/Basic/RISCVVTypes.def
index 6620de8ad50e01..ccb8cb39068e2b 100644
--- 

[clang] [clang][NFC] Trim license header comments to 81 characters (PR #82919)

2024-02-25 Thread Balazs Benics via cfe-commits

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

clang-format would format these headers poorly by splitting it into multiple 
lines.

```regex
//=.{78,}
```

>From 319329630e0d2a86b22dd435985026ea236f8e56 Mon Sep 17 00:00:00 2001
From: Balazs Benics 
Date: Sun, 25 Feb 2024 12:48:06 +0100
Subject: [PATCH] [clang][NFC] Trim license header comments to 81 characters

clang-format would format these headers poorly by splitting it into
multiple lines.

```regex
//=.{78,}
```
---
 clang/include/clang/AST/DeclOpenMP.h  | 2 +-
 clang/include/clang/AST/ParentMapContext.h| 2 +-
 clang/include/clang/Basic/OpenCLExtensionTypes.def| 2 +-
 clang/include/clang/Basic/RISCVVTypes.def | 8 
 clang/include/clang/Basic/arm_neon_incl.td| 2 +-
 .../include/clang/Serialization/PCHContainerOperations.h  | 2 +-
 .../clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h   | 2 +-
 clang/lib/ARCMigrate/TransGCAttrs.cpp | 2 +-
 clang/lib/AST/Interp/ByteCodeEmitter.h| 2 +-
 clang/lib/AST/Interp/FunctionPointer.h| 2 +-
 clang/lib/AST/Interp/PrimType.h   | 2 +-
 clang/lib/Driver/ToolChains/Arch/Mips.h   | 2 +-
 clang/lib/Driver/ToolChains/Arch/Sparc.h  | 2 +-
 clang/lib/Headers/llvm_libc_wrappers/assert.h | 2 +-
 clang/lib/Sema/AnalysisBasedWarnings.cpp  | 2 +-
 clang/lib/Sema/SemaChecking.cpp   | 2 +-
 .../lib/StaticAnalyzer/Checkers/DirectIvarAssignment.cpp  | 2 +-
 .../Checkers/ObjCAutoreleaseWriteChecker.cpp  | 2 +-
 .../lib/StaticAnalyzer/Checkers/STLAlgorithmModeling.cpp  | 2 +-
 clang/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp | 2 +-
 clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp  | 2 +-
 clang/lib/Tooling/Refactoring/AtomicChange.cpp| 2 +-
 clang/test/Analysis/misc-ps-region-store.mm   | 4 ++--
 clang/test/Rewriter/rewrite-modern-class.mm   | 2 +-
 .../tools/clang-fuzzer/proto-to-llvm/loop_proto_to_llvm.h | 2 +-
 clang/tools/diagtool/DiagTool.cpp | 2 +-
 clang/unittests/AST/ASTImporterODRStrategiesTest.cpp  | 2 +-
 clang/unittests/ASTMatchers/Dynamic/RegistryTest.cpp  | 4 ++--
 clang/unittests/ASTMatchers/Dynamic/VariantValueTest.cpp  | 4 ++--
 .../CXXOperatorCallExprTraverser.cpp  | 2 +-
 .../RecursiveASTVisitorTests/CallbacksBinaryOperator.cpp  | 4 ++--
 .../CallbacksCompoundAssignOperator.cpp   | 2 +-
 .../RecursiveASTVisitorTests/CallbacksUnaryOperator.cpp   | 4 ++--
 .../InitListExprPostOrderNoQueue.cpp  | 2 +-
 .../InitListExprPreOrderNoQueue.cpp   | 2 +-
 .../TemplateArgumentLocTraverser.cpp  | 2 +-
 36 files changed, 44 insertions(+), 44 deletions(-)

diff --git a/clang/include/clang/AST/DeclOpenMP.h 
b/clang/include/clang/AST/DeclOpenMP.h
index 73725e6e85666a..8fdfddb6c1fd74 100644
--- a/clang/include/clang/AST/DeclOpenMP.h
+++ b/clang/include/clang/AST/DeclOpenMP.h
@@ -1,4 +1,4 @@
-//===- DeclOpenMP.h - Classes for representing OpenMP directives -*- C++ 
-*-===//
+//===- DeclOpenMP.h - Classes for representing OpenMP directives -*- C++ 
-*-==//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
diff --git a/clang/include/clang/AST/ParentMapContext.h 
b/clang/include/clang/AST/ParentMapContext.h
index d3b2e3986a9935..6f79038627d9e1 100644
--- a/clang/include/clang/AST/ParentMapContext.h
+++ b/clang/include/clang/AST/ParentMapContext.h
@@ -1,4 +1,4 @@
-//===- ParentMapContext.h - Map of parents using DynTypedNode ---*- C++ 
-*-===//
+//===- ParentMapContext.h - Map of parents using DynTypedNode ---*- C++ 
-*-===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
diff --git a/clang/include/clang/Basic/OpenCLExtensionTypes.def 
b/clang/include/clang/Basic/OpenCLExtensionTypes.def
index 17c72d69a02065..50ea826c18a77c 100644
--- a/clang/include/clang/Basic/OpenCLExtensionTypes.def
+++ b/clang/include/clang/Basic/OpenCLExtensionTypes.def
@@ -1,4 +1,4 @@
-//===-- OpenCLExtensionTypes.def - Metadata about BuiltinTypes --*- C++ 
-*-===//
+//===-- OpenCLExtensionTypes.def - Metadata about BuiltinTypes --*- C++ 
-*-===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
diff --git a/clang/include/clang/Basic/RISCVVTypes.def 
b/clang/include/clang/Basic/RISCVVTypes.def
index 6620de8ad50e01..ccb8cb39068e2b 100644
--- a/clang/include/clang/Basic/RISCVVTypes.def
+++ b/clang/include/clang/Basic/RISCVVTypes.def
@@ -383,7 +383,7 @@ 

[clang] [clang] Clang should detect illegal copy constructor with template class as its parameter (PR #81251)

2024-02-25 Thread Rajveer Singh Bharadwaj via cfe-commits

https://github.com/Rajveer100 updated 
https://github.com/llvm/llvm-project/pull/81251

>From bf51e9dfb160ec32b3f3a7d052c1da24f06a Mon Sep 17 00:00:00 2001
From: Rajveer 
Date: Fri, 9 Feb 2024 19:20:39 +0530
Subject: [PATCH] [clang] Clang should detect illegal copy constructor with
 template class as its parameter

Resolves #80963
---
 clang/docs/ReleaseNotes.rst|  2 ++
 clang/lib/Sema/SemaDeclCXX.cpp |  4 +---
 clang/test/SemaCXX/GH81251.cpp | 17 +
 3 files changed, 20 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/SemaCXX/GH81251.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 529dd783ab7382..d30e13b0b1b62c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -281,6 +281,8 @@ Bug Fixes to C++ Support
   a requires-clause lie at the same depth as those of the surrounding lambda. 
This,
   in turn, results in the wrong template argument substitution during 
constraint checking.
   (`#78524 `_)
+- Clang now detects illegal copy constructor with template class as its 
parameter.
+  Fixes (`#80963 https://github.com/llvm/llvm-project/issues/80963>`_)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 7c009d9c8ec093..622bf0c258f138 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -10921,9 +10921,7 @@ void Sema::CheckConstructor(CXXConstructorDecl 
*Constructor) {
   //   either there are no other parameters or else all other
   //   parameters have default arguments.
   if (!Constructor->isInvalidDecl() &&
-  Constructor->hasOneParamOrDefaultArgs() &&
-  Constructor->getTemplateSpecializationKind() !=
-  TSK_ImplicitInstantiation) {
+  Constructor->hasOneParamOrDefaultArgs()) {
 QualType ParamType = Constructor->getParamDecl(0)->getType();
 QualType ClassTy = Context.getTagDeclType(ClassDecl);
 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
diff --git a/clang/test/SemaCXX/GH81251.cpp b/clang/test/SemaCXX/GH81251.cpp
new file mode 100644
index 00..a3e0ba07728dcc
--- /dev/null
+++ b/clang/test/SemaCXX/GH81251.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+template < class T, class V > struct A
+{
+A ();
+A (A &);
+A (A < V,T >);
+// expected-error@-1 {{copy constructor must pass its first argument by 
reference}}
+};
+
+void f ()
+{
+A  (A < int, int >());
+// expected-note@-1 {{in instantiation of template class 'A' 
requested here}}
+
+A  (A < int, double >());
+}

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


[clang] [clang] Clang should detect illegal copy constructor with template class as its parameter (PR #81251)

2024-02-25 Thread Rajveer Singh Bharadwaj via cfe-commits

https://github.com/Rajveer100 updated 
https://github.com/llvm/llvm-project/pull/81251

>From 4bb6d4d1b5a813bc3a60c1bc6aab97ea863bd261 Mon Sep 17 00:00:00 2001
From: Rajveer 
Date: Fri, 9 Feb 2024 19:20:39 +0530
Subject: [PATCH] [clang] Clang should detect illegal copy constructor with
 template class as its parameter

Resolves #80963
---
 clang/docs/ReleaseNotes.rst|  2 ++
 clang/lib/Sema/SemaDeclCXX.cpp |  4 +---
 clang/test/SemaCXX/GH81251.cpp | 17 +
 3 files changed, 20 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/SemaCXX/GH81251.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 529dd783ab7382..4c46c9bae78313 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -281,6 +281,8 @@ Bug Fixes to C++ Support
   a requires-clause lie at the same depth as those of the surrounding lambda. 
This,
   in turn, results in the wrong template argument substitution during 
constraint checking.
   (`#78524 `_)
+- Clang now detects illegal copy constructor with template class as its 
parameter.
+  Fixes (`#80963 https://github.com/llvm/llvm-project/issues/80963`_)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 7c009d9c8ec093..622bf0c258f138 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -10921,9 +10921,7 @@ void Sema::CheckConstructor(CXXConstructorDecl 
*Constructor) {
   //   either there are no other parameters or else all other
   //   parameters have default arguments.
   if (!Constructor->isInvalidDecl() &&
-  Constructor->hasOneParamOrDefaultArgs() &&
-  Constructor->getTemplateSpecializationKind() !=
-  TSK_ImplicitInstantiation) {
+  Constructor->hasOneParamOrDefaultArgs()) {
 QualType ParamType = Constructor->getParamDecl(0)->getType();
 QualType ClassTy = Context.getTagDeclType(ClassDecl);
 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
diff --git a/clang/test/SemaCXX/GH81251.cpp b/clang/test/SemaCXX/GH81251.cpp
new file mode 100644
index 00..a3e0ba07728dcc
--- /dev/null
+++ b/clang/test/SemaCXX/GH81251.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+template < class T, class V > struct A
+{
+A ();
+A (A &);
+A (A < V,T >);
+// expected-error@-1 {{copy constructor must pass its first argument by 
reference}}
+};
+
+void f ()
+{
+A  (A < int, int >());
+// expected-note@-1 {{in instantiation of template class 'A' 
requested here}}
+
+A  (A < int, double >());
+}

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


[clang] [DRAFT][analyzer][NFC] clang-format our folders (PR #82599)

2024-02-25 Thread Balazs Benics via cfe-commits


@@ -33,30 +33,17 @@ namespace ento {
 /// checking.
 ///
 /// \sa CheckerContext
-class CheckerDocumentation : public Checker< check::PreStmt,
-   check::PostStmt,
-   check::PreObjCMessage,
-   check::PostObjCMessage,
-   check::ObjCMessageNil,
-   check::PreCall,
-   check::PostCall,
-   check::BranchCondition,
-   check::NewAllocator,
-   check::Location,
-   check::Bind,
-   check::DeadSymbols,
-   check::BeginFunction,
-   check::EndFunction,
-   check::EndAnalysis,
-   check::EndOfTranslationUnit,
-   eval::Call,
-   eval::Assume,
-   check::LiveSymbols,
-   check::RegionChanges,
-   check::PointerEscape,
-   check::ConstPointerEscape,
-   check::Event,
-   check::ASTDecl > {
+class CheckerDocumentation
+: public Checker<
+  check::PreStmt, check::PostStmt,
+  check::PreObjCMessage, check::PostObjCMessage, check::ObjCMessageNil,
+  check::PreCall, check::PostCall, check::BranchCondition,
+  check::NewAllocator, check::Location, check::Bind, 
check::DeadSymbols,
+  check::BeginFunction, check::EndFunction, check::EndAnalysis,
+  check::EndOfTranslationUnit, eval::Call, eval::Assume,
+  check::LiveSymbols, check::RegionChanges, check::PointerEscape,
+  check::ConstPointerEscape, check::Event,
+  check::ASTDecl> {

steakhal wrote:

I was thinking of something like this:
```c++
class CheckerDocumentation : public Checker<   //
 check::PreStmt,   //
 check::PostStmt,//
 check::PreObjCMessage,//
 check::PostObjCMessage,   //
 check::ObjCMessageNil,//
 check::PreCall,   //
 check::PostCall,  //
 check::BranchCondition,   //
 check::NewAllocator,  //
 check::Location,  //
 check::Bind,  //
 check::DeadSymbols,   //
 check::BeginFunction, //
 check::EndFunction,   //
 check::EndAnalysis,   //
 check::EndOfTranslationUnit,  //
 eval::Call,   //
 eval::Assume, //
 check::LiveSymbols,   //
 check::RegionChanges, //
 check::PointerEscape, //
 check::ConstPointerEscape,//
 check::Event, //
 check::ASTDecl  //
 > {
```

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


[clang] [clang] Clang should detect illegal copy constructor with template class as its parameter (PR #81251)

2024-02-25 Thread Rajveer Singh Bharadwaj via cfe-commits

https://github.com/Rajveer100 updated 
https://github.com/llvm/llvm-project/pull/81251

>From 5c5a91dbdf7239025d7bc5961afc0f375d3b1627 Mon Sep 17 00:00:00 2001
From: Rajveer 
Date: Fri, 9 Feb 2024 19:20:39 +0530
Subject: [PATCH] [clang] Clang should detect illegal copy constructor with
 template class as its parameter

Resolves #80963
---
 clang/docs/ReleaseNotes.rst|  3 +++
 clang/lib/Sema/SemaDeclCXX.cpp |  4 +---
 clang/test/SemaCXX/GH81251.cpp | 17 +
 3 files changed, 21 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/SemaCXX/GH81251.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 529dd783ab7382..8bd80a199ed3b0 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -281,6 +281,9 @@ Bug Fixes to C++ Support
   a requires-clause lie at the same depth as those of the surrounding lambda. 
This,
   in turn, results in the wrong template argument substitution during 
constraint checking.
   (`#78524 `_)
+  (`#782154 `_`)
+- Clang now detects illegal copy constructor with template class as its 
parameter.
+  Fixes (`#80963 https://github.com/llvm/llvm-project/issues/80963`_)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 7c009d9c8ec093..622bf0c258f138 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -10921,9 +10921,7 @@ void Sema::CheckConstructor(CXXConstructorDecl 
*Constructor) {
   //   either there are no other parameters or else all other
   //   parameters have default arguments.
   if (!Constructor->isInvalidDecl() &&
-  Constructor->hasOneParamOrDefaultArgs() &&
-  Constructor->getTemplateSpecializationKind() !=
-  TSK_ImplicitInstantiation) {
+  Constructor->hasOneParamOrDefaultArgs()) {
 QualType ParamType = Constructor->getParamDecl(0)->getType();
 QualType ClassTy = Context.getTagDeclType(ClassDecl);
 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
diff --git a/clang/test/SemaCXX/GH81251.cpp b/clang/test/SemaCXX/GH81251.cpp
new file mode 100644
index 00..a3e0ba07728dcc
--- /dev/null
+++ b/clang/test/SemaCXX/GH81251.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+template < class T, class V > struct A
+{
+A ();
+A (A &);
+A (A < V,T >);
+// expected-error@-1 {{copy constructor must pass its first argument by 
reference}}
+};
+
+void f ()
+{
+A  (A < int, int >());
+// expected-note@-1 {{in instantiation of template class 'A' 
requested here}}
+
+A  (A < int, double >());
+}

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


[clang] [clang] Clang should detect illegal copy constructor with template class as its parameter (PR #81251)

2024-02-25 Thread Rajveer Singh Bharadwaj via cfe-commits

https://github.com/Rajveer100 updated 
https://github.com/llvm/llvm-project/pull/81251

>From 7c58bd55bdd5c9a9cc838fec35e957f7952b2b52 Mon Sep 17 00:00:00 2001
From: Rajveer 
Date: Fri, 9 Feb 2024 19:20:39 +0530
Subject: [PATCH] [clang] Clang should detect illegal copy constructor with
 template class as its parameter

Resolves #80963
---
 clang/docs/ReleaseNotes.rst|  2 ++
 clang/lib/Sema/SemaDeclCXX.cpp |  4 +---
 clang/test/SemaCXX/GH81251.cpp | 17 +
 3 files changed, 20 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/SemaCXX/GH81251.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 649ad655905af2..fb213714e636ea 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -267,6 +267,8 @@ Bug Fixes to C++ Support
   was only accepted at namespace scope but not at local function scope.
 - Clang no longer tries to call consteval constructors at runtime when they 
appear in a member initializer.
   (`#782154 `_`)
+- Clang now detects illegal copy constructor with template class as its 
parameter.
+  Fixes (`#80963 https://github.com/llvm/llvm-project/issues/80963`_)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 79263bc3ff671d..5ac250d60c9a36 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -10921,9 +10921,7 @@ void Sema::CheckConstructor(CXXConstructorDecl 
*Constructor) {
   //   either there are no other parameters or else all other
   //   parameters have default arguments.
   if (!Constructor->isInvalidDecl() &&
-  Constructor->hasOneParamOrDefaultArgs() &&
-  Constructor->getTemplateSpecializationKind() !=
-  TSK_ImplicitInstantiation) {
+  Constructor->hasOneParamOrDefaultArgs()) {
 QualType ParamType = Constructor->getParamDecl(0)->getType();
 QualType ClassTy = Context.getTagDeclType(ClassDecl);
 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
diff --git a/clang/test/SemaCXX/GH81251.cpp b/clang/test/SemaCXX/GH81251.cpp
new file mode 100644
index 00..a3e0ba07728dcc
--- /dev/null
+++ b/clang/test/SemaCXX/GH81251.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+template < class T, class V > struct A
+{
+A ();
+A (A &);
+A (A < V,T >);
+// expected-error@-1 {{copy constructor must pass its first argument by 
reference}}
+};
+
+void f ()
+{
+A  (A < int, int >());
+// expected-note@-1 {{in instantiation of template class 'A' 
requested here}}
+
+A  (A < int, double >());
+}

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


[clang] [clang] Clang should detect illegal copy constructor with template class as its parameter (PR #81251)

2024-02-25 Thread Rajveer Singh Bharadwaj via cfe-commits

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


[clang] 1f6a347 - Refactor: Let MCDC::State have DecisionByStmt and BranchByStmt

2024-02-25 Thread NAKAMURA Takumi via cfe-commits

Author: NAKAMURA Takumi
Date: 2024-02-25T18:33:53+09:00
New Revision: 1f6a347c8abf8868fb4630c404480226c2efc2c2

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

LOG: Refactor: Let MCDC::State have DecisionByStmt and BranchByStmt

- Prune `RegionMCDCBitmapMap` and `RegionCondIDMap`. They are handled
  by `MCDCState`.
- Rename `s/BitmapMap/DecisionByStmt/`. It can handle Decision stuff.
- Rename `s/CondIDMap/BranchByStmt/`. It can be handle Branch stuff.
- `MCDCRecordProcessor`: Use `DecisionParams.BitmapIdx` directly.

Added: 


Modified: 
clang/lib/CodeGen/CodeGenPGO.cpp
clang/lib/CodeGen/CodeGenPGO.h
clang/lib/CodeGen/CoverageMappingGen.cpp
clang/lib/CodeGen/MCDCState.h
llvm/lib/ProfileData/Coverage/CoverageMapping.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenPGO.cpp 
b/clang/lib/CodeGen/CodeGenPGO.cpp
index 1ef7be3c72593d..8aebd3557690af 100644
--- a/clang/lib/CodeGen/CodeGenPGO.cpp
+++ b/clang/lib/CodeGen/CodeGenPGO.cpp
@@ -165,6 +165,7 @@ struct MapRegionCounters : public 
RecursiveASTVisitor {
   llvm::DenseMap 
   /// The next bitmap byte index to assign.
   unsigned NextMCDCBitmapIdx;
+  /// The state of MC/DC Coverage in this function.
   MCDC::State 
   /// Maximum number of supported MC/DC conditions in a boolean expression.
   unsigned MCDCMaxCond;
@@ -311,7 +312,7 @@ struct MapRegionCounters : public 
RecursiveASTVisitor {
 
   // Otherwise, allocate the number of bytes required for the bitmap
   // based on the number of conditions. Must be at least 1-byte long.
-  MCDCState.BitmapMap[BinOp] = NextMCDCBitmapIdx;
+  MCDCState.DecisionByStmt[BinOp].BitmapIdx = NextMCDCBitmapIdx;
   unsigned SizeInBits = std::max(1L << NumCond, CHAR_BIT);
   NextMCDCBitmapIdx += SizeInBits / CHAR_BIT;
 }
@@ -1034,7 +1035,7 @@ void CodeGenPGO::emitCounterRegionMapping(const Decl *D) {
 
   std::string CoverageMapping;
   llvm::raw_string_ostream OS(CoverageMapping);
-  RegionCondIDMap.reset(new llvm::DenseMap);
+  RegionMCDCState->BranchByStmt.clear();
   CoverageMappingGen MappingGen(
   *CGM.getCoverageMapping(), CGM.getContext().getSourceManager(),
   CGM.getLangOpts(), RegionCounterMap.get(), RegionMCDCState.get());
@@ -1142,12 +1143,12 @@ void 
CodeGenPGO::emitMCDCTestVectorBitmapUpdate(CGBuilderTy ,
 
   S = S->IgnoreParens();
 
-  auto ExprMCDCBitmapMapIterator = RegionMCDCState->BitmapMap.find(S);
-  if (ExprMCDCBitmapMapIterator == RegionMCDCState->BitmapMap.end())
+  auto DecisionStateIter = RegionMCDCState->DecisionByStmt.find(S);
+  if (DecisionStateIter == RegionMCDCState->DecisionByStmt.end())
 return;
 
-  // Extract the ID of the global bitmap associated with this expression.
-  unsigned MCDCTestVectorBitmapID = ExprMCDCBitmapMapIterator->second;
+  // Extract the offset of the global bitmap associated with this expression.
+  unsigned MCDCTestVectorBitmapOffset = DecisionStateIter->second.BitmapIdx;
   auto *I8PtrTy = llvm::PointerType::getUnqual(CGM.getLLVMContext());
 
   // Emit intrinsic responsible for updating the global bitmap corresponding to
@@ -1158,7 +1159,7 @@ void 
CodeGenPGO::emitMCDCTestVectorBitmapUpdate(CGBuilderTy ,
   llvm::Value *Args[5] = {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
   Builder.getInt64(FunctionHash),
   Builder.getInt32(RegionMCDCState->BitmapBytes),
-  Builder.getInt32(MCDCTestVectorBitmapID),
+  Builder.getInt32(MCDCTestVectorBitmapOffset),
   MCDCCondBitmapAddr.getPointer()};
   Builder.CreateCall(
   CGM.getIntrinsic(llvm::Intrinsic::instrprof_mcdc_tvbitmap_update), Args);
@@ -1171,7 +1172,7 @@ void CodeGenPGO::emitMCDCCondBitmapReset(CGBuilderTy 
, const Expr *S,
 
   S = S->IgnoreParens();
 
-  if (!RegionMCDCState->BitmapMap.contains(S))
+  if (!RegionMCDCState->DecisionByStmt.contains(S))
 return;
 
   // Emit intrinsic that resets a dedicated temporary value on the stack to 0.
@@ -1193,13 +1194,13 @@ void CodeGenPGO::emitMCDCCondBitmapUpdate(CGBuilderTy 
, const Expr *S,
   // also make debugging a bit easier.
   S = CodeGenFunction::stripCond(S);
 
-  auto ExprMCDCConditionIDMapIterator = RegionMCDCState->CondIDMap.find(S);
-  if (ExprMCDCConditionIDMapIterator == RegionMCDCState->CondIDMap.end())
+  auto BranchStateIter = RegionMCDCState->BranchByStmt.find(S);
+  if (BranchStateIter == RegionMCDCState->BranchByStmt.end())
 return;
 
   // Extract the ID of the condition we are setting in the bitmap.
-  auto CondID = ExprMCDCConditionIDMapIterator->second;
-  assert(CondID >= 0 && "Condition has no ID!");
+  const auto  = BranchStateIter->second;
+  assert(Branch.ID >= 0 && "Condition 

[clang] [clang][Darwin] Remove legacy framework search path logic in the frontend (PR #75841)

2024-02-25 Thread Brad Smith via cfe-commits

brad0 wrote:

Any chance of reviving this?

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


[clang] [clang-format] Limit how much work guessLanguage() can do (PR #78925)

2024-02-25 Thread Owen Pan via cfe-commits

owenca wrote:

@HighCommander4 see #82911

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


[clang] [clang-format] Add a parameter to getStyle() and guessLanguage() (PR #82911)

2024-02-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes

Add a boolean parameter GuessObjC that defaults to true. This allows e.g.
clangd to bypass ObjCHeaderStyleGuesser.process() by passing false for the
parameter.

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


2 Files Affected:

- (modified) clang/include/clang/Format/Format.h (+7-6) 
- (modified) clang/lib/Format/Format.cpp (+5-4) 


``diff
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index e9b2160a7b9243..af635a89d21312 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5228,19 +5228,20 @@ extern const char *DefaultFallbackStyle;
 /// \param[in] AllowUnknownOptions If true, unknown format options only
 /// emit a warning. If false, errors are emitted on unknown format
 /// options.
+/// \param[in] GuessObjC If true, guess and see if the language is Objective-C.
 ///
 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
 /// "file" and no file is found, returns ``FallbackStyle``. If no style could 
be
 /// determined, returns an Error.
-llvm::Expected getStyle(StringRef StyleName, StringRef FileName,
- StringRef FallbackStyle,
- StringRef Code = "",
- llvm::vfs::FileSystem *FS = nullptr,
- bool AllowUnknownOptions = false);
+llvm::Expected
+getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyle,
+ StringRef Code = "", llvm::vfs::FileSystem *FS = nullptr,
+ bool AllowUnknownOptions = false, bool GuessObjC = true);
 
 // Guesses the language from the ``FileName`` and ``Code`` to be formatted.
 // Defaults to FormatStyle::LK_Cpp.
-FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code);
+FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code,
+bool GuessObjC = true);
 
 // Returns a string representation of ``Language``.
 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 2f6b52510099a7..f5190745165ef6 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3914,13 +3914,14 @@ static FormatStyle::LanguageKind 
getLanguageByFileName(StringRef FileName) {
   return FormatStyle::LK_Cpp;
 }
 
-FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) {
+FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code,
+bool GuessObjC) {
   const auto GuessedLanguage = getLanguageByFileName(FileName);
   if (GuessedLanguage == FormatStyle::LK_Cpp) {
 auto Extension = llvm::sys::path::extension(FileName);
 // If there's no file extension (or it's .h), we need to check the contents
 // of the code to see if it contains Objective-C.
-if (Extension.empty() || Extension == ".h") {
+if (GuessObjC && (Extension.empty() || Extension == ".h")) {
   auto NonEmptyFileName = FileName.empty() ? "guess.h" : FileName;
   Environment Env(Code, NonEmptyFileName, /*Ranges=*/{});
   ObjCHeaderStyleGuesser Guesser(Env, getLLVMStyle());
@@ -3952,8 +3953,8 @@ loadAndParseConfigFile(StringRef ConfigFile, 
llvm::vfs::FileSystem *FS,
 llvm::Expected getStyle(StringRef StyleName, StringRef FileName,
  StringRef FallbackStyleName,
  StringRef Code, llvm::vfs::FileSystem *FS,
- bool AllowUnknownOptions) {
-  FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code));
+ bool AllowUnknownOptions, bool GuessObjC) 
{
+  FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code, GuessObjC));
   FormatStyle FallbackStyle = getNoStyle();
   if (!getPredefinedStyle(FallbackStyleName, Style.Language, ))
 return make_string_error("Invalid fallback style: " + FallbackStyleName);

``




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


[clang] [clang-format] Add a parameter to getStyle() and guessLanguage() (PR #82911)

2024-02-25 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/82911

Add a boolean parameter GuessObjC that defaults to true. This allows e.g.
clangd to bypass ObjCHeaderStyleGuesser.process() by passing false for the
parameter.

>From bd85fd1dff5ac7b72913ed175daec3809896e6c0 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sun, 25 Feb 2024 00:00:23 -0800
Subject: [PATCH] [clang-format] Add a parameter to getStyle() and
 guessLanguage()

Add a boolean parameter GuessObjC that defaults to true. This allows e.g.
clangd to bypass ObjCHeaderStyleGuesser.process() by passing false for the
parameter.
---
 clang/include/clang/Format/Format.h | 13 +++--
 clang/lib/Format/Format.cpp |  9 +
 2 files changed, 12 insertions(+), 10 deletions(-)

diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index e9b2160a7b9243..af635a89d21312 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5228,19 +5228,20 @@ extern const char *DefaultFallbackStyle;
 /// \param[in] AllowUnknownOptions If true, unknown format options only
 /// emit a warning. If false, errors are emitted on unknown format
 /// options.
+/// \param[in] GuessObjC If true, guess and see if the language is Objective-C.
 ///
 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
 /// "file" and no file is found, returns ``FallbackStyle``. If no style could 
be
 /// determined, returns an Error.
-llvm::Expected getStyle(StringRef StyleName, StringRef FileName,
- StringRef FallbackStyle,
- StringRef Code = "",
- llvm::vfs::FileSystem *FS = nullptr,
- bool AllowUnknownOptions = false);
+llvm::Expected
+getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyle,
+ StringRef Code = "", llvm::vfs::FileSystem *FS = nullptr,
+ bool AllowUnknownOptions = false, bool GuessObjC = true);
 
 // Guesses the language from the ``FileName`` and ``Code`` to be formatted.
 // Defaults to FormatStyle::LK_Cpp.
-FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code);
+FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code,
+bool GuessObjC = true);
 
 // Returns a string representation of ``Language``.
 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 2f6b52510099a7..f5190745165ef6 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3914,13 +3914,14 @@ static FormatStyle::LanguageKind 
getLanguageByFileName(StringRef FileName) {
   return FormatStyle::LK_Cpp;
 }
 
-FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) {
+FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code,
+bool GuessObjC) {
   const auto GuessedLanguage = getLanguageByFileName(FileName);
   if (GuessedLanguage == FormatStyle::LK_Cpp) {
 auto Extension = llvm::sys::path::extension(FileName);
 // If there's no file extension (or it's .h), we need to check the contents
 // of the code to see if it contains Objective-C.
-if (Extension.empty() || Extension == ".h") {
+if (GuessObjC && (Extension.empty() || Extension == ".h")) {
   auto NonEmptyFileName = FileName.empty() ? "guess.h" : FileName;
   Environment Env(Code, NonEmptyFileName, /*Ranges=*/{});
   ObjCHeaderStyleGuesser Guesser(Env, getLLVMStyle());
@@ -3952,8 +3953,8 @@ loadAndParseConfigFile(StringRef ConfigFile, 
llvm::vfs::FileSystem *FS,
 llvm::Expected getStyle(StringRef StyleName, StringRef FileName,
  StringRef FallbackStyleName,
  StringRef Code, llvm::vfs::FileSystem *FS,
- bool AllowUnknownOptions) {
-  FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code));
+ bool AllowUnknownOptions, bool GuessObjC) 
{
+  FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code, GuessObjC));
   FormatStyle FallbackStyle = getNoStyle();
   if (!getPredefinedStyle(FallbackStyleName, Style.Language, ))
 return make_string_error("Invalid fallback style: " + FallbackStyleName);

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