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

2024-02-05 Thread Pierre van Houtryve via cfe-commits


@@ -605,12 +606,197 @@ class SIGfx12CacheControl : public SIGfx11CacheControl {
   bool IsNonTemporal) const override;
 };
 
+class SIPreciseMemorySupport {
+protected:
+  const GCNSubtarget 
+  const SIInstrInfo *TII = nullptr;
+
+  IsaVersion IV;
+
+  SIPreciseMemorySupport(const GCNSubtarget ) : ST(ST) {
+TII = ST.getInstrInfo();
+IV = getIsaVersion(ST.getCPU());
+  }
+
+public:
+  static std::unique_ptr create(const GCNSubtarget 
);
+
+  virtual bool handleNonAtomic(MachineBasicBlock::iterator ) = 0;
+  /// Handles atomic instruction \p MI with \p ret indicating whether \p MI
+  /// returns a result.
+  virtual bool handleAtomic(MachineBasicBlock::iterator , bool ret) = 0;
+};
+
+class SIGfx9PreciseMemorySupport : public SIPreciseMemorySupport {
+public:
+  SIGfx9PreciseMemorySupport(const GCNSubtarget )
+  : SIPreciseMemorySupport(ST) {}
+  bool handleNonAtomic(MachineBasicBlock::iterator ) override;
+  bool handleAtomic(MachineBasicBlock::iterator , bool ret) override;
+};
+
+class SIGfx10And11PreciseMemorySupport : public SIPreciseMemorySupport {
+public:
+  SIGfx10And11PreciseMemorySupport(const GCNSubtarget )
+  : SIPreciseMemorySupport(ST) {}
+  bool handleNonAtomic(MachineBasicBlock::iterator ) override;
+  bool handleAtomic(MachineBasicBlock::iterator , bool ret) override;
+};
+
+std::unique_ptr
+SIPreciseMemorySupport::create(const GCNSubtarget ) {
+  GCNSubtarget::Generation Generation = ST.getGeneration();
+  if (Generation < AMDGPUSubtarget::GFX10)
+return std::make_unique(ST);
+  return std::make_unique(ST);
+}
+
+bool SIGfx9PreciseMemorySupport ::handleNonAtomic(
+MachineBasicBlock::iterator ) {
+  assert(MI->mayLoadOrStore());
+
+  MachineInstr  = *MI;
+  AMDGPU::Waitcnt Wait;
+
+  if (TII->isSMRD(Inst)) { // scalar
+if (Inst.mayStore())
+  return false;
+Wait.DsCnt = 0;   // LgkmCnt
+  } else {// vector
+if (Inst.mayLoad()) { // vector load
+  if (TII->isVMEM(Inst)) {// VMEM load
+Wait.LoadCnt = 0; // VmCnt
+  } else if (TII->isFLAT(Inst)) { // Flat load
+Wait.LoadCnt = 0; // VmCnt
+Wait.DsCnt = 0;   // LgkmCnt
+  } else {// LDS load
+Wait.DsCnt = 0;   // LgkmCnt
+  }
+} else {  // vector store
+  if (TII->isVMEM(Inst)) {// VMEM store
+Wait.LoadCnt = 0; // VmCnt
+  } else if (TII->isFLAT(Inst)) { // Flat store
+Wait.LoadCnt = 0; // VmCnt
+Wait.DsCnt = 0;   // LgkmCnt
+  } else {
+Wait.DsCnt = 0; // LDS store; LgkmCnt
+  }
+}
+  }
+
+  unsigned Enc = AMDGPU::encodeWaitcnt(IV, Wait);
+  MachineBasicBlock  = *MI->getParent();
+  BuildMI(MBB, ++MI, DebugLoc(), TII->get(AMDGPU::S_WAITCNT)).addImm(Enc);
+  --MI;
+  return true;
+}
+
+bool SIGfx9PreciseMemorySupport ::handleAtomic(MachineBasicBlock::iterator ,
+   bool ret) {
+  assert(MI->mayLoadOrStore());
+
+  AMDGPU::Waitcnt Wait;
+
+  Wait.LoadCnt = 0; // VmCnt
+  Wait.DsCnt = 0;   // LgkmCnt
+
+  unsigned Enc = AMDGPU::encodeWaitcnt(IV, Wait);
+  MachineBasicBlock  = *MI->getParent();
+  BuildMI(MBB, ++MI, DebugLoc(), TII->get(AMDGPU::S_WAITCNT)).addImm(Enc);
+  --MI;
+  return true;
+}
+
+bool SIGfx10And11PreciseMemorySupport ::handleNonAtomic(
+MachineBasicBlock::iterator ) {
+  assert(MI->mayLoadOrStore());
+
+  MachineInstr  = *MI;
+  AMDGPU::Waitcnt Wait;
+
+  bool BuildWaitCnt = true;
+  bool BuildVsCnt = false;
+
+  if (TII->isSMRD(Inst)) { // scalar
+if (Inst.mayStore())
+  return false;
+Wait.DsCnt = 0;   // LgkmCnt
+  } else {// vector
+if (Inst.mayLoad()) { // vector load
+  if (TII->isVMEM(Inst)) {// VMEM load
+Wait.LoadCnt = 0; // VmCnt
+  } else if (TII->isFLAT(Inst)) { // Flat load
+Wait.LoadCnt = 0; // VmCnt
+Wait.DsCnt = 0;   // LgkmCnt
+  } else {// LDS load
+Wait.DsCnt = 0;   // LgkmCnt
+  }
+}
+
+// For some instructions, mayLoad() and mayStore() can be both true.
+if (Inst.mayStore()) { // vector store; an instruction can be both
+   // load/store
+  if (TII->isVMEM(Inst)) { // VMEM store
+if (!Inst.mayLoad())
+  BuildWaitCnt = false;
+BuildVsCnt = true;
+  } else if (TII->isFLAT(Inst)) { // Flat store
+Wait.DsCnt = 0;   // LgkmCnt
+BuildVsCnt = true;
+  } else {
+Wait.DsCnt = 0; // LDS store; LgkmCnt
+  }
+}
+  }
+
+  MachineBasicBlock  = *MI->getParent();
+  if (BuildWaitCnt) {
+unsigned Enc = AMDGPU::encodeWaitcnt(IV, Wait);
+BuildMI(MBB, ++MI, 

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

2024-02-05 Thread Pierre van Houtryve via cfe-commits


@@ -605,12 +606,197 @@ class SIGfx12CacheControl : public SIGfx11CacheControl {
   bool IsNonTemporal) const override;
 };
 
+class SIPreciseMemorySupport {
+protected:
+  const GCNSubtarget 
+  const SIInstrInfo *TII = nullptr;
+
+  IsaVersion IV;
+
+  SIPreciseMemorySupport(const GCNSubtarget ) : ST(ST) {
+TII = ST.getInstrInfo();
+IV = getIsaVersion(ST.getCPU());
+  }
+
+public:
+  static std::unique_ptr create(const GCNSubtarget 
);
+
+  virtual bool handleNonAtomic(MachineBasicBlock::iterator ) = 0;
+  /// Handles atomic instruction \p MI with \p ret indicating whether \p MI
+  /// returns a result.
+  virtual bool handleAtomic(MachineBasicBlock::iterator , bool ret) = 0;
+};
+
+class SIGfx9PreciseMemorySupport : public SIPreciseMemorySupport {
+public:
+  SIGfx9PreciseMemorySupport(const GCNSubtarget )
+  : SIPreciseMemorySupport(ST) {}
+  bool handleNonAtomic(MachineBasicBlock::iterator ) override;
+  bool handleAtomic(MachineBasicBlock::iterator , bool ret) override;
+};
+
+class SIGfx10And11PreciseMemorySupport : public SIPreciseMemorySupport {
+public:
+  SIGfx10And11PreciseMemorySupport(const GCNSubtarget )
+  : SIPreciseMemorySupport(ST) {}
+  bool handleNonAtomic(MachineBasicBlock::iterator ) override;
+  bool handleAtomic(MachineBasicBlock::iterator , bool ret) override;
+};
+
+std::unique_ptr
+SIPreciseMemorySupport::create(const GCNSubtarget ) {
+  GCNSubtarget::Generation Generation = ST.getGeneration();
+  if (Generation < AMDGPUSubtarget::GFX10)

Pierre-vh wrote:

GFX12 is missing

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


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

2024-02-05 Thread Pierre van Houtryve via cfe-commits


@@ -167,6 +167,10 @@ def FeatureCuMode : SubtargetFeature<"cumode",
   "Enable CU wavefront execution mode"
 >;
 
+def FeaturePreciseMemory

Pierre-vh wrote:

Understood :) 
Can you remove the `amdgpu` prefix from the option? All target features are 
already specific to AMDGPU, e.g. xnack, sramecc, etc. so you can just use 
something like `precise-memory`

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


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

2024-02-05 Thread Pierre van Houtryve via cfe-commits


@@ -0,0 +1,362 @@
+; RUN: llc -mtriple=amdgcn -mcpu=gfx900 -mattr=+amdgpu-precise-memory-op < %s 
| FileCheck %s -check-prefixes=GFX9
+; RUN: llc -mtriple=amdgcn -mcpu=gfx90a -mattr=+amdgpu-precise-memory-op < %s 
| FileCheck %s -check-prefixes=GFX90A
+; RUN: llc -mtriple=amdgcn -mcpu=gfx1010 -mattr=+amdgpu-precise-memory-op < %s 
| FileCheck %s -check-prefixes=GFX10
+; RUN: llc -mtriple=amdgcn-- -mcpu=gfx900 
-mattr=-flat-for-global,+enable-flat-scratch,+amdgpu-precise-memory-op 
-amdgpu-use-divergent-register-indexing < %s | FileCheck 
--check-prefixes=GFX9-FLATSCR %s

Pierre-vh wrote:

gfx11 and 12 tests

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


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

2024-02-05 Thread Pierre van Houtryve via cfe-commits


@@ -605,12 +606,197 @@ class SIGfx12CacheControl : public SIGfx11CacheControl {
   bool IsNonTemporal) const override;
 };
 
+class SIPreciseMemorySupport {

Pierre-vh wrote:

Why does it need to be a separate class hierarchy?
It could just be part of CacheControl, and the functions can be named 
`handlePreciseMemoryAtomic/NonAtomic` ?
That would avoid a lot of boilerplate.

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


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

2024-02-05 Thread Pierre van Houtryve via cfe-commits

https://github.com/Pierre-vh requested changes to this pull request.

When you made changes, you can click the "Re-request review" icon next to 
reviewers to put it back in the review queues :)

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


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

2024-02-05 Thread Pierre van Houtryve via cfe-commits

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


[clang] Diagnose invalid fixed point conversion (PR #80763)

2024-02-05 Thread Petr Hosek via cfe-commits

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


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


[clang-tools-extra] [clangd] forward clang-tidy's readability-identifier-naming fix to textDocument/rename (PR #78454)

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

HighCommander4 wrote:

Looks pretty good!

Are there further changes you're planning to make, or is this ready to graduate 
from "Draft" status?

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


[llvm] [clang-tools-extra] [clang] [PGO] Add ability to mark cold functions as optsize/minsize/optnone (PR #69030)

2024-02-05 Thread David Li via cfe-commits

david-xl wrote:

> > > > I don't understand, if you're saying the profile is accurate, then 
> > > > those functions are actually cold, so we should be able to mark them as 
> > > > optsize?
> > > 
> > > 
> > > Accurate is not black or white. The current heuristic requires certain 
> > > level of accuracy to be effective. If you make the heuristics more 
> > > aggressive (like what this patch is doing), you're raising the 
> > > requirement of what can be considered accurate, and profile not meeting 
> > > that new requirement could see regression with new heuristic.
> > > Whether a function is cold or not also depends on what is the calling 
> > > context and how inlining is done. All that makes function level 
> > > annotation inherently inaccurate when done before inlining. Not that we 
> > > shouldn't try it, but it's not as clear cut as it appears to be, and we 
> > > need to be careful.
> > 
> > 
> > It will be more conservative (pre-inlining), so won't cause additional 
> > optimization suppression compared with the current PGSO.
> 
> Sample PGO profile has inline context, so in the profile, we may have `foo` 
> as cold and `bar->foo` as hot, but if later inliner rejects `bar->foo` 
> inlining, `foo` can be hot. So marking `foo` as cold pre-inline can still be 
> inaccurate (and not conservative).
> 
> In this PR, you have `PGOColdFuncAttr` default to `ColdFuncOpt::Default`. As 
> long as you keep it that way, this PR is fine for sample pgo (it's no-op 
> unless `pgo-cold-func-opt` is used explicitly).

Good example. This pass should be run post-inline.  @aeubanks, any reason we 
want to run it early in the pipeline?

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


[clang] Diagnose invalid fixed point conversion (PR #80763)

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

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


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


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

2024-02-05 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/80802

>From 741793c9584753e6e888c9824961501b676b1143 Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Tue, 6 Feb 2024 14:06:40 +0800
Subject: [PATCH] [Clang][Sema] fix crash in codegen stage when an lambda
 expression declared in an unevaluated context

---
 clang/docs/ReleaseNotes.rst|  2 ++
 clang/lib/Sema/SemaTemplateInstantiate.cpp |  7 ---
 clang/test/CodeGen/PR76674.cpp | 11 +++
 3 files changed, 17 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/CodeGen/PR76674.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 4d57ea4fd55b8..7ad575e4f57fa 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -204,6 +204,8 @@ Bug Fixes to C++ Support
   parameter where we did an incorrect specialization of the initialization of
   the default parameter.
   Fixes (`#68490 `_)
+- Fix a crash in codegen when lambdas declared in an unevaluated context.
+  Fixes (`#76674 `_)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 6d59180bc446d..383163ea969a9 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -1613,8 +1613,8 @@ namespace {
 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
   if (T.isNull())
 return true;
-
-  if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
+  if (T->isInstantiationDependentType() || T->isVariablyModifiedType() ||
+  (SemaRef.getLangOpts().CPlusPlus20 && T->isDecltypeType()))
 return false;
 
   getSema().MarkDeclarationsReferencedInType(Loc, T);
@@ -2685,7 +2685,8 @@ QualType Sema::SubstType(QualType T,
 
   // If T is not a dependent type or a variably-modified type, there
   // is nothing to do.
-  if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
+  if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType() &&
+  (getLangOpts().CPlusPlus20 && !T->isDecltypeType()))
 return T;
 
   TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
diff --git a/clang/test/CodeGen/PR76674.cpp b/clang/test/CodeGen/PR76674.cpp
new file mode 100644
index 0..e47184b7fcb59
--- /dev/null
+++ b/clang/test/CodeGen/PR76674.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -verify -std=c++20 -emit-llvm -o - %s
+// expected-no-diagnostics
+
+template 
+struct A {
+template 
+using Func = decltype([] {return U{};});
+};
+
+A::Func f{};
+int i{f()};

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


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

2024-02-05 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/80802

>From 6dbd0937e8ded4dd8f71afb876bb3930c309 Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Tue, 6 Feb 2024 14:06:40 +0800
Subject: [PATCH] [Clang][Sema] fix crash in codegen stage when an lambda
 expression declared in an unevaluated context

---
 clang/docs/ReleaseNotes.rst|  2 ++
 clang/lib/Sema/SemaTemplateInstantiate.cpp |  7 ---
 clang/test/CodeGen/PR76674.cpp | 11 +++
 3 files changed, 17 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/CodeGen/PR76674.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 4d57ea4fd55b8c..7ad575e4f57fa6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -204,6 +204,8 @@ Bug Fixes to C++ Support
   parameter where we did an incorrect specialization of the initialization of
   the default parameter.
   Fixes (`#68490 `_)
+- Fix a crash in codegen when lambdas declared in an unevaluated context.
+  Fixes (`#76674 `_)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 6d59180bc446d2..383163ea969a95 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -1613,8 +1613,8 @@ namespace {
 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
   if (T.isNull())
 return true;
-
-  if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
+  if (T->isInstantiationDependentType() || T->isVariablyModifiedType() ||
+  (SemaRef.getLangOpts().CPlusPlus20 && T->isDecltypeType()))
 return false;
 
   getSema().MarkDeclarationsReferencedInType(Loc, T);
@@ -2685,7 +2685,8 @@ QualType Sema::SubstType(QualType T,
 
   // If T is not a dependent type or a variably-modified type, there
   // is nothing to do.
-  if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
+  if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType() &&
+  (getLangOpts().CPlusPlus20 && !T->isDecltypeType()))
 return T;
 
   TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
diff --git a/clang/test/CodeGen/PR76674.cpp b/clang/test/CodeGen/PR76674.cpp
new file mode 100644
index 00..11b730dc44dbd6
--- /dev/null
+++ b/clang/test/CodeGen/PR76674.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -std=c++20 -emit-llvm %s  -o /dev/null
+// expected-no-diagnostics
+
+template 
+struct A {
+template 
+using Func = decltype([] {return U{};});
+};
+
+A::Func f{};
+int i{f()};

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


[clang] [clang-tools-extra] [llvm] [AArch64] Add an AArch64 pass for loop idiom transformations (PR #72273)

2024-02-05 Thread via cfe-commits

shaojingzhi wrote:

Hi! I wonder that have you conducted any tests to determine the potential 
performance increase of this pass in the SPEC2017 557xz benchmark? I attempted 
to apply it to the xz benchmark, but only one copy(--copies=1) demonstrated a 
significant increase(about 3%), but there was no increase when I set 
--copies=128 or higher. Do you have any suggestions or test results that you 
could share?

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


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

2024-02-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Qizhi Hu (jcsxky)


Changes

Try to fix [issue](https://github.com/llvm/llvm-project/issues/76674)
When transform a lambda expression which is declared in an unevaluated context, 
`isInstantiationDependentType()` and `isVariablyModifiedType()` both return 
false and lead to skip transforming the lambda expression. On the other hand, 
`AlreadyTransformed` also skip transform in this case. Add the condition to 
check whether it's in decltype makes it work.

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


3 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+2) 
- (modified) clang/lib/Sema/SemaTemplateInstantiate.cpp (+4-3) 
- (added) clang/test/SemaTemplate/PR76674.cpp (+11) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 4d57ea4fd55b8..7ad575e4f57fa 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -204,6 +204,8 @@ Bug Fixes to C++ Support
   parameter where we did an incorrect specialization of the initialization of
   the default parameter.
   Fixes (`#68490 `_)
+- Fix a crash in codegen when lambdas declared in an unevaluated context.
+  Fixes (`#76674 `_)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 6d59180bc446d..383163ea969a9 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -1613,8 +1613,8 @@ namespace {
 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
   if (T.isNull())
 return true;
-
-  if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
+  if (T->isInstantiationDependentType() || T->isVariablyModifiedType() ||
+  (SemaRef.getLangOpts().CPlusPlus20 && T->isDecltypeType()))
 return false;
 
   getSema().MarkDeclarationsReferencedInType(Loc, T);
@@ -2685,7 +2685,8 @@ QualType Sema::SubstType(QualType T,
 
   // If T is not a dependent type or a variably-modified type, there
   // is nothing to do.
-  if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
+  if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType() &&
+  (getLangOpts().CPlusPlus20 && !T->isDecltypeType()))
 return T;
 
   TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
diff --git a/clang/test/SemaTemplate/PR76674.cpp 
b/clang/test/SemaTemplate/PR76674.cpp
new file mode 100644
index 0..50e9053e41e0f
--- /dev/null
+++ b/clang/test/SemaTemplate/PR76674.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -c -std=c++20 -verify=cxx20 -o /dev/null %s
+// expected-no-diagnostics
+
+template 
+struct A {
+template 
+using Func = decltype([] {return U{};});
+};
+
+A::Func f{};
+int i{f()};

``




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


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

2024-02-05 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky created 
https://github.com/llvm/llvm-project/pull/80802

Try to fix [issue](https://github.com/llvm/llvm-project/issues/76674)
When transform a lambda expression which is declared in an unevaluated context, 
`isInstantiationDependentType()` and `isVariablyModifiedType()` both return 
false and lead to skip transforming the lambda expression. On the other hand, 
`AlreadyTransformed` also skip transform in this case. Add the condition to 
check whether it's in decltype makes it work.

>From f8ce2878f95df00aa84afb17bd14c20e82d44cd4 Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Tue, 6 Feb 2024 14:06:40 +0800
Subject: [PATCH] [Clang][Sema] fix crash in codegen stage when an lambda
 expression declared in an unevaluated context

---
 clang/docs/ReleaseNotes.rst|  2 ++
 clang/lib/Sema/SemaTemplateInstantiate.cpp |  7 ---
 clang/test/SemaTemplate/PR76674.cpp| 11 +++
 3 files changed, 17 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/SemaTemplate/PR76674.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 4d57ea4fd55b8..7ad575e4f57fa 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -204,6 +204,8 @@ Bug Fixes to C++ Support
   parameter where we did an incorrect specialization of the initialization of
   the default parameter.
   Fixes (`#68490 `_)
+- Fix a crash in codegen when lambdas declared in an unevaluated context.
+  Fixes (`#76674 `_)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 6d59180bc446d..383163ea969a9 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -1613,8 +1613,8 @@ namespace {
 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
   if (T.isNull())
 return true;
-
-  if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
+  if (T->isInstantiationDependentType() || T->isVariablyModifiedType() ||
+  (SemaRef.getLangOpts().CPlusPlus20 && T->isDecltypeType()))
 return false;
 
   getSema().MarkDeclarationsReferencedInType(Loc, T);
@@ -2685,7 +2685,8 @@ QualType Sema::SubstType(QualType T,
 
   // If T is not a dependent type or a variably-modified type, there
   // is nothing to do.
-  if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
+  if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType() &&
+  (getLangOpts().CPlusPlus20 && !T->isDecltypeType()))
 return T;
 
   TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
diff --git a/clang/test/SemaTemplate/PR76674.cpp 
b/clang/test/SemaTemplate/PR76674.cpp
new file mode 100644
index 0..50e9053e41e0f
--- /dev/null
+++ b/clang/test/SemaTemplate/PR76674.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -c -std=c++20 -verify=cxx20 -o /dev/null %s
+// expected-no-diagnostics
+
+template 
+struct A {
+template 
+using Func = decltype([] {return U{};});
+};
+
+A::Func f{};
+int i{f()};

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


[clang] [clang-tools-extra] [llvm] [PGO] Add ability to mark cold functions as optsize/minsize/optnone (PR #69030)

2024-02-05 Thread via cfe-commits

WenleiHe wrote:

> > > I don't understand, if you're saying the profile is accurate, then those 
> > > functions are actually cold, so we should be able to mark them as optsize?
> > 
> > 
> > Accurate is not black or white. The current heuristic requires certain 
> > level of accuracy to be effective. If you make the heuristics more 
> > aggressive (like what this patch is doing), you're raising the requirement 
> > of what can be considered accurate, and profile not meeting that new 
> > requirement could see regression with new heuristic.
> > Whether a function is cold or not also depends on what is the calling 
> > context and how inlining is done. All that makes function level annotation 
> > inherently inaccurate when done before inlining. Not that we shouldn't try 
> > it, but it's not as clear cut as it appears to be, and we need to be 
> > careful.
> 
> It will be more conservative (pre-inlining), so won't cause additional 
> optimization suppression compared with the current PGSO.

Sample PGO profile has inline context, so in the profile, we may have `foo` as 
cold and `bar->foo` as hot, but if later inliner rejects `bar->foo` inlining, 
`foo` can be hot. So marking `foo` as cold pre-inline can still be inaccurate 
(and not conservative). 

In this PR, you have `PGOColdFuncAttr` default to `ColdFuncOpt::Default`. As 
long as you keep it that way, this PR is fine for sample pgo (it's no-op unless 
`pgo-cold-func-opt` is used explicitly). 

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


[clang] [clang] require template arg list after template kw (PR #80801)

2024-02-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Erick Velez (evelez7)


Changes

Require a template argument list after an identifier prefixed by the template 
keyword. Introduced by [CWG 
96](https://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#96). 
Current wording of [temp.names] introduced in 
[P1787R6](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p1787r6.html).

Fixes #53095

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


8 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticParseKinds.td (+3) 
- (modified) clang/lib/Parse/ParseExprCXX.cpp (+17-6) 
- (modified) clang/test/CXX/drs/dr0xx.cpp (+1-1) 
- (modified) clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp (+3-3) 
- (modified) clang/test/SemaCXX/template-specialization.cpp (+1-1) 
- (modified) clang/test/SemaTemplate/dependent-names.cpp (+3-3) 
- (modified) clang/test/SemaTemplate/template-id-expr.cpp (+18-18) 
- (modified) clang/test/SemaTemplate/template-id-printing.cpp (-13) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index a30ab27566ec3e..159600f3e26dc0 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -868,6 +868,9 @@ def err_requires_expr_in_simple_requirement : Error<
   "requires expression in requirement body; did "
   "you intend to place it in a nested requirement? (add another 'requires' "
   "before the expression)">;
+def err_missing_template_arg_list_after_template_kw : Error<
+  "a template argument list is expected after a name prefixed by the template "
+  "keyword">;
 
 def err_missing_dependent_template_keyword : Error<
   "use 'template' keyword to treat '%0' as a dependent template name">;
diff --git a/clang/lib/Parse/ParseExprCXX.cpp b/clang/lib/Parse/ParseExprCXX.cpp
index fd262ff31e661a..b3a1a6f6cf80d0 100644
--- a/clang/lib/Parse/ParseExprCXX.cpp
+++ b/clang/lib/Parse/ParseExprCXX.cpp
@@ -14,6 +14,7 @@
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/Basic/PrettyStackTrace.h"
+#include "clang/Basic/TemplateKinds.h"
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/LiteralSupport.h"
 #include "clang/Parse/ParseDiagnostic.h"
@@ -2995,13 +2996,23 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec , 
ParsedType ObjectType,
   SS, ObjectType, ObjectHadErrors,
   TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
   EnteringContext, Result, TemplateSpecified);
-else if (TemplateSpecified &&
- Actions.ActOnTemplateName(
- getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
- EnteringContext, Template,
- /*AllowInjectedClassName*/ true) == TNK_Non_template)
-  return true;
 
+if (TemplateSpecified) {
+  TemplateNameKind TNK =
+  Actions.ActOnTemplateName(getCurScope(), SS, *TemplateKWLoc, Result,
+ObjectType, EnteringContext, Template,
+/*AllowInjectedClassName*/ true);
+  if (TNK == TNK_Non_template)
+return true;
+
+  // C++ [template.names]p6
+  // A name prefixed by the keyword template shall be followed by a 
template
+  // argument list or refer to a class template or an alias template.
+  if ((TNK == TNK_Function_template || TNK == TNK_Dependent_template_name 
||
+   TNK == TNK_Var_template) &&
+  !Tok.is(tok::less))
+Diag(IdLoc, diag::err_missing_template_arg_list_after_template_kw);
+}
 return false;
   }
 
diff --git a/clang/test/CXX/drs/dr0xx.cpp b/clang/test/CXX/drs/dr0xx.cpp
index 5959f0a0c8dd65..127d45be5bda97 100644
--- a/clang/test/CXX/drs/dr0xx.cpp
+++ b/clang/test/CXX/drs/dr0xx.cpp
@@ -1414,7 +1414,7 @@ namespace dr96 { // dr96: no
 // FIXME: This is ill-formed, because 'f' is not a template-id and does not
 // name a class template.
 // FIXME: What about alias templates?
-int k2 = a.template f(1);
+int k2 = a.template f(1); // expected-error {{a template argument list is 
expected after a name prefixed by the template keyword}}
 A::template S s;
 B b;
   }
diff --git a/clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp 
b/clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
index af121a8b75d512..37dbe0b212eb6a 100644
--- a/clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
+++ b/clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
@@ -384,16 +384,16 @@ namespace dependent_static_var_template {
   struct A {
 template static int n; // expected-note 2{{here}}
   };
-  int  = A::template n; // expected-error {{use of variable template 'n' 
requires template arguments}}
+  int  = A::template n; // expected-error {{use of variable template 'n' 
requires template arguments}} expected-error {{a template argument list is 
expected after a name 

[clang] [clang] require template arg list after template kw (PR #80801)

2024-02-05 Thread Erick Velez via cfe-commits

https://github.com/evelez7 created 
https://github.com/llvm/llvm-project/pull/80801

Require a template argument list after an identifier prefixed by the template 
keyword. Introduced by [CWG 
96](https://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#96). Current 
wording of [temp.names] introduced in 
[P1787R6](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p1787r6.html).

Fixes #53095

>From fd07c0a15eb45c3e7eb400026ea7702ae909a11e Mon Sep 17 00:00:00 2001
From: Erick Velez 
Date: Mon, 5 Feb 2024 21:26:07 -0800
Subject: [PATCH] [clang] require template arg list after template kw

Require a template argument list after an identifier prefixed by the
template keyword. Introduced by CWG 96.

Fixes #53095
---
 .../clang/Basic/DiagnosticParseKinds.td   |  3 ++
 clang/lib/Parse/ParseExprCXX.cpp  | 23 
 clang/test/CXX/drs/dr0xx.cpp  |  2 +-
 .../cxx1y-variable-templates_in_class.cpp |  6 ++--
 .../test/SemaCXX/template-specialization.cpp  |  2 +-
 clang/test/SemaTemplate/dependent-names.cpp   |  6 ++--
 clang/test/SemaTemplate/template-id-expr.cpp  | 36 +--
 .../SemaTemplate/template-id-printing.cpp | 13 ---
 8 files changed, 46 insertions(+), 45 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index a30ab27566ec3e..159600f3e26dc0 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -868,6 +868,9 @@ def err_requires_expr_in_simple_requirement : Error<
   "requires expression in requirement body; did "
   "you intend to place it in a nested requirement? (add another 'requires' "
   "before the expression)">;
+def err_missing_template_arg_list_after_template_kw : Error<
+  "a template argument list is expected after a name prefixed by the template "
+  "keyword">;
 
 def err_missing_dependent_template_keyword : Error<
   "use 'template' keyword to treat '%0' as a dependent template name">;
diff --git a/clang/lib/Parse/ParseExprCXX.cpp b/clang/lib/Parse/ParseExprCXX.cpp
index fd262ff31e661a..b3a1a6f6cf80d0 100644
--- a/clang/lib/Parse/ParseExprCXX.cpp
+++ b/clang/lib/Parse/ParseExprCXX.cpp
@@ -14,6 +14,7 @@
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/Basic/PrettyStackTrace.h"
+#include "clang/Basic/TemplateKinds.h"
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/LiteralSupport.h"
 #include "clang/Parse/ParseDiagnostic.h"
@@ -2995,13 +2996,23 @@ bool Parser::ParseUnqualifiedId(CXXScopeSpec , 
ParsedType ObjectType,
   SS, ObjectType, ObjectHadErrors,
   TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
   EnteringContext, Result, TemplateSpecified);
-else if (TemplateSpecified &&
- Actions.ActOnTemplateName(
- getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
- EnteringContext, Template,
- /*AllowInjectedClassName*/ true) == TNK_Non_template)
-  return true;
 
+if (TemplateSpecified) {
+  TemplateNameKind TNK =
+  Actions.ActOnTemplateName(getCurScope(), SS, *TemplateKWLoc, Result,
+ObjectType, EnteringContext, Template,
+/*AllowInjectedClassName*/ true);
+  if (TNK == TNK_Non_template)
+return true;
+
+  // C++ [template.names]p6
+  // A name prefixed by the keyword template shall be followed by a 
template
+  // argument list or refer to a class template or an alias template.
+  if ((TNK == TNK_Function_template || TNK == TNK_Dependent_template_name 
||
+   TNK == TNK_Var_template) &&
+  !Tok.is(tok::less))
+Diag(IdLoc, diag::err_missing_template_arg_list_after_template_kw);
+}
 return false;
   }
 
diff --git a/clang/test/CXX/drs/dr0xx.cpp b/clang/test/CXX/drs/dr0xx.cpp
index 5959f0a0c8dd65..127d45be5bda97 100644
--- a/clang/test/CXX/drs/dr0xx.cpp
+++ b/clang/test/CXX/drs/dr0xx.cpp
@@ -1414,7 +1414,7 @@ namespace dr96 { // dr96: no
 // FIXME: This is ill-formed, because 'f' is not a template-id and does not
 // name a class template.
 // FIXME: What about alias templates?
-int k2 = a.template f(1);
+int k2 = a.template f(1); // expected-error {{a template argument list is 
expected after a name prefixed by the template keyword}}
 A::template S s;
 B b;
   }
diff --git a/clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp 
b/clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
index af121a8b75d512..37dbe0b212eb6a 100644
--- a/clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
+++ b/clang/test/SemaCXX/cxx1y-variable-templates_in_class.cpp
@@ -384,16 +384,16 @@ namespace dependent_static_var_template {
   struct A {
 template static int n; // expected-note 2{{here}}
   };
-  int  = A::template n; // expected-error {{use of 

[clang] [clang] Add zero-initialization for fixed point types (PR #80781)

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


@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -ffixed-point -S -emit-llvm %s -o - | FileCheck %s
+
+// CHECK: @_ZL1a = internal constant [2 x i32] zeroinitializer
+constexpr _Accum a[2] = {};

MaskRay wrote:

Consider a `test/AST/` test like `static_assert(a[0] == 0 && a[0] != 1);`

This is not supported by -fexperimental-new-constant-interpreter, but I think 
it is ok.

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


[llvm] [clang] [RISCV] Add Ssqosid support to -march. (PR #80747)

2024-02-05 Thread Yingwei Zheng via cfe-commits


@@ -1612,6 +1613,14 @@
 // RUN:   -o - | FileCheck --check-prefix=CHECK-SUPM-EXT %s
 // CHECK-SUPM-EXT: __riscv_supm 8000{{$}}
 
+// RUN: %clang --target=riscv32 -menable-experimental-extensions \
+// RUN:   -march=rv32i_ssqosid1p0 -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-SSQOSID-EXT %s
+// RUN: %clang --target=riscv64 \
+// RUN:   -march=rv64i_ssqosid1p0 -E -dM %s -menable-experimental-extensions \

dtcxzyw wrote:

It is required for clang when using experimental RISC-V extensions.
> def menable_experimental_extensions : Flag<["-"], 
> "menable-experimental-extensions">, Group,
  HelpText<"Enable use of experimental RISC-V extensions.">;


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


[llvm] [clang] [RISCV] Add Ssqosid support to -march. (PR #80747)

2024-02-05 Thread Craig Topper via cfe-commits


@@ -1612,6 +1613,14 @@
 // RUN:   -o - | FileCheck --check-prefix=CHECK-SUPM-EXT %s
 // CHECK-SUPM-EXT: __riscv_supm 8000{{$}}
 
+// RUN: %clang --target=riscv32 -menable-experimental-extensions \
+// RUN:   -march=rv32i_ssqosid1p0 -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-SSQOSID-EXT %s
+// RUN: %clang --target=riscv64 \
+// RUN:   -march=rv64i_ssqosid1p0 -E -dM %s -menable-experimental-extensions \

topperc wrote:

It's not ratified yet right?

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


[llvm] [clang] [RISCV] Add Ssqosid support to -march. (PR #80747)

2024-02-05 Thread Wang Pengcheng via cfe-commits


@@ -1612,6 +1613,14 @@
 // RUN:   -o - | FileCheck --check-prefix=CHECK-SUPM-EXT %s
 // CHECK-SUPM-EXT: __riscv_supm 8000{{$}}
 
+// RUN: %clang --target=riscv32 -menable-experimental-extensions \
+// RUN:   -march=rv32i_ssqosid1p0 -E -dM %s \
+// RUN:   -o - | FileCheck --check-prefix=CHECK-SSQOSID-EXT %s
+// RUN: %clang --target=riscv64 \
+// RUN:   -march=rv64i_ssqosid1p0 -E -dM %s -menable-experimental-extensions \

wangpc-pp wrote:

Why is `-menable-experimental-extensions` here?

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


[compiler-rt] [clang] [llvm] [X86] Support APXF to enable __builtin_cpu_supports. (PR #80636)

2024-02-05 Thread Freddy Ye via cfe-commits


@@ -248,10 +248,11 @@ X86_FEATURE_COMPAT(AVXVNNIINT16,"avxvnniint16",   
0)
 X86_FEATURE_COMPAT(SM3, "sm3",0)
 X86_FEATURE_COMPAT(SHA512,  "sha512", 0)
 X86_FEATURE_COMPAT(SM4, "sm4",0)
-X86_FEATURE   (EGPR,"egpr")
+X86_FEATURE_COMPAT(APXF,"apxf",   0)
 X86_FEATURE_COMPAT(USERMSR, "usermsr",0)
 X86_FEATURE_COMPAT(AVX10_1, "avx10.1-256",0)
 X86_FEATURE_COMPAT(AVX10_1_512, "avx10.1-512",0)
+X86_FEATURE   (EGPR,"egpr")

FreddyLeaf wrote:

E.g. we need 4 `X86_FEATURE` inserted between `X86_FEATURE_COMPAT(AVX512FP16,` 
and `X86_FEATURE_COMPAT(AVXIFMA,`

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


[clang] [-Wunsafe-buffer-usage] Introduce std::array fixits (PR #80084)

2024-02-05 Thread via cfe-commits


@@ -61,6 +61,7 @@ void testArraySubscripts(int *p, int **pp) {
   );
 
 int a[10];  // expected-warning{{'a' is an unsafe buffer that does 
not perform bounds checks}}
+// expected-note@-1{{change type of 'a' to 
'std::array' to harden it}}

jkorous-apple wrote:

"so it can benefit from libc++ hardening"?

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


[llvm] [clang] [compiler-rt] [X86] Support APXF to enable __builtin_cpu_supports. (PR #80636)

2024-02-05 Thread Shengchen Kan via cfe-commits


@@ -248,10 +248,11 @@ X86_FEATURE_COMPAT(AVXVNNIINT16,"avxvnniint16",   
0)
 X86_FEATURE_COMPAT(SM3, "sm3",0)
 X86_FEATURE_COMPAT(SHA512,  "sha512", 0)
 X86_FEATURE_COMPAT(SM4, "sm4",0)
-X86_FEATURE   (EGPR,"egpr")
+X86_FEATURE_COMPAT(APXF,"apxf",   0)
 X86_FEATURE_COMPAT(USERMSR, "usermsr",0)
 X86_FEATURE_COMPAT(AVX10_1, "avx10.1-256",0)
 X86_FEATURE_COMPAT(AVX10_1_512, "avx10.1-512",0)
+X86_FEATURE   (EGPR,"egpr")

KanRobert wrote:

I think only the position of X86_FEATURE_COMPAT matters while X86_FEATURE does 
not?

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


[clang] [-Wunsafe-buffer-usage] Fix debug notes for unclaimed DREs (PR #80787)

2024-02-05 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 8f80df0f52c4294d23d0510b01be6d6491714058 
90e7145fe0133828b4abc16730b9786fc68df8b9 -- 
clang/lib/Analysis/UnsafeBufferUsage.cpp 
clang/test/SemaCXX/warn-unsafe-buffer-usage-debug.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 6feff1d508..a6dcf16b92 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -2879,27 +2879,27 @@ void clang::checkUnsafeBufferUsage(const Decl *D,
 "' : init capture"));
 #endif
 it = FixablesForAllVars.byVar.erase(it);
-  }else {
-  ++it;
-}
+  } else {
+++it;
+  }
   }
 
 #ifndef NDEBUG
-  for (const auto& it : UnsafeOps.byVar) {
-const VarDecl* const UnsafeVD = it.first;
+  for (const auto  : UnsafeOps.byVar) {
+const VarDecl *const UnsafeVD = it.first;
 auto UnclaimedDREs = Tracker.getUnclaimedUses(UnsafeVD);
 if (UnclaimedDREs.empty())
   continue;
 const auto UnfixedVDName = UnsafeVD->getNameAsString();
-for (const clang::DeclRefExpr* UnclaimedDRE : UnclaimedDREs) {
+for (const clang::DeclRefExpr *UnclaimedDRE : UnclaimedDREs) {
   std::string UnclaimedUseTrace =
   getDREAncestorString(UnclaimedDRE, D->getASTContext());
 
   Handler.addDebugNoteForVar(
   UnsafeVD, UnclaimedDRE->getBeginLoc(),
   ("failed to produce fixit for '" + UnfixedVDName +
-"' : has an unclaimed use\nThe unclaimed DRE trace: " +
-UnclaimedUseTrace));
+   "' : has an unclaimed use\nThe unclaimed DRE trace: " +
+   UnclaimedUseTrace));
 }
   }
 #endif

``




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


[clang] [-Wunsafe-buffer-usage] Fix debug notes for unclaimed DREs (PR #80787)

2024-02-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (jkorous-apple)


Changes

Debug notes for unclaimed DeclRefExpr should report any DRE of an unsafe 
variable that is not covered by a Fixable (i. e. fixit for the particular AST 
pattern isn't implemented for whatever reason). Currently not all unclaimed 
DeclRefExpr-s are reported which is a bug. The debug notes report only those 
DREs where the referred VarDecl has at least one other DeclRefExpr which is 
claimed (covered by a fixit). If there is an unsafe VarDecl that has exactly 
one DRE and the DRE isn't claimed then the debug note about missing fixit won't 
be emitted. That is because the debug note is emitted from within a loop over 
set of successfully matched FixableGadgets which by-definition is missing those 
DRE that are not matched at all.

The new code simply iterates over all unsafe VarDecls and all of their 
unclaimed DREs.

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


2 Files Affected:

- (modified) clang/lib/Analysis/UnsafeBufferUsage.cpp (+20-13) 
- (modified) clang/test/SemaCXX/warn-unsafe-buffer-usage-debug.cpp (+7) 


``diff
diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 823cd2a7b9969..6feff1d508e67 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -2870,19 +2870,6 @@ void clang::checkUnsafeBufferUsage(const Decl *D,
 #endif
 it = FixablesForAllVars.byVar.erase(it);
   } else if (Tracker.hasUnclaimedUses(it->first)) {
-#ifndef NDEBUG
-auto AllUnclaimed = Tracker.getUnclaimedUses(it->first);
-for (auto UnclaimedDRE : AllUnclaimed) {
-std::string UnclaimedUseTrace =
-getDREAncestorString(UnclaimedDRE, D->getASTContext());
-
-Handler.addDebugNoteForVar(
-it->first, UnclaimedDRE->getBeginLoc(),
-("failed to produce fixit for '" + it->first->getNameAsString() +
- "' : has an unclaimed use\nThe unclaimed DRE trace: " +
- UnclaimedUseTrace));
-}
-#endif
 it = FixablesForAllVars.byVar.erase(it);
   } else if (it->first->isInitCapture()) {
 #ifndef NDEBUG
@@ -2897,6 +2884,26 @@ void clang::checkUnsafeBufferUsage(const Decl *D,
 }
   }
 
+#ifndef NDEBUG
+  for (const auto& it : UnsafeOps.byVar) {
+const VarDecl* const UnsafeVD = it.first;
+auto UnclaimedDREs = Tracker.getUnclaimedUses(UnsafeVD);
+if (UnclaimedDREs.empty())
+  continue;
+const auto UnfixedVDName = UnsafeVD->getNameAsString();
+for (const clang::DeclRefExpr* UnclaimedDRE : UnclaimedDREs) {
+  std::string UnclaimedUseTrace =
+  getDREAncestorString(UnclaimedDRE, D->getASTContext());
+
+  Handler.addDebugNoteForVar(
+  UnsafeVD, UnclaimedDRE->getBeginLoc(),
+  ("failed to produce fixit for '" + UnfixedVDName +
+"' : has an unclaimed use\nThe unclaimed DRE trace: " +
+UnclaimedUseTrace));
+}
+  }
+#endif
+
   // Fixpoint iteration for pointer assignments
   using DepMapTy = DenseMap>;
   DepMapTy DependenciesMap{};
diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-debug.cpp 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-debug.cpp
index e08f70d97e391..5fff0854d4546 100644
--- a/clang/test/SemaCXX/warn-unsafe-buffer-usage-debug.cpp
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-debug.cpp
@@ -98,3 +98,10 @@ void test_struct_claim_use() {
   x[6] = 8;  // expected-warning{{unsafe buffer access}}
   x++;  // expected-warning{{unsafe pointer arithmetic}}
 }
+
+void use(int*);
+void array2d(int idx) {
+  int buffer[10][5]; // expected-warning{{'buffer' is an unsafe buffer that 
does not perform bounds checks}}
+  use(buffer[idx]);  // expected-note{{used in buffer access here}} \
+  // debug-note{{safe buffers debug: failed to produce fixit for 'buffer' : 
has an unclaimed use}}
+}

``




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


[clang] [-Wunsafe-buffer-usage] Fix debug notes for unclaimed DREs (PR #80787)

2024-02-05 Thread via cfe-commits

https://github.com/jkorous-apple created 
https://github.com/llvm/llvm-project/pull/80787

Debug notes for unclaimed DeclRefExpr should report any DRE of an unsafe 
variable that is not covered by a Fixable (i. e. fixit for the particular AST 
pattern isn't implemented for whatever reason). Currently not all unclaimed 
DeclRefExpr-s are reported which is a bug. The debug notes report only those 
DREs where the referred VarDecl has at least one other DeclRefExpr which is 
claimed (covered by a fixit). If there is an unsafe VarDecl that has exactly 
one DRE and the DRE isn't claimed then the debug note about missing fixit won't 
be emitted. That is because the debug note is emitted from within a loop over 
set of successfully matched FixableGadgets which by-definition is missing those 
DRE that are not matched at all.

The new code simply iterates over all unsafe VarDecls and all of their 
unclaimed DREs.

>From 90e7145fe0133828b4abc16730b9786fc68df8b9 Mon Sep 17 00:00:00 2001
From: Jan Korous 
Date: Mon, 5 Feb 2024 18:21:50 -0800
Subject: [PATCH] [-Wunsafe-buffer-usage] Fix debug notes for unclaimed DREs

Debug notes for unclaimed DeclRefExpr should report any DRE of an unsafe 
variable that is not covered by a Fixable (i. e. fixit for the particular AST 
pattern isn't implemented for whatever reason).
Currently not all unclaimed DeclRefExpr-s are reported which is a bug. The 
debug notes report only those DREs where the referred VarDecl has at least one 
other DeclRefExpr which is claimed (covered by a fixit).
If there is an unsafe VarDecl that has exactly one DRE and the DRE isn't 
claimed then the debug note about missing fixit won't be emitted.
That is because the debug note is emitted from within a loop over set of 
successfully matched FixableGadgets which by-definition is missing those DRE 
that are not matched at all.

The new code simply iterates over all unsafe VarDecls and all of their 
unclaimed DREs.
---
 clang/lib/Analysis/UnsafeBufferUsage.cpp  | 33 +++
 .../warn-unsafe-buffer-usage-debug.cpp|  7 
 2 files changed, 27 insertions(+), 13 deletions(-)

diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 823cd2a7b99691..6feff1d508e673 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -2870,19 +2870,6 @@ void clang::checkUnsafeBufferUsage(const Decl *D,
 #endif
 it = FixablesForAllVars.byVar.erase(it);
   } else if (Tracker.hasUnclaimedUses(it->first)) {
-#ifndef NDEBUG
-auto AllUnclaimed = Tracker.getUnclaimedUses(it->first);
-for (auto UnclaimedDRE : AllUnclaimed) {
-std::string UnclaimedUseTrace =
-getDREAncestorString(UnclaimedDRE, D->getASTContext());
-
-Handler.addDebugNoteForVar(
-it->first, UnclaimedDRE->getBeginLoc(),
-("failed to produce fixit for '" + it->first->getNameAsString() +
- "' : has an unclaimed use\nThe unclaimed DRE trace: " +
- UnclaimedUseTrace));
-}
-#endif
 it = FixablesForAllVars.byVar.erase(it);
   } else if (it->first->isInitCapture()) {
 #ifndef NDEBUG
@@ -2897,6 +2884,26 @@ void clang::checkUnsafeBufferUsage(const Decl *D,
 }
   }
 
+#ifndef NDEBUG
+  for (const auto& it : UnsafeOps.byVar) {
+const VarDecl* const UnsafeVD = it.first;
+auto UnclaimedDREs = Tracker.getUnclaimedUses(UnsafeVD);
+if (UnclaimedDREs.empty())
+  continue;
+const auto UnfixedVDName = UnsafeVD->getNameAsString();
+for (const clang::DeclRefExpr* UnclaimedDRE : UnclaimedDREs) {
+  std::string UnclaimedUseTrace =
+  getDREAncestorString(UnclaimedDRE, D->getASTContext());
+
+  Handler.addDebugNoteForVar(
+  UnsafeVD, UnclaimedDRE->getBeginLoc(),
+  ("failed to produce fixit for '" + UnfixedVDName +
+"' : has an unclaimed use\nThe unclaimed DRE trace: " +
+UnclaimedUseTrace));
+}
+  }
+#endif
+
   // Fixpoint iteration for pointer assignments
   using DepMapTy = DenseMap>;
   DepMapTy DependenciesMap{};
diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-debug.cpp 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-debug.cpp
index e08f70d97e3912..5fff0854d45467 100644
--- a/clang/test/SemaCXX/warn-unsafe-buffer-usage-debug.cpp
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-debug.cpp
@@ -98,3 +98,10 @@ void test_struct_claim_use() {
   x[6] = 8;  // expected-warning{{unsafe buffer access}}
   x++;  // expected-warning{{unsafe pointer arithmetic}}
 }
+
+void use(int*);
+void array2d(int idx) {
+  int buffer[10][5]; // expected-warning{{'buffer' is an unsafe buffer that 
does not perform bounds checks}}
+  use(buffer[idx]);  // expected-note{{used in buffer access here}} \
+  // debug-note{{safe buffers debug: failed to produce fixit for 'buffer' : 
has an unclaimed use}}
+}

___
cfe-commits mailing list

[clang] [clang][Darwin] Remove legacy framework search path logic in the frontend (PR #75841)

2024-02-05 Thread Brad Smith via cfe-commits

brad0 wrote:

Ping.

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


[clang] [Driver] Check the environment version except wasm case. (PR #80783)

2024-02-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: None (ZijunZhaoCCK)


Changes

Add isWasm() check for here: 
https://github.com/llvm/llvm-project/pull/78655#issuecomment-1928075569

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


1 Files Affected:

- (modified) clang/lib/Driver/Driver.cpp (+12-10) 


``diff
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 29db9543f36553..04d02ea500d19f 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -1443,16 +1443,18 @@ Compilation *Driver::BuildCompilation(ArrayRef ArgList) {
   const ToolChain  = getToolChain(
   *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
 
-  // Check if the environment version is valid.
-  llvm::Triple Triple = TC.getTriple();
-  StringRef TripleVersionName = Triple.getEnvironmentVersionString();
-  StringRef TripleObjectFormat =
-  Triple.getObjectFormatTypeName(Triple.getObjectFormat());
-  if (Triple.getEnvironmentVersion().empty() && TripleVersionName != "" &&
-  TripleVersionName != TripleObjectFormat) {
-Diags.Report(diag::err_drv_triple_version_invalid)
-<< TripleVersionName << TC.getTripleString();
-ContainsError = true;
+  // Check if the environment version is valid except wasm case.
+  if (!TC.getTriple().isWasm()) {
+llvm::Triple Triple = TC.getTriple();
+StringRef TripleVersionName = Triple.getEnvironmentVersionString();
+StringRef TripleObjectFormat =
+Triple.getObjectFormatTypeName(Triple.getObjectFormat());
+if (Triple.getEnvironmentVersion().empty() && TripleVersionName != "" &&
+TripleVersionName != TripleObjectFormat) {
+  Diags.Report(diag::err_drv_triple_version_invalid)
+  << TripleVersionName << TC.getTripleString();
+  ContainsError = true;
+}
   }
 
   // Report warning when arm64EC option is overridden by specified target

``




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


[clang] [Driver] Check the environment version except wasm case. (PR #80783)

2024-02-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (ZijunZhaoCCK)


Changes

Add isWasm() check for here: 
https://github.com/llvm/llvm-project/pull/78655#issuecomment-1928075569

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


1 Files Affected:

- (modified) clang/lib/Driver/Driver.cpp (+12-10) 


``diff
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 29db9543f3655..04d02ea500d19 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -1443,16 +1443,18 @@ Compilation *Driver::BuildCompilation(ArrayRef ArgList) {
   const ToolChain  = getToolChain(
   *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
 
-  // Check if the environment version is valid.
-  llvm::Triple Triple = TC.getTriple();
-  StringRef TripleVersionName = Triple.getEnvironmentVersionString();
-  StringRef TripleObjectFormat =
-  Triple.getObjectFormatTypeName(Triple.getObjectFormat());
-  if (Triple.getEnvironmentVersion().empty() && TripleVersionName != "" &&
-  TripleVersionName != TripleObjectFormat) {
-Diags.Report(diag::err_drv_triple_version_invalid)
-<< TripleVersionName << TC.getTripleString();
-ContainsError = true;
+  // Check if the environment version is valid except wasm case.
+  if (!TC.getTriple().isWasm()) {
+llvm::Triple Triple = TC.getTriple();
+StringRef TripleVersionName = Triple.getEnvironmentVersionString();
+StringRef TripleObjectFormat =
+Triple.getObjectFormatTypeName(Triple.getObjectFormat());
+if (Triple.getEnvironmentVersion().empty() && TripleVersionName != "" &&
+TripleVersionName != TripleObjectFormat) {
+  Diags.Report(diag::err_drv_triple_version_invalid)
+  << TripleVersionName << TC.getTripleString();
+  ContainsError = true;
+}
   }
 
   // Report warning when arm64EC option is overridden by specified target

``




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


[clang] [Driver] Check the environment version except wasm case. (PR #80783)

2024-02-05 Thread via cfe-commits

https://github.com/ZijunZhaoCCK created 
https://github.com/llvm/llvm-project/pull/80783

Add isWasm() check for here: 
https://github.com/llvm/llvm-project/pull/78655#issuecomment-1928075569

>From 84506beecc20a064a5c895cf5c04135118da6606 Mon Sep 17 00:00:00 2001
From: zijunzhao 
Date: Tue, 6 Feb 2024 01:58:58 +
Subject: [PATCH] [Driver] Check the environment version except wasm case.

---
 clang/lib/Driver/Driver.cpp | 22 --
 1 file changed, 12 insertions(+), 10 deletions(-)

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 29db9543f3655..04d02ea500d19 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -1443,16 +1443,18 @@ Compilation *Driver::BuildCompilation(ArrayRef ArgList) {
   const ToolChain  = getToolChain(
   *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
 
-  // Check if the environment version is valid.
-  llvm::Triple Triple = TC.getTriple();
-  StringRef TripleVersionName = Triple.getEnvironmentVersionString();
-  StringRef TripleObjectFormat =
-  Triple.getObjectFormatTypeName(Triple.getObjectFormat());
-  if (Triple.getEnvironmentVersion().empty() && TripleVersionName != "" &&
-  TripleVersionName != TripleObjectFormat) {
-Diags.Report(diag::err_drv_triple_version_invalid)
-<< TripleVersionName << TC.getTripleString();
-ContainsError = true;
+  // Check if the environment version is valid except wasm case.
+  if (!TC.getTriple().isWasm()) {
+llvm::Triple Triple = TC.getTriple();
+StringRef TripleVersionName = Triple.getEnvironmentVersionString();
+StringRef TripleObjectFormat =
+Triple.getObjectFormatTypeName(Triple.getObjectFormat());
+if (Triple.getEnvironmentVersion().empty() && TripleVersionName != "" &&
+TripleVersionName != TripleObjectFormat) {
+  Diags.Report(diag::err_drv_triple_version_invalid)
+  << TripleVersionName << TC.getTripleString();
+  ContainsError = true;
+}
   }
 
   // Report warning when arm64EC option is overridden by specified target

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-02-05 Thread Alex Hoppen via cfe-commits


@@ -538,11 +565,254 @@ std::optional checkName(const NamedDecl 
,
 Conflict->getLocation().printToString(ASTCtx.getSourceManager())};
 }
   }
-  if (Result)
+  if (Result) {
 InvalidNameMetric.record(1, toString(Result->K));
+return makeError(*Result);
+  }
+  return std::nullopt;
+}
+
+bool isMatchingSelectorName(const syntax::Token , const syntax::Token 
,
+const SourceManager ,
+llvm::StringRef SelectorName) {
+  if (SelectorName.empty())
+return Cur.kind() == tok::colon;
+  return Cur.kind() == tok::identifier && Next.kind() == tok::colon &&
+ Cur.text(SM) == SelectorName &&
+ // We require the selector name and : to be contiguous to avoid
+ // potential conflicts with ternary expression.
+ //
+ // e.g. support `foo:` but not `foo :`.
+ Cur.endLocation() == Next.location();
+}
+
+bool isSelectorLike(const syntax::Token , const syntax::Token ) {
+  return Cur.kind() == tok::identifier && Next.kind() == tok::colon &&
+ // We require the selector name and : to be contiguous.
+ // e.g. support `foo:` but not `foo :`.
+ Cur.endLocation() == Next.location();
+}
+
+bool parseMessageExpression(llvm::ArrayRef Tokens,
+const SourceManager , unsigned Index,
+unsigned Last, Selector Sel,
+std::vector ) {
+
+  unsigned NumArgs = Sel.getNumArgs();
+  llvm::SmallVector Closes;
+  SelectorPieces.clear();
+  while (Index < Last) {
+const auto  = Tokens[Index];
+
+if (Closes.empty()) {
+  auto PieceCount = SelectorPieces.size();
+  if (PieceCount < NumArgs &&
+  isMatchingSelectorName(Tok, Tokens[Index + 1], SM,
+ Sel.getNameForSlot(PieceCount))) {
+// If 'foo:' instead of ':' (empty selector), we need to skip the ':'
+// token after the name.
+if (!Sel.getNameForSlot(PieceCount).empty()) {
+  ++Index;
+}
+SelectorPieces.push_back(
+halfOpenToRange(SM, Tok.range(SM).toCharRange(SM)));
+continue;
+  }
+  // If we've found all pieces but the current token looks like another
+  // selector piece, it means the method being renamed is a strict prefix 
of
+  // the selector we've found - should be skipped.
+  if (SelectorPieces.size() >= NumArgs &&
+  isSelectorLike(Tok, Tokens[Index + 1]))
+return false;
+}
+
+switch (Tok.kind()) {
+case tok::l_square:
+  Closes.push_back(']');
+  break;
+case tok::l_paren:
+  Closes.push_back(')');
+  break;
+case tok::l_brace:
+  Closes.push_back('}');
+  break;
+case tok::r_square:
+  if (Closes.empty())
+return SelectorPieces.size() == NumArgs;
+
+  if (Closes.back() != ']')
+return false;
+  Closes.pop_back();
+  break;
+case tok::r_paren:
+  if (Closes.empty() || Closes.back() != ')')
+return false;
+  Closes.pop_back();
+  break;
+case tok::r_brace:
+  if (Closes.empty() || Closes.back() != '}')
+return false;
+  Closes.pop_back();
+  break;
+case tok::semi:
+  // top level ; ends all statements.
+  if (Closes.empty())
+return false;
+  break;
+default:
+  break;
+}
+
+++Index;
+  }
+  return false;
+}
+
+/// Collects all ranges of the given identifier/selector in the source code.
+///
+/// If a selector is given, this does a full lex of the given source code in
+/// order to identify all selector fragments (e.g. in method exprs/decls) since
+/// they are non-contiguous.
+std::vector collectRenameIdentifierRanges(
+llvm::StringRef Identifier, llvm::StringRef Content,
+const LangOptions , std::optional Selector) {
+  std::vector Ranges;
+  if (!Selector) {
+auto IdentifierRanges =
+collectIdentifierRanges(Identifier, Content, LangOpts);
+for (const auto  : IdentifierRanges)
+  Ranges.emplace_back(R);
+return Ranges;
+  }
+  // FIXME: InMemoryFileAdapter crashes unless the buffer is null terminated!
+  std::string NullTerminatedCode = Content.str();
+  SourceManagerForFile FileSM("mock_file_name.cpp", NullTerminatedCode);
+  auto  = FileSM.get();
+
+  // We track parens and braces to ensure that we don't accidentally try 
parsing
+  // a method declaration or definition which isn't at the top level or similar
+  // looking expressions (e.g. an @selector() expression).
+  unsigned ParenCount = 0;
+  unsigned BraceCount = 0;
+  unsigned NumArgs = Selector->getNumArgs();
+
+  std::vector SelectorPieces;
+  auto Tokens = syntax::tokenize(SM.getMainFileID(), SM, LangOpts);

ahoppen wrote:

I don’t think it’s too bad to force that onto the caller. AFAICT we have two 
calls to `collectRenameIdentifierRanges` at the moment, one of which already 
has the tokens and one 

[clang] [clang] Add zero-initialization for fixed point types (PR #80781)

2024-02-05 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff cf401f72e1b5aa6be0719ab45c95c10ea06bec9a 
916a10f1cebbb339dec98bd18c945b63991190f1 -- 
clang/test/CodeGenCXX/fixed-point-zero-init.cpp clang/lib/AST/ExprConstant.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 089bc20945..79541ff8ea 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -11427,9 +11427,7 @@ class FixedPointExprEvaluator
 return true;
   }
 
-  bool ZeroInitialization(const Expr *E) {
-return Success(0, E);
-  }
+  bool ZeroInitialization(const Expr *E) { return Success(0, E); }
 
   
//======//
   //Visitor Methods

``




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


[clang] [clang] Match -isysroot behaviour with system compiler on Darwin (PR #80524)

2024-02-05 Thread Daniel Rodríguez Troitiño via cfe-commits

drodriguez wrote:

I agree with Dmitry in that it would be preferred to have the system compiler 
behaviour until the system compiler actually changes.

I have tried again with Xcode 14.3.1 (released almost 1 year ago), which 
includes `include/c++/v1` side by side with the compiler, and for it, passing 
`-isysroot` still overrides the side by side path.

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


[clang] [clang] Add zero-initialization for fixed point types (PR #80781)

2024-02-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (PiJoules)


Changes



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


2 Files Affected:

- (modified) clang/lib/AST/ExprConstant.cpp (+4) 
- (added) clang/test/CodeGenCXX/fixed-point-zero-init.cpp (+9) 


``diff
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 63453890d9879..089bc2094567f 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -11427,6 +11427,10 @@ class FixedPointExprEvaluator
 return true;
   }
 
+  bool ZeroInitialization(const Expr *E) {
+return Success(0, E);
+  }
+
   
//======//
   //Visitor Methods
   
//======//
diff --git a/clang/test/CodeGenCXX/fixed-point-zero-init.cpp 
b/clang/test/CodeGenCXX/fixed-point-zero-init.cpp
new file mode 100644
index 0..9a7a6600fe556
--- /dev/null
+++ b/clang/test/CodeGenCXX/fixed-point-zero-init.cpp
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -ffixed-point -S -emit-llvm %s -o - | FileCheck %s
+
+// CHECK: @_ZL1a = internal constant [2 x i32] zeroinitializer
+constexpr _Accum a[2] = {};
+
+void func2(const _Accum *);
+void func() {
+  func2(a);
+}

``




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


[clang-tools-extra] [llvm] [clang] [concepts] Extract function template pack arguments from the current instantiation if possible (PR #80594)

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

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


[clang] 2c2d291 - [concepts] Extract function template pack arguments from the current instantiation if possible (#80594)

2024-02-05 Thread via cfe-commits

Author: Younan Zhang
Date: 2024-02-06T09:59:16+08:00
New Revision: 2c2d291b4568381999442e47fc77f949f19be0bc

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

LOG: [concepts] Extract function template pack arguments from the current 
instantiation if possible (#80594)

Before the constraint substitution, we employ
`getTemplateInstantiationArgs`, which in turn attempts to inspect
`TemplateArgument`s from the function template. For parameter packs from
their parent contexts, we used to extract the arguments from the
specialization type, in which could result in non-canonical argument
types e.g. `PackExpansionType`.

This may break the contract that, during a tree transformation, in
`TreeTransform::TryExpandParameterPacks`, the corresponding
`TemplateArgument`s for an `UnexpandedParameterPack` are expected to be
of `Pack` kinds if we're expanding template parameters.

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/test/SemaTemplate/concepts-out-of-line-def.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3596109bf044f..4d57ea4fd55b8 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -197,6 +197,9 @@ Bug Fixes to C++ Support
   Fixes (`#67976 `_)
 - Fix crash and diagnostic with const qualified member operator new.
   Fixes (`#79748 `_)
+- Fixed a crash where substituting into a requires-expression that involves 
parameter packs
+  during the equivalence determination of two constraint expressions.
+  (`#72557 `_)
 - Fix a crash when specializing an out-of-line member function with a default
   parameter where we did an incorrect specialization of the initialization of
   the default parameter.

diff  --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index e5999fa50117e..6d59180bc446d 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -241,10 +241,38 @@ Response HandleFunctionTemplateDecl(const 
FunctionTemplateDecl *FTD,
 
 while (const Type *Ty = NNS ? NNS->getAsType() : nullptr) {
   if (NNS->isInstantiationDependent()) {
-if (const auto *TSTy = Ty->getAs())
+if (const auto *TSTy = Ty->getAs()) {
+  ArrayRef Arguments = TSTy->template_arguments();
+  // Prefer template arguments from the injected-class-type if 
possible.
+  // For example,
+  // ```cpp
+  // template  struct S {
+  //   template  void foo();
+  // };
+  // template  template 
+  //   ^ InjectedTemplateArgs
+  //   They're of kind TemplateArgument::Pack, not of
+  //   TemplateArgument::Type.
+  // void S::foo() {}
+  //^^^
+  //TSTy->template_arguments() (which are of PackExpansionType)
+  // ```
+  // This meets the contract in
+  // TreeTransform::TryExpandParameterPacks that the template arguments
+  // for unexpanded parameters should be of a Pack kind.
+  if (TSTy->isCurrentInstantiation()) {
+auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl();
+if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
+  Arguments = CTD->getInjectedTemplateArgs();
+else if (auto *Specialization =
+ dyn_cast(RD))
+  Arguments =
+  Specialization->getTemplateInstantiationArgs().asArray();
+  }
   Result.addOuterTemplateArguments(
-  const_cast(FTD), 
TSTy->template_arguments(),
+  const_cast(FTD), Arguments,
   /*Final=*/false);
+}
   }
 
   NNS = NNS->getPrefix();

diff  --git a/clang/test/SemaTemplate/concepts-out-of-line-def.cpp 
b/clang/test/SemaTemplate/concepts-out-of-line-def.cpp
index b6fea2e0b4b31..0142efcdc3ee8 100644
--- a/clang/test/SemaTemplate/concepts-out-of-line-def.cpp
+++ b/clang/test/SemaTemplate/concepts-out-of-line-def.cpp
@@ -581,3 +581,21 @@ void S::test(T target, U... value)
   }
 {}
 } // namespace GH74447
+
+namespace GH72557 {
+
+template 
+concept IsAnyOf = true;
+
+template  struct DerivedCollection {
+  template 
+requires IsAnyOf
+  unsigned long index();
+};
+
+template 
+template 
+  requires IsAnyOf
+unsigned long DerivedCollection::index() {}
+
+} // namespace GH72557



___

[clang] [clang] Add zero-initialization for fixed point types (PR #80781)

2024-02-05 Thread via cfe-commits

https://github.com/PiJoules created 
https://github.com/llvm/llvm-project/pull/80781

None

>From 916a10f1cebbb339dec98bd18c945b63991190f1 Mon Sep 17 00:00:00 2001
From: Leonard Chan 
Date: Mon, 5 Feb 2024 17:58:08 -0800
Subject: [PATCH] [clang] Add zero-initialization for fixed point types

---
 clang/lib/AST/ExprConstant.cpp  | 4 
 clang/test/CodeGenCXX/fixed-point-zero-init.cpp | 9 +
 2 files changed, 13 insertions(+)
 create mode 100644 clang/test/CodeGenCXX/fixed-point-zero-init.cpp

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 63453890d9879..089bc2094567f 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -11427,6 +11427,10 @@ class FixedPointExprEvaluator
 return true;
   }
 
+  bool ZeroInitialization(const Expr *E) {
+return Success(0, E);
+  }
+
   
//======//
   //Visitor Methods
   
//======//
diff --git a/clang/test/CodeGenCXX/fixed-point-zero-init.cpp 
b/clang/test/CodeGenCXX/fixed-point-zero-init.cpp
new file mode 100644
index 0..9a7a6600fe556
--- /dev/null
+++ b/clang/test/CodeGenCXX/fixed-point-zero-init.cpp
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -ffixed-point -S -emit-llvm %s -o - | FileCheck %s
+
+// CHECK: @_ZL1a = internal constant [2 x i32] zeroinitializer
+constexpr _Accum a[2] = {};
+
+void func2(const _Accum *);
+void func() {
+  func2(a);
+}

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


[clang] [WebAssembly] Add tests for generic CPU config (PR #80775)

2024-02-05 Thread Heejin Ahn via cfe-commits

https://github.com/aheejin updated 
https://github.com/llvm/llvm-project/pull/80775

>From dbb74ca85ef047260a2820f6d470448279ea44f4 Mon Sep 17 00:00:00 2001
From: Heejin Ahn 
Date: Tue, 6 Feb 2024 00:51:40 +
Subject: [PATCH 1/2] [WebAssembly] Add tests for generic CPU config

This adds tests for `generic` cpu configuration. We had tests for `mvp`
and `bleeding-edge` configs but not `generic`.
---
 clang/test/Driver/wasm-features.c |  6 ++
 .../test/Preprocessor/wasm-target-features.c  | 21 +++
 2 files changed, 27 insertions(+)

diff --git a/clang/test/Driver/wasm-features.c 
b/clang/test/Driver/wasm-features.c
index 1a43361a4a108..33058051f67eb 100644
--- a/clang/test/Driver/wasm-features.c
+++ b/clang/test/Driver/wasm-features.c
@@ -4,6 +4,7 @@
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s 2>&1 | FileCheck %s 
-check-prefix=DEFAULT
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mcpu=mvp 2>&1 | 
FileCheck %s -check-prefix=MVP
+// RUN: %clang --target=wasm32-unknown-unknown -### %s -mcpu=generic 2>&1 | 
FileCheck %s -check-prefix=GENERIC
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mcpu=bleeding-edge 
2>&1 | FileCheck %s -check-prefix=BLEEDING-EDGE
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mbulk-memory 2>&1 | 
FileCheck %s -check-prefix=BULK-MEMORY
@@ -13,6 +14,7 @@
 // NO-BULK-MEMORY: "-target-feature" "-bulk-memory"
 // DEFAULT-NOT: "-target-feature" "-bulk-memory"
 // MVP-NOT: "-target-feature" "+bulk-memory"
+// GENERIC-NOT: "-target-feature" "+bulk-memory"
 // BLEEDING-EDGE-NOT: "-target-feature" "-bulk-memory"
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mmutable-globals 2>&1 
| FileCheck %s -check-prefix=MUTABLE-GLOBALS
@@ -22,6 +24,7 @@
 // NO-MUTABLE-GLOBALS: "-target-feature" "-mutable-globals"
 // DEFAULT-NOT: "-target-feature" "-mutable-globals"
 // MVP-NOT: "-target-feature" "+mutable-globals"
+// GENERIC-NOT: "-target-feature" "-mutable-globals"
 // BLEEDING-EDGE-NOT: "-target-feature" "-mutable-globals"
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -msign-ext 2>&1 | 
FileCheck %s -check-prefix=SIGN-EXT
@@ -31,6 +34,7 @@
 // NO-SIGN-EXT: "-target-feature" "-sign-ext"
 // DEFAULT-NOT: "-target-feature" "-sign-ext"
 // MVP-NOT: "-target-feature" "+sign-ext"
+// GENERIC-NOT: "-target-feature" "-sign-ext"
 // BLEEDING-EDGE-NOT: "-target-feature" "-sign-ext"
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mnontrapping-fptoint 
2>&1 | FileCheck %s -check-prefix=NONTRAPPING-FPTOINT
@@ -40,6 +44,7 @@
 // NO-NONTRAPPING-FPTOINT: "-target-feature" "-nontrapping-fptoint"
 // DEFAULT-NOT: "-target-feature" "-nontrapping-fptoint"
 // MVP-NOT: "-target-feature" "+nontrapping-fptoint"
+// GENERIC-NOT: "-target-feature" "+nontrapping-fptoint"
 // BLEEDING-EDGE-NOT: "-target-feature" "-nontrapping-fptoint"
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mmultimemory 2>&1 | 
FileCheck %s -check-prefix=MULTIMEMORY
@@ -49,4 +54,5 @@
 // NO-MULTIMEMORY: "-target-feature" "-multimemory"
 // DEFAULT-NOT: "-target-feature" "-multimemory"
 // MVP-NOT: "-target-feature" "+multimemory"
+// GENERIC-NOT: "-target-feature" "+multimemory"
 // BLEEDING-EDGE-NOT: "-target-feature" "-multimemory"
diff --git a/clang/test/Preprocessor/wasm-target-features.c 
b/clang/test/Preprocessor/wasm-target-features.c
index c225e226b69ba..17f75c83ef734 100644
--- a/clang/test/Preprocessor/wasm-target-features.c
+++ b/clang/test/Preprocessor/wasm-target-features.c
@@ -145,6 +145,27 @@
 // MVP-NOT:#define __wasm_extended_const__
 // MVP-NOT:#define __wasm_multimemory__
 
+// RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: -target wasm32-unknown-unknown -mcpu=generic \
+// RUN:   | FileCheck %s -check-prefix=GENERIC
+// RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: -target wasm64-unknown-unknown -mcpu=generic \
+// RUN:   | FileCheck %s -check-prefix=GENERIC
+//
+// GENERIC-DAG:#define __wasm_sign_ext__ 1{{$}}
+// GENERIC-DAG:#define __wasm_mutable_globals__ 1{{$}}
+// GENERIC-NOT:#define __wasm_nontrapping_fptoint__ 1{{$}}
+// GENERIC-NOT:#define __wasm_bulk_memory__ 1{{$}}
+// GENERIC-NOT:#define __wasm_simd128__ 1{{$}}
+// GENERIC-NOT:#define __wasm_atomics__ 1{{$}}
+// GENERIC-NOT:#define __wasm_tail_call__ 1{{$}}
+// GENERIC-NOT:#define __wasm_multimemory__ 1{{$}}
+// GENERIC-NOT:#define __wasm_unimplemented_simd128__ 1{{$}}
+// GENERIC-NOT:#define __wasm_exception_handling__ 1{{$}}
+// GENERIC-NOT:#define __wasm_multivalue__ 1{{$}}
+// GENERIC-NOT:#define __wasm_reference_types__ 1{{$}}
+// GENERIC-NOT:#define __wasm_extended_const__ 1{{$}}
+
 // RUN: %clang -E -dM %s -o - 2>&1 \
 // RUN: -target wasm32-unknown-unknown -mcpu=bleeding-edge \
 // RUN:   | FileCheck %s -check-prefix=BLEEDING-EDGE

>From d1e55d8e117bf1a294746d483495018b21f83757 Mon Sep 17 00:00:00 2001
From: Heejin Ahn 
Date: Tue, 6 Feb 2024 01:07:53 +
Subject: [PATCH 2/2] Delete unnecessary line

---
 

[clang] [RISCV] Add -march string as Module metadata in IR. (PR #80760)

2024-02-05 Thread Jessica Clarke via cfe-commits

jrtc27 wrote:

My thoughts on this in the past have been:

1. target-abi should really be a target-independent thing we record; its 
meaning depends on the target, but the ABI exists throughout LLVM as a concept 
regardless of the target
2. module-level target features in general likely should be the thing we 
record, corresponding to the subtarget, not some target-dependent 
representation, as, again, all targets have that throughout LLVM and just use 
them to a greater or lesser extent

RISC-V is the most sensitive to this, but it's just a symptom of not having the 
general mechanism in place, and I'm not a huge fan of adding ad-hoc stuff 
specific to RISC-V rather than addressing the underlying problem. Other targets 
just care less upstream today so get away with this lack of information in 
practice, but that won't always true (e.g. I believe we need this information 
on Morello (CHERI+AArch64 prototype) downstream, not just for CHERI-RISC-V).

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


[clang] [WebAssembly] Add tests for generic CPU config (PR #80775)

2024-02-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Heejin Ahn (aheejin)


Changes

This adds tests for `generic` cpu configuration. We had tests for `mvp` and 
`bleeding-edge` configs but not `generic`.

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


2 Files Affected:

- (modified) clang/test/Driver/wasm-features.c (+6) 
- (modified) clang/test/Preprocessor/wasm-target-features.c (+21) 


``diff
diff --git a/clang/test/Driver/wasm-features.c 
b/clang/test/Driver/wasm-features.c
index 1a43361a4a108..33058051f67eb 100644
--- a/clang/test/Driver/wasm-features.c
+++ b/clang/test/Driver/wasm-features.c
@@ -4,6 +4,7 @@
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s 2>&1 | FileCheck %s 
-check-prefix=DEFAULT
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mcpu=mvp 2>&1 | 
FileCheck %s -check-prefix=MVP
+// RUN: %clang --target=wasm32-unknown-unknown -### %s -mcpu=generic 2>&1 | 
FileCheck %s -check-prefix=GENERIC
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mcpu=bleeding-edge 
2>&1 | FileCheck %s -check-prefix=BLEEDING-EDGE
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mbulk-memory 2>&1 | 
FileCheck %s -check-prefix=BULK-MEMORY
@@ -13,6 +14,7 @@
 // NO-BULK-MEMORY: "-target-feature" "-bulk-memory"
 // DEFAULT-NOT: "-target-feature" "-bulk-memory"
 // MVP-NOT: "-target-feature" "+bulk-memory"
+// GENERIC-NOT: "-target-feature" "+bulk-memory"
 // BLEEDING-EDGE-NOT: "-target-feature" "-bulk-memory"
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mmutable-globals 2>&1 
| FileCheck %s -check-prefix=MUTABLE-GLOBALS
@@ -22,6 +24,7 @@
 // NO-MUTABLE-GLOBALS: "-target-feature" "-mutable-globals"
 // DEFAULT-NOT: "-target-feature" "-mutable-globals"
 // MVP-NOT: "-target-feature" "+mutable-globals"
+// GENERIC-NOT: "-target-feature" "-mutable-globals"
 // BLEEDING-EDGE-NOT: "-target-feature" "-mutable-globals"
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -msign-ext 2>&1 | 
FileCheck %s -check-prefix=SIGN-EXT
@@ -31,6 +34,7 @@
 // NO-SIGN-EXT: "-target-feature" "-sign-ext"
 // DEFAULT-NOT: "-target-feature" "-sign-ext"
 // MVP-NOT: "-target-feature" "+sign-ext"
+// GENERIC-NOT: "-target-feature" "-sign-ext"
 // BLEEDING-EDGE-NOT: "-target-feature" "-sign-ext"
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mnontrapping-fptoint 
2>&1 | FileCheck %s -check-prefix=NONTRAPPING-FPTOINT
@@ -40,6 +44,7 @@
 // NO-NONTRAPPING-FPTOINT: "-target-feature" "-nontrapping-fptoint"
 // DEFAULT-NOT: "-target-feature" "-nontrapping-fptoint"
 // MVP-NOT: "-target-feature" "+nontrapping-fptoint"
+// GENERIC-NOT: "-target-feature" "+nontrapping-fptoint"
 // BLEEDING-EDGE-NOT: "-target-feature" "-nontrapping-fptoint"
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mmultimemory 2>&1 | 
FileCheck %s -check-prefix=MULTIMEMORY
@@ -49,4 +54,5 @@
 // NO-MULTIMEMORY: "-target-feature" "-multimemory"
 // DEFAULT-NOT: "-target-feature" "-multimemory"
 // MVP-NOT: "-target-feature" "+multimemory"
+// GENERIC-NOT: "-target-feature" "+multimemory"
 // BLEEDING-EDGE-NOT: "-target-feature" "-multimemory"
diff --git a/clang/test/Preprocessor/wasm-target-features.c 
b/clang/test/Preprocessor/wasm-target-features.c
index c225e226b69ba..17f75c83ef734 100644
--- a/clang/test/Preprocessor/wasm-target-features.c
+++ b/clang/test/Preprocessor/wasm-target-features.c
@@ -145,6 +145,27 @@
 // MVP-NOT:#define __wasm_extended_const__
 // MVP-NOT:#define __wasm_multimemory__
 
+// RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: -target wasm32-unknown-unknown -mcpu=generic \
+// RUN:   | FileCheck %s -check-prefix=GENERIC
+// RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: -target wasm64-unknown-unknown -mcpu=generic \
+// RUN:   | FileCheck %s -check-prefix=GENERIC
+//
+// GENERIC-DAG:#define __wasm_sign_ext__ 1{{$}}
+// GENERIC-DAG:#define __wasm_mutable_globals__ 1{{$}}
+// GENERIC-NOT:#define __wasm_nontrapping_fptoint__ 1{{$}}
+// GENERIC-NOT:#define __wasm_bulk_memory__ 1{{$}}
+// GENERIC-NOT:#define __wasm_simd128__ 1{{$}}
+// GENERIC-NOT:#define __wasm_atomics__ 1{{$}}
+// GENERIC-NOT:#define __wasm_tail_call__ 1{{$}}
+// GENERIC-NOT:#define __wasm_multimemory__ 1{{$}}
+// GENERIC-NOT:#define __wasm_unimplemented_simd128__ 1{{$}}
+// GENERIC-NOT:#define __wasm_exception_handling__ 1{{$}}
+// GENERIC-NOT:#define __wasm_multivalue__ 1{{$}}
+// GENERIC-NOT:#define __wasm_reference_types__ 1{{$}}
+// GENERIC-NOT:#define __wasm_extended_const__ 1{{$}}
+
 // RUN: %clang -E -dM %s -o - 2>&1 \
 // RUN: -target wasm32-unknown-unknown -mcpu=bleeding-edge \
 // RUN:   | FileCheck %s -check-prefix=BLEEDING-EDGE

``




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


[clang] [WebAssembly] Add tests for generic CPU config (PR #80775)

2024-02-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Heejin Ahn (aheejin)


Changes

This adds tests for `generic` cpu configuration. We had tests for `mvp` and 
`bleeding-edge` configs but not `generic`.

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


2 Files Affected:

- (modified) clang/test/Driver/wasm-features.c (+6) 
- (modified) clang/test/Preprocessor/wasm-target-features.c (+21) 


``diff
diff --git a/clang/test/Driver/wasm-features.c 
b/clang/test/Driver/wasm-features.c
index 1a43361a4a108..33058051f67eb 100644
--- a/clang/test/Driver/wasm-features.c
+++ b/clang/test/Driver/wasm-features.c
@@ -4,6 +4,7 @@
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s 2>&1 | FileCheck %s 
-check-prefix=DEFAULT
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mcpu=mvp 2>&1 | 
FileCheck %s -check-prefix=MVP
+// RUN: %clang --target=wasm32-unknown-unknown -### %s -mcpu=generic 2>&1 | 
FileCheck %s -check-prefix=GENERIC
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mcpu=bleeding-edge 
2>&1 | FileCheck %s -check-prefix=BLEEDING-EDGE
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mbulk-memory 2>&1 | 
FileCheck %s -check-prefix=BULK-MEMORY
@@ -13,6 +14,7 @@
 // NO-BULK-MEMORY: "-target-feature" "-bulk-memory"
 // DEFAULT-NOT: "-target-feature" "-bulk-memory"
 // MVP-NOT: "-target-feature" "+bulk-memory"
+// GENERIC-NOT: "-target-feature" "+bulk-memory"
 // BLEEDING-EDGE-NOT: "-target-feature" "-bulk-memory"
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mmutable-globals 2>&1 
| FileCheck %s -check-prefix=MUTABLE-GLOBALS
@@ -22,6 +24,7 @@
 // NO-MUTABLE-GLOBALS: "-target-feature" "-mutable-globals"
 // DEFAULT-NOT: "-target-feature" "-mutable-globals"
 // MVP-NOT: "-target-feature" "+mutable-globals"
+// GENERIC-NOT: "-target-feature" "-mutable-globals"
 // BLEEDING-EDGE-NOT: "-target-feature" "-mutable-globals"
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -msign-ext 2>&1 | 
FileCheck %s -check-prefix=SIGN-EXT
@@ -31,6 +34,7 @@
 // NO-SIGN-EXT: "-target-feature" "-sign-ext"
 // DEFAULT-NOT: "-target-feature" "-sign-ext"
 // MVP-NOT: "-target-feature" "+sign-ext"
+// GENERIC-NOT: "-target-feature" "-sign-ext"
 // BLEEDING-EDGE-NOT: "-target-feature" "-sign-ext"
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mnontrapping-fptoint 
2>&1 | FileCheck %s -check-prefix=NONTRAPPING-FPTOINT
@@ -40,6 +44,7 @@
 // NO-NONTRAPPING-FPTOINT: "-target-feature" "-nontrapping-fptoint"
 // DEFAULT-NOT: "-target-feature" "-nontrapping-fptoint"
 // MVP-NOT: "-target-feature" "+nontrapping-fptoint"
+// GENERIC-NOT: "-target-feature" "+nontrapping-fptoint"
 // BLEEDING-EDGE-NOT: "-target-feature" "-nontrapping-fptoint"
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mmultimemory 2>&1 | 
FileCheck %s -check-prefix=MULTIMEMORY
@@ -49,4 +54,5 @@
 // NO-MULTIMEMORY: "-target-feature" "-multimemory"
 // DEFAULT-NOT: "-target-feature" "-multimemory"
 // MVP-NOT: "-target-feature" "+multimemory"
+// GENERIC-NOT: "-target-feature" "+multimemory"
 // BLEEDING-EDGE-NOT: "-target-feature" "-multimemory"
diff --git a/clang/test/Preprocessor/wasm-target-features.c 
b/clang/test/Preprocessor/wasm-target-features.c
index c225e226b69ba..17f75c83ef734 100644
--- a/clang/test/Preprocessor/wasm-target-features.c
+++ b/clang/test/Preprocessor/wasm-target-features.c
@@ -145,6 +145,27 @@
 // MVP-NOT:#define __wasm_extended_const__
 // MVP-NOT:#define __wasm_multimemory__
 
+// RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: -target wasm32-unknown-unknown -mcpu=generic \
+// RUN:   | FileCheck %s -check-prefix=GENERIC
+// RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: -target wasm64-unknown-unknown -mcpu=generic \
+// RUN:   | FileCheck %s -check-prefix=GENERIC
+//
+// GENERIC-DAG:#define __wasm_sign_ext__ 1{{$}}
+// GENERIC-DAG:#define __wasm_mutable_globals__ 1{{$}}
+// GENERIC-NOT:#define __wasm_nontrapping_fptoint__ 1{{$}}
+// GENERIC-NOT:#define __wasm_bulk_memory__ 1{{$}}
+// GENERIC-NOT:#define __wasm_simd128__ 1{{$}}
+// GENERIC-NOT:#define __wasm_atomics__ 1{{$}}
+// GENERIC-NOT:#define __wasm_tail_call__ 1{{$}}
+// GENERIC-NOT:#define __wasm_multimemory__ 1{{$}}
+// GENERIC-NOT:#define __wasm_unimplemented_simd128__ 1{{$}}
+// GENERIC-NOT:#define __wasm_exception_handling__ 1{{$}}
+// GENERIC-NOT:#define __wasm_multivalue__ 1{{$}}
+// GENERIC-NOT:#define __wasm_reference_types__ 1{{$}}
+// GENERIC-NOT:#define __wasm_extended_const__ 1{{$}}
+
 // RUN: %clang -E -dM %s -o - 2>&1 \
 // RUN: -target wasm32-unknown-unknown -mcpu=bleeding-edge \
 // RUN:   | FileCheck %s -check-prefix=BLEEDING-EDGE

``




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


[clang] [WebAssembly] Add tests for generic CPU config (PR #80775)

2024-02-05 Thread Heejin Ahn via cfe-commits

https://github.com/aheejin created 
https://github.com/llvm/llvm-project/pull/80775

This adds tests for `generic` cpu configuration. We had tests for `mvp` and 
`bleeding-edge` configs but not `generic`.

>From dbb74ca85ef047260a2820f6d470448279ea44f4 Mon Sep 17 00:00:00 2001
From: Heejin Ahn 
Date: Tue, 6 Feb 2024 00:51:40 +
Subject: [PATCH] [WebAssembly] Add tests for generic CPU config

This adds tests for `generic` cpu configuration. We had tests for `mvp`
and `bleeding-edge` configs but not `generic`.
---
 clang/test/Driver/wasm-features.c |  6 ++
 .../test/Preprocessor/wasm-target-features.c  | 21 +++
 2 files changed, 27 insertions(+)

diff --git a/clang/test/Driver/wasm-features.c 
b/clang/test/Driver/wasm-features.c
index 1a43361a4a108..33058051f67eb 100644
--- a/clang/test/Driver/wasm-features.c
+++ b/clang/test/Driver/wasm-features.c
@@ -4,6 +4,7 @@
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s 2>&1 | FileCheck %s 
-check-prefix=DEFAULT
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mcpu=mvp 2>&1 | 
FileCheck %s -check-prefix=MVP
+// RUN: %clang --target=wasm32-unknown-unknown -### %s -mcpu=generic 2>&1 | 
FileCheck %s -check-prefix=GENERIC
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mcpu=bleeding-edge 
2>&1 | FileCheck %s -check-prefix=BLEEDING-EDGE
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mbulk-memory 2>&1 | 
FileCheck %s -check-prefix=BULK-MEMORY
@@ -13,6 +14,7 @@
 // NO-BULK-MEMORY: "-target-feature" "-bulk-memory"
 // DEFAULT-NOT: "-target-feature" "-bulk-memory"
 // MVP-NOT: "-target-feature" "+bulk-memory"
+// GENERIC-NOT: "-target-feature" "+bulk-memory"
 // BLEEDING-EDGE-NOT: "-target-feature" "-bulk-memory"
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mmutable-globals 2>&1 
| FileCheck %s -check-prefix=MUTABLE-GLOBALS
@@ -22,6 +24,7 @@
 // NO-MUTABLE-GLOBALS: "-target-feature" "-mutable-globals"
 // DEFAULT-NOT: "-target-feature" "-mutable-globals"
 // MVP-NOT: "-target-feature" "+mutable-globals"
+// GENERIC-NOT: "-target-feature" "-mutable-globals"
 // BLEEDING-EDGE-NOT: "-target-feature" "-mutable-globals"
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -msign-ext 2>&1 | 
FileCheck %s -check-prefix=SIGN-EXT
@@ -31,6 +34,7 @@
 // NO-SIGN-EXT: "-target-feature" "-sign-ext"
 // DEFAULT-NOT: "-target-feature" "-sign-ext"
 // MVP-NOT: "-target-feature" "+sign-ext"
+// GENERIC-NOT: "-target-feature" "-sign-ext"
 // BLEEDING-EDGE-NOT: "-target-feature" "-sign-ext"
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mnontrapping-fptoint 
2>&1 | FileCheck %s -check-prefix=NONTRAPPING-FPTOINT
@@ -40,6 +44,7 @@
 // NO-NONTRAPPING-FPTOINT: "-target-feature" "-nontrapping-fptoint"
 // DEFAULT-NOT: "-target-feature" "-nontrapping-fptoint"
 // MVP-NOT: "-target-feature" "+nontrapping-fptoint"
+// GENERIC-NOT: "-target-feature" "+nontrapping-fptoint"
 // BLEEDING-EDGE-NOT: "-target-feature" "-nontrapping-fptoint"
 
 // RUN: %clang --target=wasm32-unknown-unknown -### %s -mmultimemory 2>&1 | 
FileCheck %s -check-prefix=MULTIMEMORY
@@ -49,4 +54,5 @@
 // NO-MULTIMEMORY: "-target-feature" "-multimemory"
 // DEFAULT-NOT: "-target-feature" "-multimemory"
 // MVP-NOT: "-target-feature" "+multimemory"
+// GENERIC-NOT: "-target-feature" "+multimemory"
 // BLEEDING-EDGE-NOT: "-target-feature" "-multimemory"
diff --git a/clang/test/Preprocessor/wasm-target-features.c 
b/clang/test/Preprocessor/wasm-target-features.c
index c225e226b69ba..17f75c83ef734 100644
--- a/clang/test/Preprocessor/wasm-target-features.c
+++ b/clang/test/Preprocessor/wasm-target-features.c
@@ -145,6 +145,27 @@
 // MVP-NOT:#define __wasm_extended_const__
 // MVP-NOT:#define __wasm_multimemory__
 
+// RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: -target wasm32-unknown-unknown -mcpu=generic \
+// RUN:   | FileCheck %s -check-prefix=GENERIC
+// RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: -target wasm64-unknown-unknown -mcpu=generic \
+// RUN:   | FileCheck %s -check-prefix=GENERIC
+//
+// GENERIC-DAG:#define __wasm_sign_ext__ 1{{$}}
+// GENERIC-DAG:#define __wasm_mutable_globals__ 1{{$}}
+// GENERIC-NOT:#define __wasm_nontrapping_fptoint__ 1{{$}}
+// GENERIC-NOT:#define __wasm_bulk_memory__ 1{{$}}
+// GENERIC-NOT:#define __wasm_simd128__ 1{{$}}
+// GENERIC-NOT:#define __wasm_atomics__ 1{{$}}
+// GENERIC-NOT:#define __wasm_tail_call__ 1{{$}}
+// GENERIC-NOT:#define __wasm_multimemory__ 1{{$}}
+// GENERIC-NOT:#define __wasm_unimplemented_simd128__ 1{{$}}
+// GENERIC-NOT:#define __wasm_exception_handling__ 1{{$}}
+// GENERIC-NOT:#define __wasm_multivalue__ 1{{$}}
+// GENERIC-NOT:#define __wasm_reference_types__ 1{{$}}
+// GENERIC-NOT:#define __wasm_extended_const__ 1{{$}}
+
 // RUN: %clang -E -dM %s -o - 2>&1 \
 // RUN: -target wasm32-unknown-unknown -mcpu=bleeding-edge \
 // RUN:   | FileCheck %s -check-prefix=BLEEDING-EDGE

___
cfe-commits mailing list

[clang] [RISCV] Add -march string as Module metadata in IR. (PR #80760)

2024-02-05 Thread Craig Topper via cfe-commits

topperc wrote:

> I'm surprised only 1 test file needed the metadata updated as a result of 
> this change.

Maybe other tests are better about using regexes to hide the numbers?

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


[clang] [RISCV] Add -march string as Module metadata in IR. (PR #80760)

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

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

Thank you for this. I expect this to be a big help w/ the various target 
features bugs we've seen in LTO builds.

I'm surprised only 1 test file needed the metadata updated as a result of this 
change.

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


[lld] [clang] [compiler-rt] [libcxx] [clang-tools-extra] [mlir] [llvm] [openmp] [libc] [flang] [lldb] [Driver] Report invalid target triple versions for all environment types. (PR #78655)

2024-02-05 Thread via cfe-commits

ZijunZhaoCCK wrote:

> > > There's apparently also wasm32-wasi-preview2 and wasm32-wasi-pthread, 
> > > which I suppose are equally broken by this change.
> > 
> > 
> > Yes, I think so. I think adding these environment types in wasi-libc repo 
> > could help fix those errors.
> 
> If wasm can arbitrary environment types, it seems that we can opt out the 
> check for `isWasm()`. We define new environment types when they affect the 
> compiler behavior. If wasm arbitrary sets the environment, we should not 
> define a type for each one.

Okay, I will add this check.

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


[clang] Turn 'counted_by' into a type attribute and parse it into 'CountAttributedType' (PR #78000)

2024-02-05 Thread Yeoul Na via cfe-commits

rapidsna wrote:

> It's generally not a good idea to use sugar to represent constructs that are 
> semantically significant: anything that uses the canonical type will throw it 
> away. We try to avoid throwing away sugar in most cases, but we aren't always 
> successful.

> It's possible there are other considerations here (maybe it matters less if 
> the attribute is only relevant inside the definition?), but I'd like an 
> explanation of the tradeoffs.

Thanks @efriedma-quic! Yes, these are really good points. 

The main reason that we decided it to be a sugar type was that this type of 
attribute doesn't change the shape of the underlying type so we wanted such as 
`isa(BoundAttributedTy)` or `isa(BoundAttributedTy)` 
still holds true depending on the underlying canonical type (in the current 
implementation the attribute only applies to array type but it will be extended 
to support pointer type as well). And we figured that adding a sugar type might 
less disruptive to the rest of Clang code base compared to extending the 
existing Clang types.

But as you pointed out we encountered cases where the sugar wasn't preserved as 
it needed to be so we had to specially handle such cases in our own 
implementation, so we're open for other suggestions.

An alternative design could be to create new canonical types that inherit 
`IncompleteArrayType` or `PointerType` respectively so `isa` still holds, but 
unfortunately `IncompleteArrayType` is `final`. 

We could also add an additional field in the `IncompleteArrayType` class to 
contain the optional `count` expression, then the question is what we want to 
do for `ConstantArrayType` later when we like to have it count attribute as 
well (this could be potentially relevant for flexible array member-like array 
member with a constant size).

Similarly, we could add more fields to `PointerType` to contain the optional 
count expression (or upper bound expression) and necessary data. For this, we 
should be careful not to grow the size of `PointerType` by default, possibly by 
adding additional data as `TrailingObject`.

We haven't experimented these alternative designs so I'm curious about 
@AaronBallman's thoughts.

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


[clang] Consider aggregate bases when checking if an InitListExpr is constant (PR #80519)

2024-02-05 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 820f244aa92f11292e59440c9bc5afbdec395b20 
c630eee1f930c87d2c461de92271c02de220b290 -- clang/lib/AST/Expr.cpp 
clang/test/SemaCXX/compound-literal.cpp clang/unittests/AST/ASTExprTest.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/unittests/AST/ASTExprTest.cpp 
b/clang/unittests/AST/ASTExprTest.cpp
index 257ac9c55d..5ec6aea8ed 100644
--- a/clang/unittests/AST/ASTExprTest.cpp
+++ b/clang/unittests/AST/ASTExprTest.cpp
@@ -28,12 +28,14 @@ using clang::tooling::buildASTFromCode;
 
 static IntegerLiteral *createIntLiteral(ASTContext , uint32_t Value) {
   const int numBits = 32;
-  return IntegerLiteral::Create(Ctx, llvm::APInt(numBits, Value),
-Ctx.IntTy, {});
+  return IntegerLiteral::Create(Ctx, llvm::APInt(numBits, Value), Ctx.IntTy,
+{});
 }
 
-const CXXRecordDecl *getCXXRecordDeclNode(ASTUnit *AST, const std::string 
) {
-  auto Result = match(cxxRecordDecl(hasName(Name)).bind("record"), 
AST->getASTContext());
+const CXXRecordDecl *getCXXRecordDeclNode(ASTUnit *AST,
+  const std::string ) {
+  auto Result =
+  match(cxxRecordDecl(hasName(Name)).bind("record"), AST->getASTContext());
   EXPECT_FALSE(Result.empty());
   return Result[0].getNodeAs("record");
 }
@@ -89,9 +91,9 @@ TEST(ASTExpr, InitListIsConstantInitialized) {
   InitListExpr *BaseInit = new (Ctx) InitListExpr(Ctx, Loc, {}, Loc);
   BaseInit->setType(Ctx.getRecordType(Empty));
   Expr *Exprs[3] = {
-BaseInit,
-createIntLiteral(Ctx, 13),
-createIntLiteral(Ctx, 42),
+  BaseInit,
+  createIntLiteral(Ctx, 13),
+  createIntLiteral(Ctx, 42),
   };
   InitListExpr *FooInit = new (Ctx) InitListExpr(Ctx, Loc, Exprs, Loc);
   FooInit->setType(Ctx.getRecordType(Foo));

``




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


[clang] Consider aggregate bases when checking if an InitListExpr is constant (PR #80519)

2024-02-05 Thread Reid Kleckner via cfe-commits

https://github.com/rnk updated https://github.com/llvm/llvm-project/pull/80519

>From 6ab5ba3f970eaaea542fbed09cae17d3666df6b3 Mon Sep 17 00:00:00 2001
From: Reid Kleckner 
Date: Sat, 3 Feb 2024 00:18:42 +
Subject: [PATCH 1/3] wip

---
 clang/lib/AST/Expr.cpp  | 12 
 clang/test/SemaCXX/compound-literal.cpp | 20 
 2 files changed, 32 insertions(+)

diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index d665a08deb47e6..8852fadf79b9ac 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3342,6 +3342,18 @@ bool Expr::isConstantInitializer(ASTContext , bool 
IsForRef,
 if (ILE->getType()->isRecordType()) {
   unsigned ElementNo = 0;
   RecordDecl *RD = ILE->getType()->castAs()->getDecl();
+
+  // Check bases for C++17 aggregate initializers.
+  if (const auto *CXXRD = dyn_cast(RD)) {
+for (unsigned i = 0, e = CXXRD->getNumBases(); i < e; i++) {
+  if (ElementNo < ILE->getNumInits()) {
+const Expr *Elt = ILE->getInit(ElementNo++);
+if (!Elt->isConstantInitializer(Ctx, false, Culprit))
+  return false;
+  }
+}
+  }
+
   for (const auto *Field : RD->fields()) {
 // If this is a union, skip all the fields that aren't being 
initialized.
 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
diff --git a/clang/test/SemaCXX/compound-literal.cpp 
b/clang/test/SemaCXX/compound-literal.cpp
index 5957099de53af3..81f8b41ff0313e 100644
--- a/clang/test/SemaCXX/compound-literal.cpp
+++ b/clang/test/SemaCXX/compound-literal.cpp
@@ -3,6 +3,7 @@
 // RUN: %clang_cc1 -fsyntax-only -std=c++11 -verify -ast-dump %s > %t-11
 // RUN: FileCheck --input-file=%t-11 %s
 // RUN: FileCheck --input-file=%t-11 %s --check-prefix=CHECK-CXX11
+// RUN: %clang_cc1 -verify -std=c++17 %s
 
 // http://llvm.org/PR7905
 namespace PR7905 {
@@ -108,3 +109,22 @@ int computed_with_lambda = [] {
   return result;
 }();
 #endif
+
+#if __cplusplus >= 201703L
+namespace DynamicFileScopeLiteral {
+// This covers the case where we have a file-scope compound literal with a
+// non-constant initializer in C++. Previously, we had a bug where Clang forgot
+// to consider initializer list elements for bases.
+struct Empty {};
+struct Foo : Empty {
+  int x;
+  int y;
+};
+int f();
+Foo o = (Foo){
+  {},
+  1,
+  f() // expected-error {{initializer element is not a compile-time constant}}
+};
+}
+#endif

>From c630eee1f930c87d2c461de92271c02de220b290 Mon Sep 17 00:00:00 2001
From: Reid Kleckner 
Date: Mon, 5 Feb 2024 23:47:57 +
Subject: [PATCH 2/3] update comments, run test in past language modes, and add
 unit test

---
 clang/lib/AST/Expr.cpp  |  9 +++-
 clang/test/SemaCXX/compound-literal.cpp | 17 ---
 clang/unittests/AST/ASTExprTest.cpp | 66 ++---
 3 files changed, 75 insertions(+), 17 deletions(-)

diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 8852fadf79b9ac..9190995c1df20e 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3328,6 +3328,12 @@ bool Expr::isConstantInitializer(ASTContext , bool 
IsForRef,
DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
   }
   case InitListExprClass: {
+// C++ [temp.dep.expr]p2:
+//   The elements of an aggregate are:
+//   — for an array, the array elements in increasing subscript order, or
+//   — for a class, the direct base classes in declaration order, followed
+// by the direct non-static data members (11.4) that are not members of
+// an anonymous union, in declaration order.
 const InitListExpr *ILE = cast(this);
 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
 if (ILE->getType()->isArrayType()) {
@@ -3343,7 +3349,8 @@ bool Expr::isConstantInitializer(ASTContext , bool 
IsForRef,
   unsigned ElementNo = 0;
   RecordDecl *RD = ILE->getType()->castAs()->getDecl();
 
-  // Check bases for C++17 aggregate initializers.
+  // In C++17, bases were added to the list of members used by aggregate
+  // initialization.
   if (const auto *CXXRD = dyn_cast(RD)) {
 for (unsigned i = 0, e = CXXRD->getNumBases(); i < e; i++) {
   if (ElementNo < ILE->getNumInits()) {
diff --git a/clang/test/SemaCXX/compound-literal.cpp 
b/clang/test/SemaCXX/compound-literal.cpp
index 81f8b41ff0313e..a3d3b9faa9fee9 100644
--- a/clang/test/SemaCXX/compound-literal.cpp
+++ b/clang/test/SemaCXX/compound-literal.cpp
@@ -110,21 +110,22 @@ int computed_with_lambda = [] {
 }();
 #endif
 
-#if __cplusplus >= 201703L
 namespace DynamicFileScopeLiteral {
 // This covers the case where we have a file-scope compound literal with a
 // non-constant initializer in C++. Previously, we had a bug where Clang forgot
 // to consider initializer list elements for bases.
 struct Empty {};
-struct Foo : Empty {
+struct Foo : Empty { // expected-note 0+ 

[clang] Consider aggregate bases when checking if an InitListExpr is constant (PR #80519)

2024-02-05 Thread Reid Kleckner via cfe-commits

rnk wrote:

> Also in the issue: #80510 you pointed out a crash bug. We should have the bug 
> covered in the test case as well.

I think that is covered by the existing test case, instead of crashing, we now 
reject with an error. In the future if we want to align with GCC as you 
suggest, we'll need to have a codegen test case for non-constant compound 
literals of aggregates with bases.

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


[clang] Consider aggregate bases when checking if an InitListExpr is constant (PR #80519)

2024-02-05 Thread Reid Kleckner via cfe-commits


@@ -108,3 +109,22 @@ int computed_with_lambda = [] {
   return result;
 }();
 #endif
+
+#if __cplusplus >= 201703L
+namespace DynamicFileScopeLiteral {
+// This covers the case where we have a file-scope compound literal with a
+// non-constant initializer in C++. Previously, we had a bug where Clang forgot
+// to consider initializer list elements for bases.
+struct Empty {};
+struct Foo : Empty {
+  int x;
+  int y;
+};
+int f();
+Foo o = (Foo){
+  {},
+  1,
+  f() // expected-error {{initializer element is not a compile-time constant}}

rnk wrote:

I went ahead and make a targeted unit test for `isConstantInitializer` to see 
if that is nicer

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


[clang] Consider aggregate bases when checking if an InitListExpr is constant (PR #80519)

2024-02-05 Thread Reid Kleckner via cfe-commits

https://github.com/rnk updated https://github.com/llvm/llvm-project/pull/80519

>From 6ab5ba3f970eaaea542fbed09cae17d3666df6b3 Mon Sep 17 00:00:00 2001
From: Reid Kleckner 
Date: Sat, 3 Feb 2024 00:18:42 +
Subject: [PATCH 1/2] wip

---
 clang/lib/AST/Expr.cpp  | 12 
 clang/test/SemaCXX/compound-literal.cpp | 20 
 2 files changed, 32 insertions(+)

diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index d665a08deb47e..8852fadf79b9a 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3342,6 +3342,18 @@ bool Expr::isConstantInitializer(ASTContext , bool 
IsForRef,
 if (ILE->getType()->isRecordType()) {
   unsigned ElementNo = 0;
   RecordDecl *RD = ILE->getType()->castAs()->getDecl();
+
+  // Check bases for C++17 aggregate initializers.
+  if (const auto *CXXRD = dyn_cast(RD)) {
+for (unsigned i = 0, e = CXXRD->getNumBases(); i < e; i++) {
+  if (ElementNo < ILE->getNumInits()) {
+const Expr *Elt = ILE->getInit(ElementNo++);
+if (!Elt->isConstantInitializer(Ctx, false, Culprit))
+  return false;
+  }
+}
+  }
+
   for (const auto *Field : RD->fields()) {
 // If this is a union, skip all the fields that aren't being 
initialized.
 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
diff --git a/clang/test/SemaCXX/compound-literal.cpp 
b/clang/test/SemaCXX/compound-literal.cpp
index 5957099de53af..81f8b41ff0313 100644
--- a/clang/test/SemaCXX/compound-literal.cpp
+++ b/clang/test/SemaCXX/compound-literal.cpp
@@ -3,6 +3,7 @@
 // RUN: %clang_cc1 -fsyntax-only -std=c++11 -verify -ast-dump %s > %t-11
 // RUN: FileCheck --input-file=%t-11 %s
 // RUN: FileCheck --input-file=%t-11 %s --check-prefix=CHECK-CXX11
+// RUN: %clang_cc1 -verify -std=c++17 %s
 
 // http://llvm.org/PR7905
 namespace PR7905 {
@@ -108,3 +109,22 @@ int computed_with_lambda = [] {
   return result;
 }();
 #endif
+
+#if __cplusplus >= 201703L
+namespace DynamicFileScopeLiteral {
+// This covers the case where we have a file-scope compound literal with a
+// non-constant initializer in C++. Previously, we had a bug where Clang forgot
+// to consider initializer list elements for bases.
+struct Empty {};
+struct Foo : Empty {
+  int x;
+  int y;
+};
+int f();
+Foo o = (Foo){
+  {},
+  1,
+  f() // expected-error {{initializer element is not a compile-time constant}}
+};
+}
+#endif

>From c630eee1f930c87d2c461de92271c02de220b290 Mon Sep 17 00:00:00 2001
From: Reid Kleckner 
Date: Mon, 5 Feb 2024 23:47:57 +
Subject: [PATCH 2/2] update comments, run test in past language modes, and add
 unit test

---
 clang/lib/AST/Expr.cpp  |  9 +++-
 clang/test/SemaCXX/compound-literal.cpp | 17 ---
 clang/unittests/AST/ASTExprTest.cpp | 66 ++---
 3 files changed, 75 insertions(+), 17 deletions(-)

diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 8852fadf79b9a..9190995c1df20 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3328,6 +3328,12 @@ bool Expr::isConstantInitializer(ASTContext , bool 
IsForRef,
DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
   }
   case InitListExprClass: {
+// C++ [temp.dep.expr]p2:
+//   The elements of an aggregate are:
+//   — for an array, the array elements in increasing subscript order, or
+//   — for a class, the direct base classes in declaration order, followed
+// by the direct non-static data members (11.4) that are not members of
+// an anonymous union, in declaration order.
 const InitListExpr *ILE = cast(this);
 assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
 if (ILE->getType()->isArrayType()) {
@@ -3343,7 +3349,8 @@ bool Expr::isConstantInitializer(ASTContext , bool 
IsForRef,
   unsigned ElementNo = 0;
   RecordDecl *RD = ILE->getType()->castAs()->getDecl();
 
-  // Check bases for C++17 aggregate initializers.
+  // In C++17, bases were added to the list of members used by aggregate
+  // initialization.
   if (const auto *CXXRD = dyn_cast(RD)) {
 for (unsigned i = 0, e = CXXRD->getNumBases(); i < e; i++) {
   if (ElementNo < ILE->getNumInits()) {
diff --git a/clang/test/SemaCXX/compound-literal.cpp 
b/clang/test/SemaCXX/compound-literal.cpp
index 81f8b41ff0313..a3d3b9faa9fee 100644
--- a/clang/test/SemaCXX/compound-literal.cpp
+++ b/clang/test/SemaCXX/compound-literal.cpp
@@ -110,21 +110,22 @@ int computed_with_lambda = [] {
 }();
 #endif
 
-#if __cplusplus >= 201703L
 namespace DynamicFileScopeLiteral {
 // This covers the case where we have a file-scope compound literal with a
 // non-constant initializer in C++. Previously, we had a bug where Clang forgot
 // to consider initializer list elements for bases.
 struct Empty {};
-struct Foo : Empty {
+struct Foo : Empty { // expected-note 0+ 

[clang] Fix a crash in clang::isGetterOfRefCounted by checking nullptr in tryToFindPtrOrigin (PR #80768)

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

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

>From f9f11843c2d09775de20d47dc71c5e482a1ff8b4 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Mon, 5 Feb 2024 16:07:09 -0800
Subject: [PATCH] Fix a crash in clang::isGetterOfRefCounted by checking
 nullptr in tryToFindPtrOrigin

---
 .../Checkers/WebKit/ASTUtils.cpp  | 15 ++-
 .../WebKit/member-function-pointer-crash.cpp  | 26 +++
 2 files changed, 35 insertions(+), 6 deletions(-)
 create mode 100644 
clang/test/Analysis/Checkers/WebKit/member-function-pointer-crash.cpp

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
index 64028b2770215..4526fac64735b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
@@ -34,13 +34,16 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
 }
 if (auto *call = dyn_cast(E)) {
   if (auto *memberCall = dyn_cast(call)) {
-std::optional IsGetterOfRefCt = 
isGetterOfRefCounted(memberCall->getMethodDecl());
-if (IsGetterOfRefCt && *IsGetterOfRefCt) {
-  E = memberCall->getImplicitObjectArgument();
-  if (StopAtFirstRefCountedObj) {
-return {E, true};
+if (auto *decl = memberCall->getMethodDecl()) {
+  std::optional IsGetterOfRefCt =
+  isGetterOfRefCounted(memberCall->getMethodDecl());
+  if (IsGetterOfRefCt && *IsGetterOfRefCt) {
+E = memberCall->getImplicitObjectArgument();
+if (StopAtFirstRefCountedObj) {
+  return {E, true};
+}
+continue;
   }
-  continue;
 }
   }
 
diff --git 
a/clang/test/Analysis/Checkers/WebKit/member-function-pointer-crash.cpp 
b/clang/test/Analysis/Checkers/WebKit/member-function-pointer-crash.cpp
new file mode 100644
index 0..16d3b89b3ac4e
--- /dev/null
+++ b/clang/test/Analysis/Checkers/WebKit/member-function-pointer-crash.cpp
@@ -0,0 +1,26 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=alpha.webkit.UncountedLocalVarsChecker -verify %s
+
+#include "mock-types.h"
+
+class RenderStyle;
+
+class FillLayer {
+public:
+void ref() const;
+void deref() const;
+};
+
+class FillLayersPropertyWrapper {
+public:
+typedef const FillLayer& (RenderStyle::*LayersGetter)() const;
+
+private:
+bool canInterpolate(const RenderStyle& from) const
+{
+auto* fromLayer = &(from.*m_layersGetter)();
+// expected-warning@-1{{Local variable 'fromLayer' is uncounted and 
unsafe}}
+return true;
+}
+
+LayersGetter m_layersGetter;
+};

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


[llvm] [clang] [clang] Support per-function [[clang::code_align(N)]] attribute. (PR #80765)

2024-02-05 Thread Anton Bikineev via cfe-commits

https://github.com/AntonBikineev updated 
https://github.com/llvm/llvm-project/pull/80765

>From 88151098d3087f95d3a5b652309a12fb2e9f757e Mon Sep 17 00:00:00 2001
From: Anton Bikineev 
Date: Mon, 5 Feb 2024 12:24:17 +0100
Subject: [PATCH] [clang] Support per-function [[clang::code_align(N)]]
 attribute.

The existing attribute works only for loop headers. This can
unfortunately be quite limiting, especially as a protection against the
"Jump Conditional Code Erratum" [0] (for example, if there is an
unaligned check in a hot loop). The command line option
-malign-branch-boundary can help with that, but it's too coarse-grained
and can significantly increase the binary size.

This change introduces a per-function [[clang::code_align(N)]] attribute
that aligns all the basic blocks of a function by the given N.

[0] 
https://www.intel.com/content/dam/support/us/en/documents/processors/mitigations-jump-conditional-code-erratum.pdf
---
 clang/include/clang/Basic/Attr.td |  7 ++--
 clang/include/clang/Basic/AttrDocs.td | 16 ---
 clang/lib/CodeGen/CodeGenModule.cpp   |  6 +++
 clang/lib/Sema/SemaDeclAttr.cpp   | 10 +
 clang/test/CodeGen/code_align_function.c  | 42 +++
 ...a-attribute-supported-attributes-list.test |  1 +
 clang/test/Sema/code_align.c  | 14 ++-
 llvm/lib/CodeGen/MachineBlockPlacement.cpp| 28 ++---
 .../CodeGen/X86/code-align-basic-blocks.ll| 29 +
 9 files changed, 137 insertions(+), 16 deletions(-)
 create mode 100644 clang/test/CodeGen/code_align_function.c
 create mode 100644 llvm/test/CodeGen/X86/code-align-basic-blocks.ll

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index b2d5309e142c1..abce685e9f7a6 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4435,10 +4435,11 @@ def PreferredType: InheritableAttr {
   let Documentation = [PreferredTypeDocumentation];
 }
 
-def CodeAlign: StmtAttr {
+def CodeAlign : InheritableAttr {
   let Spellings = [Clang<"code_align">];
-  let Subjects = SubjectList<[ForStmt, CXXForRangeStmt, WhileStmt, DoStmt],
-  ErrorDiag, "'for', 'while', and 'do' 
statements">;
+  let Subjects =
+  SubjectList<[ForStmt, CXXForRangeStmt, WhileStmt, DoStmt, Function],
+  ErrorDiag, "'for', 'while', 'do' statements and functions">;
   let Args = [ExprArgument<"Alignment">];
   let Documentation = [CodeAlignAttrDocs];
   let AdditionalMembers = [{
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 041786f37fb8a..57b63469f1573 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -7704,11 +7704,12 @@ def CodeAlignAttrDocs : Documentation {
   let Category = DocCatVariable;
   let Heading = "clang::code_align";
   let Content = [{
-The ``clang::code_align(N)`` attribute applies to a loop and specifies the byte
-alignment for a loop. The attribute accepts a positive integer constant
-initialization expression indicating the number of bytes for the minimum
-alignment boundary. Its value must be a power of 2, between 1 and 4096
-(inclusive).
+The ``clang::code_align(N)`` attribute applies to a loop or a function. When
+applied to a loop it specifies the byte alignment for the loop header. When
+applied to a function it aligns all the basic blocks of the function. The
+attribute accepts a positive integer constant initialization expression
+indicating the number of bytes for the minimum alignment boundary. Its value
+must be a power of 2, between 1 and 4096 (inclusive).
 
 .. code-block:: c++
 
@@ -7738,6 +7739,11 @@ alignment boundary. Its value must be a power of 2, 
between 1 and 4096
 [[clang::code_align(A)]] for(;;) { }
   }
 
+  [[clang:code_align(16)]] int foo(bool b) {
+if (b) return 2;
+return 3;
+  }
+
   }];
 }
 
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 36b63d78b06f8..87a822e91fff6 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -2515,6 +2515,12 @@ void 
CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
   F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
   }
 
+  if (const auto *CodeAlign = D->getAttr()) {
+const auto *CE = cast(CodeAlign->getAlignment());
+std::string ArgValStr = llvm::toString(CE->getResultAsAPSInt(), 10);
+F->addFnAttr("align-basic-blocks", ArgValStr);
+  }
+
   // In the cross-dso CFI mode with canonical jump tables, we want !type
   // attributes on definitions only.
   if (CodeGenOpts.SanitizeCfiCrossDso &&
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index d785714c4d811..40412801b632a 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -9036,6 +9036,12 @@ static void handleArmNewAttr(Sema , 

[clang] [clang][CodeGen][UBSan] Fixing shift-exponent generation for _BitInt (PR #80515)

2024-02-05 Thread Björn Pettersson via cfe-commits

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

LG

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


[clang] Fix a crash in clang::isGetterOfRefCounted by checking nullptr in tryToFindPtrOrigin (PR #80768)

2024-02-05 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 6ce03ff3fef8fb6fa9afe8eb22c6d98bced26d48 
4e10436ddd55f1b1bed2bb99856e1101b9462117 -- 
clang/test/Analysis/Checkers/WebKit/member-function-pointer-crash.cpp 
clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
index 728772ed91..4526fac647 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
@@ -35,7 +35,8 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
 if (auto *call = dyn_cast(E)) {
   if (auto *memberCall = dyn_cast(call)) {
 if (auto *decl = memberCall->getMethodDecl()) {
-  std::optional IsGetterOfRefCt = 
isGetterOfRefCounted(memberCall->getMethodDecl());
+  std::optional IsGetterOfRefCt =
+  isGetterOfRefCounted(memberCall->getMethodDecl());
   if (IsGetterOfRefCt && *IsGetterOfRefCt) {
 E = memberCall->getImplicitObjectArgument();
 if (StopAtFirstRefCountedObj) {

``




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


[clang] Disable FTZ/DAZ when compiling shared libraries by default. (PR #80475)

2024-02-05 Thread Andy Kaylor via cfe-commits

andykaylor wrote:

> > (Sidenote: "dynamic" isn't even 
> > [documented](https://clang.llvm.org/docs/UsersManual.html#cmdoption-fdenormal-fp-math)).
> 
> It's not a selectable enum of the Clang `-fdenormal-fp-math` flag, but it is 
> one for the LLVM function attribute `denormal-fp-math`.

This is also a bit of a problem. After inlining we can have instructions with 
fast-math disabled appearing in the middle of functions that were compiled with 
fast-math enabled. What happens to the "denormal-fp-math" attribute in such 
cases? I wanted to show this in compiler explorer, but "#pragma 
float_control()" doesn't update the "denormal-fp-math attribute.

https://godbolt.org/z/KEP3YEEe9

I may have mentioned a few times that I don't like function attributes 
controlling fast-math behaviors.

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


[clang] Fix a crash in clang::isGetterOfRefCounted by checking nullptr in tryToFindPtrOrigin (PR #80768)

2024-02-05 Thread via cfe-commits

llvmbot wrote:




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

Author: Ryosuke Niwa (rniwa)


Changes



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


2 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp (+8-6) 
- (added) clang/test/Analysis/Checkers/WebKit/member-function-pointer-crash.cpp 
(+26) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
index 64028b2770215..728772ed910af 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
@@ -34,13 +34,15 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
 }
 if (auto *call = dyn_cast(E)) {
   if (auto *memberCall = dyn_cast(call)) {
-std::optional IsGetterOfRefCt = 
isGetterOfRefCounted(memberCall->getMethodDecl());
-if (IsGetterOfRefCt && *IsGetterOfRefCt) {
-  E = memberCall->getImplicitObjectArgument();
-  if (StopAtFirstRefCountedObj) {
-return {E, true};
+if (auto *decl = memberCall->getMethodDecl()) {
+  std::optional IsGetterOfRefCt = 
isGetterOfRefCounted(memberCall->getMethodDecl());
+  if (IsGetterOfRefCt && *IsGetterOfRefCt) {
+E = memberCall->getImplicitObjectArgument();
+if (StopAtFirstRefCountedObj) {
+  return {E, true};
+}
+continue;
   }
-  continue;
 }
   }
 
diff --git 
a/clang/test/Analysis/Checkers/WebKit/member-function-pointer-crash.cpp 
b/clang/test/Analysis/Checkers/WebKit/member-function-pointer-crash.cpp
new file mode 100644
index 0..16d3b89b3ac4e
--- /dev/null
+++ b/clang/test/Analysis/Checkers/WebKit/member-function-pointer-crash.cpp
@@ -0,0 +1,26 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=alpha.webkit.UncountedLocalVarsChecker -verify %s
+
+#include "mock-types.h"
+
+class RenderStyle;
+
+class FillLayer {
+public:
+void ref() const;
+void deref() const;
+};
+
+class FillLayersPropertyWrapper {
+public:
+typedef const FillLayer& (RenderStyle::*LayersGetter)() const;
+
+private:
+bool canInterpolate(const RenderStyle& from) const
+{
+auto* fromLayer = &(from.*m_layersGetter)();
+// expected-warning@-1{{Local variable 'fromLayer' is uncounted and 
unsafe}}
+return true;
+}
+
+LayersGetter m_layersGetter;
+};

``




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


[clang] Fix a crash in clang::isGetterOfRefCounted by checking nullptr in tryToFindPtrOrigin (PR #80768)

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

https://github.com/rniwa created https://github.com/llvm/llvm-project/pull/80768

None

>From 4e10436ddd55f1b1bed2bb99856e1101b9462117 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Mon, 5 Feb 2024 16:07:09 -0800
Subject: [PATCH] Fix a crash in clang::isGetterOfRefCounted by checking
 nullptr in tryToFindPtrOrigin

---
 .../Checkers/WebKit/ASTUtils.cpp  | 14 +-
 .../WebKit/member-function-pointer-crash.cpp  | 26 +++
 2 files changed, 34 insertions(+), 6 deletions(-)
 create mode 100644 
clang/test/Analysis/Checkers/WebKit/member-function-pointer-crash.cpp

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
index 64028b27702150..728772ed910afc 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
@@ -34,13 +34,15 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
 }
 if (auto *call = dyn_cast(E)) {
   if (auto *memberCall = dyn_cast(call)) {
-std::optional IsGetterOfRefCt = 
isGetterOfRefCounted(memberCall->getMethodDecl());
-if (IsGetterOfRefCt && *IsGetterOfRefCt) {
-  E = memberCall->getImplicitObjectArgument();
-  if (StopAtFirstRefCountedObj) {
-return {E, true};
+if (auto *decl = memberCall->getMethodDecl()) {
+  std::optional IsGetterOfRefCt = 
isGetterOfRefCounted(memberCall->getMethodDecl());
+  if (IsGetterOfRefCt && *IsGetterOfRefCt) {
+E = memberCall->getImplicitObjectArgument();
+if (StopAtFirstRefCountedObj) {
+  return {E, true};
+}
+continue;
   }
-  continue;
 }
   }
 
diff --git 
a/clang/test/Analysis/Checkers/WebKit/member-function-pointer-crash.cpp 
b/clang/test/Analysis/Checkers/WebKit/member-function-pointer-crash.cpp
new file mode 100644
index 00..16d3b89b3ac4e7
--- /dev/null
+++ b/clang/test/Analysis/Checkers/WebKit/member-function-pointer-crash.cpp
@@ -0,0 +1,26 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=alpha.webkit.UncountedLocalVarsChecker -verify %s
+
+#include "mock-types.h"
+
+class RenderStyle;
+
+class FillLayer {
+public:
+void ref() const;
+void deref() const;
+};
+
+class FillLayersPropertyWrapper {
+public:
+typedef const FillLayer& (RenderStyle::*LayersGetter)() const;
+
+private:
+bool canInterpolate(const RenderStyle& from) const
+{
+auto* fromLayer = &(from.*m_layersGetter)();
+// expected-warning@-1{{Local variable 'fromLayer' is uncounted and 
unsafe}}
+return true;
+}
+
+LayersGetter m_layersGetter;
+};

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


[clang] [AMDGPU] Add missing `__builtin_amdgcn_wavefrontsize` builtin (PR #80741)

2024-02-05 Thread Joseph Huber via cfe-commits

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


[clang] dbed898 - [AMDGPU] Add missing `__builtin_amdgcn_wavefrontsize` builtin (#80741)

2024-02-05 Thread via cfe-commits

Author: Joseph Huber
Date: 2024-02-05T17:58:19-06:00
New Revision: dbed89814e5b9ba25a349a5b9acf4a7164e33834

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

LOG: [AMDGPU] Add missing `__builtin_amdgcn_wavefrontsize` builtin (#80741)

Summary:
The backend supports the wavefrontsize intrinsic, and suggests that it
is tied to a corresponding clang builtin, but it is not actually
present. This simply adds it in so it can be used from clang. This
attribute likely isn't the best to rely on, but for the `libc` use-case
we will need to detect a struct's differing size in a way that will
depend on the wavefront size.

Added: 


Modified: 
clang/include/clang/Basic/BuiltinsAMDGPU.def
clang/test/CodeGenOpenCL/builtins-amdgcn.cl

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsAMDGPU.def 
b/clang/include/clang/Basic/BuiltinsAMDGPU.def
index 5f8001e61a028..213311b96df74 100644
--- a/clang/include/clang/Basic/BuiltinsAMDGPU.def
+++ b/clang/include/clang/Basic/BuiltinsAMDGPU.def
@@ -69,6 +69,7 @@ BUILTIN(__builtin_amdgcn_s_dcache_inv, "v", "n")
 BUILTIN(__builtin_amdgcn_buffer_wbinvl1, "v", "n")
 BUILTIN(__builtin_amdgcn_fence, "vUicC*", "n")
 BUILTIN(__builtin_amdgcn_groupstaticsize, "Ui", "n")
+BUILTIN(__builtin_amdgcn_wavefrontsize, "Ui", "nc")
 
 BUILTIN(__builtin_amdgcn_atomic_inc32, "UZiUZiD*UZiUicC*", "n")
 BUILTIN(__builtin_amdgcn_atomic_inc64, "UWiUWiD*UWiUicC*", "n")

diff  --git a/clang/test/CodeGenOpenCL/builtins-amdgcn.cl 
b/clang/test/CodeGenOpenCL/builtins-amdgcn.cl
index 8d9e4e018b12e..7d9010ee9067d 100644
--- a/clang/test/CodeGenOpenCL/builtins-amdgcn.cl
+++ b/clang/test/CodeGenOpenCL/builtins-amdgcn.cl
@@ -832,6 +832,13 @@ void test_atomic_inc_dec(local uint *lptr, global uint 
*gptr, uint val) {
   res = __builtin_amdgcn_atomic_dec32((volatile global uint*)gptr, val, 
__ATOMIC_SEQ_CST, "");
 }
 
+// CHECK-LABEL test_wavefrontsize(
+unsigned test_wavefrontsize() {
+
+  // CHECK: call i32 @llvm.amdgcn.wavefrontsize()
+  return __builtin_amdgcn_wavefrontsize();
+}
+
 // CHECK-DAG: [[$WI_RANGE]] = !{i32 0, i32 1024}
 // CHECK-DAG: [[$WS_RANGE]] = !{i16 1, i16 1025}
 // CHECK-DAG: attributes #[[$NOUNWIND_READONLY]] = { convergent mustprogress 
nocallback nofree nounwind willreturn memory(none) }



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


[libc] [clang-tools-extra] [openmp] [libcxx] [compiler-rt] [lldb] [mlir] [llvm] [lld] [flang] [clang] [Driver] Report invalid target triple versions for all environment types. (PR #78655)

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

MaskRay wrote:

> > There's apparently also wasm32-wasi-preview2 and wasm32-wasi-pthread, which 
> > I suppose are equally broken by this change.
> 
> Yes, I think so. I think adding these environment types in wasi-libc repo 
> could help fix those errors.

If wasm can arbitrary environment types, it seems that we can opt out the check 
for `isWasm()`.
We define new environment types when they affect the compiler behavior. If wasm 
arbitrary sets the environment, we should not define a type for each one.


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


[llvm] [clang] [clang] Support per-function [[clang::code_align(N)]] attribute. (PR #80765)

2024-02-05 Thread Anton Bikineev via cfe-commits

https://github.com/AntonBikineev updated 
https://github.com/llvm/llvm-project/pull/80765

>From 99d2cc55fb952361b1fe04e2c21dcb5b04f11d47 Mon Sep 17 00:00:00 2001
From: Anton Bikineev 
Date: Mon, 5 Feb 2024 12:24:17 +0100
Subject: [PATCH] [clang] Support per-function [[clang::code_align(N)]]
 attribute.

The existing attribute works only for loop headers. This can
unfortunately be quite limiting, especially as a protection against the
"Jump Conditional Code Erratum" [0] (for example, if there is an
unaligned check in a hot loop). The command line option
-malign-branch-boundary can help with that, but it's too coarse-grained
and can significantly increase the binary size.

This change introduces a per-function [[clang::code_align(N)]] attribute
that aligns all the basic blocks of a function by the given N.

[0] 
https://www.intel.com/content/dam/support/us/en/documents/processors/mitigations-jump-conditional-code-erratum.pdf
---
 clang/include/clang/Basic/Attr.td |  7 ++--
 clang/include/clang/Basic/AttrDocs.td | 16 ---
 clang/lib/CodeGen/CodeGenModule.cpp   |  6 +++
 clang/lib/Sema/SemaDeclAttr.cpp   | 10 +
 clang/test/CodeGen/code_align_function.c  | 42 +++
 clang/test/Sema/code_align.c  | 14 ++-
 llvm/lib/CodeGen/MachineBlockPlacement.cpp| 28 ++---
 .../CodeGen/X86/code-align-basic-blocks.ll| 29 +
 8 files changed, 136 insertions(+), 16 deletions(-)
 create mode 100644 clang/test/CodeGen/code_align_function.c
 create mode 100644 llvm/test/CodeGen/X86/code-align-basic-blocks.ll

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index b2d5309e142c1a..abce685e9f7a64 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4435,10 +4435,11 @@ def PreferredType: InheritableAttr {
   let Documentation = [PreferredTypeDocumentation];
 }
 
-def CodeAlign: StmtAttr {
+def CodeAlign : InheritableAttr {
   let Spellings = [Clang<"code_align">];
-  let Subjects = SubjectList<[ForStmt, CXXForRangeStmt, WhileStmt, DoStmt],
-  ErrorDiag, "'for', 'while', and 'do' 
statements">;
+  let Subjects =
+  SubjectList<[ForStmt, CXXForRangeStmt, WhileStmt, DoStmt, Function],
+  ErrorDiag, "'for', 'while', 'do' statements and functions">;
   let Args = [ExprArgument<"Alignment">];
   let Documentation = [CodeAlignAttrDocs];
   let AdditionalMembers = [{
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 041786f37fb8a7..57b63469f1573f 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -7704,11 +7704,12 @@ def CodeAlignAttrDocs : Documentation {
   let Category = DocCatVariable;
   let Heading = "clang::code_align";
   let Content = [{
-The ``clang::code_align(N)`` attribute applies to a loop and specifies the byte
-alignment for a loop. The attribute accepts a positive integer constant
-initialization expression indicating the number of bytes for the minimum
-alignment boundary. Its value must be a power of 2, between 1 and 4096
-(inclusive).
+The ``clang::code_align(N)`` attribute applies to a loop or a function. When
+applied to a loop it specifies the byte alignment for the loop header. When
+applied to a function it aligns all the basic blocks of the function. The
+attribute accepts a positive integer constant initialization expression
+indicating the number of bytes for the minimum alignment boundary. Its value
+must be a power of 2, between 1 and 4096 (inclusive).
 
 .. code-block:: c++
 
@@ -7738,6 +7739,11 @@ alignment boundary. Its value must be a power of 2, 
between 1 and 4096
 [[clang::code_align(A)]] for(;;) { }
   }
 
+  [[clang:code_align(16)]] int foo(bool b) {
+if (b) return 2;
+return 3;
+  }
+
   }];
 }
 
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 36b63d78b06f83..87a822e91fff61 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -2515,6 +2515,12 @@ void 
CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
   F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
   }
 
+  if (const auto *CodeAlign = D->getAttr()) {
+const auto *CE = cast(CodeAlign->getAlignment());
+std::string ArgValStr = llvm::toString(CE->getResultAsAPSInt(), 10);
+F->addFnAttr("align-basic-blocks", ArgValStr);
+  }
+
   // In the cross-dso CFI mode with canonical jump tables, we want !type
   // attributes on definitions only.
   if (CodeGenOpts.SanitizeCfiCrossDso &&
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index d785714c4d811e..40412801b632ae 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -9036,6 +9036,12 @@ static void handleArmNewAttr(Sema , Decl *D, const 
ParsedAttr ) {
 

[llvm] [clang] [clang] Support per-function [[clang::code_align(N)]] attribute. (PR #80765)

2024-02-05 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff a7bc9cb6ffa91ff0ebabc45c0c7263c7c2c3a4de 
ff8cf4e87473dec2e3f55114cb92ae5a63d9488c -- 
clang/test/CodeGen/code_align_function.c clang/lib/CodeGen/CodeGenModule.cpp 
clang/lib/Sema/SemaDeclAttr.cpp clang/test/Sema/code_align.c 
llvm/lib/CodeGen/MachineBlockPlacement.cpp
``





View the diff from clang-format here.


``diff
diff --git a/llvm/lib/CodeGen/MachineBlockPlacement.cpp 
b/llvm/lib/CodeGen/MachineBlockPlacement.cpp
index ba4f161ef3..90e3c91707 100644
--- a/llvm/lib/CodeGen/MachineBlockPlacement.cpp
+++ b/llvm/lib/CodeGen/MachineBlockPlacement.cpp
@@ -3499,7 +3499,8 @@ bool 
MachineBlockPlacement::runOnMachineFunction(MachineFunction ) {
 // specific alignment.
 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
   auto LayoutPred = std::prev(MBI);
-  unsigned MaxAlignment = std::max(1ULL << AlignAllNonFallThruBlocks, 
MBBAlignment);
+  unsigned MaxAlignment =
+  std::max(1ULL << AlignAllNonFallThruBlocks, MBBAlignment);
   if (!LayoutPred->isSuccessor(&*MBI)) {
 if (HasMaxBytesOverride)
   MBI->setAlignment(std::max(Align(MaxAlignment), MBI->getAlignment()),

``




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


[compiler-rt] [mlir] [clang] [libc] [flang] [clang-tools-extra] [lld] [openmp] [lldb] [llvm] [libcxx] [Driver] Report invalid target triple versions for all environment types. (PR #78655)

2024-02-05 Thread Mike Hommey via cfe-commits

glandium wrote:

> Yes, I think so. I think adding these environment types in wasi-libc repo 
> could help fix those errors.

WDYM?

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


[clang] [llvm] [clang] Support per-function [[clang::code_align(N)]] attribute. (PR #80765)

2024-02-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-backend-x86

Author: Anton Bikineev (AntonBikineev)


Changes

The existing attribute works only for loop headers. This can unfortunately be 
quite limiting, especially as a protection against the "Jump Conditional Code 
Erratum" [0] (for example, if there is an unaligned check in a hot loop). The 
command line option -malign-branch-boundary can help with that, but it's too 
coarse-grained and can significantly increase the binary size.

This change introduces a per-function [[clang::code_align(N)]] attribute that 
aligns all the basic blocks of a function by the given N.

[0] 
https://www.intel.com/content/dam/support/us/en/documents/processors/mitigations-jump-conditional-code-erratum.pdf

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


8 Files Affected:

- (modified) clang/include/clang/Basic/Attr.td (+4-3) 
- (modified) clang/include/clang/Basic/AttrDocs.td (+11-5) 
- (modified) clang/lib/CodeGen/CodeGenModule.cpp (+6) 
- (modified) clang/lib/Sema/SemaDeclAttr.cpp (+10) 
- (added) clang/test/CodeGen/code_align_function.c (+42) 
- (modified) clang/test/Sema/code_align.c (+12-2) 
- (modified) llvm/lib/CodeGen/MachineBlockPlacement.cpp (+21-6) 
- (added) llvm/test/CodeGen/X86/code-align-basic-blocks.ll (+29) 


``diff
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index b2d5309e142c1..abce685e9f7a6 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4435,10 +4435,11 @@ def PreferredType: InheritableAttr {
   let Documentation = [PreferredTypeDocumentation];
 }
 
-def CodeAlign: StmtAttr {
+def CodeAlign : InheritableAttr {
   let Spellings = [Clang<"code_align">];
-  let Subjects = SubjectList<[ForStmt, CXXForRangeStmt, WhileStmt, DoStmt],
-  ErrorDiag, "'for', 'while', and 'do' 
statements">;
+  let Subjects =
+  SubjectList<[ForStmt, CXXForRangeStmt, WhileStmt, DoStmt, Function],
+  ErrorDiag, "'for', 'while', 'do' statements and functions">;
   let Args = [ExprArgument<"Alignment">];
   let Documentation = [CodeAlignAttrDocs];
   let AdditionalMembers = [{
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 041786f37fb8a..57b63469f1573 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -7704,11 +7704,12 @@ def CodeAlignAttrDocs : Documentation {
   let Category = DocCatVariable;
   let Heading = "clang::code_align";
   let Content = [{
-The ``clang::code_align(N)`` attribute applies to a loop and specifies the byte
-alignment for a loop. The attribute accepts a positive integer constant
-initialization expression indicating the number of bytes for the minimum
-alignment boundary. Its value must be a power of 2, between 1 and 4096
-(inclusive).
+The ``clang::code_align(N)`` attribute applies to a loop or a function. When
+applied to a loop it specifies the byte alignment for the loop header. When
+applied to a function it aligns all the basic blocks of the function. The
+attribute accepts a positive integer constant initialization expression
+indicating the number of bytes for the minimum alignment boundary. Its value
+must be a power of 2, between 1 and 4096 (inclusive).
 
 .. code-block:: c++
 
@@ -7738,6 +7739,11 @@ alignment boundary. Its value must be a power of 2, 
between 1 and 4096
 [[clang::code_align(A)]] for(;;) { }
   }
 
+  [[clang:code_align(16)]] int foo(bool b) {
+if (b) return 2;
+return 3;
+  }
+
   }];
 }
 
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 36b63d78b06f8..87a822e91fff6 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -2515,6 +2515,12 @@ void 
CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
   F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
   }
 
+  if (const auto *CodeAlign = D->getAttr()) {
+const auto *CE = cast(CodeAlign->getAlignment());
+std::string ArgValStr = llvm::toString(CE->getResultAsAPSInt(), 10);
+F->addFnAttr("align-basic-blocks", ArgValStr);
+  }
+
   // In the cross-dso CFI mode with canonical jump tables, we want !type
   // attributes on definitions only.
   if (CodeGenOpts.SanitizeCfiCrossDso &&
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index d785714c4d811..40412801b632a 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -9036,6 +9036,12 @@ static void handleArmNewAttr(Sema , Decl *D, const 
ParsedAttr ) {
  ArmNewAttr(S.Context, AL, NewState.data(), NewState.size()));
 }
 
+static void handleCodeAlignAttr(Sema , Decl *D, const ParsedAttr ) {
+  Expr *E = A.getArgAsExpr(0);
+  if (Attr *CodeAlignAttr = S.BuildCodeAlignAttr(A, E))
+D->addAttr(CodeAlignAttr);
+}
+
 /// ProcessDeclAttribute - Apply the specific 

[llvm] [clang] [clang] Support per-function [[clang::code_align(N)]] attribute. (PR #80765)

2024-02-05 Thread Anton Bikineev via cfe-commits

https://github.com/AntonBikineev created 
https://github.com/llvm/llvm-project/pull/80765

The existing attribute works only for loop headers. This can unfortunately be 
quite limiting, especially as a protection against the "Jump Conditional Code 
Erratum" [0] (for example, if there is an unaligned check in a hot loop). The 
command line option -malign-branch-boundary can help with that, but it's too 
coarse-grained and can significantly increase the binary size.

This change introduces a per-function [[clang::code_align(N)]] attribute that 
aligns all the basic blocks of a function by the given N.

[0] 
https://www.intel.com/content/dam/support/us/en/documents/processors/mitigations-jump-conditional-code-erratum.pdf

>From ff8cf4e87473dec2e3f55114cb92ae5a63d9488c Mon Sep 17 00:00:00 2001
From: Anton Bikineev 
Date: Mon, 5 Feb 2024 12:24:17 +0100
Subject: [PATCH] [clang] Support per-function [[clang::code_align(N)]]
 attribute.

The existing attribute works only for loop headers. This can
unfortunately be quite limiting, especially as a protection against the
"Jump Conditional Code Erratum" [0] (for example, if there is an
unaligned check in a hot loop). The command line option
-malign-branch-boundary can help with that, but it's too coarse-grained
and can significantly increase the binary size.

This change introduces a per-function [[clang::code_align(N)]] attribute
that aligns all the basic blocks of a function by the given N.

[0] 
https://www.intel.com/content/dam/support/us/en/documents/processors/mitigations-jump-conditional-code-erratum.pdf
---
 clang/include/clang/Basic/Attr.td |  7 ++--
 clang/include/clang/Basic/AttrDocs.td | 16 ---
 clang/lib/CodeGen/CodeGenModule.cpp   |  6 +++
 clang/lib/Sema/SemaDeclAttr.cpp   | 10 +
 clang/test/CodeGen/code_align_function.c  | 42 +++
 clang/test/Sema/code_align.c  | 14 ++-
 llvm/lib/CodeGen/MachineBlockPlacement.cpp| 27 +---
 .../CodeGen/X86/code-align-basic-blocks.ll| 29 +
 8 files changed, 135 insertions(+), 16 deletions(-)
 create mode 100644 clang/test/CodeGen/code_align_function.c
 create mode 100644 llvm/test/CodeGen/X86/code-align-basic-blocks.ll

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index b2d5309e142c1..abce685e9f7a6 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4435,10 +4435,11 @@ def PreferredType: InheritableAttr {
   let Documentation = [PreferredTypeDocumentation];
 }
 
-def CodeAlign: StmtAttr {
+def CodeAlign : InheritableAttr {
   let Spellings = [Clang<"code_align">];
-  let Subjects = SubjectList<[ForStmt, CXXForRangeStmt, WhileStmt, DoStmt],
-  ErrorDiag, "'for', 'while', and 'do' 
statements">;
+  let Subjects =
+  SubjectList<[ForStmt, CXXForRangeStmt, WhileStmt, DoStmt, Function],
+  ErrorDiag, "'for', 'while', 'do' statements and functions">;
   let Args = [ExprArgument<"Alignment">];
   let Documentation = [CodeAlignAttrDocs];
   let AdditionalMembers = [{
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 041786f37fb8a..57b63469f1573 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -7704,11 +7704,12 @@ def CodeAlignAttrDocs : Documentation {
   let Category = DocCatVariable;
   let Heading = "clang::code_align";
   let Content = [{
-The ``clang::code_align(N)`` attribute applies to a loop and specifies the byte
-alignment for a loop. The attribute accepts a positive integer constant
-initialization expression indicating the number of bytes for the minimum
-alignment boundary. Its value must be a power of 2, between 1 and 4096
-(inclusive).
+The ``clang::code_align(N)`` attribute applies to a loop or a function. When
+applied to a loop it specifies the byte alignment for the loop header. When
+applied to a function it aligns all the basic blocks of the function. The
+attribute accepts a positive integer constant initialization expression
+indicating the number of bytes for the minimum alignment boundary. Its value
+must be a power of 2, between 1 and 4096 (inclusive).
 
 .. code-block:: c++
 
@@ -7738,6 +7739,11 @@ alignment boundary. Its value must be a power of 2, 
between 1 and 4096
 [[clang::code_align(A)]] for(;;) { }
   }
 
+  [[clang:code_align(16)]] int foo(bool b) {
+if (b) return 2;
+return 3;
+  }
+
   }];
 }
 
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 36b63d78b06f8..87a822e91fff6 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -2515,6 +2515,12 @@ void 
CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
   F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
   }
 
+  if (const auto *CodeAlign = D->getAttr()) {
+const auto 

[lld] [flang] [llvm] [clang] [libc] [libcxx] [compiler-rt] [lldb] [clang-tools-extra] [openmp] [mlir] [Driver] Report invalid target triple versions for all environment types. (PR #78655)

2024-02-05 Thread via cfe-commits

ZijunZhaoCCK wrote:

> There's apparently also wasm32-wasi-preview2 and wasm32-wasi-pthread, which I 
> suppose are equally broken by this change.

Yes, I think so. I think adding these environment types in wasi-libc repo could 
help fix those errors.

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


[clang] Disable FTZ/DAZ when compiling shared libraries by default. (PR #80475)

2024-02-05 Thread Andy Kaylor via cfe-commits

andykaylor wrote:

I don't know anything about how non-x86 targets implement DAZ/FTZ, but for 
x86-based targets, I think trying to make any assumptions about the setting is 
bound to be wrong. In theory, it's part of the floating-point environment and 
shouldn't be modified during execution unless fenv-access is enabled.

In practical terms, I can't see any reason that you would ever want a shared 
library to be able to control this. I don't like the idea of adding an option 
to maintain that behavior, and I think we should make it a high priority to 
stop doing it by default when a shared library is compiled with fast-math 
enabled.

More generally, if you're going to be mixing fast-math with non-fast-math 
within a program, you don't want FTZ/DAZ to be enabled just because some parts 
of the program are using fast-math, so the current behavior of linking with 
crtfastmath.o is fairly reckless.

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


[clang] Diagnose invalid fixed point conversion (PR #80763)

2024-02-05 Thread via cfe-commits

https://github.com/PiJoules updated 
https://github.com/llvm/llvm-project/pull/80763

>From 81e2325ee9600e6a41de51fc26963147617f4ad6 Mon Sep 17 00:00:00 2001
From: Leonard Chan 
Date: Mon, 5 Feb 2024 15:33:09 -0800
Subject: [PATCH] [Clang] Diagnose improper fixed point conversions in C++

---
 clang/include/clang/AST/Type.h | 7 +++
 clang/lib/Sema/SemaOverload.cpp| 5 -
 clang/test/Frontend/fixed_point_errors.cpp | 4 
 3 files changed, 15 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index d6a55f39a4bede..1942b0e67f65a3 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -2613,6 +2613,9 @@ class alignas(TypeAlignment) Type : public 
ExtQualsTypeCommonBase {
   /// Return true if this is a fixed point or integer type.
   bool isFixedPointOrIntegerType() const;
 
+  /// Return true if this can be converted to (or from) a fixed point type.
+  bool isConvertibleToFixedPointType() const;
+
   /// Return true if this is a saturated fixed point type according to
   /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
   bool isSaturatedFixedPointType() const;
@@ -7493,6 +7496,10 @@ inline bool Type::isFixedPointOrIntegerType() const {
   return isFixedPointType() || isIntegerType();
 }
 
+inline bool Type::isConvertibleToFixedPointType() const {
+  return isRealFloatingType() || isFixedPointOrIntegerType();
+}
+
 inline bool Type::isSaturatedFixedPointType() const {
   if (const auto *BT = dyn_cast(CanonicalType)) {
 return BT->getKind() >= BuiltinType::SatShortAccum &&
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 940bcccb9e261b..5fdaf15eaf3423 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -2177,7 +2177,10 @@ static bool IsStandardConversion(Sema , Expr* From, 
QualType ToType,
  From->isIntegerConstantExpr(S.getASTContext())) {
 SCS.Second = ICK_Compatible_Conversion;
 FromType = ToType;
-  } else if (ToType->isFixedPointType() || FromType->isFixedPointType()) {
+  } else if ((ToType->isFixedPointType() &&
+  FromType->isConvertibleToFixedPointType()) ||
+ (FromType->isFixedPointType() &&
+  ToType->isConvertibleToFixedPointType())) {
 SCS.Second = ICK_Fixed_Point_Conversion;
 FromType = ToType;
   } else {
diff --git a/clang/test/Frontend/fixed_point_errors.cpp 
b/clang/test/Frontend/fixed_point_errors.cpp
index 4097cd73c84505..ef064bc38873d8 100644
--- a/clang/test/Frontend/fixed_point_errors.cpp
+++ b/clang/test/Frontend/fixed_point_errors.cpp
@@ -14,3 +14,7 @@ int fract_int = 10r; // expected-error{{invalid suffix 
'r' on integer consta
 float accum_flt = 0.0k;  // expected-error{{invalid suffix 'k' on floating 
constant}}
 float fract_flt = 0.0r;  // expected-error{{invalid suffix 'r' on floating 
constant}}
 #endif
+
+#ifndef WITHOUT_FIXED_POINT
+const char *c = 10.0k;  // expected-error{{cannot initialize a variable of 
type 'const char *' with an rvalue of type '_Accum'}}
+#endif

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


[llvm] [clang] Diagnose invalid fixed point conversion (PR #80763)

2024-02-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-debuginfo

Author: None (PiJoules)


Changes



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


4 Files Affected:

- (modified) clang/include/clang/AST/Type.h (+7) 
- (modified) clang/lib/Sema/SemaOverload.cpp (+4-1) 
- (modified) clang/test/Frontend/fixed_point_errors.cpp (+4) 
- (modified) llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp (+3) 


``diff
diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index d6a55f39a4bed..1942b0e67f65a 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -2613,6 +2613,9 @@ class alignas(TypeAlignment) Type : public 
ExtQualsTypeCommonBase {
   /// Return true if this is a fixed point or integer type.
   bool isFixedPointOrIntegerType() const;
 
+  /// Return true if this can be converted to (or from) a fixed point type.
+  bool isConvertibleToFixedPointType() const;
+
   /// Return true if this is a saturated fixed point type according to
   /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
   bool isSaturatedFixedPointType() const;
@@ -7493,6 +7496,10 @@ inline bool Type::isFixedPointOrIntegerType() const {
   return isFixedPointType() || isIntegerType();
 }
 
+inline bool Type::isConvertibleToFixedPointType() const {
+  return isRealFloatingType() || isFixedPointOrIntegerType();
+}
+
 inline bool Type::isSaturatedFixedPointType() const {
   if (const auto *BT = dyn_cast(CanonicalType)) {
 return BT->getKind() >= BuiltinType::SatShortAccum &&
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 940bcccb9e261..5fdaf15eaf342 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -2177,7 +2177,10 @@ static bool IsStandardConversion(Sema , Expr* From, 
QualType ToType,
  From->isIntegerConstantExpr(S.getASTContext())) {
 SCS.Second = ICK_Compatible_Conversion;
 FromType = ToType;
-  } else if (ToType->isFixedPointType() || FromType->isFixedPointType()) {
+  } else if ((ToType->isFixedPointType() &&
+  FromType->isConvertibleToFixedPointType()) ||
+ (FromType->isFixedPointType() &&
+  ToType->isConvertibleToFixedPointType())) {
 SCS.Second = ICK_Fixed_Point_Conversion;
 FromType = ToType;
   } else {
diff --git a/clang/test/Frontend/fixed_point_errors.cpp 
b/clang/test/Frontend/fixed_point_errors.cpp
index 4097cd73c8450..ef064bc38873d 100644
--- a/clang/test/Frontend/fixed_point_errors.cpp
+++ b/clang/test/Frontend/fixed_point_errors.cpp
@@ -14,3 +14,7 @@ int fract_int = 10r; // expected-error{{invalid suffix 
'r' on integer consta
 float accum_flt = 0.0k;  // expected-error{{invalid suffix 'k' on floating 
constant}}
 float fract_flt = 0.0r;  // expected-error{{invalid suffix 'r' on floating 
constant}}
 #endif
+
+#ifndef WITHOUT_FIXED_POINT
+const char *c = 10.0k;  // expected-error{{cannot initialize a variable of 
type 'const char *' with an rvalue of type '_Accum'}}
+#endif
diff --git a/llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp 
b/llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp
index eb2d992c7e75e..f00ff1565c665 100644
--- a/llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp
@@ -224,12 +224,15 @@ bool DebugHandlerBase::isUnsignedDIType(const DIType *Ty) 
{
   Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
   Encoding == dwarf::DW_ATE_boolean ||
   Encoding == dwarf::DW_ATE_complex_float ||
+  Encoding == dwarf::DW_ATE_signed_fixed ||
+  Encoding == dwarf::DW_ATE_unsigned_fixed ||
   (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
Ty->getName() == "decltype(nullptr)")) &&
  "Unsupported encoding");
   return Encoding == dwarf::DW_ATE_unsigned ||
  Encoding == dwarf::DW_ATE_unsigned_char ||
  Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
+ Encoding == llvm::dwarf::DW_ATE_unsigned_fixed ||
  Ty->getTag() == dwarf::DW_TAG_unspecified_type;
 }
 

``




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


[clang] [llvm] Diagnose invalid fixed point conversion (PR #80763)

2024-02-05 Thread via cfe-commits

https://github.com/PiJoules created 
https://github.com/llvm/llvm-project/pull/80763

None

>From faf74616efab09e59aade180ce44b68e04259e0e Mon Sep 17 00:00:00 2001
From: Leonard Chan 
Date: Mon, 5 Feb 2024 14:55:34 -0800
Subject: [PATCH 1/2] [llvm] Fix assertion error where we didn't check fixed
 point types.

---
 llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp 
b/llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp
index eb2d992c7e75e..f00ff1565c665 100644
--- a/llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/DebugHandlerBase.cpp
@@ -224,12 +224,15 @@ bool DebugHandlerBase::isUnsignedDIType(const DIType *Ty) 
{
   Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF ||
   Encoding == dwarf::DW_ATE_boolean ||
   Encoding == dwarf::DW_ATE_complex_float ||
+  Encoding == dwarf::DW_ATE_signed_fixed ||
+  Encoding == dwarf::DW_ATE_unsigned_fixed ||
   (Ty->getTag() == dwarf::DW_TAG_unspecified_type &&
Ty->getName() == "decltype(nullptr)")) &&
  "Unsupported encoding");
   return Encoding == dwarf::DW_ATE_unsigned ||
  Encoding == dwarf::DW_ATE_unsigned_char ||
  Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean ||
+ Encoding == llvm::dwarf::DW_ATE_unsigned_fixed ||
  Ty->getTag() == dwarf::DW_TAG_unspecified_type;
 }
 

>From 9c8af35404e5f8f4737be1fc725000cf0c3d52f1 Mon Sep 17 00:00:00 2001
From: Leonard Chan 
Date: Mon, 5 Feb 2024 15:33:09 -0800
Subject: [PATCH 2/2] [Clang] Diagnose improper fixed point conversions in C++

---
 clang/include/clang/AST/Type.h | 7 +++
 clang/lib/Sema/SemaOverload.cpp| 5 -
 clang/test/Frontend/fixed_point_errors.cpp | 4 
 3 files changed, 15 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index d6a55f39a4bed..1942b0e67f65a 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -2613,6 +2613,9 @@ class alignas(TypeAlignment) Type : public 
ExtQualsTypeCommonBase {
   /// Return true if this is a fixed point or integer type.
   bool isFixedPointOrIntegerType() const;
 
+  /// Return true if this can be converted to (or from) a fixed point type.
+  bool isConvertibleToFixedPointType() const;
+
   /// Return true if this is a saturated fixed point type according to
   /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
   bool isSaturatedFixedPointType() const;
@@ -7493,6 +7496,10 @@ inline bool Type::isFixedPointOrIntegerType() const {
   return isFixedPointType() || isIntegerType();
 }
 
+inline bool Type::isConvertibleToFixedPointType() const {
+  return isRealFloatingType() || isFixedPointOrIntegerType();
+}
+
 inline bool Type::isSaturatedFixedPointType() const {
   if (const auto *BT = dyn_cast(CanonicalType)) {
 return BT->getKind() >= BuiltinType::SatShortAccum &&
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 940bcccb9e261..5fdaf15eaf342 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -2177,7 +2177,10 @@ static bool IsStandardConversion(Sema , Expr* From, 
QualType ToType,
  From->isIntegerConstantExpr(S.getASTContext())) {
 SCS.Second = ICK_Compatible_Conversion;
 FromType = ToType;
-  } else if (ToType->isFixedPointType() || FromType->isFixedPointType()) {
+  } else if ((ToType->isFixedPointType() &&
+  FromType->isConvertibleToFixedPointType()) ||
+ (FromType->isFixedPointType() &&
+  ToType->isConvertibleToFixedPointType())) {
 SCS.Second = ICK_Fixed_Point_Conversion;
 FromType = ToType;
   } else {
diff --git a/clang/test/Frontend/fixed_point_errors.cpp 
b/clang/test/Frontend/fixed_point_errors.cpp
index 4097cd73c8450..ef064bc38873d 100644
--- a/clang/test/Frontend/fixed_point_errors.cpp
+++ b/clang/test/Frontend/fixed_point_errors.cpp
@@ -14,3 +14,7 @@ int fract_int = 10r; // expected-error{{invalid suffix 
'r' on integer consta
 float accum_flt = 0.0k;  // expected-error{{invalid suffix 'k' on floating 
constant}}
 float fract_flt = 0.0r;  // expected-error{{invalid suffix 'r' on floating 
constant}}
 #endif
+
+#ifndef WITHOUT_FIXED_POINT
+const char *c = 10.0k;  // expected-error{{cannot initialize a variable of 
type 'const char *' with an rvalue of type '_Accum'}}
+#endif

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


[clang] [clang][CodeGen][UBSan] Fixing shift-exponent generation for _BitInt (PR #80515)

2024-02-05 Thread Adam Magier via cfe-commits

https://github.com/AdamMagierFOSS updated 
https://github.com/llvm/llvm-project/pull/80515

>From 4e1c37ae83dec050fc9b7aa172db01fa0b2b6d68 Mon Sep 17 00:00:00 2001
From: Adam Magier 
Date: Sat, 3 Feb 2024 00:38:54 +0100
Subject: [PATCH 1/3] [clang][CodeGen][UBSan] Fixing shift-exponent generation
 for _BitInt

Testing the shift-exponent check with small width _BitInt values exposed
a bug in ScalarExprEmitter::GetWidthMinusOneValue when using the result
to determine valid exponent sizes. False positives were reported for
some left shifts when width(LHS)-1 > range(RHS) and false negatives were
reported for right shifts when value(RHS) > range(LHS). This patch caps
the maximum value of GetWidthMinusOneValue to fit within range(RHS) to
fix the issue with left shifts and fixes a code generation in EmitShr to
fix the issue with right shifts.
---
 clang/lib/CodeGen/CGExprScalar.cpp  |  9 ++-
 clang/test/CodeGen/ubsan-shift-bitint.c | 36 +
 2 files changed, 44 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/CodeGen/ubsan-shift-bitint.c

diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 5502f685f64743..e2e3ed839714a2 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -4121,6 +4121,13 @@ Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* 
LHS,Value* RHS) {
 Ty = cast(VT->getElementType());
   else
 Ty = cast(LHS->getType());
+  // Testing with small _BitInt types has shown that Ty->getBitwidth() - 1
+  // can sometimes overflow the capacity of RHS->getType(), cap the value
+  // to be the largest RHS->getType() can hold
+  llvm::APInt RHSMax =
+  llvm::APInt::getMaxValue(RHS->getType()->getScalarSizeInBits());
+  if (RHSMax.ult(Ty->getBitWidth()))
+return llvm::ConstantInt::get(RHS->getType(), RHSMax);
   return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
 }
 
@@ -4235,7 +4242,7 @@ Value *ScalarExprEmitter::EmitShr(const BinOpInfo ) {
isa(Ops.LHS->getType())) {
 CodeGenFunction::SanitizerScope SanScope();
 llvm::Value *Valid =
-Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
+Builder.CreateICmpULE(Ops.RHS, GetWidthMinusOneValue(Ops.LHS, 
Ops.RHS));
 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
   }
 
diff --git a/clang/test/CodeGen/ubsan-shift-bitint.c 
b/clang/test/CodeGen/ubsan-shift-bitint.c
new file mode 100644
index 00..8ca94b7de5a42d
--- /dev/null
+++ b/clang/test/CodeGen/ubsan-shift-bitint.c
@@ -0,0 +1,36 @@
+// RUN: %clang_cc1 %s -O0 -fsanitize=shift-exponent -emit-llvm -o - | 
FileCheck %s
+
+// Checking that the code generation is using the unextended/untruncated
+// exponent values and capping the values accordingly
+
+// CHECK-LABEL: define{{.*}} i32 @test_left_variable
+int test_left_variable(unsigned _BitInt(5) b, unsigned _BitInt(2) e) {
+  // CHECK: [[E_REG:%.+]] = load [[E_SIZE:i2]]
+  // CHECK: icmp ule [[E_SIZE]] [[E_REG]], -1
+  return b << e;
+}
+
+// CHECK-LABEL: define{{.*}} i32 @test_right_variable
+int test_right_variable(unsigned _BitInt(2) b, unsigned _BitInt(3) e) {
+  // CHECK: [[E_REG:%.+]] = load [[E_SIZE:i3]]
+  // CHECK: icmp ule [[E_SIZE]] [[E_REG]], 1
+  return b >> e;
+}
+
+// Old code generation would give false positives on left shifts when:
+//   value(e) > (width(b) - 1 % 2 ** width(e))
+// CHECK-LABEL: define{{.*}} i32 @test_left_literal
+int test_left_literal(unsigned _BitInt(5) b) {
+  // CHECK-NOT: br i1 false, label %cont, label %handler.shift_out_of_bounds
+  // CHECK: br i1 true, label %cont, label %handler.shift_out_of_bounds
+  return b << 3uwb;
+}
+
+// Old code generation would give false positives on right shifts when:
+//   (value(e) % 2 ** width(b)) < width(b)
+// CHECK-LABEL: define{{.*}} i32 @test_right_literal
+int test_right_literal(unsigned _BitInt(2) b) {
+  // CHECK-NOT: br i1 true, label %cont, label %handler.shift_out_of_bounds
+  // CHECK: br i1 false, label %cont, label %handler.shift_out_of_bounds
+  return b >> 4uwb;
+}

>From c3be3ebd7a8ae57d319eedbb97ab85324c814db2 Mon Sep 17 00:00:00 2001
From: Adam Magier 
Date: Tue, 6 Feb 2024 00:11:19 +0100
Subject: [PATCH 2/3] Updating with feedback

---
 clang/lib/CodeGen/CGExprScalar.cpp  | 27 +
 clang/test/CodeGen/ubsan-shift-bitint.c |  4 ++--
 2 files changed, 16 insertions(+), 15 deletions(-)

diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index e2e3ed839714a2..f08fb8d4e3b349 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -774,7 +774,7 @@ class ScalarExprEmitter
   void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo ,
   llvm::Value *Zero,bool 
isDiv);
   // Common helper for getting how wide LHS of shift is.
-  static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
+  

[clang] [clang][CodeGen][UBSan] Fixing shift-exponent generation for _BitInt (PR #80515)

2024-02-05 Thread Adam Magier via cfe-commits

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


[clang] Consider aggregate bases when checking if an InitListExpr is constant (PR #80519)

2024-02-05 Thread Reid Kleckner via cfe-commits


@@ -108,3 +109,22 @@ int computed_with_lambda = [] {
   return result;
 }();
 #endif
+
+#if __cplusplus >= 201703L
+namespace DynamicFileScopeLiteral {
+// This covers the case where we have a file-scope compound literal with a
+// non-constant initializer in C++. Previously, we had a bug where Clang forgot
+// to consider initializer list elements for bases.
+struct Empty {};
+struct Foo : Empty {
+  int x;
+  int y;
+};
+int f();
+Foo o = (Foo){
+  {},
+  1,
+  f() // expected-error {{initializer element is not a compile-time constant}}

rnk wrote:

That is correct and I did discover that in my testing, but I think fixing that 
goes beyond the scope of this patch. Clang currently rejects this case if you 
remove the empty base: https://godbolt.org/z/1x8hshM75 Adding support for 
non-constant compound literals at file scope requires codegen changes, and this 
is fixing a small bug to make more `isConstantInitializer` correct.

The real issue is that I couldn't find a better way to test 
`isConstantInitializer` that will be resilient to that future bug fix, and I'm 
not sure what to do about that.

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


[clang] [RISCV] Add -march string as Module metadata in IR. (PR #80760)

2024-02-05 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-backend-risc-v

Author: Craig Topper (topperc)


Changes

In an LTO build, we don't set the ELF attributes to indicate what extensions 
were compiled with. The target CPU/Attrs in RISCVTargetMachine do not get set 
for an LTO build. Each function gets a target-cpu/feature attribute, but this 
isn't usable to set ELF attributs since we wouldn't know what function to use. 
We can't just once since it might have been compiler with an attribute likes 
target_verson.

This patch adds the ISA as Module metadata so we can retrieve it in the 
backend. Individual translation units can still be compiled with different 
strings so we need to collect the unique set when Modules are merged.

The backend will need to combine the unique ISA strings to produce a single 
value for the ELF attributes. This will be done in a separate patch.

---

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


3 Files Affected:

- (modified) clang/lib/CodeGen/CodeGenModule.cpp (+11) 
- (modified) clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c 
(+175-175) 
- (added) clang/test/CodeGen/RISCV/riscv-metadata-arch.c (+20) 


``diff
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 36b63d78b06f8..25b8d5cae36d3 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -67,6 +67,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ConvertUTF.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/RISCVISAInfo.h"
 #include "llvm/Support/TimeProfiler.h"
 #include "llvm/Support/xxhash.h"
 #include "llvm/TargetParser/Triple.h"
@@ -1056,6 +1057,16 @@ void CodeGenModule::Release() {
 llvm::LLVMContext  = TheModule.getContext();
 getModule().addModuleFlag(llvm::Module::Error, "target-abi",
   llvm::MDString::get(Ctx, ABIStr));
+
+const std::vector  =
+getTarget().getTargetOpts().Features;
+auto ParseResult =
+llvm::RISCVISAInfo::parseFeatures(T.isRISCV64() ? 64 : 32, Features);
+if (!errorToBool(ParseResult.takeError()))
+  getModule().addModuleFlag(
+  llvm::Module::AppendUnique, "riscv-arch",
+  llvm::MDNode::get(
+  Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString(;
   }
 
   if (CodeGenOpts.SanitizeCfiCrossDso) {
diff --git a/clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c 
b/clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c
index 897edbc6450af..b11c2ca010e7c 100644
--- a/clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c
+++ b/clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c
@@ -28,190 +28,190 @@ vint8m1_t *scvc1, *scvc2;
 
 // clang-format off
 void ntl_all_sizes() {   // CHECK-LABEL: 
ntl_all_sizes
-  uc = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
i8{{.*}}align 1, !nontemporal !4, !riscv-nontemporal-domain !5
-  sc = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
i8{{.*}}align 1, !nontemporal !4, !riscv-nontemporal-domain !5
-  us = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
i16{{.*}}align 2, !nontemporal !4, !riscv-nontemporal-domain !5
-  ss = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
i16{{.*}}align 2, !nontemporal !4, !riscv-nontemporal-domain !5
-  ui = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
i32{{.*}}align 4, !nontemporal !4, !riscv-nontemporal-domain !5
-  si = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
i32{{.*}}align 4, !nontemporal !4, !riscv-nontemporal-domain !5
-  ull = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE); // CHECK: load 
i64{{.*}}align 8, !nontemporal !4, !riscv-nontemporal-domain !5
-  sll = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE); // CHECK: load 
i64{{.*}}align 8, !nontemporal !4, !riscv-nontemporal-domain !5
-  h1 = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
half{{.*}}align 2, !nontemporal !4, !riscv-nontemporal-domain !5
-  f1 = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
float{{.*}}align 4, !nontemporal !4, !riscv-nontemporal-domain !5
-  d1 = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
double{{.*}}align 8, !nontemporal !4, !riscv-nontemporal-domain !5
-  v4si1 = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // 
CHECK: load <4 x i32>{{.*}}align 16, !nontemporal !4, !riscv-nontemporal-domain 
!5
-  v8ss1 = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // 
CHECK: load <8 x i16>{{.*}}align 16, !nontemporal !4, !riscv-nontemporal-domain 
!5
-  v16sc1 = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // 
CHECK: load <16 x i8>{{.*}}align 16, !nontemporal !4, !riscv-nontemporal-domain 
!5
-  *scvi1 = __riscv_ntl_load(scvi2, 

[clang] [RISCV] Add -march string as Module metadata in IR. (PR #80760)

2024-02-05 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-codegen

Author: Craig Topper (topperc)


Changes

In an LTO build, we don't set the ELF attributes to indicate what extensions 
were compiled with. The target CPU/Attrs in RISCVTargetMachine do not get set 
for an LTO build. Each function gets a target-cpu/feature attribute, but this 
isn't usable to set ELF attributs since we wouldn't know what function to use. 
We can't just once since it might have been compiler with an attribute likes 
target_verson.

This patch adds the ISA as Module metadata so we can retrieve it in the 
backend. Individual translation units can still be compiled with different 
strings so we need to collect the unique set when Modules are merged.

The backend will need to combine the unique ISA strings to produce a single 
value for the ELF attributes. This will be done in a separate patch.

---

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


3 Files Affected:

- (modified) clang/lib/CodeGen/CodeGenModule.cpp (+11) 
- (modified) clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c 
(+175-175) 
- (added) clang/test/CodeGen/RISCV/riscv-metadata-arch.c (+20) 


``diff
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 36b63d78b06f83..25b8d5cae36d3a 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -67,6 +67,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ConvertUTF.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/RISCVISAInfo.h"
 #include "llvm/Support/TimeProfiler.h"
 #include "llvm/Support/xxhash.h"
 #include "llvm/TargetParser/Triple.h"
@@ -1056,6 +1057,16 @@ void CodeGenModule::Release() {
 llvm::LLVMContext  = TheModule.getContext();
 getModule().addModuleFlag(llvm::Module::Error, "target-abi",
   llvm::MDString::get(Ctx, ABIStr));
+
+const std::vector  =
+getTarget().getTargetOpts().Features;
+auto ParseResult =
+llvm::RISCVISAInfo::parseFeatures(T.isRISCV64() ? 64 : 32, Features);
+if (!errorToBool(ParseResult.takeError()))
+  getModule().addModuleFlag(
+  llvm::Module::AppendUnique, "riscv-arch",
+  llvm::MDNode::get(
+  Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString(;
   }
 
   if (CodeGenOpts.SanitizeCfiCrossDso) {
diff --git a/clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c 
b/clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c
index 897edbc6450af6..b11c2ca010e7ce 100644
--- a/clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c
+++ b/clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c
@@ -28,190 +28,190 @@ vint8m1_t *scvc1, *scvc2;
 
 // clang-format off
 void ntl_all_sizes() {   // CHECK-LABEL: 
ntl_all_sizes
-  uc = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
i8{{.*}}align 1, !nontemporal !4, !riscv-nontemporal-domain !5
-  sc = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
i8{{.*}}align 1, !nontemporal !4, !riscv-nontemporal-domain !5
-  us = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
i16{{.*}}align 2, !nontemporal !4, !riscv-nontemporal-domain !5
-  ss = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
i16{{.*}}align 2, !nontemporal !4, !riscv-nontemporal-domain !5
-  ui = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
i32{{.*}}align 4, !nontemporal !4, !riscv-nontemporal-domain !5
-  si = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
i32{{.*}}align 4, !nontemporal !4, !riscv-nontemporal-domain !5
-  ull = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE); // CHECK: load 
i64{{.*}}align 8, !nontemporal !4, !riscv-nontemporal-domain !5
-  sll = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE); // CHECK: load 
i64{{.*}}align 8, !nontemporal !4, !riscv-nontemporal-domain !5
-  h1 = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
half{{.*}}align 2, !nontemporal !4, !riscv-nontemporal-domain !5
-  f1 = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
float{{.*}}align 4, !nontemporal !4, !riscv-nontemporal-domain !5
-  d1 = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
double{{.*}}align 8, !nontemporal !4, !riscv-nontemporal-domain !5
-  v4si1 = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // 
CHECK: load <4 x i32>{{.*}}align 16, !nontemporal !4, !riscv-nontemporal-domain 
!5
-  v8ss1 = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // 
CHECK: load <8 x i16>{{.*}}align 16, !nontemporal !4, !riscv-nontemporal-domain 
!5
-  v16sc1 = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // 
CHECK: load <16 x i8>{{.*}}align 16, !nontemporal !4, !riscv-nontemporal-domain 
!5
-  *scvi1 = 

[clang] [RISCV] Add -march string as Module metadata in IR. (PR #80760)

2024-02-05 Thread Craig Topper via cfe-commits

https://github.com/topperc created 
https://github.com/llvm/llvm-project/pull/80760

In an LTO build, we don't set the ELF attributes to indicate what extensions 
were compiled with. The target CPU/Attrs in RISCVTargetMachine do not get set 
for an LTO build. Each function gets a target-cpu/feature attribute, but this 
isn't usable to set ELF attributs since we wouldn't know what function to use. 
We can't just once since it might have been compiler with an attribute likes 
target_verson.

This patch adds the ISA as Module metadata so we can retrieve it in the 
backend. Individual translation units can still be compiled with different 
strings so we need to collect the unique set when Modules are merged.

The backend will need to combine the unique ISA strings to produce a single 
value for the ELF attributes. This will be done in a separate patch.

>From 8000459a247317400eda6213a23f32ac89e1ea75 Mon Sep 17 00:00:00 2001
From: Craig Topper 
Date: Mon, 5 Feb 2024 14:57:17 -0800
Subject: [PATCH] [RISCV] Add -march string as Module metadata in IR.

In an LTO build, we don't set the ELF attributes to indicate what
extensions were compiled with. The target CPU/Attrs in RISCVTargetMachine
do not get set for an LTO build. Each function gets a target-cpu/feature
attribute, but this isn't usable to set ELF attributs since we wouldn't
know what function to use. We can't just once since it might have been
compiler with an attribute likes target_verson.

This patch adds the ISA as Module metadata so we can retrieve it in the
backend. Individual translation units can still be compiled with different
strings so we need to collect the unique set when Modules are merged.

The backend will need to combine the unique ISA strings to produce a single
value for the ELF attributes. This will be done in a separate patch.
---
 clang/lib/CodeGen/CodeGenModule.cpp   |  11 +
 .../RISCV/ntlh-intrinsics/riscv32-zihintntl.c | 350 +-
 .../test/CodeGen/RISCV/riscv-metadata-arch.c  |  20 +
 3 files changed, 206 insertions(+), 175 deletions(-)
 create mode 100644 clang/test/CodeGen/RISCV/riscv-metadata-arch.c

diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 36b63d78b06f8..25b8d5cae36d3 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -67,6 +67,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ConvertUTF.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/RISCVISAInfo.h"
 #include "llvm/Support/TimeProfiler.h"
 #include "llvm/Support/xxhash.h"
 #include "llvm/TargetParser/Triple.h"
@@ -1056,6 +1057,16 @@ void CodeGenModule::Release() {
 llvm::LLVMContext  = TheModule.getContext();
 getModule().addModuleFlag(llvm::Module::Error, "target-abi",
   llvm::MDString::get(Ctx, ABIStr));
+
+const std::vector  =
+getTarget().getTargetOpts().Features;
+auto ParseResult =
+llvm::RISCVISAInfo::parseFeatures(T.isRISCV64() ? 64 : 32, Features);
+if (!errorToBool(ParseResult.takeError()))
+  getModule().addModuleFlag(
+  llvm::Module::AppendUnique, "riscv-arch",
+  llvm::MDNode::get(
+  Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString(;
   }
 
   if (CodeGenOpts.SanitizeCfiCrossDso) {
diff --git a/clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c 
b/clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c
index 897edbc6450af..b11c2ca010e7c 100644
--- a/clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c
+++ b/clang/test/CodeGen/RISCV/ntlh-intrinsics/riscv32-zihintntl.c
@@ -28,190 +28,190 @@ vint8m1_t *scvc1, *scvc2;
 
 // clang-format off
 void ntl_all_sizes() {   // CHECK-LABEL: 
ntl_all_sizes
-  uc = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
i8{{.*}}align 1, !nontemporal !4, !riscv-nontemporal-domain !5
-  sc = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
i8{{.*}}align 1, !nontemporal !4, !riscv-nontemporal-domain !5
-  us = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
i16{{.*}}align 2, !nontemporal !4, !riscv-nontemporal-domain !5
-  ss = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
i16{{.*}}align 2, !nontemporal !4, !riscv-nontemporal-domain !5
-  ui = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
i32{{.*}}align 4, !nontemporal !4, !riscv-nontemporal-domain !5
-  si = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE);   // CHECK: load 
i32{{.*}}align 4, !nontemporal !4, !riscv-nontemporal-domain !5
-  ull = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE); // CHECK: load 
i64{{.*}}align 8, !nontemporal !4, !riscv-nontemporal-domain !5
-  sll = __riscv_ntl_load(, __RISCV_NTLH_INNERMOST_PRIVATE); // CHECK: load 
i64{{.*}}align 8, !nontemporal !4, !riscv-nontemporal-domain !5
-  h1 = __riscv_ntl_load(, 

[compiler-rt] [openmp] [clang] [lldb] [mlir] [llvm] [libcxx] [flang] [libc] [lld] [clang-tools-extra] [Driver] Report invalid target triple versions for all environment types. (PR #78655)

2024-02-05 Thread Mike Hommey via cfe-commits

glandium wrote:

There's apparently also wasm32-wasi-preview2 and wasm32-wasi-pthread, which I 
suppose are equally broken by this change.

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


[clang-tools-extra] [openmp] [compiler-rt] [llvm] [libcxx] [lldb] [lld] [clang] [flang] [libc] [mlir] [Driver] Report invalid target triple versions for all environment types. (PR #78655)

2024-02-05 Thread Mike Hommey via cfe-commits

glandium wrote:

We stumbled upon this downstream because we have jobs building wasi-sdk with 
clang-trunk, and wasi-sdk builds some things with that target. It apparently 
comes from https://github.com/WebAssembly/wasi-libc/pull/381

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


[clang] [clang][CodeGen][UBSan] Fixing shift-exponent generation for _BitInt (PR #80515)

2024-02-05 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff e296cedcd686e24fee75756185669f1bb3b47fdd 
c3be3ebd7a8ae57d319eedbb97ab85324c814db2 -- 
clang/test/CodeGen/ubsan-shift-bitint.c clang/lib/CodeGen/CGExprScalar.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index f08fb8d4e3..df8f71cf1d 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -774,7 +774,7 @@ public:
   void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo ,
   llvm::Value *Zero,bool 
isDiv);
   // Common helper for getting how wide LHS of shift is.
-  static Value *GetMaximumShiftAmount(Value* LHS,Value* RHS);
+  static Value *GetMaximumShiftAmount(Value *LHS, Value *RHS);
 
   // Used for shifting constraints for OpenCL, do mask for powers of 2, URem 
for
   // non powers of two.
@@ -4115,7 +4115,7 @@ Value *ScalarExprEmitter::EmitSub(const BinOpInfo ) {
   return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
 }
 
-Value *ScalarExprEmitter::GetMaximumShiftAmount(Value* LHS,Value* RHS) {
+Value *ScalarExprEmitter::GetMaximumShiftAmount(Value *LHS, Value *RHS) {
   llvm::IntegerType *Ty;
   if (llvm::VectorType *VT = dyn_cast(LHS->getType()))
 Ty = cast(VT->getElementType());
@@ -4141,7 +4141,7 @@ Value *ScalarExprEmitter::ConstrainShiftValue(Value *LHS, 
Value *RHS,
 Ty = cast(LHS->getType());
 
   if (llvm::isPowerOf2_64(Ty->getBitWidth()))
-return Builder.CreateAnd(RHS, GetMaximumShiftAmount(LHS, RHS), Name);
+return Builder.CreateAnd(RHS, GetMaximumShiftAmount(LHS, RHS), Name);
 
   return Builder.CreateURem(
   RHS, llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth()), Name);

``




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


[clang] [Clang] Convert __builtin_dynamic_object_size into a calculation (PR #80256)

2024-02-05 Thread Bill Wendling via cfe-commits


@@ -1051,6 +1052,145 @@ CodeGenFunction::emitFlexibleArrayMemberSize(const Expr 
*E, unsigned Type,
   return Builder.CreateSelect(Cmp, Res, ConstantInt::get(ResType, 0, 
IsSigned));
 }
 
+namespace {
+
+/// \p StructBaseExpr returns the base \p Expr with a structure or union type.
+struct StructBaseExpr : public ConstStmtVisitor {
+  StructBaseExpr() = default;
+
+  
//======//
+  //Visitor Methods
+  
//======//
+
+  const Expr *VisitStmt(const Stmt *S) { return nullptr; }
+
+  const Expr *Visit(const Expr *E) {
+QualType Ty = E->getType();
+if (Ty->isStructureType() || Ty->isUnionType())
+  return E;
+
+return ConstStmtVisitor::Visit(E);
+  }
+
+  const Expr *VisitDeclRefExpr(const DeclRefExpr *E) { return E; }
+
+  const Expr *VisitMemberExpr(const MemberExpr *E) {
+return Visit(E->getBase());
+  }
+  const Expr *VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
+return Visit(E->getBase());
+  }
+  const Expr *VisitCastExpr(const CastExpr *E) {
+return Visit(E->getSubExpr());
+  }
+  const Expr *VisitParenExpr(const ParenExpr *E) {
+return Visit(E->getSubExpr());
+  }
+  const Expr *VisitUnaryAddrOf(const clang::UnaryOperator *E) {
+return Visit(E->getSubExpr());
+  }
+  const Expr *VisitUnaryDeref(const clang::UnaryOperator *E) {
+return Visit(E->getSubExpr());
+  }
+};
+
+} // end anonymous namespace
+
+/// The offset of a field from the beginning of the record.
+llvm::Value *
+CodeGenFunction::tryEmitObjectSizeCalculation(const Expr *E, unsigned Type,
+  llvm::IntegerType *ResType) {
+  if ((Type & 0x01) != 0)
+// We handle only the whole object size.
+return nullptr;
+
+  E = E->IgnoreParenImpCasts();
+
+  const Expr *Base = StructBaseExpr().Visit(E);
+  if (!Base)
+return nullptr;
+
+  const RecordDecl *RD = Base->getType()->getAsRecordDecl();
+  if (!RD)
+return nullptr;
+
+  // Get the full size of the struct.
+  ASTContext  = getContext();
+  const RecordDecl *OuterRD = RD->getOuterLexicalRecordContext();
+  const clang::Type *RT = OuterRD->getTypeForDecl();
+  CharUnits RecordSize = Ctx.getTypeSizeInChars(RT);
+
+  Value *Res = nullptr;
+
+  if (const auto *U = dyn_cast(E);
+  U && (U->getOpcode() == UO_AddrOf || U->getOpcode() == UO_Deref))
+E = U->getSubExpr()->IgnoreParenImpCasts();
+
+  if (const auto *ASE = dyn_cast(E)) {
+const Expr *Idx = ASE->getIdx();
+Base = ASE->getBase()->IgnoreParenImpCasts();
+
+if (const auto *ME = dyn_cast(Base);
+ME && ME->getType()->isConstantArrayType()) {
+  // The simple case:
+  //
+  // struct s {
+  // int arr[42];
+  // char c;
+  // /* others */
+  // };
+  //
+  // __builtin_dynamic_object_size(>arr[idx], 0);
+  //
+  // We can translate the __builtin_dynamic_object_call into:
+  //
+  // sizeof(struct s) - offsetof(arr) - (idx * sizeof(int))
+  //

bwendling wrote:

This PR isn't dealing with the sub-object issue from the previous PR. This just 
mimics the current behavior of the intrinsic. I'll be extending it to 
sub-objects further on. The point about type 2 returning zero if the argument 
can point to multiple objects is messy on the GCC side of things. It's there 
because of how GCC's internal representation, but doesn't appear to apply to 
Clang.

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


[clang] [clang][CodeGen][UBSan] Fixing shift-exponent generation for _BitInt (PR #80515)

2024-02-05 Thread Adam Magier via cfe-commits

AdamMagierFOSS wrote:

> > One thing I'll preemptively address is I didn't know where to put the new 
> > unit testing - creating a separate file seems a little heavy handed but I 
> > see that there's a test for UBSan shift generation 
> > (`clang/test/CodeGen/ubsan-shift.c`) and one for UBSan + _BitInt 
> > (`clang/test/CodeGen/ext-int-sanitizer.cpp`). Both seem equally "valid" but 
> > neither seem to test in the same way that I'm trying to test these changes. 
> > Advice on this would be appreciated.
> 
> Either one is fine as long as you aren't having to narrow the portability of 
> a test case in order to use `_BitInt` in it.
> 
> Patch generally LGTM.

After thinking about it some more maybe it would be best to keep this test its 
own file. The other two tests check the optimized code but in this test I 
explicitly want to test the unoptimized code to make sure the base code 
generation is going as anticipated. The way I understand it, either I include 
these test cases in the existing tests and there's a disconnect in how the 
"first part" of the test gets performed vs the "second part" of the test or I 
keep the test separate. Unless there's a strong opinion otherwise I think this 
would be the best way forward.

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


[clang] [clang][CodeGen][UBSan] Fixing shift-exponent generation for _BitInt (PR #80515)

2024-02-05 Thread Adam Magier via cfe-commits


@@ -0,0 +1,36 @@
+// RUN: %clang_cc1 %s -O0 -fsanitize=shift-exponent -emit-llvm -o - | 
FileCheck %s
+
+// Checking that the code generation is using the unextended/untruncated
+// exponent values and capping the values accordingly
+
+// CHECK-LABEL: define{{.*}} i32 @test_left_variable
+int test_left_variable(unsigned _BitInt(5) b, unsigned _BitInt(2) e) {
+  // CHECK: [[E_REG:%.+]] = load [[E_SIZE:i2]]
+  // CHECK: icmp ule [[E_SIZE]] [[E_REG]], -1

AdamMagierFOSS wrote:

I tried to include this type of optimization in this patch but there's an 
assert that expects a check to be generated when the shift-exponent check is 
enabled. I suppose it wouldn't be too difficult to refactor this but from what 
I can tell none of the UBSan checks are really optimized in this way and 
instead rely on the middle end to optimize this out (e.g. the array-bounds 
check still generates a check on an array of size 256 when indexing with 
`uint8_t`). Don't know how much of an impact this type of pre-emptive 
optimization would have either.

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


[clang] [clang][CodeGen][UBSan] Fixing shift-exponent generation for _BitInt (PR #80515)

2024-02-05 Thread Adam Magier via cfe-commits


@@ -4121,6 +4121,13 @@ Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* 
LHS,Value* RHS) {
 Ty = cast(VT->getElementType());
   else
 Ty = cast(LHS->getType());
+  // Testing with small _BitInt types has shown that Ty->getBitwidth() - 1

AdamMagierFOSS wrote:

I've renamed the function to be more accurate, but to keep a consistent style 
with the surrounding code I've not put a formal function description and 
instead kept the explanatory comment (though rewriting it to not include 
mentions of _BitInt).

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


[clang] [clang][CodeGen][UBSan] Fixing shift-exponent generation for _BitInt (PR #80515)

2024-02-05 Thread Adam Magier via cfe-commits


@@ -0,0 +1,36 @@
+// RUN: %clang_cc1 %s -O0 -fsanitize=shift-exponent -emit-llvm -o - | 
FileCheck %s

AdamMagierFOSS wrote:

Sounds good, thank you for the recommendation!

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


[clang] [clang][CodeGen][UBSan] Fixing shift-exponent generation for _BitInt (PR #80515)

2024-02-05 Thread Adam Magier via cfe-commits

https://github.com/AdamMagierFOSS updated 
https://github.com/llvm/llvm-project/pull/80515

>From 4e1c37ae83dec050fc9b7aa172db01fa0b2b6d68 Mon Sep 17 00:00:00 2001
From: Adam Magier 
Date: Sat, 3 Feb 2024 00:38:54 +0100
Subject: [PATCH 1/2] [clang][CodeGen][UBSan] Fixing shift-exponent generation
 for _BitInt

Testing the shift-exponent check with small width _BitInt values exposed
a bug in ScalarExprEmitter::GetWidthMinusOneValue when using the result
to determine valid exponent sizes. False positives were reported for
some left shifts when width(LHS)-1 > range(RHS) and false negatives were
reported for right shifts when value(RHS) > range(LHS). This patch caps
the maximum value of GetWidthMinusOneValue to fit within range(RHS) to
fix the issue with left shifts and fixes a code generation in EmitShr to
fix the issue with right shifts.
---
 clang/lib/CodeGen/CGExprScalar.cpp  |  9 ++-
 clang/test/CodeGen/ubsan-shift-bitint.c | 36 +
 2 files changed, 44 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/CodeGen/ubsan-shift-bitint.c

diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 5502f685f6474..e2e3ed839714a 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -4121,6 +4121,13 @@ Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* 
LHS,Value* RHS) {
 Ty = cast(VT->getElementType());
   else
 Ty = cast(LHS->getType());
+  // Testing with small _BitInt types has shown that Ty->getBitwidth() - 1
+  // can sometimes overflow the capacity of RHS->getType(), cap the value
+  // to be the largest RHS->getType() can hold
+  llvm::APInt RHSMax =
+  llvm::APInt::getMaxValue(RHS->getType()->getScalarSizeInBits());
+  if (RHSMax.ult(Ty->getBitWidth()))
+return llvm::ConstantInt::get(RHS->getType(), RHSMax);
   return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
 }
 
@@ -4235,7 +4242,7 @@ Value *ScalarExprEmitter::EmitShr(const BinOpInfo ) {
isa(Ops.LHS->getType())) {
 CodeGenFunction::SanitizerScope SanScope();
 llvm::Value *Valid =
-Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
+Builder.CreateICmpULE(Ops.RHS, GetWidthMinusOneValue(Ops.LHS, 
Ops.RHS));
 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
   }
 
diff --git a/clang/test/CodeGen/ubsan-shift-bitint.c 
b/clang/test/CodeGen/ubsan-shift-bitint.c
new file mode 100644
index 0..8ca94b7de5a42
--- /dev/null
+++ b/clang/test/CodeGen/ubsan-shift-bitint.c
@@ -0,0 +1,36 @@
+// RUN: %clang_cc1 %s -O0 -fsanitize=shift-exponent -emit-llvm -o - | 
FileCheck %s
+
+// Checking that the code generation is using the unextended/untruncated
+// exponent values and capping the values accordingly
+
+// CHECK-LABEL: define{{.*}} i32 @test_left_variable
+int test_left_variable(unsigned _BitInt(5) b, unsigned _BitInt(2) e) {
+  // CHECK: [[E_REG:%.+]] = load [[E_SIZE:i2]]
+  // CHECK: icmp ule [[E_SIZE]] [[E_REG]], -1
+  return b << e;
+}
+
+// CHECK-LABEL: define{{.*}} i32 @test_right_variable
+int test_right_variable(unsigned _BitInt(2) b, unsigned _BitInt(3) e) {
+  // CHECK: [[E_REG:%.+]] = load [[E_SIZE:i3]]
+  // CHECK: icmp ule [[E_SIZE]] [[E_REG]], 1
+  return b >> e;
+}
+
+// Old code generation would give false positives on left shifts when:
+//   value(e) > (width(b) - 1 % 2 ** width(e))
+// CHECK-LABEL: define{{.*}} i32 @test_left_literal
+int test_left_literal(unsigned _BitInt(5) b) {
+  // CHECK-NOT: br i1 false, label %cont, label %handler.shift_out_of_bounds
+  // CHECK: br i1 true, label %cont, label %handler.shift_out_of_bounds
+  return b << 3uwb;
+}
+
+// Old code generation would give false positives on right shifts when:
+//   (value(e) % 2 ** width(b)) < width(b)
+// CHECK-LABEL: define{{.*}} i32 @test_right_literal
+int test_right_literal(unsigned _BitInt(2) b) {
+  // CHECK-NOT: br i1 true, label %cont, label %handler.shift_out_of_bounds
+  // CHECK: br i1 false, label %cont, label %handler.shift_out_of_bounds
+  return b >> 4uwb;
+}

>From c3be3ebd7a8ae57d319eedbb97ab85324c814db2 Mon Sep 17 00:00:00 2001
From: Adam Magier 
Date: Tue, 6 Feb 2024 00:11:19 +0100
Subject: [PATCH 2/2] Updating with feedback

---
 clang/lib/CodeGen/CGExprScalar.cpp  | 27 +
 clang/test/CodeGen/ubsan-shift-bitint.c |  4 ++--
 2 files changed, 16 insertions(+), 15 deletions(-)

diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index e2e3ed839714a..f08fb8d4e3b34 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -774,7 +774,7 @@ class ScalarExprEmitter
   void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo ,
   llvm::Value *Zero,bool 
isDiv);
   // Common helper for getting how wide LHS of shift is.
-  static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
+  static 

[clang] [clang][CodeGen][UBSan] Fixing shift-exponent generation for _BitInt (PR #80515)

2024-02-05 Thread Adam Magier via cfe-commits

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


[clang] [Clang] Convert __builtin_dynamic_object_size into a calculation (PR #80256)

2024-02-05 Thread Bill Wendling via cfe-commits

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


[clang] [Clang] Convert __builtin_dynamic_object_size into a calculation (PR #80256)

2024-02-05 Thread Bill Wendling via cfe-commits

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


[clang] [Clang] Convert __builtin_dynamic_object_size into a calculation (PR #80256)

2024-02-05 Thread Bill Wendling via cfe-commits


@@ -1051,6 +1052,145 @@ CodeGenFunction::emitFlexibleArrayMemberSize(const Expr 
*E, unsigned Type,
   return Builder.CreateSelect(Cmp, Res, ConstantInt::get(ResType, 0, 
IsSigned));
 }
 
+namespace {
+
+/// \p StructBaseExpr returns the base \p Expr with a structure or union type.
+struct StructBaseExpr : public ConstStmtVisitor {
+  StructBaseExpr() = default;
+
+  
//======//
+  //Visitor Methods
+  
//======//
+
+  const Expr *VisitStmt(const Stmt *S) { return nullptr; }
+
+  const Expr *Visit(const Expr *E) {
+QualType Ty = E->getType();
+if (Ty->isStructureType() || Ty->isUnionType())
+  return E;
+
+return ConstStmtVisitor::Visit(E);
+  }
+
+  const Expr *VisitDeclRefExpr(const DeclRefExpr *E) { return E; }
+
+  const Expr *VisitMemberExpr(const MemberExpr *E) {
+return Visit(E->getBase());
+  }
+  const Expr *VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
+return Visit(E->getBase());
+  }
+  const Expr *VisitCastExpr(const CastExpr *E) {
+return Visit(E->getSubExpr());
+  }
+  const Expr *VisitParenExpr(const ParenExpr *E) {
+return Visit(E->getSubExpr());
+  }
+  const Expr *VisitUnaryAddrOf(const clang::UnaryOperator *E) {
+return Visit(E->getSubExpr());
+  }
+  const Expr *VisitUnaryDeref(const clang::UnaryOperator *E) {
+return Visit(E->getSubExpr());
+  }

bwendling wrote:

The Visitor is only to get the structure that the member resides in. The thing 
about `__builtin_dynamic_object_size(p, 0)` is that we're not trying to 
calculate what `p` points to, but the size of the struct from p to the end. 
It's counter-intuitive, but it's not (currently) supported to ask `__bdos` the 
size of what `p` points to is.

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-02-05 Thread Alex Hoppen via cfe-commits


@@ -508,24 +513,46 @@ static bool mayBeValidIdentifier(llvm::StringRef Ident) {
   !isAsciiIdentifierStart(Ident.front(), AllowDollar))
 return false;
   for (char C : Ident) {
+if (AllowColon && C == ':')

ahoppen wrote:

Oh, I just assumed that the first selector argument had to be named. I never 
checked if it can be unnamed.

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-02-05 Thread Alex Hoppen via cfe-commits


@@ -538,11 +565,254 @@ std::optional checkName(const NamedDecl 
,
 Conflict->getLocation().printToString(ASTCtx.getSourceManager())};
 }
   }
-  if (Result)
+  if (Result) {
 InvalidNameMetric.record(1, toString(Result->K));
+return makeError(*Result);
+  }
+  return std::nullopt;
+}
+
+bool isMatchingSelectorName(const syntax::Token , const syntax::Token 
,
+const SourceManager ,
+llvm::StringRef SelectorName) {
+  if (SelectorName.empty())
+return Cur.kind() == tok::colon;
+  return Cur.kind() == tok::identifier && Next.kind() == tok::colon &&
+ Cur.text(SM) == SelectorName &&
+ // We require the selector name and : to be contiguous to avoid
+ // potential conflicts with ternary expression.
+ //
+ // e.g. support `foo:` but not `foo :`.
+ Cur.endLocation() == Next.location();
+}
+
+bool isSelectorLike(const syntax::Token , const syntax::Token ) {
+  return Cur.kind() == tok::identifier && Next.kind() == tok::colon &&
+ // We require the selector name and : to be contiguous.
+ // e.g. support `foo:` but not `foo :`.
+ Cur.endLocation() == Next.location();
+}
+
+bool parseMessageExpression(llvm::ArrayRef Tokens,
+const SourceManager , unsigned Index,
+unsigned Last, Selector Sel,
+std::vector ) {
+
+  unsigned NumArgs = Sel.getNumArgs();
+  llvm::SmallVector Closes;
+  SelectorPieces.clear();
+  while (Index < Last) {
+const auto  = Tokens[Index];
+
+if (Closes.empty()) {
+  auto PieceCount = SelectorPieces.size();
+  if (PieceCount < NumArgs &&
+  isMatchingSelectorName(Tok, Tokens[Index + 1], SM,
+ Sel.getNameForSlot(PieceCount))) {
+// If 'foo:' instead of ':' (empty selector), we need to skip the ':'
+// token after the name.
+if (!Sel.getNameForSlot(PieceCount).empty()) {
+  ++Index;
+}
+SelectorPieces.push_back(
+halfOpenToRange(SM, Tok.range(SM).toCharRange(SM)));
+continue;
+  }
+  // If we've found all pieces but the current token looks like another
+  // selector piece, it means the method being renamed is a strict prefix 
of
+  // the selector we've found - should be skipped.
+  if (SelectorPieces.size() >= NumArgs &&
+  isSelectorLike(Tok, Tokens[Index + 1]))
+return false;
+}
+
+switch (Tok.kind()) {
+case tok::l_square:
+  Closes.push_back(']');
+  break;
+case tok::l_paren:
+  Closes.push_back(')');
+  break;
+case tok::l_brace:
+  Closes.push_back('}');
+  break;
+case tok::r_square:
+  if (Closes.empty())
+return SelectorPieces.size() == NumArgs;
+
+  if (Closes.back() != ']')
+return false;
+  Closes.pop_back();
+  break;
+case tok::r_paren:
+  if (Closes.empty() || Closes.back() != ')')
+return false;
+  Closes.pop_back();
+  break;
+case tok::r_brace:
+  if (Closes.empty() || Closes.back() != '}')
+return false;
+  Closes.pop_back();
+  break;
+case tok::semi:
+  // top level ; ends all statements.
+  if (Closes.empty())
+return false;
+  break;
+default:
+  break;
+}
+
+++Index;
+  }
+  return false;
+}
+
+/// Collects all ranges of the given identifier/selector in the source code.
+///
+/// If a selector is given, this does a full lex of the given source code in
+/// order to identify all selector fragments (e.g. in method exprs/decls) since
+/// they are non-contiguous.
+std::vector collectRenameIdentifierRanges(
+llvm::StringRef Identifier, llvm::StringRef Content,
+const LangOptions , std::optional Selector) {
+  std::vector Ranges;
+  if (!Selector) {
+auto IdentifierRanges =
+collectIdentifierRanges(Identifier, Content, LangOpts);
+for (const auto  : IdentifierRanges)
+  Ranges.emplace_back(R);
+return Ranges;
+  }
+  // FIXME: InMemoryFileAdapter crashes unless the buffer is null terminated!
+  std::string NullTerminatedCode = Content.str();
+  SourceManagerForFile FileSM("mock_file_name.cpp", NullTerminatedCode);
+  auto  = FileSM.get();
+
+  // We track parens and braces to ensure that we don't accidentally try 
parsing
+  // a method declaration or definition which isn't at the top level or similar
+  // looking expressions (e.g. an @selector() expression).
+  unsigned ParenCount = 0;
+  unsigned BraceCount = 0;
+  unsigned NumArgs = Selector->getNumArgs();
+
+  std::vector SelectorPieces;
+  auto Tokens = syntax::tokenize(SM.getMainFileID(), SM, LangOpts);
+  unsigned Last = Tokens.size() - 1;
+  for (unsigned Index = 0; Index < Last; ++Index) {
+const auto  = Tokens[Index];
+
+if (BraceCount == 0 && ParenCount == 0) {
+  auto PieceCount = 

[clang] [clang-format] Fix a regression in dumping the config (PR #80628)

2024-02-05 Thread Ben Hamilton via cfe-commits

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


[clang] [clang-format] Fix a regression in dumping the config (PR #80628)

2024-02-05 Thread Ben Hamilton via cfe-commits


@@ -0,0 +1,3 @@
+// RUN: clang-format -dump-config 2>&1 | FileCheck %s

bhamiltoncx wrote:

Can you also add a test with `clang-format --assume-filename=foo.m -dump-config 
2>&1 | FileCheck %s`?

It should result in `Language: ObjC`.


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


[clang] [clang-format] Fix a regression in dumping the config (PR #80628)

2024-02-05 Thread Ben Hamilton via cfe-commits

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

Looks good. Can you add one more test, please?

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


[openmp] [clang] [libc] [mlir] [libcxx] [compiler-rt] [lld] [lldb] [llvm] [clang-tools-extra] [flang] [Driver] Report invalid target triple versions for all environment types. (PR #78655)

2024-02-05 Thread via cfe-commits

ZijunZhaoCCK wrote:

> This broke the wasi-threads target: `clang: error: version 'threads' in 
> target triple 'wasm32-unknown-wasi-threads' is invalid`

Because `threads` is not in EnvironmentType list: 
https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/TargetParser/Triple.h#L231
 or ObjectType list: 
https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/TargetParser/Triple.h#L284
 . 

The format should be `arch-vendor-os-env`. If `threads` is a new environment 
type, please add it in the list. If `wasi-threads` is a special case, please 
let me know!

And one more question, would you mind pointing me out the test case of 
`wasm32-unknown-wasi-threads` ? I don't see it. Thank you!

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-02-05 Thread Alex Hoppen via cfe-commits


@@ -538,11 +565,254 @@ std::optional checkName(const NamedDecl 
,
 Conflict->getLocation().printToString(ASTCtx.getSourceManager())};
 }
   }
-  if (Result)
+  if (Result) {
 InvalidNameMetric.record(1, toString(Result->K));
+return makeError(*Result);
+  }
+  return std::nullopt;
+}
+
+bool isMatchingSelectorName(const syntax::Token , const syntax::Token 
,
+const SourceManager ,
+llvm::StringRef SelectorName) {
+  if (SelectorName.empty())
+return Cur.kind() == tok::colon;
+  return Cur.kind() == tok::identifier && Next.kind() == tok::colon &&
+ Cur.text(SM) == SelectorName &&
+ // We require the selector name and : to be contiguous to avoid
+ // potential conflicts with ternary expression.
+ //
+ // e.g. support `foo:` but not `foo :`.
+ Cur.endLocation() == Next.location();
+}
+
+bool isSelectorLike(const syntax::Token , const syntax::Token ) {
+  return Cur.kind() == tok::identifier && Next.kind() == tok::colon &&
+ // We require the selector name and : to be contiguous.
+ // e.g. support `foo:` but not `foo :`.
+ Cur.endLocation() == Next.location();
+}
+
+bool parseMessageExpression(llvm::ArrayRef Tokens,
+const SourceManager , unsigned Index,
+unsigned Last, Selector Sel,
+std::vector ) {
+
+  unsigned NumArgs = Sel.getNumArgs();
+  llvm::SmallVector Closes;
+  SelectorPieces.clear();
+  while (Index < Last) {
+const auto  = Tokens[Index];
+
+if (Closes.empty()) {
+  auto PieceCount = SelectorPieces.size();
+  if (PieceCount < NumArgs &&
+  isMatchingSelectorName(Tok, Tokens[Index + 1], SM,
+ Sel.getNameForSlot(PieceCount))) {
+// If 'foo:' instead of ':' (empty selector), we need to skip the ':'
+// token after the name.
+if (!Sel.getNameForSlot(PieceCount).empty()) {
+  ++Index;
+}
+SelectorPieces.push_back(
+halfOpenToRange(SM, Tok.range(SM).toCharRange(SM)));
+continue;
+  }
+  // If we've found all pieces but the current token looks like another
+  // selector piece, it means the method being renamed is a strict prefix 
of
+  // the selector we've found - should be skipped.
+  if (SelectorPieces.size() >= NumArgs &&
+  isSelectorLike(Tok, Tokens[Index + 1]))
+return false;
+}
+
+switch (Tok.kind()) {
+case tok::l_square:
+  Closes.push_back(']');
+  break;
+case tok::l_paren:
+  Closes.push_back(')');
+  break;
+case tok::l_brace:
+  Closes.push_back('}');
+  break;
+case tok::r_square:
+  if (Closes.empty())
+return SelectorPieces.size() == NumArgs;
+
+  if (Closes.back() != ']')
+return false;
+  Closes.pop_back();
+  break;
+case tok::r_paren:
+  if (Closes.empty() || Closes.back() != ')')
+return false;
+  Closes.pop_back();
+  break;
+case tok::r_brace:
+  if (Closes.empty() || Closes.back() != '}')
+return false;
+  Closes.pop_back();
+  break;
+case tok::semi:
+  // top level ; ends all statements.
+  if (Closes.empty())
+return false;
+  break;
+default:
+  break;
+}
+
+++Index;
+  }
+  return false;
+}
+
+/// Collects all ranges of the given identifier/selector in the source code.
+///
+/// If a selector is given, this does a full lex of the given source code in
+/// order to identify all selector fragments (e.g. in method exprs/decls) since
+/// they are non-contiguous.
+std::vector collectRenameIdentifierRanges(
+llvm::StringRef Identifier, llvm::StringRef Content,
+const LangOptions , std::optional Selector) {
+  std::vector Ranges;
+  if (!Selector) {
+auto IdentifierRanges =
+collectIdentifierRanges(Identifier, Content, LangOpts);
+for (const auto  : IdentifierRanges)
+  Ranges.emplace_back(R);
+return Ranges;
+  }
+  // FIXME: InMemoryFileAdapter crashes unless the buffer is null terminated!
+  std::string NullTerminatedCode = Content.str();
+  SourceManagerForFile FileSM("mock_file_name.cpp", NullTerminatedCode);
+  auto  = FileSM.get();
+
+  // We track parens and braces to ensure that we don't accidentally try 
parsing
+  // a method declaration or definition which isn't at the top level or similar
+  // looking expressions (e.g. an @selector() expression).
+  unsigned ParenCount = 0;
+  unsigned BraceCount = 0;
+  unsigned NumArgs = Selector->getNumArgs();
+
+  std::vector SelectorPieces;
+  auto Tokens = syntax::tokenize(SM.getMainFileID(), SM, LangOpts);
+  unsigned Last = Tokens.size() - 1;
+  for (unsigned Index = 0; Index < Last; ++Index) {
+const auto  = Tokens[Index];
+

ahoppen wrote:

But shouldn’t we know based on the index data that `- 

  1   2   3   4   5   >