[clang-tools-extra] [clangd] Support go-to-definition on type hints. The core part (PR #86629)

2024-04-01 Thread Younan Zhang via cfe-commits

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

>From b8a69cbd9e0ee0aa35b38b7e3a78048cbe61447e Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sat, 16 Mar 2024 23:30:10 +0800
Subject: [PATCH 1/9] [clangd] Support go-to-definition on type hints. The core
 part

---
 clang-tools-extra/clangd/AST.cpp  |   9 +
 clang-tools-extra/clangd/AST.h|   2 +
 clang-tools-extra/clangd/InlayHints.cpp   | 251 +-
 .../clangd/index/IndexAction.cpp  |   9 +-
 .../clangd/unittests/InlayHintTests.cpp   |  22 ++
 5 files changed, 279 insertions(+), 14 deletions(-)

diff --git a/clang-tools-extra/clangd/AST.cpp b/clang-tools-extra/clangd/AST.cpp
index 1b86ea19cf28da..ef87f1bcb8443c 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -1019,5 +1019,14 @@ bool isExpandedFromParameterPack(const ParmVarDecl *D) {
   return getUnderlyingPackType(D) != nullptr;
 }
 
+std::optional toURI(OptionalFileEntryRef File) {
+  if (!File)
+return std::nullopt;
+  auto AbsolutePath = File->getFileEntry().tryGetRealPathName();
+  if (AbsolutePath.empty())
+return std::nullopt;
+  return URI::create(AbsolutePath);
+}
+
 } // namespace clangd
 } // namespace clang
diff --git a/clang-tools-extra/clangd/AST.h b/clang-tools-extra/clangd/AST.h
index fb0722d697cd06..3ae624b1ab7415 100644
--- a/clang-tools-extra/clangd/AST.h
+++ b/clang-tools-extra/clangd/AST.h
@@ -250,6 +250,8 @@ resolveForwardingParameters(const FunctionDecl *D, unsigned 
MaxDepth = 10);
 /// reference to one (e.g. `Args&...` or `Args&&...`).
 bool isExpandedFromParameterPack(const ParmVarDecl *D);
 
+std::optional toURI(OptionalFileEntryRef File);
+
 } // namespace clangd
 } // namespace clang
 
diff --git a/clang-tools-extra/clangd/InlayHints.cpp 
b/clang-tools-extra/clangd/InlayHints.cpp
index cd4f1931b3ce1d..f9e0a51ddcc9f0 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/Stmt.h"
 #include "clang/AST/StmtVisitor.h"
 #include "clang/AST/Type.h"
+#include "clang/AST/TypeVisitor.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/OperatorKinds.h"
 #include "clang/Basic/SourceManager.h"
@@ -372,6 +373,197 @@ maybeDropCxxExplicitObjectParameters(ArrayRef Params) {
   return Params;
 }
 
+std::optional toLocation(SourceManager &SM, SourceRange Range) {
+  if (Range.isInvalid())
+return std::nullopt;
+  if (auto URI =
+  toURI(SM.getFileEntryRefForID(SM.getFileID(Range.getBegin() {
+Location L;
+L.range.start = sourceLocToPosition(SM, Range.getBegin());
+L.range.end = sourceLocToPosition(SM, Range.getEnd());
+if (auto File = URIForFile::fromURI(*URI, ""))
+  L.uri = File.get();
+return L;
+  }
+  return std::nullopt;
+}
+
+class TypeInlayHintLabelPartBuilder
+: public TypeVisitor {
+  QualType Current;
+  ASTContext &Context;
+  const PrintingPolicy &PP;
+  std::vector &LabelChunks;
+
+  bool ShouldAddLinksToTagTypes = false;
+
+  struct CurrentTypeRAII {
+TypeInlayHintLabelPartBuilder &Builder;
+QualType PreviousType;
+bool PreviousShouldAddLinksToTagTypes;
+CurrentTypeRAII(TypeInlayHintLabelPartBuilder &Builder, QualType New,
+bool ShouldAddLinksToTagTypes)
+: Builder(Builder), PreviousType(Builder.Current) {
+  Builder.Current = New;
+  Builder.ShouldAddLinksToTagTypes = ShouldAddLinksToTagTypes;
+}
+~CurrentTypeRAII() {
+  Builder.Current = PreviousType;
+  Builder.ShouldAddLinksToTagTypes = PreviousShouldAddLinksToTagTypes;
+}
+  };
+
+  void addLabel(llvm::function_ref NamePrinter,
+llvm::function_ref SourceRangeGetter) {
+auto &Name = LabelChunks.emplace_back();
+llvm::raw_string_ostream OS(Name.value);
+NamePrinter(OS);
+Name.location = toLocation(Context.getSourceManager(), 
SourceRangeGetter());
+  }
+
+  void printTemplateArgumentList(llvm::ArrayRef Args) {
+unsigned Size = Args.size();
+for (unsigned I = 0; I < Size; ++I) {
+  auto &TA = Args[I];
+  if (PP.SuppressDefaultTemplateArgs && TA.getIsDefaulted())
+continue;
+  if (I)
+LabelChunks.emplace_back(", ");
+  printTemplateArgument(TA);
+}
+  }
+
+  void printTemplateArgument(const TemplateArgument &TA) {
+if (TA.getKind() == TemplateArgument::Pack)
+  return printTemplateArgumentList(TA.pack_elements());
+if (TA.getKind() == TemplateArgument::Type) {
+  CurrentTypeRAII Guard(*this, TA.getAsType(),
+/*ShouldAddLinksToTagTypes=*/true);
+  return Visit(TA.getAsType().getTypePtr());
+}
+llvm::raw_string_ostream OS(LabelChunks.emplace_back().value);
+TA.print(PP, OS, /*IncludeType=*/true);
+  }
+
+  void
+  processTemplateSpecialization(TemplateName TN,
+llvm::ArrayRef Args,
+So

[clang] [C++20] [Modules] Introduce -fexperimental-modules-reduced-bmi (PR #85050)

2024-04-01 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

> > Got it. I've renamed the flag as `-fexperimental-modules-reduced-bmi`.
> 
> Thanks.
> 
> > I feel the suggestion like let users to use `-Xclang` options look odd..
> 
> I think the point here is that we want **expert** users to try this out (with 
> understanding that it might not behave exactly as they expect). Because it is 
> experimental, it is not yet ready for "end users" - I would expect expert 
> users to be able to deal with -Xclang x (but I will not insist, it's just 
> a suggestion)

Agreed.

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


[clang] [C++20] [Modules] Introduce -fexperimental-modules-reduced-bmi (PR #85050)

2024-04-01 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

I'd like to land this patch in next week if no objection comes in.

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


[clang] [llvm] [InstCombiner] Remove trivially dead `llvm.allow.{runtime,ubsan}.check()` (PR #84851)

2024-04-01 Thread Vitaly Buka via cfe-commits

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


[clang-tools-extra] [clang-tidy] add new check readability-enum-initial-value (PR #86129)

2024-04-01 Thread Congcong Cai via cfe-commits

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


[clang-tools-extra] 3365d62 - [clang-tidy] add new check readability-enum-initial-value (#86129)

2024-04-01 Thread via cfe-commits

Author: Congcong Cai
Date: 2024-04-01T15:53:57+08:00
New Revision: 3365d62179011aad6da3e4cbcb31044eec3462a2

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

LOG: [clang-tidy] add new check readability-enum-initial-value (#86129)

Fixes: #85243.

Added: 
clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp
clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.h
clang-tools-extra/docs/clang-tidy/checks/readability/enum-initial-value.rst
clang-tools-extra/test/clang-tidy/checkers/readability/enum-initial-value.c

clang-tools-extra/test/clang-tidy/checkers/readability/enum-initial-value.cpp

Modified: 
clang-tools-extra/clang-tidy/readability/CMakeLists.txt
clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/list.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
index 5728c9970fb65d..dd772d69202548 100644
--- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
@@ -17,6 +17,7 @@ add_clang_library(clangTidyReadabilityModule
   DeleteNullPointerCheck.cpp
   DuplicateIncludeCheck.cpp
   ElseAfterReturnCheck.cpp
+  EnumInitialValueCheck.cpp
   FunctionCognitiveComplexityCheck.cpp
   FunctionSizeCheck.cpp
   IdentifierLengthCheck.cpp

diff  --git 
a/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp
new file mode 100644
index 00..8f2841c32259a2
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp
@@ -0,0 +1,200 @@
+//===--- EnumInitialValueCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "EnumInitialValueCheck.h"
+#include "../utils/LexerUtils.h"
+#include "clang/AST/Decl.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallString.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+static bool isNoneEnumeratorsInitialized(const EnumDecl &Node) {
+  return llvm::all_of(Node.enumerators(), [](const EnumConstantDecl *ECD) {
+return ECD->getInitExpr() == nullptr;
+  });
+}
+
+static bool isOnlyFirstEnumeratorInitialized(const EnumDecl &Node) {
+  bool IsFirst = true;
+  for (const EnumConstantDecl *ECD : Node.enumerators()) {
+if ((IsFirst && ECD->getInitExpr() == nullptr) ||
+(!IsFirst && ECD->getInitExpr() != nullptr))
+  return false;
+IsFirst = false;
+  }
+  return !IsFirst;
+}
+
+static bool areAllEnumeratorsInitialized(const EnumDecl &Node) {
+  return llvm::all_of(Node.enumerators(), [](const EnumConstantDecl *ECD) {
+return ECD->getInitExpr() != nullptr;
+  });
+}
+
+/// Check if \p Enumerator is initialized with a (potentially negated) \c
+/// IntegerLiteral.
+static bool isInitializedByLiteral(const EnumConstantDecl *Enumerator) {
+  const Expr *const Init = Enumerator->getInitExpr();
+  if (!Init)
+return false;
+  return Init->isIntegerConstantExpr(Enumerator->getASTContext());
+}
+
+static void cleanInitialValue(DiagnosticBuilder &Diag,
+  const EnumConstantDecl *ECD,
+  const SourceManager &SM,
+  const LangOptions &LangOpts) {
+  const SourceRange InitExprRange = ECD->getInitExpr()->getSourceRange();
+  if (InitExprRange.isInvalid() || InitExprRange.getBegin().isMacroID() ||
+  InitExprRange.getEnd().isMacroID())
+return;
+  std::optional EqualToken = 
utils::lexer::findNextTokenSkippingComments(
+  ECD->getLocation(), SM, LangOpts);
+  if (!EqualToken.has_value() ||
+  EqualToken.value().getKind() != tok::TokenKind::equal)
+return;
+  const SourceLocation EqualLoc{EqualToken->getLocation()};
+  if (EqualLoc.isInvalid() || EqualLoc.isMacroID())
+return;
+  Diag << FixItHint::CreateRemoval(EqualLoc)
+   << FixItHint::CreateRemoval(InitExprRange);
+  return;
+}
+
+namespace {
+
+AST_MATCHER(EnumDecl, isMacro) {
+  SourceLocation Loc = Node.getBeginLoc();
+  return Loc.isMacroID();
+}
+
+AST_MATCHER(EnumDecl, hasConsistentInitialValues) {
+  return isNoneEnumeratorsInitialized(Node) |

[clang] ef0291e - [NFC] [Serialization] Reordering lexcical and visible TU block after type decl offsets

2024-04-01 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2024-04-01T16:16:03+08:00
New Revision: ef0291e5f4451abbafab0c839bf51a6382f735f3

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

LOG: [NFC] [Serialization] Reordering lexcical and visible TU block after type 
decl offsets

This patch reorder the lexical block for the translation unit, visible update 
block for the TU and
the viisble upaete block for the extern C context after the type decl
offsets block.

This should be a NFC patch.

This is helpful for later optimizations for eliding unreachable
declarations in the global module fragment. See the comments in
https://github.com/llvm/llvm-project/pull/76930.

Simply, if we want to get the reachable sets of declaratins during the
writing process, we need to write the file-level context later than the
process of writing declarations (which is the main process to determine
the reachable set).

Added: 


Modified: 
clang/lib/Serialization/ASTWriter.cpp
clang/test/Modules/language-linkage.cppm

Removed: 




diff  --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 1e5734c9c834eb..2438fbc166062f 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -4959,38 +4959,12 @@ ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, 
StringRef isysroot,
 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
   }
 
-  // Create a lexical update block containing all of the declarations in the
-  // translation unit that do not come from other AST files.
   const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
-  SmallVector NewGlobalKindDeclPairs;
-  for (const auto *D : TU->noload_decls()) {
-if (!D->isFromASTFile()) {
-  NewGlobalKindDeclPairs.push_back(D->getKind());
-  NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
-}
-  }
-
-  auto Abv = std::make_shared();
-  Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
-  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
-  unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
-  {
-RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
-Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
-  bytes(NewGlobalKindDeclPairs));
-  }
 
-  // And a visible updates block for the translation unit.
-  Abv = std::make_shared();
-  Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
-  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
-  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
-  UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
-  WriteDeclContextVisibleUpdate(TU);
-
-  // If we have any extern "C" names, write out a visible update for them.
-  if (Context.ExternCContext)
-WriteDeclContextVisibleUpdate(Context.ExternCContext);
+  // Force all top level declarations to be emitted.
+  for (const auto *D : TU->noload_decls())
+if (!D->isFromASTFile())
+  GetDeclRef(D);
 
   // If the translation unit has an anonymous namespace, and we don't already
   // have an update block for it, write it as an update block.
@@ -5131,6 +5105,14 @@ ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, 
StringRef isysroot,
   for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
 DeclsToCheckForDeferredDiags.push_back(GetDeclRef(D));
 
+  {
+auto Abv = std::make_shared();
+Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
+Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
+Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
+UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
+  }
+
   RecordData DeclUpdatesOffsetsRecord;
 
   // Keep writing types, declarations, and declaration update records
@@ -5158,6 +5140,35 @@ ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, 
StringRef isysroot,
   WriteTypeDeclOffsets();
   if (!DeclUpdatesOffsetsRecord.empty())
 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
+
+  // Create a lexical update block containing all of the declarations in the
+  // translation unit that do not come from other AST files.
+  {
+SmallVector NewGlobalKindDeclPairs;
+for (const auto *D : TU->noload_decls()) {
+  if (!D->isFromASTFile()) {
+NewGlobalKindDeclPairs.push_back(D->getKind());
+NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
+  }
+}
+
+auto Abv = std::make_shared();
+Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
+Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
+unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
+
+RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
+Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
+  bytes(NewGlo

[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-04-01 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

I think the support for modules in clangd is pretty important. I posted 
https://discourse.llvm.org/t/rfc-directions-for-modules-support-in-clangd/78072 
and let's see if we can make some progress.

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


[clang] [llvm] [PowerPC] Implement 32-bit expansion for rldimi (PR #86783)

2024-04-01 Thread Qiu Chaofan via cfe-commits

https://github.com/ecnelises updated 
https://github.com/llvm/llvm-project/pull/86783

>From b886dcf2da25417d9f8cd75ff4aa58686e35139d Mon Sep 17 00:00:00 2001
From: Qiu Chaofan 
Date: Wed, 27 Mar 2024 17:11:04 +0800
Subject: [PATCH] [PowerPC] Implement 32-bit expansion for rldimi

rldimi is 64-bit instruction, due to backward compatibility, it needs to
be expanded into series of rlwimi in 32-bit environment. In the future,
we may improve bit permutation selector and remove such direct codegen.
---
 clang/lib/Sema/SemaChecking.cpp |   1 -
 llvm/lib/Target/PowerPC/PPCISelLowering.cpp | 109 --
 llvm/test/CodeGen/PowerPC/rldimi.ll | 366 
 3 files changed, 454 insertions(+), 22 deletions(-)

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 11401b6f56c0ea..d2cbe5417d682d 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -5236,7 +5236,6 @@ static bool isPPC_64Builtin(unsigned BuiltinID) {
   case PPC::BI__builtin_ppc_fetch_and_andlp:
   case PPC::BI__builtin_ppc_fetch_and_orlp:
   case PPC::BI__builtin_ppc_fetch_and_swaplp:
-  case PPC::BI__builtin_ppc_rldimi:
 return true;
   }
   return false;
diff --git a/llvm/lib/Target/PowerPC/PPCISelLowering.cpp 
b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
index 7436b202fba0d9..3281a0dfd08729 100644
--- a/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
+++ b/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
@@ -643,6 +643,7 @@ PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine 
&TM,
   // We want to custom lower some of our intrinsics.
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f64, Custom);
+  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::ppcf128, Custom);
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f64, Custom);
@@ -10757,6 +10758,88 @@ static bool getVectorCompareInfo(SDValue Intrin, int 
&CompareOpc,
   return true;
 }
 
+static SDValue getRotateInsert32(SelectionDAG &DAG, SDLoc Loc, SDValue Dst,
+ SDValue Src, unsigned SH, unsigned MB,
+ unsigned ME) {
+  assert(SH < 32 && MB < 32 && ME < 32 &&
+ "Invalid argument for rotate insert!");
+  return SDValue(
+  DAG.getMachineNode(PPC::RLWIMI, Loc, MVT::i32,
+ {Dst, Src, DAG.getTargetConstant(SH, Loc, MVT::i32),
+  DAG.getTargetConstant(MB, Loc, MVT::i32),
+  DAG.getTargetConstant(ME, Loc, MVT::i32)}),
+  0);
+}
+
+static SDValue getRotateInsert64(SelectionDAG &DAG, SDLoc Loc, SDValue Dst,
+ SDValue Src, unsigned SH, unsigned MB,
+ unsigned ME, bool IsPPC64) {
+  assert(SH < 64 && MB < 64 && ME < 64 &&
+ "Invalid argument for rotate insert!");
+  if (IsPPC64) {
+// rldimi requires ME=63-SH, otherwise rotation is needed before rldimi.
+if (ME < 63 - SH) {
+  Src = DAG.getNode(ISD::ROTL, Loc, MVT::i64, Src,
+DAG.getConstant(ME + SH + 1, Loc, MVT::i32));
+} else if (ME > 63 - SH) {
+  Src = DAG.getNode(ISD::ROTL, Loc, MVT::i64, Src,
+DAG.getConstant(ME + SH - 63, Loc, MVT::i32));
+}
+return SDValue(DAG.getMachineNode(
+   PPC::RLDIMI, Loc, MVT::i64,
+   {Dst, Src, DAG.getTargetConstant(63 - ME, Loc, 
MVT::i32),
+DAG.getTargetConstant(MB, Loc, MVT::i32)}),
+   0);
+  }
+
+  // To implement rldimi(Dst, Src) on 32-bit target, four parts are needed. SH
+  // is adjusted to simplify cases. Invalid ranges will be skipped.
+  // - SrcHi inserted into DstHi with [0, 32-SH)
+  // - SrcLo inserted into DstHi with [32-SH, 32)
+  // - SrcHi inserted into DstLo with [32, 64-SH)
+  // - SrcLo inserted into DstLo with [64-SH, 64)
+  auto [SrcLo, SrcHi] = DAG.SplitScalar(Src, Loc, MVT::i32, MVT::i32);
+  auto [DstLo, DstHi] = DAG.SplitScalar(Dst, Loc, MVT::i32, MVT::i32);
+  if (SH >= 32) {
+SH -= 32;
+std::swap(SrcLo, SrcHi);
+  }
+  auto GetSubInsert = [&DAG, &Loc, SH](unsigned Left, unsigned Right,
+   SDValue Src, SDValue Dst, unsigned MB,
+   unsigned ME) {
+if (Left > Right)
+  return Dst;
+
+if (MB <= ME) {
+  if (MB <= Right && ME >= Left)
+return getRotateInsert32(DAG, Loc, Dst, Src, SH,
+ std::max(MB, Left) % 32,
+ std::min(ME, Right) % 32);
+} else {
+  if (MB < Left || ME > Right)
+return getRotateInsert32(DAG, Loc, Dst, Src, SH, Left % 32, Right % 
32);
+
+  if (MB <= Right && ME < Left)
+return getRotateInsert32(DAG, Loc, Ds

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

2024-04-01 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

Friendly ping @cor3ntin and @erichkeane if you're back in the offices.

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


[clang] [clang] Constexpr for __builtin_shufflevector and __builtin_convertvector (PR #76615)

2024-04-01 Thread Pol M via cfe-commits
Pol Marcet =?utf-8?q?Sardà?= ,
Pol Marcet =?utf-8?q?Sardà?= ,
Pol Marcet =?utf-8?q?Sardà?= 
Message-ID:
In-Reply-To: 



@@ -10895,6 +10899,132 @@ bool VectorExprEvaluator::VisitUnaryOperator(const 
UnaryOperator *E) {
   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
 }
 
+static bool EvaluateVectorOrLValue(APValue &Result, EvalInfo &Info,
+   const Expr *E, const QualType &Type) {
+  if (!Evaluate(Result, Info, E))
+return false;
+
+  if (Result.isLValue()) {
+// Source of the data is an lvalue; Manually handle the lvalue as if
+// it was an rvalue to get the current APValue.
+LValue LValueFound;
+LValueFound.setFrom(Info.Ctx, Result);
+if (!handleLValueToRValueConversion(Info, E, Type, LValueFound, Result))
+  return false;
+  }
+
+  return Result.isVector();
+}
+
+static bool handleVectorConversion(EvalInfo &Info, const FPOptions FPO,
+   const Expr *E, QualType SourceTy,
+   QualType DestTy, APValue const &Original,
+   APValue &Result) {
+  if (SourceTy->isIntegerType()) {
+if (DestTy->isRealFloatingType()) {
+  Result = APValue(APFloat(0.0));
+  return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
+  DestTy, Result.getFloat());
+}
+if (DestTy->isIntegerType()) {
+  Result = APValue(
+  HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
+  return true;
+}
+  } else if (SourceTy->isRealFloatingType()) {
+if (DestTy->isRealFloatingType()) {
+  Result = Original;
+  return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
+Result.getFloat());
+}
+if (DestTy->isIntegerType()) {
+  Result = APValue(APSInt());
+  return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
+  DestTy, Result.getInt());
+}
+  }
+  return false;
+}
+
+bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
+  APValue Source;
+  QualType SourceVecType = E->getSrcExpr()->getType();
+  if (!EvaluateVectorOrLValue(Source, Info, E->getSrcExpr(), SourceVecType))
+return false;
+
+  QualType DestTy = E->getType()->castAs()->getElementType();
+  QualType SourceTy = SourceVecType->castAs()->getElementType();
+
+  const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
+
+  auto SourceLen = Source.getVectorLength();
+  SmallVector ResultElements;

Destroyerrrocket wrote:

304 bytes is definitely inside what I'd be slightly worried to allocate without 
thinking into the stack, but having looked at it I think it's going to be fine. 
We're not the only case of smallVectors with APValues, and I'm sure that if it 
ever becomes a problem the default stack size can be modified (or the code can 
be refactored, I'm sure that if that ever happens it's not going to be "just" 
the fault of a smallvector of APValues). I thank you for pointing it out, as I 
simply did not check!

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


[clang] [clang] Constexpr for __builtin_shufflevector and __builtin_convertvector (PR #76615)

2024-04-01 Thread Pol M via cfe-commits
Pol Marcet =?utf-8?q?Sardà?= ,
Pol Marcet =?utf-8?q?Sardà?= ,
Pol Marcet =?utf-8?q?Sardà?= 
Message-ID:
In-Reply-To: 



@@ -10895,6 +10899,132 @@ bool VectorExprEvaluator::VisitUnaryOperator(const 
UnaryOperator *E) {
   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
 }
 
+static bool EvaluateVectorOrLValue(APValue &Result, EvalInfo &Info,
+   const Expr *E, const QualType &Type) {
+  if (!Evaluate(Result, Info, E))
+return false;
+
+  if (Result.isLValue()) {
+// Source of the data is an lvalue; Manually handle the lvalue as if
+// it was an rvalue to get the current APValue.
+LValue LValueFound;
+LValueFound.setFrom(Info.Ctx, Result);
+if (!handleLValueToRValueConversion(Info, E, Type, LValueFound, Result))
+  return false;
+  }
+
+  return Result.isVector();
+}
+
+static bool handleVectorConversion(EvalInfo &Info, const FPOptions FPO,
+   const Expr *E, QualType SourceTy,
+   QualType DestTy, APValue const &Original,
+   APValue &Result) {
+  if (SourceTy->isIntegerType()) {
+if (DestTy->isRealFloatingType()) {
+  Result = APValue(APFloat(0.0));
+  return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
+  DestTy, Result.getFloat());
+}
+if (DestTy->isIntegerType()) {
+  Result = APValue(
+  HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
+  return true;
+}
+  } else if (SourceTy->isRealFloatingType()) {
+if (DestTy->isRealFloatingType()) {
+  Result = Original;
+  return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
+Result.getFloat());
+}
+if (DestTy->isIntegerType()) {
+  Result = APValue(APSInt());
+  return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
+  DestTy, Result.getInt());
+}
+  }
+  return false;
+}
+
+bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
+  APValue Source;
+  QualType SourceVecType = E->getSrcExpr()->getType();
+  if (!EvaluateVectorOrLValue(Source, Info, E->getSrcExpr(), SourceVecType))
+return false;
+
+  QualType DestTy = E->getType()->castAs()->getElementType();
+  QualType SourceTy = SourceVecType->castAs()->getElementType();
+
+  const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
+
+  auto SourceLen = Source.getVectorLength();
+  SmallVector ResultElements;
+  ResultElements.reserve(SourceLen);
+  for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
+APValue Elt;
+if (!handleVectorConversion(Info, FPO, E, SourceTy, DestTy,
+Source.getVectorElt(EltNum), Elt))
+  return false;
+ResultElements.push_back(std::move(Elt));
+  }
+
+  return Success(APValue(ResultElements.data(), ResultElements.size()), E);
+}
+
+static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
+QualType ElemType, APValue const &VecVal1,
+APValue const &VecVal2, unsigned EltNum,
+APValue &Result) {
+  unsigned const TotalElementsInAVector = VecVal1.getVectorLength();

Destroyerrrocket wrote:

I see! It seems like Gcc has extra characteristics then. given that at some 
point it could happen that such a thing needs to be supported, let's actually 
rewrite the code to support both sizes. Beware, I won't be able to test it, as 
Sema will prevent it from reaching constexpr. 

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


[clang] [clang] Constexpr for __builtin_shufflevector and __builtin_convertvector (PR #76615)

2024-04-01 Thread Pol M via cfe-commits
Pol Marcet =?utf-8?q?Sardà?= ,
Pol Marcet =?utf-8?q?Sardà?= ,
Pol Marcet =?utf-8?q?Sardà?= 
Message-ID:
In-Reply-To: 



@@ -10895,6 +10899,132 @@ bool VectorExprEvaluator::VisitUnaryOperator(const 
UnaryOperator *E) {
   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
 }
 
+static bool EvaluateVectorOrLValue(APValue &Result, EvalInfo &Info,
+   const Expr *E, const QualType &Type) {
+  if (!Evaluate(Result, Info, E))
+return false;
+
+  if (Result.isLValue()) {
+// Source of the data is an lvalue; Manually handle the lvalue as if
+// it was an rvalue to get the current APValue.
+LValue LValueFound;
+LValueFound.setFrom(Info.Ctx, Result);
+if (!handleLValueToRValueConversion(Info, E, Type, LValueFound, Result))
+  return false;
+  }
+
+  return Result.isVector();
+}
+
+static bool handleVectorConversion(EvalInfo &Info, const FPOptions FPO,
+   const Expr *E, QualType SourceTy,
+   QualType DestTy, APValue const &Original,
+   APValue &Result) {
+  if (SourceTy->isIntegerType()) {
+if (DestTy->isRealFloatingType()) {
+  Result = APValue(APFloat(0.0));
+  return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
+  DestTy, Result.getFloat());
+}
+if (DestTy->isIntegerType()) {
+  Result = APValue(
+  HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
+  return true;
+}
+  } else if (SourceTy->isRealFloatingType()) {
+if (DestTy->isRealFloatingType()) {
+  Result = Original;
+  return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
+Result.getFloat());
+}
+if (DestTy->isIntegerType()) {
+  Result = APValue(APSInt());
+  return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
+  DestTy, Result.getInt());
+}
+  }
+  return false;
+}
+
+bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
+  APValue Source;
+  QualType SourceVecType = E->getSrcExpr()->getType();
+  if (!EvaluateVectorOrLValue(Source, Info, E->getSrcExpr(), SourceVecType))
+return false;
+
+  QualType DestTy = E->getType()->castAs()->getElementType();
+  QualType SourceTy = SourceVecType->castAs()->getElementType();
+
+  const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
+
+  auto SourceLen = Source.getVectorLength();
+  SmallVector ResultElements;
+  ResultElements.reserve(SourceLen);
+  for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
+APValue Elt;
+if (!handleVectorConversion(Info, FPO, E, SourceTy, DestTy,
+Source.getVectorElt(EltNum), Elt))
+  return false;
+ResultElements.push_back(std::move(Elt));
+  }
+
+  return Success(APValue(ResultElements.data(), ResultElements.size()), E);
+}
+
+static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
+QualType ElemType, APValue const &VecVal1,
+APValue const &VecVal2, unsigned EltNum,
+APValue &Result) {
+  unsigned const TotalElementsInAVector = VecVal1.getVectorLength();
+
+  Expr const *IndexExpr = E->getExpr(2 + EltNum);
+  APSInt IndexVal;
+  if (!EvaluateInteger(IndexExpr, IndexVal, Info))
+return false;
+
+  uint32_t index = IndexVal.getZExtValue();
+  // The spec says that -1 should be treated as undef for optimizations,
+  // but in constexpr we need to choose a value. We'll choose 0.
+  if (index >= TotalElementsInAVector * 2)
+index = 0;

Destroyerrrocket wrote:

Great, let's hope operator[] makes it.

The error comes from somewhere in the depths of ExprConst, it intentionally 
tells you that undefined values are indeed illegal in constexpr code. I agree 
with you, a shame it makes sense!

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


[clang] [llvm] [PowerPC] Implement 32-bit expansion for rldimi (PR #86783)

2024-04-01 Thread Kai Luo via cfe-commits

bzEq wrote:

> due to backward compatibility, it needs to be expanded into series of rlwimi 
> in 32-bit environment

Why must be 'series of rlwimi'?

Why don't we just expand it following what ISA describes and let legalizer 
generates code sequence under 32-bit mode?
```
n ← sh5 || sh0:4
r ← ROTL64((RS), n)
b ← mb5 || mb0:4
m ← MASK(b, ¬n) RA ← r&m | (RA) & ¬m
```

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


[clang] [C99] Claim conformance to WG14 N717 (PR #87228)

2024-04-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Aaron Ballman (AaronBallman)


Changes

This was the paper that added Universal Character Names to C.

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


3 Files Affected:

- (added) clang/test/C/C99/n717.c (+69) 
- (added) clang/test/C/C99/n717.py (+39) 
- (modified) clang/www/c_status.html (+1-1) 


``diff
diff --git a/clang/test/C/C99/n717.c b/clang/test/C/C99/n717.c
new file mode 100644
index 00..cc1aa0fd5d53cf
--- /dev/null
+++ b/clang/test/C/C99/n717.c
@@ -0,0 +1,69 @@
+// RUN: %clang_cc1 -verify -std=c99 %s
+// RUN: %clang_cc1 -verify -std=c99 -fno-dollars-in-identifiers %s
+
+/* WG14 N717: Clang 17
+ * Extended identifiers
+ */
+
+// Used as a sink for UCNs.
+#define M(arg)
+
+// C99 6.4.3p1 specifies the grammar for UCNs. A \u must be followed by exactly
+// four hex digits, and \U must be followed by exactly eight.
+M(\u1)// expected-warning {{incomplete universal character name; treating 
as '\' followed by identifier}}
+M(\u12)   // expected-warning {{incomplete universal character name; treating 
as '\' followed by identifier}}
+M(\u123)  // expected-warning {{incomplete universal character name; treating 
as '\' followed by identifier}}
+M(\u1234) // Okay
+M(\u12345)// Okay, two tokens (UCN followed by 5)
+
+M(\U1) // expected-warning {{incomplete universal character name; 
treating as '\' followed by identifier}}
+M(\U12)// expected-warning {{incomplete universal character name; 
treating as '\' followed by identifier}}
+M(\U123)   // expected-warning {{incomplete universal character name; 
treating as '\' followed by identifier}}
+M(\U1234)  // expected-warning {{incomplete universal character name; 
treating as '\' followed by identifier}} \
+  expected-note {{did you mean to use '\u'?}}
+M(\U12345) // expected-warning {{incomplete universal character name; 
treating as '\' followed by identifier}}
+M(\U123456)// expected-warning {{incomplete universal character name; 
treating as '\' followed by identifier}}
+M(\U1234567)   // expected-warning {{incomplete universal character name; 
treating as '\' followed by identifier}}
+M(\U12345678)  // Okay
+M(\U123456789) // Okay-ish, two tokens (valid-per-spec-but-actually-invalid 
UCN followed by 9)
+
+// C99 6.4.3p2:
+// A universal character name shall not specify a character whose short
+// identifier is less than 00A0 other than 0024 ($), 0040 (@), or 0060 (�), nor
+// one in the range D800 through DFFF inclusive.
+//
+// We use a python script to generate the test contents for the large ranges
+// without edge cases.
+// RUN: %python %S/n717.py >%t.inc
+// RUN: %clang_cc1 -verify -std=c99 -Wno-unicode-whitespace 
-Wno-unicode-homoglyph -Wno-unicode-zero-width 
-Wno-mathematical-notation-identifier-extension %t.inc
+
+// Now test the ones that should work. Note, these work in C17 and earlier but
+// are part of the basic character set in C23 and thus should be diagnosed in
+// that mode. They're valid in a character constant, but not valid in an
+// identifier, except for U+0024 which is allowed if -fdollars-in-identifiers
+// is enabled.
+// FIXME: These three should be handled the same way, and should be accepted
+// when dollar signs are allowed in identifiers, rather than rejected, see
+// GH87106.
+M(\u0024) // expected-error {{character '$' cannot be specified by a universal 
character name}}
+M(\U0024) // expected-error {{character '$' cannot be specified by a 
universal character name}}
+M($)
+
+// These should always be rejected because they're not valid identifier
+// characters.
+// FIXME: the diagnostic could be improved to make it clear this is an issue
+// with forming an identifier rather than a UCN.
+M(\u0040) // expected-error {{character '@' cannot be specified by a universal 
character name}}
+M(\u0060) // expected-error {{character '`' cannot be specified by a universal 
character name}}
+M(\U0040) // expected-error {{character '@' cannot be specified by a 
universal character name}}
+M(\U0060) // expected-error {{character '`' cannot be specified by a 
universal character name}}
+
+// These should always be accepted because they're a valid in a character
+// constant.
+M('\u0024')
+M('\u0040')
+M('\u0060')
+
+M('\U0024')
+M('\U0040')
+M('\U0060')
diff --git a/clang/test/C/C99/n717.py b/clang/test/C/C99/n717.py
new file mode 100644
index 00..8c02d336ff6f60
--- /dev/null
+++ b/clang/test/C/C99/n717.py
@@ -0,0 +1,39 @@
+print("#define M(arg)")
+
+def test(size):
+  Prefix = 'U' if size == 8 else 'u'
+  # [0x to 0x00A0) excluding [0x0020, 0x007F)
+  for val in [val for val in range(0x, 0x00A0) if val < 0x0020 or val >= 
0x007F]:
+ print(f'M(\\{Prefix}{val:0{size}X}) // expected-error universal 
character name refers to a control character')
+  print('')
+  
+  # [0x0020 to 0x007F), excluding 0x0024, 0x0040, and 0x0060
+  for v

[clang] [C99] Claim conformance to WG14 N717 (PR #87228)

2024-04-01 Thread via cfe-commits

github-actions[bot] wrote:




:warning: Python code formatter, darker found issues in your code. :warning:



You can test this locally with the following command:


``bash
darker --check --diff -r 
84299df301dc07ea83fa8378051103195c3a7c65...f8e130df9e602662444280346b71a82347ae8a29
 clang/test/C/C99/n717.py
``





View the diff from darker here.


``diff
--- n717.py 2024-04-01 11:27:32.00 +
+++ n717.py 2024-04-01 11:32:12.636120 +
@@ -1,29 +1,41 @@
 print("#define M(arg)")
 
+
 def test(size):
-  Prefix = 'U' if size == 8 else 'u'
-  # [0x to 0x00A0) excluding [0x0020, 0x007F)
-  for val in [val for val in range(0x, 0x00A0) if val < 0x0020 or val >= 
0x007F]:
- print(f'M(\\{Prefix}{val:0{size}X}) // expected-error universal 
character name refers to a control character')
-  print('')
-  
-  # [0x0020 to 0x007F), excluding 0x0024, 0x0040, and 0x0060
-  for val in [val for val in range(0x0020, 0x007F) if val != 0x0024 and val != 
0x0040 and val != 0x0060]:
- print(f"M(\\{Prefix}{val:0{size}X}) // expected-error character 
'{chr(val)}' cannot be specified by a universal character name")
-  print('')
-  
-  # [0xD800 to 0xDFFF]
-  for val in range(0xD800, 0xDFFF + 1):
-print(f'M(\\{Prefix}{val:0{size}X}) // expected-error invalid 
universal character')
-  print('')
-  
-  # Everything in this range should be accepted, though it may produce a
-  # warning diagnostic for things like homoglyphs, whitespace, etc.
-  for val in range(0x00A1, 0xD800):
-print(f'M(\\{Prefix}{val:0{size}X})')
-  print('')
+Prefix = "U" if size == 8 else "u"
+# [0x to 0x00A0) excluding [0x0020, 0x007F)
+for val in [val for val in range(0x, 0x00A0) if val < 0x0020 or val >= 
0x007F]:
+print(
+f"M(\\{Prefix}{val:0{size}X}) // expected-error universal 
character name refers to a control character"
+)
+print("")
+
+# [0x0020 to 0x007F), excluding 0x0024, 0x0040, and 0x0060
+for val in [
+val
+for val in range(0x0020, 0x007F)
+if val != 0x0024 and val != 0x0040 and val != 0x0060
+]:
+print(
+f"M(\\{Prefix}{val:0{size}X}) // expected-error character 
'{chr(val)}' cannot be specified by a universal character name"
+)
+print("")
+
+# [0xD800 to 0xDFFF]
+for val in range(0xD800, 0xDFFF + 1):
+print(
+f"M(\\{Prefix}{val:0{size}X}) // expected-error invalid 
universal character"
+)
+print("")
+
+# Everything in this range should be accepted, though it may produce a
+# warning diagnostic for things like homoglyphs, whitespace, etc.
+for val in range(0x00A1, 0xD800):
+print(f"M(\\{Prefix}{val:0{size}X})")
+print("")
+
 
 # Print \u tests
 test(4)
 # Print \U tests
 test(8)
@@ -32,8 +44,8 @@
 # within the valid (short) range.
 # This is disabled because enabling the test 1) requires using L because u and
 # U don't exist until C11, 2) is questionable in terms of value because the
 # code points could be different if L isn't using a Unicode encoding, and 3)
 # this addition to the test adds 10x the execution time when running the test.
-#for val in range(0x00A1, 0xD800):
+# for val in range(0x00A1, 0xD800):
 #  print(f"_Static_assert(L'\\u{val:04X}' == L'\\U{val:08X}', \"\");")
-#print('')
+# print('')

``




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


[clang] [llvm] MIPS: Support -m(no-)unaligned-access for r6 (PR #85174)

2024-04-01 Thread Nathan Sidwell via cfe-commits

urnathan wrote:

#65742 is committed, so MIPS' TargetInfo will need adjusting to propagate the 
unaligned capability. See 7df79ababee8

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


[clang] [clang][dataflow] Refactor `widen` API to be explicit about change effect. (PR #87233)

2024-04-01 Thread Yitzhak Mandelbaum via cfe-commits

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

The previous API relied on pointer equality of inputs and outputs to signal
whether a change occured. This was too subtle and led to bugs in practice. It
was also very limiting: the override could not return an equivalent (but not
identical) value.


>From 6889df911a11fc5c27149f138176166aef3e1f73 Mon Sep 17 00:00:00 2001
From: Yitzhak Mandelbaum 
Date: Mon, 1 Apr 2024 12:13:39 +
Subject: [PATCH] [clang][dataflow] Refactor `widen` API to be explicit about
 change effect.

The previous API relied on pointer equality of inputs and outputs to signal
whether a change occured. This was too subtle and led to bugs in practice. It
was also very limiting: the override could not return an equivalent (but not
identical) value.
---
 .../FlowSensitive/DataflowEnvironment.h   | 43 +--
 .../FlowSensitive/DataflowEnvironment.cpp | 42 ++
 2 files changed, 53 insertions(+), 32 deletions(-)

diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index c30bccd06674a4..8e4e846e594f5b 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -97,6 +97,16 @@ class Environment {
   const Value &Val2, const Environment &Env2,
   Value &JoinedVal, Environment &JoinedEnv) {}
 
+/// The result of the `widen` operation.
+struct WidenResult {
+  /// Non-null pointer to a potentially widened version of the widening
+  /// input.
+  Value *V;
+  /// Whether `V` represents a "change" (that is, a different value) with
+  /// respect to the previous value in the sequence.
+  LatticeJoinEffect Effect;
+};
+
 /// This function may widen the current value -- replace it with an
 /// approximation that can reach a fixed point more quickly than iterated
 /// application of the transfer function alone. The previous value is
@@ -104,14 +114,17 @@ class Environment {
 /// serve as a comparison operation, by indicating whether the widened 
value
 /// is equivalent to the previous value.
 ///
-/// Returns either:
-///
-///   `nullptr`, if this value is not of interest to the model, or
-///
-///   `&Prev`, if the widened value is equivalent to `Prev`, or
-///
-///   A non-null value that approximates `Current`. `Prev` is available to
-///   inform the chosen approximation.
+/// Returns one of the folowing:
+/// *  `std::nullopt`, if this value is not of interest to the
+/// model.
+/// *  A `WidenResult` with:
+///*  A non-null `Value *` that points either to `Current` or a widened
+///   version of `Current`. This value must be consistent with
+///   the flow condition of `CurrentEnv`. We particularly caution
+///   against using `Prev`, which is rarely consistent.
+///*  A `LatticeJoinEffect` indicating whether the value should be
+///   considered a new value (`Changed`) or one *equivalent* (if not
+///   necessarily equal) to `Prev` (`Unchanged`).
 ///
 /// `PrevEnv` and `CurrentEnv` can be used to query child values and path
 /// condition implications of `Prev` and `Current`, respectively.
@@ -122,17 +135,19 @@ class Environment {
 ///
 ///  `Prev` and `Current` must be assigned to the same storage location in
 ///  `PrevEnv` and `CurrentEnv`, respectively.
-virtual Value *widen(QualType Type, Value &Prev, const Environment 
&PrevEnv,
- Value &Current, Environment &CurrentEnv) {
+virtual std::optional widen(QualType Type, Value &Prev,
+ const Environment &PrevEnv,
+ Value &Current,
+ Environment &CurrentEnv) {
   // The default implementation reduces to just comparison, since 
comparison
   // is required by the API, even if no widening is performed.
   switch (compare(Type, Prev, PrevEnv, Current, CurrentEnv)) {
+case ComparisonResult::Unknown:
+  return std::nullopt;
 case ComparisonResult::Same:
-  return &Prev;
+  return WidenResult{&Current, LatticeJoinEffect::Unchanged};
 case ComparisonResult::Different:
-  return &Current;
-case ComparisonResult::Unknown:
-  return nullptr;
+  return WidenResult{&Current, LatticeJoinEffect::Changed};
   }
   llvm_unreachable("all cases in switch covered");
 }
diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index f729d676dd0de8..d41f03262ecf4c 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/An

[clang] [clang][dataflow] Refactor `widen` API to be explicit about change effect. (PR #87233)

2024-04-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Yitzhak Mandelbaum (ymand)


Changes

The previous API relied on pointer equality of inputs and outputs to signal
whether a change occured. This was too subtle and led to bugs in practice. It
was also very limiting: the override could not return an equivalent (but not
identical) value.


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


2 Files Affected:

- (modified) clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
(+29-14) 
- (modified) clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (+24-18) 


``diff
diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index c30bccd06674a4..8e4e846e594f5b 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -97,6 +97,16 @@ class Environment {
   const Value &Val2, const Environment &Env2,
   Value &JoinedVal, Environment &JoinedEnv) {}
 
+/// The result of the `widen` operation.
+struct WidenResult {
+  /// Non-null pointer to a potentially widened version of the widening
+  /// input.
+  Value *V;
+  /// Whether `V` represents a "change" (that is, a different value) with
+  /// respect to the previous value in the sequence.
+  LatticeJoinEffect Effect;
+};
+
 /// This function may widen the current value -- replace it with an
 /// approximation that can reach a fixed point more quickly than iterated
 /// application of the transfer function alone. The previous value is
@@ -104,14 +114,17 @@ class Environment {
 /// serve as a comparison operation, by indicating whether the widened 
value
 /// is equivalent to the previous value.
 ///
-/// Returns either:
-///
-///   `nullptr`, if this value is not of interest to the model, or
-///
-///   `&Prev`, if the widened value is equivalent to `Prev`, or
-///
-///   A non-null value that approximates `Current`. `Prev` is available to
-///   inform the chosen approximation.
+/// Returns one of the folowing:
+/// *  `std::nullopt`, if this value is not of interest to the
+/// model.
+/// *  A `WidenResult` with:
+///*  A non-null `Value *` that points either to `Current` or a widened
+///   version of `Current`. This value must be consistent with
+///   the flow condition of `CurrentEnv`. We particularly caution
+///   against using `Prev`, which is rarely consistent.
+///*  A `LatticeJoinEffect` indicating whether the value should be
+///   considered a new value (`Changed`) or one *equivalent* (if not
+///   necessarily equal) to `Prev` (`Unchanged`).
 ///
 /// `PrevEnv` and `CurrentEnv` can be used to query child values and path
 /// condition implications of `Prev` and `Current`, respectively.
@@ -122,17 +135,19 @@ class Environment {
 ///
 ///  `Prev` and `Current` must be assigned to the same storage location in
 ///  `PrevEnv` and `CurrentEnv`, respectively.
-virtual Value *widen(QualType Type, Value &Prev, const Environment 
&PrevEnv,
- Value &Current, Environment &CurrentEnv) {
+virtual std::optional widen(QualType Type, Value &Prev,
+ const Environment &PrevEnv,
+ Value &Current,
+ Environment &CurrentEnv) {
   // The default implementation reduces to just comparison, since 
comparison
   // is required by the API, even if no widening is performed.
   switch (compare(Type, Prev, PrevEnv, Current, CurrentEnv)) {
+case ComparisonResult::Unknown:
+  return std::nullopt;
 case ComparisonResult::Same:
-  return &Prev;
+  return WidenResult{&Current, LatticeJoinEffect::Unchanged};
 case ComparisonResult::Different:
-  return &Current;
-case ComparisonResult::Unknown:
-  return nullptr;
+  return WidenResult{&Current, LatticeJoinEffect::Changed};
   }
   llvm_unreachable("all cases in switch covered");
 }
diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index f729d676dd0de8..d41f03262ecf4c 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -166,17 +166,19 @@ static Value *joinDistinctValues(QualType Type, Value 
&Val1,
   return JoinedVal;
 }
 
-// When widening does not change `Current`, return value will equal `&Prev`.
-static Value &widenDistinctValues(QualType Type, Value &Prev,
-  const Environment &PrevEnv, Value &Current,
-

[clang] [Clang] Fix __is_array returning true for zero-sized arrays (PR #86652)

2024-04-01 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

> As I've just commented at https://gcc.gnu.org/bugzilla/show_bug.cgi?id=114479 
> the `__is_array` intrinsic exists to optimize `std::is_array` and so should 
> match its existing behaviour. If you want to change the behaviour of 
> `std::is_array` then please do so via an LWG issue, e.g. requesting 
> clarification of the behaviour for `T[0]`.
> 
> An optimization to speed up compilation of `std::is_array` should not dictate 
> its behaviour.

Errr, I think there's some circular logic here perhaps:

> [dcl.array] says that for T[N] the value "N specifies the array bound, i.e., 
> the
number of elements in the array; N shall be greater than zero."
>
> So T[0] is not a valid array type.

Except `T[0]` is a valid array type because it's supported as a language 
extension in Clang and GCC; that's the whole reason you can spell `T[0]` at all.

This boils down to a fundamental question: what makes something an array type 
in the first place? Is it the declaration syntax or is it the semantics? If 
it's declaration syntax, then `T[0]` is clearly an array type. If it's 
semantics, then `T[0]` is not an array type but `std::vector` is. 
Personally, I think the declaration syntax is what makes something an array 
type per https://eel.is/c++draft/dcl.array#1 saying "a declaration of the 
form". Yes, it says the size shall not be zero, but that's the bit we've 
extended, so it's circular to say "the standard says zero isn't allowed and 
therefore the library behavior is to return false from std::is_array".

So I think I'm arguing for an LWG issue.

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


[clang] [clang][dataflow] Refactor `widen` API to be explicit about change effect. (PR #87233)

2024-04-01 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 a1a8bb1d3ae9a535526aba9514e87f76e2d040fa 
6889df911a11fc5c27149f138176166aef3e1f73 -- 
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index 8e4e846e59..0a37d9d68e 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -142,12 +142,12 @@ public:
   // The default implementation reduces to just comparison, since 
comparison
   // is required by the API, even if no widening is performed.
   switch (compare(Type, Prev, PrevEnv, Current, CurrentEnv)) {
-case ComparisonResult::Unknown:
-  return std::nullopt;
-case ComparisonResult::Same:
-  return WidenResult{&Current, LatticeJoinEffect::Unchanged};
-case ComparisonResult::Different:
-  return WidenResult{&Current, LatticeJoinEffect::Changed};
+  case ComparisonResult::Unknown:
+return std::nullopt;
+  case ComparisonResult::Same:
+return WidenResult{&Current, LatticeJoinEffect::Unchanged};
+  case ComparisonResult::Different:
+return WidenResult{&Current, LatticeJoinEffect::Changed};
   }
   llvm_unreachable("all cases in switch covered");
 }
diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index d41f03262e..8ae51b7cdb 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -170,9 +170,10 @@ namespace {
 using WidenResult = Environment::ValueModel::WidenResult;
 }
 
-static WidenResult widenDistinctValues(
-QualType Type, Value &Prev, const Environment &PrevEnv, Value &Current,
-Environment &CurrentEnv, Environment::ValueModel &Model) {
+static WidenResult widenDistinctValues(QualType Type, Value &Prev,
+   const Environment &PrevEnv,
+   Value &Current, Environment &CurrentEnv,
+   Environment::ValueModel &Model) {
   // Boolean-model widening.
   if (auto *PrevBool = dyn_cast(&Prev)) {
 if (isa(Prev))

``




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


[clang] [clang][dataflow] Refactor `widen` API to be explicit about change effect. (PR #87233)

2024-04-01 Thread Yitzhak Mandelbaum via cfe-commits

https://github.com/ymand updated https://github.com/llvm/llvm-project/pull/87233

>From b7f63ed7ca3c503f55eccc215f0a66368e2c5e5e Mon Sep 17 00:00:00 2001
From: Yitzhak Mandelbaum 
Date: Mon, 1 Apr 2024 12:13:39 +
Subject: [PATCH] [clang][dataflow] Refactor `widen` API to be explicit about
 change effect.

The previous API relied on pointer equality of inputs and outputs to signal
whether a change occured. This was too subtle and led to bugs in practice. It
was also very limiting: the override could not return an equivalent (but not
identical) value.
---
 .../FlowSensitive/DataflowEnvironment.h   | 47 ---
 .../FlowSensitive/DataflowEnvironment.cpp | 43 ++---
 2 files changed, 56 insertions(+), 34 deletions(-)

diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index c30bccd06674a4..0a37d9d68e2898 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -97,6 +97,16 @@ class Environment {
   const Value &Val2, const Environment &Env2,
   Value &JoinedVal, Environment &JoinedEnv) {}
 
+/// The result of the `widen` operation.
+struct WidenResult {
+  /// Non-null pointer to a potentially widened version of the widening
+  /// input.
+  Value *V;
+  /// Whether `V` represents a "change" (that is, a different value) with
+  /// respect to the previous value in the sequence.
+  LatticeJoinEffect Effect;
+};
+
 /// This function may widen the current value -- replace it with an
 /// approximation that can reach a fixed point more quickly than iterated
 /// application of the transfer function alone. The previous value is
@@ -104,14 +114,17 @@ class Environment {
 /// serve as a comparison operation, by indicating whether the widened 
value
 /// is equivalent to the previous value.
 ///
-/// Returns either:
-///
-///   `nullptr`, if this value is not of interest to the model, or
-///
-///   `&Prev`, if the widened value is equivalent to `Prev`, or
-///
-///   A non-null value that approximates `Current`. `Prev` is available to
-///   inform the chosen approximation.
+/// Returns one of the folowing:
+/// *  `std::nullopt`, if this value is not of interest to the
+/// model.
+/// *  A `WidenResult` with:
+///*  A non-null `Value *` that points either to `Current` or a widened
+///   version of `Current`. This value must be consistent with
+///   the flow condition of `CurrentEnv`. We particularly caution
+///   against using `Prev`, which is rarely consistent.
+///*  A `LatticeJoinEffect` indicating whether the value should be
+///   considered a new value (`Changed`) or one *equivalent* (if not
+///   necessarily equal) to `Prev` (`Unchanged`).
 ///
 /// `PrevEnv` and `CurrentEnv` can be used to query child values and path
 /// condition implications of `Prev` and `Current`, respectively.
@@ -122,17 +135,19 @@ class Environment {
 ///
 ///  `Prev` and `Current` must be assigned to the same storage location in
 ///  `PrevEnv` and `CurrentEnv`, respectively.
-virtual Value *widen(QualType Type, Value &Prev, const Environment 
&PrevEnv,
- Value &Current, Environment &CurrentEnv) {
+virtual std::optional widen(QualType Type, Value &Prev,
+ const Environment &PrevEnv,
+ Value &Current,
+ Environment &CurrentEnv) {
   // The default implementation reduces to just comparison, since 
comparison
   // is required by the API, even if no widening is performed.
   switch (compare(Type, Prev, PrevEnv, Current, CurrentEnv)) {
-case ComparisonResult::Same:
-  return &Prev;
-case ComparisonResult::Different:
-  return &Current;
-case ComparisonResult::Unknown:
-  return nullptr;
+  case ComparisonResult::Unknown:
+return std::nullopt;
+  case ComparisonResult::Same:
+return WidenResult{&Current, LatticeJoinEffect::Unchanged};
+  case ComparisonResult::Different:
+return WidenResult{&Current, LatticeJoinEffect::Changed};
   }
   llvm_unreachable("all cases in switch covered");
 }
diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index f729d676dd0de8..8ae51b7cdb444d 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -166,17 +166,20 @@ static Value *joinDistinctValues(QualType Type, Value 
&Val1,
   return JoinedVal;
 }
 
-// When widening does not c

[clang] [Clang] Fix __is_array returning true for zero-sized arrays (PR #86652)

2024-04-01 Thread Jonathan Wakely via cfe-commits

jwakely wrote:

Last time I checked, neither GCC nor Clang allowed T[0] to match a partial 
specialization for `is_array` so the extension isn't very well extended :)

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


[clang] [Clang] Fix __is_array returning true for zero-sized arrays (PR #86652)

2024-04-01 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

> Last time I checked, neither GCC nor Clang allowed T[0] to match a partial 
> specialization for `is_array` so the extension isn't very well extended 
> :)

Oh, I agree, I am learning to loathe this extension the more I look into this. 
Did you see this lovely bit:

> Oh wow, and it gets even more surprising... adding a zero-length array to a 
> structure reduces the size of the structure (in C++): 
> https://godbolt.org/z/5E4YsT1Ye

But that's why I'm asking questions about what we *should* be doing with the 
feature overall. As it currently stands, this extension seems like it is broken 
in C++ in multiple ways. Fixing a tiny corner of it is fine, but I'd like to 
know what the overall big picture is so we can know whether the tiny corner 
changes fit or not. We could fix this by changing partial specializations to 
care about zero-sized arrays, too. (Personally, I would love to "fix" this by 
deprecating the extension as the only justification for it I've been able to 
dig up is as a hack for flexible arrays -- deprecating this extension outside 
of GNU89 mode has some appeal, barring other information about its value.)

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


[clang] [RFC][Clang] Enable custom type checking for printf (PR #86801)

2024-04-01 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

> > I looked at the OpenCL spec for C standard library support and was 
> > surprised that 1) it's only talking about C99 so it's unclear what happens 
> > for C11 (clause 6 says "This document describes the modifications and 
> > restrictions to C99 and C11 in OpenCL C" but 6.11 only talks about C99 
> > headers and leaves `iso646.h`, `math.h`, `stdbool.h`, `stddef.h`, (all in 
> > C99) as well as `stdalign.h`, `stdatomic.h`, `stdnoreturn.h`, `threads.h`, 
> > and `uchar.h` available?), and 2) OpenCL's `printf` is not really the same 
> > function as C's `printf` 
> > (https://registry.khronos.org/OpenCL/specs/3.0-unified/html/OpenCL_C.html#differences-between-opencl-c-and-c99-printf).
> > #1 is probably more of an oversight than anything, at least with the C11 
> > headers. So maybe this isn't a super slippery slope, but maybe C23 will 
> > change that (I can imagine `stdbit.h` being of use in OpenCL for 
> > bit-bashing operations). However, the fact that the builtin isn't really 
> > `printf` but is `printf`-like makes me think we should make it a separate 
> > builtin to avoid surprises (we do diagnostics based on builtin IDs and we 
> > have special checking logic that we perhaps should be exempting in some 
> > cases).
> 
> Understood. Then I propose the following.
> 
> 1. Currently Builtin TableGen does not seem to support specifying lang 
> address spaces in function prototypes. this needs to be implemented first if 
> not already in development.
> 
> 2. We could have two new macro variants probably named "OCL_BUILTIN" and 
> "OCL_LIB_BUILTIN" which will take the ID's of the form 
> "BI_OCL##". we would also need corresponding TableGen classes 
> (probably named similar to the macros) which can expose such overloaded 
> prototypes when required.
> 
> 
> How does this sound ?

I think that sounds like a reasonable way forward, thank you!

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


[clang] [clang][dataflow] Refactor `widen` API to be explicit about change effect. (PR #87233)

2024-04-01 Thread Yitzhak Mandelbaum via cfe-commits

https://github.com/ymand updated https://github.com/llvm/llvm-project/pull/87233

>From d8d875271bd47b71701143afb06ea654546e2b7c Mon Sep 17 00:00:00 2001
From: Yitzhak Mandelbaum 
Date: Mon, 1 Apr 2024 12:13:39 +
Subject: [PATCH] [clang][dataflow] Refactor `widen` API to be explicit about
 change effect.

The previous API relied on pointer equality of inputs and outputs to signal
whether a change occured. This was too subtle and led to bugs in practice. It
was also very limiting: the override could not return an equivalent (but not
identical) value.
---
 .../FlowSensitive/DataflowEnvironment.h   | 47 +++---
 .../FlowSensitive/DataflowEnvironment.cpp | 43 ++---
 .../TypeErasedDataflowAnalysisTest.cpp| 48 +++
 3 files changed, 104 insertions(+), 34 deletions(-)

diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index c30bccd06674a4..0a37d9d68e2898 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -97,6 +97,16 @@ class Environment {
   const Value &Val2, const Environment &Env2,
   Value &JoinedVal, Environment &JoinedEnv) {}
 
+/// The result of the `widen` operation.
+struct WidenResult {
+  /// Non-null pointer to a potentially widened version of the widening
+  /// input.
+  Value *V;
+  /// Whether `V` represents a "change" (that is, a different value) with
+  /// respect to the previous value in the sequence.
+  LatticeJoinEffect Effect;
+};
+
 /// This function may widen the current value -- replace it with an
 /// approximation that can reach a fixed point more quickly than iterated
 /// application of the transfer function alone. The previous value is
@@ -104,14 +114,17 @@ class Environment {
 /// serve as a comparison operation, by indicating whether the widened 
value
 /// is equivalent to the previous value.
 ///
-/// Returns either:
-///
-///   `nullptr`, if this value is not of interest to the model, or
-///
-///   `&Prev`, if the widened value is equivalent to `Prev`, or
-///
-///   A non-null value that approximates `Current`. `Prev` is available to
-///   inform the chosen approximation.
+/// Returns one of the folowing:
+/// *  `std::nullopt`, if this value is not of interest to the
+/// model.
+/// *  A `WidenResult` with:
+///*  A non-null `Value *` that points either to `Current` or a widened
+///   version of `Current`. This value must be consistent with
+///   the flow condition of `CurrentEnv`. We particularly caution
+///   against using `Prev`, which is rarely consistent.
+///*  A `LatticeJoinEffect` indicating whether the value should be
+///   considered a new value (`Changed`) or one *equivalent* (if not
+///   necessarily equal) to `Prev` (`Unchanged`).
 ///
 /// `PrevEnv` and `CurrentEnv` can be used to query child values and path
 /// condition implications of `Prev` and `Current`, respectively.
@@ -122,17 +135,19 @@ class Environment {
 ///
 ///  `Prev` and `Current` must be assigned to the same storage location in
 ///  `PrevEnv` and `CurrentEnv`, respectively.
-virtual Value *widen(QualType Type, Value &Prev, const Environment 
&PrevEnv,
- Value &Current, Environment &CurrentEnv) {
+virtual std::optional widen(QualType Type, Value &Prev,
+ const Environment &PrevEnv,
+ Value &Current,
+ Environment &CurrentEnv) {
   // The default implementation reduces to just comparison, since 
comparison
   // is required by the API, even if no widening is performed.
   switch (compare(Type, Prev, PrevEnv, Current, CurrentEnv)) {
-case ComparisonResult::Same:
-  return &Prev;
-case ComparisonResult::Different:
-  return &Current;
-case ComparisonResult::Unknown:
-  return nullptr;
+  case ComparisonResult::Unknown:
+return std::nullopt;
+  case ComparisonResult::Same:
+return WidenResult{&Current, LatticeJoinEffect::Unchanged};
+  case ComparisonResult::Different:
+return WidenResult{&Current, LatticeJoinEffect::Changed};
   }
   llvm_unreachable("all cases in switch covered");
 }
diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index f729d676dd0de8..8ae51b7cdb444d 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -166,17 +166,20 @@ static Value *joinDistinctValues(QualType Ty

[clang] [clang] Fix bitfield access unit for vbase corner case (PR #87238)

2024-04-01 Thread Nathan Sidwell via cfe-commits

https://github.com/urnathan created 
https://github.com/llvm/llvm-project/pull/87238

This fixes #87227 My change to bitfield access unit allocation (#65742) causes 
an ICE for a corner case of vbase allocation: a class where an unshared (i.e. 
not the nearly-empty base optimization) vbase is placed below nvsize. 
Unfortunately, although there was a testcase for such a class layout, it didn't 
have the immediately preceding bitfield -- the reason the scissor needs to be 
correct.

The fix is to break out the scissor calculation from `accumulateVbases`, and 
have `allocateBitfields` be aware it is creating either the base subobject, or 
the complete object. Then it can call the scissor calculator to get the 
appropriate upper bound. The scissor calculation can cause a base walk, I 
thought it best to cache the result in `allocateBitfields`, as we can reach 
that point multiple times with unfortunately-sized bitfield spans.

In breaking out the scissor calculation, I discovered a couple more member fns 
that could be const qualified -- as before do you want that as a separate PR?

>From 3b0bfce77d6d70bc35316484b39bb83123b8a583 Mon Sep 17 00:00:00 2001
From: Nathan Sidwell 
Date: Sun, 31 Mar 2024 11:11:13 -0400
Subject: [PATCH] [clang] Fix bitfield access unit for vbase corner case

We must account for unshared vbases that are allocated below nvsize.
---
 clang/lib/CodeGen/CGRecordLayoutBuilder.cpp   |  57 +++---
 .../test/CodeGenCXX/bitfield-access-tail.cpp  | 104 --
 2 files changed, 113 insertions(+), 48 deletions(-)

diff --git a/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp 
b/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
index e32023aeac1e6f..634a55fec5182e 100644
--- a/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
+++ b/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
@@ -185,9 +185,10 @@ struct CGRecordLowering {
   /// Lowers an ASTRecordLayout to a llvm type.
   void lower(bool NonVirtualBaseType);
   void lowerUnion(bool isNoUniqueAddress);
-  void accumulateFields();
+  void accumulateFields(bool isNonVirtualBaseType);
   RecordDecl::field_iterator
-  accumulateBitFields(RecordDecl::field_iterator Field,
+  accumulateBitFields(bool isNonVirtualBaseType,
+  RecordDecl::field_iterator Field,
   RecordDecl::field_iterator FieldEnd);
   void computeVolatileBitfields();
   void accumulateBases();
@@ -195,8 +196,10 @@ struct CGRecordLowering {
   void accumulateVBases();
   /// Recursively searches all of the bases to find out if a vbase is
   /// not the primary vbase of some base class.
-  bool hasOwnStorage(const CXXRecordDecl *Decl, const CXXRecordDecl *Query);
+  bool hasOwnStorage(const CXXRecordDecl *Decl,
+ const CXXRecordDecl *Query) const;
   void calculateZeroInit();
+  CharUnits calculateTailClippingOffset(bool isNonVirtualBaseType) const;
   /// Lowers bitfield storage types to I8 arrays for bitfields with tail
   /// padding that is or can potentially be used.
   void clipTailPadding();
@@ -287,7 +290,7 @@ void CGRecordLowering::lower(bool NVBaseType) {
 computeVolatileBitfields();
 return;
   }
-  accumulateFields();
+  accumulateFields(NVBaseType);
   // RD implies C++.
   if (RD) {
 accumulateVPtrs();
@@ -378,12 +381,12 @@ void CGRecordLowering::lowerUnion(bool isNoUniqueAddress) 
{
 Packed = true;
 }
 
-void CGRecordLowering::accumulateFields() {
+void CGRecordLowering::accumulateFields(bool isNonVirtualBaseType) {
   for (RecordDecl::field_iterator Field = D->field_begin(),
   FieldEnd = D->field_end();
Field != FieldEnd;) {
 if (Field->isBitField()) {
-  Field = accumulateBitFields(Field, FieldEnd);
+  Field = accumulateBitFields(isNonVirtualBaseType, Field, FieldEnd);
   assert((Field == FieldEnd || !Field->isBitField()) &&
  "Failed to accumulate all the bitfields");
 } else if (Field->isZeroSize(Context)) {
@@ -404,9 +407,12 @@ void CGRecordLowering::accumulateFields() {
 }
 
 // Create members for bitfields. Field is a bitfield, and FieldEnd is the end
-// iterator of the record. Return the first non-bitfield encountered.
+// iterator of the record. Return the first non-bitfield encountered.  We need
+// to know whether this is the base or complete layout, as virtual bases could
+// affect the upper bound of bitfield access unit allocation.
 RecordDecl::field_iterator
-CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field,
+CGRecordLowering::accumulateBitFields(bool isNonVirtualBaseType,
+  RecordDecl::field_iterator Field,
   RecordDecl::field_iterator FieldEnd) {
   if (isDiscreteBitFieldABI()) {
 // Run stores the first element of the current run of bitfields. FieldEnd 
is
@@ -505,6 +511,10 @@ 
CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field,
   bitsToCharUnits(Context.getTargetInfo().getRegisterWidth())

[clang] [clang] Move tailclipping to bitfield allocation (PR #87090)

2024-04-01 Thread Nathan Sidwell via cfe-commits

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


[clang] [clang] Factor out OpenACC part of `Sema` (PR #84184)

2024-04-01 Thread Aaron Ballman via cfe-commits

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

LGTM, but I think the next steps are two-fold: add a second `Sema` class for 
something else (perhaps OpenMP?) and add a base class for accessing commonly 
used functionality (`getASTContext()`, `Diag()`, etc).

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


[clang] [clang] Factor out OpenACC part of `Sema` (PR #84184)

2024-04-01 Thread Vlad Serebrennikov via cfe-commits

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

>From 23f4208fb9978370f59cae16db0747acb3e2c906 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Wed, 6 Mar 2024 18:01:35 +0300
Subject: [PATCH 1/7] [clang] Factor out OpenACC part of `Sema`

This patch moves OpenACC parts of `Sema` into a separate class `SemaOpenACC` 
that is placed in a separate header `Sema/SemaOpenACC.h`. This patch is 
intended to be a model of factoring things out of `Sema`, so I picked a small 
OpenACC part.

Goals are the following:
1) Split `Sema` into manageable parts.
2) Make dependencies between parts visible.
3) Improve Clang development cycle by avoiding recompiling unrelated parts of 
the compiler.
4) Avoid compile-time regressions.
5) Avoid notational regressions in the code that uses Sema.
---
 clang/include/clang/Sema/Sema.h| 77 --
 clang/include/clang/Sema/SemaOpenACC.h | 68 +++
 clang/lib/Parse/ParseOpenACC.cpp   | 22 
 clang/lib/Sema/Sema.cpp|  4 +-
 clang/lib/Sema/SemaOpenACC.cpp | 44 ---
 clang/lib/Sema/TreeTransform.h | 11 ++--
 6 files changed, 137 insertions(+), 89 deletions(-)
 create mode 100644 clang/include/clang/Sema/SemaOpenACC.h

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index f3d3a57104ee07..932676c52b1f30 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -183,6 +183,7 @@ class Preprocessor;
 class PseudoDestructorTypeStorage;
 class PseudoObjectExpr;
 class QualType;
+class SemaOpenACC;
 class StandardConversionSequence;
 class Stmt;
 class StringLiteral;
@@ -466,9 +467,8 @@ class Sema final {
   // 37. Name Lookup for RISC-V Vector Intrinsic (SemaRISCVVectorLookup.cpp)
   // 38. CUDA (SemaCUDA.cpp)
   // 39. HLSL Constructs (SemaHLSL.cpp)
-  // 40. OpenACC Constructs (SemaOpenACC.cpp)
-  // 41. OpenMP Directives and Clauses (SemaOpenMP.cpp)
-  // 42. SYCL Constructs (SemaSYCL.cpp)
+  // 40. OpenMP Directives and Clauses (SemaOpenMP.cpp)
+  // 41. SYCL Constructs (SemaSYCL.cpp)
 
   /// \name Semantic Analysis
   /// Implementations are in Sema.cpp
@@ -1200,6 +1200,27 @@ class Sema final {
   //
   //
 
+  /// \name Sema Components
+  /// Parts of Sema
+  ///@{
+
+  // Just in this section, private members are followed by public, because
+  // C++ requires us to create (private) objects before (public) references.
+
+private:
+  std::unique_ptr OpenACCPtr;
+
+public:
+  SemaOpenACC &OpenACC;
+
+  ///@}
+
+  //
+  //
+  // -
+  //
+  //
+
   /// \name C++ Access Control
   /// Implementations are in SemaAccess.cpp
   ///@{
@@ -13309,56 +13330,6 @@ class Sema final {
   //
   //
 
-  /// \name OpenACC Constructs
-  /// Implementations are in SemaOpenACC.cpp
-  ///@{
-
-public:
-  /// Called after parsing an OpenACC Clause so that it can be checked.
-  bool ActOnOpenACCClause(OpenACCClauseKind ClauseKind,
-  SourceLocation StartLoc);
-
-  /// Called after the construct has been parsed, but clauses haven't been
-  /// parsed.  This allows us to diagnose not-implemented, as well as set up 
any
-  /// state required for parsing the clauses.
-  void ActOnOpenACCConstruct(OpenACCDirectiveKind K, SourceLocation StartLoc);
-
-  /// Called after the directive, including its clauses, have been parsed and
-  /// parsing has consumed the 'annot_pragma_openacc_end' token. This DOES
-  /// happen before any associated declarations or statements have been parsed.
-  /// This function is only called when we are parsing a 'statement' context.
-  bool ActOnStartOpenACCStmtDirective(OpenACCDirectiveKind K,
-  SourceLocation StartLoc);
-
-  /// Called after the directive, including its clauses, have been parsed and
-  /// parsing has consumed the 'annot_pragma_openacc_end' token. This DOES
-  /// happen before any associated declarations or statements have been parsed.
-  /// This function is only called when we are parsing a 'Decl' context.
-  bool ActOnStartOpenACCDeclDirective(OpenACCDirectiveKind K,
-  SourceLocation StartLoc);
-  /// Called when we encounter an associated statement for our construct, this
-  /// should check legality of the statement as it appertains to this 
Construct.
-  StmtResult ActOnOpenACCAssociatedStmt(OpenACCDirectiveKind K,
-StmtResult AssocStmt);
-
-  /// Called after the directive has been completely parsed, including the
-  /// declaration group or associated statement.
-  StmtResult ActOnEndOpenACCStmtDirective(OpenACCDirectiveKind K,
-  SourceLocation StartLoc,
-  SourceLocation EndLoc,
-  StmtResult AssocStmt);
-  /// Called after the directive has 

[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-01 Thread Erich Keane via cfe-commits

https://github.com/erichkeane commented:

A quick few things I noticed, not nearly a thorough review.

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


[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-01 Thread Erich Keane via cfe-commits


@@ -1980,6 +1981,23 @@ static void handleWeakRefAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
 }
 
+// Mark alias/ifunc target as used. For C++, we look up the demangled name
+// ignoring parameters. This should handle the majority of use cases while
+// leaveing false positives for namespace scope names and false negatives in
+// the presence of overloads.
+static void markUsedForAliasOrIfunc(Sema &S, Decl *D, const ParsedAttr &AL,
+StringRef Str) {
+  char *Demangled = llvm::itaniumDemangle(Str, /*ParseParams=*/false);

erichkeane wrote:

We can't really assume 'itanium demangle' here, this could be a non-itanium 
build.

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


[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-01 Thread Erich Keane via cfe-commits


@@ -1980,6 +1981,23 @@ static void handleWeakRefAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
 }
 
+// Mark alias/ifunc target as used. For C++, we look up the demangled name
+// ignoring parameters. This should handle the majority of use cases while
+// leaveing false positives for namespace scope names and false negatives in
+// the presence of overloads.
+static void markUsedForAliasOrIfunc(Sema &S, Decl *D, const ParsedAttr &AL,
+StringRef Str) {
+  char *Demangled = llvm::itaniumDemangle(Str, /*ParseParams=*/false);
+  if (Demangled)
+Str = Demangled;
+  const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
+  LookupResult LR(S, target, Sema::LookupOrdinaryName);
+  if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
+for (NamedDecl *ND : LR)
+  ND->markUsed(S.Context);

erichkeane wrote:

This loop doesn't seem quite right either.  First, we need to ensure we're only 
marking 'functions' as used, not all possible named decls I think.  

Second, we need to ensure we're doing a better job with testing, this doesn't 
seem to be adding enough test infrastructure to make sure we're picking up the 
right function.

Finally, what does this mean in the case of template 
declarations/instantiations?  We need to make sure we're marking those 
correctly (or not picking them up at all perhaps?).

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


[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-01 Thread Erich Keane via cfe-commits


@@ -1980,6 +1981,23 @@ static void handleWeakRefAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
 }
 
+// Mark alias/ifunc target as used. For C++, we look up the demangled name
+// ignoring parameters. This should handle the majority of use cases while
+// leaveing false positives for namespace scope names and false negatives in
+// the presence of overloads.
+static void markUsedForAliasOrIfunc(Sema &S, Decl *D, const ParsedAttr &AL,
+StringRef Str) {
+  char *Demangled = llvm::itaniumDemangle(Str, /*ParseParams=*/false);
+  if (Demangled)
+Str = Demangled;

erichkeane wrote:

Doesn't this cause a use-after-free?  This seems wrong to me, with the 'free' 
below.

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


[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-01 Thread Erich Keane via cfe-commits

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


[clang] [Clang] Fix __is_array returning true for zero-sized arrays (PR #86652)

2024-04-01 Thread Nikolas Klauser via cfe-commits

philnik777 wrote:

I'd personally be fine with deprecating it. As I said above, we use it in 
libc++ for padding inside `string` like
```c++
struct short_string {
  ;
  char padding[sizeof(value_type) - 1];
  ;
};
```
That could be refactored relatively easily as
```c++
template 
struct padding_t {
  char data[Size];
};

template <>
struct padding_t<0> {};

struct short_string {
  ;
  [[no_unique_address]] padding_t padding;
  ;
};

```
so I don't think that's a use-case worth keeping the extension for.

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


[clang] [HLSL] Implement array temporary support (PR #79382)

2024-04-01 Thread Chris B via cfe-commits

https://github.com/llvm-beanz updated 
https://github.com/llvm/llvm-project/pull/79382

>From bd74d7db681cd07fda56f26e79e047c6d1a41f6b Mon Sep 17 00:00:00 2001
From: Chris Bieneman 
Date: Thu, 29 Feb 2024 15:37:50 -0600
Subject: [PATCH 1/9] [HLSL] Pass arrays by value

HLSL constant sized array function parameters do not decay to pointers.
Instead constant sized array types are preserved as unique types for
overload resolution, template instantiation and name mangling.

This implements the change by adding a new `ArrayParameterType` which
represents a non-decaying `ConstantArrayType`. The new type behaves the
same as `ConstantArrayType` except that it does not decay to a pointer.

Values of `ConstantArrayType` in HLSL decay during overload resolution
via a new `HLSLArrayRValue` cast to `ArrayParameterType`.

`ArrayParamterType` values are passed indirectly by-value to functions
in IR generation resulting in callee generated memcpy instructions.
---
 clang/docs/HLSL/FunctionCalls.rst |  32 +++---
 clang/include/clang/AST/ASTContext.h  |   7 ++
 clang/include/clang/AST/OperationKinds.def|   3 +
 clang/include/clang/AST/RecursiveASTVisitor.h |  11 ++
 clang/include/clang/AST/Type.h|  44 +++-
 clang/include/clang/AST/TypeLoc.h |   5 +
 clang/include/clang/AST/TypeProperties.td |   7 ++
 clang/include/clang/Basic/TypeNodes.td|   1 +
 clang/include/clang/Sema/Overload.h   |   3 +
 .../clang/Serialization/TypeBitCodes.def  |   1 +
 clang/lib/AST/ASTContext.cpp  |  62 ++-
 clang/lib/AST/ASTImporter.cpp |   9 ++
 clang/lib/AST/ASTStructuralEquivalence.cpp|   1 +
 clang/lib/AST/Expr.cpp|   1 +
 clang/lib/AST/ExprConstant.cpp|   3 +
 clang/lib/AST/ItaniumMangle.cpp   |   5 +
 clang/lib/AST/MicrosoftMangle.cpp |   5 +
 clang/lib/AST/ODRHash.cpp |   4 +
 clang/lib/AST/Type.cpp|  11 ++
 clang/lib/AST/TypePrinter.cpp |  11 ++
 clang/lib/CodeGen/CGCall.cpp  |   7 ++
 clang/lib/CodeGen/CGDebugInfo.cpp |   1 +
 clang/lib/CodeGen/CGExpr.cpp  |   1 +
 clang/lib/CodeGen/CGExprAgg.cpp   |   4 +
 clang/lib/CodeGen/CGExprComplex.cpp   |   1 +
 clang/lib/CodeGen/CGExprConstant.cpp  |   1 +
 clang/lib/CodeGen/CGExprScalar.cpp|   3 +-
 clang/lib/CodeGen/CodeGenFunction.cpp |   6 +
 clang/lib/CodeGen/CodeGenTypes.cpp|   1 +
 clang/lib/CodeGen/ItaniumCXXABI.cpp   |   4 +
 clang/lib/Edit/RewriteObjCFoundationAPI.cpp   |   1 +
 clang/lib/Sema/Sema.cpp   |   1 +
 clang/lib/Sema/SemaExpr.cpp   |   5 +
 clang/lib/Sema/SemaExprCXX.cpp|   8 ++
 clang/lib/Sema/SemaInit.cpp   |   5 +-
 clang/lib/Sema/SemaLookup.cpp |   4 +
 clang/lib/Sema/SemaOverload.cpp   |  16 +++
 clang/lib/Sema/SemaTemplate.cpp   |   5 +
 clang/lib/Sema/SemaTemplateDeduction.cpp  |   3 +-
 clang/lib/Sema/SemaType.cpp   |   3 +
 clang/lib/Sema/TreeTransform.h|  17 +++
 clang/lib/Serialization/ASTReader.cpp |   4 +
 clang/lib/Serialization/ASTWriter.cpp |   4 +
 clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp |   3 +-
 clang/test/CodeGenHLSL/ArrayTemporary.hlsl| 104 ++
 clang/test/SemaHLSL/ArrayParams.hlsl  |  29 +
 clang/test/SemaHLSL/ArrayTemporary.hlsl   |  92 
 clang/test/SemaHLSL/ArrayTemporary.ll |  76 +
 clang/tools/libclang/CIndex.cpp   |   1 +
 49 files changed, 609 insertions(+), 27 deletions(-)
 create mode 100644 clang/test/CodeGenHLSL/ArrayTemporary.hlsl
 create mode 100644 clang/test/SemaHLSL/ArrayParams.hlsl
 create mode 100644 clang/test/SemaHLSL/ArrayTemporary.hlsl
 create mode 100644 clang/test/SemaHLSL/ArrayTemporary.ll

diff --git a/clang/docs/HLSL/FunctionCalls.rst 
b/clang/docs/HLSL/FunctionCalls.rst
index 7317de2163f897..34f52004ec30f0 100644
--- a/clang/docs/HLSL/FunctionCalls.rst
+++ b/clang/docs/HLSL/FunctionCalls.rst
@@ -157,22 +157,24 @@ Clang Implementation
   of the changes in the prototype implementation are restoring Clang-3.7 code
   that was previously modified to its original state.
 
-The implementation in clang depends on two new AST nodes and minor extensions 
to
-Clang's existing support for Objective-C write-back arguments. The goal of this
-design is to capture the semantic details of HLSL function calls in the AST, 
and
-minimize the amount of magic that needs to occur during IR generation.
-
-The two new AST nodes are ``HLSLArrayTemporaryExpr`` and ``HLSLOutParamExpr``,
-which respectively represent the temporaries used for passing arrays by value
-and the temporaries created for function outputs.
+The implementation in clang adds a new non

[clang] [Clang][Sema] Skip checking anonymous enum in using enum declaration (PR #87144)

2024-04-01 Thread Aaron Ballman via cfe-commits

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


[clang] [Clang][Sema] Skip checking anonymous enum in using enum declaration (PR #87144)

2024-04-01 Thread Aaron Ballman via cfe-commits

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

Thank you! LGTM aside from expanding the testing a bit.

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


[clang] [Clang][Sema] Skip checking anonymous enum in using enum declaration (PR #87144)

2024-04-01 Thread Aaron Ballman via cfe-commits


@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -verify -std=c++20 -fsyntax-only %s
+// expected-no-diagnostics
+
+enum {A, S, D, F};
+int main() {
+using asdf = decltype(A);
+using enum asdf; // this line causes the crash
+return 0;
+}

AaronBallman wrote:

I'd like to see an additional test case demonstrating that we correctly added 
the enumerators to the correct scope:
```
enum {A, S, D, F};
constexpr struct T {
  using asdf = decltype(A);
  using enum asdf;
} t;

static_assert(t.D == D);
static_assert(T::S == S);
```
and
```
enum {A, S, D, F};
constexpr struct T {
  struct {
using asdf = decltype(A);
using enum asdf;
  } inner;
} t;

static_assert(t.inner.D == D);
static_assert(t.D == D); // expected-error
```

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


[clang] [Clang][AST][NFC] Move template argument dependence computations for MemberExpr to computeDependence (PR #86682)

2024-04-01 Thread Krystian Stasiowski via cfe-commits

sdkrystian wrote:

Ping @erichkeane 

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


[clang] [Clang][AST][NFC] Move template argument dependence computations for MemberExpr to computeDependence (PR #86682)

2024-04-01 Thread Erich Keane via cfe-commits

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


[clang] [Clang][AST][NFC] Move template argument dependence computations for MemberExpr to computeDependence (PR #86682)

2024-04-01 Thread Erich Keane via cfe-commits


@@ -583,11 +583,14 @@ class alignas(void *) Stmt {
 unsigned IsArrow : 1;
 
 /// True if this member expression used a nested-name-specifier to
-/// refer to the member, e.g., "x->Base::f", or found its member via
-/// a using declaration.  When true, a MemberExprNameQualifier
-/// structure is allocated immediately after the MemberExpr.
+/// refer to the member, e.g., "x->Base::f".
 LLVM_PREFERRED_TYPE(bool)
-unsigned HasQualifierOrFoundDecl : 1;
+unsigned HasQualifier : 1;
+
+// True if this member expression found its member via

erichkeane wrote:

Wrap on this comment seems odd... did clang-format do this one?

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


[clang] [Clang][AST][NFC] Move template argument dependence computations for MemberExpr to computeDependence (PR #86682)

2024-04-01 Thread Erich Keane via cfe-commits

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

2 nits, else LGTM.

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


[clang] [Clang][AST][NFC] Move template argument dependence computations for MemberExpr to computeDependence (PR #86682)

2024-04-01 Thread Erich Keane via cfe-commits


@@ -1735,48 +1757,21 @@ MemberExpr *MemberExpr::Create(
 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
 DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
 QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
-  bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
-FoundDecl.getAccess() != MemberDecl->getAccess();
+  bool HasQualifier = QualifierLoc.hasQualifier();
+  bool HasFoundDecl = FoundDecl.getDecl() != MemberDecl ||
+  FoundDecl.getAccess() != MemberDecl->getAccess();
   bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
   std::size_t Size =
-  totalSizeToAlloc(
-  HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
+  totalSizeToAlloc(
+  HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0,

erichkeane wrote:

Please just use the variable itself instead of ternary; bool-to-int conversion 
is well defined.

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


[clang] [Clang][AST][NFC] Move template argument dependence computations for MemberExpr to computeDependence (PR #86682)

2024-04-01 Thread Krystian Stasiowski via cfe-commits


@@ -1735,48 +1757,21 @@ MemberExpr *MemberExpr::Create(
 ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
 DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
 QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
-  bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
-FoundDecl.getAccess() != MemberDecl->getAccess();
+  bool HasQualifier = QualifierLoc.hasQualifier();
+  bool HasFoundDecl = FoundDecl.getDecl() != MemberDecl ||
+  FoundDecl.getAccess() != MemberDecl->getAccess();
   bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
   std::size_t Size =
-  totalSizeToAlloc(
-  HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
+  totalSizeToAlloc(
+  HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0,

sdkrystian wrote:

Sounds good to me, I prefer writing it that way anyways :) (was just following 
the style of the existing code)

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


[clang] [Clang] Unify interface for accessing template arguments as written for class/variable template specializations (PR #81642)

2024-04-01 Thread Krystian Stasiowski via cfe-commits

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

>From b45a42322682f3b872e6753965c4e4a7edb68333 Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Fri, 9 Feb 2024 14:00:49 -0500
Subject: [PATCH 1/4] [Clang] Unify interface for accessing template arguments
 as written for class/variable template specializations

---
 clang/include/clang/AST/DeclTemplate.h| 186 --
 clang/include/clang/AST/RecursiveASTVisitor.h |  27 +--
 clang/include/clang/ASTMatchers/ASTMatchers.h |   7 +-
 .../clang/ASTMatchers/ASTMatchersInternal.h   |   4 -
 clang/lib/AST/ASTImporter.cpp |  55 +++---
 clang/lib/AST/DeclPrinter.cpp |  15 +-
 clang/lib/AST/DeclTemplate.cpp| 145 --
 clang/lib/AST/TypePrinter.cpp |  24 +--
 clang/lib/Index/IndexDecl.cpp |   9 +-
 clang/lib/Sema/Sema.cpp   |   2 +-
 clang/lib/Sema/SemaTemplate.cpp   |  47 ++---
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 155 ++-
 clang/lib/Serialization/ASTReaderDecl.cpp |  20 +-
 clang/lib/Serialization/ASTWriterDecl.cpp |  16 +-
 clang/test/AST/ast-dump-template-decls.cpp|  18 +-
 clang/test/Index/Core/index-source.cpp|  11 --
 clang/test/Index/index-refs.cpp   |   1 -
 clang/tools/libclang/CIndex.cpp   |  29 ++-
 .../ASTMatchers/ASTMatchersNodeTest.cpp   |  12 --
 .../ASTMatchers/ASTMatchersTraversalTest.cpp  |  18 +-
 20 files changed, 360 insertions(+), 441 deletions(-)

diff --git a/clang/include/clang/AST/DeclTemplate.h 
b/clang/include/clang/AST/DeclTemplate.h
index e3b6a7efb1127af..b5c2d4597151205 100644
--- a/clang/include/clang/AST/DeclTemplate.h
+++ b/clang/include/clang/AST/DeclTemplate.h
@@ -1792,10 +1792,9 @@ class ClassTemplateSpecializationDecl
   llvm::PointerUnion
 SpecializedTemplate;
 
-  /// Further info for explicit template specialization/instantiation.
-  struct ExplicitSpecializationInfo {
-/// The type-as-written.
-TypeSourceInfo *TypeAsWritten = nullptr;
+  struct ExplicitInstantiationInfo {
+/// The template arguments as written..
+const ASTTemplateArgumentListInfo *TemplateArgsAsWritten = nullptr;
 
 /// The location of the extern keyword.
 SourceLocation ExternLoc;
@@ -1803,12 +1802,14 @@ class ClassTemplateSpecializationDecl
 /// The location of the template keyword.
 SourceLocation TemplateKeywordLoc;
 
-ExplicitSpecializationInfo() = default;
+ExplicitInstantiationInfo() = default;
   };
 
   /// Further info for explicit template specialization/instantiation.
   /// Does not apply to implicit specializations.
-  ExplicitSpecializationInfo *ExplicitInfo = nullptr;
+  llvm::PointerUnion
+  ExplicitInfo = nullptr;
 
   /// The template arguments used to describe this specialization.
   const TemplateArgumentList *TemplateArgs;
@@ -1985,44 +1986,45 @@ class ClassTemplateSpecializationDecl
 SpecializedTemplate = TemplDecl;
   }
 
-  /// Sets the type of this specialization as it was written by
-  /// the user. This will be a class template specialization type.
-  void setTypeAsWritten(TypeSourceInfo *T) {
-if (!ExplicitInfo)
-  ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
-ExplicitInfo->TypeAsWritten = T;
-  }
-
-  /// Gets the type of this specialization as it was written by
-  /// the user, if it was so written.
-  TypeSourceInfo *getTypeAsWritten() const {
-return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
+  const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
+if (auto *Info = ExplicitInfo.dyn_cast())
+  return Info->TemplateArgsAsWritten;
+return ExplicitInfo.get();
   }
 
   /// Gets the location of the extern keyword, if present.
   SourceLocation getExternLoc() const {
-return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
+if (auto *Info = ExplicitInfo.dyn_cast())
+  return Info->ExternLoc;
+return SourceLocation();
   }
 
-  /// Sets the location of the extern keyword.
-  void setExternLoc(SourceLocation Loc) {
-if (!ExplicitInfo)
-  ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
-ExplicitInfo->ExternLoc = Loc;
+  /// Gets the location of the template keyword, if present.
+  SourceLocation getTemplateKeywordLoc() const {
+if (auto *Info = ExplicitInfo.dyn_cast())
+  return Info->TemplateKeywordLoc;
+return SourceLocation();
   }
 
-  /// Sets the location of the template keyword.
-  void setTemplateKeywordLoc(SourceLocation Loc) {
-if (!ExplicitInfo)
-  ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
-ExplicitInfo->TemplateKeywordLoc = Loc;
+  void
+  setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten) {
+if (auto *Info = ExplicitInfo.dyn_cast())
+  Info->TemplateArgsAsWritten = ArgsWritten;
+else
+  ExplicitInfo = ArgsW

[clang] [Clang] Unify interface for accessing template arguments as written for class/variable template specializations (PR #81642)

2024-04-01 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 f914e8e77c4703814e2f2dcef1d4569b17837c92 
01858345a1146f761dec8e5d0a5a36dc0507ec48 -- 
clang/include/clang/AST/DeclTemplate.h 
clang/include/clang/AST/RecursiveASTVisitor.h 
clang/include/clang/ASTMatchers/ASTMatchers.h 
clang/include/clang/ASTMatchers/ASTMatchersInternal.h 
clang/lib/AST/ASTImporter.cpp clang/lib/AST/DeclPrinter.cpp 
clang/lib/AST/DeclTemplate.cpp clang/lib/AST/TypePrinter.cpp 
clang/lib/Index/IndexDecl.cpp clang/lib/Sema/Sema.cpp 
clang/lib/Sema/SemaTemplate.cpp clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
clang/lib/Serialization/ASTReaderDecl.cpp 
clang/lib/Serialization/ASTWriterDecl.cpp 
clang/test/AST/ast-dump-template-decls.cpp 
clang/test/Index/Core/index-source.cpp clang/test/Index/index-refs.cpp 
clang/tools/libclang/CIndex.cpp 
clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp 
clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 7bfd54c333..3844cafb5c 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -445,8 +445,7 @@ namespace clang {
 FunctionDecl *FromFD);
 
 template 
-Error ImportTemplateParameterLists(const DeclTy *FromD,
-   DeclTy *ToD);
+Error ImportTemplateParameterLists(const DeclTy *FromD, DeclTy *ToD);
 
 Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD);
 
diff --git a/clang/lib/AST/DeclTemplate.cpp b/clang/lib/AST/DeclTemplate.cpp
index f1fb5ba378..adcf9188a9 100644
--- a/clang/lib/AST/DeclTemplate.cpp
+++ b/clang/lib/AST/DeclTemplate.cpp
@@ -987,23 +987,26 @@ ClassTemplateSpecializationDecl::getSpecializedTemplate() 
const {
 SourceRange
 ClassTemplateSpecializationDecl::getSourceRange() const {
   if (getSpecializationKind() == TSK_ExplicitInstantiationDeclaration) {
-return SourceRange(getExternLoc(), 
getTemplateArgsAsWritten()->getRAngleLoc());
+return SourceRange(getExternLoc(),
+   getTemplateArgsAsWritten()->getRAngleLoc());
   } else if (getSpecializationKind() == TSK_ExplicitInstantiationDefinition) {
-return SourceRange(getTemplateKeywordLoc(), 
getTemplateArgsAsWritten()->getRAngleLoc());
+return SourceRange(getTemplateKeywordLoc(),
+   getTemplateArgsAsWritten()->getRAngleLoc());
   } else if (!isExplicitSpecialization()) {
 // No explicit info available.
 llvm::PointerUnion
-  InstFrom = getInstantiatedFrom();
+InstFrom = getInstantiatedFrom();
 if (InstFrom.isNull())
   return getSpecializedTemplate()->getSourceRange();
 if (const auto *CTD = InstFrom.dyn_cast())
   return CTD->getSourceRange();
 return InstFrom.get()
-  ->getSourceRange();
+->getSourceRange();
   }
   SourceLocation Begin = TagDecl::getOuterLocStart();
-  if (const auto *CTPSD = 
dyn_cast(this)) {
+  if (const auto *CTPSD =
+  dyn_cast(this)) {
 if (const auto *InstFrom = CTPSD->getInstantiatedFromMember())
   return InstFrom->getSourceRange();
 else if (!getNumTemplateParameterLists())
@@ -1381,10 +1384,12 @@ SourceRange 
VarTemplateSpecializationDecl::getSourceRange() const {
   if (isExplicitSpecialization() && !hasInit()) {
 if (const ASTTemplateArgumentListInfo *Info = getTemplateArgsAsWritten())
   return SourceRange(getOuterLocStart(), Info->getRAngleLoc());
-  } else if (getTemplateSpecializationKind() == 
TSK_ExplicitInstantiationDeclaration ) {
+  } else if (getTemplateSpecializationKind() ==
+ TSK_ExplicitInstantiationDeclaration) {
 if (const ASTTemplateArgumentListInfo *Info = getTemplateArgsAsWritten())
   return SourceRange(getExternLoc(), Info->getRAngleLoc());
-  } else if (getTemplateSpecializationKind() == 
TSK_ExplicitInstantiationDefinition) {
+  } else if (getTemplateSpecializationKind() ==
+ TSK_ExplicitInstantiationDefinition) {
 if (const ASTTemplateArgumentListInfo *Info = getTemplateArgsAsWritten())
   return SourceRange(getTemplateKeywordLoc(), Info->getRAngleLoc());
   }

``




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


[clang] [Clang] Unify interface for accessing template arguments as written for class/variable template specializations (PR #81642)

2024-04-01 Thread Krystian Stasiowski via cfe-commits

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

>From b45a42322682f3b872e6753965c4e4a7edb68333 Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Fri, 9 Feb 2024 14:00:49 -0500
Subject: [PATCH 1/5] [Clang] Unify interface for accessing template arguments
 as written for class/variable template specializations

---
 clang/include/clang/AST/DeclTemplate.h| 186 --
 clang/include/clang/AST/RecursiveASTVisitor.h |  27 +--
 clang/include/clang/ASTMatchers/ASTMatchers.h |   7 +-
 .../clang/ASTMatchers/ASTMatchersInternal.h   |   4 -
 clang/lib/AST/ASTImporter.cpp |  55 +++---
 clang/lib/AST/DeclPrinter.cpp |  15 +-
 clang/lib/AST/DeclTemplate.cpp| 145 --
 clang/lib/AST/TypePrinter.cpp |  24 +--
 clang/lib/Index/IndexDecl.cpp |   9 +-
 clang/lib/Sema/Sema.cpp   |   2 +-
 clang/lib/Sema/SemaTemplate.cpp   |  47 ++---
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 155 ++-
 clang/lib/Serialization/ASTReaderDecl.cpp |  20 +-
 clang/lib/Serialization/ASTWriterDecl.cpp |  16 +-
 clang/test/AST/ast-dump-template-decls.cpp|  18 +-
 clang/test/Index/Core/index-source.cpp|  11 --
 clang/test/Index/index-refs.cpp   |   1 -
 clang/tools/libclang/CIndex.cpp   |  29 ++-
 .../ASTMatchers/ASTMatchersNodeTest.cpp   |  12 --
 .../ASTMatchers/ASTMatchersTraversalTest.cpp  |  18 +-
 20 files changed, 360 insertions(+), 441 deletions(-)

diff --git a/clang/include/clang/AST/DeclTemplate.h 
b/clang/include/clang/AST/DeclTemplate.h
index e3b6a7efb1127af..b5c2d4597151205 100644
--- a/clang/include/clang/AST/DeclTemplate.h
+++ b/clang/include/clang/AST/DeclTemplate.h
@@ -1792,10 +1792,9 @@ class ClassTemplateSpecializationDecl
   llvm::PointerUnion
 SpecializedTemplate;
 
-  /// Further info for explicit template specialization/instantiation.
-  struct ExplicitSpecializationInfo {
-/// The type-as-written.
-TypeSourceInfo *TypeAsWritten = nullptr;
+  struct ExplicitInstantiationInfo {
+/// The template arguments as written..
+const ASTTemplateArgumentListInfo *TemplateArgsAsWritten = nullptr;
 
 /// The location of the extern keyword.
 SourceLocation ExternLoc;
@@ -1803,12 +1802,14 @@ class ClassTemplateSpecializationDecl
 /// The location of the template keyword.
 SourceLocation TemplateKeywordLoc;
 
-ExplicitSpecializationInfo() = default;
+ExplicitInstantiationInfo() = default;
   };
 
   /// Further info for explicit template specialization/instantiation.
   /// Does not apply to implicit specializations.
-  ExplicitSpecializationInfo *ExplicitInfo = nullptr;
+  llvm::PointerUnion
+  ExplicitInfo = nullptr;
 
   /// The template arguments used to describe this specialization.
   const TemplateArgumentList *TemplateArgs;
@@ -1985,44 +1986,45 @@ class ClassTemplateSpecializationDecl
 SpecializedTemplate = TemplDecl;
   }
 
-  /// Sets the type of this specialization as it was written by
-  /// the user. This will be a class template specialization type.
-  void setTypeAsWritten(TypeSourceInfo *T) {
-if (!ExplicitInfo)
-  ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
-ExplicitInfo->TypeAsWritten = T;
-  }
-
-  /// Gets the type of this specialization as it was written by
-  /// the user, if it was so written.
-  TypeSourceInfo *getTypeAsWritten() const {
-return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
+  const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
+if (auto *Info = ExplicitInfo.dyn_cast())
+  return Info->TemplateArgsAsWritten;
+return ExplicitInfo.get();
   }
 
   /// Gets the location of the extern keyword, if present.
   SourceLocation getExternLoc() const {
-return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
+if (auto *Info = ExplicitInfo.dyn_cast())
+  return Info->ExternLoc;
+return SourceLocation();
   }
 
-  /// Sets the location of the extern keyword.
-  void setExternLoc(SourceLocation Loc) {
-if (!ExplicitInfo)
-  ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
-ExplicitInfo->ExternLoc = Loc;
+  /// Gets the location of the template keyword, if present.
+  SourceLocation getTemplateKeywordLoc() const {
+if (auto *Info = ExplicitInfo.dyn_cast())
+  return Info->TemplateKeywordLoc;
+return SourceLocation();
   }
 
-  /// Sets the location of the template keyword.
-  void setTemplateKeywordLoc(SourceLocation Loc) {
-if (!ExplicitInfo)
-  ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
-ExplicitInfo->TemplateKeywordLoc = Loc;
+  void
+  setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten) {
+if (auto *Info = ExplicitInfo.dyn_cast())
+  Info->TemplateArgsAsWritten = ArgsWritten;
+else
+  ExplicitInfo = ArgsW

[clang-tools-extra] Add clang-tidy check readability-math-missing-parentheses (PR #84481)

2024-04-01 Thread Bhuminjay Soni via cfe-commits

https://github.com/11happy updated 
https://github.com/llvm/llvm-project/pull/84481

>From 8fdf6306085ed4cf0f77b7e718e374e9f65fedf9 Mon Sep 17 00:00:00 2001
From: 11happy 
Date: Fri, 8 Mar 2024 19:02:47 +0530
Subject: [PATCH 01/10] add clang-tidy check
 readability-math-missing-parentheses

Signed-off-by: 11happy 
---
 .../clang-tidy/readability/CMakeLists.txt |   1 +
 .../MathMissingParenthesesCheck.cpp   | 167 ++
 .../readability/MathMissingParenthesesCheck.h |  31 
 .../readability/ReadabilityTidyModule.cpp |   3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../readability/math-missing-parentheses.rst  |  19 ++
 .../readability/math-missing-parentheses.cpp  |  42 +
 8 files changed, 270 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/readability/math-missing-parentheses.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/readability/math-missing-parentheses.cpp

diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
index a6c8cbd8eb448a..0d4fa095501dfb 100644
--- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
@@ -27,6 +27,7 @@ add_clang_library(clangTidyReadabilityModule
   IsolateDeclarationCheck.cpp
   MagicNumbersCheck.cpp
   MakeMemberFunctionConstCheck.cpp
+  MathMissingParenthesesCheck.cpp
   MisleadingIndentationCheck.cpp
   MisplacedArrayIndexCheck.cpp
   NamedParameterCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp
new file mode 100644
index 00..d9574a9fb7a476
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp
@@ -0,0 +1,167 @@
+//===--- MathMissingParenthesesCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "MathMissingParenthesesCheck.h"
+#include "../utils/ASTUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+#include 
+#include 
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+void MathMissingParenthesesCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(binaryOperator(unless(hasParent(binaryOperator())),
+hasDescendant(binaryOperator()))
+ .bind("binOp"),
+ this);
+}
+static int precedenceCheck(const char op) {
+  if (op == '/' || op == '*' || op == '%')
+return 5;
+
+  else if (op == '+' || op == '-')
+return 4;
+
+  else if (op == '&')
+return 3;
+  else if (op == '^')
+return 2;
+
+  else if (op == '|')
+return 1;
+
+  else
+return 0;
+}
+static bool isOperand(const char c) {
+  if (c >= 'a' && c <= 'z')
+return true;
+  else if (c >= 'A' && c <= 'Z')
+return true;
+  else if (c >= '0' && c <= '9')
+return true;
+  else if (c == '$')
+return true;
+  else
+return false;
+}
+static bool conditionForNegative(const std::string s, int i,
+ const std::string CurStr) {
+  if (CurStr[0] == '-') {
+if (i == 0) {
+  return true;
+} else {
+  while (s[i - 1] == ' ') {
+i--;
+  }
+  if (!isOperand(s[i - 1])) {
+return true;
+  } else {
+return false;
+  }
+}
+  } else {
+return false;
+  }
+}
+static std::string getOperationOrder(std::string s, std::set &Operators) 
{
+  std::stack StackOne;
+  std::string TempStr = "";
+  for (int i = 0; i < s.length(); i++) {
+std::string CurStr = "";
+CurStr += s[i];
+if (CurStr == " ")
+  continue;
+else {
+  if (isOperand(CurStr[0]) || conditionForNegative(s, i, CurStr)) {
+while (i < s.length() && (isOperand(s[i]) || s[i] == '-')) {
+  if (s[i] == '-') {
+TempStr += "$";
+  } else {
+TempStr += CurStr;
+  }
+  i++;
+  CurStr = s[i];
+}
+TempStr += " ";
+  } else if (CurStr == "(") {
+StackOne.push("(");
+  } else if (CurStr == ")") {
+while (StackOne.top() != "(") {
+  TempStr += StackOne.top();
+  StackOne.pop();
+}
+StackOne.pop();
+  } else {
+while (!StackOne.empty() && precedenceCh

[clang-tools-extra] Add clang-tidy check readability-math-missing-parentheses (PR #84481)

2024-04-01 Thread Bhuminjay Soni via cfe-commits


@@ -129,6 +129,12 @@ New checks
   Replaces certain conditional statements with equivalent calls to
   ``std::min`` or ``std::max``.
 
+- New :doc:`readability-math-missing-parentheses

11happy wrote:

done

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


[clang-tools-extra] Add clang-tidy check readability-math-missing-parentheses (PR #84481)

2024-04-01 Thread Bhuminjay Soni via cfe-commits


@@ -0,0 +1,112 @@
+//===--- MathMissingParenthesesCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "MathMissingParenthesesCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+void MathMissingParenthesesCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(binaryOperator(unless(hasParent(binaryOperator())),
+unless(allOf(hasOperatorName("&&"),
+ hasOperatorName("||"))),
+hasDescendant(binaryOperator()))
+ .bind("binOp"),
+ this);
+}
+
+static int getPrecedence(const BinaryOperator *BinOp) {
+  if (!BinOp)
+return 0;
+  switch (BinOp->getOpcode()) {
+  case BO_Mul:
+  case BO_Div:
+  case BO_Rem:
+return 5;
+  case BO_Add:
+  case BO_Sub:
+return 4;
+  case BO_And:
+return 3;
+  case BO_Xor:
+return 2;
+  case BO_Or:
+return 1;
+  default:
+return 0;
+  }
+}
+static bool addParantheses(
+const BinaryOperator *BinOp, const BinaryOperator *ParentBinOp,
+std::vector<
+std::pair>>
+&Insertions,
+const clang::SourceManager &SM, const clang::LangOptions &LangOpts) {
+  bool NeedToDiagnose = false;
+  if (!BinOp)
+return NeedToDiagnose;
+
+  if (ParentBinOp != nullptr &&
+  getPrecedence(BinOp) != getPrecedence(ParentBinOp)) {
+NeedToDiagnose = true;
+const clang::SourceLocation StartLoc = BinOp->getBeginLoc();
+clang::SourceLocation EndLoc =
+clang::Lexer::getLocForEndOfToken(BinOp->getEndLoc(), 0, SM, LangOpts);
+Insertions.push_back(
+{clang::SourceRange(StartLoc, EndLoc), {BinOp, ParentBinOp}});

11happy wrote:

done

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


[clang-tools-extra] Add clang-tidy check readability-math-missing-parentheses (PR #84481)

2024-04-01 Thread Bhuminjay Soni via cfe-commits


@@ -0,0 +1,25 @@
+.. title:: clang-tidy - readability-math-missing-parentheses
+
+readability-math-missing-parentheses
+
+
+Check for missing parentheses in mathematical expressions that involve 
operators
+of different priorities. Parentheses in mathematical expressions clarify the 
order

11happy wrote:

done

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


[clang-tools-extra] Add clang-tidy check readability-math-missing-parentheses (PR #84481)

2024-04-01 Thread Bhuminjay Soni via cfe-commits


@@ -0,0 +1,112 @@
+//===--- MathMissingParenthesesCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "MathMissingParenthesesCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+void MathMissingParenthesesCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(binaryOperator(unless(hasParent(binaryOperator())),
+unless(allOf(hasOperatorName("&&"),
+ hasOperatorName("||"))),
+hasDescendant(binaryOperator()))
+ .bind("binOp"),
+ this);
+}
+
+static int getPrecedence(const BinaryOperator *BinOp) {
+  if (!BinOp)
+return 0;
+  switch (BinOp->getOpcode()) {
+  case BO_Mul:
+  case BO_Div:
+  case BO_Rem:
+return 5;
+  case BO_Add:
+  case BO_Sub:
+return 4;
+  case BO_And:
+return 3;
+  case BO_Xor:
+return 2;
+  case BO_Or:
+return 1;
+  default:
+return 0;
+  }
+}
+static bool addParantheses(
+const BinaryOperator *BinOp, const BinaryOperator *ParentBinOp,
+std::vector<
+std::pair>>
+&Insertions,
+const clang::SourceManager &SM, const clang::LangOptions &LangOpts) {
+  bool NeedToDiagnose = false;
+  if (!BinOp)
+return NeedToDiagnose;
+
+  if (ParentBinOp != nullptr &&
+  getPrecedence(BinOp) != getPrecedence(ParentBinOp)) {
+NeedToDiagnose = true;
+const clang::SourceLocation StartLoc = BinOp->getBeginLoc();
+clang::SourceLocation EndLoc =
+clang::Lexer::getLocForEndOfToken(BinOp->getEndLoc(), 0, SM, LangOpts);
+Insertions.push_back(
+{clang::SourceRange(StartLoc, EndLoc), {BinOp, ParentBinOp}});
+  }
+
+  NeedToDiagnose |= addParantheses(
+  dyn_cast(BinOp->getLHS()->IgnoreImpCasts()), BinOp,
+  Insertions, SM, LangOpts);
+  NeedToDiagnose |= addParantheses(
+  dyn_cast(BinOp->getRHS()->IgnoreImpCasts()), BinOp,
+  Insertions, SM, LangOpts);
+  return NeedToDiagnose;
+}
+
+void MathMissingParenthesesCheck::check(
+const MatchFinder::MatchResult &Result) {
+  const auto *BinOp = Result.Nodes.getNodeAs("binOp");
+  std::vector<
+  std::pair>>
+  Insertions;
+  const clang::SourceLocation StartLoc = BinOp->getBeginLoc();
+  const SourceManager &SM = *Result.SourceManager;
+  const clang::LangOptions &LO = Result.Context->getLangOpts();
+
+  if (addParantheses(BinOp, nullptr, Insertions, SM, LO)) {
+for (const auto &Insertion : Insertions) {
+  const clang::BinaryOperator *BinOp1 = Insertion.second.first;
+  const clang::BinaryOperator *BinOp2 = Insertion.second.second;
+
+  int Precedence1 = getPrecedence(BinOp1);
+  int Precedence2 = getPrecedence(BinOp2);
+
+  auto Diag = diag(Insertion.first.getBegin(),
+   "'%0' has higher precedence than '%1'; add parentheses "
+   "to make the precedence of operations explicit")

11happy wrote:

done

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


[clang-tools-extra] Add clang-tidy check readability-math-missing-parentheses (PR #84481)

2024-04-01 Thread Bhuminjay Soni via cfe-commits


@@ -0,0 +1,81 @@
+// RUN: %check_clang_tidy %s readability-math-missing-parentheses %t
+
+int foo(){
+return 5;
+}
+
+int bar(){
+return 4;
+}
+
+class fun{
+public:  
+int A;
+double B;
+fun(){
+A = 5;
+B = 5.4;
+}
+};
+
+void f(){
+//CHECK-MESSAGES: :[[@LINE+2]]:17: warning: '*' has higher precedence than 
'+'; add parentheses to make the precedence of operations explicit 
[readability-math-missing-parentheses]
+//CHECK-FIXES: int a = 1 + (2 * 3);
+int a = 1 + 2 * 3; 
+
+int b = 1 + 2 + 3; // No warning
+
+int c = 1 * 2 * 3; // No warning
+
+//CHECK-MESSAGES: :[[@LINE+3]]:17: warning: '*' has higher precedence than 
'+'; add parentheses to make the precedence of operations explicit 
[readability-math-missing-parentheses]
+//CHECK-MESSAGES: :[[@LINE+2]]:25: warning: '/' has higher precedence than 
'-'; add parentheses to make the precedence of operations explicit 
[readability-math-missing-parentheses]
+//CHECK-FIXES: int d = 1 + (2 * 3) - (4 / 5);
+int d = 1 + 2 * 3 - 4 / 5;

11happy wrote:

done

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


[clang-tools-extra] Add clang-tidy check readability-math-missing-parentheses (PR #84481)

2024-04-01 Thread Bhuminjay Soni via cfe-commits


@@ -0,0 +1,112 @@
+//===--- MathMissingParenthesesCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "MathMissingParenthesesCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+void MathMissingParenthesesCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(binaryOperator(unless(hasParent(binaryOperator())),

11happy wrote:

done

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


[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-01 Thread Nick Desaulniers via cfe-commits


@@ -1980,6 +1981,23 @@ static void handleWeakRefAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
 }
 
+// Mark alias/ifunc target as used. For C++, we look up the demangled name
+// ignoring parameters. This should handle the majority of use cases while
+// leaveing false positives for namespace scope names and false negatives in
+// the presence of overloads.
+static void markUsedForAliasOrIfunc(Sema &S, Decl *D, const ParsedAttr &AL,
+StringRef Str) {
+  char *Demangled = llvm::itaniumDemangle(Str, /*ParseParams=*/false);
+  if (Demangled)
+Str = Demangled;
+  const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
+  LookupResult LR(S, target, Sema::LookupOrdinaryName);
+  if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
+for (NamedDecl *ND : LR)
+  ND->markUsed(S.Context);

nickdesaulniers wrote:

I believe you can put `alias` attributes on non-functions: 
https://godbolt.org/z/s1PbojYr4.

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


[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-01 Thread Erich Keane via cfe-commits


@@ -1980,6 +1981,23 @@ static void handleWeakRefAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
 }
 
+// Mark alias/ifunc target as used. For C++, we look up the demangled name
+// ignoring parameters. This should handle the majority of use cases while
+// leaveing false positives for namespace scope names and false negatives in
+// the presence of overloads.
+static void markUsedForAliasOrIfunc(Sema &S, Decl *D, const ParsedAttr &AL,
+StringRef Str) {
+  char *Demangled = llvm::itaniumDemangle(Str, /*ParseParams=*/false);
+  if (Demangled)
+Str = Demangled;
+  const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
+  LookupResult LR(S, target, Sema::LookupOrdinaryName);
+  if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
+for (NamedDecl *ND : LR)
+  ND->markUsed(S.Context);

erichkeane wrote:

> I believe you can put `alias` attributes on non-functions: 
> https://godbolt.org/z/s1PbojYr4.

`ifuncs` cannot, so we perhaps need to be more careful there.

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


[clang] [Clang] Unify interface for accessing template arguments as written for class/variable template specializations (PR #81642)

2024-04-01 Thread Erich Keane via cfe-commits

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


[clang] [Clang] Unify interface for accessing template arguments as written for class/variable template specializations (PR #81642)

2024-04-01 Thread Erich Keane via cfe-commits


@@ -2596,27 +2588,14 @@ class VarTemplateSpecializationDecl : public VarDecl,
   llvm::PointerUnion
   SpecializedTemplate;
 
-  /// Further info for explicit template specialization/instantiation.
-  struct ExplicitSpecializationInfo {
-/// The type-as-written.
-TypeSourceInfo *TypeAsWritten = nullptr;
-
-/// The location of the extern keyword.
-SourceLocation ExternLoc;
-
-/// The location of the template keyword.
-SourceLocation TemplateKeywordLoc;
-
-ExplicitSpecializationInfo() = default;
-  };
-
   /// Further info for explicit template specialization/instantiation.
   /// Does not apply to implicit specializations.
-  ExplicitSpecializationInfo *ExplicitInfo = nullptr;
+  llvm::PointerUnionhttps://github.com/llvm/llvm-project/pull/81642
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] Unify interface for accessing template arguments as written for class/variable template specializations (PR #81642)

2024-04-01 Thread Erich Keane via cfe-commits


@@ -2545,10 +2545,12 @@ ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
   }
 
   // Explicit info.
-  if (TypeSourceInfo *TyInfo = readTypeSourceInfo()) {
-auto *ExplicitInfo =
-new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
-ExplicitInfo->TypeAsWritten = TyInfo;
+  if (Record.readBool()) {
+// FIXME: We don't need to allocate this if ExternLoc and 
TemplateKeywordLoc

erichkeane wrote:

Still waiting on this?

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


[clang] [Clang] Unify interface for accessing template arguments as written for class/variable template specializations (PR #81642)

2024-04-01 Thread Erich Keane via cfe-commits

https://github.com/erichkeane commented:

A few more suggestions, also I like Shafik's suggestion on the variable name.

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


[clang] [Clang] Unify interface for accessing template arguments as written for class/variable template specializations (PR #81642)

2024-04-01 Thread Erich Keane via cfe-commits


@@ -1455,21 +1455,17 @@ void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) 
{
 
   // If this is a class template specialization, print the template
   // arguments.
-  if (const auto *Spec = dyn_cast(D)) {
-ArrayRef Args;
-TypeSourceInfo *TAW = Spec->getTypeAsWritten();
-if (!Policy.PrintCanonicalTypes && TAW) {
-  const TemplateSpecializationType *TST =
-cast(TAW->getType());
-  Args = TST->template_arguments();
-} else {
-  const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
-  Args = TemplateArgs.asArray();
-}
+  if (auto S = dyn_cast(D)) {
+const TemplateParameterList *TParams =
+S->getSpecializedTemplate()->getTemplateParameters();
+const auto *TArgAsWritten = S->getTemplateArgsAsWritten();

erichkeane wrote:

By coding standard, we can't really use 'auto' here IIRC.

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


[clang] [Clang] Unify interface for accessing template arguments as written for class/variable template specializations (PR #81642)

2024-04-01 Thread Erich Keane via cfe-commits


@@ -1455,21 +1455,17 @@ void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) 
{
 
   // If this is a class template specialization, print the template
   // arguments.
-  if (const auto *Spec = dyn_cast(D)) {
-ArrayRef Args;
-TypeSourceInfo *TAW = Spec->getTypeAsWritten();
-if (!Policy.PrintCanonicalTypes && TAW) {
-  const TemplateSpecializationType *TST =
-cast(TAW->getType());
-  Args = TST->template_arguments();
-} else {
-  const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
-  Args = TemplateArgs.asArray();
-}
+  if (auto S = dyn_cast(D)) {
+const TemplateParameterList *TParams =
+S->getSpecializedTemplate()->getTemplateParameters();
+const auto *TArgAsWritten = S->getTemplateArgsAsWritten();
 IncludeStrongLifetimeRAII Strong(Policy);
-printTemplateArgumentList(
-OS, Args, Policy,
-Spec->getSpecializedTemplate()->getTemplateParameters());
+if (TArgAsWritten && !Policy.PrintCanonicalTypes)

erichkeane wrote:

This exact pattern happens 2x... it would be nice/useful if we could get a 
helper function to capture this pattern (perhaps an overload of 
`printTemplateArgumentList`?).

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


[clang-tools-extra] Add clang-tidy check readability-math-missing-parentheses (PR #84481)

2024-04-01 Thread Bhuminjay Soni via cfe-commits

https://github.com/11happy updated 
https://github.com/llvm/llvm-project/pull/84481

>From 8fdf6306085ed4cf0f77b7e718e374e9f65fedf9 Mon Sep 17 00:00:00 2001
From: 11happy 
Date: Fri, 8 Mar 2024 19:02:47 +0530
Subject: [PATCH 01/11] add clang-tidy check
 readability-math-missing-parentheses

Signed-off-by: 11happy 
---
 .../clang-tidy/readability/CMakeLists.txt |   1 +
 .../MathMissingParenthesesCheck.cpp   | 167 ++
 .../readability/MathMissingParenthesesCheck.h |  31 
 .../readability/ReadabilityTidyModule.cpp |   3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../readability/math-missing-parentheses.rst  |  19 ++
 .../readability/math-missing-parentheses.cpp  |  42 +
 8 files changed, 270 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/readability/math-missing-parentheses.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/readability/math-missing-parentheses.cpp

diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
index a6c8cbd8eb448a..0d4fa095501dfb 100644
--- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
@@ -27,6 +27,7 @@ add_clang_library(clangTidyReadabilityModule
   IsolateDeclarationCheck.cpp
   MagicNumbersCheck.cpp
   MakeMemberFunctionConstCheck.cpp
+  MathMissingParenthesesCheck.cpp
   MisleadingIndentationCheck.cpp
   MisplacedArrayIndexCheck.cpp
   NamedParameterCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp
new file mode 100644
index 00..d9574a9fb7a476
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp
@@ -0,0 +1,167 @@
+//===--- MathMissingParenthesesCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "MathMissingParenthesesCheck.h"
+#include "../utils/ASTUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+#include 
+#include 
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+void MathMissingParenthesesCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(binaryOperator(unless(hasParent(binaryOperator())),
+hasDescendant(binaryOperator()))
+ .bind("binOp"),
+ this);
+}
+static int precedenceCheck(const char op) {
+  if (op == '/' || op == '*' || op == '%')
+return 5;
+
+  else if (op == '+' || op == '-')
+return 4;
+
+  else if (op == '&')
+return 3;
+  else if (op == '^')
+return 2;
+
+  else if (op == '|')
+return 1;
+
+  else
+return 0;
+}
+static bool isOperand(const char c) {
+  if (c >= 'a' && c <= 'z')
+return true;
+  else if (c >= 'A' && c <= 'Z')
+return true;
+  else if (c >= '0' && c <= '9')
+return true;
+  else if (c == '$')
+return true;
+  else
+return false;
+}
+static bool conditionForNegative(const std::string s, int i,
+ const std::string CurStr) {
+  if (CurStr[0] == '-') {
+if (i == 0) {
+  return true;
+} else {
+  while (s[i - 1] == ' ') {
+i--;
+  }
+  if (!isOperand(s[i - 1])) {
+return true;
+  } else {
+return false;
+  }
+}
+  } else {
+return false;
+  }
+}
+static std::string getOperationOrder(std::string s, std::set &Operators) 
{
+  std::stack StackOne;
+  std::string TempStr = "";
+  for (int i = 0; i < s.length(); i++) {
+std::string CurStr = "";
+CurStr += s[i];
+if (CurStr == " ")
+  continue;
+else {
+  if (isOperand(CurStr[0]) || conditionForNegative(s, i, CurStr)) {
+while (i < s.length() && (isOperand(s[i]) || s[i] == '-')) {
+  if (s[i] == '-') {
+TempStr += "$";
+  } else {
+TempStr += CurStr;
+  }
+  i++;
+  CurStr = s[i];
+}
+TempStr += " ";
+  } else if (CurStr == "(") {
+StackOne.push("(");
+  } else if (CurStr == ")") {
+while (StackOne.top() != "(") {
+  TempStr += StackOne.top();
+  StackOne.pop();
+}
+StackOne.pop();
+  } else {
+while (!StackOne.empty() && precedenceCh

[clang-tools-extra] Add clang-tidy check readability-math-missing-parentheses (PR #84481)

2024-04-01 Thread Bhuminjay Soni via cfe-commits

https://github.com/11happy updated 
https://github.com/llvm/llvm-project/pull/84481

>From 8fdf6306085ed4cf0f77b7e718e374e9f65fedf9 Mon Sep 17 00:00:00 2001
From: 11happy 
Date: Fri, 8 Mar 2024 19:02:47 +0530
Subject: [PATCH 01/11] add clang-tidy check
 readability-math-missing-parentheses

Signed-off-by: 11happy 
---
 .../clang-tidy/readability/CMakeLists.txt |   1 +
 .../MathMissingParenthesesCheck.cpp   | 167 ++
 .../readability/MathMissingParenthesesCheck.h |  31 
 .../readability/ReadabilityTidyModule.cpp |   3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../readability/math-missing-parentheses.rst  |  19 ++
 .../readability/math-missing-parentheses.cpp  |  42 +
 8 files changed, 270 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/readability/math-missing-parentheses.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/readability/math-missing-parentheses.cpp

diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
index a6c8cbd8eb448a..0d4fa095501dfb 100644
--- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
@@ -27,6 +27,7 @@ add_clang_library(clangTidyReadabilityModule
   IsolateDeclarationCheck.cpp
   MagicNumbersCheck.cpp
   MakeMemberFunctionConstCheck.cpp
+  MathMissingParenthesesCheck.cpp
   MisleadingIndentationCheck.cpp
   MisplacedArrayIndexCheck.cpp
   NamedParameterCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp
new file mode 100644
index 00..d9574a9fb7a476
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp
@@ -0,0 +1,167 @@
+//===--- MathMissingParenthesesCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "MathMissingParenthesesCheck.h"
+#include "../utils/ASTUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+#include 
+#include 
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+void MathMissingParenthesesCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(binaryOperator(unless(hasParent(binaryOperator())),
+hasDescendant(binaryOperator()))
+ .bind("binOp"),
+ this);
+}
+static int precedenceCheck(const char op) {
+  if (op == '/' || op == '*' || op == '%')
+return 5;
+
+  else if (op == '+' || op == '-')
+return 4;
+
+  else if (op == '&')
+return 3;
+  else if (op == '^')
+return 2;
+
+  else if (op == '|')
+return 1;
+
+  else
+return 0;
+}
+static bool isOperand(const char c) {
+  if (c >= 'a' && c <= 'z')
+return true;
+  else if (c >= 'A' && c <= 'Z')
+return true;
+  else if (c >= '0' && c <= '9')
+return true;
+  else if (c == '$')
+return true;
+  else
+return false;
+}
+static bool conditionForNegative(const std::string s, int i,
+ const std::string CurStr) {
+  if (CurStr[0] == '-') {
+if (i == 0) {
+  return true;
+} else {
+  while (s[i - 1] == ' ') {
+i--;
+  }
+  if (!isOperand(s[i - 1])) {
+return true;
+  } else {
+return false;
+  }
+}
+  } else {
+return false;
+  }
+}
+static std::string getOperationOrder(std::string s, std::set &Operators) 
{
+  std::stack StackOne;
+  std::string TempStr = "";
+  for (int i = 0; i < s.length(); i++) {
+std::string CurStr = "";
+CurStr += s[i];
+if (CurStr == " ")
+  continue;
+else {
+  if (isOperand(CurStr[0]) || conditionForNegative(s, i, CurStr)) {
+while (i < s.length() && (isOperand(s[i]) || s[i] == '-')) {
+  if (s[i] == '-') {
+TempStr += "$";
+  } else {
+TempStr += CurStr;
+  }
+  i++;
+  CurStr = s[i];
+}
+TempStr += " ";
+  } else if (CurStr == "(") {
+StackOne.push("(");
+  } else if (CurStr == ")") {
+while (StackOne.top() != "(") {
+  TempStr += StackOne.top();
+  StackOne.pop();
+}
+StackOne.pop();
+  } else {
+while (!StackOne.empty() && precedenceCh

[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-01 Thread Nick Desaulniers via cfe-commits

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


[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-01 Thread Nick Desaulniers via cfe-commits


@@ -1980,6 +1981,23 @@ static void handleWeakRefAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
 }
 
+// Mark alias/ifunc target as used. For C++, we look up the demangled name
+// ignoring parameters. This should handle the majority of use cases while
+// leaveing false positives for namespace scope names and false negatives in
+// the presence of overloads.
+static void markUsedForAliasOrIfunc(Sema &S, Decl *D, const ParsedAttr &AL,
+StringRef Str) {
+  char *Demangled = llvm::itaniumDemangle(Str, /*ParseParams=*/false);

nickdesaulniers wrote:

How does one specify a "non-itanium build?"

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


[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-01 Thread Nick Desaulniers via cfe-commits

https://github.com/nickdesaulniers commented:

As the author of https://reviews.llvm.org/D54188 and the TODO added from there, 
this patch is the right thing to do.  I fixed a false positive diagnostic for C 
and knew that the fix was insufficient for C++.

I do appreciate the abundance of caution here, but this looks generally like 
what we want to do.

>  We fix false positives while causing false negatives when overloads are 
> present.

Can we avoid the false negatives?

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


[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-01 Thread Nick Desaulniers via cfe-commits


@@ -1,7 +1,35 @@
-// RUN: %clang_cc1 -triple x86_64-linux-gnu -Wunneeded-internal-declaration -x 
c -verify %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -Wunused -x c -verify %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -Wunused -x c++ -verify %s
+
+#ifdef __cplusplus
+extern "C" {
+#else
 // expected-no-diagnostics
+#endif
 static int f(void) { return 42; }
 int g(void) __attribute__((alias("f")));
 
 static int foo [] = { 42, 0xDEAD };
 extern typeof(foo) bar __attribute__((unused, alias("foo")));
+
+static int (*resolver(void))(void) { return f; }
+int ifunc(void) __attribute__((ifunc("resolver")));
+
+#ifdef __cplusplus
+}
+
+/// We demangle alias/ifunc target and mark all found functions as used.
+static int f1(int) { return 42; }

nickdesaulniers wrote:

This behavior differs from GCC; https://godbolt.org/z/fz8a153qY.  Even which 
function is retained for codegen purposes is different. That's sure to lead to 
compatibility issues.  So beyond this diagnostic related change, it looks like 
we may have a pre-existing codegen bug here, too.

---

Given an alias to `_ZL2f1v`, that demangles to `f1()`. So we _should_ diagnose 
that `f1(int)` is unused (`_ZL2f1i`).

Same for `_ZL9resolver1v` below.

You allude to fixing false positives in lieu of adding false negatives, but I 
would prefer to not have to compromise like that.

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


[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-01 Thread Nick Desaulniers via cfe-commits


@@ -1,7 +1,35 @@
-// RUN: %clang_cc1 -triple x86_64-linux-gnu -Wunneeded-internal-declaration -x 
c -verify %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -Wunused -x c -verify %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -Wunused -x c++ -verify %s
+
+#ifdef __cplusplus
+extern "C" {
+#else
 // expected-no-diagnostics
+#endif
 static int f(void) { return 42; }
 int g(void) __attribute__((alias("f")));
 
 static int foo [] = { 42, 0xDEAD };
 extern typeof(foo) bar __attribute__((unused, alias("foo")));
+
+static int (*resolver(void))(void) { return f; }
+int ifunc(void) __attribute__((ifunc("resolver")));
+
+#ifdef __cplusplus
+}
+
+/// We demangle alias/ifunc target and mark all found functions as used.
+static int f1(int) { return 42; }
+static int f1(void) { return 42; }
+int g1(void) __attribute__((alias("_ZL2f1v")));
+
+static int (*resolver1(void))(void) { return f; }
+static int (*resolver1(int))(void) { return f; }
+int ifunc1(void) __attribute__((ifunc("_ZL9resolver1v")));
+
+namespace ns {
+static int f2(int) { return 42; } // expected-warning{{unused function 'f2'}}
+static int f2(void) { return 42; } // expected-warning{{unused function 'f2'}}

nickdesaulniers wrote:

Why warn for `f2(void)`? Would `_ZNL2nsL2f2Ev` be the mangling? (an additional 
`L` between `N` and `2`)?

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


[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-01 Thread Nick Desaulniers via cfe-commits


@@ -1,7 +1,35 @@
-// RUN: %clang_cc1 -triple x86_64-linux-gnu -Wunneeded-internal-declaration -x 
c -verify %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -Wunused -x c -verify %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -Wunused -x c++ -verify %s
+
+#ifdef __cplusplus
+extern "C" {
+#else
 // expected-no-diagnostics
+#endif
 static int f(void) { return 42; }
 int g(void) __attribute__((alias("f")));
 
 static int foo [] = { 42, 0xDEAD };
 extern typeof(foo) bar __attribute__((unused, alias("foo")));
+
+static int (*resolver(void))(void) { return f; }
+int ifunc(void) __attribute__((ifunc("resolver")));
+
+#ifdef __cplusplus
+}
+
+/// We demangle alias/ifunc target and mark all found functions as used.
+static int f1(int) { return 42; }
+static int f1(void) { return 42; }
+int g1(void) __attribute__((alias("_ZL2f1v")));
+
+static int (*resolver1(void))(void) { return f; }
+static int (*resolver1(int))(void) { return f; }
+int ifunc1(void) __attribute__((ifunc("_ZL9resolver1v")));
+
+namespace ns {
+static int f2(int) { return 42; } // expected-warning{{unused function 'f2'}}
+static int f2(void) { return 42; } // expected-warning{{unused function 'f2'}}
+int g2(void) __attribute__((alias("_ZN2nsL2f2Ev")));

nickdesaulniers wrote:

If these functions are only checked in `__cplusplus` mode, omit the `void` from 
the parameter list?

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


[clang] [compiler-rt] [llvm] [InstrFDO][TypeProf] Implement binary instrumentation and profile read/write (PR #66825)

2024-04-01 Thread Mingming Liu via cfe-commits

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


[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-04-01 Thread via cfe-commits


@@ -0,0 +1,252 @@
+//===--- MinMaxUseInitializerListCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "MinMaxUseInitializerListCheck.h"
+#include "../utils/ASTUtils.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang;
+
+namespace {
+
+struct FindArgsResult {
+  const Expr *First;
+  const Expr *Last;
+  const Expr *Compare;
+  std::vector Args;
+};
+
+} // anonymous namespace
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+static FindArgsResult findArgs(const CallExpr *Call) {
+  FindArgsResult Result;
+  Result.First = nullptr;
+  Result.Last = nullptr;
+  Result.Compare = nullptr;
+
+  if (Call->getNumArgs() == 3) {
+auto ArgIterator = Call->arguments().begin();
+std::advance(ArgIterator, 2);
+Result.Compare = *ArgIterator;
+  } else {
+auto ArgIterator = Call->arguments().begin();
+
+if (const auto *InitListExpr =
+dyn_cast(*ArgIterator)) {
+  if (const auto *InitList = dyn_cast(
+  InitListExpr->getSubExpr()->IgnoreImplicit())) {

sopyb wrote:

> https://github.com/llvm/llvm-project/pull/85572#discussion_r1545536522

I applied the suggestion I was given and I don't think it's possible for it to 
be nullptr here or I couldn't make it be null in my testing. I can undo it to 
have the tempExpr.

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


[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-04-01 Thread via cfe-commits

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


[clang] [OpenCL] Fix BIenqueue_kernel fallthrough (PR #83238)

2024-04-01 Thread Anastasia Stulova via cfe-commits

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

Makes sense, LGTM! Thanks

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


[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-04-01 Thread via cfe-commits


@@ -0,0 +1,276 @@
+//===--- MinMaxUseInitializerListCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "MinMaxUseInitializerListCheck.h"
+#include "../utils/ASTUtils.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang;
+
+namespace {
+
+struct FindArgsResult {
+  const Expr *First;
+  const Expr *Last;
+  const Expr *Compare;
+  SmallVector Args;

sopyb wrote:

Most probably I am only going to have 2 arguments. But in the case the argument 
is an initializer list the number or args is impossible to know ahead of time.

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


[compiler-rt] [libcxx] [libcxxabi] [libunwind] [libunwind][libcxx][libcxxabi][compiler-rt-builtins] Fix Exception Handling build for wasm (PR #79667)

2024-04-01 Thread via cfe-commits


@@ -12,6 +12,7 @@
 #ifndef __LIBUNWIND_EXT__
 #define __LIBUNWIND_EXT__
 
+#ifndef __wasm__

EricWF wrote:

I would much rather you guard the usage of this header in each file.

That way it's clear to the reader in context that the include is unused under a 
certain configuration.
If the entire file contains no WASM code, then it probably shouldn't mention 
WASM at all.

Can you please explain what the `__WASM_EXCEPTIONS__` or 
`__USING_WASM_EXCEPTIONS__` was? 


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


[compiler-rt] [libcxx] [libcxxabi] [libunwind] [libunwind][libcxx][libcxxabi][compiler-rt-builtins] Fix Exception Handling build for wasm (PR #79667)

2024-04-01 Thread via cfe-commits


@@ -10,6 +10,7 @@
 #ifndef LIBUNWIND_CET_UNWIND_H
 #define LIBUNWIND_CET_UNWIND_H
 
+#ifndef __wasm__

EricWF wrote:

Again, I don't think `#ifdef`-ing out entire headers is the best way to do 
this, or is even necessary. 

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


[compiler-rt] [libcxx] [libcxxabi] [libunwind] [libunwind][libcxx][libcxxabi][compiler-rt-builtins] Fix Exception Handling build for wasm (PR #79667)

2024-04-01 Thread via cfe-commits


@@ -15,6 +15,7 @@
 #ifndef UNWIND_ASSEMBLY_H
 #define UNWIND_ASSEMBLY_H
 
+#ifndef __wasm__

EricWF wrote:

Again, this is not OK.

First, this file just defines macros, so even under WASM it should be safe to 
include.
If you're hitting the `#error` case in the `#else`, then add an `#elif 
__wasm__`.

While his style of code may not cause issues for you, because you don't use it. 
It makes things more complicated for every change that actually uses these 
files.



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


[compiler-rt] [libcxx] [libcxxabi] [libunwind] [libunwind][libcxx][libcxxabi][compiler-rt-builtins] Fix Exception Handling build for wasm (PR #79667)

2024-04-01 Thread via cfe-commits


@@ -431,6 +432,7 @@ int __unw_remove_find_dynamic_unwind_sections(
 }
 
 #endif // __APPLE__
+#endif

EricWF wrote:

At minimum this needs a comment matching it to the specific block it's closing.

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


[compiler-rt] [libcxx] [libcxxabi] [libunwind] [libunwind][libcxx][libcxxabi][compiler-rt-builtins] Fix Exception Handling build for wasm (PR #79667)

2024-04-01 Thread via cfe-commits


@@ -12,7 +12,7 @@
 // functions. We need to ensure that the return value is sign-extended in the
 // same way as GCC expects (since otherwise GCC-generated __builtin_isinf
 // returns true for finite 128-bit floating-point numbers).
-#ifdef __aarch64__
+#if defined(__aarch64__) || defined(__wasm__)

EricWF wrote:

Could you update the comment above to mention why WASM needs this too?

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


[compiler-rt] [libcxx] [libcxxabi] [libunwind] [libunwind][libcxx][libcxxabi][compiler-rt-builtins] Fix Exception Handling build for wasm (PR #79667)

2024-04-01 Thread via cfe-commits


@@ -39,3 +40,5 @@ extern void *__libunwind_cet_get_registers(unw_cursor_t *);
 extern void *__libunwind_cet_get_jump_target(void);

EricWF wrote:

What is the problem with exposing these two declarations, even if they're not 
defined?

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


[compiler-rt] [libcxx] [libcxxabi] [libunwind] [libunwind][libcxx][libcxxabi][compiler-rt-builtins] Fix Exception Handling build for wasm (PR #79667)

2024-04-01 Thread via cfe-commits


@@ -12,6 +12,7 @@
 #include 
 
 #include "config.h"
+#ifndef __wasm__

EricWF wrote:

The problem is that it makes the file a lot harder to read, each `#ifdef` block 
enclosed within becomes harder to read and reason about its scope. 

Though I see that _maybe_ WASM uses the log functions declared at the bottom? 
Do you know if it does?





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


[compiler-rt] [libcxx] [libcxxabi] [libunwind] [libunwind][libcxx][libcxxabi][compiler-rt-builtins] Fix Exception Handling build for wasm (PR #79667)

2024-04-01 Thread via cfe-commits

EricWF wrote:

@trcrsired Could you please describe what bits of libunwind WASM uses? It seems 
to me almost all of the functionality is stripped out?

Could you also provide instructions to build and test libunwind under WASM so 
we could add CI coverage? And so I can test this change myself.

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


[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-01 Thread Erich Keane via cfe-commits


@@ -1980,6 +1981,23 @@ static void handleWeakRefAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
 }
 
+// Mark alias/ifunc target as used. For C++, we look up the demangled name
+// ignoring parameters. This should handle the majority of use cases while
+// leaveing false positives for namespace scope names and false negatives in
+// the presence of overloads.
+static void markUsedForAliasOrIfunc(Sema &S, Decl *D, const ParsedAttr &AL,
+StringRef Str) {
+  char *Demangled = llvm::itaniumDemangle(Str, /*ParseParams=*/false);

erichkeane wrote:

Triple is the only way I am aware of IIRC.  So we should be checking that 
triple.  I think `ifunc` is ELF/Itanium only, and I'm unsure about `alias`.  
That said, I'm aware of at least 1 downstream (IIRC) that used an ELF system 
with an MSVC mangling (one of the offload compilers).

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


[clang-tools-extra] [clang-tidy] add check to suggest replacement of nested std::min or std::max with initializer lists (PR #85572)

2024-04-01 Thread via cfe-commits


@@ -0,0 +1,252 @@
+//===--- MinMaxUseInitializerListCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "MinMaxUseInitializerListCheck.h"
+#include "../utils/ASTUtils.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang;
+
+namespace {
+
+struct FindArgsResult {
+  const Expr *First;
+  const Expr *Last;
+  const Expr *Compare;
+  std::vector Args;
+};
+
+} // anonymous namespace
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+static FindArgsResult findArgs(const CallExpr *Call) {
+  FindArgsResult Result;
+  Result.First = nullptr;
+  Result.Last = nullptr;
+  Result.Compare = nullptr;
+
+  if (Call->getNumArgs() == 3) {
+auto ArgIterator = Call->arguments().begin();
+std::advance(ArgIterator, 2);
+Result.Compare = *ArgIterator;
+  } else {
+auto ArgIterator = Call->arguments().begin();
+
+if (const auto *InitListExpr =
+dyn_cast(*ArgIterator)) {
+  if (const auto *InitList = dyn_cast(
+  InitListExpr->getSubExpr()->IgnoreImplicit())) {
+Result.Args.insert(Result.Args.begin(), InitList->inits().begin(),
+   InitList->inits().end());
+
+Result.First = *ArgIterator;
+Result.Last = *ArgIterator;
+
+std::advance(ArgIterator, 1);
+if (ArgIterator != Call->arguments().end()) {
+  Result.Compare = *ArgIterator;
+}
+return Result;
+  }
+}
+  }
+
+  for (const Expr *Arg : Call->arguments()) {
+if (!Result.First)
+  Result.First = Arg;
+
+if (Arg == Result.Compare)
+  continue;
+
+Result.Args.push_back(Arg);
+Result.Last = Arg;
+  }
+
+  return Result;
+}
+
+static std::vector
+generateReplacement(const MatchFinder::MatchResult &Match,
+const CallExpr *TopCall, const FindArgsResult &Result) {
+  std::vector FixItHints;
+
+  const QualType ResultType = TopCall->getDirectCallee()
+  ->getReturnType()
+  .getNonReferenceType()
+  .getUnqualifiedType()
+  .getCanonicalType();
+  const bool IsInitializerList = Result.First == Result.Last;
+
+  if (!IsInitializerList)
+FixItHints.push_back(
+FixItHint::CreateInsertion(Result.First->getBeginLoc(), "{"));
+
+  for (const Expr *Arg : Result.Args) {

sopyb wrote:

I tried to restructure the code so the code makes logical sense handling 
everything related to the current call then for each argument going remove 
function call, remove (), remove {} if any and then remove the compare function 
after the last argument. This also solved having to use -1 on 
`InnerReplacements.end`. I don't really see how I could improve this much 
further.

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


[clang] [clang] Fix incorrect line numbers with -E and raw string (#47577) (PR #77021)

2024-04-01 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

> > This will need a release note
> 
> Are you asking me to do this? I did not see any instructions about how to do 
> this.

Sorry for not seeing this question earlier! Yes, you should add a release note 
to clang/docs/ReleaseNotes.rst; we have a section for bug fixes: 
https://github.com/llvm/llvm-project/blob/985c1a44f8d49e0afeba907fe29d881c19b319fc/clang/docs/ReleaseNotes.rst?plain=1#L319

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


[clang] [Clang] Unify interface for accessing template arguments as written for class/variable template specializations (PR #81642)

2024-04-01 Thread Krystian Stasiowski via cfe-commits

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

>From b45a42322682f3b872e6753965c4e4a7edb68333 Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Fri, 9 Feb 2024 14:00:49 -0500
Subject: [PATCH 1/6] [Clang] Unify interface for accessing template arguments
 as written for class/variable template specializations

---
 clang/include/clang/AST/DeclTemplate.h| 186 --
 clang/include/clang/AST/RecursiveASTVisitor.h |  27 +--
 clang/include/clang/ASTMatchers/ASTMatchers.h |   7 +-
 .../clang/ASTMatchers/ASTMatchersInternal.h   |   4 -
 clang/lib/AST/ASTImporter.cpp |  55 +++---
 clang/lib/AST/DeclPrinter.cpp |  15 +-
 clang/lib/AST/DeclTemplate.cpp| 145 --
 clang/lib/AST/TypePrinter.cpp |  24 +--
 clang/lib/Index/IndexDecl.cpp |   9 +-
 clang/lib/Sema/Sema.cpp   |   2 +-
 clang/lib/Sema/SemaTemplate.cpp   |  47 ++---
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 155 ++-
 clang/lib/Serialization/ASTReaderDecl.cpp |  20 +-
 clang/lib/Serialization/ASTWriterDecl.cpp |  16 +-
 clang/test/AST/ast-dump-template-decls.cpp|  18 +-
 clang/test/Index/Core/index-source.cpp|  11 --
 clang/test/Index/index-refs.cpp   |   1 -
 clang/tools/libclang/CIndex.cpp   |  29 ++-
 .../ASTMatchers/ASTMatchersNodeTest.cpp   |  12 --
 .../ASTMatchers/ASTMatchersTraversalTest.cpp  |  18 +-
 20 files changed, 360 insertions(+), 441 deletions(-)

diff --git a/clang/include/clang/AST/DeclTemplate.h 
b/clang/include/clang/AST/DeclTemplate.h
index e3b6a7efb1127a..b5c2d459715120 100644
--- a/clang/include/clang/AST/DeclTemplate.h
+++ b/clang/include/clang/AST/DeclTemplate.h
@@ -1792,10 +1792,9 @@ class ClassTemplateSpecializationDecl
   llvm::PointerUnion
 SpecializedTemplate;
 
-  /// Further info for explicit template specialization/instantiation.
-  struct ExplicitSpecializationInfo {
-/// The type-as-written.
-TypeSourceInfo *TypeAsWritten = nullptr;
+  struct ExplicitInstantiationInfo {
+/// The template arguments as written..
+const ASTTemplateArgumentListInfo *TemplateArgsAsWritten = nullptr;
 
 /// The location of the extern keyword.
 SourceLocation ExternLoc;
@@ -1803,12 +1802,14 @@ class ClassTemplateSpecializationDecl
 /// The location of the template keyword.
 SourceLocation TemplateKeywordLoc;
 
-ExplicitSpecializationInfo() = default;
+ExplicitInstantiationInfo() = default;
   };
 
   /// Further info for explicit template specialization/instantiation.
   /// Does not apply to implicit specializations.
-  ExplicitSpecializationInfo *ExplicitInfo = nullptr;
+  llvm::PointerUnion
+  ExplicitInfo = nullptr;
 
   /// The template arguments used to describe this specialization.
   const TemplateArgumentList *TemplateArgs;
@@ -1985,44 +1986,45 @@ class ClassTemplateSpecializationDecl
 SpecializedTemplate = TemplDecl;
   }
 
-  /// Sets the type of this specialization as it was written by
-  /// the user. This will be a class template specialization type.
-  void setTypeAsWritten(TypeSourceInfo *T) {
-if (!ExplicitInfo)
-  ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
-ExplicitInfo->TypeAsWritten = T;
-  }
-
-  /// Gets the type of this specialization as it was written by
-  /// the user, if it was so written.
-  TypeSourceInfo *getTypeAsWritten() const {
-return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
+  const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
+if (auto *Info = ExplicitInfo.dyn_cast())
+  return Info->TemplateArgsAsWritten;
+return ExplicitInfo.get();
   }
 
   /// Gets the location of the extern keyword, if present.
   SourceLocation getExternLoc() const {
-return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
+if (auto *Info = ExplicitInfo.dyn_cast())
+  return Info->ExternLoc;
+return SourceLocation();
   }
 
-  /// Sets the location of the extern keyword.
-  void setExternLoc(SourceLocation Loc) {
-if (!ExplicitInfo)
-  ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
-ExplicitInfo->ExternLoc = Loc;
+  /// Gets the location of the template keyword, if present.
+  SourceLocation getTemplateKeywordLoc() const {
+if (auto *Info = ExplicitInfo.dyn_cast())
+  return Info->TemplateKeywordLoc;
+return SourceLocation();
   }
 
-  /// Sets the location of the template keyword.
-  void setTemplateKeywordLoc(SourceLocation Loc) {
-if (!ExplicitInfo)
-  ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
-ExplicitInfo->TemplateKeywordLoc = Loc;
+  void
+  setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten) {
+if (auto *Info = ExplicitInfo.dyn_cast())
+  Info->TemplateArgsAsWritten = ArgsWritten;
+else
+  ExplicitInfo = ArgsWri

[clang] MIPS/Clang: Set HasUnalignedAccess false if +strict-align (PR #87256)

2024-04-01 Thread YunQiang Su via cfe-commits

https://github.com/wzssyqa created 
https://github.com/llvm/llvm-project/pull/87256

TargetInfo has HasUnalignedAccess support now. For MIPSr6, we should set it 
according strict-align.

For pre-R6, we always set strict-align and HasUnalignedAccess to false.

>From ecee40e72582c98e74e89d3aff97a832ece3fd70 Mon Sep 17 00:00:00 2001
From: YunQiang Su 
Date: Tue, 2 Apr 2024 00:20:55 +0800
Subject: [PATCH] MIPS/Clang: Set HasUnalignedAccess false if +strict-align

TargetInfo has HasUnalignedAccess support now. For MIPSr6,
we should set it according strict-align.

For pre-R6, we always set strict-align and HasUnalignedAccess to
false.
---
 clang/lib/Basic/Targets/Mips.h | 6 ++
 1 file changed, 6 insertions(+)

diff --git a/clang/lib/Basic/Targets/Mips.h b/clang/lib/Basic/Targets/Mips.h
index c9dcf434c93b0b..f5ce1bc735a700 100644
--- a/clang/lib/Basic/Targets/Mips.h
+++ b/clang/lib/Basic/Targets/Mips.h
@@ -318,6 +318,7 @@ class LLVM_LIBRARY_VISIBILITY MipsTargetInfo : public 
TargetInfo {
 FPMode = isFP64Default() ? FP64 : FPXX;
 NoOddSpreg = false;
 bool OddSpregGiven = false;
+bool StrictAlign = false;
 
 for (const auto &Feature : Features) {
   if (Feature == "+single-float")
@@ -330,6 +331,8 @@ class LLVM_LIBRARY_VISIBILITY MipsTargetInfo : public 
TargetInfo {
 IsMicromips = true;
   else if (Feature == "+mips32r6" || Feature == "+mips64r6")
 HasUnalignedAccess = true;
+  else if (Feature == "+strict-align")
+StrictAlign = true;
   else if (Feature == "+dsp")
 DspRev = std::max(DspRev, DSP1);
   else if (Feature == "+dspr2")
@@ -368,6 +371,9 @@ class LLVM_LIBRARY_VISIBILITY MipsTargetInfo : public 
TargetInfo {
 if (FPMode == FPXX && !OddSpregGiven)
   NoOddSpreg = true;
 
+if (StrictAlign)
+  HasUnalignedAccess = false;
+
 setDataLayout();
 
 return true;

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


[clang] MIPS/Clang: Set HasUnalignedAccess false if +strict-align (PR #87256)

2024-04-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: YunQiang Su (wzssyqa)


Changes

TargetInfo has HasUnalignedAccess support now. For MIPSr6, we should set it 
according strict-align.

For pre-R6, we always set strict-align and HasUnalignedAccess to false.

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


1 Files Affected:

- (modified) clang/lib/Basic/Targets/Mips.h (+6) 


``diff
diff --git a/clang/lib/Basic/Targets/Mips.h b/clang/lib/Basic/Targets/Mips.h
index c9dcf434c93b0b..f5ce1bc735a700 100644
--- a/clang/lib/Basic/Targets/Mips.h
+++ b/clang/lib/Basic/Targets/Mips.h
@@ -318,6 +318,7 @@ class LLVM_LIBRARY_VISIBILITY MipsTargetInfo : public 
TargetInfo {
 FPMode = isFP64Default() ? FP64 : FPXX;
 NoOddSpreg = false;
 bool OddSpregGiven = false;
+bool StrictAlign = false;
 
 for (const auto &Feature : Features) {
   if (Feature == "+single-float")
@@ -330,6 +331,8 @@ class LLVM_LIBRARY_VISIBILITY MipsTargetInfo : public 
TargetInfo {
 IsMicromips = true;
   else if (Feature == "+mips32r6" || Feature == "+mips64r6")
 HasUnalignedAccess = true;
+  else if (Feature == "+strict-align")
+StrictAlign = true;
   else if (Feature == "+dsp")
 DspRev = std::max(DspRev, DSP1);
   else if (Feature == "+dspr2")
@@ -368,6 +371,9 @@ class LLVM_LIBRARY_VISIBILITY MipsTargetInfo : public 
TargetInfo {
 if (FPMode == FPXX && !OddSpregGiven)
   NoOddSpreg = true;
 
+if (StrictAlign)
+  HasUnalignedAccess = false;
+
 setDataLayout();
 
 return true;

``




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


[clang] [Clang] Unify interface for accessing template arguments as written for class/variable template specializations (PR #81642)

2024-04-01 Thread Krystian Stasiowski via cfe-commits

sdkrystian wrote:

@erichkeane Regarding "Still waiting on this?", I pushed a commit that 
addresses the fixme. I'll be addressing the rest of your review comments in a 
subsequent commit..

Also, if we are renaming `ExplicitInstantiationInfo::ExternLoc` to 
`ExternKeywordLoc`, should we rename the getters and setters to 
`getExternKeywordLoc`/`setExternKeywordLoc` as well?

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


[clang] [clang][FMV] Direct-call FMV callees from FMV callers (PR #80093)

2024-04-01 Thread Erich Keane via cfe-commits

erichkeane wrote:

I'd be OK with Clang providing some level of metadata to clarify which is an 
FMV, and what our target features are.  But this sort of analysis still needs 
to happen in LLVM.  

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


[clang] [Clang] Unify interface for accessing template arguments as written for class/variable template specializations (PR #81642)

2024-04-01 Thread Erich Keane via cfe-commits

erichkeane wrote:

> @erichkeane Regarding "Still waiting on this?", I pushed a commit that 
> addresses the fixme. I'll be addressing the rest of your review comments in a 
> subsequent commit..
> 
> Also, if we are renaming `ExplicitInstantiationInfo::ExternLoc` to 
> `ExternKeywordLoc`, should we rename the getters and setters to 
> `getExternKeywordLoc`/`setExternKeywordLoc` as well?

I think that rename makes sense as well.

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


[clang] Add support for builtin_verbose_trap (PR #79230)

2024-04-01 Thread Akira Hatanaka via cfe-commits

https://github.com/ahatanak updated 
https://github.com/llvm/llvm-project/pull/79230

>From 44813fefa59b442abcc6cb23c2ac8d3f78e44efc Mon Sep 17 00:00:00 2001
From: Akira Hatanaka 
Date: Tue, 16 Jan 2024 13:18:09 -0800
Subject: [PATCH 01/11] Add support for builtin_verbose_trap

The builtin causes the program to stop its execution abnormally and shows a
human-readable description of the reason for the termination when a debugger is
attached or in a symbolicated crash log.

The motivation for the builtin is explained in the following RFC:

https://discourse.llvm.org/t/rfc-adding-builtin-verbose-trap-string-literal/75845
---
 clang/docs/LanguageExtensions.rst | 48 ++
 clang/include/clang/AST/Expr.h|  5 ++
 clang/include/clang/Basic/Builtins.td |  6 +++
 .../clang/Basic/DiagnosticSemaKinds.td|  2 +
 clang/lib/AST/ExprConstant.cpp| 18 +--
 clang/lib/CodeGen/CGBuiltin.cpp   | 12 +
 clang/lib/CodeGen/CGDebugInfo.cpp | 42 
 clang/lib/CodeGen/CGDebugInfo.h   | 20 
 clang/lib/Sema/SemaChecking.cpp   | 22 +
 .../CodeGenCXX/debug-info-verbose-trap.cpp| 49 +++
 clang/test/SemaCXX/verbose-trap.cpp   | 28 +++
 11 files changed, 249 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/debug-info-verbose-trap.cpp
 create mode 100644 clang/test/SemaCXX/verbose-trap.cpp

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 7b23e4d1c2f30c..4e4151e7803875 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -3464,6 +3464,54 @@ Query for this feature with 
``__has_builtin(__builtin_trap)``.
 
 ``__builtin_arm_trap`` is lowered to the ``llvm.aarch64.break`` builtin, and 
then to ``brk #payload``.
 
+``__builtin_verbose_trap``
+--
+
+``__builtin_verbose_trap`` causes the program to stop its execution abnormally
+and shows a human-readable description of the reason for the termination when a
+debugger is attached or in a symbolicated crash log.
+
+**Syntax**:
+
+.. code-block:: c++
+
+__builtin_verbose_trap(const char *reason)
+
+**Description**
+
+``__builtin_verbose_trap`` is lowered to the ` ``llvm.trap`` 
`_ builtin.
+Additionally, clang emits debug metadata that represents an artificial inline
+frame whose name encodes the string passed to the builtin, prefixed by a 
"magic"
+prefix.
+
+For example, consider the following code:
+
+.. code-block:: c++
+
+void foo(int* p) {
+  if (p == nullptr)
+__builtin_verbose_trap("Argument_must_not_be_null");
+}
+
+The debug metadata would look as if it were produced for the following code:
+
+.. code-block:: c++
+
+__attribute__((always_inline))
+inline void "__llvm_verbose_trap: Argument_must_not_be_null"() {
+  __builtin_trap();
+}
+
+void foo(int* p) {
+  if (p == nullptr)
+"__llvm_verbose_trap: Argument_must_not_be_null"();
+}
+
+However, the LLVM IR would not actually contain a call to the artificial
+function — it only exists in the debug metadata.
+
+Query for this feature with ``__has_builtin(__builtin_verbose_trap)``.
+
 ``__builtin_nondeterministic_value``
 
 
diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 6e153ebe024b42..789bedbd9724a6 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -787,6 +787,11 @@ class Expr : public ValueStmt {
  const Expr *PtrExpression, ASTContext &Ctx,
  EvalResult &Status) const;
 
+  /// If the current Expr can be evaluated to a pointer to a null-terminated
+  /// constant string, return the constant string (without the terminating 
null)
+  /// in Result. Return true if it succeeds.
+  bool tryEvaluateString(std::string &Result, ASTContext &Ctx) const;
+
   /// Enumeration used to describe the kind of Null pointer constant
   /// returned from \c isNullPointerConstant().
   enum NullPointerConstantKind {
diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index f421223ff087de..df7b0460c1f21d 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -1152,6 +1152,12 @@ def Trap : Builtin {
   let Prototype = "void()";
 }
 
+def VerboseTrap : Builtin {
+  let Spellings = ["__builtin_verbose_trap"];
+  let Attributes = [NoThrow, NoReturn];
+  let Prototype = "void(char const*)";
+}
+
 def Debugtrap : Builtin {
   let Spellings = ["__builtin_debugtrap"];
   let Attributes = [NoThrow];
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index df57f5e6ce11ba..03f52c88ea1f1f 100644
--- a/clang/include/clang/Basic/Diagnostic

[clang] MIPS/Clang: Set HasUnalignedAccess false if +strict-align (PR #87257)

2024-04-01 Thread YunQiang Su via cfe-commits

https://github.com/wzssyqa created 
https://github.com/llvm/llvm-project/pull/87257

TargetInfo has HasUnalignedAccess support now. For MIPSr6, we should set it 
according strict-align.

For pre-R6, we always set strict-align and HasUnalignedAccess to false.

>From ecee40e72582c98e74e89d3aff97a832ece3fd70 Mon Sep 17 00:00:00 2001
From: YunQiang Su 
Date: Tue, 2 Apr 2024 00:20:55 +0800
Subject: [PATCH] MIPS/Clang: Set HasUnalignedAccess false if +strict-align

TargetInfo has HasUnalignedAccess support now. For MIPSr6,
we should set it according strict-align.

For pre-R6, we always set strict-align and HasUnalignedAccess to
false.
---
 clang/lib/Basic/Targets/Mips.h | 6 ++
 1 file changed, 6 insertions(+)

diff --git a/clang/lib/Basic/Targets/Mips.h b/clang/lib/Basic/Targets/Mips.h
index c9dcf434c93b0b..f5ce1bc735a700 100644
--- a/clang/lib/Basic/Targets/Mips.h
+++ b/clang/lib/Basic/Targets/Mips.h
@@ -318,6 +318,7 @@ class LLVM_LIBRARY_VISIBILITY MipsTargetInfo : public 
TargetInfo {
 FPMode = isFP64Default() ? FP64 : FPXX;
 NoOddSpreg = false;
 bool OddSpregGiven = false;
+bool StrictAlign = false;
 
 for (const auto &Feature : Features) {
   if (Feature == "+single-float")
@@ -330,6 +331,8 @@ class LLVM_LIBRARY_VISIBILITY MipsTargetInfo : public 
TargetInfo {
 IsMicromips = true;
   else if (Feature == "+mips32r6" || Feature == "+mips64r6")
 HasUnalignedAccess = true;
+  else if (Feature == "+strict-align")
+StrictAlign = true;
   else if (Feature == "+dsp")
 DspRev = std::max(DspRev, DSP1);
   else if (Feature == "+dspr2")
@@ -368,6 +371,9 @@ class LLVM_LIBRARY_VISIBILITY MipsTargetInfo : public 
TargetInfo {
 if (FPMode == FPXX && !OddSpregGiven)
   NoOddSpreg = true;
 
+if (StrictAlign)
+  HasUnalignedAccess = false;
+
 setDataLayout();
 
 return true;

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


[clang] MIPS/Clang: Set HasUnalignedAccess false if +strict-align (PR #87257)

2024-04-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: YunQiang Su (wzssyqa)


Changes

TargetInfo has HasUnalignedAccess support now. For MIPSr6, we should set it 
according strict-align.

For pre-R6, we always set strict-align and HasUnalignedAccess to false.

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


1 Files Affected:

- (modified) clang/lib/Basic/Targets/Mips.h (+6) 


``diff
diff --git a/clang/lib/Basic/Targets/Mips.h b/clang/lib/Basic/Targets/Mips.h
index c9dcf434c93b0b..f5ce1bc735a700 100644
--- a/clang/lib/Basic/Targets/Mips.h
+++ b/clang/lib/Basic/Targets/Mips.h
@@ -318,6 +318,7 @@ class LLVM_LIBRARY_VISIBILITY MipsTargetInfo : public 
TargetInfo {
 FPMode = isFP64Default() ? FP64 : FPXX;
 NoOddSpreg = false;
 bool OddSpregGiven = false;
+bool StrictAlign = false;
 
 for (const auto &Feature : Features) {
   if (Feature == "+single-float")
@@ -330,6 +331,8 @@ class LLVM_LIBRARY_VISIBILITY MipsTargetInfo : public 
TargetInfo {
 IsMicromips = true;
   else if (Feature == "+mips32r6" || Feature == "+mips64r6")
 HasUnalignedAccess = true;
+  else if (Feature == "+strict-align")
+StrictAlign = true;
   else if (Feature == "+dsp")
 DspRev = std::max(DspRev, DSP1);
   else if (Feature == "+dspr2")
@@ -368,6 +371,9 @@ class LLVM_LIBRARY_VISIBILITY MipsTargetInfo : public 
TargetInfo {
 if (FPMode == FPXX && !OddSpregGiven)
   NoOddSpreg = true;
 
+if (StrictAlign)
+  HasUnalignedAccess = false;
+
 setDataLayout();
 
 return true;

``




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


[clang] [M68k] Change gcc register name from a7 to sp. (PR #87095)

2024-04-01 Thread Min-Yih Hsu via cfe-commits

mshockwave wrote:

Is it possible use `TargetInfo::getGCCRegAliases` to model the aliasing between 
a7 and sp?
Also, could you add a simple test?

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


[clang] [clang][FMV] Direct-call FMV callees from FMV callers (PR #80093)

2024-04-01 Thread Jon Roelofs via cfe-commits

jroelofs wrote:

I'm not sure llvm needs to know the priorities. I haven't had time to work on 
this, but my plan was to have something that attempts to step through the 
resolver instruction by instruction with known bits for the value loaded from 
`__aarch64_cpu_features.features` according to the caller's target features. If 
the return value is known, then we can fold away the resolver for that call 
site. If we encounter a loop, a call, or some other pattern we don't 
understand, then bail & leave that call site alone.

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


[clang] [clang][FMV] Direct-call FMV callees from FMV callers (PR #80093)

2024-04-01 Thread Erich Keane via cfe-commits

erichkeane wrote:

> I'm not sure llvm needs to know the priorities. I haven't had time to work on 
> this, but my plan was to have something that attempts to step through the 
> resolver instruction by instruction with known bits for the value loaded from 
> `__aarch64_cpu_features.features` according to the caller's target features. 
> If the return value is known, then we can fold away the resolver for that 
> call site. If we encounter a loop, a call, or some other pattern we don't 
> understand, then bail & leave that call site alone.

That seems sensible to me.  It would be nice to be able to recognize this /get 
this optimization for 'hand rolled' resolvers as well.

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


  1   2   3   4   >