[clang] [compiler-rt] [Sanitizer] add signed-integer-wrap sanitizer (PR #80089)

2024-02-20 Thread Fangrui Song via cfe-commits

MaskRay wrote:

> GCC folks have not answered. Adding -wrap keeps the behavior for -overflow 
> the same between GCC and Clang. Can we please move this forward and land it 
> as is? We can trivially change this in the future if we need to.

I believe we can move forward by reusing `-fsanitize=signed-integer-overflow`, 
which adds least complexity to Clang and is very reasonable.

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


[clang] [compiler-rt] [Sanitizer] add signed-integer-wrap sanitizer (PR #80089)

2024-02-20 Thread Fangrui Song via cfe-commits

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

.

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


[clang] [llvm] [AMDGPU] Fix operand types for `V_DOT2_F32_BF16` (PR #82044)

2024-02-20 Thread Stanislav Mekhanoshin via cfe-commits

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


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


[clang] The lambda call inside of a type alias (PR #82310)

2024-02-20 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 updated 
https://github.com/llvm/llvm-project/pull/82310

>From 0f97fae5d1ba4debe04824e5d2d98598504d003d Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Tue, 20 Feb 2024 14:54:14 +0800
Subject: [PATCH 1/2] The lambda call inside of a type alias

---
 clang/docs/ReleaseNotes.rst   |  5 ++
 clang/include/clang/AST/DeclCXX.h |  4 +
 clang/include/clang/Sema/Sema.h   |  8 ++
 clang/lib/Frontend/FrontendActions.cpp|  2 +
 clang/lib/Sema/SemaConcept.cpp| 15 ++--
 clang/lib/Sema/SemaTemplate.cpp   |  9 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 64 ++-
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |  5 ++
 clang/lib/Sema/TreeTransform.h|  9 ++
 .../alias-template-with-lambdas.cpp   | 82 +++
 10 files changed, 189 insertions(+), 14 deletions(-)
 create mode 100644 clang/test/SemaTemplate/alias-template-with-lambdas.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 649ad655905af2..7988912faa2075 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -267,6 +267,11 @@ Bug Fixes to C++ Support
   was only accepted at namespace scope but not at local function scope.
 - Clang no longer tries to call consteval constructors at runtime when they 
appear in a member initializer.
   (`#782154 `_`)
+- Clang now supports direct lambda calls inside of a type alias template 
declarations.
+  This addresses (`#70601 
`_),
+  (`#76674 `_),
+  (`#79555 `_),
+  (`#81145 `_), and so on.
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/AST/DeclCXX.h 
b/clang/include/clang/AST/DeclCXX.h
index 9cebaff63bb0db..7aed4d5cbc002e 100644
--- a/clang/include/clang/AST/DeclCXX.h
+++ b/clang/include/clang/AST/DeclCXX.h
@@ -1869,6 +1869,10 @@ class CXXRecordDecl : public RecordDecl {
 DL.MethodTyInfo = TS;
   }
 
+  void setLambdaDependencyKind(unsigned Kind) {
+getLambdaData().DependencyKind = Kind;
+  }
+
   void setLambdaIsGeneric(bool IsGeneric) {
 assert(DefinitionData && DefinitionData->IsLambda &&
"setting lambda property of non-lambda class");
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index e9cd42ae777df5..488d2e07a2732e 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -9622,6 +9622,8 @@ class Sema final {
 
   /// We are building deduction guides for a class.
   BuildingDeductionGuides,
+
+  TypeAliasTemplateInstantiation,
 } Kind;
 
 /// Was the enclosing context a non-instantiation SFINAE context?
@@ -9812,6 +9814,12 @@ class Sema final {
   FunctionDecl *Entity, ExceptionSpecification,
   SourceRange InstantiationRange = SourceRange());
 
+/// Note that we are instantiating a type alias template declaration.
+InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
+  TypeAliasTemplateDecl *Template,
+  ArrayRef TemplateArgs,
+  SourceRange InstantiationRange = SourceRange());
+
 /// Note that we are instantiating a default argument in a
 /// template-id.
 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
diff --git a/clang/lib/Frontend/FrontendActions.cpp 
b/clang/lib/Frontend/FrontendActions.cpp
index b9ed5dedfa4223..43d6e2230fb129 100644
--- a/clang/lib/Frontend/FrontendActions.cpp
+++ b/clang/lib/Frontend/FrontendActions.cpp
@@ -426,6 +426,8 @@ class DefaultTemplateInstCallback : public 
TemplateInstantiationCallback {
   return "BuildingBuiltinDumpStructCall";
 case CodeSynthesisContext::BuildingDeductionGuides:
   return "BuildingDeductionGuides";
+case Sema::CodeSynthesisContext::TypeAliasTemplateInstantiation:
+  return "TypeAliasTemplateInstantiation";
 }
 return "";
   }
diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 2878e4d31ee8fe..5cc6236c3991b6 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -614,14 +614,13 @@ bool Sema::SetupConstraintScope(
 // reference the original primary template.
 // We walk up the instantiated template chain so that nested lambdas get
 // handled properly.
-for (FunctionTemplateDecl *FromMemTempl =
- PrimaryTemplate->getInstantiatedFromMemberTemplate();
- FromMemTempl;
- FromMemTempl = FromMemTempl->getInstantiatedFromMemberTemplate()) {
-  if (addInstantiatedParametersToScope(FD, 
FromMemTempl->getTemplatedDecl(),
-   

[clang] 119a728 - [clang-format][NFC] Remove redundant calls to guessIsObjC()

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

Author: Owen Pan
Date: 2024-02-20T00:28:26-08:00
New Revision: 119a72866f0e143127355fe6e03f57c4f8bab1ae

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

LOG: [clang-format][NFC] Remove redundant calls to guessIsObjC()

Running clang-format on the following input
```
int lambdas() {
  return [&] {
  return [&] {
  return [&] {
  return [&] {
  return [&] {
  return [&] {
  return [&] { return 3; } ();
  } (); } (); } (); } (); } (); } (); }
```
will finish instantly if you pass clang-format a .cpp input with this
content, but hang for tens of seconds if you pass the same via stdin
or a .h file.

Adding some debug statements showed that guessIsObjC was getting called
tens of millions of times in a manner that scales very rapidly with the
amount of nesting (if clang-format just takes a few seconds with that
input passed on stdin, try adding a couple more levels of nesting).

This change moves the recursive guessIsObjC call one level of nesting
out of an inner loop whose iterations don't affect the input to the
recursive call. This resolves the performance issue.

Authored-by: davidvc1 and Uran198

Differential Revision: https://reviews.llvm.org/D114837
Differential Revision: https://reviews.llvm.org/D47515

Added: 


Modified: 
clang/lib/Format/Format.cpp

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index e67b2101f5821b..2c815128b1a59d 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -2948,9 +2948,9 @@ class ObjCHeaderStyleGuesser : public TokenAnalyzer {
  << getTokenTypeName(FormatTok->getType()) << "\n");
   return true;
 }
-if (guessIsObjC(SourceManager, Line->Children, Keywords))
-  return true;
   }
+  if (guessIsObjC(SourceManager, Line->Children, Keywords))
+return true;
 }
 return false;
   }



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


[clang] The lambda call inside of a type alias (PR #82310)

2024-02-20 Thread Younan Zhang via cfe-commits

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


[clang] [Clang][Sema] Fix the lambda call expression inside of a type alias declaration (PR #82310)

2024-02-20 Thread Younan Zhang via cfe-commits

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


[clang] [Clang][Sema] Fix the lambda call expression inside of a type alias declaration (PR #82310)

2024-02-20 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

The Windows CI is still broken and I have to run the libc++ tests locally.

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


[clang] [clang][analyzer] Simplify code of StreamChecker (NFC). (PR #82228)

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

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

From 0c93cbe17010dfd1382486952d80898ba1360243 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bal=C3=A1zs=20K=C3=A9ri?= 
Date: Mon, 19 Feb 2024 09:39:30 +0100
Subject: [PATCH 1/2] [clang][analyzer] Simplify code of StreamChecker (NFC).

Continuation of commit 42b5037, apply changes to the remaining
functions.
Code for function `fflush` was not changed, because it is more
special compared to the others.
---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 345 ++
 1 file changed, 112 insertions(+), 233 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 354217c1e52922..82296e0b83649b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -265,6 +265,11 @@ struct StreamOperationEvaluator {
SVB.makeIntVal(Val, CE->getCallReturnType(ACtx)));
   }
 
+  ProgramStateRef bindReturnValue(ProgramStateRef State, CheckerContext &C,
+  SVal Val) {
+return State->BindExpr(CE, C.getLocationContext(), Val);
+  }
+
   ProgramStateRef bindNullReturnValue(ProgramStateRef State,
   CheckerContext &C) {
 return State->BindExpr(CE, C.getLocationContext(),
@@ -280,6 +285,13 @@ struct StreamOperationEvaluator {
   return nullptr;
 return State->assume(*Cond, true);
   }
+
+  ProgramStatePair makeRetValAndAssumeDual(ProgramStateRef State,
+   CheckerContext &C) {
+DefinedSVal RetVal = makeRetVal(C, CE);
+State = State->BindExpr(CE, C.getLocationContext(), RetVal);
+return C.getConstraintManager().assumeDual(State, RetVal);
+  }
 };
 
 class StreamChecker : public Checker(Call.getOriginExpr());
-  if (!CE)
-return;
 
-  const StreamState *OldSS = State->get(StreamSym);
-  if (!OldSS)
+  ProgramStateRef State = C.getState();
+  StreamOperationEvaluator E(C);
+  if (!E.Init(Desc, Call, C, State))
 return;
 
-  assertStreamStateOpened(OldSS);
-
-  NonLoc RetVal = makeRetVal(C, CE).castAs();
-  State = State->BindExpr(CE, C.getLocationContext(), RetVal);
-  SValBuilder &SVB = C.getSValBuilder();
-  auto &ACtx = C.getASTContext();
-  auto Cond = SVB.evalBinOp(State, BO_GE, RetVal, SVB.makeZeroVal(ACtx.IntTy),
-SVB.getConditionType())
-  .getAs();
+  NonLoc RetVal = makeRetVal(C, E.CE).castAs();
+  State = State->BindExpr(E.CE, C.getLocationContext(), RetVal);
+  auto Cond =
+  E.SVB
+  .evalBinOp(State, BO_GE, RetVal, E.SVB.makeZeroVal(E.ACtx.IntTy),
+ E.SVB.getConditionType())
+  .getAs();
   if (!Cond)
 return;
   ProgramStateRef StateNotFailed, StateFailed;
   std::tie(StateNotFailed, StateFailed) = State->assume(*Cond);
 
   StateNotFailed =
-  StateNotFailed->set(StreamSym, StreamState::getOpened(Desc));
+  E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
   C.addTransition(StateNotFailed);
 
   // Add transition for the failed state. The resulting value of the file
   // position indicator for the stream is indeterminate.
-  StateFailed = StateFailed->set(
-  StreamSym, StreamState::getOpened(Desc, ErrorFError, true));
+  StateFailed = E.setStreamState(
+  StateFailed, StreamState::getOpened(Desc, ErrorFError, true));
   C.addTransition(StateFailed);
 }
 
 void StreamChecker::evalFscanf(const FnDescription *Desc, const CallEvent 
&Call,
CheckerContext &C) const {
-  ProgramStateRef State = C.getState();
   if (Call.getNumArgs() < 2)
 return;
-  SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
-  if (!StreamSym)
-return;
-
-  const CallExpr *CE = dyn_cast_or_null(Call.getOriginExpr());
-  if (!CE)
-return;
 
-  const StreamState *OldSS = State->get(StreamSym);
-  if (!OldSS)
+  ProgramStateRef State = C.getState();
+  StreamOperationEvaluator E(C);
+  if (!E.Init(Desc, Call, C, State))
 return;
 
-  assertStreamStateOpened(OldSS);
-
-  SValBuilder &SVB = C.getSValBuilder();
-  ASTContext &ACtx = C.getASTContext();
-
   // 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,
@@ -1007,19 +998,15 @@ void StreamChecker::evalFscanf(const FnDescription 
*Desc, const CallEvent &Call,
   // then EOF or read error happens. Now this case is handled like a "success"
   // case, and no error flags are set on the stream. This is probably not
   // accurate, and the POSIX documentation does not tell more.
-  if (OldSS->ErrorState != ErrorFEof) {
-NonLoc RetVal = makeRetVal(C, CE).castAs();
+  if (!E.isStreamEof()) {
+NonLoc RetVal = makeRetVal(C, E.CE).castAs();
 ProgramStateRef StateNotFailed =
-State->Bind

[clang] [clang][analyzer] Simplify code of StreamChecker (NFC). (PR #82228)

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

balazske wrote:

The initial commit was somehow incomplete and code was not tested. New commit 
should fix the problems.

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


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

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

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

>From c25b0ba3286c008dc8ebcea72f28db3e05fcbf3c 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 | 225 --
 .../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, 290 insertions(+), 119 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index a7891d2da07c18..ee7dd4199b0ff8 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -244,18 +244,43 @@ 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 +296,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 +318,27 @@ 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 De

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

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

owenca wrote:

> > couldn't we just use the .clang-format-ignore file to say... hey don't 
> > bother with this file, we can't do it...
> 
> I think that's a good solution for avoiding the OOM when actually trying to 
> format the file, in combination with this patch for avoiding the OOM in 
> `guessLanguage()`.
> 
> The reason this is such a severe issue for clangd is that clangd calls into 
> `guessLanguage()` whenever a file is opened, thereby triggering the OOM for 
> any downstream user of such a single-header library who happens to open the 
> header in their editor, not just developers of the library itself. Those 
> users have no reason to try to format the library header, so this would solve 
> what's otherwise a puzzling hang for them with no configuration required.

The OOM is not limited to `guessLanguage()`. (See 119a72866f0e for an 
improvement to the performance of `guessLanguage()`.) It occurs even if you 
rename the header files to .cpp files and clang-format the renamed files 
directly. I'm with @mydeveloperday on this and believe a more general solution 
is needed.

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


[clang] [analyzer] UnixAPIMisuseChecker Get O_CREAT from preprocessor (PR #81855)

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

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

I did not find problems now. The failed checks looks to be different problem.

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


[clang] [Clang][Sema] fix crash in codegen stage when an lambda expression declared in an unevaluated context (PR #80802)

2024-02-20 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

@jcsxky Do you have more test cases other than the one from #76674? I wonder 
what'll happen if constraint checking is involved.

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


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

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

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

>From e2da6c6663235cfe086b6721a219fe6bddfad415 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 | 223 --
 .../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, 288 insertions(+), 119 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index a7891d2da07c18..cdca313746578b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -244,18 +244,42 @@ 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 +295,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 +317,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->

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

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

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

>From 383c7bf1a02f7cb2f1050fc8653ecd4d455f089c 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 | 223 --
 .../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, 288 insertions(+), 119 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index a7891d2da07c18..ba4f496dffa995 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -244,18 +244,42 @@ 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 +295,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 +317,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->

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

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

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

>From 8b2cf0bfe5b7b59c4ec8e28ad50b5d47128d1f86 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] [Clang][Sema] Fix the lambda call expression inside of a type alias declaration (PR #82310)

2024-02-20 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

Result for libc++ tests:
```

Failed Tests (1):
  llvm-libc++-shared.cfg.in :: libcxx/headers_in_modulemap.sh.py


Testing Time: 1232.89s

Total Discovered Tests: 9673
  Unsupported  :  585 (6.05%)
  Passed   : 9062 (93.68%)
  Expectedly Failed:   25 (0.26%)
  Failed   :1 (0.01%)
```

The failing test seems to be my local configuration issue and doesn't relate to 
this patch IIUC.

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


[clang] 37c19f9 - [analyzer] UnixAPIMisuseChecker Get O_CREAT from preprocessor (#81855)

2024-02-20 Thread via cfe-commits

Author: Alejandro Álvarez Ayllón
Date: 2024-02-20T10:25:01+01:00
New Revision: 37c19f9a35c5adad009ad82c608b9ca11155ec06

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

LOG: [analyzer] UnixAPIMisuseChecker Get O_CREAT from preprocessor (#81855)

Now calling `open` with the `O_CREAT` flag and no mode parameter will
raise an issue in any system that defines `O_CREAT`.

The value for this flag is obtained after the full source code has been
parsed, leveraging `checkASTDecl`.
Hence, any `#define` or `#undefine` of `O_CREAT` following an `open` may
alter the results. Nevertheless, since redefining reserved identifiers
is UB, this is probably ok.

Added: 
clang/test/Analysis/unix-fns-o_creat.c

Modified: 
clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
clang/test/Analysis/Inputs/expected-plists/unix-fns.c.plist
clang/test/Analysis/unix-fns.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
index b05ce610067cfa..19f1ca2dc824c9 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
@@ -18,6 +18,7 @@
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
@@ -39,13 +40,18 @@ enum class OpenVariant {
 
 namespace {
 
-class UnixAPIMisuseChecker : public Checker< check::PreStmt > {
+class UnixAPIMisuseChecker
+: public Checker,
+ check::ASTDecl> {
   const BugType BT_open{this, "Improper use of 'open'", categories::UnixAPI};
   const BugType BT_pthreadOnce{this, "Improper use of 'pthread_once'",
categories::UnixAPI};
   mutable std::optional Val_O_CREAT;
 
 public:
+  void checkASTDecl(const TranslationUnitDecl *TU, AnalysisManager &Mgr,
+BugReporter &BR) const;
+
   void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
 
   void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
@@ -55,11 +61,8 @@ class UnixAPIMisuseChecker : public Checker< 
check::PreStmt > {
   void CheckOpenVariant(CheckerContext &C,
 const CallExpr *CE, OpenVariant Variant) const;
 
-  void ReportOpenBug(CheckerContext &C,
- ProgramStateRef State,
- const char *Msg,
+  void ReportOpenBug(CheckerContext &C, ProgramStateRef State, const char *Msg,
  SourceRange SR) const;
-
 };
 
 class UnixAPIPortabilityChecker : public Checker< check::PreStmt > {
@@ -90,7 +93,21 @@ class UnixAPIPortabilityChecker : public Checker< 
check::PreStmt > {
 const char *fn) const;
 };
 
-} //end anonymous namespace
+} // end anonymous namespace
+
+void UnixAPIMisuseChecker::checkASTDecl(const TranslationUnitDecl *TU,
+AnalysisManager &Mgr,
+BugReporter &) const {
+  // The definition of O_CREAT is platform specific.
+  // Try to get the macro value from the preprocessor.
+  Val_O_CREAT = tryExpandAsInteger("O_CREAT", Mgr.getPreprocessor());
+  // If we failed, fall-back to known values.
+  if (!Val_O_CREAT) {
+if (TU->getASTContext().getTargetInfo().getTriple().getVendor() ==
+llvm::Triple::Apple)
+  Val_O_CREAT = 0x0200;
+  }
+}
 
 
//===--===//
 // "open" (man 2 open)
@@ -204,19 +221,8 @@ void UnixAPIMisuseChecker::CheckOpenVariant(CheckerContext 
&C,
 return;
   }
 
-  // The definition of O_CREAT is platform specific.  We need a better way
-  // of querying this information from the checking environment.
   if (!Val_O_CREAT) {
-if (C.getASTContext().getTargetInfo().getTriple().getVendor()
-  == llvm::Triple::Apple)
-  Val_O_CREAT = 0x0200;
-else {
-  // FIXME: We need a more general way of getting the O_CREAT value.
-  // We could possibly grovel through the preprocessor state, but
-  // that would require passing the Preprocessor object to the ExprEngine.
-  // See also: MallocChecker.cpp / M_ZERO.
-  return;
-}
+return;
   }
 
   // Now check if oflags has O_CREAT set.

diff  --git a/clang/test/Analysis/Inputs/expected-plists/unix-fns.c.plist 
b/clang/test/Analysis/Inputs/expected-plists/unix-fns.c.plist
index 2594f3b6d097d5..d7913cbc338fd0 100644
--- a/clang/test/Analysis/Inputs/expected-plists/unix-fns.c.plist
+++ b/clang/te

[clang] [analyzer] UnixAPIMisuseChecker Get O_CREAT from preprocessor (PR #81855)

2024-02-20 Thread Balazs Benics via cfe-commits
Alejandro =?utf-8?q?Álvarez_Ayllón?Message-ID:
In-Reply-To: 


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


[clang] [Clang][Sema] Fix the lambda call expression inside of a type alias declaration (PR #82310)

2024-02-20 Thread Younan Zhang via cfe-commits

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


[clang] [Clang][Sema] Fix the lambda call expression inside of a type alias declaration (PR #82310)

2024-02-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Younan Zhang (zyn0217)


Changes

This patch attempts to fix the lambda call expression inside of a type alias 
declaration from two aspects:
1. Defer the lambda call expression building until after we have sufficient 
template arguments. This avoids the overeager (and often wrong) semantic 
checking before the type alias instantiation.
2. Properly obtain template arguments involving a template type alias for 
constraint checking.

It is unfortunate that a `TypeAliasTemplateDecl` (or a `TypeAliasDecl`) is 
never a `DeclContext`, nor does it have an associated specialization Decl from 
which we could collect these template arguments. Thus, I added a new 
CodeSynthesisContext to record template arguments for alias declarations.

Fixes https://github.com/llvm/llvm-project/issues/70601
Fixes https://github.com/llvm/llvm-project/issues/76674
Fixes https://github.com/llvm/llvm-project/issues/79555
Fixes https://github.com/llvm/llvm-project/issues/81145

Note that this doesn't involve the fix for 
https://github.com/llvm/llvm-project/issues/23317. That seems different, and 
I'd like to leave it as a follow-up.

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


10 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+5) 
- (modified) clang/include/clang/AST/DeclCXX.h (+4) 
- (modified) clang/include/clang/Sema/Sema.h (+9) 
- (modified) clang/lib/Frontend/FrontendActions.cpp (+2) 
- (modified) clang/lib/Sema/SemaConcept.cpp (+8-4) 
- (modified) clang/lib/Sema/SemaTemplate.cpp (+7-3) 
- (modified) clang/lib/Sema/SemaTemplateInstantiate.cpp (+95-3) 
- (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+5) 
- (modified) clang/lib/Sema/TreeTransform.h (+31) 
- (added) clang/test/SemaTemplate/alias-template-with-lambdas.cpp (+82) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 649ad655905af2..7988912faa2075 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -267,6 +267,11 @@ Bug Fixes to C++ Support
   was only accepted at namespace scope but not at local function scope.
 - Clang no longer tries to call consteval constructors at runtime when they 
appear in a member initializer.
   (`#782154 `_`)
+- Clang now supports direct lambda calls inside of a type alias template 
declarations.
+  This addresses (`#70601 
`_),
+  (`#76674 `_),
+  (`#79555 `_),
+  (`#81145 `_), and so on.
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/AST/DeclCXX.h 
b/clang/include/clang/AST/DeclCXX.h
index 9cebaff63bb0db..7aed4d5cbc002e 100644
--- a/clang/include/clang/AST/DeclCXX.h
+++ b/clang/include/clang/AST/DeclCXX.h
@@ -1869,6 +1869,10 @@ class CXXRecordDecl : public RecordDecl {
 DL.MethodTyInfo = TS;
   }
 
+  void setLambdaDependencyKind(unsigned Kind) {
+getLambdaData().DependencyKind = Kind;
+  }
+
   void setLambdaIsGeneric(bool IsGeneric) {
 assert(DefinitionData && DefinitionData->IsLambda &&
"setting lambda property of non-lambda class");
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index e9cd42ae777df5..5847b0301a4ca4 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -9622,6 +9622,9 @@ class Sema final {
 
   /// We are building deduction guides for a class.
   BuildingDeductionGuides,
+
+  /// We are instantiating a type alias template declaration.
+  TypeAliasTemplateInstantiation,
 } Kind;
 
 /// Was the enclosing context a non-instantiation SFINAE context?
@@ -9812,6 +9815,12 @@ class Sema final {
   FunctionDecl *Entity, ExceptionSpecification,
   SourceRange InstantiationRange = SourceRange());
 
+/// Note that we are instantiating a type alias template declaration.
+InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
+  TypeAliasTemplateDecl *Template,
+  ArrayRef TemplateArgs,
+  SourceRange InstantiationRange = SourceRange());
+
 /// Note that we are instantiating a default argument in a
 /// template-id.
 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
diff --git a/clang/lib/Frontend/FrontendActions.cpp 
b/clang/lib/Frontend/FrontendActions.cpp
index b9ed5dedfa4223..43d6e2230fb129 100644
--- a/clang/lib/Frontend/FrontendActions.cpp
+++ b/clang/lib/Frontend/FrontendActions.cpp
@@ -426,6 +426,8 @@ class DefaultTemplateInstCallback : public 
TemplateInstantiationCallback {
   return "BuildingBuiltinDumpStructCall";
 case CodeSynthesisContext::BuildingDeductionGuide

[clang] 9fa18f6 - [clang][Interp] Handle complex values in visitBool() (#79452)

2024-02-20 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-02-20T10:27:41+01:00
New Revision: 9fa18f65983ba761c9fbf7be4c67801a14bf4b34

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

LOG: [clang][Interp] Handle complex values in visitBool() (#79452)

In C++, we get a ComplexToBool cast, but we might not in C.

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/lib/AST/Interp/ByteCodeExprGen.h
clang/test/AST/Interp/c.c
clang/test/AST/Interp/complex.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 2fdc6f4f32bed9..d4b285941d46d1 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -241,57 +241,11 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
 
   case CK_IntegralComplexToBoolean:
   case CK_FloatingComplexToBoolean: {
-PrimType ElemT = classifyComplexElementType(SubExpr->getType());
-// We emit the expression (__real(E) != 0 || __imag(E) != 0)
-// for us, that means (bool)E[0] || (bool)E[1]
+if (DiscardResult)
+  return this->discard(SubExpr);
 if (!this->visit(SubExpr))
   return false;
-if (!this->emitConstUint8(0, CE))
-  return false;
-if (!this->emitArrayElemPtrUint8(CE))
-  return false;
-if (!this->emitLoadPop(ElemT, CE))
-  return false;
-if (ElemT == PT_Float) {
-  if (!this->emitCastFloatingIntegral(PT_Bool, CE))
-return false;
-} else {
-  if (!this->emitCast(ElemT, PT_Bool, CE))
-return false;
-}
-
-// We now have the bool value of E[0] on the stack.
-LabelTy LabelTrue = this->getLabel();
-if (!this->jumpTrue(LabelTrue))
-  return false;
-
-if (!this->emitConstUint8(1, CE))
-  return false;
-if (!this->emitArrayElemPtrPopUint8(CE))
-  return false;
-if (!this->emitLoadPop(ElemT, CE))
-  return false;
-if (ElemT == PT_Float) {
-  if (!this->emitCastFloatingIntegral(PT_Bool, CE))
-return false;
-} else {
-  if (!this->emitCast(ElemT, PT_Bool, CE))
-return false;
-}
-// Leave the boolean value of E[1] on the stack.
-LabelTy EndLabel = this->getLabel();
-this->jump(EndLabel);
-
-this->emitLabel(LabelTrue);
-if (!this->emitPopPtr(CE))
-  return false;
-if (!this->emitConstBool(true, CE))
-  return false;
-
-this->fallthrough(EndLabel);
-this->emitLabel(EndLabel);
-
-return true;
+return this->emitComplexBoolCast(SubExpr);
   }
 
   case CK_IntegralComplexToReal:
@@ -2223,8 +2177,15 @@ bool ByteCodeExprGen::visitInitializer(const 
Expr *E) {
 template 
 bool ByteCodeExprGen::visitBool(const Expr *E) {
   std::optional T = classify(E->getType());
-  if (!T)
+  if (!T) {
+// Convert complex values to bool.
+if (E->getType()->isAnyComplexType()) {
+  if (!this->visit(E))
+return false;
+  return this->emitComplexBoolCast(E);
+}
 return false;
+  }
 
   if (!this->visit(E))
 return false;
@@ -3383,6 +3344,63 @@ bool ByteCodeExprGen::emitComplexReal(const 
Expr *SubExpr) {
   return true;
 }
 
+template 
+bool ByteCodeExprGen::emitComplexBoolCast(const Expr *E) {
+  assert(!DiscardResult);
+  PrimType ElemT = classifyComplexElementType(E->getType());
+  // We emit the expression (__real(E) != 0 || __imag(E) != 0)
+  // for us, that means (bool)E[0] || (bool)E[1]
+  if (!this->emitConstUint8(0, E))
+return false;
+  if (!this->emitArrayElemPtrUint8(E))
+return false;
+  if (!this->emitLoadPop(ElemT, E))
+return false;
+  if (ElemT == PT_Float) {
+if (!this->emitCastFloatingIntegral(PT_Bool, E))
+  return false;
+  } else {
+if (!this->emitCast(ElemT, PT_Bool, E))
+  return false;
+  }
+
+  // We now have the bool value of E[0] on the stack.
+  LabelTy LabelTrue = this->getLabel();
+  if (!this->jumpTrue(LabelTrue))
+return false;
+
+  if (!this->emitConstUint8(1, E))
+return false;
+  if (!this->emitArrayElemPtrPopUint8(E))
+return false;
+  if (!this->emitLoadPop(ElemT, E))
+return false;
+  if (ElemT == PT_Float) {
+if (!this->emitCastFloatingIntegral(PT_Bool, E))
+  return false;
+  } else {
+if (!this->emitCast(ElemT, PT_Bool, E))
+  return false;
+  }
+  // Leave the boolean value of E[1] on the stack.
+  LabelTy EndLabel = this->getLabel();
+  this->jump(EndLabel);
+
+  this->emitLabel(LabelTrue);
+  if (!this->emitPopPtr(E))
+return false;
+  if (!this->emitConstBool(true, E))
+return false;
+
+  this->fallthrough(EndLabel);
+  this->emitLabel(EndLabel);
+
+  return true;
+}
+
+/// When calling this, we have a pointer of the local-to-destroy
+/// on the stack.
+/// Emit destruction of record types (or arrays of record typ

[clang] [clang][Interp] Handle complex values in visitBool() (PR #79452)

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

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


[clang] [Clang][Sema] Fix the lambda call expression inside of a type alias declaration (PR #82310)

2024-02-20 Thread Younan Zhang via cfe-commits

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


[clang] [Clang][Sema] Fix the lambda call expression inside of a type alias declaration (PR #82310)

2024-02-20 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

Also added @shafik for some insights on tests / other existing issues.

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


[clang] 3be9132 - [clang][analyzer] Simplify code of StreamChecker - part 2 (NFC). (#82228)

2024-02-20 Thread via cfe-commits

Author: Balázs Kéri
Date: 2024-02-20T10:57:30+01:00
New Revision: 3be913289893bf695ef679647c0e1a71128ae812

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

LOG: [clang][analyzer] Simplify code of StreamChecker - part 2 (NFC). (#82228)

Continuation of commit 42b5037, apply changes to the remaining
functions.
Code for function `fflush` was not changed, because it is more special
compared to the others.

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 354217c1e52922..7e7e3f0eee2b48 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -265,6 +265,11 @@ struct StreamOperationEvaluator {
SVB.makeIntVal(Val, CE->getCallReturnType(ACtx)));
   }
 
+  ProgramStateRef bindReturnValue(ProgramStateRef State, CheckerContext &C,
+  SVal Val) {
+return State->BindExpr(CE, C.getLocationContext(), Val);
+  }
+
   ProgramStateRef bindNullReturnValue(ProgramStateRef State,
   CheckerContext &C) {
 return State->BindExpr(CE, C.getLocationContext(),
@@ -280,6 +285,13 @@ struct StreamOperationEvaluator {
   return nullptr;
 return State->assume(*Cond, true);
   }
+
+  ConstraintManager::ProgramStatePair
+  makeRetValAndAssumeDual(ProgramStateRef State, CheckerContext &C) {
+DefinedSVal RetVal = makeRetVal(C, CE);
+State = State->BindExpr(CE, C.getLocationContext(), RetVal);
+return C.getConstraintManager().assumeDual(State, RetVal);
+  }
 };
 
 class StreamChecker : public Checker(Call.getOriginExpr());
-  if (!CE)
-return;
 
-  const StreamState *OldSS = State->get(StreamSym);
-  if (!OldSS)
+  ProgramStateRef State = C.getState();
+  StreamOperationEvaluator E(C);
+  if (!E.Init(Desc, Call, C, State))
 return;
 
-  assertStreamStateOpened(OldSS);
-
-  NonLoc RetVal = makeRetVal(C, CE).castAs();
-  State = State->BindExpr(CE, C.getLocationContext(), RetVal);
-  SValBuilder &SVB = C.getSValBuilder();
-  auto &ACtx = C.getASTContext();
-  auto Cond = SVB.evalBinOp(State, BO_GE, RetVal, SVB.makeZeroVal(ACtx.IntTy),
-SVB.getConditionType())
-  .getAs();
+  NonLoc RetVal = makeRetVal(C, E.CE).castAs();
+  State = State->BindExpr(E.CE, C.getLocationContext(), RetVal);
+  auto Cond =
+  E.SVB
+  .evalBinOp(State, BO_GE, RetVal, E.SVB.makeZeroVal(E.ACtx.IntTy),
+ E.SVB.getConditionType())
+  .getAs();
   if (!Cond)
 return;
   ProgramStateRef StateNotFailed, StateFailed;
   std::tie(StateNotFailed, StateFailed) = State->assume(*Cond);
 
   StateNotFailed =
-  StateNotFailed->set(StreamSym, StreamState::getOpened(Desc));
+  E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
   C.addTransition(StateNotFailed);
 
   // Add transition for the failed state. The resulting value of the file
   // position indicator for the stream is indeterminate.
-  StateFailed = StateFailed->set(
-  StreamSym, StreamState::getOpened(Desc, ErrorFError, true));
+  StateFailed = E.setStreamState(
+  StateFailed, StreamState::getOpened(Desc, ErrorFError, true));
   C.addTransition(StateFailed);
 }
 
 void StreamChecker::evalFscanf(const FnDescription *Desc, const CallEvent 
&Call,
CheckerContext &C) const {
-  ProgramStateRef State = C.getState();
   if (Call.getNumArgs() < 2)
 return;
-  SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
-  if (!StreamSym)
-return;
-
-  const CallExpr *CE = dyn_cast_or_null(Call.getOriginExpr());
-  if (!CE)
-return;
 
-  const StreamState *OldSS = State->get(StreamSym);
-  if (!OldSS)
+  ProgramStateRef State = C.getState();
+  StreamOperationEvaluator E(C);
+  if (!E.Init(Desc, Call, C, State))
 return;
 
-  assertStreamStateOpened(OldSS);
-
-  SValBuilder &SVB = C.getSValBuilder();
-  ASTContext &ACtx = C.getASTContext();
-
   // 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,
@@ -1007,19 +998,15 @@ void StreamChecker::evalFscanf(const FnDescription 
*Desc, const CallEvent &Call,
   // then EOF or read error happens. Now this case is handled like a "success"
   // case, and no error flags are set on the stream. This is probably not
   // accurate, and the POSIX documentation does not tell more.
-  if (OldSS->ErrorState != ErrorFEof) {
-NonLoc RetVal = makeRetVal(C, CE).castAs();
+  if (!E.isStreamEof()) {
+NonLoc RetVal

[clang] [clang][analyzer] Simplify code of StreamChecker (NFC). (PR #82228)

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

https://github.com/balazske closed 
https://github.com/llvm/llvm-project/pull/82228
___
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-20 Thread kadir çetinkaya via cfe-commits

kadircet wrote:

cc @hokein 

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] [compiler-rt] [llvm] [clang-repl] [ORC] Add support for out-of-process execution on ELF (PR #79936)

2024-02-20 Thread Stefan Gränitz via cfe-commits

weliveindetail wrote:

Thanks for your follow-up. Yes, I agree it's best to leave it here as a draft. 
We can reference it from future PRs to provide context, if we decide to 
implement one part or the other in isolation. Thanks!

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


[clang] 39fd3fc - [clang][Interp] Don't fail on shifts greater than type bitwidth

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

Author: Timm Bäder
Date: 2024-02-20T11:32:37+01:00
New Revision: 39fd3fcd4527d627ee7f526a651aa47c27a9ad0d

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

LOG: [clang][Interp] Don't fail on shifts greater than type bitwidth

We need to limit the shift width to the type bitwidth, then do the
shift and report success, but still diagnose what we limited the
shiftwidth.

Added: 


Modified: 
clang/lib/AST/Interp/Interp.h
clang/test/AST/Interp/shifts.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 5e9c07545ae1fb..23a2756a18f690 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -135,7 +135,7 @@ bool CheckShift(InterpState &S, CodePtr OpPC, const LT 
&LHS, const RT &RHS,
 const APSInt Val = RHS.toAPSInt();
 QualType Ty = E->getType();
 S.CCEDiag(E, diag::note_constexpr_large_shift) << Val << Ty << Bits;
-return false;
+return true; // We will do the shift anyway but fix up the shift amount.
   }
 
   if (LHS.isSigned() && !S.getLangOpts().CPlusPlus20) {
@@ -1798,11 +1798,17 @@ inline bool Shr(InterpState &S, CodePtr OpPC) {
   if (!CheckShift(S, OpPC, LHS, RHS, Bits))
 return false;
 
+  // Limit the shift amount to Bits - 1. If this happened,
+  // it has already been diagnosed by CheckShift() above,
+  // but we still need to handle it.
   typename LT::AsUnsigned R;
-  LT::AsUnsigned::shiftRight(LT::AsUnsigned::from(LHS),
- LT::AsUnsigned::from(RHS), Bits, &R);
+  if (RHS > RT::from(Bits - 1, RHS.bitWidth()))
+LT::AsUnsigned::shiftRight(LT::AsUnsigned::from(LHS),
+   LT::AsUnsigned::from(Bits - 1), Bits, &R);
+  else
+LT::AsUnsigned::shiftRight(LT::AsUnsigned::from(LHS),
+   LT::AsUnsigned::from(RHS, Bits), Bits, &R);
   S.Stk.push(LT::from(R));
-
   return true;
 }
 
@@ -1817,9 +1823,17 @@ inline bool Shl(InterpState &S, CodePtr OpPC) {
   if (!CheckShift(S, OpPC, LHS, RHS, Bits))
 return false;
 
+  // Limit the shift amount to Bits - 1. If this happened,
+  // it has already been diagnosed by CheckShift() above,
+  // but we still need to handle it.
   typename LT::AsUnsigned R;
-  LT::AsUnsigned::shiftLeft(LT::AsUnsigned::from(LHS),
-LT::AsUnsigned::from(RHS, Bits), Bits, &R);
+  if (RHS > RT::from(Bits - 1, RHS.bitWidth()))
+LT::AsUnsigned::shiftLeft(LT::AsUnsigned::from(LHS),
+  LT::AsUnsigned::from(Bits - 1), Bits, &R);
+  else
+LT::AsUnsigned::shiftLeft(LT::AsUnsigned::from(LHS),
+  LT::AsUnsigned::from(RHS, Bits), Bits, &R);
+
   S.Stk.push(LT::from(R));
   return true;
 }

diff  --git a/clang/test/AST/Interp/shifts.cpp 
b/clang/test/AST/Interp/shifts.cpp
index e5201b3f8bbef7..76047d0f752d54 100644
--- a/clang/test/AST/Interp/shifts.cpp
+++ b/clang/test/AST/Interp/shifts.cpp
@@ -34,12 +34,13 @@ namespace shifts {
  // ref-warning {{shift count is negative}} \
  // ref-cxx17-warning {{shift count is negative}}
 c = 1 << (unsigned)-1; // expected-warning {{shift count >= width of 
type}} \
-   // FIXME: 'implicit conversion' warning missing in 
the new interpreter. \
+   // expected-warning {{implicit conversion from 
'int' to 'char' changes value from -2147483648 to 0}} \
// cxx17-warning {{shift count >= width of type}} \
+   // cxx17-warning {{implicit conversion from 'int' 
to 'char' changes value from -2147483648 to 0}} \
// ref-warning {{shift count >= width of type}} \
-   // ref-warning {{implicit conversion}} \
+   // ref-warning {{implicit conversion from 'int' to 
'char' changes value from -2147483648 to 0}} \
// ref-cxx17-warning {{shift count >= width of 
type}} \
-   // ref-cxx17-warning {{implicit conversion}}
+   // ref-cxx17-warning {{implicit conversion from 
'int' to 'char' changes value from -2147483648 to 0}}
 c = 1 >> (unsigned)-1; // expected-warning {{shift count >= width of 
type}} \
// cxx17-warning {{shift count >= width of type}} \
// ref-warning {{shift count >= width of type}} \



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


[clang] [clang-format] Do not update cursor pos if no includes replacement (PR #77456)

2024-02-20 Thread via cfe-commits

NorthBlue333 wrote:

Hi there,
Any update on this?
Friendly ping @owenca or @mydeveloperday.
I think we could maybe divide the issue in two @HazardyKnusperkeks?

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


[clang] b3e4686 - [clang][Interp] Implement __builtin_{ctz, clz, bswap}

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

Author: Timm Bäder
Date: 2024-02-20T11:55:20+01:00
New Revision: b3e4686af37c7879790f48f244afcb2da21d3af8

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

LOG: [clang][Interp] Implement __builtin_{ctz,clz,bswap}

Added: 


Modified: 
clang/lib/AST/Interp/InterpBuiltin.cpp
clang/test/AST/Interp/builtin-functions.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/InterpBuiltin.cpp 
b/clang/lib/AST/Interp/InterpBuiltin.cpp
index f1040d15a1d2ad..401af580e1aaf6 100644
--- a/clang/lib/AST/Interp/InterpBuiltin.cpp
+++ b/clang/lib/AST/Interp/InterpBuiltin.cpp
@@ -841,6 +841,52 @@ static bool interp__builtin_carryop(InterpState &S, 
CodePtr OpPC,
   return true;
 }
 
+static bool interp__builtin_clz(InterpState &S, CodePtr OpPC,
+const InterpFrame *Frame, const Function *Func,
+const CallExpr *Call) {
+  unsigned BuiltinOp = Func->getBuiltinID();
+  PrimType ValT = *S.getContext().classify(Call->getArg(0));
+  const APSInt &Val = peekToAPSInt(S.Stk, ValT);
+
+  // When the argument is 0, the result of GCC builtins is undefined, whereas
+  // for Microsoft intrinsics, the result is the bit-width of the argument.
+  bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
+ BuiltinOp != Builtin::BI__lzcnt &&
+ BuiltinOp != Builtin::BI__lzcnt64;
+
+  if (ZeroIsUndefined && Val == 0)
+return false;
+
+  pushInt(S, Val.countl_zero());
+  return true;
+}
+
+static bool interp__builtin_ctz(InterpState &S, CodePtr OpPC,
+const InterpFrame *Frame, const Function *Func,
+const CallExpr *Call) {
+  PrimType ValT = *S.getContext().classify(Call->getArg(0));
+  const APSInt &Val = peekToAPSInt(S.Stk, ValT);
+
+  if (Val == 0)
+return false;
+
+  pushInt(S, Val.countr_zero());
+  return true;
+}
+
+static bool interp__builtin_bswap(InterpState &S, CodePtr OpPC,
+  const InterpFrame *Frame,
+  const Function *Func, const CallExpr *Call) {
+  PrimType ReturnT = *S.getContext().classify(Call->getType());
+  PrimType ValT = *S.getContext().classify(Call->getArg(0));
+  const APSInt &Val = peekToAPSInt(S.Stk, ValT);
+  assert(Val.getActiveBits() <= 64);
+
+  INT_TYPE_SWITCH(ReturnT,
+  { S.Stk.push(T::from(Val.byteSwap().getZExtValue())); });
+  return true;
+}
+
 bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
   const CallExpr *Call) {
   InterpFrame *Frame = S.Current;
@@ -1114,6 +1160,32 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC, 
const Function *F,
   return false;
 break;
 
+  case Builtin::BI__builtin_clz:
+  case Builtin::BI__builtin_clzl:
+  case Builtin::BI__builtin_clzll:
+  case Builtin::BI__builtin_clzs:
+  case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
+  case Builtin::BI__lzcnt:
+  case Builtin::BI__lzcnt64:
+if (!interp__builtin_clz(S, OpPC, Frame, F, Call))
+  return false;
+break;
+
+  case Builtin::BI__builtin_ctz:
+  case Builtin::BI__builtin_ctzl:
+  case Builtin::BI__builtin_ctzll:
+  case Builtin::BI__builtin_ctzs:
+if (!interp__builtin_ctz(S, OpPC, Frame, F, Call))
+  return false;
+break;
+
+  case Builtin::BI__builtin_bswap16:
+  case Builtin::BI__builtin_bswap32:
+  case Builtin::BI__builtin_bswap64:
+if (!interp__builtin_bswap(S, OpPC, Frame, F, Call))
+  return false;
+break;
+
   default:
 return false;
   }

diff  --git a/clang/test/AST/Interp/builtin-functions.cpp 
b/clang/test/AST/Interp/builtin-functions.cpp
index cbcfe7d5374d1a..3701106e02f05b 100644
--- a/clang/test/AST/Interp/builtin-functions.cpp
+++ b/clang/test/AST/Interp/builtin-functions.cpp
@@ -444,3 +444,32 @@ void test_noexcept(int *i) {
 }
 #undef TEST_TYPE
 } // end namespace test_launder
+
+namespace clz {
+  char clz1[__builtin_clz(1) == BITSIZE(int) - 1 ? 1 : -1];
+  char clz2[__builtin_clz(7) == BITSIZE(int) - 3 ? 1 : -1];
+  char clz3[__builtin_clz(1 << (BITSIZE(int) - 1)) == 0 ? 1 : -1];
+  int clz4 = __builtin_clz(0);
+  char clz5[__builtin_clzl(0xFL) == BITSIZE(long) - 4 ? 1 : -1];
+  char clz6[__builtin_clzll(0xFFLL) == BITSIZE(long long) - 8 ? 1 : -1];
+  char clz7[__builtin_clzs(0x1) == BITSIZE(short) - 1 ? 1 : -1];
+  char clz8[__builtin_clzs(0xf) == BITSIZE(short) - 4 ? 1 : -1];
+  char clz9[__builtin_clzs(0xfff) == BITSIZE(short) - 12 ? 1 : -1];
+}
+
+namespace ctz {
+  char ctz1[__builtin_ctz(1) == 0 ? 1 : -1];
+  char ctz2[__builtin_ctz(8) == 3 ? 1 : -1];
+  char ctz3[__builtin_ctz(1 << (BITSIZE(int) - 1)) == BITSIZE(int) - 1 ? 1 : 
-1];
+  int ctz4 = __builtin_ctz(0);
+  char ctz5[__builtin_ctzl(

[clang] 9bec1ef - [clang][Interp] assignments aren't always lvalues in C

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

Author: Timm Bäder
Date: 2024-02-20T12:26:15+01:00
New Revision: 9bec1ef5f97b1f3cf2b994dced73268ebb312972

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

LOG: [clang][Interp] assignments aren't always lvalues in C

If they aren't we need to load from the pointer the Store op
leaves on the stack.

Added: 


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

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index d4b285941d46d1..70e2bca2ebf16d 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -505,8 +505,18 @@ bool ByteCodeExprGen::VisitBinaryOperator(const 
BinaryOperator *BO) {
 if (DiscardResult)
   return LHS->refersToBitField() ? this->emitStoreBitFieldPop(*T, BO)
  : this->emitStorePop(*T, BO);
-return LHS->refersToBitField() ? this->emitStoreBitField(*T, BO)
-   : this->emitStore(*T, BO);
+if (LHS->refersToBitField()) {
+  if (!this->emitStoreBitField(*T, BO))
+return false;
+} else {
+  if (!this->emitStore(*T, BO))
+return false;
+}
+// Assignments aren't necessarily lvalues in C.
+// Load from them in that case.
+if (!BO->isLValue())
+  return this->emitLoadPop(*T, BO);
+return true;
   case BO_And:
 return Discard(this->emitBitAnd(*T, BO));
   case BO_Or:

diff  --git a/clang/test/AST/Interp/c.c b/clang/test/AST/Interp/c.c
index 168b56988d065f..b67fe93417058e 100644
--- a/clang/test/AST/Interp/c.c
+++ b/clang/test/AST/Interp/c.c
@@ -171,3 +171,9 @@ const _Bool CTB3 = (_Complex double){0.0, 1.0}; // 
pedantic-ref-warning {{extens
 _Static_assert(CTB3, ""); // pedantic-ref-warning {{GNU extension}} \
   // pedantic-expected-warning {{GNU extension}}
 
+
+int t1 = sizeof(int);
+void test4(void) {
+  t1 = sizeof(int);
+}
+



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


[clang] [clang] Support `__is_trivially_copyable(int()&)==false` (PR #81298)

2024-02-20 Thread Amirreza Ashouri via cfe-commits

https://github.com/AMP999 updated 
https://github.com/llvm/llvm-project/pull/81298

>From d59c262b31937fdd2b907ec11d7f08e4a385007c Mon Sep 17 00:00:00 2001
From: Amirreza Ashouri 
Date: Fri, 9 Feb 2024 21:55:03 +0330
Subject: [PATCH 1/5] [clang] Support `__is_trivially_copyable(int()&)==false`

IMHO it would be productive to make a similar change for `typeid`,
in `ParseCXXTypeid`, in order to improve Clang's error message for
https://godbolt.org/z/oKKWxeYra
But that might be better done by adding a new DeclaratorContext
specifically for TypeidArg, instead of pretending that the argument
to `typeid` is a template argument, because I don't know what else
that change might affect.

Fixes https://github.com/llvm/llvm-project/issues/77585
---
 clang/lib/Parse/ParseExprCXX.cpp | 6 --
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Parse/ParseExprCXX.cpp b/clang/lib/Parse/ParseExprCXX.cpp
index fd262ff31e661a..746a8b2286ac4c 100644
--- a/clang/lib/Parse/ParseExprCXX.cpp
+++ b/clang/lib/Parse/ParseExprCXX.cpp
@@ -3899,7 +3899,9 @@ ExprResult Parser::ParseTypeTrait() {
   SmallVector Args;
   do {
 // Parse the next type.
-TypeResult Ty = ParseTypeName();
+TypeResult Ty = ParseTypeName(nullptr, getLangOpts().CPlusPlus
+   ? DeclaratorContext::TemplateArg
+   : DeclaratorContext::TypeName);
 if (Ty.isInvalid()) {
   Parens.skipToEnd();
   return ExprError();
@@ -3941,7 +3943,7 @@ ExprResult Parser::ParseArrayTypeTrait() {
   if (T.expectAndConsume())
 return ExprError();
 
-  TypeResult Ty = ParseTypeName();
+  TypeResult Ty = ParseTypeName(nullptr, DeclaratorContext::TemplateArg);
   if (Ty.isInvalid()) {
 SkipUntil(tok::comma, StopAtSemi);
 SkipUntil(tok::r_paren, StopAtSemi);

>From 4c58f4f351a17cf4bf3c9d0ccfa118d0fe3a52de Mon Sep 17 00:00:00 2001
From: Amirreza Ashouri 
Date: Sun, 11 Feb 2024 20:35:04 +0330
Subject: [PATCH 2/5] [clang] Fix the failing test in #81298

---
 clang/test/Sema/static-assert.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/test/Sema/static-assert.c b/clang/test/Sema/static-assert.c
index 4e9e6b7ee558bd..7e1ce135cbd995 100644
--- a/clang/test/Sema/static-assert.c
+++ b/clang/test/Sema/static-assert.c
@@ -57,7 +57,7 @@ UNION(char[2], short) u2 = { .one = { 'a', 'b' } }; // 
ext-warning 3 {{'_Static_
 typedef UNION(char, short) U3; // expected-error {{static assertion failed due 
to requirement 'sizeof(char) == sizeof(short)': type size mismatch}} \
// expected-note{{evaluates to '1 == 2'}} \
// ext-warning 3 {{'_Static_assert' is a C11 
extension}}
-typedef UNION(float, 0.5f) U4; // expected-error {{expected a type}} \
+typedef UNION(float, 0.5f) U4; // expected-error-re type name requires a 
specifier or qualifier|expected a type \
// ext-warning 3 {{'_Static_assert' is a C11 
extension}}
 
 // After defining the assert macro in MS-compatibility mode, we should

>From 03c2cfb73fc291ecfc5318077b295a6e38cd9869 Mon Sep 17 00:00:00 2001
From: Amirreza Ashouri 
Date: Mon, 12 Feb 2024 23:47:33 +0330
Subject: [PATCH 3/5] Add a release note.

---
 clang/docs/ReleaseNotes.rst | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 32440ee64e3ebe..0beb10af709804 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -217,6 +217,8 @@ Bug Fixes to C++ Support
   Fixes (`#80971 ICE when explicit object parameter be a function parameter 
pack`)
 - Fixed a bug where abbreviated function templates would append their invented 
template parameters to
   an empty template parameter lists.
+- Fix parsing of abominable function types inside type traits. 
+  Fixes (`#77585 `_)
 
 Bug Fixes to AST Handling
 ^

>From 0de0aa09fb5f45fcde688d988377582b9257b6b8 Mon Sep 17 00:00:00 2001
From: Amirreza Ashouri 
Date: Tue, 13 Feb 2024 01:19:27 +0330
Subject: [PATCH 4/5] Remove trailing white space in ReleaseNotes.rst.

---
 clang/docs/ReleaseNotes.rst | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 0beb10af709804..55f3faea365a07 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -217,7 +217,7 @@ Bug Fixes to C++ Support
   Fixes (`#80971 ICE when explicit object parameter be a function parameter 
pack`)
 - Fixed a bug where abbreviated function templates would append their invented 
template parameters to
   an empty template parameter lists.
-- Fix parsing of abominable function types inside type traits. 
+- Fix parsing of abominable function types inside type traits.
   Fixes (`#77585 `_)
 
 Bug Fixes to AST Handling

>

[clang] [clang] Support `__is_trivially_copyable(int()&)==false` (PR #81298)

2024-02-20 Thread Amirreza Ashouri via cfe-commits

https://github.com/AMP999 updated 
https://github.com/llvm/llvm-project/pull/81298

>From d59c262b31937fdd2b907ec11d7f08e4a385007c Mon Sep 17 00:00:00 2001
From: Amirreza Ashouri 
Date: Fri, 9 Feb 2024 21:55:03 +0330
Subject: [PATCH 1/5] [clang] Support `__is_trivially_copyable(int()&)==false`

IMHO it would be productive to make a similar change for `typeid`,
in `ParseCXXTypeid`, in order to improve Clang's error message for
https://godbolt.org/z/oKKWxeYra
But that might be better done by adding a new DeclaratorContext
specifically for TypeidArg, instead of pretending that the argument
to `typeid` is a template argument, because I don't know what else
that change might affect.

Fixes https://github.com/llvm/llvm-project/issues/77585
---
 clang/lib/Parse/ParseExprCXX.cpp | 6 --
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Parse/ParseExprCXX.cpp b/clang/lib/Parse/ParseExprCXX.cpp
index fd262ff31e661a..746a8b2286ac4c 100644
--- a/clang/lib/Parse/ParseExprCXX.cpp
+++ b/clang/lib/Parse/ParseExprCXX.cpp
@@ -3899,7 +3899,9 @@ ExprResult Parser::ParseTypeTrait() {
   SmallVector Args;
   do {
 // Parse the next type.
-TypeResult Ty = ParseTypeName();
+TypeResult Ty = ParseTypeName(nullptr, getLangOpts().CPlusPlus
+   ? DeclaratorContext::TemplateArg
+   : DeclaratorContext::TypeName);
 if (Ty.isInvalid()) {
   Parens.skipToEnd();
   return ExprError();
@@ -3941,7 +3943,7 @@ ExprResult Parser::ParseArrayTypeTrait() {
   if (T.expectAndConsume())
 return ExprError();
 
-  TypeResult Ty = ParseTypeName();
+  TypeResult Ty = ParseTypeName(nullptr, DeclaratorContext::TemplateArg);
   if (Ty.isInvalid()) {
 SkipUntil(tok::comma, StopAtSemi);
 SkipUntil(tok::r_paren, StopAtSemi);

>From 4c58f4f351a17cf4bf3c9d0ccfa118d0fe3a52de Mon Sep 17 00:00:00 2001
From: Amirreza Ashouri 
Date: Sun, 11 Feb 2024 20:35:04 +0330
Subject: [PATCH 2/5] [clang] Fix the failing test in #81298

---
 clang/test/Sema/static-assert.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/test/Sema/static-assert.c b/clang/test/Sema/static-assert.c
index 4e9e6b7ee558bd..7e1ce135cbd995 100644
--- a/clang/test/Sema/static-assert.c
+++ b/clang/test/Sema/static-assert.c
@@ -57,7 +57,7 @@ UNION(char[2], short) u2 = { .one = { 'a', 'b' } }; // 
ext-warning 3 {{'_Static_
 typedef UNION(char, short) U3; // expected-error {{static assertion failed due 
to requirement 'sizeof(char) == sizeof(short)': type size mismatch}} \
// expected-note{{evaluates to '1 == 2'}} \
// ext-warning 3 {{'_Static_assert' is a C11 
extension}}
-typedef UNION(float, 0.5f) U4; // expected-error {{expected a type}} \
+typedef UNION(float, 0.5f) U4; // expected-error-re type name requires a 
specifier or qualifier|expected a type \
// ext-warning 3 {{'_Static_assert' is a C11 
extension}}
 
 // After defining the assert macro in MS-compatibility mode, we should

>From 03c2cfb73fc291ecfc5318077b295a6e38cd9869 Mon Sep 17 00:00:00 2001
From: Amirreza Ashouri 
Date: Mon, 12 Feb 2024 23:47:33 +0330
Subject: [PATCH 3/5] Add a release note.

---
 clang/docs/ReleaseNotes.rst | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 32440ee64e3ebe..0beb10af709804 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -217,6 +217,8 @@ Bug Fixes to C++ Support
   Fixes (`#80971 ICE when explicit object parameter be a function parameter 
pack`)
 - Fixed a bug where abbreviated function templates would append their invented 
template parameters to
   an empty template parameter lists.
+- Fix parsing of abominable function types inside type traits. 
+  Fixes (`#77585 `_)
 
 Bug Fixes to AST Handling
 ^

>From 0de0aa09fb5f45fcde688d988377582b9257b6b8 Mon Sep 17 00:00:00 2001
From: Amirreza Ashouri 
Date: Tue, 13 Feb 2024 01:19:27 +0330
Subject: [PATCH 4/5] Remove trailing white space in ReleaseNotes.rst.

---
 clang/docs/ReleaseNotes.rst | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 0beb10af709804..55f3faea365a07 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -217,7 +217,7 @@ Bug Fixes to C++ Support
   Fixes (`#80971 ICE when explicit object parameter be a function parameter 
pack`)
 - Fixed a bug where abbreviated function templates would append their invented 
template parameters to
   an empty template parameter lists.
-- Fix parsing of abominable function types inside type traits. 
+- Fix parsing of abominable function types inside type traits.
   Fixes (`#77585 `_)
 
 Bug Fixes to AST Handling

>

[clang] [Driver] Remove dead -freroll-loops flag (PR #82254)

2024-02-20 Thread Bruno De Fraine via cfe-commits


@@ -3871,10 +3871,6 @@ def funroll_loops : Flag<["-"], "funroll-loops">, 
Group,
   HelpText<"Turn on loop unroller">, Visibility<[ClangOption, CC1Option]>;
 def fno_unroll_loops : Flag<["-"], "fno-unroll-loops">, Group,
   HelpText<"Turn off loop unroller">, Visibility<[ClangOption, CC1Option]>;
-defm reroll_loops : BoolFOption<"reroll-loops",
-  CodeGenOpts<"RerollLoops">, DefaultFalse,
-  PosFlag,
-  NegFlag>;

brunodf-snps wrote:

Will the removal from the td file also remove the option from the documentation?
https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-freroll-loops

(In that case, issue #59065 can be closed.)

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


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

2024-02-20 Thread Alexey Bataev via cfe-commits

https://github.com/alexey-bataev approved this pull request.

LG

https://github.com/llvm/llvm-project/pull/82220
___
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-20 Thread via cfe-commits

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

None

>From fc41d1efdcff94857e7ccd3b8a1a75c3e83a84ee Mon Sep 17 00:00:00 2001
From: Martin Braenne 
Date: Tue, 20 Feb 2024 11:57:23 +
Subject: [PATCH] [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->i

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

2024-02-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (martinboehme)


Changes



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


5 Files Affected:

- (modified) clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
(+6-3) 
- (modified) clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (+14-4) 
- (modified) clang/lib/Analysis/FlowSensitive/Transfer.cpp (+15-11) 
- (modified) clang/unittests/Analysis/FlowSensitive/TestingSupport.h (+19) 
- (modified) clang/unittests/Analysis/FlowSensitive/TransferTest.cpp (+12-2) 


``diff
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->inits();
 size_t InitIdx = 0;
@@ -731,6 +723,18 @@ class TransferVisitor : public 
ConstStmtVisitor {
   Fi

[clang] [clang-format] Fix crash in TokenAnnotator (PR #82349)

2024-02-20 Thread Emilia Kond via cfe-commits

https://github.com/rymiel created 
https://github.com/llvm/llvm-project/pull/82349

The while loop on line 3814 can cause a segmentation fault getting the Next 
field on a nullptr. This is because further down, on line 3823, there is 
another for loop, which assigns Tok to Tok->Next in its initializer. This for 
loop has a condition to check if the result of that isn't null. If it is, the 
loop is skipped and we drop back out to the outer loop, except, now Tok is 
null, and we try to dereference it without checking first.

This patch adds a defensive check that returns if Tok->Next is null before we 
make it to the second for loop.

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

>From 25ca98534f0d5dbd96ff74c802528171787ced45 Mon Sep 17 00:00:00 2001
From: Emilia Kond 
Date: Tue, 20 Feb 2024 14:11:33 +0200
Subject: [PATCH] [clang-format] Fix crash in TokenAnnotator

The while loop on line 3814 can cause a segmentation fault getting the
Next field on a nullptr. This is because further down, on line 3823,
there is another for loop, which assigns Tok to Tok->Next in its
initializer. This for loop has a condition to check if the result of that
isn't null. If it is, the loop is skipped and we drop back out to the
outer loop, except, now Tok is null, and we try to dereference it without
checking first.

This patch adds a defensive check that returns if Tok->Next is null
before we make it to the second for loop.

Fixes https://github.com/llvm/llvm-project/issues/82328
---
 clang/lib/Format/TokenAnnotator.cpp   | 2 +-
 clang/unittests/Format/FormatTest.cpp | 3 +++
 2 files changed, 4 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index ec7b7f4dbe3470..a38ba8762f8505 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3817,7 +3817,7 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const {
 do {
   Tok = Tok->Next;
 } while (Tok && Tok->isNot(TT_OverloadedOperatorLParen));
-if (!Tok)
+if (!Tok || !Tok->Next)
   break;
 const auto *LeftParen = Tok;
 for (Tok = Tok->Next; Tok && Tok != LeftParen->MatchingParen;
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 24f62af8ddcb87..3a3c88f609af7a 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -13503,6 +13503,9 @@ TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
   verifyFormat("{");
   verifyFormat("#})");
   verifyNoCrash("(/**/[:!] ?[).");
+  verifyNoCrash("struct X{"
+"  operator iunt("
+"};");
 }
 
 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {

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


[clang] [clang-format] Fix crash in TokenAnnotator (PR #82349)

2024-02-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Emilia Kond (rymiel)


Changes

The while loop on line 3814 can cause a segmentation fault getting the Next 
field on a nullptr. This is because further down, on line 3823, there is 
another for loop, which assigns Tok to Tok->Next in its initializer. This 
for loop has a condition to check if the result of that isn't null. If it is, 
the loop is skipped and we drop back out to the outer loop, except, now Tok is 
null, and we try to dereference it without checking first.

This patch adds a defensive check that returns if Tok->Next is null before 
we make it to the second for loop.

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

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


2 Files Affected:

- (modified) clang/lib/Format/TokenAnnotator.cpp (+1-1) 
- (modified) clang/unittests/Format/FormatTest.cpp (+3) 


``diff
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index ec7b7f4dbe3470..a38ba8762f8505 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3817,7 +3817,7 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const {
 do {
   Tok = Tok->Next;
 } while (Tok && Tok->isNot(TT_OverloadedOperatorLParen));
-if (!Tok)
+if (!Tok || !Tok->Next)
   break;
 const auto *LeftParen = Tok;
 for (Tok = Tok->Next; Tok && Tok != LeftParen->MatchingParen;
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 24f62af8ddcb87..3a3c88f609af7a 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -13503,6 +13503,9 @@ TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
   verifyFormat("{");
   verifyFormat("#})");
   verifyNoCrash("(/**/[:!] ?[).");
+  verifyNoCrash("struct X{"
+"  operator iunt("
+"};");
 }
 
 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {

``




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


[clang] [Driver] Remove dead -freroll-loops flag (PR #82254)

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

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


[clang] [Driver] Remove dead -freroll-loops flag (PR #82254)

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


@@ -3871,10 +3871,6 @@ def funroll_loops : Flag<["-"], "funroll-loops">, 
Group,
   HelpText<"Turn on loop unroller">, Visibility<[ClangOption, CC1Option]>;
 def fno_unroll_loops : Flag<["-"], "fno-unroll-loops">, Group,
   HelpText<"Turn off loop unroller">, Visibility<[ClangOption, CC1Option]>;
-defm reroll_loops : BoolFOption<"reroll-loops",
-  CodeGenOpts<"RerollLoops">, DefaultFalse,
-  PosFlag,
-  NegFlag>;

nikic wrote:

Yes, the documentation is generated from Options.td.

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


[clang] f1efc64 - [Driver] Remove dead -freroll-loops flag (#82254)

2024-02-20 Thread via cfe-commits

Author: Nikita Popov
Date: 2024-02-20T13:50:41+01:00
New Revision: f1efc64b86d6fa60182c4d4a9ad7c8a051c21dbc

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

LOG: [Driver] Remove dead -freroll-loops flag (#82254)

Remove the `-freroll-loops` flag, which has not had any effect since the
migration to the new pass manager. The underlying pass has been removed
entirely in #80972 due to lack of maintenance and known bugs.

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/Driver/clang_f_opts.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 649ad655905af2..2095b8a5480322 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -167,6 +167,8 @@ Modified Compiler Flags
 Removed Compiler Flags
 -
 
+- The ``-freroll-loops`` flag has been removed. It had no effect since Clang 
13.
+
 Attribute Changes in Clang
 --
 

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 53f23f9abb4c96..36a42b1b050c23 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3871,10 +3871,6 @@ def funroll_loops : Flag<["-"], "funroll-loops">, 
Group,
   HelpText<"Turn on loop unroller">, Visibility<[ClangOption, CC1Option]>;
 def fno_unroll_loops : Flag<["-"], "fno-unroll-loops">, Group,
   HelpText<"Turn off loop unroller">, Visibility<[ClangOption, CC1Option]>;
-defm reroll_loops : BoolFOption<"reroll-loops",
-  CodeGenOpts<"RerollLoops">, DefaultFalse,
-  PosFlag,
-  NegFlag>;
 def ffinite_loops: Flag<["-"],  "ffinite-loops">, Group,
   HelpText<"Assume all loops are finite.">, Visibility<[ClangOption, 
CC1Option]>;
 def fno_finite_loops: Flag<["-"], "fno-finite-loops">, Group,

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 47305f798c5fee..7daf945ae12712 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6660,11 +6660,6 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   CmdArgs.push_back("-fwrapv");
   }
 
-  if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
-   options::OPT_fno_reroll_loops))
-if (A->getOption().matches(options::OPT_freroll_loops))
-  CmdArgs.push_back("-freroll-loops");
-
   Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
   options::OPT_fno_finite_loops);
 

diff  --git a/clang/test/Driver/clang_f_opts.c 
b/clang/test/Driver/clang_f_opts.c
index 33e4aa8386c3b3..472d0725a79340 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -45,13 +45,6 @@
 // CHECK-UNROLL-LOOPS: "-funroll-loops"
 // CHECK-NO-UNROLL-LOOPS: "-fno-unroll-loops"
 
-// RUN: %clang -### -S -freroll-loops %s 2>&1 | FileCheck 
-check-prefix=CHECK-REROLL-LOOPS %s
-// RUN: %clang -### -S -fno-reroll-loops %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-REROLL-LOOPS %s
-// RUN: %clang -### -S -fno-reroll-loops -freroll-loops %s 2>&1 | FileCheck 
-check-prefix=CHECK-REROLL-LOOPS %s
-// RUN: %clang -### -S -freroll-loops -fno-reroll-loops %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-REROLL-LOOPS %s
-// CHECK-REROLL-LOOPS: "-freroll-loops"
-// CHECK-NO-REROLL-LOOPS-NOT: "-freroll-loops"
-
 // RUN: %clang -### -S -fprofile-sample-accurate %s 2>&1 | FileCheck 
-check-prefix=CHECK-PROFILE-SAMPLE-ACCURATE %s
 // CHECK-PROFILE-SAMPLE-ACCURATE: "-fprofile-sample-accurate"
 



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


[clang] [Driver] Remove dead -freroll-loops flag (PR #82254)

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

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


[clang] [clang] Implement `__is_layout_compatible` (PR #81506)

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

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

LGTM!

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


[clang] [clang-format] Fix crash in TokenAnnotator (PR #82349)

2024-02-20 Thread via cfe-commits

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

LGTM

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


[clang] d5922cf - [clang] Implement `__is_layout_compatible` (#81506)

2024-02-20 Thread via cfe-commits

Author: Vlad Serebrennikov
Date: 2024-02-20T16:54:51+04:00
New Revision: d5922cf72cc18a7ac9f7afd1941ee2f7773d8469

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

LOG: [clang] Implement `__is_layout_compatible` (#81506)

This patch implements `__is_layout_compatible` intrinsic, which supports
`std::is_layout_compatible` type trait introduced in C++20
([P0466R5](https://wg21.link/p0466r5) "Layout-compatibility and
Pointer-interconvertibility Traits"). Name matches GCC and MSVC
intrinsic.

Basically, this patch exposes our existing machinery for checking for
layout compatibility and figuring out common initial sequences. Said
machinery is a bit outdated, as it doesn't implement
[CWG1719](https://cplusplus.github.io/CWG/issues/1719.html) "Layout
compatibility and cv-qualification revisited" and
[CWG2759](https://cplusplus.github.io/CWG/issues/2759.html)
"`[[no_unique_address]` and common initial sequence". Those defect
reports are considered out of scope of of this PR, but will be
implemented in subsequent PRs.

Partially addresses #48204

Added: 


Modified: 
clang/docs/LanguageExtensions.rst
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/TokenKinds.def
clang/include/clang/Sema/Sema.h
clang/lib/Parse/ParseExpr.cpp
clang/lib/Sema/SemaChecking.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/test/CXX/drs/dr13xx.cpp
clang/test/CXX/drs/dr17xx.cpp
clang/test/SemaCXX/type-traits.cpp

Removed: 




diff  --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index fd439662773420..fb4d7a02dd086f 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -1582,6 +1582,7 @@ The following type trait primitives are supported by 
Clang. Those traits marked
 * ``__is_integral`` (C++, Embarcadero)
 * ``__is_interface_class`` (Microsoft):
   Returns ``false``, even for types defined with ``__interface``.
+* ``__is_layout_compatible`` (C++, GNU, Microsoft)
 * ``__is_literal`` (Clang):
   Synonym for ``__is_literal_type``.
 * ``__is_literal_type`` (C++, GNU, Microsoft):

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2095b8a5480322..8ea4a9a5a4256c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -96,6 +96,12 @@ C++20 Feature Support
   behavior can use the flag '-Xclang -fno-skip-odr-check-in-gmf'.
   (`#79240 `_).
 
+- 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.
+
 C++23 Feature Support
 ^
 

diff  --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index 2046ab9dc0198c..1d16e4843615d9 100644
--- a/clang/include/clang/Basic/TokenKinds.def
+++ b/clang/include/clang/Basic/TokenKinds.def
@@ -520,6 +520,7 @@ TYPE_TRAIT_1(__is_trivially_copyable, IsTriviallyCopyable, 
KEYCXX)
 TYPE_TRAIT_1(__is_union, IsUnion, KEYCXX)
 TYPE_TRAIT_1(__has_unique_object_representations,
  HasUniqueObjectRepresentations, KEYCXX)
+TYPE_TRAIT_2(__is_layout_compatible, IsLayoutCompatible, KEYCXX)
 
 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) KEYWORD(__##Trait, KEYCXX)
 #include "clang/Basic/TransformTypeTraits.def"

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index e9cd42ae777df5..89215bf3d1c69a 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -14078,6 +14078,8 @@ class Sema final {
   bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
 
 public:
+  bool IsLayoutCompatible(QualType T1, QualType T2) const;
+
   // Used by C++ template instantiation.
   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
   ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,

diff  --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp
index f1417456ffe510..4bf954b5cc4db5 100644
--- a/clang/lib/Parse/ParseExpr.cpp
+++ b/clang/lib/Parse/ParseExpr.cpp
@@ -1114,6 +1114,7 @@ ExprResult Parser::ParseCastExpression(CastParseKind 
ParseKind,
   REVERTIBLE_TYPE_TRAIT(__is_fundamental);
   REVERTIBLE_TYPE_TRAIT(__is_integral);
   REVERTIBLE_TYPE_TRAIT(__is_interface_class);
+  REVERTIBLE_TYPE_TRAIT(__is_layout_compatible);
   REVERTIBLE_TYPE_TRAIT(__is_literal);
   REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
   REVERTIBLE_TYP

[clang] [clang] Implement `__is_layout_compatible` (PR #81506)

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

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


[clang] [clang-format] Fix RemoveSemicolon for empty functions (PR #82278)

2024-02-20 Thread via cfe-commits

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

LGTM

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


[clang] [llvm] [mlir] [OpenMP] Migrate GPU Reductions CodeGen from Clang to OMPIRBuilder (PR #80343)

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

TIFitis wrote:

Ping for review :)

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


[clang] 9563746 - [clang][Interp] Diagnose uninitialized global variables explicitly

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

Author: Timm Bäder
Date: 2024-02-20T14:20:17+01:00
New Revision: 9563746d358c68c0c4a6242fa20bc21fdf632dfe

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

LOG: [clang][Interp] Diagnose uninitialized global variables explicitly

There used to be some diagnostic differences between the new
interpreter and the old one.

Added: 


Modified: 
clang/lib/AST/Interp/Descriptor.h
clang/lib/AST/Interp/Interp.cpp
clang/test/AST/Interp/cxx17.cpp
clang/test/AST/Interp/records.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Descriptor.h 
b/clang/lib/AST/Interp/Descriptor.h
index 6a53205af59926..ac8707a521e194 100644
--- a/clang/lib/AST/Interp/Descriptor.h
+++ b/clang/lib/AST/Interp/Descriptor.h
@@ -165,6 +165,10 @@ struct Descriptor final {
 return dyn_cast_if_present(asDecl());
   }
 
+  const VarDecl *asVarDecl() const {
+return dyn_cast_if_present(asDecl());
+  }
+
   const FieldDecl *asFieldDecl() const {
 return dyn_cast_if_present(asDecl());
   }

diff  --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index 51434d65e2f53b..1a48b8bddced02 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -357,10 +357,18 @@ bool CheckMutable(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr) {
 
 bool CheckInitialized(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
   AccessKinds AK) {
+  assert(Ptr.isLive());
+
   if (Ptr.isInitialized())
 return true;
 
   if (!S.checkingPotentialConstantExpression()) {
+if (const auto *VD = Ptr.getDeclDesc()->asVarDecl();
+VD && VD->hasGlobalStorage()) {
+  const SourceInfo &Loc = S.Current->getSource(OpPC);
+  S.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << VD;
+  S.Note(VD->getLocation(), diag::note_declared_at);
+}
 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_uninit)
 << AK << /*uninitialized=*/true << S.Current->getRange(OpPC);
   }

diff  --git a/clang/test/AST/Interp/cxx17.cpp b/clang/test/AST/Interp/cxx17.cpp
index 76d985eb22e178..5e38d1a5887007 100644
--- a/clang/test/AST/Interp/cxx17.cpp
+++ b/clang/test/AST/Interp/cxx17.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -std=c++17 -verify 
%s
-// RUN: %clang_cc1 -std=c++17 -verify=ref %s
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -std=c++17 
-verify=expected,both %s
+// RUN: %clang_cc1 -std=c++17 -verify=ref,both %s
 
 struct F { int a; int b;};
 constexpr F getF() {
@@ -81,22 +81,15 @@ constexpr int b() {
 }
 static_assert(b() == 11);
 
-/// The diagnostics between the two interpreters are 
diff erent here.
+/// The diagnostics between the two interpreters used to be 
diff erent here.
 struct S { int a; };
-constexpr S getS() { // expected-error {{constexpr function never produces a 
constant expression}} \\
- // ref-error {{constexpr function never produces a 
constant expression}}
-  (void)(1/0); // expected-note 2{{division by zero}} \
-   // expected-warning {{division by zero}} \
-   // ref-note 2{{division by zero}} \
-   // ref-warning {{division by zero}}
+constexpr S getS() { // both-error {{constexpr function never produces a 
constant expression}}
+  (void)(1/0); // both-note 2{{division by zero}} \
+   // both-warning {{division by zero}}
   return S{12};
 }
-constexpr S s = getS(); // expected-error {{must be initialized by a constant 
expression}} \
-// expected-note {{in call to 'getS()'}} \
-// ref-error {{must be initialized by a constant 
expression}} \\
-// ref-note {{in call to 'getS()'}} \
-// ref-note {{declared here}}
-static_assert(s.a == 12, ""); // expected-error {{not an integral constant 
expression}} \
-  // expected-note {{read of uninitialized 
object}} \
-  // ref-error {{not an integral constant 
expression}} \
-  // ref-note {{initializer of 's' is not a 
constant expression}}
+constexpr S s = getS(); // both-error {{must be initialized by a constant 
expression}} \
+// both-note {{in call to 'getS()'}} \
+// both-note {{declared here}}
+static_assert(s.a == 12, ""); // both-error {{not an integral constant 
expression}} \
+  // both-note {{initializer of 's' is not a 
constant expression}}

diff  --git a/clang/test/AST/Interp/records.cpp 
b/clang/test/AST/Interp/records.cpp
index 7cc5987e0a958f..7ddc56c9b5dfc4 100644
--- a/clang/test/AST/Interp/records.cpp
+++ b/clang/test/AST/Interp/records.cpp
@@ -420,11 +420,10 @@ n

[clang] 2ad43fa - [AMDGPU] Fix operand types for `V_DOT2_F32_BF16` (#82044)

2024-02-20 Thread via cfe-commits

Author: Shilei Tian
Date: 2024-02-20T08:25:01-05:00
New Revision: 2ad43fa467b0b1755535c21b0795f0444d1327fd

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

LOG: [AMDGPU] Fix operand types for `V_DOT2_F32_BF16` (#82044)

Added: 


Modified: 
clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl
llvm/include/llvm/IR/IntrinsicsAMDGPU.td
llvm/lib/Target/AMDGPU/SIInstrInfo.td
llvm/lib/Target/AMDGPU/VOP3PInstructions.td
llvm/test/CodeGen/AMDGPU/llvm.amdgcn.fdot2.f32.bf16.ll
llvm/test/MC/AMDGPU/bf16_imm.s
llvm/test/MC/Disassembler/AMDGPU/bf16_imm.txt

Removed: 




diff  --git a/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl 
b/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl
index 7688dfa55a78e3..1ada16610d0b3a 100644
--- a/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl
+++ b/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx11.cl
@@ -15,8 +15,8 @@ typedef unsigned short __attribute__((ext_vector_type(2))) 
ushort2;
 // CHECK-NEXT: [[s2:%[0-9]+]] = bitcast <2 x i16> %v2ssB to <2 x bfloat>
 // CHECK-NEXT: [[s3:%[0-9]+]] = bitcast i16 %sC to bfloat
 // CHECK-NEXT: [[d:%[0-9]+]] = tail call bfloat 
@llvm.amdgcn.fdot2.bf16.bf16(<2 x bfloat> [[s1]], <2 x bfloat> [[s2]], bfloat 
[[s3]])
-// CHECK: call float @llvm.amdgcn.fdot2.f32.bf16(<2 x i16> %v2ssA, <2 x i16> 
%v2ssB, float %fC, i1 false)
-// CHECK: call float @llvm.amdgcn.fdot2.f32.bf16(<2 x i16> %v2ssA, <2 x i16> 
%v2ssB, float %fC, i1 true)
+// CHECK: call float @llvm.amdgcn.fdot2.f32.bf16(<2 x bfloat> [[s1]], <2 x 
bfloat> [[s2]], float %fC, i1 false)
+// CHECK: call float @llvm.amdgcn.fdot2.f32.bf16(<2 x bfloat> [[s1]], <2 x 
bfloat> [[s2]], float %fC, i1 true)
 // CHECK: call i32 @llvm.amdgcn.udot4(i32 %uiA, i32 %uiB, i32 %uiC, i1 false)
 // CHECK: call i32 @llvm.amdgcn.udot4(i32 %uiA, i32 %uiB, i32 %uiC, i1 true)
 // CHECK: call i32 @llvm.amdgcn.sudot4(i1 true, i32 %A, i1 false, i32 %B, i32 
%C, i1 false)

diff  --git a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td 
b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
index 6795fb7aa0edb8..0f29653f1f5bec 100644
--- a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
+++ b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
@@ -2835,8 +2835,8 @@ def int_amdgcn_fdot2_f32_bf16 :
   DefaultAttrsIntrinsic<
 [llvm_float_ty], // %r
 [
-  llvm_v2i16_ty, // %a
-  llvm_v2i16_ty, // %b
+  llvm_v2bf16_ty, // %a
+  llvm_v2bf16_ty, // %b
   llvm_float_ty, // %c
   llvm_i1_ty // %clamp
 ],

diff  --git a/llvm/lib/Target/AMDGPU/SIInstrInfo.td 
b/llvm/lib/Target/AMDGPU/SIInstrInfo.td
index 140c99ff304143..cd14c12a8a80c6 100644
--- a/llvm/lib/Target/AMDGPU/SIInstrInfo.td
+++ b/llvm/lib/Target/AMDGPU/SIInstrInfo.td
@@ -2494,7 +2494,7 @@ def VOP_V2I16_I32_I32 : VOPProfile <[v2i16, i32, i32, 
untyped]>;
 
 def VOP_F16_V2F16_V2F16_F16 : VOPProfile <[f16, v2f16, v2f16, f16]>;
 def VOP_BF16_V2BF16_V2BF16_BF16: VOPProfile <[bf16, v2bf16, v2bf16, bf16]>;
-def VOP_F32_V2I16_V2I16_F32 : VOPProfile <[f32, v2i16, v2i16, f32]>;
+def VOP_F32_V2BF16_V2BF16_F32 : VOPProfile <[f32, v2bf16, v2bf16, f32]>;
 
 def VOP_F32_V2F16_V2F16_V2F16 : VOPProfile <[f32, v2f16, v2f16, v2f16]>;
 

diff  --git a/llvm/lib/Target/AMDGPU/VOP3PInstructions.td 
b/llvm/lib/Target/AMDGPU/VOP3PInstructions.td
index 886858b5ab1ad3..74f451b6d4f7fe 100644
--- a/llvm/lib/Target/AMDGPU/VOP3PInstructions.td
+++ b/llvm/lib/Target/AMDGPU/VOP3PInstructions.td
@@ -396,7 +396,7 @@ defm V_DOT8_I32_I4  : VOP3PInst<"v_dot8_i32_i4",
 } // End OtherPredicates = [HasDot1Insts]
 
 def DOT2_BF16_Profile
-  : VOP3P_Profile {
+  : VOP3P_Profile {
   let HasSrc1Mods = 1;
 }
 

diff  --git a/llvm/test/CodeGen/AMDGPU/llvm.amdgcn.fdot2.f32.bf16.ll 
b/llvm/test/CodeGen/AMDGPU/llvm.amdgcn.fdot2.f32.bf16.ll
index 367ff57bae2fd6..e51b1d2da2e414 100644
--- a/llvm/test/CodeGen/AMDGPU/llvm.amdgcn.fdot2.f32.bf16.ll
+++ b/llvm/test/CodeGen/AMDGPU/llvm.amdgcn.fdot2.f32.bf16.ll
@@ -2,7 +2,7 @@
 ; RUN: llc -mtriple=amdgcn -mcpu=gfx1100 -verify-machineinstrs < %s | 
FileCheck %s --check-prefixes=GFX11
 ; RUN: llc -global-isel -mtriple=amdgcn -mcpu=gfx1100 -verify-machineinstrs < 
%s | FileCheck %s --check-prefixes=GFX11
 
-declare float @llvm.amdgcn.fdot2.f32.bf16(<2 x i16> %a, <2 x i16> %b, float 
%c, i1 %clamp)
+declare float @llvm.amdgcn.fdot2.f32.bf16(<2 x bfloat> %a, <2 x bfloat> %b, 
float %c, i1 %clamp)
 
 define amdgpu_kernel void @test_llvm_amdgcn_fdot2_f32_bf16_clamp(
 ; GFX11-LABEL: test_llvm_amdgcn_fdot2_f32_bf16_clamp:
@@ -25,10 +25,10 @@ define amdgpu_kernel void 
@test_llvm_amdgcn_fdot2_f32_bf16_clamp(
 ptr addrspace(1) %b,
 ptr addrspace(1) %c) {
 entry:
-  %a.val = load <2 x i16>, ptr addrspace(1) %a
-  %b.val = load <2 x i16>, ptr addrspace(1) %b
+  %a.val = load <2 x bfloat>, p

[clang] [llvm] [AMDGPU] Fix operand types for `V_DOT2_F32_BF16` (PR #82044)

2024-02-20 Thread Shilei Tian via cfe-commits

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


[clang] [Clang][Sema] Fix the lambda call expression inside of a type alias declaration (PR #82310)

2024-02-20 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 updated 
https://github.com/llvm/llvm-project/pull/82310

>From 0f97fae5d1ba4debe04824e5d2d98598504d003d Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Tue, 20 Feb 2024 14:54:14 +0800
Subject: [PATCH 1/3] The lambda call inside of a type alias

---
 clang/docs/ReleaseNotes.rst   |  5 ++
 clang/include/clang/AST/DeclCXX.h |  4 +
 clang/include/clang/Sema/Sema.h   |  8 ++
 clang/lib/Frontend/FrontendActions.cpp|  2 +
 clang/lib/Sema/SemaConcept.cpp| 15 ++--
 clang/lib/Sema/SemaTemplate.cpp   |  9 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 64 ++-
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |  5 ++
 clang/lib/Sema/TreeTransform.h|  9 ++
 .../alias-template-with-lambdas.cpp   | 82 +++
 10 files changed, 189 insertions(+), 14 deletions(-)
 create mode 100644 clang/test/SemaTemplate/alias-template-with-lambdas.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 649ad655905af2..7988912faa2075 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -267,6 +267,11 @@ Bug Fixes to C++ Support
   was only accepted at namespace scope but not at local function scope.
 - Clang no longer tries to call consteval constructors at runtime when they 
appear in a member initializer.
   (`#782154 `_`)
+- Clang now supports direct lambda calls inside of a type alias template 
declarations.
+  This addresses (`#70601 
`_),
+  (`#76674 `_),
+  (`#79555 `_),
+  (`#81145 `_), and so on.
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/AST/DeclCXX.h 
b/clang/include/clang/AST/DeclCXX.h
index 9cebaff63bb0db..7aed4d5cbc002e 100644
--- a/clang/include/clang/AST/DeclCXX.h
+++ b/clang/include/clang/AST/DeclCXX.h
@@ -1869,6 +1869,10 @@ class CXXRecordDecl : public RecordDecl {
 DL.MethodTyInfo = TS;
   }
 
+  void setLambdaDependencyKind(unsigned Kind) {
+getLambdaData().DependencyKind = Kind;
+  }
+
   void setLambdaIsGeneric(bool IsGeneric) {
 assert(DefinitionData && DefinitionData->IsLambda &&
"setting lambda property of non-lambda class");
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index e9cd42ae777df5..488d2e07a2732e 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -9622,6 +9622,8 @@ class Sema final {
 
   /// We are building deduction guides for a class.
   BuildingDeductionGuides,
+
+  TypeAliasTemplateInstantiation,
 } Kind;
 
 /// Was the enclosing context a non-instantiation SFINAE context?
@@ -9812,6 +9814,12 @@ class Sema final {
   FunctionDecl *Entity, ExceptionSpecification,
   SourceRange InstantiationRange = SourceRange());
 
+/// Note that we are instantiating a type alias template declaration.
+InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
+  TypeAliasTemplateDecl *Template,
+  ArrayRef TemplateArgs,
+  SourceRange InstantiationRange = SourceRange());
+
 /// Note that we are instantiating a default argument in a
 /// template-id.
 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
diff --git a/clang/lib/Frontend/FrontendActions.cpp 
b/clang/lib/Frontend/FrontendActions.cpp
index b9ed5dedfa4223..43d6e2230fb129 100644
--- a/clang/lib/Frontend/FrontendActions.cpp
+++ b/clang/lib/Frontend/FrontendActions.cpp
@@ -426,6 +426,8 @@ class DefaultTemplateInstCallback : public 
TemplateInstantiationCallback {
   return "BuildingBuiltinDumpStructCall";
 case CodeSynthesisContext::BuildingDeductionGuides:
   return "BuildingDeductionGuides";
+case Sema::CodeSynthesisContext::TypeAliasTemplateInstantiation:
+  return "TypeAliasTemplateInstantiation";
 }
 return "";
   }
diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 2878e4d31ee8fe..5cc6236c3991b6 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -614,14 +614,13 @@ bool Sema::SetupConstraintScope(
 // reference the original primary template.
 // We walk up the instantiated template chain so that nested lambdas get
 // handled properly.
-for (FunctionTemplateDecl *FromMemTempl =
- PrimaryTemplate->getInstantiatedFromMemberTemplate();
- FromMemTempl;
- FromMemTempl = FromMemTempl->getInstantiatedFromMemberTemplate()) {
-  if (addInstantiatedParametersToScope(FD, 
FromMemTempl->getTemplatedDecl(),
-   

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

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

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

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

>From 15d9428a47ea5d7ba3b4ffd2e766406b16d781e0 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Tue, 20 Feb 2024 16:44:04 +0300
Subject: [PATCH] [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), ""); // F

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

2024-02-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Vlad Serebrennikov (Endilll)


Changes

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

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


5 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+6-3) 
- (modified) clang/lib/Sema/SemaChecking.cpp (+7-6) 
- (modified) clang/test/CXX/drs/dr17xx.cpp (+5-6) 
- (modified) clang/test/SemaCXX/type-traits.cpp (+7-7) 
- (modified) clang/www/cxx_dr_status.html (+2-2) 


``diff
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
-  static_assert(!__is_layout_compatible(const int, volatile int), ""); // 
FIXME: this is CWG1719
+  static_assert(__is_layout_compatible(void, const void), "");
+  static_asser

[clang] [RISCV] Disable generation of asynchronous unwind tables for RISCV baremetal (PR #81727)

2024-02-20 Thread Garvit Gupta via cfe-commits

https://github.com/quic-garvgupt updated 
https://github.com/llvm/llvm-project/pull/81727

>From 42211bccd8ffc60751234ab5695be135ea8b6373 Mon Sep 17 00:00:00 2001
From: Garvit Gupta 
Date: Wed, 14 Feb 2024 03:00:20 -0800
Subject: [PATCH 1/2] [RISCV] Disable generation of asynchronous unwind tables
 for RISCV baremetal

The below culprit patch enabled the generation of asynchronous unwind tables
(-funwind-tables=2) by default for RISCV for both linux and RISCVToolChain
baremetal object. However, since there are 2 baremetal toolchain objects for
RISCV, this created a discrepancy between their behavior. Moreover, enabling
the generation of asynchronous unwind tables based on whether `-gcc-toolchain`
option is present or not doesn't seem to be the best criteria to decide on
the same.

Culprit Patch - https://reviews.llvm.org/D145164
---
 clang/lib/Driver/ToolChains/RISCVToolchain.cpp | 5 +
 clang/lib/Driver/ToolChains/RISCVToolchain.h   | 2 ++
 clang/test/Driver/clang-translation.c  | 8 
 3 files changed, 15 insertions(+)

diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp 
b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
index 85beb945cbf6fc..624099d21ae124 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
@@ -86,6 +86,11 @@ RISCVToolChain::GetUnwindLibType(const llvm::opt::ArgList 
&Args) const {
   return ToolChain::UNW_None;
 }
 
+ToolChain::UnwindTableLevel RISCVToolChain::getDefaultUnwindTableLevel(
+const llvm::opt::ArgList &Args) const {
+  return UnwindTableLevel::None;
+}
+
 void RISCVToolChain::addClangTargetOptions(
 const llvm::opt::ArgList &DriverArgs,
 llvm::opt::ArgStringList &CC1Args,
diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.h 
b/clang/lib/Driver/ToolChains/RISCVToolchain.h
index cec817ef7190be..fa0aa265d842bb 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.h
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.h
@@ -28,6 +28,8 @@ class LLVM_LIBRARY_VISIBILITY RISCVToolChain : public 
Generic_ELF {
   RuntimeLibType GetDefaultRuntimeLibType() const override;
   UnwindLibType
   GetUnwindLibType(const llvm::opt::ArgList &Args) const override;
+  UnwindTableLevel
+  getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const override;
   void
   AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
 llvm::opt::ArgStringList &CC1Args) const override;
diff --git a/clang/test/Driver/clang-translation.c 
b/clang/test/Driver/clang-translation.c
index a7343ea18b2135..64d55f1b88ea6d 100644
--- a/clang/test/Driver/clang-translation.c
+++ b/clang/test/Driver/clang-translation.c
@@ -421,3 +421,11 @@
 // MIPSN32R6EL: "-target-cpu" "mips64r6"
 // MIPSN32R6EL: "-target-abi" "n32"
 // MIPSN32R6EL: "-mfloat-abi" "hard"
+
+// RUN: %clang --target=riscv32-unknown-elf --gcc-toolchain="" -### %s 2>&1 | 
FileCheck %s -check-prefix=NOUWTABLE
+// RUN: %clang --target=riscv32-unknown-elf --gcc-toolchain="" 
-fasynchronous-unwind-tables -### %s 2>&1 | FileCheck %s -check-prefix=UWTABLE
+// RUN: %clang --target=riscv64-unknown-elf --gcc-toolchain="" -### %s 2>&1 | 
FileCheck %s -check-prefix=NOUWTABLE
+// RUN: %clang --target=riscv64-unknown-elf --gcc-toolchain="" 
-fasynchronous-unwind-tables -### %s 2>&1 | FileCheck %s -check-prefix=UWTABLE
+//
+// UWTABLE: "-funwind-tables=2"
+// NOUWTABLE-NOT: "-funwind-tables=2"
\ No newline at end of file

>From 559f1d6e4221dc94cd035c0f568dea630dcb6f37 Mon Sep 17 00:00:00 2001
From: Garvit Gupta 
Date: Wed, 14 Feb 2024 03:00:20 -0800
Subject: [PATCH 2/2] [RISCV] Disable generation of asynchronous unwind tables
 for RISCV baremetal

The below culprit patch enabled the generation of asynchronous unwind tables
(-funwind-tables=2) by default for RISCV for both linux and RISCVToolChain
baremetal object. However, since there are 2 baremetal toolchain objects for
RISCV, this created a discrepancy between their behavior. Moreover, enabling
the generation of asynchronous unwind tables based on whether `-gcc-toolchain`
option is present or not doesn't seem to be the best criteria to decide on
the same.

Culprit Patch - https://reviews.llvm.org/D145164
---
 clang/test/Driver/riscv-features.c | 8 
 1 file changed, 8 insertions(+)

diff --git a/clang/test/Driver/riscv-features.c 
b/clang/test/Driver/riscv-features.c
index d3700f71aa7e1d..15832e79d2a491 100644
--- a/clang/test/Driver/riscv-features.c
+++ b/clang/test/Driver/riscv-features.c
@@ -35,6 +35,14 @@
 // FAST-UNALIGNED-ACCESS: "-target-feature" "+fast-unaligned-access"
 // NO-FAST-UNALIGNED-ACCESS: "-target-feature" "-fast-unaligned-access"
 
+// RUN: %clang --target=riscv32-unknown-elf --gcc-toolchain="" -### %s 2>&1 | 
FileCheck %s -check-prefix=NOUWTABLE
+// RUN: %clang --target=riscv32-unknown-elf --gcc-toolchain="" 
-fasynchronous-unwind-tables -### %s 2>&1 | FileCheck %s -check-prefix=UWTABLE
+// RUN: %clang --target=riscv64-unknown-elf --gcc-toolchain="" -#

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

2024-02-20 Thread via cfe-commits

mahtohappy wrote:

Ping @AaronBallman @cor3ntin @shafik @erichkeane 

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] Implement __builtin_popcountg (PR #82359)

2024-02-20 Thread via cfe-commits

https://github.com/overmighty created 
https://github.com/llvm/llvm-project/pull/82359

Fixes #82058.


>From c14dab5f9419507cc3d0ac803e1bfebb3f3b0f94 Mon Sep 17 00:00:00 2001
From: OverMighty 
Date: Tue, 20 Feb 2024 13:45:13 +
Subject: [PATCH] [clang] Implement __builtin_popcountg

Fixes #82058.
---
 clang/include/clang/Basic/Builtins.td |  6 
 clang/lib/CodeGen/CGBuiltin.cpp   |  7 -
 clang/test/CodeGen/builtins.c | 43 +++
 3 files changed, 55 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index df74026c5d2d50..3134450250edd5 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -688,6 +688,12 @@ def Popcount : Builtin, BitInt_Long_LongLongTemplate {
   let Prototype = "int(unsigned T)";
 }
 
+def Popcountg : Builtin {
+  let Spellings = ["__builtin_popcountg"];
+  let Attributes = [NoThrow, Const, Constexpr];
+  let Prototype = "int(...)";
+}
+
 def Clrsb : Builtin, BitInt_Long_LongLongTemplate {
   let Spellings = ["__builtin_clrsb"];
   let Attributes = [NoThrow, Const, Constexpr];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index d454ccc1dd8613..d36d24e84f0afa 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3216,7 +3216,12 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
   case Builtin::BI__popcnt64:
   case Builtin::BI__builtin_popcount:
   case Builtin::BI__builtin_popcountl:
-  case Builtin::BI__builtin_popcountll: {
+  case Builtin::BI__builtin_popcountll:
+  case Builtin::BI__builtin_popcountg: {
+if (BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_popcountg) {
+  assert(E->getNumArgs() == 1 && "__builtin_popcountg takes 1 argument");
+}
+
 Value *ArgValue = EmitScalarExpr(E->getArg(0));
 
 llvm::Type *ArgType = ArgValue->getType();
diff --git a/clang/test/CodeGen/builtins.c b/clang/test/CodeGen/builtins.c
index 88282120283b8a..73866116e07e72 100644
--- a/clang/test/CodeGen/builtins.c
+++ b/clang/test/CodeGen/builtins.c
@@ -940,4 +940,47 @@ void test_builtin_os_log_long_double(void *buf, long 
double ld) {
 // CHECK: %[[V3:.*]] = load i128, ptr %[[ARG0_ADDR]], align 16
 // CHECK: store i128 %[[V3]], ptr %[[ARGDATA]], align 1
 
+// CHECK-LABEL: define{{.*}} void @test_builtin_popcountg
+void test_builtin_popcountg(unsigned char uc, unsigned short us,
+unsigned int ui, unsigned long ul,
+unsigned long long ull, unsigned __int128 ui128,
+unsigned _BitInt(128) ubi128) {
+  volatile int pop;
+  pop = __builtin_popcountg(uc);
+  // CHECK: %1 = load i8, ptr %uc.addr, align 1
+  // CHECK-NEXT: %conv = zext i8 %1 to i32
+  // CHECK-NEXT: %2 = call i32 @llvm.ctpop.i32(i32 %conv)
+  // CHECK-NEXT: store volatile i32 %2, ptr %pop, align 4
+  pop = __builtin_popcountg(us);
+  // CHECK-NEXT: %3 = load i16, ptr %us.addr, align 2
+  // CHECK-NEXT: %conv1 = zext i16 %3 to i32
+  // CHECK-NEXT: %4 = call i32 @llvm.ctpop.i32(i32 %conv1)
+  // CHECK-NEXT: store volatile i32 %4, ptr %pop, align 4
+  pop = __builtin_popcountg(ui);
+  // CHECK-NEXT: %5 = load i32, ptr %ui.addr, align 4
+  // CHECK-NEXT: %6 = call i32 @llvm.ctpop.i32(i32 %5)
+  // CHECK-NEXT: store volatile i32 %6, ptr %pop, align 4
+  pop = __builtin_popcountg(ul);
+  // CHECK-NEXT: %7 = load i64, ptr %ul.addr, align 8
+  // CHECK-NEXT: %8 = call i64 @llvm.ctpop.i64(i64 %7)
+  // CHECK-NEXT: %cast = trunc i64 %8 to i32
+  // CHECK-NEXT: store volatile i32 %cast, ptr %pop, align 4
+  pop = __builtin_popcountg(ull);
+  // CHECK-NEXT: %9 = load i64, ptr %ull.addr, align 8
+  // CHECK-NEXT: %10 = call i64 @llvm.ctpop.i64(i64 %9)
+  // CHECK-NEXT: %cast2 = trunc i64 %10 to i32
+  // CHECK-NEXT: store volatile i32 %cast2, ptr %pop, align 4
+  pop = __builtin_popcountg(ui128);
+  // CHECK-NEXT: %11 = load i128, ptr %ui128.addr, align 16
+  // CHECK-NEXT: %12 = call i128 @llvm.ctpop.i128(i128 %11)
+  // CHECK-NEXT: %cast3 = trunc i128 %12 to i32
+  // CHECK-NEXT: store volatile i32 %cast3, ptr %pop, align 4
+  pop = __builtin_popcountg(ubi128);
+  // CHECK-NEXT: %13 = load i128, ptr %ubi128.addr, align 8
+  // CHECK-NEXT: %14 = call i128 @llvm.ctpop.i128(i128 %13)
+  // CHECK-NEXT: %cast4 = trunc i128 %14 to i32
+  // CHECK-NEXT: store volatile i32 %cast4, ptr %pop, align 4
+  // CHECK-NEXT: ret void
+}
+
 #endif

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


[clang] [clang] Implement __builtin_popcountg (PR #82359)

2024-02-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: OverMighty (overmighty)


Changes

Fixes #82058.


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


3 Files Affected:

- (modified) clang/include/clang/Basic/Builtins.td (+6) 
- (modified) clang/lib/CodeGen/CGBuiltin.cpp (+6-1) 
- (modified) clang/test/CodeGen/builtins.c (+43) 


``diff
diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index df74026c5d2d50..3134450250edd5 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -688,6 +688,12 @@ def Popcount : Builtin, BitInt_Long_LongLongTemplate {
   let Prototype = "int(unsigned T)";
 }
 
+def Popcountg : Builtin {
+  let Spellings = ["__builtin_popcountg"];
+  let Attributes = [NoThrow, Const, Constexpr];
+  let Prototype = "int(...)";
+}
+
 def Clrsb : Builtin, BitInt_Long_LongLongTemplate {
   let Spellings = ["__builtin_clrsb"];
   let Attributes = [NoThrow, Const, Constexpr];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index d454ccc1dd8613..d36d24e84f0afa 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3216,7 +3216,12 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
   case Builtin::BI__popcnt64:
   case Builtin::BI__builtin_popcount:
   case Builtin::BI__builtin_popcountl:
-  case Builtin::BI__builtin_popcountll: {
+  case Builtin::BI__builtin_popcountll:
+  case Builtin::BI__builtin_popcountg: {
+if (BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_popcountg) {
+  assert(E->getNumArgs() == 1 && "__builtin_popcountg takes 1 argument");
+}
+
 Value *ArgValue = EmitScalarExpr(E->getArg(0));
 
 llvm::Type *ArgType = ArgValue->getType();
diff --git a/clang/test/CodeGen/builtins.c b/clang/test/CodeGen/builtins.c
index 88282120283b8a..73866116e07e72 100644
--- a/clang/test/CodeGen/builtins.c
+++ b/clang/test/CodeGen/builtins.c
@@ -940,4 +940,47 @@ void test_builtin_os_log_long_double(void *buf, long 
double ld) {
 // CHECK: %[[V3:.*]] = load i128, ptr %[[ARG0_ADDR]], align 16
 // CHECK: store i128 %[[V3]], ptr %[[ARGDATA]], align 1
 
+// CHECK-LABEL: define{{.*}} void @test_builtin_popcountg
+void test_builtin_popcountg(unsigned char uc, unsigned short us,
+unsigned int ui, unsigned long ul,
+unsigned long long ull, unsigned __int128 ui128,
+unsigned _BitInt(128) ubi128) {
+  volatile int pop;
+  pop = __builtin_popcountg(uc);
+  // CHECK: %1 = load i8, ptr %uc.addr, align 1
+  // CHECK-NEXT: %conv = zext i8 %1 to i32
+  // CHECK-NEXT: %2 = call i32 @llvm.ctpop.i32(i32 %conv)
+  // CHECK-NEXT: store volatile i32 %2, ptr %pop, align 4
+  pop = __builtin_popcountg(us);
+  // CHECK-NEXT: %3 = load i16, ptr %us.addr, align 2
+  // CHECK-NEXT: %conv1 = zext i16 %3 to i32
+  // CHECK-NEXT: %4 = call i32 @llvm.ctpop.i32(i32 %conv1)
+  // CHECK-NEXT: store volatile i32 %4, ptr %pop, align 4
+  pop = __builtin_popcountg(ui);
+  // CHECK-NEXT: %5 = load i32, ptr %ui.addr, align 4
+  // CHECK-NEXT: %6 = call i32 @llvm.ctpop.i32(i32 %5)
+  // CHECK-NEXT: store volatile i32 %6, ptr %pop, align 4
+  pop = __builtin_popcountg(ul);
+  // CHECK-NEXT: %7 = load i64, ptr %ul.addr, align 8
+  // CHECK-NEXT: %8 = call i64 @llvm.ctpop.i64(i64 %7)
+  // CHECK-NEXT: %cast = trunc i64 %8 to i32
+  // CHECK-NEXT: store volatile i32 %cast, ptr %pop, align 4
+  pop = __builtin_popcountg(ull);
+  // CHECK-NEXT: %9 = load i64, ptr %ull.addr, align 8
+  // CHECK-NEXT: %10 = call i64 @llvm.ctpop.i64(i64 %9)
+  // CHECK-NEXT: %cast2 = trunc i64 %10 to i32
+  // CHECK-NEXT: store volatile i32 %cast2, ptr %pop, align 4
+  pop = __builtin_popcountg(ui128);
+  // CHECK-NEXT: %11 = load i128, ptr %ui128.addr, align 16
+  // CHECK-NEXT: %12 = call i128 @llvm.ctpop.i128(i128 %11)
+  // CHECK-NEXT: %cast3 = trunc i128 %12 to i32
+  // CHECK-NEXT: store volatile i32 %cast3, ptr %pop, align 4
+  pop = __builtin_popcountg(ubi128);
+  // CHECK-NEXT: %13 = load i128, ptr %ubi128.addr, align 8
+  // CHECK-NEXT: %14 = call i128 @llvm.ctpop.i128(i128 %13)
+  // CHECK-NEXT: %cast4 = trunc i128 %14 to i32
+  // CHECK-NEXT: store volatile i32 %cast4, ptr %pop, align 4
+  // CHECK-NEXT: ret void
+}
+
 #endif

``




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


[clang] [clang] Implement __builtin_popcountg (PR #82359)

2024-02-20 Thread via cfe-commits

overmighty wrote:

Should I add support for `__builtin_popcountg` in constant expressions in this 
PR too or in a later one?

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


[clang] [RISCV] Disable generation of asynchronous unwind tables for RISCV baremetal (PR #81727)

2024-02-20 Thread Garvit Gupta via cfe-commits

https://github.com/quic-garvgupt updated 
https://github.com/llvm/llvm-project/pull/81727

>From 42211bccd8ffc60751234ab5695be135ea8b6373 Mon Sep 17 00:00:00 2001
From: Garvit Gupta 
Date: Wed, 14 Feb 2024 03:00:20 -0800
Subject: [PATCH] [RISCV] Disable generation of asynchronous unwind tables for
 RISCV baremetal

The below culprit patch enabled the generation of asynchronous unwind tables
(-funwind-tables=2) by default for RISCV for both linux and RISCVToolChain
baremetal object. However, since there are 2 baremetal toolchain objects for
RISCV, this created a discrepancy between their behavior. Moreover, enabling
the generation of asynchronous unwind tables based on whether `-gcc-toolchain`
option is present or not doesn't seem to be the best criteria to decide on
the same.

Culprit Patch - https://reviews.llvm.org/D145164
---
 clang/lib/Driver/ToolChains/RISCVToolchain.cpp | 5 +
 clang/lib/Driver/ToolChains/RISCVToolchain.h   | 2 ++
 clang/test/Driver/clang-translation.c  | 8 
 3 files changed, 15 insertions(+)

diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp 
b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
index 85beb945cbf6fc..624099d21ae124 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
@@ -86,6 +86,11 @@ RISCVToolChain::GetUnwindLibType(const llvm::opt::ArgList 
&Args) const {
   return ToolChain::UNW_None;
 }
 
+ToolChain::UnwindTableLevel RISCVToolChain::getDefaultUnwindTableLevel(
+const llvm::opt::ArgList &Args) const {
+  return UnwindTableLevel::None;
+}
+
 void RISCVToolChain::addClangTargetOptions(
 const llvm::opt::ArgList &DriverArgs,
 llvm::opt::ArgStringList &CC1Args,
diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.h 
b/clang/lib/Driver/ToolChains/RISCVToolchain.h
index cec817ef7190be..fa0aa265d842bb 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.h
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.h
@@ -28,6 +28,8 @@ class LLVM_LIBRARY_VISIBILITY RISCVToolChain : public 
Generic_ELF {
   RuntimeLibType GetDefaultRuntimeLibType() const override;
   UnwindLibType
   GetUnwindLibType(const llvm::opt::ArgList &Args) const override;
+  UnwindTableLevel
+  getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const override;
   void
   AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
 llvm::opt::ArgStringList &CC1Args) const override;
diff --git a/clang/test/Driver/clang-translation.c 
b/clang/test/Driver/clang-translation.c
index a7343ea18b2135..64d55f1b88ea6d 100644
--- a/clang/test/Driver/clang-translation.c
+++ b/clang/test/Driver/clang-translation.c
@@ -421,3 +421,11 @@
 // MIPSN32R6EL: "-target-cpu" "mips64r6"
 // MIPSN32R6EL: "-target-abi" "n32"
 // MIPSN32R6EL: "-mfloat-abi" "hard"
+
+// RUN: %clang --target=riscv32-unknown-elf --gcc-toolchain="" -### %s 2>&1 | 
FileCheck %s -check-prefix=NOUWTABLE
+// RUN: %clang --target=riscv32-unknown-elf --gcc-toolchain="" 
-fasynchronous-unwind-tables -### %s 2>&1 | FileCheck %s -check-prefix=UWTABLE
+// RUN: %clang --target=riscv64-unknown-elf --gcc-toolchain="" -### %s 2>&1 | 
FileCheck %s -check-prefix=NOUWTABLE
+// RUN: %clang --target=riscv64-unknown-elf --gcc-toolchain="" 
-fasynchronous-unwind-tables -### %s 2>&1 | FileCheck %s -check-prefix=UWTABLE
+//
+// UWTABLE: "-funwind-tables=2"
+// NOUWTABLE-NOT: "-funwind-tables=2"
\ No newline at end of file

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


[clang] [RISCV] Disable generation of asynchronous unwind tables for RISCV baremetal (PR #81727)

2024-02-20 Thread Garvit Gupta via cfe-commits

https://github.com/quic-garvgupt updated 
https://github.com/llvm/llvm-project/pull/81727

>From 8cc7535ed4c05d4cf14cdedc26077eccf06c8d53 Mon Sep 17 00:00:00 2001
From: Garvit Gupta 
Date: Wed, 14 Feb 2024 03:00:20 -0800
Subject: [PATCH] [RISCV] Disable generation of asynchronous unwind tables for
 RISCV baremetal

The below culprit patch enabled the generation of asynchronous unwind tables
(-funwind-tables=2) by default for RISCV for both linux and RISCVToolChain
baremetal object. However, since there are 2 baremetal toolchain objects for
RISCV, this created a discrepancy between their behavior. Moreover, enabling
the generation of asynchronous unwind tables based on whether `-gcc-toolchain`
option is present or not doesn't seem to be the best criteria to decide on
the same.

Culprit Patch - https://reviews.llvm.org/D145164
---
 clang/lib/Driver/ToolChains/RISCVToolchain.cpp | 5 +
 clang/lib/Driver/ToolChains/RISCVToolchain.h   | 2 ++
 clang/test/Driver/riscv-features.c | 8 
 3 files changed, 15 insertions(+)

diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp 
b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
index 85beb945cbf6fc..624099d21ae124 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.cpp
@@ -86,6 +86,11 @@ RISCVToolChain::GetUnwindLibType(const llvm::opt::ArgList 
&Args) const {
   return ToolChain::UNW_None;
 }
 
+ToolChain::UnwindTableLevel RISCVToolChain::getDefaultUnwindTableLevel(
+const llvm::opt::ArgList &Args) const {
+  return UnwindTableLevel::None;
+}
+
 void RISCVToolChain::addClangTargetOptions(
 const llvm::opt::ArgList &DriverArgs,
 llvm::opt::ArgStringList &CC1Args,
diff --git a/clang/lib/Driver/ToolChains/RISCVToolchain.h 
b/clang/lib/Driver/ToolChains/RISCVToolchain.h
index cec817ef7190be..fa0aa265d842bb 100644
--- a/clang/lib/Driver/ToolChains/RISCVToolchain.h
+++ b/clang/lib/Driver/ToolChains/RISCVToolchain.h
@@ -28,6 +28,8 @@ class LLVM_LIBRARY_VISIBILITY RISCVToolChain : public 
Generic_ELF {
   RuntimeLibType GetDefaultRuntimeLibType() const override;
   UnwindLibType
   GetUnwindLibType(const llvm::opt::ArgList &Args) const override;
+  UnwindTableLevel
+  getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const override;
   void
   AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
 llvm::opt::ArgStringList &CC1Args) const override;
diff --git a/clang/test/Driver/riscv-features.c 
b/clang/test/Driver/riscv-features.c
index d3700f71aa7e1d..15832e79d2a491 100644
--- a/clang/test/Driver/riscv-features.c
+++ b/clang/test/Driver/riscv-features.c
@@ -35,6 +35,14 @@
 // FAST-UNALIGNED-ACCESS: "-target-feature" "+fast-unaligned-access"
 // NO-FAST-UNALIGNED-ACCESS: "-target-feature" "-fast-unaligned-access"
 
+// RUN: %clang --target=riscv32-unknown-elf --gcc-toolchain="" -### %s 2>&1 | 
FileCheck %s -check-prefix=NOUWTABLE
+// RUN: %clang --target=riscv32-unknown-elf --gcc-toolchain="" 
-fasynchronous-unwind-tables -### %s 2>&1 | FileCheck %s -check-prefix=UWTABLE
+// RUN: %clang --target=riscv64-unknown-elf --gcc-toolchain="" -### %s 2>&1 | 
FileCheck %s -check-prefix=NOUWTABLE
+// RUN: %clang --target=riscv64-unknown-elf --gcc-toolchain="" 
-fasynchronous-unwind-tables -### %s 2>&1 | FileCheck %s -check-prefix=UWTABLE
+//
+// UWTABLE: "-funwind-tables=2"
+// NOUWTABLE-NOT: "-funwind-tables=2"
+
 // RUN: %clang --target=riscv32-linux -### %s -fsyntax-only 2>&1 \
 // RUN:   | FileCheck %s -check-prefix=DEFAULT-LINUX
 // RUN: %clang --target=riscv64-linux -### %s -fsyntax-only 2>&1 \

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


[clang] [RISCV] Disable generation of asynchronous unwind tables for RISCV baremetal (PR #81727)

2024-02-20 Thread Garvit Gupta via cfe-commits


@@ -421,3 +421,11 @@
 // MIPSN32R6EL: "-target-cpu" "mips64r6"
 // MIPSN32R6EL: "-target-abi" "n32"
 // MIPSN32R6EL: "-mfloat-abi" "hard"
+
+// RUN: %clang --target=riscv32-unknown-elf --gcc-toolchain="" -### %s 2>&1 | 
FileCheck %s -check-prefix=NOUWTABLE

quic-garvgupt wrote:

Done

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


[clang] [C23] Add __TYPE_FMTB__ and __TYPE_FMTb__ predefined macros (PR #82361)

2024-02-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Aaron Ballman (AaronBallman)


Changes

This adds predefined formatting macros in C23 mode for printing unsigned 
integers in binary format (e.g, UINT_FAST64_FMTB). These are used to implement 
the PRIb (et al) macros in inttypes.h

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

(Was previously reviewed in 
[82037](https://github.com/llvm/llvm-project/pull/82037), this is fixing some 
failures found post-commit.)

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


3 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+5) 
- (modified) clang/lib/Frontend/InitPreprocessor.cpp (+59-47) 
- (modified) clang/test/Preprocessor/init.c (+64) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 16f79a349c20c8..7083d66ae8f45d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -135,6 +135,11 @@ C23 Feature Support
 
   Fixes (`#81472 `_).
 
+- Clang now generates predefined macros of the form ``__TYPE_FMTB__`` and
+  ``__TYPE_FMTb__`` (e.g., ``__UINT_FAST64_FMTB__``) in C23 mode for use with
+  macros typically exposed from , such as ``PRIb8``.
+  (`#81896: `_).
+
 Non-comprehensive list of changes in this release
 -
 
diff --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 1b250cda42a4dd..9b979d810fa127 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -181,14 +181,21 @@ static void DefineTypeSize(const Twine &MacroName, 
TargetInfo::IntType Ty,
  TI.isTypeSigned(Ty), Builder);
 }
 
-static void DefineFmt(const Twine &Prefix, TargetInfo::IntType Ty,
-  const TargetInfo &TI, MacroBuilder &Builder) {
-  bool IsSigned = TI.isTypeSigned(Ty);
+static void DefineFmt(const LangOptions &LangOpts, const Twine &Prefix,
+  TargetInfo::IntType Ty, const TargetInfo &TI,
+  MacroBuilder &Builder) {
   StringRef FmtModifier = TI.getTypeFormatModifier(Ty);
-  for (const char *Fmt = IsSigned ? "di" : "ouxX"; *Fmt; ++Fmt) {
-Builder.defineMacro(Prefix + "_FMT" + Twine(*Fmt) + "__",
-Twine("\"") + FmtModifier + Twine(*Fmt) + "\"");
-  }
+  auto Emitter = [&](char Fmt) {
+Builder.defineMacro(Prefix + "_FMT" + Twine(Fmt) + "__",
+Twine("\"") + FmtModifier + Twine(Fmt) + "\"");
+  };
+  bool IsSigned = TI.isTypeSigned(Ty);
+  llvm::for_each(StringRef(IsSigned ? "di" : "ouxX"), Emitter);
+
+  // C23 added the b and B modifiers for printing binary output of unsigned
+  // integers. Conditionally define those if compiling in C23 mode.
+  if (LangOpts.C23 && !IsSigned)
+llvm::for_each(StringRef("bB"), Emitter);
 }
 
 static void DefineType(const Twine &MacroName, TargetInfo::IntType Ty,
@@ -217,7 +224,8 @@ static void DefineTypeSizeAndWidth(const Twine &Prefix, 
TargetInfo::IntType Ty,
   DefineTypeWidth(Prefix + "_WIDTH__", Ty, TI, Builder);
 }
 
-static void DefineExactWidthIntType(TargetInfo::IntType Ty,
+static void DefineExactWidthIntType(const LangOptions &LangOpts,
+TargetInfo::IntType Ty,
 const TargetInfo &TI,
 MacroBuilder &Builder) {
   int TypeWidth = TI.getTypeWidth(Ty);
@@ -236,7 +244,7 @@ static void DefineExactWidthIntType(TargetInfo::IntType Ty,
   const char *Prefix = IsSigned ? "__INT" : "__UINT";
 
   DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
-  DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder);
+  DefineFmt(LangOpts, Prefix + Twine(TypeWidth), Ty, TI, Builder);
 
   StringRef ConstSuffix(TI.getTypeConstantSuffix(Ty));
   Builder.defineMacro(Prefix + Twine(TypeWidth) + "_C_SUFFIX__", ConstSuffix);
@@ -259,7 +267,8 @@ static void DefineExactWidthIntTypeSize(TargetInfo::IntType 
Ty,
   DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder);
 }
 
-static void DefineLeastWidthIntType(unsigned TypeWidth, bool IsSigned,
+static void DefineLeastWidthIntType(const LangOptions &LangOpts,
+unsigned TypeWidth, bool IsSigned,
 const TargetInfo &TI,
 MacroBuilder &Builder) {
   TargetInfo::IntType Ty = TI.getLeastIntTypeByWidth(TypeWidth, IsSigned);
@@ -274,11 +283,12 @@ static void DefineLeastWidthIntType(unsigned TypeWidth, 
bool IsSigned,
 DefineTypeSizeAndWidth(Prefix + Twine(TypeWidth), Ty, TI, Builder);
   else
 DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder);
-  DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder);
+  DefineFmt(LangOpts, Prefix + Twine(TypeWidth), Ty, TI, Builder);
 }
 
-static void DefineFa

[clang] [C23] Add __TYPE_FMTB__ and __TYPE_FMTb__ predefined macros (PR #82361)

2024-02-20 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff a4ce870859a2d8b5ce8b92732594089e2a81b4fb 
eb729828e8052b14ac61a36fe1d3b3965c0ef185 -- 
clang/lib/Frontend/InitPreprocessor.cpp clang/test/Preprocessor/init.c
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 9b979d810f..17715121f1 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -306,7 +306,6 @@ static void DefineFastIntType(const LangOptions &LangOpts, 
unsigned TypeWidth,
   DefineFmt(LangOpts, Prefix + Twine(TypeWidth), Ty, TI, Builder);
 }
 
-
 /// Get the value the ATOMIC_*_LOCK_FREE macro should have for a type with
 /// the specified properties.
 static const char *getLockFreeValue(unsigned TypeWidth, const TargetInfo &TI) {

``




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


[clang] [RISCV] Disable generation of asynchronous unwind tables for RISCV baremetal (PR #81727)

2024-02-20 Thread Garvit Gupta via cfe-commits

quic-garvgupt wrote:

Hi @asb, I do not have write access,  requesting to merge this PR on my behalf. 
Also, requesting to backport this PR onto the release  branch. Thanks in 
advance!

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


[clang] [clang] Implement CTAD for type alias template. (PR #77890)

2024-02-20 Thread Haojian Wu via cfe-commits

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


[clang] 052ee74 - [C23] Add __TYPE_FMTB__ and __TYPE_FMTb__ predefined macros (#82361)

2024-02-20 Thread via cfe-commits

Author: Aaron Ballman
Date: 2024-02-20T09:32:23-05:00
New Revision: 052ee74dae3b43e5f8a4a5df9d41386ef7592c18

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

LOG: [C23] Add __TYPE_FMTB__ and __TYPE_FMTb__ predefined macros (#82361)

This adds predefined formatting macros in C23 mode for printing unsigned
integers in binary format (e.g, UINT_FAST64_FMTB). These are used to
implement the PRIb (et al) macros in inttypes.h

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

(Was previously reviewed in
[82037](https://github.com/llvm/llvm-project/pull/82037), this is fixing
some failures found post-commit.)

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Frontend/InitPreprocessor.cpp
clang/test/Preprocessor/init.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8ea4a9a5a4256c..762e8133f5d536 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -141,6 +141,11 @@ C23 Feature Support
 
   Fixes (`#81472 `_).
 
+- Clang now generates predefined macros of the form ``__TYPE_FMTB__`` and
+  ``__TYPE_FMTb__`` (e.g., ``__UINT_FAST64_FMTB__``) in C23 mode for use with
+  macros typically exposed from , such as ``PRIb8``.
+  (`#81896: `_).
+
 Non-comprehensive list of changes in this release
 -
 

diff  --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 1b250cda42a4dd..9b979d810fa127 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -181,14 +181,21 @@ static void DefineTypeSize(const Twine &MacroName, 
TargetInfo::IntType Ty,
  TI.isTypeSigned(Ty), Builder);
 }
 
-static void DefineFmt(const Twine &Prefix, TargetInfo::IntType Ty,
-  const TargetInfo &TI, MacroBuilder &Builder) {
-  bool IsSigned = TI.isTypeSigned(Ty);
+static void DefineFmt(const LangOptions &LangOpts, const Twine &Prefix,
+  TargetInfo::IntType Ty, const TargetInfo &TI,
+  MacroBuilder &Builder) {
   StringRef FmtModifier = TI.getTypeFormatModifier(Ty);
-  for (const char *Fmt = IsSigned ? "di" : "ouxX"; *Fmt; ++Fmt) {
-Builder.defineMacro(Prefix + "_FMT" + Twine(*Fmt) + "__",
-Twine("\"") + FmtModifier + Twine(*Fmt) + "\"");
-  }
+  auto Emitter = [&](char Fmt) {
+Builder.defineMacro(Prefix + "_FMT" + Twine(Fmt) + "__",
+Twine("\"") + FmtModifier + Twine(Fmt) + "\"");
+  };
+  bool IsSigned = TI.isTypeSigned(Ty);
+  llvm::for_each(StringRef(IsSigned ? "di" : "ouxX"), Emitter);
+
+  // C23 added the b and B modifiers for printing binary output of unsigned
+  // integers. Conditionally define those if compiling in C23 mode.
+  if (LangOpts.C23 && !IsSigned)
+llvm::for_each(StringRef("bB"), Emitter);
 }
 
 static void DefineType(const Twine &MacroName, TargetInfo::IntType Ty,
@@ -217,7 +224,8 @@ static void DefineTypeSizeAndWidth(const Twine &Prefix, 
TargetInfo::IntType Ty,
   DefineTypeWidth(Prefix + "_WIDTH__", Ty, TI, Builder);
 }
 
-static void DefineExactWidthIntType(TargetInfo::IntType Ty,
+static void DefineExactWidthIntType(const LangOptions &LangOpts,
+TargetInfo::IntType Ty,
 const TargetInfo &TI,
 MacroBuilder &Builder) {
   int TypeWidth = TI.getTypeWidth(Ty);
@@ -236,7 +244,7 @@ static void DefineExactWidthIntType(TargetInfo::IntType Ty,
   const char *Prefix = IsSigned ? "__INT" : "__UINT";
 
   DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
-  DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder);
+  DefineFmt(LangOpts, Prefix + Twine(TypeWidth), Ty, TI, Builder);
 
   StringRef ConstSuffix(TI.getTypeConstantSuffix(Ty));
   Builder.defineMacro(Prefix + Twine(TypeWidth) + "_C_SUFFIX__", ConstSuffix);
@@ -259,7 +267,8 @@ static void DefineExactWidthIntTypeSize(TargetInfo::IntType 
Ty,
   DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder);
 }
 
-static void DefineLeastWidthIntType(unsigned TypeWidth, bool IsSigned,
+static void DefineLeastWidthIntType(const LangOptions &LangOpts,
+unsigned TypeWidth, bool IsSigned,
 const TargetInfo &TI,
 MacroBuilder &Builder) {
   TargetInfo::IntType Ty = TI.getLeastIntTypeByWidth(TypeWidth, IsSigned);
@@ -274,11 +283,12 @@ static void DefineLeastWidthIntType(unsigned TypeWidth, 
bool IsSigned,
 DefineTypeSizeAndWidth(Prefix + Twine(TypeWidth), Ty, TI, 

[clang] [C23] Add __TYPE_FMTB__ and __TYPE_FMTb__ predefined macros (PR #82361)

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

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


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

2024-02-20 Thread via cfe-commits

https://github.com/Qwinci updated 
https://github.com/llvm/llvm-project/pull/69011

>From e7380b096db802072d75d3bc48971d9758b704cf Mon Sep 17 00:00:00 2001
From: Qwinci <32550582+qwi...@users.noreply.github.com>
Date: Fri, 13 Oct 2023 19:38:19 +0300
Subject: [PATCH] clangd: Show argument names for function pointer struct
 fields

---
 .../clangd/unittests/CodeCompleteTests.cpp  | 17 +
 clang/lib/Sema/SemaCodeComplete.cpp |  8 
 2 files changed, 25 insertions(+)

diff --git a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp 
b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
index 766998eb4f3c71..bd88a0912b537d 100644
--- a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -1462,6 +1462,23 @@ TEST(SignatureHelpTest, FunctionPointers) {
 typedef void (__stdcall *fn)(int x, int y);
 fn foo;
 int main() { foo(^); }
+  )cpp",
+  // Field of function pointer type
+  R"cpp(
+struct S {
+  void (*foo)(int x, int y);
+};
+S s;
+int main() { s.foo(^); }
+  )cpp",
+  // Field of function pointer typedef type
+  R"cpp(
+typedef void (*fn)(int x, int y);
+struct S {
+  fn foo;
+};
+S s;
+int main() { s.foo(^); }
   )cpp"};
   for (auto Test : Tests)
 EXPECT_THAT(signatures(Test).signatures,
diff --git a/clang/lib/Sema/SemaCodeComplete.cpp 
b/clang/lib/Sema/SemaCodeComplete.cpp
index adb82d3f6d176a..4cff91e05ba11b 100644
--- a/clang/lib/Sema/SemaCodeComplete.cpp
+++ b/clang/lib/Sema/SemaCodeComplete.cpp
@@ -6133,6 +6133,7 @@ ProduceSignatureHelp(Sema &SemaRef, 
MutableArrayRef Candidates,
 // so that we can recover argument names from it.
 static FunctionProtoTypeLoc GetPrototypeLoc(Expr *Fn) {
   TypeLoc Target;
+
   if (const auto *T = Fn->getType().getTypePtr()->getAs()) {
 Target = T->getDecl()->getTypeSourceInfo()->getTypeLoc();
 
@@ -6143,6 +6144,13 @@ static FunctionProtoTypeLoc GetPrototypeLoc(Expr *Fn) {
 }
   }
 
+  if (const auto *ME = dyn_cast(Fn)) {
+const auto *MD = ME->getMemberDecl();
+if (const auto *FD = dyn_cast(MD); !Target && FD) {
+  Target = FD->getTypeSourceInfo()->getTypeLoc();
+}
+  }
+
   if (!Target)
 return {};
 

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


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

2024-02-20 Thread via cfe-commits


@@ -6133,7 +6133,17 @@ ProduceSignatureHelp(Sema &SemaRef, 
MutableArrayRef Candidates,
 // so that we can recover argument names from it.
 static FunctionProtoTypeLoc GetPrototypeLoc(Expr *Fn) {
   TypeLoc Target;
-  if (const auto *T = Fn->getType().getTypePtr()->getAs()) {
+
+  if (const auto *ME = dyn_cast(Fn)) {
+const auto *MD = ME->getMemberDecl();
+if (const auto *FD = dyn_cast(MD)) {
+  if (const auto *T = FD->getType().getTypePtr()->getAs()) {

Qwinci wrote:

I forgot this PR, it should be fixed now.

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


[clang] [Clang][Sema] Fix the lambda call expression inside of a type alias declaration (PR #82310)

2024-02-20 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

Although this patch doesn't fix 
https://github.com/llvm/llvm-project/issues/82104 yet, which is a crash caused 
by a mismatch in the template argument during the return type deduction, I 
still tried a temporary workaround (turning some switches off / on for 
getTemplateInstantiationArgs), and that proves we can move forward the fix with 
this patch.

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


[clang] [clang] Implement CTAD for type alias template. (PR #77890)

2024-02-20 Thread Haojian Wu via cfe-commits


@@ -10636,6 +10889,113 @@ QualType 
Sema::DeduceTemplateSpecializationFromInitializer(
   // clear on this, but they're not found by name so access does not apply.
   Guides.suppressDiagnostics();
 
+  SmallVector GuidesCandidates;
+  if (AliasTemplate) {

hokein wrote:

Yes, and this is not the proper place to construct deduction guides for alias 
templates (they should live in `DeclareImplicitDeductionGuides`).

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


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

2024-02-20 Thread via cfe-commits

Sirraide wrote:

@cor3ntin ping

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


[clang] [clang] Implement CTAD for type alias template. (PR #77890)

2024-02-20 Thread Haojian Wu via cfe-commits

hokein wrote:

This patch is ready for review now.

https://github.com/llvm/llvm-project/pull/77890
___
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-20 Thread Haojian Wu via cfe-commits

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


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] [llvm] [AIX] Lower intrinsic __builtin_cpu_is into AIX platform-specific code. (PR #80069)

2024-02-20 Thread Amy Kwan via cfe-commits

https://github.com/amy-kwan approved this pull request.

Aside from the comments about updating the assert in `SemaChecking.cpp` and the 
two comments in `PPCTargetParser.def`, this also LGTM.

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


[clang] [Clang][Sema] Convert warning for extraneous template parameter lists to an extension warning (PR #82277)

2024-02-20 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian updated 
https://github.com/llvm/llvm-project/pull/82277

>From c7521b9ad5d86d5817060e777b0da60e2aa96871 Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Mon, 19 Feb 2024 15:36:10 -0500
Subject: [PATCH 1/2] [Clang][Sema] Convert warning for extraneous template
 parameter lists to an extension warning

---
 clang/include/clang/Basic/DiagnosticSemaKinds.td|  2 +-
 clang/lib/Sema/SemaTemplate.cpp |  2 +-
 clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p23.cpp |  6 ++
 clang/test/CXX/drs/dr5xx.cpp| 10 --
 clang/test/Misc/warning-flags.c |  2 +-
 5 files changed, 9 insertions(+), 13 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index b4dc4feee8e63a..1a7b91bb4b45b6 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5323,7 +5323,7 @@ def err_alias_template_extra_headers : Error<
 def err_template_spec_extra_headers : Error<
   "extraneous template parameter list in template specialization or "
   "out-of-line template definition">;
-def warn_template_spec_extra_headers : Warning<
+def ext_template_spec_extra_headers : ExtWarn<
   "extraneous template parameter list in template specialization">;
 def note_explicit_template_spec_does_not_need_header : Note<
   "'template<>' header not required for explicitly-specialized class %0 "
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index cf781e0e1bf3f4..73c0167ab75778 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -3667,7 +3667,7 @@ TemplateParameterList 
*Sema::MatchTemplateParametersToScopeSpecifier(
 
 if (!SuppressDiagnostic)
   Diag(ParamLists[ParamIdx]->getTemplateLoc(),
-   AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
+   AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
   : diag::err_template_spec_extra_headers)
   << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
  ParamLists[ParamLists.size() - 2]->getRAngleLoc());
diff --git a/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p23.cpp 
b/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p23.cpp
index 469c4e091953c3..683392c5891538 100644
--- a/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p23.cpp
+++ b/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p23.cpp
@@ -1,7 +1,6 @@
 // RUN: %clang_cc1 -std=c++20 -pedantic-errors -verify %s
 
-// FIXME: This should be an error with -pedantic-errors.
-template<> // expected-warning {{extraneous template parameter list in 
template specialization}}
+template<> // expected-error {{extraneous template parameter list in template 
specialization}}
 void f(auto);
 
 template
@@ -18,7 +17,6 @@ void A::g(auto) { }
 template<>
 void A::g(auto) { }
 
-// FIXME: This should be an error with -pedantic-errors.
 template<>
-template<> // expected-warning {{extraneous template parameter list in 
template specialization}}
+template<> // expected-error {{extraneous template parameter list in template 
specialization}}
 void A::g(auto) { }
diff --git a/clang/test/CXX/drs/dr5xx.cpp b/clang/test/CXX/drs/dr5xx.cpp
index 21a6646d4abcf1..0e1de342f6706f 100644
--- a/clang/test/CXX/drs/dr5xx.cpp
+++ b/clang/test/CXX/drs/dr5xx.cpp
@@ -354,17 +354,15 @@ namespace dr531 { // dr531: partial
 
 template<> void A::f(char) {}
 // expected-error@-1 {{no function template matches function template 
specialization 'f'}}
-// FIXME: This is ill-formed; -pedantic-errors should reject.
 template<> template void A::g(char, U) {}
-// expected-warning@-1 {{extraneous template parameter list in template 
specialization}}
+// expected-error@-1 {{extraneous template parameter list in template 
specialization}}
 //   expected-note@#dr531-A-char {{'template<>' header not required for 
explicitly-specialized class 'dr531::bad::A' declared here}}
 template<> struct A::B {};
 // expected-error@-1 {{extraneous 'template<>' in declaration of struct 
'B'}}
 // expected-error@-2 {{specialization of member 'dr531::bad::A::B' 
does not specialize an instantiated member}}
 //  expected-note@#dr531-B {{attempt to specialize declaration here}}
-// FIXME: This is ill-formed; -pedantic-errors should reject.
 template<> template struct A::C {};
-// expected-warning@-1 {{extraneous template parameter list in template 
specialization}}
+// expected-error@-1 {{extraneous template parameter list in template 
specialization}}
 //   expected-note@#dr531-A-char {{'template<>' header not required for 
explicitly-specialized class 'dr531::bad::A' declared here}}
 template<> char A::n = 0;
 // expected-error@-1 {{extraneous 'template<>' in declaration of variable 
'n'}}
@@ -808,7 +806,7 @@ namespace dr571 { // dr571 unknown
   int 

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

2024-02-20 Thread Haojian Wu via cfe-commits

hokein wrote:

> It might have been commented out so that it doesn't take up space in the 
> compiled binary.
> 
> I'd like seeing it compiled, just to make sure it doesn't break. But I'd also 
> like if it doesn't appear in the final binary. Perhaps we can change 
> visibility so that `--gc-sections` or LTO can optimize it out? But I'm not 
> sure if that's enough.

If we don't want it to be in the final binary, how about guarding this part of 
code (`declaration` & `definition`) with `#ifndef NDEBUG`? 

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


[clang] [Clang][Sema] Convert warning for extraneous template parameter lists to an extension warning (PR #82277)

2024-02-20 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian updated 
https://github.com/llvm/llvm-project/pull/82277

>From c31ab160b6fb1fb765a885ab3f553437c5768d28 Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Mon, 19 Feb 2024 15:36:10 -0500
Subject: [PATCH 1/2] [Clang][Sema] Convert warning for extraneous template
 parameter lists to an extension warning

---
 clang/include/clang/Basic/DiagnosticSemaKinds.td|  2 +-
 clang/lib/Sema/SemaTemplate.cpp |  2 +-
 clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p23.cpp |  6 ++
 clang/test/CXX/drs/dr5xx.cpp| 10 --
 clang/test/Misc/warning-flags.c |  2 +-
 5 files changed, 9 insertions(+), 13 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 6e3cebc311eeb9..47e892e34260c3 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5325,7 +5325,7 @@ def err_alias_template_extra_headers : Error<
 def err_template_spec_extra_headers : Error<
   "extraneous template parameter list in template specialization or "
   "out-of-line template definition">;
-def warn_template_spec_extra_headers : Warning<
+def ext_template_spec_extra_headers : ExtWarn<
   "extraneous template parameter list in template specialization">;
 def note_explicit_template_spec_does_not_need_header : Note<
   "'template<>' header not required for explicitly-specialized class %0 "
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 9e516da2aa27a1..1a975a8d0a0df5 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -3667,7 +3667,7 @@ TemplateParameterList 
*Sema::MatchTemplateParametersToScopeSpecifier(
 
 if (!SuppressDiagnostic)
   Diag(ParamLists[ParamIdx]->getTemplateLoc(),
-   AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
+   AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
   : diag::err_template_spec_extra_headers)
   << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
  ParamLists[ParamLists.size() - 2]->getRAngleLoc());
diff --git a/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p23.cpp 
b/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p23.cpp
index 469c4e091953c3..683392c5891538 100644
--- a/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p23.cpp
+++ b/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p23.cpp
@@ -1,7 +1,6 @@
 // RUN: %clang_cc1 -std=c++20 -pedantic-errors -verify %s
 
-// FIXME: This should be an error with -pedantic-errors.
-template<> // expected-warning {{extraneous template parameter list in 
template specialization}}
+template<> // expected-error {{extraneous template parameter list in template 
specialization}}
 void f(auto);
 
 template
@@ -18,7 +17,6 @@ void A::g(auto) { }
 template<>
 void A::g(auto) { }
 
-// FIXME: This should be an error with -pedantic-errors.
 template<>
-template<> // expected-warning {{extraneous template parameter list in 
template specialization}}
+template<> // expected-error {{extraneous template parameter list in template 
specialization}}
 void A::g(auto) { }
diff --git a/clang/test/CXX/drs/dr5xx.cpp b/clang/test/CXX/drs/dr5xx.cpp
index 21a6646d4abcf1..0e1de342f6706f 100644
--- a/clang/test/CXX/drs/dr5xx.cpp
+++ b/clang/test/CXX/drs/dr5xx.cpp
@@ -354,17 +354,15 @@ namespace dr531 { // dr531: partial
 
 template<> void A::f(char) {}
 // expected-error@-1 {{no function template matches function template 
specialization 'f'}}
-// FIXME: This is ill-formed; -pedantic-errors should reject.
 template<> template void A::g(char, U) {}
-// expected-warning@-1 {{extraneous template parameter list in template 
specialization}}
+// expected-error@-1 {{extraneous template parameter list in template 
specialization}}
 //   expected-note@#dr531-A-char {{'template<>' header not required for 
explicitly-specialized class 'dr531::bad::A' declared here}}
 template<> struct A::B {};
 // expected-error@-1 {{extraneous 'template<>' in declaration of struct 
'B'}}
 // expected-error@-2 {{specialization of member 'dr531::bad::A::B' 
does not specialize an instantiated member}}
 //  expected-note@#dr531-B {{attempt to specialize declaration here}}
-// FIXME: This is ill-formed; -pedantic-errors should reject.
 template<> template struct A::C {};
-// expected-warning@-1 {{extraneous template parameter list in template 
specialization}}
+// expected-error@-1 {{extraneous template parameter list in template 
specialization}}
 //   expected-note@#dr531-A-char {{'template<>' header not required for 
explicitly-specialized class 'dr531::bad::A' declared here}}
 template<> char A::n = 0;
 // expected-error@-1 {{extraneous 'template<>' in declaration of variable 
'n'}}
@@ -808,7 +806,7 @@ namespace dr571 { // dr571 unknown
   int 

[clang] [Clang][Sema] Convert warning for extraneous template parameter lists to an extension warning (PR #82277)

2024-02-20 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian updated 
https://github.com/llvm/llvm-project/pull/82277

>From c31ab160b6fb1fb765a885ab3f553437c5768d28 Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Mon, 19 Feb 2024 15:36:10 -0500
Subject: [PATCH 1/3] [Clang][Sema] Convert warning for extraneous template
 parameter lists to an extension warning

---
 clang/include/clang/Basic/DiagnosticSemaKinds.td|  2 +-
 clang/lib/Sema/SemaTemplate.cpp |  2 +-
 clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p23.cpp |  6 ++
 clang/test/CXX/drs/dr5xx.cpp| 10 --
 clang/test/Misc/warning-flags.c |  2 +-
 5 files changed, 9 insertions(+), 13 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 6e3cebc311eeb9..47e892e34260c3 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5325,7 +5325,7 @@ def err_alias_template_extra_headers : Error<
 def err_template_spec_extra_headers : Error<
   "extraneous template parameter list in template specialization or "
   "out-of-line template definition">;
-def warn_template_spec_extra_headers : Warning<
+def ext_template_spec_extra_headers : ExtWarn<
   "extraneous template parameter list in template specialization">;
 def note_explicit_template_spec_does_not_need_header : Note<
   "'template<>' header not required for explicitly-specialized class %0 "
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 9e516da2aa27a1..1a975a8d0a0df5 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -3667,7 +3667,7 @@ TemplateParameterList 
*Sema::MatchTemplateParametersToScopeSpecifier(
 
 if (!SuppressDiagnostic)
   Diag(ParamLists[ParamIdx]->getTemplateLoc(),
-   AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
+   AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
   : diag::err_template_spec_extra_headers)
   << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
  ParamLists[ParamLists.size() - 2]->getRAngleLoc());
diff --git a/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p23.cpp 
b/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p23.cpp
index 469c4e091953c3..683392c5891538 100644
--- a/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p23.cpp
+++ b/clang/test/CXX/dcl.decl/dcl.meaning/dcl.fct/p23.cpp
@@ -1,7 +1,6 @@
 // RUN: %clang_cc1 -std=c++20 -pedantic-errors -verify %s
 
-// FIXME: This should be an error with -pedantic-errors.
-template<> // expected-warning {{extraneous template parameter list in 
template specialization}}
+template<> // expected-error {{extraneous template parameter list in template 
specialization}}
 void f(auto);
 
 template
@@ -18,7 +17,6 @@ void A::g(auto) { }
 template<>
 void A::g(auto) { }
 
-// FIXME: This should be an error with -pedantic-errors.
 template<>
-template<> // expected-warning {{extraneous template parameter list in 
template specialization}}
+template<> // expected-error {{extraneous template parameter list in template 
specialization}}
 void A::g(auto) { }
diff --git a/clang/test/CXX/drs/dr5xx.cpp b/clang/test/CXX/drs/dr5xx.cpp
index 21a6646d4abcf1..0e1de342f6706f 100644
--- a/clang/test/CXX/drs/dr5xx.cpp
+++ b/clang/test/CXX/drs/dr5xx.cpp
@@ -354,17 +354,15 @@ namespace dr531 { // dr531: partial
 
 template<> void A::f(char) {}
 // expected-error@-1 {{no function template matches function template 
specialization 'f'}}
-// FIXME: This is ill-formed; -pedantic-errors should reject.
 template<> template void A::g(char, U) {}
-// expected-warning@-1 {{extraneous template parameter list in template 
specialization}}
+// expected-error@-1 {{extraneous template parameter list in template 
specialization}}
 //   expected-note@#dr531-A-char {{'template<>' header not required for 
explicitly-specialized class 'dr531::bad::A' declared here}}
 template<> struct A::B {};
 // expected-error@-1 {{extraneous 'template<>' in declaration of struct 
'B'}}
 // expected-error@-2 {{specialization of member 'dr531::bad::A::B' 
does not specialize an instantiated member}}
 //  expected-note@#dr531-B {{attempt to specialize declaration here}}
-// FIXME: This is ill-formed; -pedantic-errors should reject.
 template<> template struct A::C {};
-// expected-warning@-1 {{extraneous template parameter list in template 
specialization}}
+// expected-error@-1 {{extraneous template parameter list in template 
specialization}}
 //   expected-note@#dr531-A-char {{'template<>' header not required for 
explicitly-specialized class 'dr531::bad::A' declared here}}
 template<> char A::n = 0;
 // expected-error@-1 {{extraneous 'template<>' in declaration of variable 
'n'}}
@@ -808,7 +806,7 @@ namespace dr571 { // dr571 unknown
   int 

[clang] [Clang][Sema] Diagnose declarative nested-name-specifiers naming alias templates (PR #80842)

2024-02-20 Thread Krystian Stasiowski via cfe-commits

sdkrystian wrote:

@erichkeane Should i wait for additional reviews, or can this be merged?

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


[clang] Reapply "[Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (#78274)" (PR #79683)

2024-02-20 Thread Krystian Stasiowski via cfe-commits


@@ -885,16 +885,19 @@ bool Sema::DiagnoseUninstantiableTemplate(SourceLocation 
PointOfInstantiation,
 /// that the template parameter 'PrevDecl' is being shadowed by a new
 /// declaration at location Loc. Returns true to indicate that this is
 /// an error, and false otherwise.
-void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) 
{
+void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
+   bool IssueWarning) {

sdkrystian wrote:

Ping @cor3ntin 

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


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

2024-02-20 Thread Erich Keane via cfe-commits

erichkeane wrote:

> what would be the reason for windows build failing , is it a CI issue or 
> specific to this PR & what can I do to resolve that. Thank you

That appears to be a problem with the CI itself.  I think we've fixed up a 
bunch of the CI, but it will require doing a 'merge' with main.  That said, I 
think you're OK to just squash/merge as-is.

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


[clang] [clang][NFC] Regroup declarations in `Sema` (PR #82217)

2024-02-20 Thread Erich Keane via cfe-commits

erichkeane wrote:

> This is going to be rather disruptive on downstream projects. At least we 
> should wait until after the release of clang 18 to merge it, to avoid endless 
> merge conflicts

For the most part, git will handle these pretty well on downstreams I think, 
and as they are declarations, I suspect this isn't going to be super tough of a 
merge conflict.  That said, waiting until after 18 is perhaps a good diea.

>  Table of contents added at the very beginning of `Sema`. Grouping is 
> reflected in Doxygen commands, so structure of API reference of `Sema` is 
> also significantly improved ([example from official 
> documentation](https://www.doxygen.nl/manual/examples/memgrp/html/class_memgrp___test.html)).

Neat!
> 
> While grouping is intentional, as well as each group consisting of `public` 
> declarations followed by `private` ones (without changing access in-between),

I MIGHT suggest private followed by public?  It is a not-uncommon pattern I've 
seen to have a private 'helper' class(or data member) defined inline, that is 
then used by inline-defined public functions.  

>Data members and inline function definitions in `Sema.h` complicate the 
>matter, since it's not obvious which group they belong to. Further work is 
>expected to refine contents and order of declarations.

This IS going to be complicated unfortunately.  Many of the function 
definitions at least are going to be 1-liners that are just calling into a 
different definition.  Data members you'll probably have to hunt down where 
they are used to see the relationship.

> What is also intentional is some kind of layering, where Concepts group 
> follows template groups, and ObjC, code completion, CUDA, HLSL, OpenACC, 
> OpenMP, and SYCL are all placed at the end of the file, after C and C++ parts 
> of `Sema`.

 
> Member initializer list of `Sema` in `Sema.cpp` is rewritten to reflect new 
> order of data members in order to avoid `-Wreorder-ctor`.

I wouldn't mind some sort of 'static_assert' to ensure that this doesn't 
accidentally increase the size of Sema or cause some sort of pessimization for 
layout.  I realize we're not particularly concerned about the size, but I could 
imagine goofy things going on.  

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


[clang] [flang] [RFC][flang][runtime] Add FortranFloat128Math wrapper library. (PR #81971)

2024-02-20 Thread Peter Klausler via cfe-commits

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


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


[clang] [flang] [RFC][flang][runtime] Add FortranFloat128Math wrapper library. (PR #81971)

2024-02-20 Thread Kiran Chandramohan via cfe-commits

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

Thanks Slava.

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


[clang] [llvm] [AMDGPU] Adding the amdgpu-num-work-groups function attribute (PR #79035)

2024-02-20 Thread Erich Keane via cfe-commits

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


[clang] [llvm] [AMDGPU] Adding the amdgpu-num-work-groups function attribute (PR #79035)

2024-02-20 Thread Erich Keane via cfe-commits

https://github.com/erichkeane commented:

Reviewed the CFE component, didn't look at LLVM.

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


[clang] [llvm] [AMDGPU] Adding the amdgpu-num-work-groups function attribute (PR #79035)

2024-02-20 Thread Erich Keane via cfe-commits


@@ -2705,6 +2705,33 @@ An error will be given if:
   }];
 }
 
+def AMDGPUMaxNumWorkGroupsDocs : Documentation {
+  let Category = DocCatAMDGPUAttributes;
+  let Content = [{
+This attribute specifies the max number of work groups when the kernel
+is dispatched.
+
+Clang supports the
+``__attribute__((amdgpu_max_num_work_groups(, , )))`` or
+``[[clang::amdgpu_max_num_work_groups(, , )]]`` attribute for the
+AMDGPU target. This attribute may be attached to HIP or OpenCL kernel function
+definitions and is an optimization hint.
+
+ parameter specifies the maximum number of work groups in the x 
dimension.
+Similarly  and  are for the y and z dimensions respectively.
+Each of the three numbers must be >=1. The attribute is ignored if any of the

erichkeane wrote:

I don't think 'ignored' is the right semantics here: that should diagnose.

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


[clang] [llvm] [AMDGPU] Adding the amdgpu-num-work-groups function attribute (PR #79035)

2024-02-20 Thread Erich Keane via cfe-commits


@@ -2705,6 +2705,33 @@ An error will be given if:
   }];
 }
 
+def AMDGPUMaxNumWorkGroupsDocs : Documentation {
+  let Category = DocCatAMDGPUAttributes;
+  let Content = [{
+This attribute specifies the max number of work groups when the kernel
+is dispatched.
+
+Clang supports the
+``__attribute__((amdgpu_max_num_work_groups(, , )))`` or
+``[[clang::amdgpu_max_num_work_groups(, , )]]`` attribute for the
+AMDGPU target. This attribute may be attached to HIP or OpenCL kernel function
+definitions and is an optimization hint.
+
+ parameter specifies the maximum number of work groups in the x 
dimension.
+Similarly  and  are for the y and z dimensions respectively.
+Each of the three numbers must be >=1. The attribute is ignored if any of the

erichkeane wrote:

```suggestion
Each of the three values must be greater than zero. The attribute is ignored if 
any of the
```

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


[clang] [llvm] [AMDGPU] Adding the amdgpu-num-work-groups function attribute (PR #79035)

2024-02-20 Thread Erich Keane via cfe-commits


@@ -2705,6 +2705,33 @@ An error will be given if:
   }];
 }
 
+def AMDGPUMaxNumWorkGroupsDocs : Documentation {
+  let Category = DocCatAMDGPUAttributes;
+  let Content = [{
+This attribute specifies the max number of work groups when the kernel
+is dispatched.
+
+Clang supports the
+``__attribute__((amdgpu_max_num_work_groups(, , )))`` or
+``[[clang::amdgpu_max_num_work_groups(, , )]]`` attribute for the
+AMDGPU target. This attribute may be attached to HIP or OpenCL kernel function
+definitions and is an optimization hint.
+
+ parameter specifies the maximum number of work groups in the x 
dimension.

erichkeane wrote:

```suggestion
The  parameter specifies the maximum number of work groups in the x 
dimension.
```

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


[clang] [llvm] [AMDGPU] Adding the amdgpu-num-work-groups function attribute (PR #79035)

2024-02-20 Thread Erich Keane via cfe-commits


@@ -8069,6 +8069,26 @@ static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, 
const ParsedAttr &AL) {
   D->addAttr(::new (S.Context) AMDGPUNumVGPRAttr(S.Context, AL, NumVGPR));
 }
 
+static void handleAMDGPUMaxNumWorkGroupsAttr(Sema &S, Decl *D,
+ const ParsedAttr &AL) {
+  uint32_t NumWGX = 0;
+  uint32_t NumWGY = 0;
+  uint32_t NumWGZ = 0;
+  Expr *NumWGXExpr = AL.getArgAsExpr(0);
+  Expr *NumWGYExpr = AL.getArgAsExpr(1);
+  Expr *NumWGZExpr = AL.getArgAsExpr(2);
+  if (!checkUInt32Argument(S, AL, NumWGXExpr, NumWGX))
+return;
+  if (!checkUInt32Argument(S, AL, NumWGYExpr, NumWGY))
+return;
+  if (!checkUInt32Argument(S, AL, NumWGZExpr, NumWGZ))
+return;
+
+  if (NumWGX != 0 && NumWGY != 0 && NumWGZ != 0)

erichkeane wrote:

This needs to diagnose.

https://github.com/llvm/llvm-project/pull/79035
___
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-20 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/2] [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-tools-extra] [clangd] Prevent printing huge initializer lists in hover definitions (PR #79746)

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


@@ -143,8 +143,16 @@ std::string printDefinition(const Decl *D, PrintingPolicy 
PP,
   // Initializers might be huge and result in lots of memory allocations in
   // some catostrophic cases. Such long lists are not useful in hover cards
   // anyway.
-  if (200 < TB.expandedTokens(IE->getSourceRange()).size())
+  const auto &SM = VD->getASTContext().getSourceManager();
+  if (!SM.isInMainFile(VD->getLocation())) {

kadircet wrote:

we actually need `IE->getSourceRange()` to be inside the mainfile, this can 
still be `int x[] = EXPANDS_TO_CRAZY_LONG_INIT_DEFINED_OUTSIDE_THE_MAINFILE`. 
also you're just checking the first level of children now, we can have 
something like: `int **x = { {CRAZY_EXPANSION} };` which only has a single 
children at top level, but still has a ton nested underneath.

can we just have:
```
auto TotalChildrenInStmt = [&](const Stmt *S) {
  size_t res = 1;
  for(auto &C : S->children()) res += TotalChildrenInStmt(C);
  return res;
};
PP.SuppressInitializers = 200 < TB.expandedTokens(IE->getSourceRange()).size() 
|| 100 < TotalChildrenInExpr(IE);
```

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


[clang] [Clang][Sema] Diagnose declarative nested-name-specifiers naming alias templates (PR #80842)

2024-02-20 Thread Erich Keane via cfe-commits

erichkeane wrote:

I think we're good, feel free to resolve your conflict and commit.

https://github.com/llvm/llvm-project/pull/80842
___
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-20 Thread via cfe-commits
=?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= 
Message-ID:
In-Reply-To: 


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

LGTM, thanks for the update!

The new `getZeroVal()` is a nice simplification.

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


  1   2   3   4   5   >