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

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


@@ -171,6 +151,24 @@ class UncountedLocalVarsChecker
 
 std::optional IsUncountedPtr = isUncountedPtr(ArgType);
 if (IsUncountedPtr && *IsUncountedPtr) {
+
+  ASTContext &ctx = V->getASTContext();
+  for (DynTypedNodeList ancestors = ctx.getParents(*V); !ancestors.empty();
+   ancestors = ctx.getParents(*ancestors.begin())) {

rniwa wrote:

Okay, I've rewritten to do that instead. Indeed, this looks cleaner.

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


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

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

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

>From fd171b82d03b29926984b5b835ad9c0ccf197536 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Mon, 19 Feb 2024 01:07:13 -0800
Subject: [PATCH 1/4] [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 defd83ec8e179c1..904781e6ea72ae2 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -245,18 +245,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.
@@ -272,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); }
@@ -286,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] [X86][AArch64][PowerPC] __builtin_cpu_supports accepts unknown options. (PR #83515)

2024-02-29 Thread via cfe-commits

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

Thanks!

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


[clang] [clang-format][doc] fix documentation for clang-format (PR #83415)

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

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


[clang] Don't do casting of atomic FP loads/stores in FE. (PR #83446)

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


@@ -1410,13 +1414,14 @@ RValue 
AtomicInfo::ConvertIntToValueOrAtomic(llvm::Value *IntVal,
 auto *ValTy = AsValue
   ? CGF.ConvertTypeForMem(ValueTy)
   : getAtomicAddress().getElementType();
-if (ValTy->isIntegerTy()) {
-  assert(IntVal->getType() == ValTy && "Different integer types.");
-  return RValue::get(CGF.EmitFromMemory(IntVal, ValueTy));
+if (ValTy->isIntegerTy() || (!CastFP && ValTy->isIEEELikeFPTy())) {
+  assert((!ValTy->isIntegerTy() || Val->getType() == ValTy) &&
+ "Different integer types.");
+  return RValue::get(CGF.EmitFromMemory(Val, ValueTy));
 } else if (ValTy->isPointerTy())
-  return RValue::get(CGF.Builder.CreateIntToPtr(IntVal, ValTy));
-else if (llvm::CastInst::isBitCastable(IntVal->getType(), ValTy))
-  return RValue::get(CGF.Builder.CreateBitCast(IntVal, ValTy));
+  return RValue::get(CGF.Builder.CreateIntToPtr(Val, ValTy));
+else if (llvm::CastInst::isBitCastable(Val->getType(), ValTy))
+  return RValue::get(CGF.Builder.CreateBitCast(Val, ValTy));

arsenm wrote:

Shouldn't be casting pointers either. I think this should pass through all 
types directly to atomicrmw 

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


[clang] [clang][Documentation] fix documentation for clang-format (PR #83415)

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

owenca wrote:

Hi, you need to edit `clang/include/clang/Format/Format.h` and then run 
`clang/docs/tools/dump_format_style.py` to regenerate 
`clang/docs/ClangFormatStyleOptions.rst`.

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


[clang] [clang][analyzer] Add StreamChecker note tags for "indeterminate stream position". (PR #83288)

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

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


[clang] 012b697 - [clang][analyzer] Add StreamChecker note tags for "indeterminate stream position". (#83288)

2024-02-29 Thread via cfe-commits

Author: Balázs Kéri
Date: 2024-03-01T08:21:57+01:00
New Revision: 012b697e7c3633ae17639b086414fd6c02127810

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

LOG: [clang][analyzer] Add StreamChecker note tags for "indeterminate stream 
position". (#83288)

If a stream operation fails the position can become "indeterminate".
This may cause warning from the checker at a later operation. The new
note tag shows the place where the position becomes "indeterminate",
this is where a failure occurred.

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
clang/test/Analysis/stream-note.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 65bdc4cac30940..0208f94e1b5a2a 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -174,6 +174,9 @@ using FnCheck = std::function::max();
 
+const char *FeofNote = "Assuming stream reaches end-of-file here";
+const char *FerrorNote = "Assuming this stream operation fails";
+
 struct FnDescription {
   FnCheck PreFn;
   FnCheck EvalFn;
@@ -218,87 +221,6 @@ inline void assertStreamStateOpened(const StreamState *SS) 
{
   assert(SS->isOpened() && "Stream is expected to be opened");
 }
 
-struct StreamOperationEvaluator {
-  SValBuilder &SVB;
-  const ASTContext &ACtx;
-
-  SymbolRef StreamSym;
-  const StreamState *SS = nullptr;
-  const CallExpr *CE = nullptr;
-
-  StreamOperationEvaluator(CheckerContext &C)
-  : SVB(C.getSValBuilder()), ACtx(C.getASTContext()) {
-;
-  }
-
-  bool Init(const FnDescription *Desc, const CallEvent &Call, CheckerContext 
&C,
-ProgramStateRef State) {
-StreamSym = getStreamArg(Desc, Call).getAsSymbol();
-if (!StreamSym)
-  return false;
-SS = State->get(StreamSym);
-if (!SS)
-  return false;
-CE = dyn_cast_or_null(Call.getOriginExpr());
-if (!CE)
-  return false;
-
-assertStreamStateOpened(SS);
-
-return true;
-  }
-
-  bool isStreamEof() const { return SS->ErrorState == ErrorFEof; }
-
-  NonLoc getZeroVal(const CallEvent &Call) {
-return *SVB.makeZeroVal(Call.getResultType()).getAs();
-  }
-
-  ProgramStateRef setStreamState(ProgramStateRef State,
- const StreamState &NewSS) {
-return State->set(StreamSym, NewSS);
-  }
-
-  ProgramStateRef makeAndBindRetVal(ProgramStateRef State, CheckerContext &C) {
-NonLoc RetVal = makeRetVal(C, CE).castAs();
-return State->BindExpr(CE, C.getLocationContext(), RetVal);
-  }
-
-  ProgramStateRef bindReturnValue(ProgramStateRef State, CheckerContext &C,
-  uint64_t Val) {
-return State->BindExpr(CE, C.getLocationContext(),
-   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(),
-   C.getSValBuilder().makeNullWithType(CE->getType()));
-  }
-
-  ProgramStateRef assumeBinOpNN(ProgramStateRef State,
-BinaryOperator::Opcode Op, NonLoc LHS,
-NonLoc RHS) {
-auto Cond = SVB.evalBinOpNN(State, Op, LHS, RHS, SVB.getConditionType())
-.getAs();
-if (!Cond)
-  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 
{
   BugType BT_FileNull{this, "NULL stream pointer", "Stream handling error"};
@@ -322,11 +244,59 @@ class StreamChecker : public CheckergetBT_StreamEof())
+return "";
+
+  BR.markNotInteresting(StreamSym);
+
+  return FeofNote;
+});
+  }
+
+  const NoteTag *constructSetErrorNoteTag(CheckerContext &C,
+  SymbolRef StreamSym) const {
+return C.getNoteTag([this, StreamSym](PathSensitiveBugReport &BR) {
+  if (!BR.isInteresting(StreamSym) ||
+  &BR.getBugType() != this->getBT_IndeterminatePosition())
+return "";
+
+  BR.markNotInteresting(StreamSym);
+
+  return FerrorNote;
+});
+  }
+
+  const NoteTag *constructSetEofOrError

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

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

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

>From fd171b82d03b29926984b5b835ad9c0ccf197536 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Mon, 19 Feb 2024 01:07:13 -0800
Subject: [PATCH 1/3] [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 defd83ec8e179c1..904781e6ea72ae2 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -245,18 +245,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.
@@ -272,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); }
@@ -286,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-29 Thread Ryosuke Niwa via cfe-commits


@@ -70,15 +71,27 @@ bool isSingleton(const FunctionDecl *F);
 class TrivialFunctionAnalysis {
 public:
   /// \returns true if \p D is a "trivial" function.
-  bool isTrivial(const Decl *D) const { return isTrivialImpl(D, TheCache); }
+  bool isTrivial(const Decl *D) const {
+return isTrivialImpl(D, TheFunctionCache, TheStatementCache);
+  }
+
+  bool isTrivial(const Stmt *S) const {
+return isTrivialImpl(S, TheFunctionCache, TheStatementCache);
+  }
 
 private:
   friend class TrivialFunctionAnalysisVisitor;
 
-  using CacheTy = llvm::DenseMap;
-  mutable CacheTy TheCache{};
+  using FunctionCacheTy = llvm::DenseMap;
+  mutable FunctionCacheTy TheFunctionCache{};
+
+  using StatementCacheTy = llvm::DenseMap;
+  mutable StatementCacheTy TheStatementCache{};

rniwa wrote:

Okay, done that.

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


[clang] [FMV] Use lexicographic order of feature names when mangling. (PR #83464)

2024-02-29 Thread via cfe-commits

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

LGTM

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


[clang] [clang-format][NFC] Replace Style.isCpp() with IsCpp (PR #83533)

2024-02-29 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes



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


5 Files Affected:

- (modified) clang/lib/Format/FormatToken.h (+2-2) 
- (modified) clang/lib/Format/TokenAnnotator.cpp (+18-21) 
- (modified) clang/lib/Format/TokenAnnotator.h (+3-1) 
- (modified) clang/lib/Format/UnwrappedLineParser.cpp (+21-22) 
- (modified) clang/lib/Format/UnwrappedLineParser.h (+1) 


``diff
diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 0c1dce7a294082..31245495041960 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -821,8 +821,8 @@ struct FormatToken {
 
   /// Returns whether the token is the left square bracket of a C++
   /// structured binding declaration.
-  bool isCppStructuredBinding(const FormatStyle &Style) const {
-if (!Style.isCpp() || isNot(tok::l_square))
+  bool isCppStructuredBinding(bool IsCpp) const {
+if (!IsCpp || isNot(tok::l_square))
   return false;
 const FormatToken *T = this;
 do {
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index a60d6ae197a24e..04f0374b674e53 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -126,7 +126,7 @@ class AnnotatingParser {
const AdditionalKeywords &Keywords,
SmallVector &Scopes)
   : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
-Keywords(Keywords), Scopes(Scopes) {
+IsCpp(Style.isCpp()), Keywords(Keywords), Scopes(Scopes) {
 Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
 resetTokenMetadata();
   }
@@ -676,13 +676,13 @@ class AnnotatingParser {
 // In C++, this can happen either in array of templates (foo[10])
 // or when array is a nested template type (unique_ptr[]>).
 bool CppArrayTemplates =
-Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) &&
+IsCpp && Parent && Parent->is(TT_TemplateCloser) &&
 (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
  Contexts.back().ContextType == Context::TemplateArgument);
 
 const bool IsInnerSquare = Contexts.back().InCpp11AttributeSpecifier;
 const bool IsCpp11AttributeSpecifier =
-isCppAttribute(Style.isCpp(), *Left) || IsInnerSquare;
+isCppAttribute(IsCpp, *Left) || IsInnerSquare;
 
 // Treat C# Attributes [STAThread] much like C++ attributes [[...]].
 bool IsCSharpAttributeSpecifier =
@@ -690,12 +690,11 @@ class AnnotatingParser {
 Contexts.back().InCSharpAttributeSpecifier;
 
 bool InsideInlineASM = Line.startsWith(tok::kw_asm);
-bool IsCppStructuredBinding = Left->isCppStructuredBinding(Style);
+bool IsCppStructuredBinding = Left->isCppStructuredBinding(IsCpp);
 bool StartsObjCMethodExpr =
 !IsCppStructuredBinding && !InsideInlineASM && !CppArrayTemplates &&
-Style.isCpp() && !IsCpp11AttributeSpecifier &&
-!IsCSharpAttributeSpecifier && Contexts.back().CanBeExpression &&
-Left->isNot(TT_LambdaLSquare) &&
+IsCpp && !IsCpp11AttributeSpecifier && !IsCSharpAttributeSpecifier &&
+Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
 !CurrentToken->isOneOf(tok::l_brace, tok::r_square) &&
 (!Parent ||
  Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
@@ -723,7 +722,7 @@ class AnnotatingParser {
  Contexts.back().ContextKind == tok::l_brace &&
  Parent->isOneOf(tok::l_brace, tok::comma)) {
 Left->setType(TT_JsComputedPropertyName);
-  } else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace 
&&
+  } else if (IsCpp && Contexts.back().ContextKind == tok::l_brace &&
  Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
 Left->setType(TT_DesignatedInitializerLSquare);
   } else if (IsCSharpAttributeSpecifier) {
@@ -1161,7 +1160,7 @@ class AnnotatingParser {
 if (Previous->is(TT_JsTypeOptionalQuestion))
   Previous = Previous->getPreviousNonComment();
 if ((CurrentToken->is(tok::colon) && !Style.isTableGen() &&
- (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
+ (!Contexts.back().ColonIsDictLiteral || !IsCpp)) ||
 Style.isProto()) {
   OpeningBrace.setType(TT_DictLiteral);
   if (Previous->Tok.getIdentifierInfo() ||
@@ -1230,7 +1229,7 @@ class AnnotatingParser {
   }
 
   bool consumeToken() {
-if (Style.isCpp()) {
+if (IsCpp) {
   const auto *Prev = CurrentToken->getPreviousNonComment();
   if (Prev && Prev->is(tok::r_square) && Prev->is(TT_AttributeSquare) &&
   CurrentToken->isOneOf(tok::kw_if, tok::kw_switch, tok::kw_case,
@@ -1424,7 +1423,7 @@ class AnnotatingParser {
 if (CurrentToken && CurrentToken->is(Ke

[clang] [clang-format][NFC] Replace Style.isCpp() with IsCpp (PR #83533)

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

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

None

>From a643963e818a9c6c4abea93c15f8c48f7291a837 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Thu, 29 Feb 2024 23:07:58 -0800
Subject: [PATCH] [clang-format][NFC] Replace Style.isCpp() with IsCpp

---
 clang/lib/Format/FormatToken.h   |  4 +--
 clang/lib/Format/TokenAnnotator.cpp  | 39 ++---
 clang/lib/Format/TokenAnnotator.h|  4 ++-
 clang/lib/Format/UnwrappedLineParser.cpp | 43 
 clang/lib/Format/UnwrappedLineParser.h   |  1 +
 5 files changed, 45 insertions(+), 46 deletions(-)

diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 0c1dce7a294082..31245495041960 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -821,8 +821,8 @@ struct FormatToken {
 
   /// Returns whether the token is the left square bracket of a C++
   /// structured binding declaration.
-  bool isCppStructuredBinding(const FormatStyle &Style) const {
-if (!Style.isCpp() || isNot(tok::l_square))
+  bool isCppStructuredBinding(bool IsCpp) const {
+if (!IsCpp || isNot(tok::l_square))
   return false;
 const FormatToken *T = this;
 do {
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index a60d6ae197a24e..04f0374b674e53 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -126,7 +126,7 @@ class AnnotatingParser {
const AdditionalKeywords &Keywords,
SmallVector &Scopes)
   : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
-Keywords(Keywords), Scopes(Scopes) {
+IsCpp(Style.isCpp()), Keywords(Keywords), Scopes(Scopes) {
 Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
 resetTokenMetadata();
   }
@@ -676,13 +676,13 @@ class AnnotatingParser {
 // In C++, this can happen either in array of templates (foo[10])
 // or when array is a nested template type (unique_ptr[]>).
 bool CppArrayTemplates =
-Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) &&
+IsCpp && Parent && Parent->is(TT_TemplateCloser) &&
 (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
  Contexts.back().ContextType == Context::TemplateArgument);
 
 const bool IsInnerSquare = Contexts.back().InCpp11AttributeSpecifier;
 const bool IsCpp11AttributeSpecifier =
-isCppAttribute(Style.isCpp(), *Left) || IsInnerSquare;
+isCppAttribute(IsCpp, *Left) || IsInnerSquare;
 
 // Treat C# Attributes [STAThread] much like C++ attributes [[...]].
 bool IsCSharpAttributeSpecifier =
@@ -690,12 +690,11 @@ class AnnotatingParser {
 Contexts.back().InCSharpAttributeSpecifier;
 
 bool InsideInlineASM = Line.startsWith(tok::kw_asm);
-bool IsCppStructuredBinding = Left->isCppStructuredBinding(Style);
+bool IsCppStructuredBinding = Left->isCppStructuredBinding(IsCpp);
 bool StartsObjCMethodExpr =
 !IsCppStructuredBinding && !InsideInlineASM && !CppArrayTemplates &&
-Style.isCpp() && !IsCpp11AttributeSpecifier &&
-!IsCSharpAttributeSpecifier && Contexts.back().CanBeExpression &&
-Left->isNot(TT_LambdaLSquare) &&
+IsCpp && !IsCpp11AttributeSpecifier && !IsCSharpAttributeSpecifier &&
+Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
 !CurrentToken->isOneOf(tok::l_brace, tok::r_square) &&
 (!Parent ||
  Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
@@ -723,7 +722,7 @@ class AnnotatingParser {
  Contexts.back().ContextKind == tok::l_brace &&
  Parent->isOneOf(tok::l_brace, tok::comma)) {
 Left->setType(TT_JsComputedPropertyName);
-  } else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace 
&&
+  } else if (IsCpp && Contexts.back().ContextKind == tok::l_brace &&
  Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
 Left->setType(TT_DesignatedInitializerLSquare);
   } else if (IsCSharpAttributeSpecifier) {
@@ -1161,7 +1160,7 @@ class AnnotatingParser {
 if (Previous->is(TT_JsTypeOptionalQuestion))
   Previous = Previous->getPreviousNonComment();
 if ((CurrentToken->is(tok::colon) && !Style.isTableGen() &&
- (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
+ (!Contexts.back().ColonIsDictLiteral || !IsCpp)) ||
 Style.isProto()) {
   OpeningBrace.setType(TT_DictLiteral);
   if (Previous->Tok.getIdentifierInfo() ||
@@ -1230,7 +1229,7 @@ class AnnotatingParser {
   }
 
   bool consumeToken() {
-if (Style.isCpp()) {
+if (IsCpp) {
   const auto *Prev = CurrentToken->getPreviousNonComment();
   if (Prev && Prev->is(tok::r_square) && Prev->is(TT_AttributeSquare) &&
   CurrentTok

[clang] [clang][Sema] Warn on self move for inlined static cast (PR #76646)

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


@@ -18843,17 +18843,26 @@ void Sema::DiagnoseSelfMove(const Expr *LHSExpr, 
const Expr *RHSExpr,
   LHSExpr = LHSExpr->IgnoreParenImpCasts();
   RHSExpr = RHSExpr->IgnoreParenImpCasts();
 
-  // Check for a call expression
+  // Check for a call expression or static_cast expression
   const CallExpr *CE = dyn_cast(RHSExpr);
-  if (!CE || CE->getNumArgs() != 1)
+  const auto *CXXSCE = dyn_cast(RHSExpr);
+  if (!CE && !CXXSCE)
 return;
 
   // Check for a call to std::move
-  if (!CE->isCallToStdMove())
+  if (CE && (CE->getNumArgs() != 1 || !CE->isCallToStdMove()))
 return;
 
-  // Get argument from std::move
-  RHSExpr = CE->getArg(0);
+  // Check for a static_cast(..) to an xvalue which we can treat as an
+  // inlined std::move
+  if (CXXSCE && !CXXSCE->isXValue())
+return;
+
+  // Get argument from std::move or static_cast
+  if (CE)
+RHSExpr = CE->getArg(0);
+  else
+RHSExpr = CXXSCE->getSubExpr();

tbaederr wrote:

```suggestion
  if (const auto *CE = dyn_cast(RHSExpr);
  CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
RHSExpr = CE->getArg(0);
  else if (const auto *CXXSCE = dyn_cast(RHSExpr);
  CXXSCE && CXXSCE->isXValue())
RHSExpr = CXXSCE->getSubExpr();
  else
return;
```

I think that would be shorter and cleaner. (This replaces the few lines above 
as well but I can't add a suggestion like that in Github).

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


[clang] [clang-tools-extra] [clang-tidy] Add new check `modernize-use-designated-initializers` (PR #80541)

2024-02-29 Thread Danny Mösch via cfe-commits

SimplyDanny wrote:

Thank you for the fast fix, @PiotrZSL!

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


[clang] [llvm] [RISCV] RISCV vector calling convention (1/2) (PR #77560)

2024-02-29 Thread Shao-Ce SUN via cfe-commits

sunshaoce wrote:

I tried compiling it and then got two warnings.
```
llvm-project/clang/lib/CodeGen/CGDebugInfo.cpp:1408:11: warning: enumeration 
value 'CC_RISCVVectorCall' not handled in switch [-Wswitch]
 1408 |   switch (CC) {
  |   ^~
1 warning generated.
[3629/3776] Building CXX object 
tools/clang/tools/libclang/CMakeFiles/libclang.dir/CXType.cpp.o
llvm-project/clang/tools/libclang/CXType.cpp:662:13: warning: enumeration value 
'CC_RISCVVectorCall' not handled in switch [-Wswitch]
  662 | switch (FD->getCallConv()) {
  | ^
1 warning generated.
```

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


[clang-tools-extra] [clangd] Remove calls to getFileLoc() in declToSym() (PR #83532)

2024-02-29 Thread via cfe-commits

llvmbot wrote:




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

Author: Nathan Ridge (HighCommander4)


Changes

toHalfOpenFileRange() already handles translating macro locations to file 
locations, and it can provide a better result by knowing about both ends of the 
range.

Fixes https://github.com/clangd/clangd/issues/1941

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


2 Files Affected:

- (modified) clang-tools-extra/clangd/FindSymbols.cpp (+2-2) 
- (modified) clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp (+8-1) 


``diff
diff --git a/clang-tools-extra/clangd/FindSymbols.cpp 
b/clang-tools-extra/clangd/FindSymbols.cpp
index 5b3e46a7b4dc16..5244a4e893769e 100644
--- a/clang-tools-extra/clangd/FindSymbols.cpp
+++ b/clang-tools-extra/clangd/FindSymbols.cpp
@@ -223,8 +223,8 @@ std::string getSymbolDetail(ASTContext &Ctx, const 
NamedDecl &ND) {
 std::optional declToSym(ASTContext &Ctx, const NamedDecl &ND) {
   auto &SM = Ctx.getSourceManager();
 
-  SourceLocation BeginLoc = SM.getFileLoc(ND.getBeginLoc());
-  SourceLocation EndLoc = SM.getFileLoc(ND.getEndLoc());
+  SourceLocation BeginLoc = ND.getBeginLoc();
+  SourceLocation EndLoc = ND.getEndLoc();
   const auto SymbolRange =
   toHalfOpenFileRange(SM, Ctx.getLangOpts(), {BeginLoc, EndLoc});
   if (!SymbolRange)
diff --git a/clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp 
b/clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
index b1b8b4ccd184c2..4276a44275f535 100644
--- a/clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
@@ -750,6 +750,9 @@ TEST(DocumentSymbols, RangeFromMacro) {
 $fullDef[[FF3() {
   int var = 42;
 }]]
+
+#define FF4(name) int name = 0
+$FooRange[[FF4($FooSelectionRange[[foo]])]];
   )");
   TU.Code = Main.code().str();
   EXPECT_THAT(
@@ -766,7 +769,11 @@ TEST(DocumentSymbols, RangeFromMacro) {
   AllOf(withName("FF3"), withDetail("()"),
 symRange(Main.range("fullDef")),
 children(AllOf(withName("waldo"), withDetail("void ()"),
-   symRange(Main.range("fullDef")));
+   symRange(Main.range("fullDef"),
+  AllOf(
+  withName("FF4"), withDetail("(foo)"),
+  children(AllOf(withName("foo"), symRange(Main.range("FooRange")),
+ 
symNameRange(Main.range("FooSelectionRange")));
 }
 
 TEST(DocumentSymbols, FuncTemplates) {

``




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


[clang-tools-extra] [clangd] Remove calls to getFileLoc() in declToSym() (PR #83532)

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

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

toHalfOpenFileRange() already handles translating macro locations to file 
locations, and it can provide a better result by knowing about both ends of the 
range.

Fixes https://github.com/clangd/clangd/issues/1941

>From b419bcb01b406321af2cf226b3d30390d7231487 Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Wed, 28 Feb 2024 03:26:07 -0500
Subject: [PATCH] [clangd] Remove calls to getFileLoc() in declToSym()

toHalfOpenFileRange() already handles translating macro locations
to file locations, and it can provide a better result by knowing
about both ends of the range.

https://github.com/clangd/clangd/issues/1941
---
 clang-tools-extra/clangd/FindSymbols.cpp| 4 ++--
 clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp | 9 -
 2 files changed, 10 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clangd/FindSymbols.cpp 
b/clang-tools-extra/clangd/FindSymbols.cpp
index 5b3e46a7b4dc16..5244a4e893769e 100644
--- a/clang-tools-extra/clangd/FindSymbols.cpp
+++ b/clang-tools-extra/clangd/FindSymbols.cpp
@@ -223,8 +223,8 @@ std::string getSymbolDetail(ASTContext &Ctx, const 
NamedDecl &ND) {
 std::optional declToSym(ASTContext &Ctx, const NamedDecl &ND) {
   auto &SM = Ctx.getSourceManager();
 
-  SourceLocation BeginLoc = SM.getFileLoc(ND.getBeginLoc());
-  SourceLocation EndLoc = SM.getFileLoc(ND.getEndLoc());
+  SourceLocation BeginLoc = ND.getBeginLoc();
+  SourceLocation EndLoc = ND.getEndLoc();
   const auto SymbolRange =
   toHalfOpenFileRange(SM, Ctx.getLangOpts(), {BeginLoc, EndLoc});
   if (!SymbolRange)
diff --git a/clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp 
b/clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
index b1b8b4ccd184c2..4276a44275f535 100644
--- a/clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
@@ -750,6 +750,9 @@ TEST(DocumentSymbols, RangeFromMacro) {
 $fullDef[[FF3() {
   int var = 42;
 }]]
+
+#define FF4(name) int name = 0
+$FooRange[[FF4($FooSelectionRange[[foo]])]];
   )");
   TU.Code = Main.code().str();
   EXPECT_THAT(
@@ -766,7 +769,11 @@ TEST(DocumentSymbols, RangeFromMacro) {
   AllOf(withName("FF3"), withDetail("()"),
 symRange(Main.range("fullDef")),
 children(AllOf(withName("waldo"), withDetail("void ()"),
-   symRange(Main.range("fullDef")));
+   symRange(Main.range("fullDef"),
+  AllOf(
+  withName("FF4"), withDetail("(foo)"),
+  children(AllOf(withName("foo"), symRange(Main.range("FooRange")),
+ 
symNameRange(Main.range("FooSelectionRange")));
 }
 
 TEST(DocumentSymbols, FuncTemplates) {

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


[clang] [compiler-rt] [AArch64] Implement __builtin_cpu_supports, compiler-rt tests. (PR #82378)

2024-02-29 Thread via cfe-commits

eaeltsin wrote:

Thanks @ilinpv !

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


[clang] [clang-format] Enable again some operator tests (PR #83380)

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

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


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


[clang] [clang-format] Enable again some operator tests (PR #83380)

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


@@ -16710,7 +16705,7 @@ TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
   verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
   verifyFormat("T A::operator()();", SpaceFuncDef);
   verifyFormat("X A::operator++(T);", SpaceFuncDef);
-  // verifyFormat("T A::operator() () {}", SpaceFuncDef);
+  verifyFormat("T A::operator()() {}", SpaceFuncDef);

owenca wrote:

Ditto.

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


[clang] [clang-format] Enable again some operator tests (PR #83380)

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

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


[clang] [clang-format] Enable again some operator tests (PR #83380)

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


@@ -16671,9 +16667,8 @@ TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
SpaceFuncDecl);
   verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
   verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
-  // FIXME these tests regressed behaviour.
-  // verifyFormat("T A::operator() ();", SpaceFuncDecl);
-  // verifyFormat("X A::operator++ (T);", SpaceFuncDecl);
+  verifyFormat("T A::operator()();", SpaceFuncDecl);
+  verifyFormat("X A::operator++(T);", SpaceFuncDecl);

owenca wrote:

It seems that D114696 restored the space in `operator` function declarations 
and definitions.

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


[clang] 8116dfb - [InstallAPI] Use unique identifiers for input buffers (#83523)

2024-02-29 Thread via cfe-commits

Author: Cyndy Ishida
Date: 2024-02-29T21:42:43-08:00
New Revision: 8116dfb8b58a65e78e341f09f5728d345f086b7b

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

LOG: [InstallAPI] Use unique identifiers for input buffers (#83523)

Added: 


Modified: 
clang/lib/InstallAPI/Frontend.cpp

Removed: 




diff  --git a/clang/lib/InstallAPI/Frontend.cpp 
b/clang/lib/InstallAPI/Frontend.cpp
index 9f675ef7d1bd22..133e49230ffa9b 100644
--- a/clang/lib/InstallAPI/Frontend.cpp
+++ b/clang/lib/InstallAPI/Frontend.cpp
@@ -51,8 +51,10 @@ std::unique_ptr createInputBuffer(const 
InstallAPIContext &Ctx) {
   if (Contents.empty())
 return nullptr;
 
-  return llvm::MemoryBuffer::getMemBufferCopy(
-  Contents, "installapi-includes" + getFileExtension(Ctx.LangMode));
+  SmallString<64> BufferName(
+  {"installapi-includes-", Ctx.Slice->getTriple().str(), "-",
+   getName(Ctx.Type), getFileExtension(Ctx.LangMode)});
+  return llvm::MemoryBuffer::getMemBufferCopy(Contents, BufferName);
 }
 
 } // namespace clang::installapi



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


[clang] [InstallAPI] Use unique identifiers for input buffers (PR #83523)

2024-02-29 Thread Cyndy Ishida via cfe-commits

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


[clang] [llvm] [RISCV] RISCV vector calling convention (1/2) (PR #77560)

2024-02-29 Thread Brandon Wu via cfe-commits

4vtomat wrote:

ping

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


[clang] [InstallAPI] Use unique identifiers for input buffers (PR #83523)

2024-02-29 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Cyndy Ishida (cyndyishida)


Changes



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


1 Files Affected:

- (modified) clang/lib/InstallAPI/Frontend.cpp (+4-2) 


``diff
diff --git a/clang/lib/InstallAPI/Frontend.cpp 
b/clang/lib/InstallAPI/Frontend.cpp
index 9f675ef7d1bd22..133e49230ffa9b 100644
--- a/clang/lib/InstallAPI/Frontend.cpp
+++ b/clang/lib/InstallAPI/Frontend.cpp
@@ -51,8 +51,10 @@ std::unique_ptr createInputBuffer(const 
InstallAPIContext &Ctx) {
   if (Contents.empty())
 return nullptr;
 
-  return llvm::MemoryBuffer::getMemBufferCopy(
-  Contents, "installapi-includes" + getFileExtension(Ctx.LangMode));
+  SmallString<64> BufferName(
+  {"installapi-includes-", Ctx.Slice->getTriple().str(), "-",
+   getName(Ctx.Type), getFileExtension(Ctx.LangMode)});
+  return llvm::MemoryBuffer::getMemBufferCopy(Contents, BufferName);
 }
 
 } // namespace clang::installapi

``




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


[clang] [InstallAPI] Use unique identifiers for input buffers (PR #83523)

2024-02-29 Thread Cyndy Ishida via cfe-commits

https://github.com/cyndyishida created 
https://github.com/llvm/llvm-project/pull/83523

None

>From 82521efd33c253b34da149b5dfe6bbb7823589c1 Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Thu, 29 Feb 2024 21:04:58 -0800
Subject: [PATCH] [InstallAPI] Use unique name for input buffers

---
 clang/lib/InstallAPI/Frontend.cpp | 6 --
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/clang/lib/InstallAPI/Frontend.cpp 
b/clang/lib/InstallAPI/Frontend.cpp
index 9f675ef7d1bd22..133e49230ffa9b 100644
--- a/clang/lib/InstallAPI/Frontend.cpp
+++ b/clang/lib/InstallAPI/Frontend.cpp
@@ -51,8 +51,10 @@ std::unique_ptr createInputBuffer(const 
InstallAPIContext &Ctx) {
   if (Contents.empty())
 return nullptr;
 
-  return llvm::MemoryBuffer::getMemBufferCopy(
-  Contents, "installapi-includes" + getFileExtension(Ctx.LangMode));
+  SmallString<64> BufferName(
+  {"installapi-includes-", Ctx.Slice->getTriple().str(), "-",
+   getName(Ctx.Type), getFileExtension(Ctx.LangMode)});
+  return llvm::MemoryBuffer::getMemBufferCopy(Contents, BufferName);
 }
 
 } // namespace clang::installapi

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


[clang] [llvm] [AMDGPU] Add code model (#70760) test for amdgpu target. (PR #71019)

2024-02-29 Thread Pravin Jagtap via cfe-commits

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


[clang] [llvm] [PseudoProbe] Mix and reorder block and call probe ID in lexical order (PR #75092)

2024-02-29 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 cf68c0427d9d3816eefcfe7d3d648a98146c07cf 
6641409c4ee90807e48023ea071be016f52c11ff -- 
clang/test/CodeGen/pseudo-probe-emit.c 
llvm/include/llvm/Transforms/IPO/SampleProfileProbe.h 
llvm/lib/Transforms/IPO/SampleProfile.cpp 
llvm/lib/Transforms/IPO/SampleProfileProbe.cpp
``





View the diff from clang-format here.


``diff
diff --git a/llvm/lib/Transforms/IPO/SampleProfile.cpp 
b/llvm/lib/Transforms/IPO/SampleProfile.cpp
index 402920d3a9..ffc26f1a0a 100644
--- a/llvm/lib/Transforms/IPO/SampleProfile.cpp
+++ b/llvm/lib/Transforms/IPO/SampleProfile.cpp
@@ -1190,7 +1190,7 @@ void SampleProfileLoader::findExternalInlineCandidate(
 CalleeSample->getContext().hasAttribute(ContextShouldBeInlined);
 if (!PreInline && CalleeSample->getHeadSamplesEstimate() < Threshold)
   continue;
-
+
 Function *Func = SymbolMap.lookup(CalleeSample->getFunction());
 // Add to the import list only when it's defined out of module.
 if (!Func || Func->isDeclaration())

``




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


[clang] [llvm] [PseudoProbe] Mix and reorder block and call probe ID in lexical order (PR #75092)

2024-02-29 Thread Lei Wang via cfe-commits

https://github.com/wlei-llvm updated 
https://github.com/llvm/llvm-project/pull/75092

>From e6f735a336f87659ee3236fc795ad4b7107dff4d Mon Sep 17 00:00:00 2001
From: wlei 
Date: Sun, 10 Dec 2023 18:30:42 -0800
Subject: [PATCH 1/5] [PseudoProbe] Mix and reorder block and call probe ID in
 lexical order

---
 clang/test/CodeGen/pseudo-probe-emit.c|  8 +++
 .../llvm/Transforms/IPO/SampleProfileProbe.h  |  3 +--
 .../lib/Transforms/IPO/SampleProfileProbe.cpp | 19 +---
 .../Inputs/pseudo-probe-profile.prof  |  8 +++
 .../Inputs/pseudo-probe-update.prof   |  8 +++
 .../SampleProfile/pseudo-probe-dangle.ll  | 12 +-
 .../pseudo-probe-discriminator.ll |  6 ++---
 .../pseudo-probe-profile-metadata-2.ll| 15 ++---
 .../SampleProfile/pseudo-probe-profile.ll | 22 +--
 .../SampleProfile/pseudo-probe-update.ll  | 11 +-
 .../SampleProfile/pseudo-probe-verify.ll  | 16 +++---
 11 files changed, 59 insertions(+), 69 deletions(-)

diff --git a/clang/test/CodeGen/pseudo-probe-emit.c 
b/clang/test/CodeGen/pseudo-probe-emit.c
index c7a3f7e6d5b02b..360f831e842945 100644
--- a/clang/test/CodeGen/pseudo-probe-emit.c
+++ b/clang/test/CodeGen/pseudo-probe-emit.c
@@ -10,9 +10,9 @@ void foo(int x) {
   // CHECK: call void @llvm.pseudoprobe(i64 [[#GUID:]], i64 1, i32 0, i64 -1)
   if (x == 0)
 // CHECK: call void @llvm.pseudoprobe(i64 [[#GUID]], i64 2, i32 0, i64 -1)
-bar();
+bar();  // probe id : 3
   else
-// CHECK: call void @llvm.pseudoprobe(i64 [[#GUID]], i64 3, i32 0, i64 -1)
-go();
-  // CHECK: call void @llvm.pseudoprobe(i64 [[#GUID]], i64 4, i32 0, i64 -1)
+// CHECK: call void @llvm.pseudoprobe(i64 [[#GUID]], i64 4, i32 0, i64 -1)
+go(); // probe id : 5
+  // CHECK: call void @llvm.pseudoprobe(i64 [[#GUID]], i64 6, i32 0, i64 -1)
 }
diff --git a/llvm/include/llvm/Transforms/IPO/SampleProfileProbe.h 
b/llvm/include/llvm/Transforms/IPO/SampleProfileProbe.h
index 0f2729a9462de2..69b87adf105fd1 100644
--- a/llvm/include/llvm/Transforms/IPO/SampleProfileProbe.h
+++ b/llvm/include/llvm/Transforms/IPO/SampleProfileProbe.h
@@ -82,8 +82,7 @@ class SampleProfileProber {
   uint32_t getBlockId(const BasicBlock *BB) const;
   uint32_t getCallsiteId(const Instruction *Call) const;
   void computeCFGHash();
-  void computeProbeIdForBlocks();
-  void computeProbeIdForCallsites();
+  void computeProbeId();
 
   Function *F;
 
diff --git a/llvm/lib/Transforms/IPO/SampleProfileProbe.cpp 
b/llvm/lib/Transforms/IPO/SampleProfileProbe.cpp
index 090e5560483edb..975c1bc2347aa4 100644
--- a/llvm/lib/Transforms/IPO/SampleProfileProbe.cpp
+++ b/llvm/lib/Transforms/IPO/SampleProfileProbe.cpp
@@ -173,8 +173,7 @@ SampleProfileProber::SampleProfileProber(Function &Func,
   BlockProbeIds.clear();
   CallProbeIds.clear();
   LastProbeId = (uint32_t)PseudoProbeReservedId::Last;
-  computeProbeIdForBlocks();
-  computeProbeIdForCallsites();
+  computeProbeId();
   computeCFGHash();
 }
 
@@ -207,7 +206,10 @@ void SampleProfileProber::computeCFGHash() {
 << ", Hash = " << FunctionHash << "\n");
 }
 
-void SampleProfileProber::computeProbeIdForBlocks() {
+void SampleProfileProber::computeProbeId() {
+  LLVMContext &Ctx = F->getContext();
+  Module *M = F->getParent();
+
   DenseSet KnownColdBlocks;
   computeEHOnlyBlocks(*F, KnownColdBlocks);
   // Insert pseudo probe to non-cold blocks only. This will reduce IR size as
@@ -216,18 +218,9 @@ void SampleProfileProber::computeProbeIdForBlocks() {
 ++LastProbeId;
 if (!KnownColdBlocks.contains(&BB))
   BlockProbeIds[&BB] = LastProbeId;
-  }
-}
 
-void SampleProfileProber::computeProbeIdForCallsites() {
-  LLVMContext &Ctx = F->getContext();
-  Module *M = F->getParent();
-
-  for (auto &BB : *F) {
 for (auto &I : BB) {
-  if (!isa(I))
-continue;
-  if (isa(&I))
+  if (!isa(I) || isa(&I))
 continue;
 
   // The current implementation uses the lower 16 bits of the discriminator
diff --git 
a/llvm/test/Transforms/SampleProfile/Inputs/pseudo-probe-profile.prof 
b/llvm/test/Transforms/SampleProfile/Inputs/pseudo-probe-profile.prof
index ba4c6117dc96ab..d3847946b94033 100644
--- a/llvm/test/Transforms/SampleProfile/Inputs/pseudo-probe-profile.prof
+++ b/llvm/test/Transforms/SampleProfile/Inputs/pseudo-probe-profile.prof
@@ -1,8 +1,8 @@
 foo:3200:13
  1: 13
  2: 7
- 3: 6
- 4: 13
- 5: 7 _Z3barv:2 _Z3foov:5
- 6: 6 _Z3barv:4 _Z3foov:2
+ 4: 6
+ 6: 13
+ 3: 7 _Z3barv:2 _Z3foov:5
+ 5: 6 _Z3barv:4 _Z3foov:2
  !CFGChecksum: 563022570642068
diff --git a/llvm/test/Transforms/SampleProfile/Inputs/pseudo-probe-update.prof 
b/llvm/test/Transforms/SampleProfile/Inputs/pseudo-probe-update.prof
index 62f9bd5992e735..213bf0b6f81cc4 100644
--- a/llvm/test/Transforms/SampleProfile/Inputs/pseudo-probe-update.prof
+++ b/llvm/test/Transforms/SampleProfile/Inputs/pseudo-probe-update.prof
@@ -1,8 +1,8 @@
 foo:3200:13
  1: 13
 

[clang] [llvm] [HLSL][DXIL] Implementation of round intrinsic (PR #83520)

2024-02-29 Thread Farzon Lotfi via cfe-commits

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


[clang] [llvm] [PseudoProbe] Mix and reorder block and call probe ID in lexical order (PR #75092)

2024-02-29 Thread Lei Wang via cfe-commits

wlei-llvm wrote:

> > > LGTM. I'd also have a change that errors out on huge staleness go in 
> > > together with this one..
> > 
> > 
> > Was thinking to use a separate diff for that, feels non-trivial to do it, 
> > but I'm also good for doing in this.
> > Just pushed one version for this, it use heuristics to check this, note 
> > that the current threshold flags is just based my "gut feeling", so I'm 
> > going to tune those flags on our internal services, hope that we can 
> > achieve the goal:
> > 
> > 1. Use the current prod profile, so all build should pass without any false 
> > positives break.
> > 2. Use the incompatible profile, so all build should error out.
> > 
> > Any early feedback is appreciated.
> 
> Sorry I wasn't clear. The error out change should be a separate patch as 
> logically it's independent of the original mix order change. By go in 
> together, I was mostly thinking about two patches that go in together..

Oh, that's my initial thought too, Ok, I will create a new PR, and hold this 
until we can go in together. 

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


[clang] [llvm] [HLSL][DXIL] Implementation of round intrinsic (PR #83520)

2024-02-29 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-hlsl
@llvm/pr-subscribers-backend-directx

@llvm/pr-subscribers-clang

Author: Farzon Lotfi (farzonl)


Changes

- Builtins.td - add the round builtin
- CGBuiltin.cpp - add the builtin to DirectX intrinsic mapping 
hlsl_intrinsics.h - add the round  api
- SemaChecking.cpp - add type checks for builtin
- IntrinsicsDirectX.td - add the round intrinsic
- DXIL.td add the llvm intrinsic to DXIL lowering mapping 
- This change implements: #70077

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


9 Files Affected:

- (modified) clang/include/clang/Basic/Builtins.td (+6) 
- (modified) clang/lib/CodeGen/CGBuiltin.cpp (+8) 
- (modified) clang/lib/Headers/hlsl/hlsl_intrinsics.h (+34) 
- (modified) clang/lib/Sema/SemaChecking.cpp (+7) 
- (added) clang/test/CodeGenHLSL/builtins/round.hlsl (+53) 
- (added) clang/test/SemaHLSL/BuiltIns/round-errors.hlsl (+27) 
- (modified) llvm/include/llvm/IR/IntrinsicsDirectX.td (+1) 
- (modified) llvm/lib/Target/DirectX/DXIL.td (+3) 
- (added) llvm/test/CodeGen/DirectX/round.ll (+43) 


``diff
diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 2c83dca248fb7d..cb59a7b26f729f 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4548,6 +4548,12 @@ def HLSLLerp : LangBuiltin<"HLSL_LANG"> {
   let Prototype = "void(...)";
 }
 
+def HLSLRound : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_elementwise_round"];
+  let Attributes = [NoThrow, Const];
+  let Prototype = "void(...)";
+}
+
 // Builtins for XRay.
 def XRayCustomEvent : Builtin {
   let Spellings = ["__xray_customevent"];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 98684448f4ff5c..a27390c4e85fb7 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -18052,6 +18052,14 @@ Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned 
BuiltinID,
 /*ReturnType*/ Op0->getType(), Intrinsic::dx_frac,
 ArrayRef{Op0}, nullptr, "dx.frac");
   }
+  case Builtin::BI__builtin_hlsl_elementwise_round: {
+Value *Op0 = EmitScalarExpr(E->getArg(0));
+if (!E->getArg(0)->getType()->hasFloatingRepresentation())
+  llvm_unreachable("round operand must have a float representation");
+return Builder.CreateIntrinsic(
+/*ReturnType*/ Op0->getType(), Intrinsic::dx_round,
+ArrayRef{Op0}, nullptr, "dx.round");
+  }
   }
   return nullptr;
 }
diff --git a/clang/lib/Headers/hlsl/hlsl_intrinsics.h 
b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
index 0aa8651ba80dc4..4f52b001440584 100644
--- a/clang/lib/Headers/hlsl/hlsl_intrinsics.h
+++ b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
@@ -831,6 +831,40 @@ uint64_t3 reversebits(uint64_t3);
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_bitreverse)
 uint64_t4 reversebits(uint64_t4);
 
+//===--===//
+// frac builtins
+//===--===//
+
+/// \fn T round(T x)
+/// \brief Rounds the specified value to the nearest integer. Halfway cases are
+/// rounded to the nearest even. \a x parameter. \param x The specified input
+/// value.
+///
+/// The return value is the \a x parameter, rounded to the nearest integer
+/// within a floating-point type.
+
+_HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_round)
+half round(half);
+_HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_round)
+half2 round(half2);
+_HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_round)
+half3 round(half3);
+_HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_round)
+half4 round(half4);
+
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_round)
+float round(float);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_round)
+float2 round(float2);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_round)
+float3 round(float3);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_round)
+float4 round(float4);
+
 
//===--===//
 // sin builtins
 
//===--===//
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 690bdaa63d058b..56e4264f85ccdd 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -5294,6 +5294,13 @@ bool Sema::CheckHLSLBuiltinFunctionCall(unsigned 
BuiltinID, CallExpr *TheCall) {
   return true;
 break;
   }
+  case Builtin::BI__builtin_hlsl_elementwise_round: {
+if (PrepareBuiltinElementwiseMathOneArgCall(TheCall))
+  return true;
+if (CheckAllArgsHaveFloatRepresentation(this, TheCall))
+  return true;
+break;
+  }
   }
   return false;
 }
diff --git a/clang/test/CodeGe

[clang] [llvm] [HLSL][DXIL] Implementation of round intrinsic (PR #83520)

2024-02-29 Thread Farzon Lotfi via cfe-commits

https://github.com/farzonl created 
https://github.com/llvm/llvm-project/pull/83520

- Builtins.td - add the round builtin
- CGBuiltin.cpp - add the builtin to DirectX intrinsic mapping 
hlsl_intrinsics.h - add the round  api
- SemaChecking.cpp - add type checks for builtin
- IntrinsicsDirectX.td - add the round intrinsic
- DXIL.td add the llvm intrinsic to DXIL lowering mapping 
- This change implements: #70077

>From f9ce067ed26268cc2015109e1f9389d0321590e8 Mon Sep 17 00:00:00 2001
From: Farzon Lotfi 
Date: Thu, 29 Feb 2024 21:48:47 -0500
Subject: [PATCH] [HLSL][DXIL] Implementation of round intrinsic Builtins.td -
 add the round builtin CGBuiltin.cpp - add the builtin to DirectX intrinsic
 mapping hlsl_intrinsics.h - add the round  api SemaChecking.cpp - add type
 checks for builtin IntrinsicsDirectX.td - add the round intrinsic DXIL.td add
 the llvm intrinsic to DXIL lowering mapping This change implements: #70077

---
 clang/include/clang/Basic/Builtins.td |  6 +++
 clang/lib/CodeGen/CGBuiltin.cpp   |  8 +++
 clang/lib/Headers/hlsl/hlsl_intrinsics.h  | 34 
 clang/lib/Sema/SemaChecking.cpp   |  7 +++
 clang/test/CodeGenHLSL/builtins/round.hlsl| 53 +++
 .../test/SemaHLSL/BuiltIns/round-errors.hlsl  | 27 ++
 llvm/include/llvm/IR/IntrinsicsDirectX.td |  1 +
 llvm/lib/Target/DirectX/DXIL.td   |  3 ++
 llvm/test/CodeGen/DirectX/round.ll| 43 +++
 9 files changed, 182 insertions(+)
 create mode 100644 clang/test/CodeGenHLSL/builtins/round.hlsl
 create mode 100644 clang/test/SemaHLSL/BuiltIns/round-errors.hlsl
 create mode 100644 llvm/test/CodeGen/DirectX/round.ll

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 2c83dca248fb7d..cb59a7b26f729f 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4548,6 +4548,12 @@ def HLSLLerp : LangBuiltin<"HLSL_LANG"> {
   let Prototype = "void(...)";
 }
 
+def HLSLRound : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_elementwise_round"];
+  let Attributes = [NoThrow, Const];
+  let Prototype = "void(...)";
+}
+
 // Builtins for XRay.
 def XRayCustomEvent : Builtin {
   let Spellings = ["__xray_customevent"];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 98684448f4ff5c..a27390c4e85fb7 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -18052,6 +18052,14 @@ Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned 
BuiltinID,
 /*ReturnType*/ Op0->getType(), Intrinsic::dx_frac,
 ArrayRef{Op0}, nullptr, "dx.frac");
   }
+  case Builtin::BI__builtin_hlsl_elementwise_round: {
+Value *Op0 = EmitScalarExpr(E->getArg(0));
+if (!E->getArg(0)->getType()->hasFloatingRepresentation())
+  llvm_unreachable("round operand must have a float representation");
+return Builder.CreateIntrinsic(
+/*ReturnType*/ Op0->getType(), Intrinsic::dx_round,
+ArrayRef{Op0}, nullptr, "dx.round");
+  }
   }
   return nullptr;
 }
diff --git a/clang/lib/Headers/hlsl/hlsl_intrinsics.h 
b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
index 0aa8651ba80dc4..4f52b001440584 100644
--- a/clang/lib/Headers/hlsl/hlsl_intrinsics.h
+++ b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
@@ -831,6 +831,40 @@ uint64_t3 reversebits(uint64_t3);
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_bitreverse)
 uint64_t4 reversebits(uint64_t4);
 
+//===--===//
+// frac builtins
+//===--===//
+
+/// \fn T round(T x)
+/// \brief Rounds the specified value to the nearest integer. Halfway cases are
+/// rounded to the nearest even. \a x parameter. \param x The specified input
+/// value.
+///
+/// The return value is the \a x parameter, rounded to the nearest integer
+/// within a floating-point type.
+
+_HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_round)
+half round(half);
+_HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_round)
+half2 round(half2);
+_HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_round)
+half3 round(half3);
+_HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_round)
+half4 round(half4);
+
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_round)
+float round(float);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_round)
+float2 round(float2);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_round)
+float3 round(float3);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_round)
+float4 round(float4);
+
 
//===--===//
 // sin builtins
 
//===--===//
diff --git a/clang/lib

[clang] [llvm] [PseudoProbe] Mix and reorder block and call probe ID in lexical order (PR #75092)

2024-02-29 Thread via cfe-commits

WenleiHe wrote:

> > LGTM. I'd also have a change that errors out on huge staleness go in 
> > together with this one..
> 
> Was thinking to use a separate diff for that, feels non-trivial to do it, but 
> I'm also good for doing in this.
> 
> Just pushed one version for this, it use heuristics to check this, note that 
> the current threshold flags is just based my "gut feeling", so I'm going to 
> tune those flags on our internal services, hope that we can achieve the goal:
> 
> 1. Use the current prod profile, so all build should pass without any false 
> positives break.
> 2. Use the incompatible profile, so all build should error out.
> 
> Any early feedback is appreciated.

Sorry I wasn't clear. The error out change should be a separate patch as 
logically it's independent of the original mix order change. By go in together, 
I was mostly thinking about two patches that go in together.. 

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


[clang] [llvm] [PseudoProbe] Mix and reorder block and call probe ID in lexical order (PR #75092)

2024-02-29 Thread Lei Wang via cfe-commits

wlei-llvm wrote:

> LGTM. I'd also have a change that errors out on huge staleness go in together 
> with this one..

Was thinking to use a separate diff for that, feels non-trivial to do it,  but 
I'm also good for doing in this. 

Just pushed one version for this, it use heuristics to check this, note that 
the current threshold flags is just based my "gut feeling", so I'm going to 
tune those flags on our internal services, hope that we can achieve the goal: 

1) Use the current prod profile, so all build should pass without any false 
positives break. 

2) Use the incompatible profile, so all build should error out. 

Any early feedback is appreciated.

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


[clang] [llvm] [PseudoProbe] Mix and reorder block and call probe ID in lexical order (PR #75092)

2024-02-29 Thread Lei Wang via cfe-commits

https://github.com/wlei-llvm updated 
https://github.com/llvm/llvm-project/pull/75092

>From e6f735a336f87659ee3236fc795ad4b7107dff4d Mon Sep 17 00:00:00 2001
From: wlei 
Date: Sun, 10 Dec 2023 18:30:42 -0800
Subject: [PATCH 1/4] [PseudoProbe] Mix and reorder block and call probe ID in
 lexical order

---
 clang/test/CodeGen/pseudo-probe-emit.c|  8 +++
 .../llvm/Transforms/IPO/SampleProfileProbe.h  |  3 +--
 .../lib/Transforms/IPO/SampleProfileProbe.cpp | 19 +---
 .../Inputs/pseudo-probe-profile.prof  |  8 +++
 .../Inputs/pseudo-probe-update.prof   |  8 +++
 .../SampleProfile/pseudo-probe-dangle.ll  | 12 +-
 .../pseudo-probe-discriminator.ll |  6 ++---
 .../pseudo-probe-profile-metadata-2.ll| 15 ++---
 .../SampleProfile/pseudo-probe-profile.ll | 22 +--
 .../SampleProfile/pseudo-probe-update.ll  | 11 +-
 .../SampleProfile/pseudo-probe-verify.ll  | 16 +++---
 11 files changed, 59 insertions(+), 69 deletions(-)

diff --git a/clang/test/CodeGen/pseudo-probe-emit.c 
b/clang/test/CodeGen/pseudo-probe-emit.c
index c7a3f7e6d5b02b..360f831e842945 100644
--- a/clang/test/CodeGen/pseudo-probe-emit.c
+++ b/clang/test/CodeGen/pseudo-probe-emit.c
@@ -10,9 +10,9 @@ void foo(int x) {
   // CHECK: call void @llvm.pseudoprobe(i64 [[#GUID:]], i64 1, i32 0, i64 -1)
   if (x == 0)
 // CHECK: call void @llvm.pseudoprobe(i64 [[#GUID]], i64 2, i32 0, i64 -1)
-bar();
+bar();  // probe id : 3
   else
-// CHECK: call void @llvm.pseudoprobe(i64 [[#GUID]], i64 3, i32 0, i64 -1)
-go();
-  // CHECK: call void @llvm.pseudoprobe(i64 [[#GUID]], i64 4, i32 0, i64 -1)
+// CHECK: call void @llvm.pseudoprobe(i64 [[#GUID]], i64 4, i32 0, i64 -1)
+go(); // probe id : 5
+  // CHECK: call void @llvm.pseudoprobe(i64 [[#GUID]], i64 6, i32 0, i64 -1)
 }
diff --git a/llvm/include/llvm/Transforms/IPO/SampleProfileProbe.h 
b/llvm/include/llvm/Transforms/IPO/SampleProfileProbe.h
index 0f2729a9462de2..69b87adf105fd1 100644
--- a/llvm/include/llvm/Transforms/IPO/SampleProfileProbe.h
+++ b/llvm/include/llvm/Transforms/IPO/SampleProfileProbe.h
@@ -82,8 +82,7 @@ class SampleProfileProber {
   uint32_t getBlockId(const BasicBlock *BB) const;
   uint32_t getCallsiteId(const Instruction *Call) const;
   void computeCFGHash();
-  void computeProbeIdForBlocks();
-  void computeProbeIdForCallsites();
+  void computeProbeId();
 
   Function *F;
 
diff --git a/llvm/lib/Transforms/IPO/SampleProfileProbe.cpp 
b/llvm/lib/Transforms/IPO/SampleProfileProbe.cpp
index 090e5560483edb..975c1bc2347aa4 100644
--- a/llvm/lib/Transforms/IPO/SampleProfileProbe.cpp
+++ b/llvm/lib/Transforms/IPO/SampleProfileProbe.cpp
@@ -173,8 +173,7 @@ SampleProfileProber::SampleProfileProber(Function &Func,
   BlockProbeIds.clear();
   CallProbeIds.clear();
   LastProbeId = (uint32_t)PseudoProbeReservedId::Last;
-  computeProbeIdForBlocks();
-  computeProbeIdForCallsites();
+  computeProbeId();
   computeCFGHash();
 }
 
@@ -207,7 +206,10 @@ void SampleProfileProber::computeCFGHash() {
 << ", Hash = " << FunctionHash << "\n");
 }
 
-void SampleProfileProber::computeProbeIdForBlocks() {
+void SampleProfileProber::computeProbeId() {
+  LLVMContext &Ctx = F->getContext();
+  Module *M = F->getParent();
+
   DenseSet KnownColdBlocks;
   computeEHOnlyBlocks(*F, KnownColdBlocks);
   // Insert pseudo probe to non-cold blocks only. This will reduce IR size as
@@ -216,18 +218,9 @@ void SampleProfileProber::computeProbeIdForBlocks() {
 ++LastProbeId;
 if (!KnownColdBlocks.contains(&BB))
   BlockProbeIds[&BB] = LastProbeId;
-  }
-}
 
-void SampleProfileProber::computeProbeIdForCallsites() {
-  LLVMContext &Ctx = F->getContext();
-  Module *M = F->getParent();
-
-  for (auto &BB : *F) {
 for (auto &I : BB) {
-  if (!isa(I))
-continue;
-  if (isa(&I))
+  if (!isa(I) || isa(&I))
 continue;
 
   // The current implementation uses the lower 16 bits of the discriminator
diff --git 
a/llvm/test/Transforms/SampleProfile/Inputs/pseudo-probe-profile.prof 
b/llvm/test/Transforms/SampleProfile/Inputs/pseudo-probe-profile.prof
index ba4c6117dc96ab..d3847946b94033 100644
--- a/llvm/test/Transforms/SampleProfile/Inputs/pseudo-probe-profile.prof
+++ b/llvm/test/Transforms/SampleProfile/Inputs/pseudo-probe-profile.prof
@@ -1,8 +1,8 @@
 foo:3200:13
  1: 13
  2: 7
- 3: 6
- 4: 13
- 5: 7 _Z3barv:2 _Z3foov:5
- 6: 6 _Z3barv:4 _Z3foov:2
+ 4: 6
+ 6: 13
+ 3: 7 _Z3barv:2 _Z3foov:5
+ 5: 6 _Z3barv:4 _Z3foov:2
  !CFGChecksum: 563022570642068
diff --git a/llvm/test/Transforms/SampleProfile/Inputs/pseudo-probe-update.prof 
b/llvm/test/Transforms/SampleProfile/Inputs/pseudo-probe-update.prof
index 62f9bd5992e735..213bf0b6f81cc4 100644
--- a/llvm/test/Transforms/SampleProfile/Inputs/pseudo-probe-update.prof
+++ b/llvm/test/Transforms/SampleProfile/Inputs/pseudo-probe-update.prof
@@ -1,8 +1,8 @@
 foo:3200:13
  1: 13
 

[clang] [Clang][Sema] Fix incorrect rejection default construction of union with nontrivial member (PR #82407)

2024-02-29 Thread Shafik Yaghmour via cfe-commits

https://github.com/shafik updated 
https://github.com/llvm/llvm-project/pull/82407

>From 5fcaeaddccc0f7e370bf7bebce113d8d52e1b1bd Mon Sep 17 00:00:00 2001
From: Shafik Yaghmour 
Date: Tue, 20 Feb 2024 11:22:39 -0800
Subject: [PATCH] [Clang][Sema] Fix incorrect rejection default construction of
 union with nontrivial member

In 765d8a192180f8f33618087b15c022fe758044af we impelemented a fix for incorrect 
deletion of
default constructors in unions. This fix missed a case and so this PR will
extend the fix to cover the additional case.

Fixes: https://github.com/llvm/llvm-project/issues/81774
---
 clang/docs/ReleaseNotes.rst|  3 +++
 clang/lib/Sema/SemaDeclCXX.cpp | 18 +++---
 .../test/CodeGen/union-non-trivial-member.cpp  | 17 +
 clang/test/SemaCXX/cxx0x-nontrivial-union.cpp  | 11 +++
 4 files changed, 46 insertions(+), 3 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5bca2c965c866b..452382eb6c4a1e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -292,6 +292,9 @@ 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 `_`)
+- Fix for clang incorrectly rejecting the default construction of a union with
+  nontrivial member when another member has an initializer.
+  (`#81774 `_)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 79263bc3ff671d..25a4b4381ca25e 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -9442,9 +9442,21 @@ bool 
SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
 
   int DiagKind = -1;
 
-  if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
-DiagKind = !Decl ? 0 : 1;
-  else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
+  if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) {
+if (CSM == Sema::CXXDefaultConstructor && Field &&
+Field->getParent()->isUnion()) {
+  // [class.default.ctor]p2:
+  //   A defaulted default constructor for class X is defined as deleted if
+  //   - X is a union that has a variant member with a non-trivial default
+  // constructor and no variant member of X has a default member
+  // initializer
+  const auto *RD = cast(Field->getParent());
+  if (!RD->hasInClassInitializer())
+DiagKind = !Decl ? 0 : 1;
+} else {
+  DiagKind = !Decl ? 0 : 1;
+}
+  } else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
 DiagKind = 2;
   else if (!isAccessible(Subobj, Decl))
 DiagKind = 3;
diff --git a/clang/test/CodeGen/union-non-trivial-member.cpp 
b/clang/test/CodeGen/union-non-trivial-member.cpp
index fdc9fd16911e14..8b055a9970fc75 100644
--- a/clang/test/CodeGen/union-non-trivial-member.cpp
+++ b/clang/test/CodeGen/union-non-trivial-member.cpp
@@ -15,14 +15,25 @@ union UnionNonTrivial {
 non_trivial_constructor b{};
 };
 
+struct Handle {
+Handle(int) {}
+};
+
+union UnionNonTrivialEqualInit {
+int NoState = 0;
+Handle CustomState;
+};
+
 void f() {
 UnionInt u1;
 UnionNonTrivial u2;
+UnionNonTrivialEqualInit u3;
 }
 
 // CHECK:  define dso_local void @_Z1fv()
 // CHECK:call void @_ZN8UnionIntC1Ev
 // CHECK-NEXT:   call void @_ZN15UnionNonTrivialC1Ev
+// CHECK-NEXT:   call void @_ZN24UnionNonTrivialEqualInitC1Ev
 
 // CHECK:  define {{.*}}void @_ZN8UnionIntC1Ev
 // CHECK:call void @_ZN8UnionIntC2Ev
@@ -30,8 +41,14 @@ void f() {
 // CHECK:  define {{.*}}void @_ZN15UnionNonTrivialC1Ev
 // CHECK:call void @_ZN15UnionNonTrivialC2Ev
 
+// CHECK:  define {{.*}}void @_ZN24UnionNonTrivialEqualInitC1Ev
+// CHECK:call void @_ZN24UnionNonTrivialEqualInitC2Ev
+
 // CHECK:  define {{.*}}void @_ZN8UnionIntC2Ev
 // CHECK:store i32 1000
 
 // CHECK:  define {{.*}}void @_ZN15UnionNonTrivialC2Ev
 // CHECK:call void @_ZN23non_trivial_constructorC1Ev
+
+// CHECK:  define {{.*}}void @_ZN24UnionNonTrivialEqualInitC2Ev
+// CHECK:store i32 0
diff --git a/clang/test/SemaCXX/cxx0x-nontrivial-union.cpp 
b/clang/test/SemaCXX/cxx0x-nontrivial-union.cpp
index c7cdf76d850dbe..833642b3d739ab 100644
--- a/clang/test/SemaCXX/cxx0x-nontrivial-union.cpp
+++ b/clang/test/SemaCXX/cxx0x-nontrivial-union.cpp
@@ -188,3 +188,14 @@ static_assert(U2().b.x == 100, "");
 static_assert(U3().b.x == 100, "");
 
 } // namespace GH48416
+
+namespace GH81774 {
+struct Handle {
+Handle(int) {}
+};
+// Should be well-formed because NoState has a brace-or-equal-initializer.
+union a {
+int NoState = 0;
+ 

[clang] [compiler-rt] [AArch64] Implement __builtin_cpu_supports, compiler-rt tests. (PR #82378)

2024-02-29 Thread Pavel Iliin via cfe-commits

ilinpv wrote:

Fix on review https://github.com/llvm/llvm-project/pull/83515
The documentation is coming next.

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


[clang] [X86][AArch64][PowerPC] __builtin_cpu_supports accepts unknown options. (PR #83515)

2024-02-29 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-codegen

@llvm/pr-subscribers-clang

Author: Pavel Iliin (ilinpv)


Changes

The patch fixes https://github.com/llvm/llvm-project/issues/83407 modifing 
__builtin_cpu_supports behaviour so that it returns false if unsupported 
features names provided in parameter and issue a warning. 
__builtin_cpu_supports is target independent, but currently supported by X86, 
AArch64 and PowerPC only.

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


7 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+1-1) 
- (modified) clang/lib/CodeGen/CGBuiltin.cpp (+6-1) 
- (modified) clang/lib/Sema/SemaChecking.cpp (+5-3) 
- (modified) clang/test/CodeGen/aarch64-cpu-supports.c (+8) 
- (modified) clang/test/Misc/warning-flags.c (+2-1) 
- (modified) clang/test/Sema/aarch64-cpu-supports.c (+5-5) 
- (modified) clang/test/Sema/builtin-cpu-supports.c (+3-3) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 4f8902e37bd3bb..938de5859513f8 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -765,7 +765,7 @@ def err_builtin_redeclare : Error<"cannot redeclare builtin 
function %0">;
 def err_arm_invalid_specialreg : Error<"invalid special register for builtin">;
 def err_arm_invalid_coproc : Error<"coprocessor %0 must be configured as "
   "%select{GCP|CDE}1">;
-def err_invalid_cpu_supports : Error<"invalid cpu feature string for builtin">;
+def warn_invalid_cpu_supports : Warning<"invalid cpu feature string for 
builtin">;
 def err_invalid_cpu_is : Error<"invalid cpu name for builtin">;
 def err_invalid_cpu_specific_dispatch_value : Error<
 "invalid option '%0' for %select{cpu_specific|cpu_dispatch}1">;
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 98684448f4ff5c..e90014261217bc 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -13952,6 +13952,8 @@ Value *CodeGenFunction::EmitX86CpuIs(StringRef CPUStr) {
 Value *CodeGenFunction::EmitX86CpuSupports(const CallExpr *E) {
   const Expr *FeatureExpr = E->getArg(0)->IgnoreParenCasts();
   StringRef FeatureStr = cast(FeatureExpr)->getString();
+  if (!getContext().getTargetInfo().validateCpuSupports(FeatureStr))
+return Builder.getFalse();
   return EmitX86CpuSupports(FeatureStr);
 }
 
@@ -14041,6 +14043,8 @@ Value *CodeGenFunction::EmitAArch64CpuSupports(const 
CallExpr *E) {
   ArgStr.split(Features, "+");
   for (auto &Feature : Features) {
 Feature = Feature.trim();
+if (!llvm::AArch64::parseArchExtension(Feature))
+  return Builder.getFalse();
 if (Feature != "default")
   Features.push_back(Feature);
   }
@@ -16639,7 +16643,8 @@ Value *CodeGenFunction::EmitPPCBuiltinExpr(unsigned 
BuiltinID,
   .Case(Name, {FA_WORD, Bitmask})
 #include "llvm/TargetParser/PPCTargetParser.def"
 .Default({0, 0});
-assert(BitMask && "Invalid target feature string. Missed by 
SemaChecking?");
+if (!BitMask)
+  return Builder.getFalse();
 Value *Op0 = llvm::ConstantInt::get(Int32Ty, FeatureWord);
 llvm::Function *F = CGM.getIntrinsic(Intrinsic::ppc_fixed_addr_ld);
 Value *TheCall = Builder.CreateCall(F, {Op0}, "cpu_supports");
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 690bdaa63d058b..7be2b31df2413f 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -2180,9 +2180,11 @@ static bool SemaBuiltinCpu(Sema &S, const TargetInfo 
&TI, CallExpr *TheCall,
 
   // Check the contents of the string.
   StringRef Feature = cast(Arg)->getString();
-  if (IsCPUSupports && !TheTI->validateCpuSupports(Feature))
-return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
-   << Arg->getSourceRange();
+  if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
+S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
+<< Arg->getSourceRange();
+return false;
+  }
   if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
<< Arg->getSourceRange();
diff --git a/clang/test/CodeGen/aarch64-cpu-supports.c 
b/clang/test/CodeGen/aarch64-cpu-supports.c
index 872fec6827ef11..c54b7475a3fd5f 100644
--- a/clang/test/CodeGen/aarch64-cpu-supports.c
+++ b/clang/test/CodeGen/aarch64-cpu-supports.c
@@ -34,6 +34,11 @@
 // CHECK-NEXT:store i32 3, ptr [[RETVAL]], align 4
 // CHECK-NEXT:br label [[RETURN]]
 // CHECK:   if.end4:
+// CHECK-NEXT:br i1 false, label [[IF_THEN5:%.*]], label [[IF_END6:%.*]]
+// CHECK:   if.then5:
+// CHECK-NEXT:store i32 4, ptr [[RETVAL]], align 4
+// CHECK-NEXT:br label [[RETURN]]
+// CHECK:   if.end6:
 // CHECK-NEXT:store i32 0, ptr [[RETVAL]], align 4
 // CHECK-NEXT:br label [[RETURN]]
 // CHECK:  

[clang] [X86][AArch64][PowerPC] __builtin_cpu_supports accepts unknown options. (PR #83515)

2024-02-29 Thread Pavel Iliin via cfe-commits

https://github.com/ilinpv created 
https://github.com/llvm/llvm-project/pull/83515

The patch fixes https://github.com/llvm/llvm-project/issues/83407 modifing 
__builtin_cpu_supports behaviour so that it returns false if unsupported 
features names provided in parameter and issue a warning. 
__builtin_cpu_supports is target independent, but currently supported by X86, 
AArch64 and PowerPC only.

>From 6cd58223b59f7a78dc349c63e27d7771a20f0f1a Mon Sep 17 00:00:00 2001
From: Pavel Iliin 
Date: Fri, 1 Mar 2024 01:46:53 +
Subject: [PATCH] [X86][AArch64][PowerPC] __builtin_cpu_supports accepts
 unknown options.

The patch fixes https://github.com/llvm/llvm-project/issues/83407
modifing __builtin_cpu_supports behaviour so that it returns false if
unsupported features names provided in parameter and issue a warning.
__builtin_cpu_supports is target independent, but currently supported
by X86, AArch64 and PowerPC only.
---
 clang/include/clang/Basic/DiagnosticSemaKinds.td |  2 +-
 clang/lib/CodeGen/CGBuiltin.cpp  |  7 ++-
 clang/lib/Sema/SemaChecking.cpp  |  8 +---
 clang/test/CodeGen/aarch64-cpu-supports.c|  8 
 clang/test/Misc/warning-flags.c  |  3 ++-
 clang/test/Sema/aarch64-cpu-supports.c   | 10 +-
 clang/test/Sema/builtin-cpu-supports.c   |  6 +++---
 7 files changed, 30 insertions(+), 14 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 4f8902e37bd3bb..938de5859513f8 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -765,7 +765,7 @@ def err_builtin_redeclare : Error<"cannot redeclare builtin 
function %0">;
 def err_arm_invalid_specialreg : Error<"invalid special register for builtin">;
 def err_arm_invalid_coproc : Error<"coprocessor %0 must be configured as "
   "%select{GCP|CDE}1">;
-def err_invalid_cpu_supports : Error<"invalid cpu feature string for builtin">;
+def warn_invalid_cpu_supports : Warning<"invalid cpu feature string for 
builtin">;
 def err_invalid_cpu_is : Error<"invalid cpu name for builtin">;
 def err_invalid_cpu_specific_dispatch_value : Error<
 "invalid option '%0' for %select{cpu_specific|cpu_dispatch}1">;
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 98684448f4ff5c..e90014261217bc 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -13952,6 +13952,8 @@ Value *CodeGenFunction::EmitX86CpuIs(StringRef CPUStr) {
 Value *CodeGenFunction::EmitX86CpuSupports(const CallExpr *E) {
   const Expr *FeatureExpr = E->getArg(0)->IgnoreParenCasts();
   StringRef FeatureStr = cast(FeatureExpr)->getString();
+  if (!getContext().getTargetInfo().validateCpuSupports(FeatureStr))
+return Builder.getFalse();
   return EmitX86CpuSupports(FeatureStr);
 }
 
@@ -14041,6 +14043,8 @@ Value *CodeGenFunction::EmitAArch64CpuSupports(const 
CallExpr *E) {
   ArgStr.split(Features, "+");
   for (auto &Feature : Features) {
 Feature = Feature.trim();
+if (!llvm::AArch64::parseArchExtension(Feature))
+  return Builder.getFalse();
 if (Feature != "default")
   Features.push_back(Feature);
   }
@@ -16639,7 +16643,8 @@ Value *CodeGenFunction::EmitPPCBuiltinExpr(unsigned 
BuiltinID,
   .Case(Name, {FA_WORD, Bitmask})
 #include "llvm/TargetParser/PPCTargetParser.def"
 .Default({0, 0});
-assert(BitMask && "Invalid target feature string. Missed by 
SemaChecking?");
+if (!BitMask)
+  return Builder.getFalse();
 Value *Op0 = llvm::ConstantInt::get(Int32Ty, FeatureWord);
 llvm::Function *F = CGM.getIntrinsic(Intrinsic::ppc_fixed_addr_ld);
 Value *TheCall = Builder.CreateCall(F, {Op0}, "cpu_supports");
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 690bdaa63d058b..7be2b31df2413f 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -2180,9 +2180,11 @@ static bool SemaBuiltinCpu(Sema &S, const TargetInfo 
&TI, CallExpr *TheCall,
 
   // Check the contents of the string.
   StringRef Feature = cast(Arg)->getString();
-  if (IsCPUSupports && !TheTI->validateCpuSupports(Feature))
-return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
-   << Arg->getSourceRange();
+  if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
+S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
+<< Arg->getSourceRange();
+return false;
+  }
   if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
<< Arg->getSourceRange();
diff --git a/clang/test/CodeGen/aarch64-cpu-supports.c 
b/clang/test/CodeGen/aarch64-cpu-supports.c
index 872fec6827ef11..c54b7475a3fd5f 100644
--- a/clang/test/CodeGen/aarch64-cpu-supports.c
+++ b/clang/test/CodeGen/aarch64-cpu-supports.c
@@ -34,6 

[clang] [Clang][Sema]: Diagnose lambda to bool implicit casts (PR #83152)

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

MaskRay wrote:

Created #83497 as a follow-up to suppress the diagnostic for certain template 
instantiation uses.

I made one change to unblock our internal users
```
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpointer-bool-conversion"
#endif
// functor_ may be a lambda, which is convertible to bool, leading to a
// -Wpointer-bool-conversion warning because the value is always true.
return functor_ == nullptr;
#ifdef __clang__
#pragma clang diagnostic pop
#endif
```

and then (when I saw another instance of wrapping a callable object) realized 
we probably should suppress the diagnostic for instantiation. This is similar 
to how we suppress the diagnostic for instantiations for -Wtautological-compare

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


[clang] [llvm] [PowerPC] Support local-dynamic TLS relocation on AIX (PR #66316)

2024-02-29 Thread Felix via cfe-commits

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


[clang] [clang] Implement __builtin_{clzg,ctzg} (PR #83431)

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


@@ -3157,7 +3177,15 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 if (Result->getType() != ResultType)

efriedma-quic wrote:

I was more thinking of the opposite: we don't need to make the result of the 
clz defined if we're not using it.

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


[clang] [llvm] [AMDGPU] Emit a waitcnt instruction after each memory instruction (PR #79236)

2024-02-29 Thread Jun Wang via cfe-commits

jwanggit86 wrote:

@jayfoad After trying the patch you provided above, it appears that this 
feature can indeed be done in SIInsertWaitcnt instead of SIMemoryLegalizer. 
Code has been updated accordingly. Pls take a look.

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


[clang] [clang] Implement __builtin_{clzg,ctzg} (PR #83431)

2024-02-29 Thread via cfe-commits


@@ -3157,7 +3177,15 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 if (Result->getType() != ResultType)

overmighty wrote:

Since in the additions below I check if the argument itself is zero instead of 
checking the result of `ctlz`, I don't see why the `ctlz` result for zero being 
undefined would be a problem.

https://github.com/llvm/llvm-project/pull/83431
___
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-29 Thread Artem Dergachev via cfe-commits

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


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

2024-02-29 Thread Artem Dergachev via cfe-commits


@@ -171,6 +151,24 @@ class UncountedLocalVarsChecker
 
 std::optional IsUncountedPtr = isUncountedPtr(ArgType);
 if (IsUncountedPtr && *IsUncountedPtr) {
+
+  ASTContext &ctx = V->getASTContext();
+  for (DynTypedNodeList ancestors = ctx.getParents(*V); !ancestors.empty();
+   ancestors = ctx.getParents(*ancestors.begin())) {

haoNoQ wrote:

I don't think this should be a recursive loop. As is, it'll match `x` not only 
in
```
if (int x = 1) {
}
```
but also in
```
if (1) {
  int x;
}
```
which is probably not what you want(?) So you probably need to check that `V` 
is the condition variable.

Also, generally speaking, usually we try to avoid `ParentMap`/`getParent()` 
shenanigans. Parent lookups aren't naturally provided by the AST, they rely on 
building the "parent map" by scanning the entire AST in the natural order and 
putting all edges into the map. There are a few very confusing cornercases in 
this algorithm and a few known crashes in that I honestly don't know how to 
fix. It also screws algorithmic complexity because now we have an additional 
backwards traversal; it's very easy to accidentally start walking back and 
forth indefinitely, or just way too many times. Sometimes it's necessary but 
most of the time there's a normal top-down approach that gives the answer 
directly.

In this case I think it's better to redefine eg. 
`VisitIfStmt()`/`TraverseIfStmt()`to manually traverse the condition variable 
in a custom manner, and then suppress the automatic traversal (or just traverse 
the initializer). That's clearly O(1) and doesn't rely on any unreliable 
technology.

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


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

2024-02-29 Thread Artem Dergachev via cfe-commits


@@ -70,15 +71,27 @@ bool isSingleton(const FunctionDecl *F);
 class TrivialFunctionAnalysis {
 public:
   /// \returns true if \p D is a "trivial" function.
-  bool isTrivial(const Decl *D) const { return isTrivialImpl(D, TheCache); }
+  bool isTrivial(const Decl *D) const {
+return isTrivialImpl(D, TheFunctionCache, TheStatementCache);
+  }
+
+  bool isTrivial(const Stmt *S) const {
+return isTrivialImpl(S, TheFunctionCache, TheStatementCache);
+  }
 
 private:
   friend class TrivialFunctionAnalysisVisitor;
 
-  using CacheTy = llvm::DenseMap;
-  mutable CacheTy TheCache{};
+  using FunctionCacheTy = llvm::DenseMap;
+  mutable FunctionCacheTy TheFunctionCache{};
+
+  using StatementCacheTy = llvm::DenseMap;
+  mutable StatementCacheTy TheStatementCache{};

haoNoQ wrote:

You can probably just combine the two maps into one by using 
`llvm::PointerUnion` as key type. (Or just `const 
void *` if you're feeling lazy. It's not like we'll ever convert it back.)

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


[clang] [llvm] [Hexagon] Add Loop Alignment pass. (PR #83379)

2024-02-29 Thread Sumanth Gundapaneni via cfe-commits

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


[clang] ca9d2e9 - [Hexagon] Add Loop Alignment pass. (#83379)

2024-02-29 Thread via cfe-commits

Author: Sumanth Gundapaneni
Date: 2024-02-29T16:57:33-06:00
New Revision: ca9d2e923b28adec9ae1754f0bb61b2e8ada025e

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

LOG: [Hexagon] Add Loop Alignment pass. (#83379)

Inspect a basic block and if its single basic block loop with a small
number of instructions, set the Loop Alignment to 32 bytes. This will
avoid the cache line break in the first packet of loop which will cause
a stall per each execution of loop.

Added: 
llvm/lib/Target/Hexagon/HexagonLoopAlign.cpp
llvm/test/CodeGen/Hexagon/loop-balign.ll
llvm/test/CodeGen/Hexagon/loop_align_count.ll
llvm/test/CodeGen/Hexagon/loop_align_count.mir
llvm/test/CodeGen/Hexagon/v6-haar-balign32.ll

Modified: 
clang/test/CodeGen/builtins-hexagon.c
llvm/lib/Target/Hexagon/CMakeLists.txt
llvm/lib/Target/Hexagon/HexagonTargetMachine.cpp
llvm/lib/Target/Hexagon/HexagonTargetMachine.h

Removed: 




diff  --git a/clang/test/CodeGen/builtins-hexagon.c 
b/clang/test/CodeGen/builtins-hexagon.c
index 9a1b733da5cdb8..52073f27ae70f5 100644
--- a/clang/test/CodeGen/builtins-hexagon.c
+++ b/clang/test/CodeGen/builtins-hexagon.c
@@ -1,5 +1,5 @@
 // REQUIRES: hexagon-registered-target
-// RUN: %clang_cc1 -triple hexagon-unknown-elf -target-cpu hexagonv65 
-target-feature +hvxv65 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple hexagon-unknown-elf -target-cpu hexagonv65 
-target-feature +hvxv65 -target-feature +hvx-length128b -emit-llvm %s -o - | 
FileCheck %s
 
 void test() {
   int v64 __attribute__((__vector_size__(64)));

diff  --git a/llvm/lib/Target/Hexagon/CMakeLists.txt 
b/llvm/lib/Target/Hexagon/CMakeLists.txt
index a22a5c11e6ab3a..cdc062eee72b1e 100644
--- a/llvm/lib/Target/Hexagon/CMakeLists.txt
+++ b/llvm/lib/Target/Hexagon/CMakeLists.txt
@@ -43,6 +43,7 @@ add_llvm_target(HexagonCodeGen
   HexagonISelDAGToDAGHVX.cpp
   HexagonISelLowering.cpp
   HexagonISelLoweringHVX.cpp
+  HexagonLoopAlign.cpp
   HexagonLoopIdiomRecognition.cpp
   HexagonMachineFunctionInfo.cpp
   HexagonMachineScheduler.cpp

diff  --git a/llvm/lib/Target/Hexagon/HexagonLoopAlign.cpp 
b/llvm/lib/Target/Hexagon/HexagonLoopAlign.cpp
new file mode 100644
index 00..c79b528ff2f3f9
--- /dev/null
+++ b/llvm/lib/Target/Hexagon/HexagonLoopAlign.cpp
@@ -0,0 +1,216 @@
+//===- HexagonLoopAlign.cpp - Generate loop alignment directives  
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+// Inspect a basic block and if its single basic block loop with a small
+// number of instructions, set the prefLoopAlignment to 32 bytes (5).
+//===--===//
+
+#define DEBUG_TYPE "hexagon-loop-align"
+
+#include "HexagonTargetMachine.h"
+#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
+#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
+#include "llvm/CodeGen/SchedulerRegistry.h"
+#include "llvm/Support/Debug.h"
+
+using namespace llvm;
+
+static cl::opt
+DisableLoopAlign("disable-hexagon-loop-align", cl::Hidden,
+ cl::desc("Disable Hexagon loop alignment pass"));
+
+static cl::opt HVXLoopAlignLimitUB(
+"hexagon-hvx-loop-align-limit-ub", cl::Hidden, cl::init(16),
+cl::desc("Set hexagon hvx loop upper bound align limit"));
+
+static cl::opt TinyLoopAlignLimitUB(
+"hexagon-tiny-loop-align-limit-ub", cl::Hidden, cl::init(16),
+cl::desc("Set hexagon tiny-core loop upper bound align limit"));
+
+static cl::opt
+LoopAlignLimitUB("hexagon-loop-align-limit-ub", cl::Hidden, cl::init(8),
+ cl::desc("Set hexagon loop upper bound align limit"));
+
+static cl::opt
+LoopAlignLimitLB("hexagon-loop-align-limit-lb", cl::Hidden, cl::init(4),
+ cl::desc("Set hexagon loop lower bound align limit"));
+
+static cl::opt
+LoopBndlAlignLimit("hexagon-loop-bundle-align-limit", cl::Hidden,
+   cl::init(4),
+   cl::desc("Set hexagon loop align bundle limit"));
+
+static cl::opt TinyLoopBndlAlignLimit(
+"hexagon-tiny-loop-bundle-align-limit", cl::Hidden, cl::init(8),
+cl::desc("Set hexagon tiny-core loop align bundle limit"));
+
+static cl::opt
+LoopEdgeThreshold("hexagon-loop-edge-threshold", cl::Hidden, 
cl::init(7500),
+  cl::desc("Set hexagon loop align edge theshold"));
+
+namespace llvm {
+FunctionPass *createHexagonLoopAlign();
+void initializeHexagonLoopAlignPass(PassRegistry &);
+} // namespace llvm
+
+namespace {
+
+class Hexagon

[clang] [clang] Implement __builtin_{clzg,ctzg} (PR #83431)

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


@@ -3157,7 +3177,15 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 if (Result->getType() != ResultType)

efriedma-quic wrote:

Not sure if the way this is handling isCLZForZeroUndef() is what you want?

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


[clang] [clang] Implement __builtin_{clzg,ctzg} (PR #83431)

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


@@ -2212,6 +2212,54 @@ static bool SemaBuiltinPopcountg(Sema &S, CallExpr 
*TheCall) {
   return false;
 }
 
+/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which 
is
+/// an unsigned integer, and an optional second argument, which is promoted to
+/// an 'int'.
+static bool SemaBuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
+  if (checkArgCountRange(S, TheCall, 1, 2))
+return true;
+
+  ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
+  if (Arg0Res.isInvalid())
+return true;
+
+  Expr *Arg0 = Arg0Res.get();
+  TheCall->setArg(0, Arg0);
+
+  QualType Arg0Ty = Arg0->getType();
+
+  if (!Arg0Ty->isUnsignedIntegerType()) {
+S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
+<< 1 << /*unsigned integer ty*/ 7 << Arg0Ty;
+return true;
+  }
+
+  if (TheCall->getNumArgs() > 1) {
+ExprResult Arg1Res = S.DefaultLvalueConversion(TheCall->getArg(1));
+if (Arg1Res.isInvalid())
+  return true;
+
+Expr *Arg1 = Arg1Res.get();
+TheCall->setArg(1, Arg1);
+
+QualType Arg1Ty = Arg1->getType();
+
+if (S.Context.isPromotableIntegerType(Arg1Ty)) {

efriedma-quic wrote:

This isn't quite the same as the way promotion normally works for arguments; it 
forbids some conversions we would normally do.  Maybe that's fine?  Maybe worth 
stating a bit more explicitly in the documentation.

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


[clang] [clang] Implement __builtin_{clzg,ctzg} (PR #83431)

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


@@ -662,6 +662,12 @@ def Clz : Builtin, BitShort_Int_Long_LongLongTemplate {
 
 // FIXME: Add int clzimax(uintmax_t)

efriedma-quic wrote:

Probably; it's unlikely we're going to add them at this point.

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


[clang] [Sema] -Wpointer-bool-conversion: suppress lambda function pointer conversion diagnostic during instantiation (PR #83497)

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

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


[clang] [Sema] -Wpointer-bool-conversion: suppress lambda function pointer conversion diagnostic during instantiation (PR #83497)

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

MaskRay wrote:

@vinayakdsci 

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


[clang] [Sema] -Wpointer-bool-conversion: suppress lambda function pointer conversion diagnostic during instantiation (PR #83497)

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

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


[clang] [Sema] -Wpointer-bool-conversion: suppress lambda function pointer conversion diagnostic during instantiation (PR #83497)

2024-02-29 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Fangrui Song (MaskRay)


Changes

I have seen internal pieces of code that uses a template type parameter
to accept std::function, a closure type, or any callable type. The
diagnostic added in #83152 would require adaptation to the template,
which is difficult and also seems unnecessary.

```cpp
template 
static bool IsFalse(const Ts&...) { return false; }

template ::value>::type>
static bool IsFalse(const Partial&, const T& p, const Ts&...) {
  return p ? false : true;
}

template 
void Init(Args&&... args) {
  if (IsFalse(absl::implicit_cast::type&>(
  args)...)) {
// A callable object convertible to false is either a null pointer or a
// null functor (e.g., a default-constructed std::function).
empty_ = true;
  } else {
empty_ = false;
new (&factory_) Factory(std::forward(args)...);
  }
}
```


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


2 Files Affected:

- (modified) clang/lib/Sema/SemaChecking.cpp (+10-7) 
- (modified) clang/test/SemaCXX/warn-bool-conversion.cpp (+13) 


``diff
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 690bdaa63d058b..3533b5c8e0d235 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -16586,13 +16586,16 @@ void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
   }
 
   // Complain if we are converting a lambda expression to a boolean value
-  if (const auto *MCallExpr = dyn_cast(E)) {
-if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
-MRecordDecl && MRecordDecl->isLambda()) {
-  Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
-  << /*LambdaPointerConversionOperatorType=*/3
-  << MRecordDecl->getSourceRange() << Range << IsEqual;
-  return;
+  // outside of instantiation.
+  if (!inTemplateInstantiation()) {
+if (const auto *MCallExpr = dyn_cast(E)) {
+  if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
+  MRecordDecl && MRecordDecl->isLambda()) {
+Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
+<< /*LambdaPointerConversionOperatorType=*/3
+<< MRecordDecl->getSourceRange() << Range << IsEqual;
+return;
+  }
 }
   }
 
diff --git a/clang/test/SemaCXX/warn-bool-conversion.cpp 
b/clang/test/SemaCXX/warn-bool-conversion.cpp
index 9e8cf0e4f8944a..8b1bf80af79d26 100644
--- a/clang/test/SemaCXX/warn-bool-conversion.cpp
+++ b/clang/test/SemaCXX/warn-bool-conversion.cpp
@@ -92,6 +92,19 @@ void foo() {
   bool is_true = [](){ return true; };
   // expected-warning@-1{{address of lambda function pointer conversion 
operator will always evaluate to 'true'}}
 }
+
+template 
+static bool IsFalse(const Ts&...) { return false; }
+template 
+static bool IsFalse(const T& p) {
+  bool b;
+  b = f7; // expected-warning {{address of lambda function pointer conversion 
operator will always evaluate to 'true'}}
+  return p ? false : true;
+}
+
+bool use_instantiation() {
+  return IsFalse([]() { return 0; });
+}
 #endif
 
 void bar() {

``




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


[clang] [Sema] -Wpointer-bool-conversion: suppress lambda function pointer conversion diagnostic during instantiation (PR #83497)

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

https://github.com/MaskRay created 
https://github.com/llvm/llvm-project/pull/83497

I have seen internal pieces of code that uses a template type parameter
to accept std::function, a closure type, or any callable type. The
diagnostic added in #83152 would require adaptation to the template,
which is difficult and also seems unnecessary.

```cpp
template 
static bool IsFalse(const Ts&...) { return false; }

template ::value>::type>
static bool IsFalse(const Partial&, const T& p, const Ts&...) {
  return p ? false : true;
}

template 
void Init(Args&&... args) {
  if (IsFalse(absl::implicit_cast::type&>(
  args)...)) {
// A callable object convertible to false is either a null pointer or a
// null functor (e.g., a default-constructed std::function).
empty_ = true;
  } else {
empty_ = false;
new (&factory_) Factory(std::forward(args)...);
  }
}
```


>From d7a168190f2fdf3b4f8ec1457400ad8e03bc3f3a Mon Sep 17 00:00:00 2001
From: Fangrui Song 
Date: Thu, 29 Feb 2024 14:40:00 -0800
Subject: [PATCH] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20initia?=
 =?UTF-8?q?l=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.4
---
 clang/lib/Sema/SemaChecking.cpp | 17 ++---
 clang/test/SemaCXX/warn-bool-conversion.cpp | 13 +
 2 files changed, 23 insertions(+), 7 deletions(-)

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 690bdaa63d058b..3533b5c8e0d235 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -16586,13 +16586,16 @@ void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
   }
 
   // Complain if we are converting a lambda expression to a boolean value
-  if (const auto *MCallExpr = dyn_cast(E)) {
-if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
-MRecordDecl && MRecordDecl->isLambda()) {
-  Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
-  << /*LambdaPointerConversionOperatorType=*/3
-  << MRecordDecl->getSourceRange() << Range << IsEqual;
-  return;
+  // outside of instantiation.
+  if (!inTemplateInstantiation()) {
+if (const auto *MCallExpr = dyn_cast(E)) {
+  if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
+  MRecordDecl && MRecordDecl->isLambda()) {
+Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
+<< /*LambdaPointerConversionOperatorType=*/3
+<< MRecordDecl->getSourceRange() << Range << IsEqual;
+return;
+  }
 }
   }
 
diff --git a/clang/test/SemaCXX/warn-bool-conversion.cpp 
b/clang/test/SemaCXX/warn-bool-conversion.cpp
index 9e8cf0e4f8944a..8b1bf80af79d26 100644
--- a/clang/test/SemaCXX/warn-bool-conversion.cpp
+++ b/clang/test/SemaCXX/warn-bool-conversion.cpp
@@ -92,6 +92,19 @@ void foo() {
   bool is_true = [](){ return true; };
   // expected-warning@-1{{address of lambda function pointer conversion 
operator will always evaluate to 'true'}}
 }
+
+template 
+static bool IsFalse(const Ts&...) { return false; }
+template 
+static bool IsFalse(const T& p) {
+  bool b;
+  b = f7; // expected-warning {{address of lambda function pointer conversion 
operator will always evaluate to 'true'}}
+  return p ? false : true;
+}
+
+bool use_instantiation() {
+  return IsFalse([]() { return 0; });
+}
 #endif
 
 void bar() {

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


[clang] [InstallAPI] Collect frontend attributes & ObjCInterface decls (PR #83378)

2024-02-29 Thread Cyndy Ishida via cfe-commits

https://github.com/cyndyishida updated 
https://github.com/llvm/llvm-project/pull/83378

>From 908e41485a148539b3d0699c55291f4f4e819858 Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Wed, 28 Feb 2024 14:15:48 -0800
Subject: [PATCH 1/2] [InstallAPI] Collect frontend attributes during &
 ObjCInterface Records.

* This patch introduces a inherited container class for holding
  records and attributes only collectable from the clang frontend.
* This also prunes out collecting declarations from headers that aren't
  considered input to installapi.
* Use these constructs for collecting global objective-c interfaces.
---
 clang/include/clang/InstallAPI/Context.h  | 27 +-
 clang/include/clang/InstallAPI/Frontend.h | 68 +--
 clang/include/clang/InstallAPI/Visitor.h  | 17 +++-
 clang/lib/InstallAPI/Frontend.cpp | 72 +++-
 clang/lib/InstallAPI/Visitor.cpp  | 74 ++--
 clang/test/InstallAPI/objcclasses.test| 86 +++
 .../clang-installapi/ClangInstallAPI.cpp  |  8 +-
 7 files changed, 330 insertions(+), 22 deletions(-)
 create mode 100644 clang/test/InstallAPI/objcclasses.test

diff --git a/clang/include/clang/InstallAPI/Context.h 
b/clang/include/clang/InstallAPI/Context.h
index 3e2046642c7fe8..3f8167b12dcd23 100644
--- a/clang/include/clang/InstallAPI/Context.h
+++ b/clang/include/clang/InstallAPI/Context.h
@@ -12,12 +12,12 @@
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/InstallAPI/HeaderFile.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/TextAPI/InterfaceFile.h"
-#include "llvm/TextAPI/RecordVisitor.h"
-#include "llvm/TextAPI/RecordsSlice.h"
 
 namespace clang {
 namespace installapi {
+class FrontendRecordsSlice;
 
 /// Struct used for generating validating InstallAPI.
 /// The attributes captured represent all necessary information
@@ -37,7 +37,7 @@ struct InstallAPIContext {
   HeaderType Type = HeaderType::Unknown;
 
   /// Active TargetSlice for symbol record collection.
-  std::shared_ptr Slice;
+  std::shared_ptr Slice;
 
   /// FileManager for all I/O operations.
   FileManager *FM = nullptr;
@@ -50,6 +50,27 @@ struct InstallAPIContext {
 
   /// What encoding to write output as.
   llvm::MachO::FileType FT = llvm::MachO::FileType::TBD_V5;
+
+  /// Populate entries of headers that should be included for TextAPI
+  /// generation.
+  void addKnownHeader(const HeaderFile &H);
+
+  /// Record visited files during frontend actions to determine whether to
+  /// include their declarations for TextAPI generation.
+  ///
+  /// \param FE Header that is being parsed.
+  /// \param PP Preprocesser used for querying how header was imported.
+  /// \return Access level of header if it should be included for TextAPI
+  /// generation.
+  std::optional findAndRecordFile(const FileEntry *FE,
+  const Preprocessor &PP);
+
+private:
+  using HeaderMap = llvm::DenseMap;
+
+  HeaderMap KnownFiles;
+  llvm::DenseMap KnownIncludes;
+  std::set UnusedFiles;
 };
 
 } // namespace installapi
diff --git a/clang/include/clang/InstallAPI/Frontend.h 
b/clang/include/clang/InstallAPI/Frontend.h
index 7ee87ae028d079..d72b4680fde400 100644
--- a/clang/include/clang/InstallAPI/Frontend.h
+++ b/clang/include/clang/InstallAPI/Frontend.h
@@ -14,6 +14,7 @@
 #define LLVM_CLANG_INSTALLAPI_FRONTEND_H
 
 #include "clang/AST/ASTConsumer.h"
+#include "clang/AST/Availability.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/InstallAPI/Context.h"
@@ -24,23 +25,78 @@
 namespace clang {
 namespace installapi {
 
+using SymbolFlags = llvm::MachO::SymbolFlags;
+using RecordLinkage = llvm::MachO::RecordLinkage;
+using GlobalRecord = llvm::MachO::GlobalRecord;
+using ObjCInterfaceRecord = llvm::MachO::ObjCInterfaceRecord;
+
+// Represents a collection of frontend records for a library that are tied to a
+// darwin target triple.
+class FrontendRecordsSlice : public llvm::MachO::RecordsSlice {
+public:
+  FrontendRecordsSlice(const llvm::Triple &T)
+  : llvm::MachO::RecordsSlice({T}) {}
+
+  /// Add non-ObjC global record with attributes from AST.
+  ///
+  /// \param Name The name of symbol.
+  /// \param Linkage The linkage of symbol.
+  /// \param GV The kind of global.
+  /// \param Avail The availability information tied to the active target
+  /// triple.
+  /// \param D The pointer to the declaration from traversing AST.
+  /// \param Access The intended access level of symbol.
+  /// \param Flags The flags that describe attributes of the symbol.
+  /// \return The non-owning pointer to added record in slice.
+  GlobalRecord *addGlobal(StringRef Name, RecordLinkage Linkage,
+  GlobalRecord::Kind GV,
+  const clang::AvailabilityInfo Avail, const Decl *D,
+  const HeaderType Access,
+  SymbolFlags

[clang] [clang] Sequence C++20 Parenthesized List Init (PR #83476)

2024-02-29 Thread Shafik Yaghmour via cfe-commits

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


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


[clang] [clang] Sequence C++20 Parenthesized List Init (PR #83476)

2024-02-29 Thread Shafik Yaghmour via cfe-commits


@@ -17615,31 +17615,28 @@ class SequenceChecker : public 
ConstEvaluatedExprVisitor {
   return VisitExpr(CCE);
 
 // In C++11, list initializations are sequenced.
-SmallVector Elts;
-SequenceTree::Seq Parent = Region;
-for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
-  E = CCE->arg_end();
- I != E; ++I) {
-  Region = Tree.allocate(Parent);
-  Elts.push_back(Region);
-  Visit(*I);
-}
-
-// Forget that the initializers are sequenced.
-Region = Parent;
-for (unsigned I = 0; I < Elts.size(); ++I)
-  Tree.merge(Elts[I]);
+SequenceExpressionsInOrder({CCE->getArgs(), CCE->getNumArgs()});

shafik wrote:

I took me a bit of checking to convince myself this was doing the right thing. 
It might be nice to refactor `CXXConstructExpr` to have an a member that does 
the same as `ILE->inits()` and returns an `ArrayRef`. It looks like do similar 
things to create an `ArrayRef` in other places as well but probably should be a 
second PR.

Maybe change this to `llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs())` to 
make it more explicit for now.

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


[clang] [clang] Sequence C++20 Parenthesized List Init (PR #83476)

2024-02-29 Thread Shafik Yaghmour via cfe-commits

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


[clang] [clang] Sequence C++20 Parenthesized List Init (PR #83476)

2024-02-29 Thread Shafik Yaghmour via cfe-commits

https://github.com/shafik commented:

LGTM after addressing comment.

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


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

2024-02-29 Thread via cfe-commits

AtariDreams wrote:

@rjmccall I do not have merge permissions or whatever it is called.

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


[clang] [clang] Sequence C++20 Parenthesized List Init (PR #83476)

2024-02-29 Thread Douglas Deslauriers via cfe-commits

https://github.com/vapdrs updated 
https://github.com/llvm/llvm-project/pull/83476

>From cc14e7a3320c36295514b75108e4da481d2f6b99 Mon Sep 17 00:00:00 2001
From: Douglas Deslauriers 
Date: Thu, 29 Feb 2024 20:18:34 +
Subject: [PATCH] [clang] Sequence C++20 Parenthesized List Init

Parenthesized list intializers are sequenced operations, see C++20
[decl.init]p16.5 and [decl.init]p16.6.2.2 for more details.

Fixes #83474
---
 clang/lib/Sema/SemaChecking.cpp   | 29 +--
 .../warn-unsequenced-paren-list-init.cpp  | 15 ++
 2 files changed, 28 insertions(+), 16 deletions(-)
 create mode 100644 clang/test/SemaCXX/warn-unsequenced-paren-list-init.cpp

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 690bdaa63d058b..de9569c799b121 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -17615,20 +17615,7 @@ class SequenceChecker : public 
ConstEvaluatedExprVisitor {
   return VisitExpr(CCE);
 
 // In C++11, list initializations are sequenced.
-SmallVector Elts;
-SequenceTree::Seq Parent = Region;
-for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
-  E = CCE->arg_end();
- I != E; ++I) {
-  Region = Tree.allocate(Parent);
-  Elts.push_back(Region);
-  Visit(*I);
-}
-
-// Forget that the initializers are sequenced.
-Region = Parent;
-for (unsigned I = 0; I < Elts.size(); ++I)
-  Tree.merge(Elts[I]);
+SequenceExpressionsInOrder({CCE->getArgs(), CCE->getNumArgs()});
   }
 
   void VisitInitListExpr(const InitListExpr *ILE) {
@@ -17636,10 +17623,20 @@ class SequenceChecker : public 
ConstEvaluatedExprVisitor {
   return VisitExpr(ILE);
 
 // In C++11, list initializations are sequenced.
+SequenceExpressionsInOrder(ILE->inits());
+  }
+
+  void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
+// C++20 parenthesized list initializations are sequenced. See C++20
+// [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
+SequenceExpressionsInOrder(PLIE->getInitExprs());
+  }
+
+private:
+  void SequenceExpressionsInOrder(ArrayRef ExpressionList) {
 SmallVector Elts;
 SequenceTree::Seq Parent = Region;
-for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
-  const Expr *E = ILE->getInit(I);
+for (const Expr *E : ExpressionList) {
   if (!E)
 continue;
   Region = Tree.allocate(Parent);
diff --git a/clang/test/SemaCXX/warn-unsequenced-paren-list-init.cpp 
b/clang/test/SemaCXX/warn-unsequenced-paren-list-init.cpp
new file mode 100644
index 00..5aeeb45f81e226
--- /dev/null
+++ b/clang/test/SemaCXX/warn-unsequenced-paren-list-init.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -Wno-unused -Wunsequenced -verify 
%s
+
+struct A {
+  int x, y;
+};
+
+void test() {
+  int a = 0;
+
+  A agg1( a++, a++ ); // no warning
+  A agg2( a++ + a, a++ ); // expected-warning {{unsequenced modification and 
access to 'a'}}
+
+  int arr1[]( a++, a++ ); // no warning
+  int arr2[]( a++ + a, a++ ); // expected-warning {{unsequenced modification 
and access to 'a'}}
+}

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


[clang] Fix implementation of [temp.param]p14's first sentence. (PR #83487)

2024-02-29 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Erich Keane (erichkeane)


Changes

The first sentence says:

If a template-parameter of a class template, variable template, or alias 
template has a default template-argument, each subsequent template-parameter 
shall either have a default template-argument supplied or be a template 
parameter pack.

However, we were only testing for "not a function function template", and 
referring to an older version of the standard.  As far as I can tell, CWG2032 
added the variable-template, and the alias-template pre-dates the standard on 
github.

This patch started as a bug fix for #83461 , but ended up fixing a 
number of similar cases, so those are validated as well.

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


2 Files Affected:

- (modified) clang/lib/Sema/SemaTemplate.cpp (+8-6) 
- (added) clang/test/SemaCXX/GH83461.cpp (+60) 


``diff
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index e91033dd886891..a7910bda874c8d 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -3141,12 +3141,14 @@ bool 
Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
diag::note_template_param_prev_default_arg_in_other_module)
   << PrevModuleName;
   Invalid = true;
-} else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
-  // C++ [temp.param]p11:
-  //   If a template-parameter of a class template has a default
-  //   template-argument, each subsequent template-parameter shall either
-  //   have a default template-argument supplied or be a template parameter
-  //   pack.
+} else if (MissingDefaultArg &&
+   (TPC == TPC_ClassTemplate || TPC == TPC_FriendClassTemplate ||
+TPC == TPC_VarTemplate || TPC == TPC_TypeAliasTemplate)) {
+  // C++ 23[temp.param]p14:
+  // If a template-parameter of a class template, variable template, or
+  // alias template has a default template argument, each subsequent
+  // template-parameter shall either have a default template argument
+  // supplied or be a template parameter pack.
   Diag((*NewParam)->getLocation(),
diag::err_template_param_default_arg_missing);
   Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
diff --git a/clang/test/SemaCXX/GH83461.cpp b/clang/test/SemaCXX/GH83461.cpp
new file mode 100644
index 00..509535e883e6d9
--- /dev/null
+++ b/clang/test/SemaCXX/GH83461.cpp
@@ -0,0 +1,60 @@
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %s
+
+struct S {
+  template
+  friend void foo(auto){}
+
+  template
+  friend void foo2(){}
+};
+
+template
+struct TemplS {
+  template
+  friend void foo3(auto){}
+
+  template
+  friend void foo4(){}
+};
+
+void Inst() {
+  TemplS();
+}
+// expected-error@+2{{template parameter missing a default argument}}
+// expected-note@+1{{previous default template argument defined here}}
+template
+struct ClassTempl{};
+
+struct HasFriendClassTempl {
+  // expected-error@+1{{default template argument not permitted on a friend 
template}}
+  template
+  friend struct Friend;
+
+  // expected-error@+3{{cannot define a type in a friend declaration}}
+  // expected-error@+1{{default template argument not permitted on a friend 
template}}
+  template
+  friend struct Friend2{};
+};
+
+template
+struct HasFriendClassTempl2 {
+  // expected-error@+3{{template parameter missing a default argument}}
+  // expected-note@+2{{previous default template argument defined here}}
+  // expected-note@#INST2{{in instantiation of template class}}
+  template
+  friend struct Friend;
+};
+
+void Inst2() {
+  HasFriendClassTempl2(); // #INST2
+}
+
+// expected-error@+2{{template parameter missing a default argument}}
+// expected-note@+1{{previous default template argument defined here}}
+template
+static constexpr U VarTempl;
+
+// expected-error@+2{{template parameter missing a default argument}}
+// expected-note@+1{{previous default template argument defined here}}
+template
+using TypeAlias = U;

``




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


[clang] Fix implementation of [temp.param]p14's first sentence. (PR #83487)

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

https://github.com/erichkeane created 
https://github.com/llvm/llvm-project/pull/83487

The first sentence says:

If a template-parameter of a class template, variable template, or alias 
template has a default template-argument, each subsequent template-parameter 
shall either have a default template-argument supplied or be a template 
parameter pack.

However, we were only testing for "not a function function template", and 
referring to an older version of the standard.  As far as I can tell, CWG2032 
added the variable-template, and the alias-template pre-dates the standard on 
github.

This patch started as a bug fix for #83461 , but ended up fixing a number of 
similar cases, so those are validated as well.

>From 1c443bec9f11c14f8971d5dcb03d12e50c080afc Mon Sep 17 00:00:00 2001
From: erichkeane 
Date: Thu, 29 Feb 2024 13:29:02 -0800
Subject: [PATCH] Fix implementation of [temp.param]p14's first sentence.

The first sentence says:

If a template-parameter of a class template, variable template, or alias
template has a default template-argument, each subsequent
template-parameter shall either have a default template-argument
supplied or be a template parameter pack.

However, we were only testing for "not a function function template",
and referring to an older version of the standard.  As far as I can
tell, CWG2032 added the variable-template, and the alias-template
pre-dates the standard on github.

This patch started as a bug fix for #83461 , but ended up fixing a
number of similar cases, so those are validated as well.
---
 clang/lib/Sema/SemaTemplate.cpp | 14 
 clang/test/SemaCXX/GH83461.cpp  | 60 +
 2 files changed, 68 insertions(+), 6 deletions(-)
 create mode 100644 clang/test/SemaCXX/GH83461.cpp

diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index e91033dd886891..a7910bda874c8d 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -3141,12 +3141,14 @@ bool 
Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
diag::note_template_param_prev_default_arg_in_other_module)
   << PrevModuleName;
   Invalid = true;
-} else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
-  // C++ [temp.param]p11:
-  //   If a template-parameter of a class template has a default
-  //   template-argument, each subsequent template-parameter shall either
-  //   have a default template-argument supplied or be a template parameter
-  //   pack.
+} else if (MissingDefaultArg &&
+   (TPC == TPC_ClassTemplate || TPC == TPC_FriendClassTemplate ||
+TPC == TPC_VarTemplate || TPC == TPC_TypeAliasTemplate)) {
+  // C++ 23[temp.param]p14:
+  // If a template-parameter of a class template, variable template, or
+  // alias template has a default template argument, each subsequent
+  // template-parameter shall either have a default template argument
+  // supplied or be a template parameter pack.
   Diag((*NewParam)->getLocation(),
diag::err_template_param_default_arg_missing);
   Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
diff --git a/clang/test/SemaCXX/GH83461.cpp b/clang/test/SemaCXX/GH83461.cpp
new file mode 100644
index 00..509535e883e6d9
--- /dev/null
+++ b/clang/test/SemaCXX/GH83461.cpp
@@ -0,0 +1,60 @@
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %s
+
+struct S {
+  template
+  friend void foo(auto){}
+
+  template
+  friend void foo2(){}
+};
+
+template
+struct TemplS {
+  template
+  friend void foo3(auto){}
+
+  template
+  friend void foo4(){}
+};
+
+void Inst() {
+  TemplS();
+}
+// expected-error@+2{{template parameter missing a default argument}}
+// expected-note@+1{{previous default template argument defined here}}
+template
+struct ClassTempl{};
+
+struct HasFriendClassTempl {
+  // expected-error@+1{{default template argument not permitted on a friend 
template}}
+  template
+  friend struct Friend;
+
+  // expected-error@+3{{cannot define a type in a friend declaration}}
+  // expected-error@+1{{default template argument not permitted on a friend 
template}}
+  template
+  friend struct Friend2{};
+};
+
+template
+struct HasFriendClassTempl2 {
+  // expected-error@+3{{template parameter missing a default argument}}
+  // expected-note@+2{{previous default template argument defined here}}
+  // expected-note@#INST2{{in instantiation of template class}}
+  template
+  friend struct Friend;
+};
+
+void Inst2() {
+  HasFriendClassTempl2(); // #INST2
+}
+
+// expected-error@+2{{template parameter missing a default argument}}
+// expected-note@+1{{previous default template argument defined here}}
+template
+static constexpr U VarTempl;
+
+// expected-error@+2{{template parameter missing a default argument}}
+// expected-note@+1{{previous default template argument defined here}}
+template
+using TypeAlias = U;

_

[clang] [llvm] [Hexagon] Add Loop Alignment pass. (PR #83379)

2024-02-29 Thread Ikhlas Ajbar via cfe-commits

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


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


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

2024-02-29 Thread Joshua Cranmer via cfe-commits


@@ -1847,19 +1847,33 @@ floating point semantic models: precise (the default), 
strict, and fast.
* ``16`` - Forces ``_Float16`` operations to be emitted without using excess
  precision arithmetic.
 
-.. option:: -fcx-limited-range:
-
-   This option enables the naive mathematical formulas for complex division and
-   multiplication with no NaN checking of results. The default is
-   ``-fno-cx-limited-range``, but this option is enabled by the ``-ffast-math``
-   option.
-
-.. option:: -fcx-fortran-rules:
-
-   This option enables the naive mathematical formulas for complex
-   multiplication and enables application of Smith's algorithm for complex
-   division. See SMITH, R. L. Algorithm 116: Complex division. Commun.
-   ACM 5, 8 (1962). The default is ``-fno-cx-fortran-rules``.
+.. option:: -fcomplex-arithmetic=:
+
+   This option specifies the implementation for complex multiplication and 
division.
+
+   Valid values are: ``basic``, ``improved``, ``full`` and ``promoted``.
+
+   * ``basic`` Implementation of complex division and multiplication using
+ algebraic formulas at source precision. No special handling to avoid
+ overflow. NaN and infinite and  values are not handled.
+   * ``improved`` Implementation of complex division using the Smith algorithm 
at
+ source precision. Smith's algorithm for complex division.
+ See SMITH, R. L. Algorithm 116: Complex division. Commun. ACM 5, 8 (1962).
+ This value offers improved handling for overflow in intermediate 
calculations,
+ but overflow may occur. NaN and infinite and  values are not handled in 
some
+ cases.
+   * ``full``  Implementation of complex division and multiplication using a
+ call to runtime library functions (generally the case, but the BE might
+ sometimes replace the library call if it knows enough about the potential
+ range of the inputs). Overflow and non-finite values are handled by the
+ library implementation.
+   * ``promoted`` Implementation of complex division using algebraic formulas 
at
+ higher precision. Overflow is handled. Non-finite values are handled in 
some
+ cases. If the target hardware does not have native support for a higher 
precision
+ data type, an implementation for the complex operation will be used to 
provide
+ improved guards against intermediate overflow, but overflow and underflow 
may
+ still occur in some cases. NaN and infinite and  values are not handled.
+ This is the default value.

jcranmer-intel wrote:

C89 doesn't have complex types, do we even support `_Complex` in -std=gnu89 
mode?

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


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

2024-02-29 Thread Joshua Cranmer via cfe-commits


@@ -982,13 +1022,18 @@ ComplexPairTy ComplexExprEmitter::EmitBinDiv(const 
BinOpInfo &Op) {
 llvm::Value *OrigLHSi = LHSi;
 if (!LHSi)
   LHSi = llvm::Constant::getNullValue(RHSi->getType());
-if (Op.FPFeatures.getComplexRange() == LangOptions::CX_Fortran)
+QualType ComplexElementTy = Op.Ty->castAs()->getElementType();
+const BuiltinType *BT = ComplexElementTy->getAs();
+if (Op.FPFeatures.getComplexRange() == LangOptions::CX_Improved ||
+(Op.FPFeatures.getComplexRange() == LangOptions::CX_Promoted &&
+ BT->getKind() == BuiltinType::Kind::LongDouble))

jcranmer-intel wrote:

This isn't going to do the right thing for `_Complex __float128` I believe. Or 
`_Complex double` in the case where `long double` is binary64, I'm pretty sure, 
since that would promote it to itself and then do basic.

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


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

2024-02-29 Thread Joshua Cranmer via cfe-commits


@@ -283,9 +283,46 @@ class ComplexExprEmitter
   ComplexPairTy EmitComplexBinOpLibCall(StringRef LibCallName,
 const BinOpInfo &Op);
 
-  QualType getPromotionType(QualType Ty) {
+  QualType HigherPrecisionTypeForComplexArithmetic(QualType ElementType,
+   bool IsDivOpCode) {
+const TargetInfo &TI = CGF.getContext().getTargetInfo();
+const LangOptions Opts = CGF.getLangOpts();
+if (const auto *BT = dyn_cast(ElementType)) {
+  switch (BT->getKind()) {
+  case BuiltinType::Kind::Float16: {
+if (TI.hasFloat16Type() && !TI.hasLegalHalfType())
+  return CGF.getContext().getComplexType(CGF.getContext().FloatTy);
+break;
+  }
+  case BuiltinType::Kind::BFloat16: {
+if (TI.hasBFloat16Type() && !TI.hasFullBFloat16Type())
+  return CGF.getContext().getComplexType(CGF.getContext().FloatTy);
+break;
+  }
+  case BuiltinType::Kind::Float:
+return CGF.getContext().getComplexType(CGF.getContext().DoubleTy);
+break;
+  case BuiltinType::Kind::Double: {
+if (TI.hasLongDoubleType())
+  return 
CGF.getContext().getComplexType(CGF.getContext().LongDoubleTy);
+return CGF.getContext().getComplexType(CGF.getContext().DoubleTy);

jcranmer-intel wrote:

I'm not sure it's a good idea to return a specific type here if it's not known 
to actually be higher precision? `long double` isn't guaranteed to be a 
different LLVM type from `double`...

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


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

2024-02-29 Thread Joshua Cranmer via cfe-commits


@@ -1847,19 +1847,50 @@ floating point semantic models: precise (the default), 
strict, and fast.
* ``16`` - Forces ``_Float16`` operations to be emitted without using excess
  precision arithmetic.
 
+.. option:: -fcomplex-arithmetic=:
+
+   This option specifies the implementation for complex multiplication and 
division.
+
+   Valid values are: ``basic``, ``improved``, ``full`` and ``promoted``.
+
+   * ``basic`` Implementation of complex division and multiplication using
+ algebraic formulas at source precision. No special handling to avoid
+ overflow. NaN and infinite values are not handled.
+   * ``improved`` Implementation of complex division using the Smith algorithm
+ at source precision. Smith's algorithm for complex division.
+ See SMITH, R. L. Algorithm 116: Complex division. Commun. ACM 5, 8 (1962).
+ This value offers improved handling for overflow in intermediate
+ calculations, but overflow may occur. NaN and infinite values are not
+ handled in some cases.
+   * ``full`` Implementation of complex division and multiplication using a
+ call to runtime library functions (generally the case, but the BE might
+ sometimes replace the library call if it knows enough about the potential
+ range of the inputs). Overflow and non-finite values are handled by the
+ library implementation. For the case of multiplication overflow will 
occur in
+ accordance with normal floating-point rules. This is the default value.
+   * ``promoted`` Implementation of complex division using algebraic formulas 
at
+ higher precision. Overflow is handled. Non-finite values are handled in 
some
+ cases. If the target does not have native support for a higher precision
+ data type, an implementation for the complex operation will be used to 
provide
+ improved guards against intermediate overflow, but overflow and underflow 
may
+ still occur in some cases. NaN and infinite values are not handled.

jcranmer-intel wrote:

This documentation doesn't make it clear what happens if there is no 
higher-precision datatype available and you use `promoted` format. And I'm 
somewhat uncomfortable with the idea that using `promoted` keeps you from being 
able to choose what happens in that case.

(In general, `promoted` is scary to me for anything larger than a `float` 
because `long double` is just such a cursed type and I'm not sure it's a good 
idea to convert `double` computations to `long double`).

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


[clang] [clang] Sequence C++20 Parenthesized List Init (PR #83476)

2024-02-29 Thread Douglas Deslauriers via cfe-commits


@@ -17626,6 +17626,25 @@ class SequenceChecker : public 
ConstEvaluatedExprVisitor {
 for (unsigned I = 0; I < Elts.size(); ++I)
   Tree.merge(Elts[I]);
   }
+
+  void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
+// C++20 parenthesized list initializations are sequenced. See C++20
+// [decl.init]p17.5 and [decl.init]p17.6.2.2
+SmallVector Elts;
+SequenceTree::Seq Parent = Region;
+for (const Expr *E : PLIE->getInitExprs()) {
+  if (!E)
+continue;
+  Region = Tree.allocate(Parent);
+  Elts.push_back(Region);
+  Visit(E);
+}
+
+// Forget that the initializers are sequenced.
+Region = Parent;
+for (unsigned I = 0; I < Elts.size(); ++I)
+  Tree.merge(Elts[I]);
+  }

vapdrs wrote:

I can do you one better and also factor out code in `VisitCXXConstructExpr` 
too, however that does call into question the comment `// In C++11, list 
initializations are sequenced.` in that function which seems to be copy pasted 
from `VisitInitListExpr`. So if you want me to remove that, let me know.

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


[clang] [llvm] [CMAKE] Enable FatLTO as a build option for LLVM (PR #80480)

2024-02-29 Thread Paul Kirth via cfe-commits

https://github.com/ilovepi updated 
https://github.com/llvm/llvm-project/pull/80480

>From 0c010db4bdf8808d95895db1ba4112fcb04f2d8b Mon Sep 17 00:00:00 2001
From: Paul Kirth 
Date: Tue, 22 Aug 2023 15:24:03 +
Subject: [PATCH 1/2] [CMAKE] Enable FatLTO as a build option for LLVM

---
 clang/cmake/caches/Fuchsia-stage2.cmake|  1 +
 llvm/cmake/modules/AddLLVM.cmake   | 11 +--
 llvm/cmake/modules/HandleLLVMOptions.cmake |  6 ++
 3 files changed, 16 insertions(+), 2 deletions(-)

diff --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index eee37c5e7901fa..d5a1662cbf4aa6 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -11,6 +11,7 @@ set(LLVM_ENABLE_RUNTIMES 
"compiler-rt;libcxx;libcxxabi;libunwind" CACHE STRING "
 
 set(LLVM_ENABLE_BACKTRACES OFF CACHE BOOL "")
 set(LLVM_ENABLE_DIA_SDK OFF CACHE BOOL "")
+set(LLVM_ENABLE_FATLTO ON CACHE BOOL "")
 set(LLVM_ENABLE_HTTPLIB ON CACHE BOOL "")
 set(LLVM_ENABLE_LIBCXX ON CACHE BOOL "")
 set(LLVM_ENABLE_LIBEDIT OFF CACHE BOOL "")
diff --git a/llvm/cmake/modules/AddLLVM.cmake b/llvm/cmake/modules/AddLLVM.cmake
index 0f1734a64ee6e6..21455c304381bf 100644
--- a/llvm/cmake/modules/AddLLVM.cmake
+++ b/llvm/cmake/modules/AddLLVM.cmake
@@ -1621,8 +1621,15 @@ function(add_unittest test_suite test_name)
   # The runtime benefits of LTO don't outweight the compile time costs for 
tests.
   if(LLVM_ENABLE_LTO)
 if((UNIX OR MINGW) AND LINKER_IS_LLD)
-  set_property(TARGET ${test_name} APPEND_STRING PROPERTY
-LINK_FLAGS " -Wl,--lto-O0")
+  if(LLVM_ENABLE_FATLTO)
+# When using FatLTO, just use relocatable linking.
+set_property(TARGET ${test_name} APPEND_STRING PROPERTY
+  LINK_FLAGS " -Wl,--no-fat-lto-objects")
+set_property(TARGET ${test_name} APPEND_STRING PROPERTY COMPILE_FLAGS 
" -fno-lto")
+  else()
+set_property(TARGET ${test_name} APPEND_STRING PROPERTY
+  LINK_FLAGS " -Wl,--lto-O0")
+  endif()
 elseif(LINKER_IS_LLD_LINK)
   set_property(TARGET ${test_name} APPEND_STRING PROPERTY
 LINK_FLAGS " /opt:lldlto=0")
diff --git a/llvm/cmake/modules/HandleLLVMOptions.cmake 
b/llvm/cmake/modules/HandleLLVMOptions.cmake
index 08ff49ded57a14..27b3ebf9a3466f 100644
--- a/llvm/cmake/modules/HandleLLVMOptions.cmake
+++ b/llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -32,6 +32,8 @@ endif()
 set(LLVM_ENABLE_LTO OFF CACHE STRING "Build LLVM with LTO. May be specified as 
Thin or Full to use a particular kind of LTO")
 string(TOUPPER "${LLVM_ENABLE_LTO}" uppercase_LLVM_ENABLE_LTO)
 
+option(LLVM_ENABLE_FATLTO "Build LLVM with -ffat-lto-objects." OFF)
+
 # Ninja Job Pool support
 # The following only works with the Ninja generator in CMake >= 3.0.
 set(LLVM_PARALLEL_COMPILE_JOBS "" CACHE STRING
@@ -1259,6 +1261,10 @@ elseif(LLVM_ENABLE_LTO)
   endif()
 endif()
 
+if(LLVM_ENABLE_FATLTO AND (FUCHSIA OR UNIX))
+append("-ffat-lto-objects" CMAKE_EXE_LINKER_FLAGS 
CMAKE_SHARED_LINKER_FLAGS)
+endif()
+
 # Set an AIX default for LLVM_EXPORT_SYMBOLS_FOR_PLUGINS based on whether we 
are
 # doing dynamic linking (see below).
 set(LLVM_EXPORT_SYMBOLS_FOR_PLUGINS_AIX_default OFF)

>From 9c10222866c1c1f696f6ce48732adf120d7f1f39 Mon Sep 17 00:00:00 2001
From: Paul Kirth 
Date: Fri, 2 Feb 2024 13:09:18 -0800
Subject: [PATCH 2/2] Add -ffat-lto-objects to CMAKE_C_FLAGS and
 CMAKE_CXX_FLAGS

---
 llvm/cmake/modules/HandleLLVMOptions.cmake | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/llvm/cmake/modules/HandleLLVMOptions.cmake 
b/llvm/cmake/modules/HandleLLVMOptions.cmake
index 27b3ebf9a3466f..e23d8d46272c4b 100644
--- a/llvm/cmake/modules/HandleLLVMOptions.cmake
+++ b/llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -1262,7 +1262,10 @@ elseif(LLVM_ENABLE_LTO)
 endif()
 
 if(LLVM_ENABLE_FATLTO AND (FUCHSIA OR UNIX))
+  append("-ffat-lto-objects" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
+  if(NOT LINKER_IS_LLD_LINK)
 append("-ffat-lto-objects" CMAKE_EXE_LINKER_FLAGS 
CMAKE_SHARED_LINKER_FLAGS)
+  endif()
 endif()
 
 # Set an AIX default for LLVM_EXPORT_SYMBOLS_FOR_PLUGINS based on whether we 
are

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


[clang] [clang] Sequence C++20 Parenthesized List Init (PR #83476)

2024-02-29 Thread Douglas Deslauriers via cfe-commits


@@ -17626,6 +17626,25 @@ class SequenceChecker : public 
ConstEvaluatedExprVisitor {
 for (unsigned I = 0; I < Elts.size(); ++I)
   Tree.merge(Elts[I]);
   }
+
+  void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
+// C++20 parenthesized list initializations are sequenced. See C++20
+// [decl.init]p17.5 and [decl.init]p17.6.2.2

vapdrs wrote:

Resolved, also updated issue and PR description

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


[clang] [clang] Sequence C++20 Parenthesized List Init (PR #83476)

2024-02-29 Thread Douglas Deslauriers via cfe-commits

https://github.com/vapdrs updated 
https://github.com/llvm/llvm-project/pull/83476

>From 85958bdf181b0cb79716a35bc4f3248e8f31c527 Mon Sep 17 00:00:00 2001
From: Douglas Deslauriers 
Date: Thu, 29 Feb 2024 20:18:34 +
Subject: [PATCH] [clang] Sequence C++20 Parenthesized List Init

Parenthesized list intializers are sequenced operations, see C++20
[decl.init]p16.5 and [decl.init]p16.6.2.2 for more details.

Fixes #83474
---
 clang/lib/Sema/SemaChecking.cpp   | 29 +--
 .../warn-unsequenced-paren-list-init.cpp  | 15 ++
 2 files changed, 28 insertions(+), 16 deletions(-)
 create mode 100644 clang/test/SemaCXX/warn-unsequenced-paren-list-init.cpp

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 016e9830662042..4a120a7e310819 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -17589,20 +17589,7 @@ class SequenceChecker : public 
ConstEvaluatedExprVisitor {
   return VisitExpr(CCE);
 
 // In C++11, list initializations are sequenced.
-SmallVector Elts;
-SequenceTree::Seq Parent = Region;
-for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
-  E = CCE->arg_end();
- I != E; ++I) {
-  Region = Tree.allocate(Parent);
-  Elts.push_back(Region);
-  Visit(*I);
-}
-
-// Forget that the initializers are sequenced.
-Region = Parent;
-for (unsigned I = 0; I < Elts.size(); ++I)
-  Tree.merge(Elts[I]);
+SequenceExpressionsInOrder({CCE->getArgs(), CCE->getNumArgs()});
   }
 
   void VisitInitListExpr(const InitListExpr *ILE) {
@@ -17610,10 +17597,20 @@ class SequenceChecker : public 
ConstEvaluatedExprVisitor {
   return VisitExpr(ILE);
 
 // In C++11, list initializations are sequenced.
+SequenceExpressionsInOrder(ILE->inits());
+  }
+
+  void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
+// C++20 parenthesized list initializations are sequenced. See C++20
+// [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
+SequenceExpressionsInOrder(PLIE->getInitExprs());
+  }
+
+private:
+  void SequenceExpressionsInOrder(ArrayRef ExpressionList) {
 SmallVector Elts;
 SequenceTree::Seq Parent = Region;
-for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
-  const Expr *E = ILE->getInit(I);
+for (const Expr *E : ExpressionList) {
   if (!E)
 continue;
   Region = Tree.allocate(Parent);
diff --git a/clang/test/SemaCXX/warn-unsequenced-paren-list-init.cpp 
b/clang/test/SemaCXX/warn-unsequenced-paren-list-init.cpp
new file mode 100644
index 00..5aeeb45f81e226
--- /dev/null
+++ b/clang/test/SemaCXX/warn-unsequenced-paren-list-init.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -Wno-unused -Wunsequenced -verify 
%s
+
+struct A {
+  int x, y;
+};
+
+void test() {
+  int a = 0;
+
+  A agg1( a++, a++ ); // no warning
+  A agg2( a++ + a, a++ ); // expected-warning {{unsequenced modification and 
access to 'a'}}
+
+  int arr1[]( a++, a++ ); // no warning
+  int arr2[]( a++ + a, a++ ); // expected-warning {{unsequenced modification 
and access to 'a'}}
+}

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


[clang] [InstallAPI] Collect frontend attributes & ObjCInterface decls (PR #83378)

2024-02-29 Thread Cyndy Ishida via cfe-commits


@@ -16,6 +16,74 @@ using namespace llvm::MachO;
 
 namespace clang::installapi {
 
+GlobalRecord *FrontendRecordsSlice::addGlobal(
+StringRef Name, RecordLinkage Linkage, GlobalRecord::Kind GV,
+const clang::AvailabilityInfo Avail, const Decl *D, const HeaderType 
Access,
+SymbolFlags Flags) {
+
+  auto *GR = llvm::MachO::RecordsSlice::addGlobal(Name, Linkage, GV, Flags);
+  if (!FrontendRecords.contains(GR))

cyndyishida wrote:

The way tapi handles this today is that none of the `frontend` attributes are 
updated or even checked if they differ. Since this is not a problem area, I 
figured to keep that behavior. 

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


[clang] [clang] Sequence C++20 Parenthesized List Init (PR #83476)

2024-02-29 Thread Douglas Deslauriers via cfe-commits

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


[clang] [InstallAPI] Collect frontend attributes & ObjCInterface decls (PR #83378)

2024-02-29 Thread Cyndy Ishida via cfe-commits


@@ -0,0 +1,86 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s|DSTROOT|%/t|g" %t/inputs.json.in > %t/inputs.json
+
+/// Check multiple targets are captured.

cyndyishida wrote:

Thanks for calling this out, forgot to remove. 

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


[clang] [InstallAPI] Collect frontend attributes & ObjCInterface decls (PR #83378)

2024-02-29 Thread Cyndy Ishida via cfe-commits


@@ -16,6 +16,74 @@ using namespace llvm::MachO;
 
 namespace clang::installapi {
 
+GlobalRecord *FrontendRecordsSlice::addGlobal(
+StringRef Name, RecordLinkage Linkage, GlobalRecord::Kind GV,
+const clang::AvailabilityInfo Avail, const Decl *D, const HeaderType 
Access,
+SymbolFlags Flags) {
+
+  auto *GR = llvm::MachO::RecordsSlice::addGlobal(Name, Linkage, GV, Flags);
+  if (!FrontendRecords.contains(GR))
+FrontendRecords.insert({GR, FrontendAttrs{Avail, D, Access}});
+  return GR;
+}
+
+ObjCInterfaceRecord *FrontendRecordsSlice::addObjCInterface(
+StringRef Name, RecordLinkage Linkage, const clang::AvailabilityInfo Avail,
+const Decl *D, HeaderType Access, bool IsEHType) {
+  ObjCIFSymbolKind SymType =
+  ObjCIFSymbolKind::Class | ObjCIFSymbolKind::MetaClass;
+  if (IsEHType)
+SymType |= ObjCIFSymbolKind::EHType;
+  auto *ObjCR =
+  llvm::MachO::RecordsSlice::addObjCInterface(Name, Linkage, SymType);
+  if (!FrontendRecords.contains(ObjCR))
+FrontendRecords.insert({ObjCR, FrontendAttrs{Avail, D, Access}});
+  return ObjCR;
+}
+
+std::optional
+InstallAPIContext::findAndRecordFile(const FileEntry *FE,
+ const Preprocessor &PP) {
+  if (!FE)
+return std::nullopt;
+
+  // Check if header has been looked up already and whether it is something
+  // installapi should use.
+  auto It = KnownFiles.find(FE);

cyndyishida wrote:

Which sets do you suggest? `KnownFiles` + `UnusedFiles`, wouldn't the lookup be 
roughly equivalent since there are no duplicates between those disjoint sets? 

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


[clang] [llvm] [Hexagon] Add Loop Alignment pass. (PR #83379)

2024-02-29 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Sumanth Gundapaneni (sgundapa)


Changes

Inspect a basic block and if its single basic block loop with a small number of 
instructions, set the Loop Alignment to 32 bytes. This will avoid the cache 
line break in the first packet of loop which will cause a stall per each 
execution of loop.

---

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


9 Files Affected:

- (modified) clang/test/CodeGen/builtins-hexagon.c (+1-1) 
- (modified) llvm/lib/Target/Hexagon/CMakeLists.txt (+1) 
- (added) llvm/lib/Target/Hexagon/HexagonLoopAlign.cpp (+216) 
- (modified) llvm/lib/Target/Hexagon/HexagonTargetMachine.cpp (+8-1) 
- (modified) llvm/lib/Target/Hexagon/HexagonTargetMachine.h (+1) 
- (added) llvm/test/CodeGen/Hexagon/loop-balign.ll (+91) 
- (added) llvm/test/CodeGen/Hexagon/loop_align_count.ll (+115) 
- (added) llvm/test/CodeGen/Hexagon/loop_align_count.mir (+130) 
- (added) llvm/test/CodeGen/Hexagon/v6-haar-balign32.ll (+117) 


``diff
diff --git a/clang/test/CodeGen/builtins-hexagon.c 
b/clang/test/CodeGen/builtins-hexagon.c
index 9a1b733da5cdb8..52073f27ae70f5 100644
--- a/clang/test/CodeGen/builtins-hexagon.c
+++ b/clang/test/CodeGen/builtins-hexagon.c
@@ -1,5 +1,5 @@
 // REQUIRES: hexagon-registered-target
-// RUN: %clang_cc1 -triple hexagon-unknown-elf -target-cpu hexagonv65 
-target-feature +hvxv65 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple hexagon-unknown-elf -target-cpu hexagonv65 
-target-feature +hvxv65 -target-feature +hvx-length128b -emit-llvm %s -o - | 
FileCheck %s
 
 void test() {
   int v64 __attribute__((__vector_size__(64)));
diff --git a/llvm/lib/Target/Hexagon/CMakeLists.txt 
b/llvm/lib/Target/Hexagon/CMakeLists.txt
index a22a5c11e6ab3a..cdc062eee72b1e 100644
--- a/llvm/lib/Target/Hexagon/CMakeLists.txt
+++ b/llvm/lib/Target/Hexagon/CMakeLists.txt
@@ -43,6 +43,7 @@ add_llvm_target(HexagonCodeGen
   HexagonISelDAGToDAGHVX.cpp
   HexagonISelLowering.cpp
   HexagonISelLoweringHVX.cpp
+  HexagonLoopAlign.cpp
   HexagonLoopIdiomRecognition.cpp
   HexagonMachineFunctionInfo.cpp
   HexagonMachineScheduler.cpp
diff --git a/llvm/lib/Target/Hexagon/HexagonLoopAlign.cpp 
b/llvm/lib/Target/Hexagon/HexagonLoopAlign.cpp
new file mode 100644
index 00..c79b528ff2f3f9
--- /dev/null
+++ b/llvm/lib/Target/Hexagon/HexagonLoopAlign.cpp
@@ -0,0 +1,216 @@
+//===- HexagonLoopAlign.cpp - Generate loop alignment directives  
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+// Inspect a basic block and if its single basic block loop with a small
+// number of instructions, set the prefLoopAlignment to 32 bytes (5).
+//===--===//
+
+#define DEBUG_TYPE "hexagon-loop-align"
+
+#include "HexagonTargetMachine.h"
+#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
+#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
+#include "llvm/CodeGen/SchedulerRegistry.h"
+#include "llvm/Support/Debug.h"
+
+using namespace llvm;
+
+static cl::opt
+DisableLoopAlign("disable-hexagon-loop-align", cl::Hidden,
+ cl::desc("Disable Hexagon loop alignment pass"));
+
+static cl::opt HVXLoopAlignLimitUB(
+"hexagon-hvx-loop-align-limit-ub", cl::Hidden, cl::init(16),
+cl::desc("Set hexagon hvx loop upper bound align limit"));
+
+static cl::opt TinyLoopAlignLimitUB(
+"hexagon-tiny-loop-align-limit-ub", cl::Hidden, cl::init(16),
+cl::desc("Set hexagon tiny-core loop upper bound align limit"));
+
+static cl::opt
+LoopAlignLimitUB("hexagon-loop-align-limit-ub", cl::Hidden, cl::init(8),
+ cl::desc("Set hexagon loop upper bound align limit"));
+
+static cl::opt
+LoopAlignLimitLB("hexagon-loop-align-limit-lb", cl::Hidden, cl::init(4),
+ cl::desc("Set hexagon loop lower bound align limit"));
+
+static cl::opt
+LoopBndlAlignLimit("hexagon-loop-bundle-align-limit", cl::Hidden,
+   cl::init(4),
+   cl::desc("Set hexagon loop align bundle limit"));
+
+static cl::opt TinyLoopBndlAlignLimit(
+"hexagon-tiny-loop-bundle-align-limit", cl::Hidden, cl::init(8),
+cl::desc("Set hexagon tiny-core loop align bundle limit"));
+
+static cl::opt
+LoopEdgeThreshold("hexagon-loop-edge-threshold", cl::Hidden, 
cl::init(7500),
+  cl::desc("Set hexagon loop align edge theshold"));
+
+namespace llvm {
+FunctionPass *createHexagonLoopAlign();
+void initializeHexagonLoopAlignPass(PassRegistry &);
+} // namespace llvm
+
+namespace {
+
+class HexagonLoopAlign : public MachineFunctionPass {
+  const HexagonSubtarget *HST = nullptr;
+ 

[clang] [llvm] [Hexagon] Add Loop Alignment pass. (PR #83379)

2024-02-29 Thread Sumanth Gundapaneni via cfe-commits

https://github.com/sgundapa updated 
https://github.com/llvm/llvm-project/pull/83379

>From 973d204ae0d8370704f1613e5206ac330a40e8f4 Mon Sep 17 00:00:00 2001
From: Sumanth Gundapaneni 
Date: Wed, 28 Feb 2024 12:23:35 -0800
Subject: [PATCH] [Hexagon] Add Loop Alignment pass.

Inspect a basic block and if its single basic block loop with a small
number of instructions, set the Loop Alignment to 32 bytes.
This will avoid the cache line break in the first packet of
loop which will cause a stall per each execution of loop.
---
 clang/test/CodeGen/builtins-hexagon.c |   2 +-
 llvm/lib/Target/Hexagon/CMakeLists.txt|   1 +
 llvm/lib/Target/Hexagon/HexagonLoopAlign.cpp  | 216 ++
 .../Target/Hexagon/HexagonTargetMachine.cpp   |   9 +-
 .../lib/Target/Hexagon/HexagonTargetMachine.h |   1 +
 llvm/test/CodeGen/Hexagon/loop-balign.ll  |  91 
 llvm/test/CodeGen/Hexagon/loop_align_count.ll | 115 ++
 .../test/CodeGen/Hexagon/loop_align_count.mir | 130 +++
 llvm/test/CodeGen/Hexagon/v6-haar-balign32.ll | 117 ++
 9 files changed, 680 insertions(+), 2 deletions(-)
 create mode 100644 llvm/lib/Target/Hexagon/HexagonLoopAlign.cpp
 create mode 100644 llvm/test/CodeGen/Hexagon/loop-balign.ll
 create mode 100644 llvm/test/CodeGen/Hexagon/loop_align_count.ll
 create mode 100644 llvm/test/CodeGen/Hexagon/loop_align_count.mir
 create mode 100644 llvm/test/CodeGen/Hexagon/v6-haar-balign32.ll

diff --git a/clang/test/CodeGen/builtins-hexagon.c 
b/clang/test/CodeGen/builtins-hexagon.c
index 9a1b733da5cdb8..52073f27ae70f5 100644
--- a/clang/test/CodeGen/builtins-hexagon.c
+++ b/clang/test/CodeGen/builtins-hexagon.c
@@ -1,5 +1,5 @@
 // REQUIRES: hexagon-registered-target
-// RUN: %clang_cc1 -triple hexagon-unknown-elf -target-cpu hexagonv65 
-target-feature +hvxv65 -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple hexagon-unknown-elf -target-cpu hexagonv65 
-target-feature +hvxv65 -target-feature +hvx-length128b -emit-llvm %s -o - | 
FileCheck %s
 
 void test() {
   int v64 __attribute__((__vector_size__(64)));
diff --git a/llvm/lib/Target/Hexagon/CMakeLists.txt 
b/llvm/lib/Target/Hexagon/CMakeLists.txt
index a22a5c11e6ab3a..cdc062eee72b1e 100644
--- a/llvm/lib/Target/Hexagon/CMakeLists.txt
+++ b/llvm/lib/Target/Hexagon/CMakeLists.txt
@@ -43,6 +43,7 @@ add_llvm_target(HexagonCodeGen
   HexagonISelDAGToDAGHVX.cpp
   HexagonISelLowering.cpp
   HexagonISelLoweringHVX.cpp
+  HexagonLoopAlign.cpp
   HexagonLoopIdiomRecognition.cpp
   HexagonMachineFunctionInfo.cpp
   HexagonMachineScheduler.cpp
diff --git a/llvm/lib/Target/Hexagon/HexagonLoopAlign.cpp 
b/llvm/lib/Target/Hexagon/HexagonLoopAlign.cpp
new file mode 100644
index 00..c79b528ff2f3f9
--- /dev/null
+++ b/llvm/lib/Target/Hexagon/HexagonLoopAlign.cpp
@@ -0,0 +1,216 @@
+//===- HexagonLoopAlign.cpp - Generate loop alignment directives  
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+// Inspect a basic block and if its single basic block loop with a small
+// number of instructions, set the prefLoopAlignment to 32 bytes (5).
+//===--===//
+
+#define DEBUG_TYPE "hexagon-loop-align"
+
+#include "HexagonTargetMachine.h"
+#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
+#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
+#include "llvm/CodeGen/SchedulerRegistry.h"
+#include "llvm/Support/Debug.h"
+
+using namespace llvm;
+
+static cl::opt
+DisableLoopAlign("disable-hexagon-loop-align", cl::Hidden,
+ cl::desc("Disable Hexagon loop alignment pass"));
+
+static cl::opt HVXLoopAlignLimitUB(
+"hexagon-hvx-loop-align-limit-ub", cl::Hidden, cl::init(16),
+cl::desc("Set hexagon hvx loop upper bound align limit"));
+
+static cl::opt TinyLoopAlignLimitUB(
+"hexagon-tiny-loop-align-limit-ub", cl::Hidden, cl::init(16),
+cl::desc("Set hexagon tiny-core loop upper bound align limit"));
+
+static cl::opt
+LoopAlignLimitUB("hexagon-loop-align-limit-ub", cl::Hidden, cl::init(8),
+ cl::desc("Set hexagon loop upper bound align limit"));
+
+static cl::opt
+LoopAlignLimitLB("hexagon-loop-align-limit-lb", cl::Hidden, cl::init(4),
+ cl::desc("Set hexagon loop lower bound align limit"));
+
+static cl::opt
+LoopBndlAlignLimit("hexagon-loop-bundle-align-limit", cl::Hidden,
+   cl::init(4),
+   cl::desc("Set hexagon loop align bundle limit"));
+
+static cl::opt TinyLoopBndlAlignLimit(
+"hexagon-tiny-loop-bundle-align-limit", cl::Hidden, cl::init(8),
+cl::desc("Set hexagon tiny-core loop align bundle limit"));
+
+static cl::opt
+LoopEdgeThreshold("hexagon

[clang] [InstallAPI] Collect frontend attributes & ObjCInterface decls (PR #83378)

2024-02-29 Thread Juergen Ributzka via cfe-commits


@@ -16,6 +16,74 @@ using namespace llvm::MachO;
 
 namespace clang::installapi {
 
+GlobalRecord *FrontendRecordsSlice::addGlobal(
+StringRef Name, RecordLinkage Linkage, GlobalRecord::Kind GV,
+const clang::AvailabilityInfo Avail, const Decl *D, const HeaderType 
Access,
+SymbolFlags Flags) {
+
+  auto *GR = llvm::MachO::RecordsSlice::addGlobal(Name, Linkage, GV, Flags);
+  if (!FrontendRecords.contains(GR))

ributzka wrote:

What if the record already exists? Should the attributes match or be merged?

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


[clang] [InstallAPI] Collect frontend attributes & ObjCInterface decls (PR #83378)

2024-02-29 Thread Juergen Ributzka via cfe-commits


@@ -16,6 +16,74 @@ using namespace llvm::MachO;
 
 namespace clang::installapi {
 
+GlobalRecord *FrontendRecordsSlice::addGlobal(
+StringRef Name, RecordLinkage Linkage, GlobalRecord::Kind GV,
+const clang::AvailabilityInfo Avail, const Decl *D, const HeaderType 
Access,
+SymbolFlags Flags) {
+
+  auto *GR = llvm::MachO::RecordsSlice::addGlobal(Name, Linkage, GV, Flags);
+  if (!FrontendRecords.contains(GR))
+FrontendRecords.insert({GR, FrontendAttrs{Avail, D, Access}});
+  return GR;
+}
+
+ObjCInterfaceRecord *FrontendRecordsSlice::addObjCInterface(
+StringRef Name, RecordLinkage Linkage, const clang::AvailabilityInfo Avail,
+const Decl *D, HeaderType Access, bool IsEHType) {
+  ObjCIFSymbolKind SymType =
+  ObjCIFSymbolKind::Class | ObjCIFSymbolKind::MetaClass;
+  if (IsEHType)
+SymType |= ObjCIFSymbolKind::EHType;
+  auto *ObjCR =
+  llvm::MachO::RecordsSlice::addObjCInterface(Name, Linkage, SymType);
+  if (!FrontendRecords.contains(ObjCR))
+FrontendRecords.insert({ObjCR, FrontendAttrs{Avail, D, Access}});
+  return ObjCR;
+}
+
+std::optional
+InstallAPIContext::findAndRecordFile(const FileEntry *FE,
+ const Preprocessor &PP) {
+  if (!FE)
+return std::nullopt;
+
+  // Check if header has been looked up already and whether it is something
+  // installapi should use.
+  auto It = KnownFiles.find(FE);
+  if (It != KnownFiles.end())
+return It->second;
+  auto UnusedIt = UnusedFiles.find(FE);
+  if (UnusedIt != UnusedFiles.end())
+return std::nullopt;
+
+  // If file was not found, search by how the header was
+  // included. This is primarily to resolve headers found
+  // in a different location than what passed directly as input.
+  StringRef IncludeName = PP.getHeaderSearchInfo().getIncludeNameForHeader(FE);
+  auto BackupIt = KnownIncludes.find(IncludeName.str());
+  if (BackupIt != KnownIncludes.end()) {
+KnownFiles[FE] = BackupIt->second;
+return BackupIt->second;
+  }
+
+  // Record that the file was found to avoid future string searches for the
+  // same file.
+  UnusedFiles.insert(FE);
+  return std::nullopt;
+}
+
+void InstallAPIContext::addKnownHeader(const HeaderFile &H) {
+  auto FE = FM->getFile(H.getPath());
+  if (!FE)
+return; // File do not exist.

ributzka wrote:

s/do/does/

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


[clang] [InstallAPI] Collect frontend attributes & ObjCInterface decls (PR #83378)

2024-02-29 Thread Juergen Ributzka via cfe-commits


@@ -16,6 +16,74 @@ using namespace llvm::MachO;
 
 namespace clang::installapi {
 
+GlobalRecord *FrontendRecordsSlice::addGlobal(
+StringRef Name, RecordLinkage Linkage, GlobalRecord::Kind GV,
+const clang::AvailabilityInfo Avail, const Decl *D, const HeaderType 
Access,
+SymbolFlags Flags) {
+
+  auto *GR = llvm::MachO::RecordsSlice::addGlobal(Name, Linkage, GV, Flags);
+  if (!FrontendRecords.contains(GR))

ributzka wrote:

You could optimize this a bit by always inserting. `insert` doesn't change 
anything if the key already exists.

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


[clang] [InstallAPI] Collect frontend attributes & ObjCInterface decls (PR #83378)

2024-02-29 Thread Juergen Ributzka via cfe-commits


@@ -0,0 +1,86 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s|DSTROOT|%/t|g" %t/inputs.json.in > %t/inputs.json
+
+/// Check multiple targets are captured.

ributzka wrote:

What do you mean with multiple targets here?

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


[clang] [InstallAPI] Collect frontend attributes & ObjCInterface decls (PR #83378)

2024-02-29 Thread Juergen Ributzka via cfe-commits


@@ -16,6 +16,74 @@ using namespace llvm::MachO;
 
 namespace clang::installapi {
 
+GlobalRecord *FrontendRecordsSlice::addGlobal(
+StringRef Name, RecordLinkage Linkage, GlobalRecord::Kind GV,
+const clang::AvailabilityInfo Avail, const Decl *D, const HeaderType 
Access,
+SymbolFlags Flags) {
+
+  auto *GR = llvm::MachO::RecordsSlice::addGlobal(Name, Linkage, GV, Flags);
+  if (!FrontendRecords.contains(GR))
+FrontendRecords.insert({GR, FrontendAttrs{Avail, D, Access}});
+  return GR;
+}
+
+ObjCInterfaceRecord *FrontendRecordsSlice::addObjCInterface(
+StringRef Name, RecordLinkage Linkage, const clang::AvailabilityInfo Avail,
+const Decl *D, HeaderType Access, bool IsEHType) {
+  ObjCIFSymbolKind SymType =
+  ObjCIFSymbolKind::Class | ObjCIFSymbolKind::MetaClass;
+  if (IsEHType)
+SymType |= ObjCIFSymbolKind::EHType;
+  auto *ObjCR =
+  llvm::MachO::RecordsSlice::addObjCInterface(Name, Linkage, SymType);
+  if (!FrontendRecords.contains(ObjCR))
+FrontendRecords.insert({ObjCR, FrontendAttrs{Avail, D, Access}});
+  return ObjCR;
+}
+
+std::optional
+InstallAPIContext::findAndRecordFile(const FileEntry *FE,
+ const Preprocessor &PP) {
+  if (!FE)
+return std::nullopt;
+
+  // Check if header has been looked up already and whether it is something
+  // installapi should use.
+  auto It = KnownFiles.find(FE);

ributzka wrote:

I think this could be optimized into a single set, so you only need to do the 
lookup once.

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


[clang-tools-extra] 21be2fb - [clang-tidy][NFC] Fix buffer overflow in modernize-use-designated-initializers

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

Author: Piotr Zegar
Date: 2024-02-29T20:53:30Z
New Revision: 21be2fbd17f9ff6f3f04e0ababc91c9cdd5aed85

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

LOG: [clang-tidy][NFC] Fix buffer overflow in 
modernize-use-designated-initializers

Instance of DenseMap were copied into local variable,
and as a result reference to string stored in that local
variable were returned from function. At the end fix-it
were applied with already destroyed string causing some
non utf-8 characters to be printed.

Related to #80541

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseDesignatedInitializersCheck.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/modernize/UseDesignatedInitializersCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseDesignatedInitializersCheck.cpp
index 9ff6bb15043b54..ebc5338d0a7bfa 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseDesignatedInitializersCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseDesignatedInitializersCheck.cpp
@@ -43,7 +43,7 @@ struct Designators {
   unsigned size() { return getCached().size(); }
 
   std::optional operator[](const SourceLocation &Location) {
-const auto Designators = getCached();
+const auto &Designators = getCached();
 const auto Result = Designators.find(Location);
 if (Result == Designators.end())
   return {};



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


[clang] [clang-tools-extra] [clang-tidy] Add new check `modernize-use-designated-initializers` (PR #80541)

2024-02-29 Thread Piotr Zegar via cfe-commits
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= 
Message-ID:
In-Reply-To: 


PiotrZSL wrote:

@SimplyDanny 

There is a bug, when run (locally) with:
`../.build-llvm-project/bin/clang-tidy 
--checks="-*,modernize-use-designated-initializers" clang/lib/Basic/Module.cpp 
--header-filter=".*" --fix`

It inserts some random characters into Module.h:

```
-  return Header{UmbrellaAsWritten, UmbrellaRelativeToRootModuleDirectory,
-*Hdr};
+  return Header{.NameAsWritten=UmbrellaAsWritten, 
.[U^@^@GI<89>}<95>ootModuleDirectory=UmbrellaRelativeToRootModuleDirectory,
+.Entry=*Hdr};
```

Looks like "use after free" error.
Probably that was a reason why tests were toggling.

Valgrind detect this as:
```
==41359== Invalid read of size 1
==41359==at 0x6A03309: memmove (vg_replace_strmem.c:1398)
==41359==by 0x2E039EB: llvm::raw_svector_ostream::write_impl(char const*, 
unsigned long) (in /fpwork/.build-llvm-project/bin/clang-tidy)
==41359==by 0x2E01C2F: llvm::raw_ostream::write(char const*, unsigned long) 
(in /fpwork/.build-llvm-project/bin/clang-tidy)
==41359==by 0x2E122C1: 
llvm::Twine::toStringRef(llvm::SmallVectorImpl&) const (in 
/fpwork/.build-llvm-project/bin/clang-tidy)
==41359==by 0x2E1214E: llvm::Twine::str[abi:cxx11]() const (in 
/fpwork/.build-llvm-project/bin/clang-tidy)
==41359==by 0x3C8B2B7: 
clang::tidy::modernize::UseDesignatedInitializersCheck::check(clang::ast_matchers::MatchFinder::MatchResult
 const&) 
```



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


[clang] [clang] Sequence C++20 Parenthesized List Init (PR #83476)

2024-02-29 Thread Richard Smith via cfe-commits

https://github.com/zygoloid commented:

Thanks!

[I'm not sure when I'll have time to circle back to this, so I'd be happy for 
someone else to finish the review and approve.]

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


[clang] [clang] Sequence C++20 Parenthesized List Init (PR #83476)

2024-02-29 Thread Richard Smith via cfe-commits

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


[clang] [clang] Sequence C++20 Parenthesized List Init (PR #83476)

2024-02-29 Thread Richard Smith via cfe-commits


@@ -17626,6 +17626,25 @@ class SequenceChecker : public 
ConstEvaluatedExprVisitor {
 for (unsigned I = 0; I < Elts.size(); ++I)
   Tree.merge(Elts[I]);
   }
+
+  void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
+// C++20 parenthesized list initializations are sequenced. See C++20
+// [decl.init]p17.5 and [decl.init]p17.6.2.2

zygoloid wrote:

I think you mean `dcl.init.general`, not `decl.init` here, and the wording is 
in p16 not p17 in C++20 and the current working paper.
```suggestion
// [dcl.init.general]p16.5 and [dcl.init.general]p16.6.2.2.
```

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


[clang] [clang] Sequence C++20 Parenthesized List Init (PR #83476)

2024-02-29 Thread Richard Smith via cfe-commits


@@ -17626,6 +17626,25 @@ class SequenceChecker : public 
ConstEvaluatedExprVisitor {
 for (unsigned I = 0; I < Elts.size(); ++I)
   Tree.merge(Elts[I]);
   }
+
+  void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
+// C++20 parenthesized list initializations are sequenced. See C++20
+// [decl.init]p17.5 and [decl.init]p17.6.2.2
+SmallVector Elts;
+SequenceTree::Seq Parent = Region;
+for (const Expr *E : PLIE->getInitExprs()) {
+  if (!E)
+continue;
+  Region = Tree.allocate(Parent);
+  Elts.push_back(Region);
+  Visit(E);
+}
+
+// Forget that the initializers are sequenced.
+Region = Parent;
+for (unsigned I = 0; I < Elts.size(); ++I)
+  Tree.merge(Elts[I]);
+  }

zygoloid wrote:

Is it feasible to factor out the common code between this and 
`VisitInitListExpr`? This looks nearly identical.

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


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

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

vinayakdsci wrote:

> Aside from some grammatical changes to the release note, the changes LGTM! 

Thank you so much! I have made changes to the Release Notes as you suggested. 
Thanks for your review!

> Do you need someone to land this on your behalf once those changes are made?

Yes, I don't have commit access at present, so I would really appreciate it if 
you or someone else could land it on my behalf.

Again, a big thanks!

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


[clang] [clang] Sequence C++20 Parenthesized List Init (PR #83476)

2024-02-29 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Douglas Deslauriers (vapdrs)


Changes

Parenthesized list intializers are sequenced operations, see C++20 
[decl.init]p17.5 and [decl.init]p17.6.2.2 for more details.

Fixes #83474

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


2 Files Affected:

- (modified) clang/lib/Sema/SemaChecking.cpp (+19) 
- (added) clang/test/SemaCXX/warn-unsequenced-paren-list-init.cpp (+15) 


``diff
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 016e9830662042..eaa45378f8eb49 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -17626,6 +17626,25 @@ class SequenceChecker : public 
ConstEvaluatedExprVisitor {
 for (unsigned I = 0; I < Elts.size(); ++I)
   Tree.merge(Elts[I]);
   }
+
+  void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
+// C++20 parenthesized list initializations are sequenced. See C++20
+// [decl.init]p17.5 and [decl.init]p17.6.2.2
+SmallVector Elts;
+SequenceTree::Seq Parent = Region;
+for (const Expr *E : PLIE->getInitExprs()) {
+  if (!E)
+continue;
+  Region = Tree.allocate(Parent);
+  Elts.push_back(Region);
+  Visit(E);
+}
+
+// Forget that the initializers are sequenced.
+Region = Parent;
+for (unsigned I = 0; I < Elts.size(); ++I)
+  Tree.merge(Elts[I]);
+  }
 };
 
 SequenceChecker::UsageInfo::UsageInfo() = default;
diff --git a/clang/test/SemaCXX/warn-unsequenced-paren-list-init.cpp 
b/clang/test/SemaCXX/warn-unsequenced-paren-list-init.cpp
new file mode 100644
index 00..5aeeb45f81e226
--- /dev/null
+++ b/clang/test/SemaCXX/warn-unsequenced-paren-list-init.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -Wno-unused -Wunsequenced -verify 
%s
+
+struct A {
+  int x, y;
+};
+
+void test() {
+  int a = 0;
+
+  A agg1( a++, a++ ); // no warning
+  A agg2( a++ + a, a++ ); // expected-warning {{unsequenced modification and 
access to 'a'}}
+
+  int arr1[]( a++, a++ ); // no warning
+  int arr2[]( a++ + a, a++ ); // expected-warning {{unsequenced modification 
and access to 'a'}}
+}

``




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


[clang] [clang] Sequence C++20 Parenthesized List Init (PR #83476)

2024-02-29 Thread via cfe-commits

github-actions[bot] wrote:



Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be
notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this 
page.

If this is not working for you, it is probably because you do not have write
permissions for the repository. In which case you can instead tag reviewers by
name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review
by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate
is once a week. Please remember that you are asking for valuable time from 
other developers.

If you have further questions, they may be answered by the [LLVM GitHub User 
Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM 
Discord](https://discord.com/invite/xS7Z362) or on the 
[forums](https://discourse.llvm.org/).

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


[clang] [clang] Sequence C++20 Parenthesized List Init (PR #83476)

2024-02-29 Thread Douglas Deslauriers via cfe-commits

https://github.com/vapdrs created 
https://github.com/llvm/llvm-project/pull/83476

Parenthesized list intializers are sequenced operations, see C++20 
[decl.init]p17.5 and [decl.init]p17.6.2.2 for more details.

Fixes #83474

>From 82e371bdcde2da8336b8679fff941f8b0a0394ae Mon Sep 17 00:00:00 2001
From: Douglas Deslauriers 
Date: Thu, 29 Feb 2024 20:18:34 +
Subject: [PATCH] [clang] Sequence C++20 Parenthesized List Init

Parenthesized list intializers are sequenced operations, see C++20
[decl.init]p17.5 and [decl.init]p17.6.2.2 for more details.

Fixes #83474
---
 clang/lib/Sema/SemaChecking.cpp   | 19 +++
 .../warn-unsequenced-paren-list-init.cpp  | 15 +++
 2 files changed, 34 insertions(+)
 create mode 100644 clang/test/SemaCXX/warn-unsequenced-paren-list-init.cpp

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 016e9830662042..eaa45378f8eb49 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -17626,6 +17626,25 @@ class SequenceChecker : public 
ConstEvaluatedExprVisitor {
 for (unsigned I = 0; I < Elts.size(); ++I)
   Tree.merge(Elts[I]);
   }
+
+  void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
+// C++20 parenthesized list initializations are sequenced. See C++20
+// [decl.init]p17.5 and [decl.init]p17.6.2.2
+SmallVector Elts;
+SequenceTree::Seq Parent = Region;
+for (const Expr *E : PLIE->getInitExprs()) {
+  if (!E)
+continue;
+  Region = Tree.allocate(Parent);
+  Elts.push_back(Region);
+  Visit(E);
+}
+
+// Forget that the initializers are sequenced.
+Region = Parent;
+for (unsigned I = 0; I < Elts.size(); ++I)
+  Tree.merge(Elts[I]);
+  }
 };
 
 SequenceChecker::UsageInfo::UsageInfo() = default;
diff --git a/clang/test/SemaCXX/warn-unsequenced-paren-list-init.cpp 
b/clang/test/SemaCXX/warn-unsequenced-paren-list-init.cpp
new file mode 100644
index 00..5aeeb45f81e226
--- /dev/null
+++ b/clang/test/SemaCXX/warn-unsequenced-paren-list-init.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -Wno-unused -Wunsequenced -verify 
%s
+
+struct A {
+  int x, y;
+};
+
+void test() {
+  int a = 0;
+
+  A agg1( a++, a++ ); // no warning
+  A agg2( a++ + a, a++ ); // expected-warning {{unsequenced modification and 
access to 'a'}}
+
+  int arr1[]( a++, a++ ); // no warning
+  int arr2[]( a++ + a, a++ ); // expected-warning {{unsequenced modification 
and access to 'a'}}
+}

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


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

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

https://github.com/vinayakdsci updated 
https://github.com/llvm/llvm-project/pull/81127

>From d4df9a7bef0f993d0c092af5f5af61202dc3effe Mon Sep 17 00:00:00 2001
From: Vinayak Dev 
Date: Thu, 8 Feb 2024 17:29:44 +0530
Subject: [PATCH] [Clang][Sema]: Allow copy constructor side effects

---
 clang/docs/ReleaseNotes.rst  |  4 +++
 clang/lib/Sema/SemaDecl.cpp  |  3 +-
 clang/test/SemaCXX/warn-unused-variables.cpp | 33 ++--
 3 files changed, 37 insertions(+), 3 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f44fef28b9f17f..2aff72733c8b77 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -218,6 +218,10 @@ Bug Fixes in This Version
   for logical operators in C23.
   Fixes (`#64356 `_).
 
+- Clang no longer produces a false-positive `-Wunused-variable` warning
+  for variables created through copy initialization having side-effects in 
C++17 and later.
+  Fixes (`#79518 `_).
+
 Bug Fixes to Compiler Builtins
 ^^
 
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 9fdd8eb236d1ee..6289cf75e17413 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -2044,7 +2044,8 @@ static bool ShouldDiagnoseUnusedDecl(const LangOptions 
&LangOpts,
   return false;
 
 if (Init) {
-  const auto *Construct = dyn_cast(Init);
+  const auto *Construct =
+  dyn_cast(Init->IgnoreImpCasts());
   if (Construct && !Construct->isElidable()) {
 const CXXConstructorDecl *CD = Construct->getConstructor();
 if (!CD->isTrivial() && !RD->hasAttr() &&
diff --git a/clang/test/SemaCXX/warn-unused-variables.cpp 
b/clang/test/SemaCXX/warn-unused-variables.cpp
index b649c7d8089355..29e8d08d37d8c6 100644
--- a/clang/test/SemaCXX/warn-unused-variables.cpp
+++ b/clang/test/SemaCXX/warn-unused-variables.cpp
@@ -1,5 +1,7 @@
 // RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify %s
-// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify -std=gnu++11 %s
+// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify=expected,cxx98-14 -std=gnu++11 %s
+// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify=expected,cxx98-14 -std=gnu++14 %s
+// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify -std=gnu++17 %s
 template void f() {
   T t;
   t = 17;
@@ -183,7 +185,8 @@ void foo(int size) {
   NonTriviallyDestructible array[2];  // no warning
   NonTriviallyDestructible nestedArray[2][2]; // no warning
 
-  Foo fooScalar = 1; // expected-warning {{unused variable 'fooScalar'}}
+  // Copy initialzation gives warning before C++17
+  Foo fooScalar = 1; // cxx98-14-warning {{unused variable 'fooScalar'}}
   Foo fooArray[] = {1,2}; // expected-warning {{unused variable 'fooArray'}}
   Foo fooNested[2][2] = { {1,2}, {3,4} }; // expected-warning {{unused 
variable 'fooNested'}}
 }
@@ -297,3 +300,29 @@ void RAIIWrapperTest() {
 }
 
 } // namespace gh54489
+
+// Ensure that -Wunused-variable does not emit warning
+// on copy constructors with side effects (C++17 and later)
+#if __cplusplus >= 201703L
+namespace gh79518 {
+
+struct S {
+S(int);
+};
+
+// With an initializer list
+struct A {
+  int x;
+  A(int x) : x(x) {}
+};
+
+void foo() {
+S s(0); // no warning
+S s2 = 0; // no warning
+S s3{0}; // no warning
+
+A a = 1; // no warning
+}
+
+} // namespace gh79518
+#endif

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


  1   2   3   4   >