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

2024-02-21 Thread via cfe-commits


@@ -1104,12 +1104,22 @@ RecordStorageLocation *getBaseObjectLocation(const 
MemberExpr &ME,
   return Env.get(*Base);
 }
 
-std::vector getFieldsForInitListExpr(const RecordDecl *RD) {
+std::vector
+getFieldsForInitListExpr(const InitListExpr *InitList) {
+  const RecordDecl *RD = InitList->getType()->getAsRecordDecl();
+  assert(RD != nullptr);
+
+  std::vector Fields;

martinboehme wrote:

Makes sense. Unfortunately, `RecordDecl` doesn't have a way (that I know of) to 
query the number of fields. There's no `getNumFields()` or similar, and 
`field_end()-field_begin()` also doesn't work (because the iterator doesn't 
support `operator-`. So we'd have to do a complete iteration through the fields 
to determine the number, and at that point, I think we're getting into 
diminishing returns.

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


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

2024-02-21 Thread via cfe-commits

https://github.com/martinboehme updated 
https://github.com/llvm/llvm-project/pull/82348

>From fc41d1efdcff94857e7ccd3b8a1a75c3e83a84ee Mon Sep 17 00:00:00 2001
From: Martin Braenne 
Date: Tue, 20 Feb 2024 11:57:23 +
Subject: [PATCH 1/2] [clang][dataflow] Correctly handle `InitListExpr` of
 union type.

---
 .../FlowSensitive/DataflowEnvironment.h   |  9 ---
 .../FlowSensitive/DataflowEnvironment.cpp | 18 ++---
 clang/lib/Analysis/FlowSensitive/Transfer.cpp | 26 +++
 .../Analysis/FlowSensitive/TestingSupport.h   | 19 ++
 .../Analysis/FlowSensitive/TransferTest.cpp   | 14 --
 5 files changed, 66 insertions(+), 20 deletions(-)

diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index 0aecc749bf415c..b3dc940705f870 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -753,9 +753,12 @@ RecordStorageLocation *getImplicitObjectLocation(const 
CXXMemberCallExpr &MCE,
 RecordStorageLocation *getBaseObjectLocation(const MemberExpr &ME,
  const Environment &Env);
 
-/// Returns the fields of `RD` that are initialized by an `InitListExpr`, in 
the
-/// order in which they appear in `InitListExpr::inits()`.
-std::vector getFieldsForInitListExpr(const RecordDecl *RD);
+/// Returns the fields of a `RecordDecl` that are initialized by an
+/// `InitListExpr`, in the order in which they appear in
+/// `InitListExpr::inits()`.
+/// `Init->getType()` must be a record type.
+std::vector
+getFieldsForInitListExpr(const InitListExpr *InitList);
 
 /// Associates a new `RecordValue` with `Loc` and returns the new value.
 RecordValue &refreshRecordValue(RecordStorageLocation &Loc, Environment &Env);
diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index d487944ce92111..0cfc26ea952cda 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -361,8 +361,8 @@ getFieldsGlobalsAndFuncs(const Stmt &S, FieldSet &Fields,
 if (const auto *FD = dyn_cast(VD))
   Fields.insert(FD);
   } else if (auto *InitList = dyn_cast(&S)) {
-if (RecordDecl *RD = InitList->getType()->getAsRecordDecl())
-  for (const auto *FD : getFieldsForInitListExpr(RD))
+if (InitList->getType()->isRecordType())
+  for (const auto *FD : getFieldsForInitListExpr(InitList))
 Fields.insert(FD);
   }
 }
@@ -1104,12 +1104,22 @@ RecordStorageLocation *getBaseObjectLocation(const 
MemberExpr &ME,
   return Env.get(*Base);
 }
 
-std::vector getFieldsForInitListExpr(const RecordDecl *RD) {
+std::vector
+getFieldsForInitListExpr(const InitListExpr *InitList) {
+  const RecordDecl *RD = InitList->getType()->getAsRecordDecl();
+  assert(RD != nullptr);
+
+  std::vector Fields;
+
+  if (InitList->getType()->isUnionType()) {
+Fields.push_back(InitList->getInitializedFieldInUnion());
+return Fields;
+  }
+
   // Unnamed bitfields are only used for padding and do not appear in
   // `InitListExpr`'s inits. However, those fields do appear in `RecordDecl`'s
   // field list, and we thus need to remove them before mapping inits to
   // fields to avoid mapping inits to the wrongs fields.
-  std::vector Fields;
   llvm::copy_if(
   RD->fields(), std::back_inserter(Fields),
   [](const FieldDecl *Field) { return !Field->isUnnamedBitfield(); });
diff --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index fe13e919bddcd8..e793e8fb593dc3 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -663,14 +663,7 @@ class TransferVisitor : public 
ConstStmtVisitor {
   void VisitInitListExpr(const InitListExpr *S) {
 QualType Type = S->getType();
 
-if (Type->isUnionType()) {
-  // FIXME: Initialize unions properly.
-  if (auto *Val = Env.createValue(Type))
-Env.setValue(*S, *Val);
-  return;
-}
-
-if (!Type->isStructureOrClassType()) {
+if (!Type->isRecordType()) {
   // Until array initialization is implemented, we don't need to care about
   // cases where `getNumInits() > 1`.
   if (S->getNumInits() == 1)
@@ -688,10 +681,9 @@ class TransferVisitor : public 
ConstStmtVisitor {
 llvm::DenseMap FieldLocs;
 
 // This only contains the direct fields for the given type.
-std::vector FieldsForInit =
-getFieldsForInitListExpr(Type->getAsRecordDecl());
+std::vector FieldsForInit = getFieldsForInitListExpr(S);
 
-// `S->inits()` contains all the initializer epressions, including the
+// `S->inits()` contains all the initializer expressions, including the
 // ones for direct base classes.
 auto Inits = S->ini

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

2024-02-21 Thread via cfe-commits


@@ -731,6 +723,18 @@ class TransferVisitor : public 
ConstStmtVisitor {
   FieldLocs.insert({Field, &Loc});
 }
 
+// In the case of a union, we don't in general have initializers for all
+// of the fields. Create storage locations for the remaining fields (but
+// don't associate them with values).
+if (Type->isUnionType()) {
+  for (const FieldDecl *Field :
+   Env.getDataflowAnalysisContext().getModeledFields(Type)) {
+if (!FieldLocs.contains(Field))
+  FieldLocs.insert(

martinboehme wrote:

Good idea -- done!

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


[clang] [clang][analyzer] Change modeling of 'fileno' in checkers. (PR #81842)

2024-02-21 Thread Balázs Kéri via cfe-commits

https://github.com/balazske updated 
https://github.com/llvm/llvm-project/pull/81842

From 0f836d8e63f462f57784e62bcd87ac1f4f5a3d00 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bal=C3=A1zs=20K=C3=A9ri?= 
Date: Thu, 15 Feb 2024 10:56:32 +0100
Subject: [PATCH 1/3] [clang][analyzer] Change modeling of 'fileno' in
 checkers.

Function 'fileno' fails only if invalid pointer is passed, this is a
case that is often ignored in source code. The failure case leads to
many "false positive" (theoretically correct bug normally "should not
happen" cases) reports. Because this, the function is now assumed to
not fail. The change affects `StdCLibraryFunctionsChecker` and
`StreamChecker`.
---
 .../Checkers/StdLibraryFunctionsChecker.cpp   |   9 +-
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 203 +++---
 .../std-c-library-functions-path-notes.c  |  22 +-
 clang/test/Analysis/stream-errno-note.c   |  12 +-
 clang/test/Analysis/stream-errno.c|  16 +-
 clang/test/Analysis/stream-error.c|  18 ++
 clang/test/Analysis/stream-noopen.c   |  10 +
 7 files changed, 172 insertions(+), 118 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index 6b8ac2629453d4..6cc88679458140 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -2388,12 +2388,15 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 .ArgConstraint(NotNull(ArgNo(0;
 
 // int fileno(FILE *stream);
+// According to POSIX 'fileno' may fail and set 'errno'.
+// But in Linux it may fail only if the specified file pointer is invalid.
+// At many places 'fileno' is used without check for failure and a failure
+// case here would produce a large amount of likely false positive 
warnings.
+// To avoid this, we assume here that it does not fail.
 addToFunctionSummaryMap(
 "fileno", Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
 Summary(NoEvalCall)
-.Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked,
-  GenericSuccessMsg)
-.Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.Case(ReturnsValidFileDescriptor, ErrnoUnchanged, 
GenericSuccessMsg)
 .ArgConstraint(NotNull(ArgNo(0;
 
 // void rewind(FILE *stream);
diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 07727b339d967a..4dda09c4817d7b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -304,7 +304,8 @@ class StreamChecker : public Checker FnTestDescriptions = {
@@ -400,6 +401,9 @@ class StreamChecker : public Checker Stream = StreamVal.getAs();
+  if (!Stream)
+return;
+
+  ProgramStateRef StateNotNull, StateNull;
+  std::tie(StateNotNull, StateNull) =
+  C.getConstraintManager().assumeDual(State, *Stream);
+  if (StateNotNull && !StateNull)
+ensureStreamOpened(StreamVal, C, StateNotNull);
+}
+
+void StreamChecker::evalFflush(const FnDescription *Desc, const CallEvent 
&Call,
+   CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+  SVal StreamVal = getStreamArg(Desc, Call);
+  std::optional Stream = StreamVal.getAs();
+  if (!Stream)
+return;
+
+  // Skip if the stream can be both NULL and non-NULL.
+  ProgramStateRef StateNotNull, StateNull;
+  std::tie(StateNotNull, StateNull) =
+  C.getConstraintManager().assumeDual(State, *Stream);
+  if (StateNotNull && StateNull)
+return;
+  if (StateNotNull && !StateNull)
+State = StateNotNull;
+  else
+State = StateNull;
+
+  const CallExpr *CE = dyn_cast_or_null(Call.getOriginExpr());
+  if (!CE)
+return;
+
+  // `fflush` returns EOF on failure, otherwise returns 0.
+  ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
+  ProgramStateRef StateNotFailed = bindInt(0, State, C, CE);
+
+  // Clear error states if `fflush` returns 0, but retain their EOF flags.
+  auto ClearErrorInNotFailed = [&StateNotFailed, Desc](SymbolRef Sym,
+   const StreamState *SS) {
+if (SS->ErrorState & ErrorFError) {
+  StreamErrorState NewES =
+  (SS->ErrorState & ErrorFEof) ? ErrorFEof : ErrorNone;
+  StreamState NewSS = StreamState::getOpened(Desc, NewES, false);
+  StateNotFailed = StateNotFailed->set(Sym, NewSS);
+}
+  };
+
+  if (StateNotNull && !StateNull) {
+// Skip if the input stream's state is unknown, open-failed or closed.
+if (SymbolRef StreamSym = StreamVal.getAsSymbol()) {
+  const StreamState *SS = State->get(StreamSym);
+  if (SS) {
+assert(SS->isOpened() && "Stream is expected to be opened");
+ClearErrorInNotFailed(StreamSym, SS);
+   

[clang] [clang] [SemaCXX] Disallow deducing "this" on operator `new` and `delete` (PR #82251)

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

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

>From 05dbfac2043c22bdb73d5f09221421209bfe1f22 Mon Sep 17 00:00:00 2001
From: Rajveer 
Date: Mon, 19 Feb 2024 19:29:48 +0530
Subject: [PATCH] [clang] [SemaCXX] Disallow deducing "this" on operator `new`
 and `delete`

Resolves Issue #82249
---
 clang/docs/ReleaseNotes.rst| 2 ++
 clang/lib/Sema/SemaDeclCXX.cpp | 4 +++-
 clang/test/SemaCXX/cxx2b-deducing-this.cpp | 4 
 3 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 649ad655905af2..213a864d25dcae 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -254,6 +254,8 @@ Bug Fixes to C++ Support
   Fixes (`#68490 `_)
 - Fix a crash when trying to call a varargs function that also has an explicit 
object parameter.
   Fixes (`#80971 ICE when explicit object parameter be a function parameter 
pack`)
+- Reject explicit object parameters on `new` and `delete` operators.
+  Fixes (`#82249 ` _)
 - Fixed a bug where abbreviated function templates would append their invented 
template parameters to
   an empty template parameter lists.
 - Clang now classifies aggregate initialization in C++17 and newer as constant
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 79263bc3ff671d..7c009d9c8ec093 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -11395,7 +11395,9 @@ void Sema::CheckExplicitObjectMemberFunction(Declarator 
&D,
 << ExplicitObjectParam->getSourceRange();
   }
 
-  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) {
+  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
+  (D.getContext() == clang::DeclaratorContext::Member &&
+   D.isStaticMember())) {
 Diag(ExplicitObjectParam->getBeginLoc(),
  diag::err_explicit_object_parameter_nonmember)
 << D.getSourceRange() << /*static=*/0 << IsLambda;
diff --git a/clang/test/SemaCXX/cxx2b-deducing-this.cpp 
b/clang/test/SemaCXX/cxx2b-deducing-this.cpp
index 30131d6adc4db0..b8ddb9ad300034 100644
--- a/clang/test/SemaCXX/cxx2b-deducing-this.cpp
+++ b/clang/test/SemaCXX/cxx2b-deducing-this.cpp
@@ -16,6 +16,10 @@ struct S {
 static void f(this auto); // expected-error{{an explicit object parameter 
cannot appear in a static function}}
 virtual void f(this S); // expected-error{{an explicit object parameter 
cannot appear in a virtual function}}
 
+// new and delete are implicitly static
+void *operator new(this unsigned long); // expected-error{{an explicit 
object parameter cannot appear in a static function}}
+void operator delete(this void*); // expected-error{{an explicit object 
parameter cannot appear in a static function}}
+
 void g(this auto) const; // expected-error{{explicit object member 
function cannot have 'const' qualifier}}
 void h(this auto) &; // expected-error{{explicit object member function 
cannot have '&' qualifier}}
 void i(this auto) &&; // expected-error{{explicit object member function 
cannot have '&&' qualifier}}

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


[clang] 1246b64 - [clang][analyzer] Change modeling of 'fileno' in checkers. (#81842)

2024-02-21 Thread via cfe-commits

Author: Balázs Kéri
Date: 2024-02-21T09:18:01+01:00
New Revision: 1246b64faa5eea1553c1c1aad425c31b701fa6ea

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

LOG: [clang][analyzer] Change modeling of 'fileno' in checkers. (#81842)

Function 'fileno' fails only if invalid pointer is passed, this is a
case that is often ignored in source code. The failure case leads to
many "false positive" reports when `fileno` returns -1 and this is not
checked in the program. Because this, the function is now assumed
to not fail (this is assumption that the passed file pointer is correct).
The change affects `StdCLibraryFunctionsChecker` and
`StreamChecker`.

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
clang/test/Analysis/std-c-library-functions-path-notes.c
clang/test/Analysis/stream-errno-note.c
clang/test/Analysis/stream-errno.c
clang/test/Analysis/stream-error.c
clang/test/Analysis/stream-noopen.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index 6b8ac2629453d4..6cc88679458140 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -2388,12 +2388,15 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 .ArgConstraint(NotNull(ArgNo(0;
 
 // int fileno(FILE *stream);
+// According to POSIX 'fileno' may fail and set 'errno'.
+// But in Linux it may fail only if the specified file pointer is invalid.
+// At many places 'fileno' is used without check for failure and a failure
+// case here would produce a large amount of likely false positive 
warnings.
+// To avoid this, we assume here that it does not fail.
 addToFunctionSummaryMap(
 "fileno", Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
 Summary(NoEvalCall)
-.Case(ReturnsValidFileDescriptor, ErrnoMustNotBeChecked,
-  GenericSuccessMsg)
-.Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.Case(ReturnsValidFileDescriptor, ErrnoUnchanged, 
GenericSuccessMsg)
 .ArgConstraint(NotNull(ArgNo(0;
 
 // void rewind(FILE *stream);

diff  --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 7e7e3f0eee2b48..a070f451694a3b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -249,6 +249,10 @@ struct StreamOperationEvaluator {
 
   bool isStreamEof() const { return SS->ErrorState == ErrorFEof; }
 
+  NonLoc getZeroVal(const CallEvent &Call) {
+return *SVB.makeZeroVal(Call.getResultType()).getAs();
+  }
+
   ProgramStateRef setStreamState(ProgramStateRef State,
  const StreamState &NewSS) {
 return State->set(StreamSym, NewSS);
@@ -390,7 +394,8 @@ class StreamChecker : public Checker FnTestDescriptions = {
@@ -486,6 +491,9 @@ class StreamChecker : public CheckerBindExpr(E.CE, C.getLocationContext(), RetVal);
 StateNotFailed =
-E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal,
-*E.SVB.makeZeroVal(E.ACtx.IntTy).getAs());
+E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(Call));
 if (!StateNotFailed)
   return;
 StateNotFailed =
@@ -1003,8 +1010,7 @@ void StreamChecker::evalFscanf(const FnDescription *Desc, 
const CallEvent &Call,
 ProgramStateRef StateNotFailed =
 State->BindExpr(E.CE, C.getLocationContext(), RetVal);
 StateNotFailed =
-E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal,
-*E.SVB.makeZeroVal(E.ACtx.IntTy).getAs());
+E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(Call));
 if (StateNotFailed)
   C.addTransition(StateNotFailed);
   }
@@ -1073,8 +1079,7 @@ void StreamChecker::evalGetdelim(const FnDescription 
*Desc,
 ProgramStateRef StateNotFailed =
 State->BindExpr(E.CE, C.getLocationContext(), RetVal);
 StateNotFailed =
-E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal,
-*E.SVB.makeZeroVal(E.CE->getType()).getAs());
+E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(Call));
 if (!StateNotFailed)
   return;
 C.addTransition(StateNotFailed);
@@ -1200,8 +1205,7 @@ void StreamChecker::evalFtell(const FnDescription *Desc, 
const CallEvent &Call,
   ProgramStateRef StateNotFailed =
   State->BindExpr(E.CE, C.getLocationContext(), RetVal);
   StateNotFailed =
-  E.assumeBinOpNN(Stat

[clang] [clang][analyzer] Change modeling of 'fileno' in checkers. (PR #81842)

2024-02-21 Thread Balázs Kéri via cfe-commits

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


[clang] [clang] [SemaCXX] Disallow deducing "this" on operator `new` and `delete` (PR #82251)

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

Rajveer100 wrote:

@cor3ntin 
I have mistakenly added a merge commit, let me fix that.


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


[clang] [clang] [SemaCXX] Disallow deducing "this" on operator `new` and `delete` (PR #82251)

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

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

>From 05dbfac2043c22bdb73d5f09221421209bfe1f22 Mon Sep 17 00:00:00 2001
From: Rajveer 
Date: Mon, 19 Feb 2024 19:29:48 +0530
Subject: [PATCH] [clang] [SemaCXX] Disallow deducing "this" on operator `new`
 and `delete`

Resolves Issue #82249
---
 clang/docs/ReleaseNotes.rst| 2 ++
 clang/lib/Sema/SemaDeclCXX.cpp | 4 +++-
 clang/test/SemaCXX/cxx2b-deducing-this.cpp | 4 
 3 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 649ad655905af2..213a864d25dcae 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -254,6 +254,8 @@ Bug Fixes to C++ Support
   Fixes (`#68490 `_)
 - Fix a crash when trying to call a varargs function that also has an explicit 
object parameter.
   Fixes (`#80971 ICE when explicit object parameter be a function parameter 
pack`)
+- Reject explicit object parameters on `new` and `delete` operators.
+  Fixes (`#82249 ` _)
 - Fixed a bug where abbreviated function templates would append their invented 
template parameters to
   an empty template parameter lists.
 - Clang now classifies aggregate initialization in C++17 and newer as constant
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 79263bc3ff671d..7c009d9c8ec093 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -11395,7 +11395,9 @@ void Sema::CheckExplicitObjectMemberFunction(Declarator 
&D,
 << ExplicitObjectParam->getSourceRange();
   }
 
-  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) {
+  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
+  (D.getContext() == clang::DeclaratorContext::Member &&
+   D.isStaticMember())) {
 Diag(ExplicitObjectParam->getBeginLoc(),
  diag::err_explicit_object_parameter_nonmember)
 << D.getSourceRange() << /*static=*/0 << IsLambda;
diff --git a/clang/test/SemaCXX/cxx2b-deducing-this.cpp 
b/clang/test/SemaCXX/cxx2b-deducing-this.cpp
index 30131d6adc4db0..b8ddb9ad300034 100644
--- a/clang/test/SemaCXX/cxx2b-deducing-this.cpp
+++ b/clang/test/SemaCXX/cxx2b-deducing-this.cpp
@@ -16,6 +16,10 @@ struct S {
 static void f(this auto); // expected-error{{an explicit object parameter 
cannot appear in a static function}}
 virtual void f(this S); // expected-error{{an explicit object parameter 
cannot appear in a virtual function}}
 
+// new and delete are implicitly static
+void *operator new(this unsigned long); // expected-error{{an explicit 
object parameter cannot appear in a static function}}
+void operator delete(this void*); // expected-error{{an explicit object 
parameter cannot appear in a static function}}
+
 void g(this auto) const; // expected-error{{explicit object member 
function cannot have 'const' qualifier}}
 void h(this auto) &; // expected-error{{explicit object member function 
cannot have '&' qualifier}}
 void i(this auto) &&; // expected-error{{explicit object member function 
cannot have '&&' qualifier}}

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


[clang] [clang] [SemaCXX] Disallow deducing "this" on operator `new` and `delete` (PR #82251)

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

Rajveer100 wrote:

> @Rajveer100 you need us to merge that for you?

I am not sure what you meant by this?

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


[clang] 5037350 - [clang] Preserve found-decl when constructing VarTemplateIds (#82265)

2024-02-21 Thread via cfe-commits

Author: kadir çetinkaya
Date: 2024-02-21T09:52:19+01:00
New Revision: 50373506d570f3db1e1af7c13d46409736452f3a

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

LOG: [clang] Preserve found-decl when constructing VarTemplateIds (#82265)

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaTemplate.cpp
clang/test/AST/ast-dump-using.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 89215bf3d1c69a..23e1a623a20d15 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -8538,7 +8538,7 @@ class Sema final {
   /// if the arguments are dependent.
   ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
 const DeclarationNameInfo &NameInfo,
-VarTemplateDecl *Template,
+VarTemplateDecl *Template, NamedDecl *FoundD,
 SourceLocation TemplateLoc,
 const TemplateArgumentListInfo *TemplateArgs);
 

diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 1a975a8d0a0df5..7d3d665194add1 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -4958,11 +4958,10 @@ Sema::CheckVarTemplateId(VarTemplateDecl *Template, 
SourceLocation TemplateLoc,
   return Decl;
 }
 
-ExprResult
-Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
- const DeclarationNameInfo &NameInfo,
- VarTemplateDecl *Template, SourceLocation TemplateLoc,
- const TemplateArgumentListInfo *TemplateArgs) {
+ExprResult Sema::CheckVarTemplateId(
+const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
+VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
+const TemplateArgumentListInfo *TemplateArgs) {
 
   DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, 
NameInfo.getLoc(),
*TemplateArgs);
@@ -4978,8 +4977,7 @@ Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
NameInfo.getLoc());
 
   // Build an ordinary singleton decl ref.
-  return BuildDeclarationNameExpr(SS, NameInfo, Var,
-  /*FoundD=*/nullptr, TemplateArgs);
+  return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
 }
 
 void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
@@ -5066,9 +5064,9 @@ ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec 
&SS,
   bool KnownDependent = false;
   // In C++1y, check variable template ids.
   if (R.getAsSingle()) {
-ExprResult Res = CheckVarTemplateId(SS, R.getLookupNameInfo(),
-R.getAsSingle(),
-TemplateKWLoc, TemplateArgs);
+ExprResult Res = CheckVarTemplateId(
+SS, R.getLookupNameInfo(), R.getAsSingle(),
+R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
 if (Res.isInvalid() || Res.isUsable())
   return Res;
 // Result is dependent. Carry on to build an UnresolvedLookupEpxr.

diff  --git a/clang/test/AST/ast-dump-using.cpp 
b/clang/test/AST/ast-dump-using.cpp
index 5a4e910ffb8654..8e5c60d3aabf4a 100644
--- a/clang/test/AST/ast-dump-using.cpp
+++ b/clang/test/AST/ast-dump-using.cpp
@@ -2,6 +2,7 @@
 
 namespace a {
 struct S;
+template  T x = {};
 }
 namespace b {
 using a::S;
@@ -21,4 +22,10 @@ typedef S e; // check the same UsingType is reused.
 // CHECK-NEXT:   `-UsingType [[TYPE_ADDR]] 'a::S' sugar
 // CHECK-NEXT: |-UsingShadow [[SHADOW_ADDR]] 'S'
 // CHECK-NEXT: `-RecordType {{.*}} 'a::S'
+using a::x;
+
+void foo() {
+  x = 3;
+  // CHECK: DeclRefExpr {{.*}} 'x' {{.*}} (UsingShadow {{.*}} 'x')
+}
 }



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


[clang] [clang] Preserve found-decl when constructing VarTemplateIds (PR #82265)

2024-02-21 Thread kadir çetinkaya via cfe-commits

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


[clang] [alpha.webkit.UncountedCallArgsChecker] Allow a variable declaration in a trivial function. (PR #82291)

2024-02-21 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa updated https://github.com/llvm/llvm-project/pull/82291

>From 0a8cfb11a601e7a6ec59489b8ac15c40136002b2 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sat, 17 Feb 2024 18:12:16 -0800
Subject: [PATCH] [alpha.webkit.UncountedCallArgsChecker] Allow a variable
 declaration in a trivial function.

---
 .../Checkers/WebKit/PtrTypesSemantics.cpp   |  8 ++--
 .../Checkers/WebKit/uncounted-obj-arg.cpp   | 17 +
 2 files changed, 23 insertions(+), 2 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index a7891d2da07c18..09c42434513177 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -309,8 +309,12 @@ class TrivialFunctionAnalysisVisitor
 return true;
   if (isa(decl))
 return true;
-  if (auto *VD = dyn_cast(decl))
-return VD->hasConstantInitialization() && VD->getEvaluatedValue();
+  if (auto *VD = dyn_cast(decl)) {
+if (VD->hasConstantInitialization() && VD->getEvaluatedValue())
+  return true;
+auto *Init = VD->getInit();
+return !Init || Visit(Init);
+  }
 }
 return false;
   }
diff --git a/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp 
b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp
index ac16a31293f3de..80a9a263dab140 100644
--- a/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp
+++ b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp
@@ -199,6 +199,8 @@ class RefCounted {
   bool trivial23() const { return 
OptionSet::fromRaw(v).contains(Flags::Flag1); }
   int trivial24() const { ASSERT(v); return v; }
   unsigned trivial25() const { return __c11_atomic_load((volatile 
_Atomic(unsigned) *)&v, __ATOMIC_RELAXED); }
+  bool trivial26() { bool hasValue = v; return !hasValue; }
+  bool trivial27(int v) { bool value; value = v ? 1 : 0; return value; }
 
   static RefCounted& singleton() {
 static RefCounted s_RefCounted;
@@ -262,6 +264,15 @@ class RefCounted {
 return __c11_atomic_load((volatile _Atomic(unsigned) *)another(), 
__ATOMIC_RELAXED);
   }
 
+  void nonTrivial11() {
+Number num(0.3);
+  }
+
+  bool nonTrivial12() {
+bool val = otherFunction();
+return val;
+  }
+
   unsigned v { 0 };
   Number* number { nullptr };
   Enum enumValue { Enum::Value1 };
@@ -309,6 +320,8 @@ class UnrelatedClass {
 getFieldTrivial().trivial23(); // no-warning
 getFieldTrivial().trivial24(); // no-warning
 getFieldTrivial().trivial25(); // no-warning
+getFieldTrivial().trivial26(); // no-warning
+getFieldTrivial().trivial27(5); // no-warning
 RefCounted::singleton().trivial18(); // no-warning
 RefCounted::singleton().someFunction(); // no-warning
 
@@ -334,6 +347,10 @@ class UnrelatedClass {
 // expected-warning@-1{{Call argument for 'this' parameter is uncounted 
and unsafe}}
 getFieldTrivial().nonTrivial10();
 // expected-warning@-1{{Call argument for 'this' parameter is uncounted 
and unsafe}}
+getFieldTrivial().nonTrivial11();
+// expected-warning@-1{{Call argument for 'this' parameter is uncounted 
and unsafe}}
+getFieldTrivial().nonTrivial12();
+// expected-warning@-1{{Call argument for 'this' parameter is uncounted 
and unsafe}}
   }
 };
 

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


[clang] [alpha.webkit.UncountedCallArgsChecker] Don't assume local variables are safe & treat guarded local variable as safe function arguments (PR #82305)

2024-02-21 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa updated https://github.com/llvm/llvm-project/pull/82305

>From 8e9b4433df511e9982d181a5c18262208a72177d Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Fri, 16 Feb 2024 19:29:54 -0800
Subject: [PATCH 1/2] [alpha.webkit.UncountedCallArgsChecker] Don't assume
 local variables are safe.

This PR makes alpha.webkit.UncountedCallArgsChecker no longer assume that every 
local variable to be safe.
Instead, we try to validate the local variable's origin in tryToFindPtrOrigin. 
To do this, this PR extracts
the code to decide whether a given type is a specialization of Ref / RefPtr as 
isTypeRefCounted and
calls it in tryToFindPtrOrigin for the declared variable. This PR also fixes a 
bug in the same function
that we were not detecting DeducedTemplateSpecializationType as a safe origin.
---
 .../lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp  |  9 -
 .../Checkers/WebKit/PtrTypesSemantics.cpp| 12 +++-
 .../Checkers/WebKit/PtrTypesSemantics.h  |  5 -
 3 files changed, 23 insertions(+), 3 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
index 1a9d6d3127fb7f..d8738bac5dae3a 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
@@ -27,6 +27,13 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
   E = tempExpr->getSubExpr();
   continue;
 }
+if (auto *DRE = dyn_cast(E)) {
+  auto *decl = DRE->getFoundDecl();
+  if (auto *VD = dyn_cast(decl)) {
+if (isTypeRefCounted(VD->getType()))
+  return {E, true};
+  }
+}
 if (auto *cast = dyn_cast(E)) {
   if (StopAtFirstRefCountedObj) {
 if (auto *ConversionFunc =
@@ -99,7 +106,7 @@ bool isASafeCallArg(const Expr *E) {
   assert(E);
   if (auto *Ref = dyn_cast(E)) {
 if (auto *D = dyn_cast_or_null(Ref->getFoundDecl())) {
-  if (isa(D) || D->isLocalVarDecl())
+  if (isa(D))
 return true;
 }
   }
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index a7891d2da07c18..99bf1ed634db56 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -122,12 +122,22 @@ bool isCtorOfRefCounted(const clang::FunctionDecl *F) {
 
 bool isReturnValueRefCounted(const clang::FunctionDecl *F) {
   assert(F);
-  QualType type = F->getReturnType();
+  return isTypeRefCounted(F->getReturnType());
+}
+
+bool isTypeRefCounted(QualType type) {
+  assert(F);
   while (!type.isNull()) {
 if (auto *elaboratedT = type->getAs()) {
   type = elaboratedT->desugar();
   continue;
 }
+if (auto *deduced = type->getAs()) {
+  if (auto *decl = deduced->getTemplateName().getAsTemplateDecl()) {
+auto name = decl->getNameAsString();
+return name == "Ref" || name == "RefPtr";
+  }
+}
 if (auto *specialT = type->getAs()) {
   if (auto *decl = specialT->getTemplateName().getAsTemplateDecl()) {
 auto name = decl->getNameAsString();
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
index e07cd31395747d..5051f4e321bb6d 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
@@ -9,7 +9,7 @@
 #ifndef LLVM_CLANG_ANALYZER_WEBKIT_PTRTYPESEMANTICS_H
 #define LLVM_CLANG_ANALYZER_WEBKIT_PTRTYPESEMANTICS_H
 
-#include "llvm/ADT/APInt.h"
+#include "clang/AST/Type.h"
 #include "llvm/ADT/DenseMap.h"
 #include 
 
@@ -55,6 +55,9 @@ bool isCtorOfRefCounted(const clang::FunctionDecl *F);
 /// \returns true if \p F returns a ref-counted object, false if not.
 bool isReturnValueRefCounted(const clang::FunctionDecl *F);
 
+/// \returns true if \p type is ref-counted object, false if not.
+bool isTypeRefCounted(QualType type);
+
 /// \returns true if \p M is getter of a ref-counted class, false if not.
 std::optional isGetterOfRefCounted(const clang::CXXMethodDecl* Method);
 

>From ab402509f580da708fffbd34a86c3a3354313c6b Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sat, 17 Feb 2024 22:43:58 -0800
Subject: [PATCH 2/2] [alpha.webkit.UncountedCallArgsChecker] Treat guarded
 local variable as safe function arguments

This PR extracts the code in UncountedLocalVarsChecker to identify a variable 
declaration which
has a guardian Ref / RefPtr variable as isVarDeclGuardedInit and integrates it 
with
alpha.webkit.UncountedCallArgsChecker so that we treat local variables that are 
"guarded" by
a Ref / RefPtr as safe function arguments.
---
 .../Checkers/WebKit/ASTUtils.cpp  | 126 ++
 .../StaticAnalyzer/Checkers/WebKit/ASTUtils.h |   5 +
 .../Checkers/WebKit/PtrTypesSemantics.c

[clang] [alpha.webkit.UncountedLocalVarsChecker] Allow uncounted object references within trivial statements (PR #82229)

2024-02-21 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa updated https://github.com/llvm/llvm-project/pull/82229

>From 099640652b62c52160b12542a16eb66da90cfc93 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Mon, 19 Feb 2024 01:07:13 -0800
Subject: [PATCH] [alpha.webkit.UncountedLocalVarsChecker] Allow uncounted
 object references within trivial statements

This PR makes alpha.webkit.UncountedLocalVarsChecker ignore raw references and 
pointers to
a ref counted type which appears within "trival" statements. To do this, this 
PR extends
TrivialFunctionAnalysis so that it can also analyze "triviality" of statements 
as well as
that of functions Each Visit* function is now augmented with withCachedResult, 
which is
responsible for looking up and updating the cache for each Visit* functions.

As this PR dramatically improves the false positive rate of the checker, it 
also deletes
the code to ignore raw pointers and references within if and for statements.
---
 .../Checkers/WebKit/PtrTypesSemantics.cpp | 221 --
 .../Checkers/WebKit/PtrTypesSemantics.h   |  21 +-
 .../WebKit/UncountedLocalVarsChecker.cpp  |  69 +++---
 .../Analysis/Checkers/WebKit/mock-types.h |   2 +
 .../Checkers/WebKit/uncounted-local-vars.cpp  |  92 +++-
 5 files changed, 286 insertions(+), 119 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index a7891d2da07c18..cb89ce59a60878 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -244,18 +244,41 @@ class TrivialFunctionAnalysisVisitor
 
   // Returns false if at least one child is non-trivial.
   bool VisitChildren(const Stmt *S) {
-for (const Stmt *Child : S->children()) {
-  if (Child && !Visit(Child))
+return withCachedResult(S, [&]() {
+  for (const Stmt *Child : S->children()) {
+if (Child && !Visit(Child))
+  return false;
+  }
+  return true;
+});
+  }
+
+  bool VisitSubExpr(const Expr *Parent, const Expr *E) {
+return withCachedResult(Parent, [&]() {
+  if (!Visit(E))
 return false;
-}
+  return true;
+});
+  }
 
-return true;
+  template 
+  bool withCachedResult(const StmtType *S, CheckFunction Function) {
+// Insert false to the cache first to avoid infinite recursion.
+auto [It, IsNew] = StatementCache.insert(std::make_pair(S, false));
+if (!IsNew)
+  return It->second;
+bool Result = Function();
+It->second = Result;
+return Result;
   }
 
 public:
-  using CacheTy = TrivialFunctionAnalysis::CacheTy;
+  using FunctionCacheTy = TrivialFunctionAnalysis::FunctionCacheTy;
+  using StatementCacheTy = TrivialFunctionAnalysis::StatementCacheTy;
 
-  TrivialFunctionAnalysisVisitor(CacheTy &Cache) : Cache(Cache) {}
+  TrivialFunctionAnalysisVisitor(FunctionCacheTy &FunctionCache,
+ StatementCacheTy &StatementCache)
+  : FunctionCache(FunctionCache), StatementCache(StatementCache) {}
 
   bool VisitStmt(const Stmt *S) {
 // All statements are non-trivial unless overriden later.
@@ -271,13 +294,21 @@ class TrivialFunctionAnalysisVisitor
 
   bool VisitReturnStmt(const ReturnStmt *RS) {
 // A return statement is allowed as long as the return value is trivial.
-if (auto *RV = RS->getRetValue())
-  return Visit(RV);
-return true;
+return withCachedResult(RS, [&]() {
+  if (auto *RV = RS->getRetValue())
+return Visit(RV);
+  return true;
+});
+  }
+
+  bool VisitCXXForRangeStmt(const CXXForRangeStmt *FS) {
+return VisitChildren(FS);
   }
 
   bool VisitDeclStmt(const DeclStmt *DS) { return VisitChildren(DS); }
   bool VisitDoStmt(const DoStmt *DS) { return VisitChildren(DS); }
+  bool VisitForStmt(const ForStmt *FS) { return VisitChildren(FS); }
+  bool VisitWhileStmt(const WhileStmt *WS) { return VisitChildren(WS); }
   bool VisitIfStmt(const IfStmt *IS) { return VisitChildren(IS); }
   bool VisitSwitchStmt(const SwitchStmt *SS) { return VisitChildren(SS); }
   bool VisitCaseStmt(const CaseStmt *CS) { return VisitChildren(CS); }
@@ -285,17 +316,26 @@ class TrivialFunctionAnalysisVisitor
 
   bool VisitUnaryOperator(const UnaryOperator *UO) {
 // Operator '*' and '!' are allowed as long as the operand is trivial.
-if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
-UO->getOpcode() == UO_LNot)
-  return Visit(UO->getSubExpr());
-
-// Other operators are non-trivial.
-return false;
+return withCachedResult(UO, [&]() {
+  auto op = UO->getOpcode();
+  if (op == UO_Deref || op == UO_AddrOf || op == UO_LNot)
+return Visit(UO->getSubExpr());
+  if (UO->isIncrementOp() || UO->isDecrementOp()) {
+if (auto *RefExpr = dyn_cast(UO->getSubExpr())) {
+  if (auto *Decl = dyn_cast(RefExpr->getDecl()))
+return Decl->isLoc

[clang] [alpha.webkit.UncountedLocalVarsChecker] Allow uncounted object references within trivial statements (PR #82229)

2024-02-21 Thread Ryosuke Niwa via cfe-commits

rniwa wrote:

> I want to spend a bit more time thinking whether this has to go into every 
> callback, maybe it can be a set-and-forget thing? (Probably not.)

What do you mean by set-and-forget?


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


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

2024-02-21 Thread via cfe-commits

martinboehme wrote:

CI failure appears to be an infrastructure issue. Patch cleanly builds and 
tests locally.

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


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

2024-02-21 Thread via cfe-commits

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


[clang] 4725993 - [clang][dataflow] Correctly handle `InitListExpr` of union type. (#82348)

2024-02-21 Thread via cfe-commits

Author: martinboehme
Date: 2024-02-21T10:10:25+01:00
New Revision: 4725993f1a812c86b9ad79d229a015d0216ff550

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

LOG: [clang][dataflow] Correctly handle `InitListExpr` of union type. (#82348)

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
clang/lib/Analysis/FlowSensitive/Transfer.cpp
clang/unittests/Analysis/FlowSensitive/TestingSupport.h
clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index 0aecc749bf415c..b3dc940705f870 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -753,9 +753,12 @@ RecordStorageLocation *getImplicitObjectLocation(const 
CXXMemberCallExpr &MCE,
 RecordStorageLocation *getBaseObjectLocation(const MemberExpr &ME,
  const Environment &Env);
 
-/// Returns the fields of `RD` that are initialized by an `InitListExpr`, in 
the
-/// order in which they appear in `InitListExpr::inits()`.
-std::vector getFieldsForInitListExpr(const RecordDecl *RD);
+/// Returns the fields of a `RecordDecl` that are initialized by an
+/// `InitListExpr`, in the order in which they appear in
+/// `InitListExpr::inits()`.
+/// `Init->getType()` must be a record type.
+std::vector
+getFieldsForInitListExpr(const InitListExpr *InitList);
 
 /// Associates a new `RecordValue` with `Loc` and returns the new value.
 RecordValue &refreshRecordValue(RecordStorageLocation &Loc, Environment &Env);

diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index d487944ce92111..0cfc26ea952cda 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -361,8 +361,8 @@ getFieldsGlobalsAndFuncs(const Stmt &S, FieldSet &Fields,
 if (const auto *FD = dyn_cast(VD))
   Fields.insert(FD);
   } else if (auto *InitList = dyn_cast(&S)) {
-if (RecordDecl *RD = InitList->getType()->getAsRecordDecl())
-  for (const auto *FD : getFieldsForInitListExpr(RD))
+if (InitList->getType()->isRecordType())
+  for (const auto *FD : getFieldsForInitListExpr(InitList))
 Fields.insert(FD);
   }
 }
@@ -1104,12 +1104,22 @@ RecordStorageLocation *getBaseObjectLocation(const 
MemberExpr &ME,
   return Env.get(*Base);
 }
 
-std::vector getFieldsForInitListExpr(const RecordDecl *RD) {
+std::vector
+getFieldsForInitListExpr(const InitListExpr *InitList) {
+  const RecordDecl *RD = InitList->getType()->getAsRecordDecl();
+  assert(RD != nullptr);
+
+  std::vector Fields;
+
+  if (InitList->getType()->isUnionType()) {
+Fields.push_back(InitList->getInitializedFieldInUnion());
+return Fields;
+  }
+
   // Unnamed bitfields are only used for padding and do not appear in
   // `InitListExpr`'s inits. However, those fields do appear in `RecordDecl`'s
   // field list, and we thus need to remove them before mapping inits to
   // fields to avoid mapping inits to the wrongs fields.
-  std::vector Fields;
   llvm::copy_if(
   RD->fields(), std::back_inserter(Fields),
   [](const FieldDecl *Field) { return !Field->isUnnamedBitfield(); });

diff  --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index fe13e919bddcd8..cd1f04e53cff68 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -663,14 +663,7 @@ class TransferVisitor : public 
ConstStmtVisitor {
   void VisitInitListExpr(const InitListExpr *S) {
 QualType Type = S->getType();
 
-if (Type->isUnionType()) {
-  // FIXME: Initialize unions properly.
-  if (auto *Val = Env.createValue(Type))
-Env.setValue(*S, *Val);
-  return;
-}
-
-if (!Type->isStructureOrClassType()) {
+if (!Type->isRecordType()) {
   // Until array initialization is implemented, we don't need to care about
   // cases where `getNumInits() > 1`.
   if (S->getNumInits() == 1)
@@ -688,10 +681,9 @@ class TransferVisitor : public 
ConstStmtVisitor {
 llvm::DenseMap FieldLocs;
 
 // This only contains the direct fields for the given type.
-std::vector FieldsForInit =
-getFieldsForInitListExpr(Type->getAsRecordDecl());
+std::vector FieldsForInit = getFieldsForInitListExpr(S);
 
-// `S->inits()` contains all the initializer epressions, including the
+// `S->inits()` contai

[clang] [analyzer] Improve handling of unsigned values in ArrayBoundCheckerV2 (PR #81034)

2024-02-21 Thread Endre Fülöp via cfe-commits

gamesh411 wrote:

I checked many false positives, even those that were not FP at first sight; I 
think we can live without them.
I also agree that we should strive to handle comparison evaluation more 
uniformly and preferably behind the API barrier of the constraint manager.
LGTM

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


[clang] [analyzer] Improve handling of unsigned values in ArrayBoundCheckerV2 (PR #81034)

2024-02-21 Thread Endre Fülöp via cfe-commits

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


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


[clang] [clang-tools-extra] [flang] [lld] [llvm] [flang][clang] Add Visibility specific help text for options (PR #81869)

2024-02-21 Thread David Spickett via cfe-commits


@@ -3391,7 +3391,10 @@ def fno_openmp : Flag<["-"], "fno-openmp">, 
Group,
 def fopenmp_version_EQ : Joined<["-"], "fopenmp-version=">, Group,
   Flags<[NoArgumentUnused]>,
   Visibility<[ClangOption, CC1Option, FlangOption, FC1Option]>,
-  HelpText<"Set OpenMP version (e.g. 45 for OpenMP 4.5, 51 for OpenMP 5.1). 
Default value is 51 for Clang">;
+  HelpText<"Set OpenMP version (e.g. 45 for OpenMP 4.5, 51 for OpenMP 5.1). 
Default value is 51 for Clang">,
+  HelpForVisibilityhttps://github.com/llvm/llvm-project/pull/81869
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [compiler-rt] [clang][UBSan] Add implicit conversion check for bitfields (PR #75481)

2024-02-21 Thread Axel Lundberg via cfe-commits

Zonotora wrote:

> Precommit CI seems to have found some related failures that should be 
> investigated. I'd love to hear opinions from the codegen code owners on this, 
> as well as @zygoloid as UBSan code owner. I'm not opposed to the changes, 
> though I do find it somewhat strange to add them to UBSan given that they're 
> not undefined behavior (even though there's precedent).

@AaronBallman CI Linux is successful, but "Trigger build on clang-ci" seems to 
be failing on unrelated format and windows build? I also find it strange that 
these checks are included in UBSan. However, it might be better to refactor 
this in a future PR, as you say, there are reasons to include it in UBSan now 
because of the current `-fsanitize=implicit-conversion` flag. How do we move 
this forward and merge the PR?

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


[clang] [clang][analyzer] StreamChecker: add more APIs, invalidate fscanf args (PR #82476)

2024-02-21 Thread Alejandro Álvarez Ayllón via cfe-commits

https://github.com/alejandro-alvarez-sonarsource created 
https://github.com/llvm/llvm-project/pull/82476

1. Model `getc`, `vfscanf`, `putc`, `vfprintf`.
2. `fscanf` invalidates all arguments after the format string.

Also, add tests for `ftello` and `fseeko`.

From a21881d82fe3674b344d4a3807e9d2590c98ce93 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?=
 
Date: Tue, 14 Nov 2023 09:28:45 +0100
Subject: [PATCH] [clang][analyzer] StreamChecker: add more APIs, invalidate
 fscanf args

1. Model getc, vfscanf, putc, vfprintf.
2. fscanf invalidates all arguments after the format string.
---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp |  39 +-
 ...ystem-header-simulator-for-simple-stream.h |   2 +-
 .../system-header-simulator-for-valist.h  |   4 +
 .../Analysis/Inputs/system-header-simulator.h |   3 +
 clang/test/Analysis/stream.c  | 128 ++
 5 files changed, 174 insertions(+), 2 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index a070f451694a3b..7938a0d30a91a3 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -21,6 +21,8 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
+#include "llvm/ADT/Sequence.h"
+#include "llvm/ADT/SmallVector.h"
 #include 
 #include 
 
@@ -171,7 +173,7 @@ using FnCheck = std::function;
 
 using ArgNoTy = unsigned int;
-static const ArgNoTy ArgNone = std::numeric_limits::max();
+const ArgNoTy ArgNone = std::numeric_limits::max();
 
 struct FnDescription {
   FnCheck PreFn;
@@ -179,6 +181,26 @@ struct FnDescription {
   ArgNoTy StreamArgNo;
 };
 
+[[nodiscard]] ProgramStateRef
+escapeArgsAfterIndex(ProgramStateRef State, CheckerContext &C,
+ const CallEvent &Call, unsigned FirstEscapingArgIndex) {
+  const auto *CE = Call.getOriginExpr();
+  assert(CE);
+
+  if (Call.getNumArgs() <= FirstEscapingArgIndex)
+return State;
+
+  SmallVector EscapingArgs;
+  EscapingArgs.reserve(Call.getNumArgs() - FirstEscapingArgIndex);
+  for (auto EscArgIdx :
+   llvm::seq(FirstEscapingArgIndex, Call.getNumArgs()))
+EscapingArgs.push_back(Call.getArgSVal(EscArgIdx));
+  State = State->invalidateRegions(EscapingArgs, CE, C.blockCount(),
+   C.getLocationContext(),
+   /*CausesPointerEscape=*/false);
+  return State;
+}
+
 /// Get the value of the stream argument out of the passed call event.
 /// The call should contain a function that is described by Desc.
 SVal getStreamArg(const FnDescription *Desc, const CallEvent &Call) {
@@ -396,6 +418,18 @@ class StreamChecker : public Checker FnTestDescriptions = {
@@ -997,6 +1031,9 @@ void StreamChecker::evalFscanf(const FnDescription *Desc, 
const CallEvent &Call,
   if (!E.Init(Desc, Call, C, State))
 return;
 
+  // The pointers passed to fscanf escape and get invalidated.
+  State = escapeArgsAfterIndex(State, C, Call, /*FirstEscapingArgIndex=*/2);
+
   // Add the success state.
   // In this context "success" means there is not an EOF or other read error
   // before any item is matched in 'fscanf'. But there may be match failure,
diff --git 
a/clang/test/Analysis/Inputs/system-header-simulator-for-simple-stream.h 
b/clang/test/Analysis/Inputs/system-header-simulator-for-simple-stream.h
index 098a2208fecbe9..c26d3582149120 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator-for-simple-stream.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator-for-simple-stream.h
@@ -5,7 +5,7 @@
 // suppressed.
 #pragma clang system_header
 
-typedef struct __sFILE {
+typedef struct _FILE {
   unsigned char *_p;
 } FILE;
 FILE *fopen(const char *restrict, const char *restrict) __asm("_" "fopen" );
diff --git a/clang/test/Analysis/Inputs/system-header-simulator-for-valist.h 
b/clang/test/Analysis/Inputs/system-header-simulator-for-valist.h
index 7299b61353d460..87688bd8b312f4 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator-for-valist.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator-for-valist.h
@@ -10,6 +10,8 @@
 #define restrict /*restrict*/
 #endif
 
+typedef struct _FILE FILE;
+
 typedef __builtin_va_list va_list;
 
 #define va_start(ap, param) __builtin_va_start(ap, param)
@@ -21,6 +23,8 @@ int vprintf (const char *restrict format, va_list arg);
 
 int vsprintf (char *restrict s, const char *restrict format, va_list arg);
 
+int vfscanf(FILE *stream, const char *format, va_list ap);
+
 int some_library_function(int n, va_list arg);
 
 // No warning from system header.
diff --git a/clang/test/Analysis/Inputs/system-header-simulator.h 
b/clang/test/Analysis/Inputs/system-header-simulator.h
index 15986984802c0e..8fd51449ecc0a4 100644
--- a/cla

[clang] [clang][analyzer] StreamChecker: Add more APIs, invalidate fscanf args (PR #82476)

2024-02-21 Thread Alejandro Álvarez Ayllón via cfe-commits

https://github.com/alejandro-alvarez-sonarsource edited 
https://github.com/llvm/llvm-project/pull/82476
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] StreamChecker: Add more APIs, invalidate fscanf args (PR #82476)

2024-02-21 Thread via cfe-commits

llvmbot wrote:




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

Author: Alejandro Álvarez Ayllón (alejandro-alvarez-sonarsource)


Changes

1. Model `getc`, `vfscanf`, `putc`, `vfprintf`.
2. `fscanf` invalidates all arguments after the format string.

Also, add tests for `ftello` and `fseeko`.

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


5 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp (+38-1) 
- (modified) 
clang/test/Analysis/Inputs/system-header-simulator-for-simple-stream.h (+1-1) 
- (modified) clang/test/Analysis/Inputs/system-header-simulator-for-valist.h 
(+4) 
- (modified) clang/test/Analysis/Inputs/system-header-simulator.h (+3) 
- (modified) clang/test/Analysis/stream.c (+128) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index a070f451694a3b..7938a0d30a91a3 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -21,6 +21,8 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
+#include "llvm/ADT/Sequence.h"
+#include "llvm/ADT/SmallVector.h"
 #include 
 #include 
 
@@ -171,7 +173,7 @@ using FnCheck = std::function;
 
 using ArgNoTy = unsigned int;
-static const ArgNoTy ArgNone = std::numeric_limits::max();
+const ArgNoTy ArgNone = std::numeric_limits::max();
 
 struct FnDescription {
   FnCheck PreFn;
@@ -179,6 +181,26 @@ struct FnDescription {
   ArgNoTy StreamArgNo;
 };
 
+[[nodiscard]] ProgramStateRef
+escapeArgsAfterIndex(ProgramStateRef State, CheckerContext &C,
+ const CallEvent &Call, unsigned FirstEscapingArgIndex) {
+  const auto *CE = Call.getOriginExpr();
+  assert(CE);
+
+  if (Call.getNumArgs() <= FirstEscapingArgIndex)
+return State;
+
+  SmallVector EscapingArgs;
+  EscapingArgs.reserve(Call.getNumArgs() - FirstEscapingArgIndex);
+  for (auto EscArgIdx :
+   llvm::seq(FirstEscapingArgIndex, Call.getNumArgs()))
+EscapingArgs.push_back(Call.getArgSVal(EscArgIdx));
+  State = State->invalidateRegions(EscapingArgs, CE, C.blockCount(),
+   C.getLocationContext(),
+   /*CausesPointerEscape=*/false);
+  return State;
+}
+
 /// Get the value of the stream argument out of the passed call event.
 /// The call should contain a function that is described by Desc.
 SVal getStreamArg(const FnDescription *Desc, const CallEvent &Call) {
@@ -396,6 +418,18 @@ class StreamChecker : public Checker FnTestDescriptions = {
@@ -997,6 +1031,9 @@ void StreamChecker::evalFscanf(const FnDescription *Desc, 
const CallEvent &Call,
   if (!E.Init(Desc, Call, C, State))
 return;
 
+  // The pointers passed to fscanf escape and get invalidated.
+  State = escapeArgsAfterIndex(State, C, Call, /*FirstEscapingArgIndex=*/2);
+
   // Add the success state.
   // In this context "success" means there is not an EOF or other read error
   // before any item is matched in 'fscanf'. But there may be match failure,
diff --git 
a/clang/test/Analysis/Inputs/system-header-simulator-for-simple-stream.h 
b/clang/test/Analysis/Inputs/system-header-simulator-for-simple-stream.h
index 098a2208fecbe9..c26d3582149120 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator-for-simple-stream.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator-for-simple-stream.h
@@ -5,7 +5,7 @@
 // suppressed.
 #pragma clang system_header
 
-typedef struct __sFILE {
+typedef struct _FILE {
   unsigned char *_p;
 } FILE;
 FILE *fopen(const char *restrict, const char *restrict) __asm("_" "fopen" );
diff --git a/clang/test/Analysis/Inputs/system-header-simulator-for-valist.h 
b/clang/test/Analysis/Inputs/system-header-simulator-for-valist.h
index 7299b61353d460..87688bd8b312f4 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator-for-valist.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator-for-valist.h
@@ -10,6 +10,8 @@
 #define restrict /*restrict*/
 #endif
 
+typedef struct _FILE FILE;
+
 typedef __builtin_va_list va_list;
 
 #define va_start(ap, param) __builtin_va_start(ap, param)
@@ -21,6 +23,8 @@ int vprintf (const char *restrict format, va_list arg);
 
 int vsprintf (char *restrict s, const char *restrict format, va_list arg);
 
+int vfscanf(FILE *stream, const char *format, va_list ap);
+
 int some_library_function(int n, va_list arg);
 
 // No warning from system header.
diff --git a/clang/test/Analysis/Inputs/system-header-simulator.h 
b/clang/test/Analysis/Inputs/system-header-simulator.h
index 15986984802c0e..8fd51449ecc0a4 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator.h
@@ -73,6 +73,9 @@ int ferror(FILE *stream);
 int fileno(FILE *stream);
 int fflush(FILE *str

[clang] [clang][analyzer] StreamChecker: Add more APIs, invalidate fscanf args (PR #82476)

2024-02-21 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Alejandro Álvarez Ayllón (alejandro-alvarez-sonarsource)


Changes

1. Model `getc`, `vfscanf`, `putc`, `vfprintf`.
2. `fscanf` invalidates all arguments after the format string.

Also, add tests for `ftello` and `fseeko`.

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


5 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp (+38-1) 
- (modified) 
clang/test/Analysis/Inputs/system-header-simulator-for-simple-stream.h (+1-1) 
- (modified) clang/test/Analysis/Inputs/system-header-simulator-for-valist.h 
(+4) 
- (modified) clang/test/Analysis/Inputs/system-header-simulator.h (+3) 
- (modified) clang/test/Analysis/stream.c (+128) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index a070f451694a3b..7938a0d30a91a3 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -21,6 +21,8 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
+#include "llvm/ADT/Sequence.h"
+#include "llvm/ADT/SmallVector.h"
 #include 
 #include 
 
@@ -171,7 +173,7 @@ using FnCheck = std::function;
 
 using ArgNoTy = unsigned int;
-static const ArgNoTy ArgNone = std::numeric_limits::max();
+const ArgNoTy ArgNone = std::numeric_limits::max();
 
 struct FnDescription {
   FnCheck PreFn;
@@ -179,6 +181,26 @@ struct FnDescription {
   ArgNoTy StreamArgNo;
 };
 
+[[nodiscard]] ProgramStateRef
+escapeArgsAfterIndex(ProgramStateRef State, CheckerContext &C,
+ const CallEvent &Call, unsigned FirstEscapingArgIndex) {
+  const auto *CE = Call.getOriginExpr();
+  assert(CE);
+
+  if (Call.getNumArgs() <= FirstEscapingArgIndex)
+return State;
+
+  SmallVector EscapingArgs;
+  EscapingArgs.reserve(Call.getNumArgs() - FirstEscapingArgIndex);
+  for (auto EscArgIdx :
+   llvm::seq(FirstEscapingArgIndex, Call.getNumArgs()))
+EscapingArgs.push_back(Call.getArgSVal(EscArgIdx));
+  State = State->invalidateRegions(EscapingArgs, CE, C.blockCount(),
+   C.getLocationContext(),
+   /*CausesPointerEscape=*/false);
+  return State;
+}
+
 /// Get the value of the stream argument out of the passed call event.
 /// The call should contain a function that is described by Desc.
 SVal getStreamArg(const FnDescription *Desc, const CallEvent &Call) {
@@ -396,6 +418,18 @@ class StreamChecker : public Checker FnTestDescriptions = {
@@ -997,6 +1031,9 @@ void StreamChecker::evalFscanf(const FnDescription *Desc, 
const CallEvent &Call,
   if (!E.Init(Desc, Call, C, State))
 return;
 
+  // The pointers passed to fscanf escape and get invalidated.
+  State = escapeArgsAfterIndex(State, C, Call, /*FirstEscapingArgIndex=*/2);
+
   // Add the success state.
   // In this context "success" means there is not an EOF or other read error
   // before any item is matched in 'fscanf'. But there may be match failure,
diff --git 
a/clang/test/Analysis/Inputs/system-header-simulator-for-simple-stream.h 
b/clang/test/Analysis/Inputs/system-header-simulator-for-simple-stream.h
index 098a2208fecbe9..c26d3582149120 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator-for-simple-stream.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator-for-simple-stream.h
@@ -5,7 +5,7 @@
 // suppressed.
 #pragma clang system_header
 
-typedef struct __sFILE {
+typedef struct _FILE {
   unsigned char *_p;
 } FILE;
 FILE *fopen(const char *restrict, const char *restrict) __asm("_" "fopen" );
diff --git a/clang/test/Analysis/Inputs/system-header-simulator-for-valist.h 
b/clang/test/Analysis/Inputs/system-header-simulator-for-valist.h
index 7299b61353d460..87688bd8b312f4 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator-for-valist.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator-for-valist.h
@@ -10,6 +10,8 @@
 #define restrict /*restrict*/
 #endif
 
+typedef struct _FILE FILE;
+
 typedef __builtin_va_list va_list;
 
 #define va_start(ap, param) __builtin_va_start(ap, param)
@@ -21,6 +23,8 @@ int vprintf (const char *restrict format, va_list arg);
 
 int vsprintf (char *restrict s, const char *restrict format, va_list arg);
 
+int vfscanf(FILE *stream, const char *format, va_list ap);
+
 int some_library_function(int n, va_list arg);
 
 // No warning from system header.
diff --git a/clang/test/Analysis/Inputs/system-header-simulator.h 
b/clang/test/Analysis/Inputs/system-header-simulator.h
index 15986984802c0e..8fd51449ecc0a4 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator.h
@@ -73,6 +73,9 @@ int ferror(FILE *stream);
 int fileno(FILE *stream);
 int fflush(FILE *stream);
 
+
+int get

[clang] [llvm] [AArch64] Added feature dependencies for SME2p1 to TargetParser (PR #81860)

2024-02-21 Thread via cfe-commits

https://github.com/Lukacma updated 
https://github.com/llvm/llvm-project/pull/81860

>From 2e3d7fbcf759230cf83487c60aabca5104a7f379 Mon Sep 17 00:00:00 2001
From: Marian Lukac 
Date: Thu, 15 Feb 2024 10:17:20 +
Subject: [PATCH 1/2] [AArch64] Added feature dependencies for SME2p1 to
 TargetParser

---
 llvm/include/llvm/TargetParser/AArch64TargetParser.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/llvm/include/llvm/TargetParser/AArch64TargetParser.h 
b/llvm/include/llvm/TargetParser/AArch64TargetParser.h
index ed9944bcef23d0..7376ac98a2b095 100644
--- a/llvm/include/llvm/TargetParser/AArch64TargetParser.h
+++ b/llvm/include/llvm/TargetParser/AArch64TargetParser.h
@@ -273,7 +273,7 @@ inline constexpr ExtensionInfo Extensions[] = {
 {"sme-i16i64", AArch64::AEK_SMEI16I64, "+sme-i16i64", "-sme-i16i64", 
FEAT_SME_I64, "+sme,+sme-i16i64,+bf16", 570},
 {"sme", AArch64::AEK_SME, "+sme", "-sme", FEAT_SME, "+sme,+bf16", 430},
 {"sme2", AArch64::AEK_SME2, "+sme2", "-sme2", FEAT_SME2, 
"+sme2,+sme,+bf16", 580},
-{"sme2p1", AArch64::AEK_SME2p1, "+sme2p1", "-sme2p1", FEAT_INIT, "", 0},
+{"sme2p1", AArch64::AEK_SME2p1, "+sme2p1", "-sme2p1", FEAT_INIT, 
"+sme2p1,+sme2,+sme,+bf16", 0},
 {"ssbs", AArch64::AEK_SSBS, "+ssbs", "-ssbs", FEAT_SSBS, "", 490},
 {"ssbs2", AArch64::AEK_NONE, {}, {}, FEAT_SSBS2, "+ssbs", 500},
 {"sve-bf16", AArch64::AEK_NONE, {}, {}, FEAT_SVE_BF16, 
"+sve,+bf16,+fullfp16,+fp-armv8,+neon", 320},

>From b35e11cae9a3286d276a521e4170099dcb1186df Mon Sep 17 00:00:00 2001
From: Marian Lukac 
Date: Tue, 20 Feb 2024 14:39:51 +
Subject: [PATCH 2/2] [AArch64] Add testcase for the bugfix

---
 clang/test/Sema/aarch64-sme2p1-diagnostics.c | 10 ++
 1 file changed, 10 insertions(+)
 create mode 100644 clang/test/Sema/aarch64-sme2p1-diagnostics.c

diff --git a/clang/test/Sema/aarch64-sme2p1-diagnostics.c 
b/clang/test/Sema/aarch64-sme2p1-diagnostics.c
new file mode 100644
index 00..a0adb040385815
--- /dev/null
+++ b/clang/test/Sema/aarch64-sme2p1-diagnostics.c
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu  -target-feature +sme2p1 
-fsyntax-only -verify %s
+
+// REQUIRES: aarch64-registered-target
+#include "arm_sme.h"
+
+svuint8x2_t  test_sme2p1(svuint8x2_t  x) {
+  // expected-no-diagnostics
+  return x;
+}
+

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


[clang] [clang] Preserve found-decl when constructing VarTemplateIds (PR #82265)

2024-02-21 Thread Nikita Popov via cfe-commits

nikic wrote:

I think this commit is responsible for the ClangIncludeCleaner test failure.

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


[clang] 3533fe7 - Revert "[clang] Preserve found-decl when constructing VarTemplateIds (#82265)"

2024-02-21 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2024-02-21T11:15:42+01:00
New Revision: 3533fe783df4b417f16077edb70099010d2d7eef

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

LOG: Revert "[clang] Preserve found-decl when constructing VarTemplateIds 
(#82265)"

This reverts commit 50373506d570f3db1e1af7c13d46409736452f3a. Broke
include-cleaner tests

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaTemplate.cpp
clang/test/AST/ast-dump-using.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 23e1a623a20d15..89215bf3d1c69a 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -8538,7 +8538,7 @@ class Sema final {
   /// if the arguments are dependent.
   ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
 const DeclarationNameInfo &NameInfo,
-VarTemplateDecl *Template, NamedDecl *FoundD,
+VarTemplateDecl *Template,
 SourceLocation TemplateLoc,
 const TemplateArgumentListInfo *TemplateArgs);
 

diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 7d3d665194add1..1a975a8d0a0df5 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -4958,10 +4958,11 @@ Sema::CheckVarTemplateId(VarTemplateDecl *Template, 
SourceLocation TemplateLoc,
   return Decl;
 }
 
-ExprResult Sema::CheckVarTemplateId(
-const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
-VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
-const TemplateArgumentListInfo *TemplateArgs) {
+ExprResult
+Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
+ const DeclarationNameInfo &NameInfo,
+ VarTemplateDecl *Template, SourceLocation TemplateLoc,
+ const TemplateArgumentListInfo *TemplateArgs) {
 
   DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, 
NameInfo.getLoc(),
*TemplateArgs);
@@ -4977,7 +4978,8 @@ ExprResult Sema::CheckVarTemplateId(
NameInfo.getLoc());
 
   // Build an ordinary singleton decl ref.
-  return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
+  return BuildDeclarationNameExpr(SS, NameInfo, Var,
+  /*FoundD=*/nullptr, TemplateArgs);
 }
 
 void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
@@ -5064,9 +5066,9 @@ ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec 
&SS,
   bool KnownDependent = false;
   // In C++1y, check variable template ids.
   if (R.getAsSingle()) {
-ExprResult Res = CheckVarTemplateId(
-SS, R.getLookupNameInfo(), R.getAsSingle(),
-R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
+ExprResult Res = CheckVarTemplateId(SS, R.getLookupNameInfo(),
+R.getAsSingle(),
+TemplateKWLoc, TemplateArgs);
 if (Res.isInvalid() || Res.isUsable())
   return Res;
 // Result is dependent. Carry on to build an UnresolvedLookupEpxr.

diff  --git a/clang/test/AST/ast-dump-using.cpp 
b/clang/test/AST/ast-dump-using.cpp
index 8e5c60d3aabf4a..5a4e910ffb8654 100644
--- a/clang/test/AST/ast-dump-using.cpp
+++ b/clang/test/AST/ast-dump-using.cpp
@@ -2,7 +2,6 @@
 
 namespace a {
 struct S;
-template  T x = {};
 }
 namespace b {
 using a::S;
@@ -22,10 +21,4 @@ typedef S e; // check the same UsingType is reused.
 // CHECK-NEXT:   `-UsingType [[TYPE_ADDR]] 'a::S' sugar
 // CHECK-NEXT: |-UsingShadow [[SHADOW_ADDR]] 'S'
 // CHECK-NEXT: `-RecordType {{.*}} 'a::S'
-using a::x;
-
-void foo() {
-  x = 3;
-  // CHECK: DeclRefExpr {{.*}} 'x' {{.*}} (UsingShadow {{.*}} 'x')
-}
 }



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


[clang] [llvm] MIPS/clang: Fix asm constraint for softfloat (PR #79116)

2024-02-21 Thread YunQiang Su via cfe-commits

https://github.com/wzssyqa updated 
https://github.com/llvm/llvm-project/pull/79116

>From 0ea3b2be9d364a042c7e7114b0f72fc3c144d2a0 Mon Sep 17 00:00:00 2001
From: YunQiang Su 
Date: Tue, 23 Jan 2024 18:14:48 +0800
Subject: [PATCH] MIPS/clang: Fix asm constraint for softfloat

This include 2 fixes:
1. Disallow 'f' for softfloat.
2. Allow 'r' for softfloat.

Currently, 'f' is accpeted by clang, then
LLVM meet an internal error.

'r' is rejected by LLVM by:
  couldn't allocate input reg for constraint 'r'

Fixes: #64241
---
 clang/lib/Basic/Targets/Mips.h|  3 +++
 .../CodeGen/Mips/inline-asm-constraints.c | 18 +
 clang/test/Sema/inline-asm-validate-mips.c|  8 ++
 llvm/lib/Target/Mips/MipsISelLowering.cpp | 10 +---
 .../Mips/inlineasm-constraints-softfloat.ll   | 25 +++
 5 files changed, 61 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/CodeGen/Mips/inline-asm-constraints.c
 create mode 100644 clang/test/Sema/inline-asm-validate-mips.c
 create mode 100644 llvm/test/CodeGen/Mips/inlineasm-constraints-softfloat.ll

diff --git a/clang/lib/Basic/Targets/Mips.h b/clang/lib/Basic/Targets/Mips.h
index f46b95abfd75c7..2b8ad6645e605f 100644
--- a/clang/lib/Basic/Targets/Mips.h
+++ b/clang/lib/Basic/Targets/Mips.h
@@ -238,6 +238,9 @@ class LLVM_LIBRARY_VISIBILITY MipsTargetInfo : public 
TargetInfo {
 case 'd': // Equivalent to "r" unless generating MIPS16 code.
 case 'y': // Equivalent to "r", backward compatibility only.
 case 'f': // floating-point registers.
+  if (*Name == 'f' && FloatABI == SoftFloat)
+return false;
+  LLVM_FALLTHROUGH;
 case 'c': // $25 for indirect jumps
 case 'l': // lo register
 case 'x': // hilo register pair
diff --git a/clang/test/CodeGen/Mips/inline-asm-constraints.c 
b/clang/test/CodeGen/Mips/inline-asm-constraints.c
new file mode 100644
index 00..0a4cb0b34570e6
--- /dev/null
+++ b/clang/test/CodeGen/Mips/inline-asm-constraints.c
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 %s -triple mips -target-feature +soft-float \
+// RUN:-DSOFT_FLOAT_CONSTRAINT_R \
+// RUN:-DFLOAT=float -emit-llvm -o - \
+// RUN:  | FileCheck %s --check-prefix SOFT_FLOAT_CONSTRAINT_R_SINGLE
+
+// RUN: %clang_cc1 %s -triple mips -target-feature +soft-float \
+// RUN:-DSOFT_FLOAT_CONSTRAINT_R \
+// RUN:-DFLOAT=double -emit-llvm -o - \
+// RUN:  | FileCheck %s --check-prefix SOFT_FLOAT_CONSTRAINT_R_DOUBLE
+
+#ifdef SOFT_FLOAT_CONSTRAINT_R
+// SOFT_FLOAT_CONSTRAINT_R_SINGLE: call void asm sideeffect "", 
"r,~{$1}"(float %2) #1, !srcloc !2
+// SOFT_FLOAT_CONSTRAINT_R_DOUBLE: call void asm sideeffect "", 
"r,~{$1}"(double %2) #1, !srcloc !2
+void read_float(FLOAT* p) {
+FLOAT result = *p;
+__asm__("" ::"r"(result));
+}
+#endif // SOFT_FLOAT_CONSTRAINT_R
diff --git a/clang/test/Sema/inline-asm-validate-mips.c 
b/clang/test/Sema/inline-asm-validate-mips.c
new file mode 100644
index 00..5a123cc5fa79c3
--- /dev/null
+++ b/clang/test/Sema/inline-asm-validate-mips.c
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -triple mips -target-feature +soft-float 
-DSOFT_FLOAT_NO_CONSTRAINT_F -fsyntax-only -verify %s
+
+#ifdef SOFT_FLOAT_NO_CONSTRAINT_F
+void read_float(float p) {
+float result = p;
+__asm__("" ::"f"(result)); // expected-error{{invalid input constraint 'f' 
in asm}}
+}
+#endif // SOFT_FLOAT_NO_CONSTRAINT_F
diff --git a/llvm/lib/Target/Mips/MipsISelLowering.cpp 
b/llvm/lib/Target/Mips/MipsISelLowering.cpp
index b2812f87914df7..97e830cec27cad 100644
--- a/llvm/lib/Target/Mips/MipsISelLowering.cpp
+++ b/llvm/lib/Target/Mips/MipsISelLowering.cpp
@@ -4128,14 +4128,18 @@ MipsTargetLowering::getRegForInlineAsmConstraint(const 
TargetRegisterInfo *TRI,
 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
 case 'y': // Same as 'r'. Exists for compatibility.
 case 'r':
-  if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8 || VT == MVT::i1) {
+  if ((VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8 ||
+   VT == MVT::i1) ||
+  (VT == MVT::f32 && Subtarget.useSoftFloat())) {
 if (Subtarget.inMips16Mode())
   return std::make_pair(0U, &Mips::CPU16RegsRegClass);
 return std::make_pair(0U, &Mips::GPR32RegClass);
   }
-  if (VT == MVT::i64 && !Subtarget.isGP64bit())
+  if ((VT == MVT::i64 || (VT == MVT::f64 && Subtarget.useSoftFloat())) &&
+  !Subtarget.isGP64bit())
 return std::make_pair(0U, &Mips::GPR32RegClass);
-  if (VT == MVT::i64 && Subtarget.isGP64bit())
+  if ((VT == MVT::i64 || (VT == MVT::f64 && Subtarget.useSoftFloat())) &&
+  Subtarget.isGP64bit())
 return std::make_pair(0U, &Mips::GPR64RegClass);
   // This will generate an error message
   return std::make_pair(0U, nullptr);
diff --git a/llvm/test/CodeGen/Mips/inlineasm-constraints-softfloat.ll 
b/llvm/test/CodeGen/Mips/i

[clang] [llvm] MIPS/clang: Fix asm constraint for softfloat (PR #79116)

2024-02-21 Thread YunQiang Su via cfe-commits


@@ -0,0 +1,25 @@
+; RUN: llc  -march=mips < %s | FileCheck %s --check-prefix=MIPS32
+; RUN: llc  -march=mips64 < %s | FileCheck %s --check-prefix=MIPS64
+
+define dso_local void @read_double(double* nocapture noundef readonly %0) 
local_unnamed_addr #0 {

wzssyqa wrote:

Thanks.

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


[clang] [llvm] MIPS/clang: Fix asm constraint for softfloat (PR #79116)

2024-02-21 Thread YunQiang Su via cfe-commits


@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -triple mips -target-feature +soft-float 
-DSOFT_FLOAT_NO_CONSTRAINT_F -fsyntax-only -verify %s
+
+#ifdef SOFT_FLOAT_NO_CONSTRAINT_F
+void read_float(float* p) {

wzssyqa wrote:

Oh, yes. we can use `float p` here.

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


[clang] [llvm] MIPS/clang: Fix asm constraint for softfloat (PR #79116)

2024-02-21 Thread YunQiang Su via cfe-commits

https://github.com/wzssyqa updated 
https://github.com/llvm/llvm-project/pull/79116

>From 838394878054831066e563fa243665ba6d68d824 Mon Sep 17 00:00:00 2001
From: YunQiang Su 
Date: Tue, 23 Jan 2024 18:14:48 +0800
Subject: [PATCH] MIPS/clang: Fix asm constraint for softfloat

This include 2 fixes:
1. Disallow 'f' for softfloat.
2. Allow 'r' for softfloat.

Currently, 'f' is accpeted by clang, then
LLVM meet an internal error.

'r' is rejected by LLVM by:
  couldn't allocate input reg for constraint 'r'

Fixes: #64241
---
 clang/lib/Basic/Targets/Mips.h|  3 +++
 .../CodeGen/Mips/inline-asm-constraints.c | 18 +
 clang/test/Sema/inline-asm-validate-mips.c|  8 ++
 llvm/lib/Target/Mips/MipsISelLowering.cpp | 10 +---
 .../Mips/inlineasm-constraints-softfloat.ll   | 25 +++
 5 files changed, 61 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/CodeGen/Mips/inline-asm-constraints.c
 create mode 100644 clang/test/Sema/inline-asm-validate-mips.c
 create mode 100644 llvm/test/CodeGen/Mips/inlineasm-constraints-softfloat.ll

diff --git a/clang/lib/Basic/Targets/Mips.h b/clang/lib/Basic/Targets/Mips.h
index f46b95abfd75c7..2b8ad6645e605f 100644
--- a/clang/lib/Basic/Targets/Mips.h
+++ b/clang/lib/Basic/Targets/Mips.h
@@ -238,6 +238,9 @@ class LLVM_LIBRARY_VISIBILITY MipsTargetInfo : public 
TargetInfo {
 case 'd': // Equivalent to "r" unless generating MIPS16 code.
 case 'y': // Equivalent to "r", backward compatibility only.
 case 'f': // floating-point registers.
+  if (*Name == 'f' && FloatABI == SoftFloat)
+return false;
+  LLVM_FALLTHROUGH;
 case 'c': // $25 for indirect jumps
 case 'l': // lo register
 case 'x': // hilo register pair
diff --git a/clang/test/CodeGen/Mips/inline-asm-constraints.c 
b/clang/test/CodeGen/Mips/inline-asm-constraints.c
new file mode 100644
index 00..0a4cb0b34570e6
--- /dev/null
+++ b/clang/test/CodeGen/Mips/inline-asm-constraints.c
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 %s -triple mips -target-feature +soft-float \
+// RUN:-DSOFT_FLOAT_CONSTRAINT_R \
+// RUN:-DFLOAT=float -emit-llvm -o - \
+// RUN:  | FileCheck %s --check-prefix SOFT_FLOAT_CONSTRAINT_R_SINGLE
+
+// RUN: %clang_cc1 %s -triple mips -target-feature +soft-float \
+// RUN:-DSOFT_FLOAT_CONSTRAINT_R \
+// RUN:-DFLOAT=double -emit-llvm -o - \
+// RUN:  | FileCheck %s --check-prefix SOFT_FLOAT_CONSTRAINT_R_DOUBLE
+
+#ifdef SOFT_FLOAT_CONSTRAINT_R
+// SOFT_FLOAT_CONSTRAINT_R_SINGLE: call void asm sideeffect "", 
"r,~{$1}"(float %2) #1, !srcloc !2
+// SOFT_FLOAT_CONSTRAINT_R_DOUBLE: call void asm sideeffect "", 
"r,~{$1}"(double %2) #1, !srcloc !2
+void read_float(FLOAT* p) {
+FLOAT result = *p;
+__asm__("" ::"r"(result));
+}
+#endif // SOFT_FLOAT_CONSTRAINT_R
diff --git a/clang/test/Sema/inline-asm-validate-mips.c 
b/clang/test/Sema/inline-asm-validate-mips.c
new file mode 100644
index 00..5a123cc5fa79c3
--- /dev/null
+++ b/clang/test/Sema/inline-asm-validate-mips.c
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -triple mips -target-feature +soft-float 
-DSOFT_FLOAT_NO_CONSTRAINT_F -fsyntax-only -verify %s
+
+#ifdef SOFT_FLOAT_NO_CONSTRAINT_F
+void read_float(float p) {
+float result = p;
+__asm__("" ::"f"(result)); // expected-error{{invalid input constraint 'f' 
in asm}}
+}
+#endif // SOFT_FLOAT_NO_CONSTRAINT_F
diff --git a/llvm/lib/Target/Mips/MipsISelLowering.cpp 
b/llvm/lib/Target/Mips/MipsISelLowering.cpp
index b2812f87914df7..97e830cec27cad 100644
--- a/llvm/lib/Target/Mips/MipsISelLowering.cpp
+++ b/llvm/lib/Target/Mips/MipsISelLowering.cpp
@@ -4128,14 +4128,18 @@ MipsTargetLowering::getRegForInlineAsmConstraint(const 
TargetRegisterInfo *TRI,
 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
 case 'y': // Same as 'r'. Exists for compatibility.
 case 'r':
-  if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8 || VT == MVT::i1) {
+  if ((VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8 ||
+   VT == MVT::i1) ||
+  (VT == MVT::f32 && Subtarget.useSoftFloat())) {
 if (Subtarget.inMips16Mode())
   return std::make_pair(0U, &Mips::CPU16RegsRegClass);
 return std::make_pair(0U, &Mips::GPR32RegClass);
   }
-  if (VT == MVT::i64 && !Subtarget.isGP64bit())
+  if ((VT == MVT::i64 || (VT == MVT::f64 && Subtarget.useSoftFloat())) &&
+  !Subtarget.isGP64bit())
 return std::make_pair(0U, &Mips::GPR32RegClass);
-  if (VT == MVT::i64 && Subtarget.isGP64bit())
+  if ((VT == MVT::i64 || (VT == MVT::f64 && Subtarget.useSoftFloat())) &&
+  Subtarget.isGP64bit())
 return std::make_pair(0U, &Mips::GPR64RegClass);
   // This will generate an error message
   return std::make_pair(0U, nullptr);
diff --git a/llvm/test/CodeGen/Mips/inlineasm-constraints-softfloat.ll 
b/llvm/test/CodeGen/Mips/i

[clang] [AArch64][SME2] Refactor arm_sme.td into multiclasses (PR #78169)

2024-02-21 Thread Sam Tebbs via cfe-commits

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


https://github.com/llvm/llvm-project/pull/78169
___
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-21 Thread Vikram Hegde via cfe-commits


@@ -178,17 +181,29 @@ RValue 
CodeGenFunction::EmitNVPTXDevicePrintfCallExpr(const CallExpr *E) {
   E, this, GetVprintfDeclaration(CGM.getModule()), false);
 }
 
+// Deterimines if an argument is a string
+static bool isString(const clang::Type *argXTy) {

vikramRH wrote:

I have removed this, addrspace cast is done during arg processing.

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][analyzer] StreamChecker: Add more APIs, invalidate fscanf args (PR #82476)

2024-02-21 Thread Balázs Kéri via cfe-commits

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


[clang] [llvm] [AArch64] Added feature dependencies for SME2p1 to TargetParser (PR #81860)

2024-02-21 Thread via cfe-commits

https://github.com/Lukacma updated 
https://github.com/llvm/llvm-project/pull/81860

>From 2e3d7fbcf759230cf83487c60aabca5104a7f379 Mon Sep 17 00:00:00 2001
From: Marian Lukac 
Date: Thu, 15 Feb 2024 10:17:20 +
Subject: [PATCH 1/2] [AArch64] Added feature dependencies for SME2p1 to
 TargetParser

---
 llvm/include/llvm/TargetParser/AArch64TargetParser.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/llvm/include/llvm/TargetParser/AArch64TargetParser.h 
b/llvm/include/llvm/TargetParser/AArch64TargetParser.h
index ed9944bcef23d0..7376ac98a2b095 100644
--- a/llvm/include/llvm/TargetParser/AArch64TargetParser.h
+++ b/llvm/include/llvm/TargetParser/AArch64TargetParser.h
@@ -273,7 +273,7 @@ inline constexpr ExtensionInfo Extensions[] = {
 {"sme-i16i64", AArch64::AEK_SMEI16I64, "+sme-i16i64", "-sme-i16i64", 
FEAT_SME_I64, "+sme,+sme-i16i64,+bf16", 570},
 {"sme", AArch64::AEK_SME, "+sme", "-sme", FEAT_SME, "+sme,+bf16", 430},
 {"sme2", AArch64::AEK_SME2, "+sme2", "-sme2", FEAT_SME2, 
"+sme2,+sme,+bf16", 580},
-{"sme2p1", AArch64::AEK_SME2p1, "+sme2p1", "-sme2p1", FEAT_INIT, "", 0},
+{"sme2p1", AArch64::AEK_SME2p1, "+sme2p1", "-sme2p1", FEAT_INIT, 
"+sme2p1,+sme2,+sme,+bf16", 0},
 {"ssbs", AArch64::AEK_SSBS, "+ssbs", "-ssbs", FEAT_SSBS, "", 490},
 {"ssbs2", AArch64::AEK_NONE, {}, {}, FEAT_SSBS2, "+ssbs", 500},
 {"sve-bf16", AArch64::AEK_NONE, {}, {}, FEAT_SVE_BF16, 
"+sve,+bf16,+fullfp16,+fp-armv8,+neon", 320},

>From b35e11cae9a3286d276a521e4170099dcb1186df Mon Sep 17 00:00:00 2001
From: Marian Lukac 
Date: Tue, 20 Feb 2024 14:39:51 +
Subject: [PATCH 2/2] [AArch64] Add testcase for the bugfix

---
 clang/test/Sema/aarch64-sme2p1-diagnostics.c | 10 ++
 1 file changed, 10 insertions(+)
 create mode 100644 clang/test/Sema/aarch64-sme2p1-diagnostics.c

diff --git a/clang/test/Sema/aarch64-sme2p1-diagnostics.c 
b/clang/test/Sema/aarch64-sme2p1-diagnostics.c
new file mode 100644
index 00..a0adb040385815
--- /dev/null
+++ b/clang/test/Sema/aarch64-sme2p1-diagnostics.c
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu  -target-feature +sme2p1 
-fsyntax-only -verify %s
+
+// REQUIRES: aarch64-registered-target
+#include "arm_sme.h"
+
+svuint8x2_t  test_sme2p1(svuint8x2_t  x) {
+  // expected-no-diagnostics
+  return x;
+}
+

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


[clang] [clang][analyzer] StreamChecker: Add more APIs, invalidate fscanf args (PR #82476)

2024-02-21 Thread Balázs Kéri via cfe-commits

https://github.com/balazske commented:

How does this relate to the other PR #79470 (why comes this new patch when 
there is another for the same problem)?
I think it is better to first commit #79470, then add remaining functions 
`getc`, `putc`, `vfscanf`, `vfprintf`. These should be added anyway in a 
separate change because it is less related to invalidation.

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


[clang] [clang][analyzer] StreamChecker: Add more APIs, invalidate fscanf args (PR #82476)

2024-02-21 Thread Balázs Kéri via cfe-commits

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


[clang] [clang][analyzer] StreamChecker: Add more APIs, invalidate fscanf args (PR #82476)

2024-02-21 Thread via cfe-commits

https://github.com/NagyDonat commented:

Looks good overall, I only have a few small suggestions/questions.

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


[clang] [clang][analyzer] StreamChecker: Add more APIs, invalidate fscanf args (PR #82476)

2024-02-21 Thread via cfe-commits


@@ -171,14 +173,34 @@ using FnCheck = std::function;
 
 using ArgNoTy = unsigned int;
-static const ArgNoTy ArgNone = std::numeric_limits::max();
+const ArgNoTy ArgNone = std::numeric_limits::max();
 
 struct FnDescription {
   FnCheck PreFn;
   FnCheck EvalFn;
   ArgNoTy StreamArgNo;
 };
 
+[[nodiscard]] ProgramStateRef
+escapeArgsAfterIndex(ProgramStateRef State, CheckerContext &C,
+ const CallEvent &Call, unsigned FirstEscapingArgIndex) {

NagyDonat wrote:

I dislike the inconsistency between the names `escapeArgsAfterIndex` and 
`FirstEscapingArgIndex`: the name of the function strongly suggests that its 
argument would be the index of the _last non-escaping_ argument. Consider 
renaming the function to `escapeArgsStartingFromIndex` (which is admittedly 
awkward but at least not misleading) or something similar.

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


[clang] [clang][analyzer] StreamChecker: Add more APIs, invalidate fscanf args (PR #82476)

2024-02-21 Thread via cfe-commits


@@ -339,3 +363,107 @@ void fflush_on_open_failed_stream(void) {
   }
   fclose(F);
 }
+
+void test_fscanf_eof() {
+  FILE *F1 = tmpfile();
+  if (!F1)
+return;
+
+  int a;
+  unsigned b;
+  int ret = fscanf(F1, "%d %u", &a, &b);
+  char c = fgetc(F1); // expected-warning {{Read function called when stream 
is in EOF state. Function has no effect}}
+  // expected-warning@-1 {{File position of the stream might be 
'indeterminate' after a failed operation. Can cause undefined behavior}}

NagyDonat wrote:

Do I understand it correctly that here the checker would print a note 
explaining that it assumes that `fscanf` reaches the end-of-file? Without that 
this checker behavior would be difficult to understand.

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


[clang] [clang][analyzer] StreamChecker: Add more APIs, invalidate fscanf args (PR #82476)

2024-02-21 Thread via cfe-commits


@@ -171,14 +173,34 @@ using FnCheck = std::function;
 
 using ArgNoTy = unsigned int;
-static const ArgNoTy ArgNone = std::numeric_limits::max();
+const ArgNoTy ArgNone = std::numeric_limits::max();

NagyDonat wrote:

Why is this change incorporated in this commit?

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


[clang] [clang][analyzer] StreamChecker: Add more APIs, invalidate fscanf args (PR #82476)

2024-02-21 Thread via cfe-commits

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


[clang] [clang][analyzer] StreamChecker: Add more APIs, invalidate fscanf args (PR #82476)

2024-02-21 Thread Balázs Kéri via cfe-commits


@@ -396,6 +418,18 @@ class StreamChecker : public Checkerhttps://github.com/llvm/llvm-project/pull/82476
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] StreamChecker: Add more APIs, invalidate fscanf args (PR #82476)

2024-02-21 Thread Balázs Kéri via cfe-commits


@@ -396,6 +418,18 @@ class StreamChecker : public Checkerhttps://github.com/llvm/llvm-project/pull/82476
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] StreamChecker: Add more APIs, invalidate fscanf args (PR #82476)

2024-02-21 Thread via cfe-commits

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


[clang] [clang-tools-extra] [flang] [lld] [llvm] [flang][clang] Add Visibility specific help text for options (PR #81869)

2024-02-21 Thread David Spickett via cfe-commits

https://github.com/DavidSpickett updated 
https://github.com/llvm/llvm-project/pull/81869

>From a996499580066213c3437cbb96735b7404291c3d Mon Sep 17 00:00:00 2001
From: David Spickett 
Date: Thu, 15 Feb 2024 09:52:22 +
Subject: [PATCH 1/3] [flang][clang] Add Visibility specific help text for
 options

And use it to print the correct default OpenMP version for flang.

This change adds an optional HelpTextForVisibility to options.
This allows you to change the help text (shown in documentation
and --help) for one specific visibility.

It could be generalised to a list, but we only need to pick out
flang right now so I've kept it simple but not so simple that it's
"if flang else".

For example the OpenMP option will show one default value for
Clang and another for Flang. Clang will use the existing HelpText
string.

I have not applied this to group descriptions just because
I don't know of one that needs changing. It could easily be
enabled for those too if needed. There are minor changes to them
just to get it all to compile.

This approach of storing many help strings per option in the 1
driver library seemed perferrable to making a whole new library
for Flang (even if that would mostly be including stuff from Clang).
---
 clang/include/clang/Driver/Options.td |  5 ++-
 clang/lib/Frontend/CompilerInvocation.cpp | 16 
 .../utils/TableGen/ClangOptionDocEmitter.cpp  | 21 +-
 flang/test/Driver/driver-help-hidden.f90  |  2 +-
 flang/test/Driver/driver-help.f90 |  2 +-
 lld/MachO/DriverUtils.cpp | 20 ++---
 lld/MinGW/Driver.cpp  | 20 ++---
 lld/wasm/Driver.cpp   | 20 ++---
 llvm/include/llvm/Option/OptParser.td | 10 +
 llvm/include/llvm/Option/OptTable.h   | 41 +--
 llvm/lib/Option/OptTable.cpp  | 14 ---
 .../Option/OptionMarshallingTest.cpp  |  6 +--
 llvm/utils/TableGen/OptParserEmitter.cpp  | 16 
 13 files changed, 143 insertions(+), 50 deletions(-)

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 53f23f9abb4c96..17004c66841e87 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3391,7 +3391,10 @@ def fno_openmp : Flag<["-"], "fno-openmp">, 
Group,
 def fopenmp_version_EQ : Joined<["-"], "fopenmp-version=">, Group,
   Flags<[NoArgumentUnused]>,
   Visibility<[ClangOption, CC1Option, FlangOption, FC1Option]>,
-  HelpText<"Set OpenMP version (e.g. 45 for OpenMP 4.5, 51 for OpenMP 5.1). 
Default value is 51 for Clang">;
+  HelpText<"Set OpenMP version (e.g. 45 for OpenMP 4.5, 51 for OpenMP 5.1). 
Default value is 51 for Clang">,
+  HelpForVisibility>;
 defm openmp_extensions: BoolFOption<"openmp-extensions",
   LangOpts<"OpenMPExtensions">, DefaultTrue,
   PosFlag(R->getValueInit("HelpTextForVisibility"))) {
+const Record *VisibilityHelp = R->getValueAsDef("HelpTextForVisibility");
+std::string VisibilityStr =
+VisibilityHelp->getValue("Visibility")->getValue()->getAsString();
+
+for (StringRef Mask : DocInfo->getValueAsListOfStrings("VisibilityMask")) {
+  if (VisibilityStr == Mask) {
+Description = escapeRST(VisibilityHelp->getValueAsString("Text"));
+break;
+  }
+}
+  }
+
+  // If there's not a program specific string, use the default one.
+  if (Description.empty())
+Description = getRSTStringWithTextFallback(R, "DocBrief", "HelpText");
 
   if (!isa(R->getValueInit("Values"))) {
 if (!Description.empty() && Description.back() != '.')
diff --git a/flang/test/Driver/driver-help-hidden.f90 
b/flang/test/Driver/driver-help-hidden.f90
index 44dbac44772b29..94f2f4d1f522ec 100644
--- a/flang/test/Driver/driver-help-hidden.f90
+++ b/flang/test/Driver/driver-help-hidden.f90
@@ -83,7 +83,7 @@
 ! CHECK-NEXT: -fopenmp-targets=
 ! CHECK-NEXT: Specify comma-separated list of triples 
OpenMP offloading targets to be supported
 ! CHECK-NEXT: -fopenmp-version=
-! CHECK-NEXT: Set OpenMP version (e.g. 45 for OpenMP 
4.5, 51 for OpenMP 5.1). Default value is 51 for Clang
+! CHECK-NEXT: Set OpenMP version (e.g. 45 for OpenMP 
4.5, 51 for OpenMP 5.1). Default value is 11 for Flang
 ! CHECK-NEXT: -fopenmpParse OpenMP pragmas and generate 
parallel code.
 ! CHECK-NEXT: -foptimization-record-file=
 ! CHECK-NEXT: Specify the output name of the file 
containing the optimization remarks. Implies -fsave-optimization-record. On 
Darwin platforms, this cannot be used with multiple -arch  options.
diff --git a/flang/test/Driver/driver-help.f90 
b/flang/test/Driver/driver-help.f90
index b4280a454e3128..31bc67e1742482 100644
--- a/flang/test/Driver/driver-help.f90
+++ b/flang/test/Driver/driver-help.f90
@@ -69,7 +69,7 @@
 ! HELP-NEXT: -fopenmp-targets=
 ! HELP-NEXT:   

[clang] b1080e1 - [clang][Interp] Convert complex initializers to rvalues

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

Author: Timm Bäder
Date: 2024-02-21T13:09:20+01:00
New Revision: b1080e187e91576ac6d44087f072583e101f0f51

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

LOG: [clang][Interp] Convert complex initializers to rvalues

We internalle handle these via pointers, but we need to return
them as RValues in initializers.

Added: 


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

Removed: 




diff  --git a/clang/lib/AST/Interp/EvalEmitter.cpp 
b/clang/lib/AST/Interp/EvalEmitter.cpp
index d90cf1812bb774..9cae25f5c4d642 100644
--- a/clang/lib/AST/Interp/EvalEmitter.cpp
+++ b/clang/lib/AST/Interp/EvalEmitter.cpp
@@ -47,6 +47,9 @@ EvaluationResult EvalEmitter::interpretExpr(const Expr *E,
 EvaluationResult EvalEmitter::interpretDecl(const VarDecl *VD,
 bool CheckFullyInitialized) {
   this->CheckFullyInitialized = CheckFullyInitialized;
+  this->ConvertResultToRValue =
+  VD->getAnyInitializer() &&
+  (VD->getAnyInitializer()->getType()->isAnyComplexType());
   EvalResult.setSource(VD);
 
   if (!this->visitDecl(VD) && EvalResult.empty())



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


[clang] [clang-tools-extra] [flang] [lld] [llvm] [flang][clang] Add Visibility specific help text for options (PR #81869)

2024-02-21 Thread David Spickett via cfe-commits

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


[clang] [clang-tools-extra] [flang] [lld] [llvm] [flang][clang] Add Visibility specific help text for options (PR #81869)

2024-02-21 Thread David Spickett via cfe-commits


@@ -3391,7 +3391,10 @@ def fno_openmp : Flag<["-"], "fno-openmp">, 
Group,
 def fopenmp_version_EQ : Joined<["-"], "fopenmp-version=">, Group,
   Flags<[NoArgumentUnused]>,
   Visibility<[ClangOption, CC1Option, FlangOption, FC1Option]>,
-  HelpText<"Set OpenMP version (e.g. 45 for OpenMP 4.5, 51 for OpenMP 5.1). 
Default value is 51 for Clang">;
+  HelpText<"Set OpenMP version (e.g. 45 for OpenMP 4.5, 51 for OpenMP 5.1). 
Default value is 51 for Clang">,
+  HelpForVisibilityhttps://github.com/llvm/llvm-project/pull/81869
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 02e17ab - [AArch64] Added feature dependencies for SME2p1 to TargetParser (#81860)

2024-02-21 Thread via cfe-commits

Author: Lukacma
Date: 2024-02-21T12:29:28Z
New Revision: 02e17ab1b97a8c0dc22facc8c66850e5aca28b60

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

LOG: [AArch64] Added feature dependencies for SME2p1 to TargetParser (#81860)

This patches adds missing target-feature dependencies for SME2.1

Added: 
clang/test/Sema/aarch64-sme2p1-diagnostics.c

Modified: 
llvm/include/llvm/TargetParser/AArch64TargetParser.h

Removed: 




diff  --git a/clang/test/Sema/aarch64-sme2p1-diagnostics.c 
b/clang/test/Sema/aarch64-sme2p1-diagnostics.c
new file mode 100644
index 00..a0adb040385815
--- /dev/null
+++ b/clang/test/Sema/aarch64-sme2p1-diagnostics.c
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu  -target-feature +sme2p1 
-fsyntax-only -verify %s
+
+// REQUIRES: aarch64-registered-target
+#include "arm_sme.h"
+
+svuint8x2_t  test_sme2p1(svuint8x2_t  x) {
+  // expected-no-diagnostics
+  return x;
+}
+

diff  --git a/llvm/include/llvm/TargetParser/AArch64TargetParser.h 
b/llvm/include/llvm/TargetParser/AArch64TargetParser.h
index ed9944bcef23d0..7376ac98a2b095 100644
--- a/llvm/include/llvm/TargetParser/AArch64TargetParser.h
+++ b/llvm/include/llvm/TargetParser/AArch64TargetParser.h
@@ -273,7 +273,7 @@ inline constexpr ExtensionInfo Extensions[] = {
 {"sme-i16i64", AArch64::AEK_SMEI16I64, "+sme-i16i64", "-sme-i16i64", 
FEAT_SME_I64, "+sme,+sme-i16i64,+bf16", 570},
 {"sme", AArch64::AEK_SME, "+sme", "-sme", FEAT_SME, "+sme,+bf16", 430},
 {"sme2", AArch64::AEK_SME2, "+sme2", "-sme2", FEAT_SME2, 
"+sme2,+sme,+bf16", 580},
-{"sme2p1", AArch64::AEK_SME2p1, "+sme2p1", "-sme2p1", FEAT_INIT, "", 0},
+{"sme2p1", AArch64::AEK_SME2p1, "+sme2p1", "-sme2p1", FEAT_INIT, 
"+sme2p1,+sme2,+sme,+bf16", 0},
 {"ssbs", AArch64::AEK_SSBS, "+ssbs", "-ssbs", FEAT_SSBS, "", 490},
 {"ssbs2", AArch64::AEK_NONE, {}, {}, FEAT_SSBS2, "+ssbs", 500},
 {"sve-bf16", AArch64::AEK_NONE, {}, {}, FEAT_SVE_BF16, 
"+sve,+bf16,+fullfp16,+fp-armv8,+neon", 320},



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


[clang] [llvm] [AArch64] Added feature dependencies for SME2p1 to TargetParser (PR #81860)

2024-02-21 Thread via cfe-commits

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


[clang] [llvm] [AArch64] Added feature dependencies for SME2p1 to TargetParser (PR #81860)

2024-02-21 Thread via cfe-commits

github-actions[bot] wrote:



@Lukacma 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/81860
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Implement CWG1719 "Layout compatibility and cv-qualification revisited" (PR #82358)

2024-02-21 Thread via cfe-commits

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


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


[clang] [clang] Implement CWG1719 "Layout compatibility and cv-qualification revisited" (PR #82358)

2024-02-21 Thread Aaron Ballman via cfe-commits

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

LGTM!

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


[clang] [clang] [SemaCXX] Disallow deducing "this" on operator `new` and `delete` (PR #82251)

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

Rajveer100 wrote:

Considering the PR sounds good to you, yes it would be great to have it merged.

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


[clang] [clang][analyzer] StreamChecker: Add more APIs, invalidate fscanf args (PR #82476)

2024-02-21 Thread Alejandro Álvarez Ayllón via cfe-commits

alejandro-alvarez-sonarsource wrote:

> How does this relate to the other PR #79470 (why comes this new patch when 
> there is another for the same problem)? I think it is better to first commit 
> #79470, then add remaining functions `getc`, `putc`, `vfscanf`, `vfprintf`. 
> These should be added anyway in a separate change because it is less related 
> to invalidation.

I started the work on this patch before #79470 was submitted, and didn't 
double-check if someone had tackled the same in the meantime. My bad. 

I agree on waiting for that one to land and strip this one down to the new set 
of functions.

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


[clang] b5437c8 - [clang][Interp] Emit const references for Float arguments (#79753)

2024-02-21 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-02-21T14:15:39+01:00
New Revision: b5437c8ab2af277548ee59b6838e365d35a0d926

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

LOG: [clang][Interp] Emit const references for Float arguments (#79753)

The Float print type is backed by the Floating class, which in turn uses
APFloat, which might heap-allocate memory, so might be expensive to
copy.

Add an 'AsRef' bit to the ArgType tablegen class, which defines whether
we pass the argument around by copy or by reference.

Added: 


Modified: 
clang/lib/AST/Interp/Opcodes.td
clang/utils/TableGen/ClangOpcodesEmitter.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Opcodes.td b/clang/lib/AST/Interp/Opcodes.td
index f1b08944a8812e..5add723842d2b2 100644
--- a/clang/lib/AST/Interp/Opcodes.td
+++ b/clang/lib/AST/Interp/Opcodes.td
@@ -35,7 +35,7 @@ def FnPtr : Type;
 // Types transferred to the interpreter.
 
//===--===//
 
-class ArgType { string Name = ?; }
+class ArgType { string Name = ?; bit AsRef = false; }
 def ArgSint8 : ArgType { let Name = "int8_t"; }
 def ArgUint8 : ArgType { let Name = "uint8_t"; }
 def ArgSint16 : ArgType { let Name = "int16_t"; }
@@ -44,9 +44,9 @@ def ArgSint32 : ArgType { let Name = "int32_t"; }
 def ArgUint32 : ArgType { let Name = "uint32_t"; }
 def ArgSint64 : ArgType { let Name = "int64_t"; }
 def ArgUint64 : ArgType { let Name = "uint64_t"; }
-def ArgFloat : ArgType { let Name = "Floating"; }
-def ArgIntAP : ArgType { let Name = "IntegralAP"; }
-def ArgIntAPS : ArgType { let Name = "IntegralAP"; }
+def ArgIntAP : ArgType { let Name = "IntegralAP"; let AsRef = true; }
+def ArgIntAPS : ArgType { let Name = "IntegralAP"; let AsRef = true; }
+def ArgFloat : ArgType { let Name = "Floating"; let AsRef = true; }
 def ArgBool : ArgType { let Name = "bool"; }
 
 def ArgFunction : ArgType { let Name = "const Function *"; }

diff  --git a/clang/utils/TableGen/ClangOpcodesEmitter.cpp 
b/clang/utils/TableGen/ClangOpcodesEmitter.cpp
index 02d5f9512d9051..1c41301ab3aeeb 100644
--- a/clang/utils/TableGen/ClangOpcodesEmitter.cpp
+++ b/clang/utils/TableGen/ClangOpcodesEmitter.cpp
@@ -126,9 +126,15 @@ void ClangOpcodesEmitter::EmitInterp(raw_ostream &OS, 
StringRef N,
 
   // Emit calls to read arguments.
   for (size_t I = 0, N = Args.size(); I < N; ++I) {
-OS << "  auto V" << I;
+const auto *Arg = Args[I];
+bool AsRef = Arg->getValueAsBit("AsRef");
+
+if (AsRef)
+  OS << "  const auto &V" << I;
+else
+  OS << "  const auto V" << I;
 OS << " = ";
-OS << "ReadArg<" << Args[I]->getValueAsString("Name")
+OS << "ReadArg<" << Arg->getValueAsString("Name")
<< ">(S, PC);\n";
   }
 
@@ -192,8 +198,14 @@ void ClangOpcodesEmitter::EmitEmitter(raw_ostream &OS, 
StringRef N,
 
 // Emit the list of arguments.
 OS << "bool ByteCodeEmitter::emit" << ID << "(";
-for (size_t I = 0, N = Args.size(); I < N; ++I)
-  OS << Args[I]->getValueAsString("Name") << " A" << I << ", ";
+for (size_t I = 0, N = Args.size(); I < N; ++I) {
+  const auto *Arg = Args[I];
+  bool AsRef = Arg->getValueAsBit("AsRef");
+  auto Name = Arg->getValueAsString("Name");
+
+  OS << (AsRef ? "const " : " ") << Name << " " << (AsRef ? "&" : "") << 
"A"
+ << I << ", ";
+}
 OS << "const SourceInfo &L) {\n";
 
 // Emit a call to write the opcodes.
@@ -218,8 +230,14 @@ void ClangOpcodesEmitter::EmitProto(raw_ostream &OS, 
StringRef N,
   auto Args = R->getValueAsListOfDefs("Args");
   Enumerate(R, N, [&OS, &Args](ArrayRef TS, const Twine &ID) {
 OS << "bool emit" << ID << "(";
-for (auto *Arg : Args)
-  OS << Arg->getValueAsString("Name") << ", ";
+for (size_t I = 0, N = Args.size(); I < N; ++I) {
+  const auto *Arg = Args[I];
+  bool AsRef = Arg->getValueAsBit("AsRef");
+  auto Name = Arg->getValueAsString("Name");
+
+  OS << (AsRef ? "const " : " ") << Name << " " << (AsRef ? "&" : "")
+ << ", ";
+}
 OS << "const SourceInfo &);\n";
   });
 
@@ -275,8 +293,14 @@ void ClangOpcodesEmitter::EmitGroup(raw_ostream &OS, 
StringRef N,
   OS << "::" << EmitFuncName << "(";
   for (size_t I = 0, N = Types->size(); I < N; ++I)
 OS << "PrimType T" << I << ", ";
-  for (size_t I = 0, N = Args.size(); I < N; ++I)
-OS << Args[I]->getValueAsString("Name") << " A" << I << ", ";
+  for (size_t I = 0, N = Args.size(); I < N; ++I) {
+const auto *Arg = Args[I];
+bool AsRef = Arg->getValueAsBit("AsRef");
+auto Name = Arg->getValueAsString("Name");
+
+

[clang] [clang][Interp] Emit const references for Float arguments (PR #79753)

2024-02-21 Thread Timm Baeder via cfe-commits

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


[clang] [clang] Implement CWG1719 "Layout compatibility and cv-qualification revisited" (PR #82358)

2024-02-21 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/82358

>From 15d9428a47ea5d7ba3b4ffd2e766406b16d781e0 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Tue, 20 Feb 2024 16:44:04 +0300
Subject: [PATCH 1/3] [clang] Implement CWG1719 "Layout compatibility and
 cv-qualification revisited"

This patch updates our internal notion of layout-compatible, which in turn 
fixes `__is_layout_compatible` intrinsic.
---
 clang/docs/ReleaseNotes.rst|  9 ++---
 clang/lib/Sema/SemaChecking.cpp| 13 +++--
 clang/test/CXX/drs/dr17xx.cpp  | 11 +--
 clang/test/SemaCXX/type-traits.cpp | 14 +++---
 clang/www/cxx_dr_status.html   |  4 ++--
 5 files changed, 27 insertions(+), 24 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8ea4a9a5a4256c..ffdc2a2629e6e9 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -98,9 +98,8 @@ C++20 Feature Support
 
 - Implemented the `__is_layout_compatible` intrinsic to support
   `P0466R5: Layout-compatibility and Pointer-interconvertibility Traits 
`_.
-  Note: `CWG1719: Layout compatibility and cv-qualification revisited  
`_
-  and `CWG2759: [[no_unique_address] and common initial sequence 
`_
-  are not yet implemented.
+  Note: `CWG2759: [[no_unique_address] and common initial sequence 
`_
+  is not yet implemented.
 
 C++23 Feature Support
 ^
@@ -120,6 +119,10 @@ Resolutions to C++ Defect Reports
   in the template parameters, but is deduced from a previous argument.
   (`#78449: `_).
 
+- ``const`` and ``volatile`` qualifiers are now ignored when evaluating
+  layout compatibility of two types.
+  (`CWG1719: Layout compatibility and cv-qualification revisited 
`_).
+
 C Language Changes
 --
 
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index d951c0fc2732d2..e8bfb215a5b4c5 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -19124,15 +19124,16 @@ static bool isLayoutCompatible(ASTContext &C, 
QualType T1, QualType T2) {
   if (T1.isNull() || T2.isNull())
 return false;
 
-  // C++11 [basic.types] p11:
-  // If two types T1 and T2 are the same type, then T1 and T2 are
-  // layout-compatible types.
-  if (C.hasSameType(T1, T2))
-return true;
-
+  // C++20 [basic.types] p11:
+  // Two types cv1 T1 and cv2 T2 are layout-compatible types
+  // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
+  // or layout-compatible standard-layout class types (11.4).
   T1 = T1.getCanonicalType().getUnqualifiedType();
   T2 = T2.getCanonicalType().getUnqualifiedType();
 
+  if (C.hasSameType(T1, T2))
+return true;
+
   const Type::TypeClass TC1 = T1->getTypeClass();
   const Type::TypeClass TC2 = T2->getTypeClass();
 
diff --git a/clang/test/CXX/drs/dr17xx.cpp b/clang/test/CXX/drs/dr17xx.cpp
index e5cee19337ebd4..d933c244aada42 100644
--- a/clang/test/CXX/drs/dr17xx.cpp
+++ b/clang/test/CXX/drs/dr17xx.cpp
@@ -46,7 +46,7 @@ namespace dr1715 { // dr1715: 3.9
 #endif
 }
 
-namespace dr1719 { // dr1719: no
+namespace dr1719 { // dr1719: 19
 #if __cplusplus >= 201103L
 struct CStruct {
   int one;
@@ -66,11 +66,10 @@ struct CStructWithQualifiers {
 static_assert(__is_layout_compatible(CStruct, const CStruct2), "");
 static_assert(__is_layout_compatible(CStruct, volatile CStruct2), "");
 static_assert(__is_layout_compatible(const CStruct, volatile CStruct2), "");
-// FIXME: all of the following pairs of types are layout-compatible
-static_assert(!__is_layout_compatible(int, const int), "");
-static_assert(!__is_layout_compatible(int, volatile int), "");
-static_assert(!__is_layout_compatible(const int, volatile int), "");
-static_assert(!__is_layout_compatible(CStruct, CStructWithQualifiers), "");
+static_assert(__is_layout_compatible(int, const int), "");
+static_assert(__is_layout_compatible(int, volatile int), "");
+static_assert(__is_layout_compatible(const int, volatile int), "");
+static_assert(__is_layout_compatible(CStruct, CStructWithQualifiers), "");
 #endif
 } // namespace dr1719
 
diff --git a/clang/test/SemaCXX/type-traits.cpp 
b/clang/test/SemaCXX/type-traits.cpp
index 6ff04b6c8c7223..94889d654abeca 100644
--- a/clang/test/SemaCXX/type-traits.cpp
+++ b/clang/test/SemaCXX/type-traits.cpp
@@ -1711,13 +1711,13 @@ void is_layout_compatible(int n)
 {
   static_assert(__is_layout_compatible(void, void), "");
   static_assert(!__is_layout_compatible(void, int), "");
-  static_assert(!__is_layout_compatible(void, const void), ""); // FIXME: this 
is CWG1719
-  static_assert(!__is_layout_compatible(void, volatile void), ""); // FIXME: 
this is CWG1719

[clang] [clang][analyzer] StreamChecker: Add more APIs, invalidate fscanf args (PR #82476)

2024-02-21 Thread Alejandro Álvarez Ayllón via cfe-commits


@@ -339,3 +363,107 @@ void fflush_on_open_failed_stream(void) {
   }
   fclose(F);
 }
+
+void test_fscanf_eof() {
+  FILE *F1 = tmpfile();
+  if (!F1)
+return;
+
+  int a;
+  unsigned b;
+  int ret = fscanf(F1, "%d %u", &a, &b);
+  char c = fgetc(F1); // expected-warning {{Read function called when stream 
is in EOF state. Function has no effect}}
+  // expected-warning@-1 {{File position of the stream might be 
'indeterminate' after a failed operation. Can cause undefined behavior}}

alejandro-alvarez-sonarsource wrote:

Yes, there is a note such as

```
clang/test/Analysis/stream.c Line 374: Assuming stream reaches end-of-file here
```

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


[clang] [clang][analyzer] StreamChecker: Add more APIs, invalidate fscanf args (PR #82476)

2024-02-21 Thread Alejandro Álvarez Ayllón via cfe-commits

https://github.com/alejandro-alvarez-sonarsource updated 
https://github.com/llvm/llvm-project/pull/82476

From a21881d82fe3674b344d4a3807e9d2590c98ce93 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?=
 
Date: Tue, 14 Nov 2023 09:28:45 +0100
Subject: [PATCH 1/3] [clang][analyzer] StreamChecker: add more APIs,
 invalidate fscanf args

1. Model getc, vfscanf, putc, vfprintf.
2. fscanf invalidates all arguments after the format string.
---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp |  39 +-
 ...ystem-header-simulator-for-simple-stream.h |   2 +-
 .../system-header-simulator-for-valist.h  |   4 +
 .../Analysis/Inputs/system-header-simulator.h |   3 +
 clang/test/Analysis/stream.c  | 128 ++
 5 files changed, 174 insertions(+), 2 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index a070f451694a3b..7938a0d30a91a3 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -21,6 +21,8 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
+#include "llvm/ADT/Sequence.h"
+#include "llvm/ADT/SmallVector.h"
 #include 
 #include 
 
@@ -171,7 +173,7 @@ using FnCheck = std::function;
 
 using ArgNoTy = unsigned int;
-static const ArgNoTy ArgNone = std::numeric_limits::max();
+const ArgNoTy ArgNone = std::numeric_limits::max();
 
 struct FnDescription {
   FnCheck PreFn;
@@ -179,6 +181,26 @@ struct FnDescription {
   ArgNoTy StreamArgNo;
 };
 
+[[nodiscard]] ProgramStateRef
+escapeArgsAfterIndex(ProgramStateRef State, CheckerContext &C,
+ const CallEvent &Call, unsigned FirstEscapingArgIndex) {
+  const auto *CE = Call.getOriginExpr();
+  assert(CE);
+
+  if (Call.getNumArgs() <= FirstEscapingArgIndex)
+return State;
+
+  SmallVector EscapingArgs;
+  EscapingArgs.reserve(Call.getNumArgs() - FirstEscapingArgIndex);
+  for (auto EscArgIdx :
+   llvm::seq(FirstEscapingArgIndex, Call.getNumArgs()))
+EscapingArgs.push_back(Call.getArgSVal(EscArgIdx));
+  State = State->invalidateRegions(EscapingArgs, CE, C.blockCount(),
+   C.getLocationContext(),
+   /*CausesPointerEscape=*/false);
+  return State;
+}
+
 /// Get the value of the stream argument out of the passed call event.
 /// The call should contain a function that is described by Desc.
 SVal getStreamArg(const FnDescription *Desc, const CallEvent &Call) {
@@ -396,6 +418,18 @@ class StreamChecker : public Checker FnTestDescriptions = {
@@ -997,6 +1031,9 @@ void StreamChecker::evalFscanf(const FnDescription *Desc, 
const CallEvent &Call,
   if (!E.Init(Desc, Call, C, State))
 return;
 
+  // The pointers passed to fscanf escape and get invalidated.
+  State = escapeArgsAfterIndex(State, C, Call, /*FirstEscapingArgIndex=*/2);
+
   // Add the success state.
   // In this context "success" means there is not an EOF or other read error
   // before any item is matched in 'fscanf'. But there may be match failure,
diff --git 
a/clang/test/Analysis/Inputs/system-header-simulator-for-simple-stream.h 
b/clang/test/Analysis/Inputs/system-header-simulator-for-simple-stream.h
index 098a2208fecbe9..c26d3582149120 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator-for-simple-stream.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator-for-simple-stream.h
@@ -5,7 +5,7 @@
 // suppressed.
 #pragma clang system_header
 
-typedef struct __sFILE {
+typedef struct _FILE {
   unsigned char *_p;
 } FILE;
 FILE *fopen(const char *restrict, const char *restrict) __asm("_" "fopen" );
diff --git a/clang/test/Analysis/Inputs/system-header-simulator-for-valist.h 
b/clang/test/Analysis/Inputs/system-header-simulator-for-valist.h
index 7299b61353d460..87688bd8b312f4 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator-for-valist.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator-for-valist.h
@@ -10,6 +10,8 @@
 #define restrict /*restrict*/
 #endif
 
+typedef struct _FILE FILE;
+
 typedef __builtin_va_list va_list;
 
 #define va_start(ap, param) __builtin_va_start(ap, param)
@@ -21,6 +23,8 @@ int vprintf (const char *restrict format, va_list arg);
 
 int vsprintf (char *restrict s, const char *restrict format, va_list arg);
 
+int vfscanf(FILE *stream, const char *format, va_list ap);
+
 int some_library_function(int n, va_list arg);
 
 // No warning from system header.
diff --git a/clang/test/Analysis/Inputs/system-header-simulator.h 
b/clang/test/Analysis/Inputs/system-header-simulator.h
index 15986984802c0e..8fd51449ecc0a4 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator.h
@@ -73,6 +73,9 @@ int ferror(FILE *stream);

[clang] [llvm] [Clang][SME] Detect always_inline used with mismatched streaming attributes (PR #77936)

2024-02-21 Thread Sander de Smalen via cfe-commits


@@ -0,0 +1,47 @@
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -S -target-feature +sme 
-verify -DTEST_NONE -x c %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -S -target-feature +sme 
-verify -DTEST_COMPATIBLE -x c %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -S -target-feature +sme 
-verify -DTEST_STREAMING -x c %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -S -target-feature +sme 
-verify -DTEST_LOCALLY -x c %s

sdesmalen-arm wrote:

If you use `-fsyntax-only` then you don't need to use the `#define`'s.

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


[clang] [llvm] [Clang][SME] Detect always_inline used with mismatched streaming attributes (PR #77936)

2024-02-21 Thread Sander de Smalen via cfe-commits


@@ -0,0 +1,47 @@
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -S -target-feature +sme 
-verify -DTEST_NONE -x c %s

sdesmalen-arm wrote:

Doing `-x c` on a .c file is redundant, as it's already interpreted as a C 
source file.

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


[clang] [llvm] [Clang][SME] Detect always_inline used with mismatched streaming attributes (PR #77936)

2024-02-21 Thread Sander de Smalen via cfe-commits


@@ -814,6 +820,43 @@ Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, 
Address VAListAddr,
   /*allowHigherAlign*/ false);
 }
 
+static bool isStreaming(const FunctionDecl *F) {
+  if (F->hasAttr())
+return true;
+  if (const auto *T = F->getType()->getAs())
+return T->getAArch64SMEAttributes() & 
FunctionType::SME_PStateSMEnabledMask;
+  return false;
+}
+
+static bool isStreamingCompatible(const FunctionDecl *F) {
+  if (const auto *T = F->getType()->getAs())
+return T->getAArch64SMEAttributes() &
+   FunctionType::SME_PStateSMCompatibleMask;
+  return false;
+}
+
+void AArch64TargetCodeGenInfo::checkFunctionCallABI(
+CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
+const FunctionDecl *Callee, const CallArgList &Args) const {
+  if (!Caller || !Callee->hasAttr())

sdesmalen-arm wrote:

nit: is it worth adding `|| !Callee` here as well? (without knowing the context 
of how this function is called, I guess you could argue that `Callee` could 
also be `nullptr`)

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


[clang] [clang][analyzer] Fix argument invalidations in StreamChecker. (PR #79470)

2024-02-21 Thread Balazs Benics via cfe-commits
=?utf-8?q?Balázs_Kéri?= 
Message-ID:
In-Reply-To: 


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

Thanks for resolving my comments.
FYI if I forget about a PR (that I promise to come back on the next day) - feel 
free to ping it or explicitly push the "request review" button.

Wait for my collage to also have a look, as I believe he might be in context to 
review this change. @alejandro-alvarez-sonarsource 

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


[clang] [clang][analyzer] Fix argument invalidations in StreamChecker. (PR #79470)

2024-02-21 Thread Alejandro Álvarez Ayllón via cfe-commits


@@ -763,6 +779,11 @@ void StreamChecker::evalFreadFwrite(const FnDescription 
*Desc,
 return;
   }
 
+  // At read, invalidate the buffer in any case of error or success,
+  // except if EOF was already present.
+  if (IsFread && (OldSS->ErrorState != ErrorFEof))
+State = escapeArgs(State, C, Call, {0});

alejandro-alvarez-sonarsource wrote:

From what I can tell, the lambda `UpdateBufferRegionForFread` is already used 
to take care of this in a more fine-grained manner. For instance:

```cpp
int buffer[10];
buffer[5] = 42;
if (1 == fread(buffer, sizeof(int), 5, fd)) {
assert(buffer[5] == 42);
}
```

Before this change, the assertion would pass, since lambda took `nmemb` into 
account. With this change, the whole buffer is invalidated.

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


[clang] [clang][analyzer] Fix argument invalidations in StreamChecker. (PR #79470)

2024-02-21 Thread Alejandro Álvarez Ayllón via cfe-commits

https://github.com/alejandro-alvarez-sonarsource edited 
https://github.com/llvm/llvm-project/pull/79470
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 91ebd01 - [clang][Interp] Remove dereference()

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

Author: Timm Bäder
Date: 2024-02-21T15:25:55+01:00
New Revision: 91ebd010aa76a711abd88f74ecca8e82e15b23cd

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

LOG: [clang][Interp] Remove dereference()

This function tried to be smart about the dereferenced value,
but it ended up hurting more than it helped. At least in the current
state, where we still try get the correct output.

I might add something similar back later.

Added: 


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

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 70e2bca2ebf16d..d11d05dd709d5e 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -81,16 +81,15 @@ bool ByteCodeExprGen::VisitCastExpr(const CastExpr 
*CE) {
 if (DiscardResult)
   return this->discard(SubExpr);
 
-return dereference(
-SubExpr, DerefKind::Read,
-[](PrimType) {
-  // Value loaded - nothing to do here.
-  return true;
-},
-[this, CE](PrimType T) {
-  // Pointer on stack - dereference it.
-  return this->emitLoadPop(T, CE);
-});
+if (SubExpr->getType()->isAnyComplexType())
+  return this->delegate(SubExpr);
+
+if (!this->visit(SubExpr))
+  return false;
+
+if (std::optional SubExprT = classify(SubExpr->getType()))
+  return this->emitLoadPop(*SubExprT, CE);
+return false;
   }
 
   case CK_UncheckedDerivedToBase:
@@ -2326,134 +2325,6 @@ bool 
ByteCodeExprGen::visitZeroRecordInitializer(const Record *R,
   return true;
 }
 
-template 
-bool ByteCodeExprGen::dereference(
-const Expr *LV, DerefKind AK, llvm::function_ref Direct,
-llvm::function_ref Indirect) {
-  if (std::optional T = classify(LV->getType())) {
-if (!LV->refersToBitField()) {
-  // Only primitive, non bit-field types can be dereferenced directly.
-  if (const auto *DE = dyn_cast(LV)) {
-if (!DE->getDecl()->getType()->isReferenceType()) {
-  if (const auto *PD = dyn_cast(DE->getDecl()))
-return dereferenceParam(LV, *T, PD, AK, Direct, Indirect);
-  if (const auto *VD = dyn_cast(DE->getDecl()))
-return dereferenceVar(LV, *T, VD, AK, Direct, Indirect);
-}
-  }
-}
-
-if (!visit(LV))
-  return false;
-return Indirect(*T);
-  }
-
-  if (LV->getType()->isAnyComplexType())
-return this->delegate(LV);
-
-  return false;
-}
-
-template 
-bool ByteCodeExprGen::dereferenceParam(
-const Expr *LV, PrimType T, const ParmVarDecl *PD, DerefKind AK,
-llvm::function_ref Direct,
-llvm::function_ref Indirect) {
-  if (auto It = this->Params.find(PD); It != this->Params.end()) {
-unsigned Idx = It->second.Offset;
-switch (AK) {
-case DerefKind::Read:
-  return DiscardResult ? true : this->emitGetParam(T, Idx, LV);
-
-case DerefKind::Write:
-  if (!Direct(T))
-return false;
-  if (!this->emitSetParam(T, Idx, LV))
-return false;
-  return DiscardResult ? true : this->emitGetPtrParam(Idx, LV);
-
-case DerefKind::ReadWrite:
-  if (!this->emitGetParam(T, Idx, LV))
-return false;
-  if (!Direct(T))
-return false;
-  if (!this->emitSetParam(T, Idx, LV))
-return false;
-  return DiscardResult ? true : this->emitGetPtrParam(Idx, LV);
-}
-return true;
-  }
-
-  // If the param is a pointer, we can dereference a dummy value.
-  if (!DiscardResult && T == PT_Ptr && AK == DerefKind::Read) {
-if (auto Idx = P.getOrCreateDummy(PD))
-  return this->emitGetPtrGlobal(*Idx, PD);
-return false;
-  }
-
-  // Value cannot be produced - try to emit pointer and do stuff with it.
-  return visit(LV) && Indirect(T);
-}
-
-template 
-bool ByteCodeExprGen::dereferenceVar(
-const Expr *LV, PrimType T, const VarDecl *VD, DerefKind AK,
-llvm::function_ref Direct,
-llvm::function_ref Indirect) {
-  auto It = Locals.find(VD);
-  if (It != Locals.end()) {
-const auto &L = It->second;
-switch (AK) {
-case DerefKind::Read:
-  if (!this->emitGetLocal(T, L.Offset, LV))
-return false;
-  return DiscardResult ? this->emitPop(T, LV) : true;
-
-case DerefKind::Write:
-  if (!Direct(T))
-return false;
-  if (!this->emitSetLocal(T, L.Offset, LV))
-return false;
-  return DiscardResult ? true : this->emitGetPtrLocal(L.Offset, LV);
-
-case DerefKind::ReadWrite:
-  if (!this->emitGetLocal(T, L.Offset, LV))
-return false;
-  if (!Direct(T))
-return false;
-  if (!this->emitSetLocal(T, L.Offset, LV))
-retur

[clang] [clang][analyzer] Fix argument invalidations in StreamChecker. (PR #79470)

2024-02-21 Thread Alejandro Álvarez Ayllón via cfe-commits

https://github.com/alejandro-alvarez-sonarsource edited 
https://github.com/llvm/llvm-project/pull/79470
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [CLANG] Full support of complex multiplication and division. (PR #81514)

2024-02-21 Thread Zahira Ammarguellat via cfe-commits

https://github.com/zahiraam updated 
https://github.com/llvm/llvm-project/pull/81514

>From 13fd73932251843173cbbc31ca93905ca0469277 Mon Sep 17 00:00:00 2001
From: Ammarguellat 
Date: Mon, 12 Feb 2024 10:58:19 -0800
Subject: [PATCH 1/3] [CLANG] Full support of complex multiplication and
 division.

---
 clang/docs/UsersManual.rst   |  32 +--
 clang/include/clang/Basic/LangOptions.h  |  27 ++-
 clang/include/clang/Driver/Options.td|  25 +--
 clang/lib/CodeGen/CGExprComplex.cpp  |  31 ++-
 clang/lib/Driver/ToolChains/Clang.cpp|  87 
 clang/lib/Parse/ParsePragma.cpp  |   4 +-
 clang/test/CodeGen/cx-complex-range.c| 222 +++
 clang/test/CodeGen/pragma-cx-limited-range.c | 179 +--
 clang/test/Driver/range.c| 103 ++---
 9 files changed, 475 insertions(+), 235 deletions(-)

diff --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index 7391e4cf3a9aeb..9ea5f89ece7511 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -1847,19 +1847,25 @@ floating point semantic models: precise (the default), 
strict, and fast.
* ``16`` - Forces ``_Float16`` operations to be emitted without using excess
  precision arithmetic.
 
-.. option:: -fcx-limited-range:
-
-   This option enables the naive mathematical formulas for complex division and
-   multiplication with no NaN checking of results. The default is
-   ``-fno-cx-limited-range``, but this option is enabled by the ``-ffast-math``
-   option.
-
-.. option:: -fcx-fortran-rules:
-
-   This option enables the naive mathematical formulas for complex
-   multiplication and enables application of Smith's algorithm for complex
-   division. See SMITH, R. L. Algorithm 116: Complex division. Commun.
-   ACM 5, 8 (1962). The default is ``-fno-cx-fortran-rules``.
+.. option:: -fcomplex-arithmetic=:
+
+   This option specifies the implementation for complex multiplication and 
division.
+
+   Valid values are: ``limited``, ``smith``, ``full`` and ``extend``.
+
+   * ``limited`` Implementation of complex division and multiplication using
+ algebraic formulas at source precision. Overflow and non-finites values
+ are not handled.
+   * ``smith`` Implementation of complex division using the Smith algorithm at
+ source precision. Smith's algorithm for complex division.
+ See SMITH, R. L. Algorithm 116: Complex division. Commun. ACM 5, 8 (1962).
+ Overflow is handled.
+   * ``full``  Implementation of complex division and multiplication using a
+ call to runtime library functions (generally the case, but the BE might
+ sometimes replace the library call if it knows enough about the potential
+ range of the inputs). Overflow and non-finite values are handled.
+   * ``extend`` Implementation of complex division using algebraic formulas at
+ higher precision. Overflow is handled.
 
 .. _floating-point-environment:
 
diff --git a/clang/include/clang/Basic/LangOptions.h 
b/clang/include/clang/Basic/LangOptions.h
index 862952d336ef31..b8b96d06888291 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -396,7 +396,32 @@ class LangOptionsBase {
 IncompleteOnly = 3,
   };
 
-  enum ComplexRangeKind { CX_Full, CX_Limited, CX_Fortran, CX_None };
+  /// Controls the various implementations for complex multiplication and
+  // division.
+  enum ComplexRangeKind {
+/// Implementation of complex division and multiplication using a call to
+/// runtime library functions (generally the case, but the BE might
+/// sometimes replace the library call if it knows enough about the
+/// potential range of the inputs). Overflow and non-finite values are
+/// handled.
+CX_Full,
+
+/// Implementation of complex division using the Smith algorithm at source
+/// precision. Overflow is handled.
+CX_Smith,
+
+/// Implementation of complex division using algebraic formulas at higher
+/// precision. Overflow is handled.
+CX_Extend,
+
+/// Implementation of complex division and multiplication using algebraic
+/// formulas at source precision. Overflow and non-finites values are not
+/// handled.
+CX_Limited,
+
+/// No range rule is enabled.
+CX_None
+  };
 
   // Define simple language options (with no accessors).
 #define LANGOPT(Name, Bits, Default, Description) unsigned Name : Bits;
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 31e8571758bfce..848cc38188d86e 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1012,28 +1012,15 @@ defm offload_uniform_block : 
BoolFOption<"offload-uniform-block",
   NegFlag,
   BothFlags<[], [ClangOption], " that kernels are launched with uniform block 
sizes (default true for CUDA/HIP and false otherwise)">>;
 
-def fcx_limited_range : Joined<["-"], "fcx-limited-range

[clang] f7c2e5f - [clang] [SemaCXX] Disallow deducing "this" on operator `new` and `delete` (#82251)

2024-02-21 Thread via cfe-commits

Author: Rajveer Singh Bharadwaj
Date: 2024-02-21T15:30:49+01:00
New Revision: f7c2e5fa05d221a3dfc53744f353517407c2ffec

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

LOG: [clang] [SemaCXX] Disallow deducing "this" on operator `new` and `delete` 
(#82251)

Resolves Issue #82249

As described in the issue, any deallocation function for a `class X` is
a static member (even if not explicitly declared static).

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaDeclCXX.cpp
clang/test/SemaCXX/cxx2b-deducing-this.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5bca2c965c866b..c17298bc7bce5e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -279,6 +279,8 @@ Bug Fixes to C++ Support
   Fixes (`#68490 `_)
 - Fix a crash when trying to call a varargs function that also has an explicit 
object parameter.
   Fixes (`#80971 ICE when explicit object parameter be a function parameter 
pack`)
+- Reject explicit object parameters on `new` and `delete` operators.
+  Fixes (`#82249 ` _)
 - Fixed a bug where abbreviated function templates would append their invented 
template parameters to
   an empty template parameter lists.
 - Clang now classifies aggregate initialization in C++17 and newer as constant

diff  --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 79263bc3ff671d..7c009d9c8ec093 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -11395,7 +11395,9 @@ void Sema::CheckExplicitObjectMemberFunction(Declarator 
&D,
 << ExplicitObjectParam->getSourceRange();
   }
 
-  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) {
+  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
+  (D.getContext() == clang::DeclaratorContext::Member &&
+   D.isStaticMember())) {
 Diag(ExplicitObjectParam->getBeginLoc(),
  diag::err_explicit_object_parameter_nonmember)
 << D.getSourceRange() << /*static=*/0 << IsLambda;

diff  --git a/clang/test/SemaCXX/cxx2b-deducing-this.cpp 
b/clang/test/SemaCXX/cxx2b-deducing-this.cpp
index 30131d6adc4db0..b8ddb9ad300034 100644
--- a/clang/test/SemaCXX/cxx2b-deducing-this.cpp
+++ b/clang/test/SemaCXX/cxx2b-deducing-this.cpp
@@ -16,6 +16,10 @@ struct S {
 static void f(this auto); // expected-error{{an explicit object parameter 
cannot appear in a static function}}
 virtual void f(this S); // expected-error{{an explicit object parameter 
cannot appear in a virtual function}}
 
+// new and delete are implicitly static
+void *operator new(this unsigned long); // expected-error{{an explicit 
object parameter cannot appear in a static function}}
+void operator delete(this void*); // expected-error{{an explicit object 
parameter cannot appear in a static function}}
+
 void g(this auto) const; // expected-error{{explicit object member 
function cannot have 'const' qualifier}}
 void h(this auto) &; // expected-error{{explicit object member function 
cannot have '&' qualifier}}
 void i(this auto) &&; // expected-error{{explicit object member function 
cannot have '&&' qualifier}}



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


[clang] [clang] [SemaCXX] Disallow deducing "this" on operator `new` and `delete` (PR #82251)

2024-02-21 Thread via cfe-commits

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


[clang] [clang] [SemaCXX] Disallow deducing "this" on operator `new` and `delete` (PR #82251)

2024-02-21 Thread via cfe-commits

cor3ntin wrote:

Thanks for working on this!

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


[clang] [Clang][Sema] Diagnosis for constexpr constructor not initializing a union member (PR #81225)

2024-02-21 Thread via cfe-commits


@@ -2393,6 +2391,17 @@ static bool CheckConstexprFunctionBody(Sema &SemaRef, 
const FunctionDecl *Dcl,
  Kind))
 return false;
   }
+} else if (!Constructor->isDelegatingConstructor()) {

mahtohappy wrote:

Hi, the check before here in the file only checks for non-templated, 
non-delegating constructors initializing the class  where union is member, and 
that produces a different warning. 
And if you're why this whole patch, then I've added the issue it resolves.  


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


[clang] [Clang][Sema] Diagnosis for constexpr constructor not initializing a union member (PR #81225)

2024-02-21 Thread via cfe-commits


@@ -2343,17 +2349,9 @@ static bool CheckConstexprFunctionBody(Sema &SemaRef, 
const FunctionDecl *Dcl,
 // - if the class is a union having variant members, exactly one of them
 //   shall be initialized;

mahtohappy wrote:

I'll add the references.


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


[clang] [Clang][Sema] Diagnosis for constexpr constructor not initializing a union member (PR #81225)

2024-02-21 Thread via cfe-commits


@@ -2471,6 +2480,23 @@ static bool CheckConstexprFunctionBody(Sema &SemaRef, 
const FunctionDecl *Dcl,
   return true;
 }
 
+static bool
+checkUnionConstructorIntializer(Sema &SemaRef, const FunctionDecl *Dcl,

mahtohappy wrote:

DiagUnionMemberConstExprCtorInitializer will be okay?

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


[clang] [clang-cl] Fix value of __FUNCTION__ in MSVC mode. (PR #67592)

2024-02-21 Thread Zahira Ammarguellat via cfe-commits

https://github.com/zahiraam updated 
https://github.com/llvm/llvm-project/pull/67592

>From 55b67a58ef8b9856e5f0a8f535b8617f59711dec Mon Sep 17 00:00:00 2001
From: Ammarguellat 
Date: Wed, 27 Sep 2023 11:59:04 -0700
Subject: [PATCH 01/18] Fix value of __FUNCTION__ and __func__ in MSVC mode.

---
 clang/lib/AST/Expr.cpp|  9 ++-
 clang/lib/AST/TypePrinter.cpp | 21 +-
 clang/test/Analysis/eval-predefined-exprs.cpp |  4 +-
 .../CodeGenCXX/mangle-nttp-anon-union.cpp |  2 +-
 clang/test/CodeGenCXX/predefined-expr.cpp | 18 -
 clang/test/SemaCXX/source_location.cpp| 72 +++
 6 files changed, 99 insertions(+), 27 deletions(-)

diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index af82ca0784af41..49f3495c090f19 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -773,8 +773,8 @@ std::string PredefinedExpr::ComputeName(IdentKind IK, const 
Decl *CurrentDecl) {
   }
   if (const FunctionDecl *FD = dyn_cast(CurrentDecl)) {
 const auto &LO = Context.getLangOpts();
-if (((IK == Func || IK == Function) && !LO.MicrosoftExt) ||
-(IK == LFunction && LO.MicrosoftExt))
+if (((IK == Function || IK == Func) && !LO.MicrosoftExt) ||
+((IK == LFunction || IK == Func) && LO.MicrosoftExt))
   return FD->getNameAsString();
 
 SmallString<256> Name;
@@ -804,7 +804,10 @@ std::string PredefinedExpr::ComputeName(IdentKind IK, 
const Decl *CurrentDecl) {
 PrintingPolicy Policy(LO);
 PrettyCallbacks PrettyCB(LO);
 Policy.Callbacks = &PrettyCB;
-Policy.UseClassForTemplateArgument = LO.MicrosoftExt;
+if (IK == Function && LO.MicrosoftExt) {
+  Policy.UseClassForTemplateArgument = LO.MicrosoftExt;
+  Policy.MSVCFormatting = LO.MicrosoftExt;
+}
 std::string Proto;
 llvm::raw_string_ostream POut(Proto);
 
diff --git a/clang/lib/AST/TypePrinter.cpp b/clang/lib/AST/TypePrinter.cpp
index 3771a29f26b173..8a7cf85cdf126b 100644
--- a/clang/lib/AST/TypePrinter.cpp
+++ b/clang/lib/AST/TypePrinter.cpp
@@ -2195,6 +2195,7 @@ printTo(raw_ostream &OS, ArrayRef Args, const 
PrintingPolicy &Policy,
 llvm::SmallVector OrigArgs;
 for (const TA &A : Args)
   OrigArgs.push_back(getArgument(A));
+
 while (!Args.empty() && getArgument(Args.back()).getIsDefaulted())
   Args = Args.drop_back();
   }
@@ -2218,10 +2219,24 @@ printTo(raw_ostream &OS, ArrayRef Args, const 
PrintingPolicy &Policy,
 } else {
   if (!FirstArg)
 OS << Comma;
-  if (Policy.UseClassForTemplateArgument &&
-  Argument.getKind() == TemplateArgument::Type)
-OS << "class ";
 
+  if (Policy.MSVCFormatting && Policy.UseClassForTemplateArgument &&
+  Argument.getKind() == TemplateArgument::Type &&
+  !Argument.getAsType()->isBuiltinType()) {
+const Type *Ty = Argument.getAsType().getTypePtr();
+const char *kw;
+if (Ty->isStructureType())
+  kw = "struct ";
+else if (Ty->isClassType())
+  kw = "class ";
+else if (Ty->isUnionType())
+  kw = "union ";
+else if (Ty->isEnumeralType())
+  kw = "enum ";
+else
+  llvm_unreachable("argument type not expected");
+OS << kw;
+  }
   // Tries to print the argument with location info if exists.
   printArgument(Arg, Policy, ArgOS,
 TemplateParameterList::shouldIncludeTypeForArgument(
diff --git a/clang/test/Analysis/eval-predefined-exprs.cpp 
b/clang/test/Analysis/eval-predefined-exprs.cpp
index 7be441eb5bad94..a6bac5ee9d486d 100644
--- a/clang/test/Analysis/eval-predefined-exprs.cpp
+++ b/clang/test/Analysis/eval-predefined-exprs.cpp
@@ -56,7 +56,7 @@ struct A {
 clang_analyzer_dump(__FUNCTION__);
 clang_analyzer_dump(__PRETTY_FUNCTION__);
 #ifdef ANALYZER_MS
-// expected-warning@-4 {{&Element{"A::A",0 S64b,char}}}
+// expected-warning@-4 {{&Element{"A",0 S64b,char}}}
 // expected-warning@-4 {{&Element{"A::A",0 S64b,char}}}
 #else
 // expected-warning@-7 {{&Element{"A",0 S64b,char}}}
@@ -80,7 +80,7 @@ struct A {
 clang_analyzer_dump(__FUNCTION__);
 clang_analyzer_dump(__PRETTY_FUNCTION__);
 #ifdef ANALYZER_MS
-// expected-warning@-4 {{&Element{"A::~A",0 S64b,char}}}
+// expected-warning@-4 {{&Element{"~A",0 S64b,char}}}
 // expected-warning@-4 {{&Element{"A::~A",0 S64b,char}}}
 #else
 // expected-warning@-7 {{&Element{"~A",0 S64b,char}}}
diff --git a/clang/test/CodeGenCXX/mangle-nttp-anon-union.cpp 
b/clang/test/CodeGenCXX/mangle-nttp-anon-union.cpp
index 78fa7c378c88d5..1982a3eeb94129 100644
--- a/clang/test/CodeGenCXX/mangle-nttp-anon-union.cpp
+++ b/clang/test/CodeGenCXX/mangle-nttp-anon-union.cpp
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -std=c++20 -emit-llvm %s -o - -triple=x86_64-linux-gnu | 
FileCheck %s
-// RUN: %clang_cc1 -std=c++20 -emit-llvm %s -o - -triple=x86_64-linux-gnu | 
llvm-cxxfilt -n | FileCheck %s --check-prefix D

[clang] [Clang][Sema] Diagnosis for constexpr constructor not initializing a union member (PR #81225)

2024-02-21 Thread via cfe-commits

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


[clang] [clang-cl] Fix value of __FUNCTION__ in MSVC mode. (PR #67592)

2024-02-21 Thread Zahira Ammarguellat via cfe-commits

zahiraam wrote:

@AaronBallman  I removed the field that I added in the policy and tried to use 
the existing ones. That broke a few LIT tests but before fixing them I want to 
check with you if the combination of policy I have added in the unittest is 
correct. Thanks.

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


[clang] [llvm] [mlir] [openmp] [OpenMP] Remove `register_requires` global constructor (PR #80460)

2024-02-21 Thread Jon Chesterfield via cfe-commits

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

I like this a lot, thank you.

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


[clang] [Clang][Sema] Diagnosis for constexpr constructor not initializing a union member (PR #81225)

2024-02-21 Thread via cfe-commits


@@ -2471,6 +2480,23 @@ static bool CheckConstexprFunctionBody(Sema &SemaRef, 
const FunctionDecl *Dcl,
   return true;
 }
 
+static bool
+checkUnionConstructorIntializer(Sema &SemaRef, const FunctionDecl *Dcl,
+const CXXConstructorDecl *Constructor,
+const CXXRecordDecl *RD,
+Sema::CheckConstexprKind Kind) {
+  if (Constructor->getNumCtorInitializers() == 0 && RD->hasVariantMembers()) {
+if (Kind == Sema::CheckConstexprKind::Diagnose) {
+  SemaRef.Diag(Dcl->getLocation(),
+   SemaRef.getLangOpts().CPlusPlus20
+   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
+   : diag::ext_constexpr_union_ctor_no_init);
+} else if (!SemaRef.getLangOpts().CPlusPlus20) {

mahtohappy wrote:

It checks if in a templated class/struct there's a union member than at least 
one member of that is initialized by the constexpr constructor. It's a warning, 
but in C++20 it's okay.
 

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


[clang] [llvm] [Clang][SME] Detect always_inline used with mismatched streaming attributes (PR #77936)

2024-02-21 Thread Sam Tebbs via cfe-commits


@@ -814,6 +820,43 @@ Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, 
Address VAListAddr,
   /*allowHigherAlign*/ false);
 }
 
+static bool isStreaming(const FunctionDecl *F) {
+  if (F->hasAttr())
+return true;
+  if (const auto *T = F->getType()->getAs())
+return T->getAArch64SMEAttributes() & 
FunctionType::SME_PStateSMEnabledMask;
+  return false;
+}
+
+static bool isStreamingCompatible(const FunctionDecl *F) {
+  if (const auto *T = F->getType()->getAs())
+return T->getAArch64SMEAttributes() &
+   FunctionType::SME_PStateSMCompatibleMask;
+  return false;
+}
+
+void AArch64TargetCodeGenInfo::checkFunctionCallABI(
+CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
+const FunctionDecl *Callee, const CallArgList &Args) const {
+  if (!Caller || !Callee->hasAttr())

SamTebbs33 wrote:

>From looking at where `checkFunctionCallABI` is called, it's not possible for 
>`Callee` to be null, but I'm happy to add a check just in case that changes.

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


[clang] [llvm] [Clang][SME] Detect always_inline used with mismatched streaming attributes (PR #77936)

2024-02-21 Thread Sam Tebbs via cfe-commits

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


[clang] [Clang][Sema] Diagnosis for constexpr constructor not initializing a union member (PR #81225)

2024-02-21 Thread via cfe-commits


@@ -2471,6 +2480,23 @@ static bool CheckConstexprFunctionBody(Sema &SemaRef, 
const FunctionDecl *Dcl,
   return true;
 }
 
+static bool
+checkUnionConstructorIntializer(Sema &SemaRef, const FunctionDecl *Dcl,
+const CXXConstructorDecl *Constructor,
+const CXXRecordDecl *RD,
+Sema::CheckConstexprKind Kind) {
+  if (Constructor->getNumCtorInitializers() == 0 && RD->hasVariantMembers()) {
+if (Kind == Sema::CheckConstexprKind::Diagnose) {
+  SemaRef.Diag(Dcl->getLocation(),
+   SemaRef.getLangOpts().CPlusPlus20
+   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
+   : diag::ext_constexpr_union_ctor_no_init);
+} else if (!SemaRef.getLangOpts().CPlusPlus20) {
+  return true;

mahtohappy wrote:

The place from where this function is called, is inside a UnionRecord Decl and 
goes on to check it's constructor to initialize the member, in the c++20 case 
we don't to initialize it so true but in c++ version before we do, hence the 
diagnosis and false result. 

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


[clang] 7318585 - [clang] Implement CWG1719 "Layout compatibility and cv-qualification revisited" (#82358)

2024-02-21 Thread via cfe-commits

Author: Vlad Serebrennikov
Date: 2024-02-21T19:02:20+04:00
New Revision: 73185854a3fc469b7d3e21d0b5d2ecb5ee15d201

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

LOG: [clang] Implement CWG1719 "Layout compatibility and cv-qualification 
revisited" (#82358)

This patch updates our internal notion of `layout-compatible` to ignore 
cv-qualification,
which in turn fixes `__is_layout_compatible` intrinsic.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaChecking.cpp
clang/test/CXX/drs/dr17xx.cpp
clang/test/SemaCXX/type-traits.cpp
clang/www/cxx_dr_status.html

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c17298bc7bce5e..15905e08955097 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -98,9 +98,8 @@ C++20 Feature Support
 
 - Implemented the `__is_layout_compatible` intrinsic to support
   `P0466R5: Layout-compatibility and Pointer-interconvertibility Traits 
`_.
-  Note: `CWG1719: Layout compatibility and cv-qualification revisited  
`_
-  and `CWG2759: [[no_unique_address] and common initial sequence 
`_
-  are not yet implemented.
+  Note: `CWG2759: [[no_unique_address] and common initial sequence 
`_
+  is not yet implemented.
 
 C++23 Feature Support
 ^
@@ -120,6 +119,10 @@ Resolutions to C++ Defect Reports
   in the template parameters, but is deduced from a previous argument.
   (`#78449: `_).
 
+- Type qualifications are now ignored when evaluating layout compatibility
+  of two types.
+  (`CWG1719: Layout compatibility and cv-qualification revisited 
`_).
+
 C Language Changes
 --
 

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index d951c0fc2732d2..e8bfb215a5b4c5 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -19124,15 +19124,16 @@ static bool isLayoutCompatible(ASTContext &C, 
QualType T1, QualType T2) {
   if (T1.isNull() || T2.isNull())
 return false;
 
-  // C++11 [basic.types] p11:
-  // If two types T1 and T2 are the same type, then T1 and T2 are
-  // layout-compatible types.
-  if (C.hasSameType(T1, T2))
-return true;
-
+  // C++20 [basic.types] p11:
+  // Two types cv1 T1 and cv2 T2 are layout-compatible types
+  // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
+  // or layout-compatible standard-layout class types (11.4).
   T1 = T1.getCanonicalType().getUnqualifiedType();
   T2 = T2.getCanonicalType().getUnqualifiedType();
 
+  if (C.hasSameType(T1, T2))
+return true;
+
   const Type::TypeClass TC1 = T1->getTypeClass();
   const Type::TypeClass TC2 = T2->getTypeClass();
 

diff  --git a/clang/test/CXX/drs/dr17xx.cpp b/clang/test/CXX/drs/dr17xx.cpp
index e5cee19337ebd4..d3cb5e58f06b32 100644
--- a/clang/test/CXX/drs/dr17xx.cpp
+++ b/clang/test/CXX/drs/dr17xx.cpp
@@ -46,7 +46,7 @@ namespace dr1715 { // dr1715: 3.9
 #endif
 }
 
-namespace dr1719 { // dr1719: no
+namespace dr1719 { // dr1719: 19
 #if __cplusplus >= 201103L
 struct CStruct {
   int one;
@@ -66,11 +66,11 @@ struct CStructWithQualifiers {
 static_assert(__is_layout_compatible(CStruct, const CStruct2), "");
 static_assert(__is_layout_compatible(CStruct, volatile CStruct2), "");
 static_assert(__is_layout_compatible(const CStruct, volatile CStruct2), "");
-// FIXME: all of the following pairs of types are layout-compatible
-static_assert(!__is_layout_compatible(int, const int), "");
-static_assert(!__is_layout_compatible(int, volatile int), "");
-static_assert(!__is_layout_compatible(const int, volatile int), "");
-static_assert(!__is_layout_compatible(CStruct, CStructWithQualifiers), "");
+static_assert(__is_layout_compatible(int, const int), "");
+static_assert(__is_layout_compatible(int, volatile int), "");
+static_assert(__is_layout_compatible(const int, volatile int), "");
+static_assert(__is_layout_compatible(CStruct, CStructWithQualifiers), "");
+static_assert(__is_layout_compatible(int[], const volatile int[]), "");
 #endif
 } // namespace dr1719
 

diff  --git a/clang/test/SemaCXX/type-traits.cpp 
b/clang/test/SemaCXX/type-traits.cpp
index 6ff04b6c8c7223..2c35d5ee19a4c6 100644
--- a/clang/test/SemaCXX/type-traits.cpp
+++ b/clang/test/SemaCXX/type-traits.cpp
@@ -1609,7 +1609,12 @@ struct CStructNoUniqueAddress2 {
   [[no_unique_address]] int two;
 };
 
-struct CStructAlignment {
+struct alignas(64) CStructAlignment {
+  int one;
+  int two;
+};
+
+struct CStructAligned

[clang] [clang] Implement CWG1719 "Layout compatibility and cv-qualification revisited" (PR #82358)

2024-02-21 Thread Vlad Serebrennikov via cfe-commits

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


[clang] [Serialization] Load Specializations Lazily (PR #76774)

2024-02-21 Thread Ilya Biryukov via cfe-commits

ilya-biryukov wrote:

Sorry for losing track of the discussion here. What is the current status here? 
Should we run another round of testing?

Also, I see proposals to land the new behaviour under a flag and have it off by 
default.
If that does not add a lot of complexity, that would definitely be something 
that's makes testing easier on our side. Our compiler is build from revisions 
close to head and don't need to wait for the next Clang release to rip the 
benefits of this approach.

https://github.com/llvm/llvm-project/pull/76774
___
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 can be statically known (PR #81335)

2024-02-21 Thread via cfe-commits

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

>From 63f3ada705b69c27ca37207c6f7e8098896602b7 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| 70 +++
 1 file changed, 70 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..0bf3336527b0a0 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,6 +1,12 @@
 // 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_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +26,70 @@ -(void)meth {
 }
 @end
 
+// Ivars declared in the @interface
+@interface SuperClass : NSObject
+@property (nonatomic, assign) int superClassProperty;
+@end
+
+@implementation SuperClass {
+  int superClassIvar; // Declare an ivar
+}
+- (void)superClassMethod {
+_superClassProperty = 42;
+superClassIvar = 10;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SuperClass
+// CHECK: getelementptr inbounds i8, ptr %1, i64 20
+}
+@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
+}
+
+- (void)intermediateClassPropertyMethod {
+self.intermediateProperty = 0;
+// CHECK: getelementptr inbounds i8, ptr %2, i64 24
+}
+@end
+
+@interface SubClass : IntermediateClass
+{
+double subClassIvar;
+}
+@end
+
+@implementation SubClass
+- (void)subclassVar {
+
+subClassIvar = 6.28;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+-(void)intermediateSubclassVar
+{
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

>From a89a220746836a6ff0931b26fc30f60ca92f0736 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 can be statically known

As of now, we only check if a class directly inherits from NSObject to 
determine if said class has fixed offsets and can therefore have its memory 
layout statically known.

However, if an NSObject subclass has fixed offsets, then so must the subclasses 
of that subclass, so this allows us to optimize instances of subclasses of 
subclasses that inherit from NSObject and so on.

To determine this, we need to find that the compiler can see the implementation 
of each intermediate class, as that means it is statically linked.
---
 clang/lib/CodeGen/CGObjCMac.cpp   | 22 ++
 .../constant-non-fragile-ivar-offset.m| 30 +--
 2 files changed, 31 insertions(+), 21 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index 27d77e9a8a5511..b3d6c3ba314cc2 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -1593,12 +1593,22 @@ class CGObjCNonFragileABIMac : public CGObjCCommonMac {
   }
 
   bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) {
-// NSObject is a fixed size. If we can see the @implementation of a class
-// which inherits from NSObject then we know that all it's offsets also 
must
-// be fixed. FIXME: Can we do this if see a chain of super classes with
-// implementations leading to NSObject?
-return ID->getImplementation() && ID->getSuperClass() &&
-   ID->getSuperClass()->getName() == "NSObject";
+// Test a class by checking its supercl

[clang] [clang][dataflow] Fix inaccuracies in `buildStmtToBasicBlockMap()`. (PR #82496)

2024-02-21 Thread via cfe-commits

https://github.com/martinboehme created 
https://github.com/llvm/llvm-project/pull/82496

See the comments added to the code for details on the inaccuracies that have
now been fixed.

The patch adds tests that fail with the old implementation.

>From 5c3df2b3151a8093e60f5fe79dcadc72a237d0ef Mon Sep 17 00:00:00 2001
From: Martin Braenne 
Date: Wed, 21 Feb 2024 15:05:55 +
Subject: [PATCH] [clang][dataflow] Fix inaccuracies in
 `buildStmtToBasicBlockMap()`.

See the comments added to the code for details on the inaccuracies that have
now been fixed.

The patch adds tests that fail with the old implementation.
---
 .../FlowSensitive/ControlFlowContext.cpp  |  31 +++-
 .../TypeErasedDataflowAnalysisTest.cpp| 143 ++
 2 files changed, 140 insertions(+), 34 deletions(-)

diff --git a/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp 
b/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
index c9ebffe6f37801..8aed19544be6a2 100644
--- a/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
+++ b/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
@@ -39,8 +39,35 @@ buildStmtToBasicBlockMap(const CFG &Cfg) {
 
   StmtToBlock[Stmt->getStmt()] = Block;
 }
-if (const Stmt *TerminatorStmt = Block->getTerminatorStmt())
-  StmtToBlock[TerminatorStmt] = Block;
+  }
+  // Some terminator conditions don't appear as a `CFGElement` anywhere else -
+  // for example, this is true if the terminator condition is a `&&` or `||`
+  // operator.
+  // We associate these conditions with the block the terminator appears in,
+  // but only if the condition has not already appeared as a regular
+  // `CFGElement`. (The `insert()` below does nothing if the key already exists
+  // in the map.)
+  for (const CFGBlock *Block : Cfg) {
+if (Block != nullptr)
+  if (const Stmt *TerminatorCond = Block->getTerminatorCondition())
+StmtToBlock.insert({TerminatorCond, Block});
+  }
+  // Terminator statements typically don't appear as a `CFGElement` anywhere
+  // else, so we want to associate them with the block that they terminate.
+  // However, there are some important special cases:
+  // -  The conditional operator is a type of terminator, but it also appears
+  //as a regular `CFGElement`, and we want to associate it with the block
+  //in which it appears as a `CFGElement`.
+  // -  The `&&` and `||` operators are types of terminators, but like the
+  //conditional operator, they can appear as a regular `CFGElement` or
+  //as a terminator condition (see above).
+  // We process terminators last to make sure that we only associate them with
+  // the block they terminate if they haven't previously occurred as a regular
+  // `CFGElement` or as a terminator condition.
+  for (const CFGBlock *Block : Cfg) {
+if (Block != nullptr)
+  if (const Stmt *TerminatorStmt = Block->getTerminatorStmt())
+StmtToBlock.insert({TerminatorStmt, Block});
   }
   return StmtToBlock;
 }
diff --git 
a/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
index 3bca9cced8d6f7..34f9b0b23719fe 100644
--- a/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -77,17 +77,33 @@ class DataflowAnalysisTest : public Test {
 return runDataflowAnalysis(*CFCtx, Analysis, Env);
   }
 
+  /// Returns the `CFGBlock` containing `S` (and asserts that it exists).
+  const CFGBlock *blockForStmt(const Stmt &S) {
+const CFGBlock *Block = CFCtx->getStmtToBlock().lookup(&S);
+assert(Block != nullptr);
+return Block;
+  }
+
   template 
   const StateT &
   blockStateForStmt(const std::vector> &BlockStates,
-const Stmt *S) {
-const CFGBlock *Block = CFCtx->getStmtToBlock().lookup(S);
-assert(Block != nullptr);
-const std::optional &MaybeState = BlockStates[Block->getBlockID()];
+const Stmt &S) {
+const std::optional &MaybeState =
+BlockStates[blockForStmt(S)->getBlockID()];
 assert(MaybeState.has_value());
 return *MaybeState;
   }
 
+  /// Returns the first node that matches `Matcher` (and asserts that the match
+  /// was successful, i.e. the returned node is not null).
+  template 
+  const NodeT &matchNode(MatcherT Matcher) {
+const auto *Node = selectFirst(
+"node", match(Matcher.bind("node"), AST->getASTContext()));
+assert(Node != nullptr);
+return *Node;
+  }
+
   std::unique_ptr AST;
   std::unique_ptr CFCtx;
   std::unique_ptr DACtx;
@@ -130,6 +146,79 @@ TEST_F(DataflowAnalysisTest, 
DiagnoseFunctionDiagnoserCalledOnEachElement) {
" (Lifetime ends)\n")));
 }
 
+// Tests for the statement-to-block map.
+using StmtToBlockTest = DataflowAnalysisTest;
+
+TEST_F(StmtToBlockTest, ConditionalOperator) {
+  std::string Code = R"(
+ 

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

2024-02-21 Thread via cfe-commits

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

>From 63f3ada705b69c27ca37207c6f7e8098896602b7 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| 70 +++
 1 file changed, 70 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..0bf3336527b0a0 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,6 +1,12 @@
 // 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_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +26,70 @@ -(void)meth {
 }
 @end
 
+// Ivars declared in the @interface
+@interface SuperClass : NSObject
+@property (nonatomic, assign) int superClassProperty;
+@end
+
+@implementation SuperClass {
+  int superClassIvar; // Declare an ivar
+}
+- (void)superClassMethod {
+_superClassProperty = 42;
+superClassIvar = 10;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SuperClass
+// CHECK: getelementptr inbounds i8, ptr %1, i64 20
+}
+@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
+}
+
+- (void)intermediateClassPropertyMethod {
+self.intermediateProperty = 0;
+// CHECK: getelementptr inbounds i8, ptr %2, i64 24
+}
+@end
+
+@interface SubClass : IntermediateClass
+{
+double subClassIvar;
+}
+@end
+
+@implementation SubClass
+- (void)subclassVar {
+
+subClassIvar = 6.28;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+-(void)intermediateSubclassVar
+{
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

>From 76eb88980c8ffc07b788809018f81a720de955c6 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 can be statically known

As of now, we only check if a class directly inherits from NSObject to 
determine if said class has fixed offsets and can therefore have its memory 
layout statically known.

However, if an NSObject subclass has fixed offsets, then so must the subclasses 
of that subclass, so this allows us to optimize instances of subclasses of 
subclasses that inherit from NSObject and so on.

To determine this, we need to find that the compiler can see the implementation 
of each intermediate class, as that means it is statically linked.
---
 clang/lib/CodeGen/CGObjCMac.cpp   | 22 ++-
 .../constant-non-fragile-ivar-offset.m| 22 +--
 2 files changed, 27 insertions(+), 17 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index 27d77e9a8a5511..b3d6c3ba314cc2 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -1593,12 +1593,22 @@ class CGObjCNonFragileABIMac : public CGObjCCommonMac {
   }
 
   bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) {
-// NSObject is a fixed size. If we can see the @implementation of a class
-// which inherits from NSObject then we know that all it's offsets also 
must
-// be fixed. FIXME: Can we do this if see a chain of super classes with
-// implementations leading to NSObject?
-return ID->getImplementation() && ID->getSuperClass() &&
-   ID->getSuperClass()->getName() == "NSObject";
+// Test a class by checking its su

[clang] [OpenMP] Remove complex reduction variable support (PR #82497)

2024-02-21 Thread Akash Banerjee via cfe-commits

https://github.com/TIFitis created 
https://github.com/llvm/llvm-project/pull/82497

This patch removes the complex reduction variables codegen. There are currently 
no tests for this, and from playing around with some complex reduction variable 
test cases the code seems unreachable.

The PR #80343 proposes to migrate reductions codegen to the OMPIRBuilder and it 
isn't currently well equipped to handle complex variables. This patch would 
enable PR #80343 to go forward.

>From 9d3e9a44089086fd8528d79709be196123a8d493 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Wed, 21 Feb 2024 15:10:43 +
Subject: [PATCH] [OpenMP] Remove complex reductions

This patch removes the complex reduction variables codegen. There are currently 
no tests for this, and from playing around with some complex reduction variable 
test cases the code seems unreachable.

The PR #80343 proposes to migrate reductions codegen to the OMPIRBuilder and it 
isn't currently well equipped to handle complex variables. This patch would 
enable PR #80343 to go forward.
---
 clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp | 15 +++
 1 file changed, 3 insertions(+), 12 deletions(-)

diff --git a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
index 299ee1460b3db0..a954ad0b3a5e2c 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -1653,12 +1653,7 @@ static void emitReductionListCopy(
 break;
   }
   case TEK_Complex: {
-CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
-CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
-Private->getExprLoc());
-CGF.EmitStoreOfComplex(
-Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
-/*isInit=*/false);
+llvm_unreachable("OpenMP Complex reduction not handled.");
 break;
   }
   case TEK_Aggregate:
@@ -2232,9 +2227,7 @@ static llvm::Value *emitListToGlobalCopyFunction(
   break;
 }
 case TEK_Complex: {
-  CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
-  CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
-  CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
+  llvm_unreachable("OpenMP Complex reduction not handled.");
   break;
 }
 case TEK_Aggregate:
@@ -2439,9 +2432,7 @@ static llvm::Value *emitGlobalToListCopyFunction(
   break;
 }
 case TEK_Complex: {
-  CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
-  CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, 
Private->getType()),
- /*isInit=*/false);
+  llvm_unreachable("OpenMP Complex reduction not handled.");
   break;
 }
 case TEK_Aggregate:

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


[clang] [OpenMP] Remove complex reduction variable support (PR #82497)

2024-02-21 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Akash Banerjee (TIFitis)


Changes

This patch removes the complex reduction variables codegen. There are currently 
no tests for this, and from playing around with some complex reduction variable 
test cases the code seems unreachable.

The PR #80343 proposes to migrate reductions codegen to the 
OMPIRBuilder and it isn't currently well equipped to handle complex variables. 
This patch would enable PR #80343 to go forward.

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


1 Files Affected:

- (modified) clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp (+3-12) 


``diff
diff --git a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
index 299ee1460b3db0..a954ad0b3a5e2c 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -1653,12 +1653,7 @@ static void emitReductionListCopy(
 break;
   }
   case TEK_Complex: {
-CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
-CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
-Private->getExprLoc());
-CGF.EmitStoreOfComplex(
-Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
-/*isInit=*/false);
+llvm_unreachable("OpenMP Complex reduction not handled.");
 break;
   }
   case TEK_Aggregate:
@@ -2232,9 +2227,7 @@ static llvm::Value *emitListToGlobalCopyFunction(
   break;
 }
 case TEK_Complex: {
-  CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
-  CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
-  CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
+  llvm_unreachable("OpenMP Complex reduction not handled.");
   break;
 }
 case TEK_Aggregate:
@@ -2439,9 +2432,7 @@ static llvm::Value *emitGlobalToListCopyFunction(
   break;
 }
 case TEK_Complex: {
-  CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
-  CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, 
Private->getType()),
- /*isInit=*/false);
+  llvm_unreachable("OpenMP Complex reduction not handled.");
   break;
 }
 case TEK_Aggregate:

``




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


[clang] [Headers][X86] Make brief descriptions briefer (PR #82422)

2024-02-21 Thread Paul T Robinson via cfe-commits


@@ -2099,9 +2099,11 @@ static __inline__ __m128i __DEFAULT_FN_ATTRS 
_mm_add_epi64(__m128i __a,
 }
 
 /// Adds, with saturation, the corresponding elements of two 128-bit
-///signed [16 x i8] vectors, saving each sum in the corresponding element 
of
-///a 128-bit result vector of [16 x i8]. Positive sums greater than 0x7F 
are
-///saturated to 0x7F. Negative sums less than 0x80 are saturated to 0x80.
+///signed [16 x i8] vectors, saving each sum in the corresponding element
+///of a 128-bit result vector of [16 x i8].
+///

pogo59 wrote:

The [description of 
brief](https://www.doxygen.nl/manual/commands.html#cmdbrief) says "A brief 
description ends when a blank line or another sectioning command is 
encountered." About the only command that would make sense here is \par which 
has to be on a line by itself, so the result would not be more compact.

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


[clang] [llvm] [Clang][SME] Detect always_inline used with mismatched streaming attributes (PR #77936)

2024-02-21 Thread Sam Tebbs via cfe-commits


@@ -0,0 +1,47 @@
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -S -target-feature +sme 
-verify -DTEST_NONE -x c %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -S -target-feature +sme 
-verify -DTEST_COMPATIBLE -x c %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -S -target-feature +sme 
-verify -DTEST_STREAMING -x c %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -S -target-feature +sme 
-verify -DTEST_LOCALLY -x c %s

SamTebbs33 wrote:

Unfortunately the part of the code that checks this isn't run under 
-fsyntax-only. It's the same for the existing target feature checks with 
always_inline: https://godbolt.org/z/frrbeah7d

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


[clang] [llvm] [Clang][SME] Detect always_inline used with mismatched streaming attributes (PR #77936)

2024-02-21 Thread Sam Tebbs via cfe-commits

https://github.com/SamTebbs33 updated 
https://github.com/llvm/llvm-project/pull/77936

>From 7314429a203900a8f555e1b0471fdd4cfd4d8d03 Mon Sep 17 00:00:00 2001
From: Samuel Tebbs 
Date: Wed, 10 Jan 2024 14:57:04 +
Subject: [PATCH 01/18] [Clang][SME] Detect always_inline used with mismatched
 streaming attributes

This patch adds an error that is emitted when a streaming function is
marked as always_inline and is called from a non-streaming function.
---
 .../clang/Basic/DiagnosticFrontendKinds.td|  2 ++
 clang/include/clang/Sema/Sema.h   |  9 +++
 clang/lib/CodeGen/CMakeLists.txt  |  1 +
 clang/lib/CodeGen/Targets/AArch64.cpp | 20 ++
 clang/lib/Sema/SemaChecking.cpp   | 27 +++
 ...-sme-func-attrs-inline-locally-streaming.c | 12 +
 .../aarch64-sme-func-attrs-inline-streaming.c | 12 +
 7 files changed, 66 insertions(+), 17 deletions(-)
 create mode 100644 
clang/test/CodeGen/aarch64-sme-func-attrs-inline-locally-streaming.c
 create mode 100644 clang/test/CodeGen/aarch64-sme-func-attrs-inline-streaming.c

diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td 
b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index 85ecfdf9de62d4..2d0f971858840d 100644
--- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -279,6 +279,8 @@ def err_builtin_needs_feature : Error<"%0 needs target 
feature %1">;
 def err_function_needs_feature : Error<
   "always_inline function %1 requires target feature '%2', but would "
   "be inlined into function %0 that is compiled without support for '%2'">;
+def err_function_alwaysinline_attribute_mismatch : Error<
+  "always_inline function %1 and its caller %0 have mismatched %2 attributes">;
 
 def warn_avx_calling_convention
 : Warning<"AVX vector %select{return|argument}0 of type %1 without '%2' "
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 6ce422d66ae5b0..dd75b5aad3d9c8 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -13832,8 +13832,17 @@ class Sema final {
 FormatArgumentPassingKind ArgPassingKind;
   };
 
+enum ArmStreamingType {
+  ArmNonStreaming,
+  ArmStreaming,
+  ArmStreamingCompatible,
+  ArmStreamingOrSVE2p1
+};
+
+
   static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
   bool IsVariadic, FormatStringInfo *FSI);
+  static ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD);
 
 private:
   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
diff --git a/clang/lib/CodeGen/CMakeLists.txt b/clang/lib/CodeGen/CMakeLists.txt
index 52216d93a302bb..03a6f2f1d7a9d2 100644
--- a/clang/lib/CodeGen/CMakeLists.txt
+++ b/clang/lib/CodeGen/CMakeLists.txt
@@ -151,4 +151,5 @@ add_clang_library(clangCodeGen
   clangFrontend
   clangLex
   clangSerialization
+  clangSema
   )
diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp 
b/clang/lib/CodeGen/Targets/AArch64.cpp
index ee7f95084d2e0b..4018f91422e358 100644
--- a/clang/lib/CodeGen/Targets/AArch64.cpp
+++ b/clang/lib/CodeGen/Targets/AArch64.cpp
@@ -8,6 +8,8 @@
 
 #include "ABIInfoImpl.h"
 #include "TargetInfo.h"
+#include "clang/Basic/DiagnosticFrontend.h"
+#include "clang/Sema/Sema.h"
 
 using namespace clang;
 using namespace clang::CodeGen;
@@ -155,6 +157,11 @@ class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
 }
 return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty);
   }
+
+  void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
+const FunctionDecl *Caller,
+const FunctionDecl *Callee,
+const CallArgList &Args) const override;
 };
 
 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
@@ -814,6 +821,19 @@ Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, 
Address VAListAddr,
   /*allowHigherAlign*/ false);
 }
 
+void AArch64TargetCodeGenInfo::checkFunctionCallABI(
+CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
+const FunctionDecl *Callee, const CallArgList &Args) const {
+if (!Callee->hasAttr())
+  return;
+
+auto CalleeIsStreaming = Sema::getArmStreamingFnType(Callee) == 
Sema::ArmStreaming;
+auto CallerIsStreaming = Sema::getArmStreamingFnType(Caller) == 
Sema::ArmStreaming;
+
+if (CalleeIsStreaming && !CallerIsStreaming)
+CGM.getDiags().Report(CallLoc, 
diag::err_function_alwaysinline_attribute_mismatch) << Caller->getDeclName() << 
Callee->getDeclName() << "streaming";
+}
+
 std::unique_ptr
 CodeGen::createAArch64TargetCodeGenInfo(CodeGenModule &CGM,
 AArch64ABIKind Kind) {
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index ace3e386988f00..a92db7d67e1cbd 100644
--- a/clang/lib/S

[clang] [llvm] [Clang][SME] Detect always_inline used with mismatched streaming attributes (PR #77936)

2024-02-21 Thread Jon Roelofs via cfe-commits


@@ -814,6 +820,43 @@ Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, 
Address VAListAddr,
   /*allowHigherAlign*/ false);
 }
 
+static bool isStreaming(const FunctionDecl *F) {
+  if (F->hasAttr())
+return true;
+  if (const auto *T = F->getType()->getAs())
+return T->getAArch64SMEAttributes() & 
FunctionType::SME_PStateSMEnabledMask;
+  return false;
+}
+
+static bool isStreamingCompatible(const FunctionDecl *F) {
+  if (const auto *T = F->getType()->getAs())
+return T->getAArch64SMEAttributes() &
+   FunctionType::SME_PStateSMCompatibleMask;
+  return false;
+}

jroelofs wrote:

@sdesmalen-arm WDYT about making these two free functions into members of 
FunctionDecl? Seems like copies of these helpers are proliferating.

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


[clang] [clang][dataflow] Fix inaccuracies in `buildStmtToBasicBlockMap()`. (PR #82496)

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

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

Nice work! Quite subtle...

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


  1   2   3   >