[PATCH] D112921: [clang] Enable sized deallocation by default in C++14 onwards

2023-08-29 Thread Wang Pengcheng via Phabricator via cfe-commits
wangpc updated this revision to Diff 554197.
wangpc marked 2 inline comments as done.
wangpc added a comment.

Rebase.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D112921/new/

https://reviews.llvm.org/D112921

Files:
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp
  clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/SizedDeallocation.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Darwin.cpp
  clang/lib/Driver/ToolChains/Darwin.h
  clang/lib/Driver/ToolChains/ZOS.cpp
  clang/test/AST/ast-dump-expr-json.cpp
  clang/test/AST/ast-dump-expr.cpp
  clang/test/AST/ast-dump-stmt-json.cpp
  clang/test/Analysis/cxxnewexpr-callback.cpp
  
clang/test/CXX/basic/basic.stc/basic.stc.dynamic/basic.stc.dynamic.deallocation/p2.cpp
  clang/test/CXX/expr/expr.unary/expr.new/p14.cpp
  clang/test/CodeGenCXX/cxx1y-sized-deallocation.cpp
  clang/test/CodeGenCXX/cxx1z-aligned-allocation.cpp
  clang/test/CodeGenCXX/cxx2a-destroying-delete.cpp
  clang/test/CodeGenCXX/delete-two-arg.cpp
  clang/test/CodeGenCXX/delete.cpp
  clang/test/CodeGenCXX/dllimport.cpp
  clang/test/CodeGenCXX/new.cpp
  clang/test/CodeGenCoroutines/coro-aligned-alloc-2.cpp
  clang/test/CodeGenCoroutines/coro-aligned-alloc.cpp
  clang/test/CodeGenCoroutines/coro-alloc.cpp
  clang/test/CodeGenCoroutines/coro-cleanup.cpp
  clang/test/CodeGenCoroutines/coro-dealloc.cpp
  clang/test/CodeGenCoroutines/coro-gro.cpp
  clang/test/CodeGenCoroutines/pr56919.cpp
  clang/test/Lexer/cxx-features.cpp
  clang/test/PCH/cxx1z-aligned-alloc.cpp
  clang/test/SemaCXX/MicrosoftExtensions.cpp
  clang/test/SemaCXX/builtin-operator-new-delete.cpp
  clang/test/SemaCXX/cxx1y-sized-deallocation.cpp
  clang/test/SemaCXX/unavailable_aligned_allocation.cpp
  clang/unittests/StaticAnalyzer/CallEventTest.cpp
  clang/www/cxx_status.html
  libcxx/test/libcxx/language.support/support.dynamic/libcpp_deallocate.sh.cpp
  
libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.array/sized_delete_array14.pass.cpp
  
libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.single/sized_delete14.pass.cpp

Index: libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.single/sized_delete14.pass.cpp
===
--- libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.single/sized_delete14.pass.cpp
+++ libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.single/sized_delete14.pass.cpp
@@ -8,11 +8,13 @@
 
 // test sized operator delete replacement.
 
+// TODO(mordante) fix this test after updating clang in Docker
+// UNSUPPORTED: clang-15, clang-16, clang-17, clang-18
 // UNSUPPORTED: sanitizer-new-delete, c++03, c++11
+// XFAIL: apple-clang
 
-// NOTE: Clang does not enable sized-deallocation in C++14 and beyond by
-// default. It is only enabled when -fsized-deallocation is given.
-// XFAIL: clang, apple-clang
+// Sized deallocation was added in macOS 10.12 and aligned OSes.
+// XFAIL: use_system_cxx_lib && target={{.+}}-apple-macosx10.{{9|10|11}}
 
 #include 
 #include 
Index: libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.array/sized_delete_array14.pass.cpp
===
--- libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.array/sized_delete_array14.pass.cpp
+++ libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.array/sized_delete_array14.pass.cpp
@@ -8,11 +8,13 @@
 
 // test sized operator delete[] replacement.
 
+// TODO(mordante) fix this test after updating clang in Docker
+// UNSUPPORTED: clang-15, clang-16, clang-17, clang-18
 // UNSUPPORTED: sanitizer-new-delete, c++03, c++11
+// XFAIL: apple-clang
 
-// NOTE: Clang does not enable sized-deallocation in C++14 and beyond by
-// default. It is only enabled when -fsized-deallocation is given.
-// XFAIL: clang, apple-clang
+// Sized deallocation was added in macOS 10.12 and aligned OSes.
+// XFAIL: use_system_cxx_lib && target={{.+}}-apple-macosx10.{{9|10|11}}
 
 #include 
 #include 
Index: libcxx/test/libcxx/language.support/support.dynamic/libcpp_deallocate.sh.cpp
===
--- libcxx/test/libcxx/language.support/support.dynamic/libcpp_deallocate.sh.cpp
+++ libcxx/test/libcxx/language.support/support.dynamic/libcpp_deallocate.sh.cpp
@@ -25,6 +25,9 @@
 // GCC doesn't support the aligned-allocation flags.
 // XFAIL: gcc
 
+// TODO(mordante) fix this test after updating clang in Docker
+// UNSUPPORTED: clang-15, clang-16, clang-17, clang-18
+
 // RUN: %{build} -faligned-allocation -fsized-deallocation
 // RUN: %{run}
 // RUN: %{build} -faligned-allocation -fno-sized-deallocation -DNO_SIZE
Index: clang/www/cxx_status.html
==

[clang] e5d8160 - Revert "[OpenMP] Allow exceptions in target regions when offloading to GPUs"

2023-08-29 Thread via cfe-commits

Author: antonrydahl
Date: 2023-08-29T00:09:21-07:00
New Revision: e5d8160040f69d9084e89260eec85f98038611b5

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

LOG: Revert "[OpenMP] Allow exceptions in target regions when offloading to 
GPUs"

Reverting commit 0cfc2dba93b172802b580713a492ea14148a0218 because it broke
build-bots that do not support nvptx64 targets.

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticCommonKinds.td
clang/include/clang/Basic/DiagnosticGroups.td
clang/lib/CodeGen/CGException.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaStmt.cpp
clang/test/OpenMP/nvptx_target_exceptions_messages.cpp

Removed: 
clang/test/OpenMP/amdgpu_exceptions.cpp
clang/test/OpenMP/amdgpu_throw.cpp
clang/test/OpenMP/amdgpu_throw_trap.cpp
clang/test/OpenMP/amdgpu_try_catch.cpp
clang/test/OpenMP/nvptx_exceptions.cpp
clang/test/OpenMP/nvptx_throw.cpp
clang/test/OpenMP/nvptx_throw_trap.cpp
clang/test/OpenMP/nvptx_try_catch.cpp
clang/test/OpenMP/x86_target_exceptions.cpp
clang/test/OpenMP/x86_target_throw.cpp
clang/test/OpenMP/x86_target_try_catch.cpp



diff  --git a/clang/include/clang/Basic/DiagnosticCommonKinds.td 
b/clang/include/clang/Basic/DiagnosticCommonKinds.td
index f2df283c74829f..cd72e254ea3b1a 100644
--- a/clang/include/clang/Basic/DiagnosticCommonKinds.td
+++ b/clang/include/clang/Basic/DiagnosticCommonKinds.td
@@ -425,13 +425,4 @@ def err_opencl_extension_and_feature_
diff ers : Error<
   "options %0 and %1 are set to 
diff erent values">;
 def err_opencl_feature_requires : Error<
   "feature %0 requires support of %1 feature">;
-
-def warn_throw_not_valid_on_target : Warning<
-  "target '%0' does not support exception handling;"
-  " 'throw' is assumed to be never reached">,
-  InGroup;
-def warn_try_not_valid_on_target : Warning<
-  "target '%0' does not support exception handling;"
-  " 'catch' block is ignored">,
-  InGroup;
 }

diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 00c458fb23e73e..d1aa51393ef357 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -1292,10 +1292,9 @@ def OpenMPTarget : DiagGroup<"openmp-target", 
[OpenMPMapping]>;
 def OpenMPPre51Compat : DiagGroup<"pre-openmp-51-compat">;
 def OpenMP51Ext : DiagGroup<"openmp-51-extensions">;
 def OpenMPExtensions : DiagGroup<"openmp-extensions">;
-def OpenMPTargetException : DiagGroup<"openmp-target-exception">;
 def OpenMP : DiagGroup<"openmp", [
 SourceUsesOpenMP, OpenMPClauses, OpenMPLoopForm, OpenMPTarget,
-OpenMPMapping, OpenMP51Ext, OpenMPExtensions, OpenMPTargetException
+OpenMPMapping, OpenMP51Ext, OpenMPExtensions
   ]>;
 
 // Backend warnings.

diff  --git a/clang/lib/CodeGen/CGException.cpp 
b/clang/lib/CodeGen/CGException.cpp
index 3996f2948349cb..9cb7d4c7731deb 100644
--- a/clang/lib/CodeGen/CGException.cpp
+++ b/clang/lib/CodeGen/CGException.cpp
@@ -440,15 +440,6 @@ llvm::Value *CodeGenFunction::getSelectorFromSlot() {
 
 void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
bool KeepInsertionPoint) {
-  // If the exception is being emitted in an OpenMP target region,
-  // and the target is a GPU, we do not support exception handling.
-  // Therefore, we emit a trap which will abort the program, and
-  // prompt a warning indicating that a trap will be emitted.
-  const llvm::Triple &T = Target.getTriple();
-  if (CGM.getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN())) 
{
-EmitTrapCall(llvm::Intrinsic::trap);
-return;
-  }
   if (const Expr *SubExpr = E->getSubExpr()) {
 QualType ThrowType = SubExpr->getType();
 if (ThrowType->isObjCObjectPointerType()) {
@@ -618,16 +609,9 @@ void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
 }
 
 void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
-  const llvm::Triple &T = Target.getTriple();
-  // If we encounter a try statement on in an OpenMP target region offloaded to
-  // a GPU, we treat it as a basic block.
-  const bool IsTargetDevice =
-  (CGM.getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || 
T.isAMDGCN()));
-  if (!IsTargetDevice)
-EnterCXXTryStmt(S);
+  EnterCXXTryStmt(S);
   EmitStmt(S.getTryBlock());
-  if (!IsTargetDevice)
-ExitCXXTryStmt(S);
+  ExitCXXTryStmt(S);
 }
 
 void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {

diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 472fbdbdb5d0e6..a6e0a8abf81b9a 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -864,21 +864,13 @@ Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr 
*Ex) 

[PATCH] D158977: [clang][dataflow] Don't associate prvalue expressions with storage locations.

2023-08-29 Thread Martin Böhme via Phabricator via cfe-commits
mboehme added a comment.

In D158977#4623402 , @xazax.hun wrote:

> Thanks! Sometimes I am wondering whether we actually need a full map for 
> PRValues. E.g., once we processed a `MaterializeTemporaryExpr`, we now have a 
> location for the value, and it feels like we represent the same thing twice, 
> once in `ExprToLoc + LocToVal` and once in `ExprToVal`. It is probably not 
> too bad and might be extra work to clean this up.

Yes, I think it's probably not worth it. (And note that the `Expr`s in question 
are different: In the `ExprToVal`, we map the prvalue expression to a value, 
whereas in `ExprToLoc`, we map the `MaterializeTemporaryExpr` to a location.)

I'd say this is just one example of the more general case when a prvalue is 
consumed by some other expression. For example, when two prvalue integer 
operands are consumed by a `+` `BinaryOperator`, we could also say that the 
entries in `ExprToVal` for the operands are now superfluous and could be 
removed -- but we still keep them around. They might be superfluous, but there 
aren't typically enough of them to hurt performance (I think?). And they may be 
useful for debugging.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158977/new/

https://reviews.llvm.org/D158977

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


[PATCH] D159024: [Parser] Parse string literal arguments of 'availability', 'external_source_symbol' and 'uuid' attributes as unevaluated

2023-08-29 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

Thanks a lot for working on this.
LGTM, except for the failing test


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159024/new/

https://reviews.llvm.org/D159024

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


[clang] 330d5bc - [clang][dataflow] Don't associate prvalue expressions with storage locations.

2023-08-29 Thread Martin Braenne via cfe-commits

Author: Martin Braenne
Date: 2023-08-29T07:28:46Z
New Revision: 330d5bcbf61043b5ca2bf5a65bd4488718c85e6e

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

LOG: [clang][dataflow] Don't associate prvalue expressions with storage 
locations.

Instead, map prvalue expressions directly to values in a newly introduced map 
`Environment::ExprToVal`.

This change introduces an additional member variable in `Environment` but is an 
overall win:

- It is more conceptually correctly, since prvalues don't have storage
  locations.

- It eliminates complexity from
  `Environment::setValue(const Expr &E, Value &Val)`.

- It reduces the amount of data stored in `Environment`: A prvalue now has a
  single entry in `ExprToVal` instead of one in `ExprToLoc` and one in
  `LocToVal`.

- Not allocating `StorageLocation`s for prvalues additionally reduces memory
  usage.

This patch is the last step in the migration to strict handling of value 
categories (see https://discourse.llvm.org/t/70086 for details). The changes 
here are almost entirely internal to `Environment`.

The only externally observable change is that when associating a `RecordValue` 
with the location returned by `Environment::getResultObjectLocation()` for a 
given expression, callers additionally need to associate the `RecordValue` with 
the expression themselves.

Reviewed By: xazax.hun

Differential Revision: https://reviews.llvm.org/D158977

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
clang/lib/Analysis/FlowSensitive/Transfer.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index f812c01d42040b..95514d940c3f6a 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -651,14 +651,17 @@ class Environment {
   // function being analyzed is only a function and not a method.
   RecordStorageLocation *ThisPointeeLoc = nullptr;
 
-  // Maps from program declarations and statements to storage locations that 
are
+  // Maps from declarations and glvalue expression to storage locations that 
are
   // assigned to them. Unlike the maps in `DataflowAnalysisContext`, these
   // include only storage locations that are in scope for a particular basic
   // block.
   llvm::DenseMap DeclToLoc;
   llvm::DenseMap ExprToLoc;
+  // Maps from prvalue expressions and storage locations to the values that
+  // are assigned to them.
   // We preserve insertion order so that join/widen process values in
   // deterministic sequence. This in turn produces deterministic SAT formulas.
+  llvm::MapVector ExprToVal;
   llvm::MapVector LocToVal;
 
   Atom FlowConditionToken;

diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index f6c8f7d2d395ec..f15ea52d6b4699 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -171,6 +171,105 @@ static Value &widenDistinctValues(QualType Type, Value 
&Prev,
   return Current;
 }
 
+// Returns whether the values in `Map1` and `Map2` compare equal for those
+// keys that `Map1` and `Map2` have in common.
+template 
+bool compareKeyToValueMaps(const llvm::MapVector &Map1,
+   const llvm::MapVector &Map2,
+   const Environment &Env1, const Environment &Env2,
+   Environment::ValueModel &Model) {
+  for (auto &Entry : Map1) {
+Key K = Entry.first;
+assert(K != nullptr);
+
+Value *Val = Entry.second;
+assert(Val != nullptr);
+
+auto It = Map2.find(K);
+if (It == Map2.end())
+  continue;
+assert(It->second != nullptr);
+
+if (!areEquivalentValues(*Val, *It->second) &&
+!compareDistinctValues(K->getType(), *Val, Env1, *It->second, Env2,
+   Model))
+  return false;
+  }
+
+  return true;
+}
+
+// Perform a join on either `LocToVal` or `ExprToVal`. `Key` must be either
+// `const StorageLocation *` or `const Expr *`.
+template 
+llvm::MapVector
+joinKeyToValueMap(const llvm::MapVector &Map1,
+  const llvm::MapVector &Map2,
+  const Environment &Env1, const Environment &Env2,
+  Environment &JoinedEnv, Environment::ValueModel &Model) {
+  llvm::MapVector MergedMap;
+  for (auto &Entry : Map1) {
+Key K = Entry.first;
+assert(K != nullptr);
+
+Value *Val = Entry.second;
+asse

[PATCH] D158977: [clang][dataflow] Don't associate prvalue expressions with storage locations.

2023-08-29 Thread Martin Böhme via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG330d5bcbf610: [clang][dataflow] Don't associate prvalue 
expressions with storage locations. (authored by mboehme).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158977/new/

https://reviews.llvm.org/D158977

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp

Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -488,6 +488,7 @@
 // we've got a record type.
 if (S->getType()->isRecordType()) {
   auto &InitialVal = *cast(Env.createValue(S->getType()));
+  Env.setValue(*S, InitialVal);
   copyRecord(InitialVal.getLoc(), Env.getResultObjectLocation(*S), Env);
 }
 
Index: clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
===
--- clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -458,8 +458,9 @@
 void transferMakeOptionalCall(const CallExpr *E,
   const MatchFinder::MatchResult &,
   LatticeTransferState &State) {
-  createOptionalValue(State.Env.getResultObjectLocation(*E),
-  State.Env.getBoolLiteralValue(true), State.Env);
+  State.Env.setValue(
+  *E, createOptionalValue(State.Env.getResultObjectLocation(*E),
+  State.Env.getBoolLiteralValue(true), State.Env));
 }
 
 void transferOptionalHasValueCall(const CXXMemberCallExpr *CallExpr,
@@ -543,7 +544,10 @@
 }
   }
 
-  createOptionalValue(*Loc, State.Env.makeAtomicBoolValue(), State.Env);
+  RecordValue &Val =
+  createOptionalValue(*Loc, State.Env.makeAtomicBoolValue(), State.Env);
+  if (E->isPRValue())
+State.Env.setValue(*E, Val);
 }
 
 void constructOptionalValue(const Expr &E, Environment &Env,
Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -171,6 +171,105 @@
   return Current;
 }
 
+// Returns whether the values in `Map1` and `Map2` compare equal for those
+// keys that `Map1` and `Map2` have in common.
+template 
+bool compareKeyToValueMaps(const llvm::MapVector &Map1,
+   const llvm::MapVector &Map2,
+   const Environment &Env1, const Environment &Env2,
+   Environment::ValueModel &Model) {
+  for (auto &Entry : Map1) {
+Key K = Entry.first;
+assert(K != nullptr);
+
+Value *Val = Entry.second;
+assert(Val != nullptr);
+
+auto It = Map2.find(K);
+if (It == Map2.end())
+  continue;
+assert(It->second != nullptr);
+
+if (!areEquivalentValues(*Val, *It->second) &&
+!compareDistinctValues(K->getType(), *Val, Env1, *It->second, Env2,
+   Model))
+  return false;
+  }
+
+  return true;
+}
+
+// Perform a join on either `LocToVal` or `ExprToVal`. `Key` must be either
+// `const StorageLocation *` or `const Expr *`.
+template 
+llvm::MapVector
+joinKeyToValueMap(const llvm::MapVector &Map1,
+  const llvm::MapVector &Map2,
+  const Environment &Env1, const Environment &Env2,
+  Environment &JoinedEnv, Environment::ValueModel &Model) {
+  llvm::MapVector MergedMap;
+  for (auto &Entry : Map1) {
+Key K = Entry.first;
+assert(K != nullptr);
+
+Value *Val = Entry.second;
+assert(Val != nullptr);
+
+auto It = Map2.find(K);
+if (It == Map2.end())
+  continue;
+assert(It->second != nullptr);
+
+if (areEquivalentValues(*Val, *It->second)) {
+  MergedMap.insert({K, Val});
+  continue;
+}
+
+if (Value *MergedVal = mergeDistinctValues(
+K->getType(), *Val, Env1, *It->second, Env2, JoinedEnv, Model)) {
+  MergedMap.insert({K, MergedVal});
+}
+  }
+
+  return MergedMap;
+}
+
+// Perform widening on either `LocToVal` or `ExprToVal`. `Key` must be either
+// `const StorageLocation *` or `const Expr *`.
+template 
+llvm::MapVector
+widenKeyToValueMap(const llvm::MapVector &CurMap,
+   const llvm::MapVector &PrevMap,
+   Environment &CurEnv, const Environment &PrevEnv,
+   Environment::ValueModel &Model, LatticeJoinEffect &Effect) {
+  llvm::MapVector WidenedMap;
+  for (auto &Entry : CurMap) {
+Key K = Entry.first;
+   

[PATCH] D158863: Implement the monolithic CI pipeline in the monorepo

2023-08-29 Thread Mikhail Goncharov via Phabricator via cfe-commits
goncharov added inline comments.



Comment at: .ci/generate-buildkite-pipeline-premerge:163
+
+if [[ ! ${SPECIFIC_PIPELINE_AVAILABLE} -eq 1 ]]; then
+  # Figure out which projects need to be built on each platform

ldionne wrote:
> goncharov wrote:
> > do I understand correctly that if mlir and libcxx modified then only libcxx 
> > will be run as SPECIFIC_PIPELINE_AVAILABLE=1?
> Yes. This corresponds to the current logic as well. Basically if a project 
> has some custom CI set up, we don't want to also run the general CI since 
> that's just a waste of resources.
The previous logic was that we caclulated first all projects that might be 
affected by current set (e.g. mlir is affected by llvm), then we added add 
dependencies.
So e.g. if mlir was modified, we should add "flang" to test set and then add 
"llvm clang" as dependincies, resutling in "mlir flang llvm clang" set. I can 
re-implement this logic later here no problem.
Also, it seems incorrect to only run "libc++" tests if libc++ was modified 
among other things. E.g. if something has touched libc++ and mlir than mlir 
should still run.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158863/new/

https://reviews.llvm.org/D158863

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


[PATCH] D112921: [clang] Enable sized deallocation by default in C++14 onwards

2023-08-29 Thread Wang Pengcheng via Phabricator via cfe-commits
wangpc added a comment.

Thanks all! I will land this patch later.
If there are some failures (especially `libcxx` part @Mordante :-) ), please 
help me to fix them. Thanks in advance!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D112921/new/

https://reviews.llvm.org/D112921

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


[clang-tools-extra] 2916b12 - [clang] Enable sized deallocation by default in C++14 onwards

2023-08-29 Thread via cfe-commits

Author: wangpc
Date: 2023-08-29T15:42:50+08:00
New Revision: 2916b125f686115deab2ba573dcaff3847566ab9

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

LOG: [clang] Enable sized deallocation by default in C++14 onwards

Since C++14 has been released for about nine years and most standard
libraries have implemented sized deallocation functions, it's time to
make this feature default again.

Reviewed By: rnk, aaron.ballman, #libc, ldionne, Mordante, MaskRay

Differential Revision: https://reviews.llvm.org/D112921

Added: 
clang/include/clang/Basic/SizedDeallocation.h

Modified: 
clang-tools-extra/clangd/unittests/FindTargetTests.cpp
clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp
clang/docs/ReleaseNotes.rst
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/Darwin.cpp
clang/lib/Driver/ToolChains/Darwin.h
clang/lib/Driver/ToolChains/ZOS.cpp
clang/test/AST/ast-dump-expr-json.cpp
clang/test/AST/ast-dump-expr.cpp
clang/test/AST/ast-dump-stmt-json.cpp
clang/test/Analysis/cxxnewexpr-callback.cpp

clang/test/CXX/basic/basic.stc/basic.stc.dynamic/basic.stc.dynamic.deallocation/p2.cpp
clang/test/CXX/expr/expr.unary/expr.new/p14.cpp
clang/test/CodeGenCXX/cxx1y-sized-deallocation.cpp
clang/test/CodeGenCXX/cxx1z-aligned-allocation.cpp
clang/test/CodeGenCXX/cxx2a-destroying-delete.cpp
clang/test/CodeGenCXX/delete-two-arg.cpp
clang/test/CodeGenCXX/delete.cpp
clang/test/CodeGenCXX/dllimport.cpp
clang/test/CodeGenCXX/new.cpp
clang/test/CodeGenCoroutines/coro-aligned-alloc-2.cpp
clang/test/CodeGenCoroutines/coro-aligned-alloc.cpp
clang/test/CodeGenCoroutines/coro-alloc.cpp
clang/test/CodeGenCoroutines/coro-cleanup.cpp
clang/test/CodeGenCoroutines/coro-dealloc.cpp
clang/test/CodeGenCoroutines/coro-gro.cpp
clang/test/CodeGenCoroutines/pr56919.cpp
clang/test/Lexer/cxx-features.cpp
clang/test/PCH/cxx1z-aligned-alloc.cpp
clang/test/SemaCXX/MicrosoftExtensions.cpp
clang/test/SemaCXX/builtin-operator-new-delete.cpp
clang/test/SemaCXX/cxx1y-sized-deallocation.cpp
clang/test/SemaCXX/unavailable_aligned_allocation.cpp
clang/unittests/StaticAnalyzer/CallEventTest.cpp
clang/www/cxx_status.html
libcxx/test/libcxx/language.support/support.dynamic/libcpp_deallocate.sh.cpp

libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.array/sized_delete_array14.pass.cpp

libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.single/sized_delete14.pass.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp 
b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
index 19e80658de063c..56cf6da70965ba 100644
--- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -812,7 +812,9 @@ TEST_F(TargetDeclTest, OverloadExpr) {
   [[delete]] x;
 }
   )cpp";
-  EXPECT_DECLS("CXXDeleteExpr", "void operator delete(void *) noexcept");
+  // Sized deallocation is enabled by default in C++14 onwards.
+  EXPECT_DECLS("CXXDeleteExpr",
+   "void operator delete(void *, unsigned long) noexcept");
 }
 
 TEST_F(TargetDeclTest, DependentExprs) {

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp
index 78f021144b2e19..f86fe8a4c5b14f 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp
@@ -12,16 +12,6 @@ struct S {
 // CHECK-MESSAGES: :[[@LINE+1]]:7: warning: declaration of 'operator new' has 
no matching declaration of 'operator delete' at the same scope
 void *operator new(size_t size) noexcept(false);
 
-struct T {
-  // Sized deallocations are not enabled by default, and so this new/delete 
pair
-  // does not match. However, we expect only one warning, for the new, because
-  // the operator delete is a placement delete and we do not warn on 
mismatching
-  // placement operations.
-  // CHECK-MESSAGES: :[[@LINE+1]]:9: warning: declaration of 'operator new' 
has no matching declaration of 'operator delete' at the same scope
-  void *operator new(size_t size) noexcept;
-  void operator delete(void *ptr, size_t) noexcept; // ok only if sized 
deallocation is enabled
-};
-
 struct U {
   void *operator new(size_t size) noexcept;
   void operator delete(void *ptr) noexcept;

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index deb53303a21b44..58a22ec5cce17d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseN

[PATCH] D112921: [clang] Enable sized deallocation by default in C++14 onwards

2023-08-29 Thread Wang Pengcheng via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2916b125f686: [clang] Enable sized deallocation by default 
in C++14 onwards (authored by wangpc).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D112921/new/

https://reviews.llvm.org/D112921

Files:
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp
  clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/SizedDeallocation.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Darwin.cpp
  clang/lib/Driver/ToolChains/Darwin.h
  clang/lib/Driver/ToolChains/ZOS.cpp
  clang/test/AST/ast-dump-expr-json.cpp
  clang/test/AST/ast-dump-expr.cpp
  clang/test/AST/ast-dump-stmt-json.cpp
  clang/test/Analysis/cxxnewexpr-callback.cpp
  
clang/test/CXX/basic/basic.stc/basic.stc.dynamic/basic.stc.dynamic.deallocation/p2.cpp
  clang/test/CXX/expr/expr.unary/expr.new/p14.cpp
  clang/test/CodeGenCXX/cxx1y-sized-deallocation.cpp
  clang/test/CodeGenCXX/cxx1z-aligned-allocation.cpp
  clang/test/CodeGenCXX/cxx2a-destroying-delete.cpp
  clang/test/CodeGenCXX/delete-two-arg.cpp
  clang/test/CodeGenCXX/delete.cpp
  clang/test/CodeGenCXX/dllimport.cpp
  clang/test/CodeGenCXX/new.cpp
  clang/test/CodeGenCoroutines/coro-aligned-alloc-2.cpp
  clang/test/CodeGenCoroutines/coro-aligned-alloc.cpp
  clang/test/CodeGenCoroutines/coro-alloc.cpp
  clang/test/CodeGenCoroutines/coro-cleanup.cpp
  clang/test/CodeGenCoroutines/coro-dealloc.cpp
  clang/test/CodeGenCoroutines/coro-gro.cpp
  clang/test/CodeGenCoroutines/pr56919.cpp
  clang/test/Lexer/cxx-features.cpp
  clang/test/PCH/cxx1z-aligned-alloc.cpp
  clang/test/SemaCXX/MicrosoftExtensions.cpp
  clang/test/SemaCXX/builtin-operator-new-delete.cpp
  clang/test/SemaCXX/cxx1y-sized-deallocation.cpp
  clang/test/SemaCXX/unavailable_aligned_allocation.cpp
  clang/unittests/StaticAnalyzer/CallEventTest.cpp
  clang/www/cxx_status.html
  libcxx/test/libcxx/language.support/support.dynamic/libcpp_deallocate.sh.cpp
  
libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.array/sized_delete_array14.pass.cpp
  
libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.single/sized_delete14.pass.cpp

Index: libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.single/sized_delete14.pass.cpp
===
--- libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.single/sized_delete14.pass.cpp
+++ libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.single/sized_delete14.pass.cpp
@@ -8,11 +8,13 @@
 
 // test sized operator delete replacement.
 
+// TODO(mordante) fix this test after updating clang in Docker
+// UNSUPPORTED: clang-15, clang-16, clang-17, clang-18
 // UNSUPPORTED: sanitizer-new-delete, c++03, c++11
+// XFAIL: apple-clang
 
-// NOTE: Clang does not enable sized-deallocation in C++14 and beyond by
-// default. It is only enabled when -fsized-deallocation is given.
-// XFAIL: clang, apple-clang
+// Sized deallocation was added in macOS 10.12 and aligned OSes.
+// XFAIL: use_system_cxx_lib && target={{.+}}-apple-macosx10.{{9|10|11}}
 
 #include 
 #include 
Index: libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.array/sized_delete_array14.pass.cpp
===
--- libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.array/sized_delete_array14.pass.cpp
+++ libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.array/sized_delete_array14.pass.cpp
@@ -8,11 +8,13 @@
 
 // test sized operator delete[] replacement.
 
+// TODO(mordante) fix this test after updating clang in Docker
+// UNSUPPORTED: clang-15, clang-16, clang-17, clang-18
 // UNSUPPORTED: sanitizer-new-delete, c++03, c++11
+// XFAIL: apple-clang
 
-// NOTE: Clang does not enable sized-deallocation in C++14 and beyond by
-// default. It is only enabled when -fsized-deallocation is given.
-// XFAIL: clang, apple-clang
+// Sized deallocation was added in macOS 10.12 and aligned OSes.
+// XFAIL: use_system_cxx_lib && target={{.+}}-apple-macosx10.{{9|10|11}}
 
 #include 
 #include 
Index: libcxx/test/libcxx/language.support/support.dynamic/libcpp_deallocate.sh.cpp
===
--- libcxx/test/libcxx/language.support/support.dynamic/libcpp_deallocate.sh.cpp
+++ libcxx/test/libcxx/language.support/support.dynamic/libcpp_deallocate.sh.cpp
@@ -25,6 +25,9 @@
 // GCC doesn't support the aligned-allocation flags.
 // XFAIL: gcc
 
+// TODO(mordante) fix this test after updating clang in Docker
+// UNSUPPORTED: clang-15, clang-16, clang-17, clan

[clang] 6982f1f - [clang-format][NFC] Test formatting the input before messing it up

2023-08-29 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2023-08-29T00:59:33-07:00
New Revision: 6982f1fc2e750cfbb4b0098a6294d341238656ca

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

LOG: [clang-format][NFC] Test formatting the input before messing it up

Differential Revision: https://reviews.llvm.org/D158947

Added: 


Modified: 
clang/unittests/Format/FormatTestBase.h

Removed: 




diff  --git a/clang/unittests/Format/FormatTestBase.h 
b/clang/unittests/Format/FormatTestBase.h
index 2b0c4550bb951f..22eea23b869a21 100644
--- a/clang/unittests/Format/FormatTestBase.h
+++ b/clang/unittests/Format/FormatTestBase.h
@@ -105,7 +105,9 @@ class FormatTestBase : public ::testing::Test {
 
   void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
  const std::optional &Style = {}) {
-_verifyFormat(File, Line, Code, test::messUp(Code), Style);
+_verifyFormat(File, Line, Code, Code, Style);
+if (const auto MessedUpCode{messUp(Code)}; MessedUpCode != Code)
+  _verifyFormat(File, Line, Code, MessedUpCode, Style);
   }
 
   void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef 
Code,



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


[PATCH] D158947: [clang-format][NFC] Test formatting the input before messing it up

2023-08-29 Thread Owen Pan via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6982f1fc2e75: [clang-format][NFC] Test formatting the input 
before messing it up (authored by owenpan).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158947/new/

https://reviews.llvm.org/D158947

Files:
  clang/unittests/Format/FormatTestBase.h


Index: clang/unittests/Format/FormatTestBase.h
===
--- clang/unittests/Format/FormatTestBase.h
+++ clang/unittests/Format/FormatTestBase.h
@@ -105,7 +105,9 @@
 
   void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
  const std::optional &Style = {}) {
-_verifyFormat(File, Line, Code, test::messUp(Code), Style);
+_verifyFormat(File, Line, Code, Code, Style);
+if (const auto MessedUpCode{messUp(Code)}; MessedUpCode != Code)
+  _verifyFormat(File, Line, Code, MessedUpCode, Style);
   }
 
   void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef 
Code,


Index: clang/unittests/Format/FormatTestBase.h
===
--- clang/unittests/Format/FormatTestBase.h
+++ clang/unittests/Format/FormatTestBase.h
@@ -105,7 +105,9 @@
 
   void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
  const std::optional &Style = {}) {
-_verifyFormat(File, Line, Code, test::messUp(Code), Style);
+_verifyFormat(File, Line, Code, Code, Style);
+if (const auto MessedUpCode{messUp(Code)}; MessedUpCode != Code)
+  _verifyFormat(File, Line, Code, MessedUpCode, Style);
   }
 
   void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef Code,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D158933: [clang] Implement -funsigned-bitfields

2023-08-29 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:18137
+
+  // TODO: Somehow get the explicit signdness info, maybe with the usage of
+  // the typedef's name (Typedef->getDecl()->getNameAsString()), look it up

The information seems preserved in `BuiltinTypeLoc::getWrittenSignSpec`
From `TypedefType::getDecl`, you can get a `TypedefNameDecl`, which has a 
`getTypeSourceInfo`, which gets you a `TypeSourceInfo`, that you can extract a 
`TypeLoc` from, and if you cast that to `BuiltinTypeLoc`, you might be able to 
find what you need. Good luck!



Comment at: clang/lib/Sema/SemaDecl.cpp:18146-18158
+  // Change to unsigned variant
+  if (ResultType == Context.CharTy)
+ResultType = Context.UnsignedCharTy;
+  else if (ResultType == Context.ShortTy)
+ResultType = Context.UnsignedShortTy;
+  else if (ResultType == Context.IntTy)
+ResultType = Context.UnsignedIntTy;

`ASTContext::getCorrespondingUnsignedType` is probably the better way to do that


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158933/new/

https://reviews.llvm.org/D158933

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


[PATCH] D158615: [clang] Emit an error if variable ends up with incomplete array type

2023-08-29 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon updated this revision to Diff 554220.
Fznamznon added a comment.

Apply suggestion, rebase to maybe pass precommit


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158615/new/

https://reviews.llvm.org/D158615

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaDecl.cpp
  clang/test/SemaCXX/gh37257.cpp


Index: clang/test/SemaCXX/gh37257.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/gh37257.cpp
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+template
+T&& create();
+
+template
+void test() {
+  T t(create()...); // expected-error{{variable has incomplete type 
'int[]'}}
+  (void) t;
+}
+
+struct A;
+
+int main() {
+  test(); // expected-note {{in instantiation of function template 
specialization 'test' requested here}}
+}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -13445,6 +13445,18 @@
 IsParenListInit = !InitSeq.steps().empty() &&
   InitSeq.step_begin()->Kind ==
   InitializationSequence::SK_ParenthesizedListInit;
+QualType VDeclType = VDecl->getType();
+if (Init && !Init->getType().isNull() &&
+!Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
+Context.getAsIncompleteArrayType(VDeclType) &&
+Context.getAsIncompleteArrayType(Init->getType())) {
+  // Bail out if it is not possible to deduce array size from the
+  // initializer.
+  Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
+  << VDeclType;
+  VDecl->setInvalidDecl();
+  return;
+}
   }
 
   // Check for self-references within variable initializers.
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -193,6 +193,9 @@
   (`#64876 `_)
 - Fixed an assertion if a function has cleanups and fatal erors.
   (`#48974 `_)
+- Clang now emits an error if it is not possible to deduce array size for a
+  variable with incomplete array type.
+  (`#37257 `_)
 
 Bug Fixes to Compiler Builtins
 ^^


Index: clang/test/SemaCXX/gh37257.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/gh37257.cpp
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+template
+T&& create();
+
+template
+void test() {
+  T t(create()...); // expected-error{{variable has incomplete type 'int[]'}}
+  (void) t;
+}
+
+struct A;
+
+int main() {
+  test(); // expected-note {{in instantiation of function template specialization 'test' requested here}}
+}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -13445,6 +13445,18 @@
 IsParenListInit = !InitSeq.steps().empty() &&
   InitSeq.step_begin()->Kind ==
   InitializationSequence::SK_ParenthesizedListInit;
+QualType VDeclType = VDecl->getType();
+if (Init && !Init->getType().isNull() &&
+!Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
+Context.getAsIncompleteArrayType(VDeclType) &&
+Context.getAsIncompleteArrayType(Init->getType())) {
+  // Bail out if it is not possible to deduce array size from the
+  // initializer.
+  Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
+  << VDeclType;
+  VDecl->setInvalidDecl();
+  return;
+}
   }
 
   // Check for self-references within variable initializers.
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -193,6 +193,9 @@
   (`#64876 `_)
 - Fixed an assertion if a function has cleanups and fatal erors.
   (`#48974 `_)
+- Clang now emits an error if it is not possible to deduce array size for a
+  variable with incomplete array type.
+  (`#37257 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D112921: [clang] Enable sized deallocation by default in C++14 onwards

2023-08-29 Thread Nikita Popov via Phabricator via cfe-commits
nikic added a comment.

FYI this resulted in some pretty wild code size swings, in particular between 
-10% and -15% for tramp3d-v4 
(http://llvm-compile-time-tracker.com/compare.php?from=6cde64a94986165547ae5237ac7dd4bddfc9f2a7&to=2916b125f686115deab2ba573dcaff3847566ab9&stat=size-text).
 Not sure whether that's an expected result of this change or not.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D112921/new/

https://reviews.llvm.org/D112921

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


[clang] 13a044c - [DebugInfo] Fix incorrect dbg.declare when nrvo flag is used

2023-08-29 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2023-08-29T11:39:59+02:00
New Revision: 13a044c6993a914fc33549b72215e698a1cdef63

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

LOG: [DebugInfo] Fix incorrect dbg.declare when nrvo flag is used

When clang generates an nrvo boolean flag, the dbg.declare for the
corresponding variable was incorrectly placed on that flag, rather
than the actual variable.

Fix this by not overwriting AllocaAddr with the nrvo flag.

This started causing verifier errors with D158743.

Differential Revision: https://reviews.llvm.org/D158972

Added: 
clang/test/CodeGenCXX/trivial_abi_debuginfo.cpp

Modified: 
clang/lib/CodeGen/CGDecl.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index d8f2fa1f593a60..99b94588f56f0a 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -1534,8 +1534,7 @@ CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
   // applied.
   llvm::Value *Zero = Builder.getFalse();
   Address NRVOFlag =
-  CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo",
-   /*ArraySize=*/nullptr, &AllocaAddr);
+  CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
   EnsureInsertPoint();
   Builder.CreateStore(Zero, NRVOFlag);
 

diff  --git a/clang/test/CodeGenCXX/trivial_abi_debuginfo.cpp 
b/clang/test/CodeGenCXX/trivial_abi_debuginfo.cpp
new file mode 100644
index 00..3d93f20ee1b242
--- /dev/null
+++ b/clang/test/CodeGenCXX/trivial_abi_debuginfo.cpp
@@ -0,0 +1,33 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --functions "makeTrivial" --version 2
+// RUN: %clang_cc1 -debug-info-kind=limited -triple x86_64-unknown-linux-gnu 
-emit-llvm -o - %s | FileCheck %s
+
+struct __attribute__((trivial_abi)) Trivial {
+  ~Trivial() {}
+  int ivar = 10;
+};
+
+// The dbg.declare should be on %retval, not on %nrvo.
+
+// CHECK-LABEL: define dso_local i32 @_Z11makeTrivialv
+// CHECK-SAME: () #[[ATTR0:[0-9]+]] !dbg [[DBG5:![0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca [[STRUCT_TRIVIAL:%.*]], align 4
+// CHECK-NEXT:[[NRVO:%.*]] = alloca i1, align 1
+// CHECK-NEXT:store i1 false, ptr [[NRVO]], align 1, !dbg [[DBG18:![0-9]+]]
+// CHECK-NEXT:call void @llvm.dbg.declare(metadata ptr [[RETVAL]], 
metadata [[META19:![0-9]+]], metadata !DIExpression()), !dbg [[DBG20:![0-9]+]]
+// CHECK-NEXT:call void @_ZN7TrivialC1Ev(ptr noundef nonnull align 4 
dereferenceable(4) [[RETVAL]]) #[[ATTR3:[0-9]+]], !dbg [[DBG20]]
+// CHECK-NEXT:store i1 true, ptr [[NRVO]], align 1, !dbg [[DBG21:![0-9]+]]
+// CHECK-NEXT:[[NRVO_VAL:%.*]] = load i1, ptr [[NRVO]], align 1, !dbg 
[[DBG22:![0-9]+]]
+// CHECK-NEXT:br i1 [[NRVO_VAL]], label [[NRVO_SKIPDTOR:%.*]], label 
[[NRVO_UNUSED:%.*]], !dbg [[DBG22]]
+// CHECK:   nrvo.unused:
+// CHECK-NEXT:call void @_ZN7TrivialD1Ev(ptr noundef nonnull align 4 
dereferenceable(4) [[RETVAL]]) #[[ATTR3]], !dbg [[DBG22]]
+// CHECK-NEXT:br label [[NRVO_SKIPDTOR]], !dbg [[DBG22]]
+// CHECK:   nrvo.skipdtor:
+// CHECK-NEXT:[[COERCE_DIVE:%.*]] = getelementptr inbounds 
[[STRUCT_TRIVIAL]], ptr [[RETVAL]], i32 0, i32 0, !dbg [[DBG22]]
+// CHECK-NEXT:[[TMP0:%.*]] = load i32, ptr [[COERCE_DIVE]], align 4, !dbg 
[[DBG22]]
+// CHECK-NEXT:ret i32 [[TMP0]], !dbg [[DBG22]]
+//
+Trivial makeTrivial() {
+  Trivial ret_val;
+  return ret_val;
+}



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


[PATCH] D158972: [DebugInfo] Fix incorrect dbg.declare when nrvo flag is used

2023-08-29 Thread Nikita Popov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG13a044c6993a: [DebugInfo] Fix incorrect dbg.declare when 
nrvo flag is used (authored by nikic).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158972/new/

https://reviews.llvm.org/D158972

Files:
  clang/lib/CodeGen/CGDecl.cpp
  clang/test/CodeGenCXX/trivial_abi_debuginfo.cpp


Index: clang/test/CodeGenCXX/trivial_abi_debuginfo.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/trivial_abi_debuginfo.cpp
@@ -0,0 +1,33 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --functions "makeTrivial" --version 2
+// RUN: %clang_cc1 -debug-info-kind=limited -triple x86_64-unknown-linux-gnu 
-emit-llvm -o - %s | FileCheck %s
+
+struct __attribute__((trivial_abi)) Trivial {
+  ~Trivial() {}
+  int ivar = 10;
+};
+
+// The dbg.declare should be on %retval, not on %nrvo.
+
+// CHECK-LABEL: define dso_local i32 @_Z11makeTrivialv
+// CHECK-SAME: () #[[ATTR0:[0-9]+]] !dbg [[DBG5:![0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca [[STRUCT_TRIVIAL:%.*]], align 4
+// CHECK-NEXT:[[NRVO:%.*]] = alloca i1, align 1
+// CHECK-NEXT:store i1 false, ptr [[NRVO]], align 1, !dbg [[DBG18:![0-9]+]]
+// CHECK-NEXT:call void @llvm.dbg.declare(metadata ptr [[RETVAL]], 
metadata [[META19:![0-9]+]], metadata !DIExpression()), !dbg [[DBG20:![0-9]+]]
+// CHECK-NEXT:call void @_ZN7TrivialC1Ev(ptr noundef nonnull align 4 
dereferenceable(4) [[RETVAL]]) #[[ATTR3:[0-9]+]], !dbg [[DBG20]]
+// CHECK-NEXT:store i1 true, ptr [[NRVO]], align 1, !dbg [[DBG21:![0-9]+]]
+// CHECK-NEXT:[[NRVO_VAL:%.*]] = load i1, ptr [[NRVO]], align 1, !dbg 
[[DBG22:![0-9]+]]
+// CHECK-NEXT:br i1 [[NRVO_VAL]], label [[NRVO_SKIPDTOR:%.*]], label 
[[NRVO_UNUSED:%.*]], !dbg [[DBG22]]
+// CHECK:   nrvo.unused:
+// CHECK-NEXT:call void @_ZN7TrivialD1Ev(ptr noundef nonnull align 4 
dereferenceable(4) [[RETVAL]]) #[[ATTR3]], !dbg [[DBG22]]
+// CHECK-NEXT:br label [[NRVO_SKIPDTOR]], !dbg [[DBG22]]
+// CHECK:   nrvo.skipdtor:
+// CHECK-NEXT:[[COERCE_DIVE:%.*]] = getelementptr inbounds 
[[STRUCT_TRIVIAL]], ptr [[RETVAL]], i32 0, i32 0, !dbg [[DBG22]]
+// CHECK-NEXT:[[TMP0:%.*]] = load i32, ptr [[COERCE_DIVE]], align 4, !dbg 
[[DBG22]]
+// CHECK-NEXT:ret i32 [[TMP0]], !dbg [[DBG22]]
+//
+Trivial makeTrivial() {
+  Trivial ret_val;
+  return ret_val;
+}
Index: clang/lib/CodeGen/CGDecl.cpp
===
--- clang/lib/CodeGen/CGDecl.cpp
+++ clang/lib/CodeGen/CGDecl.cpp
@@ -1534,8 +1534,7 @@
   // applied.
   llvm::Value *Zero = Builder.getFalse();
   Address NRVOFlag =
-  CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo",
-   /*ArraySize=*/nullptr, &AllocaAddr);
+  CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
   EnsureInsertPoint();
   Builder.CreateStore(Zero, NRVOFlag);
 


Index: clang/test/CodeGenCXX/trivial_abi_debuginfo.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/trivial_abi_debuginfo.cpp
@@ -0,0 +1,33 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --functions "makeTrivial" --version 2
+// RUN: %clang_cc1 -debug-info-kind=limited -triple x86_64-unknown-linux-gnu -emit-llvm -o - %s | FileCheck %s
+
+struct __attribute__((trivial_abi)) Trivial {
+  ~Trivial() {}
+  int ivar = 10;
+};
+
+// The dbg.declare should be on %retval, not on %nrvo.
+
+// CHECK-LABEL: define dso_local i32 @_Z11makeTrivialv
+// CHECK-SAME: () #[[ATTR0:[0-9]+]] !dbg [[DBG5:![0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[RETVAL:%.*]] = alloca [[STRUCT_TRIVIAL:%.*]], align 4
+// CHECK-NEXT:[[NRVO:%.*]] = alloca i1, align 1
+// CHECK-NEXT:store i1 false, ptr [[NRVO]], align 1, !dbg [[DBG18:![0-9]+]]
+// CHECK-NEXT:call void @llvm.dbg.declare(metadata ptr [[RETVAL]], metadata [[META19:![0-9]+]], metadata !DIExpression()), !dbg [[DBG20:![0-9]+]]
+// CHECK-NEXT:call void @_ZN7TrivialC1Ev(ptr noundef nonnull align 4 dereferenceable(4) [[RETVAL]]) #[[ATTR3:[0-9]+]], !dbg [[DBG20]]
+// CHECK-NEXT:store i1 true, ptr [[NRVO]], align 1, !dbg [[DBG21:![0-9]+]]
+// CHECK-NEXT:[[NRVO_VAL:%.*]] = load i1, ptr [[NRVO]], align 1, !dbg [[DBG22:![0-9]+]]
+// CHECK-NEXT:br i1 [[NRVO_VAL]], label [[NRVO_SKIPDTOR:%.*]], label [[NRVO_UNUSED:%.*]], !dbg [[DBG22]]
+// CHECK:   nrvo.unused:
+// CHECK-NEXT:call void @_ZN7TrivialD1Ev(ptr noundef nonnull align 4 dereferenceable(4) [[RETVAL]]) #[[ATTR3]], !dbg [[DBG22]]
+// CHECK-NEXT:br label [[NRVO_SKIPDTOR]], !dbg [[DBG22]]
+// CHECK:   nrvo.skipdtor:
+// CHECK-NEX

[clang] 14cc7a0 - [Clang] Allow __declspec(noalias) to access inaccessible memory

2023-08-29 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2023-08-29T11:43:57+02:00
New Revision: 14cc7a07727555102c52e711f476ec7671317d6a

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

LOG: [Clang] Allow __declspec(noalias) to access inaccessible memory

MSVC defines __declspec(noalias) as follows 
(https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2012/k649tyc7(v=vs.110)?redirectedfrom=MSDN):

> noalias means that a function call does not modify or reference
> visible global state and only modifies the memory pointed to
> directly by pointer parameters (first-level indirections).

> If a function is annotated as noalias, the optimizer can assume
> that, in addition to the parameters themselves, only first-level
> indirections of pointer parameters are referenced or modified
> inside the function. The visible global state is the set of all
> data that is not defined or referenced outside of the compilation
> scope, and their address is not taken. The compilation scope is
> all source files (/LTCG (Link-time Code Generation) builds) or a
> single source file (non-/LTCG build).

The wording is not super clear to me, but I believe this is saying
that __declspec(noalias) functions may access inaccessible memory
(i.e. non-visible global state in their words). Indeed, the Windows
CRT applies this attribute to malloc, which does access inaccessible
memory under LLVM's memory model.

As such, change the attribute to emit
memory(argmem: readwrite, inaccessiblemem: readwrite) instead of
memory(argmem: readwrite).

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

Differential Revision: https://reviews.llvm.org/D158984

Added: 


Modified: 
clang/lib/CodeGen/CGCall.cpp
clang/test/CodeGen/ms-declspecs.c

Removed: 




diff  --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index e323ddf8bedae9..ca31675ca4f3b8 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -2375,7 +2375,7 @@ void CodeGenModule::ConstructAttributeList(StringRef Name,
   // gcc specifies that 'pure' functions cannot have infinite loops.
   FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
 } else if (TargetDecl->hasAttr()) {
-  FuncAttrs.addMemoryAttr(llvm::MemoryEffects::argMemOnly());
+  FuncAttrs.addMemoryAttr(llvm::MemoryEffects::inaccessibleOrArgMemOnly());
   FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
 }
 if (TargetDecl->hasAttr())

diff  --git a/clang/test/CodeGen/ms-declspecs.c 
b/clang/test/CodeGen/ms-declspecs.c
index e390dddbe2b476..3029559942f12b 100644
--- a/clang/test/CodeGen/ms-declspecs.c
+++ b/clang/test/CodeGen/ms-declspecs.c
@@ -41,4 +41,4 @@ void noalias_caller(int *x) { noalias_callee(x); }
 // CHECK: attributes [[NUW]] = { nounwind{{.*}} }
 // CHECK: attributes [[NI]] = { noinline nounwind{{.*}} }
 // CHECK: attributes [[NR]] = { noreturn }
-// CHECK: attributes [[NA]] = { nounwind memory(argmem: readwrite){{.*}} }
+// CHECK: attributes [[NA]] = { nounwind memory(argmem: readwrite, 
inaccessiblemem: readwrite){{.*}} }



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


[PATCH] D158984: [Clang] Allow __declspec(noalias) to access inaccessible memory

2023-08-29 Thread Nikita Popov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG14cc7a077275: [Clang] Allow __declspec(noalias) to access 
inaccessible memory (authored by nikic).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158984/new/

https://reviews.llvm.org/D158984

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/test/CodeGen/ms-declspecs.c


Index: clang/test/CodeGen/ms-declspecs.c
===
--- clang/test/CodeGen/ms-declspecs.c
+++ clang/test/CodeGen/ms-declspecs.c
@@ -41,4 +41,4 @@
 // CHECK: attributes [[NUW]] = { nounwind{{.*}} }
 // CHECK: attributes [[NI]] = { noinline nounwind{{.*}} }
 // CHECK: attributes [[NR]] = { noreturn }
-// CHECK: attributes [[NA]] = { nounwind memory(argmem: readwrite){{.*}} }
+// CHECK: attributes [[NA]] = { nounwind memory(argmem: readwrite, 
inaccessiblemem: readwrite){{.*}} }
Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -2375,7 +2375,7 @@
   // gcc specifies that 'pure' functions cannot have infinite loops.
   FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
 } else if (TargetDecl->hasAttr()) {
-  FuncAttrs.addMemoryAttr(llvm::MemoryEffects::argMemOnly());
+  FuncAttrs.addMemoryAttr(llvm::MemoryEffects::inaccessibleOrArgMemOnly());
   FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
 }
 if (TargetDecl->hasAttr())


Index: clang/test/CodeGen/ms-declspecs.c
===
--- clang/test/CodeGen/ms-declspecs.c
+++ clang/test/CodeGen/ms-declspecs.c
@@ -41,4 +41,4 @@
 // CHECK: attributes [[NUW]] = { nounwind{{.*}} }
 // CHECK: attributes [[NI]] = { noinline nounwind{{.*}} }
 // CHECK: attributes [[NR]] = { noreturn }
-// CHECK: attributes [[NA]] = { nounwind memory(argmem: readwrite){{.*}} }
+// CHECK: attributes [[NA]] = { nounwind memory(argmem: readwrite, inaccessiblemem: readwrite){{.*}} }
Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -2375,7 +2375,7 @@
   // gcc specifies that 'pure' functions cannot have infinite loops.
   FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
 } else if (TargetDecl->hasAttr()) {
-  FuncAttrs.addMemoryAttr(llvm::MemoryEffects::argMemOnly());
+  FuncAttrs.addMemoryAttr(llvm::MemoryEffects::inaccessibleOrArgMemOnly());
   FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
 }
 if (TargetDecl->hasAttr())
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 125abbd - [flang][driver] Ensure negative flags have the same visibility as positive

2023-08-29 Thread Tom Eccles via cfe-commits

Author: Tom Eccles
Date: 2023-08-29T09:48:28Z
New Revision: 125abbdc97671d8300cfc1ebcc010d8d4248974b

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

LOG: [flang][driver] Ensure negative flags have the same visibility as positive

https://reviews.llvm.org/D157151 and https://reviews.llvm.org/D157837
added visibility flags to flang options, hiding options which are
supported only in Clang and not in Flang.

After this change, some negative flags e.g. `-fno-reciprocal-math` no
longer work with flang. These flags are supported in flang (as can be
seen from the support for the positive flags).

I also opted to make sure the clang visibility is the same on these
flags, although I did not look at changing the visibility of non-flang
flags.

Differential Revision: https://reviews.llvm.org/D158612

Added: 
flang/test/Driver/fintegrated-as.f90

Modified: 
clang/include/clang/Driver/Options.td
flang/test/Driver/driver-help-hidden.f90
flang/test/Driver/driver-help.f90

Removed: 
flang/test/Driver/fno-integrated-as.f90



diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 72e24656eca217..072030a44f01de 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2368,13 +2368,13 @@ defm reciprocal_math : BoolFOption<"reciprocal-math",
   PosFlag,
-  NegFlag>;
+  NegFlag>;
 defm approx_func : BoolFOption<"approx-func", LangOpts<"ApproxFunc">, 
DefaultFalse,
PosFlag,
-   NegFlag>;
+   NegFlag>;
 defm finite_math_only : BoolFOption<"finite-math-only",
   LangOpts<"FiniteMathOnly">, DefaultFalse,
   PosFlag,
-  PosFlag>;
+  PosFlag>;
 def fhonor_nans : Flag<["-"], "fhonor-nans">, Group,
   Visibility<[ClangOption, FlangOption]>,
   HelpText<"Specify that floating-point optimizations are not allowed that "
@@ -3385,12 +3385,12 @@ defm ropi : BoolFOption<"ropi",
   LangOpts<"ROPI">, DefaultFalse,
   PosFlag,
-  NegFlag>;
+  NegFlag>;
 defm rwpi : BoolFOption<"rwpi",
   LangOpts<"RWPI">, DefaultFalse,
   PosFlag,
-  NegFlag>;
+  NegFlag>;
 def fplugin_EQ : Joined<["-"], "fplugin=">, Group,
   Flags<[NoXarchOption]>, MetaVarName<"">,
   HelpText<"Load the named plugin (dynamic shared object)">;
@@ -5313,7 +5313,7 @@ def y : Joined<["-"], "y">;
 defm integrated_as : BoolFOption<"integrated-as",
   CodeGenOpts<"DisableIntegratedAS">, DefaultFalse,
   NegFlag,
-  PosFlag,
+  PosFlag,
   BothFlags<[], [ClangOption], " the integrated assembler">>;
 
 def fintegrated_cc1 : Flag<["-"], "fintegrated-cc1">,

diff  --git a/flang/test/Driver/driver-help-hidden.f90 
b/flang/test/Driver/driver-help-hidden.f90
index 888e580d4e845e..7aae2b195815e2 100644
--- a/flang/test/Driver/driver-help-hidden.f90
+++ b/flang/test/Driver/driver-help-hidden.f90
@@ -43,6 +43,7 @@
 ! CHECK-NEXT: -fhonor-nansSpecify that floating-point 
optimizations are not allowed that assume arguments and results are not NANs.
 ! CHECK-NEXT: -fimplicit-none No implicit typing allowed unless 
overridden by IMPLICIT statements
 ! CHECK-NEXT: -finput-charset= Specify the default character set for 
source files
+! CHECK-NEXT: -fintegrated-as Enable the integrated assembler
 ! CHECK-NEXT: -fintrinsic-modules-path 
 ! CHECK-NEXT: Specify where to find the compiled 
intrinsic modules
 ! CHECK-NEXT: -flang-experimental-hlfir

diff  --git a/flang/test/Driver/driver-help.f90 
b/flang/test/Driver/driver-help.f90
index c82f72dff164d7..549bec6aca58c1 100644
--- a/flang/test/Driver/driver-help.f90
+++ b/flang/test/Driver/driver-help.f90
@@ -39,6 +39,7 @@
 ! HELP-NEXT: -fhonor-nansSpecify that floating-point optimizations 
are not allowed that assume arguments and results are not NANs.
 ! HELP-NEXT: -fimplicit-none No implicit typing allowed unless 
overridden by IMPLICIT statements
 ! HELP-NEXT: -finput-charset= Specify the default character set for 
source files
+! HELP-NEXT: -fintegrated-as Enable the integrated assembler
 ! HELP-NEXT: -fintrinsic-modules-path 
 ! HELP-NEXT: Specify where to find the compiled 
intrinsic modules
 ! HELP-NEXT: -flarge-sizes   Use INTEGER(KIND=8) for the result type 
in size-related intrinsics

diff  --git a/flang/test/Driver/fno-integrated-as.f90 
b/flang/test/Driver/fintegrated-as.f90
similarity index 58%
rename from flang/test/Driver/fno-integrated-as.f90
rename to flang/test/Driver/fintegrated-as.f90
index d0f917d57ad830..516d3501dc8d16 100644
--- a/flang/test/Driver/fno-integrated-as.f90
+++ b/flang/test/Driver/fintegrated-as.f90
@@ -1,4 +1,4 @@
-! Tests for the `-fno-integrated-as` flag.
+! Tests for the `-f(no-)integrated-as` flag.
 
 ! UNSUPPORTED: system-windows
 
@@ -11,10 +11,11 @@
 ! CHECK-SAME: "-o" "[[as

[PATCH] D158612: [flang][driver] Ensure negative flags have the same visibility as positive

2023-08-29 Thread Tom Eccles via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG125abbdc9767: [flang][driver] Ensure negative flags have the 
same visibility as positive (authored by tblah).

Changed prior to commit:
  https://reviews.llvm.org/D158612?vs=552723&id=554232#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158612/new/

https://reviews.llvm.org/D158612

Files:
  clang/include/clang/Driver/Options.td
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/fintegrated-as.f90
  flang/test/Driver/fno-integrated-as.f90

Index: flang/test/Driver/fintegrated-as.f90
===
--- flang/test/Driver/fintegrated-as.f90
+++ flang/test/Driver/fintegrated-as.f90
@@ -1,4 +1,4 @@
-! Tests for the `-fno-integrated-as` flag.
+! Tests for the `-f(no-)integrated-as` flag.
 
 ! UNSUPPORTED: system-windows
 
@@ -11,10 +11,11 @@
 ! CHECK-SAME: "-o" "[[assembly_file:.*]].s"
 ! CHECK-NEXT: "-o" "{{.*}}.o" "[[assembly_file:.*]].s"
 
-!-
-! Without `-fno-integrated-as`
-!-
+!
+! Without `-fno-integrated-as` / With `-fintegrated-as` (default)
+!
 ! Verify that there _is no_ separate line with an assembler invocation
+! RUN: %flang -c -fintegrated-as %s -### 2>&1 | FileCheck %s -check-prefix=DEFAULT
 ! RUN: %flang -c %s -### 2>&1 | FileCheck %s -check-prefix=DEFAULT
 ! DEFAULT-LABEL: "-fc1"
-! DEFAULT-SAME: "-o" "{{.*}}.o" "{{.*}}fno-integrated-as.f90"
+! DEFAULT-SAME: "-o" "{{.*}}.o" "{{.*}}fintegrated-as.f90"
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -39,6 +39,7 @@
 ! HELP-NEXT: -fhonor-nansSpecify that floating-point optimizations are not allowed that assume arguments and results are not NANs.
 ! HELP-NEXT: -fimplicit-none No implicit typing allowed unless overridden by IMPLICIT statements
 ! HELP-NEXT: -finput-charset= Specify the default character set for source files
+! HELP-NEXT: -fintegrated-as Enable the integrated assembler
 ! HELP-NEXT: -fintrinsic-modules-path 
 ! HELP-NEXT: Specify where to find the compiled intrinsic modules
 ! HELP-NEXT: -flarge-sizes   Use INTEGER(KIND=8) for the result type in size-related intrinsics
Index: flang/test/Driver/driver-help-hidden.f90
===
--- flang/test/Driver/driver-help-hidden.f90
+++ flang/test/Driver/driver-help-hidden.f90
@@ -43,6 +43,7 @@
 ! CHECK-NEXT: -fhonor-nansSpecify that floating-point optimizations are not allowed that assume arguments and results are not NANs.
 ! CHECK-NEXT: -fimplicit-none No implicit typing allowed unless overridden by IMPLICIT statements
 ! CHECK-NEXT: -finput-charset= Specify the default character set for source files
+! CHECK-NEXT: -fintegrated-as Enable the integrated assembler
 ! CHECK-NEXT: -fintrinsic-modules-path 
 ! CHECK-NEXT: Specify where to find the compiled intrinsic modules
 ! CHECK-NEXT: -flang-experimental-hlfir
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2368,13 +2368,13 @@
   PosFlag,
-  NegFlag>;
+  NegFlag>;
 defm approx_func : BoolFOption<"approx-func", LangOpts<"ApproxFunc">, DefaultFalse,
PosFlag,
-   NegFlag>;
+   NegFlag>;
 defm finite_math_only : BoolFOption<"finite-math-only",
   LangOpts<"FiniteMathOnly">, DefaultFalse,
   PosFlag,
-  PosFlag>;
+  PosFlag>;
 def fhonor_nans : Flag<["-"], "fhonor-nans">, Group,
   Visibility<[ClangOption, FlangOption]>,
   HelpText<"Specify that floating-point optimizations are not allowed that "
@@ -3385,12 +3385,12 @@
   LangOpts<"ROPI">, DefaultFalse,
   PosFlag,
-  NegFlag>;
+  NegFlag>;
 defm rwpi : BoolFOption<"rwpi",
   LangOpts<"RWPI">, DefaultFalse,
   PosFlag,
-  NegFlag>;
+  NegFlag>;
 def fplugin_EQ : Joined<["-"], "fplugin=">, Group,
   Flags<[NoXarchOption]>, MetaVarName<"">,
   HelpText<"Load the named plugin (dynamic shared object)">;
@@ -5313,7 +5313,7 @@
 defm integrated_as : BoolFOption<"integrated-as",
   CodeGenOpts<"DisableIntegratedAS">, DefaultFalse,
   NegFlag,
-  PosFlag,
+  PosFlag,
   BothFlags<[], [ClangOption], " the integrated assembler">>;
 
 def fintegrated_cc1 : Flag<["-"], "fintegrated-cc1">,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D155858: Add a concept AST node.

2023-08-29 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang/lib/AST/TypeLoc.cpp:625
 
-DeclarationNameInfo AutoTypeLoc::getConceptNameInfo() const {
-  return DeclarationNameInfo(getNamedConcept()->getDeclName(),
- getLocalData()->ConceptNameLoc);
+ConceptReference *createConceptReference(ASTContext &Context,
+ SourceLocation Loc,

static


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D155858/new/

https://reviews.llvm.org/D155858

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


[PATCH] D158688: [Driver,ARM,AArch64] Ignore -mbranch-protection= diagnostics for assembler input

2023-08-29 Thread Ties Stuij via Phabricator via cfe-commits
stuij added a comment.

LGTM. Thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158688/new/

https://reviews.llvm.org/D158688

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


[PATCH] D158688: [Driver,ARM,AArch64] Ignore -mbranch-protection= diagnostics for assembler input

2023-08-29 Thread Simon Tatham via Phabricator via cfe-commits
simon_tatham accepted this revision.
simon_tatham added a comment.
This revision is now accepted and ready to land.

The change LGTM, and "agree with gcc" seems like a reasonable justification in 
this case.

But I'm curious more generally about what options should / shouldn't be covered 
by `-Wunused-command-line-argument`. Doesn't the same reasoning apply to 
//most// options that C compilation uses and assembly doesn't? If you have a 
command of the form `clang -someoption -c foo.c`, it's surely //always// 
convenient for a user to be able to change the `.c` into a `.s`, or to put a 
variable list of files on the end of the command line which might or might not 
include any `.c` files. Why is this option in particular different from others? 
Is there a documented policy anywhere?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158688/new/

https://reviews.llvm.org/D158688

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


[PATCH] D155858: Add a concept AST node.

2023-08-29 Thread Jens Massberg via Phabricator via cfe-commits
massberg updated this revision to Diff 554257.
massberg marked 7 inline comments as done.
massberg added a comment.

Resolve more of the open comments.

- add `getBeginLoc()`, `getEndLoc()` and `getSourceRange()` to 
`ConceptReference` and updated corresponding functions in 
`ConceptSpecializationExpr`
- additional fixed `getBeginLoc()` to work correctly with empty argument lists
- remove `const` from parameters of `TraverseConceptReference()` and 
`VisitConceptReference()`

still missing:

- Add tests for new location functions
- Investigation why we have to create a `ConceptReference` in 
`initializeLocal()` which looks not right
- Update patch description.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D155858/new/

https://reviews.llvm.org/D155858

Files:
  clang/include/clang/AST/ASTConcept.h
  clang/include/clang/AST/DeclTemplate.h
  clang/include/clang/AST/ExprConcepts.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/AST/TypeLoc.h
  clang/include/clang/Serialization/ASTRecordReader.h
  clang/include/clang/Serialization/ASTRecordWriter.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/DeclTemplate.cpp
  clang/lib/AST/ExprConcepts.cpp
  clang/lib/AST/TypeLoc.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/SemaType.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/unittests/Tooling/RecursiveASTVisitorTests/Concept.cpp

Index: clang/unittests/Tooling/RecursiveASTVisitorTests/Concept.cpp
===
--- clang/unittests/Tooling/RecursiveASTVisitorTests/Concept.cpp
+++ clang/unittests/Tooling/RecursiveASTVisitorTests/Concept.cpp
@@ -29,12 +29,22 @@
 ++ConceptRequirementsTraversed;
 return ExpectedLocationVisitor::TraverseConceptRequirement(R);
   }
+  bool TraverseConceptReference(ConceptReference *CR) {
+++ConceptReferencesTraversed;
+return ExpectedLocationVisitor::TraverseConceptReference(CR);
+  }
+  bool VisitConceptReference(ConceptReference *CR) {
+++ConceptReferencesVisited;
+return true;
+  }
 
   bool shouldVisitImplicitCode() { return ShouldVisitImplicitCode; }
 
   int ConceptSpecializationExprsVisited = 0;
   int TypeConstraintsTraversed = 0;
   int ConceptRequirementsTraversed = 0;
+  int ConceptReferencesTraversed = 0;
+  int ConceptReferencesVisited = 0;
   bool ShouldVisitImplicitCode = false;
 };
 
@@ -50,6 +60,8 @@
   EXPECT_EQ(1, Visitor.ConceptSpecializationExprsVisited);
   // Also check we traversed the TypeConstraint that produced the expr.
   EXPECT_EQ(1, Visitor.TypeConstraintsTraversed);
+  EXPECT_EQ(1, Visitor.ConceptReferencesTraversed);
+  EXPECT_EQ(1, Visitor.ConceptReferencesVisited);
 
   Visitor = {}; // Don't visit implicit code now.
   EXPECT_TRUE(Visitor.runOver("template  concept Fooable = true;\n"
@@ -59,6 +71,8 @@
   // generated immediately declared expression.
   EXPECT_EQ(0, Visitor.ConceptSpecializationExprsVisited);
   EXPECT_EQ(1, Visitor.TypeConstraintsTraversed);
+  EXPECT_EQ(1, Visitor.ConceptReferencesTraversed);
+  EXPECT_EQ(1, Visitor.ConceptReferencesVisited);
 
   Visitor = {};
   EXPECT_TRUE(Visitor.runOver("template  concept A = true;\n"
@@ -70,6 +84,8 @@
   "};",
   ConceptVisitor::Lang_CXX2a));
   EXPECT_EQ(3, Visitor.ConceptRequirementsTraversed);
+  EXPECT_EQ(1, Visitor.ConceptReferencesTraversed);
+  EXPECT_EQ(1, Visitor.ConceptReferencesVisited);
 }
 
 struct VisitDeclOnlyOnce : ExpectedLocationVisitor {
@@ -86,6 +102,10 @@
 ++AutoTypeLocVisited;
 return true;
   }
+  bool VisitConceptReference(ConceptReference *) {
+++ConceptReferencesVisited;
+return true;
+  }
 
   bool TraverseVarDecl(VarDecl *V) {
 // The base traversal visits only the `TypeLoc`.
@@ -99,6 +119,7 @@
   int ConceptDeclsVisited = 0;
   int AutoTypeVisited = 0;
   int AutoTypeLocVisited = 0;
+  int ConceptReferencesVisited = 0;
 };
 
 TEST(RecursiveASTVisitor, ConceptDeclInAutoType) {
@@ -111,6 +132,7 @@
   EXPECT_EQ(1, Visitor.AutoTypeVisited);
   EXPECT_EQ(1, Visitor.AutoTypeLocVisited);
   EXPECT_EQ(1, Visitor.ConceptDeclsVisited);
+  EXPECT_EQ(1, Visitor.ConceptReferencesVisited);
 }
 
 } // end anonymous namespace
Index: clang/lib/Serialization/ASTWriterStmt.cpp
===
--- clang/lib/Serialization/ASTWriterStmt.cpp
+++ clang/lib/Serialization/ASTWriterStmt.cpp
@@ -11,15 +11,16 @@
 ///
 //===--===//
 
-#include "clang/AST/ExprOpenMP.h"
-#include "clang/Serialization/ASTRecordWriter.h"
-#include "cla

[PATCH] D158778: [CUDA] Propagate __float128 support from the host.

2023-08-29 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

In D158778#4622901 , @tra wrote:

> @ABataev
>
> This patch breaks breaks two tests:
>
> - 
> github.com/llvm/llvm-project/blob/main/clang/test/OpenMP/nvptx_unsupported_type_codegen.cpp
> - 
> github.com/llvm/llvm-project/blob/main/clang/test/OpenMP/nvptx_unsupported_type_messages.cpp
>
> It's not clear what exactly these tests are testing for and I can't tell 
> whether I should just remove the checks related to `__float128`, or if 
> there's something else that would need to be done on the OpenMP side.
>
> AFAICT, OpenMP will pick up `double` format for `__float128` after my patch. 
> This suggests that we would only have `long double` left as an unsupported 
> type on GPU-supporting targets, which suggests that I should just remove the 
> checks related to `__float128` from those tests.
>
> Am I missing something? Is there anything else that may need to be done on 
> the OpenMP side?

Just checks removal should be fine


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158778/new/

https://reviews.llvm.org/D158778

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


[PATCH] D154838: [analyzer] Add check for null pointer passed to %p of printf family

2023-08-29 Thread Georgiy Lebedev via Phabricator via cfe-commits
CuriousGeorgiy updated this revision to Diff 554259.
CuriousGeorgiy marked 2 inline comments as done.
CuriousGeorgiy added a comment.
Herald added a subscriber: ormris.

[analyzer] Add check for null pointer passed to the %p of printf family

The result of passing a null pointer to the pointer conversion specifier of
printf family of functions is implementation defined — for instance, on
Windows zeros are printed, whilst on Linux '(nil)' is printed.

The problem described above is a minor portability issue, so we don't just
add a check for to the existing Unix API checker, since it would be
desirable to be able to disable it.

Instead, to collect such checks we add a new APIPortabilityMinor checker to
the alpha.unix package with a check for the problem described above.

The check assumes that a null pointer is only passed to a pointer
conversion specifier, otherwise it would be undefined behaviour. By making
this assumption we do not have to check the format string and match data
arguments to conversion specifiers.

Closes #43453

Differential Revision: https://reviews.llvm.org/D154838


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D154838/new/

https://reviews.llvm.org/D154838

Files:
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/lib/StaticAnalyzer/Checkers/UnixAPIPortabilityMinorChecker.cpp
  clang/test/Analysis/unix-api-portability-minor.cpp

Index: clang/test/Analysis/unix-api-portability-minor.cpp
===
--- /dev/null
+++ clang/test/Analysis/unix-api-portability-minor.cpp
@@ -0,0 +1,50 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.unix.APIPortabilityMinor -verify %s
+
+#define NULL ((void*)0)
+
+struct FILE_t;
+typedef struct FILE_t FILE;
+
+typedef __typeof(sizeof(int)) size_t;
+
+int printf(const char *, ... );
+int fprintf(FILE *, const char *, ...);
+int sprintf(char *, const char *, ...);
+int snprintf(char *, size_t, const char *, ...);
+
+// Test basic case for the whole print family.
+void test_printf_family_pointer_conversion_specifier_null(FILE *file, char *buf, size_t buf_size, char *format) {
+  printf(format, NULL); // expected-warning{{The result of passing a null pointer to the pointer conversion specifier of the printf family of functions is implementation defined}}
+  fprintf(file, format, NULL); // expected-warning{{The result of passing a null pointer to the pointer conversion specifier of the printf family of functions is implementation defined}}
+  sprintf(buf, format, NULL); // expected-warning{{The result of passing a null pointer to the pointer conversion specifier of the printf family of functions is implementation defined}}
+  snprintf(buf, buf_size, format, NULL); // expected-warning{{The result of passing a null pointer to the pointer conversion specifier of the printf family of functions is implementation defined}}
+}
+
+// Test builtin null pointer type is handled correctly.
+void test_printf_pointer_conversion_specifier_null_nullptr(char *format) {
+  printf(format, nullptr); // expected-warning{{The result of passing a null pointer to the pointer conversion specifier of the printf family of functions is implementation defined}}
+}
+
+// Test various argument indexes.
+void test_printf_pointer_conversion_specifier_null_various_arguments(char *format) {
+  printf(format, NULL); // expected-warning{{The result of passing a null pointer to the pointer conversion specifier of the printf family of functions is implementation defined}}
+  printf(format, 1, NULL); // expected-warning{{The result of passing a null pointer to the pointer conversion specifier of the printf family of functions is implementation defined}}
+  printf(format, 1, NULL, 2); // expected-warning{{The result of passing a null pointer to the pointer conversion specifier of the printf family of functions is implementation defined}}
+  printf(format, NULL, NULL); // expected-warning{{The result of passing a null pointer to the pointer conversion specifier of the printf family of functions is implementation defined}}
+  printf(format, NULL, 1, NULL); // expected-warning{{The result of passing a null pointer to the pointer conversion specifier of the printf family of functions is implementation defined}}
+  printf(format, 0); // no-warning
+}
+
+// Test pointer constraints.
+void printf_pointer_conversion_specifier_null_pointer_constraints(char *format, int *pointer1, int *pointer2) {
+  // Unknown pointer should not rase warning.
+  printf(format, pointer1); // no-warning
+  // Pointer argument should not get constrained after the check.
+  *pointer1 = 777; // no-warning
+
+  if (pointer2 != NULL) {
+printf(format, pointer1); // no-warning
+return;
+  }
+  printf(format, pointer2); // expected-warning{{The result of passing a null pointer to the pointer conversion specifier of th

[PATCH] D159083: Clang: Don't warn about unused private fields of types declared maybe_unused

2023-08-29 Thread Hans Wennborg via Phabricator via cfe-commits
hans created this revision.
hans added reviewers: aaron.ballman, shafik.
Herald added a project: All.
hans requested review of this revision.
Herald added a project: clang.

The compiler should not warn on code such as:

  class [[maybe_unused]] MaybeUnusedClass {};
  class C {
MaybeUnusedClass c;
  };

Patch based on comments on the bug by Shafik and Aaron.

Fixes #61334


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D159083

Files:
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/SemaCXX/warn-unused-private-field.cpp


Index: clang/test/SemaCXX/warn-unused-private-field.cpp
===
--- clang/test/SemaCXX/warn-unused-private-field.cpp
+++ clang/test/SemaCXX/warn-unused-private-field.cpp
@@ -284,3 +284,14 @@
 private:
   int n; // expected-warning{{private field 'n' is not used}}
 };
+
+namespace pr61334 {
+class [[maybe_unused]] MaybeUnusedClass {};
+enum [[maybe_unused]] MaybeUnusedEnum {};
+typedef int MaybeUnusedTypedef [[maybe_unused]];
+class C {
+  MaybeUnusedClass c; // no-warning
+  MaybeUnusedEnum e; // no-warning
+  MaybeUnusedTypedef t; // no-warning
+};
+}
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -3729,10 +3729,20 @@
 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
   // Remember all explicit private FieldDecls that have a name, no side
   // effects and are not part of a dependent type declaration.
+
+  auto DeclHasUnusedAttr = [](const QualType &T) {
+if (const TagDecl *TD = T->getAsTagDecl())
+  return TD->hasAttr();
+if (const TypedefType *TDT = T->getAs())
+  return TDT->getDecl()->hasAttr();
+return false;
+  };
+
   if (!FD->isImplicit() && FD->getDeclName() &&
   FD->getAccess() == AS_private &&
   !FD->hasAttr() &&
   !FD->getParent()->isDependentContext() &&
+  !DeclHasUnusedAttr(FD->getType()) &&
   !InitializationHasSideEffects(*FD))
 UnusedPrivateFields.insert(FD);
 }


Index: clang/test/SemaCXX/warn-unused-private-field.cpp
===
--- clang/test/SemaCXX/warn-unused-private-field.cpp
+++ clang/test/SemaCXX/warn-unused-private-field.cpp
@@ -284,3 +284,14 @@
 private:
   int n; // expected-warning{{private field 'n' is not used}}
 };
+
+namespace pr61334 {
+class [[maybe_unused]] MaybeUnusedClass {};
+enum [[maybe_unused]] MaybeUnusedEnum {};
+typedef int MaybeUnusedTypedef [[maybe_unused]];
+class C {
+  MaybeUnusedClass c; // no-warning
+  MaybeUnusedEnum e; // no-warning
+  MaybeUnusedTypedef t; // no-warning
+};
+}
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -3729,10 +3729,20 @@
 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
   // Remember all explicit private FieldDecls that have a name, no side
   // effects and are not part of a dependent type declaration.
+
+  auto DeclHasUnusedAttr = [](const QualType &T) {
+if (const TagDecl *TD = T->getAsTagDecl())
+  return TD->hasAttr();
+if (const TypedefType *TDT = T->getAs())
+  return TDT->getDecl()->hasAttr();
+return false;
+  };
+
   if (!FD->isImplicit() && FD->getDeclName() &&
   FD->getAccess() == AS_private &&
   !FD->hasAttr() &&
   !FD->getParent()->isDependentContext() &&
+  !DeclHasUnusedAttr(FD->getType()) &&
   !InitializationHasSideEffects(*FD))
 UnusedPrivateFields.insert(FD);
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f616c3e - [OpenMP][DeviceRTL][AMDGPU] Support code object version 5

2023-08-29 Thread Saiyedul Islam via cfe-commits

Author: Saiyedul Islam
Date: 2023-08-29T06:35:44-05:00
New Revision: f616c3eeb43f3732f53f81d291723a6a34af2de1

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

LOG: [OpenMP][DeviceRTL][AMDGPU] Support code object version 5

Update DeviceRTL and the AMDGPU plugin to support code
object version 5. Default is code object version 4.

CodeGen for __builtin_amdgpu_workgroup_size generates code
for cov4 as well as cov5 if -mcode-object-version=none
is specified. DeviceRTL compilation passes this argument
via Xclang option to generate abi-agnostic code.

Generated code for the above builtin uses a clang
control constant "llvm.amdgcn.abi.version" to branch on
the abi version, which is available during linking of
user's OpenMP code. Load of this constant gets eliminated
during linking.

AMDGPU plugin queries the ELF for code object version
and then prepares various implicitargs accordingly.

Differential Revision: https://reviews.llvm.org/D139730

Reviewed By: jhuber6, yaxunl

Added: 
clang/test/CodeGenCUDA/amdgpu-code-object-version-linking.cu

Modified: 
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/CodeGen/CodeGenModule.h
clang/lib/CodeGen/TargetInfo.h
clang/lib/CodeGen/Targets/AMDGPU.cpp
clang/lib/Driver/ToolChain.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/CodeGenCUDA/amdgpu-workgroup-size.cu
clang/test/CodeGenOpenCL/opencl_types.cl
clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
openmp/libomptarget/DeviceRTL/CMakeLists.txt
openmp/libomptarget/plugins-nextgen/amdgpu/src/rtl.cpp
openmp/libomptarget/plugins-nextgen/amdgpu/utils/UtilitiesRTL.h

Removed: 




diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 070246f099e2e9..a513eae46e358e 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -27,6 +27,7 @@
 #include "clang/AST/OSLog.h"
 #include "clang/Basic/TargetBuiltins.h"
 #include "clang/Basic/TargetInfo.h"
+#include "clang/Basic/TargetOptions.h"
 #include "clang/CodeGen/CGFunctionInfo.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
 #include "llvm/ADT/APFloat.h"
@@ -17098,24 +17099,61 @@ Value *EmitAMDGPUImplicitArgPtr(CodeGenFunction &CGF) 
{
 }
 
 // \p Index is 0, 1, and 2 for x, y, and z dimension, respectively.
+/// Emit code based on Code Object ABI version.
+/// COV_4: Emit code to use dispatch ptr
+/// COV_5: Emit code to use implicitarg ptr
+/// COV_NONE : Emit code to load a global variable "llvm.amdgcn.abi.version"
+///and use its value for COV_4 or COV_5 approach. It is used for
+///compiling device libraries in an ABI-agnostic way.
+///
+/// Note: "llvm.amdgcn.abi.version" is supposed to be emitted and intialized by
+///   clang during compilation of user code.
 Value *EmitAMDGPUWorkGroupSize(CodeGenFunction &CGF, unsigned Index) {
-  bool IsCOV_5 = CGF.getTarget().getTargetOpts().CodeObjectVersion ==
- clang::TargetOptions::COV_5;
-  Constant *Offset;
-  Value *DP;
-  if (IsCOV_5) {
+  llvm::LoadInst *LD;
+
+  auto Cov = CGF.getTarget().getTargetOpts().CodeObjectVersion;
+
+  if (Cov == clang::TargetOptions::COV_None) {
+auto *ABIVersionC = CGF.CGM.GetOrCreateLLVMGlobal(
+"llvm.amdgcn.abi.version", CGF.Int32Ty, LangAS::Default, nullptr,
+CodeGen::NotForDefinition);
+
+// This load will be eliminated by the IPSCCP because it is constant
+// weak_odr without externally_initialized. Either changing it to weak or
+// adding externally_initialized will keep the load.
+Value *ABIVersion = CGF.Builder.CreateAlignedLoad(CGF.Int32Ty, ABIVersionC,
+  CGF.CGM.getIntAlign());
+
+Value *IsCOV5 = CGF.Builder.CreateICmpSGE(
+ABIVersion,
+llvm::ConstantInt::get(CGF.Int32Ty, clang::TargetOptions::COV_5));
+
 // Indexing the implicit kernarg segment.
-Offset = llvm::ConstantInt::get(CGF.Int32Ty, 12 + Index * 2);
-DP = EmitAMDGPUImplicitArgPtr(CGF);
-  } else {
+Value *ImplicitGEP = CGF.Builder.CreateConstGEP1_32(
+CGF.Int8Ty, EmitAMDGPUImplicitArgPtr(CGF), 12 + Index * 2);
+
 // Indexing the HSA kernel_dispatch_packet struct.
-Offset = llvm::ConstantInt::get(CGF.Int32Ty, 4 + Index * 2);
-DP = EmitAMDGPUDispatchPtr(CGF);
+Value *DispatchGEP = CGF.Builder.CreateConstGEP1_32(
+CGF.Int8Ty, EmitAMDGPUDispatchPtr(CGF), 4 + Index * 2);
+
+auto Result = CGF.Builder.CreateSelect(IsCOV5, ImplicitGEP, DispatchGEP);
+LD = CGF.Builder.CreateLoad(
+Address(Result, CGF.Int16Ty, CharUnits::fromQuantity(2)));
+  } else {
+Value *GEP = nullptr;
+if (Cov == clang::TargetOptions::COV_5) {
+  // Indexing the 

[PATCH] D139730: [OpenMP][DeviceRTL][AMDGPU] Support code object version 5

2023-08-29 Thread Saiyedul Islam via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf616c3eeb43f: [OpenMP][DeviceRTL][AMDGPU] Support code 
object version 5 (authored by saiislam).

Changed prior to commit:
  https://reviews.llvm.org/D139730?vs=553991&id=554262#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D139730/new/

https://reviews.llvm.org/D139730

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/lib/CodeGen/TargetInfo.h
  clang/lib/CodeGen/Targets/AMDGPU.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGenCUDA/amdgpu-code-object-version-linking.cu
  clang/test/CodeGenCUDA/amdgpu-workgroup-size.cu
  clang/test/CodeGenOpenCL/opencl_types.cl
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  openmp/libomptarget/DeviceRTL/CMakeLists.txt
  openmp/libomptarget/plugins-nextgen/amdgpu/src/rtl.cpp
  openmp/libomptarget/plugins-nextgen/amdgpu/utils/UtilitiesRTL.h

Index: openmp/libomptarget/plugins-nextgen/amdgpu/utils/UtilitiesRTL.h
===
--- openmp/libomptarget/plugins-nextgen/amdgpu/utils/UtilitiesRTL.h
+++ openmp/libomptarget/plugins-nextgen/amdgpu/utils/UtilitiesRTL.h
@@ -25,6 +25,7 @@
 #include "llvm/Support/MemoryBufferRef.h"
 
 #include "llvm/Support/YAMLTraits.h"
+using namespace llvm::ELF;
 
 namespace llvm {
 namespace omp {
@@ -32,19 +33,29 @@
 namespace plugin {
 namespace utils {
 
-// The implicit arguments of AMDGPU kernels.
+// The implicit arguments of COV5 AMDGPU kernels.
 struct AMDGPUImplicitArgsTy {
-  uint64_t OffsetX;
-  uint64_t OffsetY;
-  uint64_t OffsetZ;
-  uint64_t HostcallPtr;
-  uint64_t Unused0;
-  uint64_t Unused1;
-  uint64_t Unused2;
+  uint32_t BlockCountX;
+  uint32_t BlockCountY;
+  uint32_t BlockCountZ;
+  uint16_t GroupSizeX;
+  uint16_t GroupSizeY;
+  uint16_t GroupSizeZ;
+  uint8_t Unused0[46]; // 46 byte offset.
+  uint16_t GridDims;
+  uint8_t Unused1[190]; // 190 byte offset.
 };
 
-static_assert(sizeof(AMDGPUImplicitArgsTy) == 56,
-  "Unexpected size of implicit arguments");
+// Dummy struct for COV4 implicitargs.
+struct AMDGPUImplicitArgsTyCOV4 {
+  uint8_t Unused[56];
+};
+
+uint32_t getImplicitArgsSize(uint16_t Version) {
+  return Version < ELF::ELFABIVERSION_AMDGPU_HSA_V5
+ ? sizeof(AMDGPUImplicitArgsTyCOV4)
+ : sizeof(AMDGPUImplicitArgsTy);
+}
 
 /// Parse a TargetID to get processor arch and feature map.
 /// Returns processor subarch.
@@ -295,7 +306,8 @@
 /// Reads the AMDGPU specific metadata from the ELF file and propagates the
 /// KernelInfoMap
 Error readAMDGPUMetaDataFromImage(MemoryBufferRef MemBuffer,
-  StringMap &KernelInfoMap) {
+  StringMap &KernelInfoMap,
+  uint16_t &ELFABIVersion) {
   Error Err = Error::success(); // Used later as out-parameter
 
   auto ELFOrError = object::ELF64LEFile::create(MemBuffer.getBuffer());
@@ -305,6 +317,12 @@
   const object::ELF64LEFile ELFObj = ELFOrError.get();
   ArrayRef Sections = cantFail(ELFObj.sections());
   KernelInfoReader Reader(KernelInfoMap);
+
+  // Read the code object version from ELF image header
+  auto Header = ELFObj.getHeader();
+  ELFABIVersion = (uint8_t)(Header.e_ident[ELF::EI_ABIVERSION]);
+  DP("ELFABIVERSION Version: %u\n", ELFABIVersion);
+
   for (const auto &S : Sections) {
 if (S.sh_type != ELF::SHT_NOTE)
   continue;
Index: openmp/libomptarget/plugins-nextgen/amdgpu/src/rtl.cpp
===
--- openmp/libomptarget/plugins-nextgen/amdgpu/src/rtl.cpp
+++ openmp/libomptarget/plugins-nextgen/amdgpu/src/rtl.cpp
@@ -381,6 +381,9 @@
   /// Get the executable.
   hsa_executable_t getExecutable() const { return Executable; }
 
+  /// Get to Code Object Version of the ELF
+  uint16_t getELFABIVersion() const { return ELFABIVersion; }
+
   /// Find an HSA device symbol by its name on the executable.
   Expected
   findDeviceSymbol(GenericDeviceTy &Device, StringRef SymbolName) const;
@@ -401,6 +404,7 @@
   hsa_executable_t Executable;
   hsa_code_object_t CodeObject;
   StringMap KernelInfoMap;
+  uint16_t ELFABIVersion;
 };
 
 /// Class implementing the AMDGPU kernel functionalities which derives from the
@@ -408,8 +412,7 @@
 struct AMDGPUKernelTy : public GenericKernelTy {
   /// Create an AMDGPU kernel with a name and an execution mode.
   AMDGPUKernelTy(const char *Name, OMPTgtExecModeFlags ExecutionMode)
-  : GenericKernelTy(Name, ExecutionMode),
-ImplicitArgsSize(sizeof(utils::AMDGPUImplicitArgsTy)) {}
+  : GenericKernelTy(Name, ExecutionMode) {}
 
   /// Initialize the AMDGPU kernel.
   Error initImpl(GenericDeviceTy &Device, DeviceImageTy &Image) override {
@@ -450,6 +453,

[PATCH] D139730: [OpenMP][DeviceRTL][AMDGPU] Support code object version 5

2023-08-29 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam added inline comments.



Comment at: clang/test/CodeGenCUDA/amdgpu-code-object-version-linking.cu:12
+// RUN: llvm-link %t_0 %t_5 -o -| llvm-dis -o - | FileCheck 
-check-prefix=LINKED5 %s
+
+#include "Inputs/cuda.h"

yaxunl wrote:
> saiislam wrote:
> > yaxunl wrote:
> > > need to test using clang -cc1 with -O3 and -mlink-builtin-bitcode to link 
> > > the device lib and verify the load of llvm.amdgcn.abi.version being 
> > > eliminated after optimization.
> > > 
> > > I think currently it cannot do that since llvm.amdgcn.abi.version is not 
> > > internalized by the internalization pass. This can cause some significant 
> > > perf drops since loading is expensive. Need to tweak the function 
> > > controlling what variables can be internalized for amdgpu so that this 
> > > variable gets internalized, or having a generic way to tell that function 
> > > which variables should be internalized, e.g. by adding a metadata 
> > > amdgcn.internalize
> > load of llvm.amdgcn.abi.version is being eliminated with cc1, -O3, and 
> > mlink-builtin-bitcode of device lib.
> It seems being eliminated by IPSCCP. It makes sense since it is constant 
> weak_odr without externally_initialized. Either changing it to weak or adding 
> externally_initialized will keep the load. Normal `__constant__` var in 
> device code may be changed by host code, therefore they are emitted with 
> externally_initialized and do not have the load eliminated.
Thank you @yaxunl !
I have added these observations as comments in the code at load emit and global 
emit locations.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D139730/new/

https://reviews.llvm.org/D139730

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


[PATCH] D112921: [clang] Enable sized deallocation by default in C++14 onwards

2023-08-29 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Looks like this breaks tests on windows: http://45.33.8.238/win/83485/step_7.txt

Please take a look and revert for now if it takes a while to fix.

(Also, if the patch doesn't already do it, it probably shouldn't change 
defaults in clang-cl mode?)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D112921/new/

https://reviews.llvm.org/D112921

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


[PATCH] D153156: [Clang] CWG1473: do not err on the lack of space after operator""

2023-08-29 Thread Steven Sun via Phabricator via cfe-commits
sunmy2019 added a comment.

For note: it possibly break fmtlib. https://github.com/fmtlib/fmt/issues/3607


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153156/new/

https://reviews.llvm.org/D153156

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


[clang] b63c6e5 - [NFC][Clang] Add missing & to function argument

2023-08-29 Thread Juan Manuel MARTINEZ CAAMAÑO via cfe-commits

Author: Juan Manuel MARTINEZ CAAMAÑO
Date: 2023-08-29T13:59:17+02:00
New Revision: b63c6e585d8662b67b38988f0cd38a0bd6e0d38a

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

LOG: [NFC][Clang] Add missing & to function argument

Differential Revision: https://reviews.llvm.org/D158991

Added: 


Modified: 
clang/lib/CodeGen/CGCall.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index ca31675ca4f3b8..7127bbb0450e93 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -2006,7 +2006,7 @@ static void getTrivialDefaultFunctionAttributes(
 /// though we had emitted it ourselves. We remove any attributes on F that
 /// conflict with the attributes we add here.
 static void mergeDefaultFunctionDefinitionAttributes(
-llvm::Function &F, const CodeGenOptions CodeGenOpts,
+llvm::Function &F, const CodeGenOptions &CodeGenOpts,
 const LangOptions &LangOpts, const TargetOptions &TargetOpts,
 bool WillInternalize) {
 



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


[PATCH] D158991: [NFC][Clang] Add missing & to function argument

2023-08-29 Thread Juan Manuel Martinez Caamaño via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb63c6e585d86: [NFC][Clang] Add missing & to function 
argument (authored by jmmartinez).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158991/new/

https://reviews.llvm.org/D158991

Files:
  clang/lib/CodeGen/CGCall.cpp


Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -2006,7 +2006,7 @@
 /// though we had emitted it ourselves. We remove any attributes on F that
 /// conflict with the attributes we add here.
 static void mergeDefaultFunctionDefinitionAttributes(
-llvm::Function &F, const CodeGenOptions CodeGenOpts,
+llvm::Function &F, const CodeGenOptions &CodeGenOpts,
 const LangOptions &LangOpts, const TargetOptions &TargetOpts,
 bool WillInternalize) {
 


Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -2006,7 +2006,7 @@
 /// though we had emitted it ourselves. We remove any attributes on F that
 /// conflict with the attributes we add here.
 static void mergeDefaultFunctionDefinitionAttributes(
-llvm::Function &F, const CodeGenOptions CodeGenOpts,
+llvm::Function &F, const CodeGenOptions &CodeGenOpts,
 const LangOptions &LangOpts, const TargetOptions &TargetOpts,
 bool WillInternalize) {
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D112921: [clang] Enable sized deallocation by default in C++14 onwards

2023-08-29 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

This caused some linking errors with the GPU libc test suite, see 
https://lab.llvm.org/staging/#/builders/247/builds/5659.

  clang++: error: ld.lld command failed with exit code 1 (use -v to see 
invocation)
  [331/473] Linking CXX executable 
libc/test/src/__support/libc.test.src.__support.uint_test.__hermetic__.__build__
  FAILED: 
libc/test/src/__support/libc.test.src.__support.uint_test.__hermetic__.__build__
 
  : && 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./bin/clang++
 --target=x86_64-unknown-linux-gnu -fPIC -fno-semantic-interposition 
-fvisibility-inlines-hidden -Werror=date-time 
-Werror=unguarded-availability-new -Wall -Wextra -Wno-unused-parameter 
-Wwrite-strings -Wcast-qual -Wmissing-field-initializers -Wimplicit-fallthrough 
-Wcovered-switch-default -Wno-noexcept-type -Wnon-virtual-dtor 
-Wdelete-non-virtual-dtor -Wsuggest-override -Wstring-conversion 
-Wmisleading-indentation -Wctad-maybe-unsupported -fdiagnostics-color 
-ffunction-sections -fdata-sections -O3 -DNDEBUG -Wl,--color-diagnostics
-nostdlib -static 
libc/startup/gpu/amdgpu/CMakeFiles/libc.startup.gpu.amdgpu.crt1.dir/start.cpp.o 
libc/test/src/__support/CMakeFiles/libc.test.src.__support.uint_test.__hermetic__.__build__.dir/uint_test.cpp.o
 -o 
libc/test/src/__support/libc.test.src.__support.uint_test.__hermetic__.__build__
  libc/test/UnitTest/libLibcTest.hermetic.a  
libc/test/UnitTest/libLibcHermeticTestSupport.hermetic.a  
libc/test/src/__support/liblibc.test.src.__support.uint_test.__hermetic__.libc.a
  -mcpu=gfx906  --target=amdgcn-amd-amdhsa  -flto  
-Wl,-mllvm,-amdgpu-lower-global-ctor-dtor=0 && :
  ld.lld: error: undefined symbol: operator delete(void*, unsigned long)
  >>> referenced by 
lto.tmp:(LlvmLibcUIntClassTest_ConstructorFromUInt128Tests::~LlvmLibcUIntClassTest_ConstructorFromUInt128Tests())
  >>> referenced by 
lto.tmp:(LlvmLibcUIntClassTest_ConstructorFromUInt128Tests::~LlvmLibcUIntClassTest_ConstructorFromUInt128Tests())
  >>> referenced by 
lto.tmp:(LlvmLibcUIntClassTest_BasicArithmeticInt128Tests::~LlvmLibcUIntClassTest_BasicArithmeticInt128Tests())
  >>> referenced 41 more times
  >>> did you mean: operator delete(void*)
  >>> defined in: lto.tmp
  clang++: error: ld.lld command failed with exit code 1 (use -v to see 
invocation)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D112921/new/

https://reviews.llvm.org/D112921

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


[PATCH] D153701: [Clang] Implement P2718R0 "Lifetime extension in range-based for loops"

2023-08-29 Thread Yurong via Phabricator via cfe-commits
yronglin added a comment.

friendly ping~


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153701/new/

https://reviews.llvm.org/D153701

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


[PATCH] D133361: [BPF] Attribute btf_decl_tag("ctx") for structs

2023-08-29 Thread Eduard Zingerman via Phabricator via cfe-commits
eddyz87 added inline comments.



Comment at: llvm/include/llvm/IR/Intrinsics.td:2432
   ImmArg>]>;
+def int_context_marker_bpf : DefaultAttrsIntrinsic<[llvm_ptr_ty],
+   [llvm_ptr_ty],

yonghong-song wrote:
> eddyz87 wrote:
> > yonghong-song wrote:
> > > Is it possible to make this builtin as BPF specific one?
> > Currently `llvm::Intrinsic::context_marker_bpf` gets defined in 
> > `llvm/IR/Intrinsics.h` (via include of generated file `IntrinsicEnums.inc`, 
> > same as `preserve_{struct,union,array}_access_index`).
> > 
> > BPF specific intrinsics are defined in `llvm/IR/IntrinsicsBPF.h` (generated 
> > directly w/o .inc intermediary).
> > 
> > Thus, if I move `context_marker_bpf` to `IntrinsicsBPF.td` I would have to 
> > include `IntrinsicsBPF.h` in `CGExpr.cpp`. However, I don't see any target 
> > specific includes in that file.
> > 
> I went through the related clang code and indeed found it is hard to get a 
> BPF target defined function in CGF or CGM. On the other hand, we can consider 
> this new builtin under the umbrella "Intrinsics that are used to preserve 
> debug information".  Maybe we can rename the intrinsic name
> to 'int_preserve_context_marker'? The goal of this builtin to preserve 
> certain load/store which should be immune from optimizations. I try to 
> generalize this so your function name 'wrapWithBPFContextMarker' can be 
> renamed to
> 'wrapWithContextMarker'. There is no need to mention BPF any more.
> 
> In the commit message, you can mention that
> similar to int_preserve_array_access_index, int_preserve_context_marker is 
> only implemented in BPF backend. But other architectures can implement 
> processing these intrinsics if they want to achieve some results similar to 
> bpf backend.
> 
> WDYT? 
I can rename these things, but tbh I don't think this functionality would be 
useful anywhere outside BPF, thus such renaming would be kind-of deceptive (and 
in case it would be useful, the renaming could be done at the time of second 
use).

---

Something more generic might look like `!btf_decl_tag ` metadata 
node attached to something. However, in the current form this would require 
transfer of such decl tag from type to function parameters and variables, e.g.:

```
lang=c
struct foo {  ... } __attribute__((btf_decl_tag("ctx")));
void bar(struct foo *p) { ... }
```

During code-gen for `bar` use rule like "if function parameter has type 
annotated with btf_decl_tag, attach metadata to such parameter":

```
lang=llvm
define void @bar(ptr %p !btf_decl_tag !1) { ... }
!1 = { "ctx" }
```

Such rule looks a bit weird:
- tag is transferred from type to it's usage
- what usages should be annotated? we care about function parameters but from 
generic point of view `alloca`s or field accesses should be annotated as well.

---

The same metadata approach but with "ctx" attributes annotating function 
parameters (as you suggested originally, if I recall correctly) seems to be 
most generic and least controversial of all, e.g.:

```
lang=c
void bar(struct foo *p __attribute__((btf_decl_tag("ctx" { ... }
```

Converted to:

```
lang=llvm
define void @bar(ptr %p !btf_decl_tag !1) { ... }
!1 = { "ctx" }
```

However, this is less ergonomic for BPF, because user will have to annotate 
function parameters. (On the other hand, no changes in the kernel headers would 
be necessary).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D133361/new/

https://reviews.llvm.org/D133361

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


[PATCH] D154838: [analyzer] Add check for null pointer passed to the %p of printf family

2023-08-29 Thread Georgiy Lebedev via Phabricator via cfe-commits
CuriousGeorgiy added a comment.

@steakhal

Thanks for the review comments!

> This line should be just as long, as the line above.

Fixed.

> Our docs aren't great, but we should have a brief description what the 
> checker detects, basically here it would be "Find null pointers being passed 
> to printf-like functions. Usually, passing null pointers to such functions is 
> implementation defined, thus non-portable. Printf-like functions are: x, y, 
> z." 
> Illustrate one example for diagnosing a case. Also illustrate one case 
> similar to the bad one, that is fixed (basically ensure that the pointer is 
> not null there).

Fixed. Added a generic comment about the checker collection, added a check list 
and described the printf pointer conversion specifier checker and provided TP 
and TN examples for it.

> I don't think we should create a separate package. A separate checker should 
> be enough in `alpha.unix`, or `alpha.optin`, or just `optin`.

Moved the checker to the `alpha.unix` package.

> Usually, the user-facing checker name which is the <"..."> part there, 
> matches the name of the checker's class name. It helps for maintenance.
> I would strongly suggest keeping this naming convention.

Changed the checker name to `APIPortabilityMinor`, dropping the `Unix` prefix, 
which seems redundant as it is part of the checker path.

> Usually, we put separate checkers into their own file.

Fixed.

> Prefer using the check::PreCall callback over the PreStmt.

Fixed.

> Nowdays, if I'm not mistaken, we just inline initialize these eagerly.
> That way you could also avoid marking it mutable.

Fixed.

> Feel free to just call it reportBug.

I cannot call it this way, since it is bug reporting function for the printf 
family pointer conversion specifier specific check.

> Also, in the cpp file, usually we use the namespaces clang,llvm,ento already. 
> You don't need to fully-qualify these names.

Fixed. Though, AFAIC, I still need to qualify the `register` and 
`shouldRegister` functions with the `ento` namespace, otherwise the ADL fails.

> For matching names, we usually use `CallDescriptions` to do it for us.
> If think you could use them while also checking if the Call is a 
> `CallEvent::isGlobalCFunction()`. I suspect, you only wanna check those.
> I think you should define a `CallDescriptionMap`, because you will also need 
> your specific data_arg_index...
> Look for uses of such maps and you will get inspired.

Thanks a lot for pointing this out, it looks very neat indeed, applied your 
suggestion, and the checker looks a lot cleaner now.

> I'd highly recommend not touching this file to avoid the bulk change in the 
> expected plist output. Please just introduce a new test file.

Fixed.

> I would appreciate a test demonstrating that the pointer argument won't get 
> constrained after the printf call. I think such case was already discussed.
> We should also demonstrate that unknown pointers (which doesn't known to be 
> neither null, nor non-null) won't raise issues.

Added these test cases to the 
`printf_pointer_conversion_specifier_null_pointer_constraints` test.

> In the checker-logic, we have the `data_args_index` for each printf-like 
> function.
> Can you demonstrate that each is handled as expected?

AFAIC, I have already done this in the 
`test_printf_pointer_conversion_specifier_null_various_arguments` test.

> Also have a test when the formatstring itself is null.

AFAIC, passing a null format string is already UB, so the check shouldn't 
handle this case specially. What test would you like to see?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D154838/new/

https://reviews.llvm.org/D154838

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


[PATCH] D112921: [clang] Enable sized deallocation by default in C++14 onwards

2023-08-29 Thread Wang Pengcheng via Phabricator via cfe-commits
wangpc added a comment.

In D112921#4624488 , @thakis wrote:

> Looks like this breaks tests on windows: 
> http://45.33.8.238/win/83485/step_7.txt
>
> Please take a look and revert for now if it takes a while to fix.
>
> (Also, if the patch doesn't already do it, it probably shouldn't change 
> defaults in clang-cl mode?)

The two failed cases are about `Interpreter`, which is not related to 
`clang-cl` mode I think? Is it because the windows environment doesn't support 
sized deallocation?
I don't know how to fix it, can someone help me?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D112921/new/

https://reviews.llvm.org/D112921

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


[PATCH] D112921: [clang] Enable sized deallocation by default in C++14 onwards

2023-08-29 Thread Wang Pengcheng via Phabricator via cfe-commits
wangpc added a comment.

In D112921#4624547 , @jhuber6 wrote:

> This caused some linking errors with the GPU libc test suite, see 
> https://lab.llvm.org/staging/#/builders/247/builds/5659.
>
>   clang++: error: ld.lld command failed with exit code 1 (use -v to see 
> invocation)
>   [331/473] Linking CXX executable 
> libc/test/src/__support/libc.test.src.__support.uint_test.__hermetic__.__build__
>   FAILED: 
> libc/test/src/__support/libc.test.src.__support.uint_test.__hermetic__.__build__
>  
>   : && 
> /home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./bin/clang++
>  --target=x86_64-unknown-linux-gnu -fPIC -fno-semantic-interposition 
> -fvisibility-inlines-hidden -Werror=date-time 
> -Werror=unguarded-availability-new -Wall -Wextra -Wno-unused-parameter 
> -Wwrite-strings -Wcast-qual -Wmissing-field-initializers 
> -Wimplicit-fallthrough -Wcovered-switch-default -Wno-noexcept-type 
> -Wnon-virtual-dtor -Wdelete-non-virtual-dtor -Wsuggest-override 
> -Wstring-conversion -Wmisleading-indentation -Wctad-maybe-unsupported 
> -fdiagnostics-color -ffunction-sections -fdata-sections -O3 -DNDEBUG 
> -Wl,--color-diagnostics-nostdlib -static 
> libc/startup/gpu/amdgpu/CMakeFiles/libc.startup.gpu.amdgpu.crt1.dir/start.cpp.o
>  
> libc/test/src/__support/CMakeFiles/libc.test.src.__support.uint_test.__hermetic__.__build__.dir/uint_test.cpp.o
>  -o 
> libc/test/src/__support/libc.test.src.__support.uint_test.__hermetic__.__build__
>   libc/test/UnitTest/libLibcTest.hermetic.a  
> libc/test/UnitTest/libLibcHermeticTestSupport.hermetic.a  
> libc/test/src/__support/liblibc.test.src.__support.uint_test.__hermetic__.libc.a
>   -mcpu=gfx906  --target=amdgcn-amd-amdhsa  -flto  
> -Wl,-mllvm,-amdgpu-lower-global-ctor-dtor=0 && :
>   ld.lld: error: undefined symbol: operator delete(void*, unsigned long)
>   >>> referenced by 
> lto.tmp:(LlvmLibcUIntClassTest_ConstructorFromUInt128Tests::~LlvmLibcUIntClassTest_ConstructorFromUInt128Tests())
>   >>> referenced by 
> lto.tmp:(LlvmLibcUIntClassTest_ConstructorFromUInt128Tests::~LlvmLibcUIntClassTest_ConstructorFromUInt128Tests())
>   >>> referenced by 
> lto.tmp:(LlvmLibcUIntClassTest_BasicArithmeticInt128Tests::~LlvmLibcUIntClassTest_BasicArithmeticInt128Tests())
>   >>> referenced 41 more times
>   >>> did you mean: operator delete(void*)
>   >>> defined in: lto.tmp
>   clang++: error: ld.lld command failed with exit code 1 (use -v to see 
> invocation)

It seems that the linker can't find sized deallocation (no support in the 
environment or AMDGPU libraries?).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D112921/new/

https://reviews.llvm.org/D112921

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


[PATCH] D159086: Change begin of macro in translateSourceRange in libclang

2023-08-29 Thread Christoph Busold via Phabricator via cfe-commits
quic-cbusold created this revision.
quic-cbusold added a reviewer: klimek.
Herald added a subscriber: arphaman.
Herald added a project: All.
quic-cbusold requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Currently translateSourceRange changes the end location in case of
a macro. When getting the source location for a macro invocation
it therefore returns the beginning of the macro definition with
the end of the macro invocation (with everything inbetween). This
change makes it return only the location of the macro invocation.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D159086

Files:
  clang/tools/libclang/CIndex.cpp


Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -151,11 +151,13 @@
   const CharSourceRange &R) {
   // We want the last character in this location, so we will adjust the
   // location accordingly.
+  SourceLocation BeginLoc = R.getBegin();
   SourceLocation EndLoc = R.getEnd();
   bool IsTokenRange = R.isTokenRange();
   if (EndLoc.isValid() && EndLoc.isMacroID() &&
   !SM.isMacroArgExpansion(EndLoc)) {
 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
+BeginLoc = Expansion.getBegin();
 EndLoc = Expansion.getEnd();
 IsTokenRange = Expansion.isTokenRange();
   }
@@ -166,7 +168,7 @@
   }
 
   CXSourceRange Result = {
-  {&SM, &LangOpts}, R.getBegin().getRawEncoding(), 
EndLoc.getRawEncoding()};
+  {&SM, &LangOpts}, BeginLoc.getRawEncoding(), EndLoc.getRawEncoding()};
   return Result;
 }
 


Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -151,11 +151,13 @@
   const CharSourceRange &R) {
   // We want the last character in this location, so we will adjust the
   // location accordingly.
+  SourceLocation BeginLoc = R.getBegin();
   SourceLocation EndLoc = R.getEnd();
   bool IsTokenRange = R.isTokenRange();
   if (EndLoc.isValid() && EndLoc.isMacroID() &&
   !SM.isMacroArgExpansion(EndLoc)) {
 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
+BeginLoc = Expansion.getBegin();
 EndLoc = Expansion.getEnd();
 IsTokenRange = Expansion.isTokenRange();
   }
@@ -166,7 +168,7 @@
   }
 
   CXSourceRange Result = {
-  {&SM, &LangOpts}, R.getBegin().getRawEncoding(), EndLoc.getRawEncoding()};
+  {&SM, &LangOpts}, BeginLoc.getRawEncoding(), EndLoc.getRawEncoding()};
   return Result;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D159068: [clang][X86] Update excessive register save diagnostic to more closely follow the interrupt attribute spec

2023-08-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman edited reviewers, added: pengfei; removed: mibintc.
aaron.ballman added a comment.

Changing the reviewers up a bit; the changes generally seem reasonable to me, 
but I'd appreciate some x86 reviewer viewpoints.




Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:317
+  " with attribute 'no_caller_saved_registers'"
+  " or be compiled with '-mgeneral-regs-only'">,
+  InGroup>;

Can you add a test case showing that `-mgeneral-regs-only` causes the 
diagnostic to be silenced?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159068/new/

https://reviews.llvm.org/D159068

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


[PATCH] D112921: [clang] Enable sized deallocation by default in C++14 onwards

2023-08-29 Thread Wang Pengcheng via Phabricator via cfe-commits
wangpc added a comment.

In D112921#4624141 , @nikic wrote:

> FYI this resulted in some pretty wild code size swings, in particular between 
> -10% and -15% for tramp3d-v4 
> (http://llvm-compile-time-tracker.com/compare.php?from=6cde64a94986165547ae5237ac7dd4bddfc9f2a7&to=2916b125f686115deab2ba573dcaff3847566ab9&stat=size-text).
>  Not sure whether that's an expected result of this change or not.

I'm surprised. From the tests diff in this patch, it should increase code size 
I think.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D112921/new/

https://reviews.llvm.org/D112921

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


[PATCH] D158995: [clang] Add a Windows build in the Clang pre-commit CI

2023-08-29 Thread Louis Dionne via Phabricator via cfe-commits
ldionne updated this revision to Diff 554277.
ldionne added a comment.

Don't upload the Windows build artifacts cause we don't use them and it fails.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158995/new/

https://reviews.llvm.org/D158995

Files:
  clang/utils/ci/buildkite-pipeline.yml
  clang/utils/ci/run-buildbot


Index: clang/utils/ci/run-buildbot
===
--- clang/utils/ci/run-buildbot
+++ clang/utils/ci/run-buildbot
@@ -95,6 +95,21 @@
 
 ninja -C ${BUILD_DIR} check-clang
 ;;
+build-clang-windows)
+cmake -S llvm -B ${BUILD_DIR} -G Ninja 
 \
+-D CMAKE_C_COMPILER_LAUNCHER=sccache   
 \
+-D CMAKE_CXX_COMPILER_LAUNCHER=sccache 
 \
+-D CMAKE_BUILD_TYPE=Release
 \
+-D CMAKE_INSTALL_PREFIX=install-windows
 \
+-D LLVM_ENABLE_PROJECTS="clang;compiler-rt"
 \
+-D LLVM_ENABLE_ASSERTIONS=ON   
 \
+-D LLVM_BUILD_EXAMPLES=ON  
 \
+-D COMPILER_RT_BUILD_LIBFUZZER=OFF 
 \
+-D COMPILER_RT_BUILD_ORC=OFF
+
+ninja -C ${BUILD_DIR} install-clang install-clang-resource-headers
+ninja -C ${BUILD_DIR} check-clang
+;;
 generic-cxx03)
 buildkite-agent artifact download install.tar.xz .
 tar -xvf install.tar.xz
Index: clang/utils/ci/buildkite-pipeline.yml
===
--- clang/utils/ci/buildkite-pipeline.yml
+++ clang/utils/ci/buildkite-pipeline.yml
@@ -31,7 +31,7 @@
 
   - wait
 
-  - label: "Building and testing clang"
+  - label: "Building and testing clang (Linux)"
 commands:
   - "clang/utils/ci/run-buildbot build-clang"
 agents:
@@ -42,6 +42,18 @@
   limit: 2
 timeout_in_minutes: 120
 
+  - label: "Building and testing clang (Windows)"
+commands:
+  - "C:\\BuildTools\\Common7\\Tools\\VsDevCmd.bat -arch=amd64 
-host_arch=amd64"
+  - "bash clang/utils/ci/run-buildbot build-clang-windows"
+agents:
+  queue: "windows"
+retry:
+  automatic:
+- exit_status: -1  # Agent was lost
+  limit: 2
+timeout_in_minutes: 120
+
   - wait
 
   - label: "Running libc++ test suite in C++03"


Index: clang/utils/ci/run-buildbot
===
--- clang/utils/ci/run-buildbot
+++ clang/utils/ci/run-buildbot
@@ -95,6 +95,21 @@
 
 ninja -C ${BUILD_DIR} check-clang
 ;;
+build-clang-windows)
+cmake -S llvm -B ${BUILD_DIR} -G Ninja  \
+-D CMAKE_C_COMPILER_LAUNCHER=sccache\
+-D CMAKE_CXX_COMPILER_LAUNCHER=sccache  \
+-D CMAKE_BUILD_TYPE=Release \
+-D CMAKE_INSTALL_PREFIX=install-windows \
+-D LLVM_ENABLE_PROJECTS="clang;compiler-rt" \
+-D LLVM_ENABLE_ASSERTIONS=ON\
+-D LLVM_BUILD_EXAMPLES=ON   \
+-D COMPILER_RT_BUILD_LIBFUZZER=OFF  \
+-D COMPILER_RT_BUILD_ORC=OFF
+
+ninja -C ${BUILD_DIR} install-clang install-clang-resource-headers
+ninja -C ${BUILD_DIR} check-clang
+;;
 generic-cxx03)
 buildkite-agent artifact download install.tar.xz .
 tar -xvf install.tar.xz
Index: clang/utils/ci/buildkite-pipeline.yml
===
--- clang/utils/ci/buildkite-pipeline.yml
+++ clang/utils/ci/buildkite-pipeline.yml
@@ -31,7 +31,7 @@
 
   - wait
 
-  - label: "Building and testing clang"
+  - label: "Building and testing clang (Linux)"
 commands:
   - "clang/utils/ci/run-buildbot build-clang"
 agents:
@@ -42,6 +42,18 @@
   limit: 2
 timeout_in_minutes: 120
 
+  - label: "Building and testing clang (Windows)"
+commands:
+  - "C:\\BuildTools\\Common7\\Tools\\VsDevCmd.bat -arch=amd64 -host_arch=amd64"
+  - "bash clang/utils/ci/run-buildbot build-clang-windows"
+agents:
+  queue: "windows"
+retry:
+  automatic:
+- exit_status: -1  # Agent was lost
+  limit: 2
+timeout_in_minutes: 120
+
   - wait
 
   - label: "Running libc++ test suite in C++03"
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D133361: [BPF] Attribute btf_decl_tag("ctx") for structs

2023-08-29 Thread Yonghong Song via Phabricator via cfe-commits
yonghong-song added a comment.

> I can rename these things, but tbh I don't think this functionality would be 
> useful anywhere outside BPF, thus such renaming would be kind-of deceptive 
> (and in case it would be useful, the renaming could be done at the time of 
> second use).

Then let us keep this for now. We can decide what to do after clang frontend 
people reviewed this code.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D133361/new/

https://reviews.llvm.org/D133361

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


[PATCH] D112921: [clang] Enable sized deallocation by default in C++14 onwards

2023-08-29 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a subscriber: sivachandra.
jhuber6 added a comment.

In D112921#4624580 , @wangpc wrote:

> It seems that the linker can't find sized deallocation (no support in the 
> environment or AMDGPU libraries?).

We should have some implementations here I thought 
https://github.com/llvm/llvm-project/blob/main/libc/src/__support/CPP/new.cpp, 
maybe @sivachandra can elucidate on that. I actually don't know what the 
expected behavior is here, since we don't really have any of this support on 
GPU targets. I'm wondering why we're currently fine with compiling `delete` but 
not with the sized version, since their definitions should both be present in 
that file.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D112921/new/

https://reviews.llvm.org/D112921

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


[PATCH] D158967: [clangd] Record the stack bottom before building AST

2023-08-29 Thread Younan Zhang via Phabricator via cfe-commits
zyounan updated this revision to Diff 554279.
zyounan added a comment.
Herald added a project: clang.

Adopt the comments.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158967/new/

https://reviews.llvm.org/D158967

Files:
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/support/Threading.cpp
  clang-tools-extra/clangd/test/infinite-instantiation.test
  clang-tools-extra/clangd/tool/Check.cpp
  clang/lib/Frontend/FrontendAction.cpp

Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -15,6 +15,7 @@
 #include "clang/Basic/FileEntry.h"
 #include "clang/Basic/LangStandard.h"
 #include "clang/Basic/Sarif.h"
+#include "clang/Basic/Stack.h"
 #include "clang/Frontend/ASTUnit.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
@@ -1054,6 +1055,11 @@
 }
 
 llvm::Error FrontendAction::Execute() {
+  // This is a fallback: If the client forgets to invoke this, we mark the
+  // current stack as the bottom. Though not optimal, this could help prevent
+  // stack overflow during deep recursion.
+  clang::noteBottomOfStack();
+
   CompilerInstance &CI = getCompilerInstance();
 
   if (CI.hasFrontendTimer()) {
Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clangd/tool/Check.cpp
@@ -57,6 +57,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/LLVM.h"
+#include "clang/Basic/Stack.h"
 #include "clang/Format/Format.h"
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Tooling/CompilationDatabase.h"
@@ -441,6 +442,7 @@
 
 bool check(llvm::StringRef File, const ThreadsafeFS &TFS,
const ClangdLSPServer::Options &Opts) {
+  clang::noteBottomOfStack();
   std::optional LineRange;
   if (!CheckFileLines.empty()) {
 uint32_t Begin = 0, End = std::numeric_limits::max();
Index: clang-tools-extra/clangd/test/infinite-instantiation.test
===
--- /dev/null
+++ clang-tools-extra/clangd/test/infinite-instantiation.test
@@ -0,0 +1,13 @@
+// RUN: cp %s %t.cpp
+// RUN: not clangd -check=%t.cpp 2>&1 | FileCheck -strict-whitespace %s
+
+// CHECK: [template_recursion_depth_exceeded]
+
+template 
+constexpr int f(T... args) {
+  return f(0, args...);
+}
+
+int main() {
+  auto i = f();
+}
Index: clang-tools-extra/clangd/support/Threading.cpp
===
--- clang-tools-extra/clangd/support/Threading.cpp
+++ clang-tools-extra/clangd/support/Threading.cpp
@@ -8,6 +8,7 @@
 
 #include "support/Threading.h"
 #include "support/Trace.h"
+#include "clang/Basic/Stack.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/Support/Threading.h"
 #include "llvm/Support/thread.h"
@@ -98,6 +99,9 @@
   auto Task = [Name = Name.str(), Action = std::move(Action),
Cleanup = std::move(CleanupTask)]() mutable {
 llvm::set_thread_name(Name);
+// Mark the bottom of the stack for clang to be aware of the stack usage and
+// prevent stack overflow.
+clang::noteBottomOfStack();
 Action();
 // Make sure function stored by ThreadFunc is destroyed before Cleanup runs.
 Action = nullptr;
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ -44,6 +44,7 @@
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Basic/Stack.h"
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/CompilerInvocation.h"
@@ -388,6 +389,7 @@
  std::unique_ptr CI,
  llvm::ArrayRef CompilerInvocationDiags,
  std::shared_ptr Preamble) {
+  clang::noteBottomOfStack();
   trace::Span Tracer("BuildAST");
   SPAN_ATTACH(Tracer, "File", Filename);
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D156565: Diagnose use of VLAs in C++ by default

2023-08-29 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

In D156565#4605027 , @shafik wrote:

> In D156565#4599812 , @aaron.ballman 
> wrote:
>
>> Enable the diagnostic by default in C++ language modes, and under -Wall in 
>> GNU++ language modes.
>
> I am happy with that approach.

Ditto! Some of the GCC folks also expressed a desire for this direction on 
their side.
Given that, and how surprising VLAs can be to c++ folks, It seems reasonable to 
go ahead with this patch


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D156565/new/

https://reviews.llvm.org/D156565

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


[PATCH] D158967: [clangd] Record the stack bottom before building AST

2023-08-29 Thread Younan Zhang via Phabricator via cfe-commits
zyounan updated this revision to Diff 554283.
zyounan added a comment.

.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158967/new/

https://reviews.llvm.org/D158967

Files:
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/support/Threading.cpp
  clang-tools-extra/clangd/test/infinite-instantiation.test
  clang-tools-extra/clangd/tool/Check.cpp
  clang/lib/Frontend/FrontendAction.cpp

Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -15,6 +15,7 @@
 #include "clang/Basic/FileEntry.h"
 #include "clang/Basic/LangStandard.h"
 #include "clang/Basic/Sarif.h"
+#include "clang/Basic/Stack.h"
 #include "clang/Frontend/ASTUnit.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
@@ -1155,6 +1156,10 @@
   CompilerInstance &CI = getCompilerInstance();
   if (!CI.hasPreprocessor())
 return;
+  // This is a fallback: If the client forgets to invoke this, we mark the
+  // current stack as the bottom. Though not optimal, this could help prevent
+  // stack overflow during deep recursion.
+  clang::noteBottomOfStack();
 
   // FIXME: Move the truncation aspect of this into Sema, we delayed this till
   // here so the source manager would be initialized.
Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clangd/tool/Check.cpp
@@ -57,6 +57,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/LLVM.h"
+#include "clang/Basic/Stack.h"
 #include "clang/Format/Format.h"
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Tooling/CompilationDatabase.h"
@@ -441,6 +442,7 @@
 
 bool check(llvm::StringRef File, const ThreadsafeFS &TFS,
const ClangdLSPServer::Options &Opts) {
+  clang::noteBottomOfStack();
   std::optional LineRange;
   if (!CheckFileLines.empty()) {
 uint32_t Begin = 0, End = std::numeric_limits::max();
Index: clang-tools-extra/clangd/test/infinite-instantiation.test
===
--- /dev/null
+++ clang-tools-extra/clangd/test/infinite-instantiation.test
@@ -0,0 +1,13 @@
+// RUN: cp %s %t.cpp
+// RUN: not clangd -check=%t.cpp 2>&1 | FileCheck -strict-whitespace %s
+
+// CHECK: [template_recursion_depth_exceeded]
+
+template 
+constexpr int f(T... args) {
+  return f(0, args...);
+}
+
+int main() {
+  auto i = f();
+}
Index: clang-tools-extra/clangd/support/Threading.cpp
===
--- clang-tools-extra/clangd/support/Threading.cpp
+++ clang-tools-extra/clangd/support/Threading.cpp
@@ -8,6 +8,7 @@
 
 #include "support/Threading.h"
 #include "support/Trace.h"
+#include "clang/Basic/Stack.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/Support/Threading.h"
 #include "llvm/Support/thread.h"
@@ -98,6 +99,9 @@
   auto Task = [Name = Name.str(), Action = std::move(Action),
Cleanup = std::move(CleanupTask)]() mutable {
 llvm::set_thread_name(Name);
+// Mark the bottom of the stack for clang to be aware of the stack usage and
+// prevent stack overflow.
+clang::noteBottomOfStack();
 Action();
 // Make sure function stored by ThreadFunc is destroyed before Cleanup runs.
 Action = nullptr;
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ -44,6 +44,7 @@
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Basic/Stack.h"
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/CompilerInvocation.h"
@@ -388,6 +389,7 @@
  std::unique_ptr CI,
  llvm::ArrayRef CompilerInvocationDiags,
  std::shared_ptr Preamble) {
+  clang::noteBottomOfStack();
   trace::Span Tracer("BuildAST");
   SPAN_ATTACH(Tracer, "File", Filename);
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D159083: Clang: Don't warn about unused private fields of types declared maybe_unused

2023-08-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Thank you for working on this! Mostly looks good, but I did have another test 
request. Also, please be sure to add a release note for the fix.




Comment at: clang/test/SemaCXX/warn-unused-private-field.cpp:291-292
+enum [[maybe_unused]] MaybeUnusedEnum {};
+typedef int MaybeUnusedTypedef [[maybe_unused]];
+class C {
+  MaybeUnusedClass c; // no-warning

Let's try one more thing:
```
template 
class C2 {
  Ty c; // no-warning
  Uy d; // warning
};

class [[maybe_unused]] Good {};
class Bad {};

C2 c;
```


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159083/new/

https://reviews.llvm.org/D159083

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


[PATCH] D158967: [clang][clangd] Ensure the stack bottom before building AST

2023-08-29 Thread Younan Zhang via Phabricator via cfe-commits
zyounan added a comment.

@ilya-biryukov I've updated the patch following your suggestion. PTAL, thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158967/new/

https://reviews.llvm.org/D158967

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


[PATCH] D112921: [clang] Enable sized deallocation by default in C++14 onwards

2023-08-29 Thread Mikael Holmén via Phabricator via cfe-commits
uabelho added a comment.

I've no idea what's happening but it seems like linking 
compiler-rt/lib/memprof/tests/MemProfUnitTests fails with this commit:

  [17/17] Linking CXX executable compiler-rt/lib/memprof/tests/MemProfUnitTests
  FAILED: compiler-rt/lib/memprof/tests/MemProfUnitTests 
  : && /repo/uabelho/dev-main/llvm/build-all-builtins/./bin/clang++ 
--target=x86_64-unknown-linux-gnu [...] 
compiler-rt/lib/memprof/tests/MemProfUnitTests  -lstdc++  -ldl && :
  clang++: error: unable to execute command: Segmentation fault (core dumped)
  clang++: error: linker command failed due to signal (use -v to see invocation)
  ninja: build stopped: subcommand failed.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D112921/new/

https://reviews.llvm.org/D112921

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


[PATCH] D158967: [clang][clangd] Ensure the stack bottom before building AST

2023-08-29 Thread Younan Zhang via Phabricator via cfe-commits
zyounan updated this revision to Diff 554285.
zyounan added a comment.

Oops, something went wrong accidently.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158967/new/

https://reviews.llvm.org/D158967

Files:
  clang-tools-extra/clangd/support/Threading.cpp
  clang-tools-extra/clangd/test/infinite-instantiation.test
  clang-tools-extra/clangd/tool/Check.cpp
  clang/lib/Frontend/FrontendAction.cpp


Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -15,6 +15,7 @@
 #include "clang/Basic/FileEntry.h"
 #include "clang/Basic/LangStandard.h"
 #include "clang/Basic/Sarif.h"
+#include "clang/Basic/Stack.h"
 #include "clang/Frontend/ASTUnit.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
@@ -1155,6 +1156,10 @@
   CompilerInstance &CI = getCompilerInstance();
   if (!CI.hasPreprocessor())
 return;
+  // This is a fallback: If the client forgets to invoke this, we mark the
+  // current stack as the bottom. Though not optimal, this could help prevent
+  // stack overflow during deep recursion.
+  clang::noteBottomOfStack();
 
   // FIXME: Move the truncation aspect of this into Sema, we delayed this till
   // here so the source manager would be initialized.
Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clangd/tool/Check.cpp
@@ -57,6 +57,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/LLVM.h"
+#include "clang/Basic/Stack.h"
 #include "clang/Format/Format.h"
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Tooling/CompilationDatabase.h"
@@ -441,6 +442,7 @@
 
 bool check(llvm::StringRef File, const ThreadsafeFS &TFS,
const ClangdLSPServer::Options &Opts) {
+  clang::noteBottomOfStack();
   std::optional LineRange;
   if (!CheckFileLines.empty()) {
 uint32_t Begin = 0, End = std::numeric_limits::max();
Index: clang-tools-extra/clangd/test/infinite-instantiation.test
===
--- /dev/null
+++ clang-tools-extra/clangd/test/infinite-instantiation.test
@@ -0,0 +1,13 @@
+// RUN: cp %s %t.cpp
+// RUN: not clangd -check=%t.cpp 2>&1 | FileCheck -strict-whitespace %s
+
+// CHECK: [template_recursion_depth_exceeded]
+
+template 
+constexpr int f(T... args) {
+  return f(0, args...);
+}
+
+int main() {
+  auto i = f();
+}
Index: clang-tools-extra/clangd/support/Threading.cpp
===
--- clang-tools-extra/clangd/support/Threading.cpp
+++ clang-tools-extra/clangd/support/Threading.cpp
@@ -8,6 +8,7 @@
 
 #include "support/Threading.h"
 #include "support/Trace.h"
+#include "clang/Basic/Stack.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/Support/Threading.h"
 #include "llvm/Support/thread.h"
@@ -98,6 +99,9 @@
   auto Task = [Name = Name.str(), Action = std::move(Action),
Cleanup = std::move(CleanupTask)]() mutable {
 llvm::set_thread_name(Name);
+// Mark the bottom of the stack for clang to be aware of the stack usage 
and
+// prevent stack overflow.
+clang::noteBottomOfStack();
 Action();
 // Make sure function stored by ThreadFunc is destroyed before Cleanup 
runs.
 Action = nullptr;


Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -15,6 +15,7 @@
 #include "clang/Basic/FileEntry.h"
 #include "clang/Basic/LangStandard.h"
 #include "clang/Basic/Sarif.h"
+#include "clang/Basic/Stack.h"
 #include "clang/Frontend/ASTUnit.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
@@ -1155,6 +1156,10 @@
   CompilerInstance &CI = getCompilerInstance();
   if (!CI.hasPreprocessor())
 return;
+  // This is a fallback: If the client forgets to invoke this, we mark the
+  // current stack as the bottom. Though not optimal, this could help prevent
+  // stack overflow during deep recursion.
+  clang::noteBottomOfStack();
 
   // FIXME: Move the truncation aspect of this into Sema, we delayed this till
   // here so the source manager would be initialized.
Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clangd/tool/Check.cpp
@@ -57,6 +57,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/LLVM.h"
+#include "clang/Basic/Stack.h"
 #include "clang/Format/Format.h"
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Tooling/CompilationData

[PATCH] D112921: [clang] Enable sized deallocation by default in C++14 onwards

2023-08-29 Thread Tom Weaver via Phabricator via cfe-commits
TWeaver added a comment.

Good afternoon from the UK!

It looks as though this change has caused the following buildbot to start 
failing:

https://lab.llvm.org/buildbot/#/builders/216/builds/26407

are you able to take a look?

Thanks in advance,
Tom W


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D112921/new/

https://reviews.llvm.org/D112921

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


[PATCH] D112921: [clang] Enable sized deallocation by default in C++14 onwards

2023-08-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Because the issues have been ongoing for a few hours now, I think it'd make 
sense to revert these changes while trying to determine what the appropriate 
fix is. @wangpc would you mind doing the revert?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D112921/new/

https://reviews.llvm.org/D112921

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


[PATCH] D159018: [clang][modules] Add a c23 module feature

2023-08-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

In D159018#4623880 , @v.g.vassilev 
wrote:

> LGTM!
>
> In D159018#4622598 , @iana wrote:
>
>> Would we want to back port this to llvm 17?
>
> Yes probably.

I believe we're only backporting critical fixes or fixes for regressions at 
this point, so I don't think we should try to backport this one right now.

That said, the changes LGTM!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159018/new/

https://reviews.llvm.org/D159018

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


[PATCH] D152752: [MS] Fix passing aligned records by value in some cases

2023-08-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D152752#4611206 , @aaron.ballman 
wrote:

> In D152752#4611043 , @rnk wrote:
>
>> Thanks, I think this is a clang bug. As I understand MSVC's behavior, we 
>> should not pass highly aligned variadic arguments indirectly: 
>> https://gcc.godbolt.org/z/Kr67xWTeE
>>
>> I'll follow up on that.
>
> Thank you!

Any update on a fix for this?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D152752/new/

https://reviews.llvm.org/D152752

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


[PATCH] D158995: [clang] Add a Windows build in the Clang pre-commit CI

2023-08-29 Thread Louis Dionne via Phabricator via cfe-commits
ldionne updated this revision to Diff 554295.
ldionne added a comment.

Poke CI -- Phabricator keeps timing out.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158995/new/

https://reviews.llvm.org/D158995

Files:
  clang/utils/ci/buildkite-pipeline.yml
  clang/utils/ci/run-buildbot


Index: clang/utils/ci/run-buildbot
===
--- clang/utils/ci/run-buildbot
+++ clang/utils/ci/run-buildbot
@@ -95,6 +95,21 @@
 
 ninja -C ${BUILD_DIR} check-clang
 ;;
+build-clang-windows)
+cmake -S llvm -B ${BUILD_DIR} -G Ninja 
 \
+-D CMAKE_C_COMPILER_LAUNCHER=sccache   
 \
+-D CMAKE_CXX_COMPILER_LAUNCHER=sccache 
 \
+-D CMAKE_BUILD_TYPE=Release
 \
+-D CMAKE_INSTALL_PREFIX=install-windows
 \
+-D LLVM_ENABLE_PROJECTS="clang;compiler-rt"
 \
+-D LLVM_ENABLE_ASSERTIONS=ON   
 \
+-D LLVM_BUILD_EXAMPLES=ON  
 \
+-D COMPILER_RT_BUILD_LIBFUZZER=OFF 
 \
+-D COMPILER_RT_BUILD_ORC=OFF
+
+ninja -C ${BUILD_DIR} install-clang install-clang-resource-headers
+ninja -C ${BUILD_DIR} check-clang
+;;
 generic-cxx03)
 buildkite-agent artifact download install.tar.xz .
 tar -xvf install.tar.xz
Index: clang/utils/ci/buildkite-pipeline.yml
===
--- clang/utils/ci/buildkite-pipeline.yml
+++ clang/utils/ci/buildkite-pipeline.yml
@@ -31,7 +31,7 @@
 
   - wait
 
-  - label: "Building and testing clang"
+  - label: "Building and testing clang (Linux)"
 commands:
   - "clang/utils/ci/run-buildbot build-clang"
 agents:
@@ -42,6 +42,18 @@
   limit: 2
 timeout_in_minutes: 120
 
+  - label: "Building and testing clang (Windows)"
+commands:
+  - "C:\\BuildTools\\Common7\\Tools\\VsDevCmd.bat -arch=amd64 
-host_arch=amd64"
+  - "bash clang/utils/ci/run-buildbot build-clang-windows"
+agents:
+  queue: "windows"
+retry:
+  automatic:
+- exit_status: -1  # Agent was lost
+  limit: 2
+timeout_in_minutes: 120
+
   - wait
 
   - label: "Running libc++ test suite in C++03"


Index: clang/utils/ci/run-buildbot
===
--- clang/utils/ci/run-buildbot
+++ clang/utils/ci/run-buildbot
@@ -95,6 +95,21 @@
 
 ninja -C ${BUILD_DIR} check-clang
 ;;
+build-clang-windows)
+cmake -S llvm -B ${BUILD_DIR} -G Ninja  \
+-D CMAKE_C_COMPILER_LAUNCHER=sccache\
+-D CMAKE_CXX_COMPILER_LAUNCHER=sccache  \
+-D CMAKE_BUILD_TYPE=Release \
+-D CMAKE_INSTALL_PREFIX=install-windows \
+-D LLVM_ENABLE_PROJECTS="clang;compiler-rt" \
+-D LLVM_ENABLE_ASSERTIONS=ON\
+-D LLVM_BUILD_EXAMPLES=ON   \
+-D COMPILER_RT_BUILD_LIBFUZZER=OFF  \
+-D COMPILER_RT_BUILD_ORC=OFF
+
+ninja -C ${BUILD_DIR} install-clang install-clang-resource-headers
+ninja -C ${BUILD_DIR} check-clang
+;;
 generic-cxx03)
 buildkite-agent artifact download install.tar.xz .
 tar -xvf install.tar.xz
Index: clang/utils/ci/buildkite-pipeline.yml
===
--- clang/utils/ci/buildkite-pipeline.yml
+++ clang/utils/ci/buildkite-pipeline.yml
@@ -31,7 +31,7 @@
 
   - wait
 
-  - label: "Building and testing clang"
+  - label: "Building and testing clang (Linux)"
 commands:
   - "clang/utils/ci/run-buildbot build-clang"
 agents:
@@ -42,6 +42,18 @@
   limit: 2
 timeout_in_minutes: 120
 
+  - label: "Building and testing clang (Windows)"
+commands:
+  - "C:\\BuildTools\\Common7\\Tools\\VsDevCmd.bat -arch=amd64 -host_arch=amd64"
+  - "bash clang/utils/ci/run-buildbot build-clang-windows"
+agents:
+  queue: "windows"
+retry:
+  automatic:
+- exit_status: -1  # Agent was lost
+  limit: 2
+timeout_in_minutes: 120
+
   - wait
 
   - label: "Running libc++ test suite in C++03"
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153690: [clang][Sema] Remove dead diagnostic for loss of __unaligned qualifier

2023-08-29 Thread Michael Jabbour via Phabricator via cfe-commits
michael-jabbour-sonarsource added a comment.

The removal of the early return in this patch causes a crash when parsing the 
following example:

  struct S {
bool operator==(int) const;
  };
  
  void func() {
S __unaligned s;
s == 42;
  }

See this Compiler Explorer link with a stacktrace: 
https://godbolt.org/z/4Mcd3crq1.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153690/new/

https://reviews.llvm.org/D153690

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


[PATCH] D159090: [clang][dataflow][NFC] Remove obsolete references to `ReferenceValue` from comments.

2023-08-29 Thread Martin Böhme via Phabricator via cfe-commits
mboehme created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
mboehme requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

`ReferenceValue` was removed in https://reviews.llvm.org/D155922.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D159090

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/include/clang/Analysis/FlowSensitive/Value.h
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp


Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -153,9 +153,9 @@
 
 // Regression test for joins of bool-typed lvalue expressions. The first loop
 // results in two passes through the code that follows. Each pass results in a
-// different `ReferenceValue` for the pointee of `v`. Then, the second loop
+// different `StorageLocation` for the pointee of `v`. Then, the second loop
 // causes a join at the loop head where the two environments map expresssion
-// `*v` to different `ReferenceValue`s.
+// `*v` to different `StorageLocation`s.
 //
 // An earlier version crashed for this condition (for boolean-typed lvalues), 
so
 // this test only verifies that the analysis runs successfully, without
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -276,8 +276,7 @@
 
 case CK_LValueToRValue: {
   // When an L-value is used as an R-value, it may result in sharing, so we
-  // need to unpack any nested `Top`s. We also need to strip off the
-  // `ReferenceValue` associated with the lvalue.
+  // need to unpack any nested `Top`s.
   auto *SubExprVal = maybeUnpackLValueExpr(*SubExpr, Env);
   if (SubExprVal == nullptr)
 break;
Index: clang/include/clang/Analysis/FlowSensitive/Value.h
===
--- clang/include/clang/Analysis/FlowSensitive/Value.h
+++ clang/include/clang/Analysis/FlowSensitive/Value.h
@@ -83,8 +83,8 @@
 /// transitivity. It does *not* include comparison of `Properties`.
 ///
 /// Computes equivalence for these subclasses:
-/// * ReferenceValue, PointerValue -- pointee locations are equal. Does not
-///   compute deep equality of `Value` at said location.
+/// * PointerValue -- pointee locations are equal. Does not compute deep
+///   equality of `Value` at said location.
 /// * TopBoolValue -- both are `TopBoolValue`s.
 ///
 /// Otherwise, falls back to pointer equality.
Index: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -254,17 +254,10 @@
   /// Requirements:
   ///
   ///  `D` must not already have a storage location in the environment.
-  ///
-  ///  If `D` has reference type, `Loc` must refer directly to the referenced
-  ///  object (if any), not to a `ReferenceValue`, and it is not permitted to
-  ///  later change `Loc` to refer to a `ReferenceValue.`
   void setStorageLocation(const ValueDecl &D, StorageLocation &Loc);
 
   /// Returns the storage location assigned to `D` in the environment, or null
   /// if `D` isn't assigned a storage location in the environment.
-  ///
-  /// Note that if `D` has reference type, the storage location that is 
returned
-  /// refers directly to the referenced object, not a `ReferenceValue`.
   StorageLocation *getStorageLocation(const ValueDecl &D) const;
 
   /// Assigns `Loc` as the storage location of the glvalue `E` in the
@@ -280,9 +273,6 @@
   /// environment, or null if `E` isn't assigned a storage location in the
   /// environment.
   ///
-  /// If the storage location for `E` is associated with a
-  /// `ReferenceValue RefVal`, returns `RefVal.getReferentLoc()` instead.
-  ///
   /// Requirements:
   ///  `E` must be a glvalue or a `BuiltinType::BuiltinFn`
   StorageLocation *getStorageLocation(const Expr &E) const;
@@ -437,7 +427,6 @@
   /// Requirements:
   ///
   ///  `E` must be a prvalue
-  ///  `Val` must not be a `ReferenceValue`
   ///  If `Val` is a `RecordValue`, its `RecordStorageLocation` must be the
   ///  same as that of any `RecordValue` that has already been associated with
   ///  `E`. This is to guarantee that the result object initialized by a 
prvalue


Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
==

[PATCH] D112921: [clang] Enable sized deallocation by default in C++14 onwards

2023-08-29 Thread Wang Pengcheng via Phabricator via cfe-commits
wangpc added a comment.

In D112921#4624674 , @aaron.ballman 
wrote:

> Because the issues have been ongoing for a few hours now, I think it'd make 
> sense to revert these changes while trying to determine what the appropriate 
> fix is. @wangpc would you mind doing the revert?

Yeah I think we should. Can you revert it for me? I am away from my computer 
now.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D112921/new/

https://reviews.llvm.org/D112921

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


[clang-tools-extra] a02f9a7 - Revert "[clang] Enable sized deallocation by default in C++14 onwards"

2023-08-29 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2023-08-29T09:36:59-04:00
New Revision: a02f9a7756e5e4c76b422f9948d5dc3f56a1d139

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

LOG: Revert "[clang] Enable sized deallocation by default in C++14 onwards"

This reverts commit 2916b125f686115deab2ba573dcaff3847566ab9.

Reverting due to failures on:
https://lab.llvm.org/buildbot/#/builders/216/builds/26407
https://lab.llvm.org/staging/#/builders/247/builds/5659
http://45.33.8.238/win/83485/step_7.txt

Added: 


Modified: 
clang-tools-extra/clangd/unittests/FindTargetTests.cpp
clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp
clang/docs/ReleaseNotes.rst
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/Darwin.cpp
clang/lib/Driver/ToolChains/Darwin.h
clang/lib/Driver/ToolChains/ZOS.cpp
clang/test/AST/ast-dump-expr-json.cpp
clang/test/AST/ast-dump-expr.cpp
clang/test/AST/ast-dump-stmt-json.cpp
clang/test/Analysis/cxxnewexpr-callback.cpp

clang/test/CXX/basic/basic.stc/basic.stc.dynamic/basic.stc.dynamic.deallocation/p2.cpp
clang/test/CXX/expr/expr.unary/expr.new/p14.cpp
clang/test/CodeGenCXX/cxx1y-sized-deallocation.cpp
clang/test/CodeGenCXX/cxx1z-aligned-allocation.cpp
clang/test/CodeGenCXX/cxx2a-destroying-delete.cpp
clang/test/CodeGenCXX/delete-two-arg.cpp
clang/test/CodeGenCXX/delete.cpp
clang/test/CodeGenCXX/dllimport.cpp
clang/test/CodeGenCXX/new.cpp
clang/test/CodeGenCoroutines/coro-aligned-alloc-2.cpp
clang/test/CodeGenCoroutines/coro-aligned-alloc.cpp
clang/test/CodeGenCoroutines/coro-alloc.cpp
clang/test/CodeGenCoroutines/coro-cleanup.cpp
clang/test/CodeGenCoroutines/coro-dealloc.cpp
clang/test/CodeGenCoroutines/coro-gro.cpp
clang/test/CodeGenCoroutines/pr56919.cpp
clang/test/Lexer/cxx-features.cpp
clang/test/PCH/cxx1z-aligned-alloc.cpp
clang/test/SemaCXX/MicrosoftExtensions.cpp
clang/test/SemaCXX/builtin-operator-new-delete.cpp
clang/test/SemaCXX/cxx1y-sized-deallocation.cpp
clang/test/SemaCXX/unavailable_aligned_allocation.cpp
clang/unittests/StaticAnalyzer/CallEventTest.cpp
clang/www/cxx_status.html
libcxx/test/libcxx/language.support/support.dynamic/libcpp_deallocate.sh.cpp

libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.array/sized_delete_array14.pass.cpp

libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.single/sized_delete14.pass.cpp

Removed: 
clang/include/clang/Basic/SizedDeallocation.h



diff  --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp 
b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
index 56cf6da70965ba..19e80658de063c 100644
--- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -812,9 +812,7 @@ TEST_F(TargetDeclTest, OverloadExpr) {
   [[delete]] x;
 }
   )cpp";
-  // Sized deallocation is enabled by default in C++14 onwards.
-  EXPECT_DECLS("CXXDeleteExpr",
-   "void operator delete(void *, unsigned long) noexcept");
+  EXPECT_DECLS("CXXDeleteExpr", "void operator delete(void *) noexcept");
 }
 
 TEST_F(TargetDeclTest, DependentExprs) {

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp
index f86fe8a4c5b14f..78f021144b2e19 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp
@@ -12,6 +12,16 @@ struct S {
 // CHECK-MESSAGES: :[[@LINE+1]]:7: warning: declaration of 'operator new' has 
no matching declaration of 'operator delete' at the same scope
 void *operator new(size_t size) noexcept(false);
 
+struct T {
+  // Sized deallocations are not enabled by default, and so this new/delete 
pair
+  // does not match. However, we expect only one warning, for the new, because
+  // the operator delete is a placement delete and we do not warn on 
mismatching
+  // placement operations.
+  // CHECK-MESSAGES: :[[@LINE+1]]:9: warning: declaration of 'operator new' 
has no matching declaration of 'operator delete' at the same scope
+  void *operator new(size_t size) noexcept;
+  void operator delete(void *ptr, size_t) noexcept; // ok only if sized 
deallocation is enabled
+};
+
 struct U {
   void *operator new(size_t size) noexcept;
   void operator delete(void *ptr) noexcept;

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 58a22ec5cce17d..deb53303a21b44 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -59,10 +59,6 @@ sectio

[clang] a02f9a7 - Revert "[clang] Enable sized deallocation by default in C++14 onwards"

2023-08-29 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2023-08-29T09:36:59-04:00
New Revision: a02f9a7756e5e4c76b422f9948d5dc3f56a1d139

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

LOG: Revert "[clang] Enable sized deallocation by default in C++14 onwards"

This reverts commit 2916b125f686115deab2ba573dcaff3847566ab9.

Reverting due to failures on:
https://lab.llvm.org/buildbot/#/builders/216/builds/26407
https://lab.llvm.org/staging/#/builders/247/builds/5659
http://45.33.8.238/win/83485/step_7.txt

Added: 


Modified: 
clang-tools-extra/clangd/unittests/FindTargetTests.cpp
clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp
clang/docs/ReleaseNotes.rst
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/Darwin.cpp
clang/lib/Driver/ToolChains/Darwin.h
clang/lib/Driver/ToolChains/ZOS.cpp
clang/test/AST/ast-dump-expr-json.cpp
clang/test/AST/ast-dump-expr.cpp
clang/test/AST/ast-dump-stmt-json.cpp
clang/test/Analysis/cxxnewexpr-callback.cpp

clang/test/CXX/basic/basic.stc/basic.stc.dynamic/basic.stc.dynamic.deallocation/p2.cpp
clang/test/CXX/expr/expr.unary/expr.new/p14.cpp
clang/test/CodeGenCXX/cxx1y-sized-deallocation.cpp
clang/test/CodeGenCXX/cxx1z-aligned-allocation.cpp
clang/test/CodeGenCXX/cxx2a-destroying-delete.cpp
clang/test/CodeGenCXX/delete-two-arg.cpp
clang/test/CodeGenCXX/delete.cpp
clang/test/CodeGenCXX/dllimport.cpp
clang/test/CodeGenCXX/new.cpp
clang/test/CodeGenCoroutines/coro-aligned-alloc-2.cpp
clang/test/CodeGenCoroutines/coro-aligned-alloc.cpp
clang/test/CodeGenCoroutines/coro-alloc.cpp
clang/test/CodeGenCoroutines/coro-cleanup.cpp
clang/test/CodeGenCoroutines/coro-dealloc.cpp
clang/test/CodeGenCoroutines/coro-gro.cpp
clang/test/CodeGenCoroutines/pr56919.cpp
clang/test/Lexer/cxx-features.cpp
clang/test/PCH/cxx1z-aligned-alloc.cpp
clang/test/SemaCXX/MicrosoftExtensions.cpp
clang/test/SemaCXX/builtin-operator-new-delete.cpp
clang/test/SemaCXX/cxx1y-sized-deallocation.cpp
clang/test/SemaCXX/unavailable_aligned_allocation.cpp
clang/unittests/StaticAnalyzer/CallEventTest.cpp
clang/www/cxx_status.html
libcxx/test/libcxx/language.support/support.dynamic/libcpp_deallocate.sh.cpp

libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.array/sized_delete_array14.pass.cpp

libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.single/sized_delete14.pass.cpp

Removed: 
clang/include/clang/Basic/SizedDeallocation.h



diff  --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp 
b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
index 56cf6da70965ba..19e80658de063c 100644
--- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -812,9 +812,7 @@ TEST_F(TargetDeclTest, OverloadExpr) {
   [[delete]] x;
 }
   )cpp";
-  // Sized deallocation is enabled by default in C++14 onwards.
-  EXPECT_DECLS("CXXDeleteExpr",
-   "void operator delete(void *, unsigned long) noexcept");
+  EXPECT_DECLS("CXXDeleteExpr", "void operator delete(void *) noexcept");
 }
 
 TEST_F(TargetDeclTest, DependentExprs) {

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp
index f86fe8a4c5b14f..78f021144b2e19 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/misc/new-delete-overloads.cpp
@@ -12,6 +12,16 @@ struct S {
 // CHECK-MESSAGES: :[[@LINE+1]]:7: warning: declaration of 'operator new' has 
no matching declaration of 'operator delete' at the same scope
 void *operator new(size_t size) noexcept(false);
 
+struct T {
+  // Sized deallocations are not enabled by default, and so this new/delete 
pair
+  // does not match. However, we expect only one warning, for the new, because
+  // the operator delete is a placement delete and we do not warn on 
mismatching
+  // placement operations.
+  // CHECK-MESSAGES: :[[@LINE+1]]:9: warning: declaration of 'operator new' 
has no matching declaration of 'operator delete' at the same scope
+  void *operator new(size_t size) noexcept;
+  void operator delete(void *ptr, size_t) noexcept; // ok only if sized 
deallocation is enabled
+};
+
 struct U {
   void *operator new(size_t size) noexcept;
   void operator delete(void *ptr) noexcept;

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 58a22ec5cce17d..deb53303a21b44 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -59,10 +59,6 @@ sectio

[PATCH] D112921: [clang] Enable sized deallocation by default in C++14 onwards

2023-08-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman reopened this revision.
aaron.ballman added a comment.

>> In D112921#4624674 , 
>> @aaron.ballman wrote:
>> Because the issues have been ongoing for a few hours now, I think it'd make 
>> sense to revert these changes while trying to determine what the appropriate 
>> fix is. @wangpc would you mind doing the revert?
>
> Yeah I think we should. Can you revert it for me? I am away from my computer 
> now.

Sure can -- I've reverted in a02f9a7756e5e4c76b422f9948d5dc3f56a1d139 
 and am 
reopening the review. Thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D112921/new/

https://reviews.llvm.org/D112921

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


[PATCH] D159068: [clang][X86] Update excessive register save diagnostic to more closely follow the interrupt attribute spec

2023-08-29 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:317
+  " with attribute 'no_caller_saved_registers'"
+  " or be compiled with '-mgeneral-regs-only'">,
+  InGroup>;

aaron.ballman wrote:
> Can you add a test case showing that `-mgeneral-regs-only` causes the 
> diagnostic to be silenced?
It's a driver only option. I think we are not suggested to invoke %clang out of 
driver testsing, right?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159068/new/

https://reviews.llvm.org/D159068

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


[PATCH] D158739: AIX: Issue an error when specifying an alias for a common symbol

2023-08-29 Thread Stephen Peckham via Phabricator via cfe-commits
stephenpeckham updated this revision to Diff 554299.

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158739/new/

https://reviews.llvm.org/D158739

Files:
  clang/include/clang/Basic/DiagnosticFrontendKinds.td
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGen/aix-common.c
  llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
  llvm/test/CodeGen/PowerPC/aix-common.ll

Index: llvm/test/CodeGen/PowerPC/aix-common.ll
===
--- /dev/null
+++ llvm/test/CodeGen/PowerPC/aix-common.ll
@@ -0,0 +1,15 @@
+; RUN: not llc -filetype=obj -mtriple powerpc-ibm-aix-xcoff -o %t.o < %s 2>&1 | FileCheck %s
+; RUN: not llc -filetype=asm -mtriple powerpc-ibm-aix-xcoff -o %t.o < %s 2>&1 | FileCheck %s
+; RUN: not llc -filetype=obj -mtriple powerpc64-ibm-aix-xcoff -o %t.o < %s 2>&1 | FileCheck %s
+; RUN: not llc -filetype=asm -mtriple powerpc64-ibm-aix-xcoff -o %t.o < %s 2>&1 | FileCheck %s
+@x= common global i32 0, align 4
+
+@y= alias i32, ptr @x
+
+; Function Attrs: noinline nounwind optnone
+define ptr @g() #0 {
+entry:
+  ret ptr @y
+}
+; CHECK: LLVM ERROR: Aliases to common variables are not allowed on AIX:
+; CHECK-NEXT:Alias attribute for y is invalid because x is common.
Index: llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
===
--- llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
+++ llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
@@ -2762,11 +2762,21 @@
 
   // Construct an aliasing list for each GlobalObject.
   for (const auto &Alias : M.aliases()) {
-const GlobalObject *Base = Alias.getAliaseeObject();
-if (!Base)
+const GlobalObject *Aliasee = Alias.getAliaseeObject();
+if (!Aliasee)
   report_fatal_error(
   "alias without a base object is not yet supported on AIX");
-GOAliasMap[Base].push_back(&Alias);
+
+if (Aliasee->hasCommonLinkage()) {
+  report_fatal_error("Aliases to common variables are not allowed on AIX:"
+ "\n\tAlias attribute for " +
+ Alias.getGlobalIdentifier() +
+ " is invalid because " + Aliasee->getName() +
+ " is common.",
+ false);
+}
+
+GOAliasMap[Aliasee].push_back(&Alias);
   }
 
   return Result;
Index: clang/test/CodeGen/aix-common.c
===
--- /dev/null
+++ clang/test/CodeGen/aix-common.c
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -triple powerpc-ibm-aix   -S -fcommon %s -verify -o -
+// RUN: %clang_cc1 -triple powerpc64-ibm-aix -S -fcommon %s -verify -o -
+int xx;
+extern int yy __attribute__((__alias__("xx") )); //expected-error {{alias to a variable in a common section is not allowed}}
+
+void *gg() { return &yy; }
+
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -563,8 +563,8 @@
 }
 
 static bool checkAliasedGlobal(
-DiagnosticsEngine &Diags, SourceLocation Location, bool IsIFunc,
-const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV,
+const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location,
+bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV,
 const llvm::MapVector &MangledDeclNames,
 SourceRange AliasRange) {
   GV = getAliasedGlobal(Alias);
@@ -573,6 +573,14 @@
 return false;
   }
 
+  if (GV->hasCommonLinkage()) {
+const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
+if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
+  Diags.Report(Location, diag::err_alias_to_common);
+  return false;
+}
+  }
+
   if (GV->isDeclaration()) {
 Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
 Diags.Report(Location, diag::note_alias_requires_mangled_name)
@@ -633,7 +641,7 @@
 StringRef MangledName = getMangledName(GD);
 llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
 const llvm::GlobalValue *GV = nullptr;
-if (!checkAliasedGlobal(Diags, Location, IsIFunc, Alias, GV,
+if (!checkAliasedGlobal(getContext(), Diags, Location, IsIFunc, Alias, GV,
 MangledDeclNames, Range)) {
   Error = true;
   continue;
Index: clang/include/clang/Basic/DiagnosticFrontendKinds.td
===
--- clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -283,6 +283,8 @@
 def err_alias_to_undefined : Error<
   "%select{alias|ifunc}0 must point to a defined "
   "%select{variable or |}1function">;
+def err_alias_to_common : Error<
+  "alias to a variable in a common section is not allowed">;
 def note_alias_requires_mangled_name : Note<
   "the %select{function or variable|function}0 specifi

[PATCH] D159068: [clang][X86] Update excessive register save diagnostic to more closely follow the interrupt attribute spec

2023-08-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:317
+  " with attribute 'no_caller_saved_registers'"
+  " or be compiled with '-mgeneral-regs-only'">,
+  InGroup>;

pengfei wrote:
> aaron.ballman wrote:
> > Can you add a test case showing that `-mgeneral-regs-only` causes the 
> > diagnostic to be silenced?
> It's a driver only option. I think we are not suggested to invoke %clang out 
> of driver testsing, right?
Oh! I hadn't realized this was a driver-only option. Looking at it harder, I 
see that for x86, setting the driver option removes the x87, mmx, and sse 
features which we do have test coverage for. Thanks @pengfei for pointing that 
out, my request was already covered!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159068/new/

https://reviews.llvm.org/D159068

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


[PATCH] D159092: [APINotes] Initial support for C++ namespaces

2023-08-29 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan created this revision.
egorzhdan added a reviewer: compnerd.
Herald added a project: All.
egorzhdan requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This upstreams a part of the C++ namespaces support in Clang API Notes.

The complete patch was recently merged downstream in the Apple fork: 
https://github.com/apple/llvm-project/pull/7230.

This patch only adds the parts of the namespace support that can be cleanly 
applied on top of the API Notes infrastructure that was upstreamed previously.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D159092

Files:
  clang/include/clang/APINotes/Types.h
  clang/lib/APINotes/APINotesFormat.h
  clang/lib/APINotes/APINotesWriter.cpp
  clang/lib/APINotes/APINotesYAMLCompiler.cpp

Index: clang/lib/APINotes/APINotesYAMLCompiler.cpp
===
--- clang/lib/APINotes/APINotesYAMLCompiler.cpp
+++ clang/lib/APINotes/APINotesYAMLCompiler.cpp
@@ -495,6 +495,9 @@
 } // namespace llvm
 
 namespace {
+struct Namespace;
+typedef std::vector NamespacesSeq;
+
 struct TopLevelItems {
   ClassesSeq Classes;
   ClassesSeq Protocols;
@@ -503,6 +506,7 @@
   EnumConstantsSeq EnumConstants;
   TagsSeq Tags;
   TypedefsSeq Typedefs;
+  NamespacesSeq Namespaces;
 };
 } // namespace
 
@@ -516,10 +520,39 @@
   IO.mapOptional("Enumerators", TLI.EnumConstants);
   IO.mapOptional("Tags", TLI.Tags);
   IO.mapOptional("Typedefs", TLI.Typedefs);
+  IO.mapOptional("Namespaces", TLI.Namespaces);
 }
 } // namespace yaml
 } // namespace llvm
 
+namespace {
+struct Namespace {
+  StringRef Name;
+  AvailabilityItem Availability;
+  StringRef SwiftName;
+  std::optional SwiftPrivate;
+  TopLevelItems Items;
+};
+} // namespace
+
+LLVM_YAML_IS_SEQUENCE_VECTOR(Namespace)
+
+namespace llvm {
+namespace yaml {
+template <> struct MappingTraits {
+  static void mapping(IO &IO, Namespace &T) {
+IO.mapRequired("Name", T.Name);
+IO.mapOptional("Availability", T.Availability.Mode,
+   APIAvailability::Available);
+IO.mapOptional("AvailabilityMsg", T.Availability.Msg, StringRef(""));
+IO.mapOptional("SwiftPrivate", T.SwiftPrivate);
+IO.mapOptional("SwiftName", T.SwiftName, StringRef(""));
+mapTopLevelItems(IO, T.Items);
+  }
+};
+} // namespace yaml
+} // namespace llvm
+
 namespace {
 struct Versioned {
   VersionTuple Version;
Index: clang/lib/APINotes/APINotesWriter.cpp
===
--- clang/lib/APINotes/APINotesWriter.cpp
+++ clang/lib/APINotes/APINotesWriter.cpp
@@ -33,15 +33,21 @@
   /// Mapping from strings to identifier IDs.
   llvm::StringMap IdentifierIDs;
 
-  /// Information about Objective-C contexts (classes or protocols).
+  /// Information about contexts (Objective-C classes or protocols or C++
+  /// namespaces).
   ///
-  /// Indexed by the identifier ID and a bit indication whether we're looking
-  /// for a class (0) or protocol (1) and provides both the context ID and
-  /// information describing the context within that module.
-  llvm::DenseMap,
+  /// Indexed by the parent context ID, context kind and the identifier ID of
+  /// this context and provides both the context ID and information describing
+  /// the context within that module.
+  llvm::DenseMap>>
   ObjCContexts;
 
+  /// Information about parent contexts for each context.
+  ///
+  /// Indexed by context ID, provides the parent context ID.
+  llvm::DenseMap ParentContexts;
+
   /// Information about Objective-C properties.
   ///
   /// Indexed by the context ID, property name, and whether this is an
@@ -64,16 +70,18 @@
 
   /// Information about global variables.
   ///
-  /// Indexed by the identifier ID.
-  llvm::DenseMap, 1>>
+  /// Indexed by the context ID, contextKind, identifier ID.
+  llvm::DenseMap<
+  ContextTableKey,
+  llvm::SmallVector, 1>>
   GlobalVariables;
 
   /// Information about global functions.
   ///
-  /// Indexed by the identifier ID.
-  llvm::DenseMap, 1>>
+  /// Indexed by the context ID, contextKind, identifier ID.
+  llvm::DenseMap<
+  ContextTableKey,
+  llvm::SmallVector, 1>>
   GlobalFunctions;
 
   /// Information about enumerators.
@@ -85,15 +93,15 @@
 
   /// Information about tags.
   ///
-  /// Indexed by the identifier ID.
-  llvm::DenseMap, 1>>
   Tags;
 
   /// Information about typedefs.
   ///
-  /// Indexed by the identifier ID.
-  llvm::DenseMap, 1>>
   Typedefs;
 
@@ -292,7 +300,7 @@
 /// Used to serialize the on-disk Objective-C context table.
 class ObjCContextIDTableInfo {
 public:
-  using key_type = std::pair; // identifier ID, is-protocol
+  using key_type = ContextTableKey;
   using key_type_ref = key_type;
   using data_type = unsigned;
   using data_type_ref = const data_type &;
@@ -300,12 +308,12 @@
   using offset_type = unsigned;
 
   hash_value_type ComputeHash(key_type_ref Key) {
-return static_c

[PATCH] D158863: Implement the monolithic CI pipeline in the monorepo

2023-08-29 Thread Louis Dionne via Phabricator via cfe-commits
ldionne marked an inline comment as done.
ldionne added inline comments.



Comment at: .ci/generate-buildkite-pipeline-premerge:163
+
+if [[ ! ${SPECIFIC_PIPELINE_AVAILABLE} -eq 1 ]]; then
+  # Figure out which projects need to be built on each platform

goncharov wrote:
> ldionne wrote:
> > goncharov wrote:
> > > do I understand correctly that if mlir and libcxx modified then only 
> > > libcxx will be run as SPECIFIC_PIPELINE_AVAILABLE=1?
> > Yes. This corresponds to the current logic as well. Basically if a project 
> > has some custom CI set up, we don't want to also run the general CI since 
> > that's just a waste of resources.
> The previous logic was that we caclulated first all projects that might be 
> affected by current set (e.g. mlir is affected by llvm), then we added add 
> dependencies.
> So e.g. if mlir was modified, we should add "flang" to test set and then add 
> "llvm clang" as dependincies, resutling in "mlir flang llvm clang" set. I can 
> re-implement this logic later here no problem.
> Also, it seems incorrect to only run "libc++" tests if libc++ was modified 
> among other things. E.g. if something has touched libc++ and mlir than mlir 
> should still run.
Ah, I see. Yeah I guess that makes sense. I'll update this review with the 
updated logic.

> Also, it seems incorrect to only run "libc++" tests if libc++ was modified 
> among other things. E.g. if something has touched libc++ and mlir than mlir 
> should still run.

You're right, I guess in that case we should run both jobs. I'll remove the 
check.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158863/new/

https://reviews.llvm.org/D158863

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


[PATCH] D158615: [clang] Emit an error if variable ends up with incomplete array type

2023-08-29 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon added a comment.

The failures in CI are unrelated and caused by another patch - 
https://reviews.llvm.org/D112921.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158615/new/

https://reviews.llvm.org/D158615

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


[PATCH] D158872: [clang][ASTMatchers] Add a few type-related Matchers

2023-08-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added reviewers: r4nt, sammccall.
aaron.ballman added a comment.

In D158872#4623193 , @danix800 wrote:

> In D158872#4622124 , @aaron.ballman 
> wrote:
>
>> Are these matchers going to be used in-tree (by clang-tidy, or something 
>> else)? We typically do not add new AST matches until there's a need for them 
>> because the AST matchers have a pretty big impact on build times of Clang 
>> itself.
>
> They are used in `ASTImporter` testcases as shown in 
> https://reviews.llvm.org/D158948. Though this might not be a strong reason to
> add these matchers and bring on too much bad impact.
>
> ASTImporter is more urgent since we still lack support for some of the AST 
> nodes so I considered adding them batchly and started with
> type-related nodes. I thought that matchers're OK to use in unittests as 
> actually they are used a lot there, but I wasn't aware of the impact
> on build of Clang.
>
> If not acceptable, I'm OK with it. We can still test importing with other 
> ways. Matchers are not mandatory.
>
> EDIT: If acceptable, tools like `clang-query` can benefit from these matchers 
> too, easy for
> debugging I guess. Please let me known whether I should proceed on this 
> revision or not. Thanks for reviewing anyway!

Pulling in a few more folks for extra opinions in case I'm off-base, but I 
think a good approach for right now is to add these matches to the unit test 
file directly in the AST importer patch and to hold off on landing this one. 
Then you still get the test coverage you need in the unit tests, but the extra 
compilation time is limited to just one .cpp file and not everything including 
`ASTMatchers.h`. As we find a need for the matchers, we can lift them from the 
unit test into the public matchers. It's not that there's no utility to these 
(there is!), it's more just the balancing act between compile times and utility.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158872/new/

https://reviews.llvm.org/D158872

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


[PATCH] D158739: AIX: Issue an error when specifying an alias for a common symbol

2023-08-29 Thread Digger Lin via Phabricator via cfe-commits
DiggerLin accepted this revision.
DiggerLin added a comment.
This revision is now accepted and ready to land.

LGTM


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158739/new/

https://reviews.llvm.org/D158739

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


[clang] bcc8811 - [clang] Emit an error if variable ends up with incomplete array type

2023-08-29 Thread via cfe-commits

Author: Podchishchaeva, Mariya
Date: 2023-08-29T06:50:32-07:00
New Revision: bcc881161aeb56ea5a38858fe0007e59f21042c4

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

LOG: [clang] Emit an error if variable ends up with incomplete array type

This adds an error if variable with incomplete type has initializer with
incomplete type, so it is not possible to deduce array size from
initializer.

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

Reviewed By: aaron.ballman, shafik

Differential Revision: https://reviews.llvm.org/D158615

Added: 
clang/test/SemaCXX/gh37257.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaDecl.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index deb53303a21b44..9cd95005d7e059 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -189,6 +189,9 @@ Bug Fixes in This Version
   (`#64876 `_)
 - Fixed an assertion if a function has cleanups and fatal erors.
   (`#48974 `_)
+- Clang now emits an error if it is not possible to deduce array size for a
+  variable with incomplete array type.
+  (`#37257 `_)
 
 Bug Fixes to Compiler Builtins
 ^^

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 664af4ccf4c635..18355b484975af 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -13445,6 +13445,18 @@ void Sema::AddInitializerToDecl(Decl *RealDecl, Expr 
*Init, bool DirectInit) {
 IsParenListInit = !InitSeq.steps().empty() &&
   InitSeq.step_begin()->Kind ==
   InitializationSequence::SK_ParenthesizedListInit;
+QualType VDeclType = VDecl->getType();
+if (Init && !Init->getType().isNull() &&
+!Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
+Context.getAsIncompleteArrayType(VDeclType) &&
+Context.getAsIncompleteArrayType(Init->getType())) {
+  // Bail out if it is not possible to deduce array size from the
+  // initializer.
+  Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
+  << VDeclType;
+  VDecl->setInvalidDecl();
+  return;
+}
   }
 
   // Check for self-references within variable initializers.

diff  --git a/clang/test/SemaCXX/gh37257.cpp b/clang/test/SemaCXX/gh37257.cpp
new file mode 100644
index 00..ebcd32d18f69da
--- /dev/null
+++ b/clang/test/SemaCXX/gh37257.cpp
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+template
+T&& create();
+
+template
+void test() {
+  T t(create()...); // expected-error{{variable has incomplete type 
'int[]'}}
+  (void) t;
+}
+
+struct A;
+
+int main() {
+  test(); // expected-note {{in instantiation of function template 
specialization 'test' requested here}}
+}



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


[PATCH] D158615: [clang] Emit an error if variable ends up with incomplete array type

2023-08-29 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbcc881161aeb: [clang] Emit an error if variable ends up with 
incomplete array type (authored by Fznamznon).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158615/new/

https://reviews.llvm.org/D158615

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaDecl.cpp
  clang/test/SemaCXX/gh37257.cpp


Index: clang/test/SemaCXX/gh37257.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/gh37257.cpp
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+template
+T&& create();
+
+template
+void test() {
+  T t(create()...); // expected-error{{variable has incomplete type 
'int[]'}}
+  (void) t;
+}
+
+struct A;
+
+int main() {
+  test(); // expected-note {{in instantiation of function template 
specialization 'test' requested here}}
+}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -13445,6 +13445,18 @@
 IsParenListInit = !InitSeq.steps().empty() &&
   InitSeq.step_begin()->Kind ==
   InitializationSequence::SK_ParenthesizedListInit;
+QualType VDeclType = VDecl->getType();
+if (Init && !Init->getType().isNull() &&
+!Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
+Context.getAsIncompleteArrayType(VDeclType) &&
+Context.getAsIncompleteArrayType(Init->getType())) {
+  // Bail out if it is not possible to deduce array size from the
+  // initializer.
+  Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
+  << VDeclType;
+  VDecl->setInvalidDecl();
+  return;
+}
   }
 
   // Check for self-references within variable initializers.
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -189,6 +189,9 @@
   (`#64876 `_)
 - Fixed an assertion if a function has cleanups and fatal erors.
   (`#48974 `_)
+- Clang now emits an error if it is not possible to deduce array size for a
+  variable with incomplete array type.
+  (`#37257 `_)
 
 Bug Fixes to Compiler Builtins
 ^^


Index: clang/test/SemaCXX/gh37257.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/gh37257.cpp
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+template
+T&& create();
+
+template
+void test() {
+  T t(create()...); // expected-error{{variable has incomplete type 'int[]'}}
+  (void) t;
+}
+
+struct A;
+
+int main() {
+  test(); // expected-note {{in instantiation of function template specialization 'test' requested here}}
+}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -13445,6 +13445,18 @@
 IsParenListInit = !InitSeq.steps().empty() &&
   InitSeq.step_begin()->Kind ==
   InitializationSequence::SK_ParenthesizedListInit;
+QualType VDeclType = VDecl->getType();
+if (Init && !Init->getType().isNull() &&
+!Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
+Context.getAsIncompleteArrayType(VDeclType) &&
+Context.getAsIncompleteArrayType(Init->getType())) {
+  // Bail out if it is not possible to deduce array size from the
+  // initializer.
+  Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
+  << VDeclType;
+  VDecl->setInvalidDecl();
+  return;
+}
   }
 
   // Check for self-references within variable initializers.
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -189,6 +189,9 @@
   (`#64876 `_)
 - Fixed an assertion if a function has cleanups and fatal erors.
   (`#48974 `_)
+- Clang now emits an error if it is not possible to deduce array size for a
+  variable with incomplete array type.
+  (`#37257 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D159068: [clang][X86] Update excessive register save diagnostic to more closely follow the interrupt attribute spec

2023-08-29 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei accepted this revision.
pengfei added a comment.
This revision is now accepted and ready to land.

I don't have prior experience about interrupt diagnostic but know something 
about mgeneral-regs-only. I think the diagnostic great.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159068/new/

https://reviews.llvm.org/D159068

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


[PATCH] D158223: [clang] Add clang::unnamed_addr attribute that marks globals' address as not significant

2023-08-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/AttrDocs.td:1416-1417
+not significant. This allows global constants with the same contents to be
+merged. This can break global pointer identity, i.e. two different globals have
+the same address.
+

aeubanks wrote:
> rnk wrote:
> > aaron.ballman wrote:
> > > aeubanks wrote:
> > > > rnk wrote:
> > > > > erichkeane wrote:
> > > > > > aeubanks wrote:
> > > > > > > erichkeane wrote:
> > > > > > > > aeubanks wrote:
> > > > > > > > > aaron.ballman wrote:
> > > > > > > > > > aeubanks wrote:
> > > > > > > > > > > aaron.ballman wrote:
> > > > > > > > > > > > aeubanks wrote:
> > > > > > > > > > > > > aaron.ballman wrote:
> > > > > > > > > > > > > > What happens for tentative definitions where the 
> > > > > > > > > > > > > > value isn't known? e.g.,
> > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > [[clang::unnamed_addr]] int i1, i2;
> > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > 
> > > > > > > > > > > > > > What happens if the types are similar but not the 
> > > > > > > > > > > > > > same?
> > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > [[clang::unnamed_addr]] signed int i1 = 32;
> > > > > > > > > > > > > > [[clang::unnamed_addr]] unsigned int i2 = 32;
> > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > 
> > > > > > > > > > > > > > Should we diagnose taking the address of such an 
> > > > > > > > > > > > > > attributed variable so users have some hope of 
> > > > > > > > > > > > > > spotting the non-conforming situations?
> > > > > > > > > > > > > > 
> > > > > > > > > > > > > > Does this attribute have impacts across translation 
> > > > > > > > > > > > > > unit boundaries (perhaps only when doing LTO) or 
> > > > > > > > > > > > > > only within a single TU?
> > > > > > > > > > > > > > 
> > > > > > > > > > > > > > What does this attribute do in C++ in the presence 
> > > > > > > > > > > > > > of constructors and destructors? e.g.,
> > > > > > > > > > > > > > ```
> > > > > > > > > > > > > > struct S {
> > > > > > > > > > > > > >   S();
> > > > > > > > > > > > > >   ~S();
> > > > > > > > > > > > > > };
> > > > > > > > > > > > > > 
> > > > > > > > > > > > > > [[clang::unnamed_addr]] S s1, s2; // Are these 
> > > > > > > > > > > > > > merged and there's only one ctor/dtor call?
> > > > > > > > > > > > > > ```
> > > > > > > > > > > > > globals are only mergeable if they're known to be 
> > > > > > > > > > > > > constant and have the same value/size. this can be 
> > > > > > > > > > > > > done at compile time only if the optimizer can see 
> > > > > > > > > > > > > the constant values, or at link time
> > > > > > > > > > > > > 
> > > > > > > > > > > > > so nothing would happen in any of the cases you've 
> > > > > > > > > > > > > given.
> > > > > > > > > > > > > 
> > > > > > > > > > > > > but yeah that does imply that we should warn when the 
> > > > > > > > > > > > > attribute is used on non const, non-POD globals. I'll 
> > > > > > > > > > > > > update this patch to do that
> > > > > > > > > > > > > 
> > > > > > > > > > > > > as mentioned in the description, we actually do want 
> > > > > > > > > > > > > to take the address of these globals for table-driven 
> > > > > > > > > > > > > parsing, but we don't care about identity equality
> > > > > > > > > > > > > globals are only mergeable if they're known to be 
> > > > > > > > > > > > > constant and have the same value/size. this can be 
> > > > > > > > > > > > > done at compile time only if the optimizer can see 
> > > > > > > > > > > > > the constant values, or at link time
> > > > > > > > > > > > >
> > > > > > > > > > > > > so nothing would happen in any of the cases you've 
> > > > > > > > > > > > > given.
> > > > > > > > > > > > 
> > > > > > > > > > > > A that's good to know. So I assume we *will* merge 
> > > > > > > > > > > > these?
> > > > > > > > > > > > 
> > > > > > > > > > > > ```
> > > > > > > > > > > > struct S {
> > > > > > > > > > > >   int i, j;
> > > > > > > > > > > >   float f;
> > > > > > > > > > > > };
> > > > > > > > > > > > 
> > > > > > > > > > > > [[clang::unnamed_addr]] const S s1 = { 1, 2, 3.0f };
> > > > > > > > > > > > [[clang::unnamed_addr]] const S s2 = { 1, 2, 3.0f };
> > > > > > > > > > > > [[clang::unnamed_addr]] const S s3 = s2;
> > > > > > > > > > > > ```
> > > > > > > > > > > > 
> > > > > > > > > > > > > but yeah that does imply that we should warn when the 
> > > > > > > > > > > > > attribute is used on non const, non-POD globals. I'll 
> > > > > > > > > > > > > update this patch to do that
> > > > > > > > > > > > 
> > > > > > > > > > > > Thank you, I think that will be more user-friendly
> > > > > > > > > > > > 
> > > > > > > > > > > > > as mentioned in the description, we actually do want 
> > > > > > > > > > > > > to take the address of these globals for table-driven 
> > > > > > > > > > > > > parsing, but we don't care about identity equality
> > > > > > > > > > > > 
> > > >

[PATCH] D159083: Clang: Don't warn about unused private fields of types declared maybe_unused

2023-08-29 Thread Hans Wennborg via Phabricator via cfe-commits
hans updated this revision to Diff 554312.
hans added a comment.

Add release note.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159083/new/

https://reviews.llvm.org/D159083

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/SemaCXX/warn-unused-private-field.cpp


Index: clang/test/SemaCXX/warn-unused-private-field.cpp
===
--- clang/test/SemaCXX/warn-unused-private-field.cpp
+++ clang/test/SemaCXX/warn-unused-private-field.cpp
@@ -284,3 +284,14 @@
 private:
   int n; // expected-warning{{private field 'n' is not used}}
 };
+
+namespace pr61334 {
+class [[maybe_unused]] MaybeUnusedClass {};
+enum [[maybe_unused]] MaybeUnusedEnum {};
+typedef int MaybeUnusedTypedef [[maybe_unused]];
+class C {
+  MaybeUnusedClass c; // no-warning
+  MaybeUnusedEnum e; // no-warning
+  MaybeUnusedTypedef t; // no-warning
+};
+}
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -3729,10 +3729,20 @@
 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
   // Remember all explicit private FieldDecls that have a name, no side
   // effects and are not part of a dependent type declaration.
+
+  auto DeclHasUnusedAttr = [](const QualType &T) {
+if (const TagDecl *TD = T->getAsTagDecl())
+  return TD->hasAttr();
+if (const TypedefType *TDT = T->getAs())
+  return TDT->getDecl()->hasAttr();
+return false;
+  };
+
   if (!FD->isImplicit() && FD->getDeclName() &&
   FD->getAccess() == AS_private &&
   !FD->hasAttr() &&
   !FD->getParent()->isDependentContext() &&
+  !DeclHasUnusedAttr(FD->getType()) &&
   !InitializationHasSideEffects(*FD))
 UnusedPrivateFields.insert(FD);
 }
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -193,6 +193,9 @@
   (`#64876 `_)
 - Fixed an assertion if a function has cleanups and fatal erors.
   (`#48974 `_)
+- Clang's ``-Wunused-private-field`` no longer warns on fields whose type is
+  declared with ``[[maybe_unused]]``.
+  (`#61334 `_)
 
 Bug Fixes to Compiler Builtins
 ^^


Index: clang/test/SemaCXX/warn-unused-private-field.cpp
===
--- clang/test/SemaCXX/warn-unused-private-field.cpp
+++ clang/test/SemaCXX/warn-unused-private-field.cpp
@@ -284,3 +284,14 @@
 private:
   int n; // expected-warning{{private field 'n' is not used}}
 };
+
+namespace pr61334 {
+class [[maybe_unused]] MaybeUnusedClass {};
+enum [[maybe_unused]] MaybeUnusedEnum {};
+typedef int MaybeUnusedTypedef [[maybe_unused]];
+class C {
+  MaybeUnusedClass c; // no-warning
+  MaybeUnusedEnum e; // no-warning
+  MaybeUnusedTypedef t; // no-warning
+};
+}
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -3729,10 +3729,20 @@
 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
   // Remember all explicit private FieldDecls that have a name, no side
   // effects and are not part of a dependent type declaration.
+
+  auto DeclHasUnusedAttr = [](const QualType &T) {
+if (const TagDecl *TD = T->getAsTagDecl())
+  return TD->hasAttr();
+if (const TypedefType *TDT = T->getAs())
+  return TDT->getDecl()->hasAttr();
+return false;
+  };
+
   if (!FD->isImplicit() && FD->getDeclName() &&
   FD->getAccess() == AS_private &&
   !FD->hasAttr() &&
   !FD->getParent()->isDependentContext() &&
+  !DeclHasUnusedAttr(FD->getType()) &&
   !InitializationHasSideEffects(*FD))
 UnusedPrivateFields.insert(FD);
 }
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -193,6 +193,9 @@
   (`#64876 `_)
 - Fixed an assertion if a function has cleanups and fatal erors.
   (`#48974 `_)
+- Clang's ``-Wunused-private-field`` no longer warns on fields whose type is
+  declared with ``[[maybe_unused]]``.
+  (`#61334 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/ma

[PATCH] D159083: Clang: Don't warn about unused private fields of types declared maybe_unused

2023-08-29 Thread Hans Wennborg via Phabricator via cfe-commits
hans added inline comments.



Comment at: clang/test/SemaCXX/warn-unused-private-field.cpp:291-292
+enum [[maybe_unused]] MaybeUnusedEnum {};
+typedef int MaybeUnusedTypedef [[maybe_unused]];
+class C {
+  MaybeUnusedClass c; // no-warning

aaron.ballman wrote:
> Let's try one more thing:
> ```
> template 
> class C2 {
>   Ty c; // no-warning
>   Uy d; // warning
> };
> 
> class [[maybe_unused]] Good {};
> class Bad {};
> 
> C2 c;
> ```
The `!FD->getParent()->isDependentContext()` condition prevents the warning 
from firing on either `C2<>::c` or `d`. (It seems that was there from the 
beginning: 
https://github.com/llvm/llvm-project/commit/0baec549a3f49d8c04a0092917f758cc89ef238d#diff-9ced4fa47ee2b9c03b6996ce89a1d131c0f5b71013993bc582209f50d5e934daR1649)


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159083/new/

https://reviews.llvm.org/D159083

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


[clang] de0df63 - [CUDA][HIP] Fix overloading resolution in global variable initializer

2023-08-29 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2023-08-29T10:17:24-04:00
New Revision: de0df639724b10001ea9a74539381ea494296be9

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

LOG: [CUDA][HIP] Fix overloading resolution in global variable initializer

Currently, clang does not resolve certain overloaded functions correctly in the 
initializer
of global variables, e.g.

template
T1 mypow(T1, U);

__attribute__((device)) double mypow(double, int);

double t_extent = mypow(1.0, 2);

In the above example, mypow is supposed to resolve to the host version
but clang resolves it to the device version instead, and emits an error
(https://godbolt.org/z/17xxzaa67).

However, if the variable is assigned in a host function, there is no error.
The discrepancy in overloading resolution inside and outside of
a function is due to clang not accounting for the host/device target
when resolving functions called in the initializer of a global variable.

This patch introduces a global host/device target context for CUDA/HIP
for functions called outside of functions. For global variable initialization,
it is determined by the host/device attribute of the variable. For other
situations, a default value of host_device is sufficient.

Reviewed by: Artem Belevich

Differential Revision: https://reviews.llvm.org/D158247

Fixes: SWDEV-416731

Added: 
clang/test/CodeGenCUDA/global-initializers.cu
clang/test/SemaCUDA/global-initializers.cu

Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Parse/ParseDecl.cpp
clang/lib/Sema/SemaCUDA.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/lib/Sema/SemaOverload.cpp
clang/lib/Sema/SemaType.cpp
clang/test/SemaCUDA/amdgpu-windows-vectorcall.cu
clang/test/SemaCUDA/function-overload.cu

Removed: 
clang/test/SemaCUDA/global-initializers-host.cu



diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index e5083ddf1847f0..ce6731f99d4cbf 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -1012,6 +1012,14 @@ class Sema final {
 }
   } DelayedDiagnostics;
 
+  enum CUDAFunctionTarget {
+CFT_Device,
+CFT_Global,
+CFT_Host,
+CFT_HostDevice,
+CFT_InvalidTarget
+  };
+
   /// A RAII object to temporarily push a declaration context.
   class ContextRAII {
   private:
@@ -4751,8 +4759,13 @@ class Sema final {
   bool isValidPointerAttrType(QualType T, bool RefOkay = false);
 
   bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
+
+  /// Check validaty of calling convention attribute \p attr. If \p FD
+  /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
+  /// target. Otherwise, it is specified by \p CFT.
   bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
-const FunctionDecl *FD = nullptr);
+const FunctionDecl *FD = nullptr,
+CUDAFunctionTarget CFT = CFT_InvalidTarget);
   bool CheckAttrTarget(const ParsedAttr &CurrAttr);
   bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
   bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
@@ -13259,14 +13272,6 @@ class Sema final {
   void checkTypeSupport(QualType Ty, SourceLocation Loc,
 ValueDecl *D = nullptr);
 
-  enum CUDAFunctionTarget {
-CFT_Device,
-CFT_Global,
-CFT_Host,
-CFT_HostDevice,
-CFT_InvalidTarget
-  };
-
   /// Determines whether the given function is a CUDA device/host/kernel/etc.
   /// function.
   ///
@@ -13285,6 +13290,29 @@ class Sema final {
   /// Determines whether the given variable is emitted on host or device side.
   CUDAVariableTarget IdentifyCUDATarget(const VarDecl *D);
 
+  /// Defines kinds of CUDA global host/device context where a function may be
+  /// called.
+  enum CUDATargetContextKind {
+CTCK_Unknown,   /// Unknown context
+CTCK_InitGlobalVar, /// Function called during global variable
+/// initialization
+  };
+
+  /// Define the current global CUDA host/device context where a function may 
be
+  /// called. Only used when a function is called outside of any functions.
+  struct CUDATargetContext {
+CUDAFunctionTarget Target = CFT_HostDevice;
+CUDATargetContextKind Kind = CTCK_Unknown;
+Decl *D = nullptr;
+  } CurCUDATargetCtx;
+
+  struct CUDATargetContextRAII {
+Sema &S;
+CUDATargetContext SavedCtx;
+CUDATargetContextRAII(Sema &S_, CUDATargetContextKind K, Decl *D);
+~CUDATargetContextRAII() { S.CurCUDATargetCtx = SavedCtx; }
+  };
+
   /// Gets the CUDA target for the current context.
   CUDAFunctionTarget CurrentCUDATarget() {
 return IdentifyCUDATarget(dyn_cast(CurContext));

diff  --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Par

[PATCH] D158247: [CUDA][HIP] Fix overloading resolution in global variable initializer

2023-08-29 Thread Yaxun Liu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGde0df639724b: [CUDA][HIP] Fix overloading resolution in 
global variable initializer (authored by yaxunl).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158247/new/

https://reviews.llvm.org/D158247

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Sema/SemaCUDA.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/CodeGenCUDA/global-initializers.cu
  clang/test/SemaCUDA/amdgpu-windows-vectorcall.cu
  clang/test/SemaCUDA/function-overload.cu
  clang/test/SemaCUDA/global-initializers-host.cu
  clang/test/SemaCUDA/global-initializers.cu

Index: clang/test/SemaCUDA/global-initializers.cu
===
--- /dev/null
+++ clang/test/SemaCUDA/global-initializers.cu
@@ -0,0 +1,72 @@
+// RUN: %clang_cc1 %s -triple x86_64-linux-unknown -fsyntax-only -o - -verify
+// RUN: %clang_cc1 %s -fcuda-is-device -triple nvptx -fsyntax-only -o - -verify
+
+#include "Inputs/cuda.h"
+
+// Check that we get an error if we try to call a __device__ function from a
+// module initializer.
+
+struct S {
+  // expected-note@-1 {{candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided}}
+  // expected-note@-2 {{candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 0 were provided}}
+  __device__ S() {}
+  // expected-note@-1 {{candidate constructor not viable: call to __device__ function from __host__ function}}
+};
+
+S s;
+// expected-error@-1 {{no matching constructor for initialization of 'S'}}
+
+struct T {
+  __host__ __device__ T() {}
+};
+T t;  // No error, this is OK.
+
+struct U {
+  // expected-note@-1 {{candidate constructor (the implicit copy constructor) not viable: no known conversion from 'int' to 'const U' for 1st argument}}
+  // expected-note@-2 {{candidate constructor (the implicit move constructor) not viable: no known conversion from 'int' to 'U' for 1st argument}}
+  __host__ U() {}
+  // expected-note@-1 {{candidate constructor not viable: requires 0 arguments, but 1 was provided}}
+  __device__ U(int) {}
+  // expected-note@-1 {{candidate constructor not viable: call to __device__ function from __host__ function}}
+};
+U u(42);
+// expected-error@-1 {{no matching constructor for initialization of 'U'}}
+
+__device__ int device_fn() { return 42; }
+// expected-note@-1 {{candidate function not viable: call to __device__ function from __host__ function}}
+int n = device_fn();
+// expected-error@-1 {{no matching function for call to 'device_fn'}}
+
+// Check host/device-based overloding resolution in global variable initializer.
+double pow(double, double);
+
+__device__ double pow(double, int);
+
+double X = pow(1.0, 1);
+__device__ double Y = pow(2.0, 2); // expected-error{{dynamic initialization is not supported for __device__, __constant__, __shared__, and __managed__ variables}}
+
+constexpr double cpow(double, double) { return 1.0; }
+
+constexpr __device__ double cpow(double, int) { return 2.0; }
+
+const double CX = cpow(1.0, 1);
+const __device__ double CY = cpow(2.0, 2);
+
+struct A {
+  double pow(double, double);
+
+  __device__ double pow(double, int);
+
+  constexpr double cpow(double, double) const { return 1.0; }
+
+  constexpr __device__ double cpow(double, int) const { return 1.0; }
+
+};
+
+A a;
+double AX = a.pow(1.0, 1);
+__device__ double AY = a.pow(2.0, 2); // expected-error{{dynamic initialization is not supported for __device__, __constant__, __shared__, and __managed__ variables}}
+
+const A ca;
+const double CAX = ca.cpow(1.0, 1);
+const __device__ double CAY = ca.cpow(2.0, 2);
Index: clang/test/SemaCUDA/global-initializers-host.cu
===
--- clang/test/SemaCUDA/global-initializers-host.cu
+++ /dev/null
@@ -1,32 +0,0 @@
-// RUN: %clang_cc1 %s --std=c++11 -triple x86_64-linux-unknown -fsyntax-only -o - -verify
-
-#include "Inputs/cuda.h"
-
-// Check that we get an error if we try to call a __device__ function from a
-// module initializer.
-
-struct S {
-  __device__ S() {}
-  // expected-note@-1 {{'S' declared here}}
-};
-
-S s;
-// expected-error@-1 {{reference to __device__ function 'S' in global initializer}}
-
-struct T {
-  __host__ __device__ T() {}
-};
-T t;  // No error, this is OK.
-
-struct U {
-  __host__ U() {}
-  __device__ U(int) {}
-  // expected-note@-1 {{'U' declared here}}
-};
-U u(42);
-// expected-error@-1 {{reference to __device__ function 'U' in global initializer}}
-
-__device__ int device_fn() { return 42; }
-// expected-note@-1 {{'device_fn' declared here}}
-int n = device_fn();
-// expected-error@-1 {{reference to __device__ function 'device_fn' 

[PATCH] D159083: Clang: Don't warn about unused private fields of types declared maybe_unused

2023-08-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/test/SemaCXX/warn-unused-private-field.cpp:291-292
+enum [[maybe_unused]] MaybeUnusedEnum {};
+typedef int MaybeUnusedTypedef [[maybe_unused]];
+class C {
+  MaybeUnusedClass c; // no-warning

hans wrote:
> aaron.ballman wrote:
> > Let's try one more thing:
> > ```
> > template 
> > class C2 {
> >   Ty c; // no-warning
> >   Uy d; // warning
> > };
> > 
> > class [[maybe_unused]] Good {};
> > class Bad {};
> > 
> > C2 c;
> > ```
> The `!FD->getParent()->isDependentContext()` condition prevents the warning 
> from firing on either `C2<>::c` or `d`. (It seems that was there from the 
> beginning: 
> https://github.com/llvm/llvm-project/commit/0baec549a3f49d8c04a0092917f758cc89ef238d#diff-9ced4fa47ee2b9c03b6996ce89a1d131c0f5b71013993bc582209f50d5e934daR1649)
Hmmm. I think that's intended to ensure we don't diagnose before we've 
instantiated the template, but once we instantiate with `C2 c;`, the 
field decl is no longer in a dependent context and we should still diagnose 
when instantiating, right?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159083/new/

https://reviews.llvm.org/D159083

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


[PATCH] D158803: [Sema][HLSL] Consolidate handling of HLSL attributes

2023-08-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158803/new/

https://reviews.llvm.org/D158803

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


[PATCH] D153339: [clang] Support vectors in __builtin_isfpclass

2023-08-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

Changes LGTM, but should come with a release note.




Comment at: clang/docs/LanguageExtensions.rst:3543-3544
 the floating-point value, specified by the first argument, falls into any of 
data
-classes, specified by the second argument. The later is a bitmask, in which 
each
-data class is represented by a bit using the encoding:
+classes, specified by the second argument. The latter is an integer constant
+expression, that is a bitmask, in which each data class is represented by a bit
+using the encoding:




Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D153339/new/

https://reviews.llvm.org/D153339

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


[PATCH] D159083: Clang: Don't warn about unused private fields of types declared maybe_unused

2023-08-29 Thread Hans Wennborg via Phabricator via cfe-commits
hans added inline comments.



Comment at: clang/test/SemaCXX/warn-unused-private-field.cpp:291-292
+enum [[maybe_unused]] MaybeUnusedEnum {};
+typedef int MaybeUnusedTypedef [[maybe_unused]];
+class C {
+  MaybeUnusedClass c; // no-warning

aaron.ballman wrote:
> hans wrote:
> > aaron.ballman wrote:
> > > Let's try one more thing:
> > > ```
> > > template 
> > > class C2 {
> > >   Ty c; // no-warning
> > >   Uy d; // warning
> > > };
> > > 
> > > class [[maybe_unused]] Good {};
> > > class Bad {};
> > > 
> > > C2 c;
> > > ```
> > The `!FD->getParent()->isDependentContext()` condition prevents the warning 
> > from firing on either `C2<>::c` or `d`. (It seems that was there from the 
> > beginning: 
> > https://github.com/llvm/llvm-project/commit/0baec549a3f49d8c04a0092917f758cc89ef238d#diff-9ced4fa47ee2b9c03b6996ce89a1d131c0f5b71013993bc582209f50d5e934daR1649)
> Hmmm. I think that's intended to ensure we don't diagnose before we've 
> instantiated the template, but once we instantiate with `C2 c;`, 
> the field decl is no longer in a dependent context and we should still 
> diagnose when instantiating, right?
I tried, and it's not diagnosing: https://godbolt.org/z/osnWbofY5

I'm guessing the motivation was that we shouldn't warn about things that depend 
on how the template is instantiated, since that could make it hard to write a 
warning-free template definition.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159083/new/

https://reviews.llvm.org/D159083

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


[PATCH] D159083: Clang: Don't warn about unused private fields of types declared maybe_unused

2023-08-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM!




Comment at: clang/test/SemaCXX/warn-unused-private-field.cpp:291-292
+enum [[maybe_unused]] MaybeUnusedEnum {};
+typedef int MaybeUnusedTypedef [[maybe_unused]];
+class C {
+  MaybeUnusedClass c; // no-warning

hans wrote:
> aaron.ballman wrote:
> > hans wrote:
> > > aaron.ballman wrote:
> > > > Let's try one more thing:
> > > > ```
> > > > template 
> > > > class C2 {
> > > >   Ty c; // no-warning
> > > >   Uy d; // warning
> > > > };
> > > > 
> > > > class [[maybe_unused]] Good {};
> > > > class Bad {};
> > > > 
> > > > C2 c;
> > > > ```
> > > The `!FD->getParent()->isDependentContext()` condition prevents the 
> > > warning from firing on either `C2<>::c` or `d`. (It seems that was there 
> > > from the beginning: 
> > > https://github.com/llvm/llvm-project/commit/0baec549a3f49d8c04a0092917f758cc89ef238d#diff-9ced4fa47ee2b9c03b6996ce89a1d131c0f5b71013993bc582209f50d5e934daR1649)
> > Hmmm. I think that's intended to ensure we don't diagnose before we've 
> > instantiated the template, but once we instantiate with `C2 c;`, 
> > the field decl is no longer in a dependent context and we should still 
> > diagnose when instantiating, right?
> I tried, and it's not diagnosing: https://godbolt.org/z/osnWbofY5
> 
> I'm guessing the motivation was that we shouldn't warn about things that 
> depend on how the template is instantiated, since that could make it hard to 
> write a warning-free template definition.
I don't think this is your bug to fix, but I still think this is a bug. 
`[[maybe_unused]]` is precisely how you would get warning-free template 
definitions -- you'd put the attribute on the field itself instead of on the 
type passed in as a template argument.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159083/new/

https://reviews.llvm.org/D159083

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


[PATCH] D158808: [Clang] Modify Parser::ParseLambdaExpressionAfterIntroducer to check whether the lambda-declarator is valid

2023-08-29 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik updated this revision to Diff 554345.
shafik added a comment.

- Add release notes


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158808/new/

https://reviews.llvm.org/D158808

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Parse/ParseExprCXX.cpp
  clang/test/Parser/cxx2a-template-lambdas.cpp
  clang/test/SemaCXX/subst-func-type-invalid-ret-type.cpp


Index: clang/test/SemaCXX/subst-func-type-invalid-ret-type.cpp
===
--- clang/test/SemaCXX/subst-func-type-invalid-ret-type.cpp
+++ clang/test/SemaCXX/subst-func-type-invalid-ret-type.cpp
@@ -5,12 +5,11 @@
 template T declval();
 
 template 
-auto Call(T x) -> decltype(declval()(0)) {} // expected-note{{candidate 
template ignored}}
+auto Call(T x) -> decltype(declval()(0)) {}
 
 class Status {};
 
 void fun() {
   // The Status() (instead of Status) here used to cause a crash.
   Call([](auto x) -> Status() {}); // expected-error{{function cannot return 
function type 'Status ()}}
-  // expected-error@-1{{no matching function for call to 'Call'}}
 }
Index: clang/test/Parser/cxx2a-template-lambdas.cpp
===
--- clang/test/Parser/cxx2a-template-lambdas.cpp
+++ clang/test/Parser/cxx2a-template-lambdas.cpp
@@ -32,3 +32,11 @@
 // expected-warning@-3 {{is a C++23 extension}}
 // expected-warning@-3 {{is a C++23 extension}}
 #endif
+
+namespace GH64962 {
+void f() {
+  [] (T i) -> int[] // expected-error {{function cannot return 
array type 'int[]'}}
+// extension-warning {{explicit template 
parameter list for lambdas is a C++20 extension}}
+{ return 3; } (v); // expected-error {{use of undeclared identifier 'v'}}
+}
+}
Index: clang/lib/Parse/ParseExprCXX.cpp
===
--- clang/lib/Parse/ParseExprCXX.cpp
+++ clang/lib/Parse/ParseExprCXX.cpp
@@ -1546,7 +1546,8 @@
   TemplateParamScope.Exit();
   LambdaScope.Exit();
 
-  if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
+  if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid() &&
+  !D.isInvalidType())
 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
 
   Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -233,6 +233,10 @@
   and appear in an implicit cast.
   (`#64949 `_).
 
+- Fix crash when parsing ill-formed lambda trailing return type. Fixes:
+  (`#64962 `_) and
+  (`#28679 `_).
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.


Index: clang/test/SemaCXX/subst-func-type-invalid-ret-type.cpp
===
--- clang/test/SemaCXX/subst-func-type-invalid-ret-type.cpp
+++ clang/test/SemaCXX/subst-func-type-invalid-ret-type.cpp
@@ -5,12 +5,11 @@
 template T declval();
 
 template 
-auto Call(T x) -> decltype(declval()(0)) {} // expected-note{{candidate template ignored}}
+auto Call(T x) -> decltype(declval()(0)) {}
 
 class Status {};
 
 void fun() {
   // The Status() (instead of Status) here used to cause a crash.
   Call([](auto x) -> Status() {}); // expected-error{{function cannot return function type 'Status ()}}
-  // expected-error@-1{{no matching function for call to 'Call'}}
 }
Index: clang/test/Parser/cxx2a-template-lambdas.cpp
===
--- clang/test/Parser/cxx2a-template-lambdas.cpp
+++ clang/test/Parser/cxx2a-template-lambdas.cpp
@@ -32,3 +32,11 @@
 // expected-warning@-3 {{is a C++23 extension}}
 // expected-warning@-3 {{is a C++23 extension}}
 #endif
+
+namespace GH64962 {
+void f() {
+  [] (T i) -> int[] // expected-error {{function cannot return array type 'int[]'}}
+// extension-warning {{explicit template parameter list for lambdas is a C++20 extension}}
+{ return 3; } (v); // expected-error {{use of undeclared identifier 'v'}}
+}
+}
Index: clang/lib/Parse/ParseExprCXX.cpp
===
--- clang/lib/Parse/ParseExprCXX.cpp
+++ clang/lib/Parse/ParseExprCXX.cpp
@@ -1546,7 +1546,8 @@
   TemplateParamScope.Exit();
   LambdaScope.Exit();
 
-  if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
+  if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid() &&
+  !D.isInvalidType())
 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
 
   Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
Index: clang/docs/ReleaseNotes.rst
===
--- cl

[PATCH] D159083: Clang: Don't warn about unused private fields of types declared maybe_unused

2023-08-29 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik accepted this revision.
shafik added a comment.

LGTM


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159083/new/

https://reviews.llvm.org/D159083

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


[PATCH] D159064: [Modules] Make clang modules for the C standard library headers

2023-08-29 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added inline comments.



Comment at: clang/lib/Headers/__stddef_null.h:14
+ * __need_NULL and rely on stddef.h to redefine NULL to the correct value 
again.
+ * Modules don't support redefining macros like that, but support that pattern
+ * in the non-modules case.

iana wrote:
> I couldn't come up with anything clever to support this in modules. If I get 
> rid of the guard, `NULL` still doesn't get redefined in modules. If I move 
> the `undef` to stddef.h then `NULL` gets undefined, but not redefined. So I 
> think precompiled modules must inherently have `#pragma once` semantics. If 
> we really had to, we could move this back into stddef.h and let it be 
> textual, but it's distasteful that `NULL` gets defined in every single module 
> that includes stddef.h and has to be merged later.
Modules are, in a way, stronger than `#pragma once`. Each module is a separate 
translation unit. If there's a module around `__stddef_null.h`, then it will 
only be compiled once, and any definitions imported from there. Other importing 
TUs get those definitions per the context the module was compiled in (they 
don't re-compile the code in their own context...).

It seems like a regression for `NULL` to degrade from `((void *)0)` to `0` 
since it loses type safety, which is rather rare and precious in C code. Maybe 
this header should remain textual when deployed to platforms that rely on this 
dance.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159064/new/

https://reviews.llvm.org/D159064

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


[PATCH] D159103: [Driver][HLSL] Improve diagnostics for invalid shader model and stage

2023-08-29 Thread Justin Bogner via Phabricator via cfe-commits
bogner created this revision.
bogner added reviewers: aaron.ballman, beanz.
Herald added subscribers: Anastasia, mcrosier.
Herald added a project: All.
bogner requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

This adds more validation that a dxil triple is actually useable when
compiling HLSL.

The OS field of the triple needs to be a versioned shader model.
Later, we should set a default if this is empty and check that the
version is a shader model we can actually handle.

The Environment field of the triple needs to be specified and be a
valid shader stage. I'd like to allow this to be empty and treat it
like library, but allowing that currently crashes in DXIL metadata
handling.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D159103

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/test/Driver/hlsl-lang-targets.hlsl
  llvm/include/llvm/TargetParser/Triple.h

Index: llvm/include/llvm/TargetParser/Triple.h
===
--- llvm/include/llvm/TargetParser/Triple.h
+++ llvm/include/llvm/TargetParser/Triple.h
@@ -271,7 +271,9 @@
 Callable,
 Mesh,
 Amplification,
+
 OpenHOS,
+
 LastEnvironmentType = OpenHOS
   };
   enum ObjectFormatType {
@@ -756,6 +758,22 @@
 return getArch() == Triple::dxil;
   }
 
+  bool isShaderModelOS() const {
+return getOS() == Triple::ShaderModel;
+  }
+
+  bool isShaderStageEnvironment() const {
+EnvironmentType Env = getEnvironment();
+return Env == Triple::Pixel || Env == Triple::Vertex ||
+   Env == Triple::Geometry || Env == Triple::Hull ||
+   Env == Triple::Domain || Env == Triple::Compute ||
+   Env == Triple::Library || Env == Triple::RayGeneration ||
+   Env == Triple::Intersection || Env == Triple::AnyHit ||
+   Env == Triple::ClosestHit || Env == Triple::Miss ||
+   Env == Triple::Callable || Env == Triple::Mesh ||
+   Env == Triple::Amplification;
+  }
+
   /// Tests whether the target is SPIR (32- or 64-bit).
   bool isSPIR() const {
 return getArch() == Triple::spir || getArch() == Triple::spir64;
Index: clang/test/Driver/hlsl-lang-targets.hlsl
===
--- clang/test/Driver/hlsl-lang-targets.hlsl
+++ clang/test/Driver/hlsl-lang-targets.hlsl
@@ -1,14 +1,52 @@
-// RUN: not %clang -target x86_64-unknown-unknown %s 2>&1 | FileCheck %s --check-prefix=X86
-// RUN: not %clang -target dxil-unknown-unknown %s 2>&1 | FileCheck %s --check-prefix=DXIL
-// RUN: not %clang -target x86_64-unknown-shadermodel %s 2>&1 | FileCheck %s --check-prefix=SM
-// RUN: not %clang -target spirv64-unknown-unknown %s 2>&1 | FileCheck %s --check-prefix=SPIRV
+// Supported targets
+//
+// RUN: %clang -target dxil--shadermodel6.2-pixel %s -S -o /dev/null 2>&1 | FileCheck --check-prefix=CHECK-VALID %s
+// RUN: %clang -target dxil-unknown-shadermodel6.2-pixel %s -S -o /dev/null 2>&1 | FileCheck --check-prefix=CHECK-VALID %s
+// RUN: %clang -target dxil--shadermodel6.2-library %s -S -o /dev/null 2>&1 | FileCheck --check-prefix=CHECK-VALID %s
+// RUN: %clang -target dxil-unknown-shadermodel6.2-library %s -S -o /dev/null 2>&1 | FileCheck --check-prefix=CHECK-VALID %s
 
+// Empty shader model
+//
+// RUN: not %clang -target dxil %s -S -o /dev/null 2>&1 | FileCheck --check-prefix=CHECK-NO-OS %s
 
-// A completely unsupported target...
-// X86: error: HLSL code generation is unsupported for target 'x86_64-unknown-unknown'
+// Invalid shader models
+//
+// RUN: not %clang -target dxil--linux %s -S -o /dev/null 2>&1 | FileCheck --check-prefix=CHECK-BAD-OS %s
+// RUN: not %clang -target dxil--win32 %s -S -o /dev/null 2>&1 | FileCheck --check-prefix=CHECK-BAD-OS %s
+// RUN: not %clang -target dxil--unknown %s -S -o /dev/null 2>&1 | FileCheck --check-prefix=CHECK-BAD-OS %s
+// RUN: not %clang -target dxil--invalidos %s -S -o /dev/null 2>&1 | FileCheck --check-prefix=CHECK-BAD-OS %s
 
-// Poorly specified targets
-// DXIL: error: HLSL code generation is unsupported for target 'dxil-unknown-unknown'
-// SM: error: HLSL code generation is unsupported for target 'x86_64-unknown-shadermodel'
+// Bad shader model versions. Currently we just check for any version at all.
+//
+// RUN: not %clang -target dxil--shadermodel %s -S -o /dev/null 2>&1 | FileCheck --check-prefix=CHECK-BAD-OS %s
+// RUN: not %clang -target dxil--shadermodel0.0 %s -S -o /dev/null 2>&1 | FileCheck --check-prefix=CHECK-BAD-OS %s
 
-// FIXME// SPIRV: error: HLSL code generation is unsupported for target 'spirv64-unknown-unknown'
+// Empty shader stage
+//
+// RUN: not %clang -target dxil-shadermodel6.2 %s -S -o /dev/null 2>&1 | FileCheck --check-prefix=CHECK-NO-ENV %s
+// RUN: not %clang -target dxil--shadermodel6.2 %s -S -o /dev/null 2>&1 | FileCheck --check-p

[PATCH] D158803: [Sema][HLSL] Consolidate handling of HLSL attributes

2023-08-29 Thread Justin Bogner via Phabricator via cfe-commits
bogner added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:12395-12398
+  // TODO: This should probably just be llvm_unreachable and we should
+  // reject triples with random ABIs and such when we build the target.
+  // For now, crash.
+  llvm::report_fatal_error("Unhandled environment in triple");

aaron.ballman wrote:
> bogner wrote:
> > aaron.ballman wrote:
> > > Hmmm, is this going to be done as a follow-up relatively soon? 
> > > `report_fatal_error` isn't acceptable in lieu of actual diagnostic 
> > > reporting, so this should either be fixed in this patch or Really Soon 
> > > After™ it lands.
> > Yeah, I'm happy to go and tackle that this week. Really I want an 
> > assert/unreachable here but since it is in fact reachable at the moment 
> > this seemed better as a temporary fix. Note that before this patch we just 
> > index out of bounds of an array and get all of the fun benefits of UB.
> SGTM to do it as a follow-up -- this is better than the out of bounds 
> indexing!
Follow up is here: https://reviews.llvm.org/D159103


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158803/new/

https://reviews.llvm.org/D158803

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


[PATCH] D159105: [analyzer] ArrayBoundCheckerV2 should check the region for taint as well

2023-08-29 Thread Balázs Benics via Phabricator via cfe-commits
steakhal created this revision.
steakhal added reviewers: NoQ, xazax.hun, donat.nagy, Szelethus.
Herald added subscribers: manas, ASDenysPetrov, martong, dkrupp, 
mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware.
Herald added a project: All.
steakhal requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Previously, we didn't report OOB accesses if the pointer itself was
tainted. This looks weird, but there is weird code out there, code like
inside the Juliet benchmark.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D159105

Files:
  clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
  clang/test/Analysis/taint-generic.c

Index: clang/test/Analysis/taint-generic.c
===
--- clang/test/Analysis/taint-generic.c
+++ clang/test/Analysis/taint-generic.c
@@ -55,10 +55,19 @@
 // CHECK-INVALID-ARG-SAME:that expects an argument number for propagation
 // CHECK-INVALID-ARG-SAME:rules greater or equal to -1
 
+typedef typeof(sizeof(int)) size_t;
 typedef long long rsize_t;
 void clang_analyzer_isTainted_char(char);
 void clang_analyzer_isTainted_charp(char*);
 void clang_analyzer_isTainted_int(int);
+void clang_analyzer_isTainted_int_ptr(const int *);
+size_t clang_analyzer_getExtent(const void *);
+void clang_analyzer_dump_int(int);
+void clang_analyzer_dump_int_ptr(const int *);
+void clang_analyzer_dump_char(char);
+void clang_analyzer_dump_char_ptr(const char*);
+void clang_analyzer_value(char);
+void clang_analyzer_printState();
 
 int scanf(const char *restrict format, ...);
 char *gets(char *str);
@@ -1107,3 +1116,36 @@
   setproctitle_init(1, argv, 0); // expected-warning {{Untrusted data is passed to a user-defined sink}}
   setproctitle_init(1, real_argv, argv); // expected-warning {{Untrusted data is passed to a user-defined sink}}
 }
+
+void testTaintedPtr() {
+  // Read a pointer from a tainted source and dereference it.
+  int *ptr;
+  scanf("%ld", &ptr); // expected-warning {{format specifies type 'long *' but the argument has type 'int **'}}
+  *ptr = 44; // expected-warning {{Out of bound memory access (index is tainted)}}
+}
+
+void testTaintedUnconstrainedIndex() {
+  int n;
+  scanf("%d", &n);
+  Buffer[n] = 1; // expected-warning {{Out of bound memory access (index is tainted)}}
+}
+
+void testTaintedLowerConstrainedIndex() {
+  int n;
+  scanf("%d", &n);
+  if (n >= 0) {
+// We only constained the lower end, and it's tainted => report.
+Buffer[n] = 1; // expected-warning {{Out of bound memory access (index is tainted)}}
+  }
+}
+
+void testUnknownExtentWithTaintedIndex(void) {
+  extern void v;
+  int *p = (int *)&v;
+  int n;
+  scanf("%d", &n);
+
+  clang_analyzer_isTainted_int(n); // expected-warning {{YES}}
+  clang_analyzer_dump_int(clang_analyzer_getExtent(p)); // expected-warning {{Unknown}}
+  p[n] = 42; // expected-warning {{Out of bound memory access (index is tainted)}}
+}
Index: clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
@@ -193,6 +193,11 @@
   reportOOB(checkerContext, state_precedesLowerBound, OOB_Precedes);
   return;
 }
+if (state_precedesLowerBound && state_withinLowerBound &&
+isTainted(state, location)) {
+  reportTaintOOB(checkerContext, state_precedesLowerBound, location);
+  return;
+}
 
 if (state_withinLowerBound)
   state = state_withinLowerBound;
@@ -204,17 +209,16 @@
 auto [state_withinUpperBound, state_exceedsUpperBound] =
 compareValueToThreshold(state, ByteOffset, *KnownSize, svalBuilder);
 
-if (state_exceedsUpperBound) {
-  if (!state_withinUpperBound) {
-// We know that the index definitely exceeds the upper bound.
-reportOOB(checkerContext, state_exceedsUpperBound, OOB_Excedes);
-return;
-  }
-  if (isTainted(state, ByteOffset)) {
-// Both cases are possible, but the index is tainted, so report.
-reportTaintOOB(checkerContext, state_exceedsUpperBound, ByteOffset);
-return;
-  }
+if (state_exceedsUpperBound && !state_withinUpperBound) {
+  // We know that the index definitely exceeds the upper bound.
+  reportOOB(checkerContext, state_exceedsUpperBound, OOB_Excedes);
+  return;
+}
+
+if (state_withinUpperBound && state_exceedsUpperBound &&
+isTainted(state, location)) {
+  reportTaintOOB(checkerContext, state_exceedsUpperBound, location);
+  return;
 }
 
 if (state_withinUpperBound)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D159106: [analyzer] ArrayBoundCheckerV2 should listen to check::Bind as well

2023-08-29 Thread Balázs Benics via Phabricator via cfe-commits
steakhal created this revision.
steakhal added reviewers: NoQ, xazax.hun, donat.nagy, Szelethus.
Herald added subscribers: manas, ASDenysPetrov, martong, dkrupp, 
mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware.
Herald added a project: All.
steakhal requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Turns out check::Location is not always called when storing a value to a
location. See the details here:
https://discourse.llvm.org/t/checklocation-vs-checkbind-when-isload-false/72728

To catch the remaining cases when binding to a location, subscribe to the
check::Bind callback.

(CWE-122 Heap Based Buffer Overflow: CWE-805-class-loop)

Depends on D554351


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D159106

Files:
  clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
  clang/test/Analysis/out-of-bounds-new.cpp


Index: clang/test/Analysis/out-of-bounds-new.cpp
===
--- clang/test/Analysis/out-of-bounds-new.cpp
+++ clang/test/Analysis/out-of-bounds-new.cpp
@@ -154,3 +154,25 @@
   unsigned *U = nullptr;
   U = new unsigned[m + n + 1];
 }
+
+
+int rng();
+struct ManyInts {
+int a, b, c, d, e, f, g;
+};
+void test_trivial_copy_move_is_checked_by_the_checker() {
+  ManyInts v;
+  ManyInts *p = &v;
+
+  switch (rng()) {
+case 0:
+  *p = ManyInts{3,2,1}; // ok
+  break;
+case -1:
+  *--p = ManyInts{3,2,1}; // expected-warning {{Out of bound memory access 
(accessed memory precedes memory block)}}
+  break;
+case 1:
+  *++p = ManyInts{3,2,1}; // expected-warning {{Out of bound memory access 
(access exceeds upper limit of memory block)}}
+  break;
+  }
+}
Index: clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
@@ -30,8 +30,7 @@
 using namespace taint;
 
 namespace {
-class ArrayBoundCheckerV2 :
-public Checker {
+class ArrayBoundCheckerV2 : public Checker {
   mutable std::unique_ptr BT;
   mutable std::unique_ptr TaintBT;
 
@@ -44,9 +43,12 @@
 
   static bool isFromCtypeMacro(const Stmt *S, ASTContext &AC);
 
+  void impl(SVal Loc, bool isLoad, const Stmt *S, CheckerContext &C) const;
+
 public:
   void checkLocation(SVal l, bool isLoad, const Stmt *S,
  CheckerContext &C) const;
+  void checkBind(SVal Loc, SVal, const Stmt *S, CheckerContext &) const;
 };
 
 // FIXME: Eventually replace RegionRawOffset with this class.
@@ -143,6 +145,17 @@
 void ArrayBoundCheckerV2::checkLocation(SVal location, bool isLoad,
 const Stmt* LoadS,
 CheckerContext &checkerContext) const {
+  if (isLoad)
+impl(location, isLoad, LoadS, checkerContext);
+}
+
+void ArrayBoundCheckerV2::checkBind(SVal Loc, SVal, const Stmt *S,
+CheckerContext &C) const {
+  impl(Loc, /*isLoad=*/false, S, C);
+}
+
+void ArrayBoundCheckerV2::impl(SVal location, bool isLoad, const Stmt *LoadS,
+   CheckerContext &checkerContext) const {
 
   // NOTE: Instead of using ProgramState::assumeInBound(), we are prototyping
   // some new logic here that reasons directly about memory region extents.


Index: clang/test/Analysis/out-of-bounds-new.cpp
===
--- clang/test/Analysis/out-of-bounds-new.cpp
+++ clang/test/Analysis/out-of-bounds-new.cpp
@@ -154,3 +154,25 @@
   unsigned *U = nullptr;
   U = new unsigned[m + n + 1];
 }
+
+
+int rng();
+struct ManyInts {
+int a, b, c, d, e, f, g;
+};
+void test_trivial_copy_move_is_checked_by_the_checker() {
+  ManyInts v;
+  ManyInts *p = &v;
+
+  switch (rng()) {
+case 0:
+  *p = ManyInts{3,2,1}; // ok
+  break;
+case -1:
+  *--p = ManyInts{3,2,1}; // expected-warning {{Out of bound memory access (accessed memory precedes memory block)}}
+  break;
+case 1:
+  *++p = ManyInts{3,2,1}; // expected-warning {{Out of bound memory access (access exceeds upper limit of memory block)}}
+  break;
+  }
+}
Index: clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
@@ -30,8 +30,7 @@
 using namespace taint;
 
 namespace {
-class ArrayBoundCheckerV2 :
-public Checker {
+class ArrayBoundCheckerV2 : public Checker {
   mutable std::unique_ptr BT;
   mutable std::unique_ptr TaintBT;
 
@@ -44,9 +43,12 @@
 
   static bool isFromCtypeMacro(const Stmt *S, ASTContext &AC);
 
+  void impl(SVal Loc, bool isLoad, const Stmt *S, CheckerContext &C) const;
+
 public:
   void checkLocation(SVal l, bool 

[PATCH] D159107: [analyzer] ArrayBoundCheckerV2 should disallow forming lvalues to out-of-bounds locations

2023-08-29 Thread Balázs Benics via Phabricator via cfe-commits
steakhal created this revision.
steakhal added reviewers: NoQ, xazax.hun, donat.nagy, Szelethus.
Herald added subscribers: manas, ASDenysPetrov, martong, dkrupp, 
mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware.
Herald added a project: All.
steakhal requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

After this patch, we no longer need the check::Location callback, as we
caught bugs earlier when forming bad references - aka. before loading or
binding anything to it.

(CWE-122 Heap Based Buffer Overflow: CWE-805-class-loop)

Depends on D159106 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D159107

Files:
  clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
  clang/test/Analysis/out-of-bounds-new.cpp

Index: clang/test/Analysis/out-of-bounds-new.cpp
===
--- clang/test/Analysis/out-of-bounds-new.cpp
+++ clang/test/Analysis/out-of-bounds-new.cpp
@@ -176,3 +176,63 @@
   break;
   }
 }
+
+void test_memberwise_copy() {
+  ManyInts dst[1];
+  ManyInts src[2] = {5};
+
+  dst[0] = src[0]; // ok
+  dst[0].a = src[0].a; // ok
+
+  // Positive indexing:
+  switch (rng()) {
+default: break;
+case 0: {
+  auto &z = dst[1]; // expected-warning {{Out of bound memory access (access exceeds upper limit of memory block)}}
+  break;
+}
+case 1: {
+  dst[1].a = src[1].a; // expected-warning {{Out of bound memory access (access exceeds upper limit of memory block)}}
+  break;
+}
+case 2: {
+  auto &z = *(dst + 1); // expected-warning {{Out of bound memory access (access exceeds upper limit of memory block)}}
+  break;
+}
+case 3: {
+  auto &z = *dst;
+  auto &zz = 1[&z]; // expected-warning {{Out of bound memory access (access exceeds upper limit of memory block)}}
+  break;
+}
+case 4: {
+  dst[1] = src[1]; // expected-warning {{Out of bound memory access (access exceeds upper limit of memory block)}}
+  break;
+}
+  }
+
+  // Negative indexing:
+  switch (rng()) {
+default: break;
+case 0: {
+  auto &z = dst[-1]; // expected-warning {{Out of bound memory access (accessed memory precedes memory block)}}
+  break;
+}
+case 1: {
+  dst[-1].a = src[1].a; // expected-warning {{Out of bound memory access (accessed memory precedes memory block)}}
+  break;
+}
+case 2: {
+  auto &z = *(dst - 1); // expected-warning {{Out of bound memory access (accessed memory precedes memory block)}}
+  break;
+}
+case 3: {
+  auto &z = *dst;
+  auto &zz = (-1)[&z]; // expected-warning {{Out of bound memory access (accessed memory precedes memory block)}}
+  break;
+}
+case 4: {
+  dst[-1] = src[1]; // expected-warning {{Out of bound memory access (accessed memory precedes memory block)}}
+  break;
+}
+  }
+}
Index: clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
@@ -30,7 +30,9 @@
 using namespace taint;
 
 namespace {
-class ArrayBoundCheckerV2 : public Checker {
+class ArrayBoundCheckerV2
+: public Checker,
+ check::PostStmt> {
   mutable std::unique_ptr BT;
   mutable std::unique_ptr TaintBT;
 
@@ -46,9 +48,9 @@
   void impl(SVal Loc, bool isLoad, const Stmt *S, CheckerContext &C) const;
 
 public:
-  void checkLocation(SVal l, bool isLoad, const Stmt *S,
- CheckerContext &C) const;
   void checkBind(SVal Loc, SVal, const Stmt *S, CheckerContext &) const;
+  void checkPostStmt(const ArraySubscriptExpr *E, CheckerContext &C) const;
+  void checkPostStmt(const UnaryOperator *E, CheckerContext &C) const;
 };
 
 // FIXME: Eventually replace RegionRawOffset with this class.
@@ -142,13 +144,6 @@
   return {nullptr, nullptr};
 }
 
-void ArrayBoundCheckerV2::checkLocation(SVal location, bool isLoad,
-const Stmt* LoadS,
-CheckerContext &checkerContext) const {
-  if (isLoad)
-impl(location, isLoad, LoadS, checkerContext);
-}
-
 void ArrayBoundCheckerV2::checkBind(SVal Loc, SVal, const Stmt *S,
 CheckerContext &C) const {
   impl(Loc, /*isLoad=*/false, S, C);
@@ -375,6 +370,21 @@
   return std::nullopt;
 }
 
+void ArrayBoundCheckerV2::checkPostStmt(const ArraySubscriptExpr *E,
+CheckerContext &C) const {
+  // TODO: Specialize the diagnostic message.
+  // It might not be a "load" operation.
+  impl(C.getSVal(E), /*isLoad=*/true, E, C);
+}
+void ArrayBoundCheckerV2::checkPostStmt(const UnaryOperator *E,
+CheckerContext &C) const {
+  if (E->getOpcode() != UO_

[PATCH] D159108: [analyzer] CStringChecker should check the first byte of the destination of strcpy, strncpy

2023-08-29 Thread Balázs Benics via Phabricator via cfe-commits
steakhal created this revision.
steakhal added reviewers: NoQ, xazax.hun, donat.nagy, Szelethus.
Herald added subscribers: manas, ASDenysPetrov, martong, dkrupp, 
mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware.
Herald added a project: All.
steakhal requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

By not checking if the first byte of the destination of strcpy and
strncpy is writable, we missed some reports in the Juliet benchmark.

(Juliet CWE-124 Buffer Underwrite: strcpy, strncpy)

Depends on D159107 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D159108

Files:
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/test/Analysis/string.c


Index: clang/test/Analysis/string.c
===
--- clang/test/Analysis/string.c
+++ clang/test/Analysis/string.c
@@ -1667,3 +1667,49 @@
   strcpy(x, "12\0");
 }
 #endif
+
+#ifndef SUPPRESS_OUT_OF_BOUND
+void testStrcpyDestinationWritableFirstByte(void) {
+  char dst[10];
+  char *p = dst - 8;
+  strcpy(p, "src"); // expected-warning {{String copy function overflows the 
destination buffer}}
+}
+
+void CWE124_Buffer_Underwrite__malloc_char_cpy() {
+  char * dataBuffer = (char *)malloc(100*sizeof(char));
+  if (dataBuffer == NULL) return;
+  memset(dataBuffer, 'A', 100-1);
+  dataBuffer[100-1] = '\0';
+  char * data = dataBuffer - 8;
+  char source[100];
+  memset(source, 'C', 100-1); // fill with 'C's
+  source[100-1] = '\0'; // null terminate
+  strcpy(data, source); // expected-warning {{String copy function overflows 
the destination buffer}}
+  free(dataBuffer);
+}
+#endif
+
+#ifndef SUPPRESS_OUT_OF_BOUND
+void testStrncpyDestinationWritableFirstByte(void) {
+  char source[100];
+  use_string(source); // escape
+  char buf[100];
+  char *p = buf - 8;
+  strncpy(p, source, 100-1); // expected-warning {{String copy function 
overflows the destination buffer}}
+}
+
+void CWE124_Buffer_Underwrite__malloc_char_ncpy() {
+  char * dataBuffer = (char *)malloc(100*sizeof(char));
+  if (dataBuffer == 0) return;
+  memset(dataBuffer, 'A', 100-1);
+  dataBuffer[100-1] = '\0';
+  char *data = dataBuffer - 8;
+
+  char source[100];
+  memset(source, 'C', 100-1); // fill with 'C's
+  source[100-1] = '\0'; // null terminate
+  strncpy(data, source, 100-1); // expected-warning {{String copy function 
overflows the destination buffer}}
+  data[100-1] = '\0'; // null terminate
+  free(dataBuffer);
+}
+#endif
Index: clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -2009,6 +2009,11 @@
   SVal maxLastElement =
   svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal, *maxLastNL, 
ptrTy);
 
+  // Check if the first byte of the destination is writable.
+  state = CheckLocation(C, state, Dst, DstVal, AccessKind::write);
+  if (!state)
+return;
+  // Check if the last byte of the destination is writable.
   state = CheckLocation(C, state, Dst, maxLastElement, AccessKind::write);
   if (!state)
 return;
@@ -2021,6 +2026,11 @@
 
   // ...and we haven't checked the bound, we'll check the actual copy.
   if (!boundWarning) {
+// Check if the first byte of the destination is writable.
+state = CheckLocation(C, state, Dst, DstVal, AccessKind::write);
+if (!state)
+  return;
+// Check if the last byte of the destination is writable.
 state = CheckLocation(C, state, Dst, lastElement, AccessKind::write);
 if (!state)
   return;


Index: clang/test/Analysis/string.c
===
--- clang/test/Analysis/string.c
+++ clang/test/Analysis/string.c
@@ -1667,3 +1667,49 @@
   strcpy(x, "12\0");
 }
 #endif
+
+#ifndef SUPPRESS_OUT_OF_BOUND
+void testStrcpyDestinationWritableFirstByte(void) {
+  char dst[10];
+  char *p = dst - 8;
+  strcpy(p, "src"); // expected-warning {{String copy function overflows the destination buffer}}
+}
+
+void CWE124_Buffer_Underwrite__malloc_char_cpy() {
+  char * dataBuffer = (char *)malloc(100*sizeof(char));
+  if (dataBuffer == NULL) return;
+  memset(dataBuffer, 'A', 100-1);
+  dataBuffer[100-1] = '\0';
+  char * data = dataBuffer - 8;
+  char source[100];
+  memset(source, 'C', 100-1); // fill with 'C's
+  source[100-1] = '\0'; // null terminate
+  strcpy(data, source); // expected-warning {{String copy function overflows the destination buffer}}
+  free(dataBuffer);
+}
+#endif
+
+#ifndef SUPPRESS_OUT_OF_BOUND
+void testStrncpyDestinationWritableFirstByte(void) {
+  char source[100];
+  use_string(source); // escape
+  char buf[100];
+  char *p = buf - 8;
+  strncpy(p, source, 100-1); // expected-warning {{String copy function overflows t

[PATCH] D159109: [analyzer] CStringChecker buffer access checks should check the first bytes

2023-08-29 Thread Balázs Benics via Phabricator via cfe-commits
steakhal created this revision.
steakhal added reviewers: NoQ, xazax.hun, donat.nagy, Szelethus.
Herald added subscribers: manas, ASDenysPetrov, martong, dkrupp, 
mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware.
Herald added a project: All.
steakhal requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

By not checking if the first byte of the buffer is accessible,
we missed some reports in the Juliet benchmark.

(Juliet CWE-124 Buffer Underwrite: memcpy, memmove)

Depends on D159108 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D159109

Files:
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/test/Analysis/string.c


Index: clang/test/Analysis/string.c
===
--- clang/test/Analysis/string.c
+++ clang/test/Analysis/string.c
@@ -71,6 +71,7 @@
 int scanf(const char *restrict format, ...);
 void *malloc(size_t);
 void free(void *);
+void *memcpy(void *dest, const void *src, unsigned long n);
 
 //===--===
 // strlen()
@@ -1713,3 +1714,21 @@
   free(dataBuffer);
 }
 #endif
+
+#ifndef SUPPRESS_OUT_OF_BOUND
+void CWE124_Buffer_Underwrite__malloc_char_memcpy() {
+  char * dataBuffer = (char *)malloc(100*sizeof(char));
+  if (dataBuffer == NULL) return;
+  memset(dataBuffer, 'A', 100-1);
+  dataBuffer[100-1] = '\0';
+  char *data = dataBuffer - 8;
+
+  char source[100];
+  memset(source, 'C', 100-1); // fill with 'C's
+  source[100-1] = '\0'; // null terminate
+
+  memcpy(data, source, 100*sizeof(char)); // expected-warning {{Memory copy 
function overflows the destination buffer}}
+  data[100-1] = '\0';
+  free(dataBuffer);
+}
+#endif
Index: clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -480,6 +480,14 @@
   if (!Filter.CheckCStringOutOfBounds)
 return State;
 
+  SVal BufStart =
+  svalBuilder.evalCast(BufVal, PtrTy, Buffer.Expression->getType());
+
+  // Check if the first byte of the buffer is accessible.
+  State = CheckLocation(C, State, Buffer, BufStart, Access, CK);
+  if (!State)
+return nullptr;
+
   // Get the access length and make sure it is known.
   // FIXME: This assumes the caller has already checked that the access length
   // is positive. And that it's unsigned.
@@ -496,8 +504,6 @@
   NonLoc LastOffset = Offset.castAs();
 
   // Check that the first buffer is sufficiently long.
-  SVal BufStart =
-  svalBuilder.evalCast(BufVal, PtrTy, Buffer.Expression->getType());
   if (std::optional BufLoc = BufStart.getAs()) {
 
 SVal BufEnd =


Index: clang/test/Analysis/string.c
===
--- clang/test/Analysis/string.c
+++ clang/test/Analysis/string.c
@@ -71,6 +71,7 @@
 int scanf(const char *restrict format, ...);
 void *malloc(size_t);
 void free(void *);
+void *memcpy(void *dest, const void *src, unsigned long n);
 
 //===--===
 // strlen()
@@ -1713,3 +1714,21 @@
   free(dataBuffer);
 }
 #endif
+
+#ifndef SUPPRESS_OUT_OF_BOUND
+void CWE124_Buffer_Underwrite__malloc_char_memcpy() {
+  char * dataBuffer = (char *)malloc(100*sizeof(char));
+  if (dataBuffer == NULL) return;
+  memset(dataBuffer, 'A', 100-1);
+  dataBuffer[100-1] = '\0';
+  char *data = dataBuffer - 8;
+
+  char source[100];
+  memset(source, 'C', 100-1); // fill with 'C's
+  source[100-1] = '\0'; // null terminate
+
+  memcpy(data, source, 100*sizeof(char)); // expected-warning {{Memory copy function overflows the destination buffer}}
+  data[100-1] = '\0';
+  free(dataBuffer);
+}
+#endif
Index: clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -480,6 +480,14 @@
   if (!Filter.CheckCStringOutOfBounds)
 return State;
 
+  SVal BufStart =
+  svalBuilder.evalCast(BufVal, PtrTy, Buffer.Expression->getType());
+
+  // Check if the first byte of the buffer is accessible.
+  State = CheckLocation(C, State, Buffer, BufStart, Access, CK);
+  if (!State)
+return nullptr;
+
   // Get the access length and make sure it is known.
   // FIXME: This assumes the caller has already checked that the access length
   // is positive. And that it's unsigned.
@@ -496,8 +504,6 @@
   NonLoc LastOffset = Offset.castAs();
 
   // Check that the first buffer is sufficiently long.
-  SVal BufStart =
-  svalBuilder.evalCast(BufVal, PtrTy, Buffer.Expression->getType());
   if (std::optional BufLoc = BufStart.getAs()) {
 
 SVal BufEnd =
_

[PATCH] D156054: [Clang][Sema] DR722 (nullptr and varargs) and missing -Wvarargs diagnostics

2023-08-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

I think this is looking close to good, just had some minor nits and an extra 
test case to consider.




Comment at: clang/lib/Sema/SemaExpr.cpp:17255
+  // Check if these are compatible types according to the C rules even in C++
+  // because va_arg is defined in C in terms of C compatibile types
+  static auto IsCompatible = [&](QualType L, QualType R) {





Comment at: clang/lib/Sema/SemaExpr.cpp:17264-17268
+  QualType PromotedType = PromotedExpr.get()->getType().getUnqualifiedType();
+  QualType VAArgType = VAArg->getType().getUnqualifiedType();
+  // If these types are compatible, it was not promoted to an incompatible 
type.
+  if (IsCompatible(PromotedType, VAArgType))
+return QualType();

This code is correct, but let's add an explicit test for the subtle edge case 
with `_Atomic` types. `getUnqualifiedType()` does not strip atomic qualifiers, 
so `int` and `_Atomic int` should remain incompatible.



Comment at: clang/test/Sema/format-pointer.c:1-8
+// RUN: %clang_cc1 -xc -Wformat %s -verify
+// RUN: %clang_cc1 -xc -Wformat -std=c2x %s -verify
+// RUN: %clang_cc1 -xc++ -Wformat %s -verify
+// RUN: %clang_cc1 -xobjective-c -Wformat -fblocks %s -verify
+// RUN: %clang_cc1 -xobjective-c++ -Wformat -fblocks %s -verify
+// RUN: %clang_cc1 -xc -std=c2x -Wformat %s -pedantic -verify=expected,pedantic
+// RUN: %clang_cc1 -xc++ -Wformat %s -pedantic -verify=expected,pedantic





Comment at: clang/test/SemaCXX/varargs.cpp:34
   enum Unscoped1 { One = 0x7FFF };
-  (void)__builtin_va_arg(ap, Unscoped1); // ok
+  (void)__builtin_va_arg(ap, Unscoped1); // expected-warning {{second argument 
to 'va_arg' is of promotable type 'Unscoped1'; this va_arg has undefined 
behavior because arguments will be promoted to 'int'}}
 

MitalAshok wrote:
> aaron.ballman wrote:
> > MitalAshok wrote:
> > > MitalAshok wrote:
> > > > Unscoped1 is promoted to int when passed to a variadic function.
> > > > 
> > > > The underlying type for Unscoped1 is unsigned int, so only Unscoped1 
> > > > and unsigned int are compatible, not Unscoped1 and int. An Unscoped1 
> > > > passed to a variadic function must be retrieved via va_arg(ap, int).
> > > > 
> > > Although I guess the warning is now wrong because even though `void f(int 
> > > x, ...) { std::va_list ap; va_start(ap, x); va_arg(ap, Unscoped1); }` 
> > > `f(0, Unscoped1{2})` would be UB, `f(0, 2u)` would not be UB.
> > > 
> > > The user still should be warned about it, so I could create a new warning 
> > > "second argument to 'va_arg' is of promotable enumeration type 
> > > 'Unscoped1'; this va_arg may have undefined behavior because arguments of 
> > > this enumeration type will be promoted to 'int', not the underlying type 
> > > 'unsigned int'", and maybe suggest a fix `Unscoped1{va_arg(ap, 
> > > unsigned)}`.
> > > 
> > > Or we could ignore it and pretend that int and enums with underlying 
> > > types unsigned are compatible for the purposes of va_arg
> > I think we shouldn't warn in this case because of C23 7.16.1.1p2:
> > 
> > >  If type is not compatible with the type of the actual next argument (as 
> > > promoted according to
> > > the default argument promotions), the behavior is undefined, except for 
> > > the following cases:
> > > ...
> > > one type is compatible with a signed integer type, the other type is 
> > > compatible with the
> > > corresponding unsigned integer type, and the value is representable in 
> > > both types;
> > 
> > Coupled with C23 6.7.2.2p13: 
> > 
> > > For all enumerations without a fixed underlying type, each enumerated 
> > > type shall be compatible
> > > with char or a signed or an unsigned integer type that is not bool or a 
> > > bit-precise integer type. The
> > > choice of type is implementation-defined., but shall be capable of 
> > > representing the values of all
> > > the members of the enumeration.
> > 
> > WDYT?
> This seems to have changed very recently between [[ 
> https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3096.pdf | N3096 ]] (April 
> C23 draft) and [[ https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3149.zip 
> | N3149 ]] (July C23 draft) by [[ 
> https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3112.pdf | N3112 ]].
> 
> For reference, the old wording (also in C17) read:
> 
> > one type is a signed integer type, the other type is the corresponding 
> > unsigned integer type,
> > and the value is representable in both types;
> 
> So with the current rules, yes they would be compatible and this shouldn't 
> warn. I've changed it so it checks types with corresponding signedness.
> This seems to have changed very recently between N3096 (April C23 draft) and 
> N3149 (July C23 draft) by N3112

Yes, this changed during ballot comment resolution at the June 2023 meeting; it 
was US-127 (see https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3148.doc f

[PATCH] D159115: [clang-repl] Adapt to the recent dylib-related changes in ORC.

2023-08-29 Thread Vassil Vassilev via Phabricator via cfe-commits
v.g.vassilev created this revision.
v.g.vassilev added reviewers: lhames, sunho.
Herald added a project: All.
v.g.vassilev requested review of this revision.

ORC splits into separate dylibs symbols coming from the process and symbols 
materialized in the Jit. This patch adapts intent of the existing interface and 
adds a regression test to make sure both Jit'd and compiled symbols can be 
found.


Repository:
  rC Clang

https://reviews.llvm.org/D159115

Files:
  clang/lib/Interpreter/IncrementalExecutor.cpp
  clang/unittests/Interpreter/InterpreterTest.cpp


Index: clang/unittests/Interpreter/InterpreterTest.cpp
===
--- clang/unittests/Interpreter/InterpreterTest.cpp
+++ clang/unittests/Interpreter/InterpreterTest.cpp
@@ -234,10 +234,16 @@
   }
 
   std::string MangledName = MangleName(FD);
-  auto Addr = cantFail(Interp->getSymbolAddress(MangledName));
-  EXPECT_NE(0U, Addr.getValue());
+  auto Addr = Interp->getSymbolAddress(MangledName);
+  EXPECT_FALSE(!Addr);
+  EXPECT_NE(0U, Addr->getValue());
   GlobalDecl GD(FD);
-  EXPECT_EQ(Addr, cantFail(Interp->getSymbolAddress(GD)));
+  EXPECT_EQ(*Addr, cantFail(Interp->getSymbolAddress(GD)));
+  cantFail(
+  Interp->ParseAndExecute("extern \"C\" int printf(const char*,...);"));
+  Addr = Interp->getSymbolAddress("printf");
+  EXPECT_FALSE(!Addr);
+  EXPECT_EQ((unsigned long long)&printf, Addr->getValue());
 }
 
 static void *AllocateObject(TypeDecl *TD, Interpreter &Interp) {
Index: clang/lib/Interpreter/IncrementalExecutor.cpp
===
--- clang/lib/Interpreter/IncrementalExecutor.cpp
+++ clang/lib/Interpreter/IncrementalExecutor.cpp
@@ -92,12 +92,20 @@
 llvm::Expected
 IncrementalExecutor::getSymbolAddress(llvm::StringRef Name,
   SymbolNameKind NameKind) const {
-  auto Sym = (NameKind == LinkerName) ? Jit->lookupLinkerMangled(Name)
-  : Jit->lookup(Name);
-
-  if (!Sym)
-return Sym.takeError();
-  return Sym;
+  using namespace llvm::orc;
+  JITDylibSearchOrder O;
+  JITDylibLookupFlags Flags = JITDylibLookupFlags::MatchExportedSymbolsOnly;
+  O.push_back({&Jit->getMainJITDylib(), Flags});
+  O.push_back({Jit->getPlatformJITDylib().get(), Flags});
+  O.push_back({Jit->getProcessSymbolsJITDylib().get(), Flags});
+
+  ExecutionSession &ES = Jit->getExecutionSession();
+
+  auto SymOrErr = ES.lookup(
+  O, ES.intern((NameKind == LinkerName) ? Name : Jit->mangle(Name)));
+  if (auto Err = SymOrErr.takeError())
+return std::move(Err);
+  return SymOrErr->getAddress();
 }
 
 } // end namespace clang


Index: clang/unittests/Interpreter/InterpreterTest.cpp
===
--- clang/unittests/Interpreter/InterpreterTest.cpp
+++ clang/unittests/Interpreter/InterpreterTest.cpp
@@ -234,10 +234,16 @@
   }
 
   std::string MangledName = MangleName(FD);
-  auto Addr = cantFail(Interp->getSymbolAddress(MangledName));
-  EXPECT_NE(0U, Addr.getValue());
+  auto Addr = Interp->getSymbolAddress(MangledName);
+  EXPECT_FALSE(!Addr);
+  EXPECT_NE(0U, Addr->getValue());
   GlobalDecl GD(FD);
-  EXPECT_EQ(Addr, cantFail(Interp->getSymbolAddress(GD)));
+  EXPECT_EQ(*Addr, cantFail(Interp->getSymbolAddress(GD)));
+  cantFail(
+  Interp->ParseAndExecute("extern \"C\" int printf(const char*,...);"));
+  Addr = Interp->getSymbolAddress("printf");
+  EXPECT_FALSE(!Addr);
+  EXPECT_EQ((unsigned long long)&printf, Addr->getValue());
 }
 
 static void *AllocateObject(TypeDecl *TD, Interpreter &Interp) {
Index: clang/lib/Interpreter/IncrementalExecutor.cpp
===
--- clang/lib/Interpreter/IncrementalExecutor.cpp
+++ clang/lib/Interpreter/IncrementalExecutor.cpp
@@ -92,12 +92,20 @@
 llvm::Expected
 IncrementalExecutor::getSymbolAddress(llvm::StringRef Name,
   SymbolNameKind NameKind) const {
-  auto Sym = (NameKind == LinkerName) ? Jit->lookupLinkerMangled(Name)
-  : Jit->lookup(Name);
-
-  if (!Sym)
-return Sym.takeError();
-  return Sym;
+  using namespace llvm::orc;
+  JITDylibSearchOrder O;
+  JITDylibLookupFlags Flags = JITDylibLookupFlags::MatchExportedSymbolsOnly;
+  O.push_back({&Jit->getMainJITDylib(), Flags});
+  O.push_back({Jit->getPlatformJITDylib().get(), Flags});
+  O.push_back({Jit->getProcessSymbolsJITDylib().get(), Flags});
+
+  ExecutionSession &ES = Jit->getExecutionSession();
+
+  auto SymOrErr = ES.lookup(
+  O, ES.intern((NameKind == LinkerName) ? Name : Jit->mangle(Name)));
+  if (auto Err = SymOrErr.takeError())
+return std::move(Err);
+  return SymOrErr->getAddress();
 }
 
 } // end namespace clang
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

[PATCH] D158948: [clang][ASTImporter] Add import of type-related nodes

2023-08-29 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added inline comments.



Comment at: clang/lib/AST/ASTImporter.cpp:1758
+  *ToAttrLocOrErr);
+}
+

At cases like this (many imported values) `importChecked` can be used, like at 
`VisitDependentSizedArrayType`.



Comment at: clang/unittests/AST/ASTImporterObjCTest.cpp:100
+  FirstDeclMatcher().match(ToInterfaceDecl, Pattern);
+  ASSERT_TRUE(ToTypeParamDeclImported);
+  ASSERT_TRUE(ToTypeParamDeclMatched);

This single assert can be sufficient for this test because the ToTU was empty 
before import, it is not expected that more than one instance will be created. 
Better is to check for example if `getTypeForDecl` is correctly imported.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158948/new/

https://reviews.llvm.org/D158948

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


[PATCH] D159115: [clang-repl] Adapt to the recent dylib-related changes in ORC.

2023-08-29 Thread Lang Hames via Phabricator via cfe-commits
lhames accepted this revision.
lhames added a comment.
This revision is now accepted and ready to land.

Otherwise LGTM!




Comment at: clang/lib/Interpreter/IncrementalExecutor.cpp:96-100
+  JITDylibSearchOrder O;
+  JITDylibLookupFlags Flags = JITDylibLookupFlags::MatchExportedSymbolsOnly;
+  O.push_back({&Jit->getMainJITDylib(), Flags});
+  O.push_back({Jit->getPlatformJITDylib().get(), Flags});
+  O.push_back({Jit->getProcessSymbolsJITDylib().get(), Flags});

I think this should be equivalent to
```
auto SO =
  makeJITDylibSearchFlags(&Jit->getMainJITDylib(),
  Jit->getPlatformJITDylib().get(),
  Jit->getProcessSymbolsJITDylib.get());
```
but this is purely cosmetic -- either way works.


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159115/new/

https://reviews.llvm.org/D159115

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


  1   2   3   >