[clang] [Clang] Warn against unused parameters in C++ coroutines with `-Wunused-parameters` (PR #70567)

2023-10-31 Thread Yuxuan Chen via cfe-commits


@@ -3165,7 +3165,16 @@ class Sema final {
 
   /// Diagnose any unused parameters in the given sequence of
   /// ParmVarDecl pointers.
-  void DiagnoseUnusedParameters(ArrayRef Parameters);
+  ///
+  /// Normally, we check if the parameter decls have the Referenced bit set.
+  /// C++ Coroutines, however, are a special case due to the existences of
+  /// parameter moves (See Sema::buildCoroutineParameterMoves), the parameters
+  /// are always referenced in coroutines. Therefore, in the case of 
coroutines,
+  /// CoroutineBodyRefs must be passed to correctly diagnose parameter usages
+  /// as written by the user.
+  void DiagnoseUnusedParameters(
+  ArrayRef Parameters,
+  llvm::SmallSet *CoroutineBodyRefs = nullptr);

yuxuanchen1997 wrote:

If so, what about adding an assertion in the original version of 
`DiagnoseUnusedParameters`? Or should we keep the interface as is (allowing 
coroutines to be diagnosed in the same function, but handle the special case in 
`DiagnoseUnusedParameters` without changing the interface?)

`CoroutineParameterMoves` does not give me what I want. It points me to `Stmt`s 
that moved the parameters while I need the opposite -- All other references to 
the parameters. 

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


[llvm] [clang] Disable memtag sanitization for global fnptrs going into .ctors (PR #70186)

2023-10-31 Thread Vitaly Buka via cfe-commits

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


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


[llvm] [clang] [clang-tools-extra] [clang][NFC] Annotate `Type` bit-fields with `clang::preferred_type` (PR #70349)

2023-10-31 Thread Vlad Serebrennikov via cfe-commits

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

>From 7329f68092d5f8f5a5978e5a6cbad6ada87d4fe8 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Thu, 26 Oct 2023 16:09:25 +0300
Subject: [PATCH 1/4] [clang][NFC] Annotate `Type` bit-fields with
 `clang::preferred_type`

---
 clang/include/clang/AST/DeclBase.h|  2 +-
 clang/include/clang/AST/DependenceFlags.h |  2 +-
 clang/include/clang/AST/Type.h| 46 ++-
 clang/include/clang/Basic/Linkage.h   |  2 +-
 4 files changed, 47 insertions(+), 5 deletions(-)

diff --git a/clang/include/clang/AST/DeclBase.h 
b/clang/include/clang/AST/DeclBase.h
index 978e4255e877ec2..0307691fdd480bf 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -49,7 +49,7 @@ class ExternalSourceSymbolAttr;
 class FunctionDecl;
 class FunctionType;
 class IdentifierInfo;
-enum Linkage : unsigned char;
+enum Linkage : unsigned;
 class LinkageSpecDecl;
 class Module;
 class NamedDecl;
diff --git a/clang/include/clang/AST/DependenceFlags.h 
b/clang/include/clang/AST/DependenceFlags.h
index 3b3c1afb096addd..e91b6ff35b34966 100644
--- a/clang/include/clang/AST/DependenceFlags.h
+++ b/clang/include/clang/AST/DependenceFlags.h
@@ -49,7 +49,7 @@ struct ExprDependenceScope {
 using ExprDependence = ExprDependenceScope::ExprDependence;
 
 struct TypeDependenceScope {
-  enum TypeDependence : uint8_t {
+  enum TypeDependence : unsigned {
 /// Whether this type contains an unexpanded parameter pack
 /// (for C++11 variadic templates)
 UnexpandedPack = 1,
diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index 1e8e1303e65f6ba..f24b1dccc240785 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -1611,22 +1611,28 @@ class alignas(TypeAlignment) Type : public 
ExtQualsTypeCommonBase {
 template  friend class TypePropertyCache;
 
 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
+[[clang::preferred_type(TypeClass)]]
 unsigned TC : 8;
 
 /// Store information on the type dependency.
+[[clang::preferred_type(TypeDependence)]]
 unsigned Dependence : llvm::BitWidth;
 
 /// True if the cache (i.e. the bitfields here starting with
 /// 'Cache') is valid.
+[[clang::preferred_type(bool)]]
 mutable unsigned CacheValid : 1;
 
 /// Linkage of this type.
+[[clang::preferred_type(Linkage)]]
 mutable unsigned CachedLinkage : 3;
 
 /// Whether this type involves and local or unnamed types.
+[[clang::preferred_type(bool)]]
 mutable unsigned CachedLocalOrUnnamed : 1;
 
 /// Whether this type comes from an AST file.
+[[clang::preferred_type(bool)]]
 mutable unsigned FromAST : 1;
 
 bool isCacheValid() const {
@@ -1652,10 +1658,12 @@ class alignas(TypeAlignment) Type : public 
ExtQualsTypeCommonBase {
   class ArrayTypeBitfields {
 friend class ArrayType;
 
+[[clang::preferred_type(TypeBitfields)]]
 unsigned : NumTypeBits;
 
 /// CVR qualifiers from declarations like
 /// 'int X[static restrict 4]'. For function parameters only.
+[[clang::preferred_type(Qualifiers)]]
 unsigned IndexTypeQuals : 3;
 
 /// Storage class qualifiers from declarations like
@@ -1671,12 +1679,14 @@ class alignas(TypeAlignment) Type : public 
ExtQualsTypeCommonBase {
 unsigned : NumArrayTypeBits;
 
 /// Whether we have a stored size expression.
+[[clang::preferred_type(bool)]]
 unsigned HasStoredSizeExpr : 1;
   };
 
   class BuiltinTypeBitfields {
 friend class BuiltinType;
 
+[[clang::preferred_type(TypeBitfields)]]
 unsigned : NumTypeBits;
 
 /// The kind (BuiltinType::Kind) of builtin type this is.
@@ -1691,15 +1701,18 @@ class alignas(TypeAlignment) Type : public 
ExtQualsTypeCommonBase {
 friend class FunctionProtoType;
 friend class FunctionType;
 
+[[clang::preferred_type(TypeBitfields)]]
 unsigned : NumTypeBits;
 
 /// Extra information which affects how the function is called, like
 /// regparm and the calling convention.
+[[clang::preferred_type(CallingConv)]]
 unsigned ExtInfo : 13;
 
 /// The ref-qualifier associated with a \c FunctionProtoType.
 ///
 /// This is a value of type \c RefQualifierKind.
+[[clang::preferred_type(RefQualifierKind)]]
 unsigned RefQualifier : 2;
 
 /// Used only by FunctionProtoType, put here to pack with the
@@ -1708,8 +1721,10 @@ class alignas(TypeAlignment) Type : public 
ExtQualsTypeCommonBase {
 ///
 /// C++ 8.3.5p4: The return type, the parameter type list and the
 /// cv-qualifier-seq, [...], are part of the function type.
+[[clang::preferred_type(Qualifiers)]]
 unsigned FastTypeQuals : Qualifiers::FastWidth;
 /// Whether this function has extended Qualifiers.
+[[clang::preferred_type(bool)]]
 unsigned HasExtQuals : 1;
 
 /// The number of parameters 

[openmp] [clang] [OpenMP] Team reduction work specialization (PR #70766)

2023-10-31 Thread Johannes Doerfert via cfe-commits

https://github.com/jdoerfert updated 
https://github.com/llvm/llvm-project/pull/70766

>From 04aafdce6f259e31304ed47118a56042b155bd77 Mon Sep 17 00:00:00 2001
From: Johannes Doerfert 
Date: Mon, 30 Oct 2023 16:39:00 -0700
Subject: [PATCH 1/2] [OpenMP][FIX] Allocate per launch memory for GPU team
 reductions

We used to perform team reduction on global memory allocated in the
runtime and by clang. This was racy as multiple instances of a kernel,
or different kernels with team reductions, would use the same locations.
Since we now have the kernel launch environment, we can allocate dynamic
memory per-launch, allowing us to move all the state into a non-racy
place.

Fixes: https://github.com/llvm/llvm-project/issues/70249
---
 clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp  |  75 ++
 clang/lib/CodeGen/CGOpenMPRuntimeGPU.h|   2 -
 .../OpenMP/nvptx_teams_reduction_codegen.cpp  | 240 +-
 .../target_teams_generic_loop_codegen.cpp |  20 +-
 .../DeviceRTL/include/Interface.h |   2 +
 .../libomptarget/DeviceRTL/src/Reduction.cpp  |  10 +-
 openmp/libomptarget/include/Environment.h |   7 +-
 .../PluginInterface/PluginInterface.cpp   |  11 +
 .../common/PluginInterface/PluginInterface.h  |   2 +-
 .../parallel_target_teams_reduction.cpp   |  36 +++
 10 files changed, 221 insertions(+), 184 deletions(-)
 create mode 100644 
openmp/libomptarget/test/offloading/parallel_target_teams_reduction.cpp

diff --git a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
index bd9329b8e2d4113..0ed665e0dfb9722 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -803,8 +803,30 @@ void CGOpenMPRuntimeGPU::emitKernelDeinit(CodeGenFunction 
,
   if (!IsSPMD)
 emitGenericVarsEpilog(CGF);
 
+  // This is temporary until we remove the fixed sized buffer.
+  ASTContext  = CGM.getContext();
+  RecordDecl *StaticRD = C.buildImplicitRecord(
+  "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
+  StaticRD->startDefinition();
+  for (const RecordDecl *TeamReductionRec : TeamsReductions) {
+QualType RecTy = C.getRecordType(TeamReductionRec);
+auto *Field = FieldDecl::Create(
+C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
+C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
+/*BW=*/nullptr, /*Mutable=*/false,
+/*InitStyle=*/ICIS_NoInit);
+Field->setAccess(AS_public);
+StaticRD->addDecl(Field);
+  }
+  StaticRD->completeDefinition();
+  QualType StaticTy = C.getRecordType(StaticRD);
+  llvm::Type *LLVMReductionsBufferTy =
+  CGM.getTypes().ConvertTypeForMem(StaticTy);
+  const auto  = CGM.getModule().getDataLayout();
+  uint64_t BufferSize =
+  DL.getTypeAllocSize(LLVMReductionsBufferTy).getFixedValue();
   CGBuilderTy  = CGF.Builder;
-  OMPBuilder.createTargetDeinit(Bld);
+  OMPBuilder.createTargetDeinit(Bld, BufferSize);
 }
 
 void CGOpenMPRuntimeGPU::emitSPMDKernel(const OMPExecutableDirective ,
@@ -2998,15 +3020,10 @@ void CGOpenMPRuntimeGPU::emitReduction(
 CGM.getContext(), PrivatesReductions, std::nullopt, VarFieldMap,
 C.getLangOpts().OpenMPCUDAReductionBufNum);
 TeamsReductions.push_back(TeamReductionRec);
-if (!KernelTeamsReductionPtr) {
-  KernelTeamsReductionPtr = new llvm::GlobalVariable(
-  CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
-  llvm::GlobalValue::InternalLinkage, nullptr,
-  "_openmp_teams_reductions_buffer_$_$ptr");
-}
-llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
-Address(KernelTeamsReductionPtr, CGF.VoidPtrTy, CGM.getPointerAlign()),
-/*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
+auto *KernelTeamsReductionPtr = CGF.EmitRuntimeCall(
+OMPBuilder.getOrCreateRuntimeFunction(
+CGM.getModule(), OMPRTL___kmpc_reduction_get_fixed_buffer),
+{}, "_openmp_teams_reductions_buffer_$_$ptr");
 llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
 llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
@@ -3021,7 +3038,7 @@ void CGOpenMPRuntimeGPU::emitReduction(
 llvm::Value *Args[] = {
 RTLoc,
 ThreadId,
-GlobalBufferPtr,
+KernelTeamsReductionPtr,
 CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
 RL,
 ShuffleAndReduceFn,
@@ -3654,42 +3671,6 @@ void CGOpenMPRuntimeGPU::processRequiresDirective(
   CGOpenMPRuntime::processRequiresDirective(D);
 }
 
-void CGOpenMPRuntimeGPU::clear() {
-
-  if (!TeamsReductions.empty()) {
-ASTContext  = CGM.getContext();
-RecordDecl *StaticRD = C.buildImplicitRecord(
-"_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
-StaticRD->startDefinition();
-for (const RecordDecl *TeamReductionRec : TeamsReductions) 

[clang] [Clang] Warn against unused parameters in C++ coroutines with `-Wunused-parameters` (PR #70567)

2023-10-31 Thread Chuanqi Xu via cfe-commits

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


[clang] [Clang] Warn against unused parameters in C++ coroutines with `-Wunused-parameters` (PR #70567)

2023-10-31 Thread Chuanqi Xu via cfe-commits


@@ -3165,7 +3165,16 @@ class Sema final {
 
   /// Diagnose any unused parameters in the given sequence of
   /// ParmVarDecl pointers.
-  void DiagnoseUnusedParameters(ArrayRef Parameters);
+  ///
+  /// Normally, we check if the parameter decls have the Referenced bit set.
+  /// C++ Coroutines, however, are a special case due to the existences of
+  /// parameter moves (See Sema::buildCoroutineParameterMoves), the parameters
+  /// are always referenced in coroutines. Therefore, in the case of 
coroutines,
+  /// CoroutineBodyRefs must be passed to correctly diagnose parameter usages
+  /// as written by the user.
+  void DiagnoseUnusedParameters(
+  ArrayRef Parameters,
+  llvm::SmallSet *CoroutineBodyRefs = nullptr);

ChuanqiXu9 wrote:

Let's try to not polluting the interfaces as much as possible. Since most of 
the functions are not coroutines, it looks not good to pollute the interfaces.

Personally, I prefer the style:

```
if (the function is coroutine)
 DiagnoseUnusedParametersInCoroutines(...);
else
 DiagnoseUnusedParameters(...); // Original call.
```

Also it may be better to use `FunctionScopeInfo::CoroutineParameterMoves` than 
yet another DeclsVisitor. It is easy prone and hard to maintain.

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


[clang] [Driver] Silence stdlib warning when linking C on *BSD / Solaris / Haiku (PR #70434)

2023-10-31 Thread Fangrui Song via cfe-commits

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


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


[clang] [clang] Additional FP classification functions (PR #69041)

2023-10-31 Thread Serge Pavlov via cfe-commits

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


[clang] fc7198b - [clang] Additional FP classification functions (#69041)

2023-10-31 Thread via cfe-commits

Author: Serge Pavlov
Date: 2023-11-01T12:10:54+07:00
New Revision: fc7198b799b0f9dc9e27b5ae4334e5c1b1c89b6e

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

LOG: [clang] Additional FP classification functions (#69041)

C language standard defined library functions `iszero`, `issignaling`
and `issubnormal`, which did not have counterparts among clang builtin
functions. This change adds new functions:

__builtin_iszero
__builtin_issubnormal
__builtin_issignaling

They provide builtin implementation for the missing standard functions.

Pull request: https://github.com/llvm/llvm-project/pull/69041

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/Builtins.def
clang/lib/AST/ExprConstant.cpp
clang/lib/AST/Interp/Floating.h
clang/lib/AST/Interp/InterpBuiltin.cpp
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/Sema/SemaChecking.cpp
clang/test/AST/Interp/builtin-functions.cpp
clang/test/CodeGen/builtins.c
clang/test/Sema/constant-builtins-2.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index bc28bb567f6932a..1cd8cf8fe328836 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -809,6 +809,8 @@ Floating Point Support in Clang
 - Add ``__builtin_exp10``, ``__builtin_exp10f``,
   ``__builtin_exp10f16``, ``__builtin_exp10l`` and
   ``__builtin_exp10f128`` builtins.
+- Add ``__builtin_iszero``, ``__builtin_issignaling`` and
+  ``__builtin_issubnormal``.
 
 AST Matchers
 

diff  --git a/clang/include/clang/Basic/Builtins.def 
b/clang/include/clang/Basic/Builtins.def
index 6033e8a955fb8bd..ec39e926889b936 100644
--- a/clang/include/clang/Basic/Builtins.def
+++ b/clang/include/clang/Basic/Builtins.def
@@ -494,6 +494,9 @@ BUILTIN(__builtin_isinf,  "i.", "FnctE")
 BUILTIN(__builtin_isinf_sign, "i.", "FnctE")
 BUILTIN(__builtin_isnan,  "i.", "FnctE")
 BUILTIN(__builtin_isnormal,   "i.", "FnctE")
+BUILTIN(__builtin_issubnormal,"i.", "FnctE")
+BUILTIN(__builtin_iszero, "i.", "FnctE")
+BUILTIN(__builtin_issignaling,"i.", "FnctE")
 BUILTIN(__builtin_isfpclass,  "i.", "nctE")
 
 // FP signbit builtins

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index aea26d380b8e822..b6b1e6617dffaa9 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -12398,6 +12398,24 @@ bool IntExprEvaluator::VisitBuiltinCallExpr(const 
CallExpr *E,
Success(Val.isNormal() ? 1 : 0, E);
   }
 
+  case Builtin::BI__builtin_issubnormal: {
+APFloat Val(0.0);
+return EvaluateFloat(E->getArg(0), Val, Info) &&
+   Success(Val.isDenormal() ? 1 : 0, E);
+  }
+
+  case Builtin::BI__builtin_iszero: {
+APFloat Val(0.0);
+return EvaluateFloat(E->getArg(0), Val, Info) &&
+   Success(Val.isZero() ? 1 : 0, E);
+  }
+
+  case Builtin::BI__builtin_issignaling: {
+APFloat Val(0.0);
+return EvaluateFloat(E->getArg(0), Val, Info) &&
+   Success(Val.isSignaling() ? 1 : 0, E);
+  }
+
   case Builtin::BI__builtin_isfpclass: {
 APSInt MaskVal;
 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))

diff  --git a/clang/lib/AST/Interp/Floating.h b/clang/lib/AST/Interp/Floating.h
index a22b3fa79f3992f..e4ac76d8509fb83 100644
--- a/clang/lib/AST/Interp/Floating.h
+++ b/clang/lib/AST/Interp/Floating.h
@@ -93,6 +93,7 @@ class Floating final {
   bool isMin() const { return F.isSmallest(); }
   bool isMinusOne() const { return F.isExactlyValue(-1.0); }
   bool isNan() const { return F.isNaN(); }
+  bool isSignaling() const { return F.isSignaling(); }
   bool isInf() const { return F.isInfinity(); }
   bool isFinite() const { return F.isFinite(); }
   bool isNormal() const { return F.isNormal(); }

diff  --git a/clang/lib/AST/Interp/InterpBuiltin.cpp 
b/clang/lib/AST/Interp/InterpBuiltin.cpp
index e329794cb79243d..f26d298f5b60045 100644
--- a/clang/lib/AST/Interp/InterpBuiltin.cpp
+++ b/clang/lib/AST/Interp/InterpBuiltin.cpp
@@ -306,6 +306,15 @@ static bool interp__builtin_isnan(InterpState , CodePtr 
OpPC,
   return true;
 }
 
+static bool interp__builtin_issignaling(InterpState , CodePtr OpPC,
+const InterpFrame *Frame,
+const Function *F) {
+  const Floating  = S.Stk.peek();
+
+  pushInt(S, Arg.isSignaling());
+  return true;
+}
+
 static bool interp__builtin_isinf(InterpState , CodePtr OpPC,
   const InterpFrame *Frame, const Function *F,
   bool CheckSign) {
@@ -337,6 +346,24 @@ static bool interp__builtin_isnormal(InterpState , 
CodePtr OpPC,
   return true;
 }
 
+static bool interp__builtin_issubnormal(InterpState , CodePtr OpPC,
+ 

[clang] [Clang] Emit type metadata on vtables when IRPGO option is on. (PR #70841)

2023-10-31 Thread Mingming Liu via cfe-commits

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


[clang] [clang] Additional FP classification functions (PR #69041)

2023-10-31 Thread Serge Pavlov via cfe-commits

spavloff wrote:

Thanks!

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


[clang] [Clang] Emit type metadata on vtables when IRPGO option is on. (PR #70841)

2023-10-31 Thread Mingming Liu via cfe-commits

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


[clang] [Clang]Emit type metadata when IRPGO is used (PR #70841)

2023-10-31 Thread Mingming Liu via cfe-commits

https://github.com/minglotus-6 updated 
https://github.com/llvm/llvm-project/pull/70841

>From 99abebc88c09346bd4a70bbf39df13b249116c09 Mon Sep 17 00:00:00 2001
From: Mingming Liu 
Date: Tue, 31 Oct 2023 01:17:03 -0700
Subject: [PATCH 1/2] [Clang]Emit type metadata when -fprofile-generate is on

---
 clang/lib/CodeGen/CGVTables.cpp |   2 +-
 clang/lib/CodeGen/MicrosoftCXXABI.cpp   |   3 +-
 clang/test/CodeGenCXX/type-metadata.cpp | 150 
 3 files changed, 80 insertions(+), 75 deletions(-)

diff --git a/clang/lib/CodeGen/CGVTables.cpp b/clang/lib/CodeGen/CGVTables.cpp
index 25e4b1c27932026..895e160dfa8a536 100644
--- a/clang/lib/CodeGen/CGVTables.cpp
+++ b/clang/lib/CodeGen/CGVTables.cpp
@@ -1312,7 +1312,7 @@ llvm::GlobalObject::VCallVisibility 
CodeGenModule::GetVCallVisibilityLevel(
 void CodeGenModule::EmitVTableTypeMetadata(const CXXRecordDecl *RD,
llvm::GlobalVariable *VTable,
const VTableLayout ) {
-  if (!getCodeGenOpts().LTOUnit)
+  if (!getCodeGenOpts().LTOUnit && !getCodeGenOpts().hasProfileIRInstr())
 return;
 
   CharUnits ComponentWidth = GetTargetTypeStoreSize(getVTableComponentType());
diff --git a/clang/lib/CodeGen/MicrosoftCXXABI.cpp 
b/clang/lib/CodeGen/MicrosoftCXXABI.cpp
index d623f8f63ae56c4..740c0b6cb1aac04 100644
--- a/clang/lib/CodeGen/MicrosoftCXXABI.cpp
+++ b/clang/lib/CodeGen/MicrosoftCXXABI.cpp
@@ -1673,7 +1673,8 @@ void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction 
,
 void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo ,
  const CXXRecordDecl *RD,
  llvm::GlobalVariable *VTable) {
-  if (!CGM.getCodeGenOpts().LTOUnit)
+  if (!CGM.getCodeGenOpts().LTOUnit &&
+  !CGM.getCodeGenOpts().hasProfileIRInstr())
 return;
 
   // TODO: Should VirtualFunctionElimination also be supported here?
diff --git a/clang/test/CodeGenCXX/type-metadata.cpp 
b/clang/test/CodeGenCXX/type-metadata.cpp
index 3f8b54af801f8d6..637ec6e6c326ab6 100644
--- a/clang/test/CodeGenCXX/type-metadata.cpp
+++ b/clang/test/CodeGenCXX/type-metadata.cpp
@@ -1,113 +1,117 @@
 // Tests for the cfi-vcall feature:
-// RUN: %clang_cc1 -flto -flto-unit -triple x86_64-unknown-linux 
-fvisibility=hidden -fsanitize=cfi-vcall -fsanitize-trap=cfi-vcall -emit-llvm 
-o - %s | FileCheck --check-prefix=CFI --check-prefix=CFI-NVT-NO-RV 
--check-prefix=ITANIUM --check-prefix=ITANIUM-MD 
--check-prefix=TT-ITANIUM-HIDDEN --check-prefix=NDIAG %s
-// RUN: %clang_cc1 -flto -flto-unit -triple x86_64-unknown-linux 
-fvisibility=hidden -fsanitize=cfi-vcall -emit-llvm -o - %s | FileCheck 
--check-prefix=CFI --check-prefix=CFI-NVT-NO-RV --check-prefix=ITANIUM 
--check-prefix=ITANIUM-MD --check-prefix=TT-ITANIUM-HIDDEN 
--check-prefix=ITANIUM-MD-DIAG --check-prefix=ITANIUM-DIAG --check-prefix=DIAG 
--check-prefix=DIAG-ABORT %s
-// RUN: %clang_cc1 -flto -flto-unit -triple x86_64-unknown-linux 
-fvisibility=hidden -fsanitize=cfi-vcall -fsanitize-recover=cfi-vcall 
-emit-llvm -o - %s | FileCheck --check-prefix=CFI --check-prefix=CFI-NVT-NO-RV 
--check-prefix=ITANIUM --check-prefix=ITANIUM-MD 
--check-prefix=TT-ITANIUM-HIDDEN --check-prefix=ITANIUM-MD-DIAG 
--check-prefix=ITANIUM-DIAG --check-prefix=DIAG --check-prefix=DIAG-RECOVER %s
-// RUN: %clang_cc1 -flto -flto-unit -triple x86_64-pc-windows-msvc 
-fsanitize=cfi-vcall -fsanitize-trap=cfi-vcall -emit-llvm -o - %s | FileCheck 
--check-prefix=CFI --check-prefix=CFI-NVT-NO-RV --check-prefix=MS 
--check-prefix=TT-MS --check-prefix=NDIAG %s
+// RUN: %clang_cc1 -flto -flto-unit -triple x86_64-unknown-linux 
-fvisibility=hidden -fsanitize=cfi-vcall -fsanitize-trap=cfi-vcall -emit-llvm 
-o - %s | FileCheck --check-prefix=CFI --check-prefix=CFI-NVT-NO-RV  
--check-prefix=ITANIUM-TYPEMETADATA --check-prefix=ITANIUM-HIDDEN 
--check-prefix=ITANIUM-MD --check-prefix=TT-ITANIUM-HIDDEN --check-prefix=NDIAG 
%s
+// RUN: %clang_cc1 -flto -flto-unit -triple x86_64-unknown-linux 
-fvisibility=hidden -fsanitize=cfi-vcall -emit-llvm -o - %s | FileCheck 
--check-prefix=CFI --check-prefix=CFI-NVT-NO-RV 
--check-prefix=ITANIUM-TYPEMETADATA --check-prefix=ITANIUM-HIDDEN 
--check-prefix=ITANIUM-MD --check-prefix=TT-ITANIUM-HIDDEN 
--check-prefix=ITANIUM-MD-DIAG --check-prefix=ITANIUM-DIAG --check-prefix=DIAG 
--check-prefix=DIAG-ABORT %s
+// RUN: %clang_cc1 -flto -flto-unit -triple x86_64-unknown-linux 
-fvisibility=hidden -fsanitize=cfi-vcall -fsanitize-recover=cfi-vcall 
-emit-llvm -o - %s | FileCheck --check-prefix=CFI --check-prefix=CFI-NVT-NO-RV 
--check-prefix=ITANIUM-TYPEMETADATA --check-prefix=ITANIUM-HIDDEN 
--check-prefix=ITANIUM-MD --check-prefix=TT-ITANIUM-HIDDEN 
--check-prefix=ITANIUM-MD-DIAG --check-prefix=ITANIUM-DIAG --check-prefix=DIAG 
--check-prefix=DIAG-RECOVER %s
+// RUN: %clang_cc1 -flto -flto-unit -triple x86_64-pc-windows-msvc 
-fsanitize=cfi-vcall 

[clang] [clang] Do not clear FP pragma stack when instantiating functions (PR #70646)

2023-10-31 Thread Serge Pavlov via cfe-commits

spavloff wrote:

Late parsing (in contrast to template instantiation) is sensitive to the pragma 
stack because the late parsed text may contain pragmas. If, for example, the 
parsed text contains unbalanced pus/pop pragmas, it is detected if the pragma 
stack is empty, but can be missed if there is an unfinished pragma.

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


[clang] [Clang] Warn against unused parameters in C++ coroutines with `-Wunused-parameters` (PR #70567)

2023-10-31 Thread Yuxuan Chen via cfe-commits

yuxuanchen1997 wrote:

@ChuanqiXu9 , I just updated the PR. Do you mind checking if using a 
`RecursiveASTVisitor` is appropriate for this? I am a first time contributor 
and would appreciate more feedback. Thank you. 

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


[clang] [Clang] Warn against unused parameters in C++ coroutines with `-Wunused-parameters` (PR #70567)

2023-10-31 Thread Yuxuan Chen via cfe-commits

https://github.com/yuxuanchen1997 updated 
https://github.com/llvm/llvm-project/pull/70567

>From 77b9cba0aaa1157cc323f2f3ef7b1cef536ef147 Mon Sep 17 00:00:00 2001
From: Yuxuan Chen 
Date: Fri, 27 Oct 2023 16:37:40 -0700
Subject: [PATCH 1/5] [Clang] Coroutines: warn against unused parameters in C++
 coroutines with -Wunused-parameters

---
 clang/include/clang/AST/DeclBase.h| 18 +++-
 clang/lib/Sema/SemaCoroutine.cpp  |  6 
 clang/lib/Sema/SemaDecl.cpp   |  5 +++-
 .../warn-unused-parameters-coroutine.cpp  | 28 +++
 4 files changed, 55 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/SemaCXX/warn-unused-parameters-coroutine.cpp

diff --git a/clang/include/clang/AST/DeclBase.h 
b/clang/include/clang/AST/DeclBase.h
index 978e4255e877ec2..dc78ee37d16bea2 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -306,6 +306,11 @@ class alignas(8) Decl {
   /// are regarded as "referenced" but not "used".
   unsigned Referenced : 1;
 
+  /// Whether the last reference to this declaration happened in Coroutine
+  /// Parameter moves. Otherwise the reference caused by such moves would
+  /// prevent a warning against unused parameters in all coroutines.
+  unsigned LastReferenceInCoroutineParamMoves : 1;
+
   /// Whether this declaration is a top-level declaration (function,
   /// global variable, etc.) that is lexically inside an objc container
   /// definition.
@@ -609,11 +614,22 @@ class alignas(8) Decl {
   /// Whether any declaration of this entity was referenced.
   bool isReferenced() const;
 
+  bool isLastReferenceInCoroutineParamMoves() const {
+return LastReferenceInCoroutineParamMoves;
+  }
+
+  void setLastReferenceInCoroutineParamMoves(bool V = true) {
+LastReferenceInCoroutineParamMoves = true;
+  }
+
   /// Whether this declaration was referenced. This should not be relied
   /// upon for anything other than debugging.
   bool isThisDeclarationReferenced() const { return Referenced; }
 
-  void setReferenced(bool R = true) { Referenced = R; }
+  void setReferenced(bool R = true) {
+Referenced = R;
+LastReferenceInCoroutineParamMoves = false;
+  }
 
   /// Whether this declaration is a top-level declaration (function,
   /// global variable, etc.) that is lexically inside an objc container
diff --git a/clang/lib/Sema/SemaCoroutine.cpp b/clang/lib/Sema/SemaCoroutine.cpp
index 38ac406b14adadf..3af42cae9ba0420 100644
--- a/clang/lib/Sema/SemaCoroutine.cpp
+++ b/clang/lib/Sema/SemaCoroutine.cpp
@@ -1965,9 +1965,15 @@ bool Sema::buildCoroutineParameterMoves(SourceLocation 
Loc) {
 if (PD->getType()->isDependentType())
   continue;
 
+bool PDRefBefore = PD->isReferenced();
+
 ExprResult PDRefExpr =
 BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
  ExprValueKind::VK_LValue, Loc); // FIXME: scope?
+
+if (!PDRefBefore)
+  PD->setLastReferenceInCoroutineParamMoves();
+
 if (PDRefExpr.isInvalid())
   return false;
 
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 824267acbb1c04e..6ce4871152a4e78 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -15092,7 +15092,10 @@ void 
Sema::DiagnoseUnusedParameters(ArrayRef Parameters) {
 return;
 
   for (const ParmVarDecl *Parameter : Parameters) {
-if (!Parameter->isReferenced() && Parameter->getDeclName() &&
+if (Parameter->isReferenced() && 
!Parameter->isLastReferenceInCoroutineParamMoves())
+  continue;
+
+if (Parameter->getDeclName() &&
 !Parameter->hasAttr() &&
 !Parameter->getIdentifier()->isPlaceholder()) {
   Diag(Parameter->getLocation(), diag::warn_unused_parameter)
diff --git a/clang/test/SemaCXX/warn-unused-parameters-coroutine.cpp 
b/clang/test/SemaCXX/warn-unused-parameters-coroutine.cpp
new file mode 100644
index 000..0fd26ea4a21be79
--- /dev/null
+++ b/clang/test/SemaCXX/warn-unused-parameters-coroutine.cpp
@@ -0,0 +1,28 @@
+// RUN: %clang_cc1 -fsyntax-only -Wunused-parameter -verify -std=c++20 %s
+
+#include "Inputs/std-coroutine.h"
+
+struct awaitable {
+  bool await_ready() noexcept;
+  void await_resume() noexcept;
+  void await_suspend(std::coroutine_handle<>) noexcept;
+};
+
+struct task : awaitable {
+  struct promise_type {
+task get_return_object() noexcept;
+awaitable initial_suspend() noexcept;
+awaitable final_suspend() noexcept;
+void unhandled_exception() noexcept;
+void return_void() noexcept;
+  };
+};
+
+task foo(int a) { // expected-warning{{unused parameter 'a'}}
+  co_return;
+}
+
+task bar(int a, int b) { // expected-warning{{unused parameter 'b'}}
+  a = a + 1;
+  co_return;
+}

>From c094a4fa29142b33cb15c41f5544395d3e87473c Mon Sep 17 00:00:00 2001
From: Yuxuan Chen 
Date: Sat, 28 Oct 2023 12:42:01 -0700
Subject: [PATCH 2/5] fix small bug: setLastReferenceInCoroutineParamMoves
 should respect 

[compiler-rt] [llvm] [clang] [Profile] Refactor profile correlation. (PR #70856)

2023-10-31 Thread Ellis Hoag via cfe-commits

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

Sounds fine to me, but I guess I don't understand why `-profile-correlate=` 
doesn't work. Do you still plan to add the flag later?

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


[clang] [openmp] [OpenMP][FIX] Allocate per launch memory for GPU team reductions (PR #70752)

2023-10-31 Thread Johannes Doerfert via cfe-commits

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


[openmp] [clang] [OpenMP][FIX] Allocate per launch memory for GPU team reductions (PR #70752)

2023-10-31 Thread Johannes Doerfert via cfe-commits

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


[clang] [openmp] [OpenMP][FIX] Allocate per launch memory for GPU team reductions (PR #70752)

2023-10-31 Thread Johannes Doerfert via cfe-commits

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


[clang] [openmp] [OpenMP] Non racy team reductions (PR #70752)

2023-10-31 Thread Johannes Doerfert via cfe-commits

https://github.com/jdoerfert updated 
https://github.com/llvm/llvm-project/pull/70752

>From 04aafdce6f259e31304ed47118a56042b155bd77 Mon Sep 17 00:00:00 2001
From: Johannes Doerfert 
Date: Mon, 30 Oct 2023 16:39:00 -0700
Subject: [PATCH] [OpenMP][FIX] Allocate per launch memory for GPU team
 reductions

We used to perform team reduction on global memory allocated in the
runtime and by clang. This was racy as multiple instances of a kernel,
or different kernels with team reductions, would use the same locations.
Since we now have the kernel launch environment, we can allocate dynamic
memory per-launch, allowing us to move all the state into a non-racy
place.

Fixes: https://github.com/llvm/llvm-project/issues/70249
---
 clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp  |  75 ++
 clang/lib/CodeGen/CGOpenMPRuntimeGPU.h|   2 -
 .../OpenMP/nvptx_teams_reduction_codegen.cpp  | 240 +-
 .../target_teams_generic_loop_codegen.cpp |  20 +-
 .../DeviceRTL/include/Interface.h |   2 +
 .../libomptarget/DeviceRTL/src/Reduction.cpp  |  10 +-
 openmp/libomptarget/include/Environment.h |   7 +-
 .../PluginInterface/PluginInterface.cpp   |  11 +
 .../common/PluginInterface/PluginInterface.h  |   2 +-
 .../parallel_target_teams_reduction.cpp   |  36 +++
 10 files changed, 221 insertions(+), 184 deletions(-)
 create mode 100644 
openmp/libomptarget/test/offloading/parallel_target_teams_reduction.cpp

diff --git a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
index bd9329b8e2d4113..0ed665e0dfb9722 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -803,8 +803,30 @@ void CGOpenMPRuntimeGPU::emitKernelDeinit(CodeGenFunction 
,
   if (!IsSPMD)
 emitGenericVarsEpilog(CGF);
 
+  // This is temporary until we remove the fixed sized buffer.
+  ASTContext  = CGM.getContext();
+  RecordDecl *StaticRD = C.buildImplicitRecord(
+  "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
+  StaticRD->startDefinition();
+  for (const RecordDecl *TeamReductionRec : TeamsReductions) {
+QualType RecTy = C.getRecordType(TeamReductionRec);
+auto *Field = FieldDecl::Create(
+C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
+C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
+/*BW=*/nullptr, /*Mutable=*/false,
+/*InitStyle=*/ICIS_NoInit);
+Field->setAccess(AS_public);
+StaticRD->addDecl(Field);
+  }
+  StaticRD->completeDefinition();
+  QualType StaticTy = C.getRecordType(StaticRD);
+  llvm::Type *LLVMReductionsBufferTy =
+  CGM.getTypes().ConvertTypeForMem(StaticTy);
+  const auto  = CGM.getModule().getDataLayout();
+  uint64_t BufferSize =
+  DL.getTypeAllocSize(LLVMReductionsBufferTy).getFixedValue();
   CGBuilderTy  = CGF.Builder;
-  OMPBuilder.createTargetDeinit(Bld);
+  OMPBuilder.createTargetDeinit(Bld, BufferSize);
 }
 
 void CGOpenMPRuntimeGPU::emitSPMDKernel(const OMPExecutableDirective ,
@@ -2998,15 +3020,10 @@ void CGOpenMPRuntimeGPU::emitReduction(
 CGM.getContext(), PrivatesReductions, std::nullopt, VarFieldMap,
 C.getLangOpts().OpenMPCUDAReductionBufNum);
 TeamsReductions.push_back(TeamReductionRec);
-if (!KernelTeamsReductionPtr) {
-  KernelTeamsReductionPtr = new llvm::GlobalVariable(
-  CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
-  llvm::GlobalValue::InternalLinkage, nullptr,
-  "_openmp_teams_reductions_buffer_$_$ptr");
-}
-llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
-Address(KernelTeamsReductionPtr, CGF.VoidPtrTy, CGM.getPointerAlign()),
-/*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
+auto *KernelTeamsReductionPtr = CGF.EmitRuntimeCall(
+OMPBuilder.getOrCreateRuntimeFunction(
+CGM.getModule(), OMPRTL___kmpc_reduction_get_fixed_buffer),
+{}, "_openmp_teams_reductions_buffer_$_$ptr");
 llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
 llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
@@ -3021,7 +3038,7 @@ void CGOpenMPRuntimeGPU::emitReduction(
 llvm::Value *Args[] = {
 RTLoc,
 ThreadId,
-GlobalBufferPtr,
+KernelTeamsReductionPtr,
 CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
 RL,
 ShuffleAndReduceFn,
@@ -3654,42 +3671,6 @@ void CGOpenMPRuntimeGPU::processRequiresDirective(
   CGOpenMPRuntime::processRequiresDirective(D);
 }
 
-void CGOpenMPRuntimeGPU::clear() {
-
-  if (!TeamsReductions.empty()) {
-ASTContext  = CGM.getContext();
-RecordDecl *StaticRD = C.buildImplicitRecord(
-"_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
-StaticRD->startDefinition();
-for (const RecordDecl *TeamReductionRec : TeamsReductions) {
- 

[clang] [clang][ASTImporter] Fix crash when template class static member imported to other translation unit. (PR #68774)

2023-10-31 Thread via cfe-commits

https://github.com/mzyKi updated https://github.com/llvm/llvm-project/pull/68774

>From 9ccc03c053904f26d771a7a7398542c6cd8bcf8c Mon Sep 17 00:00:00 2001
From: miaozhiyuan 
Date: Wed, 11 Oct 2023 15:45:36 +0800
Subject: [PATCH] [clang][ASTImporter] Fix crash when template class static
 member imported to other translation unit. Fixes: #68769

---
 clang/docs/ReleaseNotes.rst |  4 +++
 clang/lib/AST/ASTImporter.cpp   | 11 
 clang/unittests/AST/ASTImporterTest.cpp | 34 +
 3 files changed, 49 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index bc28bb567f6932a..c3179b80cfcc577 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -670,6 +670,10 @@ Bug Fixes to C++ Support
   default initializing a base class in a constant expression context. Fixes:
   (`#69890 `_)
 
+- Fix crash when template class static member imported to other translation 
unit.
+  Fixes:
+  (`#68769 `_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 650ff201e66b72e..c4e931e220f69b5 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -4476,6 +4476,17 @@ ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
 auto ToVTOrErr = import(D->getDescribedVarTemplate());
 if (!ToVTOrErr)
   return ToVTOrErr.takeError();
+  } else if (MemberSpecializationInfo *MSI = D->getMemberSpecializationInfo()) 
{
+TemplateSpecializationKind SK = MSI->getTemplateSpecializationKind();
+VarDecl *FromInst = D->getInstantiatedFromStaticDataMember();
+if (Expected ToInstOrErr = import(FromInst))
+  ToVar->setInstantiationOfStaticDataMember(*ToInstOrErr, SK);
+else
+  return ToInstOrErr.takeError();
+if (ExpectedSLoc POIOrErr = import(MSI->getPointOfInstantiation()))
+  ToVar->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
+else
+  return POIOrErr.takeError();
   }
 
   if (Error Err = ImportInitializer(D, ToVar))
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 87e6cd1e160c4cc..0cbec5cf9ba062f 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -1370,6 +1370,40 @@ TEST_P(ASTImporterOptionSpecificTestBase, 
ImportCorrectTemplatedDecl) {
   ASSERT_EQ(ToTemplated1, ToTemplated);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase,
+   ImportTemplateSpecializationStaticMember) {
+  auto FromCode =
+  R"(
+  template  class Test{
+  public:
+static const unsigned int length;
+  };
+
+  template<> const unsigned int Test::length;
+  template<> const unsigned int Test::length = 0;
+  )";
+  auto ToCode =
+  R"(
+  template  class Test {
+  public:
+static const unsigned int length;
+  };
+
+  template <> const unsigned int Test::length;
+
+  void foo() { int i = 1 / Test::length; }
+  )";
+  Decl *FromTU = getTuDecl(FromCode, Lang_CXX14);
+  auto FromDecl = FirstDeclMatcher().match(
+  FromTU, varDecl(hasName("length"), isDefinition()));
+  Decl *ToTu = getToTuDecl(ToCode, Lang_CXX14);
+  auto ToX = Import(FromDecl, Lang_CXX03);
+  auto ToDecl = FirstDeclMatcher().match(
+  ToTu, varDecl(hasName("length"), isDefinition()));
+  EXPECT_TRUE(ToX);
+  EXPECT_EQ(ToX, ToDecl);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, ImportChooseExpr) {
   // This tests the import of isConditionTrue directly to make sure the 
importer
   // gets it right.

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


[clang] [clang]get non-injected-class before finding instantiated decl (PR #70886)

2023-10-31 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Congcong Cai (HerrCai0907)


Changes

Fixes #21483 

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


3 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+2) 
- (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+3) 
- (modified) clang/test/SemaCXX/friend.cpp (+16) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index bc28bb567f6932a..a8ae5fb2596c580 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -533,6 +533,8 @@ Bug Fixes in This Version
   Fixes (`#67687 `_)
 - Fix crash from constexpr evaluator evaluating uninitialized arrays as rvalue.
   Fixes (`#67317 `_)
+- Fix an issue when do name lookup which scope resolution operator in friend 
function.
+  Fixes (`#21483 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 78a7892a35a320b..83dac8ece06b20b 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -6191,6 +6191,9 @@ NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, 
NamedDecl *D,
   }
 
   if (CXXRecordDecl *Record = dyn_cast(D)) {
+if (Record->isInjectedClassName())
+  Record = cast(Record->getDeclContext());
+
 if (!Record->isDependentContext())
   return D;
 
diff --git a/clang/test/SemaCXX/friend.cpp b/clang/test/SemaCXX/friend.cpp
index 367d6a6c1807c92..7b8e50322c4f8f9 100644
--- a/clang/test/SemaCXX/friend.cpp
+++ b/clang/test/SemaCXX/friend.cpp
@@ -429,3 +429,19 @@ namespace qualified_friend_no_match {
 friend void Y::f(double); // expected-error {{friend declaration of 'f' 
does not match any declaration in 'qualified_friend_no_match::Y'}}
   };
 }
+
+namespace gh21483 {
+template 
+struct B {
+  struct mixin {
+int type;
+friend void foo(B::mixin it) {
+  (void)it.mixin::type;
+}
+  };
+};
+
+void bar() {
+  foo(B::mixin{});
+}
+}
\ No newline at end of file

``




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


[clang] [clang]get non-injected-class before finding instantiated decl (PR #70886)

2023-10-31 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 created 
https://github.com/llvm/llvm-project/pull/70886

Fixes #21483 

>From 73471336857b84c69e51d4561838e588c7162bfa Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Tue, 31 Oct 2023 17:27:35 +0800
Subject: [PATCH 1/2] [clang]get non-injected-class before finding instantiated
 decl

---
 clang/lib/Sema/SemaTemplateInstantiateDecl.cpp | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 78a7892a35a320b..83dac8ece06b20b 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -6191,6 +6191,9 @@ NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, 
NamedDecl *D,
   }
 
   if (CXXRecordDecl *Record = dyn_cast(D)) {
+if (Record->isInjectedClassName())
+  Record = cast(Record->getDeclContext());
+
 if (!Record->isDependentContext())
   return D;
 

>From ebda1b76c090b52273d2fe72fbc30744a5fb892d Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Wed, 1 Nov 2023 10:59:12 +0800
Subject: [PATCH 2/2] add test

---
 clang/docs/ReleaseNotes.rst   |  2 ++
 clang/test/SemaCXX/friend.cpp | 16 
 2 files changed, 18 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index bc28bb567f6932a..a8ae5fb2596c580 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -533,6 +533,8 @@ Bug Fixes in This Version
   Fixes (`#67687 `_)
 - Fix crash from constexpr evaluator evaluating uninitialized arrays as rvalue.
   Fixes (`#67317 `_)
+- Fix an issue when do name lookup which scope resolution operator in friend 
function.
+  Fixes (`#21483 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/test/SemaCXX/friend.cpp b/clang/test/SemaCXX/friend.cpp
index 367d6a6c1807c92..7b8e50322c4f8f9 100644
--- a/clang/test/SemaCXX/friend.cpp
+++ b/clang/test/SemaCXX/friend.cpp
@@ -429,3 +429,19 @@ namespace qualified_friend_no_match {
 friend void Y::f(double); // expected-error {{friend declaration of 'f' 
does not match any declaration in 'qualified_friend_no_match::Y'}}
   };
 }
+
+namespace gh21483 {
+template 
+struct B {
+  struct mixin {
+int type;
+friend void foo(B::mixin it) {
+  (void)it.mixin::type;
+}
+  };
+};
+
+void bar() {
+  foo(B::mixin{});
+}
+}
\ No newline at end of file

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


[clang] Add ability for clang-format-diff to exit with non-0 status (PR #70883)

2023-10-31 Thread Owen Pan via cfe-commits


@@ -185,6 +191,8 @@ def main():
 diff_string = "".join(diff)
 if len(diff_string) > 0:
 sys.stdout.write(diff_string)
+if args.non_zero_exit_code:
+sys.exit(1)

owenca wrote:

```suggestion
sys.exit(1)
```
I don't think we need to add an option for this.

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


[clang] [clang][ASTImporter] Fix crash when template class static member imported to other translation unit. (PR #68774)

2023-10-31 Thread via cfe-commits

https://github.com/mzyKi updated https://github.com/llvm/llvm-project/pull/68774

>From 6e9fab5322a68c4f8b1f7fe94b00262c89c52975 Mon Sep 17 00:00:00 2001
From: miaozhiyuan 
Date: Wed, 11 Oct 2023 15:45:36 +0800
Subject: [PATCH] [clang][ASTImporter] Fix crash when template class static
 member imported to other translation unit. Fixes: #68769

---
 clang/docs/ReleaseNotes.rst |  4 +++
 clang/lib/AST/ASTImporter.cpp   | 11 
 clang/unittests/AST/ASTImporterTest.cpp | 34 +
 3 files changed, 49 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index bc28bb567f6932a..c3179b80cfcc577 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -670,6 +670,10 @@ Bug Fixes to C++ Support
   default initializing a base class in a constant expression context. Fixes:
   (`#69890 `_)
 
+- Fix crash when template class static member imported to other translation 
unit.
+  Fixes:
+  (`#68769 `_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 650ff201e66b72e..c4e931e220f69b5 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -4476,6 +4476,17 @@ ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
 auto ToVTOrErr = import(D->getDescribedVarTemplate());
 if (!ToVTOrErr)
   return ToVTOrErr.takeError();
+  } else if (MemberSpecializationInfo *MSI = D->getMemberSpecializationInfo()) 
{
+TemplateSpecializationKind SK = MSI->getTemplateSpecializationKind();
+VarDecl *FromInst = D->getInstantiatedFromStaticDataMember();
+if (Expected ToInstOrErr = import(FromInst))
+  ToVar->setInstantiationOfStaticDataMember(*ToInstOrErr, SK);
+else
+  return ToInstOrErr.takeError();
+if (ExpectedSLoc POIOrErr = import(MSI->getPointOfInstantiation()))
+  ToVar->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
+else
+  return POIOrErr.takeError();
   }
 
   if (Error Err = ImportInitializer(D, ToVar))
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 87e6cd1e160c4cc..d582500d124b474 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -1370,6 +1370,40 @@ TEST_P(ASTImporterOptionSpecificTestBase, 
ImportCorrectTemplatedDecl) {
   ASSERT_EQ(ToTemplated1, ToTemplated);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase,
+   ImportTemplateSpecializationStaticMember) {
+  auto FromCode = 
+R"(
+template  class Test{
+public:
+  static const unsigned int length;
+};
+
+template<> const unsigned int Test::length;
+template<> const unsigned int Test::length = 0;
+)";
+  auto ToCode = 
+R"(
+template  class Test {
+public:
+  static const unsigned int length;
+};
+
+template <> const unsigned int Test::length;
+
+void foo() { int i = 1 / Test::length; }
+)";
+  Decl *FromTU = getTuDecl(FromCode, Lang_CXX14);
+  auto FromDecl = FirstDeclMatcher().match(
+  FromTU, varDecl(hasName("length"), isDefinition()));
+  Decl *ToTu = getToTuDecl(ToCode, Lang_CXX14);
+  auto ToX = Import(FromDecl, Lang_CXX03);
+  auto ToDecl = FirstDeclMatcher().match(
+  ToTu, varDecl(hasName("length"), isDefinition()));
+  EXPECT_TRUE(ToX);
+  EXPECT_EQ(ToX, ToDecl);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, ImportChooseExpr) {
   // This tests the import of isConditionTrue directly to make sure the 
importer
   // gets it right.

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


[openmp] [flang] [clang-tools-extra] [clang] [lldb] [llvm] [libcxx] [compiler-rt] [OpenMP] Add memory diff dump for kernel record-replay (PR #70667)

2023-10-31 Thread via cfe-commits

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


[clang] [CUDA][HIP] Make template implicitly host device (PR #70369)

2023-10-31 Thread Yaxun Liu via cfe-commits

https://github.com/yxsamliu updated 
https://github.com/llvm/llvm-project/pull/70369

>From 5b783705b174fecccb8099c0c2c5b7c93a69cbcf Mon Sep 17 00:00:00 2001
From: "Yaxun (Sam) Liu" 
Date: Fri, 27 Oct 2023 23:34:51 -0400
Subject: [PATCH] [CUDA][HIP] Make template implicitly host device

Added option -foffload-implicit-host-device-templates which is off by default.

When the option is on, template functions and specializations without
host/device attributes have implicit host device attributes.

They can be overridden by device template functions with the same signagure.
They are emitted on device side only if they are used on device side.

This feature is added as an extension.
`__has_extension(cuda_implicit_host_device_templates)` can be used to
check whether it is enabled.

This is to facilitate using standard C++ headers for device.

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

Fixes: SWDEV-428314
---
 clang/include/clang/AST/ASTContext.h  |   4 +
 clang/include/clang/Basic/Features.def|   1 +
 clang/include/clang/Basic/LangOptions.def |   1 +
 clang/include/clang/Driver/Options.td |   8 ++
 clang/include/clang/Sema/Sema.h   |   4 +
 clang/lib/CodeGen/CodeGenModule.cpp   |  22 +++-
 clang/lib/Driver/ToolChains/Clang.cpp |   3 +
 clang/lib/Sema/SemaCUDA.cpp   |  42 ++-
 clang/lib/Sema/SemaExpr.cpp   |   7 ++
 .../CodeGenCUDA/implicit-host-device-fun.cu   | 118 ++
 clang/test/Lexer/has_extension.cu |  13 ++
 .../test/SemaCUDA/implicit-host-device-fun.cu |  22 
 12 files changed, 241 insertions(+), 4 deletions(-)
 create mode 100644 clang/test/CodeGenCUDA/implicit-host-device-fun.cu
 create mode 100644 clang/test/Lexer/has_extension.cu
 create mode 100644 clang/test/SemaCUDA/implicit-host-device-fun.cu

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index e5f78dfdc22ab1b..56c6b70f187043d 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -1156,6 +1156,10 @@ class ASTContext : public RefCountedBase {
   /// host code.
   llvm::DenseSet CUDAExternalDeviceDeclODRUsedByHost;
 
+  /// Keep track of CUDA/HIP implicit host device functions used on device side
+  /// in device compilation.
+  llvm::DenseSet CUDAImplicitHostDeviceFunUsedByDevice;
+
   ASTContext(LangOptions , SourceManager , IdentifierTable ,
  SelectorTable , Builtin::Context ,
  TranslationUnitKind TUKind);
diff --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index cf626d0120cc7c7..da77aee8de36990 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -283,6 +283,7 @@ FEATURE(cxx_abi_relative_vtable, LangOpts.CPlusPlus && 
LangOpts.RelativeCXXABIVT
 
 // CUDA/HIP Features
 FEATURE(cuda_noinline_keyword, LangOpts.CUDA)
+EXTENSION(cuda_implicit_host_device_templates, LangOpts.CUDA && 
LangOpts.OffloadImplicitHostDeviceTemplates)
 
 #undef EXTENSION
 #undef FEATURE
diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c0ea4ecb9806a5b..8f09d714d498c91 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -268,6 +268,7 @@ LANGOPT(CUDAAllowVariadicFunctions, 1, 0, "allowing 
variadic functions in CUDA d
 LANGOPT(CUDAHostDeviceConstexpr, 1, 1, "treating unattributed constexpr 
functions as __host__ __device__")
 LANGOPT(GPUDeviceApproxTranscendentals, 1, 0, "using approximate 
transcendental functions")
 LANGOPT(GPURelocatableDeviceCode, 1, 0, "generate relocatable device code")
+LANGOPT(OffloadImplicitHostDeviceTemplates, 1, 0, "assume template functions 
to be implicitly host device by default for CUDA/HIP")
 LANGOPT(GPUAllowDeviceInit, 1, 0, "allowing device side global init functions 
for HIP")
 LANGOPT(GPUMaxThreadsPerBlock, 32, 1024, "default max threads per block for 
kernel launch bounds for HIP")
 LANGOPT(GPUDeferDiag, 1, 0, "defer host/device related diagnostic messages for 
CUDA/HIP")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c8b730e0f7ecd84..759aee80223876d 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1146,6 +1146,14 @@ defm gpu_rdc : BoolFOption<"gpu-rdc",
   "Generate relocatable device code, also known as separate 
compilation mode">,
   NegFlag>;
 
+defm offload_implicit_host_device_templates :
+  BoolFOption<"offload-implicit-host-device-templates",
+  LangOpts<"OffloadImplicitHostDeviceTemplates">, DefaultFalse,
+  PosFlag,
+  NegFlag>;
+
 def fgpu_default_stream_EQ : Joined<["-"], "fgpu-default-stream=">,
   HelpText<"Specify default stream. The default value is 'legacy'. (CUDA/HIP 
only)">,
   Visibility<[ClangOption, CC1Option]>,
diff --git a/clang/include/clang/Sema/Sema.h 

[clang] [clang][ASTImporter] Fix crash when template class static member imported to other translation unit. (PR #68774)

2023-10-31 Thread via cfe-commits

https://github.com/mzyKi updated https://github.com/llvm/llvm-project/pull/68774

>From 4b095016c052e84a3863c8bc8b39a32efaecf5ef Mon Sep 17 00:00:00 2001
From: miaozhiyuan 
Date: Wed, 11 Oct 2023 15:45:36 +0800
Subject: [PATCH] [clang][ASTImporter] Fix crash when template class static
 member imported to other translation unit. Fixes: #68769

---
 clang/lib/AST/ASTImporter.cpp   | 11 
 clang/unittests/AST/ASTImporterTest.cpp | 34 +
 2 files changed, 45 insertions(+)

diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 650ff201e66b72e..c4e931e220f69b5 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -4476,6 +4476,17 @@ ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
 auto ToVTOrErr = import(D->getDescribedVarTemplate());
 if (!ToVTOrErr)
   return ToVTOrErr.takeError();
+  } else if (MemberSpecializationInfo *MSI = D->getMemberSpecializationInfo()) 
{
+TemplateSpecializationKind SK = MSI->getTemplateSpecializationKind();
+VarDecl *FromInst = D->getInstantiatedFromStaticDataMember();
+if (Expected ToInstOrErr = import(FromInst))
+  ToVar->setInstantiationOfStaticDataMember(*ToInstOrErr, SK);
+else
+  return ToInstOrErr.takeError();
+if (ExpectedSLoc POIOrErr = import(MSI->getPointOfInstantiation()))
+  ToVar->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
+else
+  return POIOrErr.takeError();
   }
 
   if (Error Err = ImportInitializer(D, ToVar))
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 87e6cd1e160c4cc..d582500d124b474 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -1370,6 +1370,40 @@ TEST_P(ASTImporterOptionSpecificTestBase, 
ImportCorrectTemplatedDecl) {
   ASSERT_EQ(ToTemplated1, ToTemplated);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase,
+   ImportTemplateSpecializationStaticMember) {
+  auto FromCode = 
+R"(
+template  class Test{
+public:
+  static const unsigned int length;
+};
+
+template<> const unsigned int Test::length;
+template<> const unsigned int Test::length = 0;
+)";
+  auto ToCode = 
+R"(
+template  class Test {
+public:
+  static const unsigned int length;
+};
+
+template <> const unsigned int Test::length;
+
+void foo() { int i = 1 / Test::length; }
+)";
+  Decl *FromTU = getTuDecl(FromCode, Lang_CXX14);
+  auto FromDecl = FirstDeclMatcher().match(
+  FromTU, varDecl(hasName("length"), isDefinition()));
+  Decl *ToTu = getToTuDecl(ToCode, Lang_CXX14);
+  auto ToX = Import(FromDecl, Lang_CXX03);
+  auto ToDecl = FirstDeclMatcher().match(
+  ToTu, varDecl(hasName("length"), isDefinition()));
+  EXPECT_TRUE(ToX);
+  EXPECT_EQ(ToX, ToDecl);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, ImportChooseExpr) {
   // This tests the import of isConditionTrue directly to make sure the 
importer
   // gets it right.

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


[clang] [clang][ASTImporter] Fix crash when template class static member imported to other translation unit. (PR #68774)

2023-10-31 Thread via cfe-commits

https://github.com/mzyKi updated https://github.com/llvm/llvm-project/pull/68774

>From cae81d39aa71535eea9b09cda651efa3e1fffdfc Mon Sep 17 00:00:00 2001
From: miaozhiyuan 
Date: Wed, 11 Oct 2023 15:45:36 +0800
Subject: [PATCH] [clang][ASTImporter] Fix crash when template class static
 member imported to other translation unit. Fixes: #68769

---
 clang/lib/AST/ASTImporter.cpp   | 11 
 clang/unittests/AST/ASTImporterTest.cpp | 34 +
 2 files changed, 45 insertions(+)

diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 650ff201e66b72e..c4e931e220f69b5 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -4476,6 +4476,17 @@ ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
 auto ToVTOrErr = import(D->getDescribedVarTemplate());
 if (!ToVTOrErr)
   return ToVTOrErr.takeError();
+  } else if (MemberSpecializationInfo *MSI = D->getMemberSpecializationInfo()) 
{
+TemplateSpecializationKind SK = MSI->getTemplateSpecializationKind();
+VarDecl *FromInst = D->getInstantiatedFromStaticDataMember();
+if (Expected ToInstOrErr = import(FromInst))
+  ToVar->setInstantiationOfStaticDataMember(*ToInstOrErr, SK);
+else
+  return ToInstOrErr.takeError();
+if (ExpectedSLoc POIOrErr = import(MSI->getPointOfInstantiation()))
+  ToVar->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
+else
+  return POIOrErr.takeError();
   }
 
   if (Error Err = ImportInitializer(D, ToVar))
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 87e6cd1e160c4cc..09f289f309a4be1 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -1370,6 +1370,40 @@ TEST_P(ASTImporterOptionSpecificTestBase, 
ImportCorrectTemplatedDecl) {
   ASSERT_EQ(ToTemplated1, ToTemplated);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase,
+   ImportTemplateSpecializationStaticMember) {
+  auto FromCode = 
+R"(
+template  class Test{
+public:
+   static const unsigned int length;
+};
+
+template<> const unsigned int Test::length;
+template<> const unsigned int Test::length = 0;
+)";
+  auto ToCode = 
+R"(
+template  class Test {
+public:
+  static const unsigned int length;
+};
+
+template <> const unsigned int Test::length;
+
+void foo() { int i = 1 / Test::length; }
+)";
+  Decl *FromTU = getTuDecl(FromCode, Lang_CXX14);
+  auto FromDecl = FirstDeclMatcher().match(
+  FromTU, varDecl(hasName("length"), isDefinition()));
+  Decl *ToTu = getToTuDecl(ToCode, Lang_CXX14);
+  auto ToX = Import(FromDecl, Lang_CXX03);
+  auto ToDecl = FirstDeclMatcher().match(
+  ToTu, varDecl(hasName("length"), isDefinition()));
+  EXPECT_TRUE(ToX);
+  EXPECT_EQ(ToX, ToDecl);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, ImportChooseExpr) {
   // This tests the import of isConditionTrue directly to make sure the 
importer
   // gets it right.

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


[clang] [clang][ASTImporter] Fix crash when template class static member imported to other translation unit. (PR #68774)

2023-10-31 Thread via cfe-commits

https://github.com/mzyKi updated https://github.com/llvm/llvm-project/pull/68774

>From fa32c05f7af8ee64d0cf3b427755e87b6ed07547 Mon Sep 17 00:00:00 2001
From: miaozhiyuan 
Date: Wed, 11 Oct 2023 15:45:36 +0800
Subject: [PATCH] [clang][ASTImporter] Fix crash when template class static
 member imported to other translation unit. Fixes: #68769

---
 clang/lib/AST/ASTImporter.cpp   | 11 
 clang/unittests/AST/ASTImporterTest.cpp | 34 +
 2 files changed, 45 insertions(+)

diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 650ff201e66b72e..c4e931e220f69b5 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -4476,6 +4476,17 @@ ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
 auto ToVTOrErr = import(D->getDescribedVarTemplate());
 if (!ToVTOrErr)
   return ToVTOrErr.takeError();
+  } else if (MemberSpecializationInfo *MSI = D->getMemberSpecializationInfo()) 
{
+TemplateSpecializationKind SK = MSI->getTemplateSpecializationKind();
+VarDecl *FromInst = D->getInstantiatedFromStaticDataMember();
+if (Expected ToInstOrErr = import(FromInst))
+  ToVar->setInstantiationOfStaticDataMember(*ToInstOrErr, SK);
+else
+  return ToInstOrErr.takeError();
+if (ExpectedSLoc POIOrErr = import(MSI->getPointOfInstantiation()))
+  ToVar->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
+else
+  return POIOrErr.takeError();
   }
 
   if (Error Err = ImportInitializer(D, ToVar))
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 87e6cd1e160c4cc..119ee58e55310b4 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -1370,6 +1370,40 @@ TEST_P(ASTImporterOptionSpecificTestBase, 
ImportCorrectTemplatedDecl) {
   ASSERT_EQ(ToTemplated1, ToTemplated);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase,
+   ImportTemplateSpecializationStaticMember) {
+  auto FromCode = 
+R"(
+template  class Test{
+public:
+   static const unsigned int length;
+};
+
+template<> const unsigned int Test::length;
+template<> const unsigned int Test::length = 0;
+)";
+  auto ToCode = 
+R"(
+template  class Test {
+public:
+  static const unsigned int length;
+};
+
+template <> const unsigned int Test::length;
+
+void foo() { int i = 1 / Test::length; }
+)";
+  Decl *FromTU = getTuDecl(FromCode, Lang_CXX14);
+  auto FromDecl = FirstDeclMatcher().match(
+  FromTU, varDecl(hasName("length"), isDefinition()));
+  Decl *ToTu = getToTuDecl(ToCode, Lang_CXX14);
+  auto ToX = Import(FromDecl, Lang_CXX03);
+  auto ToDecl = FirstDeclMatcher().match(
+  ToTu, varDecl(hasName("length"), isDefinition()));
+  EXPECT_TRUE(ToX);
+  EXPECT_EQ(ToX, ToDecl);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, ImportChooseExpr) {
   // This tests the import of isConditionTrue directly to make sure the 
importer
   // gets it right.

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


[clang] [llvm] [clang-tools-extra] [DAGCombine] Fold setcc_eq infinity into is.fpclass (PR #67829)

2023-10-31 Thread Matt Arsenault via cfe-commits

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


[clang] [llvm] [clang-tools-extra] [DAGCombine] Fold setcc_eq infinity into is.fpclass (PR #67829)

2023-10-31 Thread Matt Arsenault via cfe-commits

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


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


[clang] [CUDA][HIP] Make template implicitly host device (PR #70369)

2023-10-31 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 ff614a5729e9a4fc32465ad5ff3b87e044429c2d 
0c44a09f45f865f2774bbe33094f1cd262d7c045 -- 
clang/include/clang/AST/ASTContext.h clang/include/clang/Sema/Sema.h 
clang/lib/CodeGen/CodeGenModule.cpp clang/lib/Driver/ToolChains/Clang.cpp 
clang/lib/Sema/SemaCUDA.cpp clang/lib/Sema/SemaExpr.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 17a4e9003ba6..0acd2a8d0d7b 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -8630,15 +8630,14 @@ ExprResult Sema::BuildVectorLiteral(SourceLocation 
LParenLoc,
 // For OpenCL, when the number of initializers is a single value,
 // it will be replicated to all components of the vector.
 if (getLangOpts().OpenCL &&
-VTy->getVectorKind() == VectorType::GenericVector &&
-numExprs == 1) {
-QualType ElemTy = VTy->getElementType();
-ExprResult Literal = DefaultLvalueConversion(exprs[0]);
-if (Literal.isInvalid())
-  return ExprError();
-Literal = ImpCastExprToType(Literal.get(), ElemTy,
-PrepareScalarCast(Literal, ElemTy));
-return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
+VTy->getVectorKind() == VectorType::GenericVector && numExprs == 1) {
+  QualType ElemTy = VTy->getElementType();
+  ExprResult Literal = DefaultLvalueConversion(exprs[0]);
+  if (Literal.isInvalid())
+return ExprError();
+  Literal = ImpCastExprToType(Literal.get(), ElemTy,
+  PrepareScalarCast(Literal, ElemTy));
+  return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
 }
 
 initExprs.append(exprs, exprs + numExprs);
@@ -11096,9 +11095,9 @@ QualType Sema::CheckVectorOperands(ExprResult , 
ExprResult ,
 
   // AltiVec-style "vector bool op vector bool" combinations are allowed
   // for some operators but not others.
-  if (!AllowBothBool &&
-  LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
-  RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
+  if (!AllowBothBool && LHSVecType &&
+  LHSVecType->getVectorKind() == VectorType::AltiVecBool && RHSVecType &&
+  RHSVecType->getVectorKind() == VectorType::AltiVecBool)
 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
 
   // This operation may not be performed on boolean vectors.
@@ -14881,8 +14880,8 @@ static QualType CheckIncrementDecrementOperand(Sema , 
Expr *Op,
  (ResType->castAs()->getVectorKind() !=
   VectorType::AltiVecBool)) {
 // The z vector extensions allow ++ and -- for non-bool vectors.
-  } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
-ResType->castAs()->getElementType()->isIntegerType()) {
+  } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
+ ResType->castAs()->getElementType()->isIntegerType()) 
{
 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
   } else {
 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
@@ -16371,7 +16370,7 @@ ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation 
OpLoc,
  // The z vector extensions don't allow + or - with bool vectors.
  (!Context.getLangOpts().ZVector ||
   resultType->castAs()->getVectorKind() !=
-  VectorType::AltiVecBool))
+  VectorType::AltiVecBool))
   break;
 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
   break;

``




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


[openmp] [llvm] [mlir] [clang] [OpenMP] Introduce the KernelLaunchEnvironment as implicit argument (PR #70401)

2023-10-31 Thread Johannes Doerfert via cfe-commits

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


[openmp] [llvm] [mlir] [clang] [OpenMP] Introduce the KernelLaunchEnvironment as implicit argument (PR #70401)

2023-10-31 Thread Johannes Doerfert via cfe-commits

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


[clang] [CUDA][HIP] Make template implicitly host device (PR #70369)

2023-10-31 Thread Yaxun Liu via cfe-commits

https://github.com/yxsamliu updated 
https://github.com/llvm/llvm-project/pull/70369

>From 0c44a09f45f865f2774bbe33094f1cd262d7c045 Mon Sep 17 00:00:00 2001
From: "Yaxun (Sam) Liu" 
Date: Fri, 27 Oct 2023 23:34:51 -0400
Subject: [PATCH] [CUDA][HIP] Make template implicitly host device

Added option -foffload-implicit-host-device-templates which is off by default.

When the option is on, template functions and specializations without
host/device attributes have implicit host device attributes.

They can be overridden by device template functions with the same signagure.
They are emitted on device side only if they are used on device side.

This feature is added as an extension.
`__has_extension(cuda_implicit_host_device_templates)` can be used to
check whether it is enabled.

This is to facilitate using standard C++ headers for device.

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

Fixes: SWDEV-428314
---
 clang/include/clang/AST/ASTContext.h  |   4 +
 clang/include/clang/Basic/Features.def|   1 +
 clang/include/clang/Basic/LangOptions.def |   1 +
 clang/include/clang/Driver/Options.td |   8 ++
 clang/include/clang/Sema/Sema.h   |   4 +
 clang/lib/CodeGen/CodeGenModule.cpp   |  22 +++-
 clang/lib/Driver/ToolChains/Clang.cpp |   3 +
 clang/lib/Sema/SemaCUDA.cpp   |  42 ++-
 clang/lib/Sema/SemaExpr.cpp   |   7 ++
 .../CodeGenCUDA/implicit-host-device-fun.cu   | 118 ++
 clang/test/Lexer/has_extension.cu |  13 ++
 .../test/SemaCUDA/implicit-host-device-fun.cu |  22 
 12 files changed, 241 insertions(+), 4 deletions(-)
 create mode 100644 clang/test/CodeGenCUDA/implicit-host-device-fun.cu
 create mode 100644 clang/test/Lexer/has_extension.cu
 create mode 100644 clang/test/SemaCUDA/implicit-host-device-fun.cu

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 24d22a9c692cd34..e34ad155c25c3a2 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -1156,6 +1156,10 @@ class ASTContext : public RefCountedBase {
   /// host code.
   llvm::DenseSet CUDAExternalDeviceDeclODRUsedByHost;
 
+  /// Keep track of CUDA/HIP implicit host device functions used on device side
+  /// in device compilation.
+  llvm::DenseSet CUDAImplicitHostDeviceFunUsedByDevice;
+
   ASTContext(LangOptions , SourceManager , IdentifierTable ,
  SelectorTable , Builtin::Context ,
  TranslationUnitKind TUKind);
diff --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index cf626d0120cc7c7..da77aee8de36990 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -283,6 +283,7 @@ FEATURE(cxx_abi_relative_vtable, LangOpts.CPlusPlus && 
LangOpts.RelativeCXXABIVT
 
 // CUDA/HIP Features
 FEATURE(cuda_noinline_keyword, LangOpts.CUDA)
+EXTENSION(cuda_implicit_host_device_templates, LangOpts.CUDA && 
LangOpts.OffloadImplicitHostDeviceTemplates)
 
 #undef EXTENSION
 #undef FEATURE
diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c0ea4ecb9806a5b..8f09d714d498c91 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -268,6 +268,7 @@ LANGOPT(CUDAAllowVariadicFunctions, 1, 0, "allowing 
variadic functions in CUDA d
 LANGOPT(CUDAHostDeviceConstexpr, 1, 1, "treating unattributed constexpr 
functions as __host__ __device__")
 LANGOPT(GPUDeviceApproxTranscendentals, 1, 0, "using approximate 
transcendental functions")
 LANGOPT(GPURelocatableDeviceCode, 1, 0, "generate relocatable device code")
+LANGOPT(OffloadImplicitHostDeviceTemplates, 1, 0, "assume template functions 
to be implicitly host device by default for CUDA/HIP")
 LANGOPT(GPUAllowDeviceInit, 1, 0, "allowing device side global init functions 
for HIP")
 LANGOPT(GPUMaxThreadsPerBlock, 32, 1024, "default max threads per block for 
kernel launch bounds for HIP")
 LANGOPT(GPUDeferDiag, 1, 0, "defer host/device related diagnostic messages for 
CUDA/HIP")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c8b730e0f7ecd84..759aee80223876d 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1146,6 +1146,14 @@ defm gpu_rdc : BoolFOption<"gpu-rdc",
   "Generate relocatable device code, also known as separate 
compilation mode">,
   NegFlag>;
 
+defm offload_implicit_host_device_templates :
+  BoolFOption<"offload-implicit-host-device-templates",
+  LangOpts<"OffloadImplicitHostDeviceTemplates">, DefaultFalse,
+  PosFlag,
+  NegFlag>;
+
 def fgpu_default_stream_EQ : Joined<["-"], "fgpu-default-stream=">,
   HelpText<"Specify default stream. The default value is 'legacy'. (CUDA/HIP 
only)">,
   Visibility<[ClangOption, CC1Option]>,
diff --git a/clang/include/clang/Sema/Sema.h 

[clang] Add ability for clang-format-diff to exit with non-0 status (PR #70883)

2023-10-31 Thread Conrad Donahue via cfe-commits

https://github.com/conrad-donahue updated 
https://github.com/llvm/llvm-project/pull/70883

>From 646cabcf167facb63c78277b50ea62afbc61b3c0 Mon Sep 17 00:00:00 2001
From: Conrad Donahue 
Date: Tue, 31 Oct 2023 21:55:27 -0400
Subject: [PATCH 1/2] Add ability for clang-format-diff to exit with non-0
 status

---
 clang/docs/ClangFormat.rst| 1 +
 clang/tools/clang-format/clang-format-diff.py | 8 
 2 files changed, 9 insertions(+)

diff --git a/clang/docs/ClangFormat.rst b/clang/docs/ClangFormat.rst
index f52f35550d03eb6..42864b90e408037 100644
--- a/clang/docs/ClangFormat.rst
+++ b/clang/docs/ClangFormat.rst
@@ -325,6 +325,7 @@ output of a unified diff and reformats all contained lines 
with
   The name of the predefined style used as a fallback 
in case clang-format is invoked with-style=file, but can not
   find the .clang-formatfile to use.
 -binary BINARYlocation of binary to use for clang-format
+-non-zero-exit-code   exit with a non-zero status if formatting changes 
are necessary
 
 To reformat all the lines in the latest Mercurial/:program:`hg` commit, do:
 
diff --git a/clang/tools/clang-format/clang-format-diff.py 
b/clang/tools/clang-format/clang-format-diff.py
index 324ef5b7f6b35f6..755ef23649a2469 100755
--- a/clang/tools/clang-format/clang-format-diff.py
+++ b/clang/tools/clang-format/clang-format-diff.py
@@ -95,6 +95,12 @@ def main():
 default="clang-format",
 help="location of binary to use for clang-format",
 )
+parser.add_argument(
+"-non-zero-exit-code",
+action="store_true",
+default=False,
+help="exit with a non-zero status if formatting changes are necessary"
+)
 args = parser.parse_args()
 
 # Extract changed lines for each file.
@@ -185,6 +191,8 @@ def main():
 diff_string = "".join(diff)
 if len(diff_string) > 0:
 sys.stdout.write(diff_string)
+if args.non_zero_exit_code:
+sys.exit(1)
 
 
 if __name__ == "__main__":

>From 929ccfdae7bf8d377e20f69200826cb67fcca76a Mon Sep 17 00:00:00 2001
From: Conrad Donahue 
Date: Tue, 31 Oct 2023 22:14:50 -0400
Subject: [PATCH 2/2] Fix formatting in clang-format-diff.py

---
 clang/tools/clang-format/clang-format-diff.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/tools/clang-format/clang-format-diff.py 
b/clang/tools/clang-format/clang-format-diff.py
index 755ef23649a2469..3d5542b65529df2 100755
--- a/clang/tools/clang-format/clang-format-diff.py
+++ b/clang/tools/clang-format/clang-format-diff.py
@@ -99,7 +99,7 @@ def main():
 "-non-zero-exit-code",
 action="store_true",
 default=False,
-help="exit with a non-zero status if formatting changes are necessary"
+help="exit with a non-zero status if formatting changes are necessary",
 )
 args = parser.parse_args()
 

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


[clang] Add ability for clang-format-diff to exit with non-0 status (PR #70883)

2023-10-31 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
darker --check --diff -r 
2164a449dc7a9daf610b789ba0ec7d1eca7305ef..646cabcf167facb63c78277b50ea62afbc61b3c0
 clang/tools/clang-format/clang-format-diff.py
``





View the diff from darker here.


``diff
--- clang-format-diff.py2023-11-01 01:55:27.00 +
+++ clang-format-diff.py2023-11-01 02:10:13.409792 +
@@ -97,11 +97,11 @@
 )
 parser.add_argument(
 "-non-zero-exit-code",
 action="store_true",
 default=False,
-help="exit with a non-zero status if formatting changes are necessary"
+help="exit with a non-zero status if formatting changes are necessary",
 )
 args = parser.parse_args()
 
 # Extract changed lines for each file.
 filename = None

``




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


[clang] Add ability for clang-format-diff to exit with non-0 status (PR #70883)

2023-10-31 Thread Conrad Donahue via cfe-commits

https://github.com/conrad-donahue created 
https://github.com/llvm/llvm-project/pull/70883

This patch adds the ability for the clang-format-diff script to exit with a 
non-zero status if it detects that formatting changes are necessary. This makes 
it easier to use clang-format-diff as part of a DevOps pipeline, since you 
could add a stage to run clang-format-diff and fail if the formatting needs to 
be fixed.

>From 646cabcf167facb63c78277b50ea62afbc61b3c0 Mon Sep 17 00:00:00 2001
From: Conrad Donahue 
Date: Tue, 31 Oct 2023 21:55:27 -0400
Subject: [PATCH] Add ability for clang-format-diff to exit with non-0 status

---
 clang/docs/ClangFormat.rst| 1 +
 clang/tools/clang-format/clang-format-diff.py | 8 
 2 files changed, 9 insertions(+)

diff --git a/clang/docs/ClangFormat.rst b/clang/docs/ClangFormat.rst
index f52f35550d03eb6..42864b90e408037 100644
--- a/clang/docs/ClangFormat.rst
+++ b/clang/docs/ClangFormat.rst
@@ -325,6 +325,7 @@ output of a unified diff and reformats all contained lines 
with
   The name of the predefined style used as a fallback 
in case clang-format is invoked with-style=file, but can not
   find the .clang-formatfile to use.
 -binary BINARYlocation of binary to use for clang-format
+-non-zero-exit-code   exit with a non-zero status if formatting changes 
are necessary
 
 To reformat all the lines in the latest Mercurial/:program:`hg` commit, do:
 
diff --git a/clang/tools/clang-format/clang-format-diff.py 
b/clang/tools/clang-format/clang-format-diff.py
index 324ef5b7f6b35f6..755ef23649a2469 100755
--- a/clang/tools/clang-format/clang-format-diff.py
+++ b/clang/tools/clang-format/clang-format-diff.py
@@ -95,6 +95,12 @@ def main():
 default="clang-format",
 help="location of binary to use for clang-format",
 )
+parser.add_argument(
+"-non-zero-exit-code",
+action="store_true",
+default=False,
+help="exit with a non-zero status if formatting changes are necessary"
+)
 args = parser.parse_args()
 
 # Extract changed lines for each file.
@@ -185,6 +191,8 @@ def main():
 diff_string = "".join(diff)
 if len(diff_string) > 0:
 sys.stdout.write(diff_string)
+if args.non_zero_exit_code:
+sys.exit(1)
 
 
 if __name__ == "__main__":

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


[clang] [clang][analyzer] Restrict 'fopen' & 'tmpfile' modeling to POSIX versions in StreamChecker (PR #70540)

2023-10-31 Thread Ben Shi via cfe-commits

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


[clang] [clang][analyzer] Update CallDescription of 'tmpfile' & 'fopen' in StreamChecker (PR #70540)

2023-10-31 Thread Ben Shi via cfe-commits


@@ -0,0 +1,16 @@
+// RUN: %clang_analyze_cc1 -fno-builtin 
-analyzer-checker=core,alpha.unix.Stream -verify %s
+// expected-no-diagnostics
+
+typedef struct _FILE FILE;
+
+// These functions are not standard C library functions.
+FILE *tmpfile(const char *restrict path);
+FILE *fopen(const char *restrict path);
+
+void test_fopen(void) {
+  FILE *fp = fopen("file");
+}
+
+void test_tmpfile(void) {
+  FILE *fp = tmpfile("file");
+}

benshi001 wrote:

Done. Thanks.

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


[clang] [clang][analyzer] Update CallDescription of 'tmpfile' & 'fopen' in StreamChecker (PR #70540)

2023-10-31 Thread Ben Shi via cfe-commits


@@ -0,0 +1,16 @@
+// RUN: %clang_analyze_cc1 -fno-builtin 
-analyzer-checker=core,alpha.unix.Stream -verify %s
+// expected-no-diagnostics
+
+typedef struct _FILE FILE;
+
+// These functions are not standard C library functions.
+FILE *tmpfile(const char *restrict path);
+FILE *fopen(const char *restrict path);

benshi001 wrote:

Done. Thanks.

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


[clang] [clang][analyzer] Update CallDescription of 'tmpfile' & 'fopen' in StreamChecker (PR #70540)

2023-10-31 Thread Ben Shi via cfe-commits

https://github.com/benshi001 updated 
https://github.com/llvm/llvm-project/pull/70540

>From e7f49e4c01de58c61337c577854b33793da46e8a Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Tue, 31 Oct 2023 13:05:19 +0800
Subject: [PATCH] [clang][analyzer] Restrict 'fopen' & 'tmpfile' modeling to
 POSIX versions in StreamChecker

---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp|  4 ++--
 clang/test/Analysis/stream-non-posix-function.c  | 16 
 2 files changed, 18 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/Analysis/stream-non-posix-function.c

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 4b7103c20557cc4..7e8031c7545f691 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -238,10 +238,10 @@ class StreamChecker : public Checker FnDescriptions = {
-  {{{"fopen"}}, {nullptr, ::evalFopen, ArgNone}},
+  {{{"fopen"}, 2}, {nullptr, ::evalFopen, ArgNone}},
   {{{"freopen"}, 3},
{::preFreopen, ::evalFreopen, 2}},
-  {{{"tmpfile"}}, {nullptr, ::evalFopen, ArgNone}},
+  {{{"tmpfile"}, 0}, {nullptr, ::evalFopen, ArgNone}},
   {{{"fclose"}, 1},
{::preDefault, ::evalFclose, 0}},
   {{{"fread"}, 4},
diff --git a/clang/test/Analysis/stream-non-posix-function.c 
b/clang/test/Analysis/stream-non-posix-function.c
new file mode 100644
index 000..2d34d10b239bb4a
--- /dev/null
+++ b/clang/test/Analysis/stream-non-posix-function.c
@@ -0,0 +1,16 @@
+// RUN: %clang_analyze_cc1 -fno-builtin 
-analyzer-checker=core,alpha.unix.Stream -verify %s
+// expected-no-diagnostics
+
+typedef struct _FILE FILE;
+
+// These functions are not standard C library functions.
+FILE *tmpfile(const char *restrict path); // Real 'tmpfile' should have 
exactly 0 formal parameters.
+FILE *fopen(const char *restrict path);   // Real 'fopen' should have exactly 
2 formal parameters.
+
+void test_fopen_non_posix(void) {
+  FILE *fp = fopen("file"); // no-leak: this isn't the standard POSIX fopen, 
we don't the semantics of this call.
+}
+
+void test_tmpfile_non_posix(void) {
+  FILE *fp = tmpfile("file"); // no-leak: this isn't the standard POSIX 
tmpfile, we don't the semantics of this call.
+}

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


[clang] [Clang] Defer the instantiation of explicit-specifier until constraint checking completes (PR #70548)

2023-10-31 Thread via cfe-commits

https://github.com/LYP951018 updated 
https://github.com/llvm/llvm-project/pull/70548

From 11ceaed39b3f0c60c5a44c3b3a2b5856e7ee9a8d Mon Sep 17 00:00:00 2001
From: letrec 
Date: Sat, 28 Oct 2023 18:05:36 +0800
Subject: [PATCH 1/7] Defer the instantiation of explicit-specifier after
 constraint checking

---
 clang/docs/ReleaseNotes.rst   |  4 ++
 clang/include/clang/Sema/Sema.h   |  3 +
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 59 +++
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 40 -
 .../SemaCXX/cxx2a-explicit-bool-deferred.cpp  | 31 ++
 5 files changed, 123 insertions(+), 14 deletions(-)
 create mode 100644 clang/test/SemaCXX/cxx2a-explicit-bool-deferred.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index bc28bb567f6932a..d9980694de40f6f 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -670,6 +670,10 @@ Bug Fixes to C++ Support
   default initializing a base class in a constant expression context. Fixes:
   (`#69890 `_)
 
+- Clang now defers the instantiation of explicit specifier until constraint 
checking
+  completes (except deduction guides). Fixes:
+  (`#59827 `_)
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 91a4211a5cf5cce..daed24be0a86d11 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -10430,6 +10430,9 @@ class Sema final {
   const CXXConstructorDecl *Tmpl,
 const MultiLevelTemplateArgumentList 
);
 
+  ExplicitSpecifier instantiateExplicitSpecifier(
+  const MultiLevelTemplateArgumentList , ExplicitSpecifier 
ES);
+
   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
   const MultiLevelTemplateArgumentList ,
   bool FindingInstantiatedContext = false);
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 0b3f0247ea3bee3..f06332770f51d1f 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3553,6 +3553,56 @@ static unsigned getPackIndexForParam(Sema ,
   llvm_unreachable("parameter index would not be produced from template");
 }
 
+// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`
+// we try to instantiate and update its explicit specifier after constraint
+// checking.
+static Sema::TemplateDeductionResult
+tryInstantiateExplicitSpecifier(Sema , FunctionDecl *Specialization,
+const MultiLevelTemplateArgumentList 
,
+TemplateDeductionInfo ,
+FunctionTemplateDecl *FunctionTemplate,
+ArrayRef DeducedArgs) {
+
+  const auto TryInstantiateExplicitSpecifierForSingleDecl =
+  [&](auto *ExplicitDecl) {
+ExplicitSpecifier ExplicitSpecifier =
+ExplicitDecl->getExplicitSpecifier();
+Expr *const Expr = ExplicitSpecifier.getExpr();
+if (!Expr) {
+  return Sema::TDK_Success;
+}
+if (!Expr->isValueDependent()) {
+  return Sema::TDK_Success;
+}
+// TemplateDeclInstantiator::InitFunctionInstantiation set the
+// ActiveInstType to TemplateInstantiation, but we need
+// to enable SFINAE when instantiating explicit specifier.
+Sema::InstantiatingTemplate Inst(
+S, Info.getLocation(), FunctionTemplate, DeducedArgs,
+Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
+Info);
+const auto Instantiated =
+S.instantiateExplicitSpecifier(SubstArgs, ExplicitSpecifier);
+if (Instantiated.isInvalid()) {
+  ExplicitDecl->setInvalidDecl(true);
+  return clang::Sema::TDK_SubstitutionFailure;
+}
+ExplicitDecl->setExplicitSpecifier(Instantiated);
+return clang::Sema::TDK_Success;
+  };
+  Sema::TemplateDeductionResult DeductionResult = clang::Sema::TDK_Success;
+  if (CXXConstructorDecl *ConstructorDecl =
+  dyn_cast_or_null(Specialization)) {
+DeductionResult =
+TryInstantiateExplicitSpecifierForSingleDecl(ConstructorDecl);
+  } else if (CXXConversionDecl *ConversionDecl =
+ dyn_cast_or_null(Specialization)) {
+DeductionResult =
+TryInstantiateExplicitSpecifierForSingleDecl(ConversionDecl);
+  }
+  return DeductionResult;
+}
+
 /// Finish template argument deduction for a function template,
 /// checking the deduced template arguments for completeness and forming
 /// the function template specialization.
@@ -3682,6 +3732,15 @@ 

[clang] [lldb] [clang][DebugInfo] Emit global variable definitions for static data members with constant initializers (PR #70639)

2023-10-31 Thread Michael Buch via cfe-commits

Michael137 wrote:

> The DWARFASTParserClang.cpp will try to create the class from the DWARF for 
> the class definition. You will need to find the DW_TAG_variable when we are 
> creating the static field if there is no DW_AT_const_value in the 
> DW_TAG_member. But we also need to support the DW_AT_const_value being in the 
> DW_TAG_member since older DWARF will be emitted like this.

That's 100% correct. I was thinking, before [this 
block](https://github.com/llvm/llvm-project/blob/8b91de5d6a3f98dcc00bbd286e339e512f7e3682/lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp#L2909-L2919)
 where we check for the existence of a `const_value_form`. With this patch such 
constant won't exist on the declaration. So I was thinking we would try to look 
for the definition. What's interesting is that with this patch, the expression 
evaluator successfully finds the DW_TAG_variable which have a location 
attribute but not if they have a constant instead of a location. It's probably 
some logic that assumes statics always have a location

> Are we going to emit a DW_AT_const_expr now in the DW_TAG_member? If so, then 
> we will know that we need to look for the DW_TAG_variable. I don't think 
> clang emitted the DW_AT_const_expr attribute before.

That wasn't part of this patch. But would make sense to add (i've noticed GCC 
adds that attribute)

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


[clang] [Driver] Silence stdlib warning when linking C on *BSD / Solaris / Haiku (PR #70434)

2023-10-31 Thread Brad Smith via cfe-commits

brad0 wrote:

ping.

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


[clang] [clang][driver] Add \/../include/c++/v1 to include path on Darwin (PR #70817)

2023-10-31 Thread Liviu Ionescu via cfe-commits

ilg-ul wrote:

> Is there any reason why we don't just use Dir all the time?

That's a good question.

There was a long discussion in #68091, and my understanding is that, for 
compatibility reasons, the current behaviour must be preserved.

> What's the difference between those two?

`Dir` is the location where the actual executables are installed.
`InstalledDir`, when the compiler is invoked via a link, is the location where 
the link comes from.

In my use case, and probably in most use cases, the location where the link 
comes from is a plain folder, not a hierarchy specific to a toolchain.

However, for testing purposes, including several clang tests, such a hierarchy 
is created, with other headers, and a link is placed there, with the 
expectation that the compiler will use that environment and not the one where 
the toolchain is actually installed.

There are many places in the source code where something is searched for first 
in the `InstalledDir`, and, if not found, it is also searched in `Dir`. 

This patch uses exactly the same strategy for identifying the C++ headers on 
Darwin. Without the patch, when using links the compiler chooses the SDK 
headers, which is plainly wrong and damaging.



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


[clang-tools-extra] [libcxx] [clang] [llvm] [libc++] Fix complexity guarantee in ranges::clamp (PR #68413)

2023-10-31 Thread Louis Dionne via cfe-commits

https://github.com/ldionne updated 
https://github.com/llvm/llvm-project/pull/68413

>From 24d5794c366670fb4d8fe3ec72c27d7c9ef335b9 Mon Sep 17 00:00:00 2001
From: Louis Dionne 
Date: Fri, 6 Oct 2023 08:57:23 -0400
Subject: [PATCH 1/4] [libc++] Fix complexity guarantee in std::clamp

This patch prevents us from calling the projection more than 3 times in
std::clamp, as required by the Standard.

Fixes #64717
---
 libcxx/include/__algorithm/ranges_clamp.h |  5 +-
 .../alg.clamp/ranges.clamp.pass.cpp   | 49 +++
 2 files changed, 32 insertions(+), 22 deletions(-)

diff --git a/libcxx/include/__algorithm/ranges_clamp.h 
b/libcxx/include/__algorithm/ranges_clamp.h
index 9613f7f37720a6c..e6c86207254a19f 100644
--- a/libcxx/include/__algorithm/ranges_clamp.h
+++ b/libcxx/include/__algorithm/ranges_clamp.h
@@ -37,9 +37,10 @@ struct __fn {
 _LIBCPP_ASSERT_UNCATEGORIZED(!bool(std::invoke(__comp, std::invoke(__proj, 
__high), std::invoke(__proj, __low))),
  "Bad bounds passed to std::ranges::clamp");
 
-if (std::invoke(__comp, std::invoke(__proj, __value), std::invoke(__proj, 
__low)))
+auto&& __projected = std::invoke(__proj, __value);
+if (std::invoke(__comp, std::forward(__projected), 
std::invoke(__proj, __low)))
   return __low;
-else if (std::invoke(__comp, std::invoke(__proj, __high), 
std::invoke(__proj, __value)))
+else if (std::invoke(__comp, std::invoke(__proj, __high), 
std::forward(__projected)))
   return __high;
 else
   return __value;
diff --git 
a/libcxx/test/std/algorithms/alg.sorting/alg.clamp/ranges.clamp.pass.cpp 
b/libcxx/test/std/algorithms/alg.sorting/alg.clamp/ranges.clamp.pass.cpp
index 036552f75de4eb4..35ef55a91e243d4 100644
--- a/libcxx/test/std/algorithms/alg.sorting/alg.clamp/ranges.clamp.pass.cpp
+++ b/libcxx/test/std/algorithms/alg.sorting/alg.clamp/ranges.clamp.pass.cpp
@@ -38,6 +38,16 @@ static_assert(!HasClamp);
 static_assert(!HasClamp);
 static_assert(!HasClamp);
 
+struct EnsureValueCategoryComp {
+  constexpr bool operator()(const int&& x, const int&& y) const { return x < 
y; }
+  constexpr bool operator()(const int&& x, int& y) const { return x < y; }
+  constexpr bool operator()(int& x, const int&& y) const { return x < y; }
+  constexpr bool operator()(int& x, int& y) const { return x < y; }
+  constexpr bool operator()(std::same_as auto&& x, 
std::same_as auto&& y) const {
+return x < y;
+  }
+};
+
 constexpr bool test() {
   { // low < val < high
 int val = 2;
@@ -71,6 +81,7 @@ constexpr bool test() {
 
   constexpr const int& lvalue_proj() const { return i; }
   constexpr int prvalue_proj() const { return i; }
+  constexpr bool operator==(S const& other) const { return i == other.i; }
 };
 
 struct Comp {
@@ -82,31 +93,29 @@ constexpr bool test() {
 auto low = S{20};
 auto high = S{30};
 // Check that the value category of the projection return type is 
preserved.
-assert(::ranges::clamp(val, low, high, Comp{}, ::lvalue_proj) == 
);
-assert(::ranges::clamp(val, high, low, Comp{}, ::prvalue_proj) == 
);
+assert(std::ranges::clamp(val, low, high, Comp{}, ::lvalue_proj) == low);
+assert(std::ranges::clamp(val, high, low, Comp{}, ::prvalue_proj) == 
low);
   }
 
-  { // Check that the implementation doesn't cause double moves (which could 
result from calling the projection on
-// `value` once and then forwarding the result into the comparator).
-struct CheckDoubleMove {
-  int i;
-  bool moved = false;
-
-  constexpr explicit CheckDoubleMove(int set_i) : i(set_i) {}
-  constexpr CheckDoubleMove(const CheckDoubleMove&) = default;
-  constexpr CheckDoubleMove(CheckDoubleMove&& rhs) noexcept : i(rhs.i) {
-assert(!rhs.moved);
-rhs.moved = true;
-  }
+  { // Ensure that we respect the value category of the projection when 
calling the comparator.
+// This additional example was provided by Tim Song in 
https://github.com/microsoft/STL/issues/3970#issuecomment-1685120958.
+struct MoveProj {
+  constexpr int const&& operator()(int const& x) const { return 
std::move(x); }
 };
 
-auto val = CheckDoubleMove{20};
-auto low = CheckDoubleMove{10};
-auto high = CheckDoubleMove{30};
+static_assert(std::indirect_strict_weak_order>);
 
-auto moving_comp = [](CheckDoubleMove lhs, CheckDoubleMove rhs) { return 
lhs.i < rhs.i; };
-auto prvalue_proj = [](const CheckDoubleMove& x) -> CheckDoubleMove { 
return x; };
-assert(::ranges::clamp(val, low, high, moving_comp, prvalue_proj) == 
);
+assert(std::ranges::clamp(0, 1, 2, EnsureValueCategoryComp{}, MoveProj{}) 
== 1);
+  }
+
+  { // Make sure we don't call the projection more than three times per 
[alg.clamp], see #64717
+int counter  = 0;
+auto projection_function = [](const int value) -> int {
+  counter++;
+  return value;
+};
+assert(std::ranges::clamp(3, 

[clang] [clang][driver] Add \/../include/c++/v1 to include path on Darwin (PR #70817)

2023-10-31 Thread Louis Dionne via cfe-commits

ldionne wrote:

Is there any reason why we don't just use `Dir` all the time? What's the 
difference between those two? I think I wrote this code a few years ago and I 
can guarantee you that I simply didn't know there was a difference between 
`Dir` and `InstalledDir` (since I still don't know the difference).

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Bill Wendling via cfe-commits

https://github.com/bwendling updated 
https://github.com/llvm/llvm-project/pull/70606

>From 19dd7db8ab5f98a618c717944c96b34e604fbc30 Mon Sep 17 00:00:00 2001
From: Bill Wendling 
Date: Sun, 29 Oct 2023 14:58:04 -0700
Subject: [PATCH 01/11] [CodeGen] Revamp counted_by calculations

Break down the counted_by calculations so that they correctly handle
anonymous structs, which are specified internally as IndirectFieldDecls.
Also simplify the code to use helper methods to get the field referenced
by counted_by and the flexible array member itself, which also had some
issues with FAMs in sub-structs.
---
 clang/lib/CodeGen/CGBuiltin.cpp | 91 +++-
 clang/lib/CodeGen/CGExpr.cpp| 93 +++--
 clang/lib/CodeGen/CodeGenFunction.h | 12 +++-
 3 files changed, 134 insertions(+), 62 deletions(-)

diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index dce5ee5888c458e..acee2c1af1ab368 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)
+//
+if (const ValueDecl *CountedByFD = FindCountedByField(E)) {
+  // Find the flexible array member.
+  const RecordDecl *OuterRD =
+CountedByFD->getDeclContext()->getOuterLexicalRecordContext();
+  const ValueDecl *FAM = FindFlexibleArrayMemberField(getContext(),
+  OuterRD);
+
+  // Get the size of the flexible array member's base type.
+  const auto *ArrayTy = getContext().getAsArrayType(FAM->getType());
   unsigned Size = getContext().getTypeSize(ArrayTy->getElementType());
 
-  llvm::Value *CountField =
-  EmitAnyExprToTemp(MemberExpr::CreateImplicit(
-getContext(), const_cast(ME->getBase()),
-ME->isArrow(), FD, FD->getType(), VK_LValue,
-OK_Ordinary))
-  .getScalarVal();
+  // Find the outer struct expr (i.e. p in p->a.b.c.d).
+  Expr *CountedByExpr = BuildCountedByFieldExpr(const_cast(E),
+CountedByFD);
+
+  llvm::Value *CountedByInstr =
+EmitAnyExprToTemp(CountedByExpr).getScalarVal();
 
-  llvm::Value *Mul = Builder.CreateMul(
-  CountField, llvm::ConstantInt::get(CountField->getType(), Size / 8));
-  Mul = Builder.CreateZExtOrTrunc(Mul, ResType);
+  llvm::Constant *ArraySize =
+llvm::ConstantInt::get(CountedByInstr->getType(), Size / 8);
 
-  if (ObjectSize)
-return Builder.CreateAdd(ObjectSize, Mul);
+  llvm::Value *ObjectSize = Builder.CreateMul(CountedByInstr, ArraySize);
+  ObjectSize = Builder.CreateZExtOrTrunc(ObjectSize, ResType);
+
+  if (const auto *DRE = dyn_cast(E->IgnoreImpCasts())) {
+// The whole struct is specificed in the __bdos.
+QualType StructTy = DRE->getType()->getPointeeType();
+

[clang] [clang] Do not clear FP pragma stack when instantiating functions (PR #70646)

2023-10-31 Thread John McCall via cfe-commits

rjmccall wrote:

I see, that makes sense.  It shouldn't really need to be saved even during late 
template parsing, right?  Late template parsing is never at the top level, and 
push/pop are only allowed at the top level.

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


[clang] Fix to attribute plugins reaching an unreachable (PR #70877)

2023-10-31 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 604eff60abfce09f956c3b0b1414f8d0d04b5d47 
bb896fbc4b7303bc0ef524bbff91e95610cb11ce -- clang/lib/Sema/ParsedAttr.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/ParsedAttr.cpp b/clang/lib/Sema/ParsedAttr.cpp
index 2d6d17e74f6e..dd87832a2fc0 100644
--- a/clang/lib/Sema/ParsedAttr.cpp
+++ b/clang/lib/Sema/ParsedAttr.cpp
@@ -197,9 +197,8 @@ bool ParsedAttr::existsInTarget(const TargetInfo ) 
const {
   bool HasSpelling = K != IgnoredAttribute && K != UnknownAttribute &&
  K != NoSemaHandlerAttribute;
   return getInfo().existsInTarget(Target) &&
- (HasSpelling &&
-  getInfo().spellingExistsInTarget(Target,
-  getAttributeSpellingListIndex()));
+ (HasSpelling && getInfo().spellingExistsInTarget(
+ Target, getAttributeSpellingListIndex()));
 }
 
 bool ParsedAttr::isKnownToGCC() const { return getInfo().IsKnownToGCC; }

``




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


[clang] Fix to attribute plugins reaching an unreachable (PR #70877)

2023-10-31 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Amy Huang (amykhuang)


Changes

[0faee97](https://github.com/llvm/llvm-project/commit/0faee97a924adec76d5c7cd680c289ced51e6b5a)
 made the attribute plugin code hit an unreachable.

Bug: [70702](https://github.com/llvm/llvm-project/issues/70702)

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


1 Files Affected:

- (modified) clang/lib/Sema/ParsedAttr.cpp (+6-2) 


``diff
diff --git a/clang/lib/Sema/ParsedAttr.cpp b/clang/lib/Sema/ParsedAttr.cpp
index f59b01efe7ed8f4..2d6d17e74f6e38d 100644
--- a/clang/lib/Sema/ParsedAttr.cpp
+++ b/clang/lib/Sema/ParsedAttr.cpp
@@ -193,9 +193,13 @@ bool ParsedAttr::isTypeAttr() const { return 
getInfo().IsType; }
 bool ParsedAttr::isStmtAttr() const { return getInfo().IsStmt; }
 
 bool ParsedAttr::existsInTarget(const TargetInfo ) const {
+  Kind K = getParsedKind();
+  bool HasSpelling = K != IgnoredAttribute && K != UnknownAttribute &&
+ K != NoSemaHandlerAttribute;
   return getInfo().existsInTarget(Target) &&
- getInfo().spellingExistsInTarget(Target,
-  getAttributeSpellingListIndex());
+ (HasSpelling &&
+  getInfo().spellingExistsInTarget(Target,
+  getAttributeSpellingListIndex()));
 }
 
 bool ParsedAttr::isKnownToGCC() const { return getInfo().IsKnownToGCC; }

``




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


[clang] Fix to attribute plugins reaching an unreachable (PR #70877)

2023-10-31 Thread Amy Huang via cfe-commits

https://github.com/amykhuang created 
https://github.com/llvm/llvm-project/pull/70877

[0faee97](https://github.com/llvm/llvm-project/commit/0faee97a924adec76d5c7cd680c289ced51e6b5a)
 made the attribute plugin code hit an unreachable.

Bug: [70702](https://github.com/llvm/llvm-project/issues/70702)

>From bb896fbc4b7303bc0ef524bbff91e95610cb11ce Mon Sep 17 00:00:00 2001
From: Amy Huang 
Date: Tue, 31 Oct 2023 16:45:17 -0700
Subject: [PATCH] Fix attribute plugins

---
 clang/lib/Sema/ParsedAttr.cpp | 8 ++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/ParsedAttr.cpp b/clang/lib/Sema/ParsedAttr.cpp
index f59b01efe7ed8f4..2d6d17e74f6e38d 100644
--- a/clang/lib/Sema/ParsedAttr.cpp
+++ b/clang/lib/Sema/ParsedAttr.cpp
@@ -193,9 +193,13 @@ bool ParsedAttr::isTypeAttr() const { return 
getInfo().IsType; }
 bool ParsedAttr::isStmtAttr() const { return getInfo().IsStmt; }
 
 bool ParsedAttr::existsInTarget(const TargetInfo ) const {
+  Kind K = getParsedKind();
+  bool HasSpelling = K != IgnoredAttribute && K != UnknownAttribute &&
+ K != NoSemaHandlerAttribute;
   return getInfo().existsInTarget(Target) &&
- getInfo().spellingExistsInTarget(Target,
-  getAttributeSpellingListIndex());
+ (HasSpelling &&
+  getInfo().spellingExistsInTarget(Target,
+  getAttributeSpellingListIndex()));
 }
 
 bool ParsedAttr::isKnownToGCC() const { return getInfo().IsKnownToGCC; }

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Bill Wendling via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

bwendling wrote:

Okay, I added dc8f0df, which should take care of this issue here. Sorry about 
my confusion. PTAL.

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Bill Wendling via cfe-commits

https://github.com/bwendling updated 
https://github.com/llvm/llvm-project/pull/70606

>From 19dd7db8ab5f98a618c717944c96b34e604fbc30 Mon Sep 17 00:00:00 2001
From: Bill Wendling 
Date: Sun, 29 Oct 2023 14:58:04 -0700
Subject: [PATCH 01/10] [CodeGen] Revamp counted_by calculations

Break down the counted_by calculations so that they correctly handle
anonymous structs, which are specified internally as IndirectFieldDecls.
Also simplify the code to use helper methods to get the field referenced
by counted_by and the flexible array member itself, which also had some
issues with FAMs in sub-structs.
---
 clang/lib/CodeGen/CGBuiltin.cpp | 91 +++-
 clang/lib/CodeGen/CGExpr.cpp| 93 +++--
 clang/lib/CodeGen/CodeGenFunction.h | 12 +++-
 3 files changed, 134 insertions(+), 62 deletions(-)

diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index dce5ee5888c458e..acee2c1af1ab368 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)
+//
+if (const ValueDecl *CountedByFD = FindCountedByField(E)) {
+  // Find the flexible array member.
+  const RecordDecl *OuterRD =
+CountedByFD->getDeclContext()->getOuterLexicalRecordContext();
+  const ValueDecl *FAM = FindFlexibleArrayMemberField(getContext(),
+  OuterRD);
+
+  // Get the size of the flexible array member's base type.
+  const auto *ArrayTy = getContext().getAsArrayType(FAM->getType());
   unsigned Size = getContext().getTypeSize(ArrayTy->getElementType());
 
-  llvm::Value *CountField =
-  EmitAnyExprToTemp(MemberExpr::CreateImplicit(
-getContext(), const_cast(ME->getBase()),
-ME->isArrow(), FD, FD->getType(), VK_LValue,
-OK_Ordinary))
-  .getScalarVal();
+  // Find the outer struct expr (i.e. p in p->a.b.c.d).
+  Expr *CountedByExpr = BuildCountedByFieldExpr(const_cast(E),
+CountedByFD);
+
+  llvm::Value *CountedByInstr =
+EmitAnyExprToTemp(CountedByExpr).getScalarVal();
 
-  llvm::Value *Mul = Builder.CreateMul(
-  CountField, llvm::ConstantInt::get(CountField->getType(), Size / 8));
-  Mul = Builder.CreateZExtOrTrunc(Mul, ResType);
+  llvm::Constant *ArraySize =
+llvm::ConstantInt::get(CountedByInstr->getType(), Size / 8);
 
-  if (ObjectSize)
-return Builder.CreateAdd(ObjectSize, Mul);
+  llvm::Value *ObjectSize = Builder.CreateMul(CountedByInstr, ArraySize);
+  ObjectSize = Builder.CreateZExtOrTrunc(ObjectSize, ResType);
+
+  if (const auto *DRE = dyn_cast(E->IgnoreImpCasts())) {
+// The whole struct is specificed in the __bdos.
+QualType StructTy = DRE->getType()->getPointeeType();
+

[clang] [clang][deps] Skip writing `DIAG_PRAGMA_MAPPINGS` record (PR #70874)

2023-10-31 Thread Jan Svoboda via cfe-commits

https://github.com/jansvoboda11 created 
https://github.com/llvm/llvm-project/pull/70874

None

>From c3602bceb01aa93f801670a31bb43903d6a10d9c Mon Sep 17 00:00:00 2001
From: Jan Svoboda 
Date: Tue, 31 Oct 2023 16:35:38 -0700
Subject: [PATCH] [clang][deps] Skip writing `DIAG_PRAGMA_MAPPINGS` record

---
 clang/include/clang/Lex/HeaderSearchOptions.h | 4 
 clang/lib/Serialization/ASTWriter.cpp | 4 ++--
 .../Tooling/DependencyScanning/DependencyScanningWorker.cpp   | 2 ++
 3 files changed, 8 insertions(+), 2 deletions(-)

diff --git a/clang/include/clang/Lex/HeaderSearchOptions.h 
b/clang/include/clang/Lex/HeaderSearchOptions.h
index c7d95006bb779ad..e7204bf718b5f75 100644
--- a/clang/include/clang/Lex/HeaderSearchOptions.h
+++ b/clang/include/clang/Lex/HeaderSearchOptions.h
@@ -219,6 +219,10 @@ class HeaderSearchOptions {
 
   unsigned ModulesValidateDiagnosticOptions : 1;
 
+  /// Whether to entirely skip writing pragma diagnostic mappings.
+  /// Primarily used to speed up deserialization during dependency scanning.
+  unsigned ModulesSkipPragmaDiagnosticMappings : 1;
+
   unsigned ModulesHashContent : 1;
 
   /// Whether we should include all things that could impact the module in the
diff --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 739344b9a128dcf..011a94c5b55520d 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -1259,8 +1259,8 @@ void ASTWriter::writeUnhashedControlBlock(Preprocessor 
,
 
   Stream.EmitRecord(HEADER_SEARCH_PATHS, Record);
 
-  // Write out the diagnostic/pragma mappings.
-  WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
+  if (!HSOpts.ModulesSkipPragmaDiagnosticMappings)
+WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
 
   // Header search entry usage.
   auto HSEntryUsage = PP.getHeaderSearchInfo().computeUserEntryUsage();
diff --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
index 29df0c3a0afdb5c..45cd247148dd34d 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -252,6 +252,8 @@ class DependencyScanningAction : public tooling::ToolAction 
{
 // TODO: Implement diagnostic bucketing to reduce the impact of strict
 // context hashing.
 ScanInstance.getHeaderSearchOpts().ModulesStrictContextHash = true;
+ScanInstance.getHeaderSearchOpts().ModulesSkipPragmaDiagnosticMappings =
+true;
 
 // Avoid some checks and module map parsing when loading PCM files.
 ScanInstance.getPreprocessorOpts().ModulesCheckRelocated = false;

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


[clang] [llvm] [AIX][TOC] Add -mtocdata/-mno-tocdata options on AIX (PR #67999)

2023-10-31 Thread via cfe-commits

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Bill Wendling via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

bwendling wrote:

Note that it's okay for the `count * sizeof(fam)` to be less than the actual 
size of the fam. It's there to ensure the index doesn't go over what's expected.

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Bill Wendling via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

bwendling wrote:

@rapidsna Ah! Okay. That makes more sense, thank you. I'll see what I can do 
here.

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Yeoul Na via cfe-commits

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Yeoul Na via cfe-commits

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


[clang] [lldb] [clang][DebugInfo] Emit global variable definitions for static data members with constant initializers (PR #70639)

2023-10-31 Thread Greg Clayton via cfe-commits

clayborg wrote:

> > > Few minor issues, but looks good to me. (you metnioned somewhere an lldb 
> > > issue I think with this patch when the value is removed from the static 
> > > member declaration inside the class? If that's a problem - probably hold 
> > > off on committing this until lldb's been fixed so this doesn't regress 
> > > things? And document the dependence clearly in the commit message)
> > 
> > 
> > I saw the patch to lldb to test that we can find global variables that are 
> > `constexpr`. In upstream, we can't use find global variables, but the 
> > expression parser does work for these. We should make sure that both 
> > `FindGlobalVariables(...)` and expression parsing work for all `constexpr` 
> > globals.
> 
> Yup, the expression evaluator finds them by looking at the 
> `DW_AT_const_value` on the declaration. But since we're moving that constant 
> onto the definition with this patch, that will break that codepath.
> 
> Looking into how best to address that now

The DWARFASTParserClang.cpp will try to create the class from the DWARF for the 
class definition. You will need to find the `DW_TAG_variable` when we are 
creating the static field if there is no `DW_AT_const_value` in the 
`DW_TAG_member`. But we also need to support the `DW_AT_const_value` being in 
the `DW_TAG_member` since older DWARF will be emitted like this. Are we going 
to emit a `DW_AT_const_expr` now in the `DW_TAG_member`? If so, then we will 
know that we need to look for the DW_TAG_variable. I don't think clang emitted 
the `DW_AT_const_expr` attribute before.

The other option it to just see if the expression parser works since global 
variables are found correctly. Maybe the same will happen in this case?

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Yeoul Na via cfe-commits

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Yeoul Na via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

rapidsna wrote:

Okay, I think we are talking past to each other a little bit. That comment I 
was responding to this:

> Why wouldn't it include the FAM part if the full struct pointer is specified 
> to __bdos? 

I'm saying "the full struct size" isn't exactly `struct + fam` because fam 
doesn't always exactly start from sizeof(struct) when there is a padding in the 
struct due to the alignment. 

As we all see in the previous examples, the full struct size is 
`offsetof(struct s, fam) + sizeof(*p->array) * p->count` and align the result 
to `alignof(struct s)`.


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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

apple-fcloutier wrote:

Sorry, I don’t understand what we don’t mutually understand. In the same 
situation:

```
#include 

struct flex {
double dummy;
char c;
char fam[__counted_by(c)];
};

struct flex f = { 123.0, 2, { 1, 2 } };

int main() {
memset(, 0, sizeof(f) + f.c * sizeof(*f.fam));
}
```

We have an ASAN trap. Here are all the ways I can think of to reconcile this 
fact with the model that you propose:

* 2 is the wrong count value for a 2-element array;
* Clang is under-allocating for `f`;
* this is in-bounds and ASAN has a false positive;
* it's actually OK to write out of bounds when relying on 
`__builtin_dynamic_object_size(p, 1)`;
* the definition chosen for `__builtin_dynamic_object_size` is wrong.

The only one that makes sense to me is that the definition chosen for 
`__builtin_dynamic_object_size`. Which one is it to you? Do you see another way 
out?

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread via cfe-commits

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


[clang] [llvm] [AIX][TOC] Add -mtocdata/-mno-tocdata options on AIX (PR #67999)

2023-10-31 Thread Fangrui Song via cfe-commits


@@ -265,6 +269,63 @@ bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
   return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
 }
 
+void AIXTargetCodeGenInfo::setTargetAttributes(
+const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule ) const {
+  if (auto *GVar = dyn_cast(GV)) {

MaskRay wrote:

We prefer early-return pattern for this `if` use.

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


[lldb] [clang] [clang][DebugInfo] Emit global variable definitions for static data members with constant initializers (PR #70639)

2023-10-31 Thread Michael Buch via cfe-commits

https://github.com/Michael137 updated 
https://github.com/llvm/llvm-project/pull/70639

>From 18db082fc5008283f77cc98d9c733a47c63b7096 Mon Sep 17 00:00:00 2001
From: Michael Buch 
Date: Fri, 27 Oct 2023 16:19:47 +0100
Subject: [PATCH 1/7] [clang][DebugInfo] Emit global variable definitions for
 static data members with constant initializers
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

When an LLDB user asks for the value of a static data member, LLDB starts by
searching the Names accelerator table for the corresponding variable definition
DIE. For static data members with out-of-class definitions that works fine,
because those get represented as global variables with a location and making 
them
eligible to be added to the Names table. However, in-class definitions won’t get
indexed because we usually don't emit global variables for them. So in DWARF
we end up with a single `DW_TAG_member` that usually holds the constant 
initializer.
But we don't get a corresponding CU-level `DW_TAG_variable` like we do for
out-of-class definitions.

To make it more convenient for debuggers to get to the value of inline static 
data members,
this patch makes sure we emit definitions for static variables with constant 
initializers
the same way we do for other static variables. This also aligns Clang closer to 
GCC, which
produces CU-level definitions for inline statics and also emits these into 
`.debug_pubnames`.

The implementation keeps track of newly created static data members. Then in
`CGDebugInfo::finalize`, we emit a global `DW_TAG_variable` with a 
`DW_AT_const_value` for
any of those declarations that didn't end up with a definition in the 
`DeclCache`.

The newly emitted `DW_TAG_variable` will look as follows:
```
0x007b:   DW_TAG_structure_type
DW_AT_calling_convention(DW_CC_pass_by_value)
DW_AT_name  ("Foo")
...

0x008d: DW_TAG_member
  DW_AT_name("i")
  DW_AT_type(0x0062 "const int")
  DW_AT_external(true)
  DW_AT_declaration (true)
  DW_AT_const_value (4)

Newly added
v

0x009a:   DW_TAG_variable
DW_AT_specification (0x008d "i")
DW_AT_const_value   (4)
DW_AT_linkage_name  ("_ZN2t2IiE1iIfEE")
```
---
 clang/lib/CodeGen/CGDebugInfo.cpp | 46 +++
 clang/lib/CodeGen/CGDebugInfo.h   |  6 ++
 clang/test/CodeGenCXX/debug-info-class.cpp| 13 ++-
 .../debug-info-static-inline-member.cpp   | 79 +++
 .../TestConstStaticIntegralMember.py  |  7 +-
 5 files changed, 144 insertions(+), 7 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/debug-info-static-inline-member.cpp

diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 0aaf678bf287c6e..7529f114996d2ec 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1693,6 +1693,7 @@ CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, 
llvm::DIType *RecordTy,
   llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
   RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
   StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
+  StaticDataMemberDefinitionsToEmit.push_back(Var->getCanonicalDecl());
   return GV;
 }
 
@@ -5613,6 +5614,39 @@ void CGDebugInfo::EmitGlobalVariable(const ValueDecl 
*VD, const APValue ) {
   TemplateParameters, Align));
 }
 
+void CGDebugInfo::EmitGlobalVariable(const VarDecl *VD) {
+  assert(VD->hasInit());
+  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
+  if (VD->hasAttr())
+return;
+
+  auto  = DeclCache[VD];
+  if (GV)
+return;
+
+  auto const *InitVal = VD->evaluateValue();
+  if (!InitVal)
+return;
+
+  llvm::DIFile *Unit = nullptr;
+  llvm::DIScope *DContext = nullptr;
+  unsigned LineNo;
+  StringRef DeclName, LinkageName;
+  QualType T;
+  llvm::MDTuple *TemplateParameters = nullptr;
+  collectVarDeclProps(VD, Unit, LineNo, T, DeclName, LinkageName,
+  TemplateParameters, DContext);
+
+  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
+  llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(VD);
+  llvm::DIExpression *InitExpr = createConstantValueExpression(VD, *InitVal);
+
+  GV.reset(DBuilder.createGlobalVariableExpression(
+  TheCU, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
+  true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VD),
+  TemplateParameters, Align, Annotations));
+}
+
 void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
const VarDecl *D) {
   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
@@ -5883,6 +5917,18 @@ void CGDebugInfo::finalize() {
 

[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Bill Wendling via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

bwendling wrote:

> Sorry, I'm a bit confused. Could you clarify what you meant by "what this 
> feature does"?

Responding to:

> I meant the full struct size should include the FAM part that is specified by 
> __counted_by(7), but not more than that (e.g., >fam[13]).

So `s->fam[13]` access should fail, of course. And so we use `__bdos(p->array, 
1)` to get the size of the FAM. It can then be checked against this index. 
There is code however that passes in the struct pointer itself to `__bdos(p, 
1)`. In those cases, we also add in the struct size. The assumption is that the 
user really did mean to calculate the full size (struct + fam). Before this 
feature, that `__bdos` call would return `-1`. Now it can return something that 
allows for better array access checking.

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


[clang] [Driver][BoundsSafety] Add -fbounds-safety-experimental flag (PR #70480)

2023-10-31 Thread Fangrui Song via cfe-commits


@@ -330,6 +330,14 @@ def warn_alias_with_section : Warning<
   "as the %select{aliasee|resolver}2">,
   InGroup;
 
+let CategoryName = "Bounds Safety Issue" in {
+def err_bounds_safety_lang_not_supported : Error<
+  "bounds safety is only supported for C">;
+def warn_bounds_safety_asm_ignored : Warning<
+  "'-fbounds-safety' is ignored for assembly">,

MaskRay wrote:

Conventionally the language compatibility checking and other checking is 
performed in Driver, not in Frontend.. If you move the language check to 
Driver, the diagnostic will be natural since clang integrated assembler uses 
`ClangAs` instead of `Clang`.

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Yeoul Na via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

rapidsna wrote:

> @rapidsna That's what this feature does. This is why I'm so confused by this 
> argument. :-)

Sorry, I'm a bit confused. Could you clarify what you meant by "what this 
feature does"?

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Bill Wendling via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

bwendling wrote:

@rapidsna I misread the example. The `__counted_by` attr can exist there and 
the value of `c` is set correctly, so `__bdos(p, 1)` should return the correct 
value (18 in this case).

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Yeoul Na via cfe-commits

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Yeoul Na via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

rapidsna wrote:

> As for @apple-fcloutier 's example, The compiler would complain that 
> `__counted_by(c)` is applied to a non-flexible array member. If we want that 
> capability, we'll have to add it in at a later date.

I think we might have to because some structs are both statically and 
dynamically initialized. But the point the example was trying to make was to 
show how struct sizes with trailing arrays are normally calculated.

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Bill Wendling via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

bwendling wrote:

@apple-fcloutier Ah, I didn't see the square brackets. So this only works if 
the `counted_by` attribute is specified on the fam and set to the correct 
number. In the documentation, it's explicitly stated that it's up to the 
programmer to ensure that the count is correct if the size somehow changes.

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Bill Wendling via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

bwendling wrote:

@rapidsna That's what this feature does. This is why I'm so confused by this 
argument. :-)

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Yeoul Na via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

rapidsna wrote:

> Why wouldn't it include the FAM part if the full struct pointer is specified 
> to __bdos? This usage is something that shows up in the Linux kernel (a 
> motivating factor for this feature).

I meant the full struct size should include the FAM part that is specified by 
`__counted_by(7)`, but not more than that (e.g., `>fam[13]`).

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


[flang] [compiler-rt] [clang] [lldb] [llvm] [openmp] [libcxx] [clang-tools-extra] [OpenMP] Add memory diff dump for kernel record-replay (PR #70667)

2023-10-31 Thread via cfe-commits


@@ -274,7 +317,7 @@ struct RecordReplayTy {
   void saveKernelOutputInfo(const char *Name) {
 SmallString<128> OutputFilename = {
 Name, (isRecording() ? ".original.output" : ".replay.output")};

nmustakin wrote:

The motivation was to save the disk usage from the memory dumps. So having the 
diff dump along with entire dump defeats the purpose. The verification compares 
the `.original.output` to the `.replay.output` anyway. Since both are now 
replaced by diffs, the verification from the `llvm-omp-kernel-replay` tool just 
compares the diffs now. 

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

apple-fcloutier wrote:

The structure is defined with a flexible array member:

```c
struct flex {
double dummy;
char c;
char fam[/* __counted_by(c) */];
};
```

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Bill Wendling via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

bwendling wrote:

@apple-fcloutier again, why? I *still* don't see the reason why this would be 
confusing or cause erroneous checks.

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Yeoul Na via cfe-commits

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Bill Wendling via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

bwendling wrote:

Why wouldn't it include the FAM part if the full struct pointer is specified to 
__bdos? This usage is something that shows up in the Linux kernel (a motivating 
factor for this feature).

As for @apple-fcloutier 's example, The compiler would complain that 
`__counted_by(c)` is applied to a non-flexible array member. If we want that 
capability, we'll have to add it in at a later date.

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

apple-fcloutier wrote:

I cannot agree that `sizeof(*p) + p->count * sizeof(*p->array)` is the 
reasonable definition of size when ASAN can diagnose it as out of bounds.

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


[flang] [compiler-rt] [clang] [lldb] [llvm] [openmp] [libcxx] [clang-tools-extra] [OpenMP] Add memory diff dump for kernel record-replay (PR #70667)

2023-10-31 Thread via cfe-commits


@@ -274,7 +317,7 @@ struct RecordReplayTy {
   void saveKernelOutputInfo(const char *Name) {
 SmallString<128> OutputFilename = {
 Name, (isRecording() ? ".original.output" : ".replay.output")};
-dumpDeviceMemory(OutputFilename);
+dumpDeviceMemory(OutputFilename, /*saveDiff*/ true);

nmustakin wrote:

saveDiff isn't always true. For pre-record memory dump, saveDiff is false (on 
line 302)

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Yeoul Na via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

rapidsna wrote:

> __builtin_dynamic_object_size only adds the full struct size to the 
> calculation when the full struct pointer is specified: 
> __builtin_dynamic_object_size(p, 1) == 23. __builtin_dynamic_object_size only 
> adds the full struct size to the calculation when the full struct pointer is 
> specified: __builtin_dynamic_object_size(p, 1) == 23. When it's specified on 
> the fam itself (__builtin_dynamic_object_size(*p->array, 1)) it returns only 
> the size of the fam (7 in this example). This seems entirely reasonable to me 
> and fits the definition of __builtin_dynamic_object_size:

I know, but the question is why "the full struct size" should include the part 
of `>fam[13]`? It's not even conformed to how the statically initialized 
struct size is determined in C (like @apple-fcloutier 's example also 
indicates).

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Bill Wendling via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

bwendling wrote:

`__builtin_dynamic_object_size` only adds the full struct size to the 
calculation when the full struct pointer is specified: 
`__builtin_dynamic_object_size(p, 1) == 23`. When it's specified on the fam 
itself (`__builtin_dynamic_object_size(*p->array, 1)`) it returns only the size 
of the fam (7 in this example). This seems entirely reasonable to me and fits 
the definition of `__builtin_dynamic_object_size`:

> is similar to __builtin_object_size in that it returns a number of bytes from 
> ptr to the end of the object ptr pointer points to, except that the size 
> returned may not be a constant. 


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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread via cfe-commits

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread via cfe-commits

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


[openmp] [mlir] [llvm] [clang] [OpenMP] Introduce the KernelLaunchEnvironment as implicit argument (PR #70401)

2023-10-31 Thread Joseph Huber via cfe-commits

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

LG

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread via cfe-commits

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread via cfe-commits

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

apple-fcloutier wrote:

I’ve seen `sizeof(*p) + p->count * sizeof(*p->array)` often as the argument to 
`malloc`, which isn’t terribly problematic because it over-allocates a little 
bit in the worst case. However, it _would_ be a bug to use it for virtually 
anything else, such as the size of `memcpy` or `memset`, because it will cause 
an out-of-bounds access if the object hasn’t been allocated with `malloc`. Both 
clang and gcc allow structs with flexible array members to be allocated with 
static storage duration. See this ASAN failure: https://godbolt.org/z/Gxbv379qE

As Yeoul said, the correct end address is calculated with 
`>array[fam->count]`. Ahead of time, `offset` can be used to compute the 
required size of a structure with a given number of flexible elements: 
`offsetof(struct flex, .array[count])`.

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread via cfe-commits

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


[clang] [Clang] Add __datasizeof (PR #67805)

2023-10-31 Thread via cfe-commits

https://github.com/philnik777 updated 
https://github.com/llvm/llvm-project/pull/67805

>From 8010f6178df82305b5790610f0114ddfb3c0a5f8 Mon Sep 17 00:00:00 2001
From: Nikolas Klauser 
Date: Fri, 29 Sep 2023 15:45:56 +0200
Subject: [PATCH] [Clang] Add __datasizeof

---
 clang/docs/LanguageExtensions.rst| 12 ++
 clang/docs/ReleaseNotes.rst  |  2 +
 clang/include/clang/Basic/Features.def   |  1 +
 clang/include/clang/Basic/TokenKinds.def |  1 +
 clang/lib/AST/ExprConstant.cpp   | 20 +++--
 clang/lib/AST/ItaniumMangle.cpp  |  9 
 clang/lib/CodeGen/CGExprScalar.cpp   |  5 ++-
 clang/lib/Parse/ParseExpr.cpp| 42 ++-
 clang/lib/Sema/SemaExpr.cpp  |  5 ++-
 clang/test/CodeGenCXX/datasizeof.cpp | 19 +
 clang/test/SemaCXX/datasizeof.cpp| 53 
 11 files changed, 150 insertions(+), 19 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/datasizeof.cpp
 create mode 100644 clang/test/SemaCXX/datasizeof.cpp

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 30e288f986782fd..294210c6ac140a9 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -424,6 +424,18 @@ Builtin Macros
   "UTF-16" or "UTF-32" (but may change in the future if the
   ``-fwide-exec-charset="Encoding-Name"`` option is implemented.)
 
+Implementation-defined keywords
+===
+
+__datasizeof
+
+
+``__datasizeof`` behaves like ``sizeof``, except that it returns the size of 
the
+type ignoring tail padding.
+
+..
+  FIXME: This should list all the keyword extensions
+
 .. _langext-vectors:
 
 Vectors and Extended Vectors
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8eca67677f1d82c..7bce077d093462f 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -217,6 +217,8 @@ Non-comprehensive list of changes in this release
   (e.g., ``uint16x8_t``), this returns the constant number of elements at 
compile-time.
   For scalable vectors, e.g., SVE or RISC-V V, the number of elements is not 
known at compile-time and is
   determined at runtime.
+- The ``__datasizeof`` keyword has been added. It is similar to ``sizeof``
+  except that it returns the size of a type ignoring tail padding.
 
 New Compiler Flags
 --
diff --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index cf626d0120cc7c7..4a4503ac2ec375d 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -277,6 +277,7 @@ EXTENSION(gnu_asm_goto_with_outputs_full, LangOpts.GNUAsm)
 EXTENSION(matrix_types, LangOpts.MatrixTypes)
 EXTENSION(matrix_types_scalar_division, true)
 EXTENSION(cxx_attributes_on_using_declarations, LangOpts.CPlusPlus11)
+EXTENSION(datasizeof, LangOpts.CPlusPlus)
 
 FEATURE(builtin_headers_in_system_modules, 
LangOpts.BuiltinHeadersInSystemModules)
 FEATURE(cxx_abi_relative_vtable, LangOpts.CPlusPlus && 
LangOpts.RelativeCXXABIVTables)
diff --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index 3ce317d318f9bb6..6cb4b3f250c4032 100644
--- a/clang/include/clang/Basic/TokenKinds.def
+++ b/clang/include/clang/Basic/TokenKinds.def
@@ -310,6 +310,7 @@ KEYWORD(return  , KEYALL)
 KEYWORD(short   , KEYALL)
 KEYWORD(signed  , KEYALL)
 UNARY_EXPR_OR_TYPE_TRAIT(sizeof, SizeOf, KEYALL)
+UNARY_EXPR_OR_TYPE_TRAIT(__datasizeof, DataSizeOf, KEYCXX)
 KEYWORD(static  , KEYALL)
 KEYWORD(struct  , KEYALL)
 KEYWORD(switch  , KEYALL)
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 5947805f9576ff8..0fbe6fd778075df 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -3231,9 +3231,14 @@ static bool HandleLValueIndirectMember(EvalInfo , 
const Expr *E,
   return true;
 }
 
+enum class SizeOfType {
+  SizeOf,
+  DataSizeOf,
+};
+
 /// Get the size of the given type in char units.
-static bool HandleSizeof(EvalInfo , SourceLocation Loc,
- QualType Type, CharUnits ) {
+static bool HandleSizeof(EvalInfo , SourceLocation Loc, QualType Type,
+ CharUnits , SizeOfType SOT = SizeOfType::SizeOf) 
{
   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
   // extension.
   if (Type->isVoidType() || Type->isFunctionType()) {
@@ -3253,7 +3258,10 @@ static bool HandleSizeof(EvalInfo , SourceLocation 
Loc,
 return false;
   }
 
-  Size = Info.Ctx.getTypeSizeInChars(Type);
+  if (SOT == SizeOfType::SizeOf)
+Size = Info.Ctx.getTypeSizeInChars(Type);
+  else
+Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
   return true;
 }
 
@@ -13590,6 +13598,7 @@ bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
   return Success(1, E);

[clang] [Clang] Add codegen option to add passbuilder callback functions (PR #70171)

2023-10-31 Thread William Moses via cfe-commits

wsmoses wrote:

@efriedma-quic I've removed the non-options stuff, please review it at your 
convenience.

Let me see if I can make the other stuff work in a different way.

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


[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

2023-10-31 Thread Yeoul Na via cfe-commits


@@ -859,53 +859,60 @@ CodeGenFunction::emitBuiltinObjectSize(const Expr *E, 
unsigned Type,
   }
 
   if (IsDynamic) {
-LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
-getLangOpts().getStrictFlexArraysLevel();
-const Expr *Base = E->IgnoreParenImpCasts();
-
-if (FieldDecl *FD = FindCountedByField(Base, StrictFlexArraysLevel)) {
-  const auto *ME = dyn_cast(Base);
-  llvm::Value *ObjectSize = nullptr;
-
-  if (!ME) {
-const auto *DRE = dyn_cast(Base);
-ValueDecl *VD = nullptr;
-
-ObjectSize = ConstantInt::get(
-ResType,
-getContext().getTypeSize(DRE->getType()->getPointeeType()) / 8,
-true);
-
-if (auto *RD = DRE->getType()->getPointeeType()->getAsRecordDecl())
-  VD = RD->getLastField();
-
-Expr *ICE = ImplicitCastExpr::Create(
-getContext(), DRE->getType(), CK_LValueToRValue,
-const_cast(cast(DRE)), nullptr, VK_PRValue,
-FPOptionsOverride());
-ME = MemberExpr::CreateImplicit(getContext(), ICE, true, VD,
-VD->getType(), VK_LValue, OK_Ordinary);
-  }
-
-  // At this point, we know that \p ME is a flexible array member.
-  const auto *ArrayTy = getContext().getAsArrayType(ME->getType());
+// The code generated here calculates the size of a struct with a flexible
+// array member that uses the counted_by attribute. There are two instances
+// we handle:
+//
+//   struct s {
+// unsigned long flags;
+// int count;
+// int array[] __attribute__((counted_by(count)));
+//   }
+//
+//   1) bdos of the flexible array itself:
+//
+// __builtin_dynamic_object_size(p->array, 1) ==
+// p->count * sizeof(*p->array)
+//
+//   2) bdos of the whole struct, including the flexible array:
+//
+// __builtin_dynamic_object_size(p, 1) ==
+//sizeof(*p) + p->count * sizeof(*p->array)

rapidsna wrote:

> Note: sizeof(*p) + p->count * sizeof(*p->array) returning 23 is exactly what 
> I want here. :-) At least with regard to __builtin_dynamic_object_size().

hmm, I see. So, that's not what `-fbounds-safety` is meant to work: 
`__counted_by` on fam in -fbounds-safety is to exactly add `count` trailing 
elements from `>fam[0]`. So I think this semantic difference between two 
modes going to be a problem (e.g., accessing the offset 22 of the object, for 
example, will be considered OOB in -fbounds-safety).

Is there a reason you want it to be this way? I know people tends to do 
`malloc(sizeof(struct s) + p->count * sizeof(int));` to allocate an object with 
fam. But people also use `offsetof` and in such cases, 
`__builtin_dynamic_object_size` can be bigger than what it should be.

```
struct flex {
  double dummy;
  char c;
  char fam [__counted_by(7)];
};
```

 If `__builtin_dynamic_object_size` does `sizeof(*p) + p->count * 
sizeof(*p->array)`, it's like effectively considering `>fam[13]` as part of 
the object.

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


[clang] Correctly link and optimize device libraries with -mlink-builtin-bitcode (PR #69371)

2023-10-31 Thread Jacob Lambert via cfe-commits

https://github.com/lamb-j updated 
https://github.com/llvm/llvm-project/pull/69371

>From 25302c315360c166f34ab9acde2561dc7865b3bb Mon Sep 17 00:00:00 2001
From: Jacob Lambert 
Date: Tue, 17 Oct 2023 12:01:15 -0700
Subject: [PATCH 1/3] [NFC] Refactor BackendConsumer class definition into new
 header

Previously the BackendConsumer class was defined in CodeGenAction.cpp.
In order to use this class and its member functions in other files
for upcoming changes, we first need to refactor the class definition
into a separate header
---
 clang/lib/CodeGen/BackendConsumer.h | 166 +++
 clang/lib/CodeGen/CodeGenAction.cpp | 643 
 2 files changed, 448 insertions(+), 361 deletions(-)
 create mode 100644 clang/lib/CodeGen/BackendConsumer.h

diff --git a/clang/lib/CodeGen/BackendConsumer.h 
b/clang/lib/CodeGen/BackendConsumer.h
new file mode 100644
index 000..2a4f70d5668ed6b
--- /dev/null
+++ b/clang/lib/CodeGen/BackendConsumer.h
@@ -0,0 +1,166 @@
+//===--- BackendConsumer.h - LLVM BackendConsumer Header File 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_LIB_CODEGEN_BACKENDCONSUMER_H
+#define LLVM_CLANG_LIB_CODEGEN_BACKENDCONSUMER_H
+
+#include "clang/CodeGen/BackendUtil.h"
+#include "clang/CodeGen/CodeGenAction.h"
+
+#include "llvm/IR/DiagnosticInfo.h"
+#include "llvm/Support/Timer.h"
+
+namespace llvm {
+  class DiagnosticInfoDontCall;
+}
+
+namespace clang {
+class ASTContext;
+class CodeGenAction;
+class CoverageSourceInfo;
+
+class BackendConsumer : public ASTConsumer {
+  using LinkModule = CodeGenAction::LinkModule;
+
+  virtual void anchor();
+  DiagnosticsEngine 
+  BackendAction Action;
+  const HeaderSearchOptions 
+  const CodeGenOptions 
+  const TargetOptions 
+  const LangOptions 
+  std::unique_ptr AsmOutStream;
+  ASTContext *Context;
+  IntrusiveRefCntPtr FS;
+
+  llvm::Timer LLVMIRGeneration;
+  unsigned LLVMIRGenerationRefCount;
+
+  /// True if we've finished generating IR. This prevents us from generating
+  /// additional LLVM IR after emitting output in HandleTranslationUnit. This
+  /// can happen when Clang plugins trigger additional AST deserialization.
+  bool IRGenFinished = false;
+
+  bool TimerIsEnabled = false;
+
+  std::unique_ptr Gen;
+
+  SmallVector LinkModules;
+
+  // A map from mangled names to their function's source location, used for
+  // backend diagnostics as the Clang AST may be unavailable. We actually use
+  // the mangled name's hash as the key because mangled names can be very
+  // long and take up lots of space. Using a hash can cause name collision,
+  // but that is rare and the consequences are pointing to a wrong source
+  // location which is not severe. This is a vector instead of an actual map
+  // because we optimize for time building this map rather than time
+  // retrieving an entry, as backend diagnostics are uncommon.
+  std::vector>
+ManglingFullSourceLocs;
+
+
+  // This is here so that the diagnostic printer knows the module a diagnostic
+  // refers to.
+  llvm::Module *CurLinkModule = nullptr;
+
+public:
+  BackendConsumer(BackendAction Action, DiagnosticsEngine ,
+  IntrusiveRefCntPtr VFS,
+  const HeaderSearchOptions ,
+  const PreprocessorOptions ,
+  const CodeGenOptions ,
+  const TargetOptions ,
+  const LangOptions , const std::string ,
+  SmallVector LinkModules,
+  std::unique_ptr OS, llvm::LLVMContext ,
+  CoverageSourceInfo *CoverageInfo = nullptr);
+
+  // This constructor is used in installing an empty BackendConsumer
+  // to use the clang diagnostic handler for IR input files. It avoids
+  // initializing the OS field.
+  BackendConsumer(BackendAction Action, DiagnosticsEngine ,
+  IntrusiveRefCntPtr VFS,
+  const HeaderSearchOptions ,
+  const PreprocessorOptions ,
+  const CodeGenOptions ,
+  const TargetOptions ,
+  const LangOptions , llvm::Module *Module,
+  SmallVector LinkModules, llvm::LLVMContext ,
+  CoverageSourceInfo *CoverageInfo = nullptr);
+
+  llvm::Module *getModule() const;
+  std::unique_ptr takeModule();
+
+  CodeGenerator *getCodeGenerator();
+
+  void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override;
+  void Initialize(ASTContext ) override;
+  bool HandleTopLevelDecl(DeclGroupRef D) override;
+  void HandleInlineFunctionDefinition(FunctionDecl *D) override;
+  void HandleInterestingDecl(DeclGroupRef D) override;
+  void HandleTranslationUnit(ASTContext ) override;
+  void 

[clang] [Clang] Add codegen option to add passbuilder callback functions (PR #70171)

2023-10-31 Thread William Moses via cfe-commits

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


  1   2   3   4   5   6   >