[clang] [clang] Remove an incorrect assertion in ConstantFoldAttrs (PR #105789)

2024-08-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

Evaluating the attribute expression can be successful without resulting in a 
value. Namely, when the expression is of type void.



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


2 Files Affected:

- (modified) clang/lib/Sema/SemaAttr.cpp (+2-2) 
- (modified) clang/test/SemaCXX/attr-annotate.cpp (+4) 


``diff
diff --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp
index a1724820472b59..51354963c0831e 100644
--- a/clang/lib/Sema/SemaAttr.cpp
+++ b/clang/lib/Sema/SemaAttr.cpp
@@ -439,8 +439,8 @@ bool Sema::ConstantFoldAttrArgs(const AttributeCommonInfo 
&CI,
 Diag(Note.first, Note.second);
   return false;
 }
-assert(Eval.Val.hasValue());
-E = ConstantExpr::Create(Context, E, Eval.Val);
+if (Eval.Val.hasValue())
+  E = ConstantExpr::Create(Context, E, Eval.Val);
   }
 
   return true;
diff --git a/clang/test/SemaCXX/attr-annotate.cpp 
b/clang/test/SemaCXX/attr-annotate.cpp
index 846ef4119f1d7c..ff538fee9cb3c7 100644
--- a/clang/test/SemaCXX/attr-annotate.cpp
+++ b/clang/test/SemaCXX/attr-annotate.cpp
@@ -134,3 +134,7 @@ constexpr int foldable_but_invalid() {
 template  [[clang::annotate()]] void f2() {}
 // expected-error@-1 {{'annotate' attribute takes at least 1 argument}}
 }
+
+namespace test5 {
+  void bir [[clang::annotate("B", (void)1)]] ();
+}

``




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


[clang] [clang] Remove an incorrect assertion in ConstantFoldAttrs (PR #105789)

2024-08-23 Thread Timm Baeder via cfe-commits

tbaederr wrote:

I guess it might make sense to create the `ConstantExpr` in any case, even for 
a `None` `APValue`? Dumping the `ConstantExpr` didn't print any `APValue` 
though, so I was assuming that it ignores `None` anyway.

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


[clang] [RISCV][FMV] Support target_clones (PR #85786)

2024-08-23 Thread Piyou Chen via cfe-commits

https://github.com/BeMg updated https://github.com/llvm/llvm-project/pull/85786

>From 395ce72afbf9e4b12fcbfaf9cdbda8921c9ff72a Mon Sep 17 00:00:00 2001
From: Piyou Chen 
Date: Tue, 23 Jul 2024 19:59:06 -0700
Subject: [PATCH 01/12] [RISCV][FMV] Support target_clones

---
 .../clang/Basic/DiagnosticFrontendKinds.td|   4 +
 clang/include/clang/Basic/TargetInfo.h|   3 +-
 clang/include/clang/Sema/SemaRISCV.h  |   1 +
 clang/lib/AST/ASTContext.cpp  |  12 +
 clang/lib/CodeGen/CodeGenFunction.cpp | 106 -
 clang/lib/CodeGen/CodeGenFunction.h   |   3 +
 clang/lib/CodeGen/CodeGenModule.cpp   |   5 +-
 clang/lib/CodeGen/Targets/RISCV.cpp   |  35 +++
 clang/lib/Sema/SemaDeclAttr.cpp   |  30 +++
 clang/lib/Sema/SemaRISCV.cpp  |  10 +
 .../attr-target-clones-riscv-invalid.c|   8 +
 clang/test/CodeGen/attr-target-clones-riscv.c | 211 ++
 .../CodeGenCXX/attr-target-clones-riscv.cpp   | 210 +
 .../test/SemaCXX/attr-target-clones-riscv.cpp |  35 +++
 14 files changed, 670 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/CodeGen/attr-target-clones-riscv-invalid.c
 create mode 100644 clang/test/CodeGen/attr-target-clones-riscv.c
 create mode 100644 clang/test/CodeGenCXX/attr-target-clones-riscv.cpp
 create mode 100644 clang/test/SemaCXX/attr-target-clones-riscv.cpp

diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td 
b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index 8a1462c670d68f..0c870a1f3f1442 100644
--- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -378,4 +378,8 @@ def warn_missing_symbol_graph_dir : Warning<
 def err_ast_action_on_llvm_ir : Error<
   "cannot apply AST actions to LLVM IR file '%0'">,
   DefaultFatal;
+
+def err_os_unsupport_riscv_target_clones : Error<
+  "target_clones is currently only supported on Linux">;
+
 }
diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index a58fb5f9792720..f31d88a354ea28 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -1496,7 +1496,8 @@ class TargetInfo : public TransferrableTargetInfo,
   /// Identify whether this target supports multiversioning of functions,
   /// which requires support for cpu_supports and cpu_is functionality.
   bool supportsMultiVersioning() const {
-return getTriple().isX86() || getTriple().isAArch64();
+return getTriple().isX86() || getTriple().isAArch64() ||
+   getTriple().isRISCV();
   }
 
   /// Identify whether this target supports IFuncs.
diff --git a/clang/include/clang/Sema/SemaRISCV.h 
b/clang/include/clang/Sema/SemaRISCV.h
index d62fca8128b2a3..d7f17797283b86 100644
--- a/clang/include/clang/Sema/SemaRISCV.h
+++ b/clang/include/clang/Sema/SemaRISCV.h
@@ -43,6 +43,7 @@ class SemaRISCV : public SemaBase {
 
   void handleInterruptAttr(Decl *D, const ParsedAttr &AL);
   bool isAliasValid(unsigned BuiltinID, llvm::StringRef AliasName);
+  bool isValidFMVExtension(StringRef Ext);
 
   /// Indicate RISC-V vector builtin functions enabled or not.
   bool DeclareRVVBuiltins = false;
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index b201d201e1ea6a..a4d123219770bb 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -14181,6 +14181,18 @@ void 
ASTContext::getFunctionFeatureMap(llvm::StringMap &FeatureMap,
   Target->getTargetOpts().FeaturesAsWritten.begin(),
   Target->getTargetOpts().FeaturesAsWritten.end());
   Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, 
Features);
+} else if (Target->getTriple().isRISCV()) {
+  StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
+  std::vector Features;
+  if (VersionStr != "default") {
+ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
+Features.insert(Features.begin(), ParsedAttr.Features.begin(),
+ParsedAttr.Features.end());
+  }
+  Features.insert(Features.begin(),
+  Target->getTargetOpts().FeaturesAsWritten.begin(),
+  Target->getTargetOpts().FeaturesAsWritten.end());
+  Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, 
Features);
 } else {
   std::vector Features;
   StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index eff8c9f5694084..d625dde684933b 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -2877,12 +2877,116 @@ void CodeGenFunction::EmitMultiVersionResolver(
   case llvm::Triple::aarch64:
 EmitAArch64MultiVersionResolver(Resolver, Options);
 return;
+  case llvm::Triple::riscv32:
+  case 

[clang] [RISCV][FMV] Support target_clones (PR #85786)

2024-08-23 Thread Piyou Chen via cfe-commits


@@ -2877,10 +2877,144 @@ void CodeGenFunction::EmitMultiVersionResolver(
   case llvm::Triple::aarch64:
 EmitAArch64MultiVersionResolver(Resolver, Options);
 return;
+  case llvm::Triple::riscv32:
+  case llvm::Triple::riscv64:
+EmitRISCVMultiVersionResolver(Resolver, Options);
+return;
 
   default:
-assert(false && "Only implemented for x86 and AArch64 targets");
+assert(false && "Only implemented for x86, AArch64 and RISC-V targets");
+  }
+}
+
+static int getPrioiryFromAttrString(StringRef AttrStr) {
+  SmallVector Attrs;
+
+  AttrStr.split(Attrs, ";");
+
+  // Default Pri is zero.
+  int Pri = 0;
+  for (auto Attr : Attrs) {
+if (Attr.starts_with("priority=")) {
+  Attr.consume_front("priority=");
+  int Result;
+  if (!Attr.getAsInteger(0, Result)) {
+Pri = Result;
+  }
+}
+  }
+
+  return Pri;
+}
+
+void CodeGenFunction::EmitRISCVMultiVersionResolver(
+llvm::Function *Resolver, ArrayRef Options) {
+
+  if (getContext().getTargetInfo().getTriple().getOS() !=
+  llvm::Triple::OSType::Linux) {
+CGM.getDiags().Report(diag::err_os_unsupport_riscv_target_clones);
+return;
+  }
+
+  llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
+  Builder.SetInsertPoint(CurBlock);
+  EmitRISCVCpuInit();
+
+  bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
+  bool HasDefault = false;
+  unsigned DefaultIndex = 0;
+
+  SmallVector CurrOptions(
+  Options);
+
+  llvm::stable_sort(
+  CurrOptions, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
+  const CodeGenFunction::MultiVersionResolverOption &RHS) {
+return getPrioiryFromAttrString(LHS.Conditions.Features[0]) >
+   getPrioiryFromAttrString(RHS.Conditions.Features[0]);
+  });
+
+  // Check the each candidate function.
+  for (unsigned Index = 0; Index < CurrOptions.size(); Index++) {
+
+if (CurrOptions[Index].Conditions.Features[0].starts_with("default")) {

BeMg wrote:

Update testcase for semantic check

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


[clang] a69ba0a - [clang][bytecode][NFC] Get rid of const_casts in Move fns (#105698)

2024-08-23 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-08-23T09:16:22+02:00
New Revision: a69ba0a5f911ebdfd59b399e82ded8143e89e6cd

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

LOG: [clang][bytecode][NFC] Get rid of const_casts in Move fns (#105698)

Added: 


Modified: 
clang/lib/AST/ByteCode/Descriptor.cpp
clang/lib/AST/ByteCode/Descriptor.h

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Descriptor.cpp 
b/clang/lib/AST/ByteCode/Descriptor.cpp
index 47b8885c9ae379..170203fe818775 100644
--- a/clang/lib/AST/ByteCode/Descriptor.cpp
+++ b/clang/lib/AST/ByteCode/Descriptor.cpp
@@ -31,10 +31,9 @@ static void dtorTy(Block *, std::byte *Ptr, const Descriptor 
*) {
 }
 
 template 
-static void moveTy(Block *, const std::byte *Src, std::byte *Dst,
+static void moveTy(Block *, std::byte *Src, std::byte *Dst,
const Descriptor *) {
-  // FIXME: Get rid of the const_cast.
-  auto *SrcPtr = reinterpret_cast(const_cast(Src));
+  auto *SrcPtr = reinterpret_cast(Src);
   auto *DstPtr = reinterpret_cast(Dst);
   new (DstPtr) T(std::move(*SrcPtr));
 }
@@ -63,11 +62,9 @@ static void dtorArrayTy(Block *, std::byte *Ptr, const 
Descriptor *D) {
 }
 
 template 
-static void moveArrayTy(Block *, const std::byte *Src, std::byte *Dst,
+static void moveArrayTy(Block *, std::byte *Src, std::byte *Dst,
 const Descriptor *D) {
-  // FIXME: Get rid of the const_cast.
-  InitMapPtr &SrcIMP =
-  *reinterpret_cast(const_cast(Src));
+  InitMapPtr &SrcIMP = *reinterpret_cast(Src);
   if (SrcIMP) {
 // We only ever invoke the moveFunc when moving block contents to a
 // DeadBlock. DeadBlocks don't need InitMaps, so we destroy them here.
@@ -76,7 +73,7 @@ static void moveArrayTy(Block *, const std::byte *Src, 
std::byte *Dst,
   Src += sizeof(InitMapPtr);
   Dst += sizeof(InitMapPtr);
   for (unsigned I = 0, NE = D->getNumElems(); I < NE; ++I) {
-auto *SrcPtr = &reinterpret_cast(const_cast(Src))[I];
+auto *SrcPtr = &reinterpret_cast(Src)[I];
 auto *DstPtr = &reinterpret_cast(Dst)[I];
 new (DstPtr) T(std::move(*SrcPtr));
   }
@@ -126,7 +123,7 @@ static void dtorArrayDesc(Block *B, std::byte *Ptr, const 
Descriptor *D) {
   }
 }
 
-static void moveArrayDesc(Block *B, const std::byte *Src, std::byte *Dst,
+static void moveArrayDesc(Block *B, std::byte *Src, std::byte *Dst,
   const Descriptor *D) {
   const unsigned NumElems = D->getNumElems();
   const unsigned ElemSize =
@@ -134,11 +131,11 @@ static void moveArrayDesc(Block *B, const std::byte *Src, 
std::byte *Dst,
 
   unsigned ElemOffset = 0;
   for (unsigned I = 0; I < NumElems; ++I, ElemOffset += ElemSize) {
-const auto *SrcPtr = Src + ElemOffset;
+auto *SrcPtr = Src + ElemOffset;
 auto *DstPtr = Dst + ElemOffset;
 
-const auto *SrcDesc = reinterpret_cast(SrcPtr);
-const auto *SrcElemLoc = reinterpret_cast(SrcDesc + 1);
+auto *SrcDesc = reinterpret_cast(SrcPtr);
+auto *SrcElemLoc = reinterpret_cast(SrcDesc + 1);
 auto *DstDesc = reinterpret_cast(DstPtr);
 auto *DstElemLoc = reinterpret_cast(DstDesc + 1);
 
@@ -233,7 +230,7 @@ static void dtorRecord(Block *B, std::byte *Ptr, const 
Descriptor *D) {
 destroyBase(B, Ptr, F.Desc, F.Offset);
 }
 
-static void moveRecord(Block *B, const std::byte *Src, std::byte *Dst,
+static void moveRecord(Block *B, std::byte *Src, std::byte *Dst,
const Descriptor *D) {
   assert(D);
   assert(D->ElemRecord);

diff  --git a/clang/lib/AST/ByteCode/Descriptor.h 
b/clang/lib/AST/ByteCode/Descriptor.h
index 41899c3bd6831a..82f90430f7f4e5 100644
--- a/clang/lib/AST/ByteCode/Descriptor.h
+++ b/clang/lib/AST/ByteCode/Descriptor.h
@@ -44,7 +44,7 @@ using BlockDtorFn = void (*)(Block *Storage, std::byte 
*FieldPtr,
 /// blocks are persisted: the move function copies all inline descriptors and
 /// non-trivial fields, as existing pointers might need to reference those
 /// descriptors. Data is not copied since it cannot be legally read.
-using BlockMoveFn = void (*)(Block *Storage, const std::byte *SrcFieldPtr,
+using BlockMoveFn = void (*)(Block *Storage, std::byte *SrcFieldPtr,
  std::byte *DstFieldPtr,
  const Descriptor *FieldDesc);
 



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


[clang] [clang][bytecode][NFC] Get rid of const_casts in Move fns (PR #105698)

2024-08-23 Thread Timm Baeder via cfe-commits

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


[clang] e5f196e - [NFCI] [C++20] [Modules] Relax the case for duplicated declaration in multiple module units for explicit specialization

2024-08-23 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2024-08-23T15:35:57+08:00
New Revision: e5f196e4e7e3aec5c19adeacb7191ed0a099ea9a

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

LOG: [NFCI] [C++20] [Modules] Relax the case for duplicated declaration in 
multiple module units for explicit specialization

Relax the case for duplicated declaration in multiple module units for
explicit specialization and refactor the implementation of
checkMultipleDefinitionInNamedModules a little bit.

This is intended to not affect any end users since it only relaxes the
condition to emit an error.

Added: 


Modified: 
clang/lib/Serialization/ASTReaderDecl.cpp

Removed: 




diff  --git a/clang/lib/Serialization/ASTReaderDecl.cpp 
b/clang/lib/Serialization/ASTReaderDecl.cpp
index ef160228933c59..a6da103ed9799e 100644
--- a/clang/lib/Serialization/ASTReaderDecl.cpp
+++ b/clang/lib/Serialization/ASTReaderDecl.cpp
@@ -3692,12 +3692,6 @@ static void inheritDefaultTemplateArguments(ASTContext 
&Context,
 //the program is ill-formed;
 static void checkMultipleDefinitionInNamedModules(ASTReader &Reader, Decl *D,
   Decl *Previous) {
-  Module *M = Previous->getOwningModule();
-
-  // We only care about the case in named modules.
-  if (!M || !M->isNamedModule())
-return;
-
   // If it is previous implcitly introduced, it is not meaningful to
   // diagnose it.
   if (Previous->isImplicit())
@@ -3714,16 +3708,21 @@ static void 
checkMultipleDefinitionInNamedModules(ASTReader &Reader, Decl *D,
   // FIXME: Maybe this shows the implicit instantiations may have incorrect
   // module owner ships. But given we've finished the compilation of a module,
   // how can we add new entities to that module?
-  if (auto *VTSD = dyn_cast(Previous);
-  VTSD && !VTSD->isExplicitSpecialization())
+  if (isa(Previous))
 return;
-  if (auto *CTSD = dyn_cast(Previous);
-  CTSD && !CTSD->isExplicitSpecialization())
+  if (isa(Previous))
+return;
+  if (auto *Func = dyn_cast(Previous);
+  Func && Func->getTemplateSpecializationInfo())
+return;
+
+  Module *M = Previous->getOwningModule();
+  if (!M)
+return;
+
+  // We only forbids merging decls within named modules.
+  if (!M->isNamedModule())
 return;
-  if (auto *Func = dyn_cast(Previous))
-if (auto *FTSI = Func->getTemplateSpecializationInfo();
-FTSI && !FTSI->isExplicitSpecialization())
-  return;
 
   // It is fine if they are in the same module.
   if (Reader.getContext().isInSameModule(M, D->getOwningModule()))



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


[clang] [clang][ASTImporter] New fix for default template parameter values. (PR #101836)

2024-08-23 Thread Balázs Kéri via cfe-commits


@@ -5968,11 +5962,21 @@ 
ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
   }
 
   if (D->hasDefaultArgument()) {
+// Default argument can be "inherited" when it has a reference to the
+// previous declaration (of the default argument) which is stored only 
once.
+// Here we import the default argument in any case, and the inherited state
+// is updated later after the parent template was created. If the
+// inherited-from object would be imported here it causes more difficulties
+// (parent template may not be created yet and import loops can occur).
 Expected ToDefaultArgOrErr =
 import(D->getDefaultArgument());
 if (!ToDefaultArgOrErr)
   return ToDefaultArgOrErr.takeError();
-ToD->setDefaultArgument(ToD->getASTContext(), *ToDefaultArgOrErr);
+// The just called import process can trigger import of the parent template
+// which can update the default argument value to "inherited". This should
+// not be changed.
+if (!ToD->hasDefaultArgument())
+  ToD->setDefaultArgument(ToD->getASTContext(), *ToDefaultArgOrErr);

balazske wrote:

The order of redeclarable declarations can change during import, `ASTImporter` 
worked always this way. In the "order" I mean order got with `getPreviousDecl`. 
If we go back the decl chain of a template with default argument, the first one 
should have the non-inherited default argument and all others should have an 
inherited one. This property is preserved now, even if the "To" AST has 
different declaration chain than the "From" AST, always the first occurrence of 
a template will have the non-inherited default argument.

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


[clang] 39986f0 - [NFCI] [Serialization] Use demoteThisDefinitionToDeclaration instead of setCompleteDefinition(false) for CXXRecordDecl

2024-08-23 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2024-08-23T15:43:43+08:00
New Revision: 39986f0b4d797e4ad3c12607f2b4abe2322b82bb

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

LOG: [NFCI] [Serialization] Use demoteThisDefinitionToDeclaration instead of 
setCompleteDefinition(false) for CXXRecordDecl

When we merge the definition for CXXRecordDecl, we would use
setCompleteDefinition(false) to mark the merged definition. But this was
not the correct/good interface. We can't know that the merged definition
was a definition then. And actually, we provided an interface for this:
demoteThisDefinitionToDeclaration.

So this patch tries to use the correct API.

This was found in the downstream developing. This is not strictly NFC
but it is intended to be NFC for every end users.

Added: 


Modified: 
clang/lib/Serialization/ASTReaderDecl.cpp

Removed: 




diff  --git a/clang/lib/Serialization/ASTReaderDecl.cpp 
b/clang/lib/Serialization/ASTReaderDecl.cpp
index a6da103ed9799e..4d9d024796716e 100644
--- a/clang/lib/Serialization/ASTReaderDecl.cpp
+++ b/clang/lib/Serialization/ASTReaderDecl.cpp
@@ -2064,7 +2064,7 @@ void ASTDeclMerger::MergeDefinitionData(
 Reader.MergedDeclContexts.insert(std::make_pair(MergeDD.Definition,
 DD.Definition));
 Reader.PendingDefinitions.erase(MergeDD.Definition);
-MergeDD.Definition->setCompleteDefinition(false);
+MergeDD.Definition->demoteThisDefinitionToDeclaration();
 Reader.mergeDefinitionVisibility(DD.Definition, MergeDD.Definition);
 assert(!Reader.Lookups.contains(MergeDD.Definition) &&
"already loaded pending lookups for merged definition");
@@ -2175,6 +2175,9 @@ void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl 
*D, bool Update,
   D->DefinitionData = Canon->DefinitionData;
   ReadCXXDefinitionData(*DD, D, LambdaContext, IndexInLambdaContext);
 
+  // Mark this declaration as being a definition.
+  D->setCompleteDefinition(true);
+
   // We might already have a 
diff erent definition for this record. This can
   // happen either because we're reading an update record, or because we've
   // already done some merging. Either way, just merge into it.
@@ -2183,9 +2186,6 @@ void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl 
*D, bool Update,
 return;
   }
 
-  // Mark this declaration as being a definition.
-  D->setCompleteDefinition(true);
-
   // If this is not the first declaration or is an update record, we can have
   // other redeclarations already. Make a note that we need to propagate the
   // DefinitionData pointer onto them.



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


[clang] [analyzer] Detect leak of a stack address through output arguments 2/3 (PR #105653)

2024-08-23 Thread Arseniy Zaostrovnykh via cfe-commits

https://github.com/necto updated 
https://github.com/llvm/llvm-project/pull/105653

>From db68dcfba96bfbf9367ba4159b6bf179c8c56f4f Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Tue, 20 Aug 2024 10:26:38 +0200
Subject: [PATCH 1/4] [analyzer] [NFC] Add tests for and refactor
 StackAddrEscapeChecker

These tests and refactoring are preparatory for the upcoming changes:
detection of the indirect leak via global variables and output parameters.

CPP-4734
---
 .../Checkers/StackAddrEscapeChecker.cpp   |  71 ++-
 clang/test/Analysis/stack-addr-ps.c   |  31 +
 clang/test/Analysis/stack-addr-ps.cpp | 596 ++
 3 files changed, 665 insertions(+), 33 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
index ea09c43cc5ce90..2bd4ca4528de8b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
@@ -288,12 +288,37 @@ void StackAddrEscapeChecker::checkPreStmt(const 
ReturnStmt *RS,
   EmitStackError(C, R, RetE);
 }
 
+std::optional printReferrer(const MemRegion *Referrer) {
+  assert(Referrer);
+  const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
+if (isa(Space))
+  return "static";
+if (isa(Space))
+  return "global";
+assert(isa(Space));
+return "stack";
+  }(Referrer->getMemorySpace());
+
+  // We should really only have VarRegions here.
+  // Anything else is really surprising, and we should get notified if such
+  // ever happens.
+  const auto *ReferrerVar = dyn_cast(Referrer);
+  if (!ReferrerVar) {
+assert(false && "We should have a VarRegion here");
+return std::nullopt; // Defensively skip this one.
+  }
+  const std::string ReferrerVarName =
+  ReferrerVar->getDecl()->getDeclName().getAsString();
+
+  return (ReferrerMemorySpace + " variable '" + ReferrerVarName + "'").str();
+}
+
 void StackAddrEscapeChecker::checkEndFunction(const ReturnStmt *RS,
   CheckerContext &Ctx) const {
   if (!ChecksEnabled[CK_StackAddrEscapeChecker])
 return;
 
-  ProgramStateRef State = Ctx.getState();
+  ExplodedNode *Node = Ctx.getPredecessor();
 
   // Iterate over all bindings to global variables and see if it contains
   // a memory region in the stack space.
@@ -315,15 +340,10 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   if (!ReferrerMemSpace || !ReferredMemSpace)
 return false;
 
-  const auto *ReferrerFrame = ReferrerMemSpace->getStackFrame();
-  const auto *ReferredFrame = ReferredMemSpace->getStackFrame();
-
-  if (ReferrerMemSpace && ReferredMemSpace) {
-if (ReferredFrame == PoppedFrame &&
-ReferrerFrame->isParentOf(PoppedFrame)) {
-  V.emplace_back(Referrer, Referred);
-  return true;
-}
+  if (ReferredMemSpace->getStackFrame() == PoppedFrame &&
+  ReferrerMemSpace->getStackFrame()->isParentOf(PoppedFrame)) {
+V.emplace_back(Referrer, Referred);
+return true;
   }
   return false;
 }
@@ -352,6 +372,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   };
 
   CallBack Cb(Ctx);
+  ProgramStateRef State = Node->getState();
   State->getStateManager().getStoreManager().iterBindings(State->getStore(),
   Cb);
 
@@ -359,7 +380,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 return;
 
   // Generate an error node.
-  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State);
+  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State, Node);
   if (!N)
 return;
 
@@ -374,13 +395,13 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 
 // Generate a report for this bug.
 const StringRef CommonSuffix =
-"upon returning to the caller.  This will be a dangling reference";
+" upon returning to the caller.  This will be a dangling reference";
 SmallString<128> Buf;
 llvm::raw_svector_ostream Out(Buf);
 const SourceRange Range = genName(Out, Referred, Ctx.getASTContext());
 
 if (isa(Referrer)) {
-  Out << " is still referred to by a temporary object on the stack "
+  Out << " is still referred to by a temporary object on the stack"
   << CommonSuffix;
   auto Report =
   std::make_unique(*BT_stackleak, Out.str(), 
N);
@@ -390,28 +411,12 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   return;
 }
 
-const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
-  if (isa(Space))
-return "static";
-  if (isa(Space))
-return "global";
-  assert(isa(Space));
-  return "stack";
-}(Referrer->getMemorySpace());
-
-// We should really only have VarRegions here.
-// Anything else is reall

[clang] [analyzer] Detect leak of a stack address through output arguments 2/3 (PR #105653)

2024-08-23 Thread Arseniy Zaostrovnykh via cfe-commits


@@ -297,20 +314,29 @@ std::optional printReferrer(const MemRegion 
*Referrer) {
   return "global";
 assert(isa(Space));
 return "stack";
-  }(Referrer->getMemorySpace());
-
-  // We should really only have VarRegions here.
-  // Anything else is really surprising, and we should get notified if such
-  // ever happens.
-  const auto *ReferrerVar = dyn_cast(Referrer);
-  if (!ReferrerVar) {
-assert(false && "We should have a VarRegion here");
-return std::nullopt; // Defensively skip this one.
+  }(getStackOrGlobalSpaceRegion(Referrer));
+
+  while (!Referrer->canPrintPretty()) {
+if (const auto *SymReg = dyn_cast(Referrer)) {
+  Referrer = SymReg->getSymbol()->getOriginRegion()->getBaseRegion();

necto wrote:

> Consider adding a testcase which shows this limitation.

Added the test case: f223714

> Be careful with getOriginRegion(), it will return null if the symbol is not a 
> SymbolRegionValue or a SymbolDerived (e.g. a SymbolConjured returned by an 
> opaque function call)!



Added a defensive check: 4afbb63

However, I suspect it would never trigger, because I think a region containing 
a conjured symbol with no origin region associated would also have no known 
memory space so it would not reach this point because I discard such region 
[here](https://github.com/necto/llvm-project/blob/az/CPP-4734-stack-leak-output-arg/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp#L302)

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


[clang] [clang] Increase the default expression nesting limit (PR #104717)

2024-08-23 Thread Mikael Holmén via cfe-commits

mikaelholmen wrote:

We also see the ASan complaints on ```Parser/parser_overflow.c``` in downstream 
bots for several days now.
A workaround would be appreciated if a real fix is hard.

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


[clang] [analyzer] Detect leak of a stack address through output arguments 2/3 (PR #105653)

2024-08-23 Thread Donát Nagy via cfe-commits


@@ -297,20 +314,29 @@ std::optional printReferrer(const MemRegion 
*Referrer) {
   return "global";
 assert(isa(Space));
 return "stack";
-  }(Referrer->getMemorySpace());
-
-  // We should really only have VarRegions here.
-  // Anything else is really surprising, and we should get notified if such
-  // ever happens.
-  const auto *ReferrerVar = dyn_cast(Referrer);
-  if (!ReferrerVar) {
-assert(false && "We should have a VarRegion here");
-return std::nullopt; // Defensively skip this one.
+  }(getStackOrGlobalSpaceRegion(Referrer));
+
+  while (!Referrer->canPrintPretty()) {
+if (const auto *SymReg = dyn_cast(Referrer)) {
+  Referrer = SymReg->getSymbol()->getOriginRegion()->getBaseRegion();
+} else if (isa(Referrer)) {
+  // Skip members of a class, it is handled by
+  // warn_bind_ref_member_to_parameter_addr

NagyDonat wrote:

I see, it seems that `CheckExprLifetime.cpp` was probably refactored, because 
the message that you reference does not appear and instead there are two very 
similarly named messages:

![image](https://github.com/user-attachments/assets/d1384f02-d375-4d5c-9469-a77b5f58bb32)

https://github.com/llvm/llvm-project/blame/f53bfa39a7dae444650a9c0e16d52301a733f5fc/clang/lib/Sema/CheckExprLifetime.cpp#L1166

You should probably update the name `warn_bind_ref_member_to_parameter_addr` to 
either `warn_bind_ref_member_to_parameter` or 
`warn_init_ptr_member_to_parameter_addr` (whichever is the right one) _and_ 
also mention `CheckExprLifetime.cpp` as a less accurate but more robust 
reference.

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


[clang] [C++20] [Modules] Warn for duplicated decls in mutliple module units (PR #105799)

2024-08-23 Thread Chuanqi Xu via cfe-commits

https://github.com/ChuanqiXu9 created 
https://github.com/llvm/llvm-project/pull/105799

It is a long standing issue that the duplicated declarations in multiple module 
units would cause the compilation performance to get slowed down. And there are 
many questions or issue reports. So I think it is better to add a warning for 
it.

And given this is not because the users' code violates the language 
specification or any best practices, the warning is disabled by default even if 
`-Wall` is specified. The users need to specify the warning explcitly or use 
`Weverything`.

The documentation will add separately.

>From 3b5ee579f1201d6891147026f0d71d91303e59bd Mon Sep 17 00:00:00 2001
From: Chuanqi Xu 
Date: Fri, 23 Aug 2024 16:34:34 +0800
Subject: [PATCH] [C++20] [Modules] Warn for duplicated decls in mutliple
 module units

It is a long standing issue that the duplicated declarations in multiple
module units would cause the compilation performance to get slowed down.
And there are many questions or issue reports. So I think it is better
to add a warning for it.

And given this is not because the users' code violates the language
specification or any best practices, the warning is disabled by default
even if `-Wall` is specified. The users need to specify the warning
explcitly or use `Weverything`.
---
 .../Basic/DiagnosticSerializationKinds.td |  6 ++
 clang/include/clang/Serialization/ASTReader.h |  6 ++
 clang/lib/Serialization/ASTReader.cpp | 39 +
 clang/lib/Serialization/ASTReaderDecl.cpp | 21 -
 ...warn-duplicated-decls-in-module-units.cppm | 83 +++
 5 files changed, 152 insertions(+), 3 deletions(-)
 create mode 100644 
clang/test/Modules/warn-duplicated-decls-in-module-units.cppm

diff --git a/clang/include/clang/Basic/DiagnosticSerializationKinds.td 
b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
index 9854972cbfe7e4..253a955431997b 100644
--- a/clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -134,6 +134,12 @@ def warn_module_system_bit_conflict : Warning<
   "as a non-system module; any difference in diagnostic options will be 
ignored">,
   InGroup;
 
+def warn_decls_in_multiple_modules : Warning<
+  "declaration %0 is detected to be defined in multiple module units, first is 
from '%1' and second is from '%2'; "
+  "the compiler may not be good at merging the definitions. ">,
+  InGroup>,
+  DefaultIgnore;
+
 def err_failed_to_find_module_file : Error<
   "failed to find module file for module '%0'">;
 } // let CategoryName
diff --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index 4593213c5f43ce..2d8952ddbd71df 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -648,6 +648,12 @@ class ASTReader
   /// performed deduplication.
   llvm::SetVector PendingMergedDefinitionsToDeduplicate;
 
+  /// The duplicated definitions in module units which are pending to be 
warned.
+  /// We need to delay it to wait for the loading of definitions since we don't
+  /// want to warn for forward declarations.
+  llvm::SmallVector>
+  PendingWarningForDuplicatedDefsInModuleUnits;
+
   /// Read the record that describes the lexical contents of a DC.
   bool ReadLexicalDeclContextStorage(ModuleFile &M,
  llvm::BitstreamCursor &Cursor,
diff --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index fa9b815239dbb6..be83805f1e92b9 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -9955,6 +9955,45 @@ void ASTReader::finishPendingActions() {
   }
   PendingDefinitions.clear();
 
+  for (auto [D, Previous] : PendingWarningForDuplicatedDefsInModuleUnits) {
+auto hasDefinitionImpl = [this](Decl *D, auto hasDefinitionImpl) {
+  if (auto *VD = dyn_cast(D))
+return VD->isThisDeclarationADefinition() ||
+   VD->isThisDeclarationADemotedDefinition();
+
+  if (auto *TD = dyn_cast(D))
+return TD->isThisDeclarationADefinition() ||
+   TD->isThisDeclarationADemotedDefinition();
+
+  if (auto *FD = dyn_cast(D))
+return FD->isThisDeclarationADefinition() || PendingBodies.count(FD);
+
+  if (auto *RTD = dyn_cast(D))
+return hasDefinitionImpl(RTD->getTemplatedDecl(), hasDefinitionImpl);
+
+  // Conservatively return false here.
+  return false;
+};
+
+auto hasDefinition = [this, &hasDefinitionImpl](Decl *D) {
+  return hasDefinitionImpl(D, hasDefinitionImpl);
+};
+
+// It is not good to prevent multiple declarations since the forward
+// declaration is common. Let's try to avoid duplicated definitions
+// only.
+if (!hasDefinition(D) || !hasDefinition(Previous))
+  continue;
+
+Module *PM = Previous->getOwningModule();
+Module *DM = D->getOwnin

[clang] [C++20] [Modules] Warn for duplicated decls in mutliple module units (PR #105799)

2024-08-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-modules

Author: Chuanqi Xu (ChuanqiXu9)


Changes

It is a long standing issue that the duplicated declarations in multiple module 
units would cause the compilation performance to get slowed down. And there are 
many questions or issue reports. So I think it is better to add a warning for 
it.

And given this is not because the users' code violates the language 
specification or any best practices, the warning is disabled by default even if 
`-Wall` is specified. The users need to specify the warning explcitly or use 
`Weverything`.

The documentation will add separately.

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


5 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticSerializationKinds.td (+6) 
- (modified) clang/include/clang/Serialization/ASTReader.h (+6) 
- (modified) clang/lib/Serialization/ASTReader.cpp (+39) 
- (modified) clang/lib/Serialization/ASTReaderDecl.cpp (+18-3) 
- (added) clang/test/Modules/warn-duplicated-decls-in-module-units.cppm (+83) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticSerializationKinds.td 
b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
index 9854972cbfe7e4..253a955431997b 100644
--- a/clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -134,6 +134,12 @@ def warn_module_system_bit_conflict : Warning<
   "as a non-system module; any difference in diagnostic options will be 
ignored">,
   InGroup;
 
+def warn_decls_in_multiple_modules : Warning<
+  "declaration %0 is detected to be defined in multiple module units, first is 
from '%1' and second is from '%2'; "
+  "the compiler may not be good at merging the definitions. ">,
+  InGroup>,
+  DefaultIgnore;
+
 def err_failed_to_find_module_file : Error<
   "failed to find module file for module '%0'">;
 } // let CategoryName
diff --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index 4593213c5f43ce..2d8952ddbd71df 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -648,6 +648,12 @@ class ASTReader
   /// performed deduplication.
   llvm::SetVector PendingMergedDefinitionsToDeduplicate;
 
+  /// The duplicated definitions in module units which are pending to be 
warned.
+  /// We need to delay it to wait for the loading of definitions since we don't
+  /// want to warn for forward declarations.
+  llvm::SmallVector>
+  PendingWarningForDuplicatedDefsInModuleUnits;
+
   /// Read the record that describes the lexical contents of a DC.
   bool ReadLexicalDeclContextStorage(ModuleFile &M,
  llvm::BitstreamCursor &Cursor,
diff --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index fa9b815239dbb6..be83805f1e92b9 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -9955,6 +9955,45 @@ void ASTReader::finishPendingActions() {
   }
   PendingDefinitions.clear();
 
+  for (auto [D, Previous] : PendingWarningForDuplicatedDefsInModuleUnits) {
+auto hasDefinitionImpl = [this](Decl *D, auto hasDefinitionImpl) {
+  if (auto *VD = dyn_cast(D))
+return VD->isThisDeclarationADefinition() ||
+   VD->isThisDeclarationADemotedDefinition();
+
+  if (auto *TD = dyn_cast(D))
+return TD->isThisDeclarationADefinition() ||
+   TD->isThisDeclarationADemotedDefinition();
+
+  if (auto *FD = dyn_cast(D))
+return FD->isThisDeclarationADefinition() || PendingBodies.count(FD);
+
+  if (auto *RTD = dyn_cast(D))
+return hasDefinitionImpl(RTD->getTemplatedDecl(), hasDefinitionImpl);
+
+  // Conservatively return false here.
+  return false;
+};
+
+auto hasDefinition = [this, &hasDefinitionImpl](Decl *D) {
+  return hasDefinitionImpl(D, hasDefinitionImpl);
+};
+
+// It is not good to prevent multiple declarations since the forward
+// declaration is common. Let's try to avoid duplicated definitions
+// only.
+if (!hasDefinition(D) || !hasDefinition(Previous))
+  continue;
+
+Module *PM = Previous->getOwningModule();
+Module *DM = D->getOwningModule();
+Diag(D->getLocation(), diag::warn_decls_in_multiple_modules)
+<< cast(Previous) << PM->getTopLevelModuleName()
+<< (DM ? DM->getTopLevelModuleName() : "global module");
+Diag(Previous->getLocation(), diag::note_also_found);
+  }
+  PendingWarningForDuplicatedDefsInModuleUnits.clear();
+
   // Load the bodies of any functions or methods we've encountered. We do
   // this now (delayed) so that we can be sure that the declaration chains
   // have been fully wired up (hasBody relies on this).
diff --git a/clang/lib/Serialization/ASTReaderDecl.cpp 
b/clang/lib/Serialization/ASTReaderDecl.cpp
index 4d9d024796716e..d1b77358d0cde4 100644
--- a/

[clang] [clang][bytecode] Reject void InitListExpr differently (PR #105802)

2024-08-23 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr created 
https://github.com/llvm/llvm-project/pull/105802

This reverts c79d1fa540390f6e37e1ea326153559eeadd0de6 and 
125aa10b3d645bd26523a1bc321bb2e6b1cf04e1

Instead, use the previous approach but allow void-typed InitListExprs with 0 
initializers.

>From ea0509c618a49c3a665a44ef88a0824bac70979f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Thu, 22 Aug 2024 18:52:27 +0200
Subject: [PATCH] [clang][bytecode] Reject void InitListExpr differently

This reverts c79d1fa540390f6e37e1ea326153559eeadd0de6
and 125aa10b3d645bd26523a1bc321bb2e6b1cf04e1

Instead, use the previous approach but allow void-typed InitListExprs
with 0 initializers.
---
 clang/lib/AST/ByteCode/Compiler.cpp | 26 --
 clang/test/AST/ByteCode/c.c |  7 ++-
 2 files changed, 22 insertions(+), 11 deletions(-)

diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 3a3927a9671345..b70d6cc8567fbe 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -1344,6 +1344,16 @@ bool Compiler::VisitArraySubscriptExpr(const 
ArraySubscriptExpr *E) {
 template 
 bool Compiler::visitInitList(ArrayRef Inits,
   const Expr *ArrayFiller, const Expr *E) {
+  QualType QT = E->getType();
+  if (const auto *AT = QT->getAs())
+QT = AT->getValueType();
+
+  if (QT->isVoidType()) {
+if (Inits.size() == 0)
+  return true;
+return this->emitInvalid(E);
+  }
+
   // Handle discarding first.
   if (DiscardResult) {
 for (const Expr *Init : Inits) {
@@ -1353,13 +1363,6 @@ bool Compiler::visitInitList(ArrayRef Inits,
 return true;
   }
 
-  QualType QT = E->getType();
-  if (const auto *AT = QT->getAs())
-QT = AT->getValueType();
-
-  if (QT->isVoidType())
-return this->emitInvalid(E);
-
   // Primitive values.
   if (std::optional T = classify(QT)) {
 assert(!DiscardResult);
@@ -3275,9 +3278,12 @@ template  bool 
Compiler::visit(const Expr *E) {
   if (E->getType().isNull())
 return false;
 
+  if (E->getType()->isVoidType())
+return this->discard(E);
+
   // Create local variable to hold the return value.
-  if (!E->getType()->isVoidType() && !E->isGLValue() &&
-  !E->getType()->isAnyComplexType() && !classify(E->getType())) {
+  if (!E->isGLValue() && !E->getType()->isAnyComplexType() &&
+  !classify(E->getType())) {
 std::optional LocalIndex = allocateLocal(E);
 if (!LocalIndex)
   return false;
@@ -5171,7 +5177,7 @@ bool Compiler::VisitUnaryOperator(const 
UnaryOperator *E) {
 // We should already have a pointer when we get here.
 return this->delegate(SubExpr);
   case UO_Deref: // *x
-if (DiscardResult || E->getType()->isVoidType())
+if (DiscardResult)
   return this->discard(SubExpr);
 return this->visit(SubExpr);
   case UO_Not: // ~x
diff --git a/clang/test/AST/ByteCode/c.c b/clang/test/AST/ByteCode/c.c
index 60f4d6ad1b2967..7cb7f96049f2de 100644
--- a/clang/test/AST/ByteCode/c.c
+++ b/clang/test/AST/ByteCode/c.c
@@ -298,7 +298,6 @@ void T1(void) {
 enum teste1 test1f(void), (*test1)(void) = test1f; // pedantic-warning {{ISO C 
forbids forward references to 'enum' types}}
 enum teste1 { TEST1 };
 
-
 void func(void) {
   _Static_assert(func + 1 - func == 1, ""); // pedantic-warning {{arithmetic 
on a pointer to the function type}} \
 // pedantic-warning {{arithmetic 
on pointers to the function type}} \
@@ -313,3 +312,9 @@ void func(void) {
   func - 0xdeadUL; // all-warning {{expression result unused}} \
// pedantic-warning {{arithmetic on a pointer 
to the function type}}
 }
+
+void foo3 (void)
+{
+ void* x = 0;
+ void* y = &*x;
+}

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


[clang] [clang][bytecode] Reject void InitListExpr differently (PR #105802)

2024-08-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

This reverts c79d1fa540390f6e37e1ea326153559eeadd0de6 and 
125aa10b3d645bd26523a1bc321bb2e6b1cf04e1

Instead, use the previous approach but allow void-typed InitListExprs with 0 
initializers.

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


2 Files Affected:

- (modified) clang/lib/AST/ByteCode/Compiler.cpp (+16-10) 
- (modified) clang/test/AST/ByteCode/c.c (+6-1) 


``diff
diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 3a3927a9671345..b70d6cc8567fbe 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -1344,6 +1344,16 @@ bool Compiler::VisitArraySubscriptExpr(const 
ArraySubscriptExpr *E) {
 template 
 bool Compiler::visitInitList(ArrayRef Inits,
   const Expr *ArrayFiller, const Expr *E) {
+  QualType QT = E->getType();
+  if (const auto *AT = QT->getAs())
+QT = AT->getValueType();
+
+  if (QT->isVoidType()) {
+if (Inits.size() == 0)
+  return true;
+return this->emitInvalid(E);
+  }
+
   // Handle discarding first.
   if (DiscardResult) {
 for (const Expr *Init : Inits) {
@@ -1353,13 +1363,6 @@ bool Compiler::visitInitList(ArrayRef Inits,
 return true;
   }
 
-  QualType QT = E->getType();
-  if (const auto *AT = QT->getAs())
-QT = AT->getValueType();
-
-  if (QT->isVoidType())
-return this->emitInvalid(E);
-
   // Primitive values.
   if (std::optional T = classify(QT)) {
 assert(!DiscardResult);
@@ -3275,9 +3278,12 @@ template  bool 
Compiler::visit(const Expr *E) {
   if (E->getType().isNull())
 return false;
 
+  if (E->getType()->isVoidType())
+return this->discard(E);
+
   // Create local variable to hold the return value.
-  if (!E->getType()->isVoidType() && !E->isGLValue() &&
-  !E->getType()->isAnyComplexType() && !classify(E->getType())) {
+  if (!E->isGLValue() && !E->getType()->isAnyComplexType() &&
+  !classify(E->getType())) {
 std::optional LocalIndex = allocateLocal(E);
 if (!LocalIndex)
   return false;
@@ -5171,7 +5177,7 @@ bool Compiler::VisitUnaryOperator(const 
UnaryOperator *E) {
 // We should already have a pointer when we get here.
 return this->delegate(SubExpr);
   case UO_Deref: // *x
-if (DiscardResult || E->getType()->isVoidType())
+if (DiscardResult)
   return this->discard(SubExpr);
 return this->visit(SubExpr);
   case UO_Not: // ~x
diff --git a/clang/test/AST/ByteCode/c.c b/clang/test/AST/ByteCode/c.c
index 60f4d6ad1b2967..7cb7f96049f2de 100644
--- a/clang/test/AST/ByteCode/c.c
+++ b/clang/test/AST/ByteCode/c.c
@@ -298,7 +298,6 @@ void T1(void) {
 enum teste1 test1f(void), (*test1)(void) = test1f; // pedantic-warning {{ISO C 
forbids forward references to 'enum' types}}
 enum teste1 { TEST1 };
 
-
 void func(void) {
   _Static_assert(func + 1 - func == 1, ""); // pedantic-warning {{arithmetic 
on a pointer to the function type}} \
 // pedantic-warning {{arithmetic 
on pointers to the function type}} \
@@ -313,3 +312,9 @@ void func(void) {
   func - 0xdeadUL; // all-warning {{expression result unused}} \
// pedantic-warning {{arithmetic on a pointer 
to the function type}}
 }
+
+void foo3 (void)
+{
+ void* x = 0;
+ void* y = &*x;
+}

``




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


[clang] [analyzer] Detect leak of a stack address through output arguments 2/3 (PR #105653)

2024-08-23 Thread Donát Nagy via cfe-commits


@@ -297,20 +314,29 @@ std::optional printReferrer(const MemRegion 
*Referrer) {
   return "global";
 assert(isa(Space));
 return "stack";
-  }(Referrer->getMemorySpace());
-
-  // We should really only have VarRegions here.
-  // Anything else is really surprising, and we should get notified if such
-  // ever happens.
-  const auto *ReferrerVar = dyn_cast(Referrer);
-  if (!ReferrerVar) {
-assert(false && "We should have a VarRegion here");
-return std::nullopt; // Defensively skip this one.
+  }(getStackOrGlobalSpaceRegion(Referrer));
+
+  while (!Referrer->canPrintPretty()) {
+if (const auto *SymReg = dyn_cast(Referrer)) {
+  Referrer = SymReg->getSymbol()->getOriginRegion()->getBaseRegion();

NagyDonat wrote:

> a region containing a conjured symbol with no origin region associated would 
> also have no known memory space so it would not reach this point because I 
> discard such region 
> [here](https://github.com/necto/llvm-project/blob/az/CPP-4734-stack-leak-output-arg/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp#L302)

You're right that you wouldn't reach this point with a conjured symbol that has 
no origin region, because the immediately invoked lambda that defines 
`ReferrerMemorySpace` triggers the assertion 
`assert(isa(Space));` if it cannot trace back the value to 
either the static globals, the globals or the stack.

However, that's still a hard assertion in a situation that is reachable during 
normal operation of the analyzer, so you need to replace it with a no-op early 
return or something. (That would probably involve eliminating the immediately 
invoked lambda, because it cannot `return` from the function that surrounds it.)


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


[clang] [analyzer] Detect leak of a stack address through output arguments 2/3 (PR #105653)

2024-08-23 Thread Donát Nagy via cfe-commits

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


[clang] [clang][bytecode][NFC] Remove containsErrors() check from delegate (PR #105804)

2024-08-23 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr created 
https://github.com/llvm/llvm-project/pull/105804

This check was removed a while ago from visit(), remove it from delegate() as 
well.

>From 94a4986d8074bc2dbb4aa7ed11d4cf39cf963444 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Fri, 23 Aug 2024 11:05:38 +0200
Subject: [PATCH] [clang][bytecode][NFC] Remove containsErrors() check from
 delegate

This check was removed a while ago from visit(), remove it from
delegate() as well.
---
 clang/lib/AST/ByteCode/Compiler.cpp | 3 ---
 1 file changed, 3 deletions(-)

diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 3a3927a9671345..fb2fcbbb90302c 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -3262,9 +3262,6 @@ template  bool 
Compiler::discard(const Expr *E) {
 }
 
 template  bool Compiler::delegate(const Expr *E) {
-  if (E->containsErrors())
-return this->emitError(E);
-
   // We're basically doing:
   // OptionScope Scope(this, DicardResult, Initializing);
   // but that's unnecessary of course.

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


[clang] [clang][bytecode][NFC] Remove containsErrors() check from delegate (PR #105804)

2024-08-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

This check was removed a while ago from visit(), remove it from delegate() as 
well.

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


1 Files Affected:

- (modified) clang/lib/AST/ByteCode/Compiler.cpp (-3) 


``diff
diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 3a3927a9671345..fb2fcbbb90302c 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -3262,9 +3262,6 @@ template  bool 
Compiler::discard(const Expr *E) {
 }
 
 template  bool Compiler::delegate(const Expr *E) {
-  if (E->containsErrors())
-return this->emitError(E);
-
   // We're basically doing:
   // OptionScope Scope(this, DicardResult, Initializing);
   // but that's unnecessary of course.

``




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


[clang] 96509bb - [Matrix] Preserve signedness when extending matrix index expression. (#103044)

2024-08-23 Thread via cfe-commits

Author: Florian Hahn
Date: 2024-08-23T10:11:52+01:00
New Revision: 96509bb98fc0a7e929304a64362baaa2589d5a6b

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

LOG: [Matrix] Preserve signedness when extending matrix index expression. 
(#103044)

As per [1] the indices for a matrix element access operator shall have
integral or unscoped enumeration types and be non-negative. At the
moment, the index expression is converted to SizeType irrespective of
the signedness of the index expression. This causes implicit sign
conversion warnings if any of the indices is signed.

As per the spec, using signed types as indices is allowed and should not
cause any warnings. If the index expression is signed, extend to
SignedSizeType to avoid the warning.

[1]
https://clang.llvm.org/docs/MatrixTypes.html#matrix-type-element-access-operator

PR: https://github.com/llvm/llvm-project/pull/103044

Added: 


Modified: 
clang/lib/CodeGen/CGExpr.cpp
clang/lib/CodeGen/CGExprScalar.cpp
clang/lib/CodeGen/CodeGenFunction.h
clang/lib/Sema/SemaExpr.cpp
clang/test/SemaCXX/matrix-index-operator-sign-conversion.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 48d9a3b8a5acb3..426fccb721db84 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -4392,13 +4392,24 @@ LValue CodeGenFunction::EmitArraySubscriptExpr(const 
ArraySubscriptExpr *E,
   return LV;
 }
 
+llvm::Value *CodeGenFunction::EmitMatrixIndexExpr(const Expr *E) {
+  llvm::Value *Idx = EmitScalarExpr(E);
+  if (Idx->getType() == IntPtrTy)
+return Idx;
+  bool IsSigned = E->getType()->isSignedIntegerOrEnumerationType();
+  return Builder.CreateIntCast(Idx, IntPtrTy, IsSigned);
+}
+
 LValue CodeGenFunction::EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E) {
   assert(
   !E->isIncomplete() &&
   "incomplete matrix subscript expressions should be rejected during 
Sema");
   LValue Base = EmitLValue(E->getBase());
-  llvm::Value *RowIdx = EmitScalarExpr(E->getRowIdx());
-  llvm::Value *ColIdx = EmitScalarExpr(E->getColumnIdx());
+
+  // Extend or truncate the index type to 32 or 64-bits if needed.
+  llvm::Value *RowIdx = EmitMatrixIndexExpr(E->getRowIdx());
+  llvm::Value *ColIdx = EmitMatrixIndexExpr(E->getColumnIdx());
+
   llvm::Value *NumRows = Builder.getIntN(
   RowIdx->getType()->getScalarSizeInBits(),
   E->getBase()->getType()->castAs()->getNumRows());

diff  --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 3bda254c86adf6..2a726bba2dd304 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -2007,8 +2007,8 @@ Value 
*ScalarExprEmitter::VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
 
   // Handle the vector case.  The base must be a vector, the index must be an
   // integer value.
-  Value *RowIdx = Visit(E->getRowIdx());
-  Value *ColumnIdx = Visit(E->getColumnIdx());
+  Value *RowIdx = CGF.EmitMatrixIndexExpr(E->getRowIdx());
+  Value *ColumnIdx = CGF.EmitMatrixIndexExpr(E->getColumnIdx());
 
   const auto *MatrixTy = E->getBase()->getType()->castAs();
   unsigned NumRows = MatrixTy->getNumRows();

diff  --git a/clang/lib/CodeGen/CodeGenFunction.h 
b/clang/lib/CodeGen/CodeGenFunction.h
index e1b9ada3c1e1fd..05f85f8b95bfa2 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -4280,6 +4280,7 @@ class CodeGenFunction : public CodeGenTypeCache {
   LValue EmitUnaryOpLValue(const UnaryOperator *E);
   LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
 bool Accessed = false);
+  llvm::Value *EmitMatrixIndexExpr(const Expr *E);
   LValue EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E);
   LValue EmitArraySectionExpr(const ArraySectionExpr *E,
   bool IsLowerBound = true);

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index c67183df335dd5..ea57316ad8014e 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -5033,8 +5033,7 @@ ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr 
*Base, Expr *RowIdx,
   }
 }
 
-ExprResult ConvExpr =
-tryConvertExprToType(IndexExpr, Context.getSizeType());
+ExprResult ConvExpr = IndexExpr;
 assert(!ConvExpr.isInvalid() &&
"should be able to convert any integer type to size type");
 return ConvExpr.get();

diff  --git a/clang/test/SemaCXX/matrix-index-operator-sign-conversion.cpp 
b/clang/test/SemaCXX/matrix-index-operator-sign-conversion.cpp
index 4254780651c5f5..e6fe4a6c57ff22 100644
--- a/clang/test/SemaCXX/matrix-index-operator-sign-conversion.cpp
+++ b/clang/test/SemaCXX/matrix-index-operator-sign-conversion.cpp
@

[clang] [Matrix] Preserve signedness when extending matrix index expression. (PR #103044)

2024-08-23 Thread Florian Hahn via cfe-commits

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


[clang] [analyzer] Detect leaks of stack addresses via output params, indirect globals 3/3 (PR #105648)

2024-08-23 Thread Arseniy Zaostrovnykh via cfe-commits

https://github.com/necto updated 
https://github.com/llvm/llvm-project/pull/105648

>From db68dcfba96bfbf9367ba4159b6bf179c8c56f4f Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Tue, 20 Aug 2024 10:26:38 +0200
Subject: [PATCH 1/5] [analyzer] [NFC] Add tests for and refactor
 StackAddrEscapeChecker

These tests and refactoring are preparatory for the upcoming changes:
detection of the indirect leak via global variables and output parameters.

CPP-4734
---
 .../Checkers/StackAddrEscapeChecker.cpp   |  71 ++-
 clang/test/Analysis/stack-addr-ps.c   |  31 +
 clang/test/Analysis/stack-addr-ps.cpp | 596 ++
 3 files changed, 665 insertions(+), 33 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
index ea09c43cc5ce90..2bd4ca4528de8b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
@@ -288,12 +288,37 @@ void StackAddrEscapeChecker::checkPreStmt(const 
ReturnStmt *RS,
   EmitStackError(C, R, RetE);
 }
 
+std::optional printReferrer(const MemRegion *Referrer) {
+  assert(Referrer);
+  const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
+if (isa(Space))
+  return "static";
+if (isa(Space))
+  return "global";
+assert(isa(Space));
+return "stack";
+  }(Referrer->getMemorySpace());
+
+  // We should really only have VarRegions here.
+  // Anything else is really surprising, and we should get notified if such
+  // ever happens.
+  const auto *ReferrerVar = dyn_cast(Referrer);
+  if (!ReferrerVar) {
+assert(false && "We should have a VarRegion here");
+return std::nullopt; // Defensively skip this one.
+  }
+  const std::string ReferrerVarName =
+  ReferrerVar->getDecl()->getDeclName().getAsString();
+
+  return (ReferrerMemorySpace + " variable '" + ReferrerVarName + "'").str();
+}
+
 void StackAddrEscapeChecker::checkEndFunction(const ReturnStmt *RS,
   CheckerContext &Ctx) const {
   if (!ChecksEnabled[CK_StackAddrEscapeChecker])
 return;
 
-  ProgramStateRef State = Ctx.getState();
+  ExplodedNode *Node = Ctx.getPredecessor();
 
   // Iterate over all bindings to global variables and see if it contains
   // a memory region in the stack space.
@@ -315,15 +340,10 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   if (!ReferrerMemSpace || !ReferredMemSpace)
 return false;
 
-  const auto *ReferrerFrame = ReferrerMemSpace->getStackFrame();
-  const auto *ReferredFrame = ReferredMemSpace->getStackFrame();
-
-  if (ReferrerMemSpace && ReferredMemSpace) {
-if (ReferredFrame == PoppedFrame &&
-ReferrerFrame->isParentOf(PoppedFrame)) {
-  V.emplace_back(Referrer, Referred);
-  return true;
-}
+  if (ReferredMemSpace->getStackFrame() == PoppedFrame &&
+  ReferrerMemSpace->getStackFrame()->isParentOf(PoppedFrame)) {
+V.emplace_back(Referrer, Referred);
+return true;
   }
   return false;
 }
@@ -352,6 +372,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   };
 
   CallBack Cb(Ctx);
+  ProgramStateRef State = Node->getState();
   State->getStateManager().getStoreManager().iterBindings(State->getStore(),
   Cb);
 
@@ -359,7 +380,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 return;
 
   // Generate an error node.
-  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State);
+  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State, Node);
   if (!N)
 return;
 
@@ -374,13 +395,13 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 
 // Generate a report for this bug.
 const StringRef CommonSuffix =
-"upon returning to the caller.  This will be a dangling reference";
+" upon returning to the caller.  This will be a dangling reference";
 SmallString<128> Buf;
 llvm::raw_svector_ostream Out(Buf);
 const SourceRange Range = genName(Out, Referred, Ctx.getASTContext());
 
 if (isa(Referrer)) {
-  Out << " is still referred to by a temporary object on the stack "
+  Out << " is still referred to by a temporary object on the stack"
   << CommonSuffix;
   auto Report =
   std::make_unique(*BT_stackleak, Out.str(), 
N);
@@ -390,28 +411,12 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   return;
 }
 
-const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
-  if (isa(Space))
-return "static";
-  if (isa(Space))
-return "global";
-  assert(isa(Space));
-  return "stack";
-}(Referrer->getMemorySpace());
-
-// We should really only have VarRegions here.
-// Anything else is reall

[clang] 3cca522 - [C++20] [Modules] Warn for duplicated decls in mutliple module units (#105799)

2024-08-23 Thread via cfe-commits

Author: Chuanqi Xu
Date: 2024-08-23T17:42:47+08:00
New Revision: 3cca522d21876da36145655bc14f334035b4265d

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

LOG: [C++20] [Modules] Warn for duplicated decls in mutliple module units 
(#105799)

It is a long standing issue that the duplicated declarations in multiple
module units would cause the compilation performance to get slowed down.
And there are many questions or issue reports. So I think it is better
to add a warning for it.

And given this is not because the users' code violates the language
specification or any best practices, the warning is disabled by default
even if `-Wall` is specified. The users need to specify the warning
explcitly or use `Weverything`.

The documentation will add separately.

Added: 
clang/test/Modules/warn-duplicated-decls-in-module-units.cppm

Modified: 
clang/include/clang/Basic/DiagnosticSerializationKinds.td
clang/include/clang/Serialization/ASTReader.h
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTReaderDecl.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSerializationKinds.td 
b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
index 9854972cbfe7e4..253a955431997b 100644
--- a/clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -134,6 +134,12 @@ def warn_module_system_bit_conflict : Warning<
   "as a non-system module; any 
diff erence in diagnostic options will be ignored">,
   InGroup;
 
+def warn_decls_in_multiple_modules : Warning<
+  "declaration %0 is detected to be defined in multiple module units, first is 
from '%1' and second is from '%2'; "
+  "the compiler may not be good at merging the definitions. ">,
+  InGroup>,
+  DefaultIgnore;
+
 def err_failed_to_find_module_file : Error<
   "failed to find module file for module '%0'">;
 } // let CategoryName

diff  --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index 4593213c5f43ce..2d8952ddbd71df 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -648,6 +648,12 @@ class ASTReader
   /// performed deduplication.
   llvm::SetVector PendingMergedDefinitionsToDeduplicate;
 
+  /// The duplicated definitions in module units which are pending to be 
warned.
+  /// We need to delay it to wait for the loading of definitions since we don't
+  /// want to warn for forward declarations.
+  llvm::SmallVector>
+  PendingWarningForDuplicatedDefsInModuleUnits;
+
   /// Read the record that describes the lexical contents of a DC.
   bool ReadLexicalDeclContextStorage(ModuleFile &M,
  llvm::BitstreamCursor &Cursor,

diff  --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index fa9b815239dbb6..be83805f1e92b9 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -9955,6 +9955,45 @@ void ASTReader::finishPendingActions() {
   }
   PendingDefinitions.clear();
 
+  for (auto [D, Previous] : PendingWarningForDuplicatedDefsInModuleUnits) {
+auto hasDefinitionImpl = [this](Decl *D, auto hasDefinitionImpl) {
+  if (auto *VD = dyn_cast(D))
+return VD->isThisDeclarationADefinition() ||
+   VD->isThisDeclarationADemotedDefinition();
+
+  if (auto *TD = dyn_cast(D))
+return TD->isThisDeclarationADefinition() ||
+   TD->isThisDeclarationADemotedDefinition();
+
+  if (auto *FD = dyn_cast(D))
+return FD->isThisDeclarationADefinition() || PendingBodies.count(FD);
+
+  if (auto *RTD = dyn_cast(D))
+return hasDefinitionImpl(RTD->getTemplatedDecl(), hasDefinitionImpl);
+
+  // Conservatively return false here.
+  return false;
+};
+
+auto hasDefinition = [this, &hasDefinitionImpl](Decl *D) {
+  return hasDefinitionImpl(D, hasDefinitionImpl);
+};
+
+// It is not good to prevent multiple declarations since the forward
+// declaration is common. Let's try to avoid duplicated definitions
+// only.
+if (!hasDefinition(D) || !hasDefinition(Previous))
+  continue;
+
+Module *PM = Previous->getOwningModule();
+Module *DM = D->getOwningModule();
+Diag(D->getLocation(), diag::warn_decls_in_multiple_modules)
+<< cast(Previous) << PM->getTopLevelModuleName()
+<< (DM ? DM->getTopLevelModuleName() : "global module");
+Diag(Previous->getLocation(), diag::note_also_found);
+  }
+  PendingWarningForDuplicatedDefsInModuleUnits.clear();
+
   // Load the bodies of any functions or methods we've encountered. We do
   // this now (delayed) so that we can be sure that the declara

[clang] [C++20] [Modules] Warn for duplicated decls in mutliple module units (PR #105799)

2024-08-23 Thread Chuanqi Xu via cfe-commits

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


[clang] [analyzer] Detect leak of a stack address through output arguments 2/3 (PR #105653)

2024-08-23 Thread Arseniy Zaostrovnykh via cfe-commits


@@ -297,20 +314,29 @@ std::optional printReferrer(const MemRegion 
*Referrer) {
   return "global";
 assert(isa(Space));
 return "stack";
-  }(Referrer->getMemorySpace());
-
-  // We should really only have VarRegions here.
-  // Anything else is really surprising, and we should get notified if such
-  // ever happens.
-  const auto *ReferrerVar = dyn_cast(Referrer);
-  if (!ReferrerVar) {
-assert(false && "We should have a VarRegion here");
-return std::nullopt; // Defensively skip this one.
+  }(getStackOrGlobalSpaceRegion(Referrer));
+
+  while (!Referrer->canPrintPretty()) {
+if (const auto *SymReg = dyn_cast(Referrer)) {
+  Referrer = SymReg->getSymbol()->getOriginRegion()->getBaseRegion();
+} else if (isa(Referrer)) {
+  // Skip members of a class, it is handled by
+  // warn_bind_ref_member_to_parameter_addr

necto wrote:

Indeed the diagnostic name is off (and in fact both of diags you mentioned 
fit). Corrected clarified in 47b5deecc and 4081a03fb

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


[clang] [analyzer] Detect leaks of stack addresses via output params, indirect globals 3/3 (PR #105648)

2024-08-23 Thread Arseniy Zaostrovnykh via cfe-commits

https://github.com/necto updated 
https://github.com/llvm/llvm-project/pull/105648

>From db68dcfba96bfbf9367ba4159b6bf179c8c56f4f Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Tue, 20 Aug 2024 10:26:38 +0200
Subject: [PATCH 1/6] [analyzer] [NFC] Add tests for and refactor
 StackAddrEscapeChecker

These tests and refactoring are preparatory for the upcoming changes:
detection of the indirect leak via global variables and output parameters.

CPP-4734
---
 .../Checkers/StackAddrEscapeChecker.cpp   |  71 ++-
 clang/test/Analysis/stack-addr-ps.c   |  31 +
 clang/test/Analysis/stack-addr-ps.cpp | 596 ++
 3 files changed, 665 insertions(+), 33 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
index ea09c43cc5ce90..2bd4ca4528de8b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
@@ -288,12 +288,37 @@ void StackAddrEscapeChecker::checkPreStmt(const 
ReturnStmt *RS,
   EmitStackError(C, R, RetE);
 }
 
+std::optional printReferrer(const MemRegion *Referrer) {
+  assert(Referrer);
+  const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
+if (isa(Space))
+  return "static";
+if (isa(Space))
+  return "global";
+assert(isa(Space));
+return "stack";
+  }(Referrer->getMemorySpace());
+
+  // We should really only have VarRegions here.
+  // Anything else is really surprising, and we should get notified if such
+  // ever happens.
+  const auto *ReferrerVar = dyn_cast(Referrer);
+  if (!ReferrerVar) {
+assert(false && "We should have a VarRegion here");
+return std::nullopt; // Defensively skip this one.
+  }
+  const std::string ReferrerVarName =
+  ReferrerVar->getDecl()->getDeclName().getAsString();
+
+  return (ReferrerMemorySpace + " variable '" + ReferrerVarName + "'").str();
+}
+
 void StackAddrEscapeChecker::checkEndFunction(const ReturnStmt *RS,
   CheckerContext &Ctx) const {
   if (!ChecksEnabled[CK_StackAddrEscapeChecker])
 return;
 
-  ProgramStateRef State = Ctx.getState();
+  ExplodedNode *Node = Ctx.getPredecessor();
 
   // Iterate over all bindings to global variables and see if it contains
   // a memory region in the stack space.
@@ -315,15 +340,10 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   if (!ReferrerMemSpace || !ReferredMemSpace)
 return false;
 
-  const auto *ReferrerFrame = ReferrerMemSpace->getStackFrame();
-  const auto *ReferredFrame = ReferredMemSpace->getStackFrame();
-
-  if (ReferrerMemSpace && ReferredMemSpace) {
-if (ReferredFrame == PoppedFrame &&
-ReferrerFrame->isParentOf(PoppedFrame)) {
-  V.emplace_back(Referrer, Referred);
-  return true;
-}
+  if (ReferredMemSpace->getStackFrame() == PoppedFrame &&
+  ReferrerMemSpace->getStackFrame()->isParentOf(PoppedFrame)) {
+V.emplace_back(Referrer, Referred);
+return true;
   }
   return false;
 }
@@ -352,6 +372,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   };
 
   CallBack Cb(Ctx);
+  ProgramStateRef State = Node->getState();
   State->getStateManager().getStoreManager().iterBindings(State->getStore(),
   Cb);
 
@@ -359,7 +380,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 return;
 
   // Generate an error node.
-  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State);
+  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State, Node);
   if (!N)
 return;
 
@@ -374,13 +395,13 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 
 // Generate a report for this bug.
 const StringRef CommonSuffix =
-"upon returning to the caller.  This will be a dangling reference";
+" upon returning to the caller.  This will be a dangling reference";
 SmallString<128> Buf;
 llvm::raw_svector_ostream Out(Buf);
 const SourceRange Range = genName(Out, Referred, Ctx.getASTContext());
 
 if (isa(Referrer)) {
-  Out << " is still referred to by a temporary object on the stack "
+  Out << " is still referred to by a temporary object on the stack"
   << CommonSuffix;
   auto Report =
   std::make_unique(*BT_stackleak, Out.str(), 
N);
@@ -390,28 +411,12 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   return;
 }
 
-const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
-  if (isa(Space))
-return "static";
-  if (isa(Space))
-return "global";
-  assert(isa(Space));
-  return "stack";
-}(Referrer->getMemorySpace());
-
-// We should really only have VarRegions here.
-// Anything else is reall

[clang] [analyzer] Detect leak of a stack address through output arguments 2/3 (PR #105653)

2024-08-23 Thread Donát Nagy via cfe-commits


@@ -297,20 +314,29 @@ std::optional printReferrer(const MemRegion 
*Referrer) {
   return "global";
 assert(isa(Space));
 return "stack";
-  }(Referrer->getMemorySpace());
-
-  // We should really only have VarRegions here.
-  // Anything else is really surprising, and we should get notified if such
-  // ever happens.
-  const auto *ReferrerVar = dyn_cast(Referrer);
-  if (!ReferrerVar) {
-assert(false && "We should have a VarRegion here");
-return std::nullopt; // Defensively skip this one.
+  }(getStackOrGlobalSpaceRegion(Referrer));
+
+  while (!Referrer->canPrintPretty()) {
+if (const auto *SymReg = dyn_cast(Referrer)) {
+  Referrer = SymReg->getSymbol()->getOriginRegion()->getBaseRegion();
+} else if (isa(Referrer)) {
+  // Skip members of a class, it is handled by
+  // warn_bind_ref_member_to_parameter_addr

NagyDonat wrote:

Thanks, the corrections LGTM, however they don't appear on this PR right now

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


[clang] [analyzer] Detect leak of a stack address through output arguments 2/3 (PR #105653)

2024-08-23 Thread Donát Nagy via cfe-commits

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


[clang] [clang] Merge lifetimebound and GSL code paths for lifetime analysis (PR #104906)

2024-08-23 Thread Haojian Wu via cfe-commits

hokein wrote:

The removal of `EnableLifetimeWarnings` flag causes some behavior change when 
we visit a lifetimebound function argument:

- before: the `EnableLifetimeWarnings` is always `false`, which means we never 
run into the GSL codepath
- after: we remove this flag, we will continue to run the GSL codepath (unless 
the GSL diagnostic is disabled)

For the following case,
```
struct Foo;
struct FooView {
  FooView(const Foo& foo [[clang::lifetimebound]]);
};
struct Foo {};

FooView test() {
  return std::vector()[0]; // dangling
}
```

We start to emit a dangling diagnostic after this change, this looks like a 
good change as we catch more cases now.

Still need to look at the libcxx failure.

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


[clang] [analyzer] Detect leak of a stack address through output arguments 2/3 (PR #105653)

2024-08-23 Thread Arseniy Zaostrovnykh via cfe-commits

https://github.com/necto updated 
https://github.com/llvm/llvm-project/pull/105653

>From db68dcfba96bfbf9367ba4159b6bf179c8c56f4f Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Tue, 20 Aug 2024 10:26:38 +0200
Subject: [PATCH 1/6] [analyzer] [NFC] Add tests for and refactor
 StackAddrEscapeChecker

These tests and refactoring are preparatory for the upcoming changes:
detection of the indirect leak via global variables and output parameters.

CPP-4734
---
 .../Checkers/StackAddrEscapeChecker.cpp   |  71 ++-
 clang/test/Analysis/stack-addr-ps.c   |  31 +
 clang/test/Analysis/stack-addr-ps.cpp | 596 ++
 3 files changed, 665 insertions(+), 33 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
index ea09c43cc5ce90..2bd4ca4528de8b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
@@ -288,12 +288,37 @@ void StackAddrEscapeChecker::checkPreStmt(const 
ReturnStmt *RS,
   EmitStackError(C, R, RetE);
 }
 
+std::optional printReferrer(const MemRegion *Referrer) {
+  assert(Referrer);
+  const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
+if (isa(Space))
+  return "static";
+if (isa(Space))
+  return "global";
+assert(isa(Space));
+return "stack";
+  }(Referrer->getMemorySpace());
+
+  // We should really only have VarRegions here.
+  // Anything else is really surprising, and we should get notified if such
+  // ever happens.
+  const auto *ReferrerVar = dyn_cast(Referrer);
+  if (!ReferrerVar) {
+assert(false && "We should have a VarRegion here");
+return std::nullopt; // Defensively skip this one.
+  }
+  const std::string ReferrerVarName =
+  ReferrerVar->getDecl()->getDeclName().getAsString();
+
+  return (ReferrerMemorySpace + " variable '" + ReferrerVarName + "'").str();
+}
+
 void StackAddrEscapeChecker::checkEndFunction(const ReturnStmt *RS,
   CheckerContext &Ctx) const {
   if (!ChecksEnabled[CK_StackAddrEscapeChecker])
 return;
 
-  ProgramStateRef State = Ctx.getState();
+  ExplodedNode *Node = Ctx.getPredecessor();
 
   // Iterate over all bindings to global variables and see if it contains
   // a memory region in the stack space.
@@ -315,15 +340,10 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   if (!ReferrerMemSpace || !ReferredMemSpace)
 return false;
 
-  const auto *ReferrerFrame = ReferrerMemSpace->getStackFrame();
-  const auto *ReferredFrame = ReferredMemSpace->getStackFrame();
-
-  if (ReferrerMemSpace && ReferredMemSpace) {
-if (ReferredFrame == PoppedFrame &&
-ReferrerFrame->isParentOf(PoppedFrame)) {
-  V.emplace_back(Referrer, Referred);
-  return true;
-}
+  if (ReferredMemSpace->getStackFrame() == PoppedFrame &&
+  ReferrerMemSpace->getStackFrame()->isParentOf(PoppedFrame)) {
+V.emplace_back(Referrer, Referred);
+return true;
   }
   return false;
 }
@@ -352,6 +372,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   };
 
   CallBack Cb(Ctx);
+  ProgramStateRef State = Node->getState();
   State->getStateManager().getStoreManager().iterBindings(State->getStore(),
   Cb);
 
@@ -359,7 +380,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 return;
 
   // Generate an error node.
-  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State);
+  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State, Node);
   if (!N)
 return;
 
@@ -374,13 +395,13 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 
 // Generate a report for this bug.
 const StringRef CommonSuffix =
-"upon returning to the caller.  This will be a dangling reference";
+" upon returning to the caller.  This will be a dangling reference";
 SmallString<128> Buf;
 llvm::raw_svector_ostream Out(Buf);
 const SourceRange Range = genName(Out, Referred, Ctx.getASTContext());
 
 if (isa(Referrer)) {
-  Out << " is still referred to by a temporary object on the stack "
+  Out << " is still referred to by a temporary object on the stack"
   << CommonSuffix;
   auto Report =
   std::make_unique(*BT_stackleak, Out.str(), 
N);
@@ -390,28 +411,12 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   return;
 }
 
-const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
-  if (isa(Space))
-return "static";
-  if (isa(Space))
-return "global";
-  assert(isa(Space));
-  return "stack";
-}(Referrer->getMemorySpace());
-
-// We should really only have VarRegions here.
-// Anything else is reall

[clang] [clang][bytecode][NFC] Remove containsErrors() check from delegate (PR #105804)

2024-08-23 Thread Timm Baeder via cfe-commits

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


[clang] 38b8e54 - [clang][bytecode][NFC] Remove containsErrors() check from delegate (#105804)

2024-08-23 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-08-23T11:55:30+02:00
New Revision: 38b8e54682567d685bc03f9fdef26baa6b708ef9

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

LOG: [clang][bytecode][NFC] Remove containsErrors() check from delegate 
(#105804)

This check was removed a while ago from visit(), remove it from
delegate() as well.

Added: 


Modified: 
clang/lib/AST/ByteCode/Compiler.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 655983a1ca0494..d24384ca4ac7a4 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -3262,9 +3262,6 @@ template  bool 
Compiler::discard(const Expr *E) {
 }
 
 template  bool Compiler::delegate(const Expr *E) {
-  if (E->containsErrors())
-return this->emitError(E);
-
   // We're basically doing:
   // OptionScope Scope(this, DicardResult, Initializing);
   // but that's unnecessary of course.



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


[clang] [analyzer] Detect leak of a stack address through output arguments 2/3 (PR #105653)

2024-08-23 Thread Arseniy Zaostrovnykh via cfe-commits


@@ -297,20 +314,29 @@ std::optional printReferrer(const MemRegion 
*Referrer) {
   return "global";
 assert(isa(Space));
 return "stack";
-  }(Referrer->getMemorySpace());
-
-  // We should really only have VarRegions here.
-  // Anything else is really surprising, and we should get notified if such
-  // ever happens.
-  const auto *ReferrerVar = dyn_cast(Referrer);
-  if (!ReferrerVar) {
-assert(false && "We should have a VarRegion here");
-return std::nullopt; // Defensively skip this one.
+  }(getStackOrGlobalSpaceRegion(Referrer));
+
+  while (!Referrer->canPrintPretty()) {
+if (const auto *SymReg = dyn_cast(Referrer)) {
+  Referrer = SymReg->getSymbol()->getOriginRegion()->getBaseRegion();
+} else if (isa(Referrer)) {
+  // Skip members of a class, it is handled by
+  // warn_bind_ref_member_to_parameter_addr

necto wrote:

Oups, indeed, I pushed them to the wrong branch. thank you for warning me!
they are on this branch too now: 
24bd8bffc6bb clarify reference further
9b7e3d6a80a8 Clarify reference

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


[clang] 7b4b85b - [clang][bytecode] Reject void InitListExpr differently (#105802)

2024-08-23 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-08-23T11:56:42+02:00
New Revision: 7b4b85b75d22a792b2ef80e6af4f0faf18da0a43

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

LOG: [clang][bytecode] Reject void InitListExpr differently (#105802)

This reverts c79d1fa540390f6e37e1ea326153559eeadd0de6 and
125aa10b3d645bd26523a1bc321bb2e6b1cf04e1

Instead, use the previous approach but allow void-typed InitListExprs
with 0 initializers.

Added: 


Modified: 
clang/lib/AST/ByteCode/Compiler.cpp
clang/test/AST/ByteCode/c.c

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index d24384ca4ac7a4..f11196d2b02707 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -1344,6 +1344,16 @@ bool Compiler::VisitArraySubscriptExpr(const 
ArraySubscriptExpr *E) {
 template 
 bool Compiler::visitInitList(ArrayRef Inits,
   const Expr *ArrayFiller, const Expr *E) {
+  QualType QT = E->getType();
+  if (const auto *AT = QT->getAs())
+QT = AT->getValueType();
+
+  if (QT->isVoidType()) {
+if (Inits.size() == 0)
+  return true;
+return this->emitInvalid(E);
+  }
+
   // Handle discarding first.
   if (DiscardResult) {
 for (const Expr *Init : Inits) {
@@ -1353,13 +1363,6 @@ bool Compiler::visitInitList(ArrayRef Inits,
 return true;
   }
 
-  QualType QT = E->getType();
-  if (const auto *AT = QT->getAs())
-QT = AT->getValueType();
-
-  if (QT->isVoidType())
-return this->emitInvalid(E);
-
   // Primitive values.
   if (std::optional T = classify(QT)) {
 assert(!DiscardResult);
@@ -3272,9 +3275,12 @@ template  bool 
Compiler::visit(const Expr *E) {
   if (E->getType().isNull())
 return false;
 
+  if (E->getType()->isVoidType())
+return this->discard(E);
+
   // Create local variable to hold the return value.
-  if (!E->getType()->isVoidType() && !E->isGLValue() &&
-  !E->getType()->isAnyComplexType() && !classify(E->getType())) {
+  if (!E->isGLValue() && !E->getType()->isAnyComplexType() &&
+  !classify(E->getType())) {
 std::optional LocalIndex = allocateLocal(E);
 if (!LocalIndex)
   return false;
@@ -5174,7 +5180,7 @@ bool Compiler::VisitUnaryOperator(const 
UnaryOperator *E) {
 // We should already have a pointer when we get here.
 return this->delegate(SubExpr);
   case UO_Deref: // *x
-if (DiscardResult || E->getType()->isVoidType())
+if (DiscardResult)
   return this->discard(SubExpr);
 return this->visit(SubExpr);
   case UO_Not: // ~x

diff  --git a/clang/test/AST/ByteCode/c.c b/clang/test/AST/ByteCode/c.c
index 60f4d6ad1b2967..7cb7f96049f2de 100644
--- a/clang/test/AST/ByteCode/c.c
+++ b/clang/test/AST/ByteCode/c.c
@@ -298,7 +298,6 @@ void T1(void) {
 enum teste1 test1f(void), (*test1)(void) = test1f; // pedantic-warning {{ISO C 
forbids forward references to 'enum' types}}
 enum teste1 { TEST1 };
 
-
 void func(void) {
   _Static_assert(func + 1 - func == 1, ""); // pedantic-warning {{arithmetic 
on a pointer to the function type}} \
 // pedantic-warning {{arithmetic 
on pointers to the function type}} \
@@ -313,3 +312,9 @@ void func(void) {
   func - 0xdeadUL; // all-warning {{expression result unused}} \
// pedantic-warning {{arithmetic on a pointer 
to the function type}}
 }
+
+void foo3 (void)
+{
+ void* x = 0;
+ void* y = &*x;
+}



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


[clang] [clang][bytecode] Reject void InitListExpr differently (PR #105802)

2024-08-23 Thread Timm Baeder via cfe-commits

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


[clang] [clang] Catch missing format attributes (PR #105479)

2024-08-23 Thread Budimir Aranđelović via cfe-commits

https://github.com/budimirarandjelovichtec updated 
https://github.com/llvm/llvm-project/pull/105479

From 9f61f95c1a56b980b82b40b46514dd888c12330d Mon Sep 17 00:00:00 2001
From: budimirarandjelovicsyrmia 
Date: Fri, 5 Apr 2024 15:20:37 +0200
Subject: [PATCH] [clang] Catch missing format attributes

---
 clang/docs/ReleaseNotes.rst   |   3 +
 clang/include/clang/Basic/DiagnosticGroups.td |   1 -
 .../clang/Basic/DiagnosticSemaKinds.td|   3 +
 clang/include/clang/Sema/Attr.h   |   7 +
 clang/include/clang/Sema/Sema.h   |   4 +
 clang/lib/Sema/SemaDecl.cpp   |   2 +
 clang/lib/Sema/SemaDeclAttr.cpp   | 219 +-
 clang/test/Sema/attr-format-missing.c | 393 ++
 clang/test/Sema/attr-format-missing.cpp   | 174 
 9 files changed, 803 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/Sema/attr-format-missing.c
 create mode 100644 clang/test/Sema/attr-format-missing.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 93040c2eee2c0b..53e7c94c7077e7 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -235,6 +235,9 @@ Improvements to Clang's diagnostics
 
 - Improved diagnostic when trying to befriend a concept. (#GH45182).
 
+- Clang now diagnoses missing format attributes for non-template functions and
+  class/struct/union members. Fixes #GH60718
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 19c3f1e0433496..3924677150a3a4 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -529,7 +529,6 @@ def MainReturnType : DiagGroup<"main-return-type">;
 def MaxUnsignedZero : DiagGroup<"max-unsigned-zero">;
 def MissingBraces : DiagGroup<"missing-braces">;
 def MissingDeclarations: DiagGroup<"missing-declarations">;
-def : DiagGroup<"missing-format-attribute">;
 def MissingIncludeDirs : DiagGroup<"missing-include-dirs">;
 def MissingNoreturn : DiagGroup<"missing-noreturn">;
 def MultiChar : DiagGroup<"multichar">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 4b6aadd635786a..14160f2911957e 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -1040,6 +1040,9 @@ def err_opencl_invalid_param : Error<
 def err_opencl_invalid_return : Error<
   "declaring function return value of type %0 is not allowed %select{; did you 
forget * ?|}1">;
 def warn_enum_value_overflow : Warning<"overflow in enumeration value">;
+def warn_missing_format_attribute : Warning<
+  "diagnostic behavior may be improved by adding the %0 format attribute to 
the declaration of %1">,
+  InGroup>, DefaultIgnore;
 def warn_pragma_options_align_reset_failed : Warning<
   "#pragma options align=reset failed: %0">,
   InGroup;
diff --git a/clang/include/clang/Sema/Attr.h b/clang/include/clang/Sema/Attr.h
index 3f0b10212789a4..37c124ca7b454a 100644
--- a/clang/include/clang/Sema/Attr.h
+++ b/clang/include/clang/Sema/Attr.h
@@ -123,6 +123,13 @@ inline bool isInstanceMethod(const Decl *D) {
   return false;
 }
 
+inline bool checkIfMethodHasImplicitObjectParameter(const Decl *D) {
+  if (const auto *MethodDecl = dyn_cast(D))
+return MethodDecl->isInstance() &&
+   !MethodDecl->hasCXXExplicitFunctionObjectParameter();
+  return false;
+}
+
 /// Diagnose mutually exclusive attributes when present on a given
 /// declaration. Returns true if diagnosed.
 template 
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1f7e555d1b8717..9189216ed6e301 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -4619,6 +4619,10 @@ class Sema final : public SemaBase {
 
   enum class RetainOwnershipKind { NS, CF, OS };
 
+  void DiagnoseMissingFormatAttributes(Stmt *Body, const FunctionDecl *FDecl);
+  std::vector
+  GetMissingFormatAttributes(Stmt *Body, const FunctionDecl *FDecl);
+
   UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
   StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
 
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index b0ccbbe34b70c3..5b72b405c7aa57 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -16004,6 +16004,8 @@ Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt 
*Body,
 }
   }
 
+  DiagnoseMissingFormatAttributes(Body, FD);
+
   // We might not have found a prototype because we didn't wish to warn on
   // the lack of a missing prototype. Try again without the checks for
   // whether we want to warn on the missing prototype.
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 73d11ac972b020..2ef4b2da5f4935 1

[clang] [analyzer] Detect leak of a stack address through output arguments 2/3 (PR #105653)

2024-08-23 Thread Donát Nagy via cfe-commits

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


[clang] [analyzer] Detect leak of a stack address through output arguments 2/3 (PR #105653)

2024-08-23 Thread Donát Nagy via cfe-commits


@@ -161,3 +164,619 @@ C make1() {
 void test_copy_elision() {
   C c1 = make1();
 }
+
+namespace leaking_via_direct_pointer {
+void* returned_direct_pointer_top() {
+  int local = 42;
+  int* p = &local;
+  return p; // expected-warning{{associated with local variable 'local' 
returned}}
+}
+
+int* returned_direct_pointer_callee() {
+  int local = 42;
+  int* p = &local;
+  return p; // expected-warning{{associated with local variable 'local' 
returned}}
+}
+
+void returned_direct_pointer_caller() {
+  int* loc_ptr = nullptr;
+  loc_ptr = returned_direct_pointer_callee();
+  (void)loc_ptr;
+}
+
+void* global_ptr;
+
+void global_direct_pointer() {
+  int local = 42;
+  global_ptr = &local;
+} // expected-warning{{local variable 'local' is still referred to by the 
global variable 'global_ptr'}}
+
+void static_direct_pointer_top() {
+  int local = 42;
+  static int* p = &local;
+  (void)p;
+} // expected-warning{{local variable 'local' is still referred to by the 
static variable 'p'}}
+
+void static_direct_pointer_callee() {
+  int local = 42;
+  static int* p = &local;
+  (void)p; // expected-warning{{local variable 'local' is still referred to by 
the static variable 'p'}}
+}
+
+void static_direct_pointer_caller() {
+  static_direct_pointer_callee();
+}
+
+void lambda_to_global_direct_pointer() {
+  auto lambda = [&] {
+int local = 42;
+global_ptr = &local; // expected-warning{{local variable 'local' is still 
referred to by the global variable 'global_ptr'}}
+  };
+  lambda();
+}
+
+void lambda_to_context_direct_pointer() {
+  int *p = nullptr;
+  auto lambda = [&] {
+int local = 42;
+p = &local; // expected-warning{{local variable 'local' is still referred 
to by the stack variable 'p'}}
+  };
+  lambda();
+  (void)p;
+}
+
+template
+class MyFunction {
+  Callable* fptr;
+  public:
+  MyFunction(Callable* callable) :fptr(callable) {}
+};
+
+void* lambda_to_context_direct_pointer_uncalled() {
+  int *p = nullptr;
+  auto lambda = [&] {
+int local = 42;
+p = &local; // no-warning: analyzed only as top-level, ignored explicitly 
by the checker
+  };
+  return new MyFunction(&lambda);
+}
+
+void lambda_to_context_direct_pointer_lifetime_extended() {
+  int *p = nullptr;
+  auto lambda = [&] {
+int&& local = 42;
+p = &local; // expected-warning{{'int' lifetime extended by local variable 
'local' is still referred to by the stack variable 'p'}}
+  };
+  lambda();
+  (void)p;
+}
+
+template
+void lambda_param_capture_direct_pointer_callee(Callback& callee) {
+  int local = 42;
+  callee(local); // expected-warning{{'local' is still referred to by the 
stack variable 'p'}}
+}
+
+void lambda_param_capture_direct_pointer_caller() {
+  int* p = nullptr;
+  auto capt = [&p](int& param) {
+p = ¶m;
+  };
+  lambda_param_capture_direct_pointer_callee(capt);
+}
+} // namespace leaking_via_direct_pointer
+
+namespace leaking_via_ptr_to_ptr {
+void** returned_ptr_to_ptr_top() {
+  int local = 42;
+  int* p = &local;
+  void** pp = (void**)&p;
+  return pp; // expected-warning{{associated with local variable 'p' returned}}
+}
+
+void** global_pp;
+
+void global_ptr_local_to_ptr() {
+  int local = 42;
+  int* p = &local;
+  global_pp = (void**)&p;
+} // expected-warning{{local variable 'p' is still referred to by the global 
variable 'global_pp'}}
+
+void global_ptr_to_ptr() {
+  int local = 42;
+  *global_pp = &local; // no-warning FIXME
+}
+
+void *** global_ppp;
+
+void global_ptr_to_ptr_to_ptr() {
+  int local = 42;
+  **global_ppp = &local; // no-warning FIXME
+}
+
+void** get_some_pp();
+
+void static_ptr_to_ptr() {
+  int local = 42;
+  static void** pp = get_some_pp();
+  *pp = &local;
+} // no-warning False Negative, requires relating multiple bindings to cross 
the invented pointer.
+
+void param_ptr_to_ptr_top(void** pp) {
+  int local = 42;
+  *pp = &local; // no-warning FIXME
+}
+
+void param_ptr_to_ptr_callee(void** pp) {
+  int local = 42;
+  *pp = &local; // expected-warning{{local variable 'local' is still referred 
to by the stack variable 'p'}}
+}
+
+void param_ptr_to_ptr_caller() {
+  void* p = nullptr;
+  param_ptr_to_ptr_callee((void**)&p);
+}
+
+void param_ptr_to_ptr_to_ptr_top(void*** ppp) {
+  int local = 42;
+  **ppp = &local; // no-warning FIXME
+}
+
+void param_ptr_to_ptr_to_ptr_callee(void*** ppp) {
+  int local = 42;
+  **ppp = &local; // expected-warning{{local variable 'local' is still 
referred to by the stack variable 'pp'}}
+}
+
+void param_ptr_to_ptr_to_ptr_caller(void** pp) {
+  param_ptr_to_ptr_to_ptr_callee(&pp);
+}
+
+void lambda_to_context_ptr_to_ptr(int **pp) {
+  auto lambda = [&] {
+int local = 42;
+*pp = &local; // expected-warning{{local variable 'local' is still 
referred to by the stack variable 'pp'}}
+  };
+  lambda();
+  (void)*pp;
+}
+
+void param_ptr_to_ptr_fptr(int **pp) {
+  int local = 42;
+  *pp = &local; // expected-warning{{local variable 'local' is still referred 
to by the stack variable 'p'}}
+}
+
+vo

[clang] [analyzer] Detect leak of a stack address through output arguments 2/3 (PR #105653)

2024-08-23 Thread Donát Nagy via cfe-commits

https://github.com/NagyDonat commented:

Mostly LGTM and thanks for adding the "`origin_region_limitation`" test. (I 
added one minor remark as inline comment.)

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


[clang] [llvm] [NVPTX] Support __usAtomicCAS builtin (PR #99646)

2024-08-23 Thread via cfe-commits

DenisGZM wrote:

Sorry, I dont get it. Should I press the merge button? Because I dont have 
one... or I can't find it

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


[clang] [clang] Merge lifetimebound and GSL code paths for lifetime analysis (PR #104906)

2024-08-23 Thread Haojian Wu via cfe-commits

hokein wrote:

Reduced the libcxx failure to:

```
std::string_view test() {
  return std::move(*std::optional());
}
```

We should not diagnose on this case. I think the PR 
https://github.com/llvm/llvm-project/pull/104556 should fix this.

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


[clang] [NFC] Fix an incorrect comment about operator precedence. (PR #105784)

2024-08-23 Thread via cfe-commits

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

Thanks (Hi!). Do you have commit access or should I merge that for you?

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


[clang] [C++20] [Modules] Warn for duplicated decls in mutliple module units (PR #105799)

2024-08-23 Thread Mikael Holmén via cfe-commits


@@ -9955,6 +9955,45 @@ void ASTReader::finishPendingActions() {
   }
   PendingDefinitions.clear();
 
+  for (auto [D, Previous] : PendingWarningForDuplicatedDefsInModuleUnits) {
+auto hasDefinitionImpl = [this](Decl *D, auto hasDefinitionImpl) {
+  if (auto *VD = dyn_cast(D))
+return VD->isThisDeclarationADefinition() ||
+   VD->isThisDeclarationADemotedDefinition();
+
+  if (auto *TD = dyn_cast(D))
+return TD->isThisDeclarationADefinition() ||
+   TD->isThisDeclarationADemotedDefinition();
+
+  if (auto *FD = dyn_cast(D))
+return FD->isThisDeclarationADefinition() || PendingBodies.count(FD);
+
+  if (auto *RTD = dyn_cast(D))
+return hasDefinitionImpl(RTD->getTemplatedDecl(), hasDefinitionImpl);
+
+  // Conservatively return false here.
+  return false;
+};
+
+auto hasDefinition = [this, &hasDefinitionImpl](Decl *D) {

mikaelholmen wrote:

I get a clang warning here:
```
../../clang/lib/Serialization/ASTReader.cpp:9978:27: error: lambda capture 
'this' is not used [-Werror,-Wunused-lambda-capture]
auto hasDefinition = [this, &hasDefinitionImpl](Decl *D) {
  ^
1 error generated.
```

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


[clang] [llvm] [Coverage][MC/DC] Show uncoverable and unreachable conditions (PR #94137)

2024-08-23 Thread via cfe-commits


@@ -1128,15 +1132,22 @@ struct CounterCoverageMappingBuilder
 BranchParams = mcdc::BranchParameters{ID, Conds};
 
   // If a condition can fold to true or false, the corresponding branch
-  // will be removed.  Create a region with both counters hard-coded to
-  // zero. This allows us to visualize them in a special way.
+  // will be removed. Create a region with the relative counter hard-coded
+  // to zero. This allows us to visualize them in a special way.
   // Alternatively, we can prevent any optimization done via
   // constant-folding by ensuring that ConstantFoldsToSimpleInteger() in
   // CodeGenFunction.c always returns false, but that is very heavy-handed.
-  if (ConditionFoldsToBool(C))
-popRegions(pushRegion(Counter::getZero(), getStart(C), getEnd(C),
-  Counter::getZero(), BranchParams));
-  else
+  bool ConstantBool = false;
+  if (ConditionFoldsToBool(C, ConstantBool)) {
+if (ConstantBool) {
+  popRegions(pushRegion(TrueCnt, getStart(C), getEnd(C),
+Counter::getZero(), BranchParams));
+} else {
+  popRegions(pushRegion(Counter::getZero(), getStart(C), getEnd(C),

Lambdaris wrote:

The only code where I found it may cause side effect seems never impact 
`BranchRegion` or `MCDCBranchRegion`: 
https://github.com/llvm/llvm-project/blob/327edbe07ab4370ceb20ea7c805f64950871d835/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp#L854
 

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


[clang] [llvm] [Coverage][MC/DC] Show uncoverable and unreachable conditions (PR #94137)

2024-08-23 Thread via cfe-commits


@@ -47,7 +47,7 @@
 // CHECK: Branch (103:9): [True: 9, False: 1]
 
 // CHECK: switches()
-// CHECK: Branch (113:3): [True: 1, False: 0]
+// CHECK: Branch (113:3): [Folded - Ignored]

Lambdaris wrote:

It's likely the object need to be reproduced. I have tried with `clang -m32 
-fprofile-instr-generate -fcoverage-mapping -o branch-c-general.o32l 
branch-c-general.c` and this line and the line 60 are corrected but the number 
of lines and regions are not same (even without this patch). Is there anything 
I missed?

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


[clang] [PS5][clang][test] x86_64-scei-ps5 -> x86_64-sie-ps5 in tests (PR #105810)

2024-08-23 Thread Edd Dawson via cfe-commits

https://github.com/playstation-edd created 
https://github.com/llvm/llvm-project/pull/105810

`x86_64-sie-ps5` is the triple we share with PS5 toolchain users who have 
reason to care about such things. The vast majority of PS5 checks and tests 
already use this variant. Quashing the handful of stragglers will help prevent 
future copy+paste of the discouraged variant.

>From 497de2a1a1a03ae78a792634853166636bceb63c Mon Sep 17 00:00:00 2001
From: Edd Dawson 
Date: Fri, 23 Aug 2024 10:41:48 +0100
Subject: [PATCH] [PS5][clang][test] x86_64-scei-ps5 -> x86_64-sie-ps5 in tests

`x86_64-sie-ps5` is the triple we share with PS5 toolchain users who
have reason to care about such things. The vast majority of PS5 checks
and tests already use this variant. Quashing the handful of stragglers
will help prevent future copy+paste of the discouraged variant.
---
 clang/test/CodeGen/tls-maxalign-modflag.c |  2 +-
 .../CodeGenCXX/windows-itanium-init-guard.cpp |  6 +++---
 clang/test/Driver/debug-options.c |  4 ++--
 clang/test/Driver/ps5-linker.c| 20 +--
 4 files changed, 16 insertions(+), 16 deletions(-)

diff --git a/clang/test/CodeGen/tls-maxalign-modflag.c 
b/clang/test/CodeGen/tls-maxalign-modflag.c
index 685057c3551a00..26dde569f389c9 100644
--- a/clang/test/CodeGen/tls-maxalign-modflag.c
+++ b/clang/test/CodeGen/tls-maxalign-modflag.c
@@ -2,7 +2,7 @@
 
 // Test that we get the module flag TLSMaxAlign on the PS platforms.
 // RUN: %clang_cc1 -triple x86_64-scei-ps4 -emit-llvm -o - %s | FileCheck %s
-// RUN: %clang_cc1 -triple x86_64-scei-ps5 -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-sie-ps5 -emit-llvm -o - %s | FileCheck %s
 
 int main(void) {
   return 0;
diff --git a/clang/test/CodeGenCXX/windows-itanium-init-guard.cpp 
b/clang/test/CodeGenCXX/windows-itanium-init-guard.cpp
index 8bcfd272ae8f16..c51ce470061d64 100644
--- a/clang/test/CodeGenCXX/windows-itanium-init-guard.cpp
+++ b/clang/test/CodeGenCXX/windows-itanium-init-guard.cpp
@@ -11,9 +11,9 @@
 // RUN: %clang_cc1 -emit-llvm -triple x86_64-scei-ps4 -fdeclspec %s -O1 
-disable-llvm-passes -o - -DAPI="__declspec(dllexport)" | FileCheck %s 
--check-prefixes=EXPORT
 // RUN: %clang_cc1 -emit-llvm -triple x86_64-scei-ps4 -fdeclspec %s -O1 
-disable-llvm-passes -o - -DAPI="__declspec(dllimport)" | FileCheck %s 
--check-prefixes=IMPORT
 
-// RUN: %clang_cc1 -emit-llvm -triple x86_64-scei-ps5 -fdeclspec %s -O1 
-disable-llvm-passes -o - -DAPI= | FileCheck %s --check-prefixes=NONE
-// RUN: %clang_cc1 -emit-llvm -triple x86_64-scei-ps5 -fdeclspec %s -O1 
-disable-llvm-passes -o - -DAPI="__declspec(dllexport)" | FileCheck %s 
--check-prefixes=EXPORT
-// RUN: %clang_cc1 -emit-llvm -triple x86_64-scei-ps5 -fdeclspec %s -O1 
-disable-llvm-passes -o - -DAPI="__declspec(dllimport)" | FileCheck %s 
--check-prefixes=IMPORT
+// RUN: %clang_cc1 -emit-llvm -triple x86_64-sie-ps5 -fdeclspec %s -O1 
-disable-llvm-passes -o - -DAPI= | FileCheck %s --check-prefixes=NONE
+// RUN: %clang_cc1 -emit-llvm -triple x86_64-sie-ps5 -fdeclspec %s -O1 
-disable-llvm-passes -o - -DAPI="__declspec(dllexport)" | FileCheck %s 
--check-prefixes=EXPORT
+// RUN: %clang_cc1 -emit-llvm -triple x86_64-sie-ps5 -fdeclspec %s -O1 
-disable-llvm-passes -o - -DAPI="__declspec(dllimport)" | FileCheck %s 
--check-prefixes=IMPORT
 
 //NONE: @_ZZN3foo3GetEvE9Singleton = linkonce_odr {{(dso_local )?}}global
 //NONE: @_ZGVZN3foo3GetEvE9Singleton = linkonce_odr {{(dso_local )?}}global
diff --git a/clang/test/Driver/debug-options.c 
b/clang/test/Driver/debug-options.c
index 21785ba01cb410..73f2f402efa97a 100644
--- a/clang/test/Driver/debug-options.c
+++ b/clang/test/Driver/debug-options.c
@@ -138,9 +138,9 @@
 // RUN: | FileCheck -check-prefix=LDGARANGE %s
 // RUN: %clang -### %s -g -flto=full -target x86_64-scei-ps4 2>&1 \
 // RUN: | FileCheck -check-prefix=LDGARANGE %s
-// RUN: %clang -### %s -g -flto -target x86_64-scei-ps5 2>&1 \
+// RUN: %clang -### %s -g -flto -target x86_64-sie-ps5 2>&1 \
 // RUN: | FileCheck -check-prefix=LDGARANGE %s
-// RUN: %clang -### %s -g -target x86_64-scei-ps5 2>&1 \
+// RUN: %clang -### %s -g -target x86_64-sie-ps5 2>&1 \
 // RUN: | FileCheck -check-prefix=LDGARANGE %s
 
 // On the AIX, -g defaults to limited debug info.
diff --git a/clang/test/Driver/ps5-linker.c b/clang/test/Driver/ps5-linker.c
index c462e5a178e4a6..84363deb0337f7 100644
--- a/clang/test/Driver/ps5-linker.c
+++ b/clang/test/Driver/ps5-linker.c
@@ -1,14 +1,14 @@
 // Test that PIE is the default for main components
 
-// RUN: %clang --target=x86_64-scei-ps5 %s -### 2>&1 | FileCheck 
--check-prefixes=CHECK-PIE %s
+// RUN: %clang --target=x86_64-sie-ps5 %s -### 2>&1 | FileCheck 
--check-prefixes=CHECK-PIE %s
 
 // CHECK-PIE: {{ld(\.exe)?}}"
 // CHECK-PIE-SAME: "-pie"
 
-// RUN: %clang --target=x86_64-scei-ps5 -no-pie %s -### 2>&1 | FileCheck 
--check-prefixes=CHECK-NO-PIE %s
-// RUN: %clang --targ

[clang] [PS5][clang][test] x86_64-scei-ps5 -> x86_64-sie-ps5 in tests (PR #105810)

2024-08-23 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-driver

@llvm/pr-subscribers-clang

Author: Edd Dawson (playstation-edd)


Changes

`x86_64-sie-ps5` is the triple we share with PS5 toolchain users who have 
reason to care about such things. The vast majority of PS5 checks and tests 
already use this variant. Quashing the handful of stragglers will help prevent 
future copy+paste of the discouraged variant.

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


4 Files Affected:

- (modified) clang/test/CodeGen/tls-maxalign-modflag.c (+1-1) 
- (modified) clang/test/CodeGenCXX/windows-itanium-init-guard.cpp (+3-3) 
- (modified) clang/test/Driver/debug-options.c (+2-2) 
- (modified) clang/test/Driver/ps5-linker.c (+10-10) 


``diff
diff --git a/clang/test/CodeGen/tls-maxalign-modflag.c 
b/clang/test/CodeGen/tls-maxalign-modflag.c
index 685057c3551a00..26dde569f389c9 100644
--- a/clang/test/CodeGen/tls-maxalign-modflag.c
+++ b/clang/test/CodeGen/tls-maxalign-modflag.c
@@ -2,7 +2,7 @@
 
 // Test that we get the module flag TLSMaxAlign on the PS platforms.
 // RUN: %clang_cc1 -triple x86_64-scei-ps4 -emit-llvm -o - %s | FileCheck %s
-// RUN: %clang_cc1 -triple x86_64-scei-ps5 -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-sie-ps5 -emit-llvm -o - %s | FileCheck %s
 
 int main(void) {
   return 0;
diff --git a/clang/test/CodeGenCXX/windows-itanium-init-guard.cpp 
b/clang/test/CodeGenCXX/windows-itanium-init-guard.cpp
index 8bcfd272ae8f16..c51ce470061d64 100644
--- a/clang/test/CodeGenCXX/windows-itanium-init-guard.cpp
+++ b/clang/test/CodeGenCXX/windows-itanium-init-guard.cpp
@@ -11,9 +11,9 @@
 // RUN: %clang_cc1 -emit-llvm -triple x86_64-scei-ps4 -fdeclspec %s -O1 
-disable-llvm-passes -o - -DAPI="__declspec(dllexport)" | FileCheck %s 
--check-prefixes=EXPORT
 // RUN: %clang_cc1 -emit-llvm -triple x86_64-scei-ps4 -fdeclspec %s -O1 
-disable-llvm-passes -o - -DAPI="__declspec(dllimport)" | FileCheck %s 
--check-prefixes=IMPORT
 
-// RUN: %clang_cc1 -emit-llvm -triple x86_64-scei-ps5 -fdeclspec %s -O1 
-disable-llvm-passes -o - -DAPI= | FileCheck %s --check-prefixes=NONE
-// RUN: %clang_cc1 -emit-llvm -triple x86_64-scei-ps5 -fdeclspec %s -O1 
-disable-llvm-passes -o - -DAPI="__declspec(dllexport)" | FileCheck %s 
--check-prefixes=EXPORT
-// RUN: %clang_cc1 -emit-llvm -triple x86_64-scei-ps5 -fdeclspec %s -O1 
-disable-llvm-passes -o - -DAPI="__declspec(dllimport)" | FileCheck %s 
--check-prefixes=IMPORT
+// RUN: %clang_cc1 -emit-llvm -triple x86_64-sie-ps5 -fdeclspec %s -O1 
-disable-llvm-passes -o - -DAPI= | FileCheck %s --check-prefixes=NONE
+// RUN: %clang_cc1 -emit-llvm -triple x86_64-sie-ps5 -fdeclspec %s -O1 
-disable-llvm-passes -o - -DAPI="__declspec(dllexport)" | FileCheck %s 
--check-prefixes=EXPORT
+// RUN: %clang_cc1 -emit-llvm -triple x86_64-sie-ps5 -fdeclspec %s -O1 
-disable-llvm-passes -o - -DAPI="__declspec(dllimport)" | FileCheck %s 
--check-prefixes=IMPORT
 
 //NONE: @_ZZN3foo3GetEvE9Singleton = linkonce_odr {{(dso_local )?}}global
 //NONE: @_ZGVZN3foo3GetEvE9Singleton = linkonce_odr {{(dso_local )?}}global
diff --git a/clang/test/Driver/debug-options.c 
b/clang/test/Driver/debug-options.c
index 21785ba01cb410..73f2f402efa97a 100644
--- a/clang/test/Driver/debug-options.c
+++ b/clang/test/Driver/debug-options.c
@@ -138,9 +138,9 @@
 // RUN: | FileCheck -check-prefix=LDGARANGE %s
 // RUN: %clang -### %s -g -flto=full -target x86_64-scei-ps4 2>&1 \
 // RUN: | FileCheck -check-prefix=LDGARANGE %s
-// RUN: %clang -### %s -g -flto -target x86_64-scei-ps5 2>&1 \
+// RUN: %clang -### %s -g -flto -target x86_64-sie-ps5 2>&1 \
 // RUN: | FileCheck -check-prefix=LDGARANGE %s
-// RUN: %clang -### %s -g -target x86_64-scei-ps5 2>&1 \
+// RUN: %clang -### %s -g -target x86_64-sie-ps5 2>&1 \
 // RUN: | FileCheck -check-prefix=LDGARANGE %s
 
 // On the AIX, -g defaults to limited debug info.
diff --git a/clang/test/Driver/ps5-linker.c b/clang/test/Driver/ps5-linker.c
index c462e5a178e4a6..84363deb0337f7 100644
--- a/clang/test/Driver/ps5-linker.c
+++ b/clang/test/Driver/ps5-linker.c
@@ -1,14 +1,14 @@
 // Test that PIE is the default for main components
 
-// RUN: %clang --target=x86_64-scei-ps5 %s -### 2>&1 | FileCheck 
--check-prefixes=CHECK-PIE %s
+// RUN: %clang --target=x86_64-sie-ps5 %s -### 2>&1 | FileCheck 
--check-prefixes=CHECK-PIE %s
 
 // CHECK-PIE: {{ld(\.exe)?}}"
 // CHECK-PIE-SAME: "-pie"
 
-// RUN: %clang --target=x86_64-scei-ps5 -no-pie %s -### 2>&1 | FileCheck 
--check-prefixes=CHECK-NO-PIE %s
-// RUN: %clang --target=x86_64-scei-ps5 -r %s -### 2>&1 | FileCheck 
--check-prefixes=CHECK-NO-PIE %s
-// RUN: %clang --target=x86_64-scei-ps5 -shared %s -### 2>&1 | FileCheck 
--check-prefixes=CHECK-NO-PIE,CHECK-SHARED %s
-// RUN: %clang --target=x86_64-scei-ps5 -static %s -### 2>&1 | FileCheck 
--check-prefixes=CHECK-NO-PIE %s
+// RUN: %clang --target=x86_64-sie-ps5 -no-pie %s -### 2>&1 | FileCheck 
--check-pre

[clang] [clang][bytecode][NFC] Remove containsErrors check from visitInitializer (PR #105811)

2024-08-23 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr created 
https://github.com/llvm/llvm-project/pull/105811

None

>From f3e08fd46b07c83eaae700301c2e0c59743c0d19 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Fri, 23 Aug 2024 12:43:50 +0200
Subject: [PATCH] [clang][bytecode][NFC] Remove containsErrors check from
 visitInitializer

---
 clang/lib/AST/ByteCode/Compiler.cpp | 3 ---
 1 file changed, 3 deletions(-)

diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index f11196d2b02707..0fc942a4f1bc4f 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -3301,9 +3301,6 @@ template 
 bool Compiler::visitInitializer(const Expr *E) {
   assert(!classify(E->getType()));
 
-  if (E->containsErrors())
-return this->emitError(E);
-
   if (!this->checkLiteralType(E))
 return false;
 

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


[clang] [clang][bytecode][NFC] Remove containsErrors check from visitInitializer (PR #105811)

2024-08-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes



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


1 Files Affected:

- (modified) clang/lib/AST/ByteCode/Compiler.cpp (-3) 


``diff
diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index f11196d2b02707..0fc942a4f1bc4f 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -3301,9 +3301,6 @@ template 
 bool Compiler::visitInitializer(const Expr *E) {
   assert(!classify(E->getType()));
 
-  if (E->containsErrors())
-return this->emitError(E);
-
   if (!this->checkLiteralType(E))
 return false;
 

``




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


[clang] [llvm] [Coverage][MC/DC] Show uncoverable and unreachable conditions (PR #94137)

2024-08-23 Thread via cfe-commits

Lambdaris wrote:

> > I have no authority to request reviewers or commit this patch. So let's @ 
> > someone, @chapuni @ornata @hanickadot
> 
> I had some comments in the pending state that I just now noticed :( sorry 
> about that.

:fearful: Terribly sorry I was not aware that pending views are invisible to 
others.

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


[clang] [llvm] [Coverage][MC/DC] Show uncoverable and unreachable conditions (PR #94137)

2024-08-23 Thread via cfe-commits

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


[clang-tools-extra] [clangd] fix crash in include cleaner (PR #99514)

2024-08-23 Thread Yuxuan Shui via cfe-commits

yshui wrote:

@HighCommander4 It's been a while. I think I was trying to ignore everything 
but the main file in CollectMacros, but the naive approach i used wasn't working

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


[clang] [analyzer] Detect leak of a stack address through output arguments 2/3 (PR #105653)

2024-08-23 Thread Arseniy Zaostrovnykh via cfe-commits

https://github.com/necto updated 
https://github.com/llvm/llvm-project/pull/105653

>From db68dcfba96bfbf9367ba4159b6bf179c8c56f4f Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Tue, 20 Aug 2024 10:26:38 +0200
Subject: [PATCH 1/7] [analyzer] [NFC] Add tests for and refactor
 StackAddrEscapeChecker

These tests and refactoring are preparatory for the upcoming changes:
detection of the indirect leak via global variables and output parameters.

CPP-4734
---
 .../Checkers/StackAddrEscapeChecker.cpp   |  71 ++-
 clang/test/Analysis/stack-addr-ps.c   |  31 +
 clang/test/Analysis/stack-addr-ps.cpp | 596 ++
 3 files changed, 665 insertions(+), 33 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
index ea09c43cc5ce90..2bd4ca4528de8b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
@@ -288,12 +288,37 @@ void StackAddrEscapeChecker::checkPreStmt(const 
ReturnStmt *RS,
   EmitStackError(C, R, RetE);
 }
 
+std::optional printReferrer(const MemRegion *Referrer) {
+  assert(Referrer);
+  const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
+if (isa(Space))
+  return "static";
+if (isa(Space))
+  return "global";
+assert(isa(Space));
+return "stack";
+  }(Referrer->getMemorySpace());
+
+  // We should really only have VarRegions here.
+  // Anything else is really surprising, and we should get notified if such
+  // ever happens.
+  const auto *ReferrerVar = dyn_cast(Referrer);
+  if (!ReferrerVar) {
+assert(false && "We should have a VarRegion here");
+return std::nullopt; // Defensively skip this one.
+  }
+  const std::string ReferrerVarName =
+  ReferrerVar->getDecl()->getDeclName().getAsString();
+
+  return (ReferrerMemorySpace + " variable '" + ReferrerVarName + "'").str();
+}
+
 void StackAddrEscapeChecker::checkEndFunction(const ReturnStmt *RS,
   CheckerContext &Ctx) const {
   if (!ChecksEnabled[CK_StackAddrEscapeChecker])
 return;
 
-  ProgramStateRef State = Ctx.getState();
+  ExplodedNode *Node = Ctx.getPredecessor();
 
   // Iterate over all bindings to global variables and see if it contains
   // a memory region in the stack space.
@@ -315,15 +340,10 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   if (!ReferrerMemSpace || !ReferredMemSpace)
 return false;
 
-  const auto *ReferrerFrame = ReferrerMemSpace->getStackFrame();
-  const auto *ReferredFrame = ReferredMemSpace->getStackFrame();
-
-  if (ReferrerMemSpace && ReferredMemSpace) {
-if (ReferredFrame == PoppedFrame &&
-ReferrerFrame->isParentOf(PoppedFrame)) {
-  V.emplace_back(Referrer, Referred);
-  return true;
-}
+  if (ReferredMemSpace->getStackFrame() == PoppedFrame &&
+  ReferrerMemSpace->getStackFrame()->isParentOf(PoppedFrame)) {
+V.emplace_back(Referrer, Referred);
+return true;
   }
   return false;
 }
@@ -352,6 +372,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   };
 
   CallBack Cb(Ctx);
+  ProgramStateRef State = Node->getState();
   State->getStateManager().getStoreManager().iterBindings(State->getStore(),
   Cb);
 
@@ -359,7 +380,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 return;
 
   // Generate an error node.
-  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State);
+  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State, Node);
   if (!N)
 return;
 
@@ -374,13 +395,13 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 
 // Generate a report for this bug.
 const StringRef CommonSuffix =
-"upon returning to the caller.  This will be a dangling reference";
+" upon returning to the caller.  This will be a dangling reference";
 SmallString<128> Buf;
 llvm::raw_svector_ostream Out(Buf);
 const SourceRange Range = genName(Out, Referred, Ctx.getASTContext());
 
 if (isa(Referrer)) {
-  Out << " is still referred to by a temporary object on the stack "
+  Out << " is still referred to by a temporary object on the stack"
   << CommonSuffix;
   auto Report =
   std::make_unique(*BT_stackleak, Out.str(), 
N);
@@ -390,28 +411,12 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   return;
 }
 
-const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
-  if (isa(Space))
-return "static";
-  if (isa(Space))
-return "global";
-  assert(isa(Space));
-  return "stack";
-}(Referrer->getMemorySpace());
-
-// We should really only have VarRegions here.
-// Anything else is reall

[clang] [analyzer] Detect leak of a stack address through output arguments 2/3 (PR #105653)

2024-08-23 Thread Arseniy Zaostrovnykh via cfe-commits


@@ -161,3 +164,619 @@ C make1() {
 void test_copy_elision() {
   C c1 = make1();
 }
+
+namespace leaking_via_direct_pointer {
+void* returned_direct_pointer_top() {
+  int local = 42;
+  int* p = &local;
+  return p; // expected-warning{{associated with local variable 'local' 
returned}}
+}
+
+int* returned_direct_pointer_callee() {
+  int local = 42;
+  int* p = &local;
+  return p; // expected-warning{{associated with local variable 'local' 
returned}}
+}
+
+void returned_direct_pointer_caller() {
+  int* loc_ptr = nullptr;
+  loc_ptr = returned_direct_pointer_callee();
+  (void)loc_ptr;
+}
+
+void* global_ptr;
+
+void global_direct_pointer() {
+  int local = 42;
+  global_ptr = &local;
+} // expected-warning{{local variable 'local' is still referred to by the 
global variable 'global_ptr'}}
+
+void static_direct_pointer_top() {
+  int local = 42;
+  static int* p = &local;
+  (void)p;
+} // expected-warning{{local variable 'local' is still referred to by the 
static variable 'p'}}
+
+void static_direct_pointer_callee() {
+  int local = 42;
+  static int* p = &local;
+  (void)p; // expected-warning{{local variable 'local' is still referred to by 
the static variable 'p'}}
+}
+
+void static_direct_pointer_caller() {
+  static_direct_pointer_callee();
+}
+
+void lambda_to_global_direct_pointer() {
+  auto lambda = [&] {
+int local = 42;
+global_ptr = &local; // expected-warning{{local variable 'local' is still 
referred to by the global variable 'global_ptr'}}
+  };
+  lambda();
+}
+
+void lambda_to_context_direct_pointer() {
+  int *p = nullptr;
+  auto lambda = [&] {
+int local = 42;
+p = &local; // expected-warning{{local variable 'local' is still referred 
to by the stack variable 'p'}}
+  };
+  lambda();
+  (void)p;
+}
+
+template
+class MyFunction {
+  Callable* fptr;
+  public:
+  MyFunction(Callable* callable) :fptr(callable) {}
+};
+
+void* lambda_to_context_direct_pointer_uncalled() {
+  int *p = nullptr;
+  auto lambda = [&] {
+int local = 42;
+p = &local; // no-warning: analyzed only as top-level, ignored explicitly 
by the checker
+  };
+  return new MyFunction(&lambda);
+}
+
+void lambda_to_context_direct_pointer_lifetime_extended() {
+  int *p = nullptr;
+  auto lambda = [&] {
+int&& local = 42;
+p = &local; // expected-warning{{'int' lifetime extended by local variable 
'local' is still referred to by the stack variable 'p'}}
+  };
+  lambda();
+  (void)p;
+}
+
+template
+void lambda_param_capture_direct_pointer_callee(Callback& callee) {
+  int local = 42;
+  callee(local); // expected-warning{{'local' is still referred to by the 
stack variable 'p'}}
+}
+
+void lambda_param_capture_direct_pointer_caller() {
+  int* p = nullptr;
+  auto capt = [&p](int& param) {
+p = ¶m;
+  };
+  lambda_param_capture_direct_pointer_callee(capt);
+}
+} // namespace leaking_via_direct_pointer
+
+namespace leaking_via_ptr_to_ptr {
+void** returned_ptr_to_ptr_top() {
+  int local = 42;
+  int* p = &local;
+  void** pp = (void**)&p;
+  return pp; // expected-warning{{associated with local variable 'p' returned}}
+}
+
+void** global_pp;
+
+void global_ptr_local_to_ptr() {
+  int local = 42;
+  int* p = &local;
+  global_pp = (void**)&p;
+} // expected-warning{{local variable 'p' is still referred to by the global 
variable 'global_pp'}}
+
+void global_ptr_to_ptr() {
+  int local = 42;
+  *global_pp = &local; // no-warning FIXME
+}
+
+void *** global_ppp;
+
+void global_ptr_to_ptr_to_ptr() {
+  int local = 42;
+  **global_ppp = &local; // no-warning FIXME
+}
+
+void** get_some_pp();
+
+void static_ptr_to_ptr() {
+  int local = 42;
+  static void** pp = get_some_pp();
+  *pp = &local;
+} // no-warning False Negative, requires relating multiple bindings to cross 
the invented pointer.
+
+void param_ptr_to_ptr_top(void** pp) {
+  int local = 42;
+  *pp = &local; // no-warning FIXME
+}
+
+void param_ptr_to_ptr_callee(void** pp) {
+  int local = 42;
+  *pp = &local; // expected-warning{{local variable 'local' is still referred 
to by the stack variable 'p'}}
+}
+
+void param_ptr_to_ptr_caller() {
+  void* p = nullptr;
+  param_ptr_to_ptr_callee((void**)&p);
+}
+
+void param_ptr_to_ptr_to_ptr_top(void*** ppp) {
+  int local = 42;
+  **ppp = &local; // no-warning FIXME
+}
+
+void param_ptr_to_ptr_to_ptr_callee(void*** ppp) {
+  int local = 42;
+  **ppp = &local; // expected-warning{{local variable 'local' is still 
referred to by the stack variable 'pp'}}
+}
+
+void param_ptr_to_ptr_to_ptr_caller(void** pp) {
+  param_ptr_to_ptr_to_ptr_callee(&pp);
+}
+
+void lambda_to_context_ptr_to_ptr(int **pp) {
+  auto lambda = [&] {
+int local = 42;
+*pp = &local; // expected-warning{{local variable 'local' is still 
referred to by the stack variable 'pp'}}
+  };
+  lambda();
+  (void)*pp;
+}
+
+void param_ptr_to_ptr_fptr(int **pp) {
+  int local = 42;
+  *pp = &local; // expected-warning{{local variable 'local' is still referred 
to by the stack variable 'p'}}
+}
+
+vo

[clang] [clang-tools-extra] [lldb] [llvm] [mlir] [Support] Validate number of arguments passed to formatv() (PR #105745)

2024-08-23 Thread Rahul Joshi via cfe-commits

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


[clang] [analyzer] Detect leak of a stack address through output arguments 2/3 (PR #105653)

2024-08-23 Thread Arseniy Zaostrovnykh via cfe-commits

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


[clang] [clang] Compiler builtin for deduping a list of types (PR #105817)

2024-08-23 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 created 
https://github.com/llvm/llvm-project/pull/105817

None

>From 77003063912f691d246c4f94dd7a952ceace9268 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Fri, 23 Aug 2024 11:57:40 +
Subject: [PATCH] [clang] Compiler builtin for deduping a list of types

---
 .../clang/Basic/TransformTypeTraits.def   |  2 ++
 clang/include/clang/Sema/DeclSpec.h   |  2 +-
 clang/include/clang/Sema/Sema.h   |  1 +
 clang/lib/Sema/SemaTemplate.cpp   | 33 +++
 clang/lib/Sema/SemaType.cpp   |  4 +++
 5 files changed, 41 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/TransformTypeTraits.def 
b/clang/include/clang/Basic/TransformTypeTraits.def
index e27a2719a9680f..15313fb2db01eb 100644
--- a/clang/include/clang/Basic/TransformTypeTraits.def
+++ b/clang/include/clang/Basic/TransformTypeTraits.def
@@ -26,4 +26,6 @@ TRANSFORM_TYPE_TRAIT_DEF(RemoveReference, remove_reference_t)
 TRANSFORM_TYPE_TRAIT_DEF(RemoveRestrict, remove_restrict)
 TRANSFORM_TYPE_TRAIT_DEF(RemoveVolatile, remove_volatile)
 TRANSFORM_TYPE_TRAIT_DEF(EnumUnderlyingType, underlying_type)
+TRANSFORM_TYPE_TRAIT_DEF(DedupTemplateArgs, dedup_template_args)
+
 #undef TRANSFORM_TYPE_TRAIT_DEF
diff --git a/clang/include/clang/Sema/DeclSpec.h 
b/clang/include/clang/Sema/DeclSpec.h
index 425b6e2a0b30c9..fbfd68054cf002 100644
--- a/clang/include/clang/Sema/DeclSpec.h
+++ b/clang/include/clang/Sema/DeclSpec.h
@@ -469,7 +469,7 @@ class DeclSpec {
 T == TST_class);
   }
   static bool isTransformTypeTrait(TST T) {
-constexpr std::array Traits = {
+constexpr std::array Traits = {
 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) TST_##Trait,
 #include "clang/Basic/TransformTypeTraits.def"
 };
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 2ec6367eccea01..d1f6a5c11a84e3 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -14870,6 +14870,7 @@ class Sema final : public SemaBase {
   QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
SourceLocation Loc);
   QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
+  QualType BuiltinDedupTemplateArgs(QualType BaseType, SourceLocation Loc);
   QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
   QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
   QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 87b1f98bbe5ac9..28efc766401c7a 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -17,7 +17,9 @@
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/TemplateBase.h"
 #include "clang/AST/TemplateName.h"
+#include "clang/AST/Type.h"
 #include "clang/AST/TypeVisitor.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/DiagnosticSema.h"
@@ -38,6 +40,7 @@
 #include "clang/Sema/Template.h"
 #include "clang/Sema/TemplateDeduction.h"
 #include "llvm/ADT/BitVector.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/SmallBitVector.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
@@ -8037,6 +8040,36 @@ static bool 
CheckNonTypeTemplatePartialSpecializationArgs(
   return false;
 }
 
+QualType Sema::BuiltinDedupTemplateArgs(QualType BaseType, SourceLocation Loc) 
{
+  if (RequireCompleteType(Loc, BaseType,
+  diag::err_incomplete_type_used_in_type_trait_expr))
+return QualType();
+  const ElaboratedType *ET = cast(BaseType);
+  auto *TST = ET->getNamedType()->castAs();
+  if (!TST) {
+Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
+return QualType();
+  }
+  TemplateArgumentListInfo Args(Loc, Loc);
+  auto AddArg = [&](TemplateArgument T) {
+Args.addArgument(TemplateArgumentLoc(
+T, Context.getTrivialTypeSourceInfo(T.getAsType(), Loc)));
+  };
+  llvm::DenseSet SeenArgTypes;
+  for (const auto &T : TST->template_arguments()) {
+if (SeenArgTypes.contains(T.getAsType()))
+  continue;
+AddArg(T);
+SeenArgTypes.insert(T.getAsType());
+  }
+  QualType DedupType = CheckTemplateIdType(TST->getTemplateName(), Loc, Args);
+
+  if (RequireCompleteType(Loc, DedupType,
+  diag::err_coroutine_type_missing_specialization))
+return QualType();
+  return DedupType;
+}
+
 bool Sema::CheckTemplatePartialSpecializationArgs(
 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
 unsigned NumExplicit, ArrayRef TemplateArgs) {
diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 6fa39cdccef2b9..a9a05c3f15e1fa 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -9736,6 +9736,10 @@ QualType Sema::BuildUnaryTransformType(QualType 
BaseType, U

[clang] [clang] Compiler builtin for deduping a list of types (PR #105817)

2024-08-23 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated 
https://github.com/llvm/llvm-project/pull/105817

>From 77003063912f691d246c4f94dd7a952ceace9268 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Fri, 23 Aug 2024 11:57:40 +
Subject: [PATCH] [clang] Compiler builtin for deduping a list of types

---
 .../clang/Basic/TransformTypeTraits.def   |  2 ++
 clang/include/clang/Sema/DeclSpec.h   |  2 +-
 clang/include/clang/Sema/Sema.h   |  1 +
 clang/lib/Sema/SemaTemplate.cpp   | 33 +++
 clang/lib/Sema/SemaType.cpp   |  4 +++
 5 files changed, 41 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/TransformTypeTraits.def 
b/clang/include/clang/Basic/TransformTypeTraits.def
index e27a2719a9680f..15313fb2db01eb 100644
--- a/clang/include/clang/Basic/TransformTypeTraits.def
+++ b/clang/include/clang/Basic/TransformTypeTraits.def
@@ -26,4 +26,6 @@ TRANSFORM_TYPE_TRAIT_DEF(RemoveReference, remove_reference_t)
 TRANSFORM_TYPE_TRAIT_DEF(RemoveRestrict, remove_restrict)
 TRANSFORM_TYPE_TRAIT_DEF(RemoveVolatile, remove_volatile)
 TRANSFORM_TYPE_TRAIT_DEF(EnumUnderlyingType, underlying_type)
+TRANSFORM_TYPE_TRAIT_DEF(DedupTemplateArgs, dedup_template_args)
+
 #undef TRANSFORM_TYPE_TRAIT_DEF
diff --git a/clang/include/clang/Sema/DeclSpec.h 
b/clang/include/clang/Sema/DeclSpec.h
index 425b6e2a0b30c9..fbfd68054cf002 100644
--- a/clang/include/clang/Sema/DeclSpec.h
+++ b/clang/include/clang/Sema/DeclSpec.h
@@ -469,7 +469,7 @@ class DeclSpec {
 T == TST_class);
   }
   static bool isTransformTypeTrait(TST T) {
-constexpr std::array Traits = {
+constexpr std::array Traits = {
 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) TST_##Trait,
 #include "clang/Basic/TransformTypeTraits.def"
 };
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 2ec6367eccea01..d1f6a5c11a84e3 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -14870,6 +14870,7 @@ class Sema final : public SemaBase {
   QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
SourceLocation Loc);
   QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
+  QualType BuiltinDedupTemplateArgs(QualType BaseType, SourceLocation Loc);
   QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
   QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
   QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 87b1f98bbe5ac9..28efc766401c7a 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -17,7 +17,9 @@
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/TemplateBase.h"
 #include "clang/AST/TemplateName.h"
+#include "clang/AST/Type.h"
 #include "clang/AST/TypeVisitor.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/DiagnosticSema.h"
@@ -38,6 +40,7 @@
 #include "clang/Sema/Template.h"
 #include "clang/Sema/TemplateDeduction.h"
 #include "llvm/ADT/BitVector.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/SmallBitVector.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
@@ -8037,6 +8040,36 @@ static bool 
CheckNonTypeTemplatePartialSpecializationArgs(
   return false;
 }
 
+QualType Sema::BuiltinDedupTemplateArgs(QualType BaseType, SourceLocation Loc) 
{
+  if (RequireCompleteType(Loc, BaseType,
+  diag::err_incomplete_type_used_in_type_trait_expr))
+return QualType();
+  const ElaboratedType *ET = cast(BaseType);
+  auto *TST = ET->getNamedType()->castAs();
+  if (!TST) {
+Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
+return QualType();
+  }
+  TemplateArgumentListInfo Args(Loc, Loc);
+  auto AddArg = [&](TemplateArgument T) {
+Args.addArgument(TemplateArgumentLoc(
+T, Context.getTrivialTypeSourceInfo(T.getAsType(), Loc)));
+  };
+  llvm::DenseSet SeenArgTypes;
+  for (const auto &T : TST->template_arguments()) {
+if (SeenArgTypes.contains(T.getAsType()))
+  continue;
+AddArg(T);
+SeenArgTypes.insert(T.getAsType());
+  }
+  QualType DedupType = CheckTemplateIdType(TST->getTemplateName(), Loc, Args);
+
+  if (RequireCompleteType(Loc, DedupType,
+  diag::err_coroutine_type_missing_specialization))
+return QualType();
+  return DedupType;
+}
+
 bool Sema::CheckTemplatePartialSpecializationArgs(
 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
 unsigned NumExplicit, ArrayRef TemplateArgs) {
diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 6fa39cdccef2b9..a9a05c3f15e1fa 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -9736,6 +9736,10 @@ QualType Sema::BuildUnaryTransformType(QualType 
BaseType, UTTKind

[clang] [llvm] [NVPTX] Support __usAtomicCAS builtin (PR #99646)

2024-08-23 Thread via cfe-commits

https://github.com/DenisGZM updated 
https://github.com/llvm/llvm-project/pull/99646

>From 4beb77166031e339208cb71d26d4e1bc5ae6b3a9 Mon Sep 17 00:00:00 2001
From: Denis Gerasimov 
Date: Fri, 19 Jul 2024 15:47:57 +0300
Subject: [PATCH 1/8] [NVPTX] Support __usAtomicCAS builtin

---
 clang/include/clang/Basic/BuiltinsNVPTX.def   |  3 +++
 clang/lib/CodeGen/CGBuiltin.cpp   |  3 +++
 clang/lib/Headers/__clang_cuda_device_functions.h | 12 
 clang/test/CodeGen/builtins-nvptx.c   |  3 +++
 llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp   |  2 +-
 llvm/lib/Target/NVPTX/NVPTXIntrinsics.td  | 15 +++
 6 files changed, 37 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/BuiltinsNVPTX.def 
b/clang/include/clang/Basic/BuiltinsNVPTX.def
index c11970c279c4bb..20f038a0a9bbde 100644
--- a/clang/include/clang/Basic/BuiltinsNVPTX.def
+++ b/clang/include/clang/Basic/BuiltinsNVPTX.def
@@ -844,6 +844,9 @@ BUILTIN(__nvvm_atom_xor_gen_ll, "LLiLLiD*LLi", "n")
 TARGET_BUILTIN(__nvvm_atom_cta_xor_gen_ll, "LLiLLiD*LLi", "n", SM_60)
 TARGET_BUILTIN(__nvvm_atom_sys_xor_gen_ll, "LLiLLiD*LLi", "n", SM_60)
 
+TARGET_BUILTIN(__nvvm_atom_cas_gen_us, "UsUsD*UsUs", "n", SM_70)
+TARGET_BUILTIN(__nvvm_atom_cta_cas_gen_us, "UsUsD*UsUs", "n", SM_70)
+TARGET_BUILTIN(__nvvm_atom_sys_cas_gen_us, "UsUsD*UsUs", "n", SM_70)
 BUILTIN(__nvvm_atom_cas_gen_i, "iiD*ii", "n")
 TARGET_BUILTIN(__nvvm_atom_cta_cas_gen_i, "iiD*ii", "n", SM_60)
 TARGET_BUILTIN(__nvvm_atom_sys_cas_gen_i, "iiD*ii", "n", SM_60)
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 2a733e4d834cfa..4204c8ff276ab1 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -20344,6 +20344,7 @@ Value *CodeGenFunction::EmitNVPTXBuiltinExpr(unsigned 
BuiltinID,
   case NVPTX::BI__nvvm_atom_min_gen_ull:
 return MakeBinaryAtomicValue(*this, llvm::AtomicRMWInst::UMin, E);
 
+  case NVPTX::BI__nvvm_atom_cas_gen_us:
   case NVPTX::BI__nvvm_atom_cas_gen_i:
   case NVPTX::BI__nvvm_atom_cas_gen_l:
   case NVPTX::BI__nvvm_atom_cas_gen_ll:
@@ -20535,6 +20536,7 @@ Value *CodeGenFunction::EmitNVPTXBuiltinExpr(unsigned 
BuiltinID,
   case NVPTX::BI__nvvm_atom_sys_xor_gen_l:
   case NVPTX::BI__nvvm_atom_sys_xor_gen_ll:
 return MakeScopedAtomic(Intrinsic::nvvm_atomic_xor_gen_i_sys, *this, E);
+  case NVPTX::BI__nvvm_atom_cta_cas_gen_us:
   case NVPTX::BI__nvvm_atom_cta_cas_gen_i:
   case NVPTX::BI__nvvm_atom_cta_cas_gen_l:
   case NVPTX::BI__nvvm_atom_cta_cas_gen_ll: {
@@ -20546,6 +20548,7 @@ Value *CodeGenFunction::EmitNVPTXBuiltinExpr(unsigned 
BuiltinID,
 Intrinsic::nvvm_atomic_cas_gen_i_cta, {ElemTy, Ptr->getType()}),
 {Ptr, EmitScalarExpr(E->getArg(1)), EmitScalarExpr(E->getArg(2))});
   }
+  case NVPTX::BI__nvvm_atom_sys_cas_gen_us:
   case NVPTX::BI__nvvm_atom_sys_cas_gen_i:
   case NVPTX::BI__nvvm_atom_sys_cas_gen_l:
   case NVPTX::BI__nvvm_atom_sys_cas_gen_ll: {
diff --git a/clang/lib/Headers/__clang_cuda_device_functions.h 
b/clang/lib/Headers/__clang_cuda_device_functions.h
index f8a12cefdb81b4..f66fe625a39676 100644
--- a/clang/lib/Headers/__clang_cuda_device_functions.h
+++ b/clang/lib/Headers/__clang_cuda_device_functions.h
@@ -529,6 +529,18 @@ __DEVICE__ void __threadfence(void) { __nvvm_membar_gl(); }
 __DEVICE__ void __threadfence_block(void) { __nvvm_membar_cta(); };
 __DEVICE__ void __threadfence_system(void) { __nvvm_membar_sys(); };
 __DEVICE__ void __trap(void) { __asm__ __volatile__("trap;"); }
+__DEVICE__ unsigned short __usAtomicCAS(unsigned short *__p, unsigned short 
__cmp,
+unsigned short __v) {
+  return __nvvm_atom_cas_gen_us(__p, __cmp, __v);
+}
+__DEVICE__ unsigned short __usAtomicCAS_block(unsigned short *__p, unsigned 
short __cmp,
+  unsigned short __v) {
+  return __nvvm_atom_cta_cas_gen_us(__p, __cmp, __v);
+}
+__DEVICE__ unsigned short __usAtomicCAS_system(unsigned short *__p, unsigned 
short __cmp,
+   unsigned short __v) {
+  return __nvvm_atom_sys_cas_gen_us(__p, __cmp, __v);
+}
 __DEVICE__ unsigned int __uAtomicAdd(unsigned int *__p, unsigned int __v) {
   return __nvvm_atom_add_gen_i((int *)__p, __v);
 }
diff --git a/clang/test/CodeGen/builtins-nvptx.c 
b/clang/test/CodeGen/builtins-nvptx.c
index 20399b73e63757..645f036761c18f 100644
--- a/clang/test/CodeGen/builtins-nvptx.c
+++ b/clang/test/CodeGen/builtins-nvptx.c
@@ -309,6 +309,9 @@ __device__ void nvvm_atom(float *fp, float f, double *dfp, 
double df, int *ip,
   // CHECK: atomicrmw umin ptr {{.*}} seq_cst, align 8
   __nvvm_atom_min_gen_ull((unsigned long long *)&sll, ll);
 
+  // CHECK: cmpxchg ptr {{.*}} seq_cst seq_cst, align 2
+  // CHECK-NEXT: extractvalue { i16, i1 } {{%[0-9]+}}, 0
+  __nvvm_atom_cas_gen_us(ip, 0, i);
   // CHECK: cmpxchg ptr {{.*}} seq_cst seq_cst, align 4
   // CHECK-NEXT: extractvalue { 

[clang] [clang][AArch64] Add SME2.1 feature macros (PR #105657)

2024-08-23 Thread via cfe-commits

https://github.com/SpencerAbson updated 
https://github.com/llvm/llvm-project/pull/105657

>From 32eaafbdfab98781756abd3cb525e2959544f6b8 Mon Sep 17 00:00:00 2001
From: Spencer Abson 
Date: Thu, 22 Aug 2024 13:14:19 +
Subject: [PATCH] [clang][AArch64] Add SME2.1 feature macros

This patch adds the following macros to clang which are described in the
alpha SME2.1 specification within the ACLE
(https://github.com/ARM-software/acle/pull/309/files)

- __ARM_FEATURE_SMEB16B16 (enabled by '+sme-b16b16')
- __ARM_FEATURE_SVEB16B16 (enabled by '+sve-b16b16' or '+sme-b16b16')
- __ARM_FEATURE_SMEF16F16 (enabled by '+sme-f16f16')

Redundant use of the clang macro-builder has also been removed, pre-processor
tests have been added for each new macro.
---
 clang/lib/Basic/Targets/AArch64.cpp   | 40 ++-
 clang/lib/Basic/Targets/AArch64.h |  3 ++
 .../Preprocessor/aarch64-target-features.c| 16 
 3 files changed, 50 insertions(+), 9 deletions(-)

diff --git a/clang/lib/Basic/Targets/AArch64.cpp 
b/clang/lib/Basic/Targets/AArch64.cpp
index 6ba31cc05a0d75..63fc15f916c558 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -471,23 +471,25 @@ void AArch64TargetInfo::getTargetDefines(const 
LangOptions &Opts,
   if (HasSVE2 && HasSVE2SM4)
 Builder.defineMacro("__ARM_FEATURE_SVE2_SM4", "1");
 
+  if (HasSVEB16B16)
+Builder.defineMacro("__ARM_FEATURE_SVE_B16B16", "1");
+
   if (HasSME) {
 Builder.defineMacro("__ARM_FEATURE_SME");
 Builder.defineMacro("__ARM_FEATURE_LOCALLY_STREAMING", "1");
   }
 
-  if (HasSME2) {
-Builder.defineMacro("__ARM_FEATURE_SME", "1");
+  if (HasSME2)
 Builder.defineMacro("__ARM_FEATURE_SME2", "1");
-Builder.defineMacro("__ARM_FEATURE_LOCALLY_STREAMING", "1");
-  }
 
-  if (HasSME2p1) {
-Builder.defineMacro("__ARM_FEATURE_SME", "1");
-Builder.defineMacro("__ARM_FEATURE_SME2", "1");
+  if (HasSME2p1)
 Builder.defineMacro("__ARM_FEATURE_SME2p1", "1");
-Builder.defineMacro("__ARM_FEATURE_LOCALLY_STREAMING", "1");
-  }
+
+  if (HasSMEF16F16)
+Builder.defineMacro("__ARM_FEATURE_SME_F16F16", "1");
+
+  if (HasSMEB16B16)
+Builder.defineMacro("__ARM_FEATURE_SME_B16B16", "1");
 
   if (HasCRC)
 Builder.defineMacro("__ARM_FEATURE_CRC32", "1");
@@ -749,6 +751,7 @@ bool AArch64TargetInfo::hasFeature(StringRef Feature) const 
{
   .Case("sve", FPU & SveMode)
   .Case("sve-bf16", FPU & SveMode && HasBFloat16)
   .Case("sve-i8mm", FPU & SveMode && HasMatMul)
+  .Case("sve-b16b16", HasSVEB16B16)
   .Case("f32mm", FPU & SveMode && HasMatmulFP32)
   .Case("f64mm", FPU & SveMode && HasMatmulFP64)
   .Case("sve2", FPU & SveMode && HasSVE2)
@@ -763,6 +766,8 @@ bool AArch64TargetInfo::hasFeature(StringRef Feature) const 
{
   .Case("sme-f64f64", HasSMEF64F64)
   .Case("sme-i16i64", HasSMEI16I64)
   .Case("sme-fa64", HasSMEFA64)
+  .Case("sme-f16f16", HasSMEF16F16)
+  .Case("sme-b16b16", HasSMEB16B16)
   .Cases("memtag", "memtag2", HasMTE)
   .Case("sb", HasSB)
   .Case("predres", HasPredRes)
@@ -863,6 +868,8 @@ bool 
AArch64TargetInfo::handleTargetFeatures(std::vector &Features,
   HasSVE2 = true;
   HasSVE2SM4 = true;
 }
+if (Feature == "+sve-b16b16")
+  HasSVEB16B16 = true;
 if (Feature == "+sve2-bitperm") {
   FPU |= NeonMode;
   FPU |= SveMode;
@@ -919,6 +926,21 @@ bool 
AArch64TargetInfo::handleTargetFeatures(std::vector &Features,
   HasSVE2 = true;
   HasSMEFA64 = true;
 }
+if (Feature == "+sme-f16f16") {
+  HasSME = true;
+  HasSME2 = true;
+  HasBFloat16 = true;
+  HasFullFP16 = true;
+  HasSMEF16F16 = true;
+}
+if (Feature == "+sme-b16b16") {
+  HasSME = true;
+  HasSME2 = true;
+  HasBFloat16 = true;
+  HasFullFP16 = true;
+  HasSVEB16B16 = true;
+  HasSMEB16B16 = true;
+}
 if (Feature == "+sb")
   HasSB = true;
 if (Feature == "+predres")
diff --git a/clang/lib/Basic/Targets/AArch64.h 
b/clang/lib/Basic/Targets/AArch64.h
index 7bdf5a2b4106e4..526f7f30a38618 100644
--- a/clang/lib/Basic/Targets/AArch64.h
+++ b/clang/lib/Basic/Targets/AArch64.h
@@ -53,6 +53,7 @@ class LLVM_LIBRARY_VISIBILITY AArch64TargetInfo : public 
TargetInfo {
   bool HasSVE2AES = false;
   bool HasSVE2SHA3 = false;
   bool HasSVE2SM4 = false;
+  bool HasSVEB16B16 = false;
   bool HasSVE2BitPerm = false;
   bool HasMatmulFP64 = false;
   bool HasMatmulFP32 = false;
@@ -71,6 +72,8 @@ class LLVM_LIBRARY_VISIBILITY AArch64TargetInfo : public 
TargetInfo {
   bool HasSME2 = false;
   bool HasSMEF64F64 = false;
   bool HasSMEI16I64 = false;
+  bool HasSMEF16F16 = false;
+  bool HasSMEB16B16 = false;
   bool HasSME2p1 = false;
   bool HasSB = false;
   bool HasPredRes = false;
diff --git a/clang/test/Preprocessor/aarch64-target-features.c 
b/clang/test/Preprocessor/aarch64-target-features.c
index 87bd3e142d2c40..ae2bdda6f536c5 10

[clang] [clang] Compiler builtin for deduping a list of types (PR #105817)

2024-08-23 Thread Utkarsh Saxena via cfe-commits

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


[clang] [clang] Compiler builtin for deduping a list of types (PR #105817)

2024-08-23 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated 
https://github.com/llvm/llvm-project/pull/105817

>From 77003063912f691d246c4f94dd7a952ceace9268 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Fri, 23 Aug 2024 11:57:40 +
Subject: [PATCH] [clang] Compiler builtin for deduping a list of types

---
 .../clang/Basic/TransformTypeTraits.def   |  2 ++
 clang/include/clang/Sema/DeclSpec.h   |  2 +-
 clang/include/clang/Sema/Sema.h   |  1 +
 clang/lib/Sema/SemaTemplate.cpp   | 33 +++
 clang/lib/Sema/SemaType.cpp   |  4 +++
 5 files changed, 41 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/TransformTypeTraits.def 
b/clang/include/clang/Basic/TransformTypeTraits.def
index e27a2719a9680f..15313fb2db01eb 100644
--- a/clang/include/clang/Basic/TransformTypeTraits.def
+++ b/clang/include/clang/Basic/TransformTypeTraits.def
@@ -26,4 +26,6 @@ TRANSFORM_TYPE_TRAIT_DEF(RemoveReference, remove_reference_t)
 TRANSFORM_TYPE_TRAIT_DEF(RemoveRestrict, remove_restrict)
 TRANSFORM_TYPE_TRAIT_DEF(RemoveVolatile, remove_volatile)
 TRANSFORM_TYPE_TRAIT_DEF(EnumUnderlyingType, underlying_type)
+TRANSFORM_TYPE_TRAIT_DEF(DedupTemplateArgs, dedup_template_args)
+
 #undef TRANSFORM_TYPE_TRAIT_DEF
diff --git a/clang/include/clang/Sema/DeclSpec.h 
b/clang/include/clang/Sema/DeclSpec.h
index 425b6e2a0b30c9..fbfd68054cf002 100644
--- a/clang/include/clang/Sema/DeclSpec.h
+++ b/clang/include/clang/Sema/DeclSpec.h
@@ -469,7 +469,7 @@ class DeclSpec {
 T == TST_class);
   }
   static bool isTransformTypeTrait(TST T) {
-constexpr std::array Traits = {
+constexpr std::array Traits = {
 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) TST_##Trait,
 #include "clang/Basic/TransformTypeTraits.def"
 };
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 2ec6367eccea01..d1f6a5c11a84e3 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -14870,6 +14870,7 @@ class Sema final : public SemaBase {
   QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
SourceLocation Loc);
   QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
+  QualType BuiltinDedupTemplateArgs(QualType BaseType, SourceLocation Loc);
   QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
   QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
   QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 87b1f98bbe5ac9..28efc766401c7a 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -17,7 +17,9 @@
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/TemplateBase.h"
 #include "clang/AST/TemplateName.h"
+#include "clang/AST/Type.h"
 #include "clang/AST/TypeVisitor.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/DiagnosticSema.h"
@@ -38,6 +40,7 @@
 #include "clang/Sema/Template.h"
 #include "clang/Sema/TemplateDeduction.h"
 #include "llvm/ADT/BitVector.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/SmallBitVector.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
@@ -8037,6 +8040,36 @@ static bool 
CheckNonTypeTemplatePartialSpecializationArgs(
   return false;
 }
 
+QualType Sema::BuiltinDedupTemplateArgs(QualType BaseType, SourceLocation Loc) 
{
+  if (RequireCompleteType(Loc, BaseType,
+  diag::err_incomplete_type_used_in_type_trait_expr))
+return QualType();
+  const ElaboratedType *ET = cast(BaseType);
+  auto *TST = ET->getNamedType()->castAs();
+  if (!TST) {
+Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
+return QualType();
+  }
+  TemplateArgumentListInfo Args(Loc, Loc);
+  auto AddArg = [&](TemplateArgument T) {
+Args.addArgument(TemplateArgumentLoc(
+T, Context.getTrivialTypeSourceInfo(T.getAsType(), Loc)));
+  };
+  llvm::DenseSet SeenArgTypes;
+  for (const auto &T : TST->template_arguments()) {
+if (SeenArgTypes.contains(T.getAsType()))
+  continue;
+AddArg(T);
+SeenArgTypes.insert(T.getAsType());
+  }
+  QualType DedupType = CheckTemplateIdType(TST->getTemplateName(), Loc, Args);
+
+  if (RequireCompleteType(Loc, DedupType,
+  diag::err_coroutine_type_missing_specialization))
+return QualType();
+  return DedupType;
+}
+
 bool Sema::CheckTemplatePartialSpecializationArgs(
 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
 unsigned NumExplicit, ArrayRef TemplateArgs) {
diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 6fa39cdccef2b9..a9a05c3f15e1fa 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -9736,6 +9736,10 @@ QualType Sema::BuildUnaryTransformType(QualType 
BaseType, UTTKind

[clang] [clang] Compiler builtin for deduping a list of types (PR #105817)

2024-08-23 Thread Utkarsh Saxena via cfe-commits

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


[clang] Deprecate -fheinous-gnu-extensions; introduce a new warning flag (PR #105821)

2024-08-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Aaron Ballman (AaronBallman)


Changes

The new warning flag is `-Winvalid-gnu-asm-cast`, which is enabled by default 
and is a downgradable diagnostic which defaults to an error.

This language dialect flag only controls whether a single diagnostic is emitted 
as a warning or as an error, and has never been expanded to include other 
behaviors. Given the rather perjorative name, it's better for us to just expose 
a diagnostic flag for the one warning in question and let the user elect to do 
`-Wno-error=` if they need to.

There's not a lot of use of the language dialect flag in the wild, but there is 
some use of it. For the time being, this aliases the -f flag to 
`-Wno-error=invalid-gnu-asm-cast`, but the -f flag can eventually be removed.

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


12 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+9) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+2-6) 
- (modified) clang/include/clang/Basic/LangOptions.def (-1) 
- (modified) clang/include/clang/Driver/Options.td (+6-2) 
- (modified) clang/lib/Sema/SemaStmtAsm.cpp (+2-7) 
- (modified) clang/test/Analysis/asm.cpp (+1-1) 
- (modified) clang/test/Analysis/cfg.c (+1-1) 
- (modified) clang/test/Analysis/cfg.cpp (+2-2) 
- (added) clang/test/Driver/heinous-gnu-extensions.c (+5) 
- (modified) clang/test/Misc/warning-flags.c (+1-2) 
- (modified) clang/test/Sema/heinous-extensions-off.c (+6-7) 
- (modified) clang/test/Sema/heinous-extensions-on.c (+3-3) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 12a924acc14331..5a4befee0efae5 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -177,6 +177,10 @@ New Compiler Flags
 Deprecated Compiler Flags
 -
 
+- ``-fheinous-gnu-extensions`` is deprecated; it is now equivalent to
+  specifying ``-Wno-error=invalid-gnu-asm-cast`` and may be removed in the
+  future.
+
 Modified Compiler Flags
 ---
 
@@ -241,6 +245,11 @@ Improvements to Clang's diagnostics
 
 - Don't emit duplicated dangling diagnostics. (#GH93386).
 
+- Added the ``-Winvalid-gnu-asm-cast`` diagnostic group to control warnings
+  about use of "noop" casts for lvalues (a GNU extension). This diagnostic is
+  a warning which defaults to being an error, is enabled by default, and is
+  also controlled by the now-deprecated ``-fheinous-gnu-extensions`` flag.
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 4b6aadd635786a..1d2e73b25afac8 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9365,9 +9365,6 @@ let CategoryName = "Inline Assembly Issue" in {
 "invalid input size for constraint '%0'">;
   def err_asm_invalid_output_size : Error<
 "invalid output size for constraint '%0'">;
-  def err_invalid_asm_cast_lvalue : Error<
-"invalid use of a cast in a inline asm context requiring an lvalue: "
-"remove the cast or build with -fheinous-gnu-extensions">;
   def err_invalid_asm_value_for_constraint
   : Error <"value '%0' out of range for constraint '%1'">;
   def err_asm_non_addr_value_in_memory_constraint : Error <
@@ -9381,9 +9378,8 @@ let CategoryName = "Inline Assembly Issue" in {
   def warn_asm_label_on_auto_decl : Warning<
 "ignored asm label '%0' on automatic variable">;
   def warn_invalid_asm_cast_lvalue : Warning<
-"invalid use of a cast in an inline asm context requiring an lvalue: "
-"accepted due to -fheinous-gnu-extensions, but clang may remove support "
-"for this in the future">;
+"invalid use of a cast in an inline asm context requiring an lvalue">,
+InGroup>, DefaultError;
   def warn_asm_mismatched_size_modifier : Warning<
 "value size does not match register size specified by the constraint "
 "and modifier">,
diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index d454a7ff2f8cf4..956d9a2d2434c4 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -190,7 +190,6 @@ LANGOPT(POSIXThreads  , 1, 0, "POSIX thread support")
 LANGOPT(Blocks, 1, 0, "blocks extension to C")
 BENIGN_LANGOPT(EmitAllDecls  , 1, 0, "emitting all declarations")
 LANGOPT(MathErrno , 1, 1, "errno in math functions")
-BENIGN_LANGOPT(HeinousExtensions , 1, 0, "extensions that we really don't like 
and may be ripped out at any time")
 LANGOPT(Modules   , 1, 0, "modules semantics")
 COMPATIBLE_LANGOPT(CPlusPlusModules, 1, 0, "C++ modules syntax")
 LANGOPT(SkipODRCheckInGMF, 1, 0, "Skip ODR checks for decls in the global 
module fragment")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/

[clang] 2f144ac - [clang][bytecode][NFC] Remove containsErrors check from visitInitializer (#105811)

2024-08-23 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-08-23T14:28:52+02:00
New Revision: 2f144ac5a13dc39389e1850417f4ac766b1f1ada

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

LOG: [clang][bytecode][NFC] Remove containsErrors check from visitInitializer 
(#105811)

Added: 


Modified: 
clang/lib/AST/ByteCode/Compiler.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index f11196d2b02707..0fc942a4f1bc4f 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -3301,9 +3301,6 @@ template 
 bool Compiler::visitInitializer(const Expr *E) {
   assert(!classify(E->getType()));
 
-  if (E->containsErrors())
-return this->emitError(E);
-
   if (!this->checkLiteralType(E))
 return false;
 



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


[clang] [clang][bytecode][NFC] Remove containsErrors check from visitInitializer (PR #105811)

2024-08-23 Thread Timm Baeder via cfe-commits

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


[clang] [C23] Update status page for TS 18661 integration (PR #105693)

2024-08-23 Thread Aaron Ballman via cfe-commits


@@ -216,35 +216,31 @@ C23 implementation status
   

 https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2341.pdf";>N2341
-Unknown
-  
-   
-https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2401.pdf";>N2401
-Unknown
+No
   

 https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2359.pdf";>N2359
 No
   

 https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2546.pdf";>N2546
-Unknown
+No
   
   
 https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2580.htm";>N2580
-Unknown
+No

AaronBallman wrote:

Okay, since this is under an omnibus feature category, I'll just remove this 
entry.

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


[clang] [C23] Update status page for TS 18661 integration (PR #105693)

2024-08-23 Thread Aaron Ballman via cfe-commits


@@ -216,35 +216,31 @@ C23 implementation status
   

 https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2341.pdf";>N2341
-Unknown
-  
-   
-https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2401.pdf";>N2401
-Unknown
+No
   

 https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2359.pdf";>N2359
 No
   

 https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2546.pdf";>N2546
-Unknown
+No
   
   
 https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2580.htm";>N2580
-Unknown
+No
   

 https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2640.htm";>N2640
-Unknown
+No

AaronBallman wrote:

Awesome, thanks!

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


[clang] [C23] Update status page for TS 18661 integration (PR #105693)

2024-08-23 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

> It might be better to list most of these as "N/A" rather than "No", for the 
> simple reason that decimal floating point is an optional feature we do not 
> support. Or maybe just a footnote saying something to that effect?

I think eventually I'd like to split out optional annexes and TSes to a 
separate table so we can track whether they're available in Clang or not rather 
than whether we conform or not. But for right now, I'd say let's stick with 
`No` because it's clear that we don't support them rather than N/A which 
somewhat implies that we don't need to make compiler changes to support them.

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


[clang] 1e3dc8c - [Serialization] Fix a warning

2024-08-23 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2024-08-23T05:49:49-07:00
New Revision: 1e3dc8cdb49bf7b8344d1d7f7befbb95a9fbdb63

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

LOG: [Serialization] Fix a warning

This patch fixes:

  clang/lib/Serialization/ASTReader.cpp:9978:27: error: lambda capture
  'this' is not used [-Werror,-Wunused-lambda-capture]

Added: 


Modified: 
clang/lib/Serialization/ASTReader.cpp

Removed: 




diff  --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index be83805f1e92b9..ffdaec4067e1c4 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -9975,7 +9975,7 @@ void ASTReader::finishPendingActions() {
   return false;
 };
 
-auto hasDefinition = [this, &hasDefinitionImpl](Decl *D) {
+auto hasDefinition = [&hasDefinitionImpl](Decl *D) {
   return hasDefinitionImpl(D, hasDefinitionImpl);
 };
 



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


[clang] [llvm] [NFC] Use const members of `StringToOffsetTable` (PR #105824)

2024-08-23 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul created 
https://github.com/llvm/llvm-project/pull/105824

- After the table is populated and emitted as a string, we do not expect any 
modifications to the table. So use const reference and const members to access 
the table from that point on.

>From 154c0728820a8a6e1e50e3b079d5df09abb198cd Mon Sep 17 00:00:00 2001
From: Rahul Joshi 
Date: Fri, 23 Aug 2024 05:45:25 -0700
Subject: [PATCH] [NFC] Use const members of `StringToOffsetTable`

- After the table is populated and emitted as a string, we do not expect
  any modifications to the table. So use const reference and const members
  to access the table from that point on.
---
 clang/utils/TableGen/ClangDiagnosticsEmitter.cpp |  9 +
 llvm/utils/TableGen/AsmMatcherEmitter.cpp| 10 +-
 2 files changed, 10 insertions(+), 9 deletions(-)

diff --git a/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp 
b/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
index b290530444d2ab..6ca24a8c74b2ff 100644
--- a/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
+++ b/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
@@ -1634,7 +1634,7 @@ static void emitDiagArrays(std::map &DiagsInGroup,
 /// \000\020#pragma-messages\t#warnings\020CFString-literal"
 ///   };
 /// \endcode
-static void emitDiagGroupNames(StringToOffsetTable &GroupNames,
+static void emitDiagGroupNames(const StringToOffsetTable &GroupNames,
raw_ostream &OS) {
   OS << "static const char DiagGroupNames[] = {\n";
   GroupNames.EmitString(OS);
@@ -1656,7 +1656,7 @@ static void emitDiagGroupNames(StringToOffsetTable 
&GroupNames,
 static void emitAllDiagArrays(std::map &DiagsInGroup,
   RecordVec &DiagsInPedantic,
   RecordVec &GroupsInPedantic,
-  StringToOffsetTable &GroupNames,
+  const StringToOffsetTable &GroupNames,
   raw_ostream &OS) {
   OS << "\n#ifdef GET_DIAG_ARRAYS\n";
   emitDiagArrays(DiagsInGroup, DiagsInPedantic, OS);
@@ -1683,7 +1683,8 @@ static void emitAllDiagArrays(std::map &DiagsInGroup,
 static void emitDiagTable(std::map &DiagsInGroup,
   RecordVec &DiagsInPedantic,
   RecordVec &GroupsInPedantic,
-  StringToOffsetTable &GroupNames, raw_ostream &OS) {
+  const StringToOffsetTable &GroupNames,
+  raw_ostream &OS) {
   unsigned MaxLen = 0;
 
   for (auto const &I: DiagsInGroup)
@@ -1705,7 +1706,7 @@ static void emitDiagTable(std::map &DiagsInGroup,
 OS << I.first << " */, ";
 // Store a pascal-style length byte at the beginning of the string.
 std::string Name = char(I.first.size()) + I.first;
-OS << GroupNames.GetOrAddStringOffset(Name, false) << ", ";
+OS << *GroupNames.GetStringOffset(Name) << ", ";
 
 // Special handling for 'pedantic'.
 const bool IsPedantic = I.first == "pedantic";
diff --git a/llvm/utils/TableGen/AsmMatcherEmitter.cpp 
b/llvm/utils/TableGen/AsmMatcherEmitter.cpp
index 5035ef52707f4e..98d0231d3055c2 100644
--- a/llvm/utils/TableGen/AsmMatcherEmitter.cpp
+++ b/llvm/utils/TableGen/AsmMatcherEmitter.cpp
@@ -2871,7 +2871,7 @@ static bool emitMnemonicAliases(raw_ostream &OS, const 
AsmMatcherInfo &Info,
 static void
 emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
  const AsmMatcherInfo &Info, StringRef ClassName,
- StringToOffsetTable &StringTable,
+ const StringToOffsetTable &StringTable,
  unsigned MaxMnemonicIndex, unsigned MaxFeaturesIndex,
  bool HasMnemonicFirst, const Record &AsmParser) {
   unsigned MaxMask = 0;
@@ -2924,8 +2924,8 @@ emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget 
&Target,
 
 // Store a pascal-style length byte in the mnemonic.
 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.lower();
-OS << StringTable.GetOrAddStringOffset(LenMnemonic, false) << " /* "
-   << II.Mnemonic << " */, ";
+OS << *StringTable.GetStringOffset(LenMnemonic) << " /* " << II.Mnemonic
+   << " */, ";
 
 OS << OMI.OperandMask;
 OS << " /* ";
@@ -3554,8 +3554,8 @@ void AsmMatcherEmitter::run(raw_ostream &OS) {
   // Store a pascal-style length byte in the mnemonic.
   std::string LenMnemonic =
   char(MI->Mnemonic.size()) + MI->Mnemonic.lower();
-  OS << "  { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
- << " /* " << MI->Mnemonic << " */, " << Target.getInstNamespace()
+  OS << "  { " << *StringTable.GetStringOffset(LenMnemonic) << " /* "
+ << MI->Mnemonic << " */, " << Target.getInstNamespace()
  << "::" << MI->getResultInst()->TheDef->getName() << ", "
  << MI->ConversionFnKind << ", ";
 

___
cfe-commits

[clang] Enable frame pointer for non-leaf functions on Android (PR #97614)

2024-08-23 Thread Sam Elliott via cfe-commits


@@ -166,7 +155,7 @@ static bool useFramePointerForTargetByDefault(const 
llvm::opt::ArgList &Args,
 
 static bool useLeafFramePointerForTargetByDefault(const llvm::Triple &Triple) {
   if (Triple.isAArch64() || Triple.isPS() || Triple.isVE() ||
-  (Triple.isAndroid() && Triple.isRISCV64()))
+  (Triple.isAndroid() && !Triple.isARM()))

lenary wrote:

Did you mean to miss out Thumb? `isARM` is only true for `arm-*`, `armeb-*` 
triples, you would need an `isThumb` call to also cover `thumb-*` and 
`thumbeb-*` triples.

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


[clang] [Clang] Implement P2747 constexpr placement new (PR #104586)

2024-08-23 Thread Aaron Ballman via cfe-commits

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


[clang] [Clang] Implement P2747 constexpr placement new (PR #104586)

2024-08-23 Thread Aaron Ballman via cfe-commits

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

LGTM!

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


[clang] [Clang] Implement P2747 constexpr placement new (PR #104586)

2024-08-23 Thread Aaron Ballman via cfe-commits


@@ -0,0 +1,115 @@
+// RUN: %clang_cc1 -std=c++2c -verify %s
+
+
+namespace std {
+  using size_t = decltype(sizeof(0));
+}
+
+void *operator new(std::size_t, void *p) { return p; }
+void* operator new[] (std::size_t, void* p) {return p;}
+
+
+consteval int ok() {
+int i;
+new (&i) int(0);
+new (&i) int[1]{1};
+new (static_cast(&i)) int(0);
+return 0;
+}
+
+consteval int conversion() {
+int i;
+new (static_cast(&i)) float(0);
+// expected-note@-1 {{placement new would change type of storage from 
'int' to 'float'}}
+return 0;
+}
+
+consteval int indeterminate() {
+int * indeterminate;
+new (indeterminate) int(0);
+// expected-note@-1 {{read of uninitialized object is not allowed in a 
constant expression}}
+return 0;
+}
+
+consteval int array1() {
+int i[2];
+new (&i) int[]{1,2};
+new (&i) int[]{1};
+new (&i) int(0);
+new (static_cast(&i)) int[]{1,2};
+new (static_cast(&i)) int[]{1};
+return 0;
+}
+
+consteval int array2() {
+int i[1];
+new (&i) int[2];
+//expected-note@-1 {{placement new would change type of storage from 
'int[1]' to 'int[2]'}}
+return 0;
+}
+
+struct S{
+int* i;
+constexpr S() : i(new int(42)) {} // expected-note {{allocation performed 
here was not deallocated}}
+constexpr ~S() {delete i;}
+};
+
+consteval void alloc() {
+S* s = new S();
+s->~S();
+new (s) S();
+delete s;
+}
+
+
+consteval void alloc_err() {
+S* s = new S();
+new (s) S();
+delete s;
+}
+
+
+
+int a = ok();
+int b = conversion(); // expected-error {{call to consteval function 
'conversion' is not a constant expression}} \
+ // expected-note {{in call to 'conversion()'}}
+int c = indeterminate(); // expected-error {{call to consteval function 
'indeterminate' is not a constant expression}} \
+ // expected-note {{in call to 'indeterminate()'}}
+int d = array1();
+int e = array2(); // expected-error {{call to consteval function 'array2' is 
not a constant expression}} \
+  // expected-note {{in call to 'array2()'}}
+int alloc1 = (alloc(), 0);
+int alloc2 = (alloc_err(), 0); // expected-error {{call to consteval function 
'alloc_err' is not a constant expression}}
+
+constexpr int *intptr() {
+  return new int;
+}
+
+constexpr bool yay() {
+  int *ptr = new (intptr()) int(42);
+  bool ret = *ptr == 42;
+  delete ptr;
+  return ret;
+}
+static_assert(yay());
+
+constexpr bool blah() {
+  int *ptr = new (intptr()) int[3]{ 1, 2, 3 }; // expected-note {{placement 
new would change type of storage from 'int' to 'int[3]'}}

AaronBallman wrote:

hmm, I can't think of a better way to phrase the diagnostic to make that more 
clear, so LG

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


[clang] [llvm] [NFC] Use const members of `StringToOffsetTable` (PR #105824)

2024-08-23 Thread Rahul Joshi via cfe-commits

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


[clang] [llvm] [NFC] Use const members of `StringToOffsetTable` (PR #105824)

2024-08-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Rahul Joshi (jurahul)


Changes

- After the table is populated and emitted as a string, we do not expect any 
modifications to the table. So use const reference and const members to access 
the table from that point on.

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


2 Files Affected:

- (modified) clang/utils/TableGen/ClangDiagnosticsEmitter.cpp (+5-4) 
- (modified) llvm/utils/TableGen/AsmMatcherEmitter.cpp (+5-5) 


``diff
diff --git a/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp 
b/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
index b290530444d2ab..6ca24a8c74b2ff 100644
--- a/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
+++ b/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
@@ -1634,7 +1634,7 @@ static void emitDiagArrays(std::map &DiagsInGroup,
 /// \000\020#pragma-messages\t#warnings\020CFString-literal"
 ///   };
 /// \endcode
-static void emitDiagGroupNames(StringToOffsetTable &GroupNames,
+static void emitDiagGroupNames(const StringToOffsetTable &GroupNames,
raw_ostream &OS) {
   OS << "static const char DiagGroupNames[] = {\n";
   GroupNames.EmitString(OS);
@@ -1656,7 +1656,7 @@ static void emitDiagGroupNames(StringToOffsetTable 
&GroupNames,
 static void emitAllDiagArrays(std::map &DiagsInGroup,
   RecordVec &DiagsInPedantic,
   RecordVec &GroupsInPedantic,
-  StringToOffsetTable &GroupNames,
+  const StringToOffsetTable &GroupNames,
   raw_ostream &OS) {
   OS << "\n#ifdef GET_DIAG_ARRAYS\n";
   emitDiagArrays(DiagsInGroup, DiagsInPedantic, OS);
@@ -1683,7 +1683,8 @@ static void emitAllDiagArrays(std::map &DiagsInGroup,
 static void emitDiagTable(std::map &DiagsInGroup,
   RecordVec &DiagsInPedantic,
   RecordVec &GroupsInPedantic,
-  StringToOffsetTable &GroupNames, raw_ostream &OS) {
+  const StringToOffsetTable &GroupNames,
+  raw_ostream &OS) {
   unsigned MaxLen = 0;
 
   for (auto const &I: DiagsInGroup)
@@ -1705,7 +1706,7 @@ static void emitDiagTable(std::map &DiagsInGroup,
 OS << I.first << " */, ";
 // Store a pascal-style length byte at the beginning of the string.
 std::string Name = char(I.first.size()) + I.first;
-OS << GroupNames.GetOrAddStringOffset(Name, false) << ", ";
+OS << *GroupNames.GetStringOffset(Name) << ", ";
 
 // Special handling for 'pedantic'.
 const bool IsPedantic = I.first == "pedantic";
diff --git a/llvm/utils/TableGen/AsmMatcherEmitter.cpp 
b/llvm/utils/TableGen/AsmMatcherEmitter.cpp
index 5035ef52707f4e..98d0231d3055c2 100644
--- a/llvm/utils/TableGen/AsmMatcherEmitter.cpp
+++ b/llvm/utils/TableGen/AsmMatcherEmitter.cpp
@@ -2871,7 +2871,7 @@ static bool emitMnemonicAliases(raw_ostream &OS, const 
AsmMatcherInfo &Info,
 static void
 emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
  const AsmMatcherInfo &Info, StringRef ClassName,
- StringToOffsetTable &StringTable,
+ const StringToOffsetTable &StringTable,
  unsigned MaxMnemonicIndex, unsigned MaxFeaturesIndex,
  bool HasMnemonicFirst, const Record &AsmParser) {
   unsigned MaxMask = 0;
@@ -2924,8 +2924,8 @@ emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget 
&Target,
 
 // Store a pascal-style length byte in the mnemonic.
 std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.lower();
-OS << StringTable.GetOrAddStringOffset(LenMnemonic, false) << " /* "
-   << II.Mnemonic << " */, ";
+OS << *StringTable.GetStringOffset(LenMnemonic) << " /* " << II.Mnemonic
+   << " */, ";
 
 OS << OMI.OperandMask;
 OS << " /* ";
@@ -3554,8 +3554,8 @@ void AsmMatcherEmitter::run(raw_ostream &OS) {
   // Store a pascal-style length byte in the mnemonic.
   std::string LenMnemonic =
   char(MI->Mnemonic.size()) + MI->Mnemonic.lower();
-  OS << "  { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
- << " /* " << MI->Mnemonic << " */, " << Target.getInstNamespace()
+  OS << "  { " << *StringTable.GetStringOffset(LenMnemonic) << " /* "
+ << MI->Mnemonic << " */, " << Target.getInstNamespace()
  << "::" << MI->getResultInst()->TheDef->getName() << ", "
  << MI->ConversionFnKind << ", ";
 

``




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


[clang] 2617023 - [clang][AArch64] Add SME2.1 feature macros (#105657)

2024-08-23 Thread via cfe-commits

Author: SpencerAbson
Date: 2024-08-23T14:27:49+01:00
New Revision: 2617023923175b0fd2a8cb94ad677c061c01627f

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

LOG: [clang][AArch64] Add SME2.1 feature macros (#105657)

Added: 


Modified: 
clang/lib/Basic/Targets/AArch64.cpp
clang/lib/Basic/Targets/AArch64.h
clang/test/Preprocessor/aarch64-target-features.c

Removed: 




diff  --git a/clang/lib/Basic/Targets/AArch64.cpp 
b/clang/lib/Basic/Targets/AArch64.cpp
index 6ba31cc05a0d75..63fc15f916c558 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -471,23 +471,25 @@ void AArch64TargetInfo::getTargetDefines(const 
LangOptions &Opts,
   if (HasSVE2 && HasSVE2SM4)
 Builder.defineMacro("__ARM_FEATURE_SVE2_SM4", "1");
 
+  if (HasSVEB16B16)
+Builder.defineMacro("__ARM_FEATURE_SVE_B16B16", "1");
+
   if (HasSME) {
 Builder.defineMacro("__ARM_FEATURE_SME");
 Builder.defineMacro("__ARM_FEATURE_LOCALLY_STREAMING", "1");
   }
 
-  if (HasSME2) {
-Builder.defineMacro("__ARM_FEATURE_SME", "1");
+  if (HasSME2)
 Builder.defineMacro("__ARM_FEATURE_SME2", "1");
-Builder.defineMacro("__ARM_FEATURE_LOCALLY_STREAMING", "1");
-  }
 
-  if (HasSME2p1) {
-Builder.defineMacro("__ARM_FEATURE_SME", "1");
-Builder.defineMacro("__ARM_FEATURE_SME2", "1");
+  if (HasSME2p1)
 Builder.defineMacro("__ARM_FEATURE_SME2p1", "1");
-Builder.defineMacro("__ARM_FEATURE_LOCALLY_STREAMING", "1");
-  }
+
+  if (HasSMEF16F16)
+Builder.defineMacro("__ARM_FEATURE_SME_F16F16", "1");
+
+  if (HasSMEB16B16)
+Builder.defineMacro("__ARM_FEATURE_SME_B16B16", "1");
 
   if (HasCRC)
 Builder.defineMacro("__ARM_FEATURE_CRC32", "1");
@@ -749,6 +751,7 @@ bool AArch64TargetInfo::hasFeature(StringRef Feature) const 
{
   .Case("sve", FPU & SveMode)
   .Case("sve-bf16", FPU & SveMode && HasBFloat16)
   .Case("sve-i8mm", FPU & SveMode && HasMatMul)
+  .Case("sve-b16b16", HasSVEB16B16)
   .Case("f32mm", FPU & SveMode && HasMatmulFP32)
   .Case("f64mm", FPU & SveMode && HasMatmulFP64)
   .Case("sve2", FPU & SveMode && HasSVE2)
@@ -763,6 +766,8 @@ bool AArch64TargetInfo::hasFeature(StringRef Feature) const 
{
   .Case("sme-f64f64", HasSMEF64F64)
   .Case("sme-i16i64", HasSMEI16I64)
   .Case("sme-fa64", HasSMEFA64)
+  .Case("sme-f16f16", HasSMEF16F16)
+  .Case("sme-b16b16", HasSMEB16B16)
   .Cases("memtag", "memtag2", HasMTE)
   .Case("sb", HasSB)
   .Case("predres", HasPredRes)
@@ -863,6 +868,8 @@ bool 
AArch64TargetInfo::handleTargetFeatures(std::vector &Features,
   HasSVE2 = true;
   HasSVE2SM4 = true;
 }
+if (Feature == "+sve-b16b16")
+  HasSVEB16B16 = true;
 if (Feature == "+sve2-bitperm") {
   FPU |= NeonMode;
   FPU |= SveMode;
@@ -919,6 +926,21 @@ bool 
AArch64TargetInfo::handleTargetFeatures(std::vector &Features,
   HasSVE2 = true;
   HasSMEFA64 = true;
 }
+if (Feature == "+sme-f16f16") {
+  HasSME = true;
+  HasSME2 = true;
+  HasBFloat16 = true;
+  HasFullFP16 = true;
+  HasSMEF16F16 = true;
+}
+if (Feature == "+sme-b16b16") {
+  HasSME = true;
+  HasSME2 = true;
+  HasBFloat16 = true;
+  HasFullFP16 = true;
+  HasSVEB16B16 = true;
+  HasSMEB16B16 = true;
+}
 if (Feature == "+sb")
   HasSB = true;
 if (Feature == "+predres")

diff  --git a/clang/lib/Basic/Targets/AArch64.h 
b/clang/lib/Basic/Targets/AArch64.h
index 7bdf5a2b4106e4..526f7f30a38618 100644
--- a/clang/lib/Basic/Targets/AArch64.h
+++ b/clang/lib/Basic/Targets/AArch64.h
@@ -53,6 +53,7 @@ class LLVM_LIBRARY_VISIBILITY AArch64TargetInfo : public 
TargetInfo {
   bool HasSVE2AES = false;
   bool HasSVE2SHA3 = false;
   bool HasSVE2SM4 = false;
+  bool HasSVEB16B16 = false;
   bool HasSVE2BitPerm = false;
   bool HasMatmulFP64 = false;
   bool HasMatmulFP32 = false;
@@ -71,6 +72,8 @@ class LLVM_LIBRARY_VISIBILITY AArch64TargetInfo : public 
TargetInfo {
   bool HasSME2 = false;
   bool HasSMEF64F64 = false;
   bool HasSMEI16I64 = false;
+  bool HasSMEF16F16 = false;
+  bool HasSMEB16B16 = false;
   bool HasSME2p1 = false;
   bool HasSB = false;
   bool HasPredRes = false;

diff  --git a/clang/test/Preprocessor/aarch64-target-features.c 
b/clang/test/Preprocessor/aarch64-target-features.c
index 87bd3e142d2c40..ae2bdda6f536c5 100644
--- a/clang/test/Preprocessor/aarch64-target-features.c
+++ b/clang/test/Preprocessor/aarch64-target-features.c
@@ -709,3 +709,19 @@
 // CHECK-SME2p1: __ARM_FEATURE_SME 1
 // CHECK-SME2p1: __ARM_FEATURE_SME2 1
 // CHECK-SME2p1: __ARM_FEATURE_SME2p1 1
+
+// RUN: %clang --target=aarch64 -march=armv9-a+sve-b16b16 -x c -E -dM %s -o - 
| FileCheck --check-prefix=CHECK-SVEB16

[clang] [clang][AArch64] Add SME2.1 feature macros (PR #105657)

2024-08-23 Thread via cfe-commits

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


[clang] [clang-format] Treat new expressions as simple functions (PR #105168)

2024-08-23 Thread kadir çetinkaya via cfe-commits

https://github.com/kadircet updated 
https://github.com/llvm/llvm-project/pull/105168

From 089699a673d29e244e750bf1c978292594362cdc Mon Sep 17 00:00:00 2001
From: Kadir Cetinkaya 
Date: Tue, 20 Aug 2024 19:40:42 +0200
Subject: [PATCH] [clang-format] Treat new expressions as simple functions

ccae7b461be339e717d02f99ac857cf0bc7d17f improved handling for nested
calls, but this resulted in a lot of changes near `new` expressions.

This patch tries to restore previous behavior around new expressions, by
treating them as simple functions, which seem to align with the concept.

Fixes https://github.com/llvm/llvm-project/issues/105133.
---
 clang/lib/Format/ContinuationIndenter.cpp |  9 +
 clang/unittests/Format/FormatTest.cpp | 12 
 2 files changed, 21 insertions(+)

diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 4fcb776db45b58..2422deee3b8d89 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -830,6 +830,12 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
   const auto IsSimpleFunction = [&](const FormatToken &Tok) {
 if (!Tok.FakeLParens.empty() && Tok.FakeLParens.back() > prec::Unknown)
   return false;
+// Nested calls that involve `new` expressions also look like simple
+// function calls, eg:
+// - foo(new Bar())
+// - foo(::new Bar())
+if (Tok.is(tok::kw_new) || Tok.startsSequence(tok::coloncolon, 
tok::kw_new))
+  return true;
 const auto *Previous = Tok.Previous;
 if (!Previous || (!Previous->isOneOf(TT_FunctionDeclarationLParen,
  TT_LambdaDefinitionLParen) &&
@@ -852,6 +858,9 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
   //   cll(
   //   cll(
   //   caaall(aa, 
a;
+  //  or
+  //  cal(
+  //   new SomethingElseee());
   !IsSimpleFunction(Current)) {
 CurrentState.NoLineBreak = true;
   }
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 779109976a4f77..a383a624434b1f 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -9383,6 +9383,18 @@ TEST_F(FormatTest, AlignsAfterOpenBracket) {
   "(a, )) &&\n"
   ");",
   Style);
+  verifyFormat(
+  "fooo(new BAR(\n"
+  "XXXZ()));",
+  Style);
+  verifyFormat(
+  "fooo(::new BAR(\n"
+  "XXXZ()));",
+  Style);
+  verifyFormat(
+  "fooo(new FOO::BA(\n"
+  "XXXZ()));",
+  Style);
 
   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
   Style.BinPackArguments = false;

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


[clang] [clang] check deduction consistency when partial ordering function templates (PR #100692)

2024-08-23 Thread via cfe-commits

https://github.com/cor3ntin commented:

Sorry for the late review!
I think the change make sense but needs more tests. Thanks!

After we land that, could you spend some time trying to cleanup some of these 
functions?

- maybe pass an enum instead of a myriad of bool parameters
- maybe return a struct with the output parameters instead of just 
TemplateDeductionResult ?

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


[clang] [clang] check deduction consistency when partial ordering function templates (PR #100692)

2024-08-23 Thread via cfe-commits


@@ -5395,11 +5520,100 @@ static QualType 
GetImplicitObjectParameterType(ASTContext &Context,
   return Context.getLValueReferenceType(RawType);
 }
 
+static TemplateDeductionResult CheckDeductionConsistency(
+Sema &S, FunctionTemplateDecl *FTD, int ArgIdx, QualType P, QualType A,
+ArrayRef DeducedArgs, bool CheckConsistency) {
+  MultiLevelTemplateArgumentList MLTAL(FTD, DeducedArgs,
+   /*Final=*/true);
+  if (ArgIdx != -1)
+if (auto *MD = dyn_cast(FTD->getTemplatedDecl());
+MD && MD->isImplicitObjectMemberFunction())
+  ArgIdx -= 1;
+  Sema::ArgumentPackSubstitutionIndexRAII PackIndex(
+  S, ArgIdx != -1 ? ::getPackIndexForParam(S, FTD, MLTAL, ArgIdx) : -1);
+  bool IsIncompleteSubstitution = false;
+  QualType InstP = S.SubstType(P, MLTAL, FTD->getLocation(), 
FTD->getDeclName(),
+   &IsIncompleteSubstitution);
+  if (InstP.isNull())
+return TemplateDeductionResult::SubstitutionFailure;
+  if (!CheckConsistency)
+return TemplateDeductionResult::Success;
+  if (IsIncompleteSubstitution)
+return TemplateDeductionResult::Incomplete;
+
+  // [temp.deduct.call]/4 - Check we produced a consistent deduction.
+  // This handles just the cases that can appear when partial ordering.
+  if (auto *PA = dyn_cast(A);
+  PA && !isa(InstP))
+A = PA->getPattern();
+  if (!S.Context.hasSameType(
+  S.Context.getUnqualifiedArrayType(InstP.getNonReferenceType()),
+  S.Context.getUnqualifiedArrayType(A.getNonReferenceType(
+return TemplateDeductionResult::NonDeducedMismatch;
+  return TemplateDeductionResult::Success;
+}
+
+template 
+static TemplateDeductionResult FinishTemplateArgumentDeduction(
+Sema &S, FunctionTemplateDecl *FTD,
+SmallVectorImpl &Deduced,
+TemplateDeductionInfo &Info, T &&CheckDeductionConsistency) {
+  // Unevaluated SFINAE context.

cor3ntin wrote:

As is the comment adds nothing

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


[clang] [clang] check deduction consistency when partial ordering function templates (PR #100692)

2024-08-23 Thread via cfe-commits


@@ -5395,11 +5520,100 @@ static QualType 
GetImplicitObjectParameterType(ASTContext &Context,
   return Context.getLValueReferenceType(RawType);
 }
 
+static TemplateDeductionResult CheckDeductionConsistency(
+Sema &S, FunctionTemplateDecl *FTD, int ArgIdx, QualType P, QualType A,
+ArrayRef DeducedArgs, bool CheckConsistency) {
+  MultiLevelTemplateArgumentList MLTAL(FTD, DeducedArgs,
+   /*Final=*/true);
+  if (ArgIdx != -1)
+if (auto *MD = dyn_cast(FTD->getTemplatedDecl());
+MD && MD->isImplicitObjectMemberFunction())
+  ArgIdx -= 1;
+  Sema::ArgumentPackSubstitutionIndexRAII PackIndex(
+  S, ArgIdx != -1 ? ::getPackIndexForParam(S, FTD, MLTAL, ArgIdx) : -1);
+  bool IsIncompleteSubstitution = false;
+  QualType InstP = S.SubstType(P, MLTAL, FTD->getLocation(), 
FTD->getDeclName(),
+   &IsIncompleteSubstitution);
+  if (InstP.isNull())
+return TemplateDeductionResult::SubstitutionFailure;
+  if (!CheckConsistency)
+return TemplateDeductionResult::Success;
+  if (IsIncompleteSubstitution)
+return TemplateDeductionResult::Incomplete;
+
+  // [temp.deduct.call]/4 - Check we produced a consistent deduction.
+  // This handles just the cases that can appear when partial ordering.
+  if (auto *PA = dyn_cast(A);
+  PA && !isa(InstP))
+A = PA->getPattern();
+  if (!S.Context.hasSameType(
+  S.Context.getUnqualifiedArrayType(InstP.getNonReferenceType()),
+  S.Context.getUnqualifiedArrayType(A.getNonReferenceType(
+return TemplateDeductionResult::NonDeducedMismatch;
+  return TemplateDeductionResult::Success;
+}
+
+template 
+static TemplateDeductionResult FinishTemplateArgumentDeduction(
+Sema &S, FunctionTemplateDecl *FTD,
+SmallVectorImpl &Deduced,
+TemplateDeductionInfo &Info, T &&CheckDeductionConsistency) {
+  // Unevaluated SFINAE context.
+  EnterExpressionEvaluationContext Unevaluated(
+  S, Sema::ExpressionEvaluationContext::Unevaluated);
+  Sema::SFINAETrap Trap(S);
+
+  Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(FTD));
+
+  // C++ [temp.deduct.type]p2:

cor3ntin wrote:

```suggestion
  // C++26 [temp.deduct.type]p2:
```

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


[clang] [clang] check deduction consistency when partial ordering function templates (PR #100692)

2024-08-23 Thread via cfe-commits


@@ -1343,6 +1343,9 @@ namespace {
 DeclarationName Entity;
 // Whether to evaluate the C++20 constraints or simply substitute into 
them.
 bool EvaluateConstraints = true;
+// Whether Substitution was Incomplete, that is, we tried to substitute in
+// any template arguments which were null.

cor3ntin wrote:

Beecause they were not yet provided, presumably?

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


[clang] [clang] check deduction consistency when partial ordering function templates (PR #100692)

2024-08-23 Thread via cfe-commits


@@ -0,0 +1,32 @@
+// RUN: %clang_cc1 -std=c++23 -verify %s
+
+namespace t1 {
+template struct enable_if { typedef void type; };
+template  class Foo {};
+template  constexpr bool check() { return true; }
+template  struct Bar {};
+
+template void func(Bar()>::type>) {}
+// expected-note@-1 {{candidate function}}
+
+template void func(Bar>) {}
+// expected-note@-1 {{candidate function}}
+
+void g() {
+  func(Bar>()); // expected-error {{call to 'func' is ambiguous}}

cor3ntin wrote:

Interestingly everyone accepts that https://godbolt.org/z/KG9cx4c6f
I think that this is the expected behavior as I am not aware of a 
disambiguation rule but it's worth double checking @AaronBallman @zygoloid 

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


[clang] [clang] check deduction consistency when partial ordering function templates (PR #100692)

2024-08-23 Thread via cfe-commits


@@ -5421,34 +5635,139 @@ static bool isAtLeastAsSpecializedAs(Sema &S, 
SourceLocation Loc,
   //   the partial ordering is done:
   TemplateDeductionInfo Info(Loc);
   switch (TPOC) {
-  case TPOC_Call:
-if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
-Args1.data(), Args1.size(), Info, Deduced,
-TDF_None, /*PartialOrdering=*/true) !=
-TemplateDeductionResult::Success)
+  case TPOC_Call: {
+llvm::SmallBitVector HasDeducedParam(Args2.size());
+if (DeduceTemplateArguments(
+S, TemplateParams, Args2.data(), Args2.size(), Args1.data(),
+Args1.size(), Info, Deduced, TDF_None, /*PartialOrdering=*/true,
+/*HasDeducedAnyParam=*/nullptr,
+&HasDeducedParam) != TemplateDeductionResult::Success)
   return false;
 
-break;
+SmallVector DeducedArgs(Deduced.begin(),
+ Deduced.end());
+Sema::InstantiatingTemplate Inst(
+S, Info.getLocation(), FT2, DeducedArgs,
+Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
+if (Inst.isInvalid())
+  return false;
 
-  case TPOC_Conversion:
+bool AtLeastAsSpecialized = true;
+S.runWithSufficientStackSpace(Info.getLocation(), [&] {
+  AtLeastAsSpecialized =
+  ::FinishTemplateArgumentDeduction(
+  S, FT2, Deduced, Info,
+  [&](Sema &S, FunctionTemplateDecl *FTD,
+  ArrayRef DeducedArgs) {
+return ::DeduceForEachType(
+S, TemplateParams, Args2.data(), Args2.size(), 
Args1.data(),
+Args1.size(), Info, Deduced,
+/*PartialOrdering=*/true, /*FinishingDeduction=*/true,
+[&](Sema &S, TemplateParameterList *, int ParamIdx,
+int ArgIdx, QualType P, QualType A,
+TemplateDeductionInfo &Info,
+SmallVectorImpl &Deduced,
+bool) {
+  // As a provisional fix for a core issue that does not
+  // exist yet, only check the consistency of parameters
+  // which participated in deduction. We still try to
+  // substitute them though.
+  return ::CheckDeductionConsistency(
+  S, FTD, ArgIdx, P, A, DeducedArgs,
+  HasDeducedParam[ParamIdx]);
+});
+  }) == TemplateDeductionResult::Success;
+});
+if (!AtLeastAsSpecialized)
+  return false;
+  } break;
+
+  case TPOC_Conversion: {
 //   - In the context of a call to a conversion operator, the return types
 // of the conversion function templates are used.
 if (DeduceTemplateArgumentsByTypeMatch(
 S, TemplateParams, Proto2->getReturnType(), 
Proto1->getReturnType(),
 Info, Deduced, TDF_None,
-/*PartialOrdering=*/true) != TemplateDeductionResult::Success)
+/*PartialOrdering=*/true, /*DeducedFromArrayBound=*/false,
+/*HasDeducedAnyParam=*/nullptr) != 
TemplateDeductionResult::Success)
   return false;
-break;
 
-  case TPOC_Other:
+SmallVector DeducedArgs(Deduced.begin(),
+ Deduced.end());
+Sema::InstantiatingTemplate Inst(
+S, Info.getLocation(), FT2, DeducedArgs,
+Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
+if (Inst.isInvalid())
+  return false;
+
+bool AtLeastAsSpecialized;
+S.runWithSufficientStackSpace(Info.getLocation(), [&] {
+  AtLeastAsSpecialized =
+  ::FinishTemplateArgumentDeduction(
+  S, FT2, Deduced, Info,
+  [&](Sema &S, FunctionTemplateDecl *FTD,
+  ArrayRef DeducedArgs) {
+return ::CheckDeductionConsistency(
+S, FTD, /*ArgIdx=*/-1, Proto2->getReturnType(),
+Proto1->getReturnType(), DeducedArgs,
+/*CheckConsistency=*/true);
+  }) == TemplateDeductionResult::Success;
+});
+if (!AtLeastAsSpecialized)
+  return false;
+  } break;
+
+  case TPOC_Other: {
 //   - In other contexts (14.6.6.2) the function template's function type
 // is used.
 if (DeduceTemplateArgumentsByTypeMatch(
 S, TemplateParams, FD2->getType(), FD1->getType(), Info, Deduced,
 TDF_AllowCompatibleFunctionType,
-/*PartialOrdering=*/true) != TemplateDeductionResult::Success)
+/*PartialOrdering=*/true, /*DeducedFromArrayBound=*/false,
+/*HasDeducedAnyParam=*/nullptr) != 
TemplateDeductionResult::Success)
   return false;
-break;
+
+SmallVector DeducedArgs(Deduced.begin(),
+ Deduced.end());

[clang] [clang] check deduction consistency when partial ordering function templates (PR #100692)

2024-08-23 Thread via cfe-commits


@@ -5554,38 +5869,50 @@ FunctionTemplateDecl *Sema::getMoreSpecializedTemplate(
 // "that is a member function with no expicit object argument".
 // Otherwise the ordering rules for methods with expicit objet arguments
 // against anything else make no sense.
-ShouldConvert1 = Method1 && !Method1->isExplicitObjectMemberFunction();
-ShouldConvert2 = Method2 && !Method2->isExplicitObjectMemberFunction();
-if (ShouldConvert1) {
-  bool IsRValRef2 =
-  ShouldConvert2
-  ? Method2->getRefQualifier() == RQ_RValue
-  : Proto2->param_type_begin()[0]->isRValueReferenceType();
-  // Compare 'this' from Method1 against first parameter from Method2.
-  Obj1Ty = GetImplicitObjectParameterType(this->Context, Method1, 
RawObj1Ty,
-  IsRValRef2);
-  Args1.push_back(Obj1Ty);
-}
-if (ShouldConvert2) {
-  bool IsRValRef1 =
-  ShouldConvert1
-  ? Method1->getRefQualifier() == RQ_RValue
-  : Proto1->param_type_begin()[0]->isRValueReferenceType();
-  // Compare 'this' from Method2 against first parameter from Method1.
-  Obj2Ty = GetImplicitObjectParameterType(this->Context, Method2, 
RawObj2Ty,
-  IsRValRef1);
-  Args2.push_back(Obj2Ty);
-}
+
+bool NonStaticMethod1 = Method1 && !Method1->isStatic(),
+ NonStaticMethod2 = Method2 && !Method2->isStatic();
+
+auto Params1Begin = Proto1->param_type_begin(),
+ Params2Begin = Proto2->param_type_begin();
+
 size_t NumComparedArguments = NumCallArguments1;
-// Either added an argument above or the prototype includes an explicit
-// object argument we need to count
-if (Method1)
-  ++NumComparedArguments;
 
-Args1.insert(Args1.end(), Proto1->param_type_begin(),
- Proto1->param_type_end());
-Args2.insert(Args2.end(), Proto2->param_type_begin(),
- Proto2->param_type_end());
+if ((NonStaticMethod1 && NonStaticMethod2) || FD1->isOverloadedOperator()) 
{
+  ShouldConvert1 =
+  NonStaticMethod1 && 
!Method1->hasCXXExplicitFunctionObjectParameter();
+  ShouldConvert2 =
+  NonStaticMethod2 && 
!Method2->hasCXXExplicitFunctionObjectParameter();
+  NumComparedArguments += 1;
+
+  if (ShouldConvert1) {
+bool IsRValRef2 =
+ShouldConvert2
+? Method2->getRefQualifier() == RQ_RValue
+: Proto2->param_type_begin()[0]->isRValueReferenceType();
+// Compare 'this' from Method1 against first parameter from Method2.
+Obj1Ty = GetImplicitObjectParameterType(this->Context, Method1,
+RawObj1Ty, IsRValRef2);
+Args1.push_back(Obj1Ty);
+  }
+  if (ShouldConvert2) {
+bool IsRValRef1 =
+ShouldConvert1
+? Method1->getRefQualifier() == RQ_RValue
+: Proto1->param_type_begin()[0]->isRValueReferenceType();
+// Compare 'this' from Method2 against first parameter from Method1.
+Obj2Ty = GetImplicitObjectParameterType(this->Context, Method2,
+RawObj2Ty, IsRValRef1);
+Args2.push_back(Obj2Ty);
+  }
+} else {
+  if (NonStaticMethod1 && Method1->hasCXXExplicitFunctionObjectParameter())
+Params1Begin += 1;
+  if (NonStaticMethod2 && Method2->hasCXXExplicitFunctionObjectParameter())
+Params2Begin += 1;
+}
+Args1.insert(Args1.end(), Params1Begin, Proto1->param_type_end());
+Args2.insert(Args2.end(), Params2Begin, Proto2->param_type_end());

cor3ntin wrote:

We probably need some tests for explicit object member functions

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


[clang] [clang] check deduction consistency when partial ordering function templates (PR #100692)

2024-08-23 Thread via cfe-commits


@@ -5421,34 +5635,139 @@ static bool isAtLeastAsSpecializedAs(Sema &S, 
SourceLocation Loc,
   //   the partial ordering is done:
   TemplateDeductionInfo Info(Loc);
   switch (TPOC) {
-  case TPOC_Call:
-if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
-Args1.data(), Args1.size(), Info, Deduced,
-TDF_None, /*PartialOrdering=*/true) !=
-TemplateDeductionResult::Success)
+  case TPOC_Call: {
+llvm::SmallBitVector HasDeducedParam(Args2.size());
+if (DeduceTemplateArguments(
+S, TemplateParams, Args2.data(), Args2.size(), Args1.data(),
+Args1.size(), Info, Deduced, TDF_None, /*PartialOrdering=*/true,
+/*HasDeducedAnyParam=*/nullptr,
+&HasDeducedParam) != TemplateDeductionResult::Success)
   return false;
 
-break;
+SmallVector DeducedArgs(Deduced.begin(),
+ Deduced.end());
+Sema::InstantiatingTemplate Inst(
+S, Info.getLocation(), FT2, DeducedArgs,
+Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
+if (Inst.isInvalid())
+  return false;
 
-  case TPOC_Conversion:
+bool AtLeastAsSpecialized = true;
+S.runWithSufficientStackSpace(Info.getLocation(), [&] {
+  AtLeastAsSpecialized =
+  ::FinishTemplateArgumentDeduction(
+  S, FT2, Deduced, Info,
+  [&](Sema &S, FunctionTemplateDecl *FTD,
+  ArrayRef DeducedArgs) {
+return ::DeduceForEachType(
+S, TemplateParams, Args2.data(), Args2.size(), 
Args1.data(),
+Args1.size(), Info, Deduced,
+/*PartialOrdering=*/true, /*FinishingDeduction=*/true,
+[&](Sema &S, TemplateParameterList *, int ParamIdx,
+int ArgIdx, QualType P, QualType A,
+TemplateDeductionInfo &Info,
+SmallVectorImpl &Deduced,
+bool) {
+  // As a provisional fix for a core issue that does not
+  // exist yet, only check the consistency of parameters
+  // which participated in deduction. We still try to
+  // substitute them though.

cor3ntin wrote:

Did you submit it?

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


[clang] [clang] check deduction consistency when partial ordering function templates (PR #100692)

2024-08-23 Thread via cfe-commits


@@ -5395,11 +5520,100 @@ static QualType 
GetImplicitObjectParameterType(ASTContext &Context,
   return Context.getLValueReferenceType(RawType);
 }
 
+static TemplateDeductionResult CheckDeductionConsistency(
+Sema &S, FunctionTemplateDecl *FTD, int ArgIdx, QualType P, QualType A,
+ArrayRef DeducedArgs, bool CheckConsistency) {
+  MultiLevelTemplateArgumentList MLTAL(FTD, DeducedArgs,
+   /*Final=*/true);
+  if (ArgIdx != -1)
+if (auto *MD = dyn_cast(FTD->getTemplatedDecl());
+MD && MD->isImplicitObjectMemberFunction())
+  ArgIdx -= 1;
+  Sema::ArgumentPackSubstitutionIndexRAII PackIndex(
+  S, ArgIdx != -1 ? ::getPackIndexForParam(S, FTD, MLTAL, ArgIdx) : -1);
+  bool IsIncompleteSubstitution = false;
+  QualType InstP = S.SubstType(P, MLTAL, FTD->getLocation(), 
FTD->getDeclName(),
+   &IsIncompleteSubstitution);
+  if (InstP.isNull())
+return TemplateDeductionResult::SubstitutionFailure;
+  if (!CheckConsistency)
+return TemplateDeductionResult::Success;
+  if (IsIncompleteSubstitution)
+return TemplateDeductionResult::Incomplete;
+
+  // [temp.deduct.call]/4 - Check we produced a consistent deduction.
+  // This handles just the cases that can appear when partial ordering.
+  if (auto *PA = dyn_cast(A);
+  PA && !isa(InstP))
+A = PA->getPattern();
+  if (!S.Context.hasSameType(
+  S.Context.getUnqualifiedArrayType(InstP.getNonReferenceType()),
+  S.Context.getUnqualifiedArrayType(A.getNonReferenceType(
+return TemplateDeductionResult::NonDeducedMismatch;
+  return TemplateDeductionResult::Success;
+}
+
+template 
+static TemplateDeductionResult FinishTemplateArgumentDeduction(
+Sema &S, FunctionTemplateDecl *FTD,
+SmallVectorImpl &Deduced,
+TemplateDeductionInfo &Info, T &&CheckDeductionConsistency) {
+  // Unevaluated SFINAE context.
+  EnterExpressionEvaluationContext Unevaluated(
+  S, Sema::ExpressionEvaluationContext::Unevaluated);
+  Sema::SFINAETrap Trap(S);
+
+  Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(FTD));
+
+  // C++ [temp.deduct.type]p2:
+  //   [...] or if any template argument remains neither deduced nor
+  //   explicitly specified, template argument deduction fails.
+  bool IsIncomplete = false;
+  SmallVector SugaredBuilder, CanonicalBuilder;
+  if (auto Result = ConvertDeducedTemplateArguments(
+  S, FTD, /*IsDeduced=*/true, Deduced, Info, SugaredBuilder,
+  CanonicalBuilder, /*CurrentInstantiationScope=*/nullptr,
+  /*NumAlreadyConverted=*/0, &IsIncomplete);
+  Result != TemplateDeductionResult::Success)
+return Result;
+
+  // Form the template argument list from the deduced template arguments.
+  TemplateArgumentList *SugaredDeducedArgumentList =
+  TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
+  TemplateArgumentList *CanonicalDeducedArgumentList =
+  TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
+
+  Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
+
+  // Substitute the deduced template arguments into the argument
+  // and verify that the instantiated argument is both valid
+  // and equivalent to the parameter.
+  LocalInstantiationScope InstScope(S);
+
+  if (auto TDR = CheckDeductionConsistency(S, FTD, SugaredBuilder);
+  TDR != TemplateDeductionResult::Success)
+return TDR;
+
+  // C++20 [temp.deduct]p5 - Only check constraints when all parameters have
+  // been deduced.
+  if (!IsIncomplete) {

cor3ntin wrote:

```
if (IsIncomplete)
  return TemplateDeductionResult::Success;
```

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


[clang] [clang] check deduction consistency when partial ordering function templates (PR #100692)

2024-08-23 Thread via cfe-commits


@@ -1307,6 +1304,62 @@ DeduceTemplateArguments(Sema &S, TemplateParameterList 
*TemplateParams,
   return TemplateDeductionResult::Success;
 }
 
+/// Deduce the template arguments by comparing the list of parameter
+/// types to the list of argument types, as in the parameter-type-lists of
+/// function types (C++ [temp.deduct.type]p10).
+///
+/// \param S The semantic analysis object within which we are deducing
+///
+/// \param TemplateParams The template parameters that we are deducing
+///
+/// \param Params The list of parameter types
+///
+/// \param NumParams The number of types in \c Params
+///
+/// \param Args The list of argument types
+///
+/// \param NumArgs The number of types in \c Args
+///
+/// \param Info information about the template argument deduction itself
+///
+/// \param Deduced the deduced template arguments
+///
+/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
+/// how template argument deduction is performed.
+///
+/// \param PartialOrdering If true, we are performing template argument
+/// deduction for during partial ordering for a call
+/// (C++0x [temp.deduct.partial]).
+///
+/// \returns the result of template argument deduction so far. Note that a
+/// "success" result means that template argument deduction has not yet failed,
+/// but it may still fail, later, for other reasons.
+static TemplateDeductionResult DeduceTemplateArguments(
+Sema &S, TemplateParameterList *TemplateParams, const QualType *Params,
+unsigned NumParams, const QualType *Args, unsigned NumArgs,
+TemplateDeductionInfo &Info,
+SmallVectorImpl &Deduced, unsigned TDF,
+bool PartialOrdering, bool *HasDeducedAnyParam,
+llvm::SmallBitVector *HasDeducedParam) {

cor3ntin wrote:

The new params are not documented. Can we avoid having 2 parameters for what 
look like the same thing?

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


[clang] [clang] check deduction consistency when partial ordering function templates (PR #100692)

2024-08-23 Thread via cfe-commits

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


[clang] [clang] check deduction consistency when partial ordering function templates (PR #100692)

2024-08-23 Thread via cfe-commits


@@ -5399,11 +5434,85 @@ static QualType 
GetImplicitObjectParameterType(ASTContext &Context,
   return Context.getLValueReferenceType(RawType);
 }
 
+static TemplateDeductionResult FinishTemplateArgumentDeduction(
+Sema &S, FunctionTemplateDecl *FTD, int ArgIdx, QualType P, QualType A,
+SmallVectorImpl &Deduced,
+TemplateDeductionInfo &Info) {
+  // Unevaluated SFINAE context.
+  EnterExpressionEvaluationContext Unevaluated(
+  S, Sema::ExpressionEvaluationContext::Unevaluated);
+  Sema::SFINAETrap Trap(S);
+
+  Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(FTD));
+
+  // C++ [temp.deduct.type]p2:
+  //   [...] or if any template argument remains neither deduced nor
+  //   explicitly specified, template argument deduction fails.
+  bool IsIncomplete = false;
+  SmallVector SugaredBuilder, CanonicalBuilder;
+  if (auto Result = ConvertDeducedTemplateArguments(
+  S, FTD, /*IsDeduced=*/true, Deduced, Info, SugaredBuilder,
+  CanonicalBuilder, /*CurrentInstantiationScope=*/nullptr,
+  /*NumAlreadyConverted=*/0, &IsIncomplete);
+  Result != TemplateDeductionResult::Success)
+return Result;
+
+  // Form the template argument list from the deduced template arguments.
+  TemplateArgumentList *SugaredDeducedArgumentList =
+  TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
+  TemplateArgumentList *CanonicalDeducedArgumentList =
+  TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
+
+  Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
+
+  // Substitute the deduced template arguments into the argument
+  // and verify that the instantiated argument is both valid
+  // and equivalent to the parameter.
+  LocalInstantiationScope InstScope(S);
+
+  QualType InstP;
+  {
+MultiLevelTemplateArgumentList MLTAL(FTD, SugaredBuilder,
+ /*Final=*/true);
+if (ArgIdx != -1)
+  if (auto *MD = dyn_cast(FTD->getTemplatedDecl());
+  MD && MD->isImplicitObjectMemberFunction())
+ArgIdx -= 1;
+Sema::ArgumentPackSubstitutionIndexRAII PackIndex(
+S, ArgIdx != -1 ? ::getPackIndexForParam(S, FTD, MLTAL, ArgIdx) : -1);
+InstP = S.SubstType(P, MLTAL, FTD->getLocation(), FTD->getDeclName());
+if (InstP.isNull())
+  return TemplateDeductionResult::SubstitutionFailure;
+  }
+
+  if (auto *PA = dyn_cast(A);
+  PA && !isa(InstP))
+A = PA->getPattern();
+  if (!S.Context.hasSameType(
+  S.Context.getUnqualifiedArrayType(InstP.getNonReferenceType()),
+  S.Context.getUnqualifiedArrayType(A.getNonReferenceType(
+return TemplateDeductionResult::NonDeducedMismatch;
+
+  // C++20 [temp.deduct]p5 - Only check constraints when all parameters have
+  // been deduced.
+  if (!IsIncomplete) {
+if (auto Result = CheckDeducedArgumentConstraints(S, FTD, SugaredBuilder,
+  CanonicalBuilder, Info);
+Result != TemplateDeductionResult::Success)
+  return Result;
+  }

cor3ntin wrote:

Yes, there are orthogonal bugs with when we check constraints, not doing that 
here is reasonable

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


[clang] [clang] check deduction consistency when partial ordering function templates (PR #100692)

2024-08-23 Thread via cfe-commits


@@ -859,8 +861,10 @@ class PackDeductionScope {
 // by this pack expansion, then clear out the deduction.
 DeducedFromEarlierParameter = !Deduced[Index].isNull();
 DeducedPack Pack(Index);
-Pack.Saved = Deduced[Index];
-Deduced[Index] = TemplateArgument();
+if (!FinishingDeduction) {
+  Pack.Saved = Deduced[Index];
+  Deduced[Index] = TemplateArgument();
+}

cor3ntin wrote:

Can we add pack-related tests?

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


[clang] [Clang] Implement P2747 constexpr placement new (PR #104586)

2024-08-23 Thread via cfe-commits

https://github.com/cor3ntin updated 
https://github.com/llvm/llvm-project/pull/104586

>From 67201d1d2e4d092cf8712b1e1b63f2eceaf8d57c Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Tue, 9 Jul 2024 08:37:18 +0200
Subject: [PATCH 1/6] [Clang] Implement P2747 constexpr placement new

In C++26 and as an extension in C++20
---
 clang/docs/LanguageExtensions.rst |  1 +
 clang/docs/ReleaseNotes.rst   |  3 +
 .../include/clang/Basic/DiagnosticASTKinds.td |  2 +-
 clang/lib/AST/ExprConstant.cpp| 55 +++--
 clang/lib/Frontend/InitPreprocessor.cpp   |  2 +-
 clang/test/AST/ByteCode/new-delete.cpp|  4 +-
 clang/test/CXX/drs/cwg29xx.cpp| 26 ++
 clang/test/Lexer/cxx-features.cpp |  2 +-
 .../SemaCXX/constant-expression-cxx2a.cpp |  2 +-
 .../test/SemaCXX/cxx2a-constexpr-dynalloc.cpp | 82 ++-
 clang/www/cxx_dr_status.html  |  2 +-
 clang/www/cxx_status.html |  2 +-
 12 files changed, 150 insertions(+), 33 deletions(-)

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 62903fc3744cad..23fe23208763b8 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -1506,6 +1506,7 @@ Attributes on Structured Bindings
__cpp_structured_bindingsC+
 Pack Indexing__cpp_pack_indexing  
C++26 C++03
 ``= delete ("should have a reason");``   __cpp_deleted_function   
C++26 C++03
 Variadic Friends __cpp_variadic_friend
C++26 C++03
+``constexpr`` placement new  __cpp_constexpr  
C++26 C++20
   
- -
 Designated initializers (N494)
C99   C89
 Array & element qualification (N2607) 
C23   C89
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8f98167dff31ef..0852ac91ba4947 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -131,6 +131,9 @@ C++2c Feature Support
 
 - Implemented `P2893R3 Variadic Friends `_
 
+- Implemented `P2747R2 constexpr placement new `_.
+
+
 Resolutions to C++ Defect Reports
 ^
 
diff --git a/clang/include/clang/Basic/DiagnosticASTKinds.td 
b/clang/include/clang/Basic/DiagnosticASTKinds.td
index f317c5ac44f32b..569d2cc20a526c 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -335,7 +335,7 @@ def note_constexpr_new_non_replaceable : Note<
 def note_constexpr_new_placement : Note<
   "this placement new expression is not yet supported in constant 
expressions">;
 def note_constexpr_placement_new_wrong_type : Note<
-  "placement new would change type of storage from %0 to %1">;
+"placement new would change type of storage from %0 to %1">;
 def note_constexpr_new_negative : Note<
   "cannot allocate array; evaluated array bound %0 is negative">;
 def note_constexpr_new_too_large : Note<
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 5540f58b526705..3df963c554a995 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -6691,7 +6691,7 @@ static bool HandleDestructionImpl(EvalInfo &Info, 
SourceRange CallRange,
 if (Size && Size > Value.getArrayInitializedElts())
   expandArray(Value, Value.getArraySize() - 1);
 
-for (; Size != 0; --Size) {
+for (Size = Value.getArraySize(); Size != 0; --Size) {
   APValue &Elem = Value.getArrayInitializedElt(Size - 1);
   if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
   !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
@@ -10003,23 +10003,14 @@ bool PointerExprEvaluator::VisitCXXNewExpr(const 
CXXNewExpr *E) {
 return false;
 
   FunctionDecl *OperatorNew = E->getOperatorNew();
+  QualType AllocType = E->getAllocatedType();
+  QualType TargetType = AllocType;
 
   bool IsNothrow = false;
   bool IsPlacement = false;
-  if (OperatorNew->isReservedGlobalPlacementOperator() &&
-  Info.CurrentCall->isStdFunction() && !E->isArray()) {
-// FIXME Support array placement new.
-assert(E->getNumPlacementArgs() == 1);
-if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
-  return false;
-if (Result.Designator.Invalid)
-  return false;
-IsPlacement = true;
-  } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
-Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
-<< isa(OperatorNew) << OperatorNew;
-return false;
-  } else if (E->getNumPlacementArgs()) {
+
+  if (E->getNumPlacementArgs() && E

[clang] [Clang] Match MSVC handling of duplicate header search paths in Microsoft compatibility modes. (PR #105738)

2024-08-23 Thread Aaron Ballman via cfe-commits

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

LGTM but please allow some time for @rnk or @MaskRay to review before landing

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


[clang] [PS5][clang][test] x86_64-scei-ps5 -> x86_64-sie-ps5 in tests (PR #105810)

2024-08-23 Thread Paul T Robinson via cfe-commits

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

I appreciate the pedantry. Internally these are equivalent, but SIE is the 
current company abbreviation so we should try to be consistent going forward. 
LGTM

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


[clang-tools-extra] [clangd] Construct SmallVector with ArrayRef (NFC) (PR #105829)

2024-08-23 Thread Kazu Hirata via cfe-commits

https://github.com/kazutakahirata created 
https://github.com/llvm/llvm-project/pull/105829

None

>From 3fbc8e818867ef7ac950a381f98ff013089d8e96 Mon Sep 17 00:00:00 2001
From: Kazu Hirata 
Date: Fri, 23 Aug 2024 06:24:44 -0700
Subject: [PATCH] [clangd] Construct SmallVector with ArrayRef (NFC)

---
 clang-tools-extra/clangd/TUScheduler.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/TUScheduler.cpp 
b/clang-tools-extra/clangd/TUScheduler.cpp
index 324ba1fc8cb895..71548b59cc3088 100644
--- a/clang-tools-extra/clangd/TUScheduler.cpp
+++ b/clang-tools-extra/clangd/TUScheduler.cpp
@@ -1838,7 +1838,7 @@ DebouncePolicy::compute(llvm::ArrayRef 
History) const {
   // Base the result on the median rebuild.
   // nth_element needs a mutable array, take the chance to bound the data size.
   History = History.take_back(15);
-  llvm::SmallVector Recent(History.begin(), 
History.end());
+  llvm::SmallVector Recent(History);
   auto *Median = Recent.begin() + Recent.size() / 2;
   std::nth_element(Recent.begin(), Median, Recent.end());
 

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


[clang-tools-extra] [clangd] Construct SmallVector with ArrayRef (NFC) (PR #105829)

2024-08-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clangd

Author: Kazu Hirata (kazutakahirata)


Changes



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


1 Files Affected:

- (modified) clang-tools-extra/clangd/TUScheduler.cpp (+1-1) 


``diff
diff --git a/clang-tools-extra/clangd/TUScheduler.cpp 
b/clang-tools-extra/clangd/TUScheduler.cpp
index 324ba1fc8cb895..71548b59cc3088 100644
--- a/clang-tools-extra/clangd/TUScheduler.cpp
+++ b/clang-tools-extra/clangd/TUScheduler.cpp
@@ -1838,7 +1838,7 @@ DebouncePolicy::compute(llvm::ArrayRef 
History) const {
   // Base the result on the median rebuild.
   // nth_element needs a mutable array, take the chance to bound the data size.
   History = History.take_back(15);
-  llvm::SmallVector Recent(History.begin(), 
History.end());
+  llvm::SmallVector Recent(History);
   auto *Median = Recent.begin() + Recent.size() / 2;
   std::nth_element(Recent.begin(), Median, Recent.end());
 

``




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


  1   2   3   4   >